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