5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-ort.h"
18 #include "merge-ort-wrappers.h"
24 #include "wt-status.h"
26 #include "notes-utils.h"
28 #include "unpack-trees.h"
32 #include "commit-slab.h"
34 #include "commit-reach.h"
35 #include "rebase-interactive.h"
38 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40 static const char sign_off_header[] = "Signed-off-by: ";
41 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
48 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
49 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
50 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 * The file containing rebase commands, comments, and empty lines.
55 * This file is created by "git rebase -i" then edited by the user. As
56 * the lines are processed, they are removed from the front of this
57 * file and written to the tail of 'done'.
59 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
60 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65 * The rebase command lines that have already been processed. A line
66 * is moved here when it is first handled, before any associated user
69 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 * The file to keep track of how many commands were already processed (e.g.
74 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 * The file to keep track of how many commands are to be processed in total
77 * (e.g. for the prompt).
79 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 * The commit message that is planned to be used for any changes that
82 * need to be committed following a user interaction.
84 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 * The file into which is accumulated the suggested commit message for
87 * squash/fixup commands. When the first of a series of squash/fixups
88 * is seen, the file is created and the commit message from the
89 * previous commit and from the first squash/fixup commit are written
90 * to it. The commit message for each subsequent squash/fixup commit
91 * is appended to the file as it is processed.
93 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 * If the current series of squash/fixups has not yet included a squash
96 * command, then this file exists and holds the commit message of the
97 * original "pick" commit. (If the series ends without a "squash"
98 * command, then this can be used as the commit message of the combined
99 * commit without opening the editor.)
101 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 * This file contains the list fixup/squash commands that have been
104 * accumulated into message-fixup or message-squash so far.
106 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
109 * GIT_AUTHOR_DATE that will be used for the commit that is currently
112 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 * When an "edit" rebase command is being processed, the SHA1 of the
115 * commit to be edited is recorded in this file. When "git rebase
116 * --continue" is executed, if there are any staged changes then they
117 * will be amended to the HEAD commit, but only provided the HEAD
118 * commit is still the commit to be edited. When any other rebase
119 * command is processed, this file is deleted.
121 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 * When we stop at a given patch via the "edit" command, this file contains
124 * the commit object name of the corresponding patch.
126 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 * For the post-rewrite hook, we make a list of rewritten commits and
129 * their new sha1s. The rewritten-pending list keeps the sha1s of
130 * commits that have been processed, but not committed yet,
131 * e.g. because they are waiting for a 'squash' command.
133 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
134 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
135 "rebase-merge/rewritten-pending")
138 * The path of the file containing the OID of the "squash onto" commit, i.e.
139 * the dummy commit used for `reset [new root]`.
141 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144 * The path of the file listing refs that need to be deleted after the rebase
145 * finishes. This is used by the `label` command to record the need for cleanup.
147 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150 * The following files are written by git-rebase just after parsing the
153 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
154 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
155 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
156 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
157 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
158 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
159 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
160 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
161 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
162 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
163 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
164 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
165 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
166 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
167 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
169 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
171 static int git_sequencer_config(const char *k, const char *v, void *cb)
173 struct replay_opts *opts = cb;
176 if (!strcmp(k, "commit.cleanup")) {
179 status = git_config_string(&s, k, v);
183 if (!strcmp(s, "verbatim")) {
184 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
185 opts->explicit_cleanup = 1;
186 } else if (!strcmp(s, "whitespace")) {
187 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
188 opts->explicit_cleanup = 1;
189 } else if (!strcmp(s, "strip")) {
190 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
191 opts->explicit_cleanup = 1;
192 } else if (!strcmp(s, "scissors")) {
193 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
194 opts->explicit_cleanup = 1;
196 warning(_("invalid commit message cleanup mode '%s'"),
204 if (!strcmp(k, "commit.gpgsign")) {
205 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
209 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
210 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
213 * pull.twohead is allowed to be multi-valued; we only
214 * care about the first value.
216 char *tmp = strchr(opts->default_strategy, ' ');
223 status = git_gpg_config(k, v, NULL);
227 return git_diff_basic_config(k, v, NULL);
230 void sequencer_init_config(struct replay_opts *opts)
232 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
233 git_config(git_sequencer_config, opts);
236 static inline int is_rebase_i(const struct replay_opts *opts)
238 return opts->action == REPLAY_INTERACTIVE_REBASE;
241 static const char *get_dir(const struct replay_opts *opts)
243 if (is_rebase_i(opts))
244 return rebase_path();
245 return git_path_seq_dir();
248 static const char *get_todo_path(const struct replay_opts *opts)
250 if (is_rebase_i(opts))
251 return rebase_path_todo();
252 return git_path_todo_file();
256 * Returns 0 for non-conforming footer
257 * Returns 1 for conforming footer
258 * Returns 2 when sob exists within conforming footer
259 * Returns 3 when sob exists within conforming footer as last entry
261 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
262 size_t ignore_footer)
264 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
265 struct trailer_info info;
267 int found_sob = 0, found_sob_last = 0;
273 saved_char = sb->buf[sb->len - ignore_footer];
274 sb->buf[sb->len - ignore_footer] = '\0';
277 trailer_info_get(&info, sb->buf, &opts);
280 sb->buf[sb->len - ignore_footer] = saved_char;
282 if (info.trailer_start == info.trailer_end)
285 for (i = 0; i < info.trailer_nr; i++)
286 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
288 if (i == info.trailer_nr - 1)
292 trailer_info_release(&info);
301 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
303 static struct strbuf buf = STRBUF_INIT;
307 sq_quotef(&buf, "-S%s", opts->gpg_sign);
311 int sequencer_remove_state(struct replay_opts *opts)
313 struct strbuf buf = STRBUF_INIT;
316 if (is_rebase_i(opts) &&
317 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
320 char *eol = strchr(p, '\n');
323 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
324 warning(_("could not delete '%s'"), p);
333 free(opts->gpg_sign);
334 free(opts->default_strategy);
335 free(opts->strategy);
336 for (i = 0; i < opts->xopts_nr; i++)
337 free(opts->xopts[i]);
339 strbuf_release(&opts->current_fixups);
342 strbuf_addstr(&buf, get_dir(opts));
343 if (remove_dir_recursively(&buf, 0))
344 ret = error(_("could not remove '%s'"), buf.buf);
345 strbuf_release(&buf);
350 static const char *action_name(const struct replay_opts *opts)
352 switch (opts->action) {
356 return N_("cherry-pick");
357 case REPLAY_INTERACTIVE_REBASE:
360 die(_("unknown action: %d"), opts->action);
363 struct commit_message {
370 static const char *short_commit_name(struct commit *commit)
372 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
375 static int get_message(struct commit *commit, struct commit_message *out)
377 const char *abbrev, *subject;
380 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
381 abbrev = short_commit_name(commit);
383 subject_len = find_commit_subject(out->message, &subject);
385 out->subject = xmemdupz(subject, subject_len);
386 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
387 out->parent_label = xstrfmt("parent of %s", out->label);
392 static void free_message(struct commit *commit, struct commit_message *msg)
394 free(msg->parent_label);
397 unuse_commit_buffer(commit, msg->message);
400 static void print_advice(struct repository *r, int show_hint,
401 struct replay_opts *opts)
403 char *msg = getenv("GIT_CHERRY_PICK_HELP");
406 fprintf(stderr, "%s\n", msg);
408 * A conflict has occurred but the porcelain
409 * (typically rebase --interactive) wants to take care
410 * of the commit itself so remove CHERRY_PICK_HEAD
412 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
419 advise(_("after resolving the conflicts, mark the corrected paths\n"
420 "with 'git add <paths>' or 'git rm <paths>'"));
422 advise(_("after resolving the conflicts, mark the corrected paths\n"
423 "with 'git add <paths>' or 'git rm <paths>'\n"
424 "and commit the result with 'git commit'"));
428 static int write_message(const void *buf, size_t len, const char *filename,
431 struct lock_file msg_file = LOCK_INIT;
433 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
435 return error_errno(_("could not lock '%s'"), filename);
436 if (write_in_full(msg_fd, buf, len) < 0) {
437 error_errno(_("could not write to '%s'"), filename);
438 rollback_lock_file(&msg_file);
441 if (append_eol && write(msg_fd, "\n", 1) < 0) {
442 error_errno(_("could not write eol to '%s'"), filename);
443 rollback_lock_file(&msg_file);
446 if (commit_lock_file(&msg_file) < 0)
447 return error(_("failed to finalize '%s'"), filename);
452 int read_oneliner(struct strbuf *buf,
453 const char *path, unsigned flags)
455 int orig_len = buf->len;
457 if (strbuf_read_file(buf, path, 0) < 0) {
458 if ((flags & READ_ONELINER_WARN_MISSING) ||
459 (errno != ENOENT && errno != ENOTDIR))
460 warning_errno(_("could not read '%s'"), path);
464 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
465 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
467 buf->buf[buf->len] = '\0';
470 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
476 static struct tree *empty_tree(struct repository *r)
478 return lookup_tree(r, the_hash_algo->empty_tree);
481 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
483 if (repo_read_index_unmerged(repo))
484 return error_resolve_conflict(_(action_name(opts)));
486 error(_("your local changes would be overwritten by %s."),
487 _(action_name(opts)));
489 if (advice_commit_before_merge)
490 advise(_("commit your changes or stash them to proceed."));
494 static void update_abort_safety_file(void)
496 struct object_id head;
498 /* Do nothing on a single-pick */
499 if (!file_exists(git_path_seq_dir()))
502 if (!get_oid("HEAD", &head))
503 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
505 write_file(git_path_abort_safety_file(), "%s", "");
508 static int fast_forward_to(struct repository *r,
509 const struct object_id *to,
510 const struct object_id *from,
512 struct replay_opts *opts)
514 struct ref_transaction *transaction;
515 struct strbuf sb = STRBUF_INIT;
516 struct strbuf err = STRBUF_INIT;
519 if (checkout_fast_forward(r, from, to, 1))
520 return -1; /* the callee should have complained already */
522 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
524 transaction = ref_transaction_begin(&err);
526 ref_transaction_update(transaction, "HEAD",
527 to, unborn && !is_rebase_i(opts) ?
530 ref_transaction_commit(transaction, &err)) {
531 ref_transaction_free(transaction);
532 error("%s", err.buf);
534 strbuf_release(&err);
539 strbuf_release(&err);
540 ref_transaction_free(transaction);
541 update_abort_safety_file();
545 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
548 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
549 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
550 COMMIT_MSG_CLEANUP_SPACE;
551 else if (!strcmp(cleanup_arg, "verbatim"))
552 return COMMIT_MSG_CLEANUP_NONE;
553 else if (!strcmp(cleanup_arg, "whitespace"))
554 return COMMIT_MSG_CLEANUP_SPACE;
555 else if (!strcmp(cleanup_arg, "strip"))
556 return COMMIT_MSG_CLEANUP_ALL;
557 else if (!strcmp(cleanup_arg, "scissors"))
558 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
559 COMMIT_MSG_CLEANUP_SPACE;
561 die(_("Invalid cleanup mode %s"), cleanup_arg);
565 * NB using int rather than enum cleanup_mode to stop clang's
566 * -Wtautological-constant-out-of-range-compare complaining that the comparison
569 static const char *describe_cleanup_mode(int cleanup_mode)
571 static const char *modes[] = { "whitespace",
576 if (cleanup_mode < ARRAY_SIZE(modes))
577 return modes[cleanup_mode];
579 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
582 void append_conflicts_hint(struct index_state *istate,
583 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
587 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
588 strbuf_addch(msgbuf, '\n');
589 wt_status_append_cut_line(msgbuf);
590 strbuf_addch(msgbuf, comment_line_char);
593 strbuf_addch(msgbuf, '\n');
594 strbuf_commented_addf(msgbuf, "Conflicts:\n");
595 for (i = 0; i < istate->cache_nr;) {
596 const struct cache_entry *ce = istate->cache[i++];
598 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
599 while (i < istate->cache_nr &&
600 !strcmp(ce->name, istate->cache[i]->name))
606 static int do_recursive_merge(struct repository *r,
607 struct commit *base, struct commit *next,
608 const char *base_label, const char *next_label,
609 struct object_id *head, struct strbuf *msgbuf,
610 struct replay_opts *opts)
612 struct merge_options o;
613 struct merge_result result;
614 struct tree *next_tree, *base_tree, *head_tree;
615 int clean, show_output;
617 struct lock_file index_lock = LOCK_INIT;
619 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
624 init_merge_options(&o, r);
625 o.ancestor = base ? base_label : "(empty tree)";
627 o.branch2 = next ? next_label : "(empty tree)";
628 if (is_rebase_i(opts))
630 o.show_rename_progress = 1;
632 head_tree = parse_tree_indirect(head);
633 next_tree = next ? get_commit_tree(next) : empty_tree(r);
634 base_tree = base ? get_commit_tree(base) : empty_tree(r);
636 for (i = 0; i < opts->xopts_nr; i++)
637 parse_merge_opt(&o, opts->xopts[i]);
639 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
640 memset(&result, 0, sizeof(result));
641 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
643 show_output = !is_rebase_i(opts) || !result.clean;
645 * TODO: merge_switch_to_result will update index/working tree;
646 * we only really want to do that if !result.clean || this is
647 * the final patch to be picked. But determining this is the
648 * final patch would take some work, and "head_tree" would need
649 * to be replace with the tree the index matched before we
650 * started doing any picks.
652 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
653 clean = result.clean;
655 clean = merge_trees(&o, head_tree, next_tree, base_tree);
656 if (is_rebase_i(opts) && clean <= 0)
657 fputs(o.obuf.buf, stdout);
658 strbuf_release(&o.obuf);
661 rollback_lock_file(&index_lock);
665 if (write_locked_index(r->index, &index_lock,
666 COMMIT_LOCK | SKIP_IF_UNCHANGED))
668 * TRANSLATORS: %s will be "revert", "cherry-pick" or
671 return error(_("%s: Unable to write new index file"),
672 _(action_name(opts)));
675 append_conflicts_hint(r->index, msgbuf,
676 opts->default_msg_cleanup);
681 static struct object_id *get_cache_tree_oid(struct index_state *istate)
683 if (!cache_tree_fully_valid(istate->cache_tree))
684 if (cache_tree_update(istate, 0)) {
685 error(_("unable to update cache tree"));
689 return &istate->cache_tree->oid;
692 static int is_index_unchanged(struct repository *r)
694 struct object_id head_oid, *cache_tree_oid;
695 struct commit *head_commit;
696 struct index_state *istate = r->index;
698 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
699 return error(_("could not resolve HEAD commit"));
701 head_commit = lookup_commit(r, &head_oid);
704 * If head_commit is NULL, check_commit, called from
705 * lookup_commit, would have indicated that head_commit is not
706 * a commit object already. parse_commit() will return failure
707 * without further complaints in such a case. Otherwise, if
708 * the commit is invalid, parse_commit() will complain. So
709 * there is nothing for us to say here. Just return failure.
711 if (parse_commit(head_commit))
714 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
717 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
720 static int write_author_script(const char *message)
722 struct strbuf buf = STRBUF_INIT;
727 if (!*message || starts_with(message, "\n")) {
729 /* Missing 'author' line? */
730 unlink(rebase_path_author_script());
732 } else if (skip_prefix(message, "author ", &message))
734 else if ((eol = strchr(message, '\n')))
739 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
740 while (*message && *message != '\n' && *message != '\r')
741 if (skip_prefix(message, " <", &message))
743 else if (*message != '\'')
744 strbuf_addch(&buf, *(message++));
746 strbuf_addf(&buf, "'\\%c'", *(message++));
747 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
748 while (*message && *message != '\n' && *message != '\r')
749 if (skip_prefix(message, "> ", &message))
751 else if (*message != '\'')
752 strbuf_addch(&buf, *(message++));
754 strbuf_addf(&buf, "'\\%c'", *(message++));
755 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
756 while (*message && *message != '\n' && *message != '\r')
757 if (*message != '\'')
758 strbuf_addch(&buf, *(message++));
760 strbuf_addf(&buf, "'\\%c'", *(message++));
761 strbuf_addch(&buf, '\'');
762 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
763 strbuf_release(&buf);
768 * Take a series of KEY='VALUE' lines where VALUE part is
769 * sq-quoted, and append <KEY, VALUE> at the end of the string list
771 static int parse_key_value_squoted(char *buf, struct string_list *list)
774 struct string_list_item *item;
776 char *cp = strchr(buf, '=');
778 np = strchrnul(buf, '\n');
779 return error(_("no key present in '%.*s'"),
780 (int) (np - buf), buf);
782 np = strchrnul(cp, '\n');
784 item = string_list_append(list, buf);
786 buf = np + (*np == '\n');
790 return error(_("unable to dequote value of '%s'"),
792 item->util = xstrdup(cp);
798 * Reads and parses the state directory's "author-script" file, and sets name,
799 * email and date accordingly.
800 * Returns 0 on success, -1 if the file could not be parsed.
802 * The author script is of the format:
804 * GIT_AUTHOR_NAME='$author_name'
805 * GIT_AUTHOR_EMAIL='$author_email'
806 * GIT_AUTHOR_DATE='$author_date'
808 * where $author_name, $author_email and $author_date are quoted. We are strict
809 * with our parsing, as the file was meant to be eval'd in the now-removed
810 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
811 * from what this function expects, it is better to bail out than to do
812 * something that the user does not expect.
814 int read_author_script(const char *path, char **name, char **email, char **date,
817 struct strbuf buf = STRBUF_INIT;
818 struct string_list kv = STRING_LIST_INIT_DUP;
819 int retval = -1; /* assume failure */
820 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
822 if (strbuf_read_file(&buf, path, 256) <= 0) {
823 strbuf_release(&buf);
824 if (errno == ENOENT && allow_missing)
827 return error_errno(_("could not open '%s' for reading"),
831 if (parse_key_value_squoted(buf.buf, &kv))
834 for (i = 0; i < kv.nr; i++) {
835 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
837 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
840 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
842 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
845 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
847 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
851 err = error(_("unknown variable '%s'"),
856 error(_("missing 'GIT_AUTHOR_NAME'"));
858 error(_("missing 'GIT_AUTHOR_EMAIL'"));
860 error(_("missing 'GIT_AUTHOR_DATE'"));
861 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
863 *name = kv.items[name_i].util;
864 *email = kv.items[email_i].util;
865 *date = kv.items[date_i].util;
868 string_list_clear(&kv, !!retval);
869 strbuf_release(&buf);
874 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
875 * file with shell quoting into struct strvec. Returns -1 on
876 * error, 0 otherwise.
878 static int read_env_script(struct strvec *env)
880 char *name, *email, *date;
882 if (read_author_script(rebase_path_author_script(),
883 &name, &email, &date, 0))
886 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
887 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
888 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
896 static char *get_author(const char *message)
901 a = find_commit_header(message, "author", &len);
903 return xmemdupz(a, len);
908 static const char *author_date_from_env_array(const struct strvec *env)
913 for (i = 0; i < env->nr; i++)
914 if (skip_prefix(env->v[i],
915 "GIT_AUTHOR_DATE=", &date))
918 * If GIT_AUTHOR_DATE is missing we should have already errored out when
921 BUG("GIT_AUTHOR_DATE missing from author script");
924 static const char staged_changes_advice[] =
925 N_("you have staged changes in your working tree\n"
926 "If these changes are meant to be squashed into the previous commit, run:\n"
928 " git commit --amend %s\n"
930 "If they are meant to go into a new commit, run:\n"
934 "In both cases, once you're done, continue with:\n"
936 " git rebase --continue\n");
938 #define ALLOW_EMPTY (1<<0)
939 #define EDIT_MSG (1<<1)
940 #define AMEND_MSG (1<<2)
941 #define CLEANUP_MSG (1<<3)
942 #define VERIFY_MSG (1<<4)
943 #define CREATE_ROOT_COMMIT (1<<5)
944 #define VERBATIM_MSG (1<<6)
946 static int run_command_silent_on_success(struct child_process *cmd)
948 struct strbuf buf = STRBUF_INIT;
951 cmd->stdout_to_stderr = 1;
952 rc = pipe_command(cmd,
958 fputs(buf.buf, stderr);
959 strbuf_release(&buf);
964 * If we are cherry-pick, and if the merge did not result in
965 * hand-editing, we will hit this commit and inherit the original
966 * author date and name.
968 * If we are revert, or if our cherry-pick results in a hand merge,
969 * we had better say that the current user is responsible for that.
971 * An exception is when run_git_commit() is called during an
972 * interactive rebase: in that case, we will want to retain the
975 static int run_git_commit(const char *defmsg,
976 struct replay_opts *opts,
979 struct child_process cmd = CHILD_PROCESS_INIT;
981 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
982 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
986 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
987 const char *gpg_opt = gpg_sign_opt_quoted(opts);
989 return error(_(staged_changes_advice),
993 if (opts->committer_date_is_author_date)
994 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
997 author_date_from_env_array(&cmd.env_array));
998 if (opts->ignore_date)
999 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1001 strvec_push(&cmd.args, "commit");
1003 if (!(flags & VERIFY_MSG))
1004 strvec_push(&cmd.args, "-n");
1005 if ((flags & AMEND_MSG))
1006 strvec_push(&cmd.args, "--amend");
1008 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1010 strvec_push(&cmd.args, "--no-gpg-sign");
1012 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1013 else if (!(flags & EDIT_MSG))
1014 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1015 if ((flags & CLEANUP_MSG))
1016 strvec_push(&cmd.args, "--cleanup=strip");
1017 if ((flags & VERBATIM_MSG))
1018 strvec_push(&cmd.args, "--cleanup=verbatim");
1019 if ((flags & EDIT_MSG))
1020 strvec_push(&cmd.args, "-e");
1021 else if (!(flags & CLEANUP_MSG) &&
1022 !opts->signoff && !opts->record_origin &&
1023 !opts->explicit_cleanup)
1024 strvec_push(&cmd.args, "--cleanup=verbatim");
1026 if ((flags & ALLOW_EMPTY))
1027 strvec_push(&cmd.args, "--allow-empty");
1029 if (!(flags & EDIT_MSG))
1030 strvec_push(&cmd.args, "--allow-empty-message");
1032 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1033 return run_command_silent_on_success(&cmd);
1035 return run_command(&cmd);
1038 static int rest_is_empty(const struct strbuf *sb, int start)
1043 /* Check if the rest is just whitespace and Signed-off-by's. */
1044 for (i = start; i < sb->len; i++) {
1045 nl = memchr(sb->buf + i, '\n', sb->len - i);
1051 if (strlen(sign_off_header) <= eol - i &&
1052 starts_with(sb->buf + i, sign_off_header)) {
1057 if (!isspace(sb->buf[i++]))
1064 void cleanup_message(struct strbuf *msgbuf,
1065 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1067 if (verbose || /* Truncate the message just before the diff, if any. */
1068 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1069 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1070 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1071 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1075 * Find out if the message in the strbuf contains only whitespace and
1076 * Signed-off-by lines.
1078 int message_is_empty(const struct strbuf *sb,
1079 enum commit_msg_cleanup_mode cleanup_mode)
1081 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1083 return rest_is_empty(sb, 0);
1087 * See if the user edited the message in the editor or left what
1088 * was in the template intact
1090 int template_untouched(const struct strbuf *sb, const char *template_file,
1091 enum commit_msg_cleanup_mode cleanup_mode)
1093 struct strbuf tmpl = STRBUF_INIT;
1096 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1099 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1102 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1103 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1105 strbuf_release(&tmpl);
1106 return rest_is_empty(sb, start - sb->buf);
1109 int update_head_with_reflog(const struct commit *old_head,
1110 const struct object_id *new_head,
1111 const char *action, const struct strbuf *msg,
1114 struct ref_transaction *transaction;
1115 struct strbuf sb = STRBUF_INIT;
1120 strbuf_addstr(&sb, action);
1121 strbuf_addstr(&sb, ": ");
1124 nl = strchr(msg->buf, '\n');
1126 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1128 strbuf_addbuf(&sb, msg);
1129 strbuf_addch(&sb, '\n');
1132 transaction = ref_transaction_begin(err);
1134 ref_transaction_update(transaction, "HEAD", new_head,
1135 old_head ? &old_head->object.oid : &null_oid,
1137 ref_transaction_commit(transaction, err)) {
1140 ref_transaction_free(transaction);
1141 strbuf_release(&sb);
1146 static int run_rewrite_hook(const struct object_id *oldoid,
1147 const struct object_id *newoid)
1149 struct child_process proc = CHILD_PROCESS_INIT;
1150 const char *argv[3];
1152 struct strbuf sb = STRBUF_INIT;
1154 argv[0] = find_hook("post-rewrite");
1163 proc.stdout_to_stderr = 1;
1164 proc.trace2_hook_name = "post-rewrite";
1166 code = start_command(&proc);
1169 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1170 sigchain_push(SIGPIPE, SIG_IGN);
1171 write_in_full(proc.in, sb.buf, sb.len);
1173 strbuf_release(&sb);
1174 sigchain_pop(SIGPIPE);
1175 return finish_command(&proc);
1178 void commit_post_rewrite(struct repository *r,
1179 const struct commit *old_head,
1180 const struct object_id *new_head)
1182 struct notes_rewrite_cfg *cfg;
1184 cfg = init_copy_notes_for_rewrite("amend");
1186 /* we are amending, so old_head is not NULL */
1187 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1188 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1190 run_rewrite_hook(&old_head->object.oid, new_head);
1193 static int run_prepare_commit_msg_hook(struct repository *r,
1198 const char *name, *arg1 = NULL, *arg2 = NULL;
1200 name = git_path_commit_editmsg();
1201 if (write_message(msg->buf, msg->len, name, 0))
1210 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1212 ret = error(_("'prepare-commit-msg' hook failed"));
1217 static const char implicit_ident_advice_noconfig[] =
1218 N_("Your name and email address were configured automatically based\n"
1219 "on your username and hostname. Please check that they are accurate.\n"
1220 "You can suppress this message by setting them explicitly. Run the\n"
1221 "following command and follow the instructions in your editor to edit\n"
1222 "your configuration file:\n"
1224 " git config --global --edit\n"
1226 "After doing this, you may fix the identity used for this commit with:\n"
1228 " git commit --amend --reset-author\n");
1230 static const char implicit_ident_advice_config[] =
1231 N_("Your name and email address were configured automatically based\n"
1232 "on your username and hostname. Please check that they are accurate.\n"
1233 "You can suppress this message by setting them explicitly:\n"
1235 " git config --global user.name \"Your Name\"\n"
1236 " git config --global user.email you@example.com\n"
1238 "After doing this, you may fix the identity used for this commit with:\n"
1240 " git commit --amend --reset-author\n");
1242 static const char *implicit_ident_advice(void)
1244 char *user_config = expand_user_path("~/.gitconfig", 0);
1245 char *xdg_config = xdg_config_home("config");
1246 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1252 return _(implicit_ident_advice_config);
1254 return _(implicit_ident_advice_noconfig);
1258 void print_commit_summary(struct repository *r,
1260 const struct object_id *oid,
1263 struct rev_info rev;
1264 struct commit *commit;
1265 struct strbuf format = STRBUF_INIT;
1267 struct pretty_print_context pctx = {0};
1268 struct strbuf author_ident = STRBUF_INIT;
1269 struct strbuf committer_ident = STRBUF_INIT;
1271 commit = lookup_commit(r, oid);
1273 die(_("couldn't look up newly created commit"));
1274 if (parse_commit(commit))
1275 die(_("could not parse newly created commit"));
1277 strbuf_addstr(&format, "format:%h] %s");
1279 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1280 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1281 if (strbuf_cmp(&author_ident, &committer_ident)) {
1282 strbuf_addstr(&format, "\n Author: ");
1283 strbuf_addbuf_percentquote(&format, &author_ident);
1285 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1286 struct strbuf date = STRBUF_INIT;
1288 format_commit_message(commit, "%ad", &date, &pctx);
1289 strbuf_addstr(&format, "\n Date: ");
1290 strbuf_addbuf_percentquote(&format, &date);
1291 strbuf_release(&date);
1293 if (!committer_ident_sufficiently_given()) {
1294 strbuf_addstr(&format, "\n Committer: ");
1295 strbuf_addbuf_percentquote(&format, &committer_ident);
1296 if (advice_implicit_identity) {
1297 strbuf_addch(&format, '\n');
1298 strbuf_addstr(&format, implicit_ident_advice());
1301 strbuf_release(&author_ident);
1302 strbuf_release(&committer_ident);
1304 repo_init_revisions(r, &rev, prefix);
1305 setup_revisions(0, NULL, &rev, NULL);
1308 rev.diffopt.output_format =
1309 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1311 rev.verbose_header = 1;
1312 rev.show_root_diff = 1;
1313 get_commit_format(format.buf, &rev);
1314 rev.always_show_header = 0;
1315 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1316 rev.diffopt.break_opt = 0;
1317 diff_setup_done(&rev.diffopt);
1319 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1321 die_errno(_("unable to resolve HEAD after creating commit"));
1322 if (!strcmp(head, "HEAD"))
1323 head = _("detached HEAD");
1325 skip_prefix(head, "refs/heads/", &head);
1326 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1327 _(" (root-commit)") : "");
1329 if (!log_tree_commit(&rev, commit)) {
1330 rev.always_show_header = 1;
1331 rev.use_terminator = 1;
1332 log_tree_commit(&rev, commit);
1335 strbuf_release(&format);
1338 static int parse_head(struct repository *r, struct commit **head)
1340 struct commit *current_head;
1341 struct object_id oid;
1343 if (get_oid("HEAD", &oid)) {
1344 current_head = NULL;
1346 current_head = lookup_commit_reference(r, &oid);
1348 return error(_("could not parse HEAD"));
1349 if (!oideq(&oid, ¤t_head->object.oid)) {
1350 warning(_("HEAD %s is not a commit!"),
1353 if (parse_commit(current_head))
1354 return error(_("could not parse HEAD commit"));
1356 *head = current_head;
1362 * Try to commit without forking 'git commit'. In some cases we need
1363 * to run 'git commit' to display an error message
1366 * -1 - error unable to commit
1368 * 1 - run 'git commit'
1370 static int try_to_commit(struct repository *r,
1371 struct strbuf *msg, const char *author,
1372 struct replay_opts *opts, unsigned int flags,
1373 struct object_id *oid)
1375 struct object_id tree;
1376 struct commit *current_head = NULL;
1377 struct commit_list *parents = NULL;
1378 struct commit_extra_header *extra = NULL;
1379 struct strbuf err = STRBUF_INIT;
1380 struct strbuf commit_msg = STRBUF_INIT;
1381 char *amend_author = NULL;
1382 const char *committer = NULL;
1383 const char *hook_commit = NULL;
1384 enum commit_msg_cleanup_mode cleanup;
1387 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1388 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1390 if (parse_head(r, ¤t_head))
1393 if (flags & AMEND_MSG) {
1394 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1395 const char *out_enc = get_commit_output_encoding();
1396 const char *message = logmsg_reencode(current_head, NULL,
1400 const char *orig_message = NULL;
1402 find_commit_subject(message, &orig_message);
1404 strbuf_addstr(msg, orig_message);
1405 hook_commit = "HEAD";
1407 author = amend_author = get_author(message);
1408 unuse_commit_buffer(current_head, message);
1410 res = error(_("unable to parse commit author"));
1413 parents = copy_commit_list(current_head->parents);
1414 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1415 } else if (current_head &&
1416 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1417 commit_list_insert(current_head, &parents);
1420 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1421 res = error(_("git write-tree failed to write a tree"));
1425 if (!(flags & ALLOW_EMPTY)) {
1426 struct commit *first_parent = current_head;
1428 if (flags & AMEND_MSG) {
1429 if (current_head->parents) {
1430 first_parent = current_head->parents->item;
1431 if (repo_parse_commit(r, first_parent)) {
1432 res = error(_("could not parse HEAD commit"));
1436 first_parent = NULL;
1439 if (oideq(first_parent
1440 ? get_commit_tree_oid(first_parent)
1441 : the_hash_algo->empty_tree,
1443 res = 1; /* run 'git commit' to display error message */
1448 if (find_hook("prepare-commit-msg")) {
1449 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1452 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1454 res = error_errno(_("unable to read commit message "
1456 git_path_commit_editmsg());
1462 if (flags & CLEANUP_MSG)
1463 cleanup = COMMIT_MSG_CLEANUP_ALL;
1464 else if (flags & VERBATIM_MSG)
1465 cleanup = COMMIT_MSG_CLEANUP_NONE;
1466 else if ((opts->signoff || opts->record_origin) &&
1467 !opts->explicit_cleanup)
1468 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1470 cleanup = opts->default_msg_cleanup;
1472 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1473 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1474 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1475 res = 1; /* run 'git commit' to display error message */
1479 if (opts->committer_date_is_author_date) {
1480 struct ident_split id;
1481 struct strbuf date = STRBUF_INIT;
1483 if (!opts->ignore_date) {
1484 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1485 res = error(_("invalid author identity '%s'"),
1489 if (!id.date_begin) {
1491 "corrupt author: missing date information"));
1494 strbuf_addf(&date, "@%.*s %.*s",
1495 (int)(id.date_end - id.date_begin),
1497 (int)(id.tz_end - id.tz_begin),
1502 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1503 getenv("GIT_COMMITTER_EMAIL"),
1504 WANT_COMMITTER_IDENT,
1505 opts->ignore_date ? NULL : date.buf,
1507 strbuf_release(&date);
1512 if (opts->ignore_date) {
1513 struct ident_split id;
1516 if (split_ident_line(&id, author, strlen(author)) < 0) {
1517 error(_("invalid author identity '%s'"), author);
1520 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1521 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1522 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1528 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1529 author, committer, opts->gpg_sign, extra)) {
1530 res = error(_("failed to write commit object"));
1534 if (update_head_with_reflog(current_head, oid,
1535 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1536 res = error("%s", err.buf);
1540 run_commit_hook(0, r->index_file, "post-commit", NULL);
1541 if (flags & AMEND_MSG)
1542 commit_post_rewrite(r, current_head, oid);
1545 free_commit_extra_headers(extra);
1546 strbuf_release(&err);
1547 strbuf_release(&commit_msg);
1553 static int write_rebase_head(struct object_id *oid)
1555 if (update_ref("rebase", "REBASE_HEAD", oid,
1556 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1557 return error(_("could not update %s"), "REBASE_HEAD");
1562 static int do_commit(struct repository *r,
1563 const char *msg_file, const char *author,
1564 struct replay_opts *opts, unsigned int flags,
1565 struct object_id *oid)
1569 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1570 struct object_id oid;
1571 struct strbuf sb = STRBUF_INIT;
1573 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1574 return error_errno(_("unable to read commit message "
1578 res = try_to_commit(r, msg_file ? &sb : NULL,
1579 author, opts, flags, &oid);
1580 strbuf_release(&sb);
1582 refs_delete_ref(get_main_ref_store(r), "",
1583 "CHERRY_PICK_HEAD", NULL, 0);
1584 unlink(git_path_merge_msg(r));
1585 if (!is_rebase_i(opts))
1586 print_commit_summary(r, NULL, &oid,
1587 SUMMARY_SHOW_AUTHOR_DATE);
1592 if (is_rebase_i(opts) && oid)
1593 if (write_rebase_head(oid))
1595 return run_git_commit(msg_file, opts, flags);
1601 static int is_original_commit_empty(struct commit *commit)
1603 const struct object_id *ptree_oid;
1605 if (parse_commit(commit))
1606 return error(_("could not parse commit %s"),
1607 oid_to_hex(&commit->object.oid));
1608 if (commit->parents) {
1609 struct commit *parent = commit->parents->item;
1610 if (parse_commit(parent))
1611 return error(_("could not parse parent commit %s"),
1612 oid_to_hex(&parent->object.oid));
1613 ptree_oid = get_commit_tree_oid(parent);
1615 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1618 return oideq(ptree_oid, get_commit_tree_oid(commit));
1622 * Should empty commits be allowed? Return status:
1623 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1624 * 0: Halt on empty commit
1625 * 1: Allow empty commit
1626 * 2: Drop empty commit
1628 static int allow_empty(struct repository *r,
1629 struct replay_opts *opts,
1630 struct commit *commit)
1632 int index_unchanged, originally_empty;
1637 * (1) we do not allow empty at all and error out.
1639 * (2) we allow ones that were initially empty, and
1640 * just drop the ones that become empty
1642 * (3) we allow ones that were initially empty, but
1643 * halt for the ones that become empty;
1645 * (4) we allow both.
1647 if (!opts->allow_empty)
1648 return 0; /* let "git commit" barf as necessary */
1650 index_unchanged = is_index_unchanged(r);
1651 if (index_unchanged < 0)
1652 return index_unchanged;
1653 if (!index_unchanged)
1654 return 0; /* we do not have to say --allow-empty */
1656 if (opts->keep_redundant_commits)
1659 originally_empty = is_original_commit_empty(commit);
1660 if (originally_empty < 0)
1661 return originally_empty;
1662 if (originally_empty)
1664 else if (opts->drop_redundant_commits)
1673 } todo_command_info[] = {
1690 static const char *command_to_string(const enum todo_command command)
1692 if (command < TODO_COMMENT)
1693 return todo_command_info[command].str;
1694 die(_("unknown command: %d"), command);
1697 static char command_to_char(const enum todo_command command)
1699 if (command < TODO_COMMENT)
1700 return todo_command_info[command].c;
1701 return comment_line_char;
1704 static int is_noop(const enum todo_command command)
1706 return TODO_NOOP <= command;
1709 static int is_fixup(enum todo_command command)
1711 return command == TODO_FIXUP || command == TODO_SQUASH;
1714 /* Does this command create a (non-merge) commit? */
1715 static int is_pick_or_similar(enum todo_command command)
1730 static int update_squash_messages(struct repository *r,
1731 enum todo_command command,
1732 struct commit *commit,
1733 struct replay_opts *opts)
1735 struct strbuf buf = STRBUF_INIT;
1737 const char *message, *body;
1738 const char *encoding = get_commit_output_encoding();
1740 if (opts->current_fixup_count > 0) {
1741 struct strbuf header = STRBUF_INIT;
1744 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1745 return error(_("could not read '%s'"),
1746 rebase_path_squash_msg());
1748 eol = buf.buf[0] != comment_line_char ?
1749 buf.buf : strchrnul(buf.buf, '\n');
1751 strbuf_addf(&header, "%c ", comment_line_char);
1752 strbuf_addf(&header, _("This is a combination of %d commits."),
1753 opts->current_fixup_count + 2);
1754 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1755 strbuf_release(&header);
1757 struct object_id head;
1758 struct commit *head_commit;
1759 const char *head_message, *body;
1761 if (get_oid("HEAD", &head))
1762 return error(_("need a HEAD to fixup"));
1763 if (!(head_commit = lookup_commit_reference(r, &head)))
1764 return error(_("could not read HEAD"));
1765 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1766 return error(_("could not read HEAD's commit message"));
1768 find_commit_subject(head_message, &body);
1769 if (write_message(body, strlen(body),
1770 rebase_path_fixup_msg(), 0)) {
1771 unuse_commit_buffer(head_commit, head_message);
1772 return error(_("cannot write '%s'"),
1773 rebase_path_fixup_msg());
1776 strbuf_addf(&buf, "%c ", comment_line_char);
1777 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1778 strbuf_addf(&buf, "\n%c ", comment_line_char);
1779 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1780 strbuf_addstr(&buf, "\n\n");
1781 strbuf_addstr(&buf, body);
1783 unuse_commit_buffer(head_commit, head_message);
1786 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1787 return error(_("could not read commit message of %s"),
1788 oid_to_hex(&commit->object.oid));
1789 find_commit_subject(message, &body);
1791 if (command == TODO_SQUASH) {
1792 unlink(rebase_path_fixup_msg());
1793 strbuf_addf(&buf, "\n%c ", comment_line_char);
1794 strbuf_addf(&buf, _("This is the commit message #%d:"),
1795 ++opts->current_fixup_count + 1);
1796 strbuf_addstr(&buf, "\n\n");
1797 strbuf_addstr(&buf, body);
1798 } else if (command == TODO_FIXUP) {
1799 strbuf_addf(&buf, "\n%c ", comment_line_char);
1800 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1801 ++opts->current_fixup_count + 1);
1802 strbuf_addstr(&buf, "\n\n");
1803 strbuf_add_commented_lines(&buf, body, strlen(body));
1805 return error(_("unknown command: %d"), command);
1806 unuse_commit_buffer(commit, message);
1808 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1809 strbuf_release(&buf);
1812 strbuf_addf(&opts->current_fixups, "%s%s %s",
1813 opts->current_fixups.len ? "\n" : "",
1814 command_to_string(command),
1815 oid_to_hex(&commit->object.oid));
1816 res = write_message(opts->current_fixups.buf,
1817 opts->current_fixups.len,
1818 rebase_path_current_fixups(), 0);
1824 static void flush_rewritten_pending(void)
1826 struct strbuf buf = STRBUF_INIT;
1827 struct object_id newoid;
1830 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1831 !get_oid("HEAD", &newoid) &&
1832 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1833 char *bol = buf.buf, *eol;
1836 eol = strchrnul(bol, '\n');
1837 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1838 bol, oid_to_hex(&newoid));
1844 unlink(rebase_path_rewritten_pending());
1846 strbuf_release(&buf);
1849 static void record_in_rewritten(struct object_id *oid,
1850 enum todo_command next_command)
1852 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1857 fprintf(out, "%s\n", oid_to_hex(oid));
1860 if (!is_fixup(next_command))
1861 flush_rewritten_pending();
1864 static int do_pick_commit(struct repository *r,
1865 enum todo_command command,
1866 struct commit *commit,
1867 struct replay_opts *opts,
1868 int final_fixup, int *check_todo)
1870 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1871 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1872 struct object_id head;
1873 struct commit *base, *next, *parent;
1874 const char *base_label, *next_label;
1875 char *author = NULL;
1876 struct commit_message msg = { NULL, NULL, NULL, NULL };
1877 struct strbuf msgbuf = STRBUF_INIT;
1878 int res, unborn = 0, reword = 0, allow, drop_commit;
1880 if (opts->no_commit) {
1882 * We do not intend to commit immediately. We just want to
1883 * merge the differences in, so let's compute the tree
1884 * that represents the "current" state for merge-recursive
1887 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1888 return error(_("your index file is unmerged."));
1890 unborn = get_oid("HEAD", &head);
1891 /* Do we want to generate a root commit? */
1892 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1893 oideq(&head, &opts->squash_onto)) {
1894 if (is_fixup(command))
1895 return error(_("cannot fixup root commit"));
1896 flags |= CREATE_ROOT_COMMIT;
1899 oidcpy(&head, the_hash_algo->empty_tree);
1900 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1902 return error_dirty_index(r, opts);
1904 discard_index(r->index);
1906 if (!commit->parents)
1908 else if (commit->parents->next) {
1909 /* Reverting or cherry-picking a merge commit */
1911 struct commit_list *p;
1913 if (!opts->mainline)
1914 return error(_("commit %s is a merge but no -m option was given."),
1915 oid_to_hex(&commit->object.oid));
1917 for (cnt = 1, p = commit->parents;
1918 cnt != opts->mainline && p;
1921 if (cnt != opts->mainline || !p)
1922 return error(_("commit %s does not have parent %d"),
1923 oid_to_hex(&commit->object.oid), opts->mainline);
1925 } else if (1 < opts->mainline)
1927 * Non-first parent explicitly specified as mainline for
1930 return error(_("commit %s does not have parent %d"),
1931 oid_to_hex(&commit->object.oid), opts->mainline);
1933 parent = commit->parents->item;
1935 if (get_message(commit, &msg) != 0)
1936 return error(_("cannot get commit message for %s"),
1937 oid_to_hex(&commit->object.oid));
1939 if (opts->allow_ff && !is_fixup(command) &&
1940 ((parent && oideq(&parent->object.oid, &head)) ||
1941 (!parent && unborn))) {
1942 if (is_rebase_i(opts))
1943 write_author_script(msg.message);
1944 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1946 if (res || command != TODO_REWORD)
1950 goto fast_forward_edit;
1952 if (parent && parse_commit(parent) < 0)
1953 /* TRANSLATORS: The first %s will be a "todo" command like
1954 "revert" or "pick", the second %s a SHA1. */
1955 return error(_("%s: cannot parse parent commit %s"),
1956 command_to_string(command),
1957 oid_to_hex(&parent->object.oid));
1960 * "commit" is an existing commit. We would want to apply
1961 * the difference it introduces since its first parent "prev"
1962 * on top of the current HEAD if we are cherry-pick. Or the
1963 * reverse of it if we are revert.
1966 if (command == TODO_REVERT) {
1968 base_label = msg.label;
1970 next_label = msg.parent_label;
1971 strbuf_addstr(&msgbuf, "Revert \"");
1972 strbuf_addstr(&msgbuf, msg.subject);
1973 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1974 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1976 if (commit->parents && commit->parents->next) {
1977 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1978 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1980 strbuf_addstr(&msgbuf, ".\n");
1985 base_label = msg.parent_label;
1987 next_label = msg.label;
1989 /* Append the commit log message to msgbuf. */
1990 if (find_commit_subject(msg.message, &p))
1991 strbuf_addstr(&msgbuf, p);
1993 if (opts->record_origin) {
1994 strbuf_complete_line(&msgbuf);
1995 if (!has_conforming_footer(&msgbuf, NULL, 0))
1996 strbuf_addch(&msgbuf, '\n');
1997 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1998 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1999 strbuf_addstr(&msgbuf, ")\n");
2001 if (!is_fixup(command))
2002 author = get_author(msg.message);
2005 if (command == TODO_REWORD)
2007 else if (is_fixup(command)) {
2008 if (update_squash_messages(r, command, commit, opts))
2012 msg_file = rebase_path_squash_msg();
2013 else if (file_exists(rebase_path_fixup_msg())) {
2014 flags |= VERBATIM_MSG;
2015 msg_file = rebase_path_fixup_msg();
2017 const char *dest = git_path_squash_msg(r);
2019 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2020 return error(_("could not rename '%s' to '%s'"),
2021 rebase_path_squash_msg(), dest);
2022 unlink(git_path_merge_msg(r));
2028 if (opts->signoff && !is_fixup(command))
2029 append_signoff(&msgbuf, 0, 0);
2031 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2033 else if (!opts->strategy ||
2034 !strcmp(opts->strategy, "recursive") ||
2035 !strcmp(opts->strategy, "ort") ||
2036 command == TODO_REVERT) {
2037 res = do_recursive_merge(r, base, next, base_label, next_label,
2038 &head, &msgbuf, opts);
2042 res |= write_message(msgbuf.buf, msgbuf.len,
2043 git_path_merge_msg(r), 0);
2045 struct commit_list *common = NULL;
2046 struct commit_list *remotes = NULL;
2048 res = write_message(msgbuf.buf, msgbuf.len,
2049 git_path_merge_msg(r), 0);
2051 commit_list_insert(base, &common);
2052 commit_list_insert(next, &remotes);
2053 res |= try_merge_command(r, opts->strategy,
2054 opts->xopts_nr, (const char **)opts->xopts,
2055 common, oid_to_hex(&head), remotes);
2056 free_commit_list(common);
2057 free_commit_list(remotes);
2059 strbuf_release(&msgbuf);
2062 * If the merge was clean or if it failed due to conflict, we write
2063 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2064 * However, if the merge did not even start, then we don't want to
2067 if ((command == TODO_PICK || command == TODO_REWORD ||
2068 command == TODO_EDIT) && !opts->no_commit &&
2069 (res == 0 || res == 1) &&
2070 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2071 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2073 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2074 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2075 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2079 error(command == TODO_REVERT
2080 ? _("could not revert %s... %s")
2081 : _("could not apply %s... %s"),
2082 short_commit_name(commit), msg.subject);
2083 print_advice(r, res == 1, opts);
2084 repo_rerere(r, opts->allow_rerere_auto);
2089 allow = allow_empty(r, opts, commit);
2093 } else if (allow == 1) {
2094 flags |= ALLOW_EMPTY;
2095 } else if (allow == 2) {
2097 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2099 unlink(git_path_merge_msg(r));
2101 _("dropping %s %s -- patch contents already upstream\n"),
2102 oid_to_hex(&commit->object.oid), msg.subject);
2103 } /* else allow == 0 and there's nothing special to do */
2104 if (!opts->no_commit && !drop_commit) {
2105 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2106 res = do_commit(r, msg_file, author, opts, flags,
2107 commit? &commit->object.oid : NULL);
2109 res = error(_("unable to parse commit author"));
2110 *check_todo = !!(flags & EDIT_MSG);
2111 if (!res && reword) {
2113 res = run_git_commit(NULL, opts, EDIT_MSG |
2114 VERIFY_MSG | AMEND_MSG |
2115 (flags & ALLOW_EMPTY));
2121 if (!res && final_fixup) {
2122 unlink(rebase_path_fixup_msg());
2123 unlink(rebase_path_squash_msg());
2124 unlink(rebase_path_current_fixups());
2125 strbuf_reset(&opts->current_fixups);
2126 opts->current_fixup_count = 0;
2130 free_message(commit, &msg);
2132 update_abort_safety_file();
2137 static int prepare_revs(struct replay_opts *opts)
2140 * picking (but not reverting) ranges (but not individual revisions)
2141 * should be done in reverse
2143 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2144 opts->revs->reverse ^= 1;
2146 if (prepare_revision_walk(opts->revs))
2147 return error(_("revision walk setup failed"));
2152 static int read_and_refresh_cache(struct repository *r,
2153 struct replay_opts *opts)
2155 struct lock_file index_lock = LOCK_INIT;
2156 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2157 if (repo_read_index(r) < 0) {
2158 rollback_lock_file(&index_lock);
2159 return error(_("git %s: failed to read the index"),
2160 _(action_name(opts)));
2162 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2163 if (index_fd >= 0) {
2164 if (write_locked_index(r->index, &index_lock,
2165 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2166 return error(_("git %s: failed to refresh the index"),
2167 _(action_name(opts)));
2173 enum todo_item_flags {
2174 TODO_EDIT_MERGE_MSG = 1
2177 void todo_list_release(struct todo_list *todo_list)
2179 strbuf_release(&todo_list->buf);
2180 FREE_AND_NULL(todo_list->items);
2181 todo_list->nr = todo_list->alloc = 0;
2184 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2186 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2187 todo_list->total_nr++;
2188 return todo_list->items + todo_list->nr++;
2191 const char *todo_item_get_arg(struct todo_list *todo_list,
2192 struct todo_item *item)
2194 return todo_list->buf.buf + item->arg_offset;
2197 static int is_command(enum todo_command command, const char **bol)
2199 const char *str = todo_command_info[command].str;
2200 const char nick = todo_command_info[command].c;
2201 const char *p = *bol + 1;
2203 return skip_prefix(*bol, str, bol) ||
2204 ((nick && **bol == nick) &&
2205 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2209 static int parse_insn_line(struct repository *r, struct todo_item *item,
2210 const char *buf, const char *bol, char *eol)
2212 struct object_id commit_oid;
2213 char *end_of_object_name;
2214 int i, saved, status, padding;
2219 bol += strspn(bol, " \t");
2221 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2222 item->command = TODO_COMMENT;
2223 item->commit = NULL;
2224 item->arg_offset = bol - buf;
2225 item->arg_len = eol - bol;
2229 for (i = 0; i < TODO_COMMENT; i++)
2230 if (is_command(i, &bol)) {
2234 if (i >= TODO_COMMENT)
2237 /* Eat up extra spaces/ tabs before object name */
2238 padding = strspn(bol, " \t");
2241 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2243 return error(_("%s does not accept arguments: '%s'"),
2244 command_to_string(item->command), bol);
2245 item->commit = NULL;
2246 item->arg_offset = bol - buf;
2247 item->arg_len = eol - bol;
2252 return error(_("missing arguments for %s"),
2253 command_to_string(item->command));
2255 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2256 item->command == TODO_RESET) {
2257 item->commit = NULL;
2258 item->arg_offset = bol - buf;
2259 item->arg_len = (int)(eol - bol);
2263 if (item->command == TODO_MERGE) {
2264 if (skip_prefix(bol, "-C", &bol))
2265 bol += strspn(bol, " \t");
2266 else if (skip_prefix(bol, "-c", &bol)) {
2267 bol += strspn(bol, " \t");
2268 item->flags |= TODO_EDIT_MERGE_MSG;
2270 item->flags |= TODO_EDIT_MERGE_MSG;
2271 item->commit = NULL;
2272 item->arg_offset = bol - buf;
2273 item->arg_len = (int)(eol - bol);
2278 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2279 saved = *end_of_object_name;
2280 *end_of_object_name = '\0';
2281 status = get_oid(bol, &commit_oid);
2283 error(_("could not parse '%s'"), bol); /* return later */
2284 *end_of_object_name = saved;
2286 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2287 item->arg_offset = bol - buf;
2288 item->arg_len = (int)(eol - bol);
2293 item->commit = lookup_commit_reference(r, &commit_oid);
2294 return item->commit ? 0 : -1;
2297 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2299 const char *todo_file, *bol;
2300 struct strbuf buf = STRBUF_INIT;
2303 todo_file = git_path_todo_file();
2304 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2305 if (errno == ENOENT || errno == ENOTDIR)
2308 return error_errno("unable to open '%s'", todo_file);
2310 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2311 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2312 *action = REPLAY_PICK;
2313 else if (is_command(TODO_REVERT, &bol) &&
2314 (*bol == ' ' || *bol == '\t'))
2315 *action = REPLAY_REVERT;
2319 strbuf_release(&buf);
2324 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2325 struct todo_list *todo_list)
2327 struct todo_item *item;
2328 char *p = buf, *next_p;
2329 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2331 todo_list->current = todo_list->nr = 0;
2333 for (i = 1; *p; i++, p = next_p) {
2334 char *eol = strchrnul(p, '\n');
2336 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2338 if (p != eol && eol[-1] == '\r')
2339 eol--; /* strip Carriage Return */
2341 item = append_new_todo(todo_list);
2342 item->offset_in_buf = p - todo_list->buf.buf;
2343 if (parse_insn_line(r, item, buf, p, eol)) {
2344 res = error(_("invalid line %d: %.*s"),
2345 i, (int)(eol - p), p);
2346 item->command = TODO_COMMENT + 1;
2347 item->arg_offset = p - buf;
2348 item->arg_len = (int)(eol - p);
2349 item->commit = NULL;
2354 else if (is_fixup(item->command))
2355 return error(_("cannot '%s' without a previous commit"),
2356 command_to_string(item->command));
2357 else if (!is_noop(item->command))
2364 static int count_commands(struct todo_list *todo_list)
2368 for (i = 0; i < todo_list->nr; i++)
2369 if (todo_list->items[i].command != TODO_COMMENT)
2375 static int get_item_line_offset(struct todo_list *todo_list, int index)
2377 return index < todo_list->nr ?
2378 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2381 static const char *get_item_line(struct todo_list *todo_list, int index)
2383 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2386 static int get_item_line_length(struct todo_list *todo_list, int index)
2388 return get_item_line_offset(todo_list, index + 1)
2389 - get_item_line_offset(todo_list, index);
2392 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2397 fd = open(path, O_RDONLY);
2399 return error_errno(_("could not open '%s'"), path);
2400 len = strbuf_read(sb, fd, 0);
2403 return error(_("could not read '%s'."), path);
2407 static int have_finished_the_last_pick(void)
2409 struct strbuf buf = STRBUF_INIT;
2411 const char *todo_path = git_path_todo_file();
2414 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2415 if (errno == ENOENT) {
2418 error_errno("unable to open '%s'", todo_path);
2422 /* If there is only one line then we are done */
2423 eol = strchr(buf.buf, '\n');
2424 if (!eol || !eol[1])
2427 strbuf_release(&buf);
2432 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2434 struct replay_opts opts = REPLAY_OPTS_INIT;
2435 int need_cleanup = 0;
2437 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2438 if (!refs_delete_ref(get_main_ref_store(r), "",
2439 "CHERRY_PICK_HEAD", NULL, 0) &&
2441 warning(_("cancelling a cherry picking in progress"));
2442 opts.action = REPLAY_PICK;
2446 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2447 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2450 warning(_("cancelling a revert in progress"));
2451 opts.action = REPLAY_REVERT;
2458 if (!have_finished_the_last_pick())
2461 sequencer_remove_state(&opts);
2464 static void todo_list_write_total_nr(struct todo_list *todo_list)
2466 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2469 fprintf(f, "%d\n", todo_list->total_nr);
2474 static int read_populate_todo(struct repository *r,
2475 struct todo_list *todo_list,
2476 struct replay_opts *opts)
2479 const char *todo_file = get_todo_path(opts);
2482 strbuf_reset(&todo_list->buf);
2483 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2486 res = stat(todo_file, &st);
2488 return error(_("could not stat '%s'"), todo_file);
2489 fill_stat_data(&todo_list->stat, &st);
2491 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2493 if (is_rebase_i(opts))
2494 return error(_("please fix this using "
2495 "'git rebase --edit-todo'."));
2496 return error(_("unusable instruction sheet: '%s'"), todo_file);
2499 if (!todo_list->nr &&
2500 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2501 return error(_("no commits parsed."));
2503 if (!is_rebase_i(opts)) {
2504 enum todo_command valid =
2505 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2508 for (i = 0; i < todo_list->nr; i++)
2509 if (valid == todo_list->items[i].command)
2511 else if (valid == TODO_PICK)
2512 return error(_("cannot cherry-pick during a revert."));
2514 return error(_("cannot revert during a cherry-pick."));
2517 if (is_rebase_i(opts)) {
2518 struct todo_list done = TODO_LIST_INIT;
2520 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2521 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2522 todo_list->done_nr = count_commands(&done);
2524 todo_list->done_nr = 0;
2526 todo_list->total_nr = todo_list->done_nr
2527 + count_commands(todo_list);
2528 todo_list_release(&done);
2530 todo_list_write_total_nr(todo_list);
2536 static int git_config_string_dup(char **dest,
2537 const char *var, const char *value)
2540 return config_error_nonbool(var);
2542 *dest = xstrdup(value);
2546 static int populate_opts_cb(const char *key, const char *value, void *data)
2548 struct replay_opts *opts = data;
2553 else if (!strcmp(key, "options.no-commit"))
2554 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2555 else if (!strcmp(key, "options.edit"))
2556 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2557 else if (!strcmp(key, "options.allow-empty"))
2559 git_config_bool_or_int(key, value, &error_flag);
2560 else if (!strcmp(key, "options.allow-empty-message"))
2561 opts->allow_empty_message =
2562 git_config_bool_or_int(key, value, &error_flag);
2563 else if (!strcmp(key, "options.keep-redundant-commits"))
2564 opts->keep_redundant_commits =
2565 git_config_bool_or_int(key, value, &error_flag);
2566 else if (!strcmp(key, "options.signoff"))
2567 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2568 else if (!strcmp(key, "options.record-origin"))
2569 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2570 else if (!strcmp(key, "options.allow-ff"))
2571 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2572 else if (!strcmp(key, "options.mainline"))
2573 opts->mainline = git_config_int(key, value);
2574 else if (!strcmp(key, "options.strategy"))
2575 git_config_string_dup(&opts->strategy, key, value);
2576 else if (!strcmp(key, "options.gpg-sign"))
2577 git_config_string_dup(&opts->gpg_sign, key, value);
2578 else if (!strcmp(key, "options.strategy-option")) {
2579 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2580 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2581 } else if (!strcmp(key, "options.allow-rerere-auto"))
2582 opts->allow_rerere_auto =
2583 git_config_bool_or_int(key, value, &error_flag) ?
2584 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2585 else if (!strcmp(key, "options.default-msg-cleanup")) {
2586 opts->explicit_cleanup = 1;
2587 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2589 return error(_("invalid key: %s"), key);
2592 return error(_("invalid value for %s: %s"), key, value);
2597 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2600 char *strategy_opts_string = raw_opts;
2602 if (*strategy_opts_string == ' ')
2603 strategy_opts_string++;
2605 opts->xopts_nr = split_cmdline(strategy_opts_string,
2606 (const char ***)&opts->xopts);
2607 for (i = 0; i < opts->xopts_nr; i++) {
2608 const char *arg = opts->xopts[i];
2610 skip_prefix(arg, "--", &arg);
2611 opts->xopts[i] = xstrdup(arg);
2615 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2618 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2620 opts->strategy = strbuf_detach(buf, NULL);
2621 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2624 parse_strategy_opts(opts, buf->buf);
2627 static int read_populate_opts(struct replay_opts *opts)
2629 if (is_rebase_i(opts)) {
2630 struct strbuf buf = STRBUF_INIT;
2633 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2634 READ_ONELINER_SKIP_IF_EMPTY)) {
2635 if (!starts_with(buf.buf, "-S"))
2638 free(opts->gpg_sign);
2639 opts->gpg_sign = xstrdup(buf.buf + 2);
2644 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2645 READ_ONELINER_SKIP_IF_EMPTY)) {
2646 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2647 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2648 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2649 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2653 if (file_exists(rebase_path_verbose()))
2656 if (file_exists(rebase_path_quiet()))
2659 if (file_exists(rebase_path_signoff())) {
2664 if (file_exists(rebase_path_cdate_is_adate())) {
2666 opts->committer_date_is_author_date = 1;
2669 if (file_exists(rebase_path_ignore_date())) {
2671 opts->ignore_date = 1;
2674 if (file_exists(rebase_path_reschedule_failed_exec()))
2675 opts->reschedule_failed_exec = 1;
2676 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2677 opts->reschedule_failed_exec = 0;
2679 if (file_exists(rebase_path_drop_redundant_commits()))
2680 opts->drop_redundant_commits = 1;
2682 if (file_exists(rebase_path_keep_redundant_commits()))
2683 opts->keep_redundant_commits = 1;
2685 read_strategy_opts(opts, &buf);
2688 if (read_oneliner(&opts->current_fixups,
2689 rebase_path_current_fixups(),
2690 READ_ONELINER_SKIP_IF_EMPTY)) {
2691 const char *p = opts->current_fixups.buf;
2692 opts->current_fixup_count = 1;
2693 while ((p = strchr(p, '\n'))) {
2694 opts->current_fixup_count++;
2699 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2700 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2701 ret = error(_("unusable squash-onto"));
2704 opts->have_squash_onto = 1;
2708 strbuf_release(&buf);
2712 if (!file_exists(git_path_opts_file()))
2715 * The function git_parse_source(), called from git_config_from_file(),
2716 * may die() in case of a syntactically incorrect file. We do not care
2717 * about this case, though, because we wrote that file ourselves, so we
2718 * are pretty certain that it is syntactically correct.
2720 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2721 return error(_("malformed options sheet: '%s'"),
2722 git_path_opts_file());
2726 static void write_strategy_opts(struct replay_opts *opts)
2729 struct strbuf buf = STRBUF_INIT;
2731 for (i = 0; i < opts->xopts_nr; ++i)
2732 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2734 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2735 strbuf_release(&buf);
2738 int write_basic_state(struct replay_opts *opts, const char *head_name,
2739 struct commit *onto, const struct object_id *orig_head)
2742 write_file(rebase_path_head_name(), "%s\n", head_name);
2744 write_file(rebase_path_onto(), "%s\n",
2745 oid_to_hex(&onto->object.oid));
2747 write_file(rebase_path_orig_head(), "%s\n",
2748 oid_to_hex(orig_head));
2751 write_file(rebase_path_quiet(), "%s", "");
2753 write_file(rebase_path_verbose(), "%s", "");
2755 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2756 if (opts->xopts_nr > 0)
2757 write_strategy_opts(opts);
2759 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2760 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2761 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2762 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2765 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2767 write_file(rebase_path_signoff(), "--signoff\n");
2768 if (opts->drop_redundant_commits)
2769 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2770 if (opts->keep_redundant_commits)
2771 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2772 if (opts->committer_date_is_author_date)
2773 write_file(rebase_path_cdate_is_adate(), "%s", "");
2774 if (opts->ignore_date)
2775 write_file(rebase_path_ignore_date(), "%s", "");
2776 if (opts->reschedule_failed_exec)
2777 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2779 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2784 static int walk_revs_populate_todo(struct todo_list *todo_list,
2785 struct replay_opts *opts)
2787 enum todo_command command = opts->action == REPLAY_PICK ?
2788 TODO_PICK : TODO_REVERT;
2789 const char *command_string = todo_command_info[command].str;
2790 const char *encoding;
2791 struct commit *commit;
2793 if (prepare_revs(opts))
2796 encoding = get_log_output_encoding();
2798 while ((commit = get_revision(opts->revs))) {
2799 struct todo_item *item = append_new_todo(todo_list);
2800 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2801 const char *subject;
2804 item->command = command;
2805 item->commit = commit;
2806 item->arg_offset = 0;
2808 item->offset_in_buf = todo_list->buf.len;
2809 subject_len = find_commit_subject(commit_buffer, &subject);
2810 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2811 short_commit_name(commit), subject_len, subject);
2812 unuse_commit_buffer(commit, commit_buffer);
2816 return error(_("empty commit set passed"));
2821 static int create_seq_dir(struct repository *r)
2823 enum replay_action action;
2824 const char *in_progress_error = NULL;
2825 const char *in_progress_advice = NULL;
2826 unsigned int advise_skip =
2827 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
2828 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
2830 if (!sequencer_get_last_command(r, &action)) {
2833 in_progress_error = _("revert is already in progress");
2834 in_progress_advice =
2835 _("try \"git revert (--continue | %s--abort | --quit)\"");
2838 in_progress_error = _("cherry-pick is already in progress");
2839 in_progress_advice =
2840 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2843 BUG("unexpected action in create_seq_dir");
2846 if (in_progress_error) {
2847 error("%s", in_progress_error);
2848 if (advice_sequencer_in_use)
2849 advise(in_progress_advice,
2850 advise_skip ? "--skip | " : "");
2853 if (mkdir(git_path_seq_dir(), 0777) < 0)
2854 return error_errno(_("could not create sequencer directory '%s'"),
2855 git_path_seq_dir());
2860 static int save_head(const char *head)
2862 struct lock_file head_lock = LOCK_INIT;
2863 struct strbuf buf = STRBUF_INIT;
2867 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2869 return error_errno(_("could not lock HEAD"));
2870 strbuf_addf(&buf, "%s\n", head);
2871 written = write_in_full(fd, buf.buf, buf.len);
2872 strbuf_release(&buf);
2874 error_errno(_("could not write to '%s'"), git_path_head_file());
2875 rollback_lock_file(&head_lock);
2878 if (commit_lock_file(&head_lock) < 0)
2879 return error(_("failed to finalize '%s'"), git_path_head_file());
2883 static int rollback_is_safe(void)
2885 struct strbuf sb = STRBUF_INIT;
2886 struct object_id expected_head, actual_head;
2888 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2890 if (get_oid_hex(sb.buf, &expected_head)) {
2891 strbuf_release(&sb);
2892 die(_("could not parse %s"), git_path_abort_safety_file());
2894 strbuf_release(&sb);
2896 else if (errno == ENOENT)
2897 oidclr(&expected_head);
2899 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2901 if (get_oid("HEAD", &actual_head))
2902 oidclr(&actual_head);
2904 return oideq(&actual_head, &expected_head);
2907 static int reset_merge(const struct object_id *oid)
2910 struct strvec argv = STRVEC_INIT;
2912 strvec_pushl(&argv, "reset", "--merge", NULL);
2914 if (!is_null_oid(oid))
2915 strvec_push(&argv, oid_to_hex(oid));
2917 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
2918 strvec_clear(&argv);
2923 static int rollback_single_pick(struct repository *r)
2925 struct object_id head_oid;
2927 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
2928 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
2929 return error(_("no cherry-pick or revert in progress"));
2930 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2931 return error(_("cannot resolve HEAD"));
2932 if (is_null_oid(&head_oid))
2933 return error(_("cannot abort from a branch yet to be born"));
2934 return reset_merge(&head_oid);
2937 static int skip_single_pick(void)
2939 struct object_id head;
2941 if (read_ref_full("HEAD", 0, &head, NULL))
2942 return error(_("cannot resolve HEAD"));
2943 return reset_merge(&head);
2946 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2949 struct object_id oid;
2950 struct strbuf buf = STRBUF_INIT;
2953 f = fopen(git_path_head_file(), "r");
2954 if (!f && errno == ENOENT) {
2956 * There is no multiple-cherry-pick in progress.
2957 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2958 * a single-cherry-pick in progress, abort that.
2960 return rollback_single_pick(r);
2963 return error_errno(_("cannot open '%s'"), git_path_head_file());
2964 if (strbuf_getline_lf(&buf, f)) {
2965 error(_("cannot read '%s': %s"), git_path_head_file(),
2966 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2971 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2972 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2973 git_path_head_file());
2976 if (is_null_oid(&oid)) {
2977 error(_("cannot abort from a branch yet to be born"));
2981 if (!rollback_is_safe()) {
2982 /* Do not error, just do not rollback */
2983 warning(_("You seem to have moved HEAD. "
2984 "Not rewinding, check your HEAD!"));
2986 if (reset_merge(&oid))
2988 strbuf_release(&buf);
2989 return sequencer_remove_state(opts);
2991 strbuf_release(&buf);
2995 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2997 enum replay_action action = -1;
2998 sequencer_get_last_command(r, &action);
3001 * Check whether the subcommand requested to skip the commit is actually
3002 * in progress and that it's safe to skip the commit.
3004 * opts->action tells us which subcommand requested to skip the commit.
3005 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3006 * action is in progress and we can skip the commit.
3008 * Otherwise we check that the last instruction was related to the
3009 * particular subcommand we're trying to execute and barf if that's not
3012 * Finally we check that the rollback is "safe", i.e., has the HEAD
3013 * moved? In this case, it doesn't make sense to "reset the merge" and
3014 * "skip the commit" as the user already handled this by committing. But
3015 * we'd not want to barf here, instead give advice on how to proceed. We
3016 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3017 * it gets removed when the user commits, so if it still exists we're
3018 * sure the user can't have committed before.
3020 switch (opts->action) {
3022 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3023 if (action != REPLAY_REVERT)
3024 return error(_("no revert in progress"));
3025 if (!rollback_is_safe())
3030 if (!refs_ref_exists(get_main_ref_store(r),
3031 "CHERRY_PICK_HEAD")) {
3032 if (action != REPLAY_PICK)
3033 return error(_("no cherry-pick in progress"));
3034 if (!rollback_is_safe())
3039 BUG("unexpected action in sequencer_skip");
3042 if (skip_single_pick())
3043 return error(_("failed to skip the commit"));
3044 if (!is_directory(git_path_seq_dir()))
3047 return sequencer_continue(r, opts);
3050 error(_("there is nothing to skip"));
3052 if (advice_resolve_conflict) {
3053 advise(_("have you committed already?\n"
3054 "try \"git %s --continue\""),
3055 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3060 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3062 struct lock_file todo_lock = LOCK_INIT;
3063 const char *todo_path = get_todo_path(opts);
3064 int next = todo_list->current, offset, fd;
3067 * rebase -i writes "git-rebase-todo" without the currently executing
3068 * command, appending it to "done" instead.
3070 if (is_rebase_i(opts))
3073 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3075 return error_errno(_("could not lock '%s'"), todo_path);
3076 offset = get_item_line_offset(todo_list, next);
3077 if (write_in_full(fd, todo_list->buf.buf + offset,
3078 todo_list->buf.len - offset) < 0)
3079 return error_errno(_("could not write to '%s'"), todo_path);
3080 if (commit_lock_file(&todo_lock) < 0)
3081 return error(_("failed to finalize '%s'"), todo_path);
3083 if (is_rebase_i(opts) && next > 0) {
3084 const char *done = rebase_path_done();
3085 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3090 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3091 get_item_line_length(todo_list, next - 1))
3093 ret = error_errno(_("could not write to '%s'"), done);
3095 ret = error_errno(_("failed to finalize '%s'"), done);
3101 static int save_opts(struct replay_opts *opts)
3103 const char *opts_file = git_path_opts_file();
3106 if (opts->no_commit)
3107 res |= git_config_set_in_file_gently(opts_file,
3108 "options.no-commit", "true");
3110 res |= git_config_set_in_file_gently(opts_file,
3111 "options.edit", "true");
3112 if (opts->allow_empty)
3113 res |= git_config_set_in_file_gently(opts_file,
3114 "options.allow-empty", "true");
3115 if (opts->allow_empty_message)
3116 res |= git_config_set_in_file_gently(opts_file,
3117 "options.allow-empty-message", "true");
3118 if (opts->keep_redundant_commits)
3119 res |= git_config_set_in_file_gently(opts_file,
3120 "options.keep-redundant-commits", "true");
3122 res |= git_config_set_in_file_gently(opts_file,
3123 "options.signoff", "true");
3124 if (opts->record_origin)
3125 res |= git_config_set_in_file_gently(opts_file,
3126 "options.record-origin", "true");
3128 res |= git_config_set_in_file_gently(opts_file,
3129 "options.allow-ff", "true");
3130 if (opts->mainline) {
3131 struct strbuf buf = STRBUF_INIT;
3132 strbuf_addf(&buf, "%d", opts->mainline);
3133 res |= git_config_set_in_file_gently(opts_file,
3134 "options.mainline", buf.buf);
3135 strbuf_release(&buf);
3138 res |= git_config_set_in_file_gently(opts_file,
3139 "options.strategy", opts->strategy);
3141 res |= git_config_set_in_file_gently(opts_file,
3142 "options.gpg-sign", opts->gpg_sign);
3145 for (i = 0; i < opts->xopts_nr; i++)
3146 res |= git_config_set_multivar_in_file_gently(opts_file,
3147 "options.strategy-option",
3148 opts->xopts[i], "^$", 0);
3150 if (opts->allow_rerere_auto)
3151 res |= git_config_set_in_file_gently(opts_file,
3152 "options.allow-rerere-auto",
3153 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3156 if (opts->explicit_cleanup)
3157 res |= git_config_set_in_file_gently(opts_file,
3158 "options.default-msg-cleanup",
3159 describe_cleanup_mode(opts->default_msg_cleanup));
3163 static int make_patch(struct repository *r,
3164 struct commit *commit,
3165 struct replay_opts *opts)
3167 struct strbuf buf = STRBUF_INIT;
3168 struct rev_info log_tree_opt;
3169 const char *subject;
3170 char hex[GIT_MAX_HEXSZ + 1];
3173 oid_to_hex_r(hex, &commit->object.oid);
3174 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3176 res |= write_rebase_head(&commit->object.oid);
3178 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3179 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3180 repo_init_revisions(r, &log_tree_opt, NULL);
3181 log_tree_opt.abbrev = 0;
3182 log_tree_opt.diff = 1;
3183 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3184 log_tree_opt.disable_stdin = 1;
3185 log_tree_opt.no_commit_id = 1;
3186 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3187 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3188 if (!log_tree_opt.diffopt.file)
3189 res |= error_errno(_("could not open '%s'"), buf.buf);
3191 res |= log_tree_commit(&log_tree_opt, commit);
3192 fclose(log_tree_opt.diffopt.file);
3196 strbuf_addf(&buf, "%s/message", get_dir(opts));
3197 if (!file_exists(buf.buf)) {
3198 const char *encoding = get_commit_output_encoding();
3199 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3200 find_commit_subject(commit_buffer, &subject);
3201 res |= write_message(subject, strlen(subject), buf.buf, 1);
3202 unuse_commit_buffer(commit, commit_buffer);
3204 strbuf_release(&buf);
3209 static int intend_to_amend(void)
3211 struct object_id head;
3214 if (get_oid("HEAD", &head))
3215 return error(_("cannot read HEAD"));
3217 p = oid_to_hex(&head);
3218 return write_message(p, strlen(p), rebase_path_amend(), 1);
3221 static int error_with_patch(struct repository *r,
3222 struct commit *commit,
3223 const char *subject, int subject_len,
3224 struct replay_opts *opts,
3225 int exit_code, int to_amend)
3228 if (make_patch(r, commit, opts))
3230 } else if (copy_file(rebase_path_message(),
3231 git_path_merge_msg(r), 0666))
3232 return error(_("unable to copy '%s' to '%s'"),
3233 git_path_merge_msg(r), rebase_path_message());
3236 if (intend_to_amend())
3240 _("You can amend the commit now, with\n"
3242 " git commit --amend %s\n"
3244 "Once you are satisfied with your changes, run\n"
3246 " git rebase --continue\n"),
3247 gpg_sign_opt_quoted(opts));
3248 } else if (exit_code) {
3250 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3251 short_commit_name(commit), subject_len, subject);
3254 * We don't have the hash of the parent so
3255 * just print the line from the todo file.
3257 fprintf_ln(stderr, _("Could not merge %.*s"),
3258 subject_len, subject);
3264 static int error_failed_squash(struct repository *r,
3265 struct commit *commit,
3266 struct replay_opts *opts,
3268 const char *subject)
3270 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3271 return error(_("could not copy '%s' to '%s'"),
3272 rebase_path_squash_msg(), rebase_path_message());
3273 unlink(git_path_merge_msg(r));
3274 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3275 return error(_("could not copy '%s' to '%s'"),
3276 rebase_path_message(),
3277 git_path_merge_msg(r));
3278 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3281 static int do_exec(struct repository *r, const char *command_line)
3283 struct strvec child_env = STRVEC_INIT;
3284 const char *child_argv[] = { NULL, NULL };
3287 fprintf(stderr, _("Executing: %s\n"), command_line);
3288 child_argv[0] = command_line;
3289 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3290 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3291 absolute_path(get_git_work_tree()));
3292 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3295 /* force re-reading of the cache */
3296 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3297 return error(_("could not read index"));
3299 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3302 warning(_("execution failed: %s\n%s"
3303 "You can fix the problem, and then run\n"
3305 " git rebase --continue\n"
3308 dirty ? N_("and made changes to the index and/or the "
3309 "working tree\n") : "");
3311 /* command not found */
3314 warning(_("execution succeeded: %s\nbut "
3315 "left changes to the index and/or the working tree\n"
3316 "Commit or stash your changes, and then run\n"
3318 " git rebase --continue\n"
3319 "\n"), command_line);
3323 strvec_clear(&child_env);
3328 static int safe_append(const char *filename, const char *fmt, ...)
3331 struct lock_file lock = LOCK_INIT;
3332 int fd = hold_lock_file_for_update(&lock, filename,
3333 LOCK_REPORT_ON_ERROR);
3334 struct strbuf buf = STRBUF_INIT;
3339 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3340 error_errno(_("could not read '%s'"), filename);
3341 rollback_lock_file(&lock);
3344 strbuf_complete(&buf, '\n');
3346 strbuf_vaddf(&buf, fmt, ap);
3349 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3350 error_errno(_("could not write to '%s'"), filename);
3351 strbuf_release(&buf);
3352 rollback_lock_file(&lock);
3355 if (commit_lock_file(&lock) < 0) {
3356 strbuf_release(&buf);
3357 rollback_lock_file(&lock);
3358 return error(_("failed to finalize '%s'"), filename);
3361 strbuf_release(&buf);
3365 static int do_label(struct repository *r, const char *name, int len)
3367 struct ref_store *refs = get_main_ref_store(r);
3368 struct ref_transaction *transaction;
3369 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3370 struct strbuf msg = STRBUF_INIT;
3372 struct object_id head_oid;
3374 if (len == 1 && *name == '#')
3375 return error(_("illegal label name: '%.*s'"), len, name);
3377 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3378 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3380 transaction = ref_store_transaction_begin(refs, &err);
3382 error("%s", err.buf);
3384 } else if (get_oid("HEAD", &head_oid)) {
3385 error(_("could not read HEAD"));
3387 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3388 NULL, 0, msg.buf, &err) < 0 ||
3389 ref_transaction_commit(transaction, &err)) {
3390 error("%s", err.buf);
3393 ref_transaction_free(transaction);
3394 strbuf_release(&err);
3395 strbuf_release(&msg);
3398 ret = safe_append(rebase_path_refs_to_delete(),
3399 "%s\n", ref_name.buf);
3400 strbuf_release(&ref_name);
3405 static const char *reflog_message(struct replay_opts *opts,
3406 const char *sub_action, const char *fmt, ...);
3408 static int do_reset(struct repository *r,
3409 const char *name, int len,
3410 struct replay_opts *opts)
3412 struct strbuf ref_name = STRBUF_INIT;
3413 struct object_id oid;
3414 struct lock_file lock = LOCK_INIT;
3415 struct tree_desc desc;
3417 struct unpack_trees_options unpack_tree_opts;
3420 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3423 if (len == 10 && !strncmp("[new root]", name, len)) {
3424 if (!opts->have_squash_onto) {
3426 if (commit_tree("", 0, the_hash_algo->empty_tree,
3427 NULL, &opts->squash_onto,
3429 return error(_("writing fake root commit"));
3430 opts->have_squash_onto = 1;
3431 hex = oid_to_hex(&opts->squash_onto);
3432 if (write_message(hex, strlen(hex),
3433 rebase_path_squash_onto(), 0))
3434 return error(_("writing squash-onto"));
3436 oidcpy(&oid, &opts->squash_onto);
3440 /* Determine the length of the label */
3441 for (i = 0; i < len; i++)
3442 if (isspace(name[i]))
3446 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3447 if (get_oid(ref_name.buf, &oid) &&
3448 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3449 error(_("could not read '%s'"), ref_name.buf);
3450 rollback_lock_file(&lock);
3451 strbuf_release(&ref_name);
3456 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3457 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3458 unpack_tree_opts.head_idx = 1;
3459 unpack_tree_opts.src_index = r->index;
3460 unpack_tree_opts.dst_index = r->index;
3461 unpack_tree_opts.fn = oneway_merge;
3462 unpack_tree_opts.merge = 1;
3463 unpack_tree_opts.update = 1;
3464 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3466 if (repo_read_index_unmerged(r)) {
3467 rollback_lock_file(&lock);
3468 strbuf_release(&ref_name);
3469 return error_resolve_conflict(_(action_name(opts)));
3472 if (!fill_tree_descriptor(r, &desc, &oid)) {
3473 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3474 rollback_lock_file(&lock);
3475 free((void *)desc.buffer);
3476 strbuf_release(&ref_name);
3480 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3481 rollback_lock_file(&lock);
3482 free((void *)desc.buffer);
3483 strbuf_release(&ref_name);
3487 tree = parse_tree_indirect(&oid);
3488 prime_cache_tree(r, r->index, tree);
3490 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3491 ret = error(_("could not write index"));
3492 free((void *)desc.buffer);
3495 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3496 len, name), "HEAD", &oid,
3497 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3499 strbuf_release(&ref_name);
3503 static struct commit *lookup_label(const char *label, int len,
3506 struct commit *commit;
3509 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3510 commit = lookup_commit_reference_by_name(buf->buf);
3512 /* fall back to non-rewritten ref or commit */
3513 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3514 commit = lookup_commit_reference_by_name(buf->buf);
3518 error(_("could not resolve '%s'"), buf->buf);
3523 static int do_merge(struct repository *r,
3524 struct commit *commit,
3525 const char *arg, int arg_len,
3526 int flags, struct replay_opts *opts)
3528 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3529 EDIT_MSG | VERIFY_MSG : 0;
3530 struct strbuf ref_name = STRBUF_INIT;
3531 struct commit *head_commit, *merge_commit, *i;
3532 struct commit_list *bases, *j, *reversed = NULL;
3533 struct commit_list *to_merge = NULL, **tail = &to_merge;
3534 const char *strategy = !opts->xopts_nr &&
3536 !strcmp(opts->strategy, "recursive") ||
3537 !strcmp(opts->strategy, "ort")) ?
3538 NULL : opts->strategy;
3539 struct merge_options o;
3540 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3541 static struct lock_file lock;
3544 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3549 head_commit = lookup_commit_reference_by_name("HEAD");
3551 ret = error(_("cannot merge without a current revision"));
3556 * For octopus merges, the arg starts with the list of revisions to be
3557 * merged. The list is optionally followed by '#' and the oneline.
3559 merge_arg_len = oneline_offset = arg_len;
3560 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3563 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3564 p += 1 + strspn(p + 1, " \t\n");
3565 oneline_offset = p - arg;
3568 k = strcspn(p, " \t\n");
3571 merge_commit = lookup_label(p, k, &ref_name);
3572 if (!merge_commit) {
3573 ret = error(_("unable to parse '%.*s'"), k, p);
3576 tail = &commit_list_insert(merge_commit, tail)->next;
3578 merge_arg_len = p - arg;
3582 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3586 if (opts->have_squash_onto &&
3587 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3589 * When the user tells us to "merge" something into a
3590 * "[new root]", let's simply fast-forward to the merge head.
3592 rollback_lock_file(&lock);
3594 ret = error(_("octopus merge cannot be executed on "
3595 "top of a [new root]"));
3597 ret = fast_forward_to(r, &to_merge->item->object.oid,
3598 &head_commit->object.oid, 0,
3604 const char *encoding = get_commit_output_encoding();
3605 const char *message = logmsg_reencode(commit, NULL, encoding);
3610 ret = error(_("could not get commit message of '%s'"),
3611 oid_to_hex(&commit->object.oid));
3614 write_author_script(message);
3615 find_commit_subject(message, &body);
3617 ret = write_message(body, len, git_path_merge_msg(r), 0);
3618 unuse_commit_buffer(commit, message);
3620 error_errno(_("could not write '%s'"),
3621 git_path_merge_msg(r));
3625 struct strbuf buf = STRBUF_INIT;
3628 strbuf_addf(&buf, "author %s", git_author_info(0));
3629 write_author_script(buf.buf);
3632 if (oneline_offset < arg_len) {
3633 p = arg + oneline_offset;
3634 len = arg_len - oneline_offset;
3636 strbuf_addf(&buf, "Merge %s '%.*s'",
3637 to_merge->next ? "branches" : "branch",
3638 merge_arg_len, arg);
3643 ret = write_message(p, len, git_path_merge_msg(r), 0);
3644 strbuf_release(&buf);
3646 error_errno(_("could not write '%s'"),
3647 git_path_merge_msg(r));
3653 * If HEAD is not identical to the first parent of the original merge
3654 * commit, we cannot fast-forward.
3656 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3657 oideq(&commit->parents->item->object.oid,
3658 &head_commit->object.oid);
3661 * If any merge head is different from the original one, we cannot
3664 if (can_fast_forward) {
3665 struct commit_list *p = commit->parents->next;
3667 for (j = to_merge; j && p; j = j->next, p = p->next)
3668 if (!oideq(&j->item->object.oid,
3669 &p->item->object.oid)) {
3670 can_fast_forward = 0;
3674 * If the number of merge heads differs from the original merge
3675 * commit, we cannot fast-forward.
3678 can_fast_forward = 0;
3681 if (can_fast_forward) {
3682 rollback_lock_file(&lock);
3683 ret = fast_forward_to(r, &commit->object.oid,
3684 &head_commit->object.oid, 0, opts);
3685 if (flags & TODO_EDIT_MERGE_MSG) {
3686 run_commit_flags |= AMEND_MSG;
3687 goto fast_forward_edit;
3692 if (strategy || to_merge->next) {
3694 struct child_process cmd = CHILD_PROCESS_INIT;
3696 if (read_env_script(&cmd.env_array)) {
3697 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3699 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3703 if (opts->committer_date_is_author_date)
3704 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3707 author_date_from_env_array(&cmd.env_array));
3708 if (opts->ignore_date)
3709 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3712 strvec_push(&cmd.args, "merge");
3713 strvec_push(&cmd.args, "-s");
3715 strvec_push(&cmd.args, "octopus");
3717 strvec_push(&cmd.args, strategy);
3718 for (k = 0; k < opts->xopts_nr; k++)
3719 strvec_pushf(&cmd.args,
3720 "-X%s", opts->xopts[k]);
3722 strvec_push(&cmd.args, "--no-edit");
3723 strvec_push(&cmd.args, "--no-ff");
3724 strvec_push(&cmd.args, "--no-log");
3725 strvec_push(&cmd.args, "--no-stat");
3726 strvec_push(&cmd.args, "-F");
3727 strvec_push(&cmd.args, git_path_merge_msg(r));
3729 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3731 strvec_push(&cmd.args, "--no-gpg-sign");
3733 /* Add the tips to be merged */
3734 for (j = to_merge; j; j = j->next)
3735 strvec_push(&cmd.args,
3736 oid_to_hex(&j->item->object.oid));
3738 strbuf_release(&ref_name);
3739 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3741 rollback_lock_file(&lock);
3743 ret = run_command(&cmd);
3745 /* force re-reading of the cache */
3746 if (!ret && (discard_index(r->index) < 0 ||
3747 repo_read_index(r) < 0))
3748 ret = error(_("could not read index"));
3752 merge_commit = to_merge->item;
3753 bases = get_merge_bases(head_commit, merge_commit);
3754 if (bases && oideq(&merge_commit->object.oid,
3755 &bases->item->object.oid)) {
3757 /* skip merging an ancestor of HEAD */
3761 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3762 git_path_merge_head(r), 0);
3763 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3765 for (j = bases; j; j = j->next)
3766 commit_list_insert(j->item, &reversed);
3767 free_commit_list(bases);
3770 init_merge_options(&o, r);
3772 o.branch2 = ref_name.buf;
3773 o.buffer_output = 2;
3775 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3777 * TODO: Should use merge_incore_recursive() and
3778 * merge_switch_to_result(), skipping the call to
3779 * merge_switch_to_result() when we don't actually need to
3780 * update the index and working copy immediately.
3782 ret = merge_ort_recursive(&o,
3783 head_commit, merge_commit, reversed,
3786 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3790 fputs(o.obuf.buf, stdout);
3791 strbuf_release(&o.obuf);
3793 error(_("could not even attempt to merge '%.*s'"),
3794 merge_arg_len, arg);
3798 * The return value of merge_recursive() is 1 on clean, and 0 on
3801 * Let's reverse that, so that do_merge() returns 0 upon success and
3802 * 1 upon failed merge (keeping the return value -1 for the cases where
3803 * we will want to reschedule the `merge` command).
3807 if (r->index->cache_changed &&
3808 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3809 ret = error(_("merge: Unable to write new index file"));
3813 rollback_lock_file(&lock);
3815 repo_rerere(r, opts->allow_rerere_auto);
3818 * In case of problems, we now want to return a positive
3819 * value (a negative one would indicate that the `merge`
3820 * command needs to be rescheduled).
3823 ret = !!run_git_commit(git_path_merge_msg(r), opts,
3827 strbuf_release(&ref_name);
3828 rollback_lock_file(&lock);
3829 free_commit_list(to_merge);
3833 static int is_final_fixup(struct todo_list *todo_list)
3835 int i = todo_list->current;
3837 if (!is_fixup(todo_list->items[i].command))
3840 while (++i < todo_list->nr)
3841 if (is_fixup(todo_list->items[i].command))
3843 else if (!is_noop(todo_list->items[i].command))
3848 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3852 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3853 if (!is_noop(todo_list->items[i].command))
3854 return todo_list->items[i].command;
3859 void create_autostash(struct repository *r, const char *path,
3860 const char *default_reflog_action)
3862 struct strbuf buf = STRBUF_INIT;
3863 struct lock_file lock_file = LOCK_INIT;
3866 fd = repo_hold_locked_index(r, &lock_file, 0);
3867 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
3869 repo_update_index_if_able(r, &lock_file);
3870 rollback_lock_file(&lock_file);
3872 if (has_unstaged_changes(r, 1) ||
3873 has_uncommitted_changes(r, 1)) {
3874 struct child_process stash = CHILD_PROCESS_INIT;
3875 struct object_id oid;
3877 strvec_pushl(&stash.args,
3878 "stash", "create", "autostash", NULL);
3882 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
3883 die(_("Cannot autostash"));
3884 strbuf_trim_trailing_newline(&buf);
3885 if (get_oid(buf.buf, &oid))
3886 die(_("Unexpected stash response: '%s'"),
3889 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
3891 if (safe_create_leading_directories_const(path))
3892 die(_("Could not create directory for '%s'"),
3894 write_file(path, "%s", oid_to_hex(&oid));
3895 printf(_("Created autostash: %s\n"), buf.buf);
3896 if (reset_head(r, NULL, "reset --hard",
3897 NULL, RESET_HEAD_HARD, NULL, NULL,
3898 default_reflog_action) < 0)
3899 die(_("could not reset --hard"));
3901 if (discard_index(r->index) < 0 ||
3902 repo_read_index(r) < 0)
3903 die(_("could not read index"));
3905 strbuf_release(&buf);
3908 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
3910 struct child_process child = CHILD_PROCESS_INIT;
3913 if (attempt_apply) {
3915 child.no_stdout = 1;
3916 child.no_stderr = 1;
3917 strvec_push(&child.args, "stash");
3918 strvec_push(&child.args, "apply");
3919 strvec_push(&child.args, stash_oid);
3920 ret = run_command(&child);
3923 if (attempt_apply && !ret)
3924 fprintf(stderr, _("Applied autostash.\n"));
3926 struct child_process store = CHILD_PROCESS_INIT;
3929 strvec_push(&store.args, "stash");
3930 strvec_push(&store.args, "store");
3931 strvec_push(&store.args, "-m");
3932 strvec_push(&store.args, "autostash");
3933 strvec_push(&store.args, "-q");
3934 strvec_push(&store.args, stash_oid);
3935 if (run_command(&store))
3936 ret = error(_("cannot store %s"), stash_oid);
3940 "Your changes are safe in the stash.\n"
3941 "You can run \"git stash pop\" or"
3942 " \"git stash drop\" at any time.\n"),
3944 _("Applying autostash resulted in conflicts.") :
3945 _("Autostash exists; creating a new stash entry."));
3951 static int apply_save_autostash(const char *path, int attempt_apply)
3953 struct strbuf stash_oid = STRBUF_INIT;
3956 if (!read_oneliner(&stash_oid, path,
3957 READ_ONELINER_SKIP_IF_EMPTY)) {
3958 strbuf_release(&stash_oid);
3961 strbuf_trim(&stash_oid);
3963 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
3966 strbuf_release(&stash_oid);
3970 int save_autostash(const char *path)
3972 return apply_save_autostash(path, 0);
3975 int apply_autostash(const char *path)
3977 return apply_save_autostash(path, 1);
3980 int apply_autostash_oid(const char *stash_oid)
3982 return apply_save_autostash_oid(stash_oid, 1);
3985 static const char *reflog_message(struct replay_opts *opts,
3986 const char *sub_action, const char *fmt, ...)
3989 static struct strbuf buf = STRBUF_INIT;
3990 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3994 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3996 strbuf_addf(&buf, " (%s)", sub_action);
3998 strbuf_addstr(&buf, ": ");
3999 strbuf_vaddf(&buf, fmt, ap);
4006 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4007 const char *commit, const char *action)
4009 struct child_process cmd = CHILD_PROCESS_INIT;
4014 strvec_push(&cmd.args, "checkout");
4015 strvec_push(&cmd.args, commit);
4016 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4019 ret = run_command(&cmd);
4021 ret = run_command_silent_on_success(&cmd);
4024 discard_index(r->index);
4029 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4030 const char *onto_name, const struct object_id *onto,
4031 const struct object_id *orig_head)
4033 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4035 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4036 apply_autostash(rebase_path_autostash());
4037 sequencer_remove_state(opts);
4038 return error(_("could not detach HEAD"));
4041 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4044 static int stopped_at_head(struct repository *r)
4046 struct object_id head;
4047 struct commit *commit;
4048 struct commit_message message;
4050 if (get_oid("HEAD", &head) ||
4051 !(commit = lookup_commit(r, &head)) ||
4052 parse_commit(commit) || get_message(commit, &message))
4053 fprintf(stderr, _("Stopped at HEAD\n"));
4055 fprintf(stderr, _("Stopped at %s\n"), message.label);
4056 free_message(commit, &message);
4062 static const char rescheduled_advice[] =
4063 N_("Could not execute the todo command\n"
4067 "It has been rescheduled; To edit the command before continuing, please\n"
4068 "edit the todo list first:\n"
4070 " git rebase --edit-todo\n"
4071 " git rebase --continue\n");
4073 static int pick_commits(struct repository *r,
4074 struct todo_list *todo_list,
4075 struct replay_opts *opts)
4077 int res = 0, reschedule = 0;
4078 char *prev_reflog_action;
4080 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4081 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4082 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4084 assert(!(opts->signoff || opts->no_commit ||
4085 opts->record_origin || opts->edit ||
4086 opts->committer_date_is_author_date ||
4087 opts->ignore_date));
4088 if (read_and_refresh_cache(r, opts))
4091 while (todo_list->current < todo_list->nr) {
4092 struct todo_item *item = todo_list->items + todo_list->current;
4093 const char *arg = todo_item_get_arg(todo_list, item);
4096 if (save_todo(todo_list, opts))
4098 if (is_rebase_i(opts)) {
4099 if (item->command != TODO_COMMENT) {
4100 FILE *f = fopen(rebase_path_msgnum(), "w");
4102 todo_list->done_nr++;
4105 fprintf(f, "%d\n", todo_list->done_nr);
4109 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4111 todo_list->total_nr,
4112 opts->verbose ? "\n" : "\r");
4114 unlink(rebase_path_message());
4115 unlink(rebase_path_author_script());
4116 unlink(rebase_path_stopped_sha());
4117 unlink(rebase_path_amend());
4118 unlink(git_path_merge_head(r));
4119 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4121 if (item->command == TODO_BREAK) {
4124 return stopped_at_head(r);
4127 if (item->command <= TODO_SQUASH) {
4128 if (is_rebase_i(opts))
4129 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4130 command_to_string(item->command), NULL),
4132 res = do_pick_commit(r, item->command, item->commit,
4133 opts, is_final_fixup(todo_list),
4135 if (is_rebase_i(opts))
4136 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4137 if (is_rebase_i(opts) && res < 0) {
4139 advise(_(rescheduled_advice),
4140 get_item_line_length(todo_list,
4141 todo_list->current),
4142 get_item_line(todo_list,
4143 todo_list->current));
4144 todo_list->current--;
4145 if (save_todo(todo_list, opts))
4148 if (item->command == TODO_EDIT) {
4149 struct commit *commit = item->commit;
4154 _("Stopped at %s... %.*s\n"),
4155 short_commit_name(commit),
4156 item->arg_len, arg);
4158 return error_with_patch(r, commit,
4159 arg, item->arg_len, opts, res, !res);
4161 if (is_rebase_i(opts) && !res)
4162 record_in_rewritten(&item->commit->object.oid,
4163 peek_command(todo_list, 1));
4164 if (res && is_fixup(item->command)) {
4167 return error_failed_squash(r, item->commit, opts,
4168 item->arg_len, arg);
4169 } else if (res && is_rebase_i(opts) && item->commit) {
4171 struct object_id oid;
4174 * If we are rewording and have either
4175 * fast-forwarded already, or are about to
4176 * create a new root commit, we want to amend,
4177 * otherwise we do not.
4179 if (item->command == TODO_REWORD &&
4180 !get_oid("HEAD", &oid) &&
4181 (oideq(&item->commit->object.oid, &oid) ||
4182 (opts->have_squash_onto &&
4183 oideq(&opts->squash_onto, &oid))))
4186 return res | error_with_patch(r, item->commit,
4187 arg, item->arg_len, opts,
4190 } else if (item->command == TODO_EXEC) {
4191 char *end_of_arg = (char *)(arg + item->arg_len);
4192 int saved = *end_of_arg;
4197 res = do_exec(r, arg);
4198 *end_of_arg = saved;
4201 if (opts->reschedule_failed_exec)
4205 } else if (item->command == TODO_LABEL) {
4206 if ((res = do_label(r, arg, item->arg_len)))
4208 } else if (item->command == TODO_RESET) {
4209 if ((res = do_reset(r, arg, item->arg_len, opts)))
4211 } else if (item->command == TODO_MERGE) {
4212 if ((res = do_merge(r, item->commit,
4214 item->flags, opts)) < 0)
4216 else if (item->commit)
4217 record_in_rewritten(&item->commit->object.oid,
4218 peek_command(todo_list, 1));
4220 /* failed with merge conflicts */
4221 return error_with_patch(r, item->commit,
4224 } else if (!is_noop(item->command))
4225 return error(_("unknown command %d"), item->command);
4228 advise(_(rescheduled_advice),
4229 get_item_line_length(todo_list,
4230 todo_list->current),
4231 get_item_line(todo_list, todo_list->current));
4232 todo_list->current--;
4233 if (save_todo(todo_list, opts))
4236 return error_with_patch(r,
4240 } else if (is_rebase_i(opts) && check_todo && !res) {
4243 if (stat(get_todo_path(opts), &st)) {
4244 res = error_errno(_("could not stat '%s'"),
4245 get_todo_path(opts));
4246 } else if (match_stat_data(&todo_list->stat, &st)) {
4247 /* Reread the todo file if it has changed. */
4248 todo_list_release(todo_list);
4249 if (read_populate_todo(r, todo_list, opts))
4250 res = -1; /* message was printed */
4251 /* `current` will be incremented below */
4252 todo_list->current = -1;
4256 todo_list->current++;
4261 if (is_rebase_i(opts)) {
4262 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4265 /* Stopped in the middle, as planned? */
4266 if (todo_list->current < todo_list->nr)
4269 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4270 starts_with(head_ref.buf, "refs/")) {
4272 struct object_id head, orig;
4275 if (get_oid("HEAD", &head)) {
4276 res = error(_("cannot read HEAD"));
4278 strbuf_release(&head_ref);
4279 strbuf_release(&buf);
4282 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4283 get_oid_hex(buf.buf, &orig)) {
4284 res = error(_("could not read orig-head"));
4285 goto cleanup_head_ref;
4288 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4289 res = error(_("could not read 'onto'"));
4290 goto cleanup_head_ref;
4292 msg = reflog_message(opts, "finish", "%s onto %s",
4293 head_ref.buf, buf.buf);
4294 if (update_ref(msg, head_ref.buf, &head, &orig,
4295 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4296 res = error(_("could not update %s"),
4298 goto cleanup_head_ref;
4300 msg = reflog_message(opts, "finish", "returning to %s",
4302 if (create_symref("HEAD", head_ref.buf, msg)) {
4303 res = error(_("could not update HEAD to %s"),
4305 goto cleanup_head_ref;
4310 if (opts->verbose) {
4311 struct rev_info log_tree_opt;
4312 struct object_id orig, head;
4314 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4315 repo_init_revisions(r, &log_tree_opt, NULL);
4316 log_tree_opt.diff = 1;
4317 log_tree_opt.diffopt.output_format =
4318 DIFF_FORMAT_DIFFSTAT;
4319 log_tree_opt.disable_stdin = 1;
4321 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4322 !get_oid(buf.buf, &orig) &&
4323 !get_oid("HEAD", &head)) {
4324 diff_tree_oid(&orig, &head, "",
4325 &log_tree_opt.diffopt);
4326 log_tree_diff_flush(&log_tree_opt);
4329 flush_rewritten_pending();
4330 if (!stat(rebase_path_rewritten_list(), &st) &&
4332 struct child_process child = CHILD_PROCESS_INIT;
4333 const char *post_rewrite_hook =
4334 find_hook("post-rewrite");
4336 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4338 strvec_push(&child.args, "notes");
4339 strvec_push(&child.args, "copy");
4340 strvec_push(&child.args, "--for-rewrite=rebase");
4341 /* we don't care if this copying failed */
4342 run_command(&child);
4344 if (post_rewrite_hook) {
4345 struct child_process hook = CHILD_PROCESS_INIT;
4347 hook.in = open(rebase_path_rewritten_list(),
4349 hook.stdout_to_stderr = 1;
4350 hook.trace2_hook_name = "post-rewrite";
4351 strvec_push(&hook.args, post_rewrite_hook);
4352 strvec_push(&hook.args, "rebase");
4353 /* we don't care if this hook failed */
4357 apply_autostash(rebase_path_autostash());
4363 _("Successfully rebased and updated %s.\n"),
4367 strbuf_release(&buf);
4368 strbuf_release(&head_ref);
4372 * Sequence of picks finished successfully; cleanup by
4373 * removing the .git/sequencer directory
4375 return sequencer_remove_state(opts);
4378 static int continue_single_pick(struct repository *r)
4380 const char *argv[] = { "commit", NULL };
4382 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4383 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4384 return error(_("no cherry-pick or revert in progress"));
4385 return run_command_v_opt(argv, RUN_GIT_CMD);
4388 static int commit_staged_changes(struct repository *r,
4389 struct replay_opts *opts,
4390 struct todo_list *todo_list)
4392 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4393 unsigned int final_fixup = 0, is_clean;
4395 if (has_unstaged_changes(r, 1))
4396 return error(_("cannot rebase: You have unstaged changes."));
4398 is_clean = !has_uncommitted_changes(r, 0);
4400 if (file_exists(rebase_path_amend())) {
4401 struct strbuf rev = STRBUF_INIT;
4402 struct object_id head, to_amend;
4404 if (get_oid("HEAD", &head))
4405 return error(_("cannot amend non-existing commit"));
4406 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4407 return error(_("invalid file: '%s'"), rebase_path_amend());
4408 if (get_oid_hex(rev.buf, &to_amend))
4409 return error(_("invalid contents: '%s'"),
4410 rebase_path_amend());
4411 if (!is_clean && !oideq(&head, &to_amend))
4412 return error(_("\nYou have uncommitted changes in your "
4413 "working tree. Please, commit them\n"
4414 "first and then run 'git rebase "
4415 "--continue' again."));
4417 * When skipping a failed fixup/squash, we need to edit the
4418 * commit message, the current fixup list and count, and if it
4419 * was the last fixup/squash in the chain, we need to clean up
4420 * the commit message and if there was a squash, let the user
4423 if (!is_clean || !opts->current_fixup_count)
4424 ; /* this is not the final fixup */
4425 else if (!oideq(&head, &to_amend) ||
4426 !file_exists(rebase_path_stopped_sha())) {
4427 /* was a final fixup or squash done manually? */
4428 if (!is_fixup(peek_command(todo_list, 0))) {
4429 unlink(rebase_path_fixup_msg());
4430 unlink(rebase_path_squash_msg());
4431 unlink(rebase_path_current_fixups());
4432 strbuf_reset(&opts->current_fixups);
4433 opts->current_fixup_count = 0;
4436 /* we are in a fixup/squash chain */
4437 const char *p = opts->current_fixups.buf;
4438 int len = opts->current_fixups.len;
4440 opts->current_fixup_count--;
4442 BUG("Incorrect current_fixups:\n%s", p);
4443 while (len && p[len - 1] != '\n')
4445 strbuf_setlen(&opts->current_fixups, len);
4446 if (write_message(p, len, rebase_path_current_fixups(),
4448 return error(_("could not write file: '%s'"),
4449 rebase_path_current_fixups());
4452 * If a fixup/squash in a fixup/squash chain failed, the
4453 * commit message is already correct, no need to commit
4456 * Only if it is the final command in the fixup/squash
4457 * chain, and only if the chain is longer than a single
4458 * fixup/squash command (which was just skipped), do we
4459 * actually need to re-commit with a cleaned up commit
4462 if (opts->current_fixup_count > 0 &&
4463 !is_fixup(peek_command(todo_list, 0))) {
4466 * If there was not a single "squash" in the
4467 * chain, we only need to clean up the commit
4468 * message, no need to bother the user with
4469 * opening the commit message in the editor.
4471 if (!starts_with(p, "squash ") &&
4472 !strstr(p, "\nsquash "))
4473 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4474 } else if (is_fixup(peek_command(todo_list, 0))) {
4476 * We need to update the squash message to skip
4477 * the latest commit message.
4479 struct commit *commit;
4480 const char *path = rebase_path_squash_msg();
4481 const char *encoding = get_commit_output_encoding();
4483 if (parse_head(r, &commit) ||
4484 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4485 write_message(p, strlen(p), path, 0)) {
4486 unuse_commit_buffer(commit, p);
4487 return error(_("could not write file: "
4490 unuse_commit_buffer(commit, p);
4494 strbuf_release(&rev);
4499 if (refs_ref_exists(get_main_ref_store(r),
4500 "CHERRY_PICK_HEAD") &&
4501 refs_delete_ref(get_main_ref_store(r), "",
4502 "CHERRY_PICK_HEAD", NULL, 0))
4503 return error(_("could not remove CHERRY_PICK_HEAD"));
4508 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4510 return error(_("could not commit staged changes."));
4511 unlink(rebase_path_amend());
4512 unlink(git_path_merge_head(r));
4514 unlink(rebase_path_fixup_msg());
4515 unlink(rebase_path_squash_msg());
4517 if (opts->current_fixup_count > 0) {
4519 * Whether final fixup or not, we just cleaned up the commit
4522 unlink(rebase_path_current_fixups());
4523 strbuf_reset(&opts->current_fixups);
4524 opts->current_fixup_count = 0;
4529 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4531 struct todo_list todo_list = TODO_LIST_INIT;
4534 if (read_and_refresh_cache(r, opts))
4537 if (read_populate_opts(opts))
4539 if (is_rebase_i(opts)) {
4540 if ((res = read_populate_todo(r, &todo_list, opts)))
4541 goto release_todo_list;
4543 if (file_exists(rebase_path_dropped())) {
4544 if ((res = todo_list_check_against_backup(r, &todo_list)))
4545 goto release_todo_list;
4547 unlink(rebase_path_dropped());
4550 if (commit_staged_changes(r, opts, &todo_list)) {
4552 goto release_todo_list;
4554 } else if (!file_exists(get_todo_path(opts)))
4555 return continue_single_pick(r);
4556 else if ((res = read_populate_todo(r, &todo_list, opts)))
4557 goto release_todo_list;
4559 if (!is_rebase_i(opts)) {
4560 /* Verify that the conflict has been resolved */
4561 if (refs_ref_exists(get_main_ref_store(r),
4562 "CHERRY_PICK_HEAD") ||
4563 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4564 res = continue_single_pick(r);
4566 goto release_todo_list;
4568 if (index_differs_from(r, "HEAD", NULL, 0)) {
4569 res = error_dirty_index(r, opts);
4570 goto release_todo_list;
4572 todo_list.current++;
4573 } else if (file_exists(rebase_path_stopped_sha())) {
4574 struct strbuf buf = STRBUF_INIT;
4575 struct object_id oid;
4577 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4578 READ_ONELINER_SKIP_IF_EMPTY) &&
4579 !get_oid_hex(buf.buf, &oid))
4580 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4581 strbuf_release(&buf);
4584 res = pick_commits(r, &todo_list, opts);
4586 todo_list_release(&todo_list);
4590 static int single_pick(struct repository *r,
4591 struct commit *cmit,
4592 struct replay_opts *opts)
4596 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4597 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4598 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4602 int sequencer_pick_revisions(struct repository *r,
4603 struct replay_opts *opts)
4605 struct todo_list todo_list = TODO_LIST_INIT;
4606 struct object_id oid;
4610 if (read_and_refresh_cache(r, opts))
4613 for (i = 0; i < opts->revs->pending.nr; i++) {
4614 struct object_id oid;
4615 const char *name = opts->revs->pending.objects[i].name;
4617 /* This happens when using --stdin. */
4621 if (!get_oid(name, &oid)) {
4622 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4623 enum object_type type = oid_object_info(r,
4626 return error(_("%s: can't cherry-pick a %s"),
4627 name, type_name(type));
4630 return error(_("%s: bad revision"), name);
4634 * If we were called as "git cherry-pick <commit>", just
4635 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4636 * REVERT_HEAD, and don't touch the sequencer state.
4637 * This means it is possible to cherry-pick in the middle
4638 * of a cherry-pick sequence.
4640 if (opts->revs->cmdline.nr == 1 &&
4641 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4642 opts->revs->no_walk &&
4643 !opts->revs->cmdline.rev->flags) {
4644 struct commit *cmit;
4645 if (prepare_revision_walk(opts->revs))
4646 return error(_("revision walk setup failed"));
4647 cmit = get_revision(opts->revs);
4649 return error(_("empty commit set passed"));
4650 if (get_revision(opts->revs))
4651 BUG("unexpected extra commit from walk");
4652 return single_pick(r, cmit, opts);
4656 * Start a new cherry-pick/ revert sequence; but
4657 * first, make sure that an existing one isn't in
4661 if (walk_revs_populate_todo(&todo_list, opts) ||
4662 create_seq_dir(r) < 0)
4664 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4665 return error(_("can't revert as initial commit"));
4666 if (save_head(oid_to_hex(&oid)))
4668 if (save_opts(opts))
4670 update_abort_safety_file();
4671 res = pick_commits(r, &todo_list, opts);
4672 todo_list_release(&todo_list);
4676 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4678 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4679 struct strbuf sob = STRBUF_INIT;
4682 strbuf_addstr(&sob, sign_off_header);
4683 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4684 strbuf_addch(&sob, '\n');
4687 strbuf_complete_line(msgbuf);
4690 * If the whole message buffer is equal to the sob, pretend that we
4691 * found a conforming footer with a matching sob
4693 if (msgbuf->len - ignore_footer == sob.len &&
4694 !strncmp(msgbuf->buf, sob.buf, sob.len))
4697 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4700 const char *append_newlines = NULL;
4701 size_t len = msgbuf->len - ignore_footer;
4705 * The buffer is completely empty. Leave foom for
4706 * the title and body to be filled in by the user.
4708 append_newlines = "\n\n";
4709 } else if (len == 1) {
4711 * Buffer contains a single newline. Add another
4712 * so that we leave room for the title and body.
4714 append_newlines = "\n";
4715 } else if (msgbuf->buf[len - 2] != '\n') {
4717 * Buffer ends with a single newline. Add another
4718 * so that there is an empty line between the message
4721 append_newlines = "\n";
4722 } /* else, the buffer already ends with two newlines. */
4724 if (append_newlines)
4725 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4726 append_newlines, strlen(append_newlines));
4729 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4730 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4733 strbuf_release(&sob);
4736 struct labels_entry {
4737 struct hashmap_entry entry;
4738 char label[FLEX_ARRAY];
4741 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4742 const struct hashmap_entry *entry_or_key, const void *key)
4744 const struct labels_entry *a, *b;
4746 a = container_of(eptr, const struct labels_entry, entry);
4747 b = container_of(entry_or_key, const struct labels_entry, entry);
4749 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4752 struct string_entry {
4753 struct oidmap_entry entry;
4754 char string[FLEX_ARRAY];
4757 struct label_state {
4758 struct oidmap commit2label;
4759 struct hashmap labels;
4763 static const char *label_oid(struct object_id *oid, const char *label,
4764 struct label_state *state)
4766 struct labels_entry *labels_entry;
4767 struct string_entry *string_entry;
4768 struct object_id dummy;
4771 string_entry = oidmap_get(&state->commit2label, oid);
4773 return string_entry->string;
4776 * For "uninteresting" commits, i.e. commits that are not to be
4777 * rebased, and which can therefore not be labeled, we use a unique
4778 * abbreviation of the commit name. This is slightly more complicated
4779 * than calling find_unique_abbrev() because we also need to make
4780 * sure that the abbreviation does not conflict with any other
4783 * We disallow "interesting" commits to be labeled by a string that
4784 * is a valid full-length hash, to ensure that we always can find an
4785 * abbreviation for any uninteresting commit's names that does not
4786 * clash with any other label.
4788 strbuf_reset(&state->buf);
4792 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4793 label = p = state->buf.buf;
4795 find_unique_abbrev_r(p, oid, default_abbrev);
4798 * We may need to extend the abbreviated hash so that there is
4799 * no conflicting label.
4801 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4802 size_t i = strlen(p) + 1;
4804 oid_to_hex_r(p, oid);
4805 for (; i < the_hash_algo->hexsz; i++) {
4808 if (!hashmap_get_from_hash(&state->labels,
4815 struct strbuf *buf = &state->buf;
4818 * Sanitize labels by replacing non-alpha-numeric characters
4819 * (including white-space ones) by dashes, as they might be
4820 * illegal in file names (and hence in ref names).
4822 * Note that we retain non-ASCII UTF-8 characters (identified
4823 * via the most significant bit). They should be all acceptable
4824 * in file names. We do not validate the UTF-8 here, that's not
4825 * the job of this function.
4827 for (; *label; label++)
4828 if ((*label & 0x80) || isalnum(*label))
4829 strbuf_addch(buf, *label);
4830 /* avoid leading dash and double-dashes */
4831 else if (buf->len && buf->buf[buf->len - 1] != '-')
4832 strbuf_addch(buf, '-');
4834 strbuf_addstr(buf, "rev-");
4835 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4839 if ((buf->len == the_hash_algo->hexsz &&
4840 !get_oid_hex(label, &dummy)) ||
4841 (buf->len == 1 && *label == '#') ||
4842 hashmap_get_from_hash(&state->labels,
4843 strihash(label), label)) {
4845 * If the label already exists, or if the label is a
4846 * valid full OID, or the label is a '#' (which we use
4847 * as a separator between merge heads and oneline), we
4848 * append a dash and a number to make it unique.
4850 size_t len = buf->len;
4852 for (i = 2; ; i++) {
4853 strbuf_setlen(buf, len);
4854 strbuf_addf(buf, "-%d", i);
4855 if (!hashmap_get_from_hash(&state->labels,
4865 FLEX_ALLOC_STR(labels_entry, label, label);
4866 hashmap_entry_init(&labels_entry->entry, strihash(label));
4867 hashmap_add(&state->labels, &labels_entry->entry);
4869 FLEX_ALLOC_STR(string_entry, string, label);
4870 oidcpy(&string_entry->entry.oid, oid);
4871 oidmap_put(&state->commit2label, string_entry);
4873 return string_entry->string;
4876 static int make_script_with_merges(struct pretty_print_context *pp,
4877 struct rev_info *revs, struct strbuf *out,
4880 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4881 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4882 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4883 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4884 struct strbuf label = STRBUF_INIT;
4885 struct commit_list *commits = NULL, **tail = &commits, *iter;
4886 struct commit_list *tips = NULL, **tips_tail = &tips;
4887 struct commit *commit;
4888 struct oidmap commit2todo = OIDMAP_INIT;
4889 struct string_entry *entry;
4890 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4891 shown = OIDSET_INIT;
4892 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4894 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4895 const char *cmd_pick = abbr ? "p" : "pick",
4896 *cmd_label = abbr ? "l" : "label",
4897 *cmd_reset = abbr ? "t" : "reset",
4898 *cmd_merge = abbr ? "m" : "merge";
4900 oidmap_init(&commit2todo, 0);
4901 oidmap_init(&state.commit2label, 0);
4902 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4903 strbuf_init(&state.buf, 32);
4905 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4906 struct labels_entry *onto_label_entry;
4907 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4908 FLEX_ALLOC_STR(entry, string, "onto");
4909 oidcpy(&entry->entry.oid, oid);
4910 oidmap_put(&state.commit2label, entry);
4912 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4913 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4914 hashmap_add(&state.labels, &onto_label_entry->entry);
4919 * - get onelines for all commits
4920 * - gather all branch tips (i.e. 2nd or later parents of merges)
4921 * - label all branch tips
4923 while ((commit = get_revision(revs))) {
4924 struct commit_list *to_merge;
4925 const char *p1, *p2;
4926 struct object_id *oid;
4929 tail = &commit_list_insert(commit, tail)->next;
4930 oidset_insert(&interesting, &commit->object.oid);
4932 is_empty = is_original_commit_empty(commit);
4933 if (!is_empty && (commit->object.flags & PATCHSAME))
4935 if (is_empty && !keep_empty)
4938 strbuf_reset(&oneline);
4939 pretty_print_commit(pp, commit, &oneline);
4941 to_merge = commit->parents ? commit->parents->next : NULL;
4943 /* non-merge commit: easy case */
4945 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4946 oid_to_hex(&commit->object.oid),
4949 strbuf_addf(&buf, " %c empty",
4952 FLEX_ALLOC_STR(entry, string, buf.buf);
4953 oidcpy(&entry->entry.oid, &commit->object.oid);
4954 oidmap_put(&commit2todo, entry);
4959 /* Create a label */
4960 strbuf_reset(&label);
4961 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4962 (p1 = strchr(p1, '\'')) &&
4963 (p2 = strchr(++p1, '\'')))
4964 strbuf_add(&label, p1, p2 - p1);
4965 else if (skip_prefix(oneline.buf, "Merge pull request ",
4967 (p1 = strstr(p1, " from ")))
4968 strbuf_addstr(&label, p1 + strlen(" from "));
4970 strbuf_addbuf(&label, &oneline);
4973 strbuf_addf(&buf, "%s -C %s",
4974 cmd_merge, oid_to_hex(&commit->object.oid));
4976 /* label the tips of merged branches */
4977 for (; to_merge; to_merge = to_merge->next) {
4978 oid = &to_merge->item->object.oid;
4979 strbuf_addch(&buf, ' ');
4981 if (!oidset_contains(&interesting, oid)) {
4982 strbuf_addstr(&buf, label_oid(oid, NULL,
4987 tips_tail = &commit_list_insert(to_merge->item,
4990 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4992 strbuf_addf(&buf, " # %s", oneline.buf);
4994 FLEX_ALLOC_STR(entry, string, buf.buf);
4995 oidcpy(&entry->entry.oid, &commit->object.oid);
4996 oidmap_put(&commit2todo, entry);
5001 * - label branch points
5002 * - add HEAD to the branch tips
5004 for (iter = commits; iter; iter = iter->next) {
5005 struct commit_list *parent = iter->item->parents;
5006 for (; parent; parent = parent->next) {
5007 struct object_id *oid = &parent->item->object.oid;
5008 if (!oidset_contains(&interesting, oid))
5010 if (oidset_insert(&child_seen, oid))
5011 label_oid(oid, "branch-point", &state);
5014 /* Add HEAD as implicit "tip of branch" */
5016 tips_tail = &commit_list_insert(iter->item,
5021 * Third phase: output the todo list. This is a bit tricky, as we
5022 * want to avoid jumping back and forth between revisions. To
5023 * accomplish that goal, we walk backwards from the branch tips,
5024 * gathering commits not yet shown, reversing the list on the fly,
5025 * then outputting that list (labeling revisions as needed).
5027 strbuf_addf(out, "%s onto\n", cmd_label);
5028 for (iter = tips; iter; iter = iter->next) {
5029 struct commit_list *list = NULL, *iter2;
5031 commit = iter->item;
5032 if (oidset_contains(&shown, &commit->object.oid))
5034 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5037 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5039 strbuf_addch(out, '\n');
5041 while (oidset_contains(&interesting, &commit->object.oid) &&
5042 !oidset_contains(&shown, &commit->object.oid)) {
5043 commit_list_insert(commit, &list);
5044 if (!commit->parents) {
5048 commit = commit->parents->item;
5052 strbuf_addf(out, "%s %s\n", cmd_reset,
5053 rebase_cousins || root_with_onto ?
5054 "onto" : "[new root]");
5056 const char *to = NULL;
5058 entry = oidmap_get(&state.commit2label,
5059 &commit->object.oid);
5062 else if (!rebase_cousins)
5063 to = label_oid(&commit->object.oid, NULL,
5066 if (!to || !strcmp(to, "onto"))
5067 strbuf_addf(out, "%s onto\n", cmd_reset);
5069 strbuf_reset(&oneline);
5070 pretty_print_commit(pp, commit, &oneline);
5071 strbuf_addf(out, "%s %s # %s\n",
5072 cmd_reset, to, oneline.buf);
5076 for (iter2 = list; iter2; iter2 = iter2->next) {
5077 struct object_id *oid = &iter2->item->object.oid;
5078 entry = oidmap_get(&commit2todo, oid);
5079 /* only show if not already upstream */
5081 strbuf_addf(out, "%s\n", entry->string);
5082 entry = oidmap_get(&state.commit2label, oid);
5084 strbuf_addf(out, "%s %s\n",
5085 cmd_label, entry->string);
5086 oidset_insert(&shown, oid);
5089 free_commit_list(list);
5092 free_commit_list(commits);
5093 free_commit_list(tips);
5095 strbuf_release(&label);
5096 strbuf_release(&oneline);
5097 strbuf_release(&buf);
5099 oidmap_free(&commit2todo, 1);
5100 oidmap_free(&state.commit2label, 1);
5101 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5102 strbuf_release(&state.buf);
5107 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5108 const char **argv, unsigned flags)
5110 char *format = NULL;
5111 struct pretty_print_context pp = {0};
5112 struct rev_info revs;
5113 struct commit *commit;
5114 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5115 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5116 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5117 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5119 repo_init_revisions(r, &revs, NULL);
5120 revs.verbose_header = 1;
5122 revs.max_parents = 1;
5123 revs.cherry_mark = !reapply_cherry_picks;
5126 revs.right_only = 1;
5127 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5128 revs.topo_order = 1;
5130 revs.pretty_given = 1;
5131 git_config_get_string("rebase.instructionFormat", &format);
5132 if (!format || !*format) {
5134 format = xstrdup("%s");
5136 get_commit_format(format, &revs);
5138 pp.fmt = revs.commit_format;
5139 pp.output_encoding = get_log_output_encoding();
5141 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5142 return error(_("make_script: unhandled options"));
5144 if (prepare_revision_walk(&revs) < 0)
5145 return error(_("make_script: error preparing revisions"));
5148 return make_script_with_merges(&pp, &revs, out, flags);
5150 while ((commit = get_revision(&revs))) {
5151 int is_empty = is_original_commit_empty(commit);
5153 if (!is_empty && (commit->object.flags & PATCHSAME))
5155 if (is_empty && !keep_empty)
5157 strbuf_addf(out, "%s %s ", insn,
5158 oid_to_hex(&commit->object.oid));
5159 pretty_print_commit(&pp, commit, out);
5161 strbuf_addf(out, " %c empty", comment_line_char);
5162 strbuf_addch(out, '\n');
5168 * Add commands after pick and (series of) squash/fixup commands
5171 void todo_list_add_exec_commands(struct todo_list *todo_list,
5172 struct string_list *commands)
5174 struct strbuf *buf = &todo_list->buf;
5175 size_t base_offset = buf->len;
5176 int i, insert, nr = 0, alloc = 0;
5177 struct todo_item *items = NULL, *base_items = NULL;
5179 CALLOC_ARRAY(base_items, commands->nr);
5180 for (i = 0; i < commands->nr; i++) {
5181 size_t command_len = strlen(commands->items[i].string);
5183 strbuf_addstr(buf, commands->items[i].string);
5184 strbuf_addch(buf, '\n');
5186 base_items[i].command = TODO_EXEC;
5187 base_items[i].offset_in_buf = base_offset;
5188 base_items[i].arg_offset = base_offset + strlen("exec ");
5189 base_items[i].arg_len = command_len - strlen("exec ");
5191 base_offset += command_len + 1;
5195 * Insert <commands> after every pick. Here, fixup/squash chains
5196 * are considered part of the pick, so we insert the commands *after*
5197 * those chains if there are any.
5199 * As we insert the exec commands immediately after rearranging
5200 * any fixups and before the user edits the list, a fixup chain
5201 * can never contain comments (any comments are empty picks that
5202 * have been commented out because the user did not specify
5203 * --keep-empty). So, it is safe to insert an exec command
5204 * without looking at the command following a comment.
5207 for (i = 0; i < todo_list->nr; i++) {
5208 enum todo_command command = todo_list->items[i].command;
5209 if (insert && !is_fixup(command)) {
5210 ALLOC_GROW(items, nr + commands->nr, alloc);
5211 COPY_ARRAY(items + nr, base_items, commands->nr);
5217 ALLOC_GROW(items, nr + 1, alloc);
5218 items[nr++] = todo_list->items[i];
5220 if (command == TODO_PICK || command == TODO_MERGE)
5224 /* insert or append final <commands> */
5225 if (insert || nr == todo_list->nr) {
5226 ALLOC_GROW(items, nr + commands->nr, alloc);
5227 COPY_ARRAY(items + nr, base_items, commands->nr);
5232 FREE_AND_NULL(todo_list->items);
5233 todo_list->items = items;
5235 todo_list->alloc = alloc;
5238 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5239 struct strbuf *buf, int num, unsigned flags)
5241 struct todo_item *item;
5242 int i, max = todo_list->nr;
5244 if (num > 0 && num < max)
5247 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5250 /* if the item is not a command write it and continue */
5251 if (item->command >= TODO_COMMENT) {
5252 strbuf_addf(buf, "%.*s\n", item->arg_len,
5253 todo_item_get_arg(todo_list, item));
5257 /* add command to the buffer */
5258 cmd = command_to_char(item->command);
5259 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5260 strbuf_addch(buf, cmd);
5262 strbuf_addstr(buf, command_to_string(item->command));
5266 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5267 short_commit_name(item->commit) :
5268 oid_to_hex(&item->commit->object.oid);
5270 if (item->command == TODO_MERGE) {
5271 if (item->flags & TODO_EDIT_MERGE_MSG)
5272 strbuf_addstr(buf, " -c");
5274 strbuf_addstr(buf, " -C");
5277 strbuf_addf(buf, " %s", oid);
5280 /* add all the rest */
5282 strbuf_addch(buf, '\n');
5284 strbuf_addf(buf, " %.*s\n", item->arg_len,
5285 todo_item_get_arg(todo_list, item));
5289 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5290 const char *file, const char *shortrevisions,
5291 const char *shortonto, int num, unsigned flags)
5294 struct strbuf buf = STRBUF_INIT;
5296 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5297 if (flags & TODO_LIST_APPEND_TODO_HELP)
5298 append_todo_help(count_commands(todo_list),
5299 shortrevisions, shortonto, &buf);
5301 res = write_message(buf.buf, buf.len, file, 0);
5302 strbuf_release(&buf);
5307 /* skip picking commits whose parents are unchanged */
5308 static int skip_unnecessary_picks(struct repository *r,
5309 struct todo_list *todo_list,
5310 struct object_id *base_oid)
5312 struct object_id *parent_oid;
5315 for (i = 0; i < todo_list->nr; i++) {
5316 struct todo_item *item = todo_list->items + i;
5318 if (item->command >= TODO_NOOP)
5320 if (item->command != TODO_PICK)
5322 if (parse_commit(item->commit)) {
5323 return error(_("could not parse commit '%s'"),
5324 oid_to_hex(&item->commit->object.oid));
5326 if (!item->commit->parents)
5327 break; /* root commit */
5328 if (item->commit->parents->next)
5329 break; /* merge commit */
5330 parent_oid = &item->commit->parents->item->object.oid;
5331 if (!oideq(parent_oid, base_oid))
5333 oidcpy(base_oid, &item->commit->object.oid);
5336 const char *done_path = rebase_path_done();
5338 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5339 error_errno(_("could not write to '%s'"), done_path);
5343 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5345 todo_list->current = 0;
5346 todo_list->done_nr += i;
5348 if (is_fixup(peek_command(todo_list, 0)))
5349 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5355 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5356 const char *shortrevisions, const char *onto_name,
5357 struct commit *onto, const struct object_id *orig_head,
5358 struct string_list *commands, unsigned autosquash,
5359 struct todo_list *todo_list)
5361 char shortonto[GIT_MAX_HEXSZ + 1];
5362 const char *todo_file = rebase_path_todo();
5363 struct todo_list new_todo = TODO_LIST_INIT;
5364 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5365 struct object_id oid = onto->object.oid;
5368 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5370 if (buf->len == 0) {
5371 struct todo_item *item = append_new_todo(todo_list);
5372 item->command = TODO_NOOP;
5373 item->commit = NULL;
5374 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5377 if (autosquash && todo_list_rearrange_squash(todo_list))
5381 todo_list_add_exec_commands(todo_list, commands);
5383 if (count_commands(todo_list) == 0) {
5384 apply_autostash(rebase_path_autostash());
5385 sequencer_remove_state(opts);
5387 return error(_("nothing to do"));
5390 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5394 else if (res == -2) {
5395 apply_autostash(rebase_path_autostash());
5396 sequencer_remove_state(opts);
5399 } else if (res == -3) {
5400 apply_autostash(rebase_path_autostash());
5401 sequencer_remove_state(opts);
5402 todo_list_release(&new_todo);
5404 return error(_("nothing to do"));
5405 } else if (res == -4) {
5406 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5407 todo_list_release(&new_todo);
5412 /* Expand the commit IDs */
5413 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5414 strbuf_swap(&new_todo.buf, &buf2);
5415 strbuf_release(&buf2);
5416 new_todo.total_nr -= new_todo.nr;
5417 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5418 BUG("invalid todo list after expanding IDs:\n%s",
5421 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5422 todo_list_release(&new_todo);
5423 return error(_("could not skip unnecessary pick commands"));
5426 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5427 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5428 todo_list_release(&new_todo);
5429 return error_errno(_("could not write '%s'"), todo_file);
5434 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5437 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5440 todo_list_write_total_nr(&new_todo);
5441 res = pick_commits(r, &new_todo, opts);
5444 todo_list_release(&new_todo);
5449 struct subject2item_entry {
5450 struct hashmap_entry entry;
5452 char subject[FLEX_ARRAY];
5455 static int subject2item_cmp(const void *fndata,
5456 const struct hashmap_entry *eptr,
5457 const struct hashmap_entry *entry_or_key,
5460 const struct subject2item_entry *a, *b;
5462 a = container_of(eptr, const struct subject2item_entry, entry);
5463 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5465 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5468 define_commit_slab(commit_todo_item, struct todo_item *);
5471 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5472 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5473 * after the former, and change "pick" to "fixup"/"squash".
5475 * Note that if the config has specified a custom instruction format, each log
5476 * message will have to be retrieved from the commit (as the oneline in the
5477 * script cannot be trusted) in order to normalize the autosquash arrangement.
5479 int todo_list_rearrange_squash(struct todo_list *todo_list)
5481 struct hashmap subject2item;
5482 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5484 struct commit_todo_item commit_todo;
5485 struct todo_item *items = NULL;
5487 init_commit_todo_item(&commit_todo);
5489 * The hashmap maps onelines to the respective todo list index.
5491 * If any items need to be rearranged, the next[i] value will indicate
5492 * which item was moved directly after the i'th.
5494 * In that case, last[i] will indicate the index of the latest item to
5495 * be moved to appear after the i'th.
5497 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5498 ALLOC_ARRAY(next, todo_list->nr);
5499 ALLOC_ARRAY(tail, todo_list->nr);
5500 ALLOC_ARRAY(subjects, todo_list->nr);
5501 for (i = 0; i < todo_list->nr; i++) {
5502 struct strbuf buf = STRBUF_INIT;
5503 struct todo_item *item = todo_list->items + i;
5504 const char *commit_buffer, *subject, *p;
5507 struct subject2item_entry *entry;
5509 next[i] = tail[i] = -1;
5510 if (!item->commit || item->command == TODO_DROP) {
5515 if (is_fixup(item->command)) {
5516 clear_commit_todo_item(&commit_todo);
5517 return error(_("the script was already rearranged."));
5520 *commit_todo_item_at(&commit_todo, item->commit) = item;
5522 parse_commit(item->commit);
5523 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5524 find_commit_subject(commit_buffer, &subject);
5525 format_subject(&buf, subject, " ");
5526 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5527 unuse_commit_buffer(item->commit, commit_buffer);
5528 if ((skip_prefix(subject, "fixup! ", &p) ||
5529 skip_prefix(subject, "squash! ", &p))) {
5530 struct commit *commit2;
5535 if (!skip_prefix(p, "fixup! ", &p) &&
5536 !skip_prefix(p, "squash! ", &p))
5540 entry = hashmap_get_entry_from_hash(&subject2item,
5542 struct subject2item_entry,
5545 /* found by title */
5547 else if (!strchr(p, ' ') &&
5549 lookup_commit_reference_by_name(p)) &&
5550 *commit_todo_item_at(&commit_todo, commit2))
5551 /* found by commit name */
5552 i2 = *commit_todo_item_at(&commit_todo, commit2)
5555 /* copy can be a prefix of the commit subject */
5556 for (i2 = 0; i2 < i; i2++)
5558 starts_with(subjects[i2], p))
5566 todo_list->items[i].command =
5567 starts_with(subject, "fixup!") ?
5568 TODO_FIXUP : TODO_SQUASH;
5573 next[i] = next[tail[i2]];
5577 } else if (!hashmap_get_from_hash(&subject2item,
5578 strhash(subject), subject)) {
5579 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5581 hashmap_entry_init(&entry->entry,
5582 strhash(entry->subject));
5583 hashmap_put(&subject2item, &entry->entry);
5588 for (i = 0; i < todo_list->nr; i++) {
5589 enum todo_command command = todo_list->items[i].command;
5593 * Initially, all commands are 'pick's. If it is a
5594 * fixup or a squash now, we have rearranged it.
5596 if (is_fixup(command))
5600 ALLOC_GROW(items, nr + 1, alloc);
5601 items[nr++] = todo_list->items[cur];
5606 FREE_AND_NULL(todo_list->items);
5607 todo_list->items = items;
5609 todo_list->alloc = alloc;
5614 for (i = 0; i < todo_list->nr; i++)
5617 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5619 clear_commit_todo_item(&commit_todo);
5624 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5626 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5627 struct object_id cherry_pick_head, rebase_head;
5629 if (file_exists(git_path_seq_dir()))
5630 *whence = FROM_CHERRY_PICK_MULTI;
5631 if (file_exists(rebase_path()) &&
5632 !get_oid("REBASE_HEAD", &rebase_head) &&
5633 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5634 oideq(&rebase_head, &cherry_pick_head))
5635 *whence = FROM_REBASE_PICK;
5637 *whence = FROM_CHERRY_PICK_SINGLE;