Code

revert: do not pass non-literal string as format to git_path()
[git.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"
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  */
30 static const char * const revert_usage[] = {
31         "git revert [options] <commit-ish>",
32         "git revert <subcommand>",
33         NULL
34 };
36 static const char * const cherry_pick_usage[] = {
37         "git cherry-pick [options] <commit-ish>",
38         "git cherry-pick <subcommand>",
39         NULL
40 };
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 };
50 struct replay_opts {
51         enum replay_action action;
52         enum replay_subcommand subcommand;
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;
62         int mainline;
63         int commit_argc;
64         const char **commit_argv;
66         /* Merge strategy */
67         const char *strategy;
68         const char **xopts;
69         size_t xopts_nr, xopts_alloc;
70 };
72 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
74 static const char *action_name(const struct replay_opts *opts)
75 {
76         return opts->action == REVERT ? "revert" : "cherry-pick";
77 }
79 static char *get_encoding(const char *message);
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 }
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;
92         if (unset)
93                 return 0;
95         ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
96         opts->xopts[opts->xopts_nr++] = xstrdup(arg);
97         return 0;
98 }
100 static void verify_opt_compatible(const char *me, const char *base_opt, ...)
102         const char *this_opt;
103         va_list ap;
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);
112         if (this_opt)
113                 die(_("%s: %s cannot be used with %s"), me, this_opt, base_opt);
116 static void verify_opt_mutually_compatible(const char *me, ...)
118         const char *opt1, *opt2 = NULL;
119         va_list ap;
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         }
133         if (opt1 && opt2)
134                 die(_("%s: %s cannot be used with %s"), me, opt1, opt2);
137 static void parse_args(int argc, const char **argv, struct replay_opts *opts)
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         };
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         }
172         opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
173                                         PARSE_OPT_KEEP_ARGV0 |
174                                         PARSE_OPT_KEEP_UNKNOWN);
176         /* Check for incompatible subcommands */
177         verify_opt_mutually_compatible(me,
178                                 "--quit", remove_state,
179                                 "--continue", contin,
180                                 "--abort", rollback,
181                                 NULL);
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;
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                 }
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         }
216         else if (opts->commit_argc < 2)
217                 usage_with_options(usage_str, options);
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;
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 };
237 static int get_message(struct commit *commit, struct commit_message *out)
239         const char *encoding;
240         const char *abbrev, *subject;
241         int abbrev_len, subject_len;
242         char *q;
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";
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;
260         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
261         abbrev_len = strlen(abbrev);
263         subject_len = find_commit_subject(out->message, &subject);
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;
278 static void free_message(struct commit_message *msg)
280         free(msg->parent_label);
281         free(msg->reencoded_message);
284 static char *get_encoding(const char *message)
286         const char *p = message, *eol;
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;
303 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
305         const char *filename;
306         int fd;
307         struct strbuf buf = STRBUF_INIT;
309         strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
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);
320 static void print_advice(int show_hint)
322         char *msg = getenv("GIT_CHERRY_PICK_HELP");
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         }
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         }
342 static void write_message(struct strbuf *msgbuf, const char *filename)
344         static struct lock_file msg_file;
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);
355 static struct tree *empty_tree(void)
357         return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
360 static int error_dirty_index(struct replay_opts *opts)
362         if (read_cache_unmerged())
363                 return error_resolve_conflict(action_name(opts));
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."));
371         if (advice_commit_before_merge)
372                 advise(_("Commit your changes or stash them to proceed."));
373         return -1;
376 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
378         struct ref_lock *ref_lock;
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");
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)
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;
398         index_fd = hold_locked_index(&index_lock, 1);
400         read_cache();
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)";
407         head_tree = parse_tree_indirect(head);
408         next_tree = next ? next->tree : empty_tree();
409         base_tree = base ? base->tree : empty_tree();
411         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
412                 parse_merge_opt(&o, *xopt);
414         clean = merge_trees(&o,
415                             head_tree,
416                             next_tree, base_tree, &result);
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);
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         }
441         return !clean;
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)
453         /* 6 is max possible length of our args array including NULL */
454         const char *args[6];
455         int i = 0;
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;
467         return run_command_v_opt(args, RUN_GIT_CMD);
470 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
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;
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();
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;
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));
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;
523         if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
524                 return fast_forward_to(commit->object.sha1, head);
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));
532         if (get_message(commit, &msg) != 0)
533                 return error(_("Cannot get commit message for %s"),
534                         sha1_to_hex(commit->object.sha1));
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          */
543         defmsg = git_pathdup("MERGE_MSG");
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));
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;
563                 base = parent;
564                 base_label = msg.parent_label;
565                 next = commit;
566                 next_label = msg.label;
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                 }
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         }
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;
594                 write_message(&msgbuf, defmsg);
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         }
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");
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         }
628         free_message(&msg);
629         free(defmsg);
631         return res;
634 static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
636         int argc;
638         init_revisions(revs, NULL);
639         revs->no_walk = 1;
640         if (opts->action != REVERT)
641                 revs->reverse = 1;
643         argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
644         if (argc > 1)
645                 usage(*revert_or_cherry_pick_usage(opts));
647         if (prepare_revision_walk(revs))
648                 die(_("revision walk setup failed"));
650         if (!revs->commits)
651                 die(_("empty commit set passed"));
654 static void read_and_refresh_cache(struct replay_opts *opts)
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);
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)
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;
696 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
697                 struct replay_opts *opts)
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";
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;
713 static struct commit *parse_insn_line(char *start, struct replay_opts *opts)
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;
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;
732         q = strchr(p, ' ');
733         if (!q)
734                 return NULL;
735         q++;
737         strlcpy(sha1_abbrev, p, q - p);
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         }
750         if (get_sha1(sha1_abbrev, commit_sha1) < 0)
751                 return NULL;
753         return lookup_commit_reference(commit_sha1);
756 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
757                         struct replay_opts *opts)
759         struct commit_list **next = todo_list;
760         struct commit *commit;
761         char *p = buf;
762         int i;
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;
778 static void read_populate_todo(struct commit_list **todo_list,
779                         struct replay_opts *opts)
781         const char *todo_file = git_path(SEQ_TODO_FILE);
782         struct strbuf buf = STRBUF_INIT;
783         int fd, res;
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);
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);
801 static int populate_opts_cb(const char *key, const char *value, void *data)
803         struct replay_opts *opts = data;
804         int error_flag = 1;
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);
828         if (!error_flag)
829                 return error(_("Invalid value for %s: %s"), key, value);
831         return 0;
834 static void read_populate_opts(struct replay_opts **opts_ptr)
836         const char *opts_file = git_path(SEQ_OPTS_FILE);
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);
844 static void walk_revs_populate_todo(struct commit_list **todo_list,
845                                 struct replay_opts *opts)
847         struct rev_info revs;
848         struct commit *commit;
849         struct commit_list **next;
851         prepare_revs(&revs, opts);
853         next = todo_list;
854         while ((commit = get_revision(&revs)))
855                 next = commit_list_append(commit, next);
858 static int create_seq_dir(void)
860         const char *seq_dir = git_path(SEQ_DIR);
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;
872 static void save_head(const char *head)
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;
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);
887 static int reset_for_rollback(const unsigned char *sha1)
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);
897 static int rollback_single_pick(void)
899         unsigned char head_sha1[20];
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);
911 static int sequencer_rollback(struct replay_opts *opts)
913         const char *filename;
914         FILE *f;
915         unsigned char sha1[20];
916         struct strbuf buf = STRBUF_INIT;
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                 goto fail;
935         }
936         if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
937                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
938                         filename);
939                 goto fail;
940         }
941         if (reset_for_rollback(sha1))
942                 goto fail;
943         strbuf_release(&buf);
944         fclose(f);
945         return 0;
946 fail:
947         strbuf_release(&buf);
948         fclose(f);
949         return -1;
952 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
954         const char *todo_file = git_path(SEQ_TODO_FILE);
955         static struct lock_file todo_lock;
956         struct strbuf buf = STRBUF_INIT;
957         int fd;
959         fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
960         if (format_todo(&buf, todo_list, opts) < 0)
961                 die(_("Could not format %s."), todo_file);
962         if (write_in_full(fd, buf.buf, buf.len) < 0) {
963                 strbuf_release(&buf);
964                 die_errno(_("Could not write to %s"), todo_file);
965         }
966         if (commit_lock_file(&todo_lock) < 0) {
967                 strbuf_release(&buf);
968                 die(_("Error wrapping up %s."), todo_file);
969         }
970         strbuf_release(&buf);
973 static void save_opts(struct replay_opts *opts)
975         const char *opts_file = git_path(SEQ_OPTS_FILE);
977         if (opts->no_commit)
978                 git_config_set_in_file(opts_file, "options.no-commit", "true");
979         if (opts->edit)
980                 git_config_set_in_file(opts_file, "options.edit", "true");
981         if (opts->signoff)
982                 git_config_set_in_file(opts_file, "options.signoff", "true");
983         if (opts->record_origin)
984                 git_config_set_in_file(opts_file, "options.record-origin", "true");
985         if (opts->allow_ff)
986                 git_config_set_in_file(opts_file, "options.allow-ff", "true");
987         if (opts->mainline) {
988                 struct strbuf buf = STRBUF_INIT;
989                 strbuf_addf(&buf, "%d", opts->mainline);
990                 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
991                 strbuf_release(&buf);
992         }
993         if (opts->strategy)
994                 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
995         if (opts->xopts) {
996                 int i;
997                 for (i = 0; i < opts->xopts_nr; i++)
998                         git_config_set_multivar_in_file(opts_file,
999                                                         "options.strategy-option",
1000                                                         opts->xopts[i], "^$", 0);
1001         }
1004 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1006         struct commit_list *cur;
1007         int res;
1009         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1010         if (opts->allow_ff)
1011                 assert(!(opts->signoff || opts->no_commit ||
1012                                 opts->record_origin || opts->edit));
1013         read_and_refresh_cache(opts);
1015         for (cur = todo_list; cur; cur = cur->next) {
1016                 save_todo(cur, opts);
1017                 res = do_pick_commit(cur->item, opts);
1018                 if (res) {
1019                         if (!cur->next)
1020                                 /*
1021                                  * An error was encountered while
1022                                  * picking the last commit; the
1023                                  * sequencer state is useless now --
1024                                  * the user simply needs to resolve
1025                                  * the conflict and commit
1026                                  */
1027                                 remove_sequencer_state(0);
1028                         return res;
1029                 }
1030         }
1032         /*
1033          * Sequence of picks finished successfully; cleanup by
1034          * removing the .git/sequencer directory
1035          */
1036         remove_sequencer_state(1);
1037         return 0;
1040 static int pick_revisions(struct replay_opts *opts)
1042         struct commit_list *todo_list = NULL;
1043         unsigned char sha1[20];
1045         read_and_refresh_cache(opts);
1047         /*
1048          * Decide what to do depending on the arguments; a fresh
1049          * cherry-pick should be handled differently from an existing
1050          * one that is being continued
1051          */
1052         if (opts->subcommand == REPLAY_REMOVE_STATE) {
1053                 remove_sequencer_state(1);
1054                 return 0;
1055         }
1056         if (opts->subcommand == REPLAY_ROLLBACK)
1057                 return sequencer_rollback(opts);
1058         if (opts->subcommand == REPLAY_CONTINUE) {
1059                 if (!file_exists(git_path(SEQ_TODO_FILE)))
1060                         return error(_("No %s in progress"), action_name(opts));
1061                 read_populate_opts(&opts);
1062                 read_populate_todo(&todo_list, opts);
1064                 /* Verify that the conflict has been resolved */
1065                 if (!index_differs_from("HEAD", 0))
1066                         todo_list = todo_list->next;
1067                 return pick_commits(todo_list, opts);
1068         }
1070         /*
1071          * Start a new cherry-pick/ revert sequence; but
1072          * first, make sure that an existing one isn't in
1073          * progress
1074          */
1076         walk_revs_populate_todo(&todo_list, opts);
1077         if (create_seq_dir() < 0)
1078                 return -1;
1079         if (get_sha1("HEAD", sha1)) {
1080                 if (opts->action == REVERT)
1081                         return error(_("Can't revert as initial commit"));
1082                 return error(_("Can't cherry-pick into empty head"));
1083         }
1084         save_head(sha1_to_hex(sha1));
1085         save_opts(opts);
1086         return pick_commits(todo_list, opts);
1089 int cmd_revert(int argc, const char **argv, const char *prefix)
1091         struct replay_opts opts;
1092         int res;
1094         memset(&opts, 0, sizeof(opts));
1095         if (isatty(0))
1096                 opts.edit = 1;
1097         opts.action = REVERT;
1098         git_config(git_default_config, NULL);
1099         parse_args(argc, argv, &opts);
1100         res = pick_revisions(&opts);
1101         if (res < 0)
1102                 die(_("revert failed"));
1103         return res;
1106 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1108         struct replay_opts opts;
1109         int res;
1111         memset(&opts, 0, sizeof(opts));
1112         opts.action = CHERRY_PICK;
1113         git_config(git_default_config, NULL);
1114         parse_args(argc, argv, &opts);
1115         res = pick_revisions(&opts);
1116         if (res < 0)
1117                 die(_("cherry-pick failed"));
1118         return res;