cherry-pick: regression fix for empty commits
[git] / sequencer.c
1 #include "cache.h"
2 #include "sequencer.h"
3 #include "dir.h"
4 #include "object.h"
5 #include "commit.h"
6 #include "tag.h"
7 #include "run-command.h"
8 #include "exec_cmd.h"
9 #include "utf8.h"
10 #include "cache-tree.h"
11 #include "diff.h"
12 #include "revision.h"
13 #include "rerere.h"
14 #include "merge-recursive.h"
15 #include "refs.h"
16 #include "argv-array.h"
17
18 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
19
20 void remove_sequencer_state(void)
21 {
22         struct strbuf seq_dir = STRBUF_INIT;
23
24         strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
25         remove_dir_recursively(&seq_dir, 0);
26         strbuf_release(&seq_dir);
27 }
28
29 static const char *action_name(const struct replay_opts *opts)
30 {
31         return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
32 }
33
34 static char *get_encoding(const char *message);
35
36 struct commit_message {
37         char *parent_label;
38         const char *label;
39         const char *subject;
40         char *reencoded_message;
41         const char *message;
42 };
43
44 static int get_message(struct commit *commit, struct commit_message *out)
45 {
46         const char *encoding;
47         const char *abbrev, *subject;
48         int abbrev_len, subject_len;
49         char *q;
50
51         if (!commit->buffer)
52                 return -1;
53         encoding = get_encoding(commit->buffer);
54         if (!encoding)
55                 encoding = "UTF-8";
56         if (!git_commit_encoding)
57                 git_commit_encoding = "UTF-8";
58
59         out->reencoded_message = NULL;
60         out->message = commit->buffer;
61         if (strcmp(encoding, git_commit_encoding))
62                 out->reencoded_message = reencode_string(commit->buffer,
63                                         git_commit_encoding, encoding);
64         if (out->reencoded_message)
65                 out->message = out->reencoded_message;
66
67         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
68         abbrev_len = strlen(abbrev);
69
70         subject_len = find_commit_subject(out->message, &subject);
71
72         out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
73                               strlen("... ") + subject_len + 1);
74         q = out->parent_label;
75         q = mempcpy(q, "parent of ", strlen("parent of "));
76         out->label = q;
77         q = mempcpy(q, abbrev, abbrev_len);
78         q = mempcpy(q, "... ", strlen("... "));
79         out->subject = q;
80         q = mempcpy(q, subject, subject_len);
81         *q = '\0';
82         return 0;
83 }
84
85 static void free_message(struct commit_message *msg)
86 {
87         free(msg->parent_label);
88         free(msg->reencoded_message);
89 }
90
91 static char *get_encoding(const char *message)
92 {
93         const char *p = message, *eol;
94
95         while (*p && *p != '\n') {
96                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
97                         ; /* do nothing */
98                 if (!prefixcmp(p, "encoding ")) {
99                         char *result = xmalloc(eol - 8 - p);
100                         strlcpy(result, p + 9, eol - 8 - p);
101                         return result;
102                 }
103                 p = eol;
104                 if (*p == '\n')
105                         p++;
106         }
107         return NULL;
108 }
109
110 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
111 {
112         const char *filename;
113         int fd;
114         struct strbuf buf = STRBUF_INIT;
115
116         strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
117
118         filename = git_path("%s", pseudoref);
119         fd = open(filename, O_WRONLY | O_CREAT, 0666);
120         if (fd < 0)
121                 die_errno(_("Could not open '%s' for writing"), filename);
122         if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
123                 die_errno(_("Could not write to '%s'"), filename);
124         strbuf_release(&buf);
125 }
126
127 static void print_advice(int show_hint, struct replay_opts *opts)
128 {
129         char *msg = getenv("GIT_CHERRY_PICK_HELP");
130
131         if (msg) {
132                 fprintf(stderr, "%s\n", msg);
133                 /*
134                  * A conflict has occured but the porcelain
135                  * (typically rebase --interactive) wants to take care
136                  * of the commit itself so remove CHERRY_PICK_HEAD
137                  */
138                 unlink(git_path("CHERRY_PICK_HEAD"));
139                 return;
140         }
141
142         if (show_hint) {
143                 if (opts->no_commit)
144                         advise(_("after resolving the conflicts, mark the corrected paths\n"
145                                  "with 'git add <paths>' or 'git rm <paths>'"));
146                 else
147                         advise(_("after resolving the conflicts, mark the corrected paths\n"
148                                  "with 'git add <paths>' or 'git rm <paths>'\n"
149                                  "and commit the result with 'git commit'"));
150         }
151 }
152
153 static void write_message(struct strbuf *msgbuf, const char *filename)
154 {
155         static struct lock_file msg_file;
156
157         int msg_fd = hold_lock_file_for_update(&msg_file, filename,
158                                                LOCK_DIE_ON_ERROR);
159         if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
160                 die_errno(_("Could not write to %s"), filename);
161         strbuf_release(msgbuf);
162         if (commit_lock_file(&msg_file) < 0)
163                 die(_("Error wrapping up %s"), filename);
164 }
165
166 static struct tree *empty_tree(void)
167 {
168         return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
169 }
170
171 static int error_dirty_index(struct replay_opts *opts)
172 {
173         if (read_cache_unmerged())
174                 return error_resolve_conflict(action_name(opts));
175
176         /* Different translation strings for cherry-pick and revert */
177         if (opts->action == REPLAY_PICK)
178                 error(_("Your local changes would be overwritten by cherry-pick."));
179         else
180                 error(_("Your local changes would be overwritten by revert."));
181
182         if (advice_commit_before_merge)
183                 advise(_("Commit your changes or stash them to proceed."));
184         return -1;
185 }
186
187 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
188 {
189         struct ref_lock *ref_lock;
190
191         read_cache();
192         if (checkout_fast_forward(from, to))
193                 exit(1); /* the callee should have complained already */
194         ref_lock = lock_any_ref_for_update("HEAD", from, 0);
195         return write_ref_sha1(ref_lock, to, "cherry-pick");
196 }
197
198 static int do_recursive_merge(struct commit *base, struct commit *next,
199                               const char *base_label, const char *next_label,
200                               unsigned char *head, struct strbuf *msgbuf,
201                               struct replay_opts *opts)
202 {
203         struct merge_options o;
204         struct tree *result, *next_tree, *base_tree, *head_tree;
205         int clean, index_fd;
206         const char **xopt;
207         static struct lock_file index_lock;
208
209         index_fd = hold_locked_index(&index_lock, 1);
210
211         read_cache();
212
213         init_merge_options(&o);
214         o.ancestor = base ? base_label : "(empty tree)";
215         o.branch1 = "HEAD";
216         o.branch2 = next ? next_label : "(empty tree)";
217
218         head_tree = parse_tree_indirect(head);
219         next_tree = next ? next->tree : empty_tree();
220         base_tree = base ? base->tree : empty_tree();
221
222         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
223                 parse_merge_opt(&o, *xopt);
224
225         clean = merge_trees(&o,
226                             head_tree,
227                             next_tree, base_tree, &result);
228
229         if (active_cache_changed &&
230             (write_cache(index_fd, active_cache, active_nr) ||
231              commit_locked_index(&index_lock)))
232                 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
233                 die(_("%s: Unable to write new index file"), action_name(opts));
234         rollback_lock_file(&index_lock);
235
236         if (!clean) {
237                 int i;
238                 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
239                 for (i = 0; i < active_nr;) {
240                         struct cache_entry *ce = active_cache[i++];
241                         if (ce_stage(ce)) {
242                                 strbuf_addch(msgbuf, '\t');
243                                 strbuf_addstr(msgbuf, ce->name);
244                                 strbuf_addch(msgbuf, '\n');
245                                 while (i < active_nr && !strcmp(ce->name,
246                                                 active_cache[i]->name))
247                                         i++;
248                         }
249                 }
250         }
251
252         return !clean;
253 }
254
255 static int is_index_unchanged(void)
256 {
257         unsigned char head_sha1[20];
258         struct commit *head_commit;
259
260         if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
261                 return error(_("Could not resolve HEAD commit\n"));
262
263         head_commit = lookup_commit(head_sha1);
264
265         /*
266          * If head_commit is NULL, check_commit, called from
267          * lookup_commit, would have indicated that head_commit is not
268          * a commit object already.  parse_commit() will return failure
269          * without further complaints in such a case.  Otherwise, if
270          * the commit is invalid, parse_commit() will complain.  So
271          * there is nothing for us to say here.  Just return failure.
272          */
273         if (parse_commit(head_commit))
274                 return -1;
275
276         if (!active_cache_tree)
277                 active_cache_tree = cache_tree();
278
279         if (!cache_tree_fully_valid(active_cache_tree))
280                 if (cache_tree_update(active_cache_tree, active_cache,
281                                   active_nr, 0))
282                         return error(_("Unable to update cache tree\n"));
283
284         return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
285 }
286
287 /*
288  * If we are cherry-pick, and if the merge did not result in
289  * hand-editing, we will hit this commit and inherit the original
290  * author date and name.
291  * If we are revert, or if our cherry-pick results in a hand merge,
292  * we had better say that the current user is responsible for that.
293  */
294 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
295                           int allow_empty)
296 {
297         struct argv_array array;
298         int rc;
299
300         argv_array_init(&array);
301         argv_array_push(&array, "commit");
302         argv_array_push(&array, "-n");
303
304         if (opts->signoff)
305                 argv_array_push(&array, "-s");
306         if (!opts->edit) {
307                 argv_array_push(&array, "-F");
308                 argv_array_push(&array, defmsg);
309         }
310
311         if (allow_empty)
312                 argv_array_push(&array, "--allow-empty");
313
314         rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
315         argv_array_clear(&array);
316         return rc;
317 }
318
319 static int is_original_commit_empty(struct commit *commit)
320 {
321         const unsigned char *ptree_sha1;
322
323         if (parse_commit(commit))
324                 return error(_("Could not parse commit %s\n"),
325                              sha1_to_hex(commit->object.sha1));
326         if (commit->parents) {
327                 struct commit *parent = commit->parents->item;
328                 if (parse_commit(parent))
329                         return error(_("Could not parse parent commit %s\n"),
330                                 sha1_to_hex(parent->object.sha1));
331                 ptree_sha1 = parent->tree->object.sha1;
332         } else {
333                 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
334         }
335
336         return !hashcmp(ptree_sha1, commit->tree->object.sha1);
337 }
338
339 /*
340  * Do we run "git commit" with "--allow-empty"?
341  */
342 static int allow_empty(struct replay_opts *opts, struct commit *commit)
343 {
344         int index_unchanged, empty_commit;
345
346         /*
347          * Three cases:
348          *
349          * (1) we do not allow empty at all and error out.
350          *
351          * (2) we allow ones that were initially empty, but
352          * forbid the ones that become empty;
353          *
354          * (3) we allow both.
355          */
356         if (!opts->allow_empty)
357                 return 0; /* let "git commit" barf as necessary */
358
359         index_unchanged = is_index_unchanged();
360         if (index_unchanged < 0)
361                 return index_unchanged;
362         if (!index_unchanged)
363                 return 0; /* we do not have to say --allow-empty */
364
365         if (opts->keep_redundant_commits)
366                 return 1;
367
368         empty_commit = is_original_commit_empty(commit);
369         if (empty_commit < 0)
370                 return empty_commit;
371         if (!empty_commit)
372                 return 0;
373         else
374                 return 1;
375 }
376
377 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
378 {
379         unsigned char head[20];
380         struct commit *base, *next, *parent;
381         const char *base_label, *next_label;
382         struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
383         char *defmsg = NULL;
384         struct strbuf msgbuf = STRBUF_INIT;
385         int res;
386
387         if (opts->no_commit) {
388                 /*
389                  * We do not intend to commit immediately.  We just want to
390                  * merge the differences in, so let's compute the tree
391                  * that represents the "current" state for merge-recursive
392                  * to work on.
393                  */
394                 if (write_cache_as_tree(head, 0, NULL))
395                         die (_("Your index file is unmerged."));
396         } else {
397                 if (get_sha1("HEAD", head))
398                         return error(_("You do not have a valid HEAD"));
399                 if (index_differs_from("HEAD", 0))
400                         return error_dirty_index(opts);
401         }
402         discard_cache();
403
404         if (!commit->parents) {
405                 parent = NULL;
406         }
407         else if (commit->parents->next) {
408                 /* Reverting or cherry-picking a merge commit */
409                 int cnt;
410                 struct commit_list *p;
411
412                 if (!opts->mainline)
413                         return error(_("Commit %s is a merge but no -m option was given."),
414                                 sha1_to_hex(commit->object.sha1));
415
416                 for (cnt = 1, p = commit->parents;
417                      cnt != opts->mainline && p;
418                      cnt++)
419                         p = p->next;
420                 if (cnt != opts->mainline || !p)
421                         return error(_("Commit %s does not have parent %d"),
422                                 sha1_to_hex(commit->object.sha1), opts->mainline);
423                 parent = p->item;
424         } else if (0 < opts->mainline)
425                 return error(_("Mainline was specified but commit %s is not a merge."),
426                         sha1_to_hex(commit->object.sha1));
427         else
428                 parent = commit->parents->item;
429
430         if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
431                 return fast_forward_to(commit->object.sha1, head);
432
433         if (parent && parse_commit(parent) < 0)
434                 /* TRANSLATORS: The first %s will be "revert" or
435                    "cherry-pick", the second %s a SHA1 */
436                 return error(_("%s: cannot parse parent commit %s"),
437                         action_name(opts), sha1_to_hex(parent->object.sha1));
438
439         if (get_message(commit, &msg) != 0)
440                 return error(_("Cannot get commit message for %s"),
441                         sha1_to_hex(commit->object.sha1));
442
443         /*
444          * "commit" is an existing commit.  We would want to apply
445          * the difference it introduces since its first parent "prev"
446          * on top of the current HEAD if we are cherry-pick.  Or the
447          * reverse of it if we are revert.
448          */
449
450         defmsg = git_pathdup("MERGE_MSG");
451
452         if (opts->action == REPLAY_REVERT) {
453                 base = commit;
454                 base_label = msg.label;
455                 next = parent;
456                 next_label = msg.parent_label;
457                 strbuf_addstr(&msgbuf, "Revert \"");
458                 strbuf_addstr(&msgbuf, msg.subject);
459                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
460                 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
461
462                 if (commit->parents && commit->parents->next) {
463                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
464                         strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
465                 }
466                 strbuf_addstr(&msgbuf, ".\n");
467         } else {
468                 const char *p;
469
470                 base = parent;
471                 base_label = msg.parent_label;
472                 next = commit;
473                 next_label = msg.label;
474
475                 /*
476                  * Append the commit log message to msgbuf; it starts
477                  * after the tree, parent, author, committer
478                  * information followed by "\n\n".
479                  */
480                 p = strstr(msg.message, "\n\n");
481                 if (p) {
482                         p += 2;
483                         strbuf_addstr(&msgbuf, p);
484                 }
485
486                 if (opts->record_origin) {
487                         strbuf_addstr(&msgbuf, "(cherry picked from commit ");
488                         strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
489                         strbuf_addstr(&msgbuf, ")\n");
490                 }
491         }
492
493         if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
494                 res = do_recursive_merge(base, next, base_label, next_label,
495                                          head, &msgbuf, opts);
496                 write_message(&msgbuf, defmsg);
497         } else {
498                 struct commit_list *common = NULL;
499                 struct commit_list *remotes = NULL;
500
501                 write_message(&msgbuf, defmsg);
502
503                 commit_list_insert(base, &common);
504                 commit_list_insert(next, &remotes);
505                 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
506                                         common, sha1_to_hex(head), remotes);
507                 free_commit_list(common);
508                 free_commit_list(remotes);
509         }
510
511         /*
512          * If the merge was clean or if it failed due to conflict, we write
513          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
514          * However, if the merge did not even start, then we don't want to
515          * write it at all.
516          */
517         if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
518                 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
519         if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
520                 write_cherry_pick_head(commit, "REVERT_HEAD");
521
522         if (res) {
523                 error(opts->action == REPLAY_REVERT
524                       ? _("could not revert %s... %s")
525                       : _("could not apply %s... %s"),
526                       find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
527                       msg.subject);
528                 print_advice(res == 1, opts);
529                 rerere(opts->allow_rerere_auto);
530         } else {
531                 int allow = allow_empty(opts, commit);
532                 if (allow < 0)
533                         return allow;
534                 if (!opts->no_commit)
535                         res = run_git_commit(defmsg, opts, allow);
536         }
537
538         free_message(&msg);
539         free(defmsg);
540
541         return res;
542 }
543
544 static void prepare_revs(struct replay_opts *opts)
545 {
546         if (opts->action != REPLAY_REVERT)
547                 opts->revs->reverse ^= 1;
548
549         if (prepare_revision_walk(opts->revs))
550                 die(_("revision walk setup failed"));
551
552         if (!opts->revs->commits)
553                 die(_("empty commit set passed"));
554 }
555
556 static void read_and_refresh_cache(struct replay_opts *opts)
557 {
558         static struct lock_file index_lock;
559         int index_fd = hold_locked_index(&index_lock, 0);
560         if (read_index_preload(&the_index, NULL) < 0)
561                 die(_("git %s: failed to read the index"), action_name(opts));
562         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
563         if (the_index.cache_changed) {
564                 if (write_index(&the_index, index_fd) ||
565                     commit_locked_index(&index_lock))
566                         die(_("git %s: failed to refresh the index"), action_name(opts));
567         }
568         rollback_lock_file(&index_lock);
569 }
570
571 /*
572  * Append a commit to the end of the commit_list.
573  *
574  * next starts by pointing to the variable that holds the head of an
575  * empty commit_list, and is updated to point to the "next" field of
576  * the last item on the list as new commits are appended.
577  *
578  * Usage example:
579  *
580  *     struct commit_list *list;
581  *     struct commit_list **next = &list;
582  *
583  *     next = commit_list_append(c1, next);
584  *     next = commit_list_append(c2, next);
585  *     assert(commit_list_count(list) == 2);
586  *     return list;
587  */
588 static struct commit_list **commit_list_append(struct commit *commit,
589                                                struct commit_list **next)
590 {
591         struct commit_list *new = xmalloc(sizeof(struct commit_list));
592         new->item = commit;
593         *next = new;
594         new->next = NULL;
595         return &new->next;
596 }
597
598 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
599                 struct replay_opts *opts)
600 {
601         struct commit_list *cur = NULL;
602         const char *sha1_abbrev = NULL;
603         const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
604         const char *subject;
605         int subject_len;
606
607         for (cur = todo_list; cur; cur = cur->next) {
608                 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
609                 subject_len = find_commit_subject(cur->item->buffer, &subject);
610                 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
611                         subject_len, subject);
612         }
613         return 0;
614 }
615
616 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
617 {
618         unsigned char commit_sha1[20];
619         enum replay_action action;
620         char *end_of_object_name;
621         int saved, status, padding;
622
623         if (!prefixcmp(bol, "pick")) {
624                 action = REPLAY_PICK;
625                 bol += strlen("pick");
626         } else if (!prefixcmp(bol, "revert")) {
627                 action = REPLAY_REVERT;
628                 bol += strlen("revert");
629         } else
630                 return NULL;
631
632         /* Eat up extra spaces/ tabs before object name */
633         padding = strspn(bol, " \t");
634         if (!padding)
635                 return NULL;
636         bol += padding;
637
638         end_of_object_name = bol + strcspn(bol, " \t\n");
639         saved = *end_of_object_name;
640         *end_of_object_name = '\0';
641         status = get_sha1(bol, commit_sha1);
642         *end_of_object_name = saved;
643
644         /*
645          * Verify that the action matches up with the one in
646          * opts; we don't support arbitrary instructions
647          */
648         if (action != opts->action) {
649                 const char *action_str;
650                 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
651                 error(_("Cannot %s during a %s"), action_str, action_name(opts));
652                 return NULL;
653         }
654
655         if (status < 0)
656                 return NULL;
657
658         return lookup_commit_reference(commit_sha1);
659 }
660
661 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
662                         struct replay_opts *opts)
663 {
664         struct commit_list **next = todo_list;
665         struct commit *commit;
666         char *p = buf;
667         int i;
668
669         for (i = 1; *p; i++) {
670                 char *eol = strchrnul(p, '\n');
671                 commit = parse_insn_line(p, eol, opts);
672                 if (!commit)
673                         return error(_("Could not parse line %d."), i);
674                 next = commit_list_append(commit, next);
675                 p = *eol ? eol + 1 : eol;
676         }
677         if (!*todo_list)
678                 return error(_("No commits parsed."));
679         return 0;
680 }
681
682 static void read_populate_todo(struct commit_list **todo_list,
683                         struct replay_opts *opts)
684 {
685         const char *todo_file = git_path(SEQ_TODO_FILE);
686         struct strbuf buf = STRBUF_INIT;
687         int fd, res;
688
689         fd = open(todo_file, O_RDONLY);
690         if (fd < 0)
691                 die_errno(_("Could not open %s"), todo_file);
692         if (strbuf_read(&buf, fd, 0) < 0) {
693                 close(fd);
694                 strbuf_release(&buf);
695                 die(_("Could not read %s."), todo_file);
696         }
697         close(fd);
698
699         res = parse_insn_buffer(buf.buf, todo_list, opts);
700         strbuf_release(&buf);
701         if (res)
702                 die(_("Unusable instruction sheet: %s"), todo_file);
703 }
704
705 static int populate_opts_cb(const char *key, const char *value, void *data)
706 {
707         struct replay_opts *opts = data;
708         int error_flag = 1;
709
710         if (!value)
711                 error_flag = 0;
712         else if (!strcmp(key, "options.no-commit"))
713                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
714         else if (!strcmp(key, "options.edit"))
715                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
716         else if (!strcmp(key, "options.signoff"))
717                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
718         else if (!strcmp(key, "options.record-origin"))
719                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
720         else if (!strcmp(key, "options.allow-ff"))
721                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
722         else if (!strcmp(key, "options.mainline"))
723                 opts->mainline = git_config_int(key, value);
724         else if (!strcmp(key, "options.strategy"))
725                 git_config_string(&opts->strategy, key, value);
726         else if (!strcmp(key, "options.strategy-option")) {
727                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
728                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
729         } else
730                 return error(_("Invalid key: %s"), key);
731
732         if (!error_flag)
733                 return error(_("Invalid value for %s: %s"), key, value);
734
735         return 0;
736 }
737
738 static void read_populate_opts(struct replay_opts **opts_ptr)
739 {
740         const char *opts_file = git_path(SEQ_OPTS_FILE);
741
742         if (!file_exists(opts_file))
743                 return;
744         if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
745                 die(_("Malformed options sheet: %s"), opts_file);
746 }
747
748 static void walk_revs_populate_todo(struct commit_list **todo_list,
749                                 struct replay_opts *opts)
750 {
751         struct commit *commit;
752         struct commit_list **next;
753
754         prepare_revs(opts);
755
756         next = todo_list;
757         while ((commit = get_revision(opts->revs)))
758                 next = commit_list_append(commit, next);
759 }
760
761 static int create_seq_dir(void)
762 {
763         const char *seq_dir = git_path(SEQ_DIR);
764
765         if (file_exists(seq_dir)) {
766                 error(_("a cherry-pick or revert is already in progress"));
767                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
768                 return -1;
769         }
770         else if (mkdir(seq_dir, 0777) < 0)
771                 die_errno(_("Could not create sequencer directory %s"), seq_dir);
772         return 0;
773 }
774
775 static void save_head(const char *head)
776 {
777         const char *head_file = git_path(SEQ_HEAD_FILE);
778         static struct lock_file head_lock;
779         struct strbuf buf = STRBUF_INIT;
780         int fd;
781
782         fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
783         strbuf_addf(&buf, "%s\n", head);
784         if (write_in_full(fd, buf.buf, buf.len) < 0)
785                 die_errno(_("Could not write to %s"), head_file);
786         if (commit_lock_file(&head_lock) < 0)
787                 die(_("Error wrapping up %s."), head_file);
788 }
789
790 static int reset_for_rollback(const unsigned char *sha1)
791 {
792         const char *argv[4];    /* reset --merge <arg> + NULL */
793         argv[0] = "reset";
794         argv[1] = "--merge";
795         argv[2] = sha1_to_hex(sha1);
796         argv[3] = NULL;
797         return run_command_v_opt(argv, RUN_GIT_CMD);
798 }
799
800 static int rollback_single_pick(void)
801 {
802         unsigned char head_sha1[20];
803
804         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
805             !file_exists(git_path("REVERT_HEAD")))
806                 return error(_("no cherry-pick or revert in progress"));
807         if (read_ref_full("HEAD", head_sha1, 0, NULL))
808                 return error(_("cannot resolve HEAD"));
809         if (is_null_sha1(head_sha1))
810                 return error(_("cannot abort from a branch yet to be born"));
811         return reset_for_rollback(head_sha1);
812 }
813
814 static int sequencer_rollback(struct replay_opts *opts)
815 {
816         const char *filename;
817         FILE *f;
818         unsigned char sha1[20];
819         struct strbuf buf = STRBUF_INIT;
820
821         filename = git_path(SEQ_HEAD_FILE);
822         f = fopen(filename, "r");
823         if (!f && errno == ENOENT) {
824                 /*
825                  * There is no multiple-cherry-pick in progress.
826                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
827                  * a single-cherry-pick in progress, abort that.
828                  */
829                 return rollback_single_pick();
830         }
831         if (!f)
832                 return error(_("cannot open %s: %s"), filename,
833                                                 strerror(errno));
834         if (strbuf_getline(&buf, f, '\n')) {
835                 error(_("cannot read %s: %s"), filename, ferror(f) ?
836                         strerror(errno) : _("unexpected end of file"));
837                 fclose(f);
838                 goto fail;
839         }
840         fclose(f);
841         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
842                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
843                         filename);
844                 goto fail;
845         }
846         if (reset_for_rollback(sha1))
847                 goto fail;
848         remove_sequencer_state();
849         strbuf_release(&buf);
850         return 0;
851 fail:
852         strbuf_release(&buf);
853         return -1;
854 }
855
856 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
857 {
858         const char *todo_file = git_path(SEQ_TODO_FILE);
859         static struct lock_file todo_lock;
860         struct strbuf buf = STRBUF_INIT;
861         int fd;
862
863         fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
864         if (format_todo(&buf, todo_list, opts) < 0)
865                 die(_("Could not format %s."), todo_file);
866         if (write_in_full(fd, buf.buf, buf.len) < 0) {
867                 strbuf_release(&buf);
868                 die_errno(_("Could not write to %s"), todo_file);
869         }
870         if (commit_lock_file(&todo_lock) < 0) {
871                 strbuf_release(&buf);
872                 die(_("Error wrapping up %s."), todo_file);
873         }
874         strbuf_release(&buf);
875 }
876
877 static void save_opts(struct replay_opts *opts)
878 {
879         const char *opts_file = git_path(SEQ_OPTS_FILE);
880
881         if (opts->no_commit)
882                 git_config_set_in_file(opts_file, "options.no-commit", "true");
883         if (opts->edit)
884                 git_config_set_in_file(opts_file, "options.edit", "true");
885         if (opts->signoff)
886                 git_config_set_in_file(opts_file, "options.signoff", "true");
887         if (opts->record_origin)
888                 git_config_set_in_file(opts_file, "options.record-origin", "true");
889         if (opts->allow_ff)
890                 git_config_set_in_file(opts_file, "options.allow-ff", "true");
891         if (opts->mainline) {
892                 struct strbuf buf = STRBUF_INIT;
893                 strbuf_addf(&buf, "%d", opts->mainline);
894                 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
895                 strbuf_release(&buf);
896         }
897         if (opts->strategy)
898                 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
899         if (opts->xopts) {
900                 int i;
901                 for (i = 0; i < opts->xopts_nr; i++)
902                         git_config_set_multivar_in_file(opts_file,
903                                                         "options.strategy-option",
904                                                         opts->xopts[i], "^$", 0);
905         }
906 }
907
908 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
909 {
910         struct commit_list *cur;
911         int res;
912
913         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
914         if (opts->allow_ff)
915                 assert(!(opts->signoff || opts->no_commit ||
916                                 opts->record_origin || opts->edit));
917         read_and_refresh_cache(opts);
918
919         for (cur = todo_list; cur; cur = cur->next) {
920                 save_todo(cur, opts);
921                 res = do_pick_commit(cur->item, opts);
922                 if (res)
923                         return res;
924         }
925
926         /*
927          * Sequence of picks finished successfully; cleanup by
928          * removing the .git/sequencer directory
929          */
930         remove_sequencer_state();
931         return 0;
932 }
933
934 static int continue_single_pick(void)
935 {
936         const char *argv[] = { "commit", NULL };
937
938         if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
939             !file_exists(git_path("REVERT_HEAD")))
940                 return error(_("no cherry-pick or revert in progress"));
941         return run_command_v_opt(argv, RUN_GIT_CMD);
942 }
943
944 static int sequencer_continue(struct replay_opts *opts)
945 {
946         struct commit_list *todo_list = NULL;
947
948         if (!file_exists(git_path(SEQ_TODO_FILE)))
949                 return continue_single_pick();
950         read_populate_opts(&opts);
951         read_populate_todo(&todo_list, opts);
952
953         /* Verify that the conflict has been resolved */
954         if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
955             file_exists(git_path("REVERT_HEAD"))) {
956                 int ret = continue_single_pick();
957                 if (ret)
958                         return ret;
959         }
960         if (index_differs_from("HEAD", 0))
961                 return error_dirty_index(opts);
962         todo_list = todo_list->next;
963         return pick_commits(todo_list, opts);
964 }
965
966 static int single_pick(struct commit *cmit, struct replay_opts *opts)
967 {
968         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
969         return do_pick_commit(cmit, opts);
970 }
971
972 int sequencer_pick_revisions(struct replay_opts *opts)
973 {
974         struct commit_list *todo_list = NULL;
975         unsigned char sha1[20];
976
977         if (opts->subcommand == REPLAY_NONE)
978                 assert(opts->revs);
979
980         read_and_refresh_cache(opts);
981
982         /*
983          * Decide what to do depending on the arguments; a fresh
984          * cherry-pick should be handled differently from an existing
985          * one that is being continued
986          */
987         if (opts->subcommand == REPLAY_REMOVE_STATE) {
988                 remove_sequencer_state();
989                 return 0;
990         }
991         if (opts->subcommand == REPLAY_ROLLBACK)
992                 return sequencer_rollback(opts);
993         if (opts->subcommand == REPLAY_CONTINUE)
994                 return sequencer_continue(opts);
995
996         /*
997          * If we were called as "git cherry-pick <commit>", just
998          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
999          * REVERT_HEAD, and don't touch the sequencer state.
1000          * This means it is possible to cherry-pick in the middle
1001          * of a cherry-pick sequence.
1002          */
1003         if (opts->revs->cmdline.nr == 1 &&
1004             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1005             opts->revs->no_walk &&
1006             !opts->revs->cmdline.rev->flags) {
1007                 struct commit *cmit;
1008                 if (prepare_revision_walk(opts->revs))
1009                         die(_("revision walk setup failed"));
1010                 cmit = get_revision(opts->revs);
1011                 if (!cmit || get_revision(opts->revs))
1012                         die("BUG: expected exactly one commit from walk");
1013                 return single_pick(cmit, opts);
1014         }
1015
1016         /*
1017          * Start a new cherry-pick/ revert sequence; but
1018          * first, make sure that an existing one isn't in
1019          * progress
1020          */
1021
1022         walk_revs_populate_todo(&todo_list, opts);
1023         if (create_seq_dir() < 0)
1024                 return -1;
1025         if (get_sha1("HEAD", sha1)) {
1026                 if (opts->action == REPLAY_REVERT)
1027                         return error(_("Can't revert as initial commit"));
1028                 return error(_("Can't cherry-pick into empty head"));
1029         }
1030         save_head(sha1_to_hex(sha1));
1031         save_opts(opts);
1032         return pick_commits(todo_list, opts);
1033 }