Merge tag 'v2.3.0'
[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 "rewrite.h"
19
20 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
21
22 const char sign_off_header[] = "Signed-off-by: ";
23 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
24 static struct rewritten rewritten;
25
26 static void finish(struct replay_opts *opts)
27 {
28         const char *name;
29         struct strbuf msg = STRBUF_INIT;
30
31         if (opts->action != REPLAY_PICK)
32                 return;
33
34         name = opts->action_name ? opts->action_name : "cherry-pick";
35
36         if (!*name)
37                 return;
38
39         strbuf_addf(&msg, "Notes added by 'git %s'", name);
40         copy_rewrite_notes(&rewritten, name, msg.buf);
41         run_rewrite_hook(&rewritten, name);
42         strbuf_release(&msg);
43 }
44
45 static int is_rfc2822_line(const char *buf, int len)
46 {
47         int i;
48
49         for (i = 0; i < len; i++) {
50                 int ch = buf[i];
51                 if (ch == ':')
52                         return 1;
53                 if (!isalnum(ch) && ch != '-')
54                         break;
55         }
56
57         return 0;
58 }
59
60 static int is_cherry_picked_from_line(const char *buf, int len)
61 {
62         /*
63          * We only care that it looks roughly like (cherry picked from ...)
64          */
65         return len > strlen(cherry_picked_prefix) + 1 &&
66                 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
67 }
68
69 /*
70  * Returns 0 for non-conforming footer
71  * Returns 1 for conforming footer
72  * Returns 2 when sob exists within conforming footer
73  * Returns 3 when sob exists within conforming footer as last entry
74  */
75 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
76         int ignore_footer)
77 {
78         char prev;
79         int i, k;
80         int len = sb->len - ignore_footer;
81         const char *buf = sb->buf;
82         int found_sob = 0;
83
84         /* footer must end with newline */
85         if (!len || buf[len - 1] != '\n')
86                 return 0;
87
88         prev = '\0';
89         for (i = len - 1; i > 0; i--) {
90                 char ch = buf[i];
91                 if (prev == '\n' && ch == '\n') /* paragraph break */
92                         break;
93                 prev = ch;
94         }
95
96         /* require at least one blank line */
97         if (prev != '\n' || buf[i] != '\n')
98                 return 0;
99
100         /* advance to start of last paragraph */
101         while (i < len - 1 && buf[i] == '\n')
102                 i++;
103
104         for (; i < len; i = k) {
105                 int found_rfc2822;
106
107                 for (k = i; k < len && buf[k] != '\n'; k++)
108                         ; /* do nothing */
109                 k++;
110
111                 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
112                 if (found_rfc2822 && sob &&
113                     !strncmp(buf + i, sob->buf, sob->len))
114                         found_sob = k;
115
116                 if (!(found_rfc2822 ||
117                       is_cherry_picked_from_line(buf + i, k - i - 1)))
118                         return 0;
119         }
120         if (found_sob == i)
121                 return 3;
122         if (found_sob)
123                 return 2;
124         return 1;
125 }
126
127 static void remove_sequencer_state(void)
128 {
129         struct strbuf seq_dir = STRBUF_INIT;
130
131         strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
132         remove_dir_recursively(&seq_dir, 0);
133         strbuf_release(&seq_dir);
134 }
135
136 static const char *action_name(const struct replay_opts *opts)
137 {
138         return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
139 }
140
141 struct commit_message {
142         char *parent_label;
143         const char *label;
144         const char *subject;
145         const char *message;
146 };
147
148 static int get_message(struct commit *commit, struct commit_message *out)
149 {
150         const char *abbrev, *subject;
151         int abbrev_len, subject_len;
152         char *q;
153
154         if (!git_commit_encoding)
155                 git_commit_encoding = "UTF-8";
156
157         out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
158         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
159         abbrev_len = strlen(abbrev);
160
161         subject_len = find_commit_subject(out->message, &subject);
162
163         out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
164                               strlen("... ") + subject_len + 1);
165         q = out->parent_label;
166         q = mempcpy(q, "parent of ", strlen("parent of "));
167         out->label = q;
168         q = mempcpy(q, abbrev, abbrev_len);
169         q = mempcpy(q, "... ", strlen("... "));
170         out->subject = q;
171         q = mempcpy(q, subject, subject_len);
172         *q = '\0';
173         return 0;
174 }
175
176 static void free_message(struct commit *commit, struct commit_message *msg)
177 {
178         free(msg->parent_label);
179         unuse_commit_buffer(commit, msg->message);
180 }
181
182 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
183 {
184         const char *filename;
185         int fd;
186         struct strbuf buf = STRBUF_INIT;
187
188         strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
189
190         filename = git_path("%s", pseudoref);
191         fd = open(filename, O_WRONLY | O_CREAT, 0666);
192         if (fd < 0)
193                 die_errno(_("Could not open '%s' for writing"), filename);
194         if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
195                 die_errno(_("Could not write to '%s'"), filename);
196         strbuf_release(&buf);
197 }
198
199 static void print_advice(int show_hint, struct replay_opts *opts)
200 {
201         char *msg = getenv("GIT_CHERRY_PICK_HELP");
202
203         if (msg) {
204                 fprintf(stderr, "%s\n", msg);
205                 /*
206                  * A conflict has occurred but the porcelain
207                  * (typically rebase --interactive) wants to take care
208                  * of the commit itself so remove CHERRY_PICK_HEAD
209                  */
210                 unlink(git_path("CHERRY_PICK_HEAD"));
211                 return;
212         }
213
214         if (show_hint) {
215                 if (opts->no_commit)
216                         advise(_("after resolving the conflicts, mark the corrected paths\n"
217                                  "with 'git add <paths>' or 'git rm <paths>'"));
218                 else
219                         advise(_("after resolving the conflicts, mark the corrected paths\n"
220                                  "with 'git add <paths>' or 'git rm <paths>'\n"
221                                  "and commit the result with 'git commit'"));
222         }
223 }
224
225 static void write_message(struct strbuf *msgbuf, const char *filename)
226 {
227         static struct lock_file msg_file;
228
229         int msg_fd = hold_lock_file_for_update(&msg_file, filename,
230                                                LOCK_DIE_ON_ERROR);
231         if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
232                 die_errno(_("Could not write to %s"), filename);
233         strbuf_release(msgbuf);
234         if (commit_lock_file(&msg_file) < 0)
235                 die(_("Error wrapping up %s"), filename);
236 }
237
238 static struct tree *empty_tree(void)
239 {
240         return lookup_tree(EMPTY_TREE_SHA1_BIN);
241 }
242
243 static int error_dirty_index(struct replay_opts *opts)
244 {
245         if (read_cache_unmerged())
246                 return error_resolve_conflict(action_name(opts));
247
248         /* Different translation strings for cherry-pick and revert */
249         if (opts->action == REPLAY_PICK)
250                 error(_("Your local changes would be overwritten by cherry-pick."));
251         else
252                 error(_("Your local changes would be overwritten by revert."));
253
254         if (advice_commit_before_merge)
255                 advise(_("Commit your changes or stash them to proceed."));
256         return -1;
257 }
258
259 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
260                         int unborn, struct replay_opts *opts)
261 {
262         struct ref_transaction *transaction;
263         struct strbuf sb = STRBUF_INIT;
264         struct strbuf err = STRBUF_INIT;
265
266         read_cache();
267         if (checkout_fast_forward(from, to, 1))
268                 exit(128); /* the callee should have complained already */
269
270         strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
271
272         transaction = ref_transaction_begin(&err);
273         if (!transaction ||
274             ref_transaction_update(transaction, "HEAD",
275                                    to, unborn ? null_sha1 : from,
276                                    0, 1, sb.buf, &err) ||
277             ref_transaction_commit(transaction, &err)) {
278                 ref_transaction_free(transaction);
279                 error("%s", err.buf);
280                 strbuf_release(&sb);
281                 strbuf_release(&err);
282                 return -1;
283         }
284
285         strbuf_release(&sb);
286         strbuf_release(&err);
287         ref_transaction_free(transaction);
288         return 0;
289 }
290
291 void append_conflicts_hint(struct strbuf *msgbuf)
292 {
293         int i;
294
295         strbuf_addch(msgbuf, '\n');
296         strbuf_commented_addf(msgbuf, "Conflicts:\n");
297         for (i = 0; i < active_nr;) {
298                 const struct cache_entry *ce = active_cache[i++];
299                 if (ce_stage(ce)) {
300                         strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
301                         while (i < active_nr && !strcmp(ce->name,
302                                                         active_cache[i]->name))
303                                 i++;
304                 }
305         }
306 }
307
308 static int do_recursive_merge(struct commit *base, struct commit *next,
309                               const char *base_label, const char *next_label,
310                               unsigned char *head, struct strbuf *msgbuf,
311                               struct replay_opts *opts)
312 {
313         struct merge_options o;
314         struct tree *result, *next_tree, *base_tree, *head_tree;
315         int clean;
316         const char **xopt;
317         static struct lock_file index_lock;
318
319         hold_locked_index(&index_lock, 1);
320
321         read_cache();
322
323         init_merge_options(&o);
324         o.ancestor = base ? base_label : "(empty tree)";
325         o.branch1 = "HEAD";
326         o.branch2 = next ? next_label : "(empty tree)";
327
328         head_tree = parse_tree_indirect(head);
329         next_tree = next ? next->tree : empty_tree();
330         base_tree = base ? base->tree : empty_tree();
331
332         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
333                 parse_merge_opt(&o, *xopt);
334
335         clean = merge_trees(&o,
336                             head_tree,
337                             next_tree, base_tree, &result);
338
339         if (active_cache_changed &&
340             write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
341                 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
342                 die(_("%s: Unable to write new index file"), action_name(opts));
343         rollback_lock_file(&index_lock);
344
345         if (opts->signoff)
346                 append_signoff(msgbuf, 0, 0);
347
348         if (!clean)
349                 append_conflicts_hint(msgbuf);
350
351         return !clean;
352 }
353
354 static int is_index_unchanged(void)
355 {
356         unsigned char head_sha1[20];
357         struct commit *head_commit;
358
359         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
360                 return error(_("Could not resolve HEAD commit\n"));
361
362         head_commit = lookup_commit(head_sha1);
363
364         /*
365          * If head_commit is NULL, check_commit, called from
366          * lookup_commit, would have indicated that head_commit is not
367          * a commit object already.  parse_commit() will return failure
368          * without further complaints in such a case.  Otherwise, if
369          * the commit is invalid, parse_commit() will complain.  So
370          * there is nothing for us to say here.  Just return failure.
371          */
372         if (parse_commit(head_commit))
373                 return -1;
374
375         if (!active_cache_tree)
376                 active_cache_tree = cache_tree();
377
378         if (!cache_tree_fully_valid(active_cache_tree))
379                 if (cache_tree_update(&the_index, 0))
380                         return error(_("Unable to update cache tree\n"));
381
382         return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
383 }
384
385 /*
386  * If we are cherry-pick, and if the merge did not result in
387  * hand-editing, we will hit this commit and inherit the original
388  * author date and name.
389  * If we are revert, or if our cherry-pick results in a hand merge,
390  * we had better say that the current user is responsible for that.
391  */
392 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
393                           int allow_empty)
394 {
395         struct argv_array array;
396         int rc;
397
398         argv_array_init(&array);
399         argv_array_push(&array, "commit");
400         argv_array_push(&array, "-n");
401         if (opts->quiet)
402                 argv_array_push(&array, "-q");
403
404         if (opts->gpg_sign)
405                 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
406         if (opts->signoff)
407                 argv_array_push(&array, "-s");
408         if (!opts->edit) {
409                 argv_array_push(&array, "-F");
410                 argv_array_push(&array, defmsg);
411         }
412
413         if (allow_empty)
414                 argv_array_push(&array, "--allow-empty");
415
416         if (opts->allow_empty_message)
417                 argv_array_push(&array, "--allow-empty-message");
418
419         rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
420         argv_array_clear(&array);
421         return rc;
422 }
423
424 static int is_original_commit_empty(struct commit *commit)
425 {
426         const unsigned char *ptree_sha1;
427
428         if (parse_commit(commit))
429                 return error(_("Could not parse commit %s\n"),
430                              sha1_to_hex(commit->object.sha1));
431         if (commit->parents) {
432                 struct commit *parent = commit->parents->item;
433                 if (parse_commit(parent))
434                         return error(_("Could not parse parent commit %s\n"),
435                                 sha1_to_hex(parent->object.sha1));
436                 ptree_sha1 = parent->tree->object.sha1;
437         } else {
438                 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
439         }
440
441         return !hashcmp(ptree_sha1, commit->tree->object.sha1);
442 }
443
444 /*
445  * Do we run "git commit" with "--allow-empty"?
446  */
447 static int allow_empty(struct replay_opts *opts, struct commit *commit)
448 {
449         int index_unchanged, empty_commit;
450
451         /*
452          * Three cases:
453          *
454          * (1) we do not allow empty at all and error out.
455          *
456          * (2) we allow ones that were initially empty, but
457          * forbid the ones that become empty;
458          *
459          * (3) we allow both.
460          */
461         if (!opts->allow_empty)
462                 return 0; /* let "git commit" barf as necessary */
463
464         index_unchanged = is_index_unchanged();
465         if (index_unchanged < 0)
466                 return index_unchanged;
467         if (!index_unchanged)
468                 return 0; /* we do not have to say --allow-empty */
469
470         if (opts->keep_redundant_commits)
471                 return 1;
472
473         empty_commit = is_original_commit_empty(commit);
474         if (empty_commit < 0)
475                 return empty_commit;
476         if (!empty_commit)
477                 return 0;
478         else
479                 return 1;
480 }
481
482 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
483 {
484         unsigned char head[20];
485         struct commit *base, *next, *parent;
486         const char *base_label, *next_label;
487         struct commit_message msg = { NULL, NULL, NULL, NULL };
488         char *defmsg = NULL;
489         struct strbuf msgbuf = STRBUF_INIT;
490         int res, unborn = 0, allow;
491
492         if (opts->no_commit) {
493                 /*
494                  * We do not intend to commit immediately.  We just want to
495                  * merge the differences in, so let's compute the tree
496                  * that represents the "current" state for merge-recursive
497                  * to work on.
498                  */
499                 if (write_cache_as_tree(head, 0, NULL))
500                         die (_("Your index file is unmerged."));
501         } else {
502                 unborn = get_sha1("HEAD", head);
503                 if (unborn)
504                         hashcpy(head, EMPTY_TREE_SHA1_BIN);
505                 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
506                         return error_dirty_index(opts);
507         }
508         discard_cache();
509
510         if (!commit->parents) {
511                 parent = NULL;
512         }
513         else if (commit->parents->next) {
514                 /* Reverting or cherry-picking a merge commit */
515                 int cnt;
516                 struct commit_list *p;
517
518                 if (!opts->mainline)
519                         return error(_("Commit %s is a merge but no -m option was given."),
520                                 sha1_to_hex(commit->object.sha1));
521
522                 for (cnt = 1, p = commit->parents;
523                      cnt != opts->mainline && p;
524                      cnt++)
525                         p = p->next;
526                 if (cnt != opts->mainline || !p)
527                         return error(_("Commit %s does not have parent %d"),
528                                 sha1_to_hex(commit->object.sha1), opts->mainline);
529                 parent = p->item;
530         } else if (0 < opts->mainline)
531                 return error(_("Mainline was specified but commit %s is not a merge."),
532                         sha1_to_hex(commit->object.sha1));
533         else
534                 parent = commit->parents->item;
535
536         if (opts->allow_ff &&
537             ((parent && !hashcmp(parent->object.sha1, head)) ||
538              (!parent && unborn)))
539                 return fast_forward_to(commit->object.sha1, head, unborn, opts);
540
541         if (parent && parse_commit(parent) < 0)
542                 /* TRANSLATORS: The first %s will be "revert" or
543                    "cherry-pick", the second %s a SHA1 */
544                 return error(_("%s: cannot parse parent commit %s"),
545                         action_name(opts), sha1_to_hex(parent->object.sha1));
546
547         if (get_message(commit, &msg) != 0)
548                 return error(_("Cannot get commit message for %s"),
549                         sha1_to_hex(commit->object.sha1));
550
551         /*
552          * "commit" is an existing commit.  We would want to apply
553          * the difference it introduces since its first parent "prev"
554          * on top of the current HEAD if we are cherry-pick.  Or the
555          * reverse of it if we are revert.
556          */
557
558         defmsg = git_pathdup("MERGE_MSG");
559
560         if (opts->action == REPLAY_REVERT) {
561                 base = commit;
562                 base_label = msg.label;
563                 next = parent;
564                 next_label = msg.parent_label;
565                 strbuf_addstr(&msgbuf, "Revert \"");
566                 strbuf_addstr(&msgbuf, msg.subject);
567                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
568                 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
569
570                 if (commit->parents && commit->parents->next) {
571                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
572                         strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
573                 }
574                 strbuf_addstr(&msgbuf, ".\n");
575         } else {
576                 const char *p;
577
578                 base = parent;
579                 base_label = msg.parent_label;
580                 next = commit;
581                 next_label = msg.label;
582
583                 /*
584                  * Append the commit log message to msgbuf; it starts
585                  * after the tree, parent, author, committer
586                  * information followed by "\n\n".
587                  */
588                 p = strstr(msg.message, "\n\n");
589                 if (p) {
590                         p += 2;
591                         strbuf_addstr(&msgbuf, p);
592                 }
593
594                 if (opts->record_origin) {
595                         if (!has_conforming_footer(&msgbuf, NULL, 0))
596                                 strbuf_addch(&msgbuf, '\n');
597                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
598                         strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
599                         strbuf_addstr(&msgbuf, ")\n");
600                 }
601         }
602
603         if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
604                 res = do_recursive_merge(base, next, base_label, next_label,
605                                          head, &msgbuf, opts);
606                 write_message(&msgbuf, defmsg);
607         } else {
608                 struct commit_list *common = NULL;
609                 struct commit_list *remotes = NULL;
610
611                 write_message(&msgbuf, defmsg);
612
613                 commit_list_insert(base, &common);
614                 commit_list_insert(next, &remotes);
615                 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
616                                         common, sha1_to_hex(head), remotes);
617                 free_commit_list(common);
618                 free_commit_list(remotes);
619         }
620
621         /*
622          * If the merge was clean or if it failed due to conflict, we write
623          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
624          * However, if the merge did not even start, then we don't want to
625          * write it at all.
626          */
627         if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
628                 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
629         if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
630                 write_cherry_pick_head(commit, "REVERT_HEAD");
631
632         if (res) {
633                 error(opts->action == REPLAY_REVERT
634                       ? _("could not revert %s... %s")
635                       : _("could not apply %s... %s"),
636                       find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
637                       msg.subject);
638                 print_advice(res == 1, opts);
639                 rerere(opts->allow_rerere_auto);
640                 goto leave;
641         }
642
643         if (opts->skip_empty && is_index_unchanged() == 1) {
644                 if (!opts->quiet)
645                         warning(_("skipping %s... %s"),
646                                 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
647                                 msg.subject);
648                 goto leave;
649         }
650         allow = allow_empty(opts, commit);
651         if (allow < 0) {
652                 res = allow;
653                 goto leave;
654         }
655         if (!opts->no_commit)
656                 res = run_git_commit(defmsg, opts, allow);
657
658         if (!res && opts->action == REPLAY_PICK) {
659                 unsigned char to[20];
660
661                 if (read_ref("HEAD", to))
662                         goto leave;
663
664                 add_rewritten(&rewritten, commit->object.sha1, to);
665         }
666 leave:
667         free_message(commit, &msg);
668         free(defmsg);
669
670         return res;
671 }
672
673 static void prepare_revs(struct replay_opts *opts)
674 {
675         /*
676          * picking (but not reverting) ranges (but not individual revisions)
677          * should be done in reverse
678          */
679         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
680                 opts->revs->reverse ^= 1;
681
682         if (prepare_revision_walk(opts->revs))
683                 die(_("revision walk setup failed"));
684
685         if (!opts->revs->commits && !opts->quiet)
686                 error(_("empty commit set passed"));
687 }
688
689 static void read_and_refresh_cache(struct replay_opts *opts)
690 {
691         static struct lock_file index_lock;
692         int index_fd = hold_locked_index(&index_lock, 0);
693         if (read_index_preload(&the_index, NULL) < 0)
694                 die(_("git %s: failed to read the index"), action_name(opts));
695         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
696         if (the_index.cache_changed && index_fd >= 0) {
697                 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
698                         die(_("git %s: failed to refresh the index"), action_name(opts));
699         }
700         rollback_lock_file(&index_lock);
701 }
702
703 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
704                 struct replay_opts *opts)
705 {
706         struct commit_list *cur = NULL;
707         const char *sha1_abbrev = NULL;
708         const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
709         const char *subject;
710         int subject_len;
711
712         for (cur = todo_list; cur; cur = cur->next) {
713                 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
714                 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
715                 subject_len = find_commit_subject(commit_buffer, &subject);
716                 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
717                         subject_len, subject);
718                 unuse_commit_buffer(cur->item, commit_buffer);
719         }
720         return 0;
721 }
722
723 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
724 {
725         unsigned char commit_sha1[20];
726         enum replay_action action;
727         char *end_of_object_name;
728         int saved, status, padding;
729
730         if (starts_with(bol, "pick")) {
731                 action = REPLAY_PICK;
732                 bol += strlen("pick");
733         } else if (starts_with(bol, "revert")) {
734                 action = REPLAY_REVERT;
735                 bol += strlen("revert");
736         } else
737                 return NULL;
738
739         /* Eat up extra spaces/ tabs before object name */
740         padding = strspn(bol, " \t");
741         if (!padding)
742                 return NULL;
743         bol += padding;
744
745         end_of_object_name = bol + strcspn(bol, " \t\n");
746         saved = *end_of_object_name;
747         *end_of_object_name = '\0';
748         status = get_sha1(bol, commit_sha1);
749         *end_of_object_name = saved;
750
751         /*
752          * Verify that the action matches up with the one in
753          * opts; we don't support arbitrary instructions
754          */
755         if (action != opts->action) {
756                 const char *action_str;
757                 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
758                 error(_("Cannot %s during a %s"), action_str, action_name(opts));
759                 return NULL;
760         }
761
762         if (status < 0)
763                 return NULL;
764
765         return lookup_commit_reference(commit_sha1);
766 }
767
768 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
769                         struct replay_opts *opts)
770 {
771         struct commit_list **next = todo_list;
772         struct commit *commit;
773         char *p = buf;
774         int i;
775
776         for (i = 1; *p; i++) {
777                 char *eol = strchrnul(p, '\n');
778                 commit = parse_insn_line(p, eol, opts);
779                 if (!commit)
780                         return error(_("Could not parse line %d."), i);
781                 next = commit_list_append(commit, next);
782                 p = *eol ? eol + 1 : eol;
783         }
784         if (!*todo_list)
785                 return error(_("No commits parsed."));
786         return 0;
787 }
788
789 static void read_populate_todo(struct commit_list **todo_list,
790                         struct replay_opts *opts)
791 {
792         const char *todo_file = git_path(SEQ_TODO_FILE);
793         struct strbuf buf = STRBUF_INIT;
794         int fd, res;
795
796         fd = open(todo_file, O_RDONLY);
797         if (fd < 0)
798                 die_errno(_("Could not open %s"), todo_file);
799         if (strbuf_read(&buf, fd, 0) < 0) {
800                 close(fd);
801                 strbuf_release(&buf);
802                 die(_("Could not read %s."), todo_file);
803         }
804         close(fd);
805
806         res = parse_insn_buffer(buf.buf, todo_list, opts);
807         strbuf_release(&buf);
808         if (res)
809                 die(_("Unusable instruction sheet: %s"), todo_file);
810 }
811
812 static int populate_opts_cb(const char *key, const char *value, void *data)
813 {
814         struct replay_opts *opts = data;
815         int error_flag = 1;
816
817         if (!value)
818                 error_flag = 0;
819         else if (!strcmp(key, "options.no-commit"))
820                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
821         else if (!strcmp(key, "options.edit"))
822                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
823         else if (!strcmp(key, "options.signoff"))
824                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
825         else if (!strcmp(key, "options.record-origin"))
826                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
827         else if (!strcmp(key, "options.allow-ff"))
828                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
829         else if (!strcmp(key, "options.mainline"))
830                 opts->mainline = git_config_int(key, value);
831         else if (!strcmp(key, "options.strategy"))
832                 git_config_string(&opts->strategy, key, value);
833         else if (!strcmp(key, "options.gpg-sign"))
834                 git_config_string(&opts->gpg_sign, key, value);
835         else if (!strcmp(key, "options.strategy-option")) {
836                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
837                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
838         } else if (!strcmp(key, "options.allow-rerere-auto"))
839                 opts->allow_rerere_auto = git_config_int(key, value);
840         else if (!strcmp(key, "options.action-name"))
841                 git_config_string(&opts->action_name, key, value);
842         else
843                 return error(_("Invalid key: %s"), key);
844
845         if (!error_flag)
846                 return error(_("Invalid value for %s: %s"), key, value);
847
848         return 0;
849 }
850
851 static void read_populate_opts(struct replay_opts **opts_ptr)
852 {
853         const char *opts_file = git_path(SEQ_OPTS_FILE);
854
855         if (!file_exists(opts_file))
856                 return;
857         if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
858                 die(_("Malformed options sheet: %s"), opts_file);
859 }
860
861 static void walk_revs_populate_todo(struct commit_list **todo_list,
862                                 struct replay_opts *opts)
863 {
864         struct commit *commit;
865         struct commit_list **next;
866
867         prepare_revs(opts);
868
869         next = todo_list;
870         while ((commit = get_revision(opts->revs)))
871                 next = commit_list_append(commit, next);
872 }
873
874 static int create_seq_dir(void)
875 {
876         const char *seq_dir = git_path(SEQ_DIR);
877
878         if (file_exists(seq_dir)) {
879                 error(_("a cherry-pick or revert is already in progress"));
880                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
881                 return -1;
882         }
883         else if (mkdir(seq_dir, 0777) < 0)
884                 die_errno(_("Could not create sequencer directory %s"), seq_dir);
885         return 0;
886 }
887
888 static void save_head(const char *head)
889 {
890         const char *head_file = git_path(SEQ_HEAD_FILE);
891         static struct lock_file head_lock;
892         struct strbuf buf = STRBUF_INIT;
893         int fd;
894
895         fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
896         strbuf_addf(&buf, "%s\n", head);
897         if (write_in_full(fd, buf.buf, buf.len) < 0)
898                 die_errno(_("Could not write to %s"), head_file);
899         if (commit_lock_file(&head_lock) < 0)
900                 die(_("Error wrapping up %s."), head_file);
901 }
902
903 static int reset_for_rollback(const unsigned char *sha1)
904 {
905         const char *argv[4];    /* reset --merge <arg> + NULL */
906         argv[0] = "reset";
907         argv[1] = "--merge";
908         argv[2] = sha1_to_hex(sha1);
909         argv[3] = NULL;
910         return run_command_v_opt(argv, RUN_GIT_CMD);
911 }
912
913 static int rollback_single_pick(void)
914 {
915         unsigned char head_sha1[20];
916
917         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
918             !file_exists(git_path("REVERT_HEAD")))
919                 return error(_("no cherry-pick or revert in progress"));
920         if (read_ref_full("HEAD", 0, head_sha1, NULL))
921                 return error(_("cannot resolve HEAD"));
922         if (is_null_sha1(head_sha1))
923                 return error(_("cannot abort from a branch yet to be born"));
924         return reset_for_rollback(head_sha1);
925 }
926
927 static int sequencer_rollback(struct replay_opts *opts)
928 {
929         const char *filename;
930         FILE *f;
931         unsigned char sha1[20];
932         struct strbuf buf = STRBUF_INIT;
933         struct string_list merge_rr = STRING_LIST_INIT_DUP;
934
935         if (setup_rerere(&merge_rr, 0) >= 0) {
936                 rerere_clear(&merge_rr);
937                 string_list_clear(&merge_rr, 1);
938         }
939
940         filename = git_path(SEQ_HEAD_FILE);
941         f = fopen(filename, "r");
942         if (!f && errno == ENOENT) {
943                 /*
944                  * There is no multiple-cherry-pick in progress.
945                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
946                  * a single-cherry-pick in progress, abort that.
947                  */
948                 return rollback_single_pick();
949         }
950         if (!f)
951                 return error(_("cannot open %s: %s"), filename,
952                                                 strerror(errno));
953         if (strbuf_getline(&buf, f, '\n')) {
954                 error(_("cannot read %s: %s"), filename, ferror(f) ?
955                         strerror(errno) : _("unexpected end of file"));
956                 fclose(f);
957                 goto fail;
958         }
959         fclose(f);
960         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
961                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
962                         filename);
963                 goto fail;
964         }
965         if (reset_for_rollback(sha1))
966                 goto fail;
967         remove_sequencer_state();
968         strbuf_release(&buf);
969         return 0;
970 fail:
971         strbuf_release(&buf);
972         return -1;
973 }
974
975 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
976 {
977         const char *todo_file = git_path(SEQ_TODO_FILE);
978         static struct lock_file todo_lock;
979         struct strbuf buf = STRBUF_INIT;
980         int fd;
981
982         fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
983         if (format_todo(&buf, todo_list, opts) < 0)
984                 die(_("Could not format %s."), todo_file);
985         if (write_in_full(fd, buf.buf, buf.len) < 0) {
986                 strbuf_release(&buf);
987                 die_errno(_("Could not write to %s"), todo_file);
988         }
989         if (commit_lock_file(&todo_lock) < 0) {
990                 strbuf_release(&buf);
991                 die(_("Error wrapping up %s."), todo_file);
992         }
993         strbuf_release(&buf);
994 }
995
996 static void save_opts(struct replay_opts *opts)
997 {
998         const char *opts_file = git_path(SEQ_OPTS_FILE);
999
1000         if (opts->no_commit)
1001                 git_config_set_in_file(opts_file, "options.no-commit", "true");
1002         if (opts->edit)
1003                 git_config_set_in_file(opts_file, "options.edit", "true");
1004         if (opts->signoff)
1005                 git_config_set_in_file(opts_file, "options.signoff", "true");
1006         if (opts->record_origin)
1007                 git_config_set_in_file(opts_file, "options.record-origin", "true");
1008         if (opts->allow_ff)
1009                 git_config_set_in_file(opts_file, "options.allow-ff", "true");
1010         if (opts->mainline) {
1011                 struct strbuf buf = STRBUF_INIT;
1012                 strbuf_addf(&buf, "%d", opts->mainline);
1013                 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
1014                 strbuf_release(&buf);
1015         }
1016         if (opts->strategy)
1017                 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
1018         if (opts->gpg_sign)
1019                 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
1020         if (opts->xopts) {
1021                 int i;
1022                 for (i = 0; i < opts->xopts_nr; i++)
1023                         git_config_set_multivar_in_file(opts_file,
1024                                                         "options.strategy-option",
1025                                                         opts->xopts[i], "^$", 0);
1026         }
1027         if (opts->allow_rerere_auto) {
1028                 struct strbuf buf = STRBUF_INIT;
1029                 strbuf_addf(&buf, "%d", opts->allow_rerere_auto);
1030                 git_config_set_in_file(opts_file, "options.allow-rerere-auto", buf.buf);
1031                 strbuf_release(&buf);
1032         }
1033         if (opts->action_name)
1034                 git_config_set_in_file(opts_file, "options.action-name", opts->action_name);
1035 }
1036
1037 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1038 {
1039         struct commit_list *cur;
1040         int res;
1041
1042         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1043         if (opts->allow_ff)
1044                 assert(!(opts->signoff || opts->no_commit ||
1045                                 opts->record_origin || opts->edit));
1046         read_and_refresh_cache(opts);
1047
1048         for (cur = todo_list; cur; cur = cur->next) {
1049                 save_todo(cur, opts);
1050                 res = do_pick_commit(cur->item, opts);
1051                 if (res) {
1052                         if (opts->action == REPLAY_PICK)
1053                                 store_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1054                         return res;
1055                 }
1056         }
1057
1058         finish(opts);
1059
1060         /*
1061          * Sequence of picks finished successfully; cleanup by
1062          * removing the .git/sequencer directory
1063          */
1064         remove_sequencer_state();
1065         return 0;
1066 }
1067
1068 static int continue_single_pick(void)
1069 {
1070         const char *argv[] = { "commit", NULL };
1071
1072         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1073             !file_exists(git_path("REVERT_HEAD")))
1074                 return error(_("no cherry-pick or revert in progress"));
1075         return run_command_v_opt(argv, RUN_GIT_CMD);
1076 }
1077
1078 static int sequencer_continue(struct replay_opts *opts, int skip)
1079 {
1080         struct commit_list *todo_list = NULL;
1081
1082         if (!file_exists(git_path(SEQ_TODO_FILE)))
1083                 return continue_single_pick();
1084         read_populate_opts(&opts);
1085         read_populate_todo(&todo_list, opts);
1086         if (opts->action == REPLAY_PICK)
1087                 load_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1088
1089         /* Verify that the conflict has been resolved */
1090         if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1091             file_exists(git_path("REVERT_HEAD"))) {
1092                 int ret = continue_single_pick();
1093                 if (ret)
1094                         return ret;
1095         }
1096         if (index_differs_from("HEAD", 0))
1097                 return error_dirty_index(opts);
1098         if (opts->action == REPLAY_PICK && !skip) {
1099                 unsigned char to[20];
1100                 if (!read_ref("HEAD", to))
1101                         add_rewritten(&rewritten, todo_list->item->object.sha1, to);
1102         }
1103         todo_list = todo_list->next;
1104         return pick_commits(todo_list, opts);
1105 }
1106
1107 static int sequencer_skip(struct replay_opts *opts)
1108 {
1109         const char *argv[3]; /* reset --hard + NULL */
1110         struct string_list merge_rr = STRING_LIST_INIT_DUP;
1111         int ret;
1112
1113         if (setup_rerere(&merge_rr, 0) >= 0) {
1114                 rerere_clear(&merge_rr);
1115                 string_list_clear(&merge_rr, 1);
1116         }
1117
1118         argv[0] = "reset";
1119         argv[1] = "--hard";
1120         argv[2] = NULL;
1121         ret = run_command_v_opt(argv, RUN_GIT_CMD);
1122         if (ret)
1123                 return ret;
1124
1125         discard_cache();
1126         read_cache();
1127
1128         return sequencer_continue(opts, 1);
1129 }
1130
1131 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1132 {
1133         int ret;
1134         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1135         ret = do_pick_commit(cmit, opts);
1136         if (ret)
1137                 return ret;
1138         finish(opts);
1139         return 0;
1140 }
1141
1142 int sequencer_pick_revisions(struct replay_opts *opts)
1143 {
1144         struct commit_list *todo_list = NULL;
1145         unsigned char sha1[20];
1146         int i;
1147
1148         if (opts->subcommand == REPLAY_NONE)
1149                 assert(opts->revs);
1150
1151         read_and_refresh_cache(opts);
1152
1153         /*
1154          * Decide what to do depending on the arguments; a fresh
1155          * cherry-pick should be handled differently from an existing
1156          * one that is being continued
1157          */
1158         if (opts->subcommand == REPLAY_REMOVE_STATE) {
1159                 remove_sequencer_state();
1160                 return 0;
1161         }
1162         if (opts->subcommand == REPLAY_ROLLBACK)
1163                 return sequencer_rollback(opts);
1164         if (opts->subcommand == REPLAY_CONTINUE)
1165                 return sequencer_continue(opts, 0);
1166         if (opts->subcommand == REPLAY_SKIP)
1167                 return sequencer_skip(opts);
1168
1169         for (i = 0; i < opts->revs->pending.nr; i++) {
1170                 unsigned char sha1[20];
1171                 const char *name = opts->revs->pending.objects[i].name;
1172
1173                 /* This happens when using --stdin. */
1174                 if (!strlen(name))
1175                         continue;
1176
1177                 if (!get_sha1(name, sha1)) {
1178                         if (!lookup_commit_reference_gently(sha1, 1)) {
1179                                 enum object_type type = sha1_object_info(sha1, NULL);
1180                                 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1181                         }
1182                 } else
1183                         die(_("%s: bad revision"), name);
1184         }
1185
1186         /*
1187          * If we were called as "git cherry-pick <commit>", just
1188          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1189          * REVERT_HEAD, and don't touch the sequencer state.
1190          * This means it is possible to cherry-pick in the middle
1191          * of a cherry-pick sequence.
1192          */
1193         if (opts->revs->cmdline.nr == 1 &&
1194             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1195             opts->revs->no_walk &&
1196             !opts->revs->cmdline.rev->flags) {
1197                 struct commit *cmit;
1198                 if (prepare_revision_walk(opts->revs))
1199                         die(_("revision walk setup failed"));
1200                 cmit = get_revision(opts->revs);
1201                 if (!cmit || get_revision(opts->revs))
1202                         die("BUG: expected exactly one commit from walk");
1203                 return single_pick(cmit, opts);
1204         }
1205
1206         /*
1207          * Start a new cherry-pick/ revert sequence; but
1208          * first, make sure that an existing one isn't in
1209          * progress
1210          */
1211
1212         walk_revs_populate_todo(&todo_list, opts);
1213         if (create_seq_dir() < 0)
1214                 return -1;
1215         if (get_sha1("HEAD", sha1)) {
1216                 if (opts->action == REPLAY_REVERT)
1217                         return error(_("Can't revert as initial commit"));
1218                 return error(_("Can't cherry-pick into empty head"));
1219         }
1220         save_head(sha1_to_hex(sha1));
1221         save_opts(opts);
1222         return pick_commits(todo_list, opts);
1223 }
1224
1225 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1226 {
1227         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1228         struct strbuf sob = STRBUF_INIT;
1229         int has_footer;
1230
1231         strbuf_addstr(&sob, sign_off_header);
1232         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1233                                 getenv("GIT_COMMITTER_EMAIL")));
1234         strbuf_addch(&sob, '\n');
1235
1236         /*
1237          * If the whole message buffer is equal to the sob, pretend that we
1238          * found a conforming footer with a matching sob
1239          */
1240         if (msgbuf->len - ignore_footer == sob.len &&
1241             !strncmp(msgbuf->buf, sob.buf, sob.len))
1242                 has_footer = 3;
1243         else
1244                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1245
1246         if (!has_footer) {
1247                 const char *append_newlines = NULL;
1248                 size_t len = msgbuf->len - ignore_footer;
1249
1250                 if (!len) {
1251                         /*
1252                          * The buffer is completely empty.  Leave foom for
1253                          * the title and body to be filled in by the user.
1254                          */
1255                         append_newlines = "\n\n";
1256                 } else if (msgbuf->buf[len - 1] != '\n') {
1257                         /*
1258                          * Incomplete line.  Complete the line and add a
1259                          * blank one so that there is an empty line between
1260                          * the message body and the sob.
1261                          */
1262                         append_newlines = "\n\n";
1263                 } else if (len == 1) {
1264                         /*
1265                          * Buffer contains a single newline.  Add another
1266                          * so that we leave room for the title and body.
1267                          */
1268                         append_newlines = "\n";
1269                 } else if (msgbuf->buf[len - 2] != '\n') {
1270                         /*
1271                          * Buffer ends with a single newline.  Add another
1272                          * so that there is an empty line between the message
1273                          * body and the sob.
1274                          */
1275                         append_newlines = "\n";
1276                 } /* else, the buffer already ends with two newlines. */
1277
1278                 if (append_newlines)
1279                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1280                                 append_newlines, strlen(append_newlines));
1281         }
1282
1283         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1284                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1285                                 sob.buf, sob.len);
1286
1287         strbuf_release(&sob);
1288 }