submodule: Use cat instead of echo to avoid DOS line-endings
[git/dscho.git] / builtin / revert.c
blob8ee65bc024218a7502b6ddbfc06a9e6634c1ec55
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 { REPLAY_NONE, REPLAY_RESET, REPLAY_CONTINUE };
44 struct replay_opts {
45 enum replay_action action;
46 enum replay_subcommand subcommand;
48 /* Boolean options */
49 int edit;
50 int record_origin;
51 int no_commit;
52 int signoff;
53 int allow_ff;
54 int allow_rerere_auto;
56 int mainline;
58 /* Merge strategy */
59 const char *strategy;
60 const char **xopts;
61 size_t xopts_nr, xopts_alloc;
63 /* Only used by REPLAY_NONE */
64 struct rev_info *revs;
67 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
69 static const char *action_name(const struct replay_opts *opts)
71 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
74 static char *get_encoding(const char *message);
76 static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
78 return opts->action == REPLAY_REVERT ? revert_usage : cherry_pick_usage;
81 static int option_parse_x(const struct option *opt,
82 const char *arg, int unset)
84 struct replay_opts **opts_ptr = opt->value;
85 struct replay_opts *opts = *opts_ptr;
87 if (unset)
88 return 0;
90 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
91 opts->xopts[opts->xopts_nr++] = xstrdup(arg);
92 return 0;
95 static void verify_opt_compatible(const char *me, const char *base_opt, ...)
97 const char *this_opt;
98 va_list ap;
100 va_start(ap, base_opt);
101 while ((this_opt = va_arg(ap, const char *))) {
102 if (va_arg(ap, int))
103 break;
105 va_end(ap);
107 if (this_opt)
108 die(_("%s: %s cannot be used with %s"), me, this_opt, base_opt);
111 static void verify_opt_mutually_compatible(const char *me, ...)
113 const char *opt1, *opt2 = NULL;
114 va_list ap;
116 va_start(ap, me);
117 while ((opt1 = va_arg(ap, const char *))) {
118 if (va_arg(ap, int))
119 break;
121 if (opt1) {
122 while ((opt2 = va_arg(ap, const char *))) {
123 if (va_arg(ap, int))
124 break;
128 if (opt1 && opt2)
129 die(_("%s: %s cannot be used with %s"), me, opt1, opt2);
132 static void parse_args(int argc, const char **argv, struct replay_opts *opts)
134 const char * const * usage_str = revert_or_cherry_pick_usage(opts);
135 const char *me = action_name(opts);
136 int reset = 0;
137 int contin = 0;
138 struct option options[] = {
139 OPT_BOOLEAN(0, "reset", &reset, "forget the current operation"),
140 OPT_BOOLEAN(0, "continue", &contin, "continue the current operation"),
141 OPT_BOOLEAN('n', "no-commit", &opts->no_commit, "don't automatically commit"),
142 OPT_BOOLEAN('e', "edit", &opts->edit, "edit the commit message"),
143 OPT_NOOP_NOARG('r', NULL),
144 OPT_BOOLEAN('s', "signoff", &opts->signoff, "add Signed-off-by:"),
145 OPT_INTEGER('m', "mainline", &opts->mainline, "parent number"),
146 OPT_RERERE_AUTOUPDATE(&opts->allow_rerere_auto),
147 OPT_STRING(0, "strategy", &opts->strategy, "strategy", "merge strategy"),
148 OPT_CALLBACK('X', "strategy-option", &opts, "option",
149 "option for merge strategy", option_parse_x),
150 OPT_END(),
151 OPT_END(),
152 OPT_END(),
155 if (opts->action == REPLAY_PICK) {
156 struct option cp_extra[] = {
157 OPT_BOOLEAN('x', NULL, &opts->record_origin, "append commit name"),
158 OPT_BOOLEAN(0, "ff", &opts->allow_ff, "allow fast-forward"),
159 OPT_END(),
161 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
162 die(_("program error"));
165 argc = parse_options(argc, argv, NULL, options, usage_str,
166 PARSE_OPT_KEEP_ARGV0 |
167 PARSE_OPT_KEEP_UNKNOWN);
169 /* Check for incompatible subcommands */
170 verify_opt_mutually_compatible(me,
171 "--reset", reset,
172 "--continue", contin,
173 NULL);
175 /* Set the subcommand */
176 if (reset)
177 opts->subcommand = REPLAY_RESET;
178 else if (contin)
179 opts->subcommand = REPLAY_CONTINUE;
180 else
181 opts->subcommand = REPLAY_NONE;
183 /* Check for incompatible command line arguments */
184 if (opts->subcommand != REPLAY_NONE) {
185 char *this_operation;
186 if (opts->subcommand == REPLAY_RESET)
187 this_operation = "--reset";
188 else
189 this_operation = "--continue";
191 verify_opt_compatible(me, this_operation,
192 "--no-commit", opts->no_commit,
193 "--signoff", opts->signoff,
194 "--mainline", opts->mainline,
195 "--strategy", opts->strategy ? 1 : 0,
196 "--strategy-option", opts->xopts ? 1 : 0,
197 "-x", opts->record_origin,
198 "--ff", opts->allow_ff,
199 NULL);
202 if (opts->allow_ff)
203 verify_opt_compatible(me, "--ff",
204 "--signoff", opts->signoff,
205 "--no-commit", opts->no_commit,
206 "-x", opts->record_origin,
207 "--edit", opts->edit,
208 NULL);
210 if (opts->subcommand == REPLAY_NONE) {
211 opts->revs = xmalloc(sizeof(*opts->revs));
212 init_revisions(opts->revs, NULL);
213 opts->revs->no_walk = 1;
214 if (argc < 2)
215 usage_with_options(usage_str, options);
216 argc = setup_revisions(argc, argv, opts->revs, NULL);
217 } else
218 opts->revs = NULL;
220 /* Forbid stray command-line arguments */
221 if (argc > 1)
222 usage_with_options(usage_str, options);
225 struct commit_message {
226 char *parent_label;
227 const char *label;
228 const char *subject;
229 char *reencoded_message;
230 const char *message;
233 static int get_message(struct commit *commit, struct commit_message *out)
235 const char *encoding;
236 const char *abbrev, *subject;
237 int abbrev_len, subject_len;
238 char *q;
240 if (!commit->buffer)
241 return -1;
242 encoding = get_encoding(commit->buffer);
243 if (!encoding)
244 encoding = "UTF-8";
245 if (!git_commit_encoding)
246 git_commit_encoding = "UTF-8";
248 out->reencoded_message = NULL;
249 out->message = commit->buffer;
250 if (strcmp(encoding, git_commit_encoding))
251 out->reencoded_message = reencode_string(commit->buffer,
252 git_commit_encoding, encoding);
253 if (out->reencoded_message)
254 out->message = out->reencoded_message;
256 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
257 abbrev_len = strlen(abbrev);
259 subject_len = find_commit_subject(out->message, &subject);
261 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
262 strlen("... ") + subject_len + 1);
263 q = out->parent_label;
264 q = mempcpy(q, "parent of ", strlen("parent of "));
265 out->label = q;
266 q = mempcpy(q, abbrev, abbrev_len);
267 q = mempcpy(q, "... ", strlen("... "));
268 out->subject = q;
269 q = mempcpy(q, subject, subject_len);
270 *q = '\0';
271 return 0;
274 static void free_message(struct commit_message *msg)
276 free(msg->parent_label);
277 free(msg->reencoded_message);
280 static char *get_encoding(const char *message)
282 const char *p = message, *eol;
284 while (*p && *p != '\n') {
285 for (eol = p + 1; *eol && *eol != '\n'; eol++)
286 ; /* do nothing */
287 if (!prefixcmp(p, "encoding ")) {
288 char *result = xmalloc(eol - 8 - p);
289 strlcpy(result, p + 9, eol - 8 - p);
290 return result;
292 p = eol;
293 if (*p == '\n')
294 p++;
296 return NULL;
299 static void write_cherry_pick_head(struct commit *commit)
301 int fd;
302 struct strbuf buf = STRBUF_INIT;
304 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
306 fd = open(git_path("CHERRY_PICK_HEAD"), O_WRONLY | O_CREAT, 0666);
307 if (fd < 0)
308 die_errno(_("Could not open '%s' for writing"),
309 git_path("CHERRY_PICK_HEAD"));
310 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
311 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
312 strbuf_release(&buf);
315 static void print_advice(int show_hint)
317 char *msg = getenv("GIT_CHERRY_PICK_HELP");
319 if (msg) {
320 fprintf(stderr, "%s\n", msg);
322 * A conflict has occured but the porcelain
323 * (typically rebase --interactive) wants to take care
324 * of the commit itself so remove CHERRY_PICK_HEAD
326 unlink(git_path("CHERRY_PICK_HEAD"));
327 return;
330 if (show_hint) {
331 advise("after resolving the conflicts, mark the corrected paths");
332 advise("with 'git add <paths>' or 'git rm <paths>'");
333 advise("and commit the result with 'git commit'");
337 static void write_message(struct strbuf *msgbuf, const char *filename)
339 static struct lock_file msg_file;
341 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
342 LOCK_DIE_ON_ERROR);
343 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
344 die_errno(_("Could not write to %s."), filename);
345 strbuf_release(msgbuf);
346 if (commit_lock_file(&msg_file) < 0)
347 die(_("Error wrapping up %s"), filename);
350 static struct tree *empty_tree(void)
352 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
355 static int error_dirty_index(struct replay_opts *opts)
357 if (read_cache_unmerged())
358 return error_resolve_conflict(action_name(opts));
360 /* Different translation strings for cherry-pick and revert */
361 if (opts->action == REPLAY_PICK)
362 error(_("Your local changes would be overwritten by cherry-pick."));
363 else
364 error(_("Your local changes would be overwritten by revert."));
366 if (advice_commit_before_merge)
367 advise(_("Commit your changes or stash them to proceed."));
368 return -1;
371 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
373 struct ref_lock *ref_lock;
375 read_cache();
376 if (checkout_fast_forward(from, to))
377 exit(1); /* the callee should have complained already */
378 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
379 return write_ref_sha1(ref_lock, to, "cherry-pick");
382 static int do_recursive_merge(struct commit *base, struct commit *next,
383 const char *base_label, const char *next_label,
384 unsigned char *head, struct strbuf *msgbuf,
385 struct replay_opts *opts)
387 struct merge_options o;
388 struct tree *result, *next_tree, *base_tree, *head_tree;
389 int clean, index_fd;
390 const char **xopt;
391 static struct lock_file index_lock;
393 index_fd = hold_locked_index(&index_lock, 1);
395 read_cache();
397 init_merge_options(&o);
398 o.ancestor = base ? base_label : "(empty tree)";
399 o.branch1 = "HEAD";
400 o.branch2 = next ? next_label : "(empty tree)";
402 head_tree = parse_tree_indirect(head);
403 next_tree = next ? next->tree : empty_tree();
404 base_tree = base ? base->tree : empty_tree();
406 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
407 parse_merge_opt(&o, *xopt);
409 clean = merge_trees(&o,
410 head_tree,
411 next_tree, base_tree, &result);
413 if (active_cache_changed &&
414 (write_cache(index_fd, active_cache, active_nr) ||
415 commit_locked_index(&index_lock)))
416 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
417 die(_("%s: Unable to write new index file"), action_name(opts));
418 rollback_lock_file(&index_lock);
420 if (!clean) {
421 int i;
422 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
423 for (i = 0; i < active_nr;) {
424 struct cache_entry *ce = active_cache[i++];
425 if (ce_stage(ce)) {
426 strbuf_addch(msgbuf, '\t');
427 strbuf_addstr(msgbuf, ce->name);
428 strbuf_addch(msgbuf, '\n');
429 while (i < active_nr && !strcmp(ce->name,
430 active_cache[i]->name))
431 i++;
436 return !clean;
440 * If we are cherry-pick, and if the merge did not result in
441 * hand-editing, we will hit this commit and inherit the original
442 * author date and name.
443 * If we are revert, or if our cherry-pick results in a hand merge,
444 * we had better say that the current user is responsible for that.
446 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
448 /* 6 is max possible length of our args array including NULL */
449 const char *args[6];
450 int i = 0;
452 args[i++] = "commit";
453 args[i++] = "-n";
454 if (opts->signoff)
455 args[i++] = "-s";
456 if (!opts->edit) {
457 args[i++] = "-F";
458 args[i++] = defmsg;
460 args[i] = NULL;
462 return run_command_v_opt(args, RUN_GIT_CMD);
465 static int do_pick_commit(struct commit *commit, enum replay_action action,
466 struct replay_opts *opts)
468 unsigned char head[20];
469 struct commit *base, *next, *parent;
470 const char *base_label, *next_label;
471 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
472 char *defmsg = NULL;
473 struct strbuf msgbuf = STRBUF_INIT;
474 int res;
476 if (opts->no_commit) {
478 * We do not intend to commit immediately. We just want to
479 * merge the differences in, so let's compute the tree
480 * that represents the "current" state for merge-recursive
481 * to work on.
483 if (write_cache_as_tree(head, 0, NULL))
484 die (_("Your index file is unmerged."));
485 } else {
486 if (get_sha1("HEAD", head))
487 return error(_("You do not have a valid HEAD"));
488 if (index_differs_from("HEAD", 0))
489 return error_dirty_index(opts);
491 discard_cache();
493 if (!commit->parents) {
494 parent = NULL;
496 else if (commit->parents->next) {
497 /* Reverting or cherry-picking a merge commit */
498 int cnt;
499 struct commit_list *p;
501 if (!opts->mainline)
502 return error(_("Commit %s is a merge but no -m option was given."),
503 sha1_to_hex(commit->object.sha1));
505 for (cnt = 1, p = commit->parents;
506 cnt != opts->mainline && p;
507 cnt++)
508 p = p->next;
509 if (cnt != opts->mainline || !p)
510 return error(_("Commit %s does not have parent %d"),
511 sha1_to_hex(commit->object.sha1), opts->mainline);
512 parent = p->item;
513 } else if (0 < opts->mainline)
514 return error(_("Mainline was specified but commit %s is not a merge."),
515 sha1_to_hex(commit->object.sha1));
516 else
517 parent = commit->parents->item;
519 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
520 return fast_forward_to(commit->object.sha1, head);
522 if (parent && parse_commit(parent) < 0)
523 /* TRANSLATORS: The first %s will be "revert" or
524 "cherry-pick", the second %s a SHA1 */
525 return error(_("%s: cannot parse parent commit %s"),
526 action_name(opts), sha1_to_hex(parent->object.sha1));
528 if (get_message(commit, &msg) != 0)
529 return error(_("Cannot get commit message for %s"),
530 sha1_to_hex(commit->object.sha1));
533 * "commit" is an existing commit. We would want to apply
534 * the difference it introduces since its first parent "prev"
535 * on top of the current HEAD if we are cherry-pick. Or the
536 * reverse of it if we are revert.
539 defmsg = git_pathdup("MERGE_MSG");
541 if (action == REPLAY_REVERT) {
542 base = commit;
543 base_label = msg.label;
544 next = parent;
545 next_label = msg.parent_label;
546 strbuf_addstr(&msgbuf, "Revert \"");
547 strbuf_addstr(&msgbuf, msg.subject);
548 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
549 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
551 if (commit->parents && commit->parents->next) {
552 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
553 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
555 strbuf_addstr(&msgbuf, ".\n");
556 } else {
557 const char *p;
559 base = parent;
560 base_label = msg.parent_label;
561 next = commit;
562 next_label = msg.label;
565 * Append the commit log message to msgbuf; it starts
566 * after the tree, parent, author, committer
567 * information followed by "\n\n".
569 p = strstr(msg.message, "\n\n");
570 if (p) {
571 p += 2;
572 strbuf_addstr(&msgbuf, p);
575 if (opts->record_origin) {
576 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
577 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
578 strbuf_addstr(&msgbuf, ")\n");
582 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || action == REPLAY_REVERT) {
583 res = do_recursive_merge(base, next, base_label, next_label,
584 head, &msgbuf, opts);
585 write_message(&msgbuf, defmsg);
586 } else {
587 struct commit_list *common = NULL;
588 struct commit_list *remotes = NULL;
590 write_message(&msgbuf, defmsg);
592 commit_list_insert(base, &common);
593 commit_list_insert(next, &remotes);
594 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
595 common, sha1_to_hex(head), remotes);
596 free_commit_list(common);
597 free_commit_list(remotes);
601 * If the merge was clean or if it failed due to conflict, we write
602 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
603 * However, if the merge did not even start, then we don't want to
604 * write it at all.
606 if (action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
607 write_cherry_pick_head(commit);
609 if (res) {
610 error(action == REPLAY_REVERT
611 ? _("could not revert %s... %s")
612 : _("could not apply %s... %s"),
613 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
614 msg.subject);
615 print_advice(res == 1);
616 rerere(opts->allow_rerere_auto);
617 } else {
618 if (!opts->no_commit)
619 res = run_git_commit(defmsg, opts);
622 free_message(&msg);
623 free(defmsg);
625 return res;
628 static void prepare_revs(struct replay_opts *opts)
630 if (opts->action != REPLAY_REVERT)
631 opts->revs->reverse ^= 1;
633 if (prepare_revision_walk(opts->revs))
634 die(_("revision walk setup failed"));
636 if (!opts->revs->commits)
637 die(_("empty commit set passed"));
640 static void read_and_refresh_cache(struct replay_opts *opts)
642 static struct lock_file index_lock;
643 int index_fd = hold_locked_index(&index_lock, 0);
644 if (read_index_preload(&the_index, NULL) < 0)
645 die(_("git %s: failed to read the index"), action_name(opts));
646 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
647 if (the_index.cache_changed) {
648 if (write_index(&the_index, index_fd) ||
649 commit_locked_index(&index_lock))
650 die(_("git %s: failed to refresh the index"), action_name(opts));
652 rollback_lock_file(&index_lock);
656 * Append a commit to the end of the commit_list.
658 * next starts by pointing to the variable that holds the head of an
659 * empty commit_list, and is updated to point to the "next" field of
660 * the last item on the list as new commits are appended.
662 * Usage example:
664 * struct commit_list *list;
665 * struct commit_list **next = &list;
667 * next = commit_list_append(c1, next);
668 * next = commit_list_append(c2, next);
669 * assert(commit_list_count(list) == 2);
670 * return list;
672 static struct replay_insn_list **replay_insn_list_append(enum replay_action action,
673 struct commit *operand,
674 struct replay_insn_list **next)
676 struct replay_insn_list *new = xmalloc(sizeof(*new));
677 new->action = action;
678 new->operand = operand;
679 *next = new;
680 new->next = NULL;
681 return &new->next;
684 static int format_todo(struct strbuf *buf, struct replay_insn_list *todo_list)
686 struct replay_insn_list *cur;
688 for (cur = todo_list; cur; cur = cur->next) {
689 const char *sha1_abbrev, *action_str, *subject;
690 int subject_len;
692 action_str = cur->action == REPLAY_REVERT ? "revert" : "pick";
693 sha1_abbrev = find_unique_abbrev(cur->operand->object.sha1, DEFAULT_ABBREV);
694 subject_len = find_commit_subject(cur->operand->buffer, &subject);
695 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
696 subject_len, subject);
698 return 0;
701 static int parse_insn_line(char *bol, char *eol, struct replay_insn_list *item)
703 unsigned char commit_sha1[20];
704 char *end_of_object_name;
705 int saved, status;
707 if (!prefixcmp(bol, "pick ")) {
708 item->action = REPLAY_PICK;
709 bol += strlen("pick ");
710 } else if (!prefixcmp(bol, "revert ")) {
711 item->action = REPLAY_REVERT;
712 bol += strlen("revert ");
713 } else {
714 size_t len = strchrnul(bol, '\n') - bol;
715 if (len > 255)
716 len = 255;
717 return error(_("Unrecognized action: %.*s"), (int)len, bol);
720 end_of_object_name = bol + strcspn(bol, " \n");
721 saved = *end_of_object_name;
722 *end_of_object_name = '\0';
723 status = get_sha1(bol, commit_sha1);
724 *end_of_object_name = saved;
726 if (status < 0)
727 return error(_("Malformed object name: %s"), bol);
729 item->operand = lookup_commit_reference(commit_sha1);
730 if (!item->operand)
731 return error(_("Not a valid commit: %s"), bol);
733 item->next = NULL;
734 return 0;
737 static int parse_insn_buffer(char *buf, struct replay_insn_list **todo_list)
739 struct replay_insn_list **next = todo_list;
740 struct replay_insn_list item = {0, NULL, NULL};
741 char *p = buf;
742 int i;
744 for (i = 1; *p; i++) {
745 char *eol = strchrnul(p, '\n');
746 if (parse_insn_line(p, eol, &item) < 0)
747 return error(_("on line %d."), i);
748 next = replay_insn_list_append(item.action, item.operand, next);
749 p = *eol ? eol + 1 : eol;
751 if (!*todo_list)
752 return error(_("No commits parsed."));
753 return 0;
756 static void read_populate_todo(struct replay_insn_list **todo_list)
758 const char *todo_file = git_path(SEQ_TODO_FILE);
759 struct strbuf buf = STRBUF_INIT;
760 int fd, res;
762 fd = open(todo_file, O_RDONLY);
763 if (fd < 0)
764 die_errno(_("Could not open %s."), todo_file);
765 if (strbuf_read(&buf, fd, 0) < 0) {
766 close(fd);
767 strbuf_release(&buf);
768 die(_("Could not read %s."), todo_file);
770 close(fd);
772 res = parse_insn_buffer(buf.buf, todo_list);
773 strbuf_release(&buf);
774 if (res)
775 die(_("Unusable instruction sheet: %s"), todo_file);
778 static int populate_opts_cb(const char *key, const char *value, void *data)
780 struct replay_opts *opts = data;
781 int error_flag = 1;
783 if (!value)
784 error_flag = 0;
785 else if (!strcmp(key, "options.no-commit"))
786 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
787 else if (!strcmp(key, "options.edit"))
788 opts->edit = git_config_bool_or_int(key, value, &error_flag);
789 else if (!strcmp(key, "options.signoff"))
790 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
791 else if (!strcmp(key, "options.record-origin"))
792 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
793 else if (!strcmp(key, "options.allow-ff"))
794 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
795 else if (!strcmp(key, "options.mainline"))
796 opts->mainline = git_config_int(key, value);
797 else if (!strcmp(key, "options.strategy"))
798 git_config_string(&opts->strategy, key, value);
799 else if (!strcmp(key, "options.strategy-option")) {
800 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
801 opts->xopts[opts->xopts_nr++] = xstrdup(value);
802 } else
803 return error(_("Invalid key: %s"), key);
805 if (!error_flag)
806 return error(_("Invalid value for %s: %s"), key, value);
808 return 0;
811 static void read_populate_opts(struct replay_opts **opts_ptr)
813 const char *opts_file = git_path(SEQ_OPTS_FILE);
815 if (!file_exists(opts_file))
816 return;
817 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
818 die(_("Malformed options sheet: %s"), opts_file);
821 static void walk_revs_populate_todo(struct replay_insn_list **todo_list,
822 struct replay_opts *opts)
824 struct commit *commit;
825 struct replay_insn_list **next;
827 prepare_revs(opts);
829 next = todo_list;
830 while ((commit = get_revision(opts->revs)))
831 next = replay_insn_list_append(opts->action, commit, next);
834 static int create_seq_dir(void)
836 const char *seq_dir = git_path(SEQ_DIR);
838 if (file_exists(seq_dir))
839 return error(_("%s already exists."), seq_dir);
840 else if (mkdir(seq_dir, 0777) < 0)
841 die_errno(_("Could not create sequencer directory '%s'."), seq_dir);
842 return 0;
845 static void save_head(const char *head)
847 const char *head_file = git_path(SEQ_HEAD_FILE);
848 static struct lock_file head_lock;
849 struct strbuf buf = STRBUF_INIT;
850 int fd;
852 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
853 strbuf_addf(&buf, "%s\n", head);
854 if (write_in_full(fd, buf.buf, buf.len) < 0)
855 die_errno(_("Could not write to %s."), head_file);
856 if (commit_lock_file(&head_lock) < 0)
857 die(_("Error wrapping up %s."), head_file);
860 static void save_todo(struct replay_insn_list *todo_list)
862 const char *todo_file = git_path(SEQ_TODO_FILE);
863 static struct lock_file todo_lock;
864 struct strbuf buf = STRBUF_INIT;
865 int fd;
867 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
868 if (format_todo(&buf, todo_list) < 0)
869 die(_("Could not format %s."), todo_file);
870 if (write_in_full(fd, buf.buf, buf.len) < 0) {
871 strbuf_release(&buf);
872 die_errno(_("Could not write to %s."), todo_file);
874 if (commit_lock_file(&todo_lock) < 0) {
875 strbuf_release(&buf);
876 die(_("Error wrapping up %s."), todo_file);
878 strbuf_release(&buf);
881 static void save_opts(struct replay_opts *opts)
883 const char *opts_file = git_path(SEQ_OPTS_FILE);
885 if (opts->no_commit)
886 git_config_set_in_file(opts_file, "options.no-commit", "true");
887 if (opts->edit)
888 git_config_set_in_file(opts_file, "options.edit", "true");
889 if (opts->signoff)
890 git_config_set_in_file(opts_file, "options.signoff", "true");
891 if (opts->record_origin)
892 git_config_set_in_file(opts_file, "options.record-origin", "true");
893 if (opts->allow_ff)
894 git_config_set_in_file(opts_file, "options.allow-ff", "true");
895 if (opts->mainline) {
896 struct strbuf buf = STRBUF_INIT;
897 strbuf_addf(&buf, "%d", opts->mainline);
898 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
899 strbuf_release(&buf);
901 if (opts->strategy)
902 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
903 if (opts->xopts) {
904 int i;
905 for (i = 0; i < opts->xopts_nr; i++)
906 git_config_set_multivar_in_file(opts_file,
907 "options.strategy-option",
908 opts->xopts[i], "^$", 0);
912 static int pick_commits(struct replay_insn_list *todo_list,
913 struct replay_opts *opts)
915 struct replay_insn_list *cur;
916 int res;
918 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
919 if (opts->allow_ff)
920 assert(!(opts->signoff || opts->no_commit ||
921 opts->record_origin || opts->edit));
922 read_and_refresh_cache(opts);
924 for (cur = todo_list; cur; cur = cur->next) {
925 save_todo(cur);
926 res = do_pick_commit(cur->operand, cur->action, opts);
927 if (res) {
928 if (!cur->next)
930 * An error was encountered while
931 * picking the last commit; the
932 * sequencer state is useless now --
933 * the user simply needs to resolve
934 * the conflict and commit
936 remove_sequencer_state(0);
937 return res;
942 * Sequence of picks finished successfully; cleanup by
943 * removing the .git/sequencer directory
945 remove_sequencer_state(1);
946 return 0;
949 static int pick_revisions(struct replay_opts *opts)
951 struct replay_insn_list *todo_list = NULL;
952 unsigned char sha1[20];
954 if (opts->subcommand == REPLAY_NONE)
955 assert(opts->revs);
957 read_and_refresh_cache(opts);
960 * Decide what to do depending on the arguments; a fresh
961 * cherry-pick should be handled differently from an existing
962 * one that is being continued
964 if (opts->subcommand == REPLAY_RESET) {
965 remove_sequencer_state(1);
966 return 0;
967 } else if (opts->subcommand == REPLAY_CONTINUE) {
968 if (!file_exists(git_path(SEQ_TODO_FILE)))
969 goto error;
970 read_populate_opts(&opts);
971 read_populate_todo(&todo_list);
973 /* Verify that the conflict has been resolved */
974 if (!index_differs_from("HEAD", 0))
975 todo_list = todo_list->next;
976 } else {
978 * Start a new cherry-pick/ revert sequence; but
979 * first, make sure that an existing one isn't in
980 * progress
983 walk_revs_populate_todo(&todo_list, opts);
984 if (create_seq_dir() < 0) {
985 error(_("A cherry-pick or revert is in progress."));
986 advise(_("Use --continue to continue the operation"));
987 advise(_("or --reset to forget about it"));
988 return -1;
990 if (get_sha1("HEAD", sha1)) {
991 if (opts->action == REPLAY_REVERT)
992 return error(_("Can't revert as initial commit"));
993 return error(_("Can't cherry-pick into empty head"));
995 save_head(sha1_to_hex(sha1));
996 save_opts(opts);
998 return pick_commits(todo_list, opts);
999 error:
1000 return error(_("No %s in progress"), action_name(opts));
1003 int cmd_revert(int argc, const char **argv, const char *prefix)
1005 struct replay_opts opts;
1006 int res;
1008 memset(&opts, 0, sizeof(opts));
1009 if (isatty(0))
1010 opts.edit = 1;
1011 opts.action = REPLAY_REVERT;
1012 git_config(git_default_config, NULL);
1013 parse_args(argc, argv, &opts);
1014 res = pick_revisions(&opts);
1015 if (res < 0)
1016 die(_("revert failed"));
1017 return res;
1020 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1022 struct replay_opts opts;
1023 int res;
1025 memset(&opts, 0, sizeof(opts));
1026 opts.action = REPLAY_PICK;
1027 git_config(git_default_config, NULL);
1028 parse_args(argc, argv, &opts);
1029 res = pick_revisions(&opts);
1030 if (res < 0)
1031 die(_("cherry-pick failed"));
1032 return res;