submodule: Use cat instead of echo to avoid DOS line-endings
[git/dscho.git] / builtin / revert.c
blobe447449228925819c4400ae6897095133b9d0445
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_subcommand {
43 REPLAY_NONE,
44 REPLAY_REMOVE_STATE,
45 REPLAY_CONTINUE,
46 REPLAY_ROLLBACK
49 struct replay_opts {
50 enum replay_action action;
51 enum replay_subcommand subcommand;
53 /* Boolean options */
54 int edit;
55 int record_origin;
56 int no_commit;
57 int signoff;
58 int allow_ff;
59 int allow_rerere_auto;
61 int mainline;
63 /* Merge strategy */
64 const char *strategy;
65 const char **xopts;
66 size_t xopts_nr, xopts_alloc;
68 /* Only used by REPLAY_NONE */
69 struct rev_info *revs;
72 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
74 static const char *action_name(const struct replay_opts *opts)
76 return opts->action == REPLAY_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 == REPLAY_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;
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(),
162 if (opts->action == REPLAY_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(),
168 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
169 die(_("program error"));
172 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";
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);
216 if (opts->allow_ff)
217 verify_opt_compatible(me, "--ff",
218 "--signoff", opts->signoff,
219 "--no-commit", opts->no_commit,
220 "-x", opts->record_origin,
221 "--edit", opts->edit,
222 NULL);
224 if (opts->subcommand == REPLAY_NONE) {
225 opts->revs = xmalloc(sizeof(*opts->revs));
226 init_revisions(opts->revs, NULL);
227 opts->revs->no_walk = 1;
228 if (argc < 2)
229 usage_with_options(usage_str, options);
230 argc = setup_revisions(argc, argv, opts->revs, NULL);
231 } else
232 opts->revs = NULL;
234 /* Forbid stray command-line arguments */
235 if (argc > 1)
236 usage_with_options(usage_str, options);
239 struct commit_message {
240 char *parent_label;
241 const char *label;
242 const char *subject;
243 char *reencoded_message;
244 const char *message;
247 static int get_message(struct commit *commit, struct commit_message *out)
249 const char *encoding;
250 const char *abbrev, *subject;
251 int abbrev_len, subject_len;
252 char *q;
254 if (!commit->buffer)
255 return -1;
256 encoding = get_encoding(commit->buffer);
257 if (!encoding)
258 encoding = "UTF-8";
259 if (!git_commit_encoding)
260 git_commit_encoding = "UTF-8";
262 out->reencoded_message = NULL;
263 out->message = commit->buffer;
264 if (strcmp(encoding, git_commit_encoding))
265 out->reencoded_message = reencode_string(commit->buffer,
266 git_commit_encoding, encoding);
267 if (out->reencoded_message)
268 out->message = out->reencoded_message;
270 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
271 abbrev_len = strlen(abbrev);
273 subject_len = find_commit_subject(out->message, &subject);
275 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
276 strlen("... ") + subject_len + 1);
277 q = out->parent_label;
278 q = mempcpy(q, "parent of ", strlen("parent of "));
279 out->label = q;
280 q = mempcpy(q, abbrev, abbrev_len);
281 q = mempcpy(q, "... ", strlen("... "));
282 out->subject = q;
283 q = mempcpy(q, subject, subject_len);
284 *q = '\0';
285 return 0;
288 static void free_message(struct commit_message *msg)
290 free(msg->parent_label);
291 free(msg->reencoded_message);
294 static char *get_encoding(const char *message)
296 const char *p = message, *eol;
298 while (*p && *p != '\n') {
299 for (eol = p + 1; *eol && *eol != '\n'; eol++)
300 ; /* do nothing */
301 if (!prefixcmp(p, "encoding ")) {
302 char *result = xmalloc(eol - 8 - p);
303 strlcpy(result, p + 9, eol - 8 - p);
304 return result;
306 p = eol;
307 if (*p == '\n')
308 p++;
310 return NULL;
313 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
315 const char *filename;
316 int fd;
317 struct strbuf buf = STRBUF_INIT;
319 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
321 filename = git_path("%s", pseudoref);
322 fd = open(filename, O_WRONLY | O_CREAT, 0666);
323 if (fd < 0)
324 die_errno(_("Could not open '%s' for writing"), filename);
325 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
326 die_errno(_("Could not write to '%s'"), filename);
327 strbuf_release(&buf);
330 static void print_advice(int show_hint)
332 char *msg = getenv("GIT_CHERRY_PICK_HELP");
334 if (msg) {
335 fprintf(stderr, "%s\n", msg);
337 * A conflict has occured but the porcelain
338 * (typically rebase --interactive) wants to take care
339 * of the commit itself so remove CHERRY_PICK_HEAD
341 unlink(git_path("CHERRY_PICK_HEAD"));
342 return;
345 if (show_hint) {
346 advise("after resolving the conflicts, mark the corrected paths");
347 advise("with 'git add <paths>' or 'git rm <paths>'");
348 advise("and commit the result with 'git commit'");
352 static void write_message(struct strbuf *msgbuf, const char *filename)
354 static struct lock_file msg_file;
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);
365 static struct tree *empty_tree(void)
367 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
370 static int error_dirty_index(struct replay_opts *opts)
372 if (read_cache_unmerged())
373 return error_resolve_conflict(action_name(opts));
375 /* Different translation strings for cherry-pick and revert */
376 if (opts->action == REPLAY_PICK)
377 error(_("Your local changes would be overwritten by cherry-pick."));
378 else
379 error(_("Your local changes would be overwritten by revert."));
381 if (advice_commit_before_merge)
382 advise(_("Commit your changes or stash them to proceed."));
383 return -1;
386 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
388 struct ref_lock *ref_lock;
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");
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)
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;
408 index_fd = hold_locked_index(&index_lock, 1);
410 read_cache();
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)";
417 head_tree = parse_tree_indirect(head);
418 next_tree = next ? next->tree : empty_tree();
419 base_tree = base ? base->tree : empty_tree();
421 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
422 parse_merge_opt(&o, *xopt);
424 clean = merge_trees(&o,
425 head_tree,
426 next_tree, base_tree, &result);
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);
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++;
451 return !clean;
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.
461 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
463 /* 6 is max possible length of our args array including NULL */
464 const char *args[6];
465 int i = 0;
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;
475 args[i] = NULL;
477 return run_command_v_opt(args, RUN_GIT_CMD);
480 static int do_pick_commit(struct commit *commit, enum replay_action action,
481 struct replay_opts *opts)
483 unsigned char head[20];
484 struct commit *base, *next, *parent;
485 const char *base_label, *next_label;
486 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
487 char *defmsg = NULL;
488 struct strbuf msgbuf = STRBUF_INIT;
489 int res;
491 if (opts->no_commit) {
493 * We do not intend to commit immediately. We just want to
494 * merge the differences in, so let's compute the tree
495 * that represents the "current" state for merge-recursive
496 * to work on.
498 if (write_cache_as_tree(head, 0, NULL))
499 die (_("Your index file is unmerged."));
500 } else {
501 if (get_sha1("HEAD", head))
502 return error(_("You do not have a valid HEAD"));
503 if (index_differs_from("HEAD", 0))
504 return error_dirty_index(opts);
506 discard_cache();
508 if (!commit->parents) {
509 parent = NULL;
511 else if (commit->parents->next) {
512 /* Reverting or cherry-picking a merge commit */
513 int cnt;
514 struct commit_list *p;
516 if (!opts->mainline)
517 return error(_("Commit %s is a merge but no -m option was given."),
518 sha1_to_hex(commit->object.sha1));
520 for (cnt = 1, p = commit->parents;
521 cnt != opts->mainline && p;
522 cnt++)
523 p = p->next;
524 if (cnt != opts->mainline || !p)
525 return error(_("Commit %s does not have parent %d"),
526 sha1_to_hex(commit->object.sha1), opts->mainline);
527 parent = p->item;
528 } else if (0 < opts->mainline)
529 return error(_("Mainline was specified but commit %s is not a merge."),
530 sha1_to_hex(commit->object.sha1));
531 else
532 parent = commit->parents->item;
534 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
535 return fast_forward_to(commit->object.sha1, head);
537 if (parent && parse_commit(parent) < 0)
538 /* TRANSLATORS: The first %s will be "revert" or
539 "cherry-pick", the second %s a SHA1 */
540 return error(_("%s: cannot parse parent commit %s"),
541 action_name(opts), sha1_to_hex(parent->object.sha1));
543 if (get_message(commit, &msg) != 0)
544 return error(_("Cannot get commit message for %s"),
545 sha1_to_hex(commit->object.sha1));
548 * "commit" is an existing commit. We would want to apply
549 * the difference it introduces since its first parent "prev"
550 * on top of the current HEAD if we are cherry-pick. Or the
551 * reverse of it if we are revert.
554 defmsg = git_pathdup("MERGE_MSG");
556 if (action == REPLAY_REVERT) {
557 base = commit;
558 base_label = msg.label;
559 next = parent;
560 next_label = msg.parent_label;
561 strbuf_addstr(&msgbuf, "Revert \"");
562 strbuf_addstr(&msgbuf, msg.subject);
563 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
564 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
566 if (commit->parents && commit->parents->next) {
567 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
568 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
570 strbuf_addstr(&msgbuf, ".\n");
571 } else {
572 const char *p;
574 base = parent;
575 base_label = msg.parent_label;
576 next = commit;
577 next_label = msg.label;
580 * Append the commit log message to msgbuf; it starts
581 * after the tree, parent, author, committer
582 * information followed by "\n\n".
584 p = strstr(msg.message, "\n\n");
585 if (p) {
586 p += 2;
587 strbuf_addstr(&msgbuf, p);
590 if (opts->record_origin) {
591 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
592 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
593 strbuf_addstr(&msgbuf, ")\n");
597 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || action == REPLAY_REVERT) {
598 res = do_recursive_merge(base, next, base_label, next_label,
599 head, &msgbuf, opts);
600 write_message(&msgbuf, defmsg);
601 } else {
602 struct commit_list *common = NULL;
603 struct commit_list *remotes = NULL;
605 write_message(&msgbuf, defmsg);
607 commit_list_insert(base, &common);
608 commit_list_insert(next, &remotes);
609 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
610 common, sha1_to_hex(head), remotes);
611 free_commit_list(common);
612 free_commit_list(remotes);
616 * If the merge was clean or if it failed due to conflict, we write
617 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
618 * However, if the merge did not even start, then we don't want to
619 * write it at all.
621 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
622 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
623 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
624 write_cherry_pick_head(commit, "REVERT_HEAD");
626 if (res) {
627 error(action == REPLAY_REVERT
628 ? _("could not revert %s... %s")
629 : _("could not apply %s... %s"),
630 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
631 msg.subject);
632 print_advice(res == 1);
633 rerere(opts->allow_rerere_auto);
634 } else {
635 if (!opts->no_commit)
636 res = run_git_commit(defmsg, opts);
639 free_message(&msg);
640 free(defmsg);
642 return res;
645 static void prepare_revs(struct replay_opts *opts)
647 if (opts->action != REPLAY_REVERT)
648 opts->revs->reverse ^= 1;
650 if (prepare_revision_walk(opts->revs))
651 die(_("revision walk setup failed"));
653 if (!opts->revs->commits)
654 die(_("empty commit set passed"));
657 static void read_and_refresh_cache(struct replay_opts *opts)
659 static struct lock_file index_lock;
660 int index_fd = hold_locked_index(&index_lock, 0);
661 if (read_index_preload(&the_index, NULL) < 0)
662 die(_("git %s: failed to read the index"), action_name(opts));
663 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
664 if (the_index.cache_changed) {
665 if (write_index(&the_index, index_fd) ||
666 commit_locked_index(&index_lock))
667 die(_("git %s: failed to refresh the index"), action_name(opts));
669 rollback_lock_file(&index_lock);
673 * Append a commit to the end of the commit_list.
675 * next starts by pointing to the variable that holds the head of an
676 * empty commit_list, and is updated to point to the "next" field of
677 * the last item on the list as new commits are appended.
679 * Usage example:
681 * struct commit_list *list;
682 * struct commit_list **next = &list;
684 * next = commit_list_append(c1, next);
685 * next = commit_list_append(c2, next);
686 * assert(commit_list_count(list) == 2);
687 * return list;
689 static struct replay_insn_list **replay_insn_list_append(enum replay_action action,
690 struct commit *operand,
691 struct replay_insn_list **next)
693 struct replay_insn_list *new = xmalloc(sizeof(*new));
694 new->action = action;
695 new->operand = operand;
696 *next = new;
697 new->next = NULL;
698 return &new->next;
701 static int format_todo(struct strbuf *buf, struct replay_insn_list *todo_list)
703 struct replay_insn_list *cur;
705 for (cur = todo_list; cur; cur = cur->next) {
706 const char *sha1_abbrev, *action_str, *subject;
707 int subject_len;
709 action_str = cur->action == REPLAY_REVERT ? "revert" : "pick";
710 sha1_abbrev = find_unique_abbrev(cur->operand->object.sha1, DEFAULT_ABBREV);
711 subject_len = find_commit_subject(cur->operand->buffer, &subject);
712 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
713 subject_len, subject);
715 return 0;
718 static int parse_insn_line(char *bol, char *eol, struct replay_insn_list *item)
720 unsigned char commit_sha1[20];
721 char *end_of_object_name;
722 int saved, status;
724 if (!prefixcmp(bol, "pick ")) {
725 item->action = REPLAY_PICK;
726 bol += strlen("pick ");
727 } else if (!prefixcmp(bol, "revert ")) {
728 item->action = REPLAY_REVERT;
729 bol += strlen("revert ");
730 } else {
731 size_t len = strchrnul(bol, '\n') - bol;
732 if (len > 255)
733 len = 255;
734 return error(_("Unrecognized action: %.*s"), (int)len, bol);
737 end_of_object_name = bol + strcspn(bol, " \n");
738 saved = *end_of_object_name;
739 *end_of_object_name = '\0';
740 status = get_sha1(bol, commit_sha1);
741 *end_of_object_name = saved;
743 if (status < 0)
744 return error(_("Malformed object name: %s"), bol);
746 item->operand = lookup_commit_reference(commit_sha1);
747 if (!item->operand)
748 return error(_("Not a valid commit: %s"), bol);
750 item->next = NULL;
751 return 0;
754 static int parse_insn_buffer(char *buf, struct replay_insn_list **todo_list)
756 struct replay_insn_list **next = todo_list;
757 struct replay_insn_list item = {0, NULL, NULL};
758 char *p = buf;
759 int i;
761 for (i = 1; *p; i++) {
762 char *eol = strchrnul(p, '\n');
763 if (parse_insn_line(p, eol, &item) < 0)
764 return error(_("on line %d."), i);
765 next = replay_insn_list_append(item.action, item.operand, next);
766 p = *eol ? eol + 1 : eol;
768 if (!*todo_list)
769 return error(_("No commits parsed."));
770 return 0;
773 static void read_populate_todo(struct replay_insn_list **todo_list)
775 const char *todo_file = git_path(SEQ_TODO_FILE);
776 struct strbuf buf = STRBUF_INIT;
777 int fd, res;
779 fd = open(todo_file, O_RDONLY);
780 if (fd < 0)
781 die_errno(_("Could not open %s"), todo_file);
782 if (strbuf_read(&buf, fd, 0) < 0) {
783 close(fd);
784 strbuf_release(&buf);
785 die(_("Could not read %s."), todo_file);
787 close(fd);
789 res = parse_insn_buffer(buf.buf, todo_list);
790 strbuf_release(&buf);
791 if (res)
792 die(_("Unusable instruction sheet: %s"), todo_file);
795 static int populate_opts_cb(const char *key, const char *value, void *data)
797 struct replay_opts *opts = data;
798 int error_flag = 1;
800 if (!value)
801 error_flag = 0;
802 else if (!strcmp(key, "options.no-commit"))
803 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
804 else if (!strcmp(key, "options.edit"))
805 opts->edit = git_config_bool_or_int(key, value, &error_flag);
806 else if (!strcmp(key, "options.signoff"))
807 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
808 else if (!strcmp(key, "options.record-origin"))
809 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
810 else if (!strcmp(key, "options.allow-ff"))
811 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
812 else if (!strcmp(key, "options.mainline"))
813 opts->mainline = git_config_int(key, value);
814 else if (!strcmp(key, "options.strategy"))
815 git_config_string(&opts->strategy, key, value);
816 else if (!strcmp(key, "options.strategy-option")) {
817 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
818 opts->xopts[opts->xopts_nr++] = xstrdup(value);
819 } else
820 return error(_("Invalid key: %s"), key);
822 if (!error_flag)
823 return error(_("Invalid value for %s: %s"), key, value);
825 return 0;
828 static void read_populate_opts(struct replay_opts **opts_ptr)
830 const char *opts_file = git_path(SEQ_OPTS_FILE);
832 if (!file_exists(opts_file))
833 return;
834 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
835 die(_("Malformed options sheet: %s"), opts_file);
838 static void walk_revs_populate_todo(struct replay_insn_list **todo_list,
839 struct replay_opts *opts)
841 struct commit *commit;
842 struct replay_insn_list **next;
844 prepare_revs(opts);
846 next = todo_list;
847 while ((commit = get_revision(opts->revs)))
848 next = replay_insn_list_append(opts->action, commit, next);
851 static int create_seq_dir(void)
853 const char *seq_dir = git_path(SEQ_DIR);
855 if (file_exists(seq_dir)) {
856 error(_("a cherry-pick or revert is already in progress"));
857 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
858 return -1;
860 else if (mkdir(seq_dir, 0777) < 0)
861 die_errno(_("Could not create sequencer directory %s"), seq_dir);
862 return 0;
865 static void save_head(const char *head)
867 const char *head_file = git_path(SEQ_HEAD_FILE);
868 static struct lock_file head_lock;
869 struct strbuf buf = STRBUF_INIT;
870 int fd;
872 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
873 strbuf_addf(&buf, "%s\n", head);
874 if (write_in_full(fd, buf.buf, buf.len) < 0)
875 die_errno(_("Could not write to %s"), head_file);
876 if (commit_lock_file(&head_lock) < 0)
877 die(_("Error wrapping up %s."), head_file);
880 static int reset_for_rollback(const unsigned char *sha1)
882 const char *argv[4]; /* reset --merge <arg> + NULL */
883 argv[0] = "reset";
884 argv[1] = "--merge";
885 argv[2] = sha1_to_hex(sha1);
886 argv[3] = NULL;
887 return run_command_v_opt(argv, RUN_GIT_CMD);
890 static int rollback_single_pick(void)
892 unsigned char head_sha1[20];
894 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
895 !file_exists(git_path("REVERT_HEAD")))
896 return error(_("no cherry-pick or revert in progress"));
897 if (!resolve_ref("HEAD", head_sha1, 0, NULL))
898 return error(_("cannot resolve HEAD"));
899 if (is_null_sha1(head_sha1))
900 return error(_("cannot abort from a branch yet to be born"));
901 return reset_for_rollback(head_sha1);
904 static int sequencer_rollback(struct replay_opts *opts)
906 const char *filename;
907 FILE *f;
908 unsigned char sha1[20];
909 struct strbuf buf = STRBUF_INIT;
911 filename = git_path(SEQ_HEAD_FILE);
912 f = fopen(filename, "r");
913 if (!f && errno == ENOENT) {
915 * There is no multiple-cherry-pick in progress.
916 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
917 * a single-cherry-pick in progress, abort that.
919 return rollback_single_pick();
921 if (!f)
922 return error(_("cannot open %s: %s"), filename,
923 strerror(errno));
924 if (strbuf_getline(&buf, f, '\n')) {
925 error(_("cannot read %s: %s"), filename, ferror(f) ?
926 strerror(errno) : _("unexpected end of file"));
927 fclose(f);
928 goto fail;
930 fclose(f);
931 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
932 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
933 filename);
934 goto fail;
936 if (reset_for_rollback(sha1))
937 goto fail;
938 remove_sequencer_state(1);
939 strbuf_release(&buf);
940 return 0;
941 fail:
942 strbuf_release(&buf);
943 return -1;
946 static void save_todo(struct replay_insn_list *todo_list)
948 const char *todo_file = git_path(SEQ_TODO_FILE);
949 static struct lock_file todo_lock;
950 struct strbuf buf = STRBUF_INIT;
951 int fd;
953 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
954 if (format_todo(&buf, todo_list) < 0)
955 die(_("Could not format %s."), todo_file);
956 if (write_in_full(fd, buf.buf, buf.len) < 0) {
957 strbuf_release(&buf);
958 die_errno(_("Could not write to %s"), todo_file);
960 if (commit_lock_file(&todo_lock) < 0) {
961 strbuf_release(&buf);
962 die(_("Error wrapping up %s."), todo_file);
964 strbuf_release(&buf);
967 static void save_opts(struct replay_opts *opts)
969 const char *opts_file = git_path(SEQ_OPTS_FILE);
971 if (opts->no_commit)
972 git_config_set_in_file(opts_file, "options.no-commit", "true");
973 if (opts->edit)
974 git_config_set_in_file(opts_file, "options.edit", "true");
975 if (opts->signoff)
976 git_config_set_in_file(opts_file, "options.signoff", "true");
977 if (opts->record_origin)
978 git_config_set_in_file(opts_file, "options.record-origin", "true");
979 if (opts->allow_ff)
980 git_config_set_in_file(opts_file, "options.allow-ff", "true");
981 if (opts->mainline) {
982 struct strbuf buf = STRBUF_INIT;
983 strbuf_addf(&buf, "%d", opts->mainline);
984 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
985 strbuf_release(&buf);
987 if (opts->strategy)
988 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
989 if (opts->xopts) {
990 int i;
991 for (i = 0; i < opts->xopts_nr; i++)
992 git_config_set_multivar_in_file(opts_file,
993 "options.strategy-option",
994 opts->xopts[i], "^$", 0);
998 static int pick_commits(struct replay_insn_list *todo_list,
999 struct replay_opts *opts)
1001 struct replay_insn_list *cur;
1002 int res;
1004 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1005 if (opts->allow_ff)
1006 assert(!(opts->signoff || opts->no_commit ||
1007 opts->record_origin || opts->edit));
1008 read_and_refresh_cache(opts);
1010 for (cur = todo_list; cur; cur = cur->next) {
1011 save_todo(cur);
1012 res = do_pick_commit(cur->operand, cur->action, opts);
1013 if (res) {
1014 if (!cur->next)
1016 * An error was encountered while
1017 * picking the last commit; the
1018 * sequencer state is useless now --
1019 * the user simply needs to resolve
1020 * the conflict and commit
1022 remove_sequencer_state(0);
1023 return res;
1028 * Sequence of picks finished successfully; cleanup by
1029 * removing the .git/sequencer directory
1031 remove_sequencer_state(1);
1032 return 0;
1035 static int pick_revisions(struct replay_opts *opts)
1037 struct replay_insn_list *todo_list = NULL;
1038 unsigned char sha1[20];
1040 if (opts->subcommand == REPLAY_NONE)
1041 assert(opts->revs);
1043 read_and_refresh_cache(opts);
1046 * Decide what to do depending on the arguments; a fresh
1047 * cherry-pick should be handled differently from an existing
1048 * one that is being continued
1050 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1051 remove_sequencer_state(1);
1052 return 0;
1054 if (opts->subcommand == REPLAY_ROLLBACK)
1055 return sequencer_rollback(opts);
1056 if (opts->subcommand == REPLAY_CONTINUE) {
1057 if (!file_exists(git_path(SEQ_TODO_FILE)))
1058 return error(_("No %s in progress"), action_name(opts));
1059 read_populate_opts(&opts);
1060 read_populate_todo(&todo_list);
1062 /* Verify that the conflict has been resolved */
1063 if (!index_differs_from("HEAD", 0))
1064 todo_list = todo_list->next;
1065 return pick_commits(todo_list, opts);
1069 * Start a new cherry-pick/ revert sequence; but
1070 * first, make sure that an existing one isn't in
1071 * progress
1074 walk_revs_populate_todo(&todo_list, opts);
1075 if (create_seq_dir() < 0)
1076 return -1;
1077 if (get_sha1("HEAD", sha1)) {
1078 if (opts->action == REPLAY_REVERT)
1079 return error(_("Can't revert as initial commit"));
1080 return error(_("Can't cherry-pick into empty head"));
1082 save_head(sha1_to_hex(sha1));
1083 save_opts(opts);
1084 return pick_commits(todo_list, opts);
1087 int cmd_revert(int argc, const char **argv, const char *prefix)
1089 struct replay_opts opts;
1090 int res;
1092 memset(&opts, 0, sizeof(opts));
1093 if (isatty(0))
1094 opts.edit = 1;
1095 opts.action = REPLAY_REVERT;
1096 git_config(git_default_config, NULL);
1097 parse_args(argc, argv, &opts);
1098 res = pick_revisions(&opts);
1099 if (res < 0)
1100 die(_("revert failed"));
1101 return res;
1104 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1106 struct replay_opts opts;
1107 int res;
1109 memset(&opts, 0, sizeof(opts));
1110 opts.action = REPLAY_PICK;
1111 git_config(git_default_config, NULL);
1112 parse_args(argc, argv, &opts);
1113 res = pick_revisions(&opts);
1114 if (res < 0)
1115 die(_("cherry-pick failed"));
1116 return res;