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