8 #include "run-command.h"
11 #include "cache-tree.h"
15 #include "merge-recursive.h"
17 #include "argv-array.h"
21 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
23 const char sign_off_header[] = "Signed-off-by: ";
24 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
26 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
28 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
29 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
30 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
31 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
34 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
35 * GIT_AUTHOR_DATE that will be used for the commit that is currently
38 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
40 * The following files are written by git-rebase just after parsing the
41 * command-line (and are only consumed, not modified, by the sequencer).
43 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
45 /* We will introduce the 'interactive rebase' mode later */
46 static inline int is_rebase_i(const struct replay_opts *opts)
51 static const char *get_dir(const struct replay_opts *opts)
53 return git_path_seq_dir();
56 static const char *get_todo_path(const struct replay_opts *opts)
58 return git_path_todo_file();
62 * Returns 0 for non-conforming footer
63 * Returns 1 for conforming footer
64 * Returns 2 when sob exists within conforming footer
65 * Returns 3 when sob exists within conforming footer as last entry
67 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
70 struct trailer_info info;
72 int found_sob = 0, found_sob_last = 0;
74 trailer_info_get(&info, sb->buf);
76 if (info.trailer_start == info.trailer_end)
79 for (i = 0; i < info.trailer_nr; i++)
80 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
82 if (i == info.trailer_nr - 1)
86 trailer_info_release(&info);
95 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
97 static struct strbuf buf = STRBUF_INIT;
101 sq_quotef(&buf, "-S%s", opts->gpg_sign);
105 int sequencer_remove_state(struct replay_opts *opts)
107 struct strbuf dir = STRBUF_INIT;
110 free(opts->gpg_sign);
111 free(opts->strategy);
112 for (i = 0; i < opts->xopts_nr; i++)
113 free(opts->xopts[i]);
116 strbuf_addf(&dir, "%s", get_dir(opts));
117 remove_dir_recursively(&dir, 0);
118 strbuf_release(&dir);
123 static const char *action_name(const struct replay_opts *opts)
125 return opts->action == REPLAY_REVERT ? N_("revert") : N_("cherry-pick");
128 struct commit_message {
135 static const char *short_commit_name(struct commit *commit)
137 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
140 static int get_message(struct commit *commit, struct commit_message *out)
142 const char *abbrev, *subject;
145 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
146 abbrev = short_commit_name(commit);
148 subject_len = find_commit_subject(out->message, &subject);
150 out->subject = xmemdupz(subject, subject_len);
151 out->label = xstrfmt("%s... %s", abbrev, out->subject);
152 out->parent_label = xstrfmt("parent of %s", out->label);
157 static void free_message(struct commit *commit, struct commit_message *msg)
159 free(msg->parent_label);
162 unuse_commit_buffer(commit, msg->message);
165 static void print_advice(int show_hint, struct replay_opts *opts)
167 char *msg = getenv("GIT_CHERRY_PICK_HELP");
170 fprintf(stderr, "%s\n", msg);
172 * A conflict has occurred but the porcelain
173 * (typically rebase --interactive) wants to take care
174 * of the commit itself so remove CHERRY_PICK_HEAD
176 unlink(git_path_cherry_pick_head());
182 advise(_("after resolving the conflicts, mark the corrected paths\n"
183 "with 'git add <paths>' or 'git rm <paths>'"));
185 advise(_("after resolving the conflicts, mark the corrected paths\n"
186 "with 'git add <paths>' or 'git rm <paths>'\n"
187 "and commit the result with 'git commit'"));
191 static int write_message(const void *buf, size_t len, const char *filename,
194 static struct lock_file msg_file;
196 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
198 return error_errno(_("could not lock '%s'"), filename);
199 if (write_in_full(msg_fd, buf, len) < 0) {
200 rollback_lock_file(&msg_file);
201 return error_errno(_("could not write to '%s'"), filename);
203 if (append_eol && write(msg_fd, "\n", 1) < 0) {
204 rollback_lock_file(&msg_file);
205 return error_errno(_("could not write eol to '%s'"), filename);
207 if (commit_lock_file(&msg_file) < 0) {
208 rollback_lock_file(&msg_file);
209 return error(_("failed to finalize '%s'."), filename);
216 * Reads a file that was presumably written by a shell script, i.e. with an
217 * end-of-line marker that needs to be stripped.
219 * Note that only the last end-of-line marker is stripped, consistent with the
220 * behavior of "$(cat path)" in a shell script.
222 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
224 static int read_oneliner(struct strbuf *buf,
225 const char *path, int skip_if_empty)
227 int orig_len = buf->len;
229 if (!file_exists(path))
232 if (strbuf_read_file(buf, path, 0) < 0) {
233 warning_errno(_("could not read '%s'"), path);
237 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
238 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
240 buf->buf[buf->len] = '\0';
243 if (skip_if_empty && buf->len == orig_len)
249 static struct tree *empty_tree(void)
251 return lookup_tree(EMPTY_TREE_SHA1_BIN);
254 static int error_dirty_index(struct replay_opts *opts)
256 if (read_cache_unmerged())
257 return error_resolve_conflict(_(action_name(opts)));
259 error(_("your local changes would be overwritten by %s."),
260 _(action_name(opts)));
262 if (advice_commit_before_merge)
263 advise(_("commit your changes or stash them to proceed."));
267 static void update_abort_safety_file(void)
269 struct object_id head;
271 /* Do nothing on a single-pick */
272 if (!file_exists(git_path_seq_dir()))
275 if (!get_oid("HEAD", &head))
276 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
278 write_file(git_path_abort_safety_file(), "%s", "");
281 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
282 int unborn, struct replay_opts *opts)
284 struct ref_transaction *transaction;
285 struct strbuf sb = STRBUF_INIT;
286 struct strbuf err = STRBUF_INIT;
289 if (checkout_fast_forward(from, to, 1))
290 return -1; /* the callee should have complained already */
292 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
294 transaction = ref_transaction_begin(&err);
296 ref_transaction_update(transaction, "HEAD",
297 to, unborn ? null_sha1 : from,
299 ref_transaction_commit(transaction, &err)) {
300 ref_transaction_free(transaction);
301 error("%s", err.buf);
303 strbuf_release(&err);
308 strbuf_release(&err);
309 ref_transaction_free(transaction);
310 update_abort_safety_file();
314 void append_conflicts_hint(struct strbuf *msgbuf)
318 strbuf_addch(msgbuf, '\n');
319 strbuf_commented_addf(msgbuf, "Conflicts:\n");
320 for (i = 0; i < active_nr;) {
321 const struct cache_entry *ce = active_cache[i++];
323 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
324 while (i < active_nr && !strcmp(ce->name,
325 active_cache[i]->name))
331 static int do_recursive_merge(struct commit *base, struct commit *next,
332 const char *base_label, const char *next_label,
333 unsigned char *head, struct strbuf *msgbuf,
334 struct replay_opts *opts)
336 struct merge_options o;
337 struct tree *result, *next_tree, *base_tree, *head_tree;
340 static struct lock_file index_lock;
342 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
346 init_merge_options(&o);
347 o.ancestor = base ? base_label : "(empty tree)";
349 o.branch2 = next ? next_label : "(empty tree)";
351 head_tree = parse_tree_indirect(head);
352 next_tree = next ? next->tree : empty_tree();
353 base_tree = base ? base->tree : empty_tree();
355 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
356 parse_merge_opt(&o, *xopt);
358 clean = merge_trees(&o,
360 next_tree, base_tree, &result);
361 strbuf_release(&o.obuf);
365 if (active_cache_changed &&
366 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
367 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
368 return error(_("%s: Unable to write new index file"),
369 _(action_name(opts)));
370 rollback_lock_file(&index_lock);
373 append_signoff(msgbuf, 0, 0);
376 append_conflicts_hint(msgbuf);
381 static int is_index_unchanged(void)
383 unsigned char head_sha1[20];
384 struct commit *head_commit;
386 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
387 return error(_("could not resolve HEAD commit\n"));
389 head_commit = lookup_commit(head_sha1);
392 * If head_commit is NULL, check_commit, called from
393 * lookup_commit, would have indicated that head_commit is not
394 * a commit object already. parse_commit() will return failure
395 * without further complaints in such a case. Otherwise, if
396 * the commit is invalid, parse_commit() will complain. So
397 * there is nothing for us to say here. Just return failure.
399 if (parse_commit(head_commit))
402 if (!active_cache_tree)
403 active_cache_tree = cache_tree();
405 if (!cache_tree_fully_valid(active_cache_tree))
406 if (cache_tree_update(&the_index, 0))
407 return error(_("unable to update cache tree\n"));
409 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
413 * Read the author-script file into an environment block, ready for use in
414 * run_command(), that can be free()d afterwards.
416 static char **read_author_script(void)
418 struct strbuf script = STRBUF_INIT;
423 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
426 for (p = script.buf; *p; p++)
427 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
428 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
430 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
431 else if (*p == '\n') {
436 env_size = (count + 1) * sizeof(*env);
437 strbuf_grow(&script, env_size);
438 memmove(script.buf + env_size, script.buf, script.len);
439 p = script.buf + env_size;
440 env = (char **)strbuf_detach(&script, NULL);
442 for (i = 0; i < count; i++) {
451 static const char staged_changes_advice[] =
452 N_("you have staged changes in your working tree\n"
453 "If these changes are meant to be squashed into the previous commit, run:\n"
455 " git commit --amend %s\n"
457 "If they are meant to go into a new commit, run:\n"
461 "In both cases, once you're done, continue with:\n"
463 " git rebase --continue\n");
466 * If we are cherry-pick, and if the merge did not result in
467 * hand-editing, we will hit this commit and inherit the original
468 * author date and name.
470 * If we are revert, or if our cherry-pick results in a hand merge,
471 * we had better say that the current user is responsible for that.
473 * An exception is when run_git_commit() is called during an
474 * interactive rebase: in that case, we will want to retain the
477 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
478 int allow_empty, int edit, int amend,
479 int cleanup_commit_message)
482 struct argv_array array;
486 if (is_rebase_i(opts)) {
487 env = read_author_script();
489 const char *gpg_opt = gpg_sign_opt_quoted(opts);
491 return error(_(staged_changes_advice),
496 argv_array_init(&array);
497 argv_array_push(&array, "commit");
498 argv_array_push(&array, "-n");
501 argv_array_push(&array, "--amend");
503 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
505 argv_array_push(&array, "-s");
507 argv_array_pushl(&array, "-F", defmsg, NULL);
508 if (cleanup_commit_message)
509 argv_array_push(&array, "--cleanup=strip");
511 argv_array_push(&array, "-e");
512 else if (!cleanup_commit_message &&
513 !opts->signoff && !opts->record_origin &&
514 git_config_get_value("commit.cleanup", &value))
515 argv_array_push(&array, "--cleanup=verbatim");
518 argv_array_push(&array, "--allow-empty");
520 if (opts->allow_empty_message)
521 argv_array_push(&array, "--allow-empty-message");
523 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
524 (const char *const *)env);
525 argv_array_clear(&array);
531 static int is_original_commit_empty(struct commit *commit)
533 const unsigned char *ptree_sha1;
535 if (parse_commit(commit))
536 return error(_("could not parse commit %s\n"),
537 oid_to_hex(&commit->object.oid));
538 if (commit->parents) {
539 struct commit *parent = commit->parents->item;
540 if (parse_commit(parent))
541 return error(_("could not parse parent commit %s\n"),
542 oid_to_hex(&parent->object.oid));
543 ptree_sha1 = parent->tree->object.oid.hash;
545 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
548 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
552 * Do we run "git commit" with "--allow-empty"?
554 * Or do we just skip this empty commit?
556 * Returns 1 if a commit should be done with --allow-empty,
557 * 0 if a commit should be done without --allow-empty,
558 * 2 if no commit should be done at all (skip empty commit)
559 * negative values in case of error
562 static int allow_or_skip_empty(struct replay_opts *opts, struct commit *commit)
564 int index_unchanged, empty_commit;
569 * (1) we do not allow empty at all and error out;
571 * (2) we skip empty commits altogether;
573 * (3) we allow ones that were initially empty, but
574 * forbid the ones that become empty;
578 if (!opts->allow_empty && !opts->skip_empty)
579 return 0; /* let "git commit" barf as necessary */
581 index_unchanged = is_index_unchanged();
582 if (index_unchanged < 0)
583 return index_unchanged;
584 if (!index_unchanged)
585 return 0; /* we do not have to say --allow-empty */
587 if (opts->skip_empty)
590 if (opts->keep_redundant_commits)
593 empty_commit = is_original_commit_empty(commit);
594 if (empty_commit < 0)
607 static const char *todo_command_strings[] = {
612 static const char *command_to_string(const enum todo_command command)
614 if ((size_t)command < ARRAY_SIZE(todo_command_strings))
615 return todo_command_strings[command];
616 die("Unknown command: %d", command);
620 static int do_pick_commit(enum todo_command command, struct commit *commit,
621 struct replay_opts *opts)
623 unsigned char head[20];
624 struct commit *base, *next, *parent;
625 const char *base_label, *next_label;
626 struct commit_message msg = { NULL, NULL, NULL, NULL };
627 struct strbuf msgbuf = STRBUF_INIT;
628 int res = 0, unborn = 0, allow;
630 if (opts->no_commit) {
632 * We do not intend to commit immediately. We just want to
633 * merge the differences in, so let's compute the tree
634 * that represents the "current" state for merge-recursive
637 if (write_cache_as_tree(head, 0, NULL))
638 return error(_("your index file is unmerged."));
640 unborn = get_sha1("HEAD", head);
642 hashcpy(head, EMPTY_TREE_SHA1_BIN);
643 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
644 return error_dirty_index(opts);
648 if (!commit->parents) {
651 else if (commit->parents->next) {
652 /* Reverting or cherry-picking a merge commit */
654 struct commit_list *p;
657 return error(_("commit %s is a merge but no -m option was given."),
658 oid_to_hex(&commit->object.oid));
660 for (cnt = 1, p = commit->parents;
661 cnt != opts->mainline && p;
664 if (cnt != opts->mainline || !p)
665 return error(_("commit %s does not have parent %d"),
666 oid_to_hex(&commit->object.oid), opts->mainline);
668 } else if (0 < opts->mainline)
669 return error(_("mainline was specified but commit %s is not a merge."),
670 oid_to_hex(&commit->object.oid));
672 parent = commit->parents->item;
674 if (opts->allow_ff &&
675 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
676 (!parent && unborn)))
677 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
679 if (parent && parse_commit(parent) < 0)
680 /* TRANSLATORS: The first %s will be a "todo" command like
681 "revert" or "pick", the second %s a SHA1. */
682 return error(_("%s: cannot parse parent commit %s"),
683 command_to_string(command),
684 oid_to_hex(&parent->object.oid));
686 if (get_message(commit, &msg) != 0)
687 return error(_("cannot get commit message for %s"),
688 oid_to_hex(&commit->object.oid));
691 * "commit" is an existing commit. We would want to apply
692 * the difference it introduces since its first parent "prev"
693 * on top of the current HEAD if we are cherry-pick. Or the
694 * reverse of it if we are revert.
697 if (command == TODO_REVERT) {
699 base_label = msg.label;
701 next_label = msg.parent_label;
702 strbuf_addstr(&msgbuf, "Revert \"");
703 strbuf_addstr(&msgbuf, msg.subject);
704 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
705 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
707 if (commit->parents && commit->parents->next) {
708 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
709 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
711 strbuf_addstr(&msgbuf, ".\n");
716 base_label = msg.parent_label;
718 next_label = msg.label;
721 * Append the commit log message to msgbuf; it starts
722 * after the tree, parent, author, committer
723 * information followed by "\n\n".
725 p = strstr(msg.message, "\n\n");
727 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
729 if (opts->record_origin) {
730 if (!has_conforming_footer(&msgbuf, NULL, 0))
731 strbuf_addch(&msgbuf, '\n');
732 strbuf_addstr(&msgbuf, cherry_picked_prefix);
733 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
734 strbuf_addstr(&msgbuf, ")\n");
738 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
739 res = do_recursive_merge(base, next, base_label, next_label,
740 head, &msgbuf, opts);
743 res |= write_message(msgbuf.buf, msgbuf.len,
744 git_path_merge_msg(), 0);
746 struct commit_list *common = NULL;
747 struct commit_list *remotes = NULL;
749 res = write_message(msgbuf.buf, msgbuf.len,
750 git_path_merge_msg(), 0);
752 commit_list_insert(base, &common);
753 commit_list_insert(next, &remotes);
754 res |= try_merge_command(opts->strategy,
755 opts->xopts_nr, (const char **)opts->xopts,
756 common, sha1_to_hex(head), remotes);
757 free_commit_list(common);
758 free_commit_list(remotes);
760 strbuf_release(&msgbuf);
763 * If the merge was clean or if it failed due to conflict, we write
764 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
765 * However, if the merge did not even start, then we don't want to
768 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
769 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
770 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
772 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
773 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
774 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
778 error(command == TODO_REVERT
779 ? _("could not revert %s... %s")
780 : _("could not apply %s... %s"),
781 short_commit_name(commit), msg.subject);
782 print_advice(res == 1, opts);
783 rerere(opts->allow_rerere_auto);
787 allow = allow_or_skip_empty(opts, commit);
792 /* allow == 2 means skip this commit */
793 if (allow != 2 && !opts->no_commit)
794 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
795 opts, allow, opts->edit, 0, 0);
798 free_message(commit, &msg);
799 update_abort_safety_file();
804 static int prepare_revs(struct replay_opts *opts)
807 * picking (but not reverting) ranges (but not individual revisions)
808 * should be done in reverse
810 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
811 opts->revs->reverse ^= 1;
813 if (prepare_revision_walk(opts->revs))
814 return error(_("revision walk setup failed"));
816 if (!opts->revs->commits)
817 return error(_("empty commit set passed"));
821 static int read_and_refresh_cache(struct replay_opts *opts)
823 static struct lock_file index_lock;
824 int index_fd = hold_locked_index(&index_lock, 0);
825 if (read_index_preload(&the_index, NULL) < 0) {
826 rollback_lock_file(&index_lock);
827 return error(_("git %s: failed to read the index"),
828 _(action_name(opts)));
830 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
831 if (the_index.cache_changed && index_fd >= 0) {
832 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
833 rollback_lock_file(&index_lock);
834 return error(_("git %s: failed to refresh the index"),
835 _(action_name(opts)));
838 rollback_lock_file(&index_lock);
843 enum todo_command command;
844 struct commit *commit;
847 size_t offset_in_buf;
852 struct todo_item *items;
853 int nr, alloc, current;
856 #define TODO_LIST_INIT { STRBUF_INIT }
858 static void todo_list_release(struct todo_list *todo_list)
860 strbuf_release(&todo_list->buf);
861 free(todo_list->items);
862 todo_list->items = NULL;
863 todo_list->nr = todo_list->alloc = 0;
866 static struct todo_item *append_new_todo(struct todo_list *todo_list)
868 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
869 return todo_list->items + todo_list->nr++;
872 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
874 unsigned char commit_sha1[20];
875 char *end_of_object_name;
876 int i, saved, status, padding;
879 bol += strspn(bol, " \t");
881 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
882 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
886 if (i >= ARRAY_SIZE(todo_command_strings))
889 /* Eat up extra spaces/ tabs before object name */
890 padding = strspn(bol, " \t");
895 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
896 saved = *end_of_object_name;
897 *end_of_object_name = '\0';
898 status = get_sha1(bol, commit_sha1);
899 *end_of_object_name = saved;
901 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
902 item->arg_len = (int)(eol - item->arg);
907 item->commit = lookup_commit_reference(commit_sha1);
908 return !item->commit;
911 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
913 struct todo_item *item;
914 char *p = buf, *next_p;
917 for (i = 1; *p; i++, p = next_p) {
918 char *eol = strchrnul(p, '\n');
920 next_p = *eol ? eol + 1 /* skip LF */ : eol;
922 if (p != eol && eol[-1] == '\r')
923 eol--; /* strip Carriage Return */
925 item = append_new_todo(todo_list);
926 item->offset_in_buf = p - todo_list->buf.buf;
927 if (parse_insn_line(item, p, eol)) {
928 res = error(_("invalid line %d: %.*s"),
929 i, (int)(eol - p), p);
934 return error(_("no commits parsed."));
938 static int read_populate_todo(struct todo_list *todo_list,
939 struct replay_opts *opts)
941 const char *todo_file = get_todo_path(opts);
944 strbuf_reset(&todo_list->buf);
945 fd = open(todo_file, O_RDONLY);
947 return error_errno(_("could not open '%s'"), todo_file);
948 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
950 return error(_("could not read '%s'."), todo_file);
954 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
956 return error(_("unusable instruction sheet: '%s'"), todo_file);
958 if (!is_rebase_i(opts)) {
959 enum todo_command valid =
960 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
963 for (i = 0; i < todo_list->nr; i++)
964 if (valid == todo_list->items[i].command)
966 else if (valid == TODO_PICK)
967 return error(_("cannot cherry-pick during a revert."));
969 return error(_("cannot revert during a cherry-pick."));
975 static int git_config_string_dup(char **dest,
976 const char *var, const char *value)
979 return config_error_nonbool(var);
981 *dest = xstrdup(value);
985 static int populate_opts_cb(const char *key, const char *value, void *data)
987 struct replay_opts *opts = data;
992 else if (!strcmp(key, "options.no-commit"))
993 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
994 else if (!strcmp(key, "options.edit"))
995 opts->edit = git_config_bool_or_int(key, value, &error_flag);
996 else if (!strcmp(key, "options.signoff"))
997 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
998 else if (!strcmp(key, "options.record-origin"))
999 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1000 else if (!strcmp(key, "options.skip-empty"))
1001 opts->skip_empty = git_config_bool_or_int(key, value, &error_flag);
1002 else if (!strcmp(key, "options.allow-ff"))
1003 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1004 else if (!strcmp(key, "options.mainline"))
1005 opts->mainline = git_config_int(key, value);
1006 else if (!strcmp(key, "options.strategy"))
1007 git_config_string_dup(&opts->strategy, key, value);
1008 else if (!strcmp(key, "options.gpg-sign"))
1009 git_config_string_dup(&opts->gpg_sign, key, value);
1010 else if (!strcmp(key, "options.strategy-option")) {
1011 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1012 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1014 return error(_("invalid key: %s"), key);
1017 return error(_("invalid value for %s: %s"), key, value);
1022 static int read_populate_opts(struct replay_opts *opts)
1024 if (is_rebase_i(opts)) {
1025 struct strbuf buf = STRBUF_INIT;
1027 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1028 if (!starts_with(buf.buf, "-S"))
1031 free(opts->gpg_sign);
1032 opts->gpg_sign = xstrdup(buf.buf + 2);
1035 strbuf_release(&buf);
1040 if (!file_exists(git_path_opts_file()))
1043 * The function git_parse_source(), called from git_config_from_file(),
1044 * may die() in case of a syntactically incorrect file. We do not care
1045 * about this case, though, because we wrote that file ourselves, so we
1046 * are pretty certain that it is syntactically correct.
1048 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1049 return error(_("malformed options sheet: '%s'"),
1050 git_path_opts_file());
1054 static int walk_revs_populate_todo(struct todo_list *todo_list,
1055 struct replay_opts *opts)
1057 enum todo_command command = opts->action == REPLAY_PICK ?
1058 TODO_PICK : TODO_REVERT;
1059 const char *command_string = todo_command_strings[command];
1060 struct commit *commit;
1062 if (prepare_revs(opts))
1065 while ((commit = get_revision(opts->revs))) {
1066 struct todo_item *item = append_new_todo(todo_list);
1067 const char *commit_buffer = get_commit_buffer(commit, NULL);
1068 const char *subject;
1071 item->command = command;
1072 item->commit = commit;
1075 item->offset_in_buf = todo_list->buf.len;
1076 subject_len = find_commit_subject(commit_buffer, &subject);
1077 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1078 short_commit_name(commit), subject_len, subject);
1079 unuse_commit_buffer(commit, commit_buffer);
1084 static int create_seq_dir(void)
1086 if (file_exists(git_path_seq_dir())) {
1087 error(_("a cherry-pick or revert is already in progress"));
1088 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1091 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1092 return error_errno(_("could not create sequencer directory '%s'"),
1093 git_path_seq_dir());
1097 static int save_head(const char *head)
1099 static struct lock_file head_lock;
1100 struct strbuf buf = STRBUF_INIT;
1103 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1105 rollback_lock_file(&head_lock);
1106 return error_errno(_("could not lock HEAD"));
1108 strbuf_addf(&buf, "%s\n", head);
1109 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1110 rollback_lock_file(&head_lock);
1111 return error_errno(_("could not write to '%s'"),
1112 git_path_head_file());
1114 if (commit_lock_file(&head_lock) < 0) {
1115 rollback_lock_file(&head_lock);
1116 return error(_("failed to finalize '%s'."), git_path_head_file());
1121 static int rollback_is_safe(void)
1123 struct strbuf sb = STRBUF_INIT;
1124 struct object_id expected_head, actual_head;
1126 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1128 if (get_oid_hex(sb.buf, &expected_head)) {
1129 strbuf_release(&sb);
1130 die(_("could not parse %s"), git_path_abort_safety_file());
1132 strbuf_release(&sb);
1134 else if (errno == ENOENT)
1135 oidclr(&expected_head);
1137 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1139 if (get_oid("HEAD", &actual_head))
1140 oidclr(&actual_head);
1142 return !oidcmp(&actual_head, &expected_head);
1145 static int reset_for_rollback(const unsigned char *sha1)
1147 const char *argv[4]; /* reset --merge <arg> + NULL */
1150 argv[1] = "--merge";
1151 argv[2] = sha1_to_hex(sha1);
1153 return run_command_v_opt(argv, RUN_GIT_CMD);
1156 static int rollback_single_pick(void)
1158 unsigned char head_sha1[20];
1160 if (!file_exists(git_path_cherry_pick_head()) &&
1161 !file_exists(git_path_revert_head()))
1162 return error(_("no cherry-pick or revert in progress"));
1163 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1164 return error(_("cannot resolve HEAD"));
1165 if (is_null_sha1(head_sha1))
1166 return error(_("cannot abort from a branch yet to be born"));
1167 return reset_for_rollback(head_sha1);
1170 int sequencer_rollback(struct replay_opts *opts)
1173 unsigned char sha1[20];
1174 struct strbuf buf = STRBUF_INIT;
1176 f = fopen(git_path_head_file(), "r");
1177 if (!f && errno == ENOENT) {
1179 * There is no multiple-cherry-pick in progress.
1180 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1181 * a single-cherry-pick in progress, abort that.
1183 return rollback_single_pick();
1186 return error_errno(_("cannot open '%s'"), git_path_head_file());
1187 if (strbuf_getline_lf(&buf, f)) {
1188 error(_("cannot read '%s': %s"), git_path_head_file(),
1189 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1194 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1195 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1196 git_path_head_file());
1199 if (is_null_sha1(sha1)) {
1200 error(_("cannot abort from a branch yet to be born"));
1204 if (!rollback_is_safe()) {
1205 /* Do not error, just do not rollback */
1206 warning(_("You seem to have moved HEAD. "
1207 "Not rewinding, check your HEAD!"));
1209 if (reset_for_rollback(sha1))
1211 strbuf_release(&buf);
1212 return sequencer_remove_state(opts);
1214 strbuf_release(&buf);
1218 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1220 static struct lock_file todo_lock;
1221 const char *todo_path = get_todo_path(opts);
1222 int next = todo_list->current, offset, fd;
1224 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1226 return error_errno(_("could not lock '%s'"), todo_path);
1227 offset = next < todo_list->nr ?
1228 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1229 if (write_in_full(fd, todo_list->buf.buf + offset,
1230 todo_list->buf.len - offset) < 0)
1231 return error_errno(_("could not write to '%s'"), todo_path);
1232 if (commit_lock_file(&todo_lock) < 0)
1233 return error(_("failed to finalize '%s'."), todo_path);
1237 static int save_opts(struct replay_opts *opts)
1239 const char *opts_file = git_path_opts_file();
1242 if (opts->no_commit)
1243 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1245 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1247 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1248 if (opts->record_origin)
1249 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1250 if (opts->skip_empty)
1251 res |= git_config_set_in_file_gently(opts_file, "options.skip-empty", "true");
1253 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1254 if (opts->mainline) {
1255 struct strbuf buf = STRBUF_INIT;
1256 strbuf_addf(&buf, "%d", opts->mainline);
1257 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1258 strbuf_release(&buf);
1261 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1263 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1266 for (i = 0; i < opts->xopts_nr; i++)
1267 res |= git_config_set_multivar_in_file_gently(opts_file,
1268 "options.strategy-option",
1269 opts->xopts[i], "^$", 0);
1274 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1278 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1280 assert(!(opts->signoff || opts->no_commit ||
1281 opts->record_origin || opts->edit));
1282 if (read_and_refresh_cache(opts))
1285 while (todo_list->current < todo_list->nr) {
1286 struct todo_item *item = todo_list->items + todo_list->current;
1287 if (save_todo(todo_list, opts))
1289 res = do_pick_commit(item->command, item->commit, opts);
1290 todo_list->current++;
1296 * Sequence of picks finished successfully; cleanup by
1297 * removing the .git/sequencer directory
1299 return sequencer_remove_state(opts);
1302 static int continue_single_pick(void)
1304 const char *argv[] = { "commit", NULL };
1306 if (!file_exists(git_path_cherry_pick_head()) &&
1307 !file_exists(git_path_revert_head()))
1308 return error(_("no cherry-pick or revert in progress"));
1309 return run_command_v_opt(argv, RUN_GIT_CMD);
1313 * Continue the sequencing, after either committing
1314 * (cmd == 'c') or skipping (cmd == 's') the current
1317 int sequencer_continue(struct replay_opts *opts, char cmd)
1319 struct todo_list todo_list = TODO_LIST_INIT;
1322 if (read_and_refresh_cache(opts))
1325 if (!file_exists(get_todo_path(opts))) {
1327 return continue_single_pick();
1330 /* Skipping the only commit is equivalent to an abort */
1331 return sequencer_rollback(opts);
1334 if (read_populate_opts(opts))
1336 if ((res = read_populate_todo(&todo_list, opts)))
1337 goto release_todo_list;
1339 /* If we were asked to skip this commit, rollback
1340 * and continue with the next */
1342 if ((res = rollback_single_pick()))
1343 goto release_todo_list;
1344 cache_tree_free(&active_cache_tree);
1345 if ((res = read_cache()) < 0)
1346 goto release_todo_list;
1347 printf("index unchanged: %d\n", is_index_unchanged());
1348 goto skip_this_commit;
1351 /* check if there is something to commit */
1352 res = is_index_unchanged();
1354 goto release_todo_list;
1356 if (res && opts->skip_empty)
1357 goto skip_this_commit;
1359 /* Verify that the conflict has been resolved */
1360 if (file_exists(git_path_cherry_pick_head()) ||
1361 file_exists(git_path_revert_head())) {
1362 res = continue_single_pick();
1364 goto release_todo_list;
1366 if (index_differs_from("HEAD", 0, 0)) {
1367 res = error_dirty_index(opts);
1368 goto release_todo_list;
1371 todo_list.current++;
1372 res = pick_commits(&todo_list, opts);
1374 todo_list_release(&todo_list);
1378 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1380 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1381 return do_pick_commit(opts->action == REPLAY_PICK ?
1382 TODO_PICK : TODO_REVERT, cmit, opts);
1385 int sequencer_pick_revisions(struct replay_opts *opts)
1387 struct todo_list todo_list = TODO_LIST_INIT;
1388 unsigned char sha1[20];
1392 if (read_and_refresh_cache(opts))
1395 for (i = 0; i < opts->revs->pending.nr; i++) {
1396 unsigned char sha1[20];
1397 const char *name = opts->revs->pending.objects[i].name;
1399 /* This happens when using --stdin. */
1403 if (!get_sha1(name, sha1)) {
1404 if (!lookup_commit_reference_gently(sha1, 1)) {
1405 enum object_type type = sha1_object_info(sha1, NULL);
1406 return error(_("%s: can't cherry-pick a %s"),
1407 name, typename(type));
1410 return error(_("%s: bad revision"), name);
1414 * If we were called as "git cherry-pick <commit>", just
1415 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1416 * REVERT_HEAD, and don't touch the sequencer state.
1417 * This means it is possible to cherry-pick in the middle
1418 * of a cherry-pick sequence.
1420 if (opts->revs->cmdline.nr == 1 &&
1421 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1422 opts->revs->no_walk &&
1423 !opts->revs->cmdline.rev->flags) {
1424 struct commit *cmit;
1425 if (prepare_revision_walk(opts->revs))
1426 return error(_("revision walk setup failed"));
1427 cmit = get_revision(opts->revs);
1428 if (!cmit || get_revision(opts->revs))
1429 return error("BUG: expected exactly one commit from walk");
1430 return single_pick(cmit, opts);
1434 * Start a new cherry-pick/ revert sequence; but
1435 * first, make sure that an existing one isn't in
1439 if (walk_revs_populate_todo(&todo_list, opts) ||
1440 create_seq_dir() < 0)
1442 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1443 return error(_("can't revert as initial commit"));
1444 if (save_head(sha1_to_hex(sha1)))
1446 if (save_opts(opts))
1448 update_abort_safety_file();
1449 res = pick_commits(&todo_list, opts);
1450 todo_list_release(&todo_list);
1454 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1456 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1457 struct strbuf sob = STRBUF_INIT;
1460 strbuf_addstr(&sob, sign_off_header);
1461 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1462 getenv("GIT_COMMITTER_EMAIL")));
1463 strbuf_addch(&sob, '\n');
1466 * If the whole message buffer is equal to the sob, pretend that we
1467 * found a conforming footer with a matching sob
1469 if (msgbuf->len - ignore_footer == sob.len &&
1470 !strncmp(msgbuf->buf, sob.buf, sob.len))
1473 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1476 const char *append_newlines = NULL;
1477 size_t len = msgbuf->len - ignore_footer;
1481 * The buffer is completely empty. Leave foom for
1482 * the title and body to be filled in by the user.
1484 append_newlines = "\n\n";
1485 } else if (msgbuf->buf[len - 1] != '\n') {
1487 * Incomplete line. Complete the line and add a
1488 * blank one so that there is an empty line between
1489 * the message body and the sob.
1491 append_newlines = "\n\n";
1492 } else if (len == 1) {
1494 * Buffer contains a single newline. Add another
1495 * so that we leave room for the title and body.
1497 append_newlines = "\n";
1498 } else if (msgbuf->buf[len - 2] != '\n') {
1500 * Buffer ends with a single newline. Add another
1501 * so that there is an empty line between the message
1504 append_newlines = "\n";
1505 } /* else, the buffer already ends with two newlines. */
1507 if (append_newlines)
1508 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1509 append_newlines, strlen(append_newlines));
1512 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1513 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1516 strbuf_release(&sob);