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