cherry-pick: regression fix for empty commits
[alt-git.git] / sequencer.c
blob1b2168c1c2593a739c15acea42063a089d78ac77
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"
16 #include "argv-array.h"
18 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
20 void remove_sequencer_state(void)
22 struct strbuf seq_dir = STRBUF_INIT;
24 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
25 remove_dir_recursively(&seq_dir, 0);
26 strbuf_release(&seq_dir);
29 static const char *action_name(const struct replay_opts *opts)
31 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
34 static char *get_encoding(const char *message);
36 struct commit_message {
37 char *parent_label;
38 const char *label;
39 const char *subject;
40 char *reencoded_message;
41 const char *message;
44 static int get_message(struct commit *commit, struct commit_message *out)
46 const char *encoding;
47 const char *abbrev, *subject;
48 int abbrev_len, subject_len;
49 char *q;
51 if (!commit->buffer)
52 return -1;
53 encoding = get_encoding(commit->buffer);
54 if (!encoding)
55 encoding = "UTF-8";
56 if (!git_commit_encoding)
57 git_commit_encoding = "UTF-8";
59 out->reencoded_message = NULL;
60 out->message = commit->buffer;
61 if (strcmp(encoding, git_commit_encoding))
62 out->reencoded_message = reencode_string(commit->buffer,
63 git_commit_encoding, encoding);
64 if (out->reencoded_message)
65 out->message = out->reencoded_message;
67 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
68 abbrev_len = strlen(abbrev);
70 subject_len = find_commit_subject(out->message, &subject);
72 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
73 strlen("... ") + subject_len + 1);
74 q = out->parent_label;
75 q = mempcpy(q, "parent of ", strlen("parent of "));
76 out->label = q;
77 q = mempcpy(q, abbrev, abbrev_len);
78 q = mempcpy(q, "... ", strlen("... "));
79 out->subject = q;
80 q = mempcpy(q, subject, subject_len);
81 *q = '\0';
82 return 0;
85 static void free_message(struct commit_message *msg)
87 free(msg->parent_label);
88 free(msg->reencoded_message);
91 static char *get_encoding(const char *message)
93 const char *p = message, *eol;
95 while (*p && *p != '\n') {
96 for (eol = p + 1; *eol && *eol != '\n'; eol++)
97 ; /* do nothing */
98 if (!prefixcmp(p, "encoding ")) {
99 char *result = xmalloc(eol - 8 - p);
100 strlcpy(result, p + 9, eol - 8 - p);
101 return result;
103 p = eol;
104 if (*p == '\n')
105 p++;
107 return NULL;
110 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
112 const char *filename;
113 int fd;
114 struct strbuf buf = STRBUF_INIT;
116 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
118 filename = git_path("%s", pseudoref);
119 fd = open(filename, O_WRONLY | O_CREAT, 0666);
120 if (fd < 0)
121 die_errno(_("Could not open '%s' for writing"), filename);
122 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
123 die_errno(_("Could not write to '%s'"), filename);
124 strbuf_release(&buf);
127 static void print_advice(int show_hint, struct replay_opts *opts)
129 char *msg = getenv("GIT_CHERRY_PICK_HELP");
131 if (msg) {
132 fprintf(stderr, "%s\n", msg);
134 * A conflict has occured but the porcelain
135 * (typically rebase --interactive) wants to take care
136 * of the commit itself so remove CHERRY_PICK_HEAD
138 unlink(git_path("CHERRY_PICK_HEAD"));
139 return;
142 if (show_hint) {
143 if (opts->no_commit)
144 advise(_("after resolving the conflicts, mark the corrected paths\n"
145 "with 'git add <paths>' or 'git rm <paths>'"));
146 else
147 advise(_("after resolving the conflicts, mark the corrected paths\n"
148 "with 'git add <paths>' or 'git rm <paths>'\n"
149 "and commit the result with 'git commit'"));
153 static void write_message(struct strbuf *msgbuf, const char *filename)
155 static struct lock_file msg_file;
157 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
158 LOCK_DIE_ON_ERROR);
159 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
160 die_errno(_("Could not write to %s"), filename);
161 strbuf_release(msgbuf);
162 if (commit_lock_file(&msg_file) < 0)
163 die(_("Error wrapping up %s"), filename);
166 static struct tree *empty_tree(void)
168 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
171 static int error_dirty_index(struct replay_opts *opts)
173 if (read_cache_unmerged())
174 return error_resolve_conflict(action_name(opts));
176 /* Different translation strings for cherry-pick and revert */
177 if (opts->action == REPLAY_PICK)
178 error(_("Your local changes would be overwritten by cherry-pick."));
179 else
180 error(_("Your local changes would be overwritten by revert."));
182 if (advice_commit_before_merge)
183 advise(_("Commit your changes or stash them to proceed."));
184 return -1;
187 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
189 struct ref_lock *ref_lock;
191 read_cache();
192 if (checkout_fast_forward(from, to))
193 exit(1); /* the callee should have complained already */
194 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
195 return write_ref_sha1(ref_lock, to, "cherry-pick");
198 static int do_recursive_merge(struct commit *base, struct commit *next,
199 const char *base_label, const char *next_label,
200 unsigned char *head, struct strbuf *msgbuf,
201 struct replay_opts *opts)
203 struct merge_options o;
204 struct tree *result, *next_tree, *base_tree, *head_tree;
205 int clean, index_fd;
206 const char **xopt;
207 static struct lock_file index_lock;
209 index_fd = hold_locked_index(&index_lock, 1);
211 read_cache();
213 init_merge_options(&o);
214 o.ancestor = base ? base_label : "(empty tree)";
215 o.branch1 = "HEAD";
216 o.branch2 = next ? next_label : "(empty tree)";
218 head_tree = parse_tree_indirect(head);
219 next_tree = next ? next->tree : empty_tree();
220 base_tree = base ? base->tree : empty_tree();
222 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
223 parse_merge_opt(&o, *xopt);
225 clean = merge_trees(&o,
226 head_tree,
227 next_tree, base_tree, &result);
229 if (active_cache_changed &&
230 (write_cache(index_fd, active_cache, active_nr) ||
231 commit_locked_index(&index_lock)))
232 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
233 die(_("%s: Unable to write new index file"), action_name(opts));
234 rollback_lock_file(&index_lock);
236 if (!clean) {
237 int i;
238 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
239 for (i = 0; i < active_nr;) {
240 struct cache_entry *ce = active_cache[i++];
241 if (ce_stage(ce)) {
242 strbuf_addch(msgbuf, '\t');
243 strbuf_addstr(msgbuf, ce->name);
244 strbuf_addch(msgbuf, '\n');
245 while (i < active_nr && !strcmp(ce->name,
246 active_cache[i]->name))
247 i++;
252 return !clean;
255 static int is_index_unchanged(void)
257 unsigned char head_sha1[20];
258 struct commit *head_commit;
260 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
261 return error(_("Could not resolve HEAD commit\n"));
263 head_commit = lookup_commit(head_sha1);
266 * If head_commit is NULL, check_commit, called from
267 * lookup_commit, would have indicated that head_commit is not
268 * a commit object already. parse_commit() will return failure
269 * without further complaints in such a case. Otherwise, if
270 * the commit is invalid, parse_commit() will complain. So
271 * there is nothing for us to say here. Just return failure.
273 if (parse_commit(head_commit))
274 return -1;
276 if (!active_cache_tree)
277 active_cache_tree = cache_tree();
279 if (!cache_tree_fully_valid(active_cache_tree))
280 if (cache_tree_update(active_cache_tree, active_cache,
281 active_nr, 0))
282 return error(_("Unable to update cache tree\n"));
284 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
288 * If we are cherry-pick, and if the merge did not result in
289 * hand-editing, we will hit this commit and inherit the original
290 * author date and name.
291 * If we are revert, or if our cherry-pick results in a hand merge,
292 * we had better say that the current user is responsible for that.
294 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
295 int allow_empty)
297 struct argv_array array;
298 int rc;
300 argv_array_init(&array);
301 argv_array_push(&array, "commit");
302 argv_array_push(&array, "-n");
304 if (opts->signoff)
305 argv_array_push(&array, "-s");
306 if (!opts->edit) {
307 argv_array_push(&array, "-F");
308 argv_array_push(&array, defmsg);
311 if (allow_empty)
312 argv_array_push(&array, "--allow-empty");
314 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
315 argv_array_clear(&array);
316 return rc;
319 static int is_original_commit_empty(struct commit *commit)
321 const unsigned char *ptree_sha1;
323 if (parse_commit(commit))
324 return error(_("Could not parse commit %s\n"),
325 sha1_to_hex(commit->object.sha1));
326 if (commit->parents) {
327 struct commit *parent = commit->parents->item;
328 if (parse_commit(parent))
329 return error(_("Could not parse parent commit %s\n"),
330 sha1_to_hex(parent->object.sha1));
331 ptree_sha1 = parent->tree->object.sha1;
332 } else {
333 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
336 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
340 * Do we run "git commit" with "--allow-empty"?
342 static int allow_empty(struct replay_opts *opts, struct commit *commit)
344 int index_unchanged, empty_commit;
347 * Three cases:
349 * (1) we do not allow empty at all and error out.
351 * (2) we allow ones that were initially empty, but
352 * forbid the ones that become empty;
354 * (3) we allow both.
356 if (!opts->allow_empty)
357 return 0; /* let "git commit" barf as necessary */
359 index_unchanged = is_index_unchanged();
360 if (index_unchanged < 0)
361 return index_unchanged;
362 if (!index_unchanged)
363 return 0; /* we do not have to say --allow-empty */
365 if (opts->keep_redundant_commits)
366 return 1;
368 empty_commit = is_original_commit_empty(commit);
369 if (empty_commit < 0)
370 return empty_commit;
371 if (!empty_commit)
372 return 0;
373 else
374 return 1;
377 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
379 unsigned char head[20];
380 struct commit *base, *next, *parent;
381 const char *base_label, *next_label;
382 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
383 char *defmsg = NULL;
384 struct strbuf msgbuf = STRBUF_INIT;
385 int res;
387 if (opts->no_commit) {
389 * We do not intend to commit immediately. We just want to
390 * merge the differences in, so let's compute the tree
391 * that represents the "current" state for merge-recursive
392 * to work on.
394 if (write_cache_as_tree(head, 0, NULL))
395 die (_("Your index file is unmerged."));
396 } else {
397 if (get_sha1("HEAD", head))
398 return error(_("You do not have a valid HEAD"));
399 if (index_differs_from("HEAD", 0))
400 return error_dirty_index(opts);
402 discard_cache();
404 if (!commit->parents) {
405 parent = NULL;
407 else if (commit->parents->next) {
408 /* Reverting or cherry-picking a merge commit */
409 int cnt;
410 struct commit_list *p;
412 if (!opts->mainline)
413 return error(_("Commit %s is a merge but no -m option was given."),
414 sha1_to_hex(commit->object.sha1));
416 for (cnt = 1, p = commit->parents;
417 cnt != opts->mainline && p;
418 cnt++)
419 p = p->next;
420 if (cnt != opts->mainline || !p)
421 return error(_("Commit %s does not have parent %d"),
422 sha1_to_hex(commit->object.sha1), opts->mainline);
423 parent = p->item;
424 } else if (0 < opts->mainline)
425 return error(_("Mainline was specified but commit %s is not a merge."),
426 sha1_to_hex(commit->object.sha1));
427 else
428 parent = commit->parents->item;
430 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
431 return fast_forward_to(commit->object.sha1, head);
433 if (parent && parse_commit(parent) < 0)
434 /* TRANSLATORS: The first %s will be "revert" or
435 "cherry-pick", the second %s a SHA1 */
436 return error(_("%s: cannot parse parent commit %s"),
437 action_name(opts), sha1_to_hex(parent->object.sha1));
439 if (get_message(commit, &msg) != 0)
440 return error(_("Cannot get commit message for %s"),
441 sha1_to_hex(commit->object.sha1));
444 * "commit" is an existing commit. We would want to apply
445 * the difference it introduces since its first parent "prev"
446 * on top of the current HEAD if we are cherry-pick. Or the
447 * reverse of it if we are revert.
450 defmsg = git_pathdup("MERGE_MSG");
452 if (opts->action == REPLAY_REVERT) {
453 base = commit;
454 base_label = msg.label;
455 next = parent;
456 next_label = msg.parent_label;
457 strbuf_addstr(&msgbuf, "Revert \"");
458 strbuf_addstr(&msgbuf, msg.subject);
459 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
460 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
462 if (commit->parents && commit->parents->next) {
463 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
464 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
466 strbuf_addstr(&msgbuf, ".\n");
467 } else {
468 const char *p;
470 base = parent;
471 base_label = msg.parent_label;
472 next = commit;
473 next_label = msg.label;
476 * Append the commit log message to msgbuf; it starts
477 * after the tree, parent, author, committer
478 * information followed by "\n\n".
480 p = strstr(msg.message, "\n\n");
481 if (p) {
482 p += 2;
483 strbuf_addstr(&msgbuf, p);
486 if (opts->record_origin) {
487 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
488 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
489 strbuf_addstr(&msgbuf, ")\n");
493 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
494 res = do_recursive_merge(base, next, base_label, next_label,
495 head, &msgbuf, opts);
496 write_message(&msgbuf, defmsg);
497 } else {
498 struct commit_list *common = NULL;
499 struct commit_list *remotes = NULL;
501 write_message(&msgbuf, defmsg);
503 commit_list_insert(base, &common);
504 commit_list_insert(next, &remotes);
505 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
506 common, sha1_to_hex(head), remotes);
507 free_commit_list(common);
508 free_commit_list(remotes);
512 * If the merge was clean or if it failed due to conflict, we write
513 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
514 * However, if the merge did not even start, then we don't want to
515 * write it at all.
517 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
518 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
519 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
520 write_cherry_pick_head(commit, "REVERT_HEAD");
522 if (res) {
523 error(opts->action == REPLAY_REVERT
524 ? _("could not revert %s... %s")
525 : _("could not apply %s... %s"),
526 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
527 msg.subject);
528 print_advice(res == 1, opts);
529 rerere(opts->allow_rerere_auto);
530 } else {
531 int allow = allow_empty(opts, commit);
532 if (allow < 0)
533 return allow;
534 if (!opts->no_commit)
535 res = run_git_commit(defmsg, opts, allow);
538 free_message(&msg);
539 free(defmsg);
541 return res;
544 static void prepare_revs(struct replay_opts *opts)
546 if (opts->action != REPLAY_REVERT)
547 opts->revs->reverse ^= 1;
549 if (prepare_revision_walk(opts->revs))
550 die(_("revision walk setup failed"));
552 if (!opts->revs->commits)
553 die(_("empty commit set passed"));
556 static void read_and_refresh_cache(struct replay_opts *opts)
558 static struct lock_file index_lock;
559 int index_fd = hold_locked_index(&index_lock, 0);
560 if (read_index_preload(&the_index, NULL) < 0)
561 die(_("git %s: failed to read the index"), action_name(opts));
562 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
563 if (the_index.cache_changed) {
564 if (write_index(&the_index, index_fd) ||
565 commit_locked_index(&index_lock))
566 die(_("git %s: failed to refresh the index"), action_name(opts));
568 rollback_lock_file(&index_lock);
572 * Append a commit to the end of the commit_list.
574 * next starts by pointing to the variable that holds the head of an
575 * empty commit_list, and is updated to point to the "next" field of
576 * the last item on the list as new commits are appended.
578 * Usage example:
580 * struct commit_list *list;
581 * struct commit_list **next = &list;
583 * next = commit_list_append(c1, next);
584 * next = commit_list_append(c2, next);
585 * assert(commit_list_count(list) == 2);
586 * return list;
588 static struct commit_list **commit_list_append(struct commit *commit,
589 struct commit_list **next)
591 struct commit_list *new = xmalloc(sizeof(struct commit_list));
592 new->item = commit;
593 *next = new;
594 new->next = NULL;
595 return &new->next;
598 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
599 struct replay_opts *opts)
601 struct commit_list *cur = NULL;
602 const char *sha1_abbrev = NULL;
603 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
604 const char *subject;
605 int subject_len;
607 for (cur = todo_list; cur; cur = cur->next) {
608 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
609 subject_len = find_commit_subject(cur->item->buffer, &subject);
610 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
611 subject_len, subject);
613 return 0;
616 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
618 unsigned char commit_sha1[20];
619 enum replay_action action;
620 char *end_of_object_name;
621 int saved, status, padding;
623 if (!prefixcmp(bol, "pick")) {
624 action = REPLAY_PICK;
625 bol += strlen("pick");
626 } else if (!prefixcmp(bol, "revert")) {
627 action = REPLAY_REVERT;
628 bol += strlen("revert");
629 } else
630 return NULL;
632 /* Eat up extra spaces/ tabs before object name */
633 padding = strspn(bol, " \t");
634 if (!padding)
635 return NULL;
636 bol += padding;
638 end_of_object_name = bol + strcspn(bol, " \t\n");
639 saved = *end_of_object_name;
640 *end_of_object_name = '\0';
641 status = get_sha1(bol, commit_sha1);
642 *end_of_object_name = saved;
645 * Verify that the action matches up with the one in
646 * opts; we don't support arbitrary instructions
648 if (action != opts->action) {
649 const char *action_str;
650 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
651 error(_("Cannot %s during a %s"), action_str, action_name(opts));
652 return NULL;
655 if (status < 0)
656 return NULL;
658 return lookup_commit_reference(commit_sha1);
661 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
662 struct replay_opts *opts)
664 struct commit_list **next = todo_list;
665 struct commit *commit;
666 char *p = buf;
667 int i;
669 for (i = 1; *p; i++) {
670 char *eol = strchrnul(p, '\n');
671 commit = parse_insn_line(p, eol, opts);
672 if (!commit)
673 return error(_("Could not parse line %d."), i);
674 next = commit_list_append(commit, next);
675 p = *eol ? eol + 1 : eol;
677 if (!*todo_list)
678 return error(_("No commits parsed."));
679 return 0;
682 static void read_populate_todo(struct commit_list **todo_list,
683 struct replay_opts *opts)
685 const char *todo_file = git_path(SEQ_TODO_FILE);
686 struct strbuf buf = STRBUF_INIT;
687 int fd, res;
689 fd = open(todo_file, O_RDONLY);
690 if (fd < 0)
691 die_errno(_("Could not open %s"), todo_file);
692 if (strbuf_read(&buf, fd, 0) < 0) {
693 close(fd);
694 strbuf_release(&buf);
695 die(_("Could not read %s."), todo_file);
697 close(fd);
699 res = parse_insn_buffer(buf.buf, todo_list, opts);
700 strbuf_release(&buf);
701 if (res)
702 die(_("Unusable instruction sheet: %s"), todo_file);
705 static int populate_opts_cb(const char *key, const char *value, void *data)
707 struct replay_opts *opts = data;
708 int error_flag = 1;
710 if (!value)
711 error_flag = 0;
712 else if (!strcmp(key, "options.no-commit"))
713 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
714 else if (!strcmp(key, "options.edit"))
715 opts->edit = git_config_bool_or_int(key, value, &error_flag);
716 else if (!strcmp(key, "options.signoff"))
717 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
718 else if (!strcmp(key, "options.record-origin"))
719 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
720 else if (!strcmp(key, "options.allow-ff"))
721 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
722 else if (!strcmp(key, "options.mainline"))
723 opts->mainline = git_config_int(key, value);
724 else if (!strcmp(key, "options.strategy"))
725 git_config_string(&opts->strategy, key, value);
726 else if (!strcmp(key, "options.strategy-option")) {
727 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
728 opts->xopts[opts->xopts_nr++] = xstrdup(value);
729 } else
730 return error(_("Invalid key: %s"), key);
732 if (!error_flag)
733 return error(_("Invalid value for %s: %s"), key, value);
735 return 0;
738 static void read_populate_opts(struct replay_opts **opts_ptr)
740 const char *opts_file = git_path(SEQ_OPTS_FILE);
742 if (!file_exists(opts_file))
743 return;
744 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
745 die(_("Malformed options sheet: %s"), opts_file);
748 static void walk_revs_populate_todo(struct commit_list **todo_list,
749 struct replay_opts *opts)
751 struct commit *commit;
752 struct commit_list **next;
754 prepare_revs(opts);
756 next = todo_list;
757 while ((commit = get_revision(opts->revs)))
758 next = commit_list_append(commit, next);
761 static int create_seq_dir(void)
763 const char *seq_dir = git_path(SEQ_DIR);
765 if (file_exists(seq_dir)) {
766 error(_("a cherry-pick or revert is already in progress"));
767 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
768 return -1;
770 else if (mkdir(seq_dir, 0777) < 0)
771 die_errno(_("Could not create sequencer directory %s"), seq_dir);
772 return 0;
775 static void save_head(const char *head)
777 const char *head_file = git_path(SEQ_HEAD_FILE);
778 static struct lock_file head_lock;
779 struct strbuf buf = STRBUF_INIT;
780 int fd;
782 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
783 strbuf_addf(&buf, "%s\n", head);
784 if (write_in_full(fd, buf.buf, buf.len) < 0)
785 die_errno(_("Could not write to %s"), head_file);
786 if (commit_lock_file(&head_lock) < 0)
787 die(_("Error wrapping up %s."), head_file);
790 static int reset_for_rollback(const unsigned char *sha1)
792 const char *argv[4]; /* reset --merge <arg> + NULL */
793 argv[0] = "reset";
794 argv[1] = "--merge";
795 argv[2] = sha1_to_hex(sha1);
796 argv[3] = NULL;
797 return run_command_v_opt(argv, RUN_GIT_CMD);
800 static int rollback_single_pick(void)
802 unsigned char head_sha1[20];
804 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
805 !file_exists(git_path("REVERT_HEAD")))
806 return error(_("no cherry-pick or revert in progress"));
807 if (read_ref_full("HEAD", head_sha1, 0, NULL))
808 return error(_("cannot resolve HEAD"));
809 if (is_null_sha1(head_sha1))
810 return error(_("cannot abort from a branch yet to be born"));
811 return reset_for_rollback(head_sha1);
814 static int sequencer_rollback(struct replay_opts *opts)
816 const char *filename;
817 FILE *f;
818 unsigned char sha1[20];
819 struct strbuf buf = STRBUF_INIT;
821 filename = git_path(SEQ_HEAD_FILE);
822 f = fopen(filename, "r");
823 if (!f && errno == ENOENT) {
825 * There is no multiple-cherry-pick in progress.
826 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
827 * a single-cherry-pick in progress, abort that.
829 return rollback_single_pick();
831 if (!f)
832 return error(_("cannot open %s: %s"), filename,
833 strerror(errno));
834 if (strbuf_getline(&buf, f, '\n')) {
835 error(_("cannot read %s: %s"), filename, ferror(f) ?
836 strerror(errno) : _("unexpected end of file"));
837 fclose(f);
838 goto fail;
840 fclose(f);
841 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
842 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
843 filename);
844 goto fail;
846 if (reset_for_rollback(sha1))
847 goto fail;
848 remove_sequencer_state();
849 strbuf_release(&buf);
850 return 0;
851 fail:
852 strbuf_release(&buf);
853 return -1;
856 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
858 const char *todo_file = git_path(SEQ_TODO_FILE);
859 static struct lock_file todo_lock;
860 struct strbuf buf = STRBUF_INIT;
861 int fd;
863 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
864 if (format_todo(&buf, todo_list, opts) < 0)
865 die(_("Could not format %s."), todo_file);
866 if (write_in_full(fd, buf.buf, buf.len) < 0) {
867 strbuf_release(&buf);
868 die_errno(_("Could not write to %s"), todo_file);
870 if (commit_lock_file(&todo_lock) < 0) {
871 strbuf_release(&buf);
872 die(_("Error wrapping up %s."), todo_file);
874 strbuf_release(&buf);
877 static void save_opts(struct replay_opts *opts)
879 const char *opts_file = git_path(SEQ_OPTS_FILE);
881 if (opts->no_commit)
882 git_config_set_in_file(opts_file, "options.no-commit", "true");
883 if (opts->edit)
884 git_config_set_in_file(opts_file, "options.edit", "true");
885 if (opts->signoff)
886 git_config_set_in_file(opts_file, "options.signoff", "true");
887 if (opts->record_origin)
888 git_config_set_in_file(opts_file, "options.record-origin", "true");
889 if (opts->allow_ff)
890 git_config_set_in_file(opts_file, "options.allow-ff", "true");
891 if (opts->mainline) {
892 struct strbuf buf = STRBUF_INIT;
893 strbuf_addf(&buf, "%d", opts->mainline);
894 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
895 strbuf_release(&buf);
897 if (opts->strategy)
898 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
899 if (opts->xopts) {
900 int i;
901 for (i = 0; i < opts->xopts_nr; i++)
902 git_config_set_multivar_in_file(opts_file,
903 "options.strategy-option",
904 opts->xopts[i], "^$", 0);
908 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
910 struct commit_list *cur;
911 int res;
913 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
914 if (opts->allow_ff)
915 assert(!(opts->signoff || opts->no_commit ||
916 opts->record_origin || opts->edit));
917 read_and_refresh_cache(opts);
919 for (cur = todo_list; cur; cur = cur->next) {
920 save_todo(cur, opts);
921 res = do_pick_commit(cur->item, opts);
922 if (res)
923 return res;
927 * Sequence of picks finished successfully; cleanup by
928 * removing the .git/sequencer directory
930 remove_sequencer_state();
931 return 0;
934 static int continue_single_pick(void)
936 const char *argv[] = { "commit", NULL };
938 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
939 !file_exists(git_path("REVERT_HEAD")))
940 return error(_("no cherry-pick or revert in progress"));
941 return run_command_v_opt(argv, RUN_GIT_CMD);
944 static int sequencer_continue(struct replay_opts *opts)
946 struct commit_list *todo_list = NULL;
948 if (!file_exists(git_path(SEQ_TODO_FILE)))
949 return continue_single_pick();
950 read_populate_opts(&opts);
951 read_populate_todo(&todo_list, opts);
953 /* Verify that the conflict has been resolved */
954 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
955 file_exists(git_path("REVERT_HEAD"))) {
956 int ret = continue_single_pick();
957 if (ret)
958 return ret;
960 if (index_differs_from("HEAD", 0))
961 return error_dirty_index(opts);
962 todo_list = todo_list->next;
963 return pick_commits(todo_list, opts);
966 static int single_pick(struct commit *cmit, struct replay_opts *opts)
968 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
969 return do_pick_commit(cmit, opts);
972 int sequencer_pick_revisions(struct replay_opts *opts)
974 struct commit_list *todo_list = NULL;
975 unsigned char sha1[20];
977 if (opts->subcommand == REPLAY_NONE)
978 assert(opts->revs);
980 read_and_refresh_cache(opts);
983 * Decide what to do depending on the arguments; a fresh
984 * cherry-pick should be handled differently from an existing
985 * one that is being continued
987 if (opts->subcommand == REPLAY_REMOVE_STATE) {
988 remove_sequencer_state();
989 return 0;
991 if (opts->subcommand == REPLAY_ROLLBACK)
992 return sequencer_rollback(opts);
993 if (opts->subcommand == REPLAY_CONTINUE)
994 return sequencer_continue(opts);
997 * If we were called as "git cherry-pick <commit>", just
998 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
999 * REVERT_HEAD, and don't touch the sequencer state.
1000 * This means it is possible to cherry-pick in the middle
1001 * of a cherry-pick sequence.
1003 if (opts->revs->cmdline.nr == 1 &&
1004 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1005 opts->revs->no_walk &&
1006 !opts->revs->cmdline.rev->flags) {
1007 struct commit *cmit;
1008 if (prepare_revision_walk(opts->revs))
1009 die(_("revision walk setup failed"));
1010 cmit = get_revision(opts->revs);
1011 if (!cmit || get_revision(opts->revs))
1012 die("BUG: expected exactly one commit from walk");
1013 return single_pick(cmit, opts);
1017 * Start a new cherry-pick/ revert sequence; but
1018 * first, make sure that an existing one isn't in
1019 * progress
1022 walk_revs_populate_todo(&todo_list, opts);
1023 if (create_seq_dir() < 0)
1024 return -1;
1025 if (get_sha1("HEAD", sha1)) {
1026 if (opts->action == REPLAY_REVERT)
1027 return error(_("Can't revert as initial commit"));
1028 return error(_("Can't cherry-pick into empty head"));
1030 save_head(sha1_to_hex(sha1));
1031 save_opts(opts);
1032 return pick_commits(todo_list, opts);