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