]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
i18n: unmark a message in rebase.c
[thirdparty/git.git] / sequencer.c
CommitLineData
26ae337b 1#include "cache.h"
b2141fc1 2#include "config.h"
697cc8ef 3#include "lockfile.h"
26ae337b 4#include "dir.h"
cbd53a21 5#include "object-store.h"
043a4492
RR
6#include "object.h"
7#include "commit.h"
0505d604 8#include "sequencer.h"
043a4492
RR
9#include "tag.h"
10#include "run-command.h"
d807c4a0 11#include "exec-cmd.h"
043a4492
RR
12#include "utf8.h"
13#include "cache-tree.h"
14#include "diff.h"
15#include "revision.h"
16#include "rerere.h"
17#include "merge-recursive.h"
18#include "refs.h"
b27cfb0d 19#include "argv-array.h"
a1c75762 20#include "quote.h"
967dfd4d 21#include "trailer.h"
56dc3ab0 22#include "log-tree.h"
311af526 23#include "wt-status.h"
c44a4c65 24#include "hashmap.h"
a87a6f3c
PW
25#include "notes-utils.h"
26#include "sigchain.h"
9055e401
JS
27#include "unpack-trees.h"
28#include "worktree.h"
1644c73c
JS
29#include "oidmap.h"
30#include "oidset.h"
8315bd20 31#include "commit-slab.h"
65b5f948 32#include "alias.h"
64043556 33#include "commit-reach.h"
b97e1873 34#include "rebase-interactive.h"
043a4492
RR
35
36#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 37
5fe81438 38static const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 39static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 40
66618a50
PW
41GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
42
8a2a0f53
JS
43GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
44
45static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 48static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 49
84583957
JS
50static GIT_PATH_FUNC(rebase_path, "rebase-merge")
51/*
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
56 */
44b776c3 57GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
a930eb03 58GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
b97e1873 59
1df6df0c
JS
60/*
61 * The rebase command lines that have already been processed. A line
62 * is moved here when it is first handled, before any associated user
63 * actions.
64 */
65static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
ef80069a
JS
66/*
67 * The file to keep track of how many commands were already processed (e.g.
68 * for the prompt).
69 */
9ad36356 70static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
ef80069a
JS
71/*
72 * The file to keep track of how many commands are to be processed in total
73 * (e.g. for the prompt).
74 */
9ad36356 75static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
6e98de72
JS
76/*
77 * The commit message that is planned to be used for any changes that
78 * need to be committed following a user interaction.
79 */
80static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
81/*
82 * The file into which is accumulated the suggested commit message for
83 * squash/fixup commands. When the first of a series of squash/fixups
84 * is seen, the file is created and the commit message from the
85 * previous commit and from the first squash/fixup commit are written
86 * to it. The commit message for each subsequent squash/fixup commit
87 * is appended to the file as it is processed.
6e98de72
JS
88 */
89static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
90/*
91 * If the current series of squash/fixups has not yet included a squash
92 * command, then this file exists and holds the commit message of the
93 * original "pick" commit. (If the series ends without a "squash"
94 * command, then this can be used as the commit message of the combined
95 * commit without opening the editor.)
96 */
97static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
e12a7ef5
JS
98/*
99 * This file contains the list fixup/squash commands that have been
100 * accumulated into message-fixup or message-squash so far.
101 */
102static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
b5a67045
JS
103/*
104 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
105 * GIT_AUTHOR_DATE that will be used for the commit that is currently
106 * being rebased.
107 */
108static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
109/*
110 * When an "edit" rebase command is being processed, the SHA1 of the
111 * commit to be edited is recorded in this file. When "git rebase
112 * --continue" is executed, if there are any staged changes then they
113 * will be amended to the HEAD commit, but only provided the HEAD
114 * commit is still the commit to be edited. When any other rebase
115 * command is processed, this file is deleted.
116 */
117static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
118/*
119 * When we stop at a given patch via the "edit" command, this file contains
120 * the abbreviated commit name of the corresponding patch.
121 */
122static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
25cb8df9
JS
123/*
124 * For the post-rewrite hook, we make a list of rewritten commits and
125 * their new sha1s. The rewritten-pending list keeps the sha1s of
126 * commits that have been processed, but not committed yet,
127 * e.g. because they are waiting for a 'squash' command.
128 */
129static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
130static GIT_PATH_FUNC(rebase_path_rewritten_pending,
131 "rebase-merge/rewritten-pending")
9055e401 132
d87d48b2 133/*
15beaaa3 134 * The path of the file containing the OID of the "squash onto" commit, i.e.
d87d48b2
JS
135 * the dummy commit used for `reset [new root]`.
136 */
137static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
138
9055e401
JS
139/*
140 * The path of the file listing refs that need to be deleted after the rebase
141 * finishes. This is used by the `label` command to record the need for cleanup.
142 */
143static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
144
a1c75762
JS
145/*
146 * The following files are written by git-rebase just after parsing the
65850686 147 * command-line.
a1c75762
JS
148 */
149static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
556907f1
JS
150static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
151static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
899b49c4 152static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
a852ec7f 153static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
4b83ce9f
JS
154static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
155static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 156static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
ca6c6b45
JS
157static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
158static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
9b6d7a62 159static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
d421afa0 160static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
e98c4269
EN
161static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
162static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
b5a67045 163
28d6daed
PW
164static int git_sequencer_config(const char *k, const char *v, void *cb)
165{
166 struct replay_opts *opts = cb;
167 int status;
168
169 if (!strcmp(k, "commit.cleanup")) {
170 const char *s;
171
172 status = git_config_string(&s, k, v);
173 if (status)
174 return status;
175
d74f3e58 176 if (!strcmp(s, "verbatim")) {
28d6daed 177 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58
PW
178 opts->explicit_cleanup = 1;
179 } else if (!strcmp(s, "whitespace")) {
28d6daed 180 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58
PW
181 opts->explicit_cleanup = 1;
182 } else if (!strcmp(s, "strip")) {
28d6daed 183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
d74f3e58
PW
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "scissors")) {
1a2b985f 186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
d74f3e58
PW
187 opts->explicit_cleanup = 1;
188 } else {
28d6daed
PW
189 warning(_("invalid commit message cleanup mode '%s'"),
190 s);
d74f3e58 191 }
28d6daed 192
f40f3c16 193 free((char *)s);
28d6daed
PW
194 return status;
195 }
196
197 if (!strcmp(k, "commit.gpgsign")) {
ed1e5282 198 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
28d6daed
PW
199 return 0;
200 }
201
202 status = git_gpg_config(k, v, NULL);
203 if (status)
204 return status;
205
206 return git_diff_basic_config(k, v, NULL);
207}
208
209void sequencer_init_config(struct replay_opts *opts)
210{
211 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
212 git_config(git_sequencer_config, opts);
213}
214
b5a67045
JS
215static inline int is_rebase_i(const struct replay_opts *opts)
216{
84583957 217 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
218}
219
285abf56
JS
220static const char *get_dir(const struct replay_opts *opts)
221{
84583957
JS
222 if (is_rebase_i(opts))
223 return rebase_path();
285abf56
JS
224 return git_path_seq_dir();
225}
226
c0246501
JS
227static const char *get_todo_path(const struct replay_opts *opts)
228{
84583957
JS
229 if (is_rebase_i(opts))
230 return rebase_path_todo();
c0246501
JS
231 return git_path_todo_file();
232}
233
bab4d109
BC
234/*
235 * Returns 0 for non-conforming footer
236 * Returns 1 for conforming footer
237 * Returns 2 when sob exists within conforming footer
238 * Returns 3 when sob exists within conforming footer as last entry
239 */
240static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
66e83d9b 241 size_t ignore_footer)
b971e04f 242{
00a21f5c 243 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
967dfd4d 244 struct trailer_info info;
a3b636e2 245 size_t i;
967dfd4d 246 int found_sob = 0, found_sob_last = 0;
b971e04f 247
ffce7f59
JK
248 opts.no_divider = 1;
249
00a21f5c 250 trailer_info_get(&info, sb->buf, &opts);
b971e04f 251
967dfd4d 252 if (info.trailer_start == info.trailer_end)
b971e04f
BC
253 return 0;
254
967dfd4d
JT
255 for (i = 0; i < info.trailer_nr; i++)
256 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
257 found_sob = 1;
258 if (i == info.trailer_nr - 1)
259 found_sob_last = 1;
260 }
b971e04f 261
967dfd4d 262 trailer_info_release(&info);
bab4d109 263
967dfd4d 264 if (found_sob_last)
bab4d109
BC
265 return 3;
266 if (found_sob)
267 return 2;
b971e04f
BC
268 return 1;
269}
5ed75e2a 270
a1c75762
JS
271static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
272{
273 static struct strbuf buf = STRBUF_INIT;
274
275 strbuf_reset(&buf);
276 if (opts->gpg_sign)
277 sq_quotef(&buf, "-S%s", opts->gpg_sign);
278 return buf.buf;
279}
280
2863584f 281int sequencer_remove_state(struct replay_opts *opts)
26ae337b 282{
9055e401 283 struct strbuf buf = STRBUF_INIT;
37e9ee5c 284 int i, ret = 0;
03a4e260 285
9055e401
JS
286 if (is_rebase_i(opts) &&
287 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
288 char *p = buf.buf;
289 while (*p) {
290 char *eol = strchr(p, '\n');
291 if (eol)
292 *eol = '\0';
c2417d3a 293 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
9055e401 294 warning(_("could not delete '%s'"), p);
37e9ee5c
PW
295 ret = -1;
296 }
9055e401
JS
297 if (!eol)
298 break;
299 p = eol + 1;
300 }
301 }
302
03a4e260
JS
303 free(opts->gpg_sign);
304 free(opts->strategy);
305 for (i = 0; i < opts->xopts_nr; i++)
306 free(opts->xopts[i]);
307 free(opts->xopts);
e12a7ef5 308 strbuf_release(&opts->current_fixups);
26ae337b 309
9055e401
JS
310 strbuf_reset(&buf);
311 strbuf_addstr(&buf, get_dir(opts));
37e9ee5c
PW
312 if (remove_dir_recursively(&buf, 0))
313 ret = error(_("could not remove '%s'"), buf.buf);
9055e401 314 strbuf_release(&buf);
2863584f 315
37e9ee5c 316 return ret;
26ae337b 317}
043a4492
RR
318
319static const char *action_name(const struct replay_opts *opts)
320{
84583957
JS
321 switch (opts->action) {
322 case REPLAY_REVERT:
323 return N_("revert");
324 case REPLAY_PICK:
325 return N_("cherry-pick");
326 case REPLAY_INTERACTIVE_REBASE:
c2417d3a 327 return N_("rebase");
84583957 328 }
1a07e59c 329 die(_("unknown action: %d"), opts->action);
043a4492
RR
330}
331
043a4492
RR
332struct commit_message {
333 char *parent_label;
7b35eaf8
JK
334 char *label;
335 char *subject;
043a4492
RR
336 const char *message;
337};
338
39755964
JS
339static const char *short_commit_name(struct commit *commit)
340{
aab9583f 341 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
39755964
JS
342}
343
043a4492
RR
344static int get_message(struct commit *commit, struct commit_message *out)
345{
043a4492 346 const char *abbrev, *subject;
7b35eaf8 347 int subject_len;
043a4492 348
7b35eaf8 349 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
39755964 350 abbrev = short_commit_name(commit);
043a4492
RR
351
352 subject_len = find_commit_subject(out->message, &subject);
353
7b35eaf8
JK
354 out->subject = xmemdupz(subject, subject_len);
355 out->label = xstrfmt("%s... %s", abbrev, out->subject);
356 out->parent_label = xstrfmt("parent of %s", out->label);
357
043a4492
RR
358 return 0;
359}
360
d74a4e57 361static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
362{
363 free(msg->parent_label);
7b35eaf8
JK
364 free(msg->label);
365 free(msg->subject);
b66103c3 366 unuse_commit_buffer(commit, msg->message);
043a4492
RR
367}
368
005af339
NTND
369static void print_advice(struct repository *r, int show_hint,
370 struct replay_opts *opts)
043a4492
RR
371{
372 char *msg = getenv("GIT_CHERRY_PICK_HELP");
373
374 if (msg) {
375 fprintf(stderr, "%s\n", msg);
376 /*
41ccfdd9 377 * A conflict has occurred but the porcelain
043a4492
RR
378 * (typically rebase --interactive) wants to take care
379 * of the commit itself so remove CHERRY_PICK_HEAD
380 */
005af339 381 unlink(git_path_cherry_pick_head(r));
043a4492
RR
382 return;
383 }
384
ed727b19
PH
385 if (show_hint) {
386 if (opts->no_commit)
387 advise(_("after resolving the conflicts, mark the corrected paths\n"
388 "with 'git add <paths>' or 'git rm <paths>'"));
389 else
390 advise(_("after resolving the conflicts, mark the corrected paths\n"
391 "with 'git add <paths>' or 'git rm <paths>'\n"
392 "and commit the result with 'git commit'"));
393 }
043a4492
RR
394}
395
ddb81e50
AG
396static int write_message(const void *buf, size_t len, const char *filename,
397 int append_eol)
043a4492 398{
14bca6c6 399 struct lock_file msg_file = LOCK_INIT;
043a4492 400
4ef3d8f0
JS
401 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
402 if (msg_fd < 0)
93b3df6f 403 return error_errno(_("could not lock '%s'"), filename);
75871495 404 if (write_in_full(msg_fd, buf, len) < 0) {
bf5c0571 405 error_errno(_("could not write to '%s'"), filename);
4f66c837 406 rollback_lock_file(&msg_file);
bf5c0571 407 return -1;
4f66c837 408 }
f56fffef 409 if (append_eol && write(msg_fd, "\n", 1) < 0) {
bf5c0571 410 error_errno(_("could not write eol to '%s'"), filename);
f56fffef 411 rollback_lock_file(&msg_file);
bf5c0571 412 return -1;
f56fffef 413 }
350292a1
414 if (commit_lock_file(&msg_file) < 0)
415 return error(_("failed to finalize '%s'"), filename);
4ef3d8f0
JS
416
417 return 0;
043a4492
RR
418}
419
1dfc84e9
JS
420/*
421 * Reads a file that was presumably written by a shell script, i.e. with an
422 * end-of-line marker that needs to be stripped.
423 *
424 * Note that only the last end-of-line marker is stripped, consistent with the
425 * behavior of "$(cat path)" in a shell script.
426 *
427 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
428 */
429static int read_oneliner(struct strbuf *buf,
430 const char *path, int skip_if_empty)
431{
432 int orig_len = buf->len;
433
434 if (!file_exists(path))
435 return 0;
436
437 if (strbuf_read_file(buf, path, 0) < 0) {
438 warning_errno(_("could not read '%s'"), path);
439 return 0;
440 }
441
442 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
443 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
444 --buf->len;
445 buf->buf[buf->len] = '\0';
446 }
447
448 if (skip_if_empty && buf->len == orig_len)
449 return 0;
450
451 return 1;
452}
453
005af339 454static struct tree *empty_tree(struct repository *r)
043a4492 455{
005af339 456 return lookup_tree(r, the_hash_algo->empty_tree);
043a4492
RR
457}
458
e1ff0a32 459static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
043a4492 460{
e1ff0a32 461 if (repo_read_index_unmerged(repo))
c28cbc5e 462 return error_resolve_conflict(_(action_name(opts)));
043a4492 463
93b3df6f 464 error(_("your local changes would be overwritten by %s."),
c28cbc5e 465 _(action_name(opts)));
043a4492
RR
466
467 if (advice_commit_before_merge)
93b3df6f 468 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
469 return -1;
470}
471
1e41229d
SB
472static void update_abort_safety_file(void)
473{
474 struct object_id head;
475
476 /* Do nothing on a single-pick */
477 if (!file_exists(git_path_seq_dir()))
478 return;
479
480 if (!get_oid("HEAD", &head))
481 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
482 else
483 write_file(git_path_abort_safety_file(), "%s", "");
484}
485
f11c9580
NTND
486static int fast_forward_to(struct repository *r,
487 const struct object_id *to,
488 const struct object_id *from,
489 int unborn,
490 struct replay_opts *opts)
043a4492 491{
d668d16c 492 struct ref_transaction *transaction;
eb4be1cb 493 struct strbuf sb = STRBUF_INIT;
d668d16c 494 struct strbuf err = STRBUF_INIT;
043a4492 495
e1ff0a32 496 repo_read_index(r);
f11c9580 497 if (checkout_fast_forward(r, from, to, 1))
0e408fc3 498 return -1; /* the callee should have complained already */
651ab9f5 499
c28cbc5e 500 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
d668d16c
RS
501
502 transaction = ref_transaction_begin(&err);
503 if (!transaction ||
504 ref_transaction_update(transaction, "HEAD",
d87d48b2
JS
505 to, unborn && !is_rebase_i(opts) ?
506 &null_oid : from,
1d147bdf 507 0, sb.buf, &err) ||
db7516ab 508 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
509 ref_transaction_free(transaction);
510 error("%s", err.buf);
511 strbuf_release(&sb);
512 strbuf_release(&err);
513 return -1;
514 }
651ab9f5 515
eb4be1cb 516 strbuf_release(&sb);
d668d16c
RS
517 strbuf_release(&err);
518 ref_transaction_free(transaction);
1e41229d 519 update_abort_safety_file();
d668d16c 520 return 0;
043a4492
RR
521}
522
f29cd862
DL
523enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
524 int use_editor)
525{
526 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
527 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
528 COMMIT_MSG_CLEANUP_SPACE;
529 else if (!strcmp(cleanup_arg, "verbatim"))
530 return COMMIT_MSG_CLEANUP_NONE;
531 else if (!strcmp(cleanup_arg, "whitespace"))
532 return COMMIT_MSG_CLEANUP_SPACE;
533 else if (!strcmp(cleanup_arg, "strip"))
534 return COMMIT_MSG_CLEANUP_ALL;
535 else if (!strcmp(cleanup_arg, "scissors"))
536 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
537 COMMIT_MSG_CLEANUP_SPACE;
538 else
539 die(_("Invalid cleanup mode %s"), cleanup_arg);
540}
541
dc42e9a8
PW
542/*
543 * NB using int rather than enum cleanup_mode to stop clang's
544 * -Wtautological-constant-out-of-range-compare complaining that the comparison
545 * is always true.
546 */
547static const char *describe_cleanup_mode(int cleanup_mode)
548{
549 static const char *modes[] = { "whitespace",
550 "verbatim",
551 "scissors",
552 "strip" };
553
554 if (cleanup_mode < ARRAY_SIZE(modes))
555 return modes[cleanup_mode];
556
557 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
558}
559
f11c9580 560void append_conflicts_hint(struct index_state *istate,
1a2b985f 561 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
75c961b7
JH
562{
563 int i;
564
1a2b985f
DL
565 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
566 strbuf_addch(msgbuf, '\n');
567 wt_status_append_cut_line(msgbuf);
568 strbuf_addch(msgbuf, comment_line_char);
569 }
570
261f315b
JH
571 strbuf_addch(msgbuf, '\n');
572 strbuf_commented_addf(msgbuf, "Conflicts:\n");
f11c9580
NTND
573 for (i = 0; i < istate->cache_nr;) {
574 const struct cache_entry *ce = istate->cache[i++];
75c961b7 575 if (ce_stage(ce)) {
261f315b 576 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
f11c9580
NTND
577 while (i < istate->cache_nr &&
578 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
579 i++;
580 }
581 }
582}
583
f11c9580
NTND
584static int do_recursive_merge(struct repository *r,
585 struct commit *base, struct commit *next,
043a4492 586 const char *base_label, const char *next_label,
48be4c62 587 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
588 struct replay_opts *opts)
589{
590 struct merge_options o;
b4db8a2b 591 struct tree *next_tree, *base_tree, *head_tree;
03b86647 592 int clean;
03a4e260 593 char **xopt;
14bca6c6 594 struct lock_file index_lock = LOCK_INIT;
043a4492 595
3a95f31d 596 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 597 return -1;
043a4492 598
e1ff0a32 599 repo_read_index(r);
043a4492 600
0d6caa2d 601 init_merge_options(&o, r);
043a4492
RR
602 o.ancestor = base ? base_label : "(empty tree)";
603 o.branch1 = "HEAD";
604 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
605 if (is_rebase_i(opts))
606 o.buffer_output = 2;
9268cf4a 607 o.show_rename_progress = 1;
043a4492
RR
608
609 head_tree = parse_tree_indirect(head);
005af339
NTND
610 next_tree = next ? get_commit_tree(next) : empty_tree(r);
611 base_tree = base ? get_commit_tree(base) : empty_tree(r);
043a4492
RR
612
613 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
614 parse_merge_opt(&o, *xopt);
615
616 clean = merge_trees(&o,
617 head_tree,
b4db8a2b 618 next_tree, base_tree);
62fdb652
JS
619 if (is_rebase_i(opts) && clean <= 0)
620 fputs(o.obuf.buf, stdout);
548009c0 621 strbuf_release(&o.obuf);
64816524
622 if (clean < 0) {
623 rollback_lock_file(&index_lock);
f241ff0d 624 return clean;
64816524 625 }
043a4492 626
f11c9580 627 if (write_locked_index(r->index, &index_lock,
61000814 628 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
629 /*
630 * TRANSLATORS: %s will be "revert", "cherry-pick" or
c2417d3a 631 * "rebase".
84583957 632 */
c527b55e 633 return error(_("%s: Unable to write new index file"),
c28cbc5e 634 _(action_name(opts)));
043a4492 635
75c961b7 636 if (!clean)
1a2b985f
DL
637 append_conflicts_hint(r->index, msgbuf,
638 opts->default_msg_cleanup);
043a4492
RR
639
640 return !clean;
641}
642
f11c9580 643static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 644{
f11c9580
NTND
645 if (!istate->cache_tree)
646 istate->cache_tree = cache_tree();
ba97aea1 647
f11c9580
NTND
648 if (!cache_tree_fully_valid(istate->cache_tree))
649 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
650 error(_("unable to update cache tree"));
651 return NULL;
652 }
653
f11c9580 654 return &istate->cache_tree->oid;
ba97aea1
JS
655}
656
005af339 657static int is_index_unchanged(struct repository *r)
b27cfb0d 658{
ba97aea1 659 struct object_id head_oid, *cache_tree_oid;
b27cfb0d 660 struct commit *head_commit;
005af339 661 struct index_state *istate = r->index;
b27cfb0d 662
49e61479 663 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 664 return error(_("could not resolve HEAD commit"));
b27cfb0d 665
005af339 666 head_commit = lookup_commit(r, &head_oid);
4b580061
NH
667
668 /*
669 * If head_commit is NULL, check_commit, called from
670 * lookup_commit, would have indicated that head_commit is not
671 * a commit object already. parse_commit() will return failure
672 * without further complaints in such a case. Otherwise, if
673 * the commit is invalid, parse_commit() will complain. So
674 * there is nothing for us to say here. Just return failure.
675 */
676 if (parse_commit(head_commit))
677 return -1;
b27cfb0d 678
f11c9580 679 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 680 return -1;
b27cfb0d 681
4a7e27e9 682 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
683}
684
0473f28a
JS
685static int write_author_script(const char *message)
686{
687 struct strbuf buf = STRBUF_INIT;
688 const char *eol;
689 int res;
690
691 for (;;)
692 if (!*message || starts_with(message, "\n")) {
693missing_author:
694 /* Missing 'author' line? */
695 unlink(rebase_path_author_script());
696 return 0;
697 } else if (skip_prefix(message, "author ", &message))
698 break;
699 else if ((eol = strchr(message, '\n')))
700 message = eol + 1;
701 else
702 goto missing_author;
703
704 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
705 while (*message && *message != '\n' && *message != '\r')
706 if (skip_prefix(message, " <", &message))
707 break;
708 else if (*message != '\'')
709 strbuf_addch(&buf, *(message++));
710 else
4aa5ff94 711 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
712 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
713 while (*message && *message != '\n' && *message != '\r')
714 if (skip_prefix(message, "> ", &message))
715 break;
716 else if (*message != '\'')
717 strbuf_addch(&buf, *(message++));
718 else
4aa5ff94 719 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
720 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
721 while (*message && *message != '\n' && *message != '\r')
722 if (*message != '\'')
723 strbuf_addch(&buf, *(message++));
724 else
4aa5ff94 725 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 726 strbuf_addch(&buf, '\'');
0473f28a
JS
727 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
728 strbuf_release(&buf);
729 return res;
730}
731
bcd33ec2
PW
732/**
733 * Take a series of KEY='VALUE' lines where VALUE part is
734 * sq-quoted, and append <KEY, VALUE> at the end of the string list
735 */
736static int parse_key_value_squoted(char *buf, struct string_list *list)
737{
738 while (*buf) {
739 struct string_list_item *item;
740 char *np;
741 char *cp = strchr(buf, '=');
742 if (!cp) {
743 np = strchrnul(buf, '\n');
744 return error(_("no key present in '%.*s'"),
745 (int) (np - buf), buf);
746 }
747 np = strchrnul(cp, '\n');
748 *cp++ = '\0';
749 item = string_list_append(list, buf);
750
751 buf = np + (*np == '\n');
752 *np = '\0';
753 cp = sq_dequote(cp);
754 if (!cp)
755 return error(_("unable to dequote value of '%s'"),
756 item->string);
757 item->util = xstrdup(cp);
758 }
759 return 0;
760}
4aa5ff94 761
bcd33ec2
PW
762/**
763 * Reads and parses the state directory's "author-script" file, and sets name,
764 * email and date accordingly.
765 * Returns 0 on success, -1 if the file could not be parsed.
766 *
767 * The author script is of the format:
768 *
769 * GIT_AUTHOR_NAME='$author_name'
770 * GIT_AUTHOR_EMAIL='$author_email'
771 * GIT_AUTHOR_DATE='$author_date'
772 *
773 * where $author_name, $author_email and $author_date are quoted. We are strict
c3c003e7 774 * with our parsing, as the file was meant to be eval'd in the now-removed
bcd33ec2
PW
775 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
776 * from what this function expects, it is better to bail out than to do
777 * something that the user does not expect.
4aa5ff94 778 */
bcd33ec2
PW
779int read_author_script(const char *path, char **name, char **email, char **date,
780 int allow_missing)
4aa5ff94 781{
bcd33ec2
PW
782 struct strbuf buf = STRBUF_INIT;
783 struct string_list kv = STRING_LIST_INIT_DUP;
784 int retval = -1; /* assume failure */
785 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 786
bcd33ec2
PW
787 if (strbuf_read_file(&buf, path, 256) <= 0) {
788 strbuf_release(&buf);
789 if (errno == ENOENT && allow_missing)
790 return 0;
791 else
792 return error_errno(_("could not open '%s' for reading"),
793 path);
794 }
795
796 if (parse_key_value_squoted(buf.buf, &kv))
797 goto finish;
798
799 for (i = 0; i < kv.nr; i++) {
800 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
801 if (name_i != -2)
802 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
803 else
804 name_i = i;
805 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
806 if (email_i != -2)
807 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
808 else
809 email_i = i;
810 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
811 if (date_i != -2)
812 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
813 else
814 date_i = i;
815 } else {
816 err = error(_("unknown variable '%s'"),
817 kv.items[i].string);
818 }
819 }
820 if (name_i == -2)
821 error(_("missing 'GIT_AUTHOR_NAME'"));
822 if (email_i == -2)
823 error(_("missing 'GIT_AUTHOR_EMAIL'"));
824 if (date_i == -2)
825 error(_("missing 'GIT_AUTHOR_DATE'"));
826 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
827 goto finish;
4d924528
JH
828 *name = kv.items[name_i].util;
829 *email = kv.items[email_i].util;
830 *date = kv.items[date_i].util;
bcd33ec2
PW
831 retval = 0;
832finish:
833 string_list_clear(&kv, !!retval);
834 strbuf_release(&buf);
835 return retval;
4aa5ff94
PW
836}
837
b5a67045 838/*
4d010a75
PW
839 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
840 * file with shell quoting into struct argv_array. Returns -1 on
841 * error, 0 otherwise.
b5a67045 842 */
a2a20b0d 843static int read_env_script(struct argv_array *env)
b5a67045 844{
4d010a75 845 char *name, *email, *date;
b5a67045 846
4d010a75
PW
847 if (read_author_script(rebase_path_author_script(),
848 &name, &email, &date, 0))
a2a20b0d 849 return -1;
b5a67045 850
4d010a75
PW
851 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
852 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
853 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
854 free(name);
855 free(email);
856 free(date);
b5a67045 857
a2a20b0d 858 return 0;
b5a67045
JS
859}
860
356ee465
PW
861static char *get_author(const char *message)
862{
863 size_t len;
864 const char *a;
865
866 a = find_commit_header(message, "author", &len);
867 if (a)
868 return xmemdupz(a, len);
869
870 return NULL;
871}
872
791eb870
JS
873static const char staged_changes_advice[] =
874N_("you have staged changes in your working tree\n"
875"If these changes are meant to be squashed into the previous commit, run:\n"
876"\n"
877" git commit --amend %s\n"
878"\n"
879"If they are meant to go into a new commit, run:\n"
880"\n"
881" git commit %s\n"
882"\n"
883"In both cases, once you're done, continue with:\n"
884"\n"
885" git rebase --continue\n");
886
789b3eff
JS
887#define ALLOW_EMPTY (1<<0)
888#define EDIT_MSG (1<<1)
889#define AMEND_MSG (1<<2)
890#define CLEANUP_MSG (1<<3)
b92ff6e8 891#define VERIFY_MSG (1<<4)
d87d48b2 892#define CREATE_ROOT_COMMIT (1<<5)
789b3eff 893
34bec2c4
AG
894static int run_command_silent_on_success(struct child_process *cmd)
895{
896 struct strbuf buf = STRBUF_INIT;
897 int rc;
898
899 cmd->stdout_to_stderr = 1;
900 rc = pipe_command(cmd,
901 NULL, 0,
902 NULL, 0,
903 &buf, 0);
904
905 if (rc)
906 fputs(buf.buf, stderr);
907 strbuf_release(&buf);
908 return rc;
909}
910
043a4492
RR
911/*
912 * If we are cherry-pick, and if the merge did not result in
913 * hand-editing, we will hit this commit and inherit the original
914 * author date and name.
b5a67045 915 *
043a4492
RR
916 * If we are revert, or if our cherry-pick results in a hand merge,
917 * we had better say that the current user is responsible for that.
b5a67045
JS
918 *
919 * An exception is when run_git_commit() is called during an
920 * interactive rebase: in that case, we will want to retain the
921 * author metadata.
043a4492 922 */
f11c9580
NTND
923static int run_git_commit(struct repository *r,
924 const char *defmsg,
925 struct replay_opts *opts,
789b3eff 926 unsigned int flags)
043a4492 927{
07d968ef 928 struct child_process cmd = CHILD_PROCESS_INIT;
b27cfb0d 929
07d968ef
JS
930 cmd.git_cmd = 1;
931
34bec2c4
AG
932 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
933 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 934
34bec2c4
AG
935 return error(_(staged_changes_advice),
936 gpg_opt, gpg_opt);
b5a67045
JS
937 }
938
07d968ef 939 argv_array_push(&cmd.args, "commit");
043a4492 940
b92ff6e8
JS
941 if (!(flags & VERIFY_MSG))
942 argv_array_push(&cmd.args, "-n");
789b3eff 943 if ((flags & AMEND_MSG))
07d968ef 944 argv_array_push(&cmd.args, "--amend");
3bdd5522 945 if (opts->gpg_sign)
07d968ef 946 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
b5a67045 947 if (defmsg)
07d968ef 948 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3
JS
949 else if (!(flags & EDIT_MSG))
950 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 951 if ((flags & CLEANUP_MSG))
07d968ef 952 argv_array_push(&cmd.args, "--cleanup=strip");
789b3eff 953 if ((flags & EDIT_MSG))
07d968ef 954 argv_array_push(&cmd.args, "-e");
789b3eff 955 else if (!(flags & CLEANUP_MSG) &&
0009426d 956 !opts->signoff && !opts->record_origin &&
1a2b985f 957 !opts->explicit_cleanup)
07d968ef 958 argv_array_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 959
789b3eff 960 if ((flags & ALLOW_EMPTY))
07d968ef 961 argv_array_push(&cmd.args, "--allow-empty");
df478b74 962
a3ec9eaf 963 if (!(flags & EDIT_MSG))
07d968ef 964 argv_array_push(&cmd.args, "--allow-empty-message");
4bee9584 965
34bec2c4
AG
966 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
967 return run_command_silent_on_success(&cmd);
968 else
969 return run_command(&cmd);
b27cfb0d
NH
970}
971
d0aaa46f
PW
972static int rest_is_empty(const struct strbuf *sb, int start)
973{
974 int i, eol;
975 const char *nl;
976
977 /* Check if the rest is just whitespace and Signed-off-by's. */
978 for (i = start; i < sb->len; i++) {
979 nl = memchr(sb->buf + i, '\n', sb->len - i);
980 if (nl)
981 eol = nl - sb->buf;
982 else
983 eol = sb->len;
984
985 if (strlen(sign_off_header) <= eol - i &&
986 starts_with(sb->buf + i, sign_off_header)) {
987 i = eol;
988 continue;
989 }
990 while (i < eol)
991 if (!isspace(sb->buf[i++]))
992 return 0;
993 }
994
995 return 1;
996}
997
f29cd862
DL
998void cleanup_message(struct strbuf *msgbuf,
999 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1000{
1001 if (verbose || /* Truncate the message just before the diff, if any. */
1002 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1003 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1004 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1005 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1006}
1007
d0aaa46f
PW
1008/*
1009 * Find out if the message in the strbuf contains only whitespace and
1010 * Signed-off-by lines.
1011 */
1012int message_is_empty(const struct strbuf *sb,
1013 enum commit_msg_cleanup_mode cleanup_mode)
1014{
1015 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1016 return 0;
1017 return rest_is_empty(sb, 0);
1018}
1019
1020/*
1021 * See if the user edited the message in the editor or left what
1022 * was in the template intact
1023 */
1024int template_untouched(const struct strbuf *sb, const char *template_file,
1025 enum commit_msg_cleanup_mode cleanup_mode)
1026{
1027 struct strbuf tmpl = STRBUF_INIT;
1028 const char *start;
1029
1030 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1031 return 0;
1032
1033 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1034 return 0;
1035
1036 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1037 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1038 start = sb->buf;
1039 strbuf_release(&tmpl);
1040 return rest_is_empty(sb, start - sb->buf);
1041}
1042
0505d604
PW
1043int update_head_with_reflog(const struct commit *old_head,
1044 const struct object_id *new_head,
1045 const char *action, const struct strbuf *msg,
1046 struct strbuf *err)
1047{
1048 struct ref_transaction *transaction;
1049 struct strbuf sb = STRBUF_INIT;
1050 const char *nl;
1051 int ret = 0;
1052
1053 if (action) {
1054 strbuf_addstr(&sb, action);
1055 strbuf_addstr(&sb, ": ");
1056 }
1057
1058 nl = strchr(msg->buf, '\n');
1059 if (nl) {
1060 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1061 } else {
1062 strbuf_addbuf(&sb, msg);
1063 strbuf_addch(&sb, '\n');
1064 }
1065
1066 transaction = ref_transaction_begin(err);
1067 if (!transaction ||
1068 ref_transaction_update(transaction, "HEAD", new_head,
1069 old_head ? &old_head->object.oid : &null_oid,
1070 0, sb.buf, err) ||
1071 ref_transaction_commit(transaction, err)) {
1072 ret = -1;
1073 }
1074 ref_transaction_free(transaction);
1075 strbuf_release(&sb);
1076
1077 return ret;
1078}
1079
a87a6f3c
PW
1080static int run_rewrite_hook(const struct object_id *oldoid,
1081 const struct object_id *newoid)
1082{
1083 struct child_process proc = CHILD_PROCESS_INIT;
1084 const char *argv[3];
1085 int code;
1086 struct strbuf sb = STRBUF_INIT;
1087
1088 argv[0] = find_hook("post-rewrite");
1089 if (!argv[0])
1090 return 0;
1091
1092 argv[1] = "amend";
1093 argv[2] = NULL;
1094
1095 proc.argv = argv;
1096 proc.in = -1;
1097 proc.stdout_to_stderr = 1;
6206286e 1098 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1099
1100 code = start_command(&proc);
1101 if (code)
1102 return code;
1103 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1104 sigchain_push(SIGPIPE, SIG_IGN);
1105 write_in_full(proc.in, sb.buf, sb.len);
1106 close(proc.in);
1107 strbuf_release(&sb);
1108 sigchain_pop(SIGPIPE);
1109 return finish_command(&proc);
1110}
1111
1d18d758
NTND
1112void commit_post_rewrite(struct repository *r,
1113 const struct commit *old_head,
a87a6f3c
PW
1114 const struct object_id *new_head)
1115{
1116 struct notes_rewrite_cfg *cfg;
1117
1118 cfg = init_copy_notes_for_rewrite("amend");
1119 if (cfg) {
1120 /* we are amending, so old_head is not NULL */
1121 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1122 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1123 }
1124 run_rewrite_hook(&old_head->object.oid, new_head);
1125}
1126
f11c9580
NTND
1127static int run_prepare_commit_msg_hook(struct repository *r,
1128 struct strbuf *msg,
1129 const char *commit)
66618a50 1130{
49697cb7
PW
1131 int ret = 0;
1132 const char *name, *arg1 = NULL, *arg2 = NULL;
66618a50
PW
1133
1134 name = git_path_commit_editmsg();
1135 if (write_message(msg->buf, msg->len, name, 0))
1136 return -1;
1137
49697cb7
PW
1138 if (commit) {
1139 arg1 = "commit";
1140 arg2 = commit;
1141 } else {
1142 arg1 = "message";
1143 }
1144 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1145 arg1, arg2, NULL))
66618a50 1146 ret = error(_("'prepare-commit-msg' hook failed"));
66618a50
PW
1147
1148 return ret;
1149}
1150
e47c6caf
PW
1151static const char implicit_ident_advice_noconfig[] =
1152N_("Your name and email address were configured automatically based\n"
1153"on your username and hostname. Please check that they are accurate.\n"
1154"You can suppress this message by setting them explicitly. Run the\n"
1155"following command and follow the instructions in your editor to edit\n"
1156"your configuration file:\n"
1157"\n"
1158" git config --global --edit\n"
1159"\n"
1160"After doing this, you may fix the identity used for this commit with:\n"
1161"\n"
1162" git commit --amend --reset-author\n");
1163
1164static const char implicit_ident_advice_config[] =
1165N_("Your name and email address were configured automatically based\n"
1166"on your username and hostname. Please check that they are accurate.\n"
1167"You can suppress this message by setting them explicitly:\n"
1168"\n"
1169" git config --global user.name \"Your Name\"\n"
1170" git config --global user.email you@example.com\n"
1171"\n"
1172"After doing this, you may fix the identity used for this commit with:\n"
1173"\n"
1174" git commit --amend --reset-author\n");
1175
1176static const char *implicit_ident_advice(void)
1177{
1178 char *user_config = expand_user_path("~/.gitconfig", 0);
1179 char *xdg_config = xdg_config_home("config");
1180 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1181
1182 free(user_config);
1183 free(xdg_config);
1184
1185 if (config_exists)
1186 return _(implicit_ident_advice_config);
1187 else
1188 return _(implicit_ident_advice_noconfig);
1189
1190}
1191
f11c9580
NTND
1192void print_commit_summary(struct repository *r,
1193 const char *prefix,
1194 const struct object_id *oid,
e47c6caf
PW
1195 unsigned int flags)
1196{
1197 struct rev_info rev;
1198 struct commit *commit;
1199 struct strbuf format = STRBUF_INIT;
1200 const char *head;
1201 struct pretty_print_context pctx = {0};
1202 struct strbuf author_ident = STRBUF_INIT;
1203 struct strbuf committer_ident = STRBUF_INIT;
1204
f11c9580 1205 commit = lookup_commit(r, oid);
e47c6caf
PW
1206 if (!commit)
1207 die(_("couldn't look up newly created commit"));
1208 if (parse_commit(commit))
1209 die(_("could not parse newly created commit"));
1210
1211 strbuf_addstr(&format, "format:%h] %s");
1212
1213 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1214 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1215 if (strbuf_cmp(&author_ident, &committer_ident)) {
1216 strbuf_addstr(&format, "\n Author: ");
1217 strbuf_addbuf_percentquote(&format, &author_ident);
1218 }
1219 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1220 struct strbuf date = STRBUF_INIT;
1221
1222 format_commit_message(commit, "%ad", &date, &pctx);
1223 strbuf_addstr(&format, "\n Date: ");
1224 strbuf_addbuf_percentquote(&format, &date);
1225 strbuf_release(&date);
1226 }
1227 if (!committer_ident_sufficiently_given()) {
1228 strbuf_addstr(&format, "\n Committer: ");
1229 strbuf_addbuf_percentquote(&format, &committer_ident);
1230 if (advice_implicit_identity) {
1231 strbuf_addch(&format, '\n');
1232 strbuf_addstr(&format, implicit_ident_advice());
1233 }
1234 }
1235 strbuf_release(&author_ident);
1236 strbuf_release(&committer_ident);
1237
f11c9580 1238 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1239 setup_revisions(0, NULL, &rev, NULL);
1240
1241 rev.diff = 1;
1242 rev.diffopt.output_format =
1243 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1244
1245 rev.verbose_header = 1;
1246 rev.show_root_diff = 1;
1247 get_commit_format(format.buf, &rev);
1248 rev.always_show_header = 0;
0f57f731 1249 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1250 rev.diffopt.break_opt = 0;
1251 diff_setup_done(&rev.diffopt);
1252
1253 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1254 if (!head)
1255 die_errno(_("unable to resolve HEAD after creating commit"));
1256 if (!strcmp(head, "HEAD"))
1257 head = _("detached HEAD");
1258 else
1259 skip_prefix(head, "refs/heads/", &head);
1260 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1261 _(" (root-commit)") : "");
1262
1263 if (!log_tree_commit(&rev, commit)) {
1264 rev.always_show_header = 1;
1265 rev.use_terminator = 1;
1266 log_tree_commit(&rev, commit);
1267 }
1268
1269 strbuf_release(&format);
1270}
1271
005af339 1272static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1273{
1274 struct commit *current_head;
1275 struct object_id oid;
1276
1277 if (get_oid("HEAD", &oid)) {
1278 current_head = NULL;
1279 } else {
005af339 1280 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1281 if (!current_head)
1282 return error(_("could not parse HEAD"));
9001dc2a 1283 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1284 warning(_("HEAD %s is not a commit!"),
1285 oid_to_hex(&oid));
1286 }
1287 if (parse_commit(current_head))
1288 return error(_("could not parse HEAD commit"));
1289 }
1290 *head = current_head;
1291
1292 return 0;
1293}
1294
1295/*
1296 * Try to commit without forking 'git commit'. In some cases we need
1297 * to run 'git commit' to display an error message
1298 *
1299 * Returns:
1300 * -1 - error unable to commit
1301 * 0 - success
1302 * 1 - run 'git commit'
1303 */
f11c9580
NTND
1304static int try_to_commit(struct repository *r,
1305 struct strbuf *msg, const char *author,
356ee465
PW
1306 struct replay_opts *opts, unsigned int flags,
1307 struct object_id *oid)
1308{
1309 struct object_id tree;
b0a31861 1310 struct commit *current_head = NULL;
356ee465
PW
1311 struct commit_list *parents = NULL;
1312 struct commit_extra_header *extra = NULL;
1313 struct strbuf err = STRBUF_INIT;
66618a50 1314 struct strbuf commit_msg = STRBUF_INIT;
4d924528 1315 char *amend_author = NULL;
66618a50 1316 const char *hook_commit = NULL;
356ee465
PW
1317 enum commit_msg_cleanup_mode cleanup;
1318 int res = 0;
1319
005af339 1320 if (parse_head(r, &current_head))
356ee465 1321 return -1;
4d924528 1322
356ee465
PW
1323 if (flags & AMEND_MSG) {
1324 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1325 const char *out_enc = get_commit_output_encoding();
1326 const char *message = logmsg_reencode(current_head, NULL,
1327 out_enc);
1328
1329 if (!msg) {
1330 const char *orig_message = NULL;
1331
1332 find_commit_subject(message, &orig_message);
66618a50 1333 msg = &commit_msg;
356ee465 1334 strbuf_addstr(msg, orig_message);
66618a50 1335 hook_commit = "HEAD";
356ee465 1336 }
4d924528 1337 author = amend_author = get_author(message);
356ee465
PW
1338 unuse_commit_buffer(current_head, message);
1339 if (!author) {
1340 res = error(_("unable to parse commit author"));
1341 goto out;
1342 }
1343 parents = copy_commit_list(current_head->parents);
1344 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
b0a31861
PW
1345 } else if (current_head &&
1346 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
356ee465
PW
1347 commit_list_insert(current_head, &parents);
1348 }
1349
f11c9580 1350 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1351 res = error(_("git write-tree failed to write a tree"));
1352 goto out;
1353 }
1354
2d05ef27
PW
1355 if (!(flags & ALLOW_EMPTY)) {
1356 struct commit *first_parent = current_head;
1357
1358 if (flags & AMEND_MSG) {
1359 if (current_head->parents) {
1360 first_parent = current_head->parents->item;
1361 if (repo_parse_commit(r, first_parent)) {
1362 res = error(_("could not parse HEAD commit"));
1363 goto out;
1364 }
1365 } else {
1366 first_parent = NULL;
1367 }
1368 }
1369 if (oideq(first_parent
1370 ? get_commit_tree_oid(first_parent)
1371 : the_hash_algo->empty_tree,
1372 &tree)) {
1373 res = 1; /* run 'git commit' to display error message */
1374 goto out;
1375 }
356ee465
PW
1376 }
1377
66618a50 1378 if (find_hook("prepare-commit-msg")) {
f11c9580 1379 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1380 if (res)
1381 goto out;
1382 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1383 2048) < 0) {
1384 res = error_errno(_("unable to read commit message "
1385 "from '%s'"),
1386 git_path_commit_editmsg());
1387 goto out;
1388 }
1389 msg = &commit_msg;
1390 }
1391
d74f3e58
PW
1392 if (flags & CLEANUP_MSG)
1393 cleanup = COMMIT_MSG_CLEANUP_ALL;
1394 else if ((opts->signoff || opts->record_origin) &&
1395 !opts->explicit_cleanup)
1396 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1397 else
1398 cleanup = opts->default_msg_cleanup;
66618a50
PW
1399
1400 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1401 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
a3ec9eaf 1402 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1403 res = 1; /* run 'git commit' to display error message */
1404 goto out;
1405 }
1406
12f7babd
JS
1407 reset_ident_date();
1408
8be8342b
JH
1409 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1410 oid, author, opts->gpg_sign, extra)) {
356ee465
PW
1411 res = error(_("failed to write commit object"));
1412 goto out;
1413 }
1414
1415 if (update_head_with_reflog(current_head, oid,
1416 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1417 res = error("%s", err.buf);
1418 goto out;
1419 }
1420
4627bc77 1421 run_commit_hook(0, r->index_file, "post-commit", NULL);
356ee465 1422 if (flags & AMEND_MSG)
1d18d758 1423 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1424
1425out:
1426 free_commit_extra_headers(extra);
1427 strbuf_release(&err);
66618a50 1428 strbuf_release(&commit_msg);
4d924528 1429 free(amend_author);
356ee465
PW
1430
1431 return res;
1432}
1433
f11c9580
NTND
1434static int do_commit(struct repository *r,
1435 const char *msg_file, const char *author,
356ee465
PW
1436 struct replay_opts *opts, unsigned int flags)
1437{
1438 int res = 1;
1439
b0a31861 1440 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
356ee465
PW
1441 struct object_id oid;
1442 struct strbuf sb = STRBUF_INIT;
1443
1444 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1445 return error_errno(_("unable to read commit message "
1446 "from '%s'"),
1447 msg_file);
1448
f11c9580
NTND
1449 res = try_to_commit(r, msg_file ? &sb : NULL,
1450 author, opts, flags, &oid);
356ee465
PW
1451 strbuf_release(&sb);
1452 if (!res) {
f11c9580
NTND
1453 unlink(git_path_cherry_pick_head(r));
1454 unlink(git_path_merge_msg(r));
356ee465 1455 if (!is_rebase_i(opts))
f11c9580 1456 print_commit_summary(r, NULL, &oid,
356ee465
PW
1457 SUMMARY_SHOW_AUTHOR_DATE);
1458 return res;
1459 }
1460 }
1461 if (res == 1)
f11c9580 1462 return run_git_commit(r, msg_file, opts, flags);
356ee465
PW
1463
1464 return res;
1465}
1466
b27cfb0d
NH
1467static int is_original_commit_empty(struct commit *commit)
1468{
092bbcdf 1469 const struct object_id *ptree_oid;
b27cfb0d
NH
1470
1471 if (parse_commit(commit))
aee42e1f 1472 return error(_("could not parse commit %s"),
f2fd0760 1473 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1474 if (commit->parents) {
1475 struct commit *parent = commit->parents->item;
1476 if (parse_commit(parent))
aee42e1f 1477 return error(_("could not parse parent commit %s"),
f2fd0760 1478 oid_to_hex(&parent->object.oid));
2e27bd77 1479 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1480 } else {
eb0ccfd7 1481 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1482 }
043a4492 1483
4a7e27e9 1484 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1485}
1486
ac2b0e8f 1487/*
e98c4269
EN
1488 * Should empty commits be allowed? Return status:
1489 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1490 * 0: Halt on empty commit
1491 * 1: Allow empty commit
1492 * 2: Drop empty commit
ac2b0e8f 1493 */
f11c9580
NTND
1494static int allow_empty(struct repository *r,
1495 struct replay_opts *opts,
1496 struct commit *commit)
ac2b0e8f 1497{
d48e5e21 1498 int index_unchanged, originally_empty;
ac2b0e8f
JH
1499
1500 /*
e98c4269 1501 * Four cases:
ac2b0e8f
JH
1502 *
1503 * (1) we do not allow empty at all and error out.
1504 *
e98c4269
EN
1505 * (2) we allow ones that were initially empty, and
1506 * just drop the ones that become empty
ac2b0e8f 1507 *
e98c4269
EN
1508 * (3) we allow ones that were initially empty, but
1509 * halt for the ones that become empty;
1510 *
1511 * (4) we allow both.
ac2b0e8f
JH
1512 */
1513 if (!opts->allow_empty)
1514 return 0; /* let "git commit" barf as necessary */
1515
005af339 1516 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1517 if (index_unchanged < 0)
1518 return index_unchanged;
1519 if (!index_unchanged)
1520 return 0; /* we do not have to say --allow-empty */
1521
1522 if (opts->keep_redundant_commits)
1523 return 1;
1524
d48e5e21
EN
1525 originally_empty = is_original_commit_empty(commit);
1526 if (originally_empty < 0)
1527 return originally_empty;
e98c4269 1528 if (originally_empty)
ac2b0e8f 1529 return 1;
e98c4269
EN
1530 else if (opts->drop_redundant_commits)
1531 return 2;
1532 else
1533 return 0;
ac2b0e8f
JH
1534}
1535
414697a9
JS
1536static struct {
1537 char c;
1538 const char *str;
1539} todo_command_info[] = {
1540 { 'p', "pick" },
1541 { 0, "revert" },
1542 { 'e', "edit" },
04efc8b5 1543 { 'r', "reword" },
414697a9
JS
1544 { 'f', "fixup" },
1545 { 's', "squash" },
1546 { 'x', "exec" },
71f82465 1547 { 'b', "break" },
9055e401
JS
1548 { 'l', "label" },
1549 { 't', "reset" },
4c68e7dd 1550 { 'm', "merge" },
b3fdd581 1551 { 0, "noop" },
ac191470
JS
1552 { 'd', "drop" },
1553 { 0, NULL }
004fefa7
JS
1554};
1555
1556static const char *command_to_string(const enum todo_command command)
1557{
ac191470 1558 if (command < TODO_COMMENT)
414697a9 1559 return todo_command_info[command].str;
02127c63 1560 die(_("unknown command: %d"), command);
004fefa7
JS
1561}
1562
ee5462d6 1563static char command_to_char(const enum todo_command command)
d8ae6c84
LB
1564{
1565 if (command < TODO_COMMENT && todo_command_info[command].c)
1566 return todo_command_info[command].c;
1567 return comment_line_char;
1568}
1569
25c43667
JS
1570static int is_noop(const enum todo_command command)
1571{
b3fdd581 1572 return TODO_NOOP <= command;
25c43667 1573}
004fefa7 1574
6e98de72
JS
1575static int is_fixup(enum todo_command command)
1576{
1577 return command == TODO_FIXUP || command == TODO_SQUASH;
1578}
1579
d87d48b2
JS
1580/* Does this command create a (non-merge) commit? */
1581static int is_pick_or_similar(enum todo_command command)
1582{
1583 switch (command) {
1584 case TODO_PICK:
1585 case TODO_REVERT:
1586 case TODO_EDIT:
1587 case TODO_REWORD:
1588 case TODO_FIXUP:
1589 case TODO_SQUASH:
1590 return 1;
1591 default:
1592 return 0;
1593 }
1594}
1595
005af339
NTND
1596static int update_squash_messages(struct repository *r,
1597 enum todo_command command,
1598 struct commit *commit,
1599 struct replay_opts *opts)
6e98de72
JS
1600{
1601 struct strbuf buf = STRBUF_INIT;
e12a7ef5 1602 int res;
6e98de72 1603 const char *message, *body;
b3757442 1604 const char *encoding = get_commit_output_encoding();
6e98de72 1605
e12a7ef5 1606 if (opts->current_fixup_count > 0) {
6e98de72 1607 struct strbuf header = STRBUF_INIT;
e12a7ef5 1608 char *eol;
6e98de72 1609
e12a7ef5 1610 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1611 return error(_("could not read '%s'"),
1612 rebase_path_squash_msg());
1613
e12a7ef5
JS
1614 eol = buf.buf[0] != comment_line_char ?
1615 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1616
1617 strbuf_addf(&header, "%c ", comment_line_char);
e12a7ef5
JS
1618 strbuf_addf(&header, _("This is a combination of %d commits."),
1619 opts->current_fixup_count + 2);
6e98de72
JS
1620 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1621 strbuf_release(&header);
1622 } else {
33d66df3 1623 struct object_id head;
6e98de72
JS
1624 struct commit *head_commit;
1625 const char *head_message, *body;
1626
33d66df3 1627 if (get_oid("HEAD", &head))
6e98de72 1628 return error(_("need a HEAD to fixup"));
005af339 1629 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72 1630 return error(_("could not read HEAD"));
b3757442 1631 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
6e98de72
JS
1632 return error(_("could not read HEAD's commit message"));
1633
1634 find_commit_subject(head_message, &body);
1635 if (write_message(body, strlen(body),
1636 rebase_path_fixup_msg(), 0)) {
1637 unuse_commit_buffer(head_commit, head_message);
1638 return error(_("cannot write '%s'"),
1639 rebase_path_fixup_msg());
1640 }
1641
6e98de72 1642 strbuf_addf(&buf, "%c ", comment_line_char);
e12a7ef5 1643 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
6e98de72
JS
1644 strbuf_addf(&buf, "\n%c ", comment_line_char);
1645 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1646 strbuf_addstr(&buf, "\n\n");
1647 strbuf_addstr(&buf, body);
1648
1649 unuse_commit_buffer(head_commit, head_message);
1650 }
1651
b3757442 1652 if (!(message = logmsg_reencode(commit, NULL, encoding)))
6e98de72
JS
1653 return error(_("could not read commit message of %s"),
1654 oid_to_hex(&commit->object.oid));
1655 find_commit_subject(message, &body);
1656
1657 if (command == TODO_SQUASH) {
1658 unlink(rebase_path_fixup_msg());
1659 strbuf_addf(&buf, "\n%c ", comment_line_char);
e12a7ef5 1660 strbuf_addf(&buf, _("This is the commit message #%d:"),
dd2e36eb 1661 ++opts->current_fixup_count + 1);
6e98de72
JS
1662 strbuf_addstr(&buf, "\n\n");
1663 strbuf_addstr(&buf, body);
1664 } else if (command == TODO_FIXUP) {
1665 strbuf_addf(&buf, "\n%c ", comment_line_char);
1666 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
dd2e36eb 1667 ++opts->current_fixup_count + 1);
6e98de72
JS
1668 strbuf_addstr(&buf, "\n\n");
1669 strbuf_add_commented_lines(&buf, body, strlen(body));
1670 } else
1671 return error(_("unknown command: %d"), command);
1672 unuse_commit_buffer(commit, message);
1673
1674 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1675 strbuf_release(&buf);
e12a7ef5
JS
1676
1677 if (!res) {
1678 strbuf_addf(&opts->current_fixups, "%s%s %s",
1679 opts->current_fixups.len ? "\n" : "",
1680 command_to_string(command),
1681 oid_to_hex(&commit->object.oid));
1682 res = write_message(opts->current_fixups.buf,
1683 opts->current_fixups.len,
1684 rebase_path_current_fixups(), 0);
1685 }
1686
6e98de72
JS
1687 return res;
1688}
1689
3b335762
NTND
1690static void flush_rewritten_pending(void)
1691{
25cb8df9 1692 struct strbuf buf = STRBUF_INIT;
092bbcdf 1693 struct object_id newoid;
25cb8df9
JS
1694 FILE *out;
1695
092bbcdf 1696 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1697 !get_oid("HEAD", &newoid) &&
e9d983f1 1698 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
1699 char *bol = buf.buf, *eol;
1700
1701 while (*bol) {
1702 eol = strchrnul(bol, '\n');
1703 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 1704 bol, oid_to_hex(&newoid));
25cb8df9
JS
1705 if (!*eol)
1706 break;
1707 bol = eol + 1;
1708 }
1709 fclose(out);
1710 unlink(rebase_path_rewritten_pending());
1711 }
1712 strbuf_release(&buf);
1713}
1714
1715static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
1716 enum todo_command next_command)
1717{
e9d983f1 1718 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
1719
1720 if (!out)
1721 return;
1722
1723 fprintf(out, "%s\n", oid_to_hex(oid));
1724 fclose(out);
1725
1726 if (!is_fixup(next_command))
1727 flush_rewritten_pending();
1728}
1729
f11c9580
NTND
1730static int do_pick_commit(struct repository *r,
1731 enum todo_command command,
1732 struct commit *commit,
1733 struct replay_opts *opts,
a47ba3c7 1734 int final_fixup, int *check_todo)
043a4492 1735{
789b3eff 1736 unsigned int flags = opts->edit ? EDIT_MSG : 0;
f11c9580 1737 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
ace976b2 1738 struct object_id head;
043a4492
RR
1739 struct commit *base, *next, *parent;
1740 const char *base_label, *next_label;
356ee465 1741 char *author = NULL;
d74a4e57 1742 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 1743 struct strbuf msgbuf = STRBUF_INIT;
e98c4269 1744 int res, unborn = 0, reword = 0, allow, drop_commit;
043a4492
RR
1745
1746 if (opts->no_commit) {
1747 /*
1748 * We do not intend to commit immediately. We just want to
1749 * merge the differences in, so let's compute the tree
1750 * that represents the "current" state for merge-recursive
1751 * to work on.
1752 */
f11c9580 1753 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 1754 return error(_("your index file is unmerged."));
043a4492 1755 } else {
ace976b2 1756 unborn = get_oid("HEAD", &head);
d87d48b2
JS
1757 /* Do we want to generate a root commit? */
1758 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 1759 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
1760 if (is_fixup(command))
1761 return error(_("cannot fixup root commit"));
1762 flags |= CREATE_ROOT_COMMIT;
1763 unborn = 1;
1764 } else if (unborn)
eb0ccfd7 1765 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 1766 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 1767 NULL, 0))
e1ff0a32 1768 return error_dirty_index(r, opts);
043a4492 1769 }
f11c9580 1770 discard_index(r->index);
043a4492 1771
637666c8 1772 if (!commit->parents)
043a4492 1773 parent = NULL;
043a4492
RR
1774 else if (commit->parents->next) {
1775 /* Reverting or cherry-picking a merge commit */
1776 int cnt;
1777 struct commit_list *p;
1778
1779 if (!opts->mainline)
93b3df6f 1780 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 1781 oid_to_hex(&commit->object.oid));
043a4492
RR
1782
1783 for (cnt = 1, p = commit->parents;
1784 cnt != opts->mainline && p;
1785 cnt++)
1786 p = p->next;
1787 if (cnt != opts->mainline || !p)
93b3df6f 1788 return error(_("commit %s does not have parent %d"),
f2fd0760 1789 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 1790 parent = p->item;
37897bfc
SO
1791 } else if (1 < opts->mainline)
1792 /*
1793 * Non-first parent explicitly specified as mainline for
1794 * non-merge commit
1795 */
1796 return error(_("commit %s does not have parent %d"),
1797 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
1798 else
1799 parent = commit->parents->item;
1800
bcbb68be
JS
1801 if (get_message(commit, &msg) != 0)
1802 return error(_("cannot get commit message for %s"),
1803 oid_to_hex(&commit->object.oid));
1804
6e98de72 1805 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 1806 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
1807 (!parent && unborn))) {
1808 if (is_rebase_i(opts))
1809 write_author_script(msg.message);
f11c9580 1810 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
1811 opts);
1812 if (res || command != TODO_REWORD)
1813 goto leave;
450efe2d 1814 reword = 1;
bcbb68be
JS
1815 msg_file = NULL;
1816 goto fast_forward_edit;
1817 }
043a4492 1818 if (parent && parse_commit(parent) < 0)
004fefa7
JS
1819 /* TRANSLATORS: The first %s will be a "todo" command like
1820 "revert" or "pick", the second %s a SHA1. */
043a4492 1821 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
1822 command_to_string(command),
1823 oid_to_hex(&parent->object.oid));
043a4492 1824
043a4492
RR
1825 /*
1826 * "commit" is an existing commit. We would want to apply
1827 * the difference it introduces since its first parent "prev"
1828 * on top of the current HEAD if we are cherry-pick. Or the
1829 * reverse of it if we are revert.
1830 */
1831
004fefa7 1832 if (command == TODO_REVERT) {
043a4492
RR
1833 base = commit;
1834 base_label = msg.label;
1835 next = parent;
1836 next_label = msg.parent_label;
1837 strbuf_addstr(&msgbuf, "Revert \"");
1838 strbuf_addstr(&msgbuf, msg.subject);
1839 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 1840 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1841
1842 if (commit->parents && commit->parents->next) {
1843 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 1844 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1845 }
1846 strbuf_addstr(&msgbuf, ".\n");
1847 } else {
1848 const char *p;
1849
1850 base = parent;
1851 base_label = msg.parent_label;
1852 next = commit;
1853 next_label = msg.label;
1854
23aa5142
JS
1855 /* Append the commit log message to msgbuf. */
1856 if (find_commit_subject(msg.message, &p))
1857 strbuf_addstr(&msgbuf, p);
043a4492
RR
1858
1859 if (opts->record_origin) {
44dc738a 1860 strbuf_complete_line(&msgbuf);
bab4d109 1861 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1862 strbuf_addch(&msgbuf, '\n');
cd650a4e 1863 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1864 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1865 strbuf_addstr(&msgbuf, ")\n");
1866 }
356ee465
PW
1867 if (!is_fixup(command))
1868 author = get_author(msg.message);
043a4492
RR
1869 }
1870
04efc8b5 1871 if (command == TODO_REWORD)
450efe2d 1872 reword = 1;
04efc8b5 1873 else if (is_fixup(command)) {
005af339 1874 if (update_squash_messages(r, command, commit, opts))
6e98de72 1875 return -1;
789b3eff 1876 flags |= AMEND_MSG;
6e98de72
JS
1877 if (!final_fixup)
1878 msg_file = rebase_path_squash_msg();
1879 else if (file_exists(rebase_path_fixup_msg())) {
789b3eff 1880 flags |= CLEANUP_MSG;
6e98de72
JS
1881 msg_file = rebase_path_fixup_msg();
1882 } else {
f11c9580 1883 const char *dest = git_path_squash_msg(r);
6e98de72
JS
1884 unlink(dest);
1885 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1886 return error(_("could not rename '%s' to '%s'"),
1887 rebase_path_squash_msg(), dest);
f11c9580 1888 unlink(git_path_merge_msg(r));
6e98de72 1889 msg_file = dest;
789b3eff 1890 flags |= EDIT_MSG;
6e98de72
JS
1891 }
1892 }
1893
a852ec7f 1894 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
1895 append_signoff(&msgbuf, 0, 0);
1896
0473f28a
JS
1897 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1898 res = -1;
1899 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
f11c9580 1900 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 1901 &head, &msgbuf, opts);
f241ff0d 1902 if (res < 0)
19517fb9
SB
1903 goto leave;
1904
75871495 1905 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 1906 git_path_merge_msg(r), 0);
043a4492
RR
1907 } else {
1908 struct commit_list *common = NULL;
1909 struct commit_list *remotes = NULL;
1910
75871495 1911 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 1912 git_path_merge_msg(r), 0);
043a4492
RR
1913
1914 commit_list_insert(base, &common);
1915 commit_list_insert(next, &remotes);
f11c9580 1916 res |= try_merge_command(r, opts->strategy,
03a4e260 1917 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 1918 common, oid_to_hex(&head), remotes);
043a4492
RR
1919 free_commit_list(common);
1920 free_commit_list(remotes);
1921 }
452202c7 1922 strbuf_release(&msgbuf);
043a4492
RR
1923
1924 /*
1925 * If the merge was clean or if it failed due to conflict, we write
1926 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1927 * However, if the merge did not even start, then we don't want to
1928 * write it at all.
1929 */
004fefa7 1930 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
ae077771 1931 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 1932 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1933 res = -1;
004fefa7 1934 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 1935 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 1936 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1937 res = -1;
043a4492
RR
1938
1939 if (res) {
004fefa7 1940 error(command == TODO_REVERT
043a4492
RR
1941 ? _("could not revert %s... %s")
1942 : _("could not apply %s... %s"),
39755964 1943 short_commit_name(commit), msg.subject);
005af339 1944 print_advice(r, res == 1, opts);
f11c9580 1945 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 1946 goto leave;
043a4492
RR
1947 }
1948
e98c4269 1949 drop_commit = 0;
f11c9580 1950 allow = allow_empty(r, opts, commit);
706728a3
FC
1951 if (allow < 0) {
1952 res = allow;
1953 goto leave;
e98c4269 1954 } else if (allow == 1) {
789b3eff 1955 flags |= ALLOW_EMPTY;
e98c4269
EN
1956 } else if (allow == 2) {
1957 drop_commit = 1;
1958 fprintf(stderr,
1959 _("dropping %s %s -- patch contents already upstream\n"),
1960 oid_to_hex(&commit->object.oid), msg.subject);
1961 } /* else allow == 0 and there's nothing special to do */
1962 if (!opts->no_commit && !drop_commit) {
356ee465 1963 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
f11c9580 1964 res = do_commit(r, msg_file, author, opts, flags);
356ee465
PW
1965 else
1966 res = error(_("unable to parse commit author"));
a47ba3c7
PW
1967 *check_todo = !!(flags & EDIT_MSG);
1968 if (!res && reword) {
450efe2d
PW
1969fast_forward_edit:
1970 res = run_git_commit(r, NULL, opts, EDIT_MSG |
1971 VERIFY_MSG | AMEND_MSG |
1972 (flags & ALLOW_EMPTY));
a47ba3c7
PW
1973 *check_todo = 1;
1974 }
356ee465 1975 }
6e98de72 1976
450efe2d 1977
6e98de72
JS
1978 if (!res && final_fixup) {
1979 unlink(rebase_path_fixup_msg());
1980 unlink(rebase_path_squash_msg());
e12a7ef5
JS
1981 unlink(rebase_path_current_fixups());
1982 strbuf_reset(&opts->current_fixups);
1983 opts->current_fixup_count = 0;
6e98de72 1984 }
c8d1351d
FC
1985
1986leave:
d74a4e57 1987 free_message(commit, &msg);
356ee465 1988 free(author);
1e41229d 1989 update_abort_safety_file();
043a4492
RR
1990
1991 return res;
1992}
1993
c3e8618c 1994static int prepare_revs(struct replay_opts *opts)
043a4492 1995{
a73e22e9
MZ
1996 /*
1997 * picking (but not reverting) ranges (but not individual revisions)
1998 * should be done in reverse
1999 */
2000 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2001 opts->revs->reverse ^= 1;
2002
2003 if (prepare_revision_walk(opts->revs))
c3e8618c 2004 return error(_("revision walk setup failed"));
043a4492 2005
c3e8618c 2006 return 0;
043a4492
RR
2007}
2008
f11c9580
NTND
2009static int read_and_refresh_cache(struct repository *r,
2010 struct replay_opts *opts)
043a4492 2011{
14bca6c6 2012 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2013 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2014 if (repo_read_index(r) < 0) {
49fb937e 2015 rollback_lock_file(&index_lock);
0d9c6dc9 2016 return error(_("git %s: failed to read the index"),
c28cbc5e 2017 _(action_name(opts)));
49fb937e 2018 }
f11c9580 2019 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
61000814 2020 if (index_fd >= 0) {
f11c9580 2021 if (write_locked_index(r->index, &index_lock,
61000814 2022 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2023 return error(_("git %s: failed to refresh the index"),
c28cbc5e 2024 _(action_name(opts)));
49fb937e 2025 }
043a4492 2026 }
0d9c6dc9 2027 return 0;
043a4492
RR
2028}
2029
4c68e7dd
JS
2030enum todo_item_flags {
2031 TODO_EDIT_MERGE_MSG = 1
2032};
2033
5d94d545 2034void todo_list_release(struct todo_list *todo_list)
043a4492 2035{
004fefa7 2036 strbuf_release(&todo_list->buf);
6a83d902 2037 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2038 todo_list->nr = todo_list->alloc = 0;
2039}
043a4492 2040
004fefa7
JS
2041static struct todo_item *append_new_todo(struct todo_list *todo_list)
2042{
2043 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
8638114e 2044 todo_list->total_nr++;
004fefa7 2045 return todo_list->items + todo_list->nr++;
043a4492
RR
2046}
2047
6ad656db
AG
2048const char *todo_item_get_arg(struct todo_list *todo_list,
2049 struct todo_item *item)
2050{
2051 return todo_list->buf.buf + item->arg_offset;
2052}
2053
3e81bccd
PW
2054static int is_command(enum todo_command command, const char **bol)
2055{
2056 const char *str = todo_command_info[command].str;
2057 const char nick = todo_command_info[command].c;
2058 const char *p = *bol + 1;
2059
2060 return skip_prefix(*bol, str, bol) ||
2061 ((nick && **bol == nick) &&
2062 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2063 (*bol = p));
2064}
2065
005af339 2066static int parse_insn_line(struct repository *r, struct todo_item *item,
6ad656db 2067 const char *buf, const char *bol, char *eol)
043a4492 2068{
1e43ed98 2069 struct object_id commit_oid;
043a4492 2070 char *end_of_object_name;
004fefa7
JS
2071 int i, saved, status, padding;
2072
4c68e7dd
JS
2073 item->flags = 0;
2074
8f8550b3
JS
2075 /* left-trim */
2076 bol += strspn(bol, " \t");
2077
25c43667 2078 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2079 item->command = TODO_COMMENT;
25c43667 2080 item->commit = NULL;
6ad656db 2081 item->arg_offset = bol - buf;
25c43667
JS
2082 item->arg_len = eol - bol;
2083 return 0;
2084 }
2085
ac191470 2086 for (i = 0; i < TODO_COMMENT; i++)
3e81bccd 2087 if (is_command(i, &bol)) {
004fefa7
JS
2088 item->command = i;
2089 break;
2090 }
ac191470 2091 if (i >= TODO_COMMENT)
004fefa7 2092 return -1;
043a4492 2093
66afa24f
JS
2094 /* Eat up extra spaces/ tabs before object name */
2095 padding = strspn(bol, " \t");
2096 bol += padding;
2097
71f82465 2098 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2099 if (bol != eol)
2100 return error(_("%s does not accept arguments: '%s'"),
2101 command_to_string(item->command), bol);
25c43667 2102 item->commit = NULL;
6ad656db 2103 item->arg_offset = bol - buf;
25c43667
JS
2104 item->arg_len = eol - bol;
2105 return 0;
2106 }
2107
043a4492 2108 if (!padding)
66afa24f
JS
2109 return error(_("missing arguments for %s"),
2110 command_to_string(item->command));
043a4492 2111
9055e401
JS
2112 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2113 item->command == TODO_RESET) {
7dcbb3cb 2114 item->commit = NULL;
6ad656db 2115 item->arg_offset = bol - buf;
311af526
JS
2116 item->arg_len = (int)(eol - bol);
2117 return 0;
2118 }
2119
4c68e7dd
JS
2120 if (item->command == TODO_MERGE) {
2121 if (skip_prefix(bol, "-C", &bol))
2122 bol += strspn(bol, " \t");
2123 else if (skip_prefix(bol, "-c", &bol)) {
2124 bol += strspn(bol, " \t");
2125 item->flags |= TODO_EDIT_MERGE_MSG;
2126 } else {
2127 item->flags |= TODO_EDIT_MERGE_MSG;
2128 item->commit = NULL;
6ad656db 2129 item->arg_offset = bol - buf;
4c68e7dd
JS
2130 item->arg_len = (int)(eol - bol);
2131 return 0;
2132 }
2133 }
2134
004fefa7 2135 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2136 saved = *end_of_object_name;
2137 *end_of_object_name = '\0';
1e43ed98 2138 status = get_oid(bol, &commit_oid);
043a4492
RR
2139 *end_of_object_name = saved;
2140
6ad656db
AG
2141 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2142 item->arg_offset = bol - buf;
2143 item->arg_len = (int)(eol - bol);
c22f7dfb 2144
043a4492 2145 if (status < 0)
8b637cda
JS
2146 return error(_("could not parse '%.*s'"),
2147 (int)(end_of_object_name - bol), bol);
043a4492 2148
005af339 2149 item->commit = lookup_commit_reference(r, &commit_oid);
004fefa7 2150 return !item->commit;
043a4492
RR
2151}
2152
4a72486d
PW
2153int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2154{
ed5b1ca1 2155 const char *todo_file, *bol;
4a72486d 2156 struct strbuf buf = STRBUF_INIT;
ed5b1ca1 2157 int ret = 0;
4a72486d
PW
2158
2159 todo_file = git_path_todo_file();
2160 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
ed5b1ca1 2161 if (errno == ENOENT || errno == ENOTDIR)
4a72486d
PW
2162 return -1;
2163 else
2164 return error_errno("unable to open '%s'", todo_file);
2165 }
ed5b1ca1
PW
2166 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2167 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
4a72486d 2168 *action = REPLAY_PICK;
ed5b1ca1
PW
2169 else if (is_command(TODO_REVERT, &bol) &&
2170 (*bol == ' ' || *bol == '\t'))
4a72486d
PW
2171 *action = REPLAY_REVERT;
2172 else
ed5b1ca1 2173 ret = -1;
4a72486d 2174
4a72486d
PW
2175 strbuf_release(&buf);
2176
2177 return ret;
2178}
2179
5d94d545
AG
2180int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2181 struct todo_list *todo_list)
043a4492 2182{
004fefa7
JS
2183 struct todo_item *item;
2184 char *p = buf, *next_p;
6e98de72 2185 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2186
2b71595d
AG
2187 todo_list->current = todo_list->nr = 0;
2188
004fefa7 2189 for (i = 1; *p; i++, p = next_p) {
043a4492 2190 char *eol = strchrnul(p, '\n');
004fefa7
JS
2191
2192 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2193
6307041d
JS
2194 if (p != eol && eol[-1] == '\r')
2195 eol--; /* strip Carriage Return */
2196
004fefa7
JS
2197 item = append_new_todo(todo_list);
2198 item->offset_in_buf = p - todo_list->buf.buf;
6ad656db 2199 if (parse_insn_line(r, item, buf, p, eol)) {
93b3df6f 2200 res = error(_("invalid line %d: %.*s"),
004fefa7 2201 i, (int)(eol - p), p);
2b71595d 2202 item->command = TODO_COMMENT + 1;
6ad656db 2203 item->arg_offset = p - buf;
2b71595d
AG
2204 item->arg_len = (int)(eol - p);
2205 item->commit = NULL;
004fefa7 2206 }
6e98de72
JS
2207
2208 if (fixup_okay)
2209 ; /* do nothing */
2210 else if (is_fixup(item->command))
2211 return error(_("cannot '%s' without a previous commit"),
2212 command_to_string(item->command));
2213 else if (!is_noop(item->command))
2214 fixup_okay = 1;
043a4492 2215 }
52865279 2216
004fefa7 2217 return res;
043a4492
RR
2218}
2219
968492e4
JS
2220static int count_commands(struct todo_list *todo_list)
2221{
2222 int count = 0, i;
2223
2224 for (i = 0; i < todo_list->nr; i++)
2225 if (todo_list->items[i].command != TODO_COMMENT)
2226 count++;
2227
2228 return count;
2229}
2230
a01c2a5f
JS
2231static int get_item_line_offset(struct todo_list *todo_list, int index)
2232{
2233 return index < todo_list->nr ?
2234 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2235}
2236
2237static const char *get_item_line(struct todo_list *todo_list, int index)
2238{
2239 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2240}
2241
2242static int get_item_line_length(struct todo_list *todo_list, int index)
2243{
2244 return get_item_line_offset(todo_list, index + 1)
2245 - get_item_line_offset(todo_list, index);
2246}
2247
87805600
RS
2248static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2249{
2250 int fd;
2251 ssize_t len;
2252
2253 fd = open(path, O_RDONLY);
2254 if (fd < 0)
2255 return error_errno(_("could not open '%s'"), path);
2256 len = strbuf_read(sb, fd, 0);
2257 close(fd);
2258 if (len < 0)
2259 return error(_("could not read '%s'."), path);
2260 return len;
2261}
2262
b07d9bfd
PW
2263static int have_finished_the_last_pick(void)
2264{
2265 struct strbuf buf = STRBUF_INIT;
2266 const char *eol;
2267 const char *todo_path = git_path_todo_file();
2268 int ret = 0;
2269
2270 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2271 if (errno == ENOENT) {
2272 return 0;
2273 } else {
2274 error_errno("unable to open '%s'", todo_path);
2275 return 0;
2276 }
2277 }
2278 /* If there is only one line then we are done */
2279 eol = strchr(buf.buf, '\n');
2280 if (!eol || !eol[1])
2281 ret = 1;
2282
2283 strbuf_release(&buf);
2284
2285 return ret;
2286}
2287
f496b064 2288void sequencer_post_commit_cleanup(struct repository *r, int verbose)
b07d9bfd
PW
2289{
2290 struct replay_opts opts = REPLAY_OPTS_INIT;
2291 int need_cleanup = 0;
2292
2293 if (file_exists(git_path_cherry_pick_head(r))) {
f496b064
JH
2294 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2295 warning(_("cancelling a cherry picking in progress"));
b07d9bfd
PW
2296 opts.action = REPLAY_PICK;
2297 need_cleanup = 1;
2298 }
2299
2300 if (file_exists(git_path_revert_head(r))) {
f496b064
JH
2301 if (!unlink(git_path_revert_head(r)) && verbose)
2302 warning(_("cancelling a revert in progress"));
b07d9bfd
PW
2303 opts.action = REPLAY_REVERT;
2304 need_cleanup = 1;
2305 }
2306
2307 if (!need_cleanup)
2308 return;
2309
2310 if (!have_finished_the_last_pick())
2311 return;
2312
2313 sequencer_remove_state(&opts);
2314}
2315
3f34f2d8
AG
2316static void todo_list_write_total_nr(struct todo_list *todo_list)
2317{
2318 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2319
2320 if (f) {
2321 fprintf(f, "%d\n", todo_list->total_nr);
2322 fclose(f);
2323 }
2324}
2325
005af339
NTND
2326static int read_populate_todo(struct repository *r,
2327 struct todo_list *todo_list,
2328 struct replay_opts *opts)
043a4492 2329{
54fd3243 2330 struct stat st;
c0246501 2331 const char *todo_file = get_todo_path(opts);
87805600 2332 int res;
043a4492 2333
004fefa7 2334 strbuf_reset(&todo_list->buf);
87805600
RS
2335 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2336 return -1;
043a4492 2337
54fd3243
SH
2338 res = stat(todo_file, &st);
2339 if (res)
2340 return error(_("could not stat '%s'"), todo_file);
2341 fill_stat_data(&todo_list->stat, &st);
2342
5d94d545 2343 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2344 if (res) {
2345 if (is_rebase_i(opts))
2346 return error(_("please fix this using "
2347 "'git rebase --edit-todo'."));
93b3df6f 2348 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2349 }
2eeaf1b3 2350
52865279
JS
2351 if (!todo_list->nr &&
2352 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2353 return error(_("no commits parsed."));
2354
2eeaf1b3 2355 if (!is_rebase_i(opts)) {
004fefa7
JS
2356 enum todo_command valid =
2357 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2358 int i;
2359
2360 for (i = 0; i < todo_list->nr; i++)
2361 if (valid == todo_list->items[i].command)
2362 continue;
2363 else if (valid == TODO_PICK)
93b3df6f 2364 return error(_("cannot cherry-pick during a revert."));
004fefa7 2365 else
93b3df6f 2366 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2367 }
2368
968492e4
JS
2369 if (is_rebase_i(opts)) {
2370 struct todo_list done = TODO_LIST_INIT;
2371
2372 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
5d94d545 2373 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2374 todo_list->done_nr = count_commands(&done);
2375 else
2376 todo_list->done_nr = 0;
2377
2378 todo_list->total_nr = todo_list->done_nr
2379 + count_commands(todo_list);
968492e4 2380 todo_list_release(&done);
ef80069a 2381
3f34f2d8 2382 todo_list_write_total_nr(todo_list);
968492e4
JS
2383 }
2384
0ae42a03 2385 return 0;
043a4492
RR
2386}
2387
03a4e260
JS
2388static int git_config_string_dup(char **dest,
2389 const char *var, const char *value)
2390{
2391 if (!value)
2392 return config_error_nonbool(var);
2393 free(*dest);
2394 *dest = xstrdup(value);
2395 return 0;
2396}
2397
043a4492
RR
2398static int populate_opts_cb(const char *key, const char *value, void *data)
2399{
2400 struct replay_opts *opts = data;
2401 int error_flag = 1;
2402
2403 if (!value)
2404 error_flag = 0;
2405 else if (!strcmp(key, "options.no-commit"))
2406 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2407 else if (!strcmp(key, "options.edit"))
2408 opts->edit = git_config_bool_or_int(key, value, &error_flag);
6860ce5d
PW
2409 else if (!strcmp(key, "options.allow-empty"))
2410 opts->allow_empty =
2411 git_config_bool_or_int(key, value, &error_flag);
2412 else if (!strcmp(key, "options.allow-empty-message"))
2413 opts->allow_empty_message =
2414 git_config_bool_or_int(key, value, &error_flag);
2415 else if (!strcmp(key, "options.keep-redundant-commits"))
2416 opts->keep_redundant_commits =
2417 git_config_bool_or_int(key, value, &error_flag);
043a4492
RR
2418 else if (!strcmp(key, "options.signoff"))
2419 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2420 else if (!strcmp(key, "options.record-origin"))
2421 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2422 else if (!strcmp(key, "options.allow-ff"))
2423 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2424 else if (!strcmp(key, "options.mainline"))
2425 opts->mainline = git_config_int(key, value);
2426 else if (!strcmp(key, "options.strategy"))
03a4e260 2427 git_config_string_dup(&opts->strategy, key, value);
3253553e 2428 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2429 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2430 else if (!strcmp(key, "options.strategy-option")) {
2431 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2432 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2433 } else if (!strcmp(key, "options.allow-rerere-auto"))
2434 opts->allow_rerere_auto =
2435 git_config_bool_or_int(key, value, &error_flag) ?
2436 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
2437 else if (!strcmp(key, "options.default-msg-cleanup")) {
2438 opts->explicit_cleanup = 1;
2439 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2440 } else
93b3df6f 2441 return error(_("invalid key: %s"), key);
043a4492
RR
2442
2443 if (!error_flag)
93b3df6f 2444 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
2445
2446 return 0;
2447}
2448
65850686 2449void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2450{
2451 int i;
65850686 2452 char *strategy_opts_string = raw_opts;
ca6c6b45 2453
0060041d
EN
2454 if (*strategy_opts_string == ' ')
2455 strategy_opts_string++;
65850686 2456
0060041d
EN
2457 opts->xopts_nr = split_cmdline(strategy_opts_string,
2458 (const char ***)&opts->xopts);
ca6c6b45
JS
2459 for (i = 0; i < opts->xopts_nr; i++) {
2460 const char *arg = opts->xopts[i];
2461
2462 skip_prefix(arg, "--", &arg);
2463 opts->xopts[i] = xstrdup(arg);
2464 }
2465}
2466
65850686
AG
2467static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2468{
2469 strbuf_reset(buf);
2470 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2471 return;
2472 opts->strategy = strbuf_detach(buf, NULL);
2473 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2474 return;
2475
2476 parse_strategy_opts(opts, buf->buf);
2477}
2478
5adf9bdc 2479static int read_populate_opts(struct replay_opts *opts)
043a4492 2480{
a1c75762
JS
2481 if (is_rebase_i(opts)) {
2482 struct strbuf buf = STRBUF_INIT;
2483
2484 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2485 if (!starts_with(buf.buf, "-S"))
2486 strbuf_reset(&buf);
2487 else {
2488 free(opts->gpg_sign);
2489 opts->gpg_sign = xstrdup(buf.buf + 2);
2490 }
9b6d7a62
PW
2491 strbuf_reset(&buf);
2492 }
2493
2494 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2495 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2496 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2497 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2498 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2499 strbuf_reset(&buf);
a1c75762 2500 }
a1c75762 2501
556907f1
JS
2502 if (file_exists(rebase_path_verbose()))
2503 opts->verbose = 1;
2504
899b49c4
EN
2505 if (file_exists(rebase_path_quiet()))
2506 opts->quiet = 1;
2507
a852ec7f
PW
2508 if (file_exists(rebase_path_signoff())) {
2509 opts->allow_ff = 0;
2510 opts->signoff = 1;
2511 }
2512
d421afa0
JS
2513 if (file_exists(rebase_path_reschedule_failed_exec()))
2514 opts->reschedule_failed_exec = 1;
2515
e98c4269
EN
2516 if (file_exists(rebase_path_drop_redundant_commits()))
2517 opts->drop_redundant_commits = 1;
2518
2519 if (file_exists(rebase_path_keep_redundant_commits()))
2520 opts->keep_redundant_commits = 1;
2521
ca6c6b45
JS
2522 read_strategy_opts(opts, &buf);
2523 strbuf_release(&buf);
2524
e12a7ef5
JS
2525 if (read_oneliner(&opts->current_fixups,
2526 rebase_path_current_fixups(), 1)) {
2527 const char *p = opts->current_fixups.buf;
2528 opts->current_fixup_count = 1;
2529 while ((p = strchr(p, '\n'))) {
2530 opts->current_fixup_count++;
2531 p++;
2532 }
2533 }
2534
d87d48b2
JS
2535 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2536 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2537 return error(_("unusable squash-onto"));
2538 opts->have_squash_onto = 1;
2539 }
2540
b5a67045 2541 return 0;
a1c75762 2542 }
b5a67045 2543
f932729c 2544 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
2545 return 0;
2546 /*
2547 * The function git_parse_source(), called from git_config_from_file(),
2548 * may die() in case of a syntactically incorrect file. We do not care
2549 * about this case, though, because we wrote that file ourselves, so we
2550 * are pretty certain that it is syntactically correct.
2551 */
5adf9bdc 2552 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 2553 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
2554 git_path_opts_file());
2555 return 0;
043a4492
RR
2556}
2557
65850686
AG
2558static void write_strategy_opts(struct replay_opts *opts)
2559{
2560 int i;
2561 struct strbuf buf = STRBUF_INIT;
2562
2563 for (i = 0; i < opts->xopts_nr; ++i)
2564 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2565
2566 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2567 strbuf_release(&buf);
2568}
2569
2570int write_basic_state(struct replay_opts *opts, const char *head_name,
7d3488eb 2571 struct commit *onto, const char *orig_head)
65850686 2572{
65850686
AG
2573 if (head_name)
2574 write_file(rebase_path_head_name(), "%s\n", head_name);
2575 if (onto)
7d3488eb
PW
2576 write_file(rebase_path_onto(), "%s\n",
2577 oid_to_hex(&onto->object.oid));
65850686
AG
2578 if (orig_head)
2579 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2580
8a997ed1
EN
2581 if (opts->quiet)
2582 write_file(rebase_path_quiet(), "%s", "");
65850686 2583 if (opts->verbose)
4af51741 2584 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
2585 if (opts->strategy)
2586 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2587 if (opts->xopts_nr > 0)
2588 write_strategy_opts(opts);
2589
2590 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2591 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2592 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2593 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2594
2595 if (opts->gpg_sign)
2596 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2597 if (opts->signoff)
2598 write_file(rebase_path_signoff(), "--signoff\n");
e98c4269
EN
2599 if (opts->drop_redundant_commits)
2600 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2601 if (opts->keep_redundant_commits)
2602 write_file(rebase_path_keep_redundant_commits(), "%s", "");
d421afa0
JS
2603 if (opts->reschedule_failed_exec)
2604 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
65850686
AG
2605
2606 return 0;
2607}
2608
004fefa7 2609static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
2610 struct replay_opts *opts)
2611{
004fefa7
JS
2612 enum todo_command command = opts->action == REPLAY_PICK ?
2613 TODO_PICK : TODO_REVERT;
414697a9 2614 const char *command_string = todo_command_info[command].str;
019a9d83 2615 const char *encoding;
043a4492 2616 struct commit *commit;
043a4492 2617
34b0528b
JS
2618 if (prepare_revs(opts))
2619 return -1;
043a4492 2620
019a9d83
ĐTCD
2621 encoding = get_log_output_encoding();
2622
004fefa7
JS
2623 while ((commit = get_revision(opts->revs))) {
2624 struct todo_item *item = append_new_todo(todo_list);
019a9d83 2625 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
004fefa7
JS
2626 const char *subject;
2627 int subject_len;
2628
2629 item->command = command;
2630 item->commit = commit;
6ad656db 2631 item->arg_offset = 0;
c22f7dfb 2632 item->arg_len = 0;
004fefa7
JS
2633 item->offset_in_buf = todo_list->buf.len;
2634 subject_len = find_commit_subject(commit_buffer, &subject);
2635 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2636 short_commit_name(commit), subject_len, subject);
2637 unuse_commit_buffer(commit, commit_buffer);
2638 }
8530c739
JK
2639
2640 if (!todo_list->nr)
2641 return error(_("empty commit set passed"));
2642
34b0528b 2643 return 0;
043a4492
RR
2644}
2645
6a1f9046 2646static int create_seq_dir(struct repository *r)
043a4492 2647{
6a1f9046
RA
2648 enum replay_action action;
2649 const char *in_progress_error = NULL;
2650 const char *in_progress_advice = NULL;
dcb500dc
RA
2651 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2652 file_exists(git_path_cherry_pick_head(r));
6a1f9046
RA
2653
2654 if (!sequencer_get_last_command(r, &action)) {
2655 switch (action) {
2656 case REPLAY_REVERT:
2657 in_progress_error = _("revert is already in progress");
2658 in_progress_advice =
dcb500dc 2659 _("try \"git revert (--continue | %s--abort | --quit)\"");
6a1f9046
RA
2660 break;
2661 case REPLAY_PICK:
2662 in_progress_error = _("cherry-pick is already in progress");
2663 in_progress_advice =
dcb500dc 2664 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
6a1f9046
RA
2665 break;
2666 default:
2667 BUG("unexpected action in create_seq_dir");
2668 }
2669 }
2670 if (in_progress_error) {
2671 error("%s", in_progress_error);
2672 if (advice_sequencer_in_use)
dcb500dc
RA
2673 advise(in_progress_advice,
2674 advise_skip ? "--skip | " : "");
043a4492 2675 return -1;
6a1f9046
RA
2676 }
2677 if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 2678 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 2679 git_path_seq_dir());
6a1f9046 2680
043a4492
RR
2681 return 0;
2682}
2683
311fd397 2684static int save_head(const char *head)
043a4492 2685{
14bca6c6 2686 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
2687 struct strbuf buf = STRBUF_INIT;
2688 int fd;
ed3f9a12 2689 ssize_t written;
043a4492 2690
311fd397 2691 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 2692 if (fd < 0)
93b3df6f 2693 return error_errno(_("could not lock HEAD"));
043a4492 2694 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
2695 written = write_in_full(fd, buf.buf, buf.len);
2696 strbuf_release(&buf);
2697 if (written < 0) {
bf5c0571 2698 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 2699 rollback_lock_file(&head_lock);
bf5c0571 2700 return -1;
311fd397 2701 }
350292a1
2702 if (commit_lock_file(&head_lock) < 0)
2703 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 2704 return 0;
043a4492
RR
2705}
2706
1e41229d
SB
2707static int rollback_is_safe(void)
2708{
2709 struct strbuf sb = STRBUF_INIT;
2710 struct object_id expected_head, actual_head;
2711
2712 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2713 strbuf_trim(&sb);
2714 if (get_oid_hex(sb.buf, &expected_head)) {
2715 strbuf_release(&sb);
2716 die(_("could not parse %s"), git_path_abort_safety_file());
2717 }
2718 strbuf_release(&sb);
2719 }
2720 else if (errno == ENOENT)
2721 oidclr(&expected_head);
2722 else
2723 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2724
2725 if (get_oid("HEAD", &actual_head))
2726 oidclr(&actual_head);
2727
4a7e27e9 2728 return oideq(&actual_head, &expected_head);
1e41229d
SB
2729}
2730
918d1e6e 2731static int reset_merge(const struct object_id *oid)
043a4492 2732{
265ab48f
RA
2733 int ret;
2734 struct argv_array argv = ARGV_ARRAY_INIT;
1e41229d 2735
265ab48f
RA
2736 argv_array_pushl(&argv, "reset", "--merge", NULL);
2737
2738 if (!is_null_oid(oid))
2739 argv_array_push(&argv, oid_to_hex(oid));
1e41229d 2740
265ab48f
RA
2741 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2742 argv_array_clear(&argv);
2743
2744 return ret;
043a4492
RR
2745}
2746
005af339 2747static int rollback_single_pick(struct repository *r)
043a4492 2748{
092bbcdf 2749 struct object_id head_oid;
043a4492 2750
005af339
NTND
2751 if (!file_exists(git_path_cherry_pick_head(r)) &&
2752 !file_exists(git_path_revert_head(r)))
043a4492 2753 return error(_("no cherry-pick or revert in progress"));
34c290a6 2754 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 2755 return error(_("cannot resolve HEAD"));
092bbcdf 2756 if (is_null_oid(&head_oid))
043a4492 2757 return error(_("cannot abort from a branch yet to be born"));
918d1e6e 2758 return reset_merge(&head_oid);
043a4492
RR
2759}
2760
de81ca3f
RA
2761static int skip_single_pick(void)
2762{
2763 struct object_id head;
2764
2765 if (read_ref_full("HEAD", 0, &head, NULL))
2766 return error(_("cannot resolve HEAD"));
2767 return reset_merge(&head);
043a4492
RR
2768}
2769
005af339 2770int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 2771{
043a4492 2772 FILE *f;
092bbcdf 2773 struct object_id oid;
043a4492 2774 struct strbuf buf = STRBUF_INIT;
092bbcdf 2775 const char *p;
043a4492 2776
f932729c 2777 f = fopen(git_path_head_file(), "r");
043a4492
RR
2778 if (!f && errno == ENOENT) {
2779 /*
2780 * There is no multiple-cherry-pick in progress.
2781 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2782 * a single-cherry-pick in progress, abort that.
2783 */
005af339 2784 return rollback_single_pick(r);
043a4492
RR
2785 }
2786 if (!f)
f7ed1953 2787 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 2788 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 2789 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 2790 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
2791 fclose(f);
2792 goto fail;
2793 }
2794 fclose(f);
092bbcdf 2795 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 2796 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 2797 git_path_head_file());
043a4492
RR
2798 goto fail;
2799 }
092bbcdf 2800 if (is_null_oid(&oid)) {
0f974e21
MG
2801 error(_("cannot abort from a branch yet to be born"));
2802 goto fail;
2803 }
1e41229d
SB
2804
2805 if (!rollback_is_safe()) {
2806 /* Do not error, just do not rollback */
2807 warning(_("You seem to have moved HEAD. "
2808 "Not rewinding, check your HEAD!"));
2809 } else
918d1e6e 2810 if (reset_merge(&oid))
043a4492 2811 goto fail;
043a4492 2812 strbuf_release(&buf);
2863584f 2813 return sequencer_remove_state(opts);
043a4492
RR
2814fail:
2815 strbuf_release(&buf);
2816 return -1;
2817}
2818
de81ca3f
RA
2819int sequencer_skip(struct repository *r, struct replay_opts *opts)
2820{
2821 enum replay_action action = -1;
2822 sequencer_get_last_command(r, &action);
2823
2824 /*
2825 * Check whether the subcommand requested to skip the commit is actually
2826 * in progress and that it's safe to skip the commit.
2827 *
2828 * opts->action tells us which subcommand requested to skip the commit.
2829 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2830 * action is in progress and we can skip the commit.
2831 *
2832 * Otherwise we check that the last instruction was related to the
2833 * particular subcommand we're trying to execute and barf if that's not
2834 * the case.
2835 *
2836 * Finally we check that the rollback is "safe", i.e., has the HEAD
2837 * moved? In this case, it doesn't make sense to "reset the merge" and
2838 * "skip the commit" as the user already handled this by committing. But
2839 * we'd not want to barf here, instead give advice on how to proceed. We
2840 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2841 * it gets removed when the user commits, so if it still exists we're
2842 * sure the user can't have committed before.
2843 */
2844 switch (opts->action) {
2845 case REPLAY_REVERT:
2846 if (!file_exists(git_path_revert_head(r))) {
2847 if (action != REPLAY_REVERT)
2848 return error(_("no revert in progress"));
2849 if (!rollback_is_safe())
2850 goto give_advice;
2851 }
2852 break;
2853 case REPLAY_PICK:
2854 if (!file_exists(git_path_cherry_pick_head(r))) {
2855 if (action != REPLAY_PICK)
2856 return error(_("no cherry-pick in progress"));
2857 if (!rollback_is_safe())
2858 goto give_advice;
2859 }
2860 break;
2861 default:
2862 BUG("unexpected action in sequencer_skip");
2863 }
2864
2865 if (skip_single_pick())
2866 return error(_("failed to skip the commit"));
2867 if (!is_directory(git_path_seq_dir()))
2868 return 0;
2869
2870 return sequencer_continue(r, opts);
2871
2872give_advice:
2873 error(_("there is nothing to skip"));
2874
2875 if (advice_resolve_conflict) {
2876 advise(_("have you committed already?\n"
2877 "try \"git %s --continue\""),
2878 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2879 }
2880 return -1;
2881}
2882
004fefa7 2883static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2884{
14bca6c6 2885 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
2886 const char *todo_path = get_todo_path(opts);
2887 int next = todo_list->current, offset, fd;
043a4492 2888
84583957
JS
2889 /*
2890 * rebase -i writes "git-rebase-todo" without the currently executing
2891 * command, appending it to "done" instead.
2892 */
2893 if (is_rebase_i(opts))
2894 next++;
2895
004fefa7 2896 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 2897 if (fd < 0)
93b3df6f 2898 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 2899 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
2900 if (write_in_full(fd, todo_list->buf.buf + offset,
2901 todo_list->buf.len - offset) < 0)
93b3df6f 2902 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 2903 if (commit_lock_file(&todo_lock) < 0)
350292a1 2904 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 2905
a01c2a5f
JS
2906 if (is_rebase_i(opts) && next > 0) {
2907 const char *done = rebase_path_done();
2908 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2909 int ret = 0;
1df6df0c 2910
a01c2a5f
JS
2911 if (fd < 0)
2912 return 0;
2913 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2914 get_item_line_length(todo_list, next - 1))
2915 < 0)
2916 ret = error_errno(_("could not write to '%s'"), done);
2917 if (close(fd) < 0)
2918 ret = error_errno(_("failed to finalize '%s'"), done);
2919 return ret;
1df6df0c 2920 }
221675de 2921 return 0;
043a4492
RR
2922}
2923
88d5a271 2924static int save_opts(struct replay_opts *opts)
043a4492 2925{
f932729c 2926 const char *opts_file = git_path_opts_file();
88d5a271 2927 int res = 0;
043a4492
RR
2928
2929 if (opts->no_commit)
f59199d5
PW
2930 res |= git_config_set_in_file_gently(opts_file,
2931 "options.no-commit", "true");
043a4492 2932 if (opts->edit)
f59199d5
PW
2933 res |= git_config_set_in_file_gently(opts_file,
2934 "options.edit", "true");
6860ce5d
PW
2935 if (opts->allow_empty)
2936 res |= git_config_set_in_file_gently(opts_file,
2937 "options.allow-empty", "true");
2938 if (opts->allow_empty_message)
2939 res |= git_config_set_in_file_gently(opts_file,
2940 "options.allow-empty-message", "true");
2941 if (opts->keep_redundant_commits)
2942 res |= git_config_set_in_file_gently(opts_file,
2943 "options.keep-redundant-commits", "true");
043a4492 2944 if (opts->signoff)
f59199d5
PW
2945 res |= git_config_set_in_file_gently(opts_file,
2946 "options.signoff", "true");
043a4492 2947 if (opts->record_origin)
f59199d5
PW
2948 res |= git_config_set_in_file_gently(opts_file,
2949 "options.record-origin", "true");
043a4492 2950 if (opts->allow_ff)
f59199d5
PW
2951 res |= git_config_set_in_file_gently(opts_file,
2952 "options.allow-ff", "true");
043a4492
RR
2953 if (opts->mainline) {
2954 struct strbuf buf = STRBUF_INIT;
2955 strbuf_addf(&buf, "%d", opts->mainline);
f59199d5
PW
2956 res |= git_config_set_in_file_gently(opts_file,
2957 "options.mainline", buf.buf);
043a4492
RR
2958 strbuf_release(&buf);
2959 }
2960 if (opts->strategy)
f59199d5
PW
2961 res |= git_config_set_in_file_gently(opts_file,
2962 "options.strategy", opts->strategy);
3253553e 2963 if (opts->gpg_sign)
f59199d5
PW
2964 res |= git_config_set_in_file_gently(opts_file,
2965 "options.gpg-sign", opts->gpg_sign);
043a4492
RR
2966 if (opts->xopts) {
2967 int i;
2968 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 2969 res |= git_config_set_multivar_in_file_gently(opts_file,
f59199d5
PW
2970 "options.strategy-option",
2971 opts->xopts[i], "^$", 0);
043a4492 2972 }
8d8cb4b0 2973 if (opts->allow_rerere_auto)
f59199d5
PW
2974 res |= git_config_set_in_file_gently(opts_file,
2975 "options.allow-rerere-auto",
2976 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2977 "true" : "false");
dc42e9a8
PW
2978
2979 if (opts->explicit_cleanup)
2980 res |= git_config_set_in_file_gently(opts_file,
2981 "options.default-msg-cleanup",
2982 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 2983 return res;
043a4492
RR
2984}
2985
f11c9580
NTND
2986static int make_patch(struct repository *r,
2987 struct commit *commit,
2988 struct replay_opts *opts)
56dc3ab0
JS
2989{
2990 struct strbuf buf = STRBUF_INIT;
2991 struct rev_info log_tree_opt;
2992 const char *subject, *p;
2993 int res = 0;
2994
2995 p = short_commit_name(commit);
2996 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2997 return -1;
fbd7a232
NTND
2998 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2999 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
3000 res |= error(_("could not update %s"), "REBASE_HEAD");
56dc3ab0
JS
3001
3002 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3003 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3004 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
3005 log_tree_opt.abbrev = 0;
3006 log_tree_opt.diff = 1;
3007 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3008 log_tree_opt.disable_stdin = 1;
3009 log_tree_opt.no_commit_id = 1;
3010 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3011 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3012 if (!log_tree_opt.diffopt.file)
3013 res |= error_errno(_("could not open '%s'"), buf.buf);
3014 else {
3015 res |= log_tree_commit(&log_tree_opt, commit);
3016 fclose(log_tree_opt.diffopt.file);
3017 }
3018 strbuf_reset(&buf);
3019
3020 strbuf_addf(&buf, "%s/message", get_dir(opts));
3021 if (!file_exists(buf.buf)) {
52f52e5a
ĐTCD
3022 const char *encoding = get_commit_output_encoding();
3023 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
56dc3ab0
JS
3024 find_commit_subject(commit_buffer, &subject);
3025 res |= write_message(subject, strlen(subject), buf.buf, 1);
3026 unuse_commit_buffer(commit, commit_buffer);
3027 }
3028 strbuf_release(&buf);
3029
3030 return res;
3031}
3032
3033static int intend_to_amend(void)
3034{
092bbcdf 3035 struct object_id head;
56dc3ab0
JS
3036 char *p;
3037
092bbcdf 3038 if (get_oid("HEAD", &head))
56dc3ab0
JS
3039 return error(_("cannot read HEAD"));
3040
092bbcdf 3041 p = oid_to_hex(&head);
56dc3ab0
JS
3042 return write_message(p, strlen(p), rebase_path_amend(), 1);
3043}
3044
f11c9580
NTND
3045static int error_with_patch(struct repository *r,
3046 struct commit *commit,
3047 const char *subject, int subject_len,
3048 struct replay_opts *opts,
3049 int exit_code, int to_amend)
56dc3ab0 3050{
bc9238bb 3051 if (commit) {
f11c9580 3052 if (make_patch(r, commit, opts))
bc9238bb 3053 return -1;
5a5c5e95 3054 } else if (copy_file(rebase_path_message(),
f11c9580 3055 git_path_merge_msg(r), 0666))
bc9238bb 3056 return error(_("unable to copy '%s' to '%s'"),
f11c9580 3057 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
3058
3059 if (to_amend) {
3060 if (intend_to_amend())
3061 return -1;
3062
02127c63
NTND
3063 fprintf(stderr,
3064 _("You can amend the commit now, with\n"
3065 "\n"
3066 " git commit --amend %s\n"
3067 "\n"
3068 "Once you are satisfied with your changes, run\n"
3069 "\n"
3070 " git rebase --continue\n"),
3071 gpg_sign_opt_quoted(opts));
bc9238bb
PW
3072 } else if (exit_code) {
3073 if (commit)
5a5c5e95
JH
3074 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3075 short_commit_name(commit), subject_len, subject);
bc9238bb
PW
3076 else
3077 /*
3078 * We don't have the hash of the parent so
3079 * just print the line from the todo file.
3080 */
5a5c5e95
JH
3081 fprintf_ln(stderr, _("Could not merge %.*s"),
3082 subject_len, subject);
bc9238bb 3083 }
56dc3ab0
JS
3084
3085 return exit_code;
3086}
3087
f11c9580
NTND
3088static int error_failed_squash(struct repository *r,
3089 struct commit *commit,
3090 struct replay_opts *opts,
3091 int subject_len,
3092 const char *subject)
6e98de72 3093{
e12a7ef5
JS
3094 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3095 return error(_("could not copy '%s' to '%s'"),
6e98de72 3096 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
3097 unlink(git_path_merge_msg(r));
3098 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 3099 return error(_("could not copy '%s' to '%s'"),
102de880 3100 rebase_path_message(),
f11c9580
NTND
3101 git_path_merge_msg(r));
3102 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
3103}
3104
f11c9580 3105static int do_exec(struct repository *r, const char *command_line)
311af526 3106{
09d7b6c6 3107 struct argv_array child_env = ARGV_ARRAY_INIT;
311af526
JS
3108 const char *child_argv[] = { NULL, NULL };
3109 int dirty, status;
3110
3111 fprintf(stderr, "Executing: %s\n", command_line);
3112 child_argv[0] = command_line;
09d7b6c6 3113 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
ab5e67d7 3114 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3115 absolute_path(get_git_work_tree()));
09d7b6c6
JK
3116 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3117 child_env.argv);
311af526
JS
3118
3119 /* force re-reading of the cache */
e1ff0a32 3120 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
311af526
JS
3121 return error(_("could not read index"));
3122
f11c9580 3123 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
3124
3125 if (status) {
3126 warning(_("execution failed: %s\n%s"
3127 "You can fix the problem, and then run\n"
3128 "\n"
3129 " git rebase --continue\n"
3130 "\n"),
3131 command_line,
3132 dirty ? N_("and made changes to the index and/or the "
3133 "working tree\n") : "");
3134 if (status == 127)
3135 /* command not found */
3136 status = 1;
3137 } else if (dirty) {
3138 warning(_("execution succeeded: %s\nbut "
3139 "left changes to the index and/or the working tree\n"
3140 "Commit or stash your changes, and then run\n"
3141 "\n"
3142 " git rebase --continue\n"
3143 "\n"), command_line);
3144 status = 1;
3145 }
3146
09d7b6c6
JK
3147 argv_array_clear(&child_env);
3148
311af526
JS
3149 return status;
3150}
3151
9055e401
JS
3152static int safe_append(const char *filename, const char *fmt, ...)
3153{
3154 va_list ap;
3155 struct lock_file lock = LOCK_INIT;
3156 int fd = hold_lock_file_for_update(&lock, filename,
3157 LOCK_REPORT_ON_ERROR);
3158 struct strbuf buf = STRBUF_INIT;
3159
3160 if (fd < 0)
3161 return -1;
3162
3163 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3164 error_errno(_("could not read '%s'"), filename);
3165 rollback_lock_file(&lock);
3166 return -1;
3167 }
3168 strbuf_complete(&buf, '\n');
3169 va_start(ap, fmt);
3170 strbuf_vaddf(&buf, fmt, ap);
3171 va_end(ap);
3172
3173 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3174 error_errno(_("could not write to '%s'"), filename);
3175 strbuf_release(&buf);
3176 rollback_lock_file(&lock);
3177 return -1;
3178 }
3179 if (commit_lock_file(&lock) < 0) {
3180 strbuf_release(&buf);
3181 rollback_lock_file(&lock);
3182 return error(_("failed to finalize '%s'"), filename);
3183 }
3184
3185 strbuf_release(&buf);
3186 return 0;
3187}
3188
f11c9580 3189static int do_label(struct repository *r, const char *name, int len)
9055e401 3190{
f11c9580 3191 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3192 struct ref_transaction *transaction;
3193 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3194 struct strbuf msg = STRBUF_INIT;
3195 int ret = 0;
3196 struct object_id head_oid;
3197
3198 if (len == 1 && *name == '#')
02127c63 3199 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3200
3201 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
c2417d3a 3202 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
9055e401
JS
3203
3204 transaction = ref_store_transaction_begin(refs, &err);
3205 if (!transaction) {
3206 error("%s", err.buf);
3207 ret = -1;
3208 } else if (get_oid("HEAD", &head_oid)) {
3209 error(_("could not read HEAD"));
3210 ret = -1;
3211 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3212 NULL, 0, msg.buf, &err) < 0 ||
3213 ref_transaction_commit(transaction, &err)) {
3214 error("%s", err.buf);
3215 ret = -1;
3216 }
3217 ref_transaction_free(transaction);
3218 strbuf_release(&err);
3219 strbuf_release(&msg);
3220
3221 if (!ret)
3222 ret = safe_append(rebase_path_refs_to_delete(),
3223 "%s\n", ref_name.buf);
3224 strbuf_release(&ref_name);
3225
3226 return ret;
3227}
3228
3229static const char *reflog_message(struct replay_opts *opts,
3230 const char *sub_action, const char *fmt, ...);
3231
f11c9580
NTND
3232static int do_reset(struct repository *r,
3233 const char *name, int len,
3234 struct replay_opts *opts)
9055e401
JS
3235{
3236 struct strbuf ref_name = STRBUF_INIT;
3237 struct object_id oid;
3238 struct lock_file lock = LOCK_INIT;
3239 struct tree_desc desc;
3240 struct tree *tree;
3241 struct unpack_trees_options unpack_tree_opts;
71571cd7 3242 int ret = 0;
9055e401 3243
3a95f31d 3244 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3245 return -1;
3246
ebddf393
JS
3247 if (len == 10 && !strncmp("[new root]", name, len)) {
3248 if (!opts->have_squash_onto) {
3249 const char *hex;
3250 if (commit_tree("", 0, the_hash_algo->empty_tree,
3251 NULL, &opts->squash_onto,
3252 NULL, NULL))
3253 return error(_("writing fake root commit"));
3254 opts->have_squash_onto = 1;
3255 hex = oid_to_hex(&opts->squash_onto);
3256 if (write_message(hex, strlen(hex),
3257 rebase_path_squash_onto(), 0))
3258 return error(_("writing squash-onto"));
3259 }
3260 oidcpy(&oid, &opts->squash_onto);
3261 } else {
71571cd7
3262 int i;
3263
ebddf393
JS
3264 /* Determine the length of the label */
3265 for (i = 0; i < len; i++)
3266 if (isspace(name[i]))
71571cd7
3267 break;
3268 len = i;
ebddf393
JS
3269
3270 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3271 if (get_oid(ref_name.buf, &oid) &&
3272 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3273 error(_("could not read '%s'"), ref_name.buf);
3274 rollback_lock_file(&lock);
3275 strbuf_release(&ref_name);
3276 return -1;
3277 }
9055e401
JS
3278 }
3279
3280 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3281 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3282 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3283 unpack_tree_opts.src_index = r->index;
3284 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3285 unpack_tree_opts.fn = oneway_merge;
3286 unpack_tree_opts.merge = 1;
3287 unpack_tree_opts.update = 1;
3288
e1ff0a32 3289 if (repo_read_index_unmerged(r)) {
9055e401
JS
3290 rollback_lock_file(&lock);
3291 strbuf_release(&ref_name);
3292 return error_resolve_conflict(_(action_name(opts)));
3293 }
3294
5e575807 3295 if (!fill_tree_descriptor(r, &desc, &oid)) {
9055e401
JS
3296 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3297 rollback_lock_file(&lock);
3298 free((void *)desc.buffer);
3299 strbuf_release(&ref_name);
3300 return -1;
3301 }
3302
3303 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3304 rollback_lock_file(&lock);
3305 free((void *)desc.buffer);
3306 strbuf_release(&ref_name);
3307 return -1;
3308 }
3309
3310 tree = parse_tree_indirect(&oid);
c207e9e1 3311 prime_cache_tree(r, r->index, tree);
9055e401 3312
f11c9580 3313 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401
JS
3314 ret = error(_("could not write index"));
3315 free((void *)desc.buffer);
3316
3317 if (!ret)
3318 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3319 len, name), "HEAD", &oid,
3320 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3321
3322 strbuf_release(&ref_name);
3323 return ret;
3324}
3325
2b6ad0f4
JS
3326static struct commit *lookup_label(const char *label, int len,
3327 struct strbuf *buf)
3328{
3329 struct commit *commit;
3330
3331 strbuf_reset(buf);
3332 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3333 commit = lookup_commit_reference_by_name(buf->buf);
3334 if (!commit) {
3335 /* fall back to non-rewritten ref or commit */
3336 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3337 commit = lookup_commit_reference_by_name(buf->buf);
3338 }
3339
3340 if (!commit)
3341 error(_("could not resolve '%s'"), buf->buf);
3342
3343 return commit;
3344}
3345
f11c9580
NTND
3346static int do_merge(struct repository *r,
3347 struct commit *commit,
3348 const char *arg, int arg_len,
4c68e7dd
JS
3349 int flags, struct replay_opts *opts)
3350{
3351 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3352 EDIT_MSG | VERIFY_MSG : 0;
3353 struct strbuf ref_name = STRBUF_INIT;
3354 struct commit *head_commit, *merge_commit, *i;
3355 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 3356 struct commit_list *to_merge = NULL, **tail = &to_merge;
e145d993
JS
3357 const char *strategy = !opts->xopts_nr &&
3358 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3359 NULL : opts->strategy;
4c68e7dd 3360 struct merge_options o;
2b6ad0f4 3361 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3362 static struct lock_file lock;
3363 const char *p;
3364
3a95f31d 3365 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3366 ret = -1;
3367 goto leave_merge;
3368 }
3369
3370 head_commit = lookup_commit_reference_by_name("HEAD");
3371 if (!head_commit) {
3372 ret = error(_("cannot merge without a current revision"));
3373 goto leave_merge;
3374 }
3375
2b6ad0f4
JS
3376 /*
3377 * For octopus merges, the arg starts with the list of revisions to be
3378 * merged. The list is optionally followed by '#' and the oneline.
3379 */
3380 merge_arg_len = oneline_offset = arg_len;
3381 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3382 if (!*p)
3383 break;
3384 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3385 p += 1 + strspn(p + 1, " \t\n");
3386 oneline_offset = p - arg;
3387 break;
3388 }
3389 k = strcspn(p, " \t\n");
3390 if (!k)
3391 continue;
3392 merge_commit = lookup_label(p, k, &ref_name);
3393 if (!merge_commit) {
3394 ret = error(_("unable to parse '%.*s'"), k, p);
3395 goto leave_merge;
3396 }
3397 tail = &commit_list_insert(merge_commit, tail)->next;
3398 p += k;
3399 merge_arg_len = p - arg;
4c68e7dd
JS
3400 }
3401
2b6ad0f4
JS
3402 if (!to_merge) {
3403 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3404 goto leave_merge;
3405 }
3406
9c85a1c2 3407 if (opts->have_squash_onto &&
4a7e27e9 3408 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3409 /*
3410 * When the user tells us to "merge" something into a
3411 * "[new root]", let's simply fast-forward to the merge head.
3412 */
3413 rollback_lock_file(&lock);
2b6ad0f4
JS
3414 if (to_merge->next)
3415 ret = error(_("octopus merge cannot be executed on "
3416 "top of a [new root]"));
3417 else
f11c9580 3418 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3419 &head_commit->object.oid, 0,
3420 opts);
9c85a1c2
JS
3421 goto leave_merge;
3422 }
3423
4c68e7dd 3424 if (commit) {
5772b0c7
ĐTCD
3425 const char *encoding = get_commit_output_encoding();
3426 const char *message = logmsg_reencode(commit, NULL, encoding);
4c68e7dd
JS
3427 const char *body;
3428 int len;
3429
3430 if (!message) {
3431 ret = error(_("could not get commit message of '%s'"),
3432 oid_to_hex(&commit->object.oid));
3433 goto leave_merge;
3434 }
3435 write_author_script(message);
3436 find_commit_subject(message, &body);
3437 len = strlen(body);
f11c9580 3438 ret = write_message(body, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3439 unuse_commit_buffer(commit, message);
3440 if (ret) {
3441 error_errno(_("could not write '%s'"),
f11c9580 3442 git_path_merge_msg(r));
4c68e7dd
JS
3443 goto leave_merge;
3444 }
3445 } else {
3446 struct strbuf buf = STRBUF_INIT;
3447 int len;
3448
3449 strbuf_addf(&buf, "author %s", git_author_info(0));
3450 write_author_script(buf.buf);
3451 strbuf_reset(&buf);
3452
3453 if (oneline_offset < arg_len) {
3454 p = arg + oneline_offset;
3455 len = arg_len - oneline_offset;
3456 } else {
2b6ad0f4
JS
3457 strbuf_addf(&buf, "Merge %s '%.*s'",
3458 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
3459 merge_arg_len, arg);
3460 p = buf.buf;
3461 len = buf.len;
3462 }
3463
f11c9580 3464 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3465 strbuf_release(&buf);
3466 if (ret) {
3467 error_errno(_("could not write '%s'"),
f11c9580 3468 git_path_merge_msg(r));
4c68e7dd
JS
3469 goto leave_merge;
3470 }
3471 }
3472
d1e8b011
JS
3473 /*
3474 * If HEAD is not identical to the first parent of the original merge
3475 * commit, we cannot fast-forward.
3476 */
3477 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4a7e27e9
JK
3478 oideq(&commit->parents->item->object.oid,
3479 &head_commit->object.oid);
d1e8b011
JS
3480
3481 /*
2b6ad0f4 3482 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3483 * fast-forward.
3484 */
3485 if (can_fast_forward) {
2b6ad0f4 3486 struct commit_list *p = commit->parents->next;
d1e8b011 3487
2b6ad0f4 3488 for (j = to_merge; j && p; j = j->next, p = p->next)
9001dc2a 3489 if (!oideq(&j->item->object.oid,
2b6ad0f4
JS
3490 &p->item->object.oid)) {
3491 can_fast_forward = 0;
3492 break;
3493 }
3494 /*
3495 * If the number of merge heads differs from the original merge
3496 * commit, we cannot fast-forward.
3497 */
3498 if (j || p)
d1e8b011
JS
3499 can_fast_forward = 0;
3500 }
3501
2b6ad0f4 3502 if (can_fast_forward) {
d1e8b011 3503 rollback_lock_file(&lock);
f11c9580 3504 ret = fast_forward_to(r, &commit->object.oid,
d1e8b011 3505 &head_commit->object.oid, 0, opts);
6df8df08
PW
3506 if (flags & TODO_EDIT_MERGE_MSG) {
3507 run_commit_flags |= AMEND_MSG;
3508 goto fast_forward_edit;
3509 }
d1e8b011
JS
3510 goto leave_merge;
3511 }
3512
e145d993 3513 if (strategy || to_merge->next) {
2b6ad0f4
JS
3514 /* Octopus merge */
3515 struct child_process cmd = CHILD_PROCESS_INIT;
3516
3517 if (read_env_script(&cmd.env_array)) {
3518 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3519
3520 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3521 goto leave_merge;
3522 }
3523
3524 cmd.git_cmd = 1;
3525 argv_array_push(&cmd.args, "merge");
3526 argv_array_push(&cmd.args, "-s");
e145d993
JS
3527 if (!strategy)
3528 argv_array_push(&cmd.args, "octopus");
3529 else {
3530 argv_array_push(&cmd.args, strategy);
3531 for (k = 0; k < opts->xopts_nr; k++)
3532 argv_array_pushf(&cmd.args,
3533 "-X%s", opts->xopts[k]);
3534 }
2b6ad0f4
JS
3535 argv_array_push(&cmd.args, "--no-edit");
3536 argv_array_push(&cmd.args, "--no-ff");
3537 argv_array_push(&cmd.args, "--no-log");
3538 argv_array_push(&cmd.args, "--no-stat");
3539 argv_array_push(&cmd.args, "-F");
f11c9580 3540 argv_array_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4
JS
3541 if (opts->gpg_sign)
3542 argv_array_push(&cmd.args, opts->gpg_sign);
3543
3544 /* Add the tips to be merged */
3545 for (j = to_merge; j; j = j->next)
3546 argv_array_push(&cmd.args,
3547 oid_to_hex(&j->item->object.oid));
3548
3549 strbuf_release(&ref_name);
f11c9580 3550 unlink(git_path_cherry_pick_head(r));
2b6ad0f4
JS
3551 rollback_lock_file(&lock);
3552
3553 rollback_lock_file(&lock);
3554 ret = run_command(&cmd);
3555
3556 /* force re-reading of the cache */
f11c9580 3557 if (!ret && (discard_index(r->index) < 0 ||
e1ff0a32 3558 repo_read_index(r) < 0))
2b6ad0f4
JS
3559 ret = error(_("could not read index"));
3560 goto leave_merge;
3561 }
3562
3563 merge_commit = to_merge->item;
4c68e7dd 3564 bases = get_merge_bases(head_commit, merge_commit);
4a7e27e9
JK
3565 if (bases && oideq(&merge_commit->object.oid,
3566 &bases->item->object.oid)) {
7ccdf65b
JS
3567 ret = 0;
3568 /* skip merging an ancestor of HEAD */
3569 goto leave_merge;
3570 }
3571
4439c7a3 3572 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
cde55548
JH
3573 git_path_merge_head(r), 0);
3574 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 3575
4c68e7dd
JS
3576 for (j = bases; j; j = j->next)
3577 commit_list_insert(j->item, &reversed);
3578 free_commit_list(bases);
3579
e1ff0a32 3580 repo_read_index(r);
0d6caa2d 3581 init_merge_options(&o, r);
4c68e7dd
JS
3582 o.branch1 = "HEAD";
3583 o.branch2 = ref_name.buf;
3584 o.buffer_output = 2;
3585
3586 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3587 if (ret <= 0)
3588 fputs(o.obuf.buf, stdout);
3589 strbuf_release(&o.obuf);
3590 if (ret < 0) {
3591 error(_("could not even attempt to merge '%.*s'"),
3592 merge_arg_len, arg);
3593 goto leave_merge;
3594 }
3595 /*
3596 * The return value of merge_recursive() is 1 on clean, and 0 on
3597 * unclean merge.
3598 *
3599 * Let's reverse that, so that do_merge() returns 0 upon success and
3600 * 1 upon failed merge (keeping the return value -1 for the cases where
3601 * we will want to reschedule the `merge` command).
3602 */
3603 ret = !ret;
3604
f11c9580
NTND
3605 if (r->index->cache_changed &&
3606 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
3607 ret = error(_("merge: Unable to write new index file"));
3608 goto leave_merge;
3609 }
3610
3611 rollback_lock_file(&lock);
3612 if (ret)
f11c9580 3613 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
3614 else
3615 /*
3616 * In case of problems, we now want to return a positive
3617 * value (a negative one would indicate that the `merge`
3618 * command needs to be rescheduled).
3619 */
6df8df08 3620 fast_forward_edit:
f11c9580
NTND
3621 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3622 run_commit_flags);
4c68e7dd
JS
3623
3624leave_merge:
3625 strbuf_release(&ref_name);
3626 rollback_lock_file(&lock);
2b6ad0f4 3627 free_commit_list(to_merge);
4c68e7dd
JS
3628 return ret;
3629}
3630
6e98de72
JS
3631static int is_final_fixup(struct todo_list *todo_list)
3632{
3633 int i = todo_list->current;
3634
3635 if (!is_fixup(todo_list->items[i].command))
3636 return 0;
3637
3638 while (++i < todo_list->nr)
3639 if (is_fixup(todo_list->items[i].command))
3640 return 0;
3641 else if (!is_noop(todo_list->items[i].command))
3642 break;
3643 return 1;
3644}
3645
25cb8df9
JS
3646static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3647{
3648 int i;
3649
3650 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3651 if (!is_noop(todo_list->items[i].command))
3652 return todo_list->items[i].command;
3653
3654 return -1;
3655}
3656
796c7972
JS
3657static int apply_autostash(struct replay_opts *opts)
3658{
3659 struct strbuf stash_sha1 = STRBUF_INIT;
3660 struct child_process child = CHILD_PROCESS_INIT;
3661 int ret = 0;
3662
3663 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3664 strbuf_release(&stash_sha1);
3665 return 0;
3666 }
3667 strbuf_trim(&stash_sha1);
3668
3669 child.git_cmd = 1;
79a62269
PW
3670 child.no_stdout = 1;
3671 child.no_stderr = 1;
796c7972
JS
3672 argv_array_push(&child.args, "stash");
3673 argv_array_push(&child.args, "apply");
3674 argv_array_push(&child.args, stash_sha1.buf);
3675 if (!run_command(&child))
cdb866b3 3676 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
3677 else {
3678 struct child_process store = CHILD_PROCESS_INIT;
3679
3680 store.git_cmd = 1;
3681 argv_array_push(&store.args, "stash");
3682 argv_array_push(&store.args, "store");
3683 argv_array_push(&store.args, "-m");
3684 argv_array_push(&store.args, "autostash");
3685 argv_array_push(&store.args, "-q");
3686 argv_array_push(&store.args, stash_sha1.buf);
3687 if (run_command(&store))
3688 ret = error(_("cannot store %s"), stash_sha1.buf);
3689 else
cdb866b3
JS
3690 fprintf(stderr,
3691 _("Applying autostash resulted in conflicts.\n"
3692 "Your changes are safe in the stash.\n"
3693 "You can run \"git stash pop\" or"
3694 " \"git stash drop\" at any time.\n"));
796c7972
JS
3695 }
3696
3697 strbuf_release(&stash_sha1);
3698 return ret;
3699}
3700
96e832a5
JS
3701static const char *reflog_message(struct replay_opts *opts,
3702 const char *sub_action, const char *fmt, ...)
3703{
3704 va_list ap;
3705 static struct strbuf buf = STRBUF_INIT;
3706
3707 va_start(ap, fmt);
3708 strbuf_reset(&buf);
3709 strbuf_addstr(&buf, action_name(opts));
3710 if (sub_action)
3711 strbuf_addf(&buf, " (%s)", sub_action);
3712 if (fmt) {
3713 strbuf_addstr(&buf, ": ");
3714 strbuf_vaddf(&buf, fmt, ap);
3715 }
3716 va_end(ap);
3717
3718 return buf.buf;
3719}
3720
fc4a6735
PW
3721static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3722 const char *commit, const char *action)
2c58483a
AG
3723{
3724 struct child_process cmd = CHILD_PROCESS_INIT;
fc4a6735 3725 int ret;
2c58483a
AG
3726
3727 cmd.git_cmd = 1;
3728
3729 argv_array_push(&cmd.args, "checkout");
3730 argv_array_push(&cmd.args, commit);
3731 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3732
3733 if (opts->verbose)
fc4a6735 3734 ret = run_command(&cmd);
2c58483a 3735 else
fc4a6735
PW
3736 ret = run_command_silent_on_success(&cmd);
3737
3738 if (!ret)
3739 discard_index(r->index);
3740
3741 return ret;
2c58483a
AG
3742}
3743
fc4a6735
PW
3744int prepare_branch_to_be_rebased(struct repository *r, struct replay_opts *opts,
3745 const char *commit)
2c58483a
AG
3746{
3747 const char *action;
3748
3749 if (commit && *commit) {
3750 action = reflog_message(opts, "start", "checkout %s", commit);
fc4a6735 3751 if (run_git_checkout(r, opts, commit, action))
2c58483a
AG
3752 return error(_("could not checkout %s"), commit);
3753 }
3754
3755 return 0;
3756}
3757
fc4a6735 3758static int checkout_onto(struct repository *r, struct replay_opts *opts,
7d3488eb 3759 const char *onto_name, const struct object_id *onto,
91f0d95d 3760 const char *orig_head)
4df66c40
AG
3761{
3762 struct object_id oid;
3763 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3764
3765 if (get_oid(orig_head, &oid))
3766 return error(_("%s: not a valid OID"), orig_head);
3767
7d3488eb 3768 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4df66c40
AG
3769 apply_autostash(opts);
3770 sequencer_remove_state(opts);
3771 return error(_("could not detach HEAD"));
3772 }
3773
3774 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3775}
3776
005af339 3777static int stopped_at_head(struct repository *r)
71f82465
JS
3778{
3779 struct object_id head;
3780 struct commit *commit;
3781 struct commit_message message;
3782
789b1f70 3783 if (get_oid("HEAD", &head) ||
005af339 3784 !(commit = lookup_commit(r, &head)) ||
71f82465
JS
3785 parse_commit(commit) || get_message(commit, &message))
3786 fprintf(stderr, _("Stopped at HEAD\n"));
3787 else {
3788 fprintf(stderr, _("Stopped at %s\n"), message.label);
3789 free_message(commit, &message);
3790 }
3791 return 0;
3792
3793}
3794
cb5206ea
JS
3795static const char rescheduled_advice[] =
3796N_("Could not execute the todo command\n"
3797"\n"
3798" %.*s"
3799"\n"
3800"It has been rescheduled; To edit the command before continuing, please\n"
3801"edit the todo list first:\n"
3802"\n"
3803" git rebase --edit-todo\n"
3804" git rebase --continue\n");
3805
f11c9580
NTND
3806static int pick_commits(struct repository *r,
3807 struct todo_list *todo_list,
3808 struct replay_opts *opts)
043a4492 3809{
9055e401 3810 int res = 0, reschedule = 0;
043a4492
RR
3811
3812 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3813 if (opts->allow_ff)
3814 assert(!(opts->signoff || opts->no_commit ||
4d924528 3815 opts->record_origin || opts->edit));
f11c9580 3816 if (read_and_refresh_cache(r, opts))
0d9c6dc9 3817 return -1;
043a4492 3818
004fefa7
JS
3819 while (todo_list->current < todo_list->nr) {
3820 struct todo_item *item = todo_list->items + todo_list->current;
6ad656db 3821 const char *arg = todo_item_get_arg(todo_list, item);
a47ba3c7 3822 int check_todo = 0;
6ad656db 3823
004fefa7 3824 if (save_todo(todo_list, opts))
221675de 3825 return -1;
6e98de72 3826 if (is_rebase_i(opts)) {
ef80069a
JS
3827 if (item->command != TODO_COMMENT) {
3828 FILE *f = fopen(rebase_path_msgnum(), "w");
3829
3830 todo_list->done_nr++;
3831
3832 if (f) {
3833 fprintf(f, "%d\n", todo_list->done_nr);
3834 fclose(f);
3835 }
899b49c4
EN
3836 if (!opts->quiet)
3837 fprintf(stderr, "Rebasing (%d/%d)%s",
3838 todo_list->done_nr,
3839 todo_list->total_nr,
3840 opts->verbose ? "\n" : "\r");
ef80069a 3841 }
6e98de72
JS
3842 unlink(rebase_path_message());
3843 unlink(rebase_path_author_script());
3844 unlink(rebase_path_stopped_sha());
3845 unlink(rebase_path_amend());
34e7771b 3846 unlink(git_path_merge_head(r));
fbd7a232 3847 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
71f82465 3848
d7d90885
SG
3849 if (item->command == TODO_BREAK) {
3850 if (!opts->verbose)
3851 term_clear_line();
005af339 3852 return stopped_at_head(r);
d7d90885 3853 }
6e98de72
JS
3854 }
3855 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
3856 if (is_rebase_i(opts))
3857 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3858 command_to_string(item->command), NULL),
3859 1);
f11c9580 3860 res = do_pick_commit(r, item->command, item->commit,
a47ba3c7
PW
3861 opts, is_final_fixup(todo_list),
3862 &check_todo);
9d7bf3cf
JS
3863 if (is_rebase_i(opts) && res < 0) {
3864 /* Reschedule */
cb5206ea
JS
3865 advise(_(rescheduled_advice),
3866 get_item_line_length(todo_list,
3867 todo_list->current),
3868 get_item_line(todo_list,
3869 todo_list->current));
9d7bf3cf
JS
3870 todo_list->current--;
3871 if (save_todo(todo_list, opts))
3872 return -1;
3873 }
56dc3ab0
JS
3874 if (item->command == TODO_EDIT) {
3875 struct commit *commit = item->commit;
d7d90885
SG
3876 if (!res) {
3877 if (!opts->verbose)
3878 term_clear_line();
99429213 3879 fprintf(stderr,
a42e1b41 3880 _("Stopped at %s... %.*s\n"),
56dc3ab0 3881 short_commit_name(commit),
6ad656db 3882 item->arg_len, arg);
d7d90885 3883 }
f11c9580 3884 return error_with_patch(r, commit,
6ad656db 3885 arg, item->arg_len, opts, res, !res);
56dc3ab0 3886 }
25cb8df9
JS
3887 if (is_rebase_i(opts) && !res)
3888 record_in_rewritten(&item->commit->object.oid,
3889 peek_command(todo_list, 1));
6e98de72
JS
3890 if (res && is_fixup(item->command)) {
3891 if (res == 1)
3892 intend_to_amend();
f11c9580 3893 return error_failed_squash(r, item->commit, opts,
6ad656db 3894 item->arg_len, arg);
a9279c67
PW
3895 } else if (res && is_rebase_i(opts) && item->commit) {
3896 int to_amend = 0;
3897 struct object_id oid;
3898
3899 /*
3900 * If we are rewording and have either
3901 * fast-forwarded already, or are about to
3902 * create a new root commit, we want to amend,
3903 * otherwise we do not.
3904 */
3905 if (item->command == TODO_REWORD &&
3906 !get_oid("HEAD", &oid) &&
4a7e27e9 3907 (oideq(&item->commit->object.oid, &oid) ||
a9279c67 3908 (opts->have_squash_onto &&
4a7e27e9 3909 oideq(&opts->squash_onto, &oid))))
a9279c67
PW
3910 to_amend = 1;
3911
f11c9580 3912 return res | error_with_patch(r, item->commit,
6ad656db 3913 arg, item->arg_len, opts,
a9279c67
PW
3914 res, to_amend);
3915 }
311af526 3916 } else if (item->command == TODO_EXEC) {
6ad656db 3917 char *end_of_arg = (char *)(arg + item->arg_len);
311af526
JS
3918 int saved = *end_of_arg;
3919
d7d90885
SG
3920 if (!opts->verbose)
3921 term_clear_line();
311af526 3922 *end_of_arg = '\0';
6ad656db 3923 res = do_exec(r, arg);
311af526 3924 *end_of_arg = saved;
54fd3243 3925
d421afa0
JS
3926 if (res) {
3927 if (opts->reschedule_failed_exec)
3928 reschedule = 1;
54fd3243 3929 }
a47ba3c7 3930 check_todo = 1;
9055e401 3931 } else if (item->command == TODO_LABEL) {
6ad656db 3932 if ((res = do_label(r, arg, item->arg_len)))
9055e401
JS
3933 reschedule = 1;
3934 } else if (item->command == TODO_RESET) {
6ad656db 3935 if ((res = do_reset(r, arg, item->arg_len, opts)))
9055e401 3936 reschedule = 1;
4c68e7dd 3937 } else if (item->command == TODO_MERGE) {
f11c9580 3938 if ((res = do_merge(r, item->commit,
6ad656db 3939 arg, item->arg_len,
4c68e7dd
JS
3940 item->flags, opts)) < 0)
3941 reschedule = 1;
537e7d61
JS
3942 else if (item->commit)
3943 record_in_rewritten(&item->commit->object.oid,
3944 peek_command(todo_list, 1));
3945 if (res > 0)
4c68e7dd 3946 /* failed with merge conflicts */
f11c9580 3947 return error_with_patch(r, item->commit,
6ad656db
AG
3948 arg, item->arg_len,
3949 opts, res, 0);
56dc3ab0 3950 } else if (!is_noop(item->command))
25c43667
JS
3951 return error(_("unknown command %d"), item->command);
3952
9055e401
JS
3953 if (reschedule) {
3954 advise(_(rescheduled_advice),
3955 get_item_line_length(todo_list,
3956 todo_list->current),
3957 get_item_line(todo_list, todo_list->current));
3958 todo_list->current--;
3959 if (save_todo(todo_list, opts))
3960 return -1;
4c68e7dd 3961 if (item->commit)
f11c9580
NTND
3962 return error_with_patch(r,
3963 item->commit,
6ad656db
AG
3964 arg, item->arg_len,
3965 opts, res, 0);
befd4f6a 3966 } else if (is_rebase_i(opts) && check_todo && !res) {
a47ba3c7
PW
3967 struct stat st;
3968
3969 if (stat(get_todo_path(opts), &st)) {
3970 res = error_errno(_("could not stat '%s'"),
3971 get_todo_path(opts));
3972 } else if (match_stat_data(&todo_list->stat, &st)) {
3973 /* Reread the todo file if it has changed. */
3974 todo_list_release(todo_list);
3975 if (read_populate_todo(r, todo_list, opts))
3976 res = -1; /* message was printed */
3977 /* `current` will be incremented below */
3978 todo_list->current = -1;
3979 }
9055e401
JS
3980 }
3981
004fefa7 3982 todo_list->current++;
043a4492
RR
3983 if (res)
3984 return res;
3985 }
3986
56dc3ab0 3987 if (is_rebase_i(opts)) {
4b83ce9f 3988 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 3989 struct stat st;
556907f1 3990
56dc3ab0
JS
3991 /* Stopped in the middle, as planned? */
3992 if (todo_list->current < todo_list->nr)
3993 return 0;
556907f1 3994
4b83ce9f
JS
3995 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3996 starts_with(head_ref.buf, "refs/")) {
96e832a5 3997 const char *msg;
092bbcdf 3998 struct object_id head, orig;
4b83ce9f
JS
3999 int res;
4000
092bbcdf 4001 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
4002 res = error(_("cannot read HEAD"));
4003cleanup_head_ref:
4004 strbuf_release(&head_ref);
4005 strbuf_release(&buf);
4006 return res;
4007 }
4008 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 4009 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
4010 res = error(_("could not read orig-head"));
4011 goto cleanup_head_ref;
4012 }
4ab867b8 4013 strbuf_reset(&buf);
4b83ce9f
JS
4014 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4015 res = error(_("could not read 'onto'"));
4016 goto cleanup_head_ref;
4017 }
96e832a5
JS
4018 msg = reflog_message(opts, "finish", "%s onto %s",
4019 head_ref.buf, buf.buf);
ae077771 4020 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 4021 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
4022 res = error(_("could not update %s"),
4023 head_ref.buf);
4024 goto cleanup_head_ref;
4025 }
96e832a5 4026 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 4027 head_ref.buf);
96e832a5 4028 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
4029 res = error(_("could not update HEAD to %s"),
4030 head_ref.buf);
4031 goto cleanup_head_ref;
4032 }
4033 strbuf_reset(&buf);
4034 }
4035
556907f1
JS
4036 if (opts->verbose) {
4037 struct rev_info log_tree_opt;
4038 struct object_id orig, head;
4039
4040 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 4041 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
4042 log_tree_opt.diff = 1;
4043 log_tree_opt.diffopt.output_format =
4044 DIFF_FORMAT_DIFFSTAT;
4045 log_tree_opt.disable_stdin = 1;
4046
4047 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 4048 !get_oid(buf.buf, &orig) &&
4049 !get_oid("HEAD", &head)) {
66f414f8
BW
4050 diff_tree_oid(&orig, &head, "",
4051 &log_tree_opt.diffopt);
556907f1
JS
4052 log_tree_diff_flush(&log_tree_opt);
4053 }
4054 }
25cb8df9
JS
4055 flush_rewritten_pending();
4056 if (!stat(rebase_path_rewritten_list(), &st) &&
4057 st.st_size > 0) {
4058 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
4059 const char *post_rewrite_hook =
4060 find_hook("post-rewrite");
25cb8df9
JS
4061
4062 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4063 child.git_cmd = 1;
4064 argv_array_push(&child.args, "notes");
4065 argv_array_push(&child.args, "copy");
4066 argv_array_push(&child.args, "--for-rewrite=rebase");
4067 /* we don't care if this copying failed */
4068 run_command(&child);
79516045
JS
4069
4070 if (post_rewrite_hook) {
4071 struct child_process hook = CHILD_PROCESS_INIT;
4072
4073 hook.in = open(rebase_path_rewritten_list(),
4074 O_RDONLY);
4075 hook.stdout_to_stderr = 1;
6206286e 4076 hook.trace2_hook_name = "post-rewrite";
79516045
JS
4077 argv_array_push(&hook.args, post_rewrite_hook);
4078 argv_array_push(&hook.args, "rebase");
4079 /* we don't care if this hook failed */
4080 run_command(&hook);
4081 }
25cb8df9 4082 }
796c7972 4083 apply_autostash(opts);
25cb8df9 4084
d7d90885
SG
4085 if (!opts->quiet) {
4086 if (!opts->verbose)
4087 term_clear_line();
899b49c4
EN
4088 fprintf(stderr,
4089 "Successfully rebased and updated %s.\n",
4090 head_ref.buf);
d7d90885 4091 }
5da4966f 4092
556907f1 4093 strbuf_release(&buf);
4b83ce9f 4094 strbuf_release(&head_ref);
56dc3ab0
JS
4095 }
4096
043a4492
RR
4097 /*
4098 * Sequence of picks finished successfully; cleanup by
4099 * removing the .git/sequencer directory
4100 */
2863584f 4101 return sequencer_remove_state(opts);
043a4492
RR
4102}
4103
005af339 4104static int continue_single_pick(struct repository *r)
043a4492
RR
4105{
4106 const char *argv[] = { "commit", NULL };
4107
005af339
NTND
4108 if (!file_exists(git_path_cherry_pick_head(r)) &&
4109 !file_exists(git_path_revert_head(r)))
043a4492
RR
4110 return error(_("no cherry-pick or revert in progress"));
4111 return run_command_v_opt(argv, RUN_GIT_CMD);
4112}
4113
f11c9580
NTND
4114static int commit_staged_changes(struct repository *r,
4115 struct replay_opts *opts,
15ef6931 4116 struct todo_list *todo_list)
9d93ccd1 4117{
789b3eff 4118 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 4119 unsigned int final_fixup = 0, is_clean;
9d93ccd1 4120
f11c9580 4121 if (has_unstaged_changes(r, 1))
9d93ccd1 4122 return error(_("cannot rebase: You have unstaged changes."));
52632209 4123
f11c9580 4124 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1
JS
4125
4126 if (file_exists(rebase_path_amend())) {
4127 struct strbuf rev = STRBUF_INIT;
092bbcdf 4128 struct object_id head, to_amend;
9d93ccd1 4129
092bbcdf 4130 if (get_oid("HEAD", &head))
9d93ccd1
JS
4131 return error(_("cannot amend non-existing commit"));
4132 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4133 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 4134 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
4135 return error(_("invalid contents: '%s'"),
4136 rebase_path_amend());
9001dc2a 4137 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
4138 return error(_("\nYou have uncommitted changes in your "
4139 "working tree. Please, commit them\n"
4140 "first and then run 'git rebase "
4141 "--continue' again."));
15ef6931
JS
4142 /*
4143 * When skipping a failed fixup/squash, we need to edit the
4144 * commit message, the current fixup list and count, and if it
4145 * was the last fixup/squash in the chain, we need to clean up
4146 * the commit message and if there was a squash, let the user
4147 * edit it.
4148 */
10d2f354
JS
4149 if (!is_clean || !opts->current_fixup_count)
4150 ; /* this is not the final fixup */
87ae8a1a 4151 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
4152 !file_exists(rebase_path_stopped_sha())) {
4153 /* was a final fixup or squash done manually? */
4154 if (!is_fixup(peek_command(todo_list, 0))) {
4155 unlink(rebase_path_fixup_msg());
4156 unlink(rebase_path_squash_msg());
4157 unlink(rebase_path_current_fixups());
4158 strbuf_reset(&opts->current_fixups);
4159 opts->current_fixup_count = 0;
4160 }
4161 } else {
4162 /* we are in a fixup/squash chain */
15ef6931
JS
4163 const char *p = opts->current_fixups.buf;
4164 int len = opts->current_fixups.len;
4165
4166 opts->current_fixup_count--;
4167 if (!len)
4168 BUG("Incorrect current_fixups:\n%s", p);
4169 while (len && p[len - 1] != '\n')
4170 len--;
4171 strbuf_setlen(&opts->current_fixups, len);
4172 if (write_message(p, len, rebase_path_current_fixups(),
4173 0) < 0)
4174 return error(_("could not write file: '%s'"),
4175 rebase_path_current_fixups());
4176
4177 /*
4178 * If a fixup/squash in a fixup/squash chain failed, the
4179 * commit message is already correct, no need to commit
4180 * it again.
4181 *
4182 * Only if it is the final command in the fixup/squash
4183 * chain, and only if the chain is longer than a single
4184 * fixup/squash command (which was just skipped), do we
4185 * actually need to re-commit with a cleaned up commit
4186 * message.
4187 */
4188 if (opts->current_fixup_count > 0 &&
4189 !is_fixup(peek_command(todo_list, 0))) {
4190 final_fixup = 1;
4191 /*
4192 * If there was not a single "squash" in the
4193 * chain, we only need to clean up the commit
4194 * message, no need to bother the user with
4195 * opening the commit message in the editor.
4196 */
4197 if (!starts_with(p, "squash ") &&
4198 !strstr(p, "\nsquash "))
4199 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4200 } else if (is_fixup(peek_command(todo_list, 0))) {
4201 /*
4202 * We need to update the squash message to skip
4203 * the latest commit message.
4204 */
4205 struct commit *commit;
4206 const char *path = rebase_path_squash_msg();
b3757442 4207 const char *encoding = get_commit_output_encoding();
15ef6931 4208
005af339 4209 if (parse_head(r, &commit) ||
b3757442 4210 !(p = logmsg_reencode(commit, NULL, encoding)) ||
15ef6931
JS
4211 write_message(p, strlen(p), path, 0)) {
4212 unuse_commit_buffer(commit, p);
4213 return error(_("could not write file: "
4214 "'%s'"), path);
4215 }
4216 unuse_commit_buffer(commit, p);
4217 }
4218 }
9d93ccd1
JS
4219
4220 strbuf_release(&rev);
789b3eff 4221 flags |= AMEND_MSG;
9d93ccd1
JS
4222 }
4223
15ef6931 4224 if (is_clean) {
f11c9580 4225 const char *cherry_pick_head = git_path_cherry_pick_head(r);
15ef6931
JS
4226
4227 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4228 return error(_("could not remove CHERRY_PICK_HEAD"));
4229 if (!final_fixup)
4230 return 0;
4231 }
4232
f11c9580 4233 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
15ef6931 4234 opts, flags))
9d93ccd1
JS
4235 return error(_("could not commit staged changes."));
4236 unlink(rebase_path_amend());
34e7771b 4237 unlink(git_path_merge_head(r));
15ef6931
JS
4238 if (final_fixup) {
4239 unlink(rebase_path_fixup_msg());
4240 unlink(rebase_path_squash_msg());
4241 }
4242 if (opts->current_fixup_count > 0) {
4243 /*
4244 * Whether final fixup or not, we just cleaned up the commit
4245 * message...
4246 */
4247 unlink(rebase_path_current_fixups());
4248 strbuf_reset(&opts->current_fixups);
4249 opts->current_fixup_count = 0;
4250 }
9d93ccd1
JS
4251 return 0;
4252}
4253
f11c9580 4254int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 4255{
004fefa7
JS
4256 struct todo_list todo_list = TODO_LIST_INIT;
4257 int res;
043a4492 4258
f11c9580 4259 if (read_and_refresh_cache(r, opts))
2863584f
JS
4260 return -1;
4261
15ef6931
JS
4262 if (read_populate_opts(opts))
4263 return -1;
9d93ccd1 4264 if (is_rebase_i(opts)) {
005af339 4265 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 4266 goto release_todo_list;
f6b9413b
AG
4267 if (commit_staged_changes(r, opts, &todo_list)) {
4268 res = -1;
4269 goto release_todo_list;
4270 }
4258a6da 4271 } else if (!file_exists(get_todo_path(opts)))
005af339
NTND
4272 return continue_single_pick(r);
4273 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 4274 goto release_todo_list;
043a4492 4275
4258a6da
JS
4276 if (!is_rebase_i(opts)) {
4277 /* Verify that the conflict has been resolved */
f11c9580
NTND
4278 if (file_exists(git_path_cherry_pick_head(r)) ||
4279 file_exists(git_path_revert_head(r))) {
005af339 4280 res = continue_single_pick(r);
4258a6da
JS
4281 if (res)
4282 goto release_todo_list;
4283 }
ffc00a48 4284 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 4285 res = error_dirty_index(r, opts);
004fefa7 4286 goto release_todo_list;
4258a6da
JS
4287 }
4288 todo_list.current++;
ca98c6d4
JS
4289 } else if (file_exists(rebase_path_stopped_sha())) {
4290 struct strbuf buf = STRBUF_INIT;
4291 struct object_id oid;
4292
4293 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
e82caf38 4294 !get_oid_committish(buf.buf, &oid))
ca98c6d4
JS
4295 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4296 strbuf_release(&buf);
043a4492 4297 }
4258a6da 4298
f11c9580 4299 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4300release_todo_list:
4301 todo_list_release(&todo_list);
4302 return res;
043a4492
RR
4303}
4304
f11c9580
NTND
4305static int single_pick(struct repository *r,
4306 struct commit *cmit,
4307 struct replay_opts *opts)
043a4492 4308{
a47ba3c7
PW
4309 int check_todo;
4310
043a4492 4311 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
f11c9580 4312 return do_pick_commit(r, opts->action == REPLAY_PICK ?
a47ba3c7
PW
4313 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4314 &check_todo);
043a4492
RR
4315}
4316
f11c9580
NTND
4317int sequencer_pick_revisions(struct repository *r,
4318 struct replay_opts *opts)
043a4492 4319{
004fefa7 4320 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 4321 struct object_id oid;
004fefa7 4322 int i, res;
043a4492 4323
2863584f 4324 assert(opts->revs);
f11c9580 4325 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4326 return -1;
043a4492 4327
21246dbb 4328 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 4329 struct object_id oid;
21246dbb
MV
4330 const char *name = opts->revs->pending.objects[i].name;
4331
4332 /* This happens when using --stdin. */
4333 if (!strlen(name))
4334 continue;
4335
1e43ed98 4336 if (!get_oid(name, &oid)) {
f11c9580
NTND
4337 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4338 enum object_type type = oid_object_info(r,
0df8e965 4339 &oid,
abef9020 4340 NULL);
b9b946d4 4341 return error(_("%s: can't cherry-pick a %s"),
debca9d2 4342 name, type_name(type));
7c0b0d8d 4343 }
21246dbb 4344 } else
b9b946d4 4345 return error(_("%s: bad revision"), name);
21246dbb
MV
4346 }
4347
043a4492
RR
4348 /*
4349 * If we were called as "git cherry-pick <commit>", just
4350 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4351 * REVERT_HEAD, and don't touch the sequencer state.
4352 * This means it is possible to cherry-pick in the middle
4353 * of a cherry-pick sequence.
4354 */
4355 if (opts->revs->cmdline.nr == 1 &&
4356 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4357 opts->revs->no_walk &&
4358 !opts->revs->cmdline.rev->flags) {
4359 struct commit *cmit;
4360 if (prepare_revision_walk(opts->revs))
b9b946d4 4361 return error(_("revision walk setup failed"));
043a4492 4362 cmit = get_revision(opts->revs);
c5e358d0
JK
4363 if (!cmit)
4364 return error(_("empty commit set passed"));
4365 if (get_revision(opts->revs))
4366 BUG("unexpected extra commit from walk");
f11c9580 4367 return single_pick(r, cmit, opts);
043a4492
RR
4368 }
4369
4370 /*
4371 * Start a new cherry-pick/ revert sequence; but
4372 * first, make sure that an existing one isn't in
4373 * progress
4374 */
4375
34b0528b 4376 if (walk_revs_populate_todo(&todo_list, opts) ||
6a1f9046 4377 create_seq_dir(r) < 0)
043a4492 4378 return -1;
1e43ed98 4379 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 4380 return error(_("can't revert as initial commit"));
1e43ed98 4381 if (save_head(oid_to_hex(&oid)))
311fd397 4382 return -1;
88d5a271
JS
4383 if (save_opts(opts))
4384 return -1;
1e41229d 4385 update_abort_safety_file();
f11c9580 4386 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4387 todo_list_release(&todo_list);
4388 return res;
043a4492 4389}
5ed75e2a 4390
66e83d9b 4391void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 4392{
bab4d109 4393 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 4394 struct strbuf sob = STRBUF_INIT;
bab4d109 4395 int has_footer;
5ed75e2a
MV
4396
4397 strbuf_addstr(&sob, sign_off_header);
39ab4d09 4398 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 4399 strbuf_addch(&sob, '\n');
bab4d109 4400
44dc738a
JT
4401 if (!ignore_footer)
4402 strbuf_complete_line(msgbuf);
4403
bab4d109
BC
4404 /*
4405 * If the whole message buffer is equal to the sob, pretend that we
4406 * found a conforming footer with a matching sob
4407 */
4408 if (msgbuf->len - ignore_footer == sob.len &&
4409 !strncmp(msgbuf->buf, sob.buf, sob.len))
4410 has_footer = 3;
4411 else
4412 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4413
33f2f9ab
BC
4414 if (!has_footer) {
4415 const char *append_newlines = NULL;
4416 size_t len = msgbuf->len - ignore_footer;
4417
8c613fd5
BC
4418 if (!len) {
4419 /*
4420 * The buffer is completely empty. Leave foom for
4421 * the title and body to be filled in by the user.
4422 */
33f2f9ab 4423 append_newlines = "\n\n";
8c613fd5
BC
4424 } else if (len == 1) {
4425 /*
4426 * Buffer contains a single newline. Add another
4427 * so that we leave room for the title and body.
4428 */
4429 append_newlines = "\n";
4430 } else if (msgbuf->buf[len - 2] != '\n') {
4431 /*
4432 * Buffer ends with a single newline. Add another
4433 * so that there is an empty line between the message
4434 * body and the sob.
4435 */
33f2f9ab 4436 append_newlines = "\n";
8c613fd5 4437 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
4438
4439 if (append_newlines)
4440 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4441 append_newlines, strlen(append_newlines));
5ed75e2a 4442 }
bab4d109
BC
4443
4444 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4445 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4446 sob.buf, sob.len);
4447
5ed75e2a
MV
4448 strbuf_release(&sob);
4449}
62db5247 4450
1644c73c
JS
4451struct labels_entry {
4452 struct hashmap_entry entry;
4453 char label[FLEX_ARRAY];
4454};
4455
939af16e
EW
4456static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4457 const struct hashmap_entry *entry_or_key, const void *key)
1644c73c 4458{
939af16e
EW
4459 const struct labels_entry *a, *b;
4460
4461 a = container_of(eptr, const struct labels_entry, entry);
4462 b = container_of(entry_or_key, const struct labels_entry, entry);
4463
1644c73c
JS
4464 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4465}
4466
4467struct string_entry {
4468 struct oidmap_entry entry;
4469 char string[FLEX_ARRAY];
4470};
4471
4472struct label_state {
4473 struct oidmap commit2label;
4474 struct hashmap labels;
4475 struct strbuf buf;
4476};
4477
4478static const char *label_oid(struct object_id *oid, const char *label,
4479 struct label_state *state)
4480{
4481 struct labels_entry *labels_entry;
4482 struct string_entry *string_entry;
4483 struct object_id dummy;
1644c73c
JS
4484 int i;
4485
4486 string_entry = oidmap_get(&state->commit2label, oid);
4487 if (string_entry)
4488 return string_entry->string;
4489
4490 /*
4491 * For "uninteresting" commits, i.e. commits that are not to be
4492 * rebased, and which can therefore not be labeled, we use a unique
4493 * abbreviation of the commit name. This is slightly more complicated
4494 * than calling find_unique_abbrev() because we also need to make
4495 * sure that the abbreviation does not conflict with any other
4496 * label.
4497 *
4498 * We disallow "interesting" commits to be labeled by a string that
4499 * is a valid full-length hash, to ensure that we always can find an
4500 * abbreviation for any uninteresting commit's names that does not
4501 * clash with any other label.
4502 */
867bc1d2 4503 strbuf_reset(&state->buf);
1644c73c
JS
4504 if (!label) {
4505 char *p;
4506
4439c7a3 4507 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
1644c73c
JS
4508 label = p = state->buf.buf;
4509
4510 find_unique_abbrev_r(p, oid, default_abbrev);
4511
4512 /*
4513 * We may need to extend the abbreviated hash so that there is
4514 * no conflicting label.
4515 */
4516 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4517 size_t i = strlen(p) + 1;
4518
4519 oid_to_hex_r(p, oid);
4439c7a3 4520 for (; i < the_hash_algo->hexsz; i++) {
1644c73c
JS
4521 char save = p[i];
4522 p[i] = '\0';
4523 if (!hashmap_get_from_hash(&state->labels,
4524 strihash(p), p))
4525 break;
4526 p[i] = save;
4527 }
4528 }
867bc1d2 4529 } else {
1644c73c
JS
4530 struct strbuf *buf = &state->buf;
4531
1644c73c 4532 /*
cd552227
MR
4533 * Sanitize labels by replacing non-alpha-numeric characters
4534 * (including white-space ones) by dashes, as they might be
4535 * illegal in file names (and hence in ref names).
4536 *
4537 * Note that we retain non-ASCII UTF-8 characters (identified
4538 * via the most significant bit). They should be all acceptable
4539 * in file names. We do not validate the UTF-8 here, that's not
4540 * the job of this function.
1644c73c 4541 */
867bc1d2 4542 for (; *label; label++)
cd552227
MR
4543 if ((*label & 0x80) || isalnum(*label))
4544 strbuf_addch(buf, *label);
4545 /* avoid leading dash and double-dashes */
4546 else if (buf->len && buf->buf[buf->len - 1] != '-')
4547 strbuf_addch(buf, '-');
4548 if (!buf->len) {
4549 strbuf_addstr(buf, "rev-");
4550 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4551 }
867bc1d2 4552 label = buf->buf;
1644c73c 4553
867bc1d2
JS
4554 if ((buf->len == the_hash_algo->hexsz &&
4555 !get_oid_hex(label, &dummy)) ||
4556 (buf->len == 1 && *label == '#') ||
4557 hashmap_get_from_hash(&state->labels,
4558 strihash(label), label)) {
4559 /*
4560 * If the label already exists, or if the label is a
4561 * valid full OID, or the label is a '#' (which we use
4562 * as a separator between merge heads and oneline), we
4563 * append a dash and a number to make it unique.
4564 */
4565 size_t len = buf->len;
1644c73c 4566
867bc1d2
JS
4567 for (i = 2; ; i++) {
4568 strbuf_setlen(buf, len);
4569 strbuf_addf(buf, "-%d", i);
4570 if (!hashmap_get_from_hash(&state->labels,
4571 strihash(buf->buf),
4572 buf->buf))
4573 break;
4574 }
1644c73c 4575
867bc1d2
JS
4576 label = buf->buf;
4577 }
1644c73c
JS
4578 }
4579
4580 FLEX_ALLOC_STR(labels_entry, label, label);
d22245a2 4581 hashmap_entry_init(&labels_entry->entry, strihash(label));
b94e5c1d 4582 hashmap_add(&state->labels, &labels_entry->entry);
1644c73c
JS
4583
4584 FLEX_ALLOC_STR(string_entry, string, label);
4585 oidcpy(&string_entry->entry.oid, oid);
4586 oidmap_put(&state->commit2label, string_entry);
4587
4588 return string_entry->string;
4589}
4590
4591static int make_script_with_merges(struct pretty_print_context *pp,
d358fc28 4592 struct rev_info *revs, struct strbuf *out,
1644c73c
JS
4593 unsigned flags)
4594{
7543f6f4 4595 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
e1fac531 4596 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
1644c73c
JS
4597 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4598 struct strbuf label = STRBUF_INIT;
4599 struct commit_list *commits = NULL, **tail = &commits, *iter;
4600 struct commit_list *tips = NULL, **tips_tail = &tips;
4601 struct commit *commit;
4602 struct oidmap commit2todo = OIDMAP_INIT;
4603 struct string_entry *entry;
4604 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4605 shown = OIDSET_INIT;
4606 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4607
4608 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4609 const char *cmd_pick = abbr ? "p" : "pick",
4610 *cmd_label = abbr ? "l" : "label",
4611 *cmd_reset = abbr ? "t" : "reset",
4612 *cmd_merge = abbr ? "m" : "merge";
4613
4614 oidmap_init(&commit2todo, 0);
4615 oidmap_init(&state.commit2label, 0);
939af16e 4616 hashmap_init(&state.labels, labels_cmp, NULL, 0);
1644c73c
JS
4617 strbuf_init(&state.buf, 32);
4618
4619 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
e02058a7 4620 struct labels_entry *onto_label_entry;
1644c73c
JS
4621 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4622 FLEX_ALLOC_STR(entry, string, "onto");
4623 oidcpy(&entry->entry.oid, oid);
4624 oidmap_put(&state.commit2label, entry);
e02058a7
ĐTCD
4625
4626 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4627 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4628 hashmap_add(&state.labels, &onto_label_entry->entry);
1644c73c
JS
4629 }
4630
4631 /*
4632 * First phase:
4633 * - get onelines for all commits
4634 * - gather all branch tips (i.e. 2nd or later parents of merges)
4635 * - label all branch tips
4636 */
4637 while ((commit = get_revision(revs))) {
4638 struct commit_list *to_merge;
1644c73c
JS
4639 const char *p1, *p2;
4640 struct object_id *oid;
4641 int is_empty;
4642
4643 tail = &commit_list_insert(commit, tail)->next;
4644 oidset_insert(&interesting, &commit->object.oid);
4645
4646 is_empty = is_original_commit_empty(commit);
4647 if (!is_empty && (commit->object.flags & PATCHSAME))
4648 continue;
4649
4650 strbuf_reset(&oneline);
4651 pretty_print_commit(pp, commit, &oneline);
4652
4653 to_merge = commit->parents ? commit->parents->next : NULL;
4654 if (!to_merge) {
4655 /* non-merge commit: easy case */
4656 strbuf_reset(&buf);
1644c73c
JS
4657 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4658 oid_to_hex(&commit->object.oid),
4659 oneline.buf);
4660
4661 FLEX_ALLOC_STR(entry, string, buf.buf);
4662 oidcpy(&entry->entry.oid, &commit->object.oid);
4663 oidmap_put(&commit2todo, entry);
4664
4665 continue;
4666 }
4667
1644c73c
JS
4668 /* Create a label */
4669 strbuf_reset(&label);
4670 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4671 (p1 = strchr(p1, '\'')) &&
4672 (p2 = strchr(++p1, '\'')))
4673 strbuf_add(&label, p1, p2 - p1);
4674 else if (skip_prefix(oneline.buf, "Merge pull request ",
4675 &p1) &&
4676 (p1 = strstr(p1, " from ")))
4677 strbuf_addstr(&label, p1 + strlen(" from "));
4678 else
4679 strbuf_addbuf(&label, &oneline);
4680
1644c73c
JS
4681 strbuf_reset(&buf);
4682 strbuf_addf(&buf, "%s -C %s",
4683 cmd_merge, oid_to_hex(&commit->object.oid));
4684
2b6ad0f4
JS
4685 /* label the tips of merged branches */
4686 for (; to_merge; to_merge = to_merge->next) {
4687 oid = &to_merge->item->object.oid;
4688 strbuf_addch(&buf, ' ');
4689
4690 if (!oidset_contains(&interesting, oid)) {
4691 strbuf_addstr(&buf, label_oid(oid, NULL,
4692 &state));
4693 continue;
4694 }
1644c73c 4695
1644c73c
JS
4696 tips_tail = &commit_list_insert(to_merge->item,
4697 tips_tail)->next;
4698
4699 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4700 }
4701 strbuf_addf(&buf, " # %s", oneline.buf);
4702
4703 FLEX_ALLOC_STR(entry, string, buf.buf);
4704 oidcpy(&entry->entry.oid, &commit->object.oid);
4705 oidmap_put(&commit2todo, entry);
4706 }
4707
4708 /*
4709 * Second phase:
4710 * - label branch points
4711 * - add HEAD to the branch tips
4712 */
4713 for (iter = commits; iter; iter = iter->next) {
4714 struct commit_list *parent = iter->item->parents;
4715 for (; parent; parent = parent->next) {
4716 struct object_id *oid = &parent->item->object.oid;
4717 if (!oidset_contains(&interesting, oid))
4718 continue;
6e8fc70f 4719 if (oidset_insert(&child_seen, oid))
1644c73c
JS
4720 label_oid(oid, "branch-point", &state);
4721 }
4722
15beaaa3 4723 /* Add HEAD as implicit "tip of branch" */
1644c73c
JS
4724 if (!iter->next)
4725 tips_tail = &commit_list_insert(iter->item,
4726 tips_tail)->next;
4727 }
4728
4729 /*
4730 * Third phase: output the todo list. This is a bit tricky, as we
4731 * want to avoid jumping back and forth between revisions. To
4732 * accomplish that goal, we walk backwards from the branch tips,
4733 * gathering commits not yet shown, reversing the list on the fly,
4734 * then outputting that list (labeling revisions as needed).
4735 */
d358fc28 4736 strbuf_addf(out, "%s onto\n", cmd_label);
1644c73c
JS
4737 for (iter = tips; iter; iter = iter->next) {
4738 struct commit_list *list = NULL, *iter2;
4739
4740 commit = iter->item;
4741 if (oidset_contains(&shown, &commit->object.oid))
4742 continue;
4743 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4744
4745 if (entry)
d358fc28 4746 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
1644c73c 4747 else
d358fc28 4748 strbuf_addch(out, '\n');
1644c73c
JS
4749
4750 while (oidset_contains(&interesting, &commit->object.oid) &&
4751 !oidset_contains(&shown, &commit->object.oid)) {
4752 commit_list_insert(commit, &list);
4753 if (!commit->parents) {
4754 commit = NULL;
4755 break;
4756 }
4757 commit = commit->parents->item;
4758 }
4759
4760 if (!commit)
d358fc28 4761 strbuf_addf(out, "%s %s\n", cmd_reset,
e1fac531
JS
4762 rebase_cousins || root_with_onto ?
4763 "onto" : "[new root]");
1644c73c
JS
4764 else {
4765 const char *to = NULL;
4766
4767 entry = oidmap_get(&state.commit2label,
4768 &commit->object.oid);
4769 if (entry)
4770 to = entry->string;
7543f6f4
JS
4771 else if (!rebase_cousins)
4772 to = label_oid(&commit->object.oid, NULL,
4773 &state);
1644c73c
JS
4774
4775 if (!to || !strcmp(to, "onto"))
d358fc28 4776 strbuf_addf(out, "%s onto\n", cmd_reset);
1644c73c
JS
4777 else {
4778 strbuf_reset(&oneline);
4779 pretty_print_commit(pp, commit, &oneline);
d358fc28
AG
4780 strbuf_addf(out, "%s %s # %s\n",
4781 cmd_reset, to, oneline.buf);
1644c73c
JS
4782 }
4783 }
4784
4785 for (iter2 = list; iter2; iter2 = iter2->next) {
4786 struct object_id *oid = &iter2->item->object.oid;
4787 entry = oidmap_get(&commit2todo, oid);
4788 /* only show if not already upstream */
4789 if (entry)
d358fc28 4790 strbuf_addf(out, "%s\n", entry->string);
1644c73c
JS
4791 entry = oidmap_get(&state.commit2label, oid);
4792 if (entry)
d358fc28
AG
4793 strbuf_addf(out, "%s %s\n",
4794 cmd_label, entry->string);
1644c73c
JS
4795 oidset_insert(&shown, oid);
4796 }
4797
4798 free_commit_list(list);
4799 }
4800
4801 free_commit_list(commits);
4802 free_commit_list(tips);
4803
4804 strbuf_release(&label);
4805 strbuf_release(&oneline);
4806 strbuf_release(&buf);
4807
4808 oidmap_free(&commit2todo, 1);
4809 oidmap_free(&state.commit2label, 1);
c8e424c9 4810 hashmap_free_entries(&state.labels, struct labels_entry, entry);
1644c73c
JS
4811 strbuf_release(&state.buf);
4812
4813 return 0;
4814}
4815
d358fc28
AG
4816int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4817 const char **argv, unsigned flags)
62db5247
JS
4818{
4819 char *format = NULL;
4820 struct pretty_print_context pp = {0};
62db5247
JS
4821 struct rev_info revs;
4822 struct commit *commit;
d8ae6c84 4823 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 4824 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
62db5247 4825
f11c9580 4826 repo_init_revisions(r, &revs, NULL);
62db5247 4827 revs.verbose_header = 1;
1644c73c
JS
4828 if (!rebase_merges)
4829 revs.max_parents = 1;
76ea2358 4830 revs.cherry_mark = 1;
62db5247
JS
4831 revs.limited = 1;
4832 revs.reverse = 1;
4833 revs.right_only = 1;
4834 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4835 revs.topo_order = 1;
4836
4837 revs.pretty_given = 1;
4838 git_config_get_string("rebase.instructionFormat", &format);
4839 if (!format || !*format) {
4840 free(format);
4841 format = xstrdup("%s");
4842 }
4843 get_commit_format(format, &revs);
4844 free(format);
4845 pp.fmt = revs.commit_format;
4846 pp.output_encoding = get_log_output_encoding();
4847
4848 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4849 return error(_("make_script: unhandled options"));
4850
4851 if (prepare_revision_walk(&revs) < 0)
4852 return error(_("make_script: error preparing revisions"));
4853
1644c73c
JS
4854 if (rebase_merges)
4855 return make_script_with_merges(&pp, &revs, out, flags);
4856
62db5247 4857 while ((commit = get_revision(&revs))) {
d48e5e21 4858 int is_empty = is_original_commit_empty(commit);
76ea2358
PW
4859
4860 if (!is_empty && (commit->object.flags & PATCHSAME))
4861 continue;
d358fc28 4862 strbuf_addf(out, "%s %s ", insn,
d8ae6c84 4863 oid_to_hex(&commit->object.oid));
d358fc28
AG
4864 pretty_print_commit(&pp, commit, out);
4865 strbuf_addch(out, '\n');
62db5247 4866 }
62db5247
JS
4867 return 0;
4868}
3546c8d9 4869
0cce4a27
LB
4870/*
4871 * Add commands after pick and (series of) squash/fixup commands
4872 * in the todo list.
4873 */
1ba204de
AG
4874void todo_list_add_exec_commands(struct todo_list *todo_list,
4875 struct string_list *commands)
3546c8d9 4876{
683153a4
AG
4877 struct strbuf *buf = &todo_list->buf;
4878 size_t base_offset = buf->len;
4879 int i, insert, nr = 0, alloc = 0;
4880 struct todo_item *items = NULL, *base_items = NULL;
3546c8d9 4881
683153a4
AG
4882 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4883 for (i = 0; i < commands->nr; i++) {
4884 size_t command_len = strlen(commands->items[i].string);
3546c8d9 4885
683153a4
AG
4886 strbuf_addstr(buf, commands->items[i].string);
4887 strbuf_addch(buf, '\n');
3546c8d9 4888
683153a4
AG
4889 base_items[i].command = TODO_EXEC;
4890 base_items[i].offset_in_buf = base_offset;
4891 base_items[i].arg_offset = base_offset + strlen("exec ");
4892 base_items[i].arg_len = command_len - strlen("exec ");
3546c8d9 4893
683153a4 4894 base_offset += command_len + 1;
3546c8d9
JS
4895 }
4896
1ace63bc
JS
4897 /*
4898 * Insert <commands> after every pick. Here, fixup/squash chains
4899 * are considered part of the pick, so we insert the commands *after*
4900 * those chains if there are any.
683153a4 4901 *
15beaaa3 4902 * As we insert the exec commands immediately after rearranging
683153a4
AG
4903 * any fixups and before the user edits the list, a fixup chain
4904 * can never contain comments (any comments are empty picks that
4905 * have been commented out because the user did not specify
4906 * --keep-empty). So, it is safe to insert an exec command
4907 * without looking at the command following a comment.
1ace63bc 4908 */
683153a4
AG
4909 insert = 0;
4910 for (i = 0; i < todo_list->nr; i++) {
4911 enum todo_command command = todo_list->items[i].command;
4912 if (insert && !is_fixup(command)) {
4913 ALLOC_GROW(items, nr + commands->nr, alloc);
4914 COPY_ARRAY(items + nr, base_items, commands->nr);
4915 nr += commands->nr;
4916
4917 insert = 0;
0cce4a27 4918 }
1ace63bc 4919
683153a4
AG
4920 ALLOC_GROW(items, nr + 1, alloc);
4921 items[nr++] = todo_list->items[i];
4922
1ace63bc 4923 if (command == TODO_PICK || command == TODO_MERGE)
683153a4 4924 insert = 1;
0cce4a27
LB
4925 }
4926
1ace63bc 4927 /* insert or append final <commands> */
683153a4
AG
4928 if (insert || nr == todo_list->nr) {
4929 ALLOC_GROW(items, nr + commands->nr, alloc);
4930 COPY_ARRAY(items + nr, base_items, commands->nr);
4931 nr += commands->nr;
4932 }
0cce4a27 4933
683153a4
AG
4934 free(base_items);
4935 FREE_AND_NULL(todo_list->items);
4936 todo_list->items = items;
4937 todo_list->nr = nr;
4938 todo_list->alloc = alloc;
0cce4a27 4939}
3546c8d9 4940
616d7740
AG
4941static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4942 struct strbuf *buf, int num, unsigned flags)
3546c8d9 4943{
8dccc7a6 4944 struct todo_item *item;
616d7740 4945 int i, max = todo_list->nr;
3546c8d9 4946
616d7740
AG
4947 if (num > 0 && num < max)
4948 max = num;
3546c8d9 4949
616d7740 4950 for (item = todo_list->items, i = 0; i < max; i++, item++) {
8dccc7a6
LB
4951 /* if the item is not a command write it and continue */
4952 if (item->command >= TODO_COMMENT) {
616d7740 4953 strbuf_addf(buf, "%.*s\n", item->arg_len,
cbef27d6 4954 todo_item_get_arg(todo_list, item));
8dccc7a6 4955 continue;
3546c8d9 4956 }
8dccc7a6
LB
4957
4958 /* add command to the buffer */
d8ae6c84 4959 if (flags & TODO_LIST_ABBREVIATE_CMDS)
616d7740 4960 strbuf_addch(buf, command_to_char(item->command));
d8ae6c84 4961 else
616d7740 4962 strbuf_addstr(buf, command_to_string(item->command));
8dccc7a6
LB
4963
4964 /* add commit id */
4965 if (item->commit) {
313a48ea 4966 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
8dccc7a6
LB
4967 short_commit_name(item->commit) :
4968 oid_to_hex(&item->commit->object.oid);
4969
4c68e7dd
JS
4970 if (item->command == TODO_MERGE) {
4971 if (item->flags & TODO_EDIT_MERGE_MSG)
616d7740 4972 strbuf_addstr(buf, " -c");
4c68e7dd 4973 else
616d7740 4974 strbuf_addstr(buf, " -C");
4c68e7dd
JS
4975 }
4976
616d7740 4977 strbuf_addf(buf, " %s", oid);
3546c8d9 4978 }
4c68e7dd 4979
8dccc7a6 4980 /* add all the rest */
c7b4d79c 4981 if (!item->arg_len)
616d7740 4982 strbuf_addch(buf, '\n');
c7b4d79c 4983 else
616d7740 4984 strbuf_addf(buf, " %.*s\n", item->arg_len,
cbef27d6 4985 todo_item_get_arg(todo_list, item));
3546c8d9 4986 }
3546c8d9 4987}
94399949 4988
616d7740
AG
4989int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
4990 const char *file, const char *shortrevisions,
4991 const char *shortonto, int num, unsigned flags)
94399949 4992{
af1fc3ad 4993 int res;
616d7740 4994 struct strbuf buf = STRBUF_INIT;
94399949 4995
616d7740 4996 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
af1fc3ad 4997 if (flags & TODO_LIST_APPEND_TODO_HELP)
d48e5e21 4998 append_todo_help(count_commands(todo_list),
af1fc3ad 4999 shortrevisions, shortonto, &buf);
94399949 5000
616d7740 5001 res = write_message(buf.buf, buf.len, file, 0);
cbef27d6 5002 strbuf_release(&buf);
8315bd20 5003
616d7740 5004 return res;
cbef27d6 5005}
94399949 5006
6ca89c6f
AG
5007static const char edit_todo_list_advice[] =
5008N_("You can fix this with 'git rebase --edit-todo' "
5009"and then run 'git rebase --continue'.\n"
5010"Or you can abort the rebase with 'git rebase"
5011" --abort'.\n");
94399949 5012
6ca89c6f 5013int check_todo_list_from_file(struct repository *r)
94399949 5014{
6ca89c6f
AG
5015 struct todo_list old_todo = TODO_LIST_INIT, new_todo = TODO_LIST_INIT;
5016 int res = 0;
94399949 5017
6ca89c6f 5018 if (strbuf_read_file_or_whine(&new_todo.buf, rebase_path_todo()) < 0) {
87805600 5019 res = -1;
6ca89c6f 5020 goto out;
94399949
JS
5021 }
5022
6ca89c6f 5023 if (strbuf_read_file_or_whine(&old_todo.buf, rebase_path_todo_backup()) < 0) {
87805600 5024 res = -1;
6ca89c6f 5025 goto out;
94399949
JS
5026 }
5027
6ca89c6f
AG
5028 res = todo_list_parse_insn_buffer(r, old_todo.buf.buf, &old_todo);
5029 if (!res)
5030 res = todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo);
5031 if (!res)
5032 res = todo_list_check(&old_todo, &new_todo);
5033 if (res)
5034 fprintf(stderr, _(edit_todo_list_advice));
5035out:
5036 todo_list_release(&old_todo);
5037 todo_list_release(&new_todo);
94399949
JS
5038
5039 return res;
5040}
cdac2b01
JS
5041
5042/* skip picking commits whose parents are unchanged */
6bfeb7f1
AG
5043static int skip_unnecessary_picks(struct repository *r,
5044 struct todo_list *todo_list,
5045 struct object_id *base_oid)
cdac2b01 5046{
d4ed5d77 5047 struct object_id *parent_oid;
6bfeb7f1 5048 int i;
cdac2b01 5049
6bfeb7f1
AG
5050 for (i = 0; i < todo_list->nr; i++) {
5051 struct todo_item *item = todo_list->items + i;
cdac2b01
JS
5052
5053 if (item->command >= TODO_NOOP)
5054 continue;
5055 if (item->command != TODO_PICK)
5056 break;
5057 if (parse_commit(item->commit)) {
cdac2b01
JS
5058 return error(_("could not parse commit '%s'"),
5059 oid_to_hex(&item->commit->object.oid));
5060 }
5061 if (!item->commit->parents)
5062 break; /* root commit */
5063 if (item->commit->parents->next)
5064 break; /* merge commit */
5065 parent_oid = &item->commit->parents->item->object.oid;
6bfeb7f1 5066 if (!oideq(parent_oid, base_oid))
cdac2b01 5067 break;
6bfeb7f1 5068 oidcpy(base_oid, &item->commit->object.oid);
cdac2b01
JS
5069 }
5070 if (i > 0) {
cdac2b01
JS
5071 const char *done_path = rebase_path_done();
5072
6bfeb7f1 5073 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
cdac2b01 5074 error_errno(_("could not write to '%s'"), done_path);
cdac2b01
JS
5075 return -1;
5076 }
cdac2b01 5077
6bfeb7f1
AG
5078 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5079 todo_list->nr -= i;
5080 todo_list->current = 0;
34065541 5081 todo_list->done_nr += i;
cdac2b01 5082
6bfeb7f1
AG
5083 if (is_fixup(peek_command(todo_list, 0)))
5084 record_in_rewritten(base_oid, peek_command(todo_list, 0));
cdac2b01
JS
5085 }
5086
cdac2b01
JS
5087 return 0;
5088}
c44a4c65 5089
005af339 5090int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873 5091 const char *shortrevisions, const char *onto_name,
7d3488eb
PW
5092 struct commit *onto, const char *orig_head,
5093 struct string_list *commands, unsigned autosquash,
5094 struct todo_list *todo_list)
b97e1873
AG
5095{
5096 const char *shortonto, *todo_file = rebase_path_todo();
94bcad79
AG
5097 struct todo_list new_todo = TODO_LIST_INIT;
5098 struct strbuf *buf = &todo_list->buf;
7d3488eb 5099 struct object_id oid = onto->object.oid;
1451d0f6 5100 int res;
b97e1873 5101
b97e1873
AG
5102 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5103
94bcad79
AG
5104 if (buf->len == 0) {
5105 struct todo_item *item = append_new_todo(todo_list);
5106 item->command = TODO_NOOP;
5107 item->commit = NULL;
5108 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5109 }
b97e1873 5110
94bcad79 5111 if (autosquash && todo_list_rearrange_squash(todo_list))
b97e1873
AG
5112 return -1;
5113
683153a4 5114 if (commands->nr)
94bcad79 5115 todo_list_add_exec_commands(todo_list, commands);
b97e1873 5116
94bcad79 5117 if (count_commands(todo_list) == 0) {
b97e1873
AG
5118 apply_autostash(opts);
5119 sequencer_remove_state(opts);
b97e1873
AG
5120
5121 return error(_("nothing to do"));
5122 }
5123
1451d0f6
AG
5124 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5125 shortonto, flags);
5126 if (res == -1)
b97e1873 5127 return -1;
1451d0f6 5128 else if (res == -2) {
b97e1873
AG
5129 apply_autostash(opts);
5130 sequencer_remove_state(opts);
b97e1873
AG
5131
5132 return -1;
1451d0f6 5133 } else if (res == -3) {
b97e1873
AG
5134 apply_autostash(opts);
5135 sequencer_remove_state(opts);
94bcad79 5136 todo_list_release(&new_todo);
b97e1873
AG
5137
5138 return error(_("nothing to do"));
5139 }
5140
94bcad79
AG
5141 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) ||
5142 todo_list_check(todo_list, &new_todo)) {
5143 fprintf(stderr, _(edit_todo_list_advice));
7d3488eb 5144 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
94bcad79
AG
5145 todo_list_release(&new_todo);
5146
b97e1873
AG
5147 return -1;
5148 }
5149
6bfeb7f1
AG
5150 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5151 todo_list_release(&new_todo);
b97e1873 5152 return error(_("could not skip unnecessary pick commands"));
6bfeb7f1
AG
5153 }
5154
94bcad79
AG
5155 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5156 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5157 todo_list_release(&new_todo);
5158 return error_errno(_("could not write '%s'"), todo_file);
5159 }
5160
393adf7a 5161 res = -1;
b97e1873 5162
7d3488eb 5163 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
393adf7a 5164 goto cleanup;
29d51e21 5165
005af339 5166 if (require_clean_work_tree(r, "rebase", "", 1, 1))
393adf7a 5167 goto cleanup;
b97e1873 5168
393adf7a
AG
5169 todo_list_write_total_nr(&new_todo);
5170 res = pick_commits(r, &new_todo, opts);
5171
5172cleanup:
5173 todo_list_release(&new_todo);
5174
5175 return res;
b97e1873
AG
5176}
5177
c44a4c65
JS
5178struct subject2item_entry {
5179 struct hashmap_entry entry;
5180 int i;
5181 char subject[FLEX_ARRAY];
5182};
5183
5184static int subject2item_cmp(const void *fndata,
939af16e
EW
5185 const struct hashmap_entry *eptr,
5186 const struct hashmap_entry *entry_or_key,
5187 const void *key)
c44a4c65 5188{
939af16e
EW
5189 const struct subject2item_entry *a, *b;
5190
5191 a = container_of(eptr, const struct subject2item_entry, entry);
5192 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5193
c44a4c65
JS
5194 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5195}
5196
3cc0287b
NTND
5197define_commit_slab(commit_todo_item, struct todo_item *);
5198
c44a4c65
JS
5199/*
5200 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5201 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5202 * after the former, and change "pick" to "fixup"/"squash".
5203 *
5204 * Note that if the config has specified a custom instruction format, each log
5205 * message will have to be retrieved from the commit (as the oneline in the
5206 * script cannot be trusted) in order to normalize the autosquash arrangement.
5207 */
79d7e883 5208int todo_list_rearrange_squash(struct todo_list *todo_list)
c44a4c65 5209{
c44a4c65 5210 struct hashmap subject2item;
f2a04904 5211 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
c44a4c65 5212 char **subjects;
3cc0287b 5213 struct commit_todo_item commit_todo;
f2a04904 5214 struct todo_item *items = NULL;
c44a4c65 5215
3cc0287b 5216 init_commit_todo_item(&commit_todo);
c44a4c65
JS
5217 /*
5218 * The hashmap maps onelines to the respective todo list index.
5219 *
5220 * If any items need to be rearranged, the next[i] value will indicate
5221 * which item was moved directly after the i'th.
5222 *
5223 * In that case, last[i] will indicate the index of the latest item to
5224 * be moved to appear after the i'th.
5225 */
939af16e 5226 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
f2a04904
AG
5227 ALLOC_ARRAY(next, todo_list->nr);
5228 ALLOC_ARRAY(tail, todo_list->nr);
5229 ALLOC_ARRAY(subjects, todo_list->nr);
5230 for (i = 0; i < todo_list->nr; i++) {
c44a4c65 5231 struct strbuf buf = STRBUF_INIT;
f2a04904 5232 struct todo_item *item = todo_list->items + i;
c44a4c65
JS
5233 const char *commit_buffer, *subject, *p;
5234 size_t subject_len;
5235 int i2 = -1;
5236 struct subject2item_entry *entry;
5237
5238 next[i] = tail[i] = -1;
2f6b1d13 5239 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
5240 subjects[i] = NULL;
5241 continue;
5242 }
5243
5244 if (is_fixup(item->command)) {
3cc0287b 5245 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
5246 return error(_("the script was already rearranged."));
5247 }
5248
3cc0287b 5249 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
5250
5251 parse_commit(item->commit);
0798d16f 5252 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
c44a4c65
JS
5253 find_commit_subject(commit_buffer, &subject);
5254 format_subject(&buf, subject, " ");
5255 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5256 unuse_commit_buffer(item->commit, commit_buffer);
5257 if ((skip_prefix(subject, "fixup! ", &p) ||
5258 skip_prefix(subject, "squash! ", &p))) {
5259 struct commit *commit2;
5260
5261 for (;;) {
5262 while (isspace(*p))
5263 p++;
5264 if (!skip_prefix(p, "fixup! ", &p) &&
5265 !skip_prefix(p, "squash! ", &p))
5266 break;
5267 }
5268
f23a4651
EW
5269 entry = hashmap_get_entry_from_hash(&subject2item,
5270 strhash(p), p,
5271 struct subject2item_entry,
5272 entry);
5273 if (entry)
c44a4c65
JS
5274 /* found by title */
5275 i2 = entry->i;
5276 else if (!strchr(p, ' ') &&
5277 (commit2 =
5278 lookup_commit_reference_by_name(p)) &&
3cc0287b 5279 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 5280 /* found by commit name */
3cc0287b 5281 i2 = *commit_todo_item_at(&commit_todo, commit2)
f2a04904 5282 - todo_list->items;
c44a4c65
JS
5283 else {
5284 /* copy can be a prefix of the commit subject */
5285 for (i2 = 0; i2 < i; i2++)
5286 if (subjects[i2] &&
5287 starts_with(subjects[i2], p))
5288 break;
5289 if (i2 == i)
5290 i2 = -1;
5291 }
5292 }
5293 if (i2 >= 0) {
5294 rearranged = 1;
f2a04904 5295 todo_list->items[i].command =
c44a4c65
JS
5296 starts_with(subject, "fixup!") ?
5297 TODO_FIXUP : TODO_SQUASH;
5298 if (next[i2] < 0)
5299 next[i2] = i;
5300 else
5301 next[tail[i2]] = i;
5302 tail[i2] = i;
5303 } else if (!hashmap_get_from_hash(&subject2item,
5304 strhash(subject), subject)) {
5305 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5306 entry->i = i;
d22245a2
EW
5307 hashmap_entry_init(&entry->entry,
5308 strhash(entry->subject));
26b455f2 5309 hashmap_put(&subject2item, &entry->entry);
c44a4c65
JS
5310 }
5311 }
5312
5313 if (rearranged) {
f2a04904
AG
5314 for (i = 0; i < todo_list->nr; i++) {
5315 enum todo_command command = todo_list->items[i].command;
c44a4c65
JS
5316 int cur = i;
5317
5318 /*
5319 * Initially, all commands are 'pick's. If it is a
5320 * fixup or a squash now, we have rearranged it.
5321 */
5322 if (is_fixup(command))
5323 continue;
5324
5325 while (cur >= 0) {
f2a04904
AG
5326 ALLOC_GROW(items, nr + 1, alloc);
5327 items[nr++] = todo_list->items[cur];
c44a4c65
JS
5328 cur = next[cur];
5329 }
5330 }
5331
f2a04904
AG
5332 FREE_AND_NULL(todo_list->items);
5333 todo_list->items = items;
5334 todo_list->nr = nr;
5335 todo_list->alloc = alloc;
c44a4c65
JS
5336 }
5337
5338 free(next);
5339 free(tail);
f2a04904 5340 for (i = 0; i < todo_list->nr; i++)
c44a4c65
JS
5341 free(subjects[i]);
5342 free(subjects);
c8e424c9 5343 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
c44a4c65 5344
3cc0287b 5345 clear_commit_todo_item(&commit_todo);
f2a04904
AG
5346
5347 return 0;
c44a4c65 5348}