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