sequencer: factor code out of revert builtin
[git.git] / sequencer.c
blob54771196c37d32e78663322d98a4a32f6a947e28
1 #include "cache.h"
2 #include "sequencer.h"
3 #include "dir.h"
4 #include "object.h"
5 #include "commit.h"
6 #include "tag.h"
7 #include "run-command.h"
8 #include "exec_cmd.h"
9 #include "utf8.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"
17 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
19 void remove_sequencer_state(void)
21 struct strbuf seq_dir = STRBUF_INIT;
23 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
24 remove_dir_recursively(&seq_dir, 0);
25 strbuf_release(&seq_dir);
28 static const char *action_name(const struct replay_opts *opts)
30 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
33 static char *get_encoding(const char *message);
35 struct commit_message {
36 char *parent_label;
37 const char *label;
38 const char *subject;
39 char *reencoded_message;
40 const char *message;
43 static int get_message(struct commit *commit, struct commit_message *out)
45 const char *encoding;
46 const char *abbrev, *subject;
47 int abbrev_len, subject_len;
48 char *q;
50 if (!commit->buffer)
51 return -1;
52 encoding = get_encoding(commit->buffer);
53 if (!encoding)
54 encoding = "UTF-8";
55 if (!git_commit_encoding)
56 git_commit_encoding = "UTF-8";
58 out->reencoded_message = NULL;
59 out->message = commit->buffer;
60 if (strcmp(encoding, git_commit_encoding))
61 out->reencoded_message = reencode_string(commit->buffer,
62 git_commit_encoding, encoding);
63 if (out->reencoded_message)
64 out->message = out->reencoded_message;
66 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
67 abbrev_len = strlen(abbrev);
69 subject_len = find_commit_subject(out->message, &subject);
71 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
72 strlen("... ") + subject_len + 1);
73 q = out->parent_label;
74 q = mempcpy(q, "parent of ", strlen("parent of "));
75 out->label = q;
76 q = mempcpy(q, abbrev, abbrev_len);
77 q = mempcpy(q, "... ", strlen("... "));
78 out->subject = q;
79 q = mempcpy(q, subject, subject_len);
80 *q = '\0';
81 return 0;
84 static void free_message(struct commit_message *msg)
86 free(msg->parent_label);
87 free(msg->reencoded_message);
90 static char *get_encoding(const char *message)
92 const char *p = message, *eol;
94 while (*p && *p != '\n') {
95 for (eol = p + 1; *eol && *eol != '\n'; eol++)
96 ; /* do nothing */
97 if (!prefixcmp(p, "encoding ")) {
98 char *result = xmalloc(eol - 8 - p);
99 strlcpy(result, p + 9, eol - 8 - p);
100 return result;
102 p = eol;
103 if (*p == '\n')
104 p++;
106 return NULL;
109 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
111 const char *filename;
112 int fd;
113 struct strbuf buf = STRBUF_INIT;
115 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
117 filename = git_path("%s", pseudoref);
118 fd = open(filename, O_WRONLY | O_CREAT, 0666);
119 if (fd < 0)
120 die_errno(_("Could not open '%s' for writing"), filename);
121 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
122 die_errno(_("Could not write to '%s'"), filename);
123 strbuf_release(&buf);
126 static void print_advice(int show_hint)
128 char *msg = getenv("GIT_CHERRY_PICK_HELP");
130 if (msg) {
131 fprintf(stderr, "%s\n", msg);
133 * A conflict has occured but the porcelain
134 * (typically rebase --interactive) wants to take care
135 * of the commit itself so remove CHERRY_PICK_HEAD
137 unlink(git_path("CHERRY_PICK_HEAD"));
138 return;
141 if (show_hint) {
142 advise("after resolving the conflicts, mark the corrected paths");
143 advise("with 'git add <paths>' or 'git rm <paths>'");
144 advise("and commit the result with 'git commit'");
148 static void write_message(struct strbuf *msgbuf, const char *filename)
150 static struct lock_file msg_file;
152 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
153 LOCK_DIE_ON_ERROR);
154 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
155 die_errno(_("Could not write to %s"), filename);
156 strbuf_release(msgbuf);
157 if (commit_lock_file(&msg_file) < 0)
158 die(_("Error wrapping up %s"), filename);
161 static struct tree *empty_tree(void)
163 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
166 static int error_dirty_index(struct replay_opts *opts)
168 if (read_cache_unmerged())
169 return error_resolve_conflict(action_name(opts));
171 /* Different translation strings for cherry-pick and revert */
172 if (opts->action == REPLAY_PICK)
173 error(_("Your local changes would be overwritten by cherry-pick."));
174 else
175 error(_("Your local changes would be overwritten by revert."));
177 if (advice_commit_before_merge)
178 advise(_("Commit your changes or stash them to proceed."));
179 return -1;
182 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
184 struct ref_lock *ref_lock;
186 read_cache();
187 if (checkout_fast_forward(from, to))
188 exit(1); /* the callee should have complained already */
189 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
190 return write_ref_sha1(ref_lock, to, "cherry-pick");
193 static int do_recursive_merge(struct commit *base, struct commit *next,
194 const char *base_label, const char *next_label,
195 unsigned char *head, struct strbuf *msgbuf,
196 struct replay_opts *opts)
198 struct merge_options o;
199 struct tree *result, *next_tree, *base_tree, *head_tree;
200 int clean, index_fd;
201 const char **xopt;
202 static struct lock_file index_lock;
204 index_fd = hold_locked_index(&index_lock, 1);
206 read_cache();
208 init_merge_options(&o);
209 o.ancestor = base ? base_label : "(empty tree)";
210 o.branch1 = "HEAD";
211 o.branch2 = next ? next_label : "(empty tree)";
213 head_tree = parse_tree_indirect(head);
214 next_tree = next ? next->tree : empty_tree();
215 base_tree = base ? base->tree : empty_tree();
217 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
218 parse_merge_opt(&o, *xopt);
220 clean = merge_trees(&o,
221 head_tree,
222 next_tree, base_tree, &result);
224 if (active_cache_changed &&
225 (write_cache(index_fd, active_cache, active_nr) ||
226 commit_locked_index(&index_lock)))
227 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
228 die(_("%s: Unable to write new index file"), action_name(opts));
229 rollback_lock_file(&index_lock);
231 if (!clean) {
232 int i;
233 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
234 for (i = 0; i < active_nr;) {
235 struct cache_entry *ce = active_cache[i++];
236 if (ce_stage(ce)) {
237 strbuf_addch(msgbuf, '\t');
238 strbuf_addstr(msgbuf, ce->name);
239 strbuf_addch(msgbuf, '\n');
240 while (i < active_nr && !strcmp(ce->name,
241 active_cache[i]->name))
242 i++;
247 return !clean;
251 * If we are cherry-pick, and if the merge did not result in
252 * hand-editing, we will hit this commit and inherit the original
253 * author date and name.
254 * If we are revert, or if our cherry-pick results in a hand merge,
255 * we had better say that the current user is responsible for that.
257 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
259 /* 6 is max possible length of our args array including NULL */
260 const char *args[6];
261 int i = 0;
263 args[i++] = "commit";
264 args[i++] = "-n";
265 if (opts->signoff)
266 args[i++] = "-s";
267 if (!opts->edit) {
268 args[i++] = "-F";
269 args[i++] = defmsg;
271 args[i] = NULL;
273 return run_command_v_opt(args, RUN_GIT_CMD);
276 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
278 unsigned char head[20];
279 struct commit *base, *next, *parent;
280 const char *base_label, *next_label;
281 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
282 char *defmsg = NULL;
283 struct strbuf msgbuf = STRBUF_INIT;
284 int res;
286 if (opts->no_commit) {
288 * We do not intend to commit immediately. We just want to
289 * merge the differences in, so let's compute the tree
290 * that represents the "current" state for merge-recursive
291 * to work on.
293 if (write_cache_as_tree(head, 0, NULL))
294 die (_("Your index file is unmerged."));
295 } else {
296 if (get_sha1("HEAD", head))
297 return error(_("You do not have a valid HEAD"));
298 if (index_differs_from("HEAD", 0))
299 return error_dirty_index(opts);
301 discard_cache();
303 if (!commit->parents) {
304 parent = NULL;
306 else if (commit->parents->next) {
307 /* Reverting or cherry-picking a merge commit */
308 int cnt;
309 struct commit_list *p;
311 if (!opts->mainline)
312 return error(_("Commit %s is a merge but no -m option was given."),
313 sha1_to_hex(commit->object.sha1));
315 for (cnt = 1, p = commit->parents;
316 cnt != opts->mainline && p;
317 cnt++)
318 p = p->next;
319 if (cnt != opts->mainline || !p)
320 return error(_("Commit %s does not have parent %d"),
321 sha1_to_hex(commit->object.sha1), opts->mainline);
322 parent = p->item;
323 } else if (0 < opts->mainline)
324 return error(_("Mainline was specified but commit %s is not a merge."),
325 sha1_to_hex(commit->object.sha1));
326 else
327 parent = commit->parents->item;
329 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
330 return fast_forward_to(commit->object.sha1, head);
332 if (parent && parse_commit(parent) < 0)
333 /* TRANSLATORS: The first %s will be "revert" or
334 "cherry-pick", the second %s a SHA1 */
335 return error(_("%s: cannot parse parent commit %s"),
336 action_name(opts), sha1_to_hex(parent->object.sha1));
338 if (get_message(commit, &msg) != 0)
339 return error(_("Cannot get commit message for %s"),
340 sha1_to_hex(commit->object.sha1));
343 * "commit" is an existing commit. We would want to apply
344 * the difference it introduces since its first parent "prev"
345 * on top of the current HEAD if we are cherry-pick. Or the
346 * reverse of it if we are revert.
349 defmsg = git_pathdup("MERGE_MSG");
351 if (opts->action == REPLAY_REVERT) {
352 base = commit;
353 base_label = msg.label;
354 next = parent;
355 next_label = msg.parent_label;
356 strbuf_addstr(&msgbuf, "Revert \"");
357 strbuf_addstr(&msgbuf, msg.subject);
358 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
359 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
361 if (commit->parents && commit->parents->next) {
362 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
363 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
365 strbuf_addstr(&msgbuf, ".\n");
366 } else {
367 const char *p;
369 base = parent;
370 base_label = msg.parent_label;
371 next = commit;
372 next_label = msg.label;
375 * Append the commit log message to msgbuf; it starts
376 * after the tree, parent, author, committer
377 * information followed by "\n\n".
379 p = strstr(msg.message, "\n\n");
380 if (p) {
381 p += 2;
382 strbuf_addstr(&msgbuf, p);
385 if (opts->record_origin) {
386 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
387 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
388 strbuf_addstr(&msgbuf, ")\n");
392 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
393 res = do_recursive_merge(base, next, base_label, next_label,
394 head, &msgbuf, opts);
395 write_message(&msgbuf, defmsg);
396 } else {
397 struct commit_list *common = NULL;
398 struct commit_list *remotes = NULL;
400 write_message(&msgbuf, defmsg);
402 commit_list_insert(base, &common);
403 commit_list_insert(next, &remotes);
404 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
405 common, sha1_to_hex(head), remotes);
406 free_commit_list(common);
407 free_commit_list(remotes);
411 * If the merge was clean or if it failed due to conflict, we write
412 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
413 * However, if the merge did not even start, then we don't want to
414 * write it at all.
416 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
417 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
418 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
419 write_cherry_pick_head(commit, "REVERT_HEAD");
421 if (res) {
422 error(opts->action == REPLAY_REVERT
423 ? _("could not revert %s... %s")
424 : _("could not apply %s... %s"),
425 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
426 msg.subject);
427 print_advice(res == 1);
428 rerere(opts->allow_rerere_auto);
429 } else {
430 if (!opts->no_commit)
431 res = run_git_commit(defmsg, opts);
434 free_message(&msg);
435 free(defmsg);
437 return res;
440 static void prepare_revs(struct replay_opts *opts)
442 if (opts->action != REPLAY_REVERT)
443 opts->revs->reverse ^= 1;
445 if (prepare_revision_walk(opts->revs))
446 die(_("revision walk setup failed"));
448 if (!opts->revs->commits)
449 die(_("empty commit set passed"));
452 static void read_and_refresh_cache(struct replay_opts *opts)
454 static struct lock_file index_lock;
455 int index_fd = hold_locked_index(&index_lock, 0);
456 if (read_index_preload(&the_index, NULL) < 0)
457 die(_("git %s: failed to read the index"), action_name(opts));
458 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
459 if (the_index.cache_changed) {
460 if (write_index(&the_index, index_fd) ||
461 commit_locked_index(&index_lock))
462 die(_("git %s: failed to refresh the index"), action_name(opts));
464 rollback_lock_file(&index_lock);
468 * Append a commit to the end of the commit_list.
470 * next starts by pointing to the variable that holds the head of an
471 * empty commit_list, and is updated to point to the "next" field of
472 * the last item on the list as new commits are appended.
474 * Usage example:
476 * struct commit_list *list;
477 * struct commit_list **next = &list;
479 * next = commit_list_append(c1, next);
480 * next = commit_list_append(c2, next);
481 * assert(commit_list_count(list) == 2);
482 * return list;
484 static struct commit_list **commit_list_append(struct commit *commit,
485 struct commit_list **next)
487 struct commit_list *new = xmalloc(sizeof(struct commit_list));
488 new->item = commit;
489 *next = new;
490 new->next = NULL;
491 return &new->next;
494 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
495 struct replay_opts *opts)
497 struct commit_list *cur = NULL;
498 const char *sha1_abbrev = NULL;
499 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
500 const char *subject;
501 int subject_len;
503 for (cur = todo_list; cur; cur = cur->next) {
504 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
505 subject_len = find_commit_subject(cur->item->buffer, &subject);
506 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
507 subject_len, subject);
509 return 0;
512 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
514 unsigned char commit_sha1[20];
515 enum replay_action action;
516 char *end_of_object_name;
517 int saved, status, padding;
519 if (!prefixcmp(bol, "pick")) {
520 action = REPLAY_PICK;
521 bol += strlen("pick");
522 } else if (!prefixcmp(bol, "revert")) {
523 action = REPLAY_REVERT;
524 bol += strlen("revert");
525 } else
526 return NULL;
528 /* Eat up extra spaces/ tabs before object name */
529 padding = strspn(bol, " \t");
530 if (!padding)
531 return NULL;
532 bol += padding;
534 end_of_object_name = bol + strcspn(bol, " \t\n");
535 saved = *end_of_object_name;
536 *end_of_object_name = '\0';
537 status = get_sha1(bol, commit_sha1);
538 *end_of_object_name = saved;
541 * Verify that the action matches up with the one in
542 * opts; we don't support arbitrary instructions
544 if (action != opts->action) {
545 const char *action_str;
546 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
547 error(_("Cannot %s during a %s"), action_str, action_name(opts));
548 return NULL;
551 if (status < 0)
552 return NULL;
554 return lookup_commit_reference(commit_sha1);
557 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
558 struct replay_opts *opts)
560 struct commit_list **next = todo_list;
561 struct commit *commit;
562 char *p = buf;
563 int i;
565 for (i = 1; *p; i++) {
566 char *eol = strchrnul(p, '\n');
567 commit = parse_insn_line(p, eol, opts);
568 if (!commit)
569 return error(_("Could not parse line %d."), i);
570 next = commit_list_append(commit, next);
571 p = *eol ? eol + 1 : eol;
573 if (!*todo_list)
574 return error(_("No commits parsed."));
575 return 0;
578 static void read_populate_todo(struct commit_list **todo_list,
579 struct replay_opts *opts)
581 const char *todo_file = git_path(SEQ_TODO_FILE);
582 struct strbuf buf = STRBUF_INIT;
583 int fd, res;
585 fd = open(todo_file, O_RDONLY);
586 if (fd < 0)
587 die_errno(_("Could not open %s"), todo_file);
588 if (strbuf_read(&buf, fd, 0) < 0) {
589 close(fd);
590 strbuf_release(&buf);
591 die(_("Could not read %s."), todo_file);
593 close(fd);
595 res = parse_insn_buffer(buf.buf, todo_list, opts);
596 strbuf_release(&buf);
597 if (res)
598 die(_("Unusable instruction sheet: %s"), todo_file);
601 static int populate_opts_cb(const char *key, const char *value, void *data)
603 struct replay_opts *opts = data;
604 int error_flag = 1;
606 if (!value)
607 error_flag = 0;
608 else if (!strcmp(key, "options.no-commit"))
609 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
610 else if (!strcmp(key, "options.edit"))
611 opts->edit = git_config_bool_or_int(key, value, &error_flag);
612 else if (!strcmp(key, "options.signoff"))
613 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
614 else if (!strcmp(key, "options.record-origin"))
615 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
616 else if (!strcmp(key, "options.allow-ff"))
617 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
618 else if (!strcmp(key, "options.mainline"))
619 opts->mainline = git_config_int(key, value);
620 else if (!strcmp(key, "options.strategy"))
621 git_config_string(&opts->strategy, key, value);
622 else if (!strcmp(key, "options.strategy-option")) {
623 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
624 opts->xopts[opts->xopts_nr++] = xstrdup(value);
625 } else
626 return error(_("Invalid key: %s"), key);
628 if (!error_flag)
629 return error(_("Invalid value for %s: %s"), key, value);
631 return 0;
634 static void read_populate_opts(struct replay_opts **opts_ptr)
636 const char *opts_file = git_path(SEQ_OPTS_FILE);
638 if (!file_exists(opts_file))
639 return;
640 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
641 die(_("Malformed options sheet: %s"), opts_file);
644 static void walk_revs_populate_todo(struct commit_list **todo_list,
645 struct replay_opts *opts)
647 struct commit *commit;
648 struct commit_list **next;
650 prepare_revs(opts);
652 next = todo_list;
653 while ((commit = get_revision(opts->revs)))
654 next = commit_list_append(commit, next);
657 static int create_seq_dir(void)
659 const char *seq_dir = git_path(SEQ_DIR);
661 if (file_exists(seq_dir)) {
662 error(_("a cherry-pick or revert is already in progress"));
663 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
664 return -1;
666 else if (mkdir(seq_dir, 0777) < 0)
667 die_errno(_("Could not create sequencer directory %s"), seq_dir);
668 return 0;
671 static void save_head(const char *head)
673 const char *head_file = git_path(SEQ_HEAD_FILE);
674 static struct lock_file head_lock;
675 struct strbuf buf = STRBUF_INIT;
676 int fd;
678 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
679 strbuf_addf(&buf, "%s\n", head);
680 if (write_in_full(fd, buf.buf, buf.len) < 0)
681 die_errno(_("Could not write to %s"), head_file);
682 if (commit_lock_file(&head_lock) < 0)
683 die(_("Error wrapping up %s."), head_file);
686 static int reset_for_rollback(const unsigned char *sha1)
688 const char *argv[4]; /* reset --merge <arg> + NULL */
689 argv[0] = "reset";
690 argv[1] = "--merge";
691 argv[2] = sha1_to_hex(sha1);
692 argv[3] = NULL;
693 return run_command_v_opt(argv, RUN_GIT_CMD);
696 static int rollback_single_pick(void)
698 unsigned char head_sha1[20];
700 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
701 !file_exists(git_path("REVERT_HEAD")))
702 return error(_("no cherry-pick or revert in progress"));
703 if (read_ref_full("HEAD", head_sha1, 0, NULL))
704 return error(_("cannot resolve HEAD"));
705 if (is_null_sha1(head_sha1))
706 return error(_("cannot abort from a branch yet to be born"));
707 return reset_for_rollback(head_sha1);
710 static int sequencer_rollback(struct replay_opts *opts)
712 const char *filename;
713 FILE *f;
714 unsigned char sha1[20];
715 struct strbuf buf = STRBUF_INIT;
717 filename = git_path(SEQ_HEAD_FILE);
718 f = fopen(filename, "r");
719 if (!f && errno == ENOENT) {
721 * There is no multiple-cherry-pick in progress.
722 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
723 * a single-cherry-pick in progress, abort that.
725 return rollback_single_pick();
727 if (!f)
728 return error(_("cannot open %s: %s"), filename,
729 strerror(errno));
730 if (strbuf_getline(&buf, f, '\n')) {
731 error(_("cannot read %s: %s"), filename, ferror(f) ?
732 strerror(errno) : _("unexpected end of file"));
733 fclose(f);
734 goto fail;
736 fclose(f);
737 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
738 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
739 filename);
740 goto fail;
742 if (reset_for_rollback(sha1))
743 goto fail;
744 remove_sequencer_state();
745 strbuf_release(&buf);
746 return 0;
747 fail:
748 strbuf_release(&buf);
749 return -1;
752 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
754 const char *todo_file = git_path(SEQ_TODO_FILE);
755 static struct lock_file todo_lock;
756 struct strbuf buf = STRBUF_INIT;
757 int fd;
759 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
760 if (format_todo(&buf, todo_list, opts) < 0)
761 die(_("Could not format %s."), todo_file);
762 if (write_in_full(fd, buf.buf, buf.len) < 0) {
763 strbuf_release(&buf);
764 die_errno(_("Could not write to %s"), todo_file);
766 if (commit_lock_file(&todo_lock) < 0) {
767 strbuf_release(&buf);
768 die(_("Error wrapping up %s."), todo_file);
770 strbuf_release(&buf);
773 static void save_opts(struct replay_opts *opts)
775 const char *opts_file = git_path(SEQ_OPTS_FILE);
777 if (opts->no_commit)
778 git_config_set_in_file(opts_file, "options.no-commit", "true");
779 if (opts->edit)
780 git_config_set_in_file(opts_file, "options.edit", "true");
781 if (opts->signoff)
782 git_config_set_in_file(opts_file, "options.signoff", "true");
783 if (opts->record_origin)
784 git_config_set_in_file(opts_file, "options.record-origin", "true");
785 if (opts->allow_ff)
786 git_config_set_in_file(opts_file, "options.allow-ff", "true");
787 if (opts->mainline) {
788 struct strbuf buf = STRBUF_INIT;
789 strbuf_addf(&buf, "%d", opts->mainline);
790 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
791 strbuf_release(&buf);
793 if (opts->strategy)
794 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
795 if (opts->xopts) {
796 int i;
797 for (i = 0; i < opts->xopts_nr; i++)
798 git_config_set_multivar_in_file(opts_file,
799 "options.strategy-option",
800 opts->xopts[i], "^$", 0);
804 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
806 struct commit_list *cur;
807 int res;
809 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
810 if (opts->allow_ff)
811 assert(!(opts->signoff || opts->no_commit ||
812 opts->record_origin || opts->edit));
813 read_and_refresh_cache(opts);
815 for (cur = todo_list; cur; cur = cur->next) {
816 save_todo(cur, opts);
817 res = do_pick_commit(cur->item, opts);
818 if (res)
819 return res;
823 * Sequence of picks finished successfully; cleanup by
824 * removing the .git/sequencer directory
826 remove_sequencer_state();
827 return 0;
830 static int continue_single_pick(void)
832 const char *argv[] = { "commit", NULL };
834 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
835 !file_exists(git_path("REVERT_HEAD")))
836 return error(_("no cherry-pick or revert in progress"));
837 return run_command_v_opt(argv, RUN_GIT_CMD);
840 static int sequencer_continue(struct replay_opts *opts)
842 struct commit_list *todo_list = NULL;
844 if (!file_exists(git_path(SEQ_TODO_FILE)))
845 return continue_single_pick();
846 read_populate_opts(&opts);
847 read_populate_todo(&todo_list, opts);
849 /* Verify that the conflict has been resolved */
850 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
851 file_exists(git_path("REVERT_HEAD"))) {
852 int ret = continue_single_pick();
853 if (ret)
854 return ret;
856 if (index_differs_from("HEAD", 0))
857 return error_dirty_index(opts);
858 todo_list = todo_list->next;
859 return pick_commits(todo_list, opts);
862 static int single_pick(struct commit *cmit, struct replay_opts *opts)
864 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
865 return do_pick_commit(cmit, opts);
868 int sequencer_pick_revisions(struct replay_opts *opts)
870 struct commit_list *todo_list = NULL;
871 unsigned char sha1[20];
873 if (opts->subcommand == REPLAY_NONE)
874 assert(opts->revs);
876 read_and_refresh_cache(opts);
879 * Decide what to do depending on the arguments; a fresh
880 * cherry-pick should be handled differently from an existing
881 * one that is being continued
883 if (opts->subcommand == REPLAY_REMOVE_STATE) {
884 remove_sequencer_state();
885 return 0;
887 if (opts->subcommand == REPLAY_ROLLBACK)
888 return sequencer_rollback(opts);
889 if (opts->subcommand == REPLAY_CONTINUE)
890 return sequencer_continue(opts);
893 * If we were called as "git cherry-pick <commit>", just
894 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
895 * REVERT_HEAD, and don't touch the sequencer state.
896 * This means it is possible to cherry-pick in the middle
897 * of a cherry-pick sequence.
899 if (opts->revs->cmdline.nr == 1 &&
900 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
901 opts->revs->no_walk &&
902 !opts->revs->cmdline.rev->flags) {
903 struct commit *cmit;
904 if (prepare_revision_walk(opts->revs))
905 die(_("revision walk setup failed"));
906 cmit = get_revision(opts->revs);
907 if (!cmit || get_revision(opts->revs))
908 die("BUG: expected exactly one commit from walk");
909 return single_pick(cmit, opts);
913 * Start a new cherry-pick/ revert sequence; but
914 * first, make sure that an existing one isn't in
915 * progress
918 walk_revs_populate_todo(&todo_list, opts);
919 if (create_seq_dir() < 0)
920 return -1;
921 if (get_sha1("HEAD", sha1)) {
922 if (opts->action == REPLAY_REVERT)
923 return error(_("Can't revert as initial commit"));
924 return error(_("Can't cherry-pick into empty head"));
926 save_head(sha1_to_hex(sha1));
927 save_opts(opts);
928 return pick_commits(todo_list, opts);