revert: add missing va_end
[git/mingw.git] / builtin / revert.c
bloba022eadda37122b7916b063fbdd184b1d6435e7b
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"
20 * This implements the builtins revert and cherry-pick.
22 * Copyright (c) 2007 Johannes E. Schindelin
24 * Based on git-revert.sh, which is
26 * Copyright (c) 2005 Linus Torvalds
27 * Copyright (c) 2005 Junio C Hamano
30 static const char * const revert_usage[] = {
31 "git revert [options] <commit-ish>",
32 "git revert <subcommand>",
33 NULL
36 static const char * const cherry_pick_usage[] = {
37 "git cherry-pick [options] <commit-ish>",
38 "git cherry-pick <subcommand>",
39 NULL
42 enum replay_action { REVERT, CHERRY_PICK };
43 enum replay_subcommand {
44 REPLAY_NONE,
45 REPLAY_REMOVE_STATE,
46 REPLAY_CONTINUE,
47 REPLAY_ROLLBACK
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;
72 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
74 static const char *action_name(const struct replay_opts *opts)
76 return opts->action == REVERT ? "revert" : "cherry-pick";
79 static char *get_encoding(const char *message);
81 static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
83 return opts->action == REVERT ? revert_usage : cherry_pick_usage;
86 static int option_parse_x(const struct option *opt,
87 const char *arg, int unset)
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;
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;
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;
126 if (opt1) {
127 while ((opt2 = va_arg(ap, const char *))) {
128 if (va_arg(ap, int))
129 break;
132 va_end(ap);
134 if (opt1 && opt2)
135 die(_("%s: %s cannot be used with %s"), me, opt1, opt2);
138 static void parse_args(int argc, const char **argv, struct replay_opts *opts)
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(),
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(),
169 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
170 die(_("program error"));
173 opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
174 PARSE_OPT_KEEP_ARGV0 |
175 PARSE_OPT_KEEP_UNKNOWN);
177 /* Check for incompatible subcommands */
178 verify_opt_mutually_compatible(me,
179 "--quit", remove_state,
180 "--continue", contin,
181 "--abort", rollback,
182 NULL);
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;
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";
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);
217 else if (opts->commit_argc < 2)
218 usage_with_options(usage_str, options);
220 if (opts->allow_ff)
221 verify_opt_compatible(me, "--ff",
222 "--signoff", opts->signoff,
223 "--no-commit", opts->no_commit,
224 "-x", opts->record_origin,
225 "--edit", opts->edit,
226 NULL);
227 opts->commit_argv = argv;
230 struct commit_message {
231 char *parent_label;
232 const char *label;
233 const char *subject;
234 char *reencoded_message;
235 const char *message;
238 static int get_message(struct commit *commit, struct commit_message *out)
240 const char *encoding;
241 const char *abbrev, *subject;
242 int abbrev_len, subject_len;
243 char *q;
245 if (!commit->buffer)
246 return -1;
247 encoding = get_encoding(commit->buffer);
248 if (!encoding)
249 encoding = "UTF-8";
250 if (!git_commit_encoding)
251 git_commit_encoding = "UTF-8";
253 out->reencoded_message = NULL;
254 out->message = commit->buffer;
255 if (strcmp(encoding, git_commit_encoding))
256 out->reencoded_message = reencode_string(commit->buffer,
257 git_commit_encoding, encoding);
258 if (out->reencoded_message)
259 out->message = out->reencoded_message;
261 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
262 abbrev_len = strlen(abbrev);
264 subject_len = find_commit_subject(out->message, &subject);
266 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
267 strlen("... ") + subject_len + 1);
268 q = out->parent_label;
269 q = mempcpy(q, "parent of ", strlen("parent of "));
270 out->label = q;
271 q = mempcpy(q, abbrev, abbrev_len);
272 q = mempcpy(q, "... ", strlen("... "));
273 out->subject = q;
274 q = mempcpy(q, subject, subject_len);
275 *q = '\0';
276 return 0;
279 static void free_message(struct commit_message *msg)
281 free(msg->parent_label);
282 free(msg->reencoded_message);
285 static char *get_encoding(const char *message)
287 const char *p = message, *eol;
289 while (*p && *p != '\n') {
290 for (eol = p + 1; *eol && *eol != '\n'; eol++)
291 ; /* do nothing */
292 if (!prefixcmp(p, "encoding ")) {
293 char *result = xmalloc(eol - 8 - p);
294 strlcpy(result, p + 9, eol - 8 - p);
295 return result;
297 p = eol;
298 if (*p == '\n')
299 p++;
301 return NULL;
304 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
306 const char *filename;
307 int fd;
308 struct strbuf buf = STRBUF_INIT;
310 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
312 filename = git_path("%s", pseudoref);
313 fd = open(filename, O_WRONLY | O_CREAT, 0666);
314 if (fd < 0)
315 die_errno(_("Could not open '%s' for writing"), filename);
316 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
317 die_errno(_("Could not write to '%s'"), filename);
318 strbuf_release(&buf);
321 static void print_advice(int show_hint)
323 char *msg = getenv("GIT_CHERRY_PICK_HELP");
325 if (msg) {
326 fprintf(stderr, "%s\n", msg);
328 * A conflict has occured but the porcelain
329 * (typically rebase --interactive) wants to take care
330 * of the commit itself so remove CHERRY_PICK_HEAD
332 unlink(git_path("CHERRY_PICK_HEAD"));
333 return;
336 if (show_hint) {
337 advise("after resolving the conflicts, mark the corrected paths");
338 advise("with 'git add <paths>' or 'git rm <paths>'");
339 advise("and commit the result with 'git commit'");
343 static void write_message(struct strbuf *msgbuf, const char *filename)
345 static struct lock_file msg_file;
347 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
348 LOCK_DIE_ON_ERROR);
349 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
350 die_errno(_("Could not write to %s"), filename);
351 strbuf_release(msgbuf);
352 if (commit_lock_file(&msg_file) < 0)
353 die(_("Error wrapping up %s"), filename);
356 static struct tree *empty_tree(void)
358 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
361 static int error_dirty_index(struct replay_opts *opts)
363 if (read_cache_unmerged())
364 return error_resolve_conflict(action_name(opts));
366 /* Different translation strings for cherry-pick and revert */
367 if (opts->action == CHERRY_PICK)
368 error(_("Your local changes would be overwritten by cherry-pick."));
369 else
370 error(_("Your local changes would be overwritten by revert."));
372 if (advice_commit_before_merge)
373 advise(_("Commit your changes or stash them to proceed."));
374 return -1;
377 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
379 struct ref_lock *ref_lock;
381 read_cache();
382 if (checkout_fast_forward(from, to))
383 exit(1); /* the callee should have complained already */
384 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
385 return write_ref_sha1(ref_lock, to, "cherry-pick");
388 static int do_recursive_merge(struct commit *base, struct commit *next,
389 const char *base_label, const char *next_label,
390 unsigned char *head, struct strbuf *msgbuf,
391 struct replay_opts *opts)
393 struct merge_options o;
394 struct tree *result, *next_tree, *base_tree, *head_tree;
395 int clean, index_fd;
396 const char **xopt;
397 static struct lock_file index_lock;
399 index_fd = hold_locked_index(&index_lock, 1);
401 read_cache();
403 init_merge_options(&o);
404 o.ancestor = base ? base_label : "(empty tree)";
405 o.branch1 = "HEAD";
406 o.branch2 = next ? next_label : "(empty tree)";
408 head_tree = parse_tree_indirect(head);
409 next_tree = next ? next->tree : empty_tree();
410 base_tree = base ? base->tree : empty_tree();
412 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
413 parse_merge_opt(&o, *xopt);
415 clean = merge_trees(&o,
416 head_tree,
417 next_tree, base_tree, &result);
419 if (active_cache_changed &&
420 (write_cache(index_fd, active_cache, active_nr) ||
421 commit_locked_index(&index_lock)))
422 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
423 die(_("%s: Unable to write new index file"), action_name(opts));
424 rollback_lock_file(&index_lock);
426 if (!clean) {
427 int i;
428 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
429 for (i = 0; i < active_nr;) {
430 struct cache_entry *ce = active_cache[i++];
431 if (ce_stage(ce)) {
432 strbuf_addch(msgbuf, '\t');
433 strbuf_addstr(msgbuf, ce->name);
434 strbuf_addch(msgbuf, '\n');
435 while (i < active_nr && !strcmp(ce->name,
436 active_cache[i]->name))
437 i++;
442 return !clean;
446 * If we are cherry-pick, and if the merge did not result in
447 * hand-editing, we will hit this commit and inherit the original
448 * author date and name.
449 * If we are revert, or if our cherry-pick results in a hand merge,
450 * we had better say that the current user is responsible for that.
452 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
454 /* 6 is max possible length of our args array including NULL */
455 const char *args[6];
456 int i = 0;
458 args[i++] = "commit";
459 args[i++] = "-n";
460 if (opts->signoff)
461 args[i++] = "-s";
462 if (!opts->edit) {
463 args[i++] = "-F";
464 args[i++] = defmsg;
466 args[i] = NULL;
468 return run_command_v_opt(args, RUN_GIT_CMD);
471 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
473 unsigned char head[20];
474 struct commit *base, *next, *parent;
475 const char *base_label, *next_label;
476 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
477 char *defmsg = NULL;
478 struct strbuf msgbuf = STRBUF_INIT;
479 int res;
481 if (opts->no_commit) {
483 * We do not intend to commit immediately. We just want to
484 * merge the differences in, so let's compute the tree
485 * that represents the "current" state for merge-recursive
486 * to work on.
488 if (write_cache_as_tree(head, 0, NULL))
489 die (_("Your index file is unmerged."));
490 } else {
491 if (get_sha1("HEAD", head))
492 return error(_("You do not have a valid HEAD"));
493 if (index_differs_from("HEAD", 0))
494 return error_dirty_index(opts);
496 discard_cache();
498 if (!commit->parents) {
499 parent = NULL;
501 else if (commit->parents->next) {
502 /* Reverting or cherry-picking a merge commit */
503 int cnt;
504 struct commit_list *p;
506 if (!opts->mainline)
507 return error(_("Commit %s is a merge but no -m option was given."),
508 sha1_to_hex(commit->object.sha1));
510 for (cnt = 1, p = commit->parents;
511 cnt != opts->mainline && p;
512 cnt++)
513 p = p->next;
514 if (cnt != opts->mainline || !p)
515 return error(_("Commit %s does not have parent %d"),
516 sha1_to_hex(commit->object.sha1), opts->mainline);
517 parent = p->item;
518 } else if (0 < opts->mainline)
519 return error(_("Mainline was specified but commit %s is not a merge."),
520 sha1_to_hex(commit->object.sha1));
521 else
522 parent = commit->parents->item;
524 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
525 return fast_forward_to(commit->object.sha1, head);
527 if (parent && parse_commit(parent) < 0)
528 /* TRANSLATORS: The first %s will be "revert" or
529 "cherry-pick", the second %s a SHA1 */
530 return error(_("%s: cannot parse parent commit %s"),
531 action_name(opts), sha1_to_hex(parent->object.sha1));
533 if (get_message(commit, &msg) != 0)
534 return error(_("Cannot get commit message for %s"),
535 sha1_to_hex(commit->object.sha1));
538 * "commit" is an existing commit. We would want to apply
539 * the difference it introduces since its first parent "prev"
540 * on top of the current HEAD if we are cherry-pick. Or the
541 * reverse of it if we are revert.
544 defmsg = git_pathdup("MERGE_MSG");
546 if (opts->action == REVERT) {
547 base = commit;
548 base_label = msg.label;
549 next = parent;
550 next_label = msg.parent_label;
551 strbuf_addstr(&msgbuf, "Revert \"");
552 strbuf_addstr(&msgbuf, msg.subject);
553 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
554 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
556 if (commit->parents && commit->parents->next) {
557 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
558 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
560 strbuf_addstr(&msgbuf, ".\n");
561 } else {
562 const char *p;
564 base = parent;
565 base_label = msg.parent_label;
566 next = commit;
567 next_label = msg.label;
570 * Append the commit log message to msgbuf; it starts
571 * after the tree, parent, author, committer
572 * information followed by "\n\n".
574 p = strstr(msg.message, "\n\n");
575 if (p) {
576 p += 2;
577 strbuf_addstr(&msgbuf, p);
580 if (opts->record_origin) {
581 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
582 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
583 strbuf_addstr(&msgbuf, ")\n");
587 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
588 res = do_recursive_merge(base, next, base_label, next_label,
589 head, &msgbuf, opts);
590 write_message(&msgbuf, defmsg);
591 } else {
592 struct commit_list *common = NULL;
593 struct commit_list *remotes = NULL;
595 write_message(&msgbuf, defmsg);
597 commit_list_insert(base, &common);
598 commit_list_insert(next, &remotes);
599 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
600 common, sha1_to_hex(head), remotes);
601 free_commit_list(common);
602 free_commit_list(remotes);
606 * If the merge was clean or if it failed due to conflict, we write
607 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
608 * However, if the merge did not even start, then we don't want to
609 * write it at all.
611 if (opts->action == CHERRY_PICK && !opts->no_commit && (res == 0 || res == 1))
612 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
613 if (opts->action == REVERT && ((opts->no_commit && res == 0) || res == 1))
614 write_cherry_pick_head(commit, "REVERT_HEAD");
616 if (res) {
617 error(opts->action == REVERT
618 ? _("could not revert %s... %s")
619 : _("could not apply %s... %s"),
620 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
621 msg.subject);
622 print_advice(res == 1);
623 rerere(opts->allow_rerere_auto);
624 } else {
625 if (!opts->no_commit)
626 res = run_git_commit(defmsg, opts);
629 free_message(&msg);
630 free(defmsg);
632 return res;
635 static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
637 int argc;
639 init_revisions(revs, NULL);
640 revs->no_walk = 1;
641 if (opts->action != REVERT)
642 revs->reverse = 1;
644 argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
645 if (argc > 1)
646 usage(*revert_or_cherry_pick_usage(opts));
648 if (prepare_revision_walk(revs))
649 die(_("revision walk setup failed"));
651 if (!revs->commits)
652 die(_("empty commit set passed"));
655 static void read_and_refresh_cache(struct replay_opts *opts)
657 static struct lock_file index_lock;
658 int index_fd = hold_locked_index(&index_lock, 0);
659 if (read_index_preload(&the_index, NULL) < 0)
660 die(_("git %s: failed to read the index"), action_name(opts));
661 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
662 if (the_index.cache_changed) {
663 if (write_index(&the_index, index_fd) ||
664 commit_locked_index(&index_lock))
665 die(_("git %s: failed to refresh the index"), action_name(opts));
667 rollback_lock_file(&index_lock);
671 * Append a commit to the end of the commit_list.
673 * next starts by pointing to the variable that holds the head of an
674 * empty commit_list, and is updated to point to the "next" field of
675 * the last item on the list as new commits are appended.
677 * Usage example:
679 * struct commit_list *list;
680 * struct commit_list **next = &list;
682 * next = commit_list_append(c1, next);
683 * next = commit_list_append(c2, next);
684 * assert(commit_list_count(list) == 2);
685 * return list;
687 static struct commit_list **commit_list_append(struct commit *commit,
688 struct commit_list **next)
690 struct commit_list *new = xmalloc(sizeof(struct commit_list));
691 new->item = commit;
692 *next = new;
693 new->next = NULL;
694 return &new->next;
697 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
698 struct replay_opts *opts)
700 struct commit_list *cur = NULL;
701 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
702 const char *sha1_abbrev = NULL;
703 const char *action_str = opts->action == REVERT ? "revert" : "pick";
705 for (cur = todo_list; cur; cur = cur->next) {
706 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
707 if (get_message(cur->item, &msg))
708 return error(_("Cannot get commit message for %s"), sha1_abbrev);
709 strbuf_addf(buf, "%s %s %s\n", action_str, sha1_abbrev, msg.subject);
711 return 0;
714 static struct commit *parse_insn_line(char *start, struct replay_opts *opts)
716 unsigned char commit_sha1[20];
717 char sha1_abbrev[40];
718 enum replay_action action;
719 int insn_len = 0;
720 char *p, *q;
722 if (!prefixcmp(start, "pick ")) {
723 action = CHERRY_PICK;
724 insn_len = strlen("pick");
725 p = start + insn_len + 1;
726 } else if (!prefixcmp(start, "revert ")) {
727 action = REVERT;
728 insn_len = strlen("revert");
729 p = start + insn_len + 1;
730 } else
731 return NULL;
733 q = strchr(p, ' ');
734 if (!q)
735 return NULL;
736 q++;
738 strlcpy(sha1_abbrev, p, q - p);
741 * Verify that the action matches up with the one in
742 * opts; we don't support arbitrary instructions
744 if (action != opts->action) {
745 const char *action_str;
746 action_str = action == REVERT ? "revert" : "cherry-pick";
747 error(_("Cannot %s during a %s"), action_str, action_name(opts));
748 return NULL;
751 if (get_sha1(sha1_abbrev, commit_sha1) < 0)
752 return NULL;
754 return lookup_commit_reference(commit_sha1);
757 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
758 struct replay_opts *opts)
760 struct commit_list **next = todo_list;
761 struct commit *commit;
762 char *p = buf;
763 int i;
765 for (i = 1; *p; i++) {
766 commit = parse_insn_line(p, opts);
767 if (!commit)
768 return error(_("Could not parse line %d."), i);
769 next = commit_list_append(commit, next);
770 p = strchrnul(p, '\n');
771 if (*p)
772 p++;
774 if (!*todo_list)
775 return error(_("No commits parsed."));
776 return 0;
779 static void read_populate_todo(struct commit_list **todo_list,
780 struct replay_opts *opts)
782 const char *todo_file = git_path(SEQ_TODO_FILE);
783 struct strbuf buf = STRBUF_INIT;
784 int fd, res;
786 fd = open(todo_file, O_RDONLY);
787 if (fd < 0)
788 die_errno(_("Could not open %s"), todo_file);
789 if (strbuf_read(&buf, fd, 0) < 0) {
790 close(fd);
791 strbuf_release(&buf);
792 die(_("Could not read %s."), todo_file);
794 close(fd);
796 res = parse_insn_buffer(buf.buf, todo_list, opts);
797 strbuf_release(&buf);
798 if (res)
799 die(_("Unusable instruction sheet: %s"), todo_file);
802 static int populate_opts_cb(const char *key, const char *value, void *data)
804 struct replay_opts *opts = data;
805 int error_flag = 1;
807 if (!value)
808 error_flag = 0;
809 else if (!strcmp(key, "options.no-commit"))
810 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
811 else if (!strcmp(key, "options.edit"))
812 opts->edit = git_config_bool_or_int(key, value, &error_flag);
813 else if (!strcmp(key, "options.signoff"))
814 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
815 else if (!strcmp(key, "options.record-origin"))
816 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
817 else if (!strcmp(key, "options.allow-ff"))
818 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
819 else if (!strcmp(key, "options.mainline"))
820 opts->mainline = git_config_int(key, value);
821 else if (!strcmp(key, "options.strategy"))
822 git_config_string(&opts->strategy, key, value);
823 else if (!strcmp(key, "options.strategy-option")) {
824 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
825 opts->xopts[opts->xopts_nr++] = xstrdup(value);
826 } else
827 return error(_("Invalid key: %s"), key);
829 if (!error_flag)
830 return error(_("Invalid value for %s: %s"), key, value);
832 return 0;
835 static void read_populate_opts(struct replay_opts **opts_ptr)
837 const char *opts_file = git_path(SEQ_OPTS_FILE);
839 if (!file_exists(opts_file))
840 return;
841 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
842 die(_("Malformed options sheet: %s"), opts_file);
845 static void walk_revs_populate_todo(struct commit_list **todo_list,
846 struct replay_opts *opts)
848 struct rev_info revs;
849 struct commit *commit;
850 struct commit_list **next;
852 prepare_revs(&revs, opts);
854 next = todo_list;
855 while ((commit = get_revision(&revs)))
856 next = commit_list_append(commit, next);
859 static int create_seq_dir(void)
861 const char *seq_dir = git_path(SEQ_DIR);
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;
868 else if (mkdir(seq_dir, 0777) < 0)
869 die_errno(_("Could not create sequencer directory %s"), seq_dir);
870 return 0;
873 static void save_head(const char *head)
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;
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);
888 static int reset_for_rollback(const unsigned char *sha1)
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);
898 static int rollback_single_pick(void)
900 unsigned char head_sha1[20];
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);
912 static int sequencer_rollback(struct replay_opts *opts)
914 const char *filename;
915 FILE *f;
916 unsigned char sha1[20];
917 struct strbuf buf = STRBUF_INIT;
919 filename = git_path(SEQ_HEAD_FILE);
920 f = fopen(filename, "r");
921 if (!f && errno == ENOENT) {
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.
927 return rollback_single_pick();
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;
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;
944 if (reset_for_rollback(sha1))
945 goto fail;
946 remove_sequencer_state(1);
947 strbuf_release(&buf);
948 return 0;
949 fail:
950 strbuf_release(&buf);
951 return -1;
954 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
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;
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);
968 if (commit_lock_file(&todo_lock) < 0) {
969 strbuf_release(&buf);
970 die(_("Error wrapping up %s."), todo_file);
972 strbuf_release(&buf);
975 static void save_opts(struct replay_opts *opts)
977 const char *opts_file = git_path(SEQ_OPTS_FILE);
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);
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);
1006 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1008 struct commit_list *cur;
1009 int res;
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);
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 if (!cur->next)
1023 * An error was encountered while
1024 * picking the last commit; the
1025 * sequencer state is useless now --
1026 * the user simply needs to resolve
1027 * the conflict and commit
1029 remove_sequencer_state(0);
1030 return res;
1035 * Sequence of picks finished successfully; cleanup by
1036 * removing the .git/sequencer directory
1038 remove_sequencer_state(1);
1039 return 0;
1042 static int pick_revisions(struct replay_opts *opts)
1044 struct commit_list *todo_list = NULL;
1045 unsigned char sha1[20];
1047 read_and_refresh_cache(opts);
1050 * Decide what to do depending on the arguments; a fresh
1051 * cherry-pick should be handled differently from an existing
1052 * one that is being continued
1054 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1055 remove_sequencer_state(1);
1056 return 0;
1058 if (opts->subcommand == REPLAY_ROLLBACK)
1059 return sequencer_rollback(opts);
1060 if (opts->subcommand == REPLAY_CONTINUE) {
1061 if (!file_exists(git_path(SEQ_TODO_FILE)))
1062 return error(_("No %s in progress"), action_name(opts));
1063 read_populate_opts(&opts);
1064 read_populate_todo(&todo_list, opts);
1066 /* Verify that the conflict has been resolved */
1067 if (!index_differs_from("HEAD", 0))
1068 todo_list = todo_list->next;
1069 return pick_commits(todo_list, opts);
1073 * Start a new cherry-pick/ revert sequence; but
1074 * first, make sure that an existing one isn't in
1075 * progress
1078 walk_revs_populate_todo(&todo_list, opts);
1079 if (create_seq_dir() < 0)
1080 return -1;
1081 if (get_sha1("HEAD", sha1)) {
1082 if (opts->action == REVERT)
1083 return error(_("Can't revert as initial commit"));
1084 return error(_("Can't cherry-pick into empty head"));
1086 save_head(sha1_to_hex(sha1));
1087 save_opts(opts);
1088 return pick_commits(todo_list, opts);
1091 int cmd_revert(int argc, const char **argv, const char *prefix)
1093 struct replay_opts opts;
1094 int res;
1096 memset(&opts, 0, sizeof(opts));
1097 if (isatty(0))
1098 opts.edit = 1;
1099 opts.action = REVERT;
1100 git_config(git_default_config, NULL);
1101 parse_args(argc, argv, &opts);
1102 res = pick_revisions(&opts);
1103 if (res < 0)
1104 die(_("revert failed"));
1105 return res;
1108 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1110 struct replay_opts opts;
1111 int res;
1113 memset(&opts, 0, sizeof(opts));
1114 opts.action = CHERRY_PICK;
1115 git_config(git_default_config, NULL);
1116 parse_args(argc, argv, &opts);
1117 res = pick_revisions(&opts);
1118 if (res < 0)
1119 die(_("cherry-pick failed"));
1120 return res;