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