5 #include "object-store.h"
10 #include "run-command.h"
14 #include "cache-tree.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
25 #include "wt-status.h"
27 #include "notes-utils.h"
29 #include "unpack-trees.h"
33 #include "commit-slab.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
38 #include "string-list.h"
40 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
42 static const char sign_off_header[] = "Signed-off-by: ";
43 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
45 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
47 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
49 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
50 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
51 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
52 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
54 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
56 * The file containing rebase commands, comments, and empty lines.
57 * This file is created by "git rebase -i" then edited by the user. As
58 * the lines are processed, they are removed from the front of this
59 * file and written to the tail of 'done'.
61 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
62 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
64 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
67 * The rebase command lines that have already been processed. A line
68 * is moved here when it is first handled, before any associated user
71 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
73 * The file to keep track of how many commands were already processed (e.g.
76 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
78 * The file to keep track of how many commands are to be processed in total
79 * (e.g. for the prompt).
81 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
83 * The commit message that is planned to be used for any changes that
84 * need to be committed following a user interaction.
86 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
88 * The file into which is accumulated the suggested commit message for
89 * squash/fixup commands. When the first of a series of squash/fixups
90 * is seen, the file is created and the commit message from the
91 * previous commit and from the first squash/fixup commit are written
92 * to it. The commit message for each subsequent squash/fixup commit
93 * is appended to the file as it is processed.
95 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
97 * If the current series of squash/fixups has not yet included a squash
98 * command, then this file exists and holds the commit message of the
99 * original "pick" commit. (If the series ends without a "squash"
100 * command, then this can be used as the commit message of the combined
101 * commit without opening the editor.)
103 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
105 * This file contains the list fixup/squash commands that have been
106 * accumulated into message-fixup or message-squash so far.
108 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
110 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
111 * GIT_AUTHOR_DATE that will be used for the commit that is currently
114 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
116 * When an "edit" rebase command is being processed, the SHA1 of the
117 * commit to be edited is recorded in this file. When "git rebase
118 * --continue" is executed, if there are any staged changes then they
119 * will be amended to the HEAD commit, but only provided the HEAD
120 * commit is still the commit to be edited. When any other rebase
121 * command is processed, this file is deleted.
123 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
125 * When we stop at a given patch via the "edit" command, this file contains
126 * the commit object name of the corresponding patch.
128 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
130 * For the post-rewrite hook, we make a list of rewritten commits and
131 * their new sha1s. The rewritten-pending list keeps the sha1s of
132 * commits that have been processed, but not committed yet,
133 * e.g. because they are waiting for a 'squash' command.
135 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
136 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
137 "rebase-merge/rewritten-pending")
140 * The path of the file containing the OID of the "squash onto" commit, i.e.
141 * the dummy commit used for `reset [new root]`.
143 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
146 * The path of the file listing refs that need to be deleted after the rebase
147 * finishes. This is used by the `label` command to record the need for cleanup.
149 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
152 * The following files are written by git-rebase just after parsing the
155 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
156 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
157 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
158 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
159 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
160 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
161 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
162 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
163 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
164 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
165 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
166 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
167 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
168 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
169 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
170 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
171 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
173 static int git_sequencer_config(const char *k, const char *v, void *cb)
175 struct replay_opts *opts = cb;
178 if (!strcmp(k, "commit.cleanup")) {
181 status = git_config_string(&s, k, v);
185 if (!strcmp(s, "verbatim")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
187 opts->explicit_cleanup = 1;
188 } else if (!strcmp(s, "whitespace")) {
189 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
190 opts->explicit_cleanup = 1;
191 } else if (!strcmp(s, "strip")) {
192 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
193 opts->explicit_cleanup = 1;
194 } else if (!strcmp(s, "scissors")) {
195 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
196 opts->explicit_cleanup = 1;
198 warning(_("invalid commit message cleanup mode '%s'"),
206 if (!strcmp(k, "commit.gpgsign")) {
207 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
211 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
212 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
215 * pull.twohead is allowed to be multi-valued; we only
216 * care about the first value.
218 char *tmp = strchr(opts->default_strategy, ' ');
225 status = git_gpg_config(k, v, NULL);
229 return git_diff_basic_config(k, v, NULL);
232 void sequencer_init_config(struct replay_opts *opts)
234 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
235 git_config(git_sequencer_config, opts);
238 static inline int is_rebase_i(const struct replay_opts *opts)
240 return opts->action == REPLAY_INTERACTIVE_REBASE;
243 static const char *get_dir(const struct replay_opts *opts)
245 if (is_rebase_i(opts))
246 return rebase_path();
247 return git_path_seq_dir();
250 static const char *get_todo_path(const struct replay_opts *opts)
252 if (is_rebase_i(opts))
253 return rebase_path_todo();
254 return git_path_todo_file();
258 * Returns 0 for non-conforming footer
259 * Returns 1 for conforming footer
260 * Returns 2 when sob exists within conforming footer
261 * Returns 3 when sob exists within conforming footer as last entry
263 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
264 size_t ignore_footer)
266 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
267 struct trailer_info info;
269 int found_sob = 0, found_sob_last = 0;
275 saved_char = sb->buf[sb->len - ignore_footer];
276 sb->buf[sb->len - ignore_footer] = '\0';
279 trailer_info_get(&info, sb->buf, &opts);
282 sb->buf[sb->len - ignore_footer] = saved_char;
284 if (info.trailer_start == info.trailer_end)
287 for (i = 0; i < info.trailer_nr; i++)
288 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
290 if (i == info.trailer_nr - 1)
294 trailer_info_release(&info);
303 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
305 static struct strbuf buf = STRBUF_INIT;
309 sq_quotef(&buf, "-S%s", opts->gpg_sign);
313 int sequencer_remove_state(struct replay_opts *opts)
315 struct strbuf buf = STRBUF_INIT;
318 if (is_rebase_i(opts) &&
319 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
322 char *eol = strchr(p, '\n');
325 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
326 warning(_("could not delete '%s'"), p);
335 free(opts->gpg_sign);
336 free(opts->default_strategy);
337 free(opts->strategy);
338 for (i = 0; i < opts->xopts_nr; i++)
339 free(opts->xopts[i]);
341 strbuf_release(&opts->current_fixups);
344 strbuf_addstr(&buf, get_dir(opts));
345 if (remove_dir_recursively(&buf, 0))
346 ret = error(_("could not remove '%s'"), buf.buf);
347 strbuf_release(&buf);
352 static const char *action_name(const struct replay_opts *opts)
354 switch (opts->action) {
358 return N_("cherry-pick");
359 case REPLAY_INTERACTIVE_REBASE:
362 die(_("unknown action: %d"), opts->action);
365 struct commit_message {
372 static const char *short_commit_name(struct commit *commit)
374 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
377 static int get_message(struct commit *commit, struct commit_message *out)
379 const char *abbrev, *subject;
382 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
383 abbrev = short_commit_name(commit);
385 subject_len = find_commit_subject(out->message, &subject);
387 out->subject = xmemdupz(subject, subject_len);
388 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
389 out->parent_label = xstrfmt("parent of %s", out->label);
394 static void free_message(struct commit *commit, struct commit_message *msg)
396 free(msg->parent_label);
399 unuse_commit_buffer(commit, msg->message);
402 static void print_advice(struct repository *r, int show_hint,
403 struct replay_opts *opts)
405 char *msg = getenv("GIT_CHERRY_PICK_HELP");
408 fprintf(stderr, "%s\n", msg);
410 * A conflict has occurred but the porcelain
411 * (typically rebase --interactive) wants to take care
412 * of the commit itself so remove CHERRY_PICK_HEAD
414 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
421 advise(_("after resolving the conflicts, mark the corrected paths\n"
422 "with 'git add <paths>' or 'git rm <paths>'"));
424 advise(_("after resolving the conflicts, mark the corrected paths\n"
425 "with 'git add <paths>' or 'git rm <paths>'\n"
426 "and commit the result with 'git commit'"));
430 static int write_message(const void *buf, size_t len, const char *filename,
433 struct lock_file msg_file = LOCK_INIT;
435 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
437 return error_errno(_("could not lock '%s'"), filename);
438 if (write_in_full(msg_fd, buf, len) < 0) {
439 error_errno(_("could not write to '%s'"), filename);
440 rollback_lock_file(&msg_file);
443 if (append_eol && write(msg_fd, "\n", 1) < 0) {
444 error_errno(_("could not write eol to '%s'"), filename);
445 rollback_lock_file(&msg_file);
448 if (commit_lock_file(&msg_file) < 0)
449 return error(_("failed to finalize '%s'"), filename);
454 int read_oneliner(struct strbuf *buf,
455 const char *path, unsigned flags)
457 int orig_len = buf->len;
459 if (strbuf_read_file(buf, path, 0) < 0) {
460 if ((flags & READ_ONELINER_WARN_MISSING) ||
461 (errno != ENOENT && errno != ENOTDIR))
462 warning_errno(_("could not read '%s'"), path);
466 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
467 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
469 buf->buf[buf->len] = '\0';
472 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
478 static struct tree *empty_tree(struct repository *r)
480 return lookup_tree(r, the_hash_algo->empty_tree);
483 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
485 if (repo_read_index_unmerged(repo))
486 return error_resolve_conflict(_(action_name(opts)));
488 error(_("your local changes would be overwritten by %s."),
489 _(action_name(opts)));
491 if (advice_commit_before_merge)
492 advise(_("commit your changes or stash them to proceed."));
496 static void update_abort_safety_file(void)
498 struct object_id head;
500 /* Do nothing on a single-pick */
501 if (!file_exists(git_path_seq_dir()))
504 if (!get_oid("HEAD", &head))
505 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
507 write_file(git_path_abort_safety_file(), "%s", "");
510 static int fast_forward_to(struct repository *r,
511 const struct object_id *to,
512 const struct object_id *from,
514 struct replay_opts *opts)
516 struct ref_transaction *transaction;
517 struct strbuf sb = STRBUF_INIT;
518 struct strbuf err = STRBUF_INIT;
521 if (checkout_fast_forward(r, from, to, 1))
522 return -1; /* the callee should have complained already */
524 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
526 transaction = ref_transaction_begin(&err);
528 ref_transaction_update(transaction, "HEAD",
529 to, unborn && !is_rebase_i(opts) ?
532 ref_transaction_commit(transaction, &err)) {
533 ref_transaction_free(transaction);
534 error("%s", err.buf);
536 strbuf_release(&err);
541 strbuf_release(&err);
542 ref_transaction_free(transaction);
543 update_abort_safety_file();
547 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
550 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
551 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
552 COMMIT_MSG_CLEANUP_SPACE;
553 else if (!strcmp(cleanup_arg, "verbatim"))
554 return COMMIT_MSG_CLEANUP_NONE;
555 else if (!strcmp(cleanup_arg, "whitespace"))
556 return COMMIT_MSG_CLEANUP_SPACE;
557 else if (!strcmp(cleanup_arg, "strip"))
558 return COMMIT_MSG_CLEANUP_ALL;
559 else if (!strcmp(cleanup_arg, "scissors"))
560 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
561 COMMIT_MSG_CLEANUP_SPACE;
563 die(_("Invalid cleanup mode %s"), cleanup_arg);
567 * NB using int rather than enum cleanup_mode to stop clang's
568 * -Wtautological-constant-out-of-range-compare complaining that the comparison
571 static const char *describe_cleanup_mode(int cleanup_mode)
573 static const char *modes[] = { "whitespace",
578 if (cleanup_mode < ARRAY_SIZE(modes))
579 return modes[cleanup_mode];
581 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
584 void append_conflicts_hint(struct index_state *istate,
585 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
589 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
590 strbuf_addch(msgbuf, '\n');
591 wt_status_append_cut_line(msgbuf);
592 strbuf_addch(msgbuf, comment_line_char);
595 strbuf_addch(msgbuf, '\n');
596 strbuf_commented_addf(msgbuf, "Conflicts:\n");
597 for (i = 0; i < istate->cache_nr;) {
598 const struct cache_entry *ce = istate->cache[i++];
600 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
601 while (i < istate->cache_nr &&
602 !strcmp(ce->name, istate->cache[i]->name))
608 static int do_recursive_merge(struct repository *r,
609 struct commit *base, struct commit *next,
610 const char *base_label, const char *next_label,
611 struct object_id *head, struct strbuf *msgbuf,
612 struct replay_opts *opts)
614 struct merge_options o;
615 struct merge_result result;
616 struct tree *next_tree, *base_tree, *head_tree;
617 int clean, show_output;
619 struct lock_file index_lock = LOCK_INIT;
621 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
626 init_merge_options(&o, r);
627 o.ancestor = base ? base_label : "(empty tree)";
629 o.branch2 = next ? next_label : "(empty tree)";
630 if (is_rebase_i(opts))
632 o.show_rename_progress = 1;
634 head_tree = parse_tree_indirect(head);
635 next_tree = next ? get_commit_tree(next) : empty_tree(r);
636 base_tree = base ? get_commit_tree(base) : empty_tree(r);
638 for (i = 0; i < opts->xopts_nr; i++)
639 parse_merge_opt(&o, opts->xopts[i]);
641 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
642 memset(&result, 0, sizeof(result));
643 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
645 show_output = !is_rebase_i(opts) || !result.clean;
647 * TODO: merge_switch_to_result will update index/working tree;
648 * we only really want to do that if !result.clean || this is
649 * the final patch to be picked. But determining this is the
650 * final patch would take some work, and "head_tree" would need
651 * to be replace with the tree the index matched before we
652 * started doing any picks.
654 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
655 clean = result.clean;
657 clean = merge_trees(&o, head_tree, next_tree, base_tree);
658 if (is_rebase_i(opts) && clean <= 0)
659 fputs(o.obuf.buf, stdout);
660 strbuf_release(&o.obuf);
663 rollback_lock_file(&index_lock);
667 if (write_locked_index(r->index, &index_lock,
668 COMMIT_LOCK | SKIP_IF_UNCHANGED))
670 * TRANSLATORS: %s will be "revert", "cherry-pick" or
673 return error(_("%s: Unable to write new index file"),
674 _(action_name(opts)));
677 append_conflicts_hint(r->index, msgbuf,
678 opts->default_msg_cleanup);
683 static struct object_id *get_cache_tree_oid(struct index_state *istate)
685 if (!cache_tree_fully_valid(istate->cache_tree))
686 if (cache_tree_update(istate, 0)) {
687 error(_("unable to update cache tree"));
691 return &istate->cache_tree->oid;
694 static int is_index_unchanged(struct repository *r)
696 struct object_id head_oid, *cache_tree_oid;
697 struct commit *head_commit;
698 struct index_state *istate = r->index;
700 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
701 return error(_("could not resolve HEAD commit"));
703 head_commit = lookup_commit(r, &head_oid);
706 * If head_commit is NULL, check_commit, called from
707 * lookup_commit, would have indicated that head_commit is not
708 * a commit object already. parse_commit() will return failure
709 * without further complaints in such a case. Otherwise, if
710 * the commit is invalid, parse_commit() will complain. So
711 * there is nothing for us to say here. Just return failure.
713 if (parse_commit(head_commit))
716 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
719 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
722 static int write_author_script(const char *message)
724 struct strbuf buf = STRBUF_INIT;
729 if (!*message || starts_with(message, "\n")) {
731 /* Missing 'author' line? */
732 unlink(rebase_path_author_script());
734 } else if (skip_prefix(message, "author ", &message))
736 else if ((eol = strchr(message, '\n')))
741 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
742 while (*message && *message != '\n' && *message != '\r')
743 if (skip_prefix(message, " <", &message))
745 else if (*message != '\'')
746 strbuf_addch(&buf, *(message++));
748 strbuf_addf(&buf, "'\\%c'", *(message++));
749 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
750 while (*message && *message != '\n' && *message != '\r')
751 if (skip_prefix(message, "> ", &message))
753 else if (*message != '\'')
754 strbuf_addch(&buf, *(message++));
756 strbuf_addf(&buf, "'\\%c'", *(message++));
757 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
758 while (*message && *message != '\n' && *message != '\r')
759 if (*message != '\'')
760 strbuf_addch(&buf, *(message++));
762 strbuf_addf(&buf, "'\\%c'", *(message++));
763 strbuf_addch(&buf, '\'');
764 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
765 strbuf_release(&buf);
770 * Take a series of KEY='VALUE' lines where VALUE part is
771 * sq-quoted, and append <KEY, VALUE> at the end of the string list
773 static int parse_key_value_squoted(char *buf, struct string_list *list)
776 struct string_list_item *item;
778 char *cp = strchr(buf, '=');
780 np = strchrnul(buf, '\n');
781 return error(_("no key present in '%.*s'"),
782 (int) (np - buf), buf);
784 np = strchrnul(cp, '\n');
786 item = string_list_append(list, buf);
788 buf = np + (*np == '\n');
792 return error(_("unable to dequote value of '%s'"),
794 item->util = xstrdup(cp);
800 * Reads and parses the state directory's "author-script" file, and sets name,
801 * email and date accordingly.
802 * Returns 0 on success, -1 if the file could not be parsed.
804 * The author script is of the format:
806 * GIT_AUTHOR_NAME='$author_name'
807 * GIT_AUTHOR_EMAIL='$author_email'
808 * GIT_AUTHOR_DATE='$author_date'
810 * where $author_name, $author_email and $author_date are quoted. We are strict
811 * with our parsing, as the file was meant to be eval'd in the now-removed
812 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
813 * from what this function expects, it is better to bail out than to do
814 * something that the user does not expect.
816 int read_author_script(const char *path, char **name, char **email, char **date,
819 struct strbuf buf = STRBUF_INIT;
820 struct string_list kv = STRING_LIST_INIT_DUP;
821 int retval = -1; /* assume failure */
822 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
824 if (strbuf_read_file(&buf, path, 256) <= 0) {
825 strbuf_release(&buf);
826 if (errno == ENOENT && allow_missing)
829 return error_errno(_("could not open '%s' for reading"),
833 if (parse_key_value_squoted(buf.buf, &kv))
836 for (i = 0; i < kv.nr; i++) {
837 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
839 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
842 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
844 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
847 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
849 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
853 err = error(_("unknown variable '%s'"),
858 error(_("missing 'GIT_AUTHOR_NAME'"));
860 error(_("missing 'GIT_AUTHOR_EMAIL'"));
862 error(_("missing 'GIT_AUTHOR_DATE'"));
863 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
865 *name = kv.items[name_i].util;
866 *email = kv.items[email_i].util;
867 *date = kv.items[date_i].util;
870 string_list_clear(&kv, !!retval);
871 strbuf_release(&buf);
876 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
877 * file with shell quoting into struct strvec. Returns -1 on
878 * error, 0 otherwise.
880 static int read_env_script(struct strvec *env)
882 char *name, *email, *date;
884 if (read_author_script(rebase_path_author_script(),
885 &name, &email, &date, 0))
888 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
889 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
890 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
898 static char *get_author(const char *message)
903 a = find_commit_header(message, "author", &len);
905 return xmemdupz(a, len);
910 static const char *author_date_from_env_array(const struct strvec *env)
915 for (i = 0; i < env->nr; i++)
916 if (skip_prefix(env->v[i],
917 "GIT_AUTHOR_DATE=", &date))
920 * If GIT_AUTHOR_DATE is missing we should have already errored out when
923 BUG("GIT_AUTHOR_DATE missing from author script");
926 static const char staged_changes_advice[] =
927 N_("you have staged changes in your working tree\n"
928 "If these changes are meant to be squashed into the previous commit, run:\n"
930 " git commit --amend %s\n"
932 "If they are meant to go into a new commit, run:\n"
936 "In both cases, once you're done, continue with:\n"
938 " git rebase --continue\n");
940 #define ALLOW_EMPTY (1<<0)
941 #define EDIT_MSG (1<<1)
942 #define AMEND_MSG (1<<2)
943 #define CLEANUP_MSG (1<<3)
944 #define VERIFY_MSG (1<<4)
945 #define CREATE_ROOT_COMMIT (1<<5)
946 #define VERBATIM_MSG (1<<6)
948 static int run_command_silent_on_success(struct child_process *cmd)
950 struct strbuf buf = STRBUF_INIT;
953 cmd->stdout_to_stderr = 1;
954 rc = pipe_command(cmd,
960 fputs(buf.buf, stderr);
961 strbuf_release(&buf);
966 * If we are cherry-pick, and if the merge did not result in
967 * hand-editing, we will hit this commit and inherit the original
968 * author date and name.
970 * If we are revert, or if our cherry-pick results in a hand merge,
971 * we had better say that the current user is responsible for that.
973 * An exception is when run_git_commit() is called during an
974 * interactive rebase: in that case, we will want to retain the
977 static int run_git_commit(const char *defmsg,
978 struct replay_opts *opts,
981 struct child_process cmd = CHILD_PROCESS_INIT;
983 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
984 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
988 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
989 const char *gpg_opt = gpg_sign_opt_quoted(opts);
991 return error(_(staged_changes_advice),
995 if (opts->committer_date_is_author_date)
996 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
999 author_date_from_env_array(&cmd.env_array));
1000 if (opts->ignore_date)
1001 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1003 strvec_push(&cmd.args, "commit");
1005 if (!(flags & VERIFY_MSG))
1006 strvec_push(&cmd.args, "-n");
1007 if ((flags & AMEND_MSG))
1008 strvec_push(&cmd.args, "--amend");
1010 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1012 strvec_push(&cmd.args, "--no-gpg-sign");
1014 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1015 else if (!(flags & EDIT_MSG))
1016 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1017 if ((flags & CLEANUP_MSG))
1018 strvec_push(&cmd.args, "--cleanup=strip");
1019 if ((flags & VERBATIM_MSG))
1020 strvec_push(&cmd.args, "--cleanup=verbatim");
1021 if ((flags & EDIT_MSG))
1022 strvec_push(&cmd.args, "-e");
1023 else if (!(flags & CLEANUP_MSG) &&
1024 !opts->signoff && !opts->record_origin &&
1025 !opts->explicit_cleanup)
1026 strvec_push(&cmd.args, "--cleanup=verbatim");
1028 if ((flags & ALLOW_EMPTY))
1029 strvec_push(&cmd.args, "--allow-empty");
1031 if (!(flags & EDIT_MSG))
1032 strvec_push(&cmd.args, "--allow-empty-message");
1034 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1035 return run_command_silent_on_success(&cmd);
1037 return run_command(&cmd);
1040 static int rest_is_empty(const struct strbuf *sb, int start)
1045 /* Check if the rest is just whitespace and Signed-off-by's. */
1046 for (i = start; i < sb->len; i++) {
1047 nl = memchr(sb->buf + i, '\n', sb->len - i);
1053 if (strlen(sign_off_header) <= eol - i &&
1054 starts_with(sb->buf + i, sign_off_header)) {
1059 if (!isspace(sb->buf[i++]))
1066 void cleanup_message(struct strbuf *msgbuf,
1067 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1069 if (verbose || /* Truncate the message just before the diff, if any. */
1070 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1071 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1072 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1073 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1077 * Find out if the message in the strbuf contains only whitespace and
1078 * Signed-off-by lines.
1080 int message_is_empty(const struct strbuf *sb,
1081 enum commit_msg_cleanup_mode cleanup_mode)
1083 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1085 return rest_is_empty(sb, 0);
1089 * See if the user edited the message in the editor or left what
1090 * was in the template intact
1092 int template_untouched(const struct strbuf *sb, const char *template_file,
1093 enum commit_msg_cleanup_mode cleanup_mode)
1095 struct strbuf tmpl = STRBUF_INIT;
1098 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1101 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1104 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1105 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1107 strbuf_release(&tmpl);
1108 return rest_is_empty(sb, start - sb->buf);
1111 int update_head_with_reflog(const struct commit *old_head,
1112 const struct object_id *new_head,
1113 const char *action, const struct strbuf *msg,
1116 struct ref_transaction *transaction;
1117 struct strbuf sb = STRBUF_INIT;
1122 strbuf_addstr(&sb, action);
1123 strbuf_addstr(&sb, ": ");
1126 nl = strchr(msg->buf, '\n');
1128 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1130 strbuf_addbuf(&sb, msg);
1131 strbuf_addch(&sb, '\n');
1134 transaction = ref_transaction_begin(err);
1136 ref_transaction_update(transaction, "HEAD", new_head,
1137 old_head ? &old_head->object.oid : null_oid(),
1139 ref_transaction_commit(transaction, err)) {
1142 ref_transaction_free(transaction);
1143 strbuf_release(&sb);
1148 static int run_rewrite_hook(const struct object_id *oldoid,
1149 const struct object_id *newoid)
1151 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1152 struct strbuf tmp = STRBUF_INIT;
1153 struct string_list to_stdin = STRING_LIST_INIT_DUP;
1156 strvec_push(&opt.args, "amend");
1161 oid_to_hex(newoid));
1162 string_list_append(&to_stdin, tmp.buf);
1164 opt.feed_pipe = pipe_from_string_list;
1165 opt.feed_pipe_ctx = &to_stdin;
1167 code = run_hooks("post-rewrite", &opt);
1169 run_hooks_opt_clear(&opt);
1170 strbuf_release(&tmp);
1171 string_list_clear(&to_stdin, 0);
1175 void commit_post_rewrite(struct repository *r,
1176 const struct commit *old_head,
1177 const struct object_id *new_head)
1179 struct notes_rewrite_cfg *cfg;
1181 cfg = init_copy_notes_for_rewrite("amend");
1183 /* we are amending, so old_head is not NULL */
1184 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1185 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1187 run_rewrite_hook(&old_head->object.oid, new_head);
1190 static int run_prepare_commit_msg_hook(struct repository *r,
1195 const char *name, *arg1 = NULL, *arg2 = NULL;
1197 name = git_path_commit_editmsg();
1198 if (write_message(msg->buf, msg->len, name, 0))
1207 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1209 ret = error(_("'prepare-commit-msg' hook failed"));
1214 static const char implicit_ident_advice_noconfig[] =
1215 N_("Your name and email address were configured automatically based\n"
1216 "on your username and hostname. Please check that they are accurate.\n"
1217 "You can suppress this message by setting them explicitly. Run the\n"
1218 "following command and follow the instructions in your editor to edit\n"
1219 "your configuration file:\n"
1221 " git config --global --edit\n"
1223 "After doing this, you may fix the identity used for this commit with:\n"
1225 " git commit --amend --reset-author\n");
1227 static const char implicit_ident_advice_config[] =
1228 N_("Your name and email address were configured automatically based\n"
1229 "on your username and hostname. Please check that they are accurate.\n"
1230 "You can suppress this message by setting them explicitly:\n"
1232 " git config --global user.name \"Your Name\"\n"
1233 " git config --global user.email you@example.com\n"
1235 "After doing this, you may fix the identity used for this commit with:\n"
1237 " git commit --amend --reset-author\n");
1239 static const char *implicit_ident_advice(void)
1241 char *user_config = expand_user_path("~/.gitconfig", 0);
1242 char *xdg_config = xdg_config_home("config");
1243 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1249 return _(implicit_ident_advice_config);
1251 return _(implicit_ident_advice_noconfig);
1255 void print_commit_summary(struct repository *r,
1257 const struct object_id *oid,
1260 struct rev_info rev;
1261 struct commit *commit;
1262 struct strbuf format = STRBUF_INIT;
1264 struct pretty_print_context pctx = {0};
1265 struct strbuf author_ident = STRBUF_INIT;
1266 struct strbuf committer_ident = STRBUF_INIT;
1268 commit = lookup_commit(r, oid);
1270 die(_("couldn't look up newly created commit"));
1271 if (parse_commit(commit))
1272 die(_("could not parse newly created commit"));
1274 strbuf_addstr(&format, "format:%h] %s");
1276 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1277 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1278 if (strbuf_cmp(&author_ident, &committer_ident)) {
1279 strbuf_addstr(&format, "\n Author: ");
1280 strbuf_addbuf_percentquote(&format, &author_ident);
1282 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1283 struct strbuf date = STRBUF_INIT;
1285 format_commit_message(commit, "%ad", &date, &pctx);
1286 strbuf_addstr(&format, "\n Date: ");
1287 strbuf_addbuf_percentquote(&format, &date);
1288 strbuf_release(&date);
1290 if (!committer_ident_sufficiently_given()) {
1291 strbuf_addstr(&format, "\n Committer: ");
1292 strbuf_addbuf_percentquote(&format, &committer_ident);
1293 if (advice_implicit_identity) {
1294 strbuf_addch(&format, '\n');
1295 strbuf_addstr(&format, implicit_ident_advice());
1298 strbuf_release(&author_ident);
1299 strbuf_release(&committer_ident);
1301 repo_init_revisions(r, &rev, prefix);
1302 setup_revisions(0, NULL, &rev, NULL);
1305 rev.diffopt.output_format =
1306 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1308 rev.verbose_header = 1;
1309 rev.show_root_diff = 1;
1310 get_commit_format(format.buf, &rev);
1311 rev.always_show_header = 0;
1312 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1313 rev.diffopt.break_opt = 0;
1314 diff_setup_done(&rev.diffopt);
1316 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1318 die_errno(_("unable to resolve HEAD after creating commit"));
1319 if (!strcmp(head, "HEAD"))
1320 head = _("detached HEAD");
1322 skip_prefix(head, "refs/heads/", &head);
1323 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1324 _(" (root-commit)") : "");
1326 if (!log_tree_commit(&rev, commit)) {
1327 rev.always_show_header = 1;
1328 rev.use_terminator = 1;
1329 log_tree_commit(&rev, commit);
1332 strbuf_release(&format);
1335 static int parse_head(struct repository *r, struct commit **head)
1337 struct commit *current_head;
1338 struct object_id oid;
1340 if (get_oid("HEAD", &oid)) {
1341 current_head = NULL;
1343 current_head = lookup_commit_reference(r, &oid);
1345 return error(_("could not parse HEAD"));
1346 if (!oideq(&oid, ¤t_head->object.oid)) {
1347 warning(_("HEAD %s is not a commit!"),
1350 if (parse_commit(current_head))
1351 return error(_("could not parse HEAD commit"));
1353 *head = current_head;
1359 * Try to commit without forking 'git commit'. In some cases we need
1360 * to run 'git commit' to display an error message
1363 * -1 - error unable to commit
1365 * 1 - run 'git commit'
1367 static int try_to_commit(struct repository *r,
1368 struct strbuf *msg, const char *author,
1369 struct replay_opts *opts, unsigned int flags,
1370 struct object_id *oid)
1372 struct object_id tree;
1373 struct commit *current_head = NULL;
1374 struct commit_list *parents = NULL;
1375 struct commit_extra_header *extra = NULL;
1376 struct strbuf err = STRBUF_INIT;
1377 struct strbuf commit_msg = STRBUF_INIT;
1378 char *amend_author = NULL;
1379 const char *committer = NULL;
1380 const char *hook_commit = NULL;
1381 enum commit_msg_cleanup_mode cleanup;
1384 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1385 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1387 if (parse_head(r, ¤t_head))
1390 if (flags & AMEND_MSG) {
1391 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1392 const char *out_enc = get_commit_output_encoding();
1393 const char *message = logmsg_reencode(current_head, NULL,
1397 const char *orig_message = NULL;
1399 find_commit_subject(message, &orig_message);
1401 strbuf_addstr(msg, orig_message);
1402 hook_commit = "HEAD";
1404 author = amend_author = get_author(message);
1405 unuse_commit_buffer(current_head, message);
1407 res = error(_("unable to parse commit author"));
1410 parents = copy_commit_list(current_head->parents);
1411 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1412 } else if (current_head &&
1413 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1414 commit_list_insert(current_head, &parents);
1417 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1418 res = error(_("git write-tree failed to write a tree"));
1422 if (!(flags & ALLOW_EMPTY)) {
1423 struct commit *first_parent = current_head;
1425 if (flags & AMEND_MSG) {
1426 if (current_head->parents) {
1427 first_parent = current_head->parents->item;
1428 if (repo_parse_commit(r, first_parent)) {
1429 res = error(_("could not parse HEAD commit"));
1433 first_parent = NULL;
1436 if (oideq(first_parent
1437 ? get_commit_tree_oid(first_parent)
1438 : the_hash_algo->empty_tree,
1440 res = 1; /* run 'git commit' to display error message */
1445 if (hook_exists("prepare-commit-msg")) {
1446 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1449 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1451 res = error_errno(_("unable to read commit message "
1453 git_path_commit_editmsg());
1459 if (flags & CLEANUP_MSG)
1460 cleanup = COMMIT_MSG_CLEANUP_ALL;
1461 else if (flags & VERBATIM_MSG)
1462 cleanup = COMMIT_MSG_CLEANUP_NONE;
1463 else if ((opts->signoff || opts->record_origin) &&
1464 !opts->explicit_cleanup)
1465 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1467 cleanup = opts->default_msg_cleanup;
1469 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1470 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1471 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1472 res = 1; /* run 'git commit' to display error message */
1476 if (opts->committer_date_is_author_date) {
1477 struct ident_split id;
1478 struct strbuf date = STRBUF_INIT;
1480 if (!opts->ignore_date) {
1481 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1482 res = error(_("invalid author identity '%s'"),
1486 if (!id.date_begin) {
1488 "corrupt author: missing date information"));
1491 strbuf_addf(&date, "@%.*s %.*s",
1492 (int)(id.date_end - id.date_begin),
1494 (int)(id.tz_end - id.tz_begin),
1499 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1500 getenv("GIT_COMMITTER_EMAIL"),
1501 WANT_COMMITTER_IDENT,
1502 opts->ignore_date ? NULL : date.buf,
1504 strbuf_release(&date);
1509 if (opts->ignore_date) {
1510 struct ident_split id;
1513 if (split_ident_line(&id, author, strlen(author)) < 0) {
1514 error(_("invalid author identity '%s'"), author);
1517 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1518 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1519 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1525 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1526 author, committer, opts->gpg_sign, extra)) {
1527 res = error(_("failed to write commit object"));
1531 if (update_head_with_reflog(current_head, oid,
1532 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1533 res = error("%s", err.buf);
1537 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1538 if (flags & AMEND_MSG)
1539 commit_post_rewrite(r, current_head, oid);
1542 free_commit_extra_headers(extra);
1543 strbuf_release(&err);
1544 strbuf_release(&commit_msg);
1550 static int write_rebase_head(struct object_id *oid)
1552 if (update_ref("rebase", "REBASE_HEAD", oid,
1553 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1554 return error(_("could not update %s"), "REBASE_HEAD");
1559 static int do_commit(struct repository *r,
1560 const char *msg_file, const char *author,
1561 struct replay_opts *opts, unsigned int flags,
1562 struct object_id *oid)
1566 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1567 struct object_id oid;
1568 struct strbuf sb = STRBUF_INIT;
1570 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1571 return error_errno(_("unable to read commit message "
1575 res = try_to_commit(r, msg_file ? &sb : NULL,
1576 author, opts, flags, &oid);
1577 strbuf_release(&sb);
1579 refs_delete_ref(get_main_ref_store(r), "",
1580 "CHERRY_PICK_HEAD", NULL, 0);
1581 unlink(git_path_merge_msg(r));
1582 if (!is_rebase_i(opts))
1583 print_commit_summary(r, NULL, &oid,
1584 SUMMARY_SHOW_AUTHOR_DATE);
1589 if (is_rebase_i(opts) && oid)
1590 if (write_rebase_head(oid))
1592 return run_git_commit(msg_file, opts, flags);
1598 static int is_original_commit_empty(struct commit *commit)
1600 const struct object_id *ptree_oid;
1602 if (parse_commit(commit))
1603 return error(_("could not parse commit %s"),
1604 oid_to_hex(&commit->object.oid));
1605 if (commit->parents) {
1606 struct commit *parent = commit->parents->item;
1607 if (parse_commit(parent))
1608 return error(_("could not parse parent commit %s"),
1609 oid_to_hex(&parent->object.oid));
1610 ptree_oid = get_commit_tree_oid(parent);
1612 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1615 return oideq(ptree_oid, get_commit_tree_oid(commit));
1619 * Should empty commits be allowed? Return status:
1620 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1621 * 0: Halt on empty commit
1622 * 1: Allow empty commit
1623 * 2: Drop empty commit
1625 static int allow_empty(struct repository *r,
1626 struct replay_opts *opts,
1627 struct commit *commit)
1629 int index_unchanged, originally_empty;
1634 * (1) we do not allow empty at all and error out.
1636 * (2) we allow ones that were initially empty, and
1637 * just drop the ones that become empty
1639 * (3) we allow ones that were initially empty, but
1640 * halt for the ones that become empty;
1642 * (4) we allow both.
1644 if (!opts->allow_empty)
1645 return 0; /* let "git commit" barf as necessary */
1647 index_unchanged = is_index_unchanged(r);
1648 if (index_unchanged < 0)
1649 return index_unchanged;
1650 if (!index_unchanged)
1651 return 0; /* we do not have to say --allow-empty */
1653 if (opts->keep_redundant_commits)
1656 originally_empty = is_original_commit_empty(commit);
1657 if (originally_empty < 0)
1658 return originally_empty;
1659 if (originally_empty)
1661 else if (opts->drop_redundant_commits)
1670 } todo_command_info[] = {
1687 static const char *command_to_string(const enum todo_command command)
1689 if (command < TODO_COMMENT)
1690 return todo_command_info[command].str;
1691 die(_("unknown command: %d"), command);
1694 static char command_to_char(const enum todo_command command)
1696 if (command < TODO_COMMENT)
1697 return todo_command_info[command].c;
1698 return comment_line_char;
1701 static int is_noop(const enum todo_command command)
1703 return TODO_NOOP <= command;
1706 static int is_fixup(enum todo_command command)
1708 return command == TODO_FIXUP || command == TODO_SQUASH;
1711 /* Does this command create a (non-merge) commit? */
1712 static int is_pick_or_similar(enum todo_command command)
1727 enum todo_item_flags {
1728 TODO_EDIT_MERGE_MSG = (1 << 0),
1729 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1730 TODO_EDIT_FIXUP_MSG = (1 << 2),
1733 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1734 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1735 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1736 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1737 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1739 static int is_fixup_flag(enum todo_command command, unsigned flag)
1741 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1742 (flag & TODO_EDIT_FIXUP_MSG));
1746 * Wrapper around strbuf_add_commented_lines() which avoids double
1747 * commenting commit subjects.
1749 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1751 const char *s = str;
1752 while (len > 0 && s[0] == comment_line_char) {
1754 const char *n = memchr(s, '\n', len);
1759 strbuf_add(buf, s, count);
1763 strbuf_add_commented_lines(buf, s, len);
1766 /* Does the current fixup chain contain a squash command? */
1767 static int seen_squash(struct replay_opts *opts)
1769 return starts_with(opts->current_fixups.buf, "squash") ||
1770 strstr(opts->current_fixups.buf, "\nsquash");
1773 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1775 strbuf_setlen(buf1, 2);
1776 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1777 strbuf_addch(buf1, '\n');
1778 strbuf_setlen(buf2, 2);
1779 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1780 strbuf_addch(buf2, '\n');
1784 * Comment out any un-commented commit messages, updating the message comments
1785 * to say they will be skipped but do not comment out the empty lines that
1786 * surround commit messages and their comments.
1788 static void update_squash_message_for_fixup(struct strbuf *msg)
1790 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1791 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1792 const char *s, *start;
1794 size_t orig_msg_len;
1797 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1798 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1799 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1803 if (skip_prefix(s, buf1.buf, &next)) {
1805 * Copy the last message, preserving the blank line
1806 * preceding the current line
1808 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1809 copy_lines(msg, start, s - start - off);
1811 strbuf_addch(msg, '\n');
1813 * The next message needs to be commented out but the
1814 * message header is already commented out so just copy
1815 * it and the blank line that follows it.
1817 strbuf_addbuf(msg, &buf2);
1819 strbuf_addch(msg, *next++);
1821 copy_lines = add_commented_lines;
1822 update_comment_bufs(&buf1, &buf2, ++i);
1823 } else if (skip_prefix(s, buf2.buf, &next)) {
1824 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1825 copy_lines(msg, start, s - start - off);
1828 copy_lines = strbuf_add;
1829 update_comment_bufs(&buf1, &buf2, ++i);
1831 s = strchr(s, '\n');
1836 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1838 strbuf_release(&buf1);
1839 strbuf_release(&buf2);
1842 static int append_squash_message(struct strbuf *buf, const char *body,
1843 enum todo_command command, struct replay_opts *opts,
1846 const char *fixup_msg;
1847 size_t commented_len = 0, fixup_off;
1849 * amend is non-interactive and not normally used with fixup!
1850 * or squash! commits, so only comment out those subjects when
1851 * squashing commit messages.
1853 if (starts_with(body, "amend!") ||
1854 ((command == TODO_SQUASH || seen_squash(opts)) &&
1855 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1856 commented_len = commit_subject_length(body);
1858 strbuf_addf(buf, "\n%c ", comment_line_char);
1859 strbuf_addf(buf, _(nth_commit_msg_fmt),
1860 ++opts->current_fixup_count + 1);
1861 strbuf_addstr(buf, "\n\n");
1862 strbuf_add_commented_lines(buf, body, commented_len);
1863 /* buf->buf may be reallocated so store an offset into the buffer */
1864 fixup_off = buf->len;
1865 strbuf_addstr(buf, body + commented_len);
1867 /* fixup -C after squash behaves like squash */
1868 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1870 * We're replacing the commit message so we need to
1871 * append the Signed-off-by: trailer if the user
1872 * requested '--signoff'.
1875 append_signoff(buf, 0, 0);
1877 if ((command == TODO_FIXUP) &&
1878 (flag & TODO_REPLACE_FIXUP_MSG) &&
1879 (file_exists(rebase_path_fixup_msg()) ||
1880 !file_exists(rebase_path_squash_msg()))) {
1881 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1882 if (write_message(fixup_msg, strlen(fixup_msg),
1883 rebase_path_fixup_msg(), 0) < 0)
1884 return error(_("cannot write '%s'"),
1885 rebase_path_fixup_msg());
1887 unlink(rebase_path_fixup_msg());
1890 unlink(rebase_path_fixup_msg());
1896 static int update_squash_messages(struct repository *r,
1897 enum todo_command command,
1898 struct commit *commit,
1899 struct replay_opts *opts,
1902 struct strbuf buf = STRBUF_INIT;
1904 const char *message, *body;
1905 const char *encoding = get_commit_output_encoding();
1907 if (opts->current_fixup_count > 0) {
1908 struct strbuf header = STRBUF_INIT;
1911 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1912 return error(_("could not read '%s'"),
1913 rebase_path_squash_msg());
1915 eol = buf.buf[0] != comment_line_char ?
1916 buf.buf : strchrnul(buf.buf, '\n');
1918 strbuf_addf(&header, "%c ", comment_line_char);
1919 strbuf_addf(&header, _(combined_commit_msg_fmt),
1920 opts->current_fixup_count + 2);
1921 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1922 strbuf_release(&header);
1923 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1924 update_squash_message_for_fixup(&buf);
1926 struct object_id head;
1927 struct commit *head_commit;
1928 const char *head_message, *body;
1930 if (get_oid("HEAD", &head))
1931 return error(_("need a HEAD to fixup"));
1932 if (!(head_commit = lookup_commit_reference(r, &head)))
1933 return error(_("could not read HEAD"));
1934 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1935 return error(_("could not read HEAD's commit message"));
1937 find_commit_subject(head_message, &body);
1938 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1939 rebase_path_fixup_msg(), 0) < 0) {
1940 unuse_commit_buffer(head_commit, head_message);
1941 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1943 strbuf_addf(&buf, "%c ", comment_line_char);
1944 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1945 strbuf_addf(&buf, "\n%c ", comment_line_char);
1946 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1947 _(skip_first_commit_msg_str) :
1948 _(first_commit_msg_str));
1949 strbuf_addstr(&buf, "\n\n");
1950 if (is_fixup_flag(command, flag))
1951 strbuf_add_commented_lines(&buf, body, strlen(body));
1953 strbuf_addstr(&buf, body);
1955 unuse_commit_buffer(head_commit, head_message);
1958 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1959 return error(_("could not read commit message of %s"),
1960 oid_to_hex(&commit->object.oid));
1961 find_commit_subject(message, &body);
1963 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1964 res = append_squash_message(&buf, body, command, opts, flag);
1965 } else if (command == TODO_FIXUP) {
1966 strbuf_addf(&buf, "\n%c ", comment_line_char);
1967 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1968 ++opts->current_fixup_count + 1);
1969 strbuf_addstr(&buf, "\n\n");
1970 strbuf_add_commented_lines(&buf, body, strlen(body));
1972 return error(_("unknown command: %d"), command);
1973 unuse_commit_buffer(commit, message);
1976 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1978 strbuf_release(&buf);
1981 strbuf_addf(&opts->current_fixups, "%s%s %s",
1982 opts->current_fixups.len ? "\n" : "",
1983 command_to_string(command),
1984 oid_to_hex(&commit->object.oid));
1985 res = write_message(opts->current_fixups.buf,
1986 opts->current_fixups.len,
1987 rebase_path_current_fixups(), 0);
1993 static void flush_rewritten_pending(void)
1995 struct strbuf buf = STRBUF_INIT;
1996 struct object_id newoid;
1999 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2000 !get_oid("HEAD", &newoid) &&
2001 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2002 char *bol = buf.buf, *eol;
2005 eol = strchrnul(bol, '\n');
2006 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2007 bol, oid_to_hex(&newoid));
2013 unlink(rebase_path_rewritten_pending());
2015 strbuf_release(&buf);
2018 static void record_in_rewritten(struct object_id *oid,
2019 enum todo_command next_command)
2021 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2026 fprintf(out, "%s\n", oid_to_hex(oid));
2029 if (!is_fixup(next_command))
2030 flush_rewritten_pending();
2033 static int should_edit(struct replay_opts *opts) {
2036 * Note that we only handle the case of non-conflicted
2037 * commits; continue_single_pick() handles the conflicted
2038 * commits itself instead of calling this function.
2040 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2044 static int do_pick_commit(struct repository *r,
2045 struct todo_item *item,
2046 struct replay_opts *opts,
2047 int final_fixup, int *check_todo)
2049 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2050 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2051 struct object_id head;
2052 struct commit *base, *next, *parent;
2053 const char *base_label, *next_label;
2054 char *author = NULL;
2055 struct commit_message msg = { NULL, NULL, NULL, NULL };
2056 struct strbuf msgbuf = STRBUF_INIT;
2057 int res, unborn = 0, reword = 0, allow, drop_commit;
2058 enum todo_command command = item->command;
2059 struct commit *commit = item->commit;
2061 if (opts->no_commit) {
2063 * We do not intend to commit immediately. We just want to
2064 * merge the differences in, so let's compute the tree
2065 * that represents the "current" state for merge-recursive
2068 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2069 return error(_("your index file is unmerged."));
2071 unborn = get_oid("HEAD", &head);
2072 /* Do we want to generate a root commit? */
2073 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2074 oideq(&head, &opts->squash_onto)) {
2075 if (is_fixup(command))
2076 return error(_("cannot fixup root commit"));
2077 flags |= CREATE_ROOT_COMMIT;
2080 oidcpy(&head, the_hash_algo->empty_tree);
2081 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2083 return error_dirty_index(r, opts);
2085 discard_index(r->index);
2087 if (!commit->parents)
2089 else if (commit->parents->next) {
2090 /* Reverting or cherry-picking a merge commit */
2092 struct commit_list *p;
2094 if (!opts->mainline)
2095 return error(_("commit %s is a merge but no -m option was given."),
2096 oid_to_hex(&commit->object.oid));
2098 for (cnt = 1, p = commit->parents;
2099 cnt != opts->mainline && p;
2102 if (cnt != opts->mainline || !p)
2103 return error(_("commit %s does not have parent %d"),
2104 oid_to_hex(&commit->object.oid), opts->mainline);
2106 } else if (1 < opts->mainline)
2108 * Non-first parent explicitly specified as mainline for
2111 return error(_("commit %s does not have parent %d"),
2112 oid_to_hex(&commit->object.oid), opts->mainline);
2114 parent = commit->parents->item;
2116 if (get_message(commit, &msg) != 0)
2117 return error(_("cannot get commit message for %s"),
2118 oid_to_hex(&commit->object.oid));
2120 if (opts->allow_ff && !is_fixup(command) &&
2121 ((parent && oideq(&parent->object.oid, &head)) ||
2122 (!parent && unborn))) {
2123 if (is_rebase_i(opts))
2124 write_author_script(msg.message);
2125 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2127 if (res || command != TODO_REWORD)
2131 goto fast_forward_edit;
2133 if (parent && parse_commit(parent) < 0)
2134 /* TRANSLATORS: The first %s will be a "todo" command like
2135 "revert" or "pick", the second %s a SHA1. */
2136 return error(_("%s: cannot parse parent commit %s"),
2137 command_to_string(command),
2138 oid_to_hex(&parent->object.oid));
2141 * "commit" is an existing commit. We would want to apply
2142 * the difference it introduces since its first parent "prev"
2143 * on top of the current HEAD if we are cherry-pick. Or the
2144 * reverse of it if we are revert.
2147 if (command == TODO_REVERT) {
2149 base_label = msg.label;
2151 next_label = msg.parent_label;
2152 strbuf_addstr(&msgbuf, "Revert \"");
2153 strbuf_addstr(&msgbuf, msg.subject);
2154 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2155 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2157 if (commit->parents && commit->parents->next) {
2158 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2159 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2161 strbuf_addstr(&msgbuf, ".\n");
2166 base_label = msg.parent_label;
2168 next_label = msg.label;
2170 /* Append the commit log message to msgbuf. */
2171 if (find_commit_subject(msg.message, &p))
2172 strbuf_addstr(&msgbuf, p);
2174 if (opts->record_origin) {
2175 strbuf_complete_line(&msgbuf);
2176 if (!has_conforming_footer(&msgbuf, NULL, 0))
2177 strbuf_addch(&msgbuf, '\n');
2178 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2179 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2180 strbuf_addstr(&msgbuf, ")\n");
2182 if (!is_fixup(command))
2183 author = get_author(msg.message);
2186 if (command == TODO_REWORD)
2188 else if (is_fixup(command)) {
2189 if (update_squash_messages(r, command, commit,
2194 msg_file = rebase_path_squash_msg();
2195 else if (file_exists(rebase_path_fixup_msg())) {
2196 flags |= VERBATIM_MSG;
2197 msg_file = rebase_path_fixup_msg();
2199 const char *dest = git_path_squash_msg(r);
2201 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2202 return error(_("could not rename '%s' to '%s'"),
2203 rebase_path_squash_msg(), dest);
2204 unlink(git_path_merge_msg(r));
2210 if (opts->signoff && !is_fixup(command))
2211 append_signoff(&msgbuf, 0, 0);
2213 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2215 else if (!opts->strategy ||
2216 !strcmp(opts->strategy, "recursive") ||
2217 !strcmp(opts->strategy, "ort") ||
2218 command == TODO_REVERT) {
2219 res = do_recursive_merge(r, base, next, base_label, next_label,
2220 &head, &msgbuf, opts);
2224 res |= write_message(msgbuf.buf, msgbuf.len,
2225 git_path_merge_msg(r), 0);
2227 struct commit_list *common = NULL;
2228 struct commit_list *remotes = NULL;
2230 res = write_message(msgbuf.buf, msgbuf.len,
2231 git_path_merge_msg(r), 0);
2233 commit_list_insert(base, &common);
2234 commit_list_insert(next, &remotes);
2235 res |= try_merge_command(r, opts->strategy,
2236 opts->xopts_nr, (const char **)opts->xopts,
2237 common, oid_to_hex(&head), remotes);
2238 free_commit_list(common);
2239 free_commit_list(remotes);
2241 strbuf_release(&msgbuf);
2244 * If the merge was clean or if it failed due to conflict, we write
2245 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2246 * However, if the merge did not even start, then we don't want to
2249 if ((command == TODO_PICK || command == TODO_REWORD ||
2250 command == TODO_EDIT) && !opts->no_commit &&
2251 (res == 0 || res == 1) &&
2252 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2253 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2255 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2256 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2257 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2261 error(command == TODO_REVERT
2262 ? _("could not revert %s... %s")
2263 : _("could not apply %s... %s"),
2264 short_commit_name(commit), msg.subject);
2265 print_advice(r, res == 1, opts);
2266 repo_rerere(r, opts->allow_rerere_auto);
2271 allow = allow_empty(r, opts, commit);
2275 } else if (allow == 1) {
2276 flags |= ALLOW_EMPTY;
2277 } else if (allow == 2) {
2279 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2281 unlink(git_path_merge_msg(r));
2282 unlink(git_path_auto_merge(r));
2284 _("dropping %s %s -- patch contents already upstream\n"),
2285 oid_to_hex(&commit->object.oid), msg.subject);
2286 } /* else allow == 0 and there's nothing special to do */
2287 if (!opts->no_commit && !drop_commit) {
2288 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2289 res = do_commit(r, msg_file, author, opts, flags,
2290 commit? &commit->object.oid : NULL);
2292 res = error(_("unable to parse commit author"));
2293 *check_todo = !!(flags & EDIT_MSG);
2294 if (!res && reword) {
2296 res = run_git_commit(NULL, opts, EDIT_MSG |
2297 VERIFY_MSG | AMEND_MSG |
2298 (flags & ALLOW_EMPTY));
2304 if (!res && final_fixup) {
2305 unlink(rebase_path_fixup_msg());
2306 unlink(rebase_path_squash_msg());
2307 unlink(rebase_path_current_fixups());
2308 strbuf_reset(&opts->current_fixups);
2309 opts->current_fixup_count = 0;
2313 free_message(commit, &msg);
2315 update_abort_safety_file();
2320 static int prepare_revs(struct replay_opts *opts)
2323 * picking (but not reverting) ranges (but not individual revisions)
2324 * should be done in reverse
2326 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2327 opts->revs->reverse ^= 1;
2329 if (prepare_revision_walk(opts->revs))
2330 return error(_("revision walk setup failed"));
2335 static int read_and_refresh_cache(struct repository *r,
2336 struct replay_opts *opts)
2338 struct lock_file index_lock = LOCK_INIT;
2339 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2340 if (repo_read_index(r) < 0) {
2341 rollback_lock_file(&index_lock);
2342 return error(_("git %s: failed to read the index"),
2343 _(action_name(opts)));
2345 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2346 if (index_fd >= 0) {
2347 if (write_locked_index(r->index, &index_lock,
2348 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2349 return error(_("git %s: failed to refresh the index"),
2350 _(action_name(opts)));
2356 void todo_list_release(struct todo_list *todo_list)
2358 strbuf_release(&todo_list->buf);
2359 FREE_AND_NULL(todo_list->items);
2360 todo_list->nr = todo_list->alloc = 0;
2363 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2365 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2366 todo_list->total_nr++;
2367 return todo_list->items + todo_list->nr++;
2370 const char *todo_item_get_arg(struct todo_list *todo_list,
2371 struct todo_item *item)
2373 return todo_list->buf.buf + item->arg_offset;
2376 static int is_command(enum todo_command command, const char **bol)
2378 const char *str = todo_command_info[command].str;
2379 const char nick = todo_command_info[command].c;
2380 const char *p = *bol + 1;
2382 return skip_prefix(*bol, str, bol) ||
2383 ((nick && **bol == nick) &&
2384 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2388 static int parse_insn_line(struct repository *r, struct todo_item *item,
2389 const char *buf, const char *bol, char *eol)
2391 struct object_id commit_oid;
2392 char *end_of_object_name;
2393 int i, saved, status, padding;
2398 bol += strspn(bol, " \t");
2400 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2401 item->command = TODO_COMMENT;
2402 item->commit = NULL;
2403 item->arg_offset = bol - buf;
2404 item->arg_len = eol - bol;
2408 for (i = 0; i < TODO_COMMENT; i++)
2409 if (is_command(i, &bol)) {
2413 if (i >= TODO_COMMENT)
2416 /* Eat up extra spaces/ tabs before object name */
2417 padding = strspn(bol, " \t");
2420 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2422 return error(_("%s does not accept arguments: '%s'"),
2423 command_to_string(item->command), bol);
2424 item->commit = NULL;
2425 item->arg_offset = bol - buf;
2426 item->arg_len = eol - bol;
2431 return error(_("missing arguments for %s"),
2432 command_to_string(item->command));
2434 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2435 item->command == TODO_RESET) {
2436 item->commit = NULL;
2437 item->arg_offset = bol - buf;
2438 item->arg_len = (int)(eol - bol);
2442 if (item->command == TODO_FIXUP) {
2443 if (skip_prefix(bol, "-C", &bol) &&
2444 (*bol == ' ' || *bol == '\t')) {
2445 bol += strspn(bol, " \t");
2446 item->flags |= TODO_REPLACE_FIXUP_MSG;
2447 } else if (skip_prefix(bol, "-c", &bol) &&
2448 (*bol == ' ' || *bol == '\t')) {
2449 bol += strspn(bol, " \t");
2450 item->flags |= TODO_EDIT_FIXUP_MSG;
2454 if (item->command == TODO_MERGE) {
2455 if (skip_prefix(bol, "-C", &bol))
2456 bol += strspn(bol, " \t");
2457 else if (skip_prefix(bol, "-c", &bol)) {
2458 bol += strspn(bol, " \t");
2459 item->flags |= TODO_EDIT_MERGE_MSG;
2461 item->flags |= TODO_EDIT_MERGE_MSG;
2462 item->commit = NULL;
2463 item->arg_offset = bol - buf;
2464 item->arg_len = (int)(eol - bol);
2469 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2470 saved = *end_of_object_name;
2471 *end_of_object_name = '\0';
2472 status = get_oid(bol, &commit_oid);
2474 error(_("could not parse '%s'"), bol); /* return later */
2475 *end_of_object_name = saved;
2477 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2478 item->arg_offset = bol - buf;
2479 item->arg_len = (int)(eol - bol);
2484 item->commit = lookup_commit_reference(r, &commit_oid);
2485 return item->commit ? 0 : -1;
2488 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2490 const char *todo_file, *bol;
2491 struct strbuf buf = STRBUF_INIT;
2494 todo_file = git_path_todo_file();
2495 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2496 if (errno == ENOENT || errno == ENOTDIR)
2499 return error_errno("unable to open '%s'", todo_file);
2501 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2502 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2503 *action = REPLAY_PICK;
2504 else if (is_command(TODO_REVERT, &bol) &&
2505 (*bol == ' ' || *bol == '\t'))
2506 *action = REPLAY_REVERT;
2510 strbuf_release(&buf);
2515 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2516 struct todo_list *todo_list)
2518 struct todo_item *item;
2519 char *p = buf, *next_p;
2520 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2522 todo_list->current = todo_list->nr = 0;
2524 for (i = 1; *p; i++, p = next_p) {
2525 char *eol = strchrnul(p, '\n');
2527 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2529 if (p != eol && eol[-1] == '\r')
2530 eol--; /* strip Carriage Return */
2532 item = append_new_todo(todo_list);
2533 item->offset_in_buf = p - todo_list->buf.buf;
2534 if (parse_insn_line(r, item, buf, p, eol)) {
2535 res = error(_("invalid line %d: %.*s"),
2536 i, (int)(eol - p), p);
2537 item->command = TODO_COMMENT + 1;
2538 item->arg_offset = p - buf;
2539 item->arg_len = (int)(eol - p);
2540 item->commit = NULL;
2545 else if (is_fixup(item->command))
2546 return error(_("cannot '%s' without a previous commit"),
2547 command_to_string(item->command));
2548 else if (!is_noop(item->command))
2555 static int count_commands(struct todo_list *todo_list)
2559 for (i = 0; i < todo_list->nr; i++)
2560 if (todo_list->items[i].command != TODO_COMMENT)
2566 static int get_item_line_offset(struct todo_list *todo_list, int index)
2568 return index < todo_list->nr ?
2569 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2572 static const char *get_item_line(struct todo_list *todo_list, int index)
2574 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2577 static int get_item_line_length(struct todo_list *todo_list, int index)
2579 return get_item_line_offset(todo_list, index + 1)
2580 - get_item_line_offset(todo_list, index);
2583 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2588 fd = open(path, O_RDONLY);
2590 return error_errno(_("could not open '%s'"), path);
2591 len = strbuf_read(sb, fd, 0);
2594 return error(_("could not read '%s'."), path);
2598 static int have_finished_the_last_pick(void)
2600 struct strbuf buf = STRBUF_INIT;
2602 const char *todo_path = git_path_todo_file();
2605 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2606 if (errno == ENOENT) {
2609 error_errno("unable to open '%s'", todo_path);
2613 /* If there is only one line then we are done */
2614 eol = strchr(buf.buf, '\n');
2615 if (!eol || !eol[1])
2618 strbuf_release(&buf);
2623 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2625 struct replay_opts opts = REPLAY_OPTS_INIT;
2626 int need_cleanup = 0;
2628 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2629 if (!refs_delete_ref(get_main_ref_store(r), "",
2630 "CHERRY_PICK_HEAD", NULL, 0) &&
2632 warning(_("cancelling a cherry picking in progress"));
2633 opts.action = REPLAY_PICK;
2637 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2638 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2641 warning(_("cancelling a revert in progress"));
2642 opts.action = REPLAY_REVERT;
2646 unlink(git_path_auto_merge(r));
2651 if (!have_finished_the_last_pick())
2654 sequencer_remove_state(&opts);
2657 static void todo_list_write_total_nr(struct todo_list *todo_list)
2659 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2662 fprintf(f, "%d\n", todo_list->total_nr);
2667 static int read_populate_todo(struct repository *r,
2668 struct todo_list *todo_list,
2669 struct replay_opts *opts)
2672 const char *todo_file = get_todo_path(opts);
2675 strbuf_reset(&todo_list->buf);
2676 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2679 res = stat(todo_file, &st);
2681 return error(_("could not stat '%s'"), todo_file);
2682 fill_stat_data(&todo_list->stat, &st);
2684 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2686 if (is_rebase_i(opts))
2687 return error(_("please fix this using "
2688 "'git rebase --edit-todo'."));
2689 return error(_("unusable instruction sheet: '%s'"), todo_file);
2692 if (!todo_list->nr &&
2693 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2694 return error(_("no commits parsed."));
2696 if (!is_rebase_i(opts)) {
2697 enum todo_command valid =
2698 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2701 for (i = 0; i < todo_list->nr; i++)
2702 if (valid == todo_list->items[i].command)
2704 else if (valid == TODO_PICK)
2705 return error(_("cannot cherry-pick during a revert."));
2707 return error(_("cannot revert during a cherry-pick."));
2710 if (is_rebase_i(opts)) {
2711 struct todo_list done = TODO_LIST_INIT;
2713 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2714 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2715 todo_list->done_nr = count_commands(&done);
2717 todo_list->done_nr = 0;
2719 todo_list->total_nr = todo_list->done_nr
2720 + count_commands(todo_list);
2721 todo_list_release(&done);
2723 todo_list_write_total_nr(todo_list);
2729 static int git_config_string_dup(char **dest,
2730 const char *var, const char *value)
2733 return config_error_nonbool(var);
2735 *dest = xstrdup(value);
2739 static int populate_opts_cb(const char *key, const char *value, void *data)
2741 struct replay_opts *opts = data;
2746 else if (!strcmp(key, "options.no-commit"))
2747 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2748 else if (!strcmp(key, "options.edit"))
2749 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2750 else if (!strcmp(key, "options.allow-empty"))
2752 git_config_bool_or_int(key, value, &error_flag);
2753 else if (!strcmp(key, "options.allow-empty-message"))
2754 opts->allow_empty_message =
2755 git_config_bool_or_int(key, value, &error_flag);
2756 else if (!strcmp(key, "options.keep-redundant-commits"))
2757 opts->keep_redundant_commits =
2758 git_config_bool_or_int(key, value, &error_flag);
2759 else if (!strcmp(key, "options.signoff"))
2760 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2761 else if (!strcmp(key, "options.record-origin"))
2762 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2763 else if (!strcmp(key, "options.allow-ff"))
2764 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2765 else if (!strcmp(key, "options.mainline"))
2766 opts->mainline = git_config_int(key, value);
2767 else if (!strcmp(key, "options.strategy"))
2768 git_config_string_dup(&opts->strategy, key, value);
2769 else if (!strcmp(key, "options.gpg-sign"))
2770 git_config_string_dup(&opts->gpg_sign, key, value);
2771 else if (!strcmp(key, "options.strategy-option")) {
2772 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2773 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2774 } else if (!strcmp(key, "options.allow-rerere-auto"))
2775 opts->allow_rerere_auto =
2776 git_config_bool_or_int(key, value, &error_flag) ?
2777 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2778 else if (!strcmp(key, "options.default-msg-cleanup")) {
2779 opts->explicit_cleanup = 1;
2780 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2782 return error(_("invalid key: %s"), key);
2785 return error(_("invalid value for %s: %s"), key, value);
2790 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2793 char *strategy_opts_string = raw_opts;
2795 if (*strategy_opts_string == ' ')
2796 strategy_opts_string++;
2798 opts->xopts_nr = split_cmdline(strategy_opts_string,
2799 (const char ***)&opts->xopts);
2800 for (i = 0; i < opts->xopts_nr; i++) {
2801 const char *arg = opts->xopts[i];
2803 skip_prefix(arg, "--", &arg);
2804 opts->xopts[i] = xstrdup(arg);
2808 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2811 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2813 opts->strategy = strbuf_detach(buf, NULL);
2814 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2817 parse_strategy_opts(opts, buf->buf);
2820 static int read_populate_opts(struct replay_opts *opts)
2822 if (is_rebase_i(opts)) {
2823 struct strbuf buf = STRBUF_INIT;
2826 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2827 READ_ONELINER_SKIP_IF_EMPTY)) {
2828 if (!starts_with(buf.buf, "-S"))
2831 free(opts->gpg_sign);
2832 opts->gpg_sign = xstrdup(buf.buf + 2);
2837 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2838 READ_ONELINER_SKIP_IF_EMPTY)) {
2839 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2840 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2841 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2842 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2846 if (file_exists(rebase_path_verbose()))
2849 if (file_exists(rebase_path_quiet()))
2852 if (file_exists(rebase_path_signoff())) {
2857 if (file_exists(rebase_path_cdate_is_adate())) {
2859 opts->committer_date_is_author_date = 1;
2862 if (file_exists(rebase_path_ignore_date())) {
2864 opts->ignore_date = 1;
2867 if (file_exists(rebase_path_reschedule_failed_exec()))
2868 opts->reschedule_failed_exec = 1;
2869 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2870 opts->reschedule_failed_exec = 0;
2872 if (file_exists(rebase_path_drop_redundant_commits()))
2873 opts->drop_redundant_commits = 1;
2875 if (file_exists(rebase_path_keep_redundant_commits()))
2876 opts->keep_redundant_commits = 1;
2878 read_strategy_opts(opts, &buf);
2881 if (read_oneliner(&opts->current_fixups,
2882 rebase_path_current_fixups(),
2883 READ_ONELINER_SKIP_IF_EMPTY)) {
2884 const char *p = opts->current_fixups.buf;
2885 opts->current_fixup_count = 1;
2886 while ((p = strchr(p, '\n'))) {
2887 opts->current_fixup_count++;
2892 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2893 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2894 ret = error(_("unusable squash-onto"));
2897 opts->have_squash_onto = 1;
2901 strbuf_release(&buf);
2905 if (!file_exists(git_path_opts_file()))
2908 * The function git_parse_source(), called from git_config_from_file(),
2909 * may die() in case of a syntactically incorrect file. We do not care
2910 * about this case, though, because we wrote that file ourselves, so we
2911 * are pretty certain that it is syntactically correct.
2913 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2914 return error(_("malformed options sheet: '%s'"),
2915 git_path_opts_file());
2919 static void write_strategy_opts(struct replay_opts *opts)
2922 struct strbuf buf = STRBUF_INIT;
2924 for (i = 0; i < opts->xopts_nr; ++i)
2925 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2927 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2928 strbuf_release(&buf);
2931 int write_basic_state(struct replay_opts *opts, const char *head_name,
2932 struct commit *onto, const struct object_id *orig_head)
2935 write_file(rebase_path_head_name(), "%s\n", head_name);
2937 write_file(rebase_path_onto(), "%s\n",
2938 oid_to_hex(&onto->object.oid));
2940 write_file(rebase_path_orig_head(), "%s\n",
2941 oid_to_hex(orig_head));
2944 write_file(rebase_path_quiet(), "%s", "");
2946 write_file(rebase_path_verbose(), "%s", "");
2948 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2949 if (opts->xopts_nr > 0)
2950 write_strategy_opts(opts);
2952 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2953 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2954 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2955 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2958 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2960 write_file(rebase_path_signoff(), "--signoff\n");
2961 if (opts->drop_redundant_commits)
2962 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2963 if (opts->keep_redundant_commits)
2964 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2965 if (opts->committer_date_is_author_date)
2966 write_file(rebase_path_cdate_is_adate(), "%s", "");
2967 if (opts->ignore_date)
2968 write_file(rebase_path_ignore_date(), "%s", "");
2969 if (opts->reschedule_failed_exec)
2970 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2972 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2977 static int walk_revs_populate_todo(struct todo_list *todo_list,
2978 struct replay_opts *opts)
2980 enum todo_command command = opts->action == REPLAY_PICK ?
2981 TODO_PICK : TODO_REVERT;
2982 const char *command_string = todo_command_info[command].str;
2983 const char *encoding;
2984 struct commit *commit;
2986 if (prepare_revs(opts))
2989 encoding = get_log_output_encoding();
2991 while ((commit = get_revision(opts->revs))) {
2992 struct todo_item *item = append_new_todo(todo_list);
2993 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2994 const char *subject;
2997 item->command = command;
2998 item->commit = commit;
2999 item->arg_offset = 0;
3001 item->offset_in_buf = todo_list->buf.len;
3002 subject_len = find_commit_subject(commit_buffer, &subject);
3003 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3004 short_commit_name(commit), subject_len, subject);
3005 unuse_commit_buffer(commit, commit_buffer);
3009 return error(_("empty commit set passed"));
3014 static int create_seq_dir(struct repository *r)
3016 enum replay_action action;
3017 const char *in_progress_error = NULL;
3018 const char *in_progress_advice = NULL;
3019 unsigned int advise_skip =
3020 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3021 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3023 if (!sequencer_get_last_command(r, &action)) {
3026 in_progress_error = _("revert is already in progress");
3027 in_progress_advice =
3028 _("try \"git revert (--continue | %s--abort | --quit)\"");
3031 in_progress_error = _("cherry-pick is already in progress");
3032 in_progress_advice =
3033 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3036 BUG("unexpected action in create_seq_dir");
3039 if (in_progress_error) {
3040 error("%s", in_progress_error);
3041 if (advice_sequencer_in_use)
3042 advise(in_progress_advice,
3043 advise_skip ? "--skip | " : "");
3046 if (mkdir(git_path_seq_dir(), 0777) < 0)
3047 return error_errno(_("could not create sequencer directory '%s'"),
3048 git_path_seq_dir());
3053 static int save_head(const char *head)
3055 struct lock_file head_lock = LOCK_INIT;
3056 struct strbuf buf = STRBUF_INIT;
3060 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3062 return error_errno(_("could not lock HEAD"));
3063 strbuf_addf(&buf, "%s\n", head);
3064 written = write_in_full(fd, buf.buf, buf.len);
3065 strbuf_release(&buf);
3067 error_errno(_("could not write to '%s'"), git_path_head_file());
3068 rollback_lock_file(&head_lock);
3071 if (commit_lock_file(&head_lock) < 0)
3072 return error(_("failed to finalize '%s'"), git_path_head_file());
3076 static int rollback_is_safe(void)
3078 struct strbuf sb = STRBUF_INIT;
3079 struct object_id expected_head, actual_head;
3081 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3083 if (get_oid_hex(sb.buf, &expected_head)) {
3084 strbuf_release(&sb);
3085 die(_("could not parse %s"), git_path_abort_safety_file());
3087 strbuf_release(&sb);
3089 else if (errno == ENOENT)
3090 oidclr(&expected_head);
3092 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3094 if (get_oid("HEAD", &actual_head))
3095 oidclr(&actual_head);
3097 return oideq(&actual_head, &expected_head);
3100 static int reset_merge(const struct object_id *oid)
3103 struct strvec argv = STRVEC_INIT;
3105 strvec_pushl(&argv, "reset", "--merge", NULL);
3107 if (!is_null_oid(oid))
3108 strvec_push(&argv, oid_to_hex(oid));
3110 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3111 strvec_clear(&argv);
3116 static int rollback_single_pick(struct repository *r)
3118 struct object_id head_oid;
3120 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3121 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3122 return error(_("no cherry-pick or revert in progress"));
3123 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3124 return error(_("cannot resolve HEAD"));
3125 if (is_null_oid(&head_oid))
3126 return error(_("cannot abort from a branch yet to be born"));
3127 return reset_merge(&head_oid);
3130 static int skip_single_pick(void)
3132 struct object_id head;
3134 if (read_ref_full("HEAD", 0, &head, NULL))
3135 return error(_("cannot resolve HEAD"));
3136 return reset_merge(&head);
3139 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3142 struct object_id oid;
3143 struct strbuf buf = STRBUF_INIT;
3146 f = fopen(git_path_head_file(), "r");
3147 if (!f && errno == ENOENT) {
3149 * There is no multiple-cherry-pick in progress.
3150 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3151 * a single-cherry-pick in progress, abort that.
3153 return rollback_single_pick(r);
3156 return error_errno(_("cannot open '%s'"), git_path_head_file());
3157 if (strbuf_getline_lf(&buf, f)) {
3158 error(_("cannot read '%s': %s"), git_path_head_file(),
3159 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3164 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3165 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3166 git_path_head_file());
3169 if (is_null_oid(&oid)) {
3170 error(_("cannot abort from a branch yet to be born"));
3174 if (!rollback_is_safe()) {
3175 /* Do not error, just do not rollback */
3176 warning(_("You seem to have moved HEAD. "
3177 "Not rewinding, check your HEAD!"));
3179 if (reset_merge(&oid))
3181 strbuf_release(&buf);
3182 return sequencer_remove_state(opts);
3184 strbuf_release(&buf);
3188 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3190 enum replay_action action = -1;
3191 sequencer_get_last_command(r, &action);
3194 * Check whether the subcommand requested to skip the commit is actually
3195 * in progress and that it's safe to skip the commit.
3197 * opts->action tells us which subcommand requested to skip the commit.
3198 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3199 * action is in progress and we can skip the commit.
3201 * Otherwise we check that the last instruction was related to the
3202 * particular subcommand we're trying to execute and barf if that's not
3205 * Finally we check that the rollback is "safe", i.e., has the HEAD
3206 * moved? In this case, it doesn't make sense to "reset the merge" and
3207 * "skip the commit" as the user already handled this by committing. But
3208 * we'd not want to barf here, instead give advice on how to proceed. We
3209 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3210 * it gets removed when the user commits, so if it still exists we're
3211 * sure the user can't have committed before.
3213 switch (opts->action) {
3215 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3216 if (action != REPLAY_REVERT)
3217 return error(_("no revert in progress"));
3218 if (!rollback_is_safe())
3223 if (!refs_ref_exists(get_main_ref_store(r),
3224 "CHERRY_PICK_HEAD")) {
3225 if (action != REPLAY_PICK)
3226 return error(_("no cherry-pick in progress"));
3227 if (!rollback_is_safe())
3232 BUG("unexpected action in sequencer_skip");
3235 if (skip_single_pick())
3236 return error(_("failed to skip the commit"));
3237 if (!is_directory(git_path_seq_dir()))
3240 return sequencer_continue(r, opts);
3243 error(_("there is nothing to skip"));
3245 if (advice_resolve_conflict) {
3246 advise(_("have you committed already?\n"
3247 "try \"git %s --continue\""),
3248 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3253 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3255 struct lock_file todo_lock = LOCK_INIT;
3256 const char *todo_path = get_todo_path(opts);
3257 int next = todo_list->current, offset, fd;
3260 * rebase -i writes "git-rebase-todo" without the currently executing
3261 * command, appending it to "done" instead.
3263 if (is_rebase_i(opts))
3266 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3268 return error_errno(_("could not lock '%s'"), todo_path);
3269 offset = get_item_line_offset(todo_list, next);
3270 if (write_in_full(fd, todo_list->buf.buf + offset,
3271 todo_list->buf.len - offset) < 0)
3272 return error_errno(_("could not write to '%s'"), todo_path);
3273 if (commit_lock_file(&todo_lock) < 0)
3274 return error(_("failed to finalize '%s'"), todo_path);
3276 if (is_rebase_i(opts) && next > 0) {
3277 const char *done = rebase_path_done();
3278 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3283 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3284 get_item_line_length(todo_list, next - 1))
3286 ret = error_errno(_("could not write to '%s'"), done);
3288 ret = error_errno(_("failed to finalize '%s'"), done);
3294 static int save_opts(struct replay_opts *opts)
3296 const char *opts_file = git_path_opts_file();
3299 if (opts->no_commit)
3300 res |= git_config_set_in_file_gently(opts_file,
3301 "options.no-commit", "true");
3302 if (opts->edit >= 0)
3303 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3304 opts->edit ? "true" : "false");
3305 if (opts->allow_empty)
3306 res |= git_config_set_in_file_gently(opts_file,
3307 "options.allow-empty", "true");
3308 if (opts->allow_empty_message)
3309 res |= git_config_set_in_file_gently(opts_file,
3310 "options.allow-empty-message", "true");
3311 if (opts->keep_redundant_commits)
3312 res |= git_config_set_in_file_gently(opts_file,
3313 "options.keep-redundant-commits", "true");
3315 res |= git_config_set_in_file_gently(opts_file,
3316 "options.signoff", "true");
3317 if (opts->record_origin)
3318 res |= git_config_set_in_file_gently(opts_file,
3319 "options.record-origin", "true");
3321 res |= git_config_set_in_file_gently(opts_file,
3322 "options.allow-ff", "true");
3323 if (opts->mainline) {
3324 struct strbuf buf = STRBUF_INIT;
3325 strbuf_addf(&buf, "%d", opts->mainline);
3326 res |= git_config_set_in_file_gently(opts_file,
3327 "options.mainline", buf.buf);
3328 strbuf_release(&buf);
3331 res |= git_config_set_in_file_gently(opts_file,
3332 "options.strategy", opts->strategy);
3334 res |= git_config_set_in_file_gently(opts_file,
3335 "options.gpg-sign", opts->gpg_sign);
3338 for (i = 0; i < opts->xopts_nr; i++)
3339 res |= git_config_set_multivar_in_file_gently(opts_file,
3340 "options.strategy-option",
3341 opts->xopts[i], "^$", 0);
3343 if (opts->allow_rerere_auto)
3344 res |= git_config_set_in_file_gently(opts_file,
3345 "options.allow-rerere-auto",
3346 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3349 if (opts->explicit_cleanup)
3350 res |= git_config_set_in_file_gently(opts_file,
3351 "options.default-msg-cleanup",
3352 describe_cleanup_mode(opts->default_msg_cleanup));
3356 static int make_patch(struct repository *r,
3357 struct commit *commit,
3358 struct replay_opts *opts)
3360 struct strbuf buf = STRBUF_INIT;
3361 struct rev_info log_tree_opt;
3362 const char *subject;
3363 char hex[GIT_MAX_HEXSZ + 1];
3366 oid_to_hex_r(hex, &commit->object.oid);
3367 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3369 res |= write_rebase_head(&commit->object.oid);
3371 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3372 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3373 repo_init_revisions(r, &log_tree_opt, NULL);
3374 log_tree_opt.abbrev = 0;
3375 log_tree_opt.diff = 1;
3376 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3377 log_tree_opt.stdin_handling = REV_INFO_STDIN_IGNORE;
3378 log_tree_opt.no_commit_id = 1;
3379 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3380 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3381 if (!log_tree_opt.diffopt.file)
3382 res |= error_errno(_("could not open '%s'"), buf.buf);
3384 res |= log_tree_commit(&log_tree_opt, commit);
3385 fclose(log_tree_opt.diffopt.file);
3389 strbuf_addf(&buf, "%s/message", get_dir(opts));
3390 if (!file_exists(buf.buf)) {
3391 const char *encoding = get_commit_output_encoding();
3392 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3393 find_commit_subject(commit_buffer, &subject);
3394 res |= write_message(subject, strlen(subject), buf.buf, 1);
3395 unuse_commit_buffer(commit, commit_buffer);
3397 strbuf_release(&buf);
3402 static int intend_to_amend(void)
3404 struct object_id head;
3407 if (get_oid("HEAD", &head))
3408 return error(_("cannot read HEAD"));
3410 p = oid_to_hex(&head);
3411 return write_message(p, strlen(p), rebase_path_amend(), 1);
3414 static int error_with_patch(struct repository *r,
3415 struct commit *commit,
3416 const char *subject, int subject_len,
3417 struct replay_opts *opts,
3418 int exit_code, int to_amend)
3421 if (make_patch(r, commit, opts))
3423 } else if (copy_file(rebase_path_message(),
3424 git_path_merge_msg(r), 0666))
3425 return error(_("unable to copy '%s' to '%s'"),
3426 git_path_merge_msg(r), rebase_path_message());
3429 if (intend_to_amend())
3433 _("You can amend the commit now, with\n"
3435 " git commit --amend %s\n"
3437 "Once you are satisfied with your changes, run\n"
3439 " git rebase --continue\n"),
3440 gpg_sign_opt_quoted(opts));
3441 } else if (exit_code) {
3443 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3444 short_commit_name(commit), subject_len, subject);
3447 * We don't have the hash of the parent so
3448 * just print the line from the todo file.
3450 fprintf_ln(stderr, _("Could not merge %.*s"),
3451 subject_len, subject);
3457 static int error_failed_squash(struct repository *r,
3458 struct commit *commit,
3459 struct replay_opts *opts,
3461 const char *subject)
3463 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3464 return error(_("could not copy '%s' to '%s'"),
3465 rebase_path_squash_msg(), rebase_path_message());
3466 unlink(git_path_merge_msg(r));
3467 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3468 return error(_("could not copy '%s' to '%s'"),
3469 rebase_path_message(),
3470 git_path_merge_msg(r));
3471 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3474 static int do_exec(struct repository *r, const char *command_line)
3476 struct strvec child_env = STRVEC_INIT;
3477 const char *child_argv[] = { NULL, NULL };
3480 fprintf(stderr, _("Executing: %s\n"), command_line);
3481 child_argv[0] = command_line;
3482 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3483 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3484 absolute_path(get_git_work_tree()));
3485 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3488 /* force re-reading of the cache */
3489 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3490 return error(_("could not read index"));
3492 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3495 warning(_("execution failed: %s\n%s"
3496 "You can fix the problem, and then run\n"
3498 " git rebase --continue\n"
3501 dirty ? N_("and made changes to the index and/or the "
3502 "working tree\n") : "");
3504 /* command not found */
3507 warning(_("execution succeeded: %s\nbut "
3508 "left changes to the index and/or the working tree\n"
3509 "Commit or stash your changes, and then run\n"
3511 " git rebase --continue\n"
3512 "\n"), command_line);
3516 strvec_clear(&child_env);
3521 static int safe_append(const char *filename, const char *fmt, ...)
3524 struct lock_file lock = LOCK_INIT;
3525 int fd = hold_lock_file_for_update(&lock, filename,
3526 LOCK_REPORT_ON_ERROR);
3527 struct strbuf buf = STRBUF_INIT;
3532 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3533 error_errno(_("could not read '%s'"), filename);
3534 rollback_lock_file(&lock);
3537 strbuf_complete(&buf, '\n');
3539 strbuf_vaddf(&buf, fmt, ap);
3542 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3543 error_errno(_("could not write to '%s'"), filename);
3544 strbuf_release(&buf);
3545 rollback_lock_file(&lock);
3548 if (commit_lock_file(&lock) < 0) {
3549 strbuf_release(&buf);
3550 rollback_lock_file(&lock);
3551 return error(_("failed to finalize '%s'"), filename);
3554 strbuf_release(&buf);
3558 static int do_label(struct repository *r, const char *name, int len)
3560 struct ref_store *refs = get_main_ref_store(r);
3561 struct ref_transaction *transaction;
3562 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3563 struct strbuf msg = STRBUF_INIT;
3565 struct object_id head_oid;
3567 if (len == 1 && *name == '#')
3568 return error(_("illegal label name: '%.*s'"), len, name);
3570 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3571 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3573 transaction = ref_store_transaction_begin(refs, &err);
3575 error("%s", err.buf);
3577 } else if (get_oid("HEAD", &head_oid)) {
3578 error(_("could not read HEAD"));
3580 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3581 NULL, 0, msg.buf, &err) < 0 ||
3582 ref_transaction_commit(transaction, &err)) {
3583 error("%s", err.buf);
3586 ref_transaction_free(transaction);
3587 strbuf_release(&err);
3588 strbuf_release(&msg);
3591 ret = safe_append(rebase_path_refs_to_delete(),
3592 "%s\n", ref_name.buf);
3593 strbuf_release(&ref_name);
3598 static const char *reflog_message(struct replay_opts *opts,
3599 const char *sub_action, const char *fmt, ...);
3601 static int do_reset(struct repository *r,
3602 const char *name, int len,
3603 struct replay_opts *opts)
3605 struct strbuf ref_name = STRBUF_INIT;
3606 struct object_id oid;
3607 struct lock_file lock = LOCK_INIT;
3608 struct tree_desc desc;
3610 struct unpack_trees_options unpack_tree_opts;
3613 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3616 if (len == 10 && !strncmp("[new root]", name, len)) {
3617 if (!opts->have_squash_onto) {
3619 if (commit_tree("", 0, the_hash_algo->empty_tree,
3620 NULL, &opts->squash_onto,
3622 return error(_("writing fake root commit"));
3623 opts->have_squash_onto = 1;
3624 hex = oid_to_hex(&opts->squash_onto);
3625 if (write_message(hex, strlen(hex),
3626 rebase_path_squash_onto(), 0))
3627 return error(_("writing squash-onto"));
3629 oidcpy(&oid, &opts->squash_onto);
3633 /* Determine the length of the label */
3634 for (i = 0; i < len; i++)
3635 if (isspace(name[i]))
3639 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3640 if (get_oid(ref_name.buf, &oid) &&
3641 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3642 error(_("could not read '%s'"), ref_name.buf);
3643 rollback_lock_file(&lock);
3644 strbuf_release(&ref_name);
3649 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3650 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3651 unpack_tree_opts.head_idx = 1;
3652 unpack_tree_opts.src_index = r->index;
3653 unpack_tree_opts.dst_index = r->index;
3654 unpack_tree_opts.fn = oneway_merge;
3655 unpack_tree_opts.merge = 1;
3656 unpack_tree_opts.update = 1;
3657 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3659 if (repo_read_index_unmerged(r)) {
3660 rollback_lock_file(&lock);
3661 strbuf_release(&ref_name);
3662 return error_resolve_conflict(_(action_name(opts)));
3665 if (!fill_tree_descriptor(r, &desc, &oid)) {
3666 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3667 rollback_lock_file(&lock);
3668 free((void *)desc.buffer);
3669 strbuf_release(&ref_name);
3673 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3674 rollback_lock_file(&lock);
3675 free((void *)desc.buffer);
3676 strbuf_release(&ref_name);
3680 tree = parse_tree_indirect(&oid);
3681 prime_cache_tree(r, r->index, tree);
3683 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3684 ret = error(_("could not write index"));
3685 free((void *)desc.buffer);
3688 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3689 len, name), "HEAD", &oid,
3690 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3692 strbuf_release(&ref_name);
3696 static struct commit *lookup_label(const char *label, int len,
3699 struct commit *commit;
3702 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3703 commit = lookup_commit_reference_by_name(buf->buf);
3705 /* fall back to non-rewritten ref or commit */
3706 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3707 commit = lookup_commit_reference_by_name(buf->buf);
3711 error(_("could not resolve '%s'"), buf->buf);
3716 static int do_merge(struct repository *r,
3717 struct commit *commit,
3718 const char *arg, int arg_len,
3719 int flags, struct replay_opts *opts)
3721 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3722 EDIT_MSG | VERIFY_MSG : 0;
3723 struct strbuf ref_name = STRBUF_INIT;
3724 struct commit *head_commit, *merge_commit, *i;
3725 struct commit_list *bases, *j, *reversed = NULL;
3726 struct commit_list *to_merge = NULL, **tail = &to_merge;
3727 const char *strategy = !opts->xopts_nr &&
3729 !strcmp(opts->strategy, "recursive") ||
3730 !strcmp(opts->strategy, "ort")) ?
3731 NULL : opts->strategy;
3732 struct merge_options o;
3733 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3734 static struct lock_file lock;
3737 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3742 head_commit = lookup_commit_reference_by_name("HEAD");
3744 ret = error(_("cannot merge without a current revision"));
3749 * For octopus merges, the arg starts with the list of revisions to be
3750 * merged. The list is optionally followed by '#' and the oneline.
3752 merge_arg_len = oneline_offset = arg_len;
3753 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3756 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3757 p += 1 + strspn(p + 1, " \t\n");
3758 oneline_offset = p - arg;
3761 k = strcspn(p, " \t\n");
3764 merge_commit = lookup_label(p, k, &ref_name);
3765 if (!merge_commit) {
3766 ret = error(_("unable to parse '%.*s'"), k, p);
3769 tail = &commit_list_insert(merge_commit, tail)->next;
3771 merge_arg_len = p - arg;
3775 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3779 if (opts->have_squash_onto &&
3780 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3782 * When the user tells us to "merge" something into a
3783 * "[new root]", let's simply fast-forward to the merge head.
3785 rollback_lock_file(&lock);
3787 ret = error(_("octopus merge cannot be executed on "
3788 "top of a [new root]"));
3790 ret = fast_forward_to(r, &to_merge->item->object.oid,
3791 &head_commit->object.oid, 0,
3797 const char *encoding = get_commit_output_encoding();
3798 const char *message = logmsg_reencode(commit, NULL, encoding);
3803 ret = error(_("could not get commit message of '%s'"),
3804 oid_to_hex(&commit->object.oid));
3807 write_author_script(message);
3808 find_commit_subject(message, &body);
3810 ret = write_message(body, len, git_path_merge_msg(r), 0);
3811 unuse_commit_buffer(commit, message);
3813 error_errno(_("could not write '%s'"),
3814 git_path_merge_msg(r));
3818 struct strbuf buf = STRBUF_INIT;
3821 strbuf_addf(&buf, "author %s", git_author_info(0));
3822 write_author_script(buf.buf);
3825 if (oneline_offset < arg_len) {
3826 p = arg + oneline_offset;
3827 len = arg_len - oneline_offset;
3829 strbuf_addf(&buf, "Merge %s '%.*s'",
3830 to_merge->next ? "branches" : "branch",
3831 merge_arg_len, arg);
3836 ret = write_message(p, len, git_path_merge_msg(r), 0);
3837 strbuf_release(&buf);
3839 error_errno(_("could not write '%s'"),
3840 git_path_merge_msg(r));
3846 * If HEAD is not identical to the first parent of the original merge
3847 * commit, we cannot fast-forward.
3849 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3850 oideq(&commit->parents->item->object.oid,
3851 &head_commit->object.oid);
3854 * If any merge head is different from the original one, we cannot
3857 if (can_fast_forward) {
3858 struct commit_list *p = commit->parents->next;
3860 for (j = to_merge; j && p; j = j->next, p = p->next)
3861 if (!oideq(&j->item->object.oid,
3862 &p->item->object.oid)) {
3863 can_fast_forward = 0;
3867 * If the number of merge heads differs from the original merge
3868 * commit, we cannot fast-forward.
3871 can_fast_forward = 0;
3874 if (can_fast_forward) {
3875 rollback_lock_file(&lock);
3876 ret = fast_forward_to(r, &commit->object.oid,
3877 &head_commit->object.oid, 0, opts);
3878 if (flags & TODO_EDIT_MERGE_MSG) {
3879 run_commit_flags |= AMEND_MSG;
3880 goto fast_forward_edit;
3885 if (strategy || to_merge->next) {
3887 struct child_process cmd = CHILD_PROCESS_INIT;
3889 if (read_env_script(&cmd.env_array)) {
3890 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3892 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3896 if (opts->committer_date_is_author_date)
3897 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3900 author_date_from_env_array(&cmd.env_array));
3901 if (opts->ignore_date)
3902 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3905 strvec_push(&cmd.args, "merge");
3906 strvec_push(&cmd.args, "-s");
3908 strvec_push(&cmd.args, "octopus");
3910 strvec_push(&cmd.args, strategy);
3911 for (k = 0; k < opts->xopts_nr; k++)
3912 strvec_pushf(&cmd.args,
3913 "-X%s", opts->xopts[k]);
3915 strvec_push(&cmd.args, "--no-edit");
3916 strvec_push(&cmd.args, "--no-ff");
3917 strvec_push(&cmd.args, "--no-log");
3918 strvec_push(&cmd.args, "--no-stat");
3919 strvec_push(&cmd.args, "-F");
3920 strvec_push(&cmd.args, git_path_merge_msg(r));
3922 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3924 strvec_push(&cmd.args, "--no-gpg-sign");
3926 /* Add the tips to be merged */
3927 for (j = to_merge; j; j = j->next)
3928 strvec_push(&cmd.args,
3929 oid_to_hex(&j->item->object.oid));
3931 strbuf_release(&ref_name);
3932 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3934 rollback_lock_file(&lock);
3936 ret = run_command(&cmd);
3938 /* force re-reading of the cache */
3939 if (!ret && (discard_index(r->index) < 0 ||
3940 repo_read_index(r) < 0))
3941 ret = error(_("could not read index"));
3945 merge_commit = to_merge->item;
3946 bases = get_merge_bases(head_commit, merge_commit);
3947 if (bases && oideq(&merge_commit->object.oid,
3948 &bases->item->object.oid)) {
3950 /* skip merging an ancestor of HEAD */
3954 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3955 git_path_merge_head(r), 0);
3956 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3958 for (j = bases; j; j = j->next)
3959 commit_list_insert(j->item, &reversed);
3960 free_commit_list(bases);
3963 init_merge_options(&o, r);
3965 o.branch2 = ref_name.buf;
3966 o.buffer_output = 2;
3968 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3970 * TODO: Should use merge_incore_recursive() and
3971 * merge_switch_to_result(), skipping the call to
3972 * merge_switch_to_result() when we don't actually need to
3973 * update the index and working copy immediately.
3975 ret = merge_ort_recursive(&o,
3976 head_commit, merge_commit, reversed,
3979 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3983 fputs(o.obuf.buf, stdout);
3984 strbuf_release(&o.obuf);
3986 error(_("could not even attempt to merge '%.*s'"),
3987 merge_arg_len, arg);
3991 * The return value of merge_recursive() is 1 on clean, and 0 on
3994 * Let's reverse that, so that do_merge() returns 0 upon success and
3995 * 1 upon failed merge (keeping the return value -1 for the cases where
3996 * we will want to reschedule the `merge` command).
4000 if (r->index->cache_changed &&
4001 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4002 ret = error(_("merge: Unable to write new index file"));
4006 rollback_lock_file(&lock);
4008 repo_rerere(r, opts->allow_rerere_auto);
4011 * In case of problems, we now want to return a positive
4012 * value (a negative one would indicate that the `merge`
4013 * command needs to be rescheduled).
4016 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4020 strbuf_release(&ref_name);
4021 rollback_lock_file(&lock);
4022 free_commit_list(to_merge);
4026 static int is_final_fixup(struct todo_list *todo_list)
4028 int i = todo_list->current;
4030 if (!is_fixup(todo_list->items[i].command))
4033 while (++i < todo_list->nr)
4034 if (is_fixup(todo_list->items[i].command))
4036 else if (!is_noop(todo_list->items[i].command))
4041 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4045 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4046 if (!is_noop(todo_list->items[i].command))
4047 return todo_list->items[i].command;
4052 void create_autostash(struct repository *r, const char *path,
4053 const char *default_reflog_action)
4055 struct strbuf buf = STRBUF_INIT;
4056 struct lock_file lock_file = LOCK_INIT;
4059 fd = repo_hold_locked_index(r, &lock_file, 0);
4060 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4062 repo_update_index_if_able(r, &lock_file);
4063 rollback_lock_file(&lock_file);
4065 if (has_unstaged_changes(r, 1) ||
4066 has_uncommitted_changes(r, 1)) {
4067 struct child_process stash = CHILD_PROCESS_INIT;
4068 struct object_id oid;
4070 strvec_pushl(&stash.args,
4071 "stash", "create", "autostash", NULL);
4075 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4076 die(_("Cannot autostash"));
4077 strbuf_trim_trailing_newline(&buf);
4078 if (get_oid(buf.buf, &oid))
4079 die(_("Unexpected stash response: '%s'"),
4082 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4084 if (safe_create_leading_directories_const(path))
4085 die(_("Could not create directory for '%s'"),
4087 write_file(path, "%s", oid_to_hex(&oid));
4088 printf(_("Created autostash: %s\n"), buf.buf);
4089 if (reset_head(r, NULL, "reset --hard",
4090 NULL, RESET_HEAD_HARD, NULL, NULL,
4091 default_reflog_action) < 0)
4092 die(_("could not reset --hard"));
4094 if (discard_index(r->index) < 0 ||
4095 repo_read_index(r) < 0)
4096 die(_("could not read index"));
4098 strbuf_release(&buf);
4101 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4103 struct child_process child = CHILD_PROCESS_INIT;
4106 if (attempt_apply) {
4108 child.no_stdout = 1;
4109 child.no_stderr = 1;
4110 strvec_push(&child.args, "stash");
4111 strvec_push(&child.args, "apply");
4112 strvec_push(&child.args, stash_oid);
4113 ret = run_command(&child);
4116 if (attempt_apply && !ret)
4117 fprintf(stderr, _("Applied autostash.\n"));
4119 struct child_process store = CHILD_PROCESS_INIT;
4122 strvec_push(&store.args, "stash");
4123 strvec_push(&store.args, "store");
4124 strvec_push(&store.args, "-m");
4125 strvec_push(&store.args, "autostash");
4126 strvec_push(&store.args, "-q");
4127 strvec_push(&store.args, stash_oid);
4128 if (run_command(&store))
4129 ret = error(_("cannot store %s"), stash_oid);
4133 "Your changes are safe in the stash.\n"
4134 "You can run \"git stash pop\" or"
4135 " \"git stash drop\" at any time.\n"),
4137 _("Applying autostash resulted in conflicts.") :
4138 _("Autostash exists; creating a new stash entry."));
4144 static int apply_save_autostash(const char *path, int attempt_apply)
4146 struct strbuf stash_oid = STRBUF_INIT;
4149 if (!read_oneliner(&stash_oid, path,
4150 READ_ONELINER_SKIP_IF_EMPTY)) {
4151 strbuf_release(&stash_oid);
4154 strbuf_trim(&stash_oid);
4156 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4159 strbuf_release(&stash_oid);
4163 int save_autostash(const char *path)
4165 return apply_save_autostash(path, 0);
4168 int apply_autostash(const char *path)
4170 return apply_save_autostash(path, 1);
4173 int apply_autostash_oid(const char *stash_oid)
4175 return apply_save_autostash_oid(stash_oid, 1);
4178 static const char *reflog_message(struct replay_opts *opts,
4179 const char *sub_action, const char *fmt, ...)
4182 static struct strbuf buf = STRBUF_INIT;
4183 char *reflog_action = getenv(GIT_REFLOG_ACTION);
4187 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
4189 strbuf_addf(&buf, " (%s)", sub_action);
4191 strbuf_addstr(&buf, ": ");
4192 strbuf_vaddf(&buf, fmt, ap);
4199 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4200 const char *commit, const char *action)
4202 struct child_process cmd = CHILD_PROCESS_INIT;
4207 strvec_push(&cmd.args, "checkout");
4208 strvec_push(&cmd.args, commit);
4209 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4212 ret = run_command(&cmd);
4214 ret = run_command_silent_on_success(&cmd);
4217 discard_index(r->index);
4222 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4223 const char *onto_name, const struct object_id *onto,
4224 const struct object_id *orig_head)
4226 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4228 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4229 apply_autostash(rebase_path_autostash());
4230 sequencer_remove_state(opts);
4231 return error(_("could not detach HEAD"));
4234 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4237 static int stopped_at_head(struct repository *r)
4239 struct object_id head;
4240 struct commit *commit;
4241 struct commit_message message;
4243 if (get_oid("HEAD", &head) ||
4244 !(commit = lookup_commit(r, &head)) ||
4245 parse_commit(commit) || get_message(commit, &message))
4246 fprintf(stderr, _("Stopped at HEAD\n"));
4248 fprintf(stderr, _("Stopped at %s\n"), message.label);
4249 free_message(commit, &message);
4255 static const char rescheduled_advice[] =
4256 N_("Could not execute the todo command\n"
4260 "It has been rescheduled; To edit the command before continuing, please\n"
4261 "edit the todo list first:\n"
4263 " git rebase --edit-todo\n"
4264 " git rebase --continue\n");
4266 static int pick_commits(struct repository *r,
4267 struct todo_list *todo_list,
4268 struct replay_opts *opts)
4270 int res = 0, reschedule = 0;
4271 char *prev_reflog_action;
4273 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4274 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4275 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4277 assert(!(opts->signoff || opts->no_commit ||
4278 opts->record_origin || should_edit(opts) ||
4279 opts->committer_date_is_author_date ||
4280 opts->ignore_date));
4281 if (read_and_refresh_cache(r, opts))
4284 while (todo_list->current < todo_list->nr) {
4285 struct todo_item *item = todo_list->items + todo_list->current;
4286 const char *arg = todo_item_get_arg(todo_list, item);
4289 if (save_todo(todo_list, opts))
4291 if (is_rebase_i(opts)) {
4292 if (item->command != TODO_COMMENT) {
4293 FILE *f = fopen(rebase_path_msgnum(), "w");
4295 todo_list->done_nr++;
4298 fprintf(f, "%d\n", todo_list->done_nr);
4302 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4304 todo_list->total_nr,
4305 opts->verbose ? "\n" : "\r");
4307 unlink(rebase_path_message());
4308 unlink(rebase_path_author_script());
4309 unlink(rebase_path_stopped_sha());
4310 unlink(rebase_path_amend());
4311 unlink(git_path_merge_head(r));
4312 unlink(git_path_auto_merge(r));
4313 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4315 if (item->command == TODO_BREAK) {
4318 return stopped_at_head(r);
4321 if (item->command <= TODO_SQUASH) {
4322 if (is_rebase_i(opts))
4323 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4324 command_to_string(item->command), NULL),
4326 res = do_pick_commit(r, item, opts,
4327 is_final_fixup(todo_list),
4329 if (is_rebase_i(opts))
4330 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4331 if (is_rebase_i(opts) && res < 0) {
4333 advise(_(rescheduled_advice),
4334 get_item_line_length(todo_list,
4335 todo_list->current),
4336 get_item_line(todo_list,
4337 todo_list->current));
4338 todo_list->current--;
4339 if (save_todo(todo_list, opts))
4342 if (item->command == TODO_EDIT) {
4343 struct commit *commit = item->commit;
4348 _("Stopped at %s... %.*s\n"),
4349 short_commit_name(commit),
4350 item->arg_len, arg);
4352 return error_with_patch(r, commit,
4353 arg, item->arg_len, opts, res, !res);
4355 if (is_rebase_i(opts) && !res)
4356 record_in_rewritten(&item->commit->object.oid,
4357 peek_command(todo_list, 1));
4358 if (res && is_fixup(item->command)) {
4361 return error_failed_squash(r, item->commit, opts,
4362 item->arg_len, arg);
4363 } else if (res && is_rebase_i(opts) && item->commit) {
4365 struct object_id oid;
4368 * If we are rewording and have either
4369 * fast-forwarded already, or are about to
4370 * create a new root commit, we want to amend,
4371 * otherwise we do not.
4373 if (item->command == TODO_REWORD &&
4374 !get_oid("HEAD", &oid) &&
4375 (oideq(&item->commit->object.oid, &oid) ||
4376 (opts->have_squash_onto &&
4377 oideq(&opts->squash_onto, &oid))))
4380 return res | error_with_patch(r, item->commit,
4381 arg, item->arg_len, opts,
4384 } else if (item->command == TODO_EXEC) {
4385 char *end_of_arg = (char *)(arg + item->arg_len);
4386 int saved = *end_of_arg;
4391 res = do_exec(r, arg);
4392 *end_of_arg = saved;
4395 if (opts->reschedule_failed_exec)
4399 } else if (item->command == TODO_LABEL) {
4400 if ((res = do_label(r, arg, item->arg_len)))
4402 } else if (item->command == TODO_RESET) {
4403 if ((res = do_reset(r, arg, item->arg_len, opts)))
4405 } else if (item->command == TODO_MERGE) {
4406 if ((res = do_merge(r, item->commit,
4408 item->flags, opts)) < 0)
4410 else if (item->commit)
4411 record_in_rewritten(&item->commit->object.oid,
4412 peek_command(todo_list, 1));
4414 /* failed with merge conflicts */
4415 return error_with_patch(r, item->commit,
4418 } else if (!is_noop(item->command))
4419 return error(_("unknown command %d"), item->command);
4422 advise(_(rescheduled_advice),
4423 get_item_line_length(todo_list,
4424 todo_list->current),
4425 get_item_line(todo_list, todo_list->current));
4426 todo_list->current--;
4427 if (save_todo(todo_list, opts))
4430 return error_with_patch(r,
4434 } else if (is_rebase_i(opts) && check_todo && !res) {
4437 if (stat(get_todo_path(opts), &st)) {
4438 res = error_errno(_("could not stat '%s'"),
4439 get_todo_path(opts));
4440 } else if (match_stat_data(&todo_list->stat, &st)) {
4441 /* Reread the todo file if it has changed. */
4442 todo_list_release(todo_list);
4443 if (read_populate_todo(r, todo_list, opts))
4444 res = -1; /* message was printed */
4445 /* `current` will be incremented below */
4446 todo_list->current = -1;
4450 todo_list->current++;
4455 if (is_rebase_i(opts)) {
4456 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4459 /* Stopped in the middle, as planned? */
4460 if (todo_list->current < todo_list->nr)
4463 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4464 starts_with(head_ref.buf, "refs/")) {
4466 struct object_id head, orig;
4469 if (get_oid("HEAD", &head)) {
4470 res = error(_("cannot read HEAD"));
4472 strbuf_release(&head_ref);
4473 strbuf_release(&buf);
4476 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4477 get_oid_hex(buf.buf, &orig)) {
4478 res = error(_("could not read orig-head"));
4479 goto cleanup_head_ref;
4482 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4483 res = error(_("could not read 'onto'"));
4484 goto cleanup_head_ref;
4486 msg = reflog_message(opts, "finish", "%s onto %s",
4487 head_ref.buf, buf.buf);
4488 if (update_ref(msg, head_ref.buf, &head, &orig,
4489 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4490 res = error(_("could not update %s"),
4492 goto cleanup_head_ref;
4494 msg = reflog_message(opts, "finish", "returning to %s",
4496 if (create_symref("HEAD", head_ref.buf, msg)) {
4497 res = error(_("could not update HEAD to %s"),
4499 goto cleanup_head_ref;
4504 if (opts->verbose) {
4505 struct rev_info log_tree_opt;
4506 struct object_id orig, head;
4508 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4509 repo_init_revisions(r, &log_tree_opt, NULL);
4510 log_tree_opt.diff = 1;
4511 log_tree_opt.diffopt.output_format =
4512 DIFF_FORMAT_DIFFSTAT;
4513 log_tree_opt.stdin_handling = REV_INFO_STDIN_IGNORE;
4515 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4516 !get_oid(buf.buf, &orig) &&
4517 !get_oid("HEAD", &head)) {
4518 diff_tree_oid(&orig, &head, "",
4519 &log_tree_opt.diffopt);
4520 log_tree_diff_flush(&log_tree_opt);
4523 flush_rewritten_pending();
4524 if (!stat(rebase_path_rewritten_list(), &st) &&
4526 struct child_process notes_cp = CHILD_PROCESS_INIT;
4527 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
4529 notes_cp.in = open(rebase_path_rewritten_list(), O_RDONLY);
4530 notes_cp.git_cmd = 1;
4531 strvec_push(¬es_cp.args, "notes");
4532 strvec_push(¬es_cp.args, "copy");
4533 strvec_push(¬es_cp.args, "--for-rewrite=rebase");
4534 /* we don't care if this copying failed */
4535 run_command(¬es_cp);
4537 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4538 strvec_push(&hook_opt.args, "rebase");
4539 run_hooks("post-rewrite", &hook_opt);
4540 run_hooks_opt_clear(&hook_opt);
4542 apply_autostash(rebase_path_autostash());
4548 _("Successfully rebased and updated %s.\n"),
4552 strbuf_release(&buf);
4553 strbuf_release(&head_ref);
4557 * Sequence of picks finished successfully; cleanup by
4558 * removing the .git/sequencer directory
4560 return sequencer_remove_state(opts);
4563 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4565 struct strvec argv = STRVEC_INIT;
4568 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4569 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4570 return error(_("no cherry-pick or revert in progress"));
4572 strvec_push(&argv, "commit");
4575 * continue_single_pick() handles the case of recovering from a
4576 * conflict. should_edit() doesn't handle that case; for a conflict,
4577 * we want to edit if the user asked for it, or if they didn't specify
4578 * and stdin is a tty.
4580 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4582 * Include --cleanup=strip as well because we don't want the
4583 * "# Conflicts:" messages.
4585 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4587 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4588 strvec_clear(&argv);
4592 static int commit_staged_changes(struct repository *r,
4593 struct replay_opts *opts,
4594 struct todo_list *todo_list)
4596 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4597 unsigned int final_fixup = 0, is_clean;
4599 if (has_unstaged_changes(r, 1))
4600 return error(_("cannot rebase: You have unstaged changes."));
4602 is_clean = !has_uncommitted_changes(r, 0);
4604 if (file_exists(rebase_path_amend())) {
4605 struct strbuf rev = STRBUF_INIT;
4606 struct object_id head, to_amend;
4608 if (get_oid("HEAD", &head))
4609 return error(_("cannot amend non-existing commit"));
4610 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4611 return error(_("invalid file: '%s'"), rebase_path_amend());
4612 if (get_oid_hex(rev.buf, &to_amend))
4613 return error(_("invalid contents: '%s'"),
4614 rebase_path_amend());
4615 if (!is_clean && !oideq(&head, &to_amend))
4616 return error(_("\nYou have uncommitted changes in your "
4617 "working tree. Please, commit them\n"
4618 "first and then run 'git rebase "
4619 "--continue' again."));
4621 * When skipping a failed fixup/squash, we need to edit the
4622 * commit message, the current fixup list and count, and if it
4623 * was the last fixup/squash in the chain, we need to clean up
4624 * the commit message and if there was a squash, let the user
4627 if (!is_clean || !opts->current_fixup_count)
4628 ; /* this is not the final fixup */
4629 else if (!oideq(&head, &to_amend) ||
4630 !file_exists(rebase_path_stopped_sha())) {
4631 /* was a final fixup or squash done manually? */
4632 if (!is_fixup(peek_command(todo_list, 0))) {
4633 unlink(rebase_path_fixup_msg());
4634 unlink(rebase_path_squash_msg());
4635 unlink(rebase_path_current_fixups());
4636 strbuf_reset(&opts->current_fixups);
4637 opts->current_fixup_count = 0;
4640 /* we are in a fixup/squash chain */
4641 const char *p = opts->current_fixups.buf;
4642 int len = opts->current_fixups.len;
4644 opts->current_fixup_count--;
4646 BUG("Incorrect current_fixups:\n%s", p);
4647 while (len && p[len - 1] != '\n')
4649 strbuf_setlen(&opts->current_fixups, len);
4650 if (write_message(p, len, rebase_path_current_fixups(),
4652 return error(_("could not write file: '%s'"),
4653 rebase_path_current_fixups());
4656 * If a fixup/squash in a fixup/squash chain failed, the
4657 * commit message is already correct, no need to commit
4660 * Only if it is the final command in the fixup/squash
4661 * chain, and only if the chain is longer than a single
4662 * fixup/squash command (which was just skipped), do we
4663 * actually need to re-commit with a cleaned up commit
4666 if (opts->current_fixup_count > 0 &&
4667 !is_fixup(peek_command(todo_list, 0))) {
4670 * If there was not a single "squash" in the
4671 * chain, we only need to clean up the commit
4672 * message, no need to bother the user with
4673 * opening the commit message in the editor.
4675 if (!starts_with(p, "squash ") &&
4676 !strstr(p, "\nsquash "))
4677 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4678 } else if (is_fixup(peek_command(todo_list, 0))) {
4680 * We need to update the squash message to skip
4681 * the latest commit message.
4683 struct commit *commit;
4684 const char *path = rebase_path_squash_msg();
4685 const char *encoding = get_commit_output_encoding();
4687 if (parse_head(r, &commit) ||
4688 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4689 write_message(p, strlen(p), path, 0)) {
4690 unuse_commit_buffer(commit, p);
4691 return error(_("could not write file: "
4694 unuse_commit_buffer(commit, p);
4698 strbuf_release(&rev);
4703 if (refs_ref_exists(get_main_ref_store(r),
4704 "CHERRY_PICK_HEAD") &&
4705 refs_delete_ref(get_main_ref_store(r), "",
4706 "CHERRY_PICK_HEAD", NULL, 0))
4707 return error(_("could not remove CHERRY_PICK_HEAD"));
4712 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4714 return error(_("could not commit staged changes."));
4715 unlink(rebase_path_amend());
4716 unlink(git_path_merge_head(r));
4717 unlink(git_path_auto_merge(r));
4719 unlink(rebase_path_fixup_msg());
4720 unlink(rebase_path_squash_msg());
4722 if (opts->current_fixup_count > 0) {
4724 * Whether final fixup or not, we just cleaned up the commit
4727 unlink(rebase_path_current_fixups());
4728 strbuf_reset(&opts->current_fixups);
4729 opts->current_fixup_count = 0;
4734 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4736 struct todo_list todo_list = TODO_LIST_INIT;
4739 if (read_and_refresh_cache(r, opts))
4742 if (read_populate_opts(opts))
4744 if (is_rebase_i(opts)) {
4745 if ((res = read_populate_todo(r, &todo_list, opts)))
4746 goto release_todo_list;
4748 if (file_exists(rebase_path_dropped())) {
4749 if ((res = todo_list_check_against_backup(r, &todo_list)))
4750 goto release_todo_list;
4752 unlink(rebase_path_dropped());
4755 if (commit_staged_changes(r, opts, &todo_list)) {
4757 goto release_todo_list;
4759 } else if (!file_exists(get_todo_path(opts)))
4760 return continue_single_pick(r, opts);
4761 else if ((res = read_populate_todo(r, &todo_list, opts)))
4762 goto release_todo_list;
4764 if (!is_rebase_i(opts)) {
4765 /* Verify that the conflict has been resolved */
4766 if (refs_ref_exists(get_main_ref_store(r),
4767 "CHERRY_PICK_HEAD") ||
4768 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4769 res = continue_single_pick(r, opts);
4771 goto release_todo_list;
4773 if (index_differs_from(r, "HEAD", NULL, 0)) {
4774 res = error_dirty_index(r, opts);
4775 goto release_todo_list;
4777 todo_list.current++;
4778 } else if (file_exists(rebase_path_stopped_sha())) {
4779 struct strbuf buf = STRBUF_INIT;
4780 struct object_id oid;
4782 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4783 READ_ONELINER_SKIP_IF_EMPTY) &&
4784 !get_oid_hex(buf.buf, &oid))
4785 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4786 strbuf_release(&buf);
4789 res = pick_commits(r, &todo_list, opts);
4791 todo_list_release(&todo_list);
4795 static int single_pick(struct repository *r,
4796 struct commit *cmit,
4797 struct replay_opts *opts)
4800 struct todo_item item;
4802 item.command = opts->action == REPLAY_PICK ?
4803 TODO_PICK : TODO_REVERT;
4806 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4807 return do_pick_commit(r, &item, opts, 0, &check_todo);
4810 int sequencer_pick_revisions(struct repository *r,
4811 struct replay_opts *opts)
4813 struct todo_list todo_list = TODO_LIST_INIT;
4814 struct object_id oid;
4818 if (read_and_refresh_cache(r, opts))
4821 for (i = 0; i < opts->revs->pending.nr; i++) {
4822 struct object_id oid;
4823 const char *name = opts->revs->pending.objects[i].name;
4825 /* This happens when using --stdin. */
4829 if (!get_oid(name, &oid)) {
4830 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4831 enum object_type type = oid_object_info(r,
4834 return error(_("%s: can't cherry-pick a %s"),
4835 name, type_name(type));
4838 return error(_("%s: bad revision"), name);
4842 * If we were called as "git cherry-pick <commit>", just
4843 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4844 * REVERT_HEAD, and don't touch the sequencer state.
4845 * This means it is possible to cherry-pick in the middle
4846 * of a cherry-pick sequence.
4848 if (opts->revs->cmdline.nr == 1 &&
4849 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4850 opts->revs->no_walk &&
4851 !opts->revs->cmdline.rev->flags) {
4852 struct commit *cmit;
4853 if (prepare_revision_walk(opts->revs))
4854 return error(_("revision walk setup failed"));
4855 cmit = get_revision(opts->revs);
4857 return error(_("empty commit set passed"));
4858 if (get_revision(opts->revs))
4859 BUG("unexpected extra commit from walk");
4860 return single_pick(r, cmit, opts);
4864 * Start a new cherry-pick/ revert sequence; but
4865 * first, make sure that an existing one isn't in
4869 if (walk_revs_populate_todo(&todo_list, opts) ||
4870 create_seq_dir(r) < 0)
4872 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4873 return error(_("can't revert as initial commit"));
4874 if (save_head(oid_to_hex(&oid)))
4876 if (save_opts(opts))
4878 update_abort_safety_file();
4879 res = pick_commits(r, &todo_list, opts);
4880 todo_list_release(&todo_list);
4884 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4886 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4887 struct strbuf sob = STRBUF_INIT;
4890 strbuf_addstr(&sob, sign_off_header);
4891 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4892 strbuf_addch(&sob, '\n');
4895 strbuf_complete_line(msgbuf);
4898 * If the whole message buffer is equal to the sob, pretend that we
4899 * found a conforming footer with a matching sob
4901 if (msgbuf->len - ignore_footer == sob.len &&
4902 !strncmp(msgbuf->buf, sob.buf, sob.len))
4905 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4908 const char *append_newlines = NULL;
4909 size_t len = msgbuf->len - ignore_footer;
4913 * The buffer is completely empty. Leave foom for
4914 * the title and body to be filled in by the user.
4916 append_newlines = "\n\n";
4917 } else if (len == 1) {
4919 * Buffer contains a single newline. Add another
4920 * so that we leave room for the title and body.
4922 append_newlines = "\n";
4923 } else if (msgbuf->buf[len - 2] != '\n') {
4925 * Buffer ends with a single newline. Add another
4926 * so that there is an empty line between the message
4929 append_newlines = "\n";
4930 } /* else, the buffer already ends with two newlines. */
4932 if (append_newlines)
4933 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4934 append_newlines, strlen(append_newlines));
4937 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4938 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4941 strbuf_release(&sob);
4944 struct labels_entry {
4945 struct hashmap_entry entry;
4946 char label[FLEX_ARRAY];
4949 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4950 const struct hashmap_entry *entry_or_key, const void *key)
4952 const struct labels_entry *a, *b;
4954 a = container_of(eptr, const struct labels_entry, entry);
4955 b = container_of(entry_or_key, const struct labels_entry, entry);
4957 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4960 struct string_entry {
4961 struct oidmap_entry entry;
4962 char string[FLEX_ARRAY];
4965 struct label_state {
4966 struct oidmap commit2label;
4967 struct hashmap labels;
4971 static const char *label_oid(struct object_id *oid, const char *label,
4972 struct label_state *state)
4974 struct labels_entry *labels_entry;
4975 struct string_entry *string_entry;
4976 struct object_id dummy;
4979 string_entry = oidmap_get(&state->commit2label, oid);
4981 return string_entry->string;
4984 * For "uninteresting" commits, i.e. commits that are not to be
4985 * rebased, and which can therefore not be labeled, we use a unique
4986 * abbreviation of the commit name. This is slightly more complicated
4987 * than calling find_unique_abbrev() because we also need to make
4988 * sure that the abbreviation does not conflict with any other
4991 * We disallow "interesting" commits to be labeled by a string that
4992 * is a valid full-length hash, to ensure that we always can find an
4993 * abbreviation for any uninteresting commit's names that does not
4994 * clash with any other label.
4996 strbuf_reset(&state->buf);
5000 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5001 label = p = state->buf.buf;
5003 find_unique_abbrev_r(p, oid, default_abbrev);
5006 * We may need to extend the abbreviated hash so that there is
5007 * no conflicting label.
5009 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5010 size_t i = strlen(p) + 1;
5012 oid_to_hex_r(p, oid);
5013 for (; i < the_hash_algo->hexsz; i++) {
5016 if (!hashmap_get_from_hash(&state->labels,
5023 struct strbuf *buf = &state->buf;
5026 * Sanitize labels by replacing non-alpha-numeric characters
5027 * (including white-space ones) by dashes, as they might be
5028 * illegal in file names (and hence in ref names).
5030 * Note that we retain non-ASCII UTF-8 characters (identified
5031 * via the most significant bit). They should be all acceptable
5032 * in file names. We do not validate the UTF-8 here, that's not
5033 * the job of this function.
5035 for (; *label; label++)
5036 if ((*label & 0x80) || isalnum(*label))
5037 strbuf_addch(buf, *label);
5038 /* avoid leading dash and double-dashes */
5039 else if (buf->len && buf->buf[buf->len - 1] != '-')
5040 strbuf_addch(buf, '-');
5042 strbuf_addstr(buf, "rev-");
5043 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5047 if ((buf->len == the_hash_algo->hexsz &&
5048 !get_oid_hex(label, &dummy)) ||
5049 (buf->len == 1 && *label == '#') ||
5050 hashmap_get_from_hash(&state->labels,
5051 strihash(label), label)) {
5053 * If the label already exists, or if the label is a
5054 * valid full OID, or the label is a '#' (which we use
5055 * as a separator between merge heads and oneline), we
5056 * append a dash and a number to make it unique.
5058 size_t len = buf->len;
5060 for (i = 2; ; i++) {
5061 strbuf_setlen(buf, len);
5062 strbuf_addf(buf, "-%d", i);
5063 if (!hashmap_get_from_hash(&state->labels,
5073 FLEX_ALLOC_STR(labels_entry, label, label);
5074 hashmap_entry_init(&labels_entry->entry, strihash(label));
5075 hashmap_add(&state->labels, &labels_entry->entry);
5077 FLEX_ALLOC_STR(string_entry, string, label);
5078 oidcpy(&string_entry->entry.oid, oid);
5079 oidmap_put(&state->commit2label, string_entry);
5081 return string_entry->string;
5084 static int make_script_with_merges(struct pretty_print_context *pp,
5085 struct rev_info *revs, struct strbuf *out,
5088 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5089 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5090 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5091 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5092 struct strbuf label = STRBUF_INIT;
5093 struct commit_list *commits = NULL, **tail = &commits, *iter;
5094 struct commit_list *tips = NULL, **tips_tail = &tips;
5095 struct commit *commit;
5096 struct oidmap commit2todo = OIDMAP_INIT;
5097 struct string_entry *entry;
5098 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5099 shown = OIDSET_INIT;
5100 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5102 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5103 const char *cmd_pick = abbr ? "p" : "pick",
5104 *cmd_label = abbr ? "l" : "label",
5105 *cmd_reset = abbr ? "t" : "reset",
5106 *cmd_merge = abbr ? "m" : "merge";
5108 oidmap_init(&commit2todo, 0);
5109 oidmap_init(&state.commit2label, 0);
5110 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5111 strbuf_init(&state.buf, 32);
5113 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5114 struct labels_entry *onto_label_entry;
5115 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5116 FLEX_ALLOC_STR(entry, string, "onto");
5117 oidcpy(&entry->entry.oid, oid);
5118 oidmap_put(&state.commit2label, entry);
5120 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5121 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5122 hashmap_add(&state.labels, &onto_label_entry->entry);
5127 * - get onelines for all commits
5128 * - gather all branch tips (i.e. 2nd or later parents of merges)
5129 * - label all branch tips
5131 while ((commit = get_revision(revs))) {
5132 struct commit_list *to_merge;
5133 const char *p1, *p2;
5134 struct object_id *oid;
5137 tail = &commit_list_insert(commit, tail)->next;
5138 oidset_insert(&interesting, &commit->object.oid);
5140 is_empty = is_original_commit_empty(commit);
5141 if (!is_empty && (commit->object.flags & PATCHSAME))
5143 if (is_empty && !keep_empty)
5146 strbuf_reset(&oneline);
5147 pretty_print_commit(pp, commit, &oneline);
5149 to_merge = commit->parents ? commit->parents->next : NULL;
5151 /* non-merge commit: easy case */
5153 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5154 oid_to_hex(&commit->object.oid),
5157 strbuf_addf(&buf, " %c empty",
5160 FLEX_ALLOC_STR(entry, string, buf.buf);
5161 oidcpy(&entry->entry.oid, &commit->object.oid);
5162 oidmap_put(&commit2todo, entry);
5167 /* Create a label */
5168 strbuf_reset(&label);
5169 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5170 (p1 = strchr(p1, '\'')) &&
5171 (p2 = strchr(++p1, '\'')))
5172 strbuf_add(&label, p1, p2 - p1);
5173 else if (skip_prefix(oneline.buf, "Merge pull request ",
5175 (p1 = strstr(p1, " from ")))
5176 strbuf_addstr(&label, p1 + strlen(" from "));
5178 strbuf_addbuf(&label, &oneline);
5181 strbuf_addf(&buf, "%s -C %s",
5182 cmd_merge, oid_to_hex(&commit->object.oid));
5184 /* label the tips of merged branches */
5185 for (; to_merge; to_merge = to_merge->next) {
5186 oid = &to_merge->item->object.oid;
5187 strbuf_addch(&buf, ' ');
5189 if (!oidset_contains(&interesting, oid)) {
5190 strbuf_addstr(&buf, label_oid(oid, NULL,
5195 tips_tail = &commit_list_insert(to_merge->item,
5198 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5200 strbuf_addf(&buf, " # %s", oneline.buf);
5202 FLEX_ALLOC_STR(entry, string, buf.buf);
5203 oidcpy(&entry->entry.oid, &commit->object.oid);
5204 oidmap_put(&commit2todo, entry);
5209 * - label branch points
5210 * - add HEAD to the branch tips
5212 for (iter = commits; iter; iter = iter->next) {
5213 struct commit_list *parent = iter->item->parents;
5214 for (; parent; parent = parent->next) {
5215 struct object_id *oid = &parent->item->object.oid;
5216 if (!oidset_contains(&interesting, oid))
5218 if (oidset_insert(&child_seen, oid))
5219 label_oid(oid, "branch-point", &state);
5222 /* Add HEAD as implicit "tip of branch" */
5224 tips_tail = &commit_list_insert(iter->item,
5229 * Third phase: output the todo list. This is a bit tricky, as we
5230 * want to avoid jumping back and forth between revisions. To
5231 * accomplish that goal, we walk backwards from the branch tips,
5232 * gathering commits not yet shown, reversing the list on the fly,
5233 * then outputting that list (labeling revisions as needed).
5235 strbuf_addf(out, "%s onto\n", cmd_label);
5236 for (iter = tips; iter; iter = iter->next) {
5237 struct commit_list *list = NULL, *iter2;
5239 commit = iter->item;
5240 if (oidset_contains(&shown, &commit->object.oid))
5242 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5245 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5247 strbuf_addch(out, '\n');
5249 while (oidset_contains(&interesting, &commit->object.oid) &&
5250 !oidset_contains(&shown, &commit->object.oid)) {
5251 commit_list_insert(commit, &list);
5252 if (!commit->parents) {
5256 commit = commit->parents->item;
5260 strbuf_addf(out, "%s %s\n", cmd_reset,
5261 rebase_cousins || root_with_onto ?
5262 "onto" : "[new root]");
5264 const char *to = NULL;
5266 entry = oidmap_get(&state.commit2label,
5267 &commit->object.oid);
5270 else if (!rebase_cousins)
5271 to = label_oid(&commit->object.oid, NULL,
5274 if (!to || !strcmp(to, "onto"))
5275 strbuf_addf(out, "%s onto\n", cmd_reset);
5277 strbuf_reset(&oneline);
5278 pretty_print_commit(pp, commit, &oneline);
5279 strbuf_addf(out, "%s %s # %s\n",
5280 cmd_reset, to, oneline.buf);
5284 for (iter2 = list; iter2; iter2 = iter2->next) {
5285 struct object_id *oid = &iter2->item->object.oid;
5286 entry = oidmap_get(&commit2todo, oid);
5287 /* only show if not already upstream */
5289 strbuf_addf(out, "%s\n", entry->string);
5290 entry = oidmap_get(&state.commit2label, oid);
5292 strbuf_addf(out, "%s %s\n",
5293 cmd_label, entry->string);
5294 oidset_insert(&shown, oid);
5297 free_commit_list(list);
5300 free_commit_list(commits);
5301 free_commit_list(tips);
5303 strbuf_release(&label);
5304 strbuf_release(&oneline);
5305 strbuf_release(&buf);
5307 oidmap_free(&commit2todo, 1);
5308 oidmap_free(&state.commit2label, 1);
5309 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5310 strbuf_release(&state.buf);
5315 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5316 const char **argv, unsigned flags)
5318 char *format = NULL;
5319 struct pretty_print_context pp = {0};
5320 struct rev_info revs;
5321 struct commit *commit;
5322 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5323 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5324 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5325 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5327 repo_init_revisions(r, &revs, NULL);
5328 revs.verbose_header = 1;
5330 revs.max_parents = 1;
5331 revs.cherry_mark = !reapply_cherry_picks;
5334 revs.right_only = 1;
5335 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5336 revs.topo_order = 1;
5338 revs.pretty_given = 1;
5339 git_config_get_string("rebase.instructionFormat", &format);
5340 if (!format || !*format) {
5342 format = xstrdup("%s");
5344 get_commit_format(format, &revs);
5346 pp.fmt = revs.commit_format;
5347 pp.output_encoding = get_log_output_encoding();
5349 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5350 return error(_("make_script: unhandled options"));
5352 if (prepare_revision_walk(&revs) < 0)
5353 return error(_("make_script: error preparing revisions"));
5356 return make_script_with_merges(&pp, &revs, out, flags);
5358 while ((commit = get_revision(&revs))) {
5359 int is_empty = is_original_commit_empty(commit);
5361 if (!is_empty && (commit->object.flags & PATCHSAME))
5363 if (is_empty && !keep_empty)
5365 strbuf_addf(out, "%s %s ", insn,
5366 oid_to_hex(&commit->object.oid));
5367 pretty_print_commit(&pp, commit, out);
5369 strbuf_addf(out, " %c empty", comment_line_char);
5370 strbuf_addch(out, '\n');
5376 * Add commands after pick and (series of) squash/fixup commands
5379 void todo_list_add_exec_commands(struct todo_list *todo_list,
5380 struct string_list *commands)
5382 struct strbuf *buf = &todo_list->buf;
5383 size_t base_offset = buf->len;
5384 int i, insert, nr = 0, alloc = 0;
5385 struct todo_item *items = NULL, *base_items = NULL;
5387 CALLOC_ARRAY(base_items, commands->nr);
5388 for (i = 0; i < commands->nr; i++) {
5389 size_t command_len = strlen(commands->items[i].string);
5391 strbuf_addstr(buf, commands->items[i].string);
5392 strbuf_addch(buf, '\n');
5394 base_items[i].command = TODO_EXEC;
5395 base_items[i].offset_in_buf = base_offset;
5396 base_items[i].arg_offset = base_offset + strlen("exec ");
5397 base_items[i].arg_len = command_len - strlen("exec ");
5399 base_offset += command_len + 1;
5403 * Insert <commands> after every pick. Here, fixup/squash chains
5404 * are considered part of the pick, so we insert the commands *after*
5405 * those chains if there are any.
5407 * As we insert the exec commands immediately after rearranging
5408 * any fixups and before the user edits the list, a fixup chain
5409 * can never contain comments (any comments are empty picks that
5410 * have been commented out because the user did not specify
5411 * --keep-empty). So, it is safe to insert an exec command
5412 * without looking at the command following a comment.
5415 for (i = 0; i < todo_list->nr; i++) {
5416 enum todo_command command = todo_list->items[i].command;
5417 if (insert && !is_fixup(command)) {
5418 ALLOC_GROW(items, nr + commands->nr, alloc);
5419 COPY_ARRAY(items + nr, base_items, commands->nr);
5425 ALLOC_GROW(items, nr + 1, alloc);
5426 items[nr++] = todo_list->items[i];
5428 if (command == TODO_PICK || command == TODO_MERGE)
5432 /* insert or append final <commands> */
5433 if (insert || nr == todo_list->nr) {
5434 ALLOC_GROW(items, nr + commands->nr, alloc);
5435 COPY_ARRAY(items + nr, base_items, commands->nr);
5440 FREE_AND_NULL(todo_list->items);
5441 todo_list->items = items;
5443 todo_list->alloc = alloc;
5446 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5447 struct strbuf *buf, int num, unsigned flags)
5449 struct todo_item *item;
5450 int i, max = todo_list->nr;
5452 if (num > 0 && num < max)
5455 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5458 /* if the item is not a command write it and continue */
5459 if (item->command >= TODO_COMMENT) {
5460 strbuf_addf(buf, "%.*s\n", item->arg_len,
5461 todo_item_get_arg(todo_list, item));
5465 /* add command to the buffer */
5466 cmd = command_to_char(item->command);
5467 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5468 strbuf_addch(buf, cmd);
5470 strbuf_addstr(buf, command_to_string(item->command));
5474 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5475 short_commit_name(item->commit) :
5476 oid_to_hex(&item->commit->object.oid);
5478 if (item->command == TODO_FIXUP) {
5479 if (item->flags & TODO_EDIT_FIXUP_MSG)
5480 strbuf_addstr(buf, " -c");
5481 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5482 strbuf_addstr(buf, " -C");
5486 if (item->command == TODO_MERGE) {
5487 if (item->flags & TODO_EDIT_MERGE_MSG)
5488 strbuf_addstr(buf, " -c");
5490 strbuf_addstr(buf, " -C");
5493 strbuf_addf(buf, " %s", oid);
5496 /* add all the rest */
5498 strbuf_addch(buf, '\n');
5500 strbuf_addf(buf, " %.*s\n", item->arg_len,
5501 todo_item_get_arg(todo_list, item));
5505 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5506 const char *file, const char *shortrevisions,
5507 const char *shortonto, int num, unsigned flags)
5510 struct strbuf buf = STRBUF_INIT;
5512 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5513 if (flags & TODO_LIST_APPEND_TODO_HELP)
5514 append_todo_help(count_commands(todo_list),
5515 shortrevisions, shortonto, &buf);
5517 res = write_message(buf.buf, buf.len, file, 0);
5518 strbuf_release(&buf);
5523 /* skip picking commits whose parents are unchanged */
5524 static int skip_unnecessary_picks(struct repository *r,
5525 struct todo_list *todo_list,
5526 struct object_id *base_oid)
5528 struct object_id *parent_oid;
5531 for (i = 0; i < todo_list->nr; i++) {
5532 struct todo_item *item = todo_list->items + i;
5534 if (item->command >= TODO_NOOP)
5536 if (item->command != TODO_PICK)
5538 if (parse_commit(item->commit)) {
5539 return error(_("could not parse commit '%s'"),
5540 oid_to_hex(&item->commit->object.oid));
5542 if (!item->commit->parents)
5543 break; /* root commit */
5544 if (item->commit->parents->next)
5545 break; /* merge commit */
5546 parent_oid = &item->commit->parents->item->object.oid;
5547 if (!oideq(parent_oid, base_oid))
5549 oidcpy(base_oid, &item->commit->object.oid);
5552 const char *done_path = rebase_path_done();
5554 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5555 error_errno(_("could not write to '%s'"), done_path);
5559 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5561 todo_list->current = 0;
5562 todo_list->done_nr += i;
5564 if (is_fixup(peek_command(todo_list, 0)))
5565 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5571 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5572 const char *shortrevisions, const char *onto_name,
5573 struct commit *onto, const struct object_id *orig_head,
5574 struct string_list *commands, unsigned autosquash,
5575 struct todo_list *todo_list)
5577 char shortonto[GIT_MAX_HEXSZ + 1];
5578 const char *todo_file = rebase_path_todo();
5579 struct todo_list new_todo = TODO_LIST_INIT;
5580 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5581 struct object_id oid = onto->object.oid;
5584 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5586 if (buf->len == 0) {
5587 struct todo_item *item = append_new_todo(todo_list);
5588 item->command = TODO_NOOP;
5589 item->commit = NULL;
5590 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5593 if (autosquash && todo_list_rearrange_squash(todo_list))
5597 todo_list_add_exec_commands(todo_list, commands);
5599 if (count_commands(todo_list) == 0) {
5600 apply_autostash(rebase_path_autostash());
5601 sequencer_remove_state(opts);
5603 return error(_("nothing to do"));
5606 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5610 else if (res == -2) {
5611 apply_autostash(rebase_path_autostash());
5612 sequencer_remove_state(opts);
5615 } else if (res == -3) {
5616 apply_autostash(rebase_path_autostash());
5617 sequencer_remove_state(opts);
5618 todo_list_release(&new_todo);
5620 return error(_("nothing to do"));
5621 } else if (res == -4) {
5622 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5623 todo_list_release(&new_todo);
5628 /* Expand the commit IDs */
5629 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5630 strbuf_swap(&new_todo.buf, &buf2);
5631 strbuf_release(&buf2);
5632 new_todo.total_nr -= new_todo.nr;
5633 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5634 BUG("invalid todo list after expanding IDs:\n%s",
5637 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5638 todo_list_release(&new_todo);
5639 return error(_("could not skip unnecessary pick commands"));
5642 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5643 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5644 todo_list_release(&new_todo);
5645 return error_errno(_("could not write '%s'"), todo_file);
5650 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5653 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5656 todo_list_write_total_nr(&new_todo);
5657 res = pick_commits(r, &new_todo, opts);
5660 todo_list_release(&new_todo);
5665 struct subject2item_entry {
5666 struct hashmap_entry entry;
5668 char subject[FLEX_ARRAY];
5671 static int subject2item_cmp(const void *fndata,
5672 const struct hashmap_entry *eptr,
5673 const struct hashmap_entry *entry_or_key,
5676 const struct subject2item_entry *a, *b;
5678 a = container_of(eptr, const struct subject2item_entry, entry);
5679 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5681 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5684 define_commit_slab(commit_todo_item, struct todo_item *);
5686 static int skip_fixupish(const char *subject, const char **p) {
5687 return skip_prefix(subject, "fixup! ", p) ||
5688 skip_prefix(subject, "amend! ", p) ||
5689 skip_prefix(subject, "squash! ", p);
5693 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5694 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5695 * after the former, and change "pick" to "fixup"/"squash".
5697 * Note that if the config has specified a custom instruction format, each log
5698 * message will have to be retrieved from the commit (as the oneline in the
5699 * script cannot be trusted) in order to normalize the autosquash arrangement.
5701 int todo_list_rearrange_squash(struct todo_list *todo_list)
5703 struct hashmap subject2item;
5704 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5706 struct commit_todo_item commit_todo;
5707 struct todo_item *items = NULL;
5709 init_commit_todo_item(&commit_todo);
5711 * The hashmap maps onelines to the respective todo list index.
5713 * If any items need to be rearranged, the next[i] value will indicate
5714 * which item was moved directly after the i'th.
5716 * In that case, last[i] will indicate the index of the latest item to
5717 * be moved to appear after the i'th.
5719 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5720 ALLOC_ARRAY(next, todo_list->nr);
5721 ALLOC_ARRAY(tail, todo_list->nr);
5722 ALLOC_ARRAY(subjects, todo_list->nr);
5723 for (i = 0; i < todo_list->nr; i++) {
5724 struct strbuf buf = STRBUF_INIT;
5725 struct todo_item *item = todo_list->items + i;
5726 const char *commit_buffer, *subject, *p;
5729 struct subject2item_entry *entry;
5731 next[i] = tail[i] = -1;
5732 if (!item->commit || item->command == TODO_DROP) {
5737 if (is_fixup(item->command)) {
5738 clear_commit_todo_item(&commit_todo);
5739 return error(_("the script was already rearranged."));
5742 *commit_todo_item_at(&commit_todo, item->commit) = item;
5744 parse_commit(item->commit);
5745 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5746 find_commit_subject(commit_buffer, &subject);
5747 format_subject(&buf, subject, " ");
5748 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5749 unuse_commit_buffer(item->commit, commit_buffer);
5750 if (skip_fixupish(subject, &p)) {
5751 struct commit *commit2;
5756 if (!skip_fixupish(p, &p))
5760 entry = hashmap_get_entry_from_hash(&subject2item,
5762 struct subject2item_entry,
5765 /* found by title */
5767 else if (!strchr(p, ' ') &&
5769 lookup_commit_reference_by_name(p)) &&
5770 *commit_todo_item_at(&commit_todo, commit2))
5771 /* found by commit name */
5772 i2 = *commit_todo_item_at(&commit_todo, commit2)
5775 /* copy can be a prefix of the commit subject */
5776 for (i2 = 0; i2 < i; i2++)
5778 starts_with(subjects[i2], p))
5786 if (starts_with(subject, "fixup!")) {
5787 todo_list->items[i].command = TODO_FIXUP;
5788 } else if (starts_with(subject, "amend!")) {
5789 todo_list->items[i].command = TODO_FIXUP;
5790 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5792 todo_list->items[i].command = TODO_SQUASH;
5798 next[i] = next[tail[i2]];
5802 } else if (!hashmap_get_from_hash(&subject2item,
5803 strhash(subject), subject)) {
5804 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5806 hashmap_entry_init(&entry->entry,
5807 strhash(entry->subject));
5808 hashmap_put(&subject2item, &entry->entry);
5813 for (i = 0; i < todo_list->nr; i++) {
5814 enum todo_command command = todo_list->items[i].command;
5818 * Initially, all commands are 'pick's. If it is a
5819 * fixup or a squash now, we have rearranged it.
5821 if (is_fixup(command))
5825 ALLOC_GROW(items, nr + 1, alloc);
5826 items[nr++] = todo_list->items[cur];
5831 FREE_AND_NULL(todo_list->items);
5832 todo_list->items = items;
5834 todo_list->alloc = alloc;
5839 for (i = 0; i < todo_list->nr; i++)
5842 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5844 clear_commit_todo_item(&commit_todo);
5849 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5851 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5852 struct object_id cherry_pick_head, rebase_head;
5854 if (file_exists(git_path_seq_dir()))
5855 *whence = FROM_CHERRY_PICK_MULTI;
5856 if (file_exists(rebase_path()) &&
5857 !get_oid("REBASE_HEAD", &rebase_head) &&
5858 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5859 oideq(&rebase_head, &cherry_pick_head))
5860 *whence = FROM_REBASE_PICK;
5862 *whence = FROM_CHERRY_PICK_SINGLE;