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