5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-recursive.h"
19 #include "argv-array.h"
23 #include "wt-status.h"
25 #include "notes-utils.h"
27 #include "unpack-trees.h"
31 #include "commit-slab.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
43 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
61 * The rebase command lines that have already been processed. A line
62 * is moved here when it is first handled, before any associated user
65 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
67 * The file to keep track of how many commands were already processed (e.g.
70 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
72 * The file to keep track of how many commands are to be processed in total
73 * (e.g. for the prompt).
75 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
77 * The commit message that is planned to be used for any changes that
78 * need to be committed following a user interaction.
80 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
82 * The file into which is accumulated the suggested commit message for
83 * squash/fixup commands. When the first of a series of squash/fixups
84 * is seen, the file is created and the commit message from the
85 * previous commit and from the first squash/fixup commit are written
86 * to it. The commit message for each subsequent squash/fixup commit
87 * is appended to the file as it is processed.
89 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
91 * If the current series of squash/fixups has not yet included a squash
92 * command, then this file exists and holds the commit message of the
93 * original "pick" commit. (If the series ends without a "squash"
94 * command, then this can be used as the commit message of the combined
95 * commit without opening the editor.)
97 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
99 * This file contains the list fixup/squash commands that have been
100 * accumulated into message-fixup or message-squash so far.
102 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
104 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
105 * GIT_AUTHOR_DATE that will be used for the commit that is currently
108 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
110 * When an "edit" rebase command is being processed, the SHA1 of the
111 * commit to be edited is recorded in this file. When "git rebase
112 * --continue" is executed, if there are any staged changes then they
113 * will be amended to the HEAD commit, but only provided the HEAD
114 * commit is still the commit to be edited. When any other rebase
115 * command is processed, this file is deleted.
117 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
119 * When we stop at a given patch via the "edit" command, this file contains
120 * the abbreviated commit name of the corresponding patch.
122 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
124 * For the post-rewrite hook, we make a list of rewritten commits and
125 * their new sha1s. The rewritten-pending list keeps the sha1s of
126 * commits that have been processed, but not committed yet,
127 * e.g. because they are waiting for a 'squash' command.
129 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
130 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
131 "rebase-merge/rewritten-pending")
134 * The path of the file containig the OID of the "squash onto" commit, i.e.
135 * the dummy commit used for `reset [new root]`.
137 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
140 * The path of the file listing refs that need to be deleted after the rebase
141 * finishes. This is used by the `label` command to record the need for cleanup.
143 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
146 * The following files are written by git-rebase just after parsing the
149 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
150 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
151 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
152 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
153 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
154 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
155 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
156 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
157 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
158 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
159 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
160 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
162 static int git_sequencer_config(const char *k, const char *v, void *cb)
164 struct replay_opts *opts = cb;
167 if (!strcmp(k, "commit.cleanup")) {
170 status = git_config_string(&s, k, v);
174 if (!strcmp(s, "verbatim"))
175 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
176 else if (!strcmp(s, "whitespace"))
177 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
178 else if (!strcmp(s, "strip"))
179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
180 else if (!strcmp(s, "scissors"))
181 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
183 warning(_("invalid commit message cleanup mode '%s'"),
190 if (!strcmp(k, "commit.gpgsign")) {
191 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
195 status = git_gpg_config(k, v, NULL);
199 return git_diff_basic_config(k, v, NULL);
202 void sequencer_init_config(struct replay_opts *opts)
204 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
205 git_config(git_sequencer_config, opts);
208 static inline int is_rebase_i(const struct replay_opts *opts)
210 return opts->action == REPLAY_INTERACTIVE_REBASE;
213 static const char *get_dir(const struct replay_opts *opts)
215 if (is_rebase_i(opts))
216 return rebase_path();
217 return git_path_seq_dir();
220 static const char *get_todo_path(const struct replay_opts *opts)
222 if (is_rebase_i(opts))
223 return rebase_path_todo();
224 return git_path_todo_file();
228 * Returns 0 for non-conforming footer
229 * Returns 1 for conforming footer
230 * Returns 2 when sob exists within conforming footer
231 * Returns 3 when sob exists within conforming footer as last entry
233 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
234 size_t ignore_footer)
236 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
237 struct trailer_info info;
239 int found_sob = 0, found_sob_last = 0;
243 trailer_info_get(&info, sb->buf, &opts);
245 if (info.trailer_start == info.trailer_end)
248 for (i = 0; i < info.trailer_nr; i++)
249 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
251 if (i == info.trailer_nr - 1)
255 trailer_info_release(&info);
264 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
266 static struct strbuf buf = STRBUF_INIT;
270 sq_quotef(&buf, "-S%s", opts->gpg_sign);
274 int sequencer_remove_state(struct replay_opts *opts)
276 struct strbuf buf = STRBUF_INIT;
279 if (is_rebase_i(opts) &&
280 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
283 char *eol = strchr(p, '\n');
286 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0) {
287 warning(_("could not delete '%s'"), p);
296 free(opts->gpg_sign);
297 free(opts->strategy);
298 for (i = 0; i < opts->xopts_nr; i++)
299 free(opts->xopts[i]);
301 strbuf_release(&opts->current_fixups);
304 strbuf_addstr(&buf, get_dir(opts));
305 if (remove_dir_recursively(&buf, 0))
306 ret = error(_("could not remove '%s'"), buf.buf);
307 strbuf_release(&buf);
312 static const char *action_name(const struct replay_opts *opts)
314 switch (opts->action) {
318 return N_("cherry-pick");
319 case REPLAY_INTERACTIVE_REBASE:
320 return N_("rebase -i");
322 die(_("unknown action: %d"), opts->action);
325 struct commit_message {
332 static const char *short_commit_name(struct commit *commit)
334 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
337 static int get_message(struct commit *commit, struct commit_message *out)
339 const char *abbrev, *subject;
342 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
343 abbrev = short_commit_name(commit);
345 subject_len = find_commit_subject(out->message, &subject);
347 out->subject = xmemdupz(subject, subject_len);
348 out->label = xstrfmt("%s... %s", abbrev, out->subject);
349 out->parent_label = xstrfmt("parent of %s", out->label);
354 static void free_message(struct commit *commit, struct commit_message *msg)
356 free(msg->parent_label);
359 unuse_commit_buffer(commit, msg->message);
362 static void print_advice(struct repository *r, int show_hint,
363 struct replay_opts *opts)
365 char *msg = getenv("GIT_CHERRY_PICK_HELP");
368 fprintf(stderr, "%s\n", msg);
370 * A conflict has occurred but the porcelain
371 * (typically rebase --interactive) wants to take care
372 * of the commit itself so remove CHERRY_PICK_HEAD
374 unlink(git_path_cherry_pick_head(r));
380 advise(_("after resolving the conflicts, mark the corrected paths\n"
381 "with 'git add <paths>' or 'git rm <paths>'"));
383 advise(_("after resolving the conflicts, mark the corrected paths\n"
384 "with 'git add <paths>' or 'git rm <paths>'\n"
385 "and commit the result with 'git commit'"));
389 static int write_message(const void *buf, size_t len, const char *filename,
392 struct lock_file msg_file = LOCK_INIT;
394 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
396 return error_errno(_("could not lock '%s'"), filename);
397 if (write_in_full(msg_fd, buf, len) < 0) {
398 error_errno(_("could not write to '%s'"), filename);
399 rollback_lock_file(&msg_file);
402 if (append_eol && write(msg_fd, "\n", 1) < 0) {
403 error_errno(_("could not write eol to '%s'"), filename);
404 rollback_lock_file(&msg_file);
407 if (commit_lock_file(&msg_file) < 0)
408 return error(_("failed to finalize '%s'"), filename);
414 * Reads a file that was presumably written by a shell script, i.e. with an
415 * end-of-line marker that needs to be stripped.
417 * Note that only the last end-of-line marker is stripped, consistent with the
418 * behavior of "$(cat path)" in a shell script.
420 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
422 static int read_oneliner(struct strbuf *buf,
423 const char *path, int skip_if_empty)
425 int orig_len = buf->len;
427 if (!file_exists(path))
430 if (strbuf_read_file(buf, path, 0) < 0) {
431 warning_errno(_("could not read '%s'"), path);
435 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
436 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
438 buf->buf[buf->len] = '\0';
441 if (skip_if_empty && buf->len == orig_len)
447 static struct tree *empty_tree(struct repository *r)
449 return lookup_tree(r, the_hash_algo->empty_tree);
452 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
454 if (repo_read_index_unmerged(repo))
455 return error_resolve_conflict(_(action_name(opts)));
457 error(_("your local changes would be overwritten by %s."),
458 _(action_name(opts)));
460 if (advice_commit_before_merge)
461 advise(_("commit your changes or stash them to proceed."));
465 static void update_abort_safety_file(void)
467 struct object_id head;
469 /* Do nothing on a single-pick */
470 if (!file_exists(git_path_seq_dir()))
473 if (!get_oid("HEAD", &head))
474 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
476 write_file(git_path_abort_safety_file(), "%s", "");
479 static int fast_forward_to(struct repository *r,
480 const struct object_id *to,
481 const struct object_id *from,
483 struct replay_opts *opts)
485 struct ref_transaction *transaction;
486 struct strbuf sb = STRBUF_INIT;
487 struct strbuf err = STRBUF_INIT;
490 if (checkout_fast_forward(r, from, to, 1))
491 return -1; /* the callee should have complained already */
493 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
495 transaction = ref_transaction_begin(&err);
497 ref_transaction_update(transaction, "HEAD",
498 to, unborn && !is_rebase_i(opts) ?
501 ref_transaction_commit(transaction, &err)) {
502 ref_transaction_free(transaction);
503 error("%s", err.buf);
505 strbuf_release(&err);
510 strbuf_release(&err);
511 ref_transaction_free(transaction);
512 update_abort_safety_file();
516 void append_conflicts_hint(struct index_state *istate,
517 struct strbuf *msgbuf)
521 strbuf_addch(msgbuf, '\n');
522 strbuf_commented_addf(msgbuf, "Conflicts:\n");
523 for (i = 0; i < istate->cache_nr;) {
524 const struct cache_entry *ce = istate->cache[i++];
526 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
527 while (i < istate->cache_nr &&
528 !strcmp(ce->name, istate->cache[i]->name))
534 static int do_recursive_merge(struct repository *r,
535 struct commit *base, struct commit *next,
536 const char *base_label, const char *next_label,
537 struct object_id *head, struct strbuf *msgbuf,
538 struct replay_opts *opts)
540 struct merge_options o;
541 struct tree *result, *next_tree, *base_tree, *head_tree;
544 struct lock_file index_lock = LOCK_INIT;
546 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
551 init_merge_options(&o, r);
552 o.ancestor = base ? base_label : "(empty tree)";
554 o.branch2 = next ? next_label : "(empty tree)";
555 if (is_rebase_i(opts))
557 o.show_rename_progress = 1;
559 head_tree = parse_tree_indirect(head);
560 next_tree = next ? get_commit_tree(next) : empty_tree(r);
561 base_tree = base ? get_commit_tree(base) : empty_tree(r);
563 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
564 parse_merge_opt(&o, *xopt);
566 clean = merge_trees(&o,
568 next_tree, base_tree, &result);
569 if (is_rebase_i(opts) && clean <= 0)
570 fputs(o.obuf.buf, stdout);
571 strbuf_release(&o.obuf);
572 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
574 rollback_lock_file(&index_lock);
578 if (write_locked_index(r->index, &index_lock,
579 COMMIT_LOCK | SKIP_IF_UNCHANGED))
581 * TRANSLATORS: %s will be "revert", "cherry-pick" or
584 return error(_("%s: Unable to write new index file"),
585 _(action_name(opts)));
588 append_conflicts_hint(r->index, msgbuf);
593 static struct object_id *get_cache_tree_oid(struct index_state *istate)
595 if (!istate->cache_tree)
596 istate->cache_tree = cache_tree();
598 if (!cache_tree_fully_valid(istate->cache_tree))
599 if (cache_tree_update(istate, 0)) {
600 error(_("unable to update cache tree"));
604 return &istate->cache_tree->oid;
607 static int is_index_unchanged(struct repository *r)
609 struct object_id head_oid, *cache_tree_oid;
610 struct commit *head_commit;
611 struct index_state *istate = r->index;
613 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
614 return error(_("could not resolve HEAD commit"));
616 head_commit = lookup_commit(r, &head_oid);
619 * If head_commit is NULL, check_commit, called from
620 * lookup_commit, would have indicated that head_commit is not
621 * a commit object already. parse_commit() will return failure
622 * without further complaints in such a case. Otherwise, if
623 * the commit is invalid, parse_commit() will complain. So
624 * there is nothing for us to say here. Just return failure.
626 if (parse_commit(head_commit))
629 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
632 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
635 static int write_author_script(const char *message)
637 struct strbuf buf = STRBUF_INIT;
642 if (!*message || starts_with(message, "\n")) {
644 /* Missing 'author' line? */
645 unlink(rebase_path_author_script());
647 } else if (skip_prefix(message, "author ", &message))
649 else if ((eol = strchr(message, '\n')))
654 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
655 while (*message && *message != '\n' && *message != '\r')
656 if (skip_prefix(message, " <", &message))
658 else if (*message != '\'')
659 strbuf_addch(&buf, *(message++));
661 strbuf_addf(&buf, "'\\%c'", *(message++));
662 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
663 while (*message && *message != '\n' && *message != '\r')
664 if (skip_prefix(message, "> ", &message))
666 else if (*message != '\'')
667 strbuf_addch(&buf, *(message++));
669 strbuf_addf(&buf, "'\\%c'", *(message++));
670 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
671 while (*message && *message != '\n' && *message != '\r')
672 if (*message != '\'')
673 strbuf_addch(&buf, *(message++));
675 strbuf_addf(&buf, "'\\%c'", *(message++));
676 strbuf_addch(&buf, '\'');
677 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
678 strbuf_release(&buf);
683 * Take a series of KEY='VALUE' lines where VALUE part is
684 * sq-quoted, and append <KEY, VALUE> at the end of the string list
686 static int parse_key_value_squoted(char *buf, struct string_list *list)
689 struct string_list_item *item;
691 char *cp = strchr(buf, '=');
693 np = strchrnul(buf, '\n');
694 return error(_("no key present in '%.*s'"),
695 (int) (np - buf), buf);
697 np = strchrnul(cp, '\n');
699 item = string_list_append(list, buf);
701 buf = np + (*np == '\n');
705 return error(_("unable to dequote value of '%s'"),
707 item->util = xstrdup(cp);
713 * Reads and parses the state directory's "author-script" file, and sets name,
714 * email and date accordingly.
715 * Returns 0 on success, -1 if the file could not be parsed.
717 * The author script is of the format:
719 * GIT_AUTHOR_NAME='$author_name'
720 * GIT_AUTHOR_EMAIL='$author_email'
721 * GIT_AUTHOR_DATE='$author_date'
723 * where $author_name, $author_email and $author_date are quoted. We are strict
724 * with our parsing, as the file was meant to be eval'd in the old
725 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
726 * from what this function expects, it is better to bail out than to do
727 * something that the user does not expect.
729 int read_author_script(const char *path, char **name, char **email, char **date,
732 struct strbuf buf = STRBUF_INIT;
733 struct string_list kv = STRING_LIST_INIT_DUP;
734 int retval = -1; /* assume failure */
735 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
737 if (strbuf_read_file(&buf, path, 256) <= 0) {
738 strbuf_release(&buf);
739 if (errno == ENOENT && allow_missing)
742 return error_errno(_("could not open '%s' for reading"),
746 if (parse_key_value_squoted(buf.buf, &kv))
749 for (i = 0; i < kv.nr; i++) {
750 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
752 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
755 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
757 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
760 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
762 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
766 err = error(_("unknown variable '%s'"),
771 error(_("missing 'GIT_AUTHOR_NAME'"));
773 error(_("missing 'GIT_AUTHOR_EMAIL'"));
775 error(_("missing 'GIT_AUTHOR_DATE'"));
776 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
778 *name = kv.items[name_i].util;
779 *email = kv.items[email_i].util;
780 *date = kv.items[date_i].util;
783 string_list_clear(&kv, !!retval);
784 strbuf_release(&buf);
789 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
790 * file with shell quoting into struct argv_array. Returns -1 on
791 * error, 0 otherwise.
793 static int read_env_script(struct argv_array *env)
795 char *name, *email, *date;
797 if (read_author_script(rebase_path_author_script(),
798 &name, &email, &date, 0))
801 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
802 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
803 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
811 static char *get_author(const char *message)
816 a = find_commit_header(message, "author", &len);
818 return xmemdupz(a, len);
823 /* Read author-script and return an ident line (author <email> timestamp) */
824 static const char *read_author_ident(struct strbuf *buf)
826 struct strbuf out = STRBUF_INIT;
827 char *name, *email, *date;
829 if (read_author_script(rebase_path_author_script(),
830 &name, &email, &date, 0))
833 /* validate date since fmt_ident() will die() on bad value */
834 if (parse_date(date, &out)){
835 warning(_("invalid date format '%s' in '%s'"),
836 date, rebase_path_author_script());
837 strbuf_release(&out);
842 strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
843 strbuf_swap(buf, &out);
844 strbuf_release(&out);
851 static const char staged_changes_advice[] =
852 N_("you have staged changes in your working tree\n"
853 "If these changes are meant to be squashed into the previous commit, run:\n"
855 " git commit --amend %s\n"
857 "If they are meant to go into a new commit, run:\n"
861 "In both cases, once you're done, continue with:\n"
863 " git rebase --continue\n");
865 #define ALLOW_EMPTY (1<<0)
866 #define EDIT_MSG (1<<1)
867 #define AMEND_MSG (1<<2)
868 #define CLEANUP_MSG (1<<3)
869 #define VERIFY_MSG (1<<4)
870 #define CREATE_ROOT_COMMIT (1<<5)
872 static int run_command_silent_on_success(struct child_process *cmd)
874 struct strbuf buf = STRBUF_INIT;
877 cmd->stdout_to_stderr = 1;
878 rc = pipe_command(cmd,
884 fputs(buf.buf, stderr);
885 strbuf_release(&buf);
890 * If we are cherry-pick, and if the merge did not result in
891 * hand-editing, we will hit this commit and inherit the original
892 * author date and name.
894 * If we are revert, or if our cherry-pick results in a hand merge,
895 * we had better say that the current user is responsible for that.
897 * An exception is when run_git_commit() is called during an
898 * interactive rebase: in that case, we will want to retain the
901 static int run_git_commit(struct repository *r,
903 struct replay_opts *opts,
906 struct child_process cmd = CHILD_PROCESS_INIT;
909 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
910 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
911 const char *author = NULL;
912 struct object_id root_commit, *cache_tree_oid;
915 if (is_rebase_i(opts)) {
916 author = read_author_ident(&script);
918 strbuf_release(&script);
924 BUG("root commit without message");
926 if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
930 res = strbuf_read_file(&msg, defmsg, 0);
933 res = error_errno(_("could not read '%s'"), defmsg);
935 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
936 NULL, &root_commit, author,
939 strbuf_release(&msg);
940 strbuf_release(&script);
942 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
943 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
944 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
945 UPDATE_REFS_MSG_ON_ERR);
947 return res < 0 ? error(_("writing root commit")) : 0;
952 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
953 const char *gpg_opt = gpg_sign_opt_quoted(opts);
955 return error(_(staged_changes_advice),
959 argv_array_push(&cmd.args, "commit");
961 if (!(flags & VERIFY_MSG))
962 argv_array_push(&cmd.args, "-n");
963 if ((flags & AMEND_MSG))
964 argv_array_push(&cmd.args, "--amend");
966 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
968 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
969 else if (!(flags & EDIT_MSG))
970 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
971 if ((flags & CLEANUP_MSG))
972 argv_array_push(&cmd.args, "--cleanup=strip");
973 if ((flags & EDIT_MSG))
974 argv_array_push(&cmd.args, "-e");
975 else if (!(flags & CLEANUP_MSG) &&
976 !opts->signoff && !opts->record_origin &&
977 git_config_get_value("commit.cleanup", &value))
978 argv_array_push(&cmd.args, "--cleanup=verbatim");
980 if ((flags & ALLOW_EMPTY))
981 argv_array_push(&cmd.args, "--allow-empty");
983 if (!(flags & EDIT_MSG))
984 argv_array_push(&cmd.args, "--allow-empty-message");
986 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
987 return run_command_silent_on_success(&cmd);
989 return run_command(&cmd);
992 static int rest_is_empty(const struct strbuf *sb, int start)
997 /* Check if the rest is just whitespace and Signed-off-by's. */
998 for (i = start; i < sb->len; i++) {
999 nl = memchr(sb->buf + i, '\n', sb->len - i);
1005 if (strlen(sign_off_header) <= eol - i &&
1006 starts_with(sb->buf + i, sign_off_header)) {
1011 if (!isspace(sb->buf[i++]))
1019 * Find out if the message in the strbuf contains only whitespace and
1020 * Signed-off-by lines.
1022 int message_is_empty(const struct strbuf *sb,
1023 enum commit_msg_cleanup_mode cleanup_mode)
1025 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1027 return rest_is_empty(sb, 0);
1031 * See if the user edited the message in the editor or left what
1032 * was in the template intact
1034 int template_untouched(const struct strbuf *sb, const char *template_file,
1035 enum commit_msg_cleanup_mode cleanup_mode)
1037 struct strbuf tmpl = STRBUF_INIT;
1040 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1043 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1046 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1047 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1049 strbuf_release(&tmpl);
1050 return rest_is_empty(sb, start - sb->buf);
1053 int update_head_with_reflog(const struct commit *old_head,
1054 const struct object_id *new_head,
1055 const char *action, const struct strbuf *msg,
1058 struct ref_transaction *transaction;
1059 struct strbuf sb = STRBUF_INIT;
1064 strbuf_addstr(&sb, action);
1065 strbuf_addstr(&sb, ": ");
1068 nl = strchr(msg->buf, '\n');
1070 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1072 strbuf_addbuf(&sb, msg);
1073 strbuf_addch(&sb, '\n');
1076 transaction = ref_transaction_begin(err);
1078 ref_transaction_update(transaction, "HEAD", new_head,
1079 old_head ? &old_head->object.oid : &null_oid,
1081 ref_transaction_commit(transaction, err)) {
1084 ref_transaction_free(transaction);
1085 strbuf_release(&sb);
1090 static int run_rewrite_hook(const struct object_id *oldoid,
1091 const struct object_id *newoid)
1093 struct child_process proc = CHILD_PROCESS_INIT;
1094 const char *argv[3];
1096 struct strbuf sb = STRBUF_INIT;
1098 argv[0] = find_hook("post-rewrite");
1107 proc.stdout_to_stderr = 1;
1108 proc.trace2_hook_name = "post-rewrite";
1110 code = start_command(&proc);
1113 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1114 sigchain_push(SIGPIPE, SIG_IGN);
1115 write_in_full(proc.in, sb.buf, sb.len);
1117 strbuf_release(&sb);
1118 sigchain_pop(SIGPIPE);
1119 return finish_command(&proc);
1122 void commit_post_rewrite(struct repository *r,
1123 const struct commit *old_head,
1124 const struct object_id *new_head)
1126 struct notes_rewrite_cfg *cfg;
1128 cfg = init_copy_notes_for_rewrite("amend");
1130 /* we are amending, so old_head is not NULL */
1131 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1132 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1134 run_rewrite_hook(&old_head->object.oid, new_head);
1137 static int run_prepare_commit_msg_hook(struct repository *r,
1141 struct argv_array hook_env = ARGV_ARRAY_INIT;
1145 name = git_path_commit_editmsg();
1146 if (write_message(msg->buf, msg->len, name, 0))
1149 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
1150 argv_array_push(&hook_env, "GIT_EDITOR=:");
1152 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1153 "commit", commit, NULL);
1155 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1158 ret = error(_("'prepare-commit-msg' hook failed"));
1159 argv_array_clear(&hook_env);
1164 static const char implicit_ident_advice_noconfig[] =
1165 N_("Your name and email address were configured automatically based\n"
1166 "on your username and hostname. Please check that they are accurate.\n"
1167 "You can suppress this message by setting them explicitly. Run the\n"
1168 "following command and follow the instructions in your editor to edit\n"
1169 "your configuration file:\n"
1171 " git config --global --edit\n"
1173 "After doing this, you may fix the identity used for this commit with:\n"
1175 " git commit --amend --reset-author\n");
1177 static const char implicit_ident_advice_config[] =
1178 N_("Your name and email address were configured automatically based\n"
1179 "on your username and hostname. Please check that they are accurate.\n"
1180 "You can suppress this message by setting them explicitly:\n"
1182 " git config --global user.name \"Your Name\"\n"
1183 " git config --global user.email you@example.com\n"
1185 "After doing this, you may fix the identity used for this commit with:\n"
1187 " git commit --amend --reset-author\n");
1189 static const char *implicit_ident_advice(void)
1191 char *user_config = expand_user_path("~/.gitconfig", 0);
1192 char *xdg_config = xdg_config_home("config");
1193 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1199 return _(implicit_ident_advice_config);
1201 return _(implicit_ident_advice_noconfig);
1205 void print_commit_summary(struct repository *r,
1207 const struct object_id *oid,
1210 struct rev_info rev;
1211 struct commit *commit;
1212 struct strbuf format = STRBUF_INIT;
1214 struct pretty_print_context pctx = {0};
1215 struct strbuf author_ident = STRBUF_INIT;
1216 struct strbuf committer_ident = STRBUF_INIT;
1218 commit = lookup_commit(r, oid);
1220 die(_("couldn't look up newly created commit"));
1221 if (parse_commit(commit))
1222 die(_("could not parse newly created commit"));
1224 strbuf_addstr(&format, "format:%h] %s");
1226 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1227 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1228 if (strbuf_cmp(&author_ident, &committer_ident)) {
1229 strbuf_addstr(&format, "\n Author: ");
1230 strbuf_addbuf_percentquote(&format, &author_ident);
1232 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1233 struct strbuf date = STRBUF_INIT;
1235 format_commit_message(commit, "%ad", &date, &pctx);
1236 strbuf_addstr(&format, "\n Date: ");
1237 strbuf_addbuf_percentquote(&format, &date);
1238 strbuf_release(&date);
1240 if (!committer_ident_sufficiently_given()) {
1241 strbuf_addstr(&format, "\n Committer: ");
1242 strbuf_addbuf_percentquote(&format, &committer_ident);
1243 if (advice_implicit_identity) {
1244 strbuf_addch(&format, '\n');
1245 strbuf_addstr(&format, implicit_ident_advice());
1248 strbuf_release(&author_ident);
1249 strbuf_release(&committer_ident);
1251 repo_init_revisions(r, &rev, prefix);
1252 setup_revisions(0, NULL, &rev, NULL);
1255 rev.diffopt.output_format =
1256 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1258 rev.verbose_header = 1;
1259 rev.show_root_diff = 1;
1260 get_commit_format(format.buf, &rev);
1261 rev.always_show_header = 0;
1262 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1263 rev.diffopt.break_opt = 0;
1264 diff_setup_done(&rev.diffopt);
1266 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1268 die_errno(_("unable to resolve HEAD after creating commit"));
1269 if (!strcmp(head, "HEAD"))
1270 head = _("detached HEAD");
1272 skip_prefix(head, "refs/heads/", &head);
1273 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1274 _(" (root-commit)") : "");
1276 if (!log_tree_commit(&rev, commit)) {
1277 rev.always_show_header = 1;
1278 rev.use_terminator = 1;
1279 log_tree_commit(&rev, commit);
1282 strbuf_release(&format);
1285 static int parse_head(struct repository *r, struct commit **head)
1287 struct commit *current_head;
1288 struct object_id oid;
1290 if (get_oid("HEAD", &oid)) {
1291 current_head = NULL;
1293 current_head = lookup_commit_reference(r, &oid);
1295 return error(_("could not parse HEAD"));
1296 if (!oideq(&oid, ¤t_head->object.oid)) {
1297 warning(_("HEAD %s is not a commit!"),
1300 if (parse_commit(current_head))
1301 return error(_("could not parse HEAD commit"));
1303 *head = current_head;
1309 * Try to commit without forking 'git commit'. In some cases we need
1310 * to run 'git commit' to display an error message
1313 * -1 - error unable to commit
1315 * 1 - run 'git commit'
1317 static int try_to_commit(struct repository *r,
1318 struct strbuf *msg, const char *author,
1319 struct replay_opts *opts, unsigned int flags,
1320 struct object_id *oid)
1322 struct object_id tree;
1323 struct commit *current_head;
1324 struct commit_list *parents = NULL;
1325 struct commit_extra_header *extra = NULL;
1326 struct strbuf err = STRBUF_INIT;
1327 struct strbuf commit_msg = STRBUF_INIT;
1328 char *amend_author = NULL;
1329 const char *hook_commit = NULL;
1330 enum commit_msg_cleanup_mode cleanup;
1333 if (parse_head(r, ¤t_head))
1336 if (flags & AMEND_MSG) {
1337 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1338 const char *out_enc = get_commit_output_encoding();
1339 const char *message = logmsg_reencode(current_head, NULL,
1343 const char *orig_message = NULL;
1345 find_commit_subject(message, &orig_message);
1347 strbuf_addstr(msg, orig_message);
1348 hook_commit = "HEAD";
1350 author = amend_author = get_author(message);
1351 unuse_commit_buffer(current_head, message);
1353 res = error(_("unable to parse commit author"));
1356 parents = copy_commit_list(current_head->parents);
1357 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1358 } else if (current_head) {
1359 commit_list_insert(current_head, &parents);
1362 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1363 res = error(_("git write-tree failed to write a tree"));
1367 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1368 get_commit_tree_oid(current_head) :
1369 the_hash_algo->empty_tree, &tree)) {
1370 res = 1; /* run 'git commit' to display error message */
1374 if (find_hook("prepare-commit-msg")) {
1375 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1378 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1380 res = error_errno(_("unable to read commit message "
1382 git_path_commit_editmsg());
1388 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1389 opts->default_msg_cleanup;
1391 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1392 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1393 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1394 res = 1; /* run 'git commit' to display error message */
1400 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1401 oid, author, opts->gpg_sign, extra)) {
1402 res = error(_("failed to write commit object"));
1406 if (update_head_with_reflog(current_head, oid,
1407 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1408 res = error("%s", err.buf);
1412 if (flags & AMEND_MSG)
1413 commit_post_rewrite(r, current_head, oid);
1416 free_commit_extra_headers(extra);
1417 strbuf_release(&err);
1418 strbuf_release(&commit_msg);
1424 static int do_commit(struct repository *r,
1425 const char *msg_file, const char *author,
1426 struct replay_opts *opts, unsigned int flags)
1430 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1431 !(flags & CREATE_ROOT_COMMIT)) {
1432 struct object_id oid;
1433 struct strbuf sb = STRBUF_INIT;
1435 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1436 return error_errno(_("unable to read commit message "
1440 res = try_to_commit(r, msg_file ? &sb : NULL,
1441 author, opts, flags, &oid);
1442 strbuf_release(&sb);
1444 unlink(git_path_cherry_pick_head(r));
1445 unlink(git_path_merge_msg(r));
1446 if (!is_rebase_i(opts))
1447 print_commit_summary(r, NULL, &oid,
1448 SUMMARY_SHOW_AUTHOR_DATE);
1453 return run_git_commit(r, msg_file, opts, flags);
1458 static int is_original_commit_empty(struct commit *commit)
1460 const struct object_id *ptree_oid;
1462 if (parse_commit(commit))
1463 return error(_("could not parse commit %s"),
1464 oid_to_hex(&commit->object.oid));
1465 if (commit->parents) {
1466 struct commit *parent = commit->parents->item;
1467 if (parse_commit(parent))
1468 return error(_("could not parse parent commit %s"),
1469 oid_to_hex(&parent->object.oid));
1470 ptree_oid = get_commit_tree_oid(parent);
1472 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1475 return oideq(ptree_oid, get_commit_tree_oid(commit));
1479 * Do we run "git commit" with "--allow-empty"?
1481 static int allow_empty(struct repository *r,
1482 struct replay_opts *opts,
1483 struct commit *commit)
1485 int index_unchanged, empty_commit;
1490 * (1) we do not allow empty at all and error out.
1492 * (2) we allow ones that were initially empty, but
1493 * forbid the ones that become empty;
1495 * (3) we allow both.
1497 if (!opts->allow_empty)
1498 return 0; /* let "git commit" barf as necessary */
1500 index_unchanged = is_index_unchanged(r);
1501 if (index_unchanged < 0)
1502 return index_unchanged;
1503 if (!index_unchanged)
1504 return 0; /* we do not have to say --allow-empty */
1506 if (opts->keep_redundant_commits)
1509 empty_commit = is_original_commit_empty(commit);
1510 if (empty_commit < 0)
1511 return empty_commit;
1521 } todo_command_info[] = {
1538 static const char *command_to_string(const enum todo_command command)
1540 if (command < TODO_COMMENT)
1541 return todo_command_info[command].str;
1542 die(_("unknown command: %d"), command);
1545 static char command_to_char(const enum todo_command command)
1547 if (command < TODO_COMMENT && todo_command_info[command].c)
1548 return todo_command_info[command].c;
1549 return comment_line_char;
1552 static int is_noop(const enum todo_command command)
1554 return TODO_NOOP <= command;
1557 static int is_fixup(enum todo_command command)
1559 return command == TODO_FIXUP || command == TODO_SQUASH;
1562 /* Does this command create a (non-merge) commit? */
1563 static int is_pick_or_similar(enum todo_command command)
1578 static int update_squash_messages(struct repository *r,
1579 enum todo_command command,
1580 struct commit *commit,
1581 struct replay_opts *opts)
1583 struct strbuf buf = STRBUF_INIT;
1585 const char *message, *body;
1587 if (opts->current_fixup_count > 0) {
1588 struct strbuf header = STRBUF_INIT;
1591 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1592 return error(_("could not read '%s'"),
1593 rebase_path_squash_msg());
1595 eol = buf.buf[0] != comment_line_char ?
1596 buf.buf : strchrnul(buf.buf, '\n');
1598 strbuf_addf(&header, "%c ", comment_line_char);
1599 strbuf_addf(&header, _("This is a combination of %d commits."),
1600 opts->current_fixup_count + 2);
1601 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1602 strbuf_release(&header);
1604 struct object_id head;
1605 struct commit *head_commit;
1606 const char *head_message, *body;
1608 if (get_oid("HEAD", &head))
1609 return error(_("need a HEAD to fixup"));
1610 if (!(head_commit = lookup_commit_reference(r, &head)))
1611 return error(_("could not read HEAD"));
1612 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1613 return error(_("could not read HEAD's commit message"));
1615 find_commit_subject(head_message, &body);
1616 if (write_message(body, strlen(body),
1617 rebase_path_fixup_msg(), 0)) {
1618 unuse_commit_buffer(head_commit, head_message);
1619 return error(_("cannot write '%s'"),
1620 rebase_path_fixup_msg());
1623 strbuf_addf(&buf, "%c ", comment_line_char);
1624 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1625 strbuf_addf(&buf, "\n%c ", comment_line_char);
1626 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1627 strbuf_addstr(&buf, "\n\n");
1628 strbuf_addstr(&buf, body);
1630 unuse_commit_buffer(head_commit, head_message);
1633 if (!(message = get_commit_buffer(commit, NULL)))
1634 return error(_("could not read commit message of %s"),
1635 oid_to_hex(&commit->object.oid));
1636 find_commit_subject(message, &body);
1638 if (command == TODO_SQUASH) {
1639 unlink(rebase_path_fixup_msg());
1640 strbuf_addf(&buf, "\n%c ", comment_line_char);
1641 strbuf_addf(&buf, _("This is the commit message #%d:"),
1642 ++opts->current_fixup_count + 1);
1643 strbuf_addstr(&buf, "\n\n");
1644 strbuf_addstr(&buf, body);
1645 } else if (command == TODO_FIXUP) {
1646 strbuf_addf(&buf, "\n%c ", comment_line_char);
1647 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1648 ++opts->current_fixup_count + 1);
1649 strbuf_addstr(&buf, "\n\n");
1650 strbuf_add_commented_lines(&buf, body, strlen(body));
1652 return error(_("unknown command: %d"), command);
1653 unuse_commit_buffer(commit, message);
1655 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1656 strbuf_release(&buf);
1659 strbuf_addf(&opts->current_fixups, "%s%s %s",
1660 opts->current_fixups.len ? "\n" : "",
1661 command_to_string(command),
1662 oid_to_hex(&commit->object.oid));
1663 res = write_message(opts->current_fixups.buf,
1664 opts->current_fixups.len,
1665 rebase_path_current_fixups(), 0);
1671 static void flush_rewritten_pending(void)
1673 struct strbuf buf = STRBUF_INIT;
1674 struct object_id newoid;
1677 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1678 !get_oid("HEAD", &newoid) &&
1679 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1680 char *bol = buf.buf, *eol;
1683 eol = strchrnul(bol, '\n');
1684 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1685 bol, oid_to_hex(&newoid));
1691 unlink(rebase_path_rewritten_pending());
1693 strbuf_release(&buf);
1696 static void record_in_rewritten(struct object_id *oid,
1697 enum todo_command next_command)
1699 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1704 fprintf(out, "%s\n", oid_to_hex(oid));
1707 if (!is_fixup(next_command))
1708 flush_rewritten_pending();
1711 static int do_pick_commit(struct repository *r,
1712 enum todo_command command,
1713 struct commit *commit,
1714 struct replay_opts *opts,
1717 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1718 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1719 struct object_id head;
1720 struct commit *base, *next, *parent;
1721 const char *base_label, *next_label;
1722 char *author = NULL;
1723 struct commit_message msg = { NULL, NULL, NULL, NULL };
1724 struct strbuf msgbuf = STRBUF_INIT;
1725 int res, unborn = 0, allow;
1727 if (opts->no_commit) {
1729 * We do not intend to commit immediately. We just want to
1730 * merge the differences in, so let's compute the tree
1731 * that represents the "current" state for merge-recursive
1734 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1735 return error(_("your index file is unmerged."));
1737 unborn = get_oid("HEAD", &head);
1738 /* Do we want to generate a root commit? */
1739 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1740 oideq(&head, &opts->squash_onto)) {
1741 if (is_fixup(command))
1742 return error(_("cannot fixup root commit"));
1743 flags |= CREATE_ROOT_COMMIT;
1746 oidcpy(&head, the_hash_algo->empty_tree);
1747 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1749 return error_dirty_index(r, opts);
1751 discard_index(r->index);
1753 if (!commit->parents)
1755 else if (commit->parents->next) {
1756 /* Reverting or cherry-picking a merge commit */
1758 struct commit_list *p;
1760 if (!opts->mainline)
1761 return error(_("commit %s is a merge but no -m option was given."),
1762 oid_to_hex(&commit->object.oid));
1764 for (cnt = 1, p = commit->parents;
1765 cnt != opts->mainline && p;
1768 if (cnt != opts->mainline || !p)
1769 return error(_("commit %s does not have parent %d"),
1770 oid_to_hex(&commit->object.oid), opts->mainline);
1772 } else if (1 < opts->mainline)
1774 * Non-first parent explicitly specified as mainline for
1777 return error(_("commit %s does not have parent %d"),
1778 oid_to_hex(&commit->object.oid), opts->mainline);
1780 parent = commit->parents->item;
1782 if (get_message(commit, &msg) != 0)
1783 return error(_("cannot get commit message for %s"),
1784 oid_to_hex(&commit->object.oid));
1786 if (opts->allow_ff && !is_fixup(command) &&
1787 ((parent && oideq(&parent->object.oid, &head)) ||
1788 (!parent && unborn))) {
1789 if (is_rebase_i(opts))
1790 write_author_script(msg.message);
1791 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1793 if (res || command != TODO_REWORD)
1795 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1797 goto fast_forward_edit;
1799 if (parent && parse_commit(parent) < 0)
1800 /* TRANSLATORS: The first %s will be a "todo" command like
1801 "revert" or "pick", the second %s a SHA1. */
1802 return error(_("%s: cannot parse parent commit %s"),
1803 command_to_string(command),
1804 oid_to_hex(&parent->object.oid));
1807 * "commit" is an existing commit. We would want to apply
1808 * the difference it introduces since its first parent "prev"
1809 * on top of the current HEAD if we are cherry-pick. Or the
1810 * reverse of it if we are revert.
1813 if (command == TODO_REVERT) {
1815 base_label = msg.label;
1817 next_label = msg.parent_label;
1818 strbuf_addstr(&msgbuf, "Revert \"");
1819 strbuf_addstr(&msgbuf, msg.subject);
1820 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1821 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1823 if (commit->parents && commit->parents->next) {
1824 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1825 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1827 strbuf_addstr(&msgbuf, ".\n");
1832 base_label = msg.parent_label;
1834 next_label = msg.label;
1836 /* Append the commit log message to msgbuf. */
1837 if (find_commit_subject(msg.message, &p))
1838 strbuf_addstr(&msgbuf, p);
1840 if (opts->record_origin) {
1841 strbuf_complete_line(&msgbuf);
1842 if (!has_conforming_footer(&msgbuf, NULL, 0))
1843 strbuf_addch(&msgbuf, '\n');
1844 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1845 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1846 strbuf_addstr(&msgbuf, ")\n");
1848 if (!is_fixup(command))
1849 author = get_author(msg.message);
1852 if (command == TODO_REWORD)
1853 flags |= EDIT_MSG | VERIFY_MSG;
1854 else if (is_fixup(command)) {
1855 if (update_squash_messages(r, command, commit, opts))
1859 msg_file = rebase_path_squash_msg();
1860 else if (file_exists(rebase_path_fixup_msg())) {
1861 flags |= CLEANUP_MSG;
1862 msg_file = rebase_path_fixup_msg();
1864 const char *dest = git_path_squash_msg(r);
1866 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1867 return error(_("could not rename '%s' to '%s'"),
1868 rebase_path_squash_msg(), dest);
1869 unlink(git_path_merge_msg(r));
1875 if (opts->signoff && !is_fixup(command))
1876 append_signoff(&msgbuf, 0, 0);
1878 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1880 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1881 res = do_recursive_merge(r, base, next, base_label, next_label,
1882 &head, &msgbuf, opts);
1886 res |= write_message(msgbuf.buf, msgbuf.len,
1887 git_path_merge_msg(r), 0);
1889 struct commit_list *common = NULL;
1890 struct commit_list *remotes = NULL;
1892 res = write_message(msgbuf.buf, msgbuf.len,
1893 git_path_merge_msg(r), 0);
1895 commit_list_insert(base, &common);
1896 commit_list_insert(next, &remotes);
1897 res |= try_merge_command(r, opts->strategy,
1898 opts->xopts_nr, (const char **)opts->xopts,
1899 common, oid_to_hex(&head), remotes);
1900 free_commit_list(common);
1901 free_commit_list(remotes);
1903 strbuf_release(&msgbuf);
1906 * If the merge was clean or if it failed due to conflict, we write
1907 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1908 * However, if the merge did not even start, then we don't want to
1911 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1912 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1913 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1915 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1916 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1917 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1921 error(command == TODO_REVERT
1922 ? _("could not revert %s... %s")
1923 : _("could not apply %s... %s"),
1924 short_commit_name(commit), msg.subject);
1925 print_advice(r, res == 1, opts);
1926 repo_rerere(r, opts->allow_rerere_auto);
1930 allow = allow_empty(r, opts, commit);
1935 flags |= ALLOW_EMPTY;
1936 if (!opts->no_commit) {
1938 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1939 res = do_commit(r, msg_file, author, opts, flags);
1941 res = error(_("unable to parse commit author"));
1944 if (!res && final_fixup) {
1945 unlink(rebase_path_fixup_msg());
1946 unlink(rebase_path_squash_msg());
1947 unlink(rebase_path_current_fixups());
1948 strbuf_reset(&opts->current_fixups);
1949 opts->current_fixup_count = 0;
1953 free_message(commit, &msg);
1955 update_abort_safety_file();
1960 static int prepare_revs(struct replay_opts *opts)
1963 * picking (but not reverting) ranges (but not individual revisions)
1964 * should be done in reverse
1966 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1967 opts->revs->reverse ^= 1;
1969 if (prepare_revision_walk(opts->revs))
1970 return error(_("revision walk setup failed"));
1975 static int read_and_refresh_cache(struct repository *r,
1976 struct replay_opts *opts)
1978 struct lock_file index_lock = LOCK_INIT;
1979 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
1980 if (repo_read_index(r) < 0) {
1981 rollback_lock_file(&index_lock);
1982 return error(_("git %s: failed to read the index"),
1983 _(action_name(opts)));
1985 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1986 if (index_fd >= 0) {
1987 if (write_locked_index(r->index, &index_lock,
1988 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1989 return error(_("git %s: failed to refresh the index"),
1990 _(action_name(opts)));
1996 enum todo_item_flags {
1997 TODO_EDIT_MERGE_MSG = 1
2000 void todo_list_release(struct todo_list *todo_list)
2002 strbuf_release(&todo_list->buf);
2003 FREE_AND_NULL(todo_list->items);
2004 todo_list->nr = todo_list->alloc = 0;
2007 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2009 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2010 return todo_list->items + todo_list->nr++;
2013 const char *todo_item_get_arg(struct todo_list *todo_list,
2014 struct todo_item *item)
2016 return todo_list->buf.buf + item->arg_offset;
2019 static int parse_insn_line(struct repository *r, struct todo_item *item,
2020 const char *buf, const char *bol, char *eol)
2022 struct object_id commit_oid;
2023 char *end_of_object_name;
2024 int i, saved, status, padding;
2029 bol += strspn(bol, " \t");
2031 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2032 item->command = TODO_COMMENT;
2033 item->commit = NULL;
2034 item->arg_offset = bol - buf;
2035 item->arg_len = eol - bol;
2039 for (i = 0; i < TODO_COMMENT; i++)
2040 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2043 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2044 *bol == todo_command_info[i].c) {
2049 if (i >= TODO_COMMENT)
2052 /* Eat up extra spaces/ tabs before object name */
2053 padding = strspn(bol, " \t");
2056 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2058 return error(_("%s does not accept arguments: '%s'"),
2059 command_to_string(item->command), bol);
2060 item->commit = NULL;
2061 item->arg_offset = bol - buf;
2062 item->arg_len = eol - bol;
2067 return error(_("missing arguments for %s"),
2068 command_to_string(item->command));
2070 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2071 item->command == TODO_RESET) {
2072 item->commit = NULL;
2073 item->arg_offset = bol - buf;
2074 item->arg_len = (int)(eol - bol);
2078 if (item->command == TODO_MERGE) {
2079 if (skip_prefix(bol, "-C", &bol))
2080 bol += strspn(bol, " \t");
2081 else if (skip_prefix(bol, "-c", &bol)) {
2082 bol += strspn(bol, " \t");
2083 item->flags |= TODO_EDIT_MERGE_MSG;
2085 item->flags |= TODO_EDIT_MERGE_MSG;
2086 item->commit = NULL;
2087 item->arg_offset = bol - buf;
2088 item->arg_len = (int)(eol - bol);
2093 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2094 saved = *end_of_object_name;
2095 *end_of_object_name = '\0';
2096 status = get_oid(bol, &commit_oid);
2097 *end_of_object_name = saved;
2099 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2100 item->arg_offset = bol - buf;
2101 item->arg_len = (int)(eol - bol);
2106 item->commit = lookup_commit_reference(r, &commit_oid);
2107 return !item->commit;
2110 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2111 struct todo_list *todo_list)
2113 struct todo_item *item;
2114 char *p = buf, *next_p;
2115 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2117 todo_list->current = todo_list->nr = 0;
2119 for (i = 1; *p; i++, p = next_p) {
2120 char *eol = strchrnul(p, '\n');
2122 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2124 if (p != eol && eol[-1] == '\r')
2125 eol--; /* strip Carriage Return */
2127 item = append_new_todo(todo_list);
2128 item->offset_in_buf = p - todo_list->buf.buf;
2129 if (parse_insn_line(r, item, buf, p, eol)) {
2130 res = error(_("invalid line %d: %.*s"),
2131 i, (int)(eol - p), p);
2132 item->command = TODO_COMMENT + 1;
2133 item->arg_offset = p - buf;
2134 item->arg_len = (int)(eol - p);
2135 item->commit = NULL;
2140 else if (is_fixup(item->command))
2141 return error(_("cannot '%s' without a previous commit"),
2142 command_to_string(item->command));
2143 else if (!is_noop(item->command))
2150 static int count_commands(struct todo_list *todo_list)
2154 for (i = 0; i < todo_list->nr; i++)
2155 if (todo_list->items[i].command != TODO_COMMENT)
2161 static int get_item_line_offset(struct todo_list *todo_list, int index)
2163 return index < todo_list->nr ?
2164 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2167 static const char *get_item_line(struct todo_list *todo_list, int index)
2169 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2172 static int get_item_line_length(struct todo_list *todo_list, int index)
2174 return get_item_line_offset(todo_list, index + 1)
2175 - get_item_line_offset(todo_list, index);
2178 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2183 fd = open(path, O_RDONLY);
2185 return error_errno(_("could not open '%s'"), path);
2186 len = strbuf_read(sb, fd, 0);
2189 return error(_("could not read '%s'."), path);
2193 static int read_populate_todo(struct repository *r,
2194 struct todo_list *todo_list,
2195 struct replay_opts *opts)
2198 const char *todo_file = get_todo_path(opts);
2201 strbuf_reset(&todo_list->buf);
2202 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2205 res = stat(todo_file, &st);
2207 return error(_("could not stat '%s'"), todo_file);
2208 fill_stat_data(&todo_list->stat, &st);
2210 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2212 if (is_rebase_i(opts))
2213 return error(_("please fix this using "
2214 "'git rebase --edit-todo'."));
2215 return error(_("unusable instruction sheet: '%s'"), todo_file);
2218 if (!todo_list->nr &&
2219 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2220 return error(_("no commits parsed."));
2222 if (!is_rebase_i(opts)) {
2223 enum todo_command valid =
2224 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2227 for (i = 0; i < todo_list->nr; i++)
2228 if (valid == todo_list->items[i].command)
2230 else if (valid == TODO_PICK)
2231 return error(_("cannot cherry-pick during a revert."));
2233 return error(_("cannot revert during a cherry-pick."));
2236 if (is_rebase_i(opts)) {
2237 struct todo_list done = TODO_LIST_INIT;
2238 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2240 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2241 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2242 todo_list->done_nr = count_commands(&done);
2244 todo_list->done_nr = 0;
2246 todo_list->total_nr = todo_list->done_nr
2247 + count_commands(todo_list);
2248 todo_list_release(&done);
2251 fprintf(f, "%d\n", todo_list->total_nr);
2259 static int git_config_string_dup(char **dest,
2260 const char *var, const char *value)
2263 return config_error_nonbool(var);
2265 *dest = xstrdup(value);
2269 static int populate_opts_cb(const char *key, const char *value, void *data)
2271 struct replay_opts *opts = data;
2276 else if (!strcmp(key, "options.no-commit"))
2277 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2278 else if (!strcmp(key, "options.edit"))
2279 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2280 else if (!strcmp(key, "options.signoff"))
2281 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2282 else if (!strcmp(key, "options.record-origin"))
2283 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2284 else if (!strcmp(key, "options.allow-ff"))
2285 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2286 else if (!strcmp(key, "options.mainline"))
2287 opts->mainline = git_config_int(key, value);
2288 else if (!strcmp(key, "options.strategy"))
2289 git_config_string_dup(&opts->strategy, key, value);
2290 else if (!strcmp(key, "options.gpg-sign"))
2291 git_config_string_dup(&opts->gpg_sign, key, value);
2292 else if (!strcmp(key, "options.strategy-option")) {
2293 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2294 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2295 } else if (!strcmp(key, "options.allow-rerere-auto"))
2296 opts->allow_rerere_auto =
2297 git_config_bool_or_int(key, value, &error_flag) ?
2298 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2300 return error(_("invalid key: %s"), key);
2303 return error(_("invalid value for %s: %s"), key, value);
2308 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2311 char *strategy_opts_string = raw_opts;
2313 if (*strategy_opts_string == ' ')
2314 strategy_opts_string++;
2316 opts->xopts_nr = split_cmdline(strategy_opts_string,
2317 (const char ***)&opts->xopts);
2318 for (i = 0; i < opts->xopts_nr; i++) {
2319 const char *arg = opts->xopts[i];
2321 skip_prefix(arg, "--", &arg);
2322 opts->xopts[i] = xstrdup(arg);
2326 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2329 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2331 opts->strategy = strbuf_detach(buf, NULL);
2332 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2335 parse_strategy_opts(opts, buf->buf);
2338 static int read_populate_opts(struct replay_opts *opts)
2340 if (is_rebase_i(opts)) {
2341 struct strbuf buf = STRBUF_INIT;
2343 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2344 if (!starts_with(buf.buf, "-S"))
2347 free(opts->gpg_sign);
2348 opts->gpg_sign = xstrdup(buf.buf + 2);
2353 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2354 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2355 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2356 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2357 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2361 if (file_exists(rebase_path_verbose()))
2364 if (file_exists(rebase_path_quiet()))
2367 if (file_exists(rebase_path_signoff())) {
2372 if (file_exists(rebase_path_reschedule_failed_exec()))
2373 opts->reschedule_failed_exec = 1;
2375 read_strategy_opts(opts, &buf);
2376 strbuf_release(&buf);
2378 if (read_oneliner(&opts->current_fixups,
2379 rebase_path_current_fixups(), 1)) {
2380 const char *p = opts->current_fixups.buf;
2381 opts->current_fixup_count = 1;
2382 while ((p = strchr(p, '\n'))) {
2383 opts->current_fixup_count++;
2388 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2389 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2390 return error(_("unusable squash-onto"));
2391 opts->have_squash_onto = 1;
2397 if (!file_exists(git_path_opts_file()))
2400 * The function git_parse_source(), called from git_config_from_file(),
2401 * may die() in case of a syntactically incorrect file. We do not care
2402 * about this case, though, because we wrote that file ourselves, so we
2403 * are pretty certain that it is syntactically correct.
2405 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2406 return error(_("malformed options sheet: '%s'"),
2407 git_path_opts_file());
2411 static void write_strategy_opts(struct replay_opts *opts)
2414 struct strbuf buf = STRBUF_INIT;
2416 for (i = 0; i < opts->xopts_nr; ++i)
2417 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2419 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2420 strbuf_release(&buf);
2423 int write_basic_state(struct replay_opts *opts, const char *head_name,
2424 struct commit *onto, const char *orig_head)
2426 const char *quiet = getenv("GIT_QUIET");
2429 write_file(rebase_path_head_name(), "%s\n", head_name);
2431 write_file(rebase_path_onto(), "%s\n",
2432 oid_to_hex(&onto->object.oid));
2434 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2437 write_file(rebase_path_quiet(), "%s\n", quiet);
2439 write_file(rebase_path_verbose(), "%s", "");
2441 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2442 if (opts->xopts_nr > 0)
2443 write_strategy_opts(opts);
2445 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2446 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2447 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2448 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2451 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2453 write_file(rebase_path_signoff(), "--signoff\n");
2454 if (opts->reschedule_failed_exec)
2455 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2460 static int walk_revs_populate_todo(struct todo_list *todo_list,
2461 struct replay_opts *opts)
2463 enum todo_command command = opts->action == REPLAY_PICK ?
2464 TODO_PICK : TODO_REVERT;
2465 const char *command_string = todo_command_info[command].str;
2466 struct commit *commit;
2468 if (prepare_revs(opts))
2471 while ((commit = get_revision(opts->revs))) {
2472 struct todo_item *item = append_new_todo(todo_list);
2473 const char *commit_buffer = get_commit_buffer(commit, NULL);
2474 const char *subject;
2477 item->command = command;
2478 item->commit = commit;
2479 item->arg_offset = 0;
2481 item->offset_in_buf = todo_list->buf.len;
2482 subject_len = find_commit_subject(commit_buffer, &subject);
2483 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2484 short_commit_name(commit), subject_len, subject);
2485 unuse_commit_buffer(commit, commit_buffer);
2489 return error(_("empty commit set passed"));
2494 static int create_seq_dir(void)
2496 if (file_exists(git_path_seq_dir())) {
2497 error(_("a cherry-pick or revert is already in progress"));
2498 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2500 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2501 return error_errno(_("could not create sequencer directory '%s'"),
2502 git_path_seq_dir());
2506 static int save_head(const char *head)
2508 struct lock_file head_lock = LOCK_INIT;
2509 struct strbuf buf = STRBUF_INIT;
2513 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2515 return error_errno(_("could not lock HEAD"));
2516 strbuf_addf(&buf, "%s\n", head);
2517 written = write_in_full(fd, buf.buf, buf.len);
2518 strbuf_release(&buf);
2520 error_errno(_("could not write to '%s'"), git_path_head_file());
2521 rollback_lock_file(&head_lock);
2524 if (commit_lock_file(&head_lock) < 0)
2525 return error(_("failed to finalize '%s'"), git_path_head_file());
2529 static int rollback_is_safe(void)
2531 struct strbuf sb = STRBUF_INIT;
2532 struct object_id expected_head, actual_head;
2534 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2536 if (get_oid_hex(sb.buf, &expected_head)) {
2537 strbuf_release(&sb);
2538 die(_("could not parse %s"), git_path_abort_safety_file());
2540 strbuf_release(&sb);
2542 else if (errno == ENOENT)
2543 oidclr(&expected_head);
2545 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2547 if (get_oid("HEAD", &actual_head))
2548 oidclr(&actual_head);
2550 return oideq(&actual_head, &expected_head);
2553 static int reset_for_rollback(const struct object_id *oid)
2555 const char *argv[4]; /* reset --merge <arg> + NULL */
2558 argv[1] = "--merge";
2559 argv[2] = oid_to_hex(oid);
2561 return run_command_v_opt(argv, RUN_GIT_CMD);
2564 static int rollback_single_pick(struct repository *r)
2566 struct object_id head_oid;
2568 if (!file_exists(git_path_cherry_pick_head(r)) &&
2569 !file_exists(git_path_revert_head(r)))
2570 return error(_("no cherry-pick or revert in progress"));
2571 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2572 return error(_("cannot resolve HEAD"));
2573 if (is_null_oid(&head_oid))
2574 return error(_("cannot abort from a branch yet to be born"));
2575 return reset_for_rollback(&head_oid);
2578 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2581 struct object_id oid;
2582 struct strbuf buf = STRBUF_INIT;
2585 f = fopen(git_path_head_file(), "r");
2586 if (!f && errno == ENOENT) {
2588 * There is no multiple-cherry-pick in progress.
2589 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2590 * a single-cherry-pick in progress, abort that.
2592 return rollback_single_pick(r);
2595 return error_errno(_("cannot open '%s'"), git_path_head_file());
2596 if (strbuf_getline_lf(&buf, f)) {
2597 error(_("cannot read '%s': %s"), git_path_head_file(),
2598 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2603 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2604 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2605 git_path_head_file());
2608 if (is_null_oid(&oid)) {
2609 error(_("cannot abort from a branch yet to be born"));
2613 if (!rollback_is_safe()) {
2614 /* Do not error, just do not rollback */
2615 warning(_("You seem to have moved HEAD. "
2616 "Not rewinding, check your HEAD!"));
2618 if (reset_for_rollback(&oid))
2620 strbuf_release(&buf);
2621 return sequencer_remove_state(opts);
2623 strbuf_release(&buf);
2627 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2629 struct lock_file todo_lock = LOCK_INIT;
2630 const char *todo_path = get_todo_path(opts);
2631 int next = todo_list->current, offset, fd;
2634 * rebase -i writes "git-rebase-todo" without the currently executing
2635 * command, appending it to "done" instead.
2637 if (is_rebase_i(opts))
2640 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2642 return error_errno(_("could not lock '%s'"), todo_path);
2643 offset = get_item_line_offset(todo_list, next);
2644 if (write_in_full(fd, todo_list->buf.buf + offset,
2645 todo_list->buf.len - offset) < 0)
2646 return error_errno(_("could not write to '%s'"), todo_path);
2647 if (commit_lock_file(&todo_lock) < 0)
2648 return error(_("failed to finalize '%s'"), todo_path);
2650 if (is_rebase_i(opts) && next > 0) {
2651 const char *done = rebase_path_done();
2652 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2657 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2658 get_item_line_length(todo_list, next - 1))
2660 ret = error_errno(_("could not write to '%s'"), done);
2662 ret = error_errno(_("failed to finalize '%s'"), done);
2668 static int save_opts(struct replay_opts *opts)
2670 const char *opts_file = git_path_opts_file();
2673 if (opts->no_commit)
2674 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2676 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2678 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2679 if (opts->record_origin)
2680 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2682 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2683 if (opts->mainline) {
2684 struct strbuf buf = STRBUF_INIT;
2685 strbuf_addf(&buf, "%d", opts->mainline);
2686 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2687 strbuf_release(&buf);
2690 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2692 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2695 for (i = 0; i < opts->xopts_nr; i++)
2696 res |= git_config_set_multivar_in_file_gently(opts_file,
2697 "options.strategy-option",
2698 opts->xopts[i], "^$", 0);
2700 if (opts->allow_rerere_auto)
2701 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2702 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2707 static int make_patch(struct repository *r,
2708 struct commit *commit,
2709 struct replay_opts *opts)
2711 struct strbuf buf = STRBUF_INIT;
2712 struct rev_info log_tree_opt;
2713 const char *subject, *p;
2716 p = short_commit_name(commit);
2717 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2719 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2720 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2721 res |= error(_("could not update %s"), "REBASE_HEAD");
2723 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2724 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2725 repo_init_revisions(r, &log_tree_opt, NULL);
2726 log_tree_opt.abbrev = 0;
2727 log_tree_opt.diff = 1;
2728 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2729 log_tree_opt.disable_stdin = 1;
2730 log_tree_opt.no_commit_id = 1;
2731 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2732 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2733 if (!log_tree_opt.diffopt.file)
2734 res |= error_errno(_("could not open '%s'"), buf.buf);
2736 res |= log_tree_commit(&log_tree_opt, commit);
2737 fclose(log_tree_opt.diffopt.file);
2741 strbuf_addf(&buf, "%s/message", get_dir(opts));
2742 if (!file_exists(buf.buf)) {
2743 const char *commit_buffer = get_commit_buffer(commit, NULL);
2744 find_commit_subject(commit_buffer, &subject);
2745 res |= write_message(subject, strlen(subject), buf.buf, 1);
2746 unuse_commit_buffer(commit, commit_buffer);
2748 strbuf_release(&buf);
2753 static int intend_to_amend(void)
2755 struct object_id head;
2758 if (get_oid("HEAD", &head))
2759 return error(_("cannot read HEAD"));
2761 p = oid_to_hex(&head);
2762 return write_message(p, strlen(p), rebase_path_amend(), 1);
2765 static int error_with_patch(struct repository *r,
2766 struct commit *commit,
2767 const char *subject, int subject_len,
2768 struct replay_opts *opts,
2769 int exit_code, int to_amend)
2772 if (make_patch(r, commit, opts))
2774 } else if (copy_file(rebase_path_message(),
2775 git_path_merge_msg(r), 0666))
2776 return error(_("unable to copy '%s' to '%s'"),
2777 git_path_merge_msg(r), rebase_path_message());
2780 if (intend_to_amend())
2784 _("You can amend the commit now, with\n"
2786 " git commit --amend %s\n"
2788 "Once you are satisfied with your changes, run\n"
2790 " git rebase --continue\n"),
2791 gpg_sign_opt_quoted(opts));
2792 } else if (exit_code) {
2794 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2795 short_commit_name(commit), subject_len, subject);
2798 * We don't have the hash of the parent so
2799 * just print the line from the todo file.
2801 fprintf_ln(stderr, _("Could not merge %.*s"),
2802 subject_len, subject);
2808 static int error_failed_squash(struct repository *r,
2809 struct commit *commit,
2810 struct replay_opts *opts,
2812 const char *subject)
2814 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2815 return error(_("could not copy '%s' to '%s'"),
2816 rebase_path_squash_msg(), rebase_path_message());
2817 unlink(git_path_merge_msg(r));
2818 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
2819 return error(_("could not copy '%s' to '%s'"),
2820 rebase_path_message(),
2821 git_path_merge_msg(r));
2822 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
2825 static int do_exec(struct repository *r, const char *command_line)
2827 struct argv_array child_env = ARGV_ARRAY_INIT;
2828 const char *child_argv[] = { NULL, NULL };
2831 fprintf(stderr, "Executing: %s\n", command_line);
2832 child_argv[0] = command_line;
2833 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2834 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2835 absolute_path(get_git_work_tree()));
2836 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2839 /* force re-reading of the cache */
2840 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
2841 return error(_("could not read index"));
2843 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
2846 warning(_("execution failed: %s\n%s"
2847 "You can fix the problem, and then run\n"
2849 " git rebase --continue\n"
2852 dirty ? N_("and made changes to the index and/or the "
2853 "working tree\n") : "");
2855 /* command not found */
2858 warning(_("execution succeeded: %s\nbut "
2859 "left changes to the index and/or the working tree\n"
2860 "Commit or stash your changes, and then run\n"
2862 " git rebase --continue\n"
2863 "\n"), command_line);
2867 argv_array_clear(&child_env);
2872 static int safe_append(const char *filename, const char *fmt, ...)
2875 struct lock_file lock = LOCK_INIT;
2876 int fd = hold_lock_file_for_update(&lock, filename,
2877 LOCK_REPORT_ON_ERROR);
2878 struct strbuf buf = STRBUF_INIT;
2883 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2884 error_errno(_("could not read '%s'"), filename);
2885 rollback_lock_file(&lock);
2888 strbuf_complete(&buf, '\n');
2890 strbuf_vaddf(&buf, fmt, ap);
2893 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2894 error_errno(_("could not write to '%s'"), filename);
2895 strbuf_release(&buf);
2896 rollback_lock_file(&lock);
2899 if (commit_lock_file(&lock) < 0) {
2900 strbuf_release(&buf);
2901 rollback_lock_file(&lock);
2902 return error(_("failed to finalize '%s'"), filename);
2905 strbuf_release(&buf);
2909 static int do_label(struct repository *r, const char *name, int len)
2911 struct ref_store *refs = get_main_ref_store(r);
2912 struct ref_transaction *transaction;
2913 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2914 struct strbuf msg = STRBUF_INIT;
2916 struct object_id head_oid;
2918 if (len == 1 && *name == '#')
2919 return error(_("illegal label name: '%.*s'"), len, name);
2921 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2922 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2924 transaction = ref_store_transaction_begin(refs, &err);
2926 error("%s", err.buf);
2928 } else if (get_oid("HEAD", &head_oid)) {
2929 error(_("could not read HEAD"));
2931 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2932 NULL, 0, msg.buf, &err) < 0 ||
2933 ref_transaction_commit(transaction, &err)) {
2934 error("%s", err.buf);
2937 ref_transaction_free(transaction);
2938 strbuf_release(&err);
2939 strbuf_release(&msg);
2942 ret = safe_append(rebase_path_refs_to_delete(),
2943 "%s\n", ref_name.buf);
2944 strbuf_release(&ref_name);
2949 static const char *reflog_message(struct replay_opts *opts,
2950 const char *sub_action, const char *fmt, ...);
2952 static int do_reset(struct repository *r,
2953 const char *name, int len,
2954 struct replay_opts *opts)
2956 struct strbuf ref_name = STRBUF_INIT;
2957 struct object_id oid;
2958 struct lock_file lock = LOCK_INIT;
2959 struct tree_desc desc;
2961 struct unpack_trees_options unpack_tree_opts;
2964 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
2967 if (len == 10 && !strncmp("[new root]", name, len)) {
2968 if (!opts->have_squash_onto) {
2970 if (commit_tree("", 0, the_hash_algo->empty_tree,
2971 NULL, &opts->squash_onto,
2973 return error(_("writing fake root commit"));
2974 opts->have_squash_onto = 1;
2975 hex = oid_to_hex(&opts->squash_onto);
2976 if (write_message(hex, strlen(hex),
2977 rebase_path_squash_onto(), 0))
2978 return error(_("writing squash-onto"));
2980 oidcpy(&oid, &opts->squash_onto);
2984 /* Determine the length of the label */
2985 for (i = 0; i < len; i++)
2986 if (isspace(name[i]))
2990 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2991 if (get_oid(ref_name.buf, &oid) &&
2992 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2993 error(_("could not read '%s'"), ref_name.buf);
2994 rollback_lock_file(&lock);
2995 strbuf_release(&ref_name);
3000 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3001 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3002 unpack_tree_opts.head_idx = 1;
3003 unpack_tree_opts.src_index = r->index;
3004 unpack_tree_opts.dst_index = r->index;
3005 unpack_tree_opts.fn = oneway_merge;
3006 unpack_tree_opts.merge = 1;
3007 unpack_tree_opts.update = 1;
3009 if (repo_read_index_unmerged(r)) {
3010 rollback_lock_file(&lock);
3011 strbuf_release(&ref_name);
3012 return error_resolve_conflict(_(action_name(opts)));
3015 if (!fill_tree_descriptor(&desc, &oid)) {
3016 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3017 rollback_lock_file(&lock);
3018 free((void *)desc.buffer);
3019 strbuf_release(&ref_name);
3023 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3024 rollback_lock_file(&lock);
3025 free((void *)desc.buffer);
3026 strbuf_release(&ref_name);
3030 tree = parse_tree_indirect(&oid);
3031 prime_cache_tree(r, r->index, tree);
3033 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3034 ret = error(_("could not write index"));
3035 free((void *)desc.buffer);
3038 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3039 len, name), "HEAD", &oid,
3040 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3042 strbuf_release(&ref_name);
3046 static struct commit *lookup_label(const char *label, int len,
3049 struct commit *commit;
3052 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3053 commit = lookup_commit_reference_by_name(buf->buf);
3055 /* fall back to non-rewritten ref or commit */
3056 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3057 commit = lookup_commit_reference_by_name(buf->buf);
3061 error(_("could not resolve '%s'"), buf->buf);
3066 static int do_merge(struct repository *r,
3067 struct commit *commit,
3068 const char *arg, int arg_len,
3069 int flags, struct replay_opts *opts)
3071 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3072 EDIT_MSG | VERIFY_MSG : 0;
3073 struct strbuf ref_name = STRBUF_INIT;
3074 struct commit *head_commit, *merge_commit, *i;
3075 struct commit_list *bases, *j, *reversed = NULL;
3076 struct commit_list *to_merge = NULL, **tail = &to_merge;
3077 struct merge_options o;
3078 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3079 static struct lock_file lock;
3082 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3087 head_commit = lookup_commit_reference_by_name("HEAD");
3089 ret = error(_("cannot merge without a current revision"));
3094 * For octopus merges, the arg starts with the list of revisions to be
3095 * merged. The list is optionally followed by '#' and the oneline.
3097 merge_arg_len = oneline_offset = arg_len;
3098 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3101 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3102 p += 1 + strspn(p + 1, " \t\n");
3103 oneline_offset = p - arg;
3106 k = strcspn(p, " \t\n");
3109 merge_commit = lookup_label(p, k, &ref_name);
3110 if (!merge_commit) {
3111 ret = error(_("unable to parse '%.*s'"), k, p);
3114 tail = &commit_list_insert(merge_commit, tail)->next;
3116 merge_arg_len = p - arg;
3120 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3124 if (opts->have_squash_onto &&
3125 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3127 * When the user tells us to "merge" something into a
3128 * "[new root]", let's simply fast-forward to the merge head.
3130 rollback_lock_file(&lock);
3132 ret = error(_("octopus merge cannot be executed on "
3133 "top of a [new root]"));
3135 ret = fast_forward_to(r, &to_merge->item->object.oid,
3136 &head_commit->object.oid, 0,
3142 const char *message = get_commit_buffer(commit, NULL);
3147 ret = error(_("could not get commit message of '%s'"),
3148 oid_to_hex(&commit->object.oid));
3151 write_author_script(message);
3152 find_commit_subject(message, &body);
3154 ret = write_message(body, len, git_path_merge_msg(r), 0);
3155 unuse_commit_buffer(commit, message);
3157 error_errno(_("could not write '%s'"),
3158 git_path_merge_msg(r));
3162 struct strbuf buf = STRBUF_INIT;
3165 strbuf_addf(&buf, "author %s", git_author_info(0));
3166 write_author_script(buf.buf);
3169 if (oneline_offset < arg_len) {
3170 p = arg + oneline_offset;
3171 len = arg_len - oneline_offset;
3173 strbuf_addf(&buf, "Merge %s '%.*s'",
3174 to_merge->next ? "branches" : "branch",
3175 merge_arg_len, arg);
3180 ret = write_message(p, len, git_path_merge_msg(r), 0);
3181 strbuf_release(&buf);
3183 error_errno(_("could not write '%s'"),
3184 git_path_merge_msg(r));
3190 * If HEAD is not identical to the first parent of the original merge
3191 * commit, we cannot fast-forward.
3193 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3194 oideq(&commit->parents->item->object.oid,
3195 &head_commit->object.oid);
3198 * If any merge head is different from the original one, we cannot
3201 if (can_fast_forward) {
3202 struct commit_list *p = commit->parents->next;
3204 for (j = to_merge; j && p; j = j->next, p = p->next)
3205 if (!oideq(&j->item->object.oid,
3206 &p->item->object.oid)) {
3207 can_fast_forward = 0;
3211 * If the number of merge heads differs from the original merge
3212 * commit, we cannot fast-forward.
3215 can_fast_forward = 0;
3218 if (can_fast_forward) {
3219 rollback_lock_file(&lock);
3220 ret = fast_forward_to(r, &commit->object.oid,
3221 &head_commit->object.oid, 0, opts);
3225 if (to_merge->next) {
3227 struct child_process cmd = CHILD_PROCESS_INIT;
3229 if (read_env_script(&cmd.env_array)) {
3230 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3232 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3237 argv_array_push(&cmd.args, "merge");
3238 argv_array_push(&cmd.args, "-s");
3239 argv_array_push(&cmd.args, "octopus");
3240 argv_array_push(&cmd.args, "--no-edit");
3241 argv_array_push(&cmd.args, "--no-ff");
3242 argv_array_push(&cmd.args, "--no-log");
3243 argv_array_push(&cmd.args, "--no-stat");
3244 argv_array_push(&cmd.args, "-F");
3245 argv_array_push(&cmd.args, git_path_merge_msg(r));
3247 argv_array_push(&cmd.args, opts->gpg_sign);
3249 /* Add the tips to be merged */
3250 for (j = to_merge; j; j = j->next)
3251 argv_array_push(&cmd.args,
3252 oid_to_hex(&j->item->object.oid));
3254 strbuf_release(&ref_name);
3255 unlink(git_path_cherry_pick_head(r));
3256 rollback_lock_file(&lock);
3258 rollback_lock_file(&lock);
3259 ret = run_command(&cmd);
3261 /* force re-reading of the cache */
3262 if (!ret && (discard_index(r->index) < 0 ||
3263 repo_read_index(r) < 0))
3264 ret = error(_("could not read index"));
3268 merge_commit = to_merge->item;
3269 bases = get_merge_bases(head_commit, merge_commit);
3270 if (bases && oideq(&merge_commit->object.oid,
3271 &bases->item->object.oid)) {
3273 /* skip merging an ancestor of HEAD */
3277 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3278 git_path_merge_head(r), 0);
3279 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3281 for (j = bases; j; j = j->next)
3282 commit_list_insert(j->item, &reversed);
3283 free_commit_list(bases);
3286 init_merge_options(&o, r);
3288 o.branch2 = ref_name.buf;
3289 o.buffer_output = 2;
3291 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3293 fputs(o.obuf.buf, stdout);
3294 strbuf_release(&o.obuf);
3296 error(_("could not even attempt to merge '%.*s'"),
3297 merge_arg_len, arg);
3301 * The return value of merge_recursive() is 1 on clean, and 0 on
3304 * Let's reverse that, so that do_merge() returns 0 upon success and
3305 * 1 upon failed merge (keeping the return value -1 for the cases where
3306 * we will want to reschedule the `merge` command).
3310 if (r->index->cache_changed &&
3311 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3312 ret = error(_("merge: Unable to write new index file"));
3316 rollback_lock_file(&lock);
3318 repo_rerere(r, opts->allow_rerere_auto);
3321 * In case of problems, we now want to return a positive
3322 * value (a negative one would indicate that the `merge`
3323 * command needs to be rescheduled).
3325 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3329 strbuf_release(&ref_name);
3330 rollback_lock_file(&lock);
3331 free_commit_list(to_merge);
3335 static int is_final_fixup(struct todo_list *todo_list)
3337 int i = todo_list->current;
3339 if (!is_fixup(todo_list->items[i].command))
3342 while (++i < todo_list->nr)
3343 if (is_fixup(todo_list->items[i].command))
3345 else if (!is_noop(todo_list->items[i].command))
3350 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3354 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3355 if (!is_noop(todo_list->items[i].command))
3356 return todo_list->items[i].command;
3361 static int apply_autostash(struct replay_opts *opts)
3363 struct strbuf stash_sha1 = STRBUF_INIT;
3364 struct child_process child = CHILD_PROCESS_INIT;
3367 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3368 strbuf_release(&stash_sha1);
3371 strbuf_trim(&stash_sha1);
3374 child.no_stdout = 1;
3375 child.no_stderr = 1;
3376 argv_array_push(&child.args, "stash");
3377 argv_array_push(&child.args, "apply");
3378 argv_array_push(&child.args, stash_sha1.buf);
3379 if (!run_command(&child))
3380 fprintf(stderr, _("Applied autostash.\n"));
3382 struct child_process store = CHILD_PROCESS_INIT;
3385 argv_array_push(&store.args, "stash");
3386 argv_array_push(&store.args, "store");
3387 argv_array_push(&store.args, "-m");
3388 argv_array_push(&store.args, "autostash");
3389 argv_array_push(&store.args, "-q");
3390 argv_array_push(&store.args, stash_sha1.buf);
3391 if (run_command(&store))
3392 ret = error(_("cannot store %s"), stash_sha1.buf);
3395 _("Applying autostash resulted in conflicts.\n"
3396 "Your changes are safe in the stash.\n"
3397 "You can run \"git stash pop\" or"
3398 " \"git stash drop\" at any time.\n"));
3401 strbuf_release(&stash_sha1);
3405 static const char *reflog_message(struct replay_opts *opts,
3406 const char *sub_action, const char *fmt, ...)
3409 static struct strbuf buf = STRBUF_INIT;
3413 strbuf_addstr(&buf, action_name(opts));
3415 strbuf_addf(&buf, " (%s)", sub_action);
3417 strbuf_addstr(&buf, ": ");
3418 strbuf_vaddf(&buf, fmt, ap);
3425 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3426 const char *commit, const char *action)
3428 struct child_process cmd = CHILD_PROCESS_INIT;
3433 argv_array_push(&cmd.args, "checkout");
3434 argv_array_push(&cmd.args, commit);
3435 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3438 ret = run_command(&cmd);
3440 ret = run_command_silent_on_success(&cmd);
3443 discard_index(r->index);
3448 int prepare_branch_to_be_rebased(struct repository *r, struct replay_opts *opts,
3453 if (commit && *commit) {
3454 action = reflog_message(opts, "start", "checkout %s", commit);
3455 if (run_git_checkout(r, opts, commit, action))
3456 return error(_("could not checkout %s"), commit);
3462 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3463 const char *onto_name, const struct object_id *onto,
3464 const char *orig_head)
3466 struct object_id oid;
3467 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3469 if (get_oid(orig_head, &oid))
3470 return error(_("%s: not a valid OID"), orig_head);
3472 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3473 apply_autostash(opts);
3474 sequencer_remove_state(opts);
3475 return error(_("could not detach HEAD"));
3478 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3481 static int stopped_at_head(struct repository *r)
3483 struct object_id head;
3484 struct commit *commit;
3485 struct commit_message message;
3487 if (get_oid("HEAD", &head) ||
3488 !(commit = lookup_commit(r, &head)) ||
3489 parse_commit(commit) || get_message(commit, &message))
3490 fprintf(stderr, _("Stopped at HEAD\n"));
3492 fprintf(stderr, _("Stopped at %s\n"), message.label);
3493 free_message(commit, &message);
3499 static const char rescheduled_advice[] =
3500 N_("Could not execute the todo command\n"
3504 "It has been rescheduled; To edit the command before continuing, please\n"
3505 "edit the todo list first:\n"
3507 " git rebase --edit-todo\n"
3508 " git rebase --continue\n");
3510 static int pick_commits(struct repository *r,
3511 struct todo_list *todo_list,
3512 struct replay_opts *opts)
3514 int res = 0, reschedule = 0;
3516 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3518 assert(!(opts->signoff || opts->no_commit ||
3519 opts->record_origin || opts->edit));
3520 if (read_and_refresh_cache(r, opts))
3523 while (todo_list->current < todo_list->nr) {
3524 struct todo_item *item = todo_list->items + todo_list->current;
3525 const char *arg = todo_item_get_arg(todo_list, item);
3527 if (save_todo(todo_list, opts))
3529 if (is_rebase_i(opts)) {
3530 if (item->command != TODO_COMMENT) {
3531 FILE *f = fopen(rebase_path_msgnum(), "w");
3533 todo_list->done_nr++;
3536 fprintf(f, "%d\n", todo_list->done_nr);
3540 fprintf(stderr, "Rebasing (%d/%d)%s",
3542 todo_list->total_nr,
3543 opts->verbose ? "\n" : "\r");
3545 unlink(rebase_path_message());
3546 unlink(rebase_path_author_script());
3547 unlink(rebase_path_stopped_sha());
3548 unlink(rebase_path_amend());
3549 unlink(git_path_merge_head(the_repository));
3550 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3552 if (item->command == TODO_BREAK)
3553 return stopped_at_head(r);
3555 if (item->command <= TODO_SQUASH) {
3556 if (is_rebase_i(opts))
3557 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3558 command_to_string(item->command), NULL),
3560 res = do_pick_commit(r, item->command, item->commit,
3561 opts, is_final_fixup(todo_list));
3562 if (is_rebase_i(opts) && res < 0) {
3564 advise(_(rescheduled_advice),
3565 get_item_line_length(todo_list,
3566 todo_list->current),
3567 get_item_line(todo_list,
3568 todo_list->current));
3569 todo_list->current--;
3570 if (save_todo(todo_list, opts))
3573 if (item->command == TODO_EDIT) {
3574 struct commit *commit = item->commit;
3577 _("Stopped at %s... %.*s\n"),
3578 short_commit_name(commit),
3579 item->arg_len, arg);
3580 return error_with_patch(r, commit,
3581 arg, item->arg_len, opts, res, !res);
3583 if (is_rebase_i(opts) && !res)
3584 record_in_rewritten(&item->commit->object.oid,
3585 peek_command(todo_list, 1));
3586 if (res && is_fixup(item->command)) {
3589 return error_failed_squash(r, item->commit, opts,
3590 item->arg_len, arg);
3591 } else if (res && is_rebase_i(opts) && item->commit) {
3593 struct object_id oid;
3596 * If we are rewording and have either
3597 * fast-forwarded already, or are about to
3598 * create a new root commit, we want to amend,
3599 * otherwise we do not.
3601 if (item->command == TODO_REWORD &&
3602 !get_oid("HEAD", &oid) &&
3603 (oideq(&item->commit->object.oid, &oid) ||
3604 (opts->have_squash_onto &&
3605 oideq(&opts->squash_onto, &oid))))
3608 return res | error_with_patch(r, item->commit,
3609 arg, item->arg_len, opts,
3612 } else if (item->command == TODO_EXEC) {
3613 char *end_of_arg = (char *)(arg + item->arg_len);
3614 int saved = *end_of_arg;
3618 res = do_exec(r, arg);
3619 *end_of_arg = saved;
3621 /* Reread the todo file if it has changed. */
3623 if (opts->reschedule_failed_exec)
3625 } else if (stat(get_todo_path(opts), &st))
3626 res = error_errno(_("could not stat '%s'"),
3627 get_todo_path(opts));
3628 else if (match_stat_data(&todo_list->stat, &st)) {
3629 todo_list_release(todo_list);
3630 if (read_populate_todo(r, todo_list, opts))
3631 res = -1; /* message was printed */
3632 /* `current` will be incremented below */
3633 todo_list->current = -1;
3635 } else if (item->command == TODO_LABEL) {
3636 if ((res = do_label(r, arg, item->arg_len)))
3638 } else if (item->command == TODO_RESET) {
3639 if ((res = do_reset(r, arg, item->arg_len, opts)))
3641 } else if (item->command == TODO_MERGE) {
3642 if ((res = do_merge(r, item->commit,
3644 item->flags, opts)) < 0)
3646 else if (item->commit)
3647 record_in_rewritten(&item->commit->object.oid,
3648 peek_command(todo_list, 1));
3650 /* failed with merge conflicts */
3651 return error_with_patch(r, item->commit,
3654 } else if (!is_noop(item->command))
3655 return error(_("unknown command %d"), item->command);
3658 advise(_(rescheduled_advice),
3659 get_item_line_length(todo_list,
3660 todo_list->current),
3661 get_item_line(todo_list, todo_list->current));
3662 todo_list->current--;
3663 if (save_todo(todo_list, opts))
3666 return error_with_patch(r,
3672 todo_list->current++;
3677 if (is_rebase_i(opts)) {
3678 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3681 /* Stopped in the middle, as planned? */
3682 if (todo_list->current < todo_list->nr)
3685 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3686 starts_with(head_ref.buf, "refs/")) {
3688 struct object_id head, orig;
3691 if (get_oid("HEAD", &head)) {
3692 res = error(_("cannot read HEAD"));
3694 strbuf_release(&head_ref);
3695 strbuf_release(&buf);
3698 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3699 get_oid_hex(buf.buf, &orig)) {
3700 res = error(_("could not read orig-head"));
3701 goto cleanup_head_ref;
3704 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3705 res = error(_("could not read 'onto'"));
3706 goto cleanup_head_ref;
3708 msg = reflog_message(opts, "finish", "%s onto %s",
3709 head_ref.buf, buf.buf);
3710 if (update_ref(msg, head_ref.buf, &head, &orig,
3711 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3712 res = error(_("could not update %s"),
3714 goto cleanup_head_ref;
3716 msg = reflog_message(opts, "finish", "returning to %s",
3718 if (create_symref("HEAD", head_ref.buf, msg)) {
3719 res = error(_("could not update HEAD to %s"),
3721 goto cleanup_head_ref;
3726 if (opts->verbose) {
3727 struct rev_info log_tree_opt;
3728 struct object_id orig, head;
3730 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3731 repo_init_revisions(r, &log_tree_opt, NULL);
3732 log_tree_opt.diff = 1;
3733 log_tree_opt.diffopt.output_format =
3734 DIFF_FORMAT_DIFFSTAT;
3735 log_tree_opt.disable_stdin = 1;
3737 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3738 !get_oid(buf.buf, &orig) &&
3739 !get_oid("HEAD", &head)) {
3740 diff_tree_oid(&orig, &head, "",
3741 &log_tree_opt.diffopt);
3742 log_tree_diff_flush(&log_tree_opt);
3745 flush_rewritten_pending();
3746 if (!stat(rebase_path_rewritten_list(), &st) &&
3748 struct child_process child = CHILD_PROCESS_INIT;
3749 const char *post_rewrite_hook =
3750 find_hook("post-rewrite");
3752 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3754 argv_array_push(&child.args, "notes");
3755 argv_array_push(&child.args, "copy");
3756 argv_array_push(&child.args, "--for-rewrite=rebase");
3757 /* we don't care if this copying failed */
3758 run_command(&child);
3760 if (post_rewrite_hook) {
3761 struct child_process hook = CHILD_PROCESS_INIT;
3763 hook.in = open(rebase_path_rewritten_list(),
3765 hook.stdout_to_stderr = 1;
3766 hook.trace2_hook_name = "post-rewrite";
3767 argv_array_push(&hook.args, post_rewrite_hook);
3768 argv_array_push(&hook.args, "rebase");
3769 /* we don't care if this hook failed */
3773 apply_autostash(opts);
3777 "Successfully rebased and updated %s.\n",
3780 strbuf_release(&buf);
3781 strbuf_release(&head_ref);
3785 * Sequence of picks finished successfully; cleanup by
3786 * removing the .git/sequencer directory
3788 return sequencer_remove_state(opts);
3791 static int continue_single_pick(struct repository *r)
3793 const char *argv[] = { "commit", NULL };
3795 if (!file_exists(git_path_cherry_pick_head(r)) &&
3796 !file_exists(git_path_revert_head(r)))
3797 return error(_("no cherry-pick or revert in progress"));
3798 return run_command_v_opt(argv, RUN_GIT_CMD);
3801 static int commit_staged_changes(struct repository *r,
3802 struct replay_opts *opts,
3803 struct todo_list *todo_list)
3805 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3806 unsigned int final_fixup = 0, is_clean;
3808 if (has_unstaged_changes(r, 1))
3809 return error(_("cannot rebase: You have unstaged changes."));
3811 is_clean = !has_uncommitted_changes(r, 0);
3813 if (file_exists(rebase_path_amend())) {
3814 struct strbuf rev = STRBUF_INIT;
3815 struct object_id head, to_amend;
3817 if (get_oid("HEAD", &head))
3818 return error(_("cannot amend non-existing commit"));
3819 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3820 return error(_("invalid file: '%s'"), rebase_path_amend());
3821 if (get_oid_hex(rev.buf, &to_amend))
3822 return error(_("invalid contents: '%s'"),
3823 rebase_path_amend());
3824 if (!is_clean && !oideq(&head, &to_amend))
3825 return error(_("\nYou have uncommitted changes in your "
3826 "working tree. Please, commit them\n"
3827 "first and then run 'git rebase "
3828 "--continue' again."));
3830 * When skipping a failed fixup/squash, we need to edit the
3831 * commit message, the current fixup list and count, and if it
3832 * was the last fixup/squash in the chain, we need to clean up
3833 * the commit message and if there was a squash, let the user
3836 if (!is_clean || !opts->current_fixup_count)
3837 ; /* this is not the final fixup */
3838 else if (!oideq(&head, &to_amend) ||
3839 !file_exists(rebase_path_stopped_sha())) {
3840 /* was a final fixup or squash done manually? */
3841 if (!is_fixup(peek_command(todo_list, 0))) {
3842 unlink(rebase_path_fixup_msg());
3843 unlink(rebase_path_squash_msg());
3844 unlink(rebase_path_current_fixups());
3845 strbuf_reset(&opts->current_fixups);
3846 opts->current_fixup_count = 0;
3849 /* we are in a fixup/squash chain */
3850 const char *p = opts->current_fixups.buf;
3851 int len = opts->current_fixups.len;
3853 opts->current_fixup_count--;
3855 BUG("Incorrect current_fixups:\n%s", p);
3856 while (len && p[len - 1] != '\n')
3858 strbuf_setlen(&opts->current_fixups, len);
3859 if (write_message(p, len, rebase_path_current_fixups(),
3861 return error(_("could not write file: '%s'"),
3862 rebase_path_current_fixups());
3865 * If a fixup/squash in a fixup/squash chain failed, the
3866 * commit message is already correct, no need to commit
3869 * Only if it is the final command in the fixup/squash
3870 * chain, and only if the chain is longer than a single
3871 * fixup/squash command (which was just skipped), do we
3872 * actually need to re-commit with a cleaned up commit
3875 if (opts->current_fixup_count > 0 &&
3876 !is_fixup(peek_command(todo_list, 0))) {
3879 * If there was not a single "squash" in the
3880 * chain, we only need to clean up the commit
3881 * message, no need to bother the user with
3882 * opening the commit message in the editor.
3884 if (!starts_with(p, "squash ") &&
3885 !strstr(p, "\nsquash "))
3886 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3887 } else if (is_fixup(peek_command(todo_list, 0))) {
3889 * We need to update the squash message to skip
3890 * the latest commit message.
3892 struct commit *commit;
3893 const char *path = rebase_path_squash_msg();
3895 if (parse_head(r, &commit) ||
3896 !(p = get_commit_buffer(commit, NULL)) ||
3897 write_message(p, strlen(p), path, 0)) {
3898 unuse_commit_buffer(commit, p);
3899 return error(_("could not write file: "
3902 unuse_commit_buffer(commit, p);
3906 strbuf_release(&rev);
3911 const char *cherry_pick_head = git_path_cherry_pick_head(r);
3913 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3914 return error(_("could not remove CHERRY_PICK_HEAD"));
3919 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
3921 return error(_("could not commit staged changes."));
3922 unlink(rebase_path_amend());
3923 unlink(git_path_merge_head(the_repository));
3925 unlink(rebase_path_fixup_msg());
3926 unlink(rebase_path_squash_msg());
3928 if (opts->current_fixup_count > 0) {
3930 * Whether final fixup or not, we just cleaned up the commit
3933 unlink(rebase_path_current_fixups());
3934 strbuf_reset(&opts->current_fixups);
3935 opts->current_fixup_count = 0;
3940 int sequencer_continue(struct repository *r, struct replay_opts *opts)
3942 struct todo_list todo_list = TODO_LIST_INIT;
3945 if (read_and_refresh_cache(r, opts))
3948 if (read_populate_opts(opts))
3950 if (is_rebase_i(opts)) {
3951 if ((res = read_populate_todo(r, &todo_list, opts)))
3952 goto release_todo_list;
3953 if (commit_staged_changes(r, opts, &todo_list))
3955 } else if (!file_exists(get_todo_path(opts)))
3956 return continue_single_pick(r);
3957 else if ((res = read_populate_todo(r, &todo_list, opts)))
3958 goto release_todo_list;
3960 if (!is_rebase_i(opts)) {
3961 /* Verify that the conflict has been resolved */
3962 if (file_exists(git_path_cherry_pick_head(r)) ||
3963 file_exists(git_path_revert_head(r))) {
3964 res = continue_single_pick(r);
3966 goto release_todo_list;
3968 if (index_differs_from(r, "HEAD", NULL, 0)) {
3969 res = error_dirty_index(r, opts);
3970 goto release_todo_list;
3972 todo_list.current++;
3973 } else if (file_exists(rebase_path_stopped_sha())) {
3974 struct strbuf buf = STRBUF_INIT;
3975 struct object_id oid;
3977 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3978 !get_oid_committish(buf.buf, &oid))
3979 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3980 strbuf_release(&buf);
3983 res = pick_commits(r, &todo_list, opts);
3985 todo_list_release(&todo_list);
3989 static int single_pick(struct repository *r,
3990 struct commit *cmit,
3991 struct replay_opts *opts)
3993 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3994 return do_pick_commit(r, opts->action == REPLAY_PICK ?
3995 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3998 int sequencer_pick_revisions(struct repository *r,
3999 struct replay_opts *opts)
4001 struct todo_list todo_list = TODO_LIST_INIT;
4002 struct object_id oid;
4006 if (read_and_refresh_cache(r, opts))
4009 for (i = 0; i < opts->revs->pending.nr; i++) {
4010 struct object_id oid;
4011 const char *name = opts->revs->pending.objects[i].name;
4013 /* This happens when using --stdin. */
4017 if (!get_oid(name, &oid)) {
4018 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4019 enum object_type type = oid_object_info(r,
4022 return error(_("%s: can't cherry-pick a %s"),
4023 name, type_name(type));
4026 return error(_("%s: bad revision"), name);
4030 * If we were called as "git cherry-pick <commit>", just
4031 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4032 * REVERT_HEAD, and don't touch the sequencer state.
4033 * This means it is possible to cherry-pick in the middle
4034 * of a cherry-pick sequence.
4036 if (opts->revs->cmdline.nr == 1 &&
4037 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4038 opts->revs->no_walk &&
4039 !opts->revs->cmdline.rev->flags) {
4040 struct commit *cmit;
4041 if (prepare_revision_walk(opts->revs))
4042 return error(_("revision walk setup failed"));
4043 cmit = get_revision(opts->revs);
4045 return error(_("empty commit set passed"));
4046 if (get_revision(opts->revs))
4047 BUG("unexpected extra commit from walk");
4048 return single_pick(r, cmit, opts);
4052 * Start a new cherry-pick/ revert sequence; but
4053 * first, make sure that an existing one isn't in
4057 if (walk_revs_populate_todo(&todo_list, opts) ||
4058 create_seq_dir() < 0)
4060 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4061 return error(_("can't revert as initial commit"));
4062 if (save_head(oid_to_hex(&oid)))
4064 if (save_opts(opts))
4066 update_abort_safety_file();
4067 res = pick_commits(r, &todo_list, opts);
4068 todo_list_release(&todo_list);
4072 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4074 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4075 struct strbuf sob = STRBUF_INIT;
4078 strbuf_addstr(&sob, sign_off_header);
4079 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4080 strbuf_addch(&sob, '\n');
4083 strbuf_complete_line(msgbuf);
4086 * If the whole message buffer is equal to the sob, pretend that we
4087 * found a conforming footer with a matching sob
4089 if (msgbuf->len - ignore_footer == sob.len &&
4090 !strncmp(msgbuf->buf, sob.buf, sob.len))
4093 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4096 const char *append_newlines = NULL;
4097 size_t len = msgbuf->len - ignore_footer;
4101 * The buffer is completely empty. Leave foom for
4102 * the title and body to be filled in by the user.
4104 append_newlines = "\n\n";
4105 } else if (len == 1) {
4107 * Buffer contains a single newline. Add another
4108 * so that we leave room for the title and body.
4110 append_newlines = "\n";
4111 } else if (msgbuf->buf[len - 2] != '\n') {
4113 * Buffer ends with a single newline. Add another
4114 * so that there is an empty line between the message
4117 append_newlines = "\n";
4118 } /* else, the buffer already ends with two newlines. */
4120 if (append_newlines)
4121 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4122 append_newlines, strlen(append_newlines));
4125 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4126 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4129 strbuf_release(&sob);
4132 struct labels_entry {
4133 struct hashmap_entry entry;
4134 char label[FLEX_ARRAY];
4137 static int labels_cmp(const void *fndata, const struct labels_entry *a,
4138 const struct labels_entry *b, const void *key)
4140 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4143 struct string_entry {
4144 struct oidmap_entry entry;
4145 char string[FLEX_ARRAY];
4148 struct label_state {
4149 struct oidmap commit2label;
4150 struct hashmap labels;
4154 static const char *label_oid(struct object_id *oid, const char *label,
4155 struct label_state *state)
4157 struct labels_entry *labels_entry;
4158 struct string_entry *string_entry;
4159 struct object_id dummy;
4163 string_entry = oidmap_get(&state->commit2label, oid);
4165 return string_entry->string;
4168 * For "uninteresting" commits, i.e. commits that are not to be
4169 * rebased, and which can therefore not be labeled, we use a unique
4170 * abbreviation of the commit name. This is slightly more complicated
4171 * than calling find_unique_abbrev() because we also need to make
4172 * sure that the abbreviation does not conflict with any other
4175 * We disallow "interesting" commits to be labeled by a string that
4176 * is a valid full-length hash, to ensure that we always can find an
4177 * abbreviation for any uninteresting commit's names that does not
4178 * clash with any other label.
4183 strbuf_reset(&state->buf);
4184 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4185 label = p = state->buf.buf;
4187 find_unique_abbrev_r(p, oid, default_abbrev);
4190 * We may need to extend the abbreviated hash so that there is
4191 * no conflicting label.
4193 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4194 size_t i = strlen(p) + 1;
4196 oid_to_hex_r(p, oid);
4197 for (; i < GIT_SHA1_HEXSZ; i++) {
4200 if (!hashmap_get_from_hash(&state->labels,
4206 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
4207 !get_oid_hex(label, &dummy)) ||
4208 (len == 1 && *label == '#') ||
4209 hashmap_get_from_hash(&state->labels,
4210 strihash(label), label)) {
4212 * If the label already exists, or if the label is a valid full
4213 * OID, or the label is a '#' (which we use as a separator
4214 * between merge heads and oneline), we append a dash and a
4215 * number to make it unique.
4217 struct strbuf *buf = &state->buf;
4220 strbuf_add(buf, label, len);
4222 for (i = 2; ; i++) {
4223 strbuf_setlen(buf, len);
4224 strbuf_addf(buf, "-%d", i);
4225 if (!hashmap_get_from_hash(&state->labels,
4234 FLEX_ALLOC_STR(labels_entry, label, label);
4235 hashmap_entry_init(labels_entry, strihash(label));
4236 hashmap_add(&state->labels, labels_entry);
4238 FLEX_ALLOC_STR(string_entry, string, label);
4239 oidcpy(&string_entry->entry.oid, oid);
4240 oidmap_put(&state->commit2label, string_entry);
4242 return string_entry->string;
4245 static int make_script_with_merges(struct pretty_print_context *pp,
4246 struct rev_info *revs, struct strbuf *out,
4249 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4250 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4251 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4252 struct strbuf label = STRBUF_INIT;
4253 struct commit_list *commits = NULL, **tail = &commits, *iter;
4254 struct commit_list *tips = NULL, **tips_tail = &tips;
4255 struct commit *commit;
4256 struct oidmap commit2todo = OIDMAP_INIT;
4257 struct string_entry *entry;
4258 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4259 shown = OIDSET_INIT;
4260 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4262 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4263 const char *cmd_pick = abbr ? "p" : "pick",
4264 *cmd_label = abbr ? "l" : "label",
4265 *cmd_reset = abbr ? "t" : "reset",
4266 *cmd_merge = abbr ? "m" : "merge";
4268 oidmap_init(&commit2todo, 0);
4269 oidmap_init(&state.commit2label, 0);
4270 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4271 strbuf_init(&state.buf, 32);
4273 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4274 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4275 FLEX_ALLOC_STR(entry, string, "onto");
4276 oidcpy(&entry->entry.oid, oid);
4277 oidmap_put(&state.commit2label, entry);
4282 * - get onelines for all commits
4283 * - gather all branch tips (i.e. 2nd or later parents of merges)
4284 * - label all branch tips
4286 while ((commit = get_revision(revs))) {
4287 struct commit_list *to_merge;
4288 const char *p1, *p2;
4289 struct object_id *oid;
4292 tail = &commit_list_insert(commit, tail)->next;
4293 oidset_insert(&interesting, &commit->object.oid);
4295 is_empty = is_original_commit_empty(commit);
4296 if (!is_empty && (commit->object.flags & PATCHSAME))
4299 strbuf_reset(&oneline);
4300 pretty_print_commit(pp, commit, &oneline);
4302 to_merge = commit->parents ? commit->parents->next : NULL;
4304 /* non-merge commit: easy case */
4306 if (!keep_empty && is_empty)
4307 strbuf_addf(&buf, "%c ", comment_line_char);
4308 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4309 oid_to_hex(&commit->object.oid),
4312 FLEX_ALLOC_STR(entry, string, buf.buf);
4313 oidcpy(&entry->entry.oid, &commit->object.oid);
4314 oidmap_put(&commit2todo, entry);
4319 /* Create a label */
4320 strbuf_reset(&label);
4321 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4322 (p1 = strchr(p1, '\'')) &&
4323 (p2 = strchr(++p1, '\'')))
4324 strbuf_add(&label, p1, p2 - p1);
4325 else if (skip_prefix(oneline.buf, "Merge pull request ",
4327 (p1 = strstr(p1, " from ")))
4328 strbuf_addstr(&label, p1 + strlen(" from "));
4330 strbuf_addbuf(&label, &oneline);
4332 for (p1 = label.buf; *p1; p1++)
4337 strbuf_addf(&buf, "%s -C %s",
4338 cmd_merge, oid_to_hex(&commit->object.oid));
4340 /* label the tips of merged branches */
4341 for (; to_merge; to_merge = to_merge->next) {
4342 oid = &to_merge->item->object.oid;
4343 strbuf_addch(&buf, ' ');
4345 if (!oidset_contains(&interesting, oid)) {
4346 strbuf_addstr(&buf, label_oid(oid, NULL,
4351 tips_tail = &commit_list_insert(to_merge->item,
4354 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4356 strbuf_addf(&buf, " # %s", oneline.buf);
4358 FLEX_ALLOC_STR(entry, string, buf.buf);
4359 oidcpy(&entry->entry.oid, &commit->object.oid);
4360 oidmap_put(&commit2todo, entry);
4365 * - label branch points
4366 * - add HEAD to the branch tips
4368 for (iter = commits; iter; iter = iter->next) {
4369 struct commit_list *parent = iter->item->parents;
4370 for (; parent; parent = parent->next) {
4371 struct object_id *oid = &parent->item->object.oid;
4372 if (!oidset_contains(&interesting, oid))
4374 if (oidset_insert(&child_seen, oid))
4375 label_oid(oid, "branch-point", &state);
4378 /* Add HEAD as implict "tip of branch" */
4380 tips_tail = &commit_list_insert(iter->item,
4385 * Third phase: output the todo list. This is a bit tricky, as we
4386 * want to avoid jumping back and forth between revisions. To
4387 * accomplish that goal, we walk backwards from the branch tips,
4388 * gathering commits not yet shown, reversing the list on the fly,
4389 * then outputting that list (labeling revisions as needed).
4391 strbuf_addf(out, "%s onto\n", cmd_label);
4392 for (iter = tips; iter; iter = iter->next) {
4393 struct commit_list *list = NULL, *iter2;
4395 commit = iter->item;
4396 if (oidset_contains(&shown, &commit->object.oid))
4398 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4401 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4403 strbuf_addch(out, '\n');
4405 while (oidset_contains(&interesting, &commit->object.oid) &&
4406 !oidset_contains(&shown, &commit->object.oid)) {
4407 commit_list_insert(commit, &list);
4408 if (!commit->parents) {
4412 commit = commit->parents->item;
4416 strbuf_addf(out, "%s %s\n", cmd_reset,
4417 rebase_cousins ? "onto" : "[new root]");
4419 const char *to = NULL;
4421 entry = oidmap_get(&state.commit2label,
4422 &commit->object.oid);
4425 else if (!rebase_cousins)
4426 to = label_oid(&commit->object.oid, NULL,
4429 if (!to || !strcmp(to, "onto"))
4430 strbuf_addf(out, "%s onto\n", cmd_reset);
4432 strbuf_reset(&oneline);
4433 pretty_print_commit(pp, commit, &oneline);
4434 strbuf_addf(out, "%s %s # %s\n",
4435 cmd_reset, to, oneline.buf);
4439 for (iter2 = list; iter2; iter2 = iter2->next) {
4440 struct object_id *oid = &iter2->item->object.oid;
4441 entry = oidmap_get(&commit2todo, oid);
4442 /* only show if not already upstream */
4444 strbuf_addf(out, "%s\n", entry->string);
4445 entry = oidmap_get(&state.commit2label, oid);
4447 strbuf_addf(out, "%s %s\n",
4448 cmd_label, entry->string);
4449 oidset_insert(&shown, oid);
4452 free_commit_list(list);
4455 free_commit_list(commits);
4456 free_commit_list(tips);
4458 strbuf_release(&label);
4459 strbuf_release(&oneline);
4460 strbuf_release(&buf);
4462 oidmap_free(&commit2todo, 1);
4463 oidmap_free(&state.commit2label, 1);
4464 hashmap_free(&state.labels, 1);
4465 strbuf_release(&state.buf);
4470 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4471 const char **argv, unsigned flags)
4473 char *format = NULL;
4474 struct pretty_print_context pp = {0};
4475 struct rev_info revs;
4476 struct commit *commit;
4477 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4478 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4479 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4481 repo_init_revisions(r, &revs, NULL);
4482 revs.verbose_header = 1;
4484 revs.max_parents = 1;
4485 revs.cherry_mark = 1;
4488 revs.right_only = 1;
4489 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4490 revs.topo_order = 1;
4492 revs.pretty_given = 1;
4493 git_config_get_string("rebase.instructionFormat", &format);
4494 if (!format || !*format) {
4496 format = xstrdup("%s");
4498 get_commit_format(format, &revs);
4500 pp.fmt = revs.commit_format;
4501 pp.output_encoding = get_log_output_encoding();
4503 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4504 return error(_("make_script: unhandled options"));
4506 if (prepare_revision_walk(&revs) < 0)
4507 return error(_("make_script: error preparing revisions"));
4510 return make_script_with_merges(&pp, &revs, out, flags);
4512 while ((commit = get_revision(&revs))) {
4513 int is_empty = is_original_commit_empty(commit);
4515 if (!is_empty && (commit->object.flags & PATCHSAME))
4517 if (!keep_empty && is_empty)
4518 strbuf_addf(out, "%c ", comment_line_char);
4519 strbuf_addf(out, "%s %s ", insn,
4520 oid_to_hex(&commit->object.oid));
4521 pretty_print_commit(&pp, commit, out);
4522 strbuf_addch(out, '\n');
4528 * Add commands after pick and (series of) squash/fixup commands
4531 void todo_list_add_exec_commands(struct todo_list *todo_list,
4532 struct string_list *commands)
4534 struct strbuf *buf = &todo_list->buf;
4535 size_t base_offset = buf->len;
4536 int i, insert, nr = 0, alloc = 0;
4537 struct todo_item *items = NULL, *base_items = NULL;
4539 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4540 for (i = 0; i < commands->nr; i++) {
4541 size_t command_len = strlen(commands->items[i].string);
4543 strbuf_addstr(buf, commands->items[i].string);
4544 strbuf_addch(buf, '\n');
4546 base_items[i].command = TODO_EXEC;
4547 base_items[i].offset_in_buf = base_offset;
4548 base_items[i].arg_offset = base_offset + strlen("exec ");
4549 base_items[i].arg_len = command_len - strlen("exec ");
4551 base_offset += command_len + 1;
4555 * Insert <commands> after every pick. Here, fixup/squash chains
4556 * are considered part of the pick, so we insert the commands *after*
4557 * those chains if there are any.
4559 * As we insert the exec commands immediatly after rearranging
4560 * any fixups and before the user edits the list, a fixup chain
4561 * can never contain comments (any comments are empty picks that
4562 * have been commented out because the user did not specify
4563 * --keep-empty). So, it is safe to insert an exec command
4564 * without looking at the command following a comment.
4567 for (i = 0; i < todo_list->nr; i++) {
4568 enum todo_command command = todo_list->items[i].command;
4569 if (insert && !is_fixup(command)) {
4570 ALLOC_GROW(items, nr + commands->nr, alloc);
4571 COPY_ARRAY(items + nr, base_items, commands->nr);
4577 ALLOC_GROW(items, nr + 1, alloc);
4578 items[nr++] = todo_list->items[i];
4580 if (command == TODO_PICK || command == TODO_MERGE)
4584 /* insert or append final <commands> */
4585 if (insert || nr == todo_list->nr) {
4586 ALLOC_GROW(items, nr + commands->nr, alloc);
4587 COPY_ARRAY(items + nr, base_items, commands->nr);
4592 FREE_AND_NULL(todo_list->items);
4593 todo_list->items = items;
4595 todo_list->alloc = alloc;
4598 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4599 struct strbuf *buf, int num, unsigned flags)
4601 struct todo_item *item;
4602 int i, max = todo_list->nr;
4604 if (num > 0 && num < max)
4607 for (item = todo_list->items, i = 0; i < max; i++, item++) {
4608 /* if the item is not a command write it and continue */
4609 if (item->command >= TODO_COMMENT) {
4610 strbuf_addf(buf, "%.*s\n", item->arg_len,
4611 todo_item_get_arg(todo_list, item));
4615 /* add command to the buffer */
4616 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4617 strbuf_addch(buf, command_to_char(item->command));
4619 strbuf_addstr(buf, command_to_string(item->command));
4623 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4624 short_commit_name(item->commit) :
4625 oid_to_hex(&item->commit->object.oid);
4627 if (item->command == TODO_MERGE) {
4628 if (item->flags & TODO_EDIT_MERGE_MSG)
4629 strbuf_addstr(buf, " -c");
4631 strbuf_addstr(buf, " -C");
4634 strbuf_addf(buf, " %s", oid);
4637 /* add all the rest */
4639 strbuf_addch(buf, '\n');
4641 strbuf_addf(buf, " %.*s\n", item->arg_len,
4642 todo_item_get_arg(todo_list, item));
4646 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
4647 const char *file, const char *shortrevisions,
4648 const char *shortonto, int num, unsigned flags)
4651 struct strbuf buf = STRBUF_INIT;
4653 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
4654 if (flags & TODO_LIST_APPEND_TODO_HELP)
4655 append_todo_help(flags & TODO_LIST_KEEP_EMPTY, count_commands(todo_list),
4656 shortrevisions, shortonto, &buf);
4658 res = write_message(buf.buf, buf.len, file, 0);
4659 strbuf_release(&buf);
4664 static const char edit_todo_list_advice[] =
4665 N_("You can fix this with 'git rebase --edit-todo' "
4666 "and then run 'git rebase --continue'.\n"
4667 "Or you can abort the rebase with 'git rebase"
4670 int check_todo_list_from_file(struct repository *r)
4672 struct todo_list old_todo = TODO_LIST_INIT, new_todo = TODO_LIST_INIT;
4675 if (strbuf_read_file_or_whine(&new_todo.buf, rebase_path_todo()) < 0) {
4680 if (strbuf_read_file_or_whine(&old_todo.buf, rebase_path_todo_backup()) < 0) {
4685 res = todo_list_parse_insn_buffer(r, old_todo.buf.buf, &old_todo);
4687 res = todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo);
4689 res = todo_list_check(&old_todo, &new_todo);
4691 fprintf(stderr, _(edit_todo_list_advice));
4693 todo_list_release(&old_todo);
4694 todo_list_release(&new_todo);
4699 /* skip picking commits whose parents are unchanged */
4700 static int skip_unnecessary_picks(struct repository *r,
4701 struct todo_list *todo_list,
4702 struct object_id *base_oid)
4704 struct object_id *parent_oid;
4707 for (i = 0; i < todo_list->nr; i++) {
4708 struct todo_item *item = todo_list->items + i;
4710 if (item->command >= TODO_NOOP)
4712 if (item->command != TODO_PICK)
4714 if (parse_commit(item->commit)) {
4715 return error(_("could not parse commit '%s'"),
4716 oid_to_hex(&item->commit->object.oid));
4718 if (!item->commit->parents)
4719 break; /* root commit */
4720 if (item->commit->parents->next)
4721 break; /* merge commit */
4722 parent_oid = &item->commit->parents->item->object.oid;
4723 if (!oideq(parent_oid, base_oid))
4725 oidcpy(base_oid, &item->commit->object.oid);
4728 const char *done_path = rebase_path_done();
4730 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
4731 error_errno(_("could not write to '%s'"), done_path);
4735 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
4737 todo_list->current = 0;
4739 if (is_fixup(peek_command(todo_list, 0)))
4740 record_in_rewritten(base_oid, peek_command(todo_list, 0));
4746 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
4747 const char *shortrevisions, const char *onto_name,
4748 struct commit *onto, const char *orig_head,
4749 struct string_list *commands, unsigned autosquash,
4750 struct todo_list *todo_list)
4752 const char *shortonto, *todo_file = rebase_path_todo();
4753 struct todo_list new_todo = TODO_LIST_INIT;
4754 struct strbuf *buf = &todo_list->buf;
4755 struct object_id oid = onto->object.oid;
4758 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4760 if (buf->len == 0) {
4761 struct todo_item *item = append_new_todo(todo_list);
4762 item->command = TODO_NOOP;
4763 item->commit = NULL;
4764 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
4767 if (autosquash && todo_list_rearrange_squash(todo_list))
4771 todo_list_add_exec_commands(todo_list, commands);
4773 if (count_commands(todo_list) == 0) {
4774 apply_autostash(opts);
4775 sequencer_remove_state(opts);
4777 return error(_("nothing to do"));
4780 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
4784 else if (res == -2) {
4785 apply_autostash(opts);
4786 sequencer_remove_state(opts);
4789 } else if (res == -3) {
4790 apply_autostash(opts);
4791 sequencer_remove_state(opts);
4792 todo_list_release(&new_todo);
4794 return error(_("nothing to do"));
4797 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) ||
4798 todo_list_check(todo_list, &new_todo)) {
4799 fprintf(stderr, _(edit_todo_list_advice));
4800 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
4801 todo_list_release(&new_todo);
4806 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
4807 todo_list_release(&new_todo);
4808 return error(_("could not skip unnecessary pick commands"));
4811 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
4812 flags & ~(TODO_LIST_SHORTEN_IDS))) {
4813 todo_list_release(&new_todo);
4814 return error_errno(_("could not write '%s'"), todo_file);
4817 todo_list_release(&new_todo);
4819 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
4822 if (require_clean_work_tree(r, "rebase", "", 1, 1))
4825 return sequencer_continue(r, opts);
4828 struct subject2item_entry {
4829 struct hashmap_entry entry;
4831 char subject[FLEX_ARRAY];
4834 static int subject2item_cmp(const void *fndata,
4835 const struct subject2item_entry *a,
4836 const struct subject2item_entry *b, const void *key)
4838 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4841 define_commit_slab(commit_todo_item, struct todo_item *);
4844 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4845 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4846 * after the former, and change "pick" to "fixup"/"squash".
4848 * Note that if the config has specified a custom instruction format, each log
4849 * message will have to be retrieved from the commit (as the oneline in the
4850 * script cannot be trusted) in order to normalize the autosquash arrangement.
4852 int todo_list_rearrange_squash(struct todo_list *todo_list)
4854 struct hashmap subject2item;
4855 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
4857 struct commit_todo_item commit_todo;
4858 struct todo_item *items = NULL;
4860 init_commit_todo_item(&commit_todo);
4862 * The hashmap maps onelines to the respective todo list index.
4864 * If any items need to be rearranged, the next[i] value will indicate
4865 * which item was moved directly after the i'th.
4867 * In that case, last[i] will indicate the index of the latest item to
4868 * be moved to appear after the i'th.
4870 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4871 NULL, todo_list->nr);
4872 ALLOC_ARRAY(next, todo_list->nr);
4873 ALLOC_ARRAY(tail, todo_list->nr);
4874 ALLOC_ARRAY(subjects, todo_list->nr);
4875 for (i = 0; i < todo_list->nr; i++) {
4876 struct strbuf buf = STRBUF_INIT;
4877 struct todo_item *item = todo_list->items + i;
4878 const char *commit_buffer, *subject, *p;
4881 struct subject2item_entry *entry;
4883 next[i] = tail[i] = -1;
4884 if (!item->commit || item->command == TODO_DROP) {
4889 if (is_fixup(item->command)) {
4890 clear_commit_todo_item(&commit_todo);
4891 return error(_("the script was already rearranged."));
4894 *commit_todo_item_at(&commit_todo, item->commit) = item;
4896 parse_commit(item->commit);
4897 commit_buffer = get_commit_buffer(item->commit, NULL);
4898 find_commit_subject(commit_buffer, &subject);
4899 format_subject(&buf, subject, " ");
4900 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4901 unuse_commit_buffer(item->commit, commit_buffer);
4902 if ((skip_prefix(subject, "fixup! ", &p) ||
4903 skip_prefix(subject, "squash! ", &p))) {
4904 struct commit *commit2;
4909 if (!skip_prefix(p, "fixup! ", &p) &&
4910 !skip_prefix(p, "squash! ", &p))
4914 if ((entry = hashmap_get_from_hash(&subject2item,
4916 /* found by title */
4918 else if (!strchr(p, ' ') &&
4920 lookup_commit_reference_by_name(p)) &&
4921 *commit_todo_item_at(&commit_todo, commit2))
4922 /* found by commit name */
4923 i2 = *commit_todo_item_at(&commit_todo, commit2)
4926 /* copy can be a prefix of the commit subject */
4927 for (i2 = 0; i2 < i; i2++)
4929 starts_with(subjects[i2], p))
4937 todo_list->items[i].command =
4938 starts_with(subject, "fixup!") ?
4939 TODO_FIXUP : TODO_SQUASH;
4945 } else if (!hashmap_get_from_hash(&subject2item,
4946 strhash(subject), subject)) {
4947 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4949 hashmap_entry_init(entry, strhash(entry->subject));
4950 hashmap_put(&subject2item, entry);
4955 for (i = 0; i < todo_list->nr; i++) {
4956 enum todo_command command = todo_list->items[i].command;
4960 * Initially, all commands are 'pick's. If it is a
4961 * fixup or a squash now, we have rearranged it.
4963 if (is_fixup(command))
4967 ALLOC_GROW(items, nr + 1, alloc);
4968 items[nr++] = todo_list->items[cur];
4973 FREE_AND_NULL(todo_list->items);
4974 todo_list->items = items;
4976 todo_list->alloc = alloc;
4981 for (i = 0; i < todo_list->nr; i++)
4984 hashmap_free(&subject2item, 1);
4986 clear_commit_todo_item(&commit_todo);