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