worktree: move subcommand
[git] / sequencer.c
1 #include "cache.h"
2 #include "lockfile.h"
3 #include "sequencer.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "run-command.h"
9 #include "exec_cmd.h"
10 #include "utf8.h"
11 #include "cache-tree.h"
12 #include "diff.h"
13 #include "revision.h"
14 #include "rerere.h"
15 #include "merge-recursive.h"
16 #include "refs.h"
17 #include "argv-array.h"
18 #include "quote.h"
19 #include "trailer.h"
20 #include "log-tree.h"
21 #include "wt-status.h"
22
23 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
24
25 const char sign_off_header[] = "Signed-off-by: ";
26 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
27
28 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
29
30 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
31 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
32 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
33 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
34
35 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
36 /*
37  * The file containing rebase commands, comments, and empty lines.
38  * This file is created by "git rebase -i" then edited by the user. As
39  * the lines are processed, they are removed from the front of this
40  * file and written to the tail of 'done'.
41  */
42 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
43 /*
44  * The rebase command lines that have already been processed. A line
45  * is moved here when it is first handled, before any associated user
46  * actions.
47  */
48 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
49 /*
50  * The file to keep track of how many commands were already processed (e.g.
51  * for the prompt).
52  */
53 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
54 /*
55  * The file to keep track of how many commands are to be processed in total
56  * (e.g. for the prompt).
57  */
58 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
59 /*
60  * The commit message that is planned to be used for any changes that
61  * need to be committed following a user interaction.
62  */
63 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
64 /*
65  * The file into which is accumulated the suggested commit message for
66  * squash/fixup commands. When the first of a series of squash/fixups
67  * is seen, the file is created and the commit message from the
68  * previous commit and from the first squash/fixup commit are written
69  * to it. The commit message for each subsequent squash/fixup commit
70  * is appended to the file as it is processed.
71  *
72  * The first line of the file is of the form
73  *     # This is a combination of $count commits.
74  * where $count is the number of commits whose messages have been
75  * written to the file so far (including the initial "pick" commit).
76  * Each time that a commit message is processed, this line is read and
77  * updated. It is deleted just before the combined commit is made.
78  */
79 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
80 /*
81  * If the current series of squash/fixups has not yet included a squash
82  * command, then this file exists and holds the commit message of the
83  * original "pick" commit.  (If the series ends without a "squash"
84  * command, then this can be used as the commit message of the combined
85  * commit without opening the editor.)
86  */
87 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
88 /*
89  * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
90  * GIT_AUTHOR_DATE that will be used for the commit that is currently
91  * being rebased.
92  */
93 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
94 /*
95  * When an "edit" rebase command is being processed, the SHA1 of the
96  * commit to be edited is recorded in this file.  When "git rebase
97  * --continue" is executed, if there are any staged changes then they
98  * will be amended to the HEAD commit, but only provided the HEAD
99  * commit is still the commit to be edited.  When any other rebase
100  * command is processed, this file is deleted.
101  */
102 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
103 /*
104  * When we stop at a given patch via the "edit" command, this file contains
105  * the abbreviated commit name of the corresponding patch.
106  */
107 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
108 /*
109  * For the post-rewrite hook, we make a list of rewritten commits and
110  * their new sha1s.  The rewritten-pending list keeps the sha1s of
111  * commits that have been processed, but not committed yet,
112  * e.g. because they are waiting for a 'squash' command.
113  */
114 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
115 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
116         "rebase-merge/rewritten-pending")
117 /*
118  * The following files are written by git-rebase just after parsing the
119  * command-line (and are only consumed, not modified, by the sequencer).
120  */
121 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
122 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
123 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
124 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
125 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
126 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
127 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
128 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
129
130 static inline int is_rebase_i(const struct replay_opts *opts)
131 {
132         return opts->action == REPLAY_INTERACTIVE_REBASE;
133 }
134
135 static const char *get_dir(const struct replay_opts *opts)
136 {
137         if (is_rebase_i(opts))
138                 return rebase_path();
139         return git_path_seq_dir();
140 }
141
142 static const char *get_todo_path(const struct replay_opts *opts)
143 {
144         if (is_rebase_i(opts))
145                 return rebase_path_todo();
146         return git_path_todo_file();
147 }
148
149 /*
150  * Returns 0 for non-conforming footer
151  * Returns 1 for conforming footer
152  * Returns 2 when sob exists within conforming footer
153  * Returns 3 when sob exists within conforming footer as last entry
154  */
155 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
156         int ignore_footer)
157 {
158         struct trailer_info info;
159         int i;
160         int found_sob = 0, found_sob_last = 0;
161
162         trailer_info_get(&info, sb->buf);
163
164         if (info.trailer_start == info.trailer_end)
165                 return 0;
166
167         for (i = 0; i < info.trailer_nr; i++)
168                 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
169                         found_sob = 1;
170                         if (i == info.trailer_nr - 1)
171                                 found_sob_last = 1;
172                 }
173
174         trailer_info_release(&info);
175
176         if (found_sob_last)
177                 return 3;
178         if (found_sob)
179                 return 2;
180         return 1;
181 }
182
183 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
184 {
185         static struct strbuf buf = STRBUF_INIT;
186
187         strbuf_reset(&buf);
188         if (opts->gpg_sign)
189                 sq_quotef(&buf, "-S%s", opts->gpg_sign);
190         return buf.buf;
191 }
192
193 int sequencer_remove_state(struct replay_opts *opts)
194 {
195         struct strbuf dir = STRBUF_INIT;
196         int i;
197
198         free(opts->gpg_sign);
199         free(opts->strategy);
200         for (i = 0; i < opts->xopts_nr; i++)
201                 free(opts->xopts[i]);
202         free(opts->xopts);
203
204         strbuf_addf(&dir, "%s", get_dir(opts));
205         remove_dir_recursively(&dir, 0);
206         strbuf_release(&dir);
207
208         return 0;
209 }
210
211 static const char *action_name(const struct replay_opts *opts)
212 {
213         switch (opts->action) {
214         case REPLAY_REVERT:
215                 return N_("revert");
216         case REPLAY_PICK:
217                 return N_("cherry-pick");
218         case REPLAY_INTERACTIVE_REBASE:
219                 return N_("rebase -i");
220         }
221         die(_("Unknown action: %d"), opts->action);
222 }
223
224 struct commit_message {
225         char *parent_label;
226         char *label;
227         char *subject;
228         const char *message;
229 };
230
231 static const char *short_commit_name(struct commit *commit)
232 {
233         return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
234 }
235
236 static int get_message(struct commit *commit, struct commit_message *out)
237 {
238         const char *abbrev, *subject;
239         int subject_len;
240
241         out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
242         abbrev = short_commit_name(commit);
243
244         subject_len = find_commit_subject(out->message, &subject);
245
246         out->subject = xmemdupz(subject, subject_len);
247         out->label = xstrfmt("%s... %s", abbrev, out->subject);
248         out->parent_label = xstrfmt("parent of %s", out->label);
249
250         return 0;
251 }
252
253 static void free_message(struct commit *commit, struct commit_message *msg)
254 {
255         free(msg->parent_label);
256         free(msg->label);
257         free(msg->subject);
258         unuse_commit_buffer(commit, msg->message);
259 }
260
261 static void print_advice(int show_hint, struct replay_opts *opts)
262 {
263         char *msg = getenv("GIT_CHERRY_PICK_HELP");
264
265         if (msg) {
266                 fprintf(stderr, "%s\n", msg);
267                 /*
268                  * A conflict has occurred but the porcelain
269                  * (typically rebase --interactive) wants to take care
270                  * of the commit itself so remove CHERRY_PICK_HEAD
271                  */
272                 unlink(git_path_cherry_pick_head());
273                 return;
274         }
275
276         if (show_hint) {
277                 if (opts->no_commit)
278                         advise(_("after resolving the conflicts, mark the corrected paths\n"
279                                  "with 'git add <paths>' or 'git rm <paths>'"));
280                 else
281                         advise(_("after resolving the conflicts, mark the corrected paths\n"
282                                  "with 'git add <paths>' or 'git rm <paths>'\n"
283                                  "and commit the result with 'git commit'"));
284         }
285 }
286
287 static int write_message(const void *buf, size_t len, const char *filename,
288                          int append_eol)
289 {
290         static struct lock_file msg_file;
291
292         int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
293         if (msg_fd < 0)
294                 return error_errno(_("could not lock '%s'"), filename);
295         if (write_in_full(msg_fd, buf, len) < 0) {
296                 rollback_lock_file(&msg_file);
297                 return error_errno(_("could not write to '%s'"), filename);
298         }
299         if (append_eol && write(msg_fd, "\n", 1) < 0) {
300                 rollback_lock_file(&msg_file);
301                 return error_errno(_("could not write eol to '%s'"), filename);
302         }
303         if (commit_lock_file(&msg_file) < 0) {
304                 rollback_lock_file(&msg_file);
305                 return error(_("failed to finalize '%s'."), filename);
306         }
307
308         return 0;
309 }
310
311 /*
312  * Reads a file that was presumably written by a shell script, i.e. with an
313  * end-of-line marker that needs to be stripped.
314  *
315  * Note that only the last end-of-line marker is stripped, consistent with the
316  * behavior of "$(cat path)" in a shell script.
317  *
318  * Returns 1 if the file was read, 0 if it could not be read or does not exist.
319  */
320 static int read_oneliner(struct strbuf *buf,
321         const char *path, int skip_if_empty)
322 {
323         int orig_len = buf->len;
324
325         if (!file_exists(path))
326                 return 0;
327
328         if (strbuf_read_file(buf, path, 0) < 0) {
329                 warning_errno(_("could not read '%s'"), path);
330                 return 0;
331         }
332
333         if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
334                 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
335                         --buf->len;
336                 buf->buf[buf->len] = '\0';
337         }
338
339         if (skip_if_empty && buf->len == orig_len)
340                 return 0;
341
342         return 1;
343 }
344
345 static struct tree *empty_tree(void)
346 {
347         return lookup_tree(EMPTY_TREE_SHA1_BIN);
348 }
349
350 static int error_dirty_index(struct replay_opts *opts)
351 {
352         if (read_cache_unmerged())
353                 return error_resolve_conflict(_(action_name(opts)));
354
355         error(_("your local changes would be overwritten by %s."),
356                 _(action_name(opts)));
357
358         if (advice_commit_before_merge)
359                 advise(_("commit your changes or stash them to proceed."));
360         return -1;
361 }
362
363 static void update_abort_safety_file(void)
364 {
365         struct object_id head;
366
367         /* Do nothing on a single-pick */
368         if (!file_exists(git_path_seq_dir()))
369                 return;
370
371         if (!get_oid("HEAD", &head))
372                 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
373         else
374                 write_file(git_path_abort_safety_file(), "%s", "");
375 }
376
377 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
378                         int unborn, struct replay_opts *opts)
379 {
380         struct ref_transaction *transaction;
381         struct strbuf sb = STRBUF_INIT;
382         struct strbuf err = STRBUF_INIT;
383
384         read_cache();
385         if (checkout_fast_forward(from, to, 1))
386                 return -1; /* the callee should have complained already */
387
388         strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
389
390         transaction = ref_transaction_begin(&err);
391         if (!transaction ||
392             ref_transaction_update(transaction, "HEAD",
393                                    to, unborn ? null_sha1 : from,
394                                    0, sb.buf, &err) ||
395             ref_transaction_commit(transaction, &err)) {
396                 ref_transaction_free(transaction);
397                 error("%s", err.buf);
398                 strbuf_release(&sb);
399                 strbuf_release(&err);
400                 return -1;
401         }
402
403         strbuf_release(&sb);
404         strbuf_release(&err);
405         ref_transaction_free(transaction);
406         update_abort_safety_file();
407         return 0;
408 }
409
410 void append_conflicts_hint(struct strbuf *msgbuf)
411 {
412         int i;
413
414         strbuf_addch(msgbuf, '\n');
415         strbuf_commented_addf(msgbuf, "Conflicts:\n");
416         for (i = 0; i < active_nr;) {
417                 const struct cache_entry *ce = active_cache[i++];
418                 if (ce_stage(ce)) {
419                         strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
420                         while (i < active_nr && !strcmp(ce->name,
421                                                         active_cache[i]->name))
422                                 i++;
423                 }
424         }
425 }
426
427 static int do_recursive_merge(struct commit *base, struct commit *next,
428                               const char *base_label, const char *next_label,
429                               unsigned char *head, struct strbuf *msgbuf,
430                               struct replay_opts *opts)
431 {
432         struct merge_options o;
433         struct tree *result, *next_tree, *base_tree, *head_tree;
434         int clean;
435         char **xopt;
436         static struct lock_file index_lock;
437
438         hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
439
440         read_cache();
441
442         init_merge_options(&o);
443         o.ancestor = base ? base_label : "(empty tree)";
444         o.branch1 = "HEAD";
445         o.branch2 = next ? next_label : "(empty tree)";
446         if (is_rebase_i(opts))
447                 o.buffer_output = 2;
448
449         head_tree = parse_tree_indirect(head);
450         next_tree = next ? next->tree : empty_tree();
451         base_tree = base ? base->tree : empty_tree();
452
453         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
454                 parse_merge_opt(&o, *xopt);
455
456         clean = merge_trees(&o,
457                             head_tree,
458                             next_tree, base_tree, &result);
459         if (is_rebase_i(opts) && clean <= 0)
460                 fputs(o.obuf.buf, stdout);
461         strbuf_release(&o.obuf);
462         if (clean < 0)
463                 return clean;
464
465         if (active_cache_changed &&
466             write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
467                 /* TRANSLATORS: %s will be "revert", "cherry-pick" or
468                  * "rebase -i".
469                  */
470                 return error(_("%s: Unable to write new index file"),
471                         _(action_name(opts)));
472         rollback_lock_file(&index_lock);
473
474         if (opts->signoff)
475                 append_signoff(msgbuf, 0, 0);
476
477         if (!clean)
478                 append_conflicts_hint(msgbuf);
479
480         return !clean;
481 }
482
483 static int is_index_unchanged(void)
484 {
485         unsigned char head_sha1[20];
486         struct commit *head_commit;
487
488         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
489                 return error(_("could not resolve HEAD commit\n"));
490
491         head_commit = lookup_commit(head_sha1);
492
493         /*
494          * If head_commit is NULL, check_commit, called from
495          * lookup_commit, would have indicated that head_commit is not
496          * a commit object already.  parse_commit() will return failure
497          * without further complaints in such a case.  Otherwise, if
498          * the commit is invalid, parse_commit() will complain.  So
499          * there is nothing for us to say here.  Just return failure.
500          */
501         if (parse_commit(head_commit))
502                 return -1;
503
504         if (!active_cache_tree)
505                 active_cache_tree = cache_tree();
506
507         if (!cache_tree_fully_valid(active_cache_tree))
508                 if (cache_tree_update(&the_index, 0))
509                         return error(_("unable to update cache tree\n"));
510
511         return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
512 }
513
514 static int write_author_script(const char *message)
515 {
516         struct strbuf buf = STRBUF_INIT;
517         const char *eol;
518         int res;
519
520         for (;;)
521                 if (!*message || starts_with(message, "\n")) {
522 missing_author:
523                         /* Missing 'author' line? */
524                         unlink(rebase_path_author_script());
525                         return 0;
526                 } else if (skip_prefix(message, "author ", &message))
527                         break;
528                 else if ((eol = strchr(message, '\n')))
529                         message = eol + 1;
530                 else
531                         goto missing_author;
532
533         strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
534         while (*message && *message != '\n' && *message != '\r')
535                 if (skip_prefix(message, " <", &message))
536                         break;
537                 else if (*message != '\'')
538                         strbuf_addch(&buf, *(message++));
539                 else
540                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
541         strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
542         while (*message && *message != '\n' && *message != '\r')
543                 if (skip_prefix(message, "> ", &message))
544                         break;
545                 else if (*message != '\'')
546                         strbuf_addch(&buf, *(message++));
547                 else
548                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
549         strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
550         while (*message && *message != '\n' && *message != '\r')
551                 if (*message != '\'')
552                         strbuf_addch(&buf, *(message++));
553                 else
554                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
555         res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
556         strbuf_release(&buf);
557         return res;
558 }
559
560 /*
561  * Read a list of environment variable assignments (such as the author-script
562  * file) into an environment block. Returns -1 on error, 0 otherwise.
563  */
564 static int read_env_script(struct argv_array *env)
565 {
566         struct strbuf script = STRBUF_INIT;
567         int i, count = 0;
568         char *p, *p2;
569
570         if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
571                 return -1;
572
573         for (p = script.buf; *p; p++)
574                 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
575                         strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
576                 else if (*p == '\'')
577                         strbuf_splice(&script, p-- - script.buf, 1, "", 0);
578                 else if (*p == '\n') {
579                         *p = '\0';
580                         count++;
581                 }
582
583         for (i = 0, p = script.buf; i < count; i++) {
584                 argv_array_push(env, p);
585                 p += strlen(p) + 1;
586         }
587
588         return 0;
589 }
590
591 static const char staged_changes_advice[] =
592 N_("you have staged changes in your working tree\n"
593 "If these changes are meant to be squashed into the previous commit, run:\n"
594 "\n"
595 "  git commit --amend %s\n"
596 "\n"
597 "If they are meant to go into a new commit, run:\n"
598 "\n"
599 "  git commit %s\n"
600 "\n"
601 "In both cases, once you're done, continue with:\n"
602 "\n"
603 "  git rebase --continue\n");
604
605 #define ALLOW_EMPTY (1<<0)
606 #define EDIT_MSG    (1<<1)
607 #define AMEND_MSG   (1<<2)
608 #define CLEANUP_MSG (1<<3)
609 #define VERIFY_MSG  (1<<4)
610
611 /*
612  * If we are cherry-pick, and if the merge did not result in
613  * hand-editing, we will hit this commit and inherit the original
614  * author date and name.
615  *
616  * If we are revert, or if our cherry-pick results in a hand merge,
617  * we had better say that the current user is responsible for that.
618  *
619  * An exception is when run_git_commit() is called during an
620  * interactive rebase: in that case, we will want to retain the
621  * author metadata.
622  */
623 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
624                           unsigned int flags)
625 {
626         struct child_process cmd = CHILD_PROCESS_INIT;
627         const char *value;
628
629         cmd.git_cmd = 1;
630
631         if (is_rebase_i(opts)) {
632                 if (!(flags & EDIT_MSG)) {
633                         cmd.stdout_to_stderr = 1;
634                         cmd.err = -1;
635                 }
636
637                 if (read_env_script(&cmd.env_array)) {
638                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
639
640                         return error(_(staged_changes_advice),
641                                      gpg_opt, gpg_opt);
642                 }
643         }
644
645         argv_array_push(&cmd.args, "commit");
646
647         if (!(flags & VERIFY_MSG))
648                 argv_array_push(&cmd.args, "-n");
649         if ((flags & AMEND_MSG))
650                 argv_array_push(&cmd.args, "--amend");
651         if (opts->gpg_sign)
652                 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
653         if (opts->signoff)
654                 argv_array_push(&cmd.args, "-s");
655         if (defmsg)
656                 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
657         if ((flags & CLEANUP_MSG))
658                 argv_array_push(&cmd.args, "--cleanup=strip");
659         if ((flags & EDIT_MSG))
660                 argv_array_push(&cmd.args, "-e");
661         else if (!(flags & CLEANUP_MSG) &&
662                  !opts->signoff && !opts->record_origin &&
663                  git_config_get_value("commit.cleanup", &value))
664                 argv_array_push(&cmd.args, "--cleanup=verbatim");
665
666         if ((flags & ALLOW_EMPTY))
667                 argv_array_push(&cmd.args, "--allow-empty");
668
669         if (opts->allow_empty_message)
670                 argv_array_push(&cmd.args, "--allow-empty-message");
671
672         if (cmd.err == -1) {
673                 /* hide stderr on success */
674                 struct strbuf buf = STRBUF_INIT;
675                 int rc = pipe_command(&cmd,
676                                       NULL, 0,
677                                       /* stdout is already redirected */
678                                       NULL, 0,
679                                       &buf, 0);
680                 if (rc)
681                         fputs(buf.buf, stderr);
682                 strbuf_release(&buf);
683                 return rc;
684         }
685
686         return run_command(&cmd);
687 }
688
689 static int is_original_commit_empty(struct commit *commit)
690 {
691         const unsigned char *ptree_sha1;
692
693         if (parse_commit(commit))
694                 return error(_("could not parse commit %s\n"),
695                              oid_to_hex(&commit->object.oid));
696         if (commit->parents) {
697                 struct commit *parent = commit->parents->item;
698                 if (parse_commit(parent))
699                         return error(_("could not parse parent commit %s\n"),
700                                 oid_to_hex(&parent->object.oid));
701                 ptree_sha1 = parent->tree->object.oid.hash;
702         } else {
703                 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
704         }
705
706         return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
707 }
708
709 /*
710  * Do we run "git commit" with "--allow-empty"?
711  */
712 static int allow_empty(struct replay_opts *opts, struct commit *commit)
713 {
714         int index_unchanged, empty_commit;
715
716         /*
717          * Three cases:
718          *
719          * (1) we do not allow empty at all and error out.
720          *
721          * (2) we allow ones that were initially empty, but
722          * forbid the ones that become empty;
723          *
724          * (3) we allow both.
725          */
726         if (!opts->allow_empty)
727                 return 0; /* let "git commit" barf as necessary */
728
729         index_unchanged = is_index_unchanged();
730         if (index_unchanged < 0)
731                 return index_unchanged;
732         if (!index_unchanged)
733                 return 0; /* we do not have to say --allow-empty */
734
735         if (opts->keep_redundant_commits)
736                 return 1;
737
738         empty_commit = is_original_commit_empty(commit);
739         if (empty_commit < 0)
740                 return empty_commit;
741         if (!empty_commit)
742                 return 0;
743         else
744                 return 1;
745 }
746
747 /*
748  * Note that ordering matters in this enum. Not only must it match the mapping
749  * below, it is also divided into several sections that matter.  When adding
750  * new commands, make sure you add it in the right section.
751  */
752 enum todo_command {
753         /* commands that handle commits */
754         TODO_PICK = 0,
755         TODO_REVERT,
756         TODO_EDIT,
757         TODO_REWORD,
758         TODO_FIXUP,
759         TODO_SQUASH,
760         /* commands that do something else than handling a single commit */
761         TODO_EXEC,
762         /* commands that do nothing but are counted for reporting progress */
763         TODO_NOOP,
764         TODO_DROP,
765         /* comments (not counted for reporting progress) */
766         TODO_COMMENT
767 };
768
769 static struct {
770         char c;
771         const char *str;
772 } todo_command_info[] = {
773         { 'p', "pick" },
774         { 0,   "revert" },
775         { 'e', "edit" },
776         { 'r', "reword" },
777         { 'f', "fixup" },
778         { 's', "squash" },
779         { 'x', "exec" },
780         { 0,   "noop" },
781         { 'd', "drop" },
782         { 0,   NULL }
783 };
784
785 static const char *command_to_string(const enum todo_command command)
786 {
787         if (command < TODO_COMMENT)
788                 return todo_command_info[command].str;
789         die("Unknown command: %d", command);
790 }
791
792 static int is_noop(const enum todo_command command)
793 {
794         return TODO_NOOP <= command;
795 }
796
797 static int is_fixup(enum todo_command command)
798 {
799         return command == TODO_FIXUP || command == TODO_SQUASH;
800 }
801
802 static int update_squash_messages(enum todo_command command,
803                 struct commit *commit, struct replay_opts *opts)
804 {
805         struct strbuf buf = STRBUF_INIT;
806         int count, res;
807         const char *message, *body;
808
809         if (file_exists(rebase_path_squash_msg())) {
810                 struct strbuf header = STRBUF_INIT;
811                 char *eol, *p;
812
813                 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
814                         return error(_("could not read '%s'"),
815                                 rebase_path_squash_msg());
816
817                 p = buf.buf + 1;
818                 eol = strchrnul(buf.buf, '\n');
819                 if (buf.buf[0] != comment_line_char ||
820                     (p += strcspn(p, "0123456789\n")) == eol)
821                         return error(_("unexpected 1st line of squash message:"
822                                        "\n\n\t%.*s"),
823                                      (int)(eol - buf.buf), buf.buf);
824                 count = strtol(p, NULL, 10);
825
826                 if (count < 1)
827                         return error(_("invalid 1st line of squash message:\n"
828                                        "\n\t%.*s"),
829                                      (int)(eol - buf.buf), buf.buf);
830
831                 strbuf_addf(&header, "%c ", comment_line_char);
832                 strbuf_addf(&header,
833                             _("This is a combination of %d commits."), ++count);
834                 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
835                 strbuf_release(&header);
836         } else {
837                 unsigned char head[20];
838                 struct commit *head_commit;
839                 const char *head_message, *body;
840
841                 if (get_sha1("HEAD", head))
842                         return error(_("need a HEAD to fixup"));
843                 if (!(head_commit = lookup_commit_reference(head)))
844                         return error(_("could not read HEAD"));
845                 if (!(head_message = get_commit_buffer(head_commit, NULL)))
846                         return error(_("could not read HEAD's commit message"));
847
848                 find_commit_subject(head_message, &body);
849                 if (write_message(body, strlen(body),
850                                   rebase_path_fixup_msg(), 0)) {
851                         unuse_commit_buffer(head_commit, head_message);
852                         return error(_("cannot write '%s'"),
853                                      rebase_path_fixup_msg());
854                 }
855
856                 count = 2;
857                 strbuf_addf(&buf, "%c ", comment_line_char);
858                 strbuf_addf(&buf, _("This is a combination of %d commits."),
859                             count);
860                 strbuf_addf(&buf, "\n%c ", comment_line_char);
861                 strbuf_addstr(&buf, _("This is the 1st commit message:"));
862                 strbuf_addstr(&buf, "\n\n");
863                 strbuf_addstr(&buf, body);
864
865                 unuse_commit_buffer(head_commit, head_message);
866         }
867
868         if (!(message = get_commit_buffer(commit, NULL)))
869                 return error(_("could not read commit message of %s"),
870                              oid_to_hex(&commit->object.oid));
871         find_commit_subject(message, &body);
872
873         if (command == TODO_SQUASH) {
874                 unlink(rebase_path_fixup_msg());
875                 strbuf_addf(&buf, "\n%c ", comment_line_char);
876                 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
877                 strbuf_addstr(&buf, "\n\n");
878                 strbuf_addstr(&buf, body);
879         } else if (command == TODO_FIXUP) {
880                 strbuf_addf(&buf, "\n%c ", comment_line_char);
881                 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
882                             count);
883                 strbuf_addstr(&buf, "\n\n");
884                 strbuf_add_commented_lines(&buf, body, strlen(body));
885         } else
886                 return error(_("unknown command: %d"), command);
887         unuse_commit_buffer(commit, message);
888
889         res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
890         strbuf_release(&buf);
891         return res;
892 }
893
894 static void flush_rewritten_pending(void) {
895         struct strbuf buf = STRBUF_INIT;
896         unsigned char newsha1[20];
897         FILE *out;
898
899         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), 82) > 0 &&
900                         !get_sha1("HEAD", newsha1) &&
901                         (out = fopen(rebase_path_rewritten_list(), "a"))) {
902                 char *bol = buf.buf, *eol;
903
904                 while (*bol) {
905                         eol = strchrnul(bol, '\n');
906                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
907                                         bol, sha1_to_hex(newsha1));
908                         if (!*eol)
909                                 break;
910                         bol = eol + 1;
911                 }
912                 fclose(out);
913                 unlink(rebase_path_rewritten_pending());
914         }
915         strbuf_release(&buf);
916 }
917
918 static void record_in_rewritten(struct object_id *oid,
919                 enum todo_command next_command) {
920         FILE *out = fopen(rebase_path_rewritten_pending(), "a");
921
922         if (!out)
923                 return;
924
925         fprintf(out, "%s\n", oid_to_hex(oid));
926         fclose(out);
927
928         if (!is_fixup(next_command))
929                 flush_rewritten_pending();
930 }
931
932 static int do_pick_commit(enum todo_command command, struct commit *commit,
933                 struct replay_opts *opts, int final_fixup)
934 {
935         unsigned int flags = opts->edit ? EDIT_MSG : 0;
936         const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
937         unsigned char head[20];
938         struct commit *base, *next, *parent;
939         const char *base_label, *next_label;
940         struct commit_message msg = { NULL, NULL, NULL, NULL };
941         struct strbuf msgbuf = STRBUF_INIT;
942         int res, unborn = 0, allow;
943
944         if (opts->no_commit) {
945                 /*
946                  * We do not intend to commit immediately.  We just want to
947                  * merge the differences in, so let's compute the tree
948                  * that represents the "current" state for merge-recursive
949                  * to work on.
950                  */
951                 if (write_cache_as_tree(head, 0, NULL))
952                         return error(_("your index file is unmerged."));
953         } else {
954                 unborn = get_sha1("HEAD", head);
955                 if (unborn)
956                         hashcpy(head, EMPTY_TREE_SHA1_BIN);
957                 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
958                         return error_dirty_index(opts);
959         }
960         discard_cache();
961
962         if (!commit->parents)
963                 parent = NULL;
964         else if (commit->parents->next) {
965                 /* Reverting or cherry-picking a merge commit */
966                 int cnt;
967                 struct commit_list *p;
968
969                 if (!opts->mainline)
970                         return error(_("commit %s is a merge but no -m option was given."),
971                                 oid_to_hex(&commit->object.oid));
972
973                 for (cnt = 1, p = commit->parents;
974                      cnt != opts->mainline && p;
975                      cnt++)
976                         p = p->next;
977                 if (cnt != opts->mainline || !p)
978                         return error(_("commit %s does not have parent %d"),
979                                 oid_to_hex(&commit->object.oid), opts->mainline);
980                 parent = p->item;
981         } else if (0 < opts->mainline)
982                 return error(_("mainline was specified but commit %s is not a merge."),
983                         oid_to_hex(&commit->object.oid));
984         else
985                 parent = commit->parents->item;
986
987         if (get_message(commit, &msg) != 0)
988                 return error(_("cannot get commit message for %s"),
989                         oid_to_hex(&commit->object.oid));
990
991         if (opts->allow_ff && !is_fixup(command) &&
992             ((parent && !hashcmp(parent->object.oid.hash, head)) ||
993              (!parent && unborn))) {
994                 if (is_rebase_i(opts))
995                         write_author_script(msg.message);
996                 res = fast_forward_to(commit->object.oid.hash, head, unborn,
997                         opts);
998                 if (res || command != TODO_REWORD)
999                         goto leave;
1000                 flags |= EDIT_MSG | AMEND_MSG;
1001                 if (command == TODO_REWORD)
1002                         flags |= VERIFY_MSG;
1003                 msg_file = NULL;
1004                 goto fast_forward_edit;
1005         }
1006         if (parent && parse_commit(parent) < 0)
1007                 /* TRANSLATORS: The first %s will be a "todo" command like
1008                    "revert" or "pick", the second %s a SHA1. */
1009                 return error(_("%s: cannot parse parent commit %s"),
1010                         command_to_string(command),
1011                         oid_to_hex(&parent->object.oid));
1012
1013         /*
1014          * "commit" is an existing commit.  We would want to apply
1015          * the difference it introduces since its first parent "prev"
1016          * on top of the current HEAD if we are cherry-pick.  Or the
1017          * reverse of it if we are revert.
1018          */
1019
1020         if (command == TODO_REVERT) {
1021                 base = commit;
1022                 base_label = msg.label;
1023                 next = parent;
1024                 next_label = msg.parent_label;
1025                 strbuf_addstr(&msgbuf, "Revert \"");
1026                 strbuf_addstr(&msgbuf, msg.subject);
1027                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1028                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1029
1030                 if (commit->parents && commit->parents->next) {
1031                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1032                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1033                 }
1034                 strbuf_addstr(&msgbuf, ".\n");
1035         } else {
1036                 const char *p;
1037
1038                 base = parent;
1039                 base_label = msg.parent_label;
1040                 next = commit;
1041                 next_label = msg.label;
1042
1043                 /* Append the commit log message to msgbuf. */
1044                 if (find_commit_subject(msg.message, &p))
1045                         strbuf_addstr(&msgbuf, p);
1046
1047                 if (opts->record_origin) {
1048                         if (!has_conforming_footer(&msgbuf, NULL, 0))
1049                                 strbuf_addch(&msgbuf, '\n');
1050                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
1051                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1052                         strbuf_addstr(&msgbuf, ")\n");
1053                 }
1054         }
1055
1056         if (command == TODO_REWORD)
1057                 flags |= EDIT_MSG | VERIFY_MSG;
1058         else if (is_fixup(command)) {
1059                 if (update_squash_messages(command, commit, opts))
1060                         return -1;
1061                 flags |= AMEND_MSG;
1062                 if (!final_fixup)
1063                         msg_file = rebase_path_squash_msg();
1064                 else if (file_exists(rebase_path_fixup_msg())) {
1065                         flags |= CLEANUP_MSG;
1066                         msg_file = rebase_path_fixup_msg();
1067                 } else {
1068                         const char *dest = git_path("SQUASH_MSG");
1069                         unlink(dest);
1070                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
1071                                 return error(_("could not rename '%s' to '%s'"),
1072                                              rebase_path_squash_msg(), dest);
1073                         unlink(git_path("MERGE_MSG"));
1074                         msg_file = dest;
1075                         flags |= EDIT_MSG;
1076                 }
1077         }
1078
1079         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1080                 res = -1;
1081         else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1082                 res = do_recursive_merge(base, next, base_label, next_label,
1083                                          head, &msgbuf, opts);
1084                 if (res < 0)
1085                         return res;
1086                 res |= write_message(msgbuf.buf, msgbuf.len,
1087                                      git_path_merge_msg(), 0);
1088         } else {
1089                 struct commit_list *common = NULL;
1090                 struct commit_list *remotes = NULL;
1091
1092                 res = write_message(msgbuf.buf, msgbuf.len,
1093                                     git_path_merge_msg(), 0);
1094
1095                 commit_list_insert(base, &common);
1096                 commit_list_insert(next, &remotes);
1097                 res |= try_merge_command(opts->strategy,
1098                                          opts->xopts_nr, (const char **)opts->xopts,
1099                                         common, sha1_to_hex(head), remotes);
1100                 free_commit_list(common);
1101                 free_commit_list(remotes);
1102         }
1103         strbuf_release(&msgbuf);
1104
1105         /*
1106          * If the merge was clean or if it failed due to conflict, we write
1107          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1108          * However, if the merge did not even start, then we don't want to
1109          * write it at all.
1110          */
1111         if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1112             update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
1113                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1114                 res = -1;
1115         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1116             update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
1117                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1118                 res = -1;
1119
1120         if (res) {
1121                 error(command == TODO_REVERT
1122                       ? _("could not revert %s... %s")
1123                       : _("could not apply %s... %s"),
1124                       short_commit_name(commit), msg.subject);
1125                 print_advice(res == 1, opts);
1126                 rerere(opts->allow_rerere_auto);
1127                 goto leave;
1128         }
1129
1130         allow = allow_empty(opts, commit);
1131         if (allow < 0) {
1132                 res = allow;
1133                 goto leave;
1134         } else if (allow)
1135                 flags |= ALLOW_EMPTY;
1136         if (!opts->no_commit)
1137 fast_forward_edit:
1138                 res = run_git_commit(msg_file, opts, flags);
1139
1140         if (!res && final_fixup) {
1141                 unlink(rebase_path_fixup_msg());
1142                 unlink(rebase_path_squash_msg());
1143         }
1144
1145 leave:
1146         free_message(commit, &msg);
1147         update_abort_safety_file();
1148
1149         return res;
1150 }
1151
1152 static int prepare_revs(struct replay_opts *opts)
1153 {
1154         /*
1155          * picking (but not reverting) ranges (but not individual revisions)
1156          * should be done in reverse
1157          */
1158         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1159                 opts->revs->reverse ^= 1;
1160
1161         if (prepare_revision_walk(opts->revs))
1162                 return error(_("revision walk setup failed"));
1163
1164         if (!opts->revs->commits)
1165                 return error(_("empty commit set passed"));
1166         return 0;
1167 }
1168
1169 static int read_and_refresh_cache(struct replay_opts *opts)
1170 {
1171         static struct lock_file index_lock;
1172         int index_fd = hold_locked_index(&index_lock, 0);
1173         if (read_index_preload(&the_index, NULL) < 0) {
1174                 rollback_lock_file(&index_lock);
1175                 return error(_("git %s: failed to read the index"),
1176                         _(action_name(opts)));
1177         }
1178         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1179         if (the_index.cache_changed && index_fd >= 0) {
1180                 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1181                         rollback_lock_file(&index_lock);
1182                         return error(_("git %s: failed to refresh the index"),
1183                                 _(action_name(opts)));
1184                 }
1185         }
1186         rollback_lock_file(&index_lock);
1187         return 0;
1188 }
1189
1190 struct todo_item {
1191         enum todo_command command;
1192         struct commit *commit;
1193         const char *arg;
1194         int arg_len;
1195         size_t offset_in_buf;
1196 };
1197
1198 struct todo_list {
1199         struct strbuf buf;
1200         struct todo_item *items;
1201         int nr, alloc, current;
1202         int done_nr, total_nr;
1203 };
1204
1205 #define TODO_LIST_INIT { STRBUF_INIT }
1206
1207 static void todo_list_release(struct todo_list *todo_list)
1208 {
1209         strbuf_release(&todo_list->buf);
1210         free(todo_list->items);
1211         todo_list->items = NULL;
1212         todo_list->nr = todo_list->alloc = 0;
1213 }
1214
1215 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1216 {
1217         ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1218         return todo_list->items + todo_list->nr++;
1219 }
1220
1221 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1222 {
1223         unsigned char commit_sha1[20];
1224         char *end_of_object_name;
1225         int i, saved, status, padding;
1226
1227         /* left-trim */
1228         bol += strspn(bol, " \t");
1229
1230         if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1231                 item->command = TODO_COMMENT;
1232                 item->commit = NULL;
1233                 item->arg = bol;
1234                 item->arg_len = eol - bol;
1235                 return 0;
1236         }
1237
1238         for (i = 0; i < TODO_COMMENT; i++)
1239                 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1240                         item->command = i;
1241                         break;
1242                 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1243                         bol++;
1244                         item->command = i;
1245                         break;
1246                 }
1247         if (i >= TODO_COMMENT)
1248                 return -1;
1249
1250         if (item->command == TODO_NOOP) {
1251                 item->commit = NULL;
1252                 item->arg = bol;
1253                 item->arg_len = eol - bol;
1254                 return 0;
1255         }
1256
1257         /* Eat up extra spaces/ tabs before object name */
1258         padding = strspn(bol, " \t");
1259         if (!padding)
1260                 return -1;
1261         bol += padding;
1262
1263         if (item->command == TODO_EXEC) {
1264                 item->arg = bol;
1265                 item->arg_len = (int)(eol - bol);
1266                 return 0;
1267         }
1268
1269         end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1270         saved = *end_of_object_name;
1271         *end_of_object_name = '\0';
1272         status = get_sha1(bol, commit_sha1);
1273         *end_of_object_name = saved;
1274
1275         item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1276         item->arg_len = (int)(eol - item->arg);
1277
1278         if (status < 0)
1279                 return -1;
1280
1281         item->commit = lookup_commit_reference(commit_sha1);
1282         return !item->commit;
1283 }
1284
1285 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1286 {
1287         struct todo_item *item;
1288         char *p = buf, *next_p;
1289         int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1290
1291         for (i = 1; *p; i++, p = next_p) {
1292                 char *eol = strchrnul(p, '\n');
1293
1294                 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1295
1296                 if (p != eol && eol[-1] == '\r')
1297                         eol--; /* strip Carriage Return */
1298
1299                 item = append_new_todo(todo_list);
1300                 item->offset_in_buf = p - todo_list->buf.buf;
1301                 if (parse_insn_line(item, p, eol)) {
1302                         res = error(_("invalid line %d: %.*s"),
1303                                 i, (int)(eol - p), p);
1304                         item->command = TODO_NOOP;
1305                 }
1306
1307                 if (fixup_okay)
1308                         ; /* do nothing */
1309                 else if (is_fixup(item->command))
1310                         return error(_("cannot '%s' without a previous commit"),
1311                                 command_to_string(item->command));
1312                 else if (!is_noop(item->command))
1313                         fixup_okay = 1;
1314         }
1315
1316         return res;
1317 }
1318
1319 static int count_commands(struct todo_list *todo_list)
1320 {
1321         int count = 0, i;
1322
1323         for (i = 0; i < todo_list->nr; i++)
1324                 if (todo_list->items[i].command != TODO_COMMENT)
1325                         count++;
1326
1327         return count;
1328 }
1329
1330 static int read_populate_todo(struct todo_list *todo_list,
1331                         struct replay_opts *opts)
1332 {
1333         const char *todo_file = get_todo_path(opts);
1334         int fd, res;
1335
1336         strbuf_reset(&todo_list->buf);
1337         fd = open(todo_file, O_RDONLY);
1338         if (fd < 0)
1339                 return error_errno(_("could not open '%s'"), todo_file);
1340         if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1341                 close(fd);
1342                 return error(_("could not read '%s'."), todo_file);
1343         }
1344         close(fd);
1345
1346         res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1347         if (res) {
1348                 if (is_rebase_i(opts))
1349                         return error(_("please fix this using "
1350                                        "'git rebase --edit-todo'."));
1351                 return error(_("unusable instruction sheet: '%s'"), todo_file);
1352         }
1353
1354         if (!todo_list->nr &&
1355             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1356                 return error(_("no commits parsed."));
1357
1358         if (!is_rebase_i(opts)) {
1359                 enum todo_command valid =
1360                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1361                 int i;
1362
1363                 for (i = 0; i < todo_list->nr; i++)
1364                         if (valid == todo_list->items[i].command)
1365                                 continue;
1366                         else if (valid == TODO_PICK)
1367                                 return error(_("cannot cherry-pick during a revert."));
1368                         else
1369                                 return error(_("cannot revert during a cherry-pick."));
1370         }
1371
1372         if (is_rebase_i(opts)) {
1373                 struct todo_list done = TODO_LIST_INIT;
1374                 FILE *f = fopen(rebase_path_msgtotal(), "w");
1375
1376                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1377                                 !parse_insn_buffer(done.buf.buf, &done))
1378                         todo_list->done_nr = count_commands(&done);
1379                 else
1380                         todo_list->done_nr = 0;
1381
1382                 todo_list->total_nr = todo_list->done_nr
1383                         + count_commands(todo_list);
1384                 todo_list_release(&done);
1385
1386                 if (f) {
1387                         fprintf(f, "%d\n", todo_list->total_nr);
1388                         fclose(f);
1389                 }
1390         }
1391
1392         return 0;
1393 }
1394
1395 static int git_config_string_dup(char **dest,
1396                                  const char *var, const char *value)
1397 {
1398         if (!value)
1399                 return config_error_nonbool(var);
1400         free(*dest);
1401         *dest = xstrdup(value);
1402         return 0;
1403 }
1404
1405 static int populate_opts_cb(const char *key, const char *value, void *data)
1406 {
1407         struct replay_opts *opts = data;
1408         int error_flag = 1;
1409
1410         if (!value)
1411                 error_flag = 0;
1412         else if (!strcmp(key, "options.no-commit"))
1413                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1414         else if (!strcmp(key, "options.edit"))
1415                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1416         else if (!strcmp(key, "options.signoff"))
1417                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1418         else if (!strcmp(key, "options.record-origin"))
1419                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1420         else if (!strcmp(key, "options.allow-ff"))
1421                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1422         else if (!strcmp(key, "options.mainline"))
1423                 opts->mainline = git_config_int(key, value);
1424         else if (!strcmp(key, "options.strategy"))
1425                 git_config_string_dup(&opts->strategy, key, value);
1426         else if (!strcmp(key, "options.gpg-sign"))
1427                 git_config_string_dup(&opts->gpg_sign, key, value);
1428         else if (!strcmp(key, "options.strategy-option")) {
1429                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1430                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1431         } else
1432                 return error(_("invalid key: %s"), key);
1433
1434         if (!error_flag)
1435                 return error(_("invalid value for %s: %s"), key, value);
1436
1437         return 0;
1438 }
1439
1440 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1441 {
1442         int i;
1443
1444         strbuf_reset(buf);
1445         if (!read_oneliner(buf, rebase_path_strategy(), 0))
1446                 return;
1447         opts->strategy = strbuf_detach(buf, NULL);
1448         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1449                 return;
1450
1451         opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1452         for (i = 0; i < opts->xopts_nr; i++) {
1453                 const char *arg = opts->xopts[i];
1454
1455                 skip_prefix(arg, "--", &arg);
1456                 opts->xopts[i] = xstrdup(arg);
1457         }
1458 }
1459
1460 static int read_populate_opts(struct replay_opts *opts)
1461 {
1462         if (is_rebase_i(opts)) {
1463                 struct strbuf buf = STRBUF_INIT;
1464
1465                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1466                         if (!starts_with(buf.buf, "-S"))
1467                                 strbuf_reset(&buf);
1468                         else {
1469                                 free(opts->gpg_sign);
1470                                 opts->gpg_sign = xstrdup(buf.buf + 2);
1471                         }
1472                 }
1473
1474                 if (file_exists(rebase_path_verbose()))
1475                         opts->verbose = 1;
1476
1477                 read_strategy_opts(opts, &buf);
1478                 strbuf_release(&buf);
1479
1480                 return 0;
1481         }
1482
1483         if (!file_exists(git_path_opts_file()))
1484                 return 0;
1485         /*
1486          * The function git_parse_source(), called from git_config_from_file(),
1487          * may die() in case of a syntactically incorrect file. We do not care
1488          * about this case, though, because we wrote that file ourselves, so we
1489          * are pretty certain that it is syntactically correct.
1490          */
1491         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1492                 return error(_("malformed options sheet: '%s'"),
1493                         git_path_opts_file());
1494         return 0;
1495 }
1496
1497 static int walk_revs_populate_todo(struct todo_list *todo_list,
1498                                 struct replay_opts *opts)
1499 {
1500         enum todo_command command = opts->action == REPLAY_PICK ?
1501                 TODO_PICK : TODO_REVERT;
1502         const char *command_string = todo_command_info[command].str;
1503         struct commit *commit;
1504
1505         if (prepare_revs(opts))
1506                 return -1;
1507
1508         while ((commit = get_revision(opts->revs))) {
1509                 struct todo_item *item = append_new_todo(todo_list);
1510                 const char *commit_buffer = get_commit_buffer(commit, NULL);
1511                 const char *subject;
1512                 int subject_len;
1513
1514                 item->command = command;
1515                 item->commit = commit;
1516                 item->arg = NULL;
1517                 item->arg_len = 0;
1518                 item->offset_in_buf = todo_list->buf.len;
1519                 subject_len = find_commit_subject(commit_buffer, &subject);
1520                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1521                         short_commit_name(commit), subject_len, subject);
1522                 unuse_commit_buffer(commit, commit_buffer);
1523         }
1524         return 0;
1525 }
1526
1527 static int create_seq_dir(void)
1528 {
1529         if (file_exists(git_path_seq_dir())) {
1530                 error(_("a cherry-pick or revert is already in progress"));
1531                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1532                 return -1;
1533         } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1534                 return error_errno(_("could not create sequencer directory '%s'"),
1535                                    git_path_seq_dir());
1536         return 0;
1537 }
1538
1539 static int save_head(const char *head)
1540 {
1541         static struct lock_file head_lock;
1542         struct strbuf buf = STRBUF_INIT;
1543         int fd;
1544
1545         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1546         if (fd < 0) {
1547                 rollback_lock_file(&head_lock);
1548                 return error_errno(_("could not lock HEAD"));
1549         }
1550         strbuf_addf(&buf, "%s\n", head);
1551         if (write_in_full(fd, buf.buf, buf.len) < 0) {
1552                 rollback_lock_file(&head_lock);
1553                 return error_errno(_("could not write to '%s'"),
1554                                    git_path_head_file());
1555         }
1556         if (commit_lock_file(&head_lock) < 0) {
1557                 rollback_lock_file(&head_lock);
1558                 return error(_("failed to finalize '%s'."), git_path_head_file());
1559         }
1560         return 0;
1561 }
1562
1563 static int rollback_is_safe(void)
1564 {
1565         struct strbuf sb = STRBUF_INIT;
1566         struct object_id expected_head, actual_head;
1567
1568         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1569                 strbuf_trim(&sb);
1570                 if (get_oid_hex(sb.buf, &expected_head)) {
1571                         strbuf_release(&sb);
1572                         die(_("could not parse %s"), git_path_abort_safety_file());
1573                 }
1574                 strbuf_release(&sb);
1575         }
1576         else if (errno == ENOENT)
1577                 oidclr(&expected_head);
1578         else
1579                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1580
1581         if (get_oid("HEAD", &actual_head))
1582                 oidclr(&actual_head);
1583
1584         return !oidcmp(&actual_head, &expected_head);
1585 }
1586
1587 static int reset_for_rollback(const unsigned char *sha1)
1588 {
1589         const char *argv[4];    /* reset --merge <arg> + NULL */
1590
1591         argv[0] = "reset";
1592         argv[1] = "--merge";
1593         argv[2] = sha1_to_hex(sha1);
1594         argv[3] = NULL;
1595         return run_command_v_opt(argv, RUN_GIT_CMD);
1596 }
1597
1598 static int rollback_single_pick(void)
1599 {
1600         unsigned char head_sha1[20];
1601
1602         if (!file_exists(git_path_cherry_pick_head()) &&
1603             !file_exists(git_path_revert_head()))
1604                 return error(_("no cherry-pick or revert in progress"));
1605         if (read_ref_full("HEAD", 0, head_sha1, NULL))
1606                 return error(_("cannot resolve HEAD"));
1607         if (is_null_sha1(head_sha1))
1608                 return error(_("cannot abort from a branch yet to be born"));
1609         return reset_for_rollback(head_sha1);
1610 }
1611
1612 int sequencer_rollback(struct replay_opts *opts)
1613 {
1614         FILE *f;
1615         unsigned char sha1[20];
1616         struct strbuf buf = STRBUF_INIT;
1617
1618         f = fopen(git_path_head_file(), "r");
1619         if (!f && errno == ENOENT) {
1620                 /*
1621                  * There is no multiple-cherry-pick in progress.
1622                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1623                  * a single-cherry-pick in progress, abort that.
1624                  */
1625                 return rollback_single_pick();
1626         }
1627         if (!f)
1628                 return error_errno(_("cannot open '%s'"), git_path_head_file());
1629         if (strbuf_getline_lf(&buf, f)) {
1630                 error(_("cannot read '%s': %s"), git_path_head_file(),
1631                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1632                 fclose(f);
1633                 goto fail;
1634         }
1635         fclose(f);
1636         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1637                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1638                         git_path_head_file());
1639                 goto fail;
1640         }
1641         if (is_null_sha1(sha1)) {
1642                 error(_("cannot abort from a branch yet to be born"));
1643                 goto fail;
1644         }
1645
1646         if (!rollback_is_safe()) {
1647                 /* Do not error, just do not rollback */
1648                 warning(_("You seem to have moved HEAD. "
1649                           "Not rewinding, check your HEAD!"));
1650         } else
1651         if (reset_for_rollback(sha1))
1652                 goto fail;
1653         strbuf_release(&buf);
1654         return sequencer_remove_state(opts);
1655 fail:
1656         strbuf_release(&buf);
1657         return -1;
1658 }
1659
1660 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1661 {
1662         static struct lock_file todo_lock;
1663         const char *todo_path = get_todo_path(opts);
1664         int next = todo_list->current, offset, fd;
1665
1666         /*
1667          * rebase -i writes "git-rebase-todo" without the currently executing
1668          * command, appending it to "done" instead.
1669          */
1670         if (is_rebase_i(opts))
1671                 next++;
1672
1673         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1674         if (fd < 0)
1675                 return error_errno(_("could not lock '%s'"), todo_path);
1676         offset = next < todo_list->nr ?
1677                 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1678         if (write_in_full(fd, todo_list->buf.buf + offset,
1679                         todo_list->buf.len - offset) < 0)
1680                 return error_errno(_("could not write to '%s'"), todo_path);
1681         if (commit_lock_file(&todo_lock) < 0)
1682                 return error(_("failed to finalize '%s'."), todo_path);
1683
1684         if (is_rebase_i(opts)) {
1685                 const char *done_path = rebase_path_done();
1686                 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1687                 int prev_offset = !next ? 0 :
1688                         todo_list->items[next - 1].offset_in_buf;
1689
1690                 if (fd >= 0 && offset > prev_offset &&
1691                     write_in_full(fd, todo_list->buf.buf + prev_offset,
1692                                   offset - prev_offset) < 0) {
1693                         close(fd);
1694                         return error_errno(_("could not write to '%s'"),
1695                                            done_path);
1696                 }
1697                 if (fd >= 0)
1698                         close(fd);
1699         }
1700         return 0;
1701 }
1702
1703 static int save_opts(struct replay_opts *opts)
1704 {
1705         const char *opts_file = git_path_opts_file();
1706         int res = 0;
1707
1708         if (opts->no_commit)
1709                 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1710         if (opts->edit)
1711                 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1712         if (opts->signoff)
1713                 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1714         if (opts->record_origin)
1715                 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1716         if (opts->allow_ff)
1717                 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1718         if (opts->mainline) {
1719                 struct strbuf buf = STRBUF_INIT;
1720                 strbuf_addf(&buf, "%d", opts->mainline);
1721                 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1722                 strbuf_release(&buf);
1723         }
1724         if (opts->strategy)
1725                 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1726         if (opts->gpg_sign)
1727                 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1728         if (opts->xopts) {
1729                 int i;
1730                 for (i = 0; i < opts->xopts_nr; i++)
1731                         res |= git_config_set_multivar_in_file_gently(opts_file,
1732                                                         "options.strategy-option",
1733                                                         opts->xopts[i], "^$", 0);
1734         }
1735         return res;
1736 }
1737
1738 static int make_patch(struct commit *commit, struct replay_opts *opts)
1739 {
1740         struct strbuf buf = STRBUF_INIT;
1741         struct rev_info log_tree_opt;
1742         const char *subject, *p;
1743         int res = 0;
1744
1745         p = short_commit_name(commit);
1746         if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1747                 return -1;
1748
1749         strbuf_addf(&buf, "%s/patch", get_dir(opts));
1750         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1751         init_revisions(&log_tree_opt, NULL);
1752         log_tree_opt.abbrev = 0;
1753         log_tree_opt.diff = 1;
1754         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1755         log_tree_opt.disable_stdin = 1;
1756         log_tree_opt.no_commit_id = 1;
1757         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1758         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1759         if (!log_tree_opt.diffopt.file)
1760                 res |= error_errno(_("could not open '%s'"), buf.buf);
1761         else {
1762                 res |= log_tree_commit(&log_tree_opt, commit);
1763                 fclose(log_tree_opt.diffopt.file);
1764         }
1765         strbuf_reset(&buf);
1766
1767         strbuf_addf(&buf, "%s/message", get_dir(opts));
1768         if (!file_exists(buf.buf)) {
1769                 const char *commit_buffer = get_commit_buffer(commit, NULL);
1770                 find_commit_subject(commit_buffer, &subject);
1771                 res |= write_message(subject, strlen(subject), buf.buf, 1);
1772                 unuse_commit_buffer(commit, commit_buffer);
1773         }
1774         strbuf_release(&buf);
1775
1776         return res;
1777 }
1778
1779 static int intend_to_amend(void)
1780 {
1781         unsigned char head[20];
1782         char *p;
1783
1784         if (get_sha1("HEAD", head))
1785                 return error(_("cannot read HEAD"));
1786
1787         p = sha1_to_hex(head);
1788         return write_message(p, strlen(p), rebase_path_amend(), 1);
1789 }
1790
1791 static int error_with_patch(struct commit *commit,
1792         const char *subject, int subject_len,
1793         struct replay_opts *opts, int exit_code, int to_amend)
1794 {
1795         if (make_patch(commit, opts))
1796                 return -1;
1797
1798         if (to_amend) {
1799                 if (intend_to_amend())
1800                         return -1;
1801
1802                 fprintf(stderr, "You can amend the commit now, with\n"
1803                         "\n"
1804                         "  git commit --amend %s\n"
1805                         "\n"
1806                         "Once you are satisfied with your changes, run\n"
1807                         "\n"
1808                         "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
1809         } else if (exit_code)
1810                 fprintf(stderr, "Could not apply %s... %.*s\n",
1811                         short_commit_name(commit), subject_len, subject);
1812
1813         return exit_code;
1814 }
1815
1816 static int error_failed_squash(struct commit *commit,
1817         struct replay_opts *opts, int subject_len, const char *subject)
1818 {
1819         if (rename(rebase_path_squash_msg(), rebase_path_message()))
1820                 return error(_("could not rename '%s' to '%s'"),
1821                         rebase_path_squash_msg(), rebase_path_message());
1822         unlink(rebase_path_fixup_msg());
1823         unlink(git_path("MERGE_MSG"));
1824         if (copy_file(git_path("MERGE_MSG"), rebase_path_message(), 0666))
1825                 return error(_("could not copy '%s' to '%s'"),
1826                              rebase_path_message(), git_path("MERGE_MSG"));
1827         return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1828 }
1829
1830 static int do_exec(const char *command_line)
1831 {
1832         const char *child_argv[] = { NULL, NULL };
1833         int dirty, status;
1834
1835         fprintf(stderr, "Executing: %s\n", command_line);
1836         child_argv[0] = command_line;
1837         status = run_command_v_opt(child_argv, RUN_USING_SHELL);
1838
1839         /* force re-reading of the cache */
1840         if (discard_cache() < 0 || read_cache() < 0)
1841                 return error(_("could not read index"));
1842
1843         dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1844
1845         if (status) {
1846                 warning(_("execution failed: %s\n%s"
1847                           "You can fix the problem, and then run\n"
1848                           "\n"
1849                           "  git rebase --continue\n"
1850                           "\n"),
1851                         command_line,
1852                         dirty ? N_("and made changes to the index and/or the "
1853                                 "working tree\n") : "");
1854                 if (status == 127)
1855                         /* command not found */
1856                         status = 1;
1857         } else if (dirty) {
1858                 warning(_("execution succeeded: %s\nbut "
1859                           "left changes to the index and/or the working tree\n"
1860                           "Commit or stash your changes, and then run\n"
1861                           "\n"
1862                           "  git rebase --continue\n"
1863                           "\n"), command_line);
1864                 status = 1;
1865         }
1866
1867         return status;
1868 }
1869
1870 static int is_final_fixup(struct todo_list *todo_list)
1871 {
1872         int i = todo_list->current;
1873
1874         if (!is_fixup(todo_list->items[i].command))
1875                 return 0;
1876
1877         while (++i < todo_list->nr)
1878                 if (is_fixup(todo_list->items[i].command))
1879                         return 0;
1880                 else if (!is_noop(todo_list->items[i].command))
1881                         break;
1882         return 1;
1883 }
1884
1885 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
1886 {
1887         int i;
1888
1889         for (i = todo_list->current + offset; i < todo_list->nr; i++)
1890                 if (!is_noop(todo_list->items[i].command))
1891                         return todo_list->items[i].command;
1892
1893         return -1;
1894 }
1895
1896 static int apply_autostash(struct replay_opts *opts)
1897 {
1898         struct strbuf stash_sha1 = STRBUF_INIT;
1899         struct child_process child = CHILD_PROCESS_INIT;
1900         int ret = 0;
1901
1902         if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
1903                 strbuf_release(&stash_sha1);
1904                 return 0;
1905         }
1906         strbuf_trim(&stash_sha1);
1907
1908         child.git_cmd = 1;
1909         argv_array_push(&child.args, "stash");
1910         argv_array_push(&child.args, "apply");
1911         argv_array_push(&child.args, stash_sha1.buf);
1912         if (!run_command(&child))
1913                 printf(_("Applied autostash."));
1914         else {
1915                 struct child_process store = CHILD_PROCESS_INIT;
1916
1917                 store.git_cmd = 1;
1918                 argv_array_push(&store.args, "stash");
1919                 argv_array_push(&store.args, "store");
1920                 argv_array_push(&store.args, "-m");
1921                 argv_array_push(&store.args, "autostash");
1922                 argv_array_push(&store.args, "-q");
1923                 argv_array_push(&store.args, stash_sha1.buf);
1924                 if (run_command(&store))
1925                         ret = error(_("cannot store %s"), stash_sha1.buf);
1926                 else
1927                         printf(_("Applying autostash resulted in conflicts.\n"
1928                                 "Your changes are safe in the stash.\n"
1929                                 "You can run \"git stash pop\" or"
1930                                 " \"git stash drop\" at any time.\n"));
1931         }
1932
1933         strbuf_release(&stash_sha1);
1934         return ret;
1935 }
1936
1937 static const char *reflog_message(struct replay_opts *opts,
1938         const char *sub_action, const char *fmt, ...)
1939 {
1940         va_list ap;
1941         static struct strbuf buf = STRBUF_INIT;
1942
1943         va_start(ap, fmt);
1944         strbuf_reset(&buf);
1945         strbuf_addstr(&buf, action_name(opts));
1946         if (sub_action)
1947                 strbuf_addf(&buf, " (%s)", sub_action);
1948         if (fmt) {
1949                 strbuf_addstr(&buf, ": ");
1950                 strbuf_vaddf(&buf, fmt, ap);
1951         }
1952         va_end(ap);
1953
1954         return buf.buf;
1955 }
1956
1957 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1958 {
1959         int res = 0;
1960
1961         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1962         if (opts->allow_ff)
1963                 assert(!(opts->signoff || opts->no_commit ||
1964                                 opts->record_origin || opts->edit));
1965         if (read_and_refresh_cache(opts))
1966                 return -1;
1967
1968         while (todo_list->current < todo_list->nr) {
1969                 struct todo_item *item = todo_list->items + todo_list->current;
1970                 if (save_todo(todo_list, opts))
1971                         return -1;
1972                 if (is_rebase_i(opts)) {
1973                         if (item->command != TODO_COMMENT) {
1974                                 FILE *f = fopen(rebase_path_msgnum(), "w");
1975
1976                                 todo_list->done_nr++;
1977
1978                                 if (f) {
1979                                         fprintf(f, "%d\n", todo_list->done_nr);
1980                                         fclose(f);
1981                                 }
1982                                 fprintf(stderr, "Rebasing (%d/%d)%s",
1983                                         todo_list->done_nr,
1984                                         todo_list->total_nr,
1985                                         opts->verbose ? "\n" : "\r");
1986                         }
1987                         unlink(rebase_path_message());
1988                         unlink(rebase_path_author_script());
1989                         unlink(rebase_path_stopped_sha());
1990                         unlink(rebase_path_amend());
1991                 }
1992                 if (item->command <= TODO_SQUASH) {
1993                         if (is_rebase_i(opts))
1994                                 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
1995                                         command_to_string(item->command), NULL),
1996                                         1);
1997                         res = do_pick_commit(item->command, item->commit,
1998                                         opts, is_final_fixup(todo_list));
1999                         if (is_rebase_i(opts) && res < 0) {
2000                                 /* Reschedule */
2001                                 todo_list->current--;
2002                                 if (save_todo(todo_list, opts))
2003                                         return -1;
2004                         }
2005                         if (item->command == TODO_EDIT) {
2006                                 struct commit *commit = item->commit;
2007                                 if (!res)
2008                                         fprintf(stderr,
2009                                                 _("Stopped at %s...  %.*s\n"),
2010                                                 short_commit_name(commit),
2011                                                 item->arg_len, item->arg);
2012                                 return error_with_patch(commit,
2013                                         item->arg, item->arg_len, opts, res,
2014                                         !res);
2015                         }
2016                         if (is_rebase_i(opts) && !res)
2017                                 record_in_rewritten(&item->commit->object.oid,
2018                                         peek_command(todo_list, 1));
2019                         if (res && is_fixup(item->command)) {
2020                                 if (res == 1)
2021                                         intend_to_amend();
2022                                 return error_failed_squash(item->commit, opts,
2023                                         item->arg_len, item->arg);
2024                         } else if (res && is_rebase_i(opts))
2025                                 return res | error_with_patch(item->commit,
2026                                         item->arg, item->arg_len, opts, res,
2027                                         item->command == TODO_REWORD);
2028                 } else if (item->command == TODO_EXEC) {
2029                         char *end_of_arg = (char *)(item->arg + item->arg_len);
2030                         int saved = *end_of_arg;
2031
2032                         *end_of_arg = '\0';
2033                         res = do_exec(item->arg);
2034                         *end_of_arg = saved;
2035                 } else if (!is_noop(item->command))
2036                         return error(_("unknown command %d"), item->command);
2037
2038                 todo_list->current++;
2039                 if (res)
2040                         return res;
2041         }
2042
2043         if (is_rebase_i(opts)) {
2044                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2045                 struct stat st;
2046
2047                 /* Stopped in the middle, as planned? */
2048                 if (todo_list->current < todo_list->nr)
2049                         return 0;
2050
2051                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2052                                 starts_with(head_ref.buf, "refs/")) {
2053                         const char *msg;
2054                         unsigned char head[20], orig[20];
2055                         int res;
2056
2057                         if (get_sha1("HEAD", head)) {
2058                                 res = error(_("cannot read HEAD"));
2059 cleanup_head_ref:
2060                                 strbuf_release(&head_ref);
2061                                 strbuf_release(&buf);
2062                                 return res;
2063                         }
2064                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2065                                         get_sha1_hex(buf.buf, orig)) {
2066                                 res = error(_("could not read orig-head"));
2067                                 goto cleanup_head_ref;
2068                         }
2069                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2070                                 res = error(_("could not read 'onto'"));
2071                                 goto cleanup_head_ref;
2072                         }
2073                         msg = reflog_message(opts, "finish", "%s onto %s",
2074                                 head_ref.buf, buf.buf);
2075                         if (update_ref(msg, head_ref.buf, head, orig,
2076                                         REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2077                                 res = error(_("could not update %s"),
2078                                         head_ref.buf);
2079                                 goto cleanup_head_ref;
2080                         }
2081                         msg = reflog_message(opts, "finish", "returning to %s",
2082                                 head_ref.buf);
2083                         if (create_symref("HEAD", head_ref.buf, msg)) {
2084                                 res = error(_("could not update HEAD to %s"),
2085                                         head_ref.buf);
2086                                 goto cleanup_head_ref;
2087                         }
2088                         strbuf_reset(&buf);
2089                 }
2090
2091                 if (opts->verbose) {
2092                         struct rev_info log_tree_opt;
2093                         struct object_id orig, head;
2094
2095                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2096                         init_revisions(&log_tree_opt, NULL);
2097                         log_tree_opt.diff = 1;
2098                         log_tree_opt.diffopt.output_format =
2099                                 DIFF_FORMAT_DIFFSTAT;
2100                         log_tree_opt.disable_stdin = 1;
2101
2102                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2103                             !get_sha1(buf.buf, orig.hash) &&
2104                             !get_sha1("HEAD", head.hash)) {
2105                                 diff_tree_sha1(orig.hash, head.hash,
2106                                                "", &log_tree_opt.diffopt);
2107                                 log_tree_diff_flush(&log_tree_opt);
2108                         }
2109                 }
2110                 flush_rewritten_pending();
2111                 if (!stat(rebase_path_rewritten_list(), &st) &&
2112                                 st.st_size > 0) {
2113                         struct child_process child = CHILD_PROCESS_INIT;
2114                         const char *post_rewrite_hook =
2115                                 find_hook("post-rewrite");
2116
2117                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2118                         child.git_cmd = 1;
2119                         argv_array_push(&child.args, "notes");
2120                         argv_array_push(&child.args, "copy");
2121                         argv_array_push(&child.args, "--for-rewrite=rebase");
2122                         /* we don't care if this copying failed */
2123                         run_command(&child);
2124
2125                         if (post_rewrite_hook) {
2126                                 struct child_process hook = CHILD_PROCESS_INIT;
2127
2128                                 hook.in = open(rebase_path_rewritten_list(),
2129                                         O_RDONLY);
2130                                 hook.stdout_to_stderr = 1;
2131                                 argv_array_push(&hook.args, post_rewrite_hook);
2132                                 argv_array_push(&hook.args, "rebase");
2133                                 /* we don't care if this hook failed */
2134                                 run_command(&hook);
2135                         }
2136                 }
2137                 apply_autostash(opts);
2138
2139                 fprintf(stderr, "Successfully rebased and updated %s.\n",
2140                         head_ref.buf);
2141
2142                 strbuf_release(&buf);
2143                 strbuf_release(&head_ref);
2144         }
2145
2146         /*
2147          * Sequence of picks finished successfully; cleanup by
2148          * removing the .git/sequencer directory
2149          */
2150         return sequencer_remove_state(opts);
2151 }
2152
2153 static int continue_single_pick(void)
2154 {
2155         const char *argv[] = { "commit", NULL };
2156
2157         if (!file_exists(git_path_cherry_pick_head()) &&
2158             !file_exists(git_path_revert_head()))
2159                 return error(_("no cherry-pick or revert in progress"));
2160         return run_command_v_opt(argv, RUN_GIT_CMD);
2161 }
2162
2163 static int commit_staged_changes(struct replay_opts *opts)
2164 {
2165         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2166
2167         if (has_unstaged_changes(1))
2168                 return error(_("cannot rebase: You have unstaged changes."));
2169         if (!has_uncommitted_changes(0)) {
2170                 const char *cherry_pick_head = git_path("CHERRY_PICK_HEAD");
2171
2172                 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2173                         return error(_("could not remove CHERRY_PICK_HEAD"));
2174                 return 0;
2175         }
2176
2177         if (file_exists(rebase_path_amend())) {
2178                 struct strbuf rev = STRBUF_INIT;
2179                 unsigned char head[20], to_amend[20];
2180
2181                 if (get_sha1("HEAD", head))
2182                         return error(_("cannot amend non-existing commit"));
2183                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2184                         return error(_("invalid file: '%s'"), rebase_path_amend());
2185                 if (get_sha1_hex(rev.buf, to_amend))
2186                         return error(_("invalid contents: '%s'"),
2187                                 rebase_path_amend());
2188                 if (hashcmp(head, to_amend))
2189                         return error(_("\nYou have uncommitted changes in your "
2190                                        "working tree. Please, commit them\n"
2191                                        "first and then run 'git rebase "
2192                                        "--continue' again."));
2193
2194                 strbuf_release(&rev);
2195                 flags |= AMEND_MSG;
2196         }
2197
2198         if (run_git_commit(rebase_path_message(), opts, flags))
2199                 return error(_("could not commit staged changes."));
2200         unlink(rebase_path_amend());
2201         return 0;
2202 }
2203
2204 int sequencer_continue(struct replay_opts *opts)
2205 {
2206         struct todo_list todo_list = TODO_LIST_INIT;
2207         int res;
2208
2209         if (read_and_refresh_cache(opts))
2210                 return -1;
2211
2212         if (is_rebase_i(opts)) {
2213                 if (commit_staged_changes(opts))
2214                         return -1;
2215         } else if (!file_exists(get_todo_path(opts)))
2216                 return continue_single_pick();
2217         if (read_populate_opts(opts))
2218                 return -1;
2219         if ((res = read_populate_todo(&todo_list, opts)))
2220                 goto release_todo_list;
2221
2222         if (!is_rebase_i(opts)) {
2223                 /* Verify that the conflict has been resolved */
2224                 if (file_exists(git_path_cherry_pick_head()) ||
2225                     file_exists(git_path_revert_head())) {
2226                         res = continue_single_pick();
2227                         if (res)
2228                                 goto release_todo_list;
2229                 }
2230                 if (index_differs_from("HEAD", 0, 0)) {
2231                         res = error_dirty_index(opts);
2232                         goto release_todo_list;
2233                 }
2234                 todo_list.current++;
2235         } else if (file_exists(rebase_path_stopped_sha())) {
2236                 struct strbuf buf = STRBUF_INIT;
2237                 struct object_id oid;
2238
2239                 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2240                     !get_sha1_committish(buf.buf, oid.hash))
2241                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
2242                 strbuf_release(&buf);
2243         }
2244
2245         res = pick_commits(&todo_list, opts);
2246 release_todo_list:
2247         todo_list_release(&todo_list);
2248         return res;
2249 }
2250
2251 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2252 {
2253         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2254         return do_pick_commit(opts->action == REPLAY_PICK ?
2255                 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2256 }
2257
2258 int sequencer_pick_revisions(struct replay_opts *opts)
2259 {
2260         struct todo_list todo_list = TODO_LIST_INIT;
2261         unsigned char sha1[20];
2262         int i, res;
2263
2264         assert(opts->revs);
2265         if (read_and_refresh_cache(opts))
2266                 return -1;
2267
2268         for (i = 0; i < opts->revs->pending.nr; i++) {
2269                 unsigned char sha1[20];
2270                 const char *name = opts->revs->pending.objects[i].name;
2271
2272                 /* This happens when using --stdin. */
2273                 if (!strlen(name))
2274                         continue;
2275
2276                 if (!get_sha1(name, sha1)) {
2277                         if (!lookup_commit_reference_gently(sha1, 1)) {
2278                                 enum object_type type = sha1_object_info(sha1, NULL);
2279                                 return error(_("%s: can't cherry-pick a %s"),
2280                                         name, typename(type));
2281                         }
2282                 } else
2283                         return error(_("%s: bad revision"), name);
2284         }
2285
2286         /*
2287          * If we were called as "git cherry-pick <commit>", just
2288          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2289          * REVERT_HEAD, and don't touch the sequencer state.
2290          * This means it is possible to cherry-pick in the middle
2291          * of a cherry-pick sequence.
2292          */
2293         if (opts->revs->cmdline.nr == 1 &&
2294             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2295             opts->revs->no_walk &&
2296             !opts->revs->cmdline.rev->flags) {
2297                 struct commit *cmit;
2298                 if (prepare_revision_walk(opts->revs))
2299                         return error(_("revision walk setup failed"));
2300                 cmit = get_revision(opts->revs);
2301                 if (!cmit || get_revision(opts->revs))
2302                         return error("BUG: expected exactly one commit from walk");
2303                 return single_pick(cmit, opts);
2304         }
2305
2306         /*
2307          * Start a new cherry-pick/ revert sequence; but
2308          * first, make sure that an existing one isn't in
2309          * progress
2310          */
2311
2312         if (walk_revs_populate_todo(&todo_list, opts) ||
2313                         create_seq_dir() < 0)
2314                 return -1;
2315         if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
2316                 return error(_("can't revert as initial commit"));
2317         if (save_head(sha1_to_hex(sha1)))
2318                 return -1;
2319         if (save_opts(opts))
2320                 return -1;
2321         update_abort_safety_file();
2322         res = pick_commits(&todo_list, opts);
2323         todo_list_release(&todo_list);
2324         return res;
2325 }
2326
2327 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2328 {
2329         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2330         struct strbuf sob = STRBUF_INIT;
2331         int has_footer;
2332
2333         strbuf_addstr(&sob, sign_off_header);
2334         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2335                                 getenv("GIT_COMMITTER_EMAIL")));
2336         strbuf_addch(&sob, '\n');
2337
2338         /*
2339          * If the whole message buffer is equal to the sob, pretend that we
2340          * found a conforming footer with a matching sob
2341          */
2342         if (msgbuf->len - ignore_footer == sob.len &&
2343             !strncmp(msgbuf->buf, sob.buf, sob.len))
2344                 has_footer = 3;
2345         else
2346                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2347
2348         if (!has_footer) {
2349                 const char *append_newlines = NULL;
2350                 size_t len = msgbuf->len - ignore_footer;
2351
2352                 if (!len) {
2353                         /*
2354                          * The buffer is completely empty.  Leave foom for
2355                          * the title and body to be filled in by the user.
2356                          */
2357                         append_newlines = "\n\n";
2358                 } else if (msgbuf->buf[len - 1] != '\n') {
2359                         /*
2360                          * Incomplete line.  Complete the line and add a
2361                          * blank one so that there is an empty line between
2362                          * the message body and the sob.
2363                          */
2364                         append_newlines = "\n\n";
2365                 } else if (len == 1) {
2366                         /*
2367                          * Buffer contains a single newline.  Add another
2368                          * so that we leave room for the title and body.
2369                          */
2370                         append_newlines = "\n";
2371                 } else if (msgbuf->buf[len - 2] != '\n') {
2372                         /*
2373                          * Buffer ends with a single newline.  Add another
2374                          * so that there is an empty line between the message
2375                          * body and the sob.
2376                          */
2377                         append_newlines = "\n";
2378                 } /* else, the buffer already ends with two newlines. */
2379
2380                 if (append_newlines)
2381                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2382                                 append_newlines, strlen(append_newlines));
2383         }
2384
2385         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2386                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2387                                 sob.buf, sob.len);
2388
2389         strbuf_release(&sob);
2390 }