Merge branch 'mb/fetch-call-a-non-branch-a-ref' into maint
[alt-git.git] / sequencer.c
blob4307364b261bcbe7a2e97116aa631aa7aa35613c
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, struct replay_opts *opts)
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 if (opts->no_commit)
143 advise(_("after resolving the conflicts, mark the corrected paths\n"
144 "with 'git add <paths>' or 'git rm <paths>'"));
145 else
146 advise(_("after resolving the conflicts, mark the corrected paths\n"
147 "with 'git add <paths>' or 'git rm <paths>'\n"
148 "and commit the result with 'git commit'"));
152 static void write_message(struct strbuf *msgbuf, const char *filename)
154 static struct lock_file msg_file;
156 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
157 LOCK_DIE_ON_ERROR);
158 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
159 die_errno(_("Could not write to %s"), filename);
160 strbuf_release(msgbuf);
161 if (commit_lock_file(&msg_file) < 0)
162 die(_("Error wrapping up %s"), filename);
165 static struct tree *empty_tree(void)
167 return lookup_tree(EMPTY_TREE_SHA1_BIN);
170 static int error_dirty_index(struct replay_opts *opts)
172 if (read_cache_unmerged())
173 return error_resolve_conflict(action_name(opts));
175 /* Different translation strings for cherry-pick and revert */
176 if (opts->action == REPLAY_PICK)
177 error(_("Your local changes would be overwritten by cherry-pick."));
178 else
179 error(_("Your local changes would be overwritten by revert."));
181 if (advice_commit_before_merge)
182 advise(_("Commit your changes or stash them to proceed."));
183 return -1;
186 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
188 struct ref_lock *ref_lock;
190 read_cache();
191 if (checkout_fast_forward(from, to))
192 exit(1); /* the callee should have complained already */
193 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
194 return write_ref_sha1(ref_lock, to, "cherry-pick");
197 static int do_recursive_merge(struct commit *base, struct commit *next,
198 const char *base_label, const char *next_label,
199 unsigned char *head, struct strbuf *msgbuf,
200 struct replay_opts *opts)
202 struct merge_options o;
203 struct tree *result, *next_tree, *base_tree, *head_tree;
204 int clean, index_fd;
205 const char **xopt;
206 static struct lock_file index_lock;
208 index_fd = hold_locked_index(&index_lock, 1);
210 read_cache();
212 init_merge_options(&o);
213 o.ancestor = base ? base_label : "(empty tree)";
214 o.branch1 = "HEAD";
215 o.branch2 = next ? next_label : "(empty tree)";
217 head_tree = parse_tree_indirect(head);
218 next_tree = next ? next->tree : empty_tree();
219 base_tree = base ? base->tree : empty_tree();
221 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
222 parse_merge_opt(&o, *xopt);
224 clean = merge_trees(&o,
225 head_tree,
226 next_tree, base_tree, &result);
228 if (active_cache_changed &&
229 (write_cache(index_fd, active_cache, active_nr) ||
230 commit_locked_index(&index_lock)))
231 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
232 die(_("%s: Unable to write new index file"), action_name(opts));
233 rollback_lock_file(&index_lock);
235 if (!clean) {
236 int i;
237 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
238 for (i = 0; i < active_nr;) {
239 struct cache_entry *ce = active_cache[i++];
240 if (ce_stage(ce)) {
241 strbuf_addch(msgbuf, '\t');
242 strbuf_addstr(msgbuf, ce->name);
243 strbuf_addch(msgbuf, '\n');
244 while (i < active_nr && !strcmp(ce->name,
245 active_cache[i]->name))
246 i++;
251 return !clean;
255 * If we are cherry-pick, and if the merge did not result in
256 * hand-editing, we will hit this commit and inherit the original
257 * author date and name.
258 * If we are revert, or if our cherry-pick results in a hand merge,
259 * we had better say that the current user is responsible for that.
261 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
263 /* 6 is max possible length of our args array including NULL */
264 const char *args[6];
265 int i = 0;
267 args[i++] = "commit";
268 args[i++] = "-n";
269 if (opts->signoff)
270 args[i++] = "-s";
271 if (!opts->edit) {
272 args[i++] = "-F";
273 args[i++] = defmsg;
275 args[i] = NULL;
277 return run_command_v_opt(args, RUN_GIT_CMD);
280 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
282 unsigned char head[20];
283 struct commit *base, *next, *parent;
284 const char *base_label, *next_label;
285 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
286 char *defmsg = NULL;
287 struct strbuf msgbuf = STRBUF_INIT;
288 int res;
290 if (opts->no_commit) {
292 * We do not intend to commit immediately. We just want to
293 * merge the differences in, so let's compute the tree
294 * that represents the "current" state for merge-recursive
295 * to work on.
297 if (write_cache_as_tree(head, 0, NULL))
298 die (_("Your index file is unmerged."));
299 } else {
300 if (get_sha1("HEAD", head))
301 return error(_("You do not have a valid HEAD"));
302 if (index_differs_from("HEAD", 0))
303 return error_dirty_index(opts);
305 discard_cache();
307 if (!commit->parents) {
308 parent = NULL;
310 else if (commit->parents->next) {
311 /* Reverting or cherry-picking a merge commit */
312 int cnt;
313 struct commit_list *p;
315 if (!opts->mainline)
316 return error(_("Commit %s is a merge but no -m option was given."),
317 sha1_to_hex(commit->object.sha1));
319 for (cnt = 1, p = commit->parents;
320 cnt != opts->mainline && p;
321 cnt++)
322 p = p->next;
323 if (cnt != opts->mainline || !p)
324 return error(_("Commit %s does not have parent %d"),
325 sha1_to_hex(commit->object.sha1), opts->mainline);
326 parent = p->item;
327 } else if (0 < opts->mainline)
328 return error(_("Mainline was specified but commit %s is not a merge."),
329 sha1_to_hex(commit->object.sha1));
330 else
331 parent = commit->parents->item;
333 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
334 return fast_forward_to(commit->object.sha1, head);
336 if (parent && parse_commit(parent) < 0)
337 /* TRANSLATORS: The first %s will be "revert" or
338 "cherry-pick", the second %s a SHA1 */
339 return error(_("%s: cannot parse parent commit %s"),
340 action_name(opts), sha1_to_hex(parent->object.sha1));
342 if (get_message(commit, &msg) != 0)
343 return error(_("Cannot get commit message for %s"),
344 sha1_to_hex(commit->object.sha1));
347 * "commit" is an existing commit. We would want to apply
348 * the difference it introduces since its first parent "prev"
349 * on top of the current HEAD if we are cherry-pick. Or the
350 * reverse of it if we are revert.
353 defmsg = git_pathdup("MERGE_MSG");
355 if (opts->action == REPLAY_REVERT) {
356 base = commit;
357 base_label = msg.label;
358 next = parent;
359 next_label = msg.parent_label;
360 strbuf_addstr(&msgbuf, "Revert \"");
361 strbuf_addstr(&msgbuf, msg.subject);
362 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
363 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
365 if (commit->parents && commit->parents->next) {
366 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
367 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
369 strbuf_addstr(&msgbuf, ".\n");
370 } else {
371 const char *p;
373 base = parent;
374 base_label = msg.parent_label;
375 next = commit;
376 next_label = msg.label;
379 * Append the commit log message to msgbuf; it starts
380 * after the tree, parent, author, committer
381 * information followed by "\n\n".
383 p = strstr(msg.message, "\n\n");
384 if (p) {
385 p += 2;
386 strbuf_addstr(&msgbuf, p);
389 if (opts->record_origin) {
390 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
391 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
392 strbuf_addstr(&msgbuf, ")\n");
396 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
397 res = do_recursive_merge(base, next, base_label, next_label,
398 head, &msgbuf, opts);
399 write_message(&msgbuf, defmsg);
400 } else {
401 struct commit_list *common = NULL;
402 struct commit_list *remotes = NULL;
404 write_message(&msgbuf, defmsg);
406 commit_list_insert(base, &common);
407 commit_list_insert(next, &remotes);
408 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
409 common, sha1_to_hex(head), remotes);
410 free_commit_list(common);
411 free_commit_list(remotes);
415 * If the merge was clean or if it failed due to conflict, we write
416 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
417 * However, if the merge did not even start, then we don't want to
418 * write it at all.
420 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
421 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
422 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
423 write_cherry_pick_head(commit, "REVERT_HEAD");
425 if (res) {
426 error(opts->action == REPLAY_REVERT
427 ? _("could not revert %s... %s")
428 : _("could not apply %s... %s"),
429 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
430 msg.subject);
431 print_advice(res == 1, opts);
432 rerere(opts->allow_rerere_auto);
433 } else {
434 if (!opts->no_commit)
435 res = run_git_commit(defmsg, opts);
438 free_message(&msg);
439 free(defmsg);
441 return res;
444 static void prepare_revs(struct replay_opts *opts)
446 if (opts->action != REPLAY_REVERT)
447 opts->revs->reverse ^= 1;
449 if (prepare_revision_walk(opts->revs))
450 die(_("revision walk setup failed"));
452 if (!opts->revs->commits)
453 die(_("empty commit set passed"));
456 static void read_and_refresh_cache(struct replay_opts *opts)
458 static struct lock_file index_lock;
459 int index_fd = hold_locked_index(&index_lock, 0);
460 if (read_index_preload(&the_index, NULL) < 0)
461 die(_("git %s: failed to read the index"), action_name(opts));
462 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
463 if (the_index.cache_changed) {
464 if (write_index(&the_index, index_fd) ||
465 commit_locked_index(&index_lock))
466 die(_("git %s: failed to refresh the index"), action_name(opts));
468 rollback_lock_file(&index_lock);
472 * Append a commit to the end of the commit_list.
474 * next starts by pointing to the variable that holds the head of an
475 * empty commit_list, and is updated to point to the "next" field of
476 * the last item on the list as new commits are appended.
478 * Usage example:
480 * struct commit_list *list;
481 * struct commit_list **next = &list;
483 * next = commit_list_append(c1, next);
484 * next = commit_list_append(c2, next);
485 * assert(commit_list_count(list) == 2);
486 * return list;
488 static struct commit_list **commit_list_append(struct commit *commit,
489 struct commit_list **next)
491 struct commit_list *new = xmalloc(sizeof(struct commit_list));
492 new->item = commit;
493 *next = new;
494 new->next = NULL;
495 return &new->next;
498 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
499 struct replay_opts *opts)
501 struct commit_list *cur = NULL;
502 const char *sha1_abbrev = NULL;
503 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
504 const char *subject;
505 int subject_len;
507 for (cur = todo_list; cur; cur = cur->next) {
508 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
509 subject_len = find_commit_subject(cur->item->buffer, &subject);
510 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
511 subject_len, subject);
513 return 0;
516 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
518 unsigned char commit_sha1[20];
519 enum replay_action action;
520 char *end_of_object_name;
521 int saved, status, padding;
523 if (!prefixcmp(bol, "pick")) {
524 action = REPLAY_PICK;
525 bol += strlen("pick");
526 } else if (!prefixcmp(bol, "revert")) {
527 action = REPLAY_REVERT;
528 bol += strlen("revert");
529 } else
530 return NULL;
532 /* Eat up extra spaces/ tabs before object name */
533 padding = strspn(bol, " \t");
534 if (!padding)
535 return NULL;
536 bol += padding;
538 end_of_object_name = bol + strcspn(bol, " \t\n");
539 saved = *end_of_object_name;
540 *end_of_object_name = '\0';
541 status = get_sha1(bol, commit_sha1);
542 *end_of_object_name = saved;
545 * Verify that the action matches up with the one in
546 * opts; we don't support arbitrary instructions
548 if (action != opts->action) {
549 const char *action_str;
550 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
551 error(_("Cannot %s during a %s"), action_str, action_name(opts));
552 return NULL;
555 if (status < 0)
556 return NULL;
558 return lookup_commit_reference(commit_sha1);
561 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
562 struct replay_opts *opts)
564 struct commit_list **next = todo_list;
565 struct commit *commit;
566 char *p = buf;
567 int i;
569 for (i = 1; *p; i++) {
570 char *eol = strchrnul(p, '\n');
571 commit = parse_insn_line(p, eol, opts);
572 if (!commit)
573 return error(_("Could not parse line %d."), i);
574 next = commit_list_append(commit, next);
575 p = *eol ? eol + 1 : eol;
577 if (!*todo_list)
578 return error(_("No commits parsed."));
579 return 0;
582 static void read_populate_todo(struct commit_list **todo_list,
583 struct replay_opts *opts)
585 const char *todo_file = git_path(SEQ_TODO_FILE);
586 struct strbuf buf = STRBUF_INIT;
587 int fd, res;
589 fd = open(todo_file, O_RDONLY);
590 if (fd < 0)
591 die_errno(_("Could not open %s"), todo_file);
592 if (strbuf_read(&buf, fd, 0) < 0) {
593 close(fd);
594 strbuf_release(&buf);
595 die(_("Could not read %s."), todo_file);
597 close(fd);
599 res = parse_insn_buffer(buf.buf, todo_list, opts);
600 strbuf_release(&buf);
601 if (res)
602 die(_("Unusable instruction sheet: %s"), todo_file);
605 static int populate_opts_cb(const char *key, const char *value, void *data)
607 struct replay_opts *opts = data;
608 int error_flag = 1;
610 if (!value)
611 error_flag = 0;
612 else if (!strcmp(key, "options.no-commit"))
613 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
614 else if (!strcmp(key, "options.edit"))
615 opts->edit = git_config_bool_or_int(key, value, &error_flag);
616 else if (!strcmp(key, "options.signoff"))
617 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
618 else if (!strcmp(key, "options.record-origin"))
619 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
620 else if (!strcmp(key, "options.allow-ff"))
621 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
622 else if (!strcmp(key, "options.mainline"))
623 opts->mainline = git_config_int(key, value);
624 else if (!strcmp(key, "options.strategy"))
625 git_config_string(&opts->strategy, key, value);
626 else if (!strcmp(key, "options.strategy-option")) {
627 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
628 opts->xopts[opts->xopts_nr++] = xstrdup(value);
629 } else
630 return error(_("Invalid key: %s"), key);
632 if (!error_flag)
633 return error(_("Invalid value for %s: %s"), key, value);
635 return 0;
638 static void read_populate_opts(struct replay_opts **opts_ptr)
640 const char *opts_file = git_path(SEQ_OPTS_FILE);
642 if (!file_exists(opts_file))
643 return;
644 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
645 die(_("Malformed options sheet: %s"), opts_file);
648 static void walk_revs_populate_todo(struct commit_list **todo_list,
649 struct replay_opts *opts)
651 struct commit *commit;
652 struct commit_list **next;
654 prepare_revs(opts);
656 next = todo_list;
657 while ((commit = get_revision(opts->revs)))
658 next = commit_list_append(commit, next);
661 static int create_seq_dir(void)
663 const char *seq_dir = git_path(SEQ_DIR);
665 if (file_exists(seq_dir)) {
666 error(_("a cherry-pick or revert is already in progress"));
667 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
668 return -1;
670 else if (mkdir(seq_dir, 0777) < 0)
671 die_errno(_("Could not create sequencer directory %s"), seq_dir);
672 return 0;
675 static void save_head(const char *head)
677 const char *head_file = git_path(SEQ_HEAD_FILE);
678 static struct lock_file head_lock;
679 struct strbuf buf = STRBUF_INIT;
680 int fd;
682 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
683 strbuf_addf(&buf, "%s\n", head);
684 if (write_in_full(fd, buf.buf, buf.len) < 0)
685 die_errno(_("Could not write to %s"), head_file);
686 if (commit_lock_file(&head_lock) < 0)
687 die(_("Error wrapping up %s."), head_file);
690 static int reset_for_rollback(const unsigned char *sha1)
692 const char *argv[4]; /* reset --merge <arg> + NULL */
693 argv[0] = "reset";
694 argv[1] = "--merge";
695 argv[2] = sha1_to_hex(sha1);
696 argv[3] = NULL;
697 return run_command_v_opt(argv, RUN_GIT_CMD);
700 static int rollback_single_pick(void)
702 unsigned char head_sha1[20];
704 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
705 !file_exists(git_path("REVERT_HEAD")))
706 return error(_("no cherry-pick or revert in progress"));
707 if (read_ref_full("HEAD", head_sha1, 0, NULL))
708 return error(_("cannot resolve HEAD"));
709 if (is_null_sha1(head_sha1))
710 return error(_("cannot abort from a branch yet to be born"));
711 return reset_for_rollback(head_sha1);
714 static int sequencer_rollback(struct replay_opts *opts)
716 const char *filename;
717 FILE *f;
718 unsigned char sha1[20];
719 struct strbuf buf = STRBUF_INIT;
721 filename = git_path(SEQ_HEAD_FILE);
722 f = fopen(filename, "r");
723 if (!f && errno == ENOENT) {
725 * There is no multiple-cherry-pick in progress.
726 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
727 * a single-cherry-pick in progress, abort that.
729 return rollback_single_pick();
731 if (!f)
732 return error(_("cannot open %s: %s"), filename,
733 strerror(errno));
734 if (strbuf_getline(&buf, f, '\n')) {
735 error(_("cannot read %s: %s"), filename, ferror(f) ?
736 strerror(errno) : _("unexpected end of file"));
737 fclose(f);
738 goto fail;
740 fclose(f);
741 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
742 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
743 filename);
744 goto fail;
746 if (reset_for_rollback(sha1))
747 goto fail;
748 remove_sequencer_state();
749 strbuf_release(&buf);
750 return 0;
751 fail:
752 strbuf_release(&buf);
753 return -1;
756 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
758 const char *todo_file = git_path(SEQ_TODO_FILE);
759 static struct lock_file todo_lock;
760 struct strbuf buf = STRBUF_INIT;
761 int fd;
763 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
764 if (format_todo(&buf, todo_list, opts) < 0)
765 die(_("Could not format %s."), todo_file);
766 if (write_in_full(fd, buf.buf, buf.len) < 0) {
767 strbuf_release(&buf);
768 die_errno(_("Could not write to %s"), todo_file);
770 if (commit_lock_file(&todo_lock) < 0) {
771 strbuf_release(&buf);
772 die(_("Error wrapping up %s."), todo_file);
774 strbuf_release(&buf);
777 static void save_opts(struct replay_opts *opts)
779 const char *opts_file = git_path(SEQ_OPTS_FILE);
781 if (opts->no_commit)
782 git_config_set_in_file(opts_file, "options.no-commit", "true");
783 if (opts->edit)
784 git_config_set_in_file(opts_file, "options.edit", "true");
785 if (opts->signoff)
786 git_config_set_in_file(opts_file, "options.signoff", "true");
787 if (opts->record_origin)
788 git_config_set_in_file(opts_file, "options.record-origin", "true");
789 if (opts->allow_ff)
790 git_config_set_in_file(opts_file, "options.allow-ff", "true");
791 if (opts->mainline) {
792 struct strbuf buf = STRBUF_INIT;
793 strbuf_addf(&buf, "%d", opts->mainline);
794 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
795 strbuf_release(&buf);
797 if (opts->strategy)
798 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
799 if (opts->xopts) {
800 int i;
801 for (i = 0; i < opts->xopts_nr; i++)
802 git_config_set_multivar_in_file(opts_file,
803 "options.strategy-option",
804 opts->xopts[i], "^$", 0);
808 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
810 struct commit_list *cur;
811 int res;
813 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
814 if (opts->allow_ff)
815 assert(!(opts->signoff || opts->no_commit ||
816 opts->record_origin || opts->edit));
817 read_and_refresh_cache(opts);
819 for (cur = todo_list; cur; cur = cur->next) {
820 save_todo(cur, opts);
821 res = do_pick_commit(cur->item, opts);
822 if (res)
823 return res;
827 * Sequence of picks finished successfully; cleanup by
828 * removing the .git/sequencer directory
830 remove_sequencer_state();
831 return 0;
834 static int continue_single_pick(void)
836 const char *argv[] = { "commit", NULL };
838 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
839 !file_exists(git_path("REVERT_HEAD")))
840 return error(_("no cherry-pick or revert in progress"));
841 return run_command_v_opt(argv, RUN_GIT_CMD);
844 static int sequencer_continue(struct replay_opts *opts)
846 struct commit_list *todo_list = NULL;
848 if (!file_exists(git_path(SEQ_TODO_FILE)))
849 return continue_single_pick();
850 read_populate_opts(&opts);
851 read_populate_todo(&todo_list, opts);
853 /* Verify that the conflict has been resolved */
854 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
855 file_exists(git_path("REVERT_HEAD"))) {
856 int ret = continue_single_pick();
857 if (ret)
858 return ret;
860 if (index_differs_from("HEAD", 0))
861 return error_dirty_index(opts);
862 todo_list = todo_list->next;
863 return pick_commits(todo_list, opts);
866 static int single_pick(struct commit *cmit, struct replay_opts *opts)
868 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
869 return do_pick_commit(cmit, opts);
872 int sequencer_pick_revisions(struct replay_opts *opts)
874 struct commit_list *todo_list = NULL;
875 unsigned char sha1[20];
877 if (opts->subcommand == REPLAY_NONE)
878 assert(opts->revs);
880 read_and_refresh_cache(opts);
883 * Decide what to do depending on the arguments; a fresh
884 * cherry-pick should be handled differently from an existing
885 * one that is being continued
887 if (opts->subcommand == REPLAY_REMOVE_STATE) {
888 remove_sequencer_state();
889 return 0;
891 if (opts->subcommand == REPLAY_ROLLBACK)
892 return sequencer_rollback(opts);
893 if (opts->subcommand == REPLAY_CONTINUE)
894 return sequencer_continue(opts);
897 * If we were called as "git cherry-pick <commit>", just
898 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
899 * REVERT_HEAD, and don't touch the sequencer state.
900 * This means it is possible to cherry-pick in the middle
901 * of a cherry-pick sequence.
903 if (opts->revs->cmdline.nr == 1 &&
904 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
905 opts->revs->no_walk &&
906 !opts->revs->cmdline.rev->flags) {
907 struct commit *cmit;
908 if (prepare_revision_walk(opts->revs))
909 die(_("revision walk setup failed"));
910 cmit = get_revision(opts->revs);
911 if (!cmit || get_revision(opts->revs))
912 die("BUG: expected exactly one commit from walk");
913 return single_pick(cmit, opts);
917 * Start a new cherry-pick/ revert sequence; but
918 * first, make sure that an existing one isn't in
919 * progress
922 walk_revs_populate_todo(&todo_list, opts);
923 if (create_seq_dir() < 0)
924 return -1;
925 if (get_sha1("HEAD", sha1)) {
926 if (opts->action == REPLAY_REVERT)
927 return error(_("Can't revert as initial commit"));
928 return error(_("Can't cherry-pick into empty head"));
930 save_head(sha1_to_hex(sha1));
931 save_opts(opts);
932 return pick_commits(todo_list, opts);