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