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