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