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 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 static GIT_PATH_FUNC(rebase_path_todo_backup,
59 "rebase-merge/git-rebase-todo.backup")
62 * The rebase command lines that have already been processed. A line
63 * is moved here when it is first handled, before any associated user
66 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
68 * The file to keep track of how many commands were already processed (e.g.
71 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
73 * The file to keep track of how many commands are to be processed in total
74 * (e.g. for the prompt).
76 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
78 * The commit message that is planned to be used for any changes that
79 * need to be committed following a user interaction.
81 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
83 * The file into which is accumulated the suggested commit message for
84 * squash/fixup commands. When the first of a series of squash/fixups
85 * is seen, the file is created and the commit message from the
86 * previous commit and from the first squash/fixup commit are written
87 * to it. The commit message for each subsequent squash/fixup commit
88 * is appended to the file as it is processed.
90 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
92 * If the current series of squash/fixups has not yet included a squash
93 * command, then this file exists and holds the commit message of the
94 * original "pick" commit. (If the series ends without a "squash"
95 * command, then this can be used as the commit message of the combined
96 * commit without opening the editor.)
98 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
100 * This file contains the list fixup/squash commands that have been
101 * accumulated into message-fixup or message-squash so far.
103 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
105 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
106 * GIT_AUTHOR_DATE that will be used for the commit that is currently
109 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
111 * When an "edit" rebase command is being processed, the SHA1 of the
112 * commit to be edited is recorded in this file. When "git rebase
113 * --continue" is executed, if there are any staged changes then they
114 * will be amended to the HEAD commit, but only provided the HEAD
115 * commit is still the commit to be edited. When any other rebase
116 * command is processed, this file is deleted.
118 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
120 * When we stop at a given patch via the "edit" command, this file contains
121 * the abbreviated commit name of the corresponding patch.
123 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
125 * For the post-rewrite hook, we make a list of rewritten commits and
126 * their new sha1s. The rewritten-pending list keeps the sha1s of
127 * commits that have been processed, but not committed yet,
128 * e.g. because they are waiting for a 'squash' command.
130 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
131 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
132 "rebase-merge/rewritten-pending")
135 * The path of the file containig the OID of the "squash onto" commit, i.e.
136 * the dummy commit used for `reset [new root]`.
138 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
141 * The path of the file listing refs that need to be deleted after the rebase
142 * finishes. This is used by the `label` command to record the need for cleanup.
144 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
147 * The following files are written by git-rebase just after parsing the
150 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
151 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
152 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
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_quiet, "rebase-merge/quiet")
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);
294 free(opts->gpg_sign);
295 free(opts->strategy);
296 for (i = 0; i < opts->xopts_nr; i++)
297 free(opts->xopts[i]);
299 strbuf_release(&opts->current_fixups);
302 strbuf_addstr(&buf, get_dir(opts));
303 remove_dir_recursively(&buf, 0);
304 strbuf_release(&buf);
309 static const char *action_name(const struct replay_opts *opts)
311 switch (opts->action) {
315 return N_("cherry-pick");
316 case REPLAY_INTERACTIVE_REBASE:
317 return N_("rebase -i");
319 die(_("unknown action: %d"), opts->action);
322 struct commit_message {
329 static const char *short_commit_name(struct commit *commit)
331 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
334 static int get_message(struct commit *commit, struct commit_message *out)
336 const char *abbrev, *subject;
339 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
340 abbrev = short_commit_name(commit);
342 subject_len = find_commit_subject(out->message, &subject);
344 out->subject = xmemdupz(subject, subject_len);
345 out->label = xstrfmt("%s... %s", abbrev, out->subject);
346 out->parent_label = xstrfmt("parent of %s", out->label);
351 static void free_message(struct commit *commit, struct commit_message *msg)
353 free(msg->parent_label);
356 unuse_commit_buffer(commit, msg->message);
359 static void print_advice(int show_hint, struct replay_opts *opts)
361 char *msg = getenv("GIT_CHERRY_PICK_HELP");
364 fprintf(stderr, "%s\n", msg);
366 * A conflict has occurred but the porcelain
367 * (typically rebase --interactive) wants to take care
368 * of the commit itself so remove CHERRY_PICK_HEAD
370 unlink(git_path_cherry_pick_head(the_repository));
376 advise(_("after resolving the conflicts, mark the corrected paths\n"
377 "with 'git add <paths>' or 'git rm <paths>'"));
379 advise(_("after resolving the conflicts, mark the corrected paths\n"
380 "with 'git add <paths>' or 'git rm <paths>'\n"
381 "and commit the result with 'git commit'"));
385 int write_message(const void *buf, size_t len, const char *filename,
388 struct lock_file msg_file = LOCK_INIT;
390 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
392 return error_errno(_("could not lock '%s'"), filename);
393 if (write_in_full(msg_fd, buf, len) < 0) {
394 error_errno(_("could not write to '%s'"), filename);
395 rollback_lock_file(&msg_file);
398 if (append_eol && write(msg_fd, "\n", 1) < 0) {
399 error_errno(_("could not write eol to '%s'"), filename);
400 rollback_lock_file(&msg_file);
403 if (commit_lock_file(&msg_file) < 0)
404 return error(_("failed to finalize '%s'"), filename);
410 * Reads a file that was presumably written by a shell script, i.e. with an
411 * end-of-line marker that needs to be stripped.
413 * Note that only the last end-of-line marker is stripped, consistent with the
414 * behavior of "$(cat path)" in a shell script.
416 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
418 static int read_oneliner(struct strbuf *buf,
419 const char *path, int skip_if_empty)
421 int orig_len = buf->len;
423 if (!file_exists(path))
426 if (strbuf_read_file(buf, path, 0) < 0) {
427 warning_errno(_("could not read '%s'"), path);
431 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
432 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
434 buf->buf[buf->len] = '\0';
437 if (skip_if_empty && buf->len == orig_len)
443 static struct tree *empty_tree(void)
445 return lookup_tree(the_repository, the_repository->hash_algo->empty_tree);
448 static int error_dirty_index(struct replay_opts *opts)
450 if (read_cache_unmerged())
451 return error_resolve_conflict(_(action_name(opts)));
453 error(_("your local changes would be overwritten by %s."),
454 _(action_name(opts)));
456 if (advice_commit_before_merge)
457 advise(_("commit your changes or stash them to proceed."));
461 static void update_abort_safety_file(void)
463 struct object_id head;
465 /* Do nothing on a single-pick */
466 if (!file_exists(git_path_seq_dir()))
469 if (!get_oid("HEAD", &head))
470 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
472 write_file(git_path_abort_safety_file(), "%s", "");
475 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
476 int unborn, struct replay_opts *opts)
478 struct ref_transaction *transaction;
479 struct strbuf sb = STRBUF_INIT;
480 struct strbuf err = STRBUF_INIT;
482 read_index(&the_index);
483 if (checkout_fast_forward(the_repository, from, to, 1))
484 return -1; /* the callee should have complained already */
486 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
488 transaction = ref_transaction_begin(&err);
490 ref_transaction_update(transaction, "HEAD",
491 to, unborn && !is_rebase_i(opts) ?
494 ref_transaction_commit(transaction, &err)) {
495 ref_transaction_free(transaction);
496 error("%s", err.buf);
498 strbuf_release(&err);
503 strbuf_release(&err);
504 ref_transaction_free(transaction);
505 update_abort_safety_file();
509 void append_conflicts_hint(struct strbuf *msgbuf)
513 strbuf_addch(msgbuf, '\n');
514 strbuf_commented_addf(msgbuf, "Conflicts:\n");
515 for (i = 0; i < active_nr;) {
516 const struct cache_entry *ce = active_cache[i++];
518 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
519 while (i < active_nr && !strcmp(ce->name,
520 active_cache[i]->name))
526 static int do_recursive_merge(struct commit *base, struct commit *next,
527 const char *base_label, const char *next_label,
528 struct object_id *head, struct strbuf *msgbuf,
529 struct replay_opts *opts)
531 struct merge_options o;
532 struct tree *result, *next_tree, *base_tree, *head_tree;
535 struct lock_file index_lock = LOCK_INIT;
537 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
542 init_merge_options(&o);
543 o.ancestor = base ? base_label : "(empty tree)";
545 o.branch2 = next ? next_label : "(empty tree)";
546 if (is_rebase_i(opts))
548 o.show_rename_progress = 1;
550 head_tree = parse_tree_indirect(head);
551 next_tree = next ? get_commit_tree(next) : empty_tree();
552 base_tree = base ? get_commit_tree(base) : empty_tree();
554 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
555 parse_merge_opt(&o, *xopt);
557 clean = merge_trees(&o,
559 next_tree, base_tree, &result);
560 if (is_rebase_i(opts) && clean <= 0)
561 fputs(o.obuf.buf, stdout);
562 strbuf_release(&o.obuf);
563 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
565 rollback_lock_file(&index_lock);
569 if (write_locked_index(&the_index, &index_lock,
570 COMMIT_LOCK | SKIP_IF_UNCHANGED))
572 * TRANSLATORS: %s will be "revert", "cherry-pick" or
575 return error(_("%s: Unable to write new index file"),
576 _(action_name(opts)));
579 append_conflicts_hint(msgbuf);
584 static struct object_id *get_cache_tree_oid(void)
586 if (!active_cache_tree)
587 active_cache_tree = cache_tree();
589 if (!cache_tree_fully_valid(active_cache_tree))
590 if (cache_tree_update(&the_index, 0)) {
591 error(_("unable to update cache tree"));
595 return &active_cache_tree->oid;
598 static int is_index_unchanged(void)
600 struct object_id head_oid, *cache_tree_oid;
601 struct commit *head_commit;
603 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
604 return error(_("could not resolve HEAD commit"));
606 head_commit = lookup_commit(the_repository, &head_oid);
609 * If head_commit is NULL, check_commit, called from
610 * lookup_commit, would have indicated that head_commit is not
611 * a commit object already. parse_commit() will return failure
612 * without further complaints in such a case. Otherwise, if
613 * the commit is invalid, parse_commit() will complain. So
614 * there is nothing for us to say here. Just return failure.
616 if (parse_commit(head_commit))
619 if (!(cache_tree_oid = get_cache_tree_oid()))
622 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
625 static int write_author_script(const char *message)
627 struct strbuf buf = STRBUF_INIT;
632 if (!*message || starts_with(message, "\n")) {
634 /* Missing 'author' line? */
635 unlink(rebase_path_author_script());
637 } else if (skip_prefix(message, "author ", &message))
639 else if ((eol = strchr(message, '\n')))
644 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
645 while (*message && *message != '\n' && *message != '\r')
646 if (skip_prefix(message, " <", &message))
648 else if (*message != '\'')
649 strbuf_addch(&buf, *(message++));
651 strbuf_addf(&buf, "'\\%c'", *(message++));
652 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
653 while (*message && *message != '\n' && *message != '\r')
654 if (skip_prefix(message, "> ", &message))
656 else if (*message != '\'')
657 strbuf_addch(&buf, *(message++));
659 strbuf_addf(&buf, "'\\%c'", *(message++));
660 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
661 while (*message && *message != '\n' && *message != '\r')
662 if (*message != '\'')
663 strbuf_addch(&buf, *(message++));
665 strbuf_addf(&buf, "'\\%c'", *(message++));
666 strbuf_addch(&buf, '\'');
667 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
668 strbuf_release(&buf);
673 * Take a series of KEY='VALUE' lines where VALUE part is
674 * sq-quoted, and append <KEY, VALUE> at the end of the string list
676 static int parse_key_value_squoted(char *buf, struct string_list *list)
679 struct string_list_item *item;
681 char *cp = strchr(buf, '=');
683 np = strchrnul(buf, '\n');
684 return error(_("no key present in '%.*s'"),
685 (int) (np - buf), buf);
687 np = strchrnul(cp, '\n');
689 item = string_list_append(list, buf);
691 buf = np + (*np == '\n');
695 return error(_("unable to dequote value of '%s'"),
697 item->util = xstrdup(cp);
703 * Reads and parses the state directory's "author-script" file, and sets name,
704 * email and date accordingly.
705 * Returns 0 on success, -1 if the file could not be parsed.
707 * The author script is of the format:
709 * GIT_AUTHOR_NAME='$author_name'
710 * GIT_AUTHOR_EMAIL='$author_email'
711 * GIT_AUTHOR_DATE='$author_date'
713 * where $author_name, $author_email and $author_date are quoted. We are strict
714 * with our parsing, as the file was meant to be eval'd in the old
715 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
716 * from what this function expects, it is better to bail out than to do
717 * something that the user does not expect.
719 int read_author_script(const char *path, char **name, char **email, char **date,
722 struct strbuf buf = STRBUF_INIT;
723 struct string_list kv = STRING_LIST_INIT_DUP;
724 int retval = -1; /* assume failure */
725 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
727 if (strbuf_read_file(&buf, path, 256) <= 0) {
728 strbuf_release(&buf);
729 if (errno == ENOENT && allow_missing)
732 return error_errno(_("could not open '%s' for reading"),
736 if (parse_key_value_squoted(buf.buf, &kv))
739 for (i = 0; i < kv.nr; i++) {
740 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
742 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
745 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
747 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
750 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
752 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
756 err = error(_("unknown variable '%s'"),
761 error(_("missing 'GIT_AUTHOR_NAME'"));
763 error(_("missing 'GIT_AUTHOR_EMAIL'"));
765 error(_("missing 'GIT_AUTHOR_DATE'"));
766 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
768 *name = kv.items[name_i].util;
769 *email = kv.items[email_i].util;
770 *date = kv.items[date_i].util;
773 string_list_clear(&kv, !!retval);
774 strbuf_release(&buf);
779 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
780 * file with shell quoting into struct argv_array. Returns -1 on
781 * error, 0 otherwise.
783 static int read_env_script(struct argv_array *env)
785 char *name, *email, *date;
787 if (read_author_script(rebase_path_author_script(),
788 &name, &email, &date, 0))
791 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
792 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
793 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
801 static char *get_author(const char *message)
806 a = find_commit_header(message, "author", &len);
808 return xmemdupz(a, len);
813 /* Read author-script and return an ident line (author <email> timestamp) */
814 static const char *read_author_ident(struct strbuf *buf)
816 struct strbuf out = STRBUF_INIT;
817 char *name, *email, *date;
819 if (read_author_script(rebase_path_author_script(),
820 &name, &email, &date, 0))
823 /* validate date since fmt_ident() will die() on bad value */
824 if (parse_date(date, &out)){
825 warning(_("invalid date format '%s' in '%s'"),
826 date, rebase_path_author_script());
827 strbuf_release(&out);
832 strbuf_addstr(&out, fmt_ident(name, email, date, 0));
833 strbuf_swap(buf, &out);
834 strbuf_release(&out);
841 static const char staged_changes_advice[] =
842 N_("you have staged changes in your working tree\n"
843 "If these changes are meant to be squashed into the previous commit, run:\n"
845 " git commit --amend %s\n"
847 "If they are meant to go into a new commit, run:\n"
851 "In both cases, once you're done, continue with:\n"
853 " git rebase --continue\n");
855 #define ALLOW_EMPTY (1<<0)
856 #define EDIT_MSG (1<<1)
857 #define AMEND_MSG (1<<2)
858 #define CLEANUP_MSG (1<<3)
859 #define VERIFY_MSG (1<<4)
860 #define CREATE_ROOT_COMMIT (1<<5)
862 static int run_command_silent_on_success(struct child_process *cmd)
864 struct strbuf buf = STRBUF_INIT;
867 cmd->stdout_to_stderr = 1;
868 rc = pipe_command(cmd,
874 fputs(buf.buf, stderr);
875 strbuf_release(&buf);
880 * If we are cherry-pick, and if the merge did not result in
881 * hand-editing, we will hit this commit and inherit the original
882 * author date and name.
884 * If we are revert, or if our cherry-pick results in a hand merge,
885 * we had better say that the current user is responsible for that.
887 * An exception is when run_git_commit() is called during an
888 * interactive rebase: in that case, we will want to retain the
891 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
894 struct child_process cmd = CHILD_PROCESS_INIT;
897 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
898 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
899 const char *author = NULL;
900 struct object_id root_commit, *cache_tree_oid;
903 if (is_rebase_i(opts)) {
904 author = read_author_ident(&script);
906 strbuf_release(&script);
912 BUG("root commit without message");
914 if (!(cache_tree_oid = get_cache_tree_oid()))
918 res = strbuf_read_file(&msg, defmsg, 0);
921 res = error_errno(_("could not read '%s'"), defmsg);
923 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
924 NULL, &root_commit, author,
927 strbuf_release(&msg);
928 strbuf_release(&script);
930 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
931 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
932 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
933 UPDATE_REFS_MSG_ON_ERR);
935 return res < 0 ? error(_("writing root commit")) : 0;
940 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
941 const char *gpg_opt = gpg_sign_opt_quoted(opts);
943 return error(_(staged_changes_advice),
947 argv_array_push(&cmd.args, "commit");
949 if (!(flags & VERIFY_MSG))
950 argv_array_push(&cmd.args, "-n");
951 if ((flags & AMEND_MSG))
952 argv_array_push(&cmd.args, "--amend");
954 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
956 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
957 else if (!(flags & EDIT_MSG))
958 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
959 if ((flags & CLEANUP_MSG))
960 argv_array_push(&cmd.args, "--cleanup=strip");
961 if ((flags & EDIT_MSG))
962 argv_array_push(&cmd.args, "-e");
963 else if (!(flags & CLEANUP_MSG) &&
964 !opts->signoff && !opts->record_origin &&
965 git_config_get_value("commit.cleanup", &value))
966 argv_array_push(&cmd.args, "--cleanup=verbatim");
968 if ((flags & ALLOW_EMPTY))
969 argv_array_push(&cmd.args, "--allow-empty");
971 if (!(flags & EDIT_MSG))
972 argv_array_push(&cmd.args, "--allow-empty-message");
974 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
975 return run_command_silent_on_success(&cmd);
977 return run_command(&cmd);
980 static int rest_is_empty(const struct strbuf *sb, int start)
985 /* Check if the rest is just whitespace and Signed-off-by's. */
986 for (i = start; i < sb->len; i++) {
987 nl = memchr(sb->buf + i, '\n', sb->len - i);
993 if (strlen(sign_off_header) <= eol - i &&
994 starts_with(sb->buf + i, sign_off_header)) {
999 if (!isspace(sb->buf[i++]))
1007 * Find out if the message in the strbuf contains only whitespace and
1008 * Signed-off-by lines.
1010 int message_is_empty(const struct strbuf *sb,
1011 enum commit_msg_cleanup_mode cleanup_mode)
1013 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1015 return rest_is_empty(sb, 0);
1019 * See if the user edited the message in the editor or left what
1020 * was in the template intact
1022 int template_untouched(const struct strbuf *sb, const char *template_file,
1023 enum commit_msg_cleanup_mode cleanup_mode)
1025 struct strbuf tmpl = STRBUF_INIT;
1028 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1031 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1034 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1035 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1037 strbuf_release(&tmpl);
1038 return rest_is_empty(sb, start - sb->buf);
1041 int update_head_with_reflog(const struct commit *old_head,
1042 const struct object_id *new_head,
1043 const char *action, const struct strbuf *msg,
1046 struct ref_transaction *transaction;
1047 struct strbuf sb = STRBUF_INIT;
1052 strbuf_addstr(&sb, action);
1053 strbuf_addstr(&sb, ": ");
1056 nl = strchr(msg->buf, '\n');
1058 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1060 strbuf_addbuf(&sb, msg);
1061 strbuf_addch(&sb, '\n');
1064 transaction = ref_transaction_begin(err);
1066 ref_transaction_update(transaction, "HEAD", new_head,
1067 old_head ? &old_head->object.oid : &null_oid,
1069 ref_transaction_commit(transaction, err)) {
1072 ref_transaction_free(transaction);
1073 strbuf_release(&sb);
1078 static int run_rewrite_hook(const struct object_id *oldoid,
1079 const struct object_id *newoid)
1081 struct child_process proc = CHILD_PROCESS_INIT;
1082 const char *argv[3];
1084 struct strbuf sb = STRBUF_INIT;
1086 argv[0] = find_hook("post-rewrite");
1095 proc.stdout_to_stderr = 1;
1097 code = start_command(&proc);
1100 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1101 sigchain_push(SIGPIPE, SIG_IGN);
1102 write_in_full(proc.in, sb.buf, sb.len);
1104 strbuf_release(&sb);
1105 sigchain_pop(SIGPIPE);
1106 return finish_command(&proc);
1109 void commit_post_rewrite(const struct commit *old_head,
1110 const struct object_id *new_head)
1112 struct notes_rewrite_cfg *cfg;
1114 cfg = init_copy_notes_for_rewrite("amend");
1116 /* we are amending, so old_head is not NULL */
1117 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1118 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1120 run_rewrite_hook(&old_head->object.oid, new_head);
1123 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
1125 struct argv_array hook_env = ARGV_ARRAY_INIT;
1129 name = git_path_commit_editmsg();
1130 if (write_message(msg->buf, msg->len, name, 0))
1133 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
1134 argv_array_push(&hook_env, "GIT_EDITOR=:");
1136 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1137 "commit", commit, NULL);
1139 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1142 ret = error(_("'prepare-commit-msg' hook failed"));
1143 argv_array_clear(&hook_env);
1148 static const char implicit_ident_advice_noconfig[] =
1149 N_("Your name and email address were configured automatically based\n"
1150 "on your username and hostname. Please check that they are accurate.\n"
1151 "You can suppress this message by setting them explicitly. Run the\n"
1152 "following command and follow the instructions in your editor to edit\n"
1153 "your configuration file:\n"
1155 " git config --global --edit\n"
1157 "After doing this, you may fix the identity used for this commit with:\n"
1159 " git commit --amend --reset-author\n");
1161 static const char implicit_ident_advice_config[] =
1162 N_("Your name and email address were configured automatically based\n"
1163 "on your username and hostname. Please check that they are accurate.\n"
1164 "You can suppress this message by setting them explicitly:\n"
1166 " git config --global user.name \"Your Name\"\n"
1167 " git config --global user.email you@example.com\n"
1169 "After doing this, you may fix the identity used for this commit with:\n"
1171 " git commit --amend --reset-author\n");
1173 static const char *implicit_ident_advice(void)
1175 char *user_config = expand_user_path("~/.gitconfig", 0);
1176 char *xdg_config = xdg_config_home("config");
1177 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1183 return _(implicit_ident_advice_config);
1185 return _(implicit_ident_advice_noconfig);
1189 void print_commit_summary(const char *prefix, const struct object_id *oid,
1192 struct rev_info rev;
1193 struct commit *commit;
1194 struct strbuf format = STRBUF_INIT;
1196 struct pretty_print_context pctx = {0};
1197 struct strbuf author_ident = STRBUF_INIT;
1198 struct strbuf committer_ident = STRBUF_INIT;
1200 commit = lookup_commit(the_repository, oid);
1202 die(_("couldn't look up newly created commit"));
1203 if (parse_commit(commit))
1204 die(_("could not parse newly created commit"));
1206 strbuf_addstr(&format, "format:%h] %s");
1208 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1209 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1210 if (strbuf_cmp(&author_ident, &committer_ident)) {
1211 strbuf_addstr(&format, "\n Author: ");
1212 strbuf_addbuf_percentquote(&format, &author_ident);
1214 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1215 struct strbuf date = STRBUF_INIT;
1217 format_commit_message(commit, "%ad", &date, &pctx);
1218 strbuf_addstr(&format, "\n Date: ");
1219 strbuf_addbuf_percentquote(&format, &date);
1220 strbuf_release(&date);
1222 if (!committer_ident_sufficiently_given()) {
1223 strbuf_addstr(&format, "\n Committer: ");
1224 strbuf_addbuf_percentquote(&format, &committer_ident);
1225 if (advice_implicit_identity) {
1226 strbuf_addch(&format, '\n');
1227 strbuf_addstr(&format, implicit_ident_advice());
1230 strbuf_release(&author_ident);
1231 strbuf_release(&committer_ident);
1233 repo_init_revisions(the_repository, &rev, prefix);
1234 setup_revisions(0, NULL, &rev, NULL);
1237 rev.diffopt.output_format =
1238 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1240 rev.verbose_header = 1;
1241 rev.show_root_diff = 1;
1242 get_commit_format(format.buf, &rev);
1243 rev.always_show_header = 0;
1244 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1245 rev.diffopt.break_opt = 0;
1246 diff_setup_done(&rev.diffopt);
1248 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1250 die_errno(_("unable to resolve HEAD after creating commit"));
1251 if (!strcmp(head, "HEAD"))
1252 head = _("detached HEAD");
1254 skip_prefix(head, "refs/heads/", &head);
1255 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1256 _(" (root-commit)") : "");
1258 if (!log_tree_commit(&rev, commit)) {
1259 rev.always_show_header = 1;
1260 rev.use_terminator = 1;
1261 log_tree_commit(&rev, commit);
1264 strbuf_release(&format);
1267 static int parse_head(struct commit **head)
1269 struct commit *current_head;
1270 struct object_id oid;
1272 if (get_oid("HEAD", &oid)) {
1273 current_head = NULL;
1275 current_head = lookup_commit_reference(the_repository, &oid);
1277 return error(_("could not parse HEAD"));
1278 if (!oideq(&oid, ¤t_head->object.oid)) {
1279 warning(_("HEAD %s is not a commit!"),
1282 if (parse_commit(current_head))
1283 return error(_("could not parse HEAD commit"));
1285 *head = current_head;
1291 * Try to commit without forking 'git commit'. In some cases we need
1292 * to run 'git commit' to display an error message
1295 * -1 - error unable to commit
1297 * 1 - run 'git commit'
1299 static int try_to_commit(struct strbuf *msg, const char *author,
1300 struct replay_opts *opts, unsigned int flags,
1301 struct object_id *oid)
1303 struct object_id tree;
1304 struct commit *current_head;
1305 struct commit_list *parents = NULL;
1306 struct commit_extra_header *extra = NULL;
1307 struct strbuf err = STRBUF_INIT;
1308 struct strbuf commit_msg = STRBUF_INIT;
1309 char *amend_author = NULL;
1310 const char *hook_commit = NULL;
1311 enum commit_msg_cleanup_mode cleanup;
1314 if (parse_head(¤t_head))
1317 if (flags & AMEND_MSG) {
1318 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1319 const char *out_enc = get_commit_output_encoding();
1320 const char *message = logmsg_reencode(current_head, NULL,
1324 const char *orig_message = NULL;
1326 find_commit_subject(message, &orig_message);
1328 strbuf_addstr(msg, orig_message);
1329 hook_commit = "HEAD";
1331 author = amend_author = get_author(message);
1332 unuse_commit_buffer(current_head, message);
1334 res = error(_("unable to parse commit author"));
1337 parents = copy_commit_list(current_head->parents);
1338 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1339 } else if (current_head) {
1340 commit_list_insert(current_head, &parents);
1343 if (write_index_as_tree(&tree, &the_index, get_index_file(), 0, NULL)) {
1344 res = error(_("git write-tree failed to write a tree"));
1348 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1349 get_commit_tree_oid(current_head) :
1350 the_hash_algo->empty_tree, &tree)) {
1351 res = 1; /* run 'git commit' to display error message */
1355 if (find_hook("prepare-commit-msg")) {
1356 res = run_prepare_commit_msg_hook(msg, hook_commit);
1359 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1361 res = error_errno(_("unable to read commit message "
1363 git_path_commit_editmsg());
1369 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1370 opts->default_msg_cleanup;
1372 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1373 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1374 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1375 res = 1; /* run 'git commit' to display error message */
1381 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1382 oid, author, opts->gpg_sign, extra)) {
1383 res = error(_("failed to write commit object"));
1387 if (update_head_with_reflog(current_head, oid,
1388 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1389 res = error("%s", err.buf);
1393 if (flags & AMEND_MSG)
1394 commit_post_rewrite(current_head, oid);
1397 free_commit_extra_headers(extra);
1398 strbuf_release(&err);
1399 strbuf_release(&commit_msg);
1405 static int do_commit(const char *msg_file, const char *author,
1406 struct replay_opts *opts, unsigned int flags)
1410 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1411 !(flags & CREATE_ROOT_COMMIT)) {
1412 struct object_id oid;
1413 struct strbuf sb = STRBUF_INIT;
1415 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1416 return error_errno(_("unable to read commit message "
1420 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1422 strbuf_release(&sb);
1424 unlink(git_path_cherry_pick_head(the_repository));
1425 unlink(git_path_merge_msg(the_repository));
1426 if (!is_rebase_i(opts))
1427 print_commit_summary(NULL, &oid,
1428 SUMMARY_SHOW_AUTHOR_DATE);
1433 return run_git_commit(msg_file, opts, flags);
1438 static int is_original_commit_empty(struct commit *commit)
1440 const struct object_id *ptree_oid;
1442 if (parse_commit(commit))
1443 return error(_("could not parse commit %s"),
1444 oid_to_hex(&commit->object.oid));
1445 if (commit->parents) {
1446 struct commit *parent = commit->parents->item;
1447 if (parse_commit(parent))
1448 return error(_("could not parse parent commit %s"),
1449 oid_to_hex(&parent->object.oid));
1450 ptree_oid = get_commit_tree_oid(parent);
1452 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1455 return oideq(ptree_oid, get_commit_tree_oid(commit));
1459 * Do we run "git commit" with "--allow-empty"?
1461 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1463 int index_unchanged, empty_commit;
1468 * (1) we do not allow empty at all and error out.
1470 * (2) we allow ones that were initially empty, but
1471 * forbid the ones that become empty;
1473 * (3) we allow both.
1475 if (!opts->allow_empty)
1476 return 0; /* let "git commit" barf as necessary */
1478 index_unchanged = is_index_unchanged();
1479 if (index_unchanged < 0)
1480 return index_unchanged;
1481 if (!index_unchanged)
1482 return 0; /* we do not have to say --allow-empty */
1484 if (opts->keep_redundant_commits)
1487 empty_commit = is_original_commit_empty(commit);
1488 if (empty_commit < 0)
1489 return empty_commit;
1497 * Note that ordering matters in this enum. Not only must it match the mapping
1498 * below, it is also divided into several sections that matter. When adding
1499 * new commands, make sure you add it in the right section.
1502 /* commands that handle commits */
1509 /* commands that do something else than handling a single commit */
1515 /* commands that do nothing but are counted for reporting progress */
1518 /* comments (not counted for reporting progress) */
1525 } todo_command_info[] = {
1542 static const char *command_to_string(const enum todo_command command)
1544 if (command < TODO_COMMENT)
1545 return todo_command_info[command].str;
1546 die(_("unknown command: %d"), command);
1549 static char command_to_char(const enum todo_command command)
1551 if (command < TODO_COMMENT && todo_command_info[command].c)
1552 return todo_command_info[command].c;
1553 return comment_line_char;
1556 static int is_noop(const enum todo_command command)
1558 return TODO_NOOP <= command;
1561 static int is_fixup(enum todo_command command)
1563 return command == TODO_FIXUP || command == TODO_SQUASH;
1566 /* Does this command create a (non-merge) commit? */
1567 static int is_pick_or_similar(enum todo_command command)
1582 static int update_squash_messages(enum todo_command command,
1583 struct commit *commit, struct replay_opts *opts)
1585 struct strbuf buf = STRBUF_INIT;
1587 const char *message, *body;
1589 if (opts->current_fixup_count > 0) {
1590 struct strbuf header = STRBUF_INIT;
1593 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1594 return error(_("could not read '%s'"),
1595 rebase_path_squash_msg());
1597 eol = buf.buf[0] != comment_line_char ?
1598 buf.buf : strchrnul(buf.buf, '\n');
1600 strbuf_addf(&header, "%c ", comment_line_char);
1601 strbuf_addf(&header, _("This is a combination of %d commits."),
1602 opts->current_fixup_count + 2);
1603 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1604 strbuf_release(&header);
1606 struct object_id head;
1607 struct commit *head_commit;
1608 const char *head_message, *body;
1610 if (get_oid("HEAD", &head))
1611 return error(_("need a HEAD to fixup"));
1612 if (!(head_commit = lookup_commit_reference(the_repository, &head)))
1613 return error(_("could not read HEAD"));
1614 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1615 return error(_("could not read HEAD's commit message"));
1617 find_commit_subject(head_message, &body);
1618 if (write_message(body, strlen(body),
1619 rebase_path_fixup_msg(), 0)) {
1620 unuse_commit_buffer(head_commit, head_message);
1621 return error(_("cannot write '%s'"),
1622 rebase_path_fixup_msg());
1625 strbuf_addf(&buf, "%c ", comment_line_char);
1626 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1627 strbuf_addf(&buf, "\n%c ", comment_line_char);
1628 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1629 strbuf_addstr(&buf, "\n\n");
1630 strbuf_addstr(&buf, body);
1632 unuse_commit_buffer(head_commit, head_message);
1635 if (!(message = get_commit_buffer(commit, NULL)))
1636 return error(_("could not read commit message of %s"),
1637 oid_to_hex(&commit->object.oid));
1638 find_commit_subject(message, &body);
1640 if (command == TODO_SQUASH) {
1641 unlink(rebase_path_fixup_msg());
1642 strbuf_addf(&buf, "\n%c ", comment_line_char);
1643 strbuf_addf(&buf, _("This is the commit message #%d:"),
1644 ++opts->current_fixup_count + 1);
1645 strbuf_addstr(&buf, "\n\n");
1646 strbuf_addstr(&buf, body);
1647 } else if (command == TODO_FIXUP) {
1648 strbuf_addf(&buf, "\n%c ", comment_line_char);
1649 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1650 ++opts->current_fixup_count + 1);
1651 strbuf_addstr(&buf, "\n\n");
1652 strbuf_add_commented_lines(&buf, body, strlen(body));
1654 return error(_("unknown command: %d"), command);
1655 unuse_commit_buffer(commit, message);
1657 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1658 strbuf_release(&buf);
1661 strbuf_addf(&opts->current_fixups, "%s%s %s",
1662 opts->current_fixups.len ? "\n" : "",
1663 command_to_string(command),
1664 oid_to_hex(&commit->object.oid));
1665 res = write_message(opts->current_fixups.buf,
1666 opts->current_fixups.len,
1667 rebase_path_current_fixups(), 0);
1673 static void flush_rewritten_pending(void)
1675 struct strbuf buf = STRBUF_INIT;
1676 struct object_id newoid;
1679 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1680 !get_oid("HEAD", &newoid) &&
1681 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1682 char *bol = buf.buf, *eol;
1685 eol = strchrnul(bol, '\n');
1686 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1687 bol, oid_to_hex(&newoid));
1693 unlink(rebase_path_rewritten_pending());
1695 strbuf_release(&buf);
1698 static void record_in_rewritten(struct object_id *oid,
1699 enum todo_command next_command)
1701 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1706 fprintf(out, "%s\n", oid_to_hex(oid));
1709 if (!is_fixup(next_command))
1710 flush_rewritten_pending();
1713 static int do_pick_commit(enum todo_command command, struct commit *commit,
1714 struct replay_opts *opts, int final_fixup)
1716 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1717 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(the_repository);
1718 struct object_id head;
1719 struct commit *base, *next, *parent;
1720 const char *base_label, *next_label;
1721 char *author = NULL;
1722 struct commit_message msg = { NULL, NULL, NULL, NULL };
1723 struct strbuf msgbuf = STRBUF_INIT;
1724 int res, unborn = 0, allow;
1726 if (opts->no_commit) {
1728 * We do not intend to commit immediately. We just want to
1729 * merge the differences in, so let's compute the tree
1730 * that represents the "current" state for merge-recursive
1733 if (write_index_as_tree(&head, &the_index, get_index_file(), 0, NULL))
1734 return error(_("your index file is unmerged."));
1736 unborn = get_oid("HEAD", &head);
1737 /* Do we want to generate a root commit? */
1738 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1739 oideq(&head, &opts->squash_onto)) {
1740 if (is_fixup(command))
1741 return error(_("cannot fixup root commit"));
1742 flags |= CREATE_ROOT_COMMIT;
1745 oidcpy(&head, the_hash_algo->empty_tree);
1746 if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
1748 return error_dirty_index(opts);
1752 if (!commit->parents)
1754 else if (commit->parents->next) {
1755 /* Reverting or cherry-picking a merge commit */
1757 struct commit_list *p;
1759 if (!opts->mainline)
1760 return error(_("commit %s is a merge but no -m option was given."),
1761 oid_to_hex(&commit->object.oid));
1763 for (cnt = 1, p = commit->parents;
1764 cnt != opts->mainline && p;
1767 if (cnt != opts->mainline || !p)
1768 return error(_("commit %s does not have parent %d"),
1769 oid_to_hex(&commit->object.oid), opts->mainline);
1771 } else if (0 < opts->mainline)
1772 return error(_("mainline was specified but commit %s is not a merge."),
1773 oid_to_hex(&commit->object.oid));
1775 parent = commit->parents->item;
1777 if (get_message(commit, &msg) != 0)
1778 return error(_("cannot get commit message for %s"),
1779 oid_to_hex(&commit->object.oid));
1781 if (opts->allow_ff && !is_fixup(command) &&
1782 ((parent && oideq(&parent->object.oid, &head)) ||
1783 (!parent && unborn))) {
1784 if (is_rebase_i(opts))
1785 write_author_script(msg.message);
1786 res = fast_forward_to(&commit->object.oid, &head, unborn,
1788 if (res || command != TODO_REWORD)
1790 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1792 goto fast_forward_edit;
1794 if (parent && parse_commit(parent) < 0)
1795 /* TRANSLATORS: The first %s will be a "todo" command like
1796 "revert" or "pick", the second %s a SHA1. */
1797 return error(_("%s: cannot parse parent commit %s"),
1798 command_to_string(command),
1799 oid_to_hex(&parent->object.oid));
1802 * "commit" is an existing commit. We would want to apply
1803 * the difference it introduces since its first parent "prev"
1804 * on top of the current HEAD if we are cherry-pick. Or the
1805 * reverse of it if we are revert.
1808 if (command == TODO_REVERT) {
1810 base_label = msg.label;
1812 next_label = msg.parent_label;
1813 strbuf_addstr(&msgbuf, "Revert \"");
1814 strbuf_addstr(&msgbuf, msg.subject);
1815 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1816 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1818 if (commit->parents && commit->parents->next) {
1819 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1820 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1822 strbuf_addstr(&msgbuf, ".\n");
1827 base_label = msg.parent_label;
1829 next_label = msg.label;
1831 /* Append the commit log message to msgbuf. */
1832 if (find_commit_subject(msg.message, &p))
1833 strbuf_addstr(&msgbuf, p);
1835 if (opts->record_origin) {
1836 strbuf_complete_line(&msgbuf);
1837 if (!has_conforming_footer(&msgbuf, NULL, 0))
1838 strbuf_addch(&msgbuf, '\n');
1839 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1840 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1841 strbuf_addstr(&msgbuf, ")\n");
1843 if (!is_fixup(command))
1844 author = get_author(msg.message);
1847 if (command == TODO_REWORD)
1848 flags |= EDIT_MSG | VERIFY_MSG;
1849 else if (is_fixup(command)) {
1850 if (update_squash_messages(command, commit, opts))
1854 msg_file = rebase_path_squash_msg();
1855 else if (file_exists(rebase_path_fixup_msg())) {
1856 flags |= CLEANUP_MSG;
1857 msg_file = rebase_path_fixup_msg();
1859 const char *dest = git_path_squash_msg(the_repository);
1861 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1862 return error(_("could not rename '%s' to '%s'"),
1863 rebase_path_squash_msg(), dest);
1864 unlink(git_path_merge_msg(the_repository));
1870 if (opts->signoff && !is_fixup(command))
1871 append_signoff(&msgbuf, 0, 0);
1873 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1875 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1876 res = do_recursive_merge(base, next, base_label, next_label,
1877 &head, &msgbuf, opts);
1881 res |= write_message(msgbuf.buf, msgbuf.len,
1882 git_path_merge_msg(the_repository), 0);
1884 struct commit_list *common = NULL;
1885 struct commit_list *remotes = NULL;
1887 res = write_message(msgbuf.buf, msgbuf.len,
1888 git_path_merge_msg(the_repository), 0);
1890 commit_list_insert(base, &common);
1891 commit_list_insert(next, &remotes);
1892 res |= try_merge_command(the_repository, opts->strategy,
1893 opts->xopts_nr, (const char **)opts->xopts,
1894 common, oid_to_hex(&head), remotes);
1895 free_commit_list(common);
1896 free_commit_list(remotes);
1898 strbuf_release(&msgbuf);
1901 * If the merge was clean or if it failed due to conflict, we write
1902 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1903 * However, if the merge did not even start, then we don't want to
1906 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1907 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1908 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1910 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1911 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1912 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1916 error(command == TODO_REVERT
1917 ? _("could not revert %s... %s")
1918 : _("could not apply %s... %s"),
1919 short_commit_name(commit), msg.subject);
1920 print_advice(res == 1, opts);
1921 repo_rerere(the_repository, opts->allow_rerere_auto);
1925 allow = allow_empty(opts, commit);
1930 flags |= ALLOW_EMPTY;
1931 if (!opts->no_commit) {
1933 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1934 res = do_commit(msg_file, author, opts, flags);
1936 res = error(_("unable to parse commit author"));
1939 if (!res && final_fixup) {
1940 unlink(rebase_path_fixup_msg());
1941 unlink(rebase_path_squash_msg());
1942 unlink(rebase_path_current_fixups());
1943 strbuf_reset(&opts->current_fixups);
1944 opts->current_fixup_count = 0;
1948 free_message(commit, &msg);
1950 update_abort_safety_file();
1955 static int prepare_revs(struct replay_opts *opts)
1958 * picking (but not reverting) ranges (but not individual revisions)
1959 * should be done in reverse
1961 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1962 opts->revs->reverse ^= 1;
1964 if (prepare_revision_walk(opts->revs))
1965 return error(_("revision walk setup failed"));
1970 static int read_and_refresh_cache(struct replay_opts *opts)
1972 struct lock_file index_lock = LOCK_INIT;
1973 int index_fd = hold_locked_index(&index_lock, 0);
1974 if (read_index(&the_index) < 0) {
1975 rollback_lock_file(&index_lock);
1976 return error(_("git %s: failed to read the index"),
1977 _(action_name(opts)));
1979 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1980 if (index_fd >= 0) {
1981 if (write_locked_index(&the_index, &index_lock,
1982 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1983 return error(_("git %s: failed to refresh the index"),
1984 _(action_name(opts)));
1990 enum todo_item_flags {
1991 TODO_EDIT_MERGE_MSG = 1
1995 enum todo_command command;
1996 struct commit *commit;
2000 size_t offset_in_buf;
2005 struct todo_item *items;
2006 int nr, alloc, current;
2007 int done_nr, total_nr;
2008 struct stat_data stat;
2011 #define TODO_LIST_INIT { STRBUF_INIT }
2013 static void todo_list_release(struct todo_list *todo_list)
2015 strbuf_release(&todo_list->buf);
2016 FREE_AND_NULL(todo_list->items);
2017 todo_list->nr = todo_list->alloc = 0;
2020 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2022 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2023 return todo_list->items + todo_list->nr++;
2026 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
2028 struct object_id commit_oid;
2029 char *end_of_object_name;
2030 int i, saved, status, padding;
2035 bol += strspn(bol, " \t");
2037 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2038 item->command = TODO_COMMENT;
2039 item->commit = NULL;
2041 item->arg_len = eol - bol;
2045 for (i = 0; i < TODO_COMMENT; i++)
2046 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2049 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2050 *bol == todo_command_info[i].c) {
2055 if (i >= TODO_COMMENT)
2058 /* Eat up extra spaces/ tabs before object name */
2059 padding = strspn(bol, " \t");
2062 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2064 return error(_("%s does not accept arguments: '%s'"),
2065 command_to_string(item->command), bol);
2066 item->commit = NULL;
2068 item->arg_len = eol - bol;
2073 return error(_("missing arguments for %s"),
2074 command_to_string(item->command));
2076 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2077 item->command == TODO_RESET) {
2078 item->commit = NULL;
2080 item->arg_len = (int)(eol - bol);
2084 if (item->command == TODO_MERGE) {
2085 if (skip_prefix(bol, "-C", &bol))
2086 bol += strspn(bol, " \t");
2087 else if (skip_prefix(bol, "-c", &bol)) {
2088 bol += strspn(bol, " \t");
2089 item->flags |= TODO_EDIT_MERGE_MSG;
2091 item->flags |= TODO_EDIT_MERGE_MSG;
2092 item->commit = NULL;
2094 item->arg_len = (int)(eol - bol);
2099 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2100 saved = *end_of_object_name;
2101 *end_of_object_name = '\0';
2102 status = get_oid(bol, &commit_oid);
2103 *end_of_object_name = saved;
2105 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2106 item->arg_len = (int)(eol - item->arg);
2111 item->commit = lookup_commit_reference(the_repository, &commit_oid);
2112 return !item->commit;
2115 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
2117 struct todo_item *item;
2118 char *p = buf, *next_p;
2119 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2121 for (i = 1; *p; i++, p = next_p) {
2122 char *eol = strchrnul(p, '\n');
2124 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2126 if (p != eol && eol[-1] == '\r')
2127 eol--; /* strip Carriage Return */
2129 item = append_new_todo(todo_list);
2130 item->offset_in_buf = p - todo_list->buf.buf;
2131 if (parse_insn_line(item, p, eol)) {
2132 res = error(_("invalid line %d: %.*s"),
2133 i, (int)(eol - p), p);
2134 item->command = TODO_NOOP;
2139 else if (is_fixup(item->command))
2140 return error(_("cannot '%s' without a previous commit"),
2141 command_to_string(item->command));
2142 else if (!is_noop(item->command))
2149 static int count_commands(struct todo_list *todo_list)
2153 for (i = 0; i < todo_list->nr; i++)
2154 if (todo_list->items[i].command != TODO_COMMENT)
2160 static int get_item_line_offset(struct todo_list *todo_list, int index)
2162 return index < todo_list->nr ?
2163 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2166 static const char *get_item_line(struct todo_list *todo_list, int index)
2168 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2171 static int get_item_line_length(struct todo_list *todo_list, int index)
2173 return get_item_line_offset(todo_list, index + 1)
2174 - get_item_line_offset(todo_list, index);
2177 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2182 fd = open(path, O_RDONLY);
2184 return error_errno(_("could not open '%s'"), path);
2185 len = strbuf_read(sb, fd, 0);
2188 return error(_("could not read '%s'."), path);
2192 static int read_populate_todo(struct todo_list *todo_list,
2193 struct replay_opts *opts)
2196 const char *todo_file = get_todo_path(opts);
2199 strbuf_reset(&todo_list->buf);
2200 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2203 res = stat(todo_file, &st);
2205 return error(_("could not stat '%s'"), todo_file);
2206 fill_stat_data(&todo_list->stat, &st);
2208 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2210 if (is_rebase_i(opts))
2211 return error(_("please fix this using "
2212 "'git rebase --edit-todo'."));
2213 return error(_("unusable instruction sheet: '%s'"), todo_file);
2216 if (!todo_list->nr &&
2217 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2218 return error(_("no commits parsed."));
2220 if (!is_rebase_i(opts)) {
2221 enum todo_command valid =
2222 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2225 for (i = 0; i < todo_list->nr; i++)
2226 if (valid == todo_list->items[i].command)
2228 else if (valid == TODO_PICK)
2229 return error(_("cannot cherry-pick during a revert."));
2231 return error(_("cannot revert during a cherry-pick."));
2234 if (is_rebase_i(opts)) {
2235 struct todo_list done = TODO_LIST_INIT;
2236 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2238 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2239 !parse_insn_buffer(done.buf.buf, &done))
2240 todo_list->done_nr = count_commands(&done);
2242 todo_list->done_nr = 0;
2244 todo_list->total_nr = todo_list->done_nr
2245 + count_commands(todo_list);
2246 todo_list_release(&done);
2249 fprintf(f, "%d\n", todo_list->total_nr);
2257 static int git_config_string_dup(char **dest,
2258 const char *var, const char *value)
2261 return config_error_nonbool(var);
2263 *dest = xstrdup(value);
2267 static int populate_opts_cb(const char *key, const char *value, void *data)
2269 struct replay_opts *opts = data;
2274 else if (!strcmp(key, "options.no-commit"))
2275 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2276 else if (!strcmp(key, "options.edit"))
2277 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2278 else if (!strcmp(key, "options.signoff"))
2279 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2280 else if (!strcmp(key, "options.record-origin"))
2281 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2282 else if (!strcmp(key, "options.allow-ff"))
2283 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2284 else if (!strcmp(key, "options.mainline"))
2285 opts->mainline = git_config_int(key, value);
2286 else if (!strcmp(key, "options.strategy"))
2287 git_config_string_dup(&opts->strategy, key, value);
2288 else if (!strcmp(key, "options.gpg-sign"))
2289 git_config_string_dup(&opts->gpg_sign, key, value);
2290 else if (!strcmp(key, "options.strategy-option")) {
2291 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2292 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2293 } else if (!strcmp(key, "options.allow-rerere-auto"))
2294 opts->allow_rerere_auto =
2295 git_config_bool_or_int(key, value, &error_flag) ?
2296 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2298 return error(_("invalid key: %s"), key);
2301 return error(_("invalid value for %s: %s"), key, value);
2306 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2309 char *strategy_opts_string = raw_opts;
2311 if (*strategy_opts_string == ' ')
2312 strategy_opts_string++;
2314 opts->xopts_nr = split_cmdline(strategy_opts_string,
2315 (const char ***)&opts->xopts);
2316 for (i = 0; i < opts->xopts_nr; i++) {
2317 const char *arg = opts->xopts[i];
2319 skip_prefix(arg, "--", &arg);
2320 opts->xopts[i] = xstrdup(arg);
2324 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2327 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2329 opts->strategy = strbuf_detach(buf, NULL);
2330 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2333 parse_strategy_opts(opts, buf->buf);
2336 static int read_populate_opts(struct replay_opts *opts)
2338 if (is_rebase_i(opts)) {
2339 struct strbuf buf = STRBUF_INIT;
2341 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2342 if (!starts_with(buf.buf, "-S"))
2345 free(opts->gpg_sign);
2346 opts->gpg_sign = xstrdup(buf.buf + 2);
2351 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2352 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2353 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2354 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2355 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2359 if (file_exists(rebase_path_verbose()))
2362 if (file_exists(rebase_path_signoff())) {
2367 read_strategy_opts(opts, &buf);
2368 strbuf_release(&buf);
2370 if (read_oneliner(&opts->current_fixups,
2371 rebase_path_current_fixups(), 1)) {
2372 const char *p = opts->current_fixups.buf;
2373 opts->current_fixup_count = 1;
2374 while ((p = strchr(p, '\n'))) {
2375 opts->current_fixup_count++;
2380 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2381 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2382 return error(_("unusable squash-onto"));
2383 opts->have_squash_onto = 1;
2389 if (!file_exists(git_path_opts_file()))
2392 * The function git_parse_source(), called from git_config_from_file(),
2393 * may die() in case of a syntactically incorrect file. We do not care
2394 * about this case, though, because we wrote that file ourselves, so we
2395 * are pretty certain that it is syntactically correct.
2397 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2398 return error(_("malformed options sheet: '%s'"),
2399 git_path_opts_file());
2403 static void write_strategy_opts(struct replay_opts *opts)
2406 struct strbuf buf = STRBUF_INIT;
2408 for (i = 0; i < opts->xopts_nr; ++i)
2409 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2411 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2412 strbuf_release(&buf);
2415 int write_basic_state(struct replay_opts *opts, const char *head_name,
2416 const char *onto, const char *orig_head)
2418 const char *quiet = getenv("GIT_QUIET");
2421 write_file(rebase_path_head_name(), "%s\n", head_name);
2423 write_file(rebase_path_onto(), "%s\n", onto);
2425 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2428 write_file(rebase_path_quiet(), "%s\n", quiet);
2430 write_file(rebase_path_quiet(), "\n");
2433 write_file(rebase_path_verbose(), "%s", "");
2435 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2436 if (opts->xopts_nr > 0)
2437 write_strategy_opts(opts);
2439 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2440 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2441 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2442 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2445 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2447 write_file(rebase_path_signoff(), "--signoff\n");
2452 static int walk_revs_populate_todo(struct todo_list *todo_list,
2453 struct replay_opts *opts)
2455 enum todo_command command = opts->action == REPLAY_PICK ?
2456 TODO_PICK : TODO_REVERT;
2457 const char *command_string = todo_command_info[command].str;
2458 struct commit *commit;
2460 if (prepare_revs(opts))
2463 while ((commit = get_revision(opts->revs))) {
2464 struct todo_item *item = append_new_todo(todo_list);
2465 const char *commit_buffer = get_commit_buffer(commit, NULL);
2466 const char *subject;
2469 item->command = command;
2470 item->commit = commit;
2473 item->offset_in_buf = todo_list->buf.len;
2474 subject_len = find_commit_subject(commit_buffer, &subject);
2475 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2476 short_commit_name(commit), subject_len, subject);
2477 unuse_commit_buffer(commit, commit_buffer);
2481 return error(_("empty commit set passed"));
2486 static int create_seq_dir(void)
2488 if (file_exists(git_path_seq_dir())) {
2489 error(_("a cherry-pick or revert is already in progress"));
2490 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2492 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2493 return error_errno(_("could not create sequencer directory '%s'"),
2494 git_path_seq_dir());
2498 static int save_head(const char *head)
2500 struct lock_file head_lock = LOCK_INIT;
2501 struct strbuf buf = STRBUF_INIT;
2505 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2507 return error_errno(_("could not lock HEAD"));
2508 strbuf_addf(&buf, "%s\n", head);
2509 written = write_in_full(fd, buf.buf, buf.len);
2510 strbuf_release(&buf);
2512 error_errno(_("could not write to '%s'"), git_path_head_file());
2513 rollback_lock_file(&head_lock);
2516 if (commit_lock_file(&head_lock) < 0)
2517 return error(_("failed to finalize '%s'"), git_path_head_file());
2521 static int rollback_is_safe(void)
2523 struct strbuf sb = STRBUF_INIT;
2524 struct object_id expected_head, actual_head;
2526 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2528 if (get_oid_hex(sb.buf, &expected_head)) {
2529 strbuf_release(&sb);
2530 die(_("could not parse %s"), git_path_abort_safety_file());
2532 strbuf_release(&sb);
2534 else if (errno == ENOENT)
2535 oidclr(&expected_head);
2537 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2539 if (get_oid("HEAD", &actual_head))
2540 oidclr(&actual_head);
2542 return oideq(&actual_head, &expected_head);
2545 static int reset_for_rollback(const struct object_id *oid)
2547 const char *argv[4]; /* reset --merge <arg> + NULL */
2550 argv[1] = "--merge";
2551 argv[2] = oid_to_hex(oid);
2553 return run_command_v_opt(argv, RUN_GIT_CMD);
2556 static int rollback_single_pick(void)
2558 struct object_id head_oid;
2560 if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
2561 !file_exists(git_path_revert_head(the_repository)))
2562 return error(_("no cherry-pick or revert in progress"));
2563 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2564 return error(_("cannot resolve HEAD"));
2565 if (is_null_oid(&head_oid))
2566 return error(_("cannot abort from a branch yet to be born"));
2567 return reset_for_rollback(&head_oid);
2570 int sequencer_rollback(struct replay_opts *opts)
2573 struct object_id oid;
2574 struct strbuf buf = STRBUF_INIT;
2577 f = fopen(git_path_head_file(), "r");
2578 if (!f && errno == ENOENT) {
2580 * There is no multiple-cherry-pick in progress.
2581 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2582 * a single-cherry-pick in progress, abort that.
2584 return rollback_single_pick();
2587 return error_errno(_("cannot open '%s'"), git_path_head_file());
2588 if (strbuf_getline_lf(&buf, f)) {
2589 error(_("cannot read '%s': %s"), git_path_head_file(),
2590 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2595 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2596 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2597 git_path_head_file());
2600 if (is_null_oid(&oid)) {
2601 error(_("cannot abort from a branch yet to be born"));
2605 if (!rollback_is_safe()) {
2606 /* Do not error, just do not rollback */
2607 warning(_("You seem to have moved HEAD. "
2608 "Not rewinding, check your HEAD!"));
2610 if (reset_for_rollback(&oid))
2612 strbuf_release(&buf);
2613 return sequencer_remove_state(opts);
2615 strbuf_release(&buf);
2619 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2621 struct lock_file todo_lock = LOCK_INIT;
2622 const char *todo_path = get_todo_path(opts);
2623 int next = todo_list->current, offset, fd;
2626 * rebase -i writes "git-rebase-todo" without the currently executing
2627 * command, appending it to "done" instead.
2629 if (is_rebase_i(opts))
2632 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2634 return error_errno(_("could not lock '%s'"), todo_path);
2635 offset = get_item_line_offset(todo_list, next);
2636 if (write_in_full(fd, todo_list->buf.buf + offset,
2637 todo_list->buf.len - offset) < 0)
2638 return error_errno(_("could not write to '%s'"), todo_path);
2639 if (commit_lock_file(&todo_lock) < 0)
2640 return error(_("failed to finalize '%s'"), todo_path);
2642 if (is_rebase_i(opts) && next > 0) {
2643 const char *done = rebase_path_done();
2644 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2649 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2650 get_item_line_length(todo_list, next - 1))
2652 ret = error_errno(_("could not write to '%s'"), done);
2654 ret = error_errno(_("failed to finalize '%s'"), done);
2660 static int save_opts(struct replay_opts *opts)
2662 const char *opts_file = git_path_opts_file();
2665 if (opts->no_commit)
2666 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2668 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2670 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2671 if (opts->record_origin)
2672 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2674 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2675 if (opts->mainline) {
2676 struct strbuf buf = STRBUF_INIT;
2677 strbuf_addf(&buf, "%d", opts->mainline);
2678 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2679 strbuf_release(&buf);
2682 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2684 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2687 for (i = 0; i < opts->xopts_nr; i++)
2688 res |= git_config_set_multivar_in_file_gently(opts_file,
2689 "options.strategy-option",
2690 opts->xopts[i], "^$", 0);
2692 if (opts->allow_rerere_auto)
2693 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2694 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2699 static int make_patch(struct commit *commit, struct replay_opts *opts)
2701 struct strbuf buf = STRBUF_INIT;
2702 struct rev_info log_tree_opt;
2703 const char *subject, *p;
2706 p = short_commit_name(commit);
2707 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2709 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2710 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2711 res |= error(_("could not update %s"), "REBASE_HEAD");
2713 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2714 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2715 repo_init_revisions(the_repository, &log_tree_opt, NULL);
2716 log_tree_opt.abbrev = 0;
2717 log_tree_opt.diff = 1;
2718 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2719 log_tree_opt.disable_stdin = 1;
2720 log_tree_opt.no_commit_id = 1;
2721 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2722 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2723 if (!log_tree_opt.diffopt.file)
2724 res |= error_errno(_("could not open '%s'"), buf.buf);
2726 res |= log_tree_commit(&log_tree_opt, commit);
2727 fclose(log_tree_opt.diffopt.file);
2731 strbuf_addf(&buf, "%s/message", get_dir(opts));
2732 if (!file_exists(buf.buf)) {
2733 const char *commit_buffer = get_commit_buffer(commit, NULL);
2734 find_commit_subject(commit_buffer, &subject);
2735 res |= write_message(subject, strlen(subject), buf.buf, 1);
2736 unuse_commit_buffer(commit, commit_buffer);
2738 strbuf_release(&buf);
2743 static int intend_to_amend(void)
2745 struct object_id head;
2748 if (get_oid("HEAD", &head))
2749 return error(_("cannot read HEAD"));
2751 p = oid_to_hex(&head);
2752 return write_message(p, strlen(p), rebase_path_amend(), 1);
2755 static int error_with_patch(struct commit *commit,
2756 const char *subject, int subject_len,
2757 struct replay_opts *opts, int exit_code, int to_amend)
2760 if (make_patch(commit, opts))
2762 } else if (copy_file(rebase_path_message(),
2763 git_path_merge_msg(the_repository), 0666))
2764 return error(_("unable to copy '%s' to '%s'"),
2765 git_path_merge_msg(the_repository), rebase_path_message());
2768 if (intend_to_amend())
2772 _("You can amend the commit now, with\n"
2774 " git commit --amend %s\n"
2776 "Once you are satisfied with your changes, run\n"
2778 " git rebase --continue\n"),
2779 gpg_sign_opt_quoted(opts));
2780 } else if (exit_code) {
2782 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2783 short_commit_name(commit), subject_len, subject);
2786 * We don't have the hash of the parent so
2787 * just print the line from the todo file.
2789 fprintf_ln(stderr, _("Could not merge %.*s"),
2790 subject_len, subject);
2796 static int error_failed_squash(struct commit *commit,
2797 struct replay_opts *opts, int subject_len, const char *subject)
2799 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2800 return error(_("could not copy '%s' to '%s'"),
2801 rebase_path_squash_msg(), rebase_path_message());
2802 unlink(git_path_merge_msg(the_repository));
2803 if (copy_file(git_path_merge_msg(the_repository), rebase_path_message(), 0666))
2804 return error(_("could not copy '%s' to '%s'"),
2805 rebase_path_message(),
2806 git_path_merge_msg(the_repository));
2807 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2810 static int do_exec(const char *command_line)
2812 struct argv_array child_env = ARGV_ARRAY_INIT;
2813 const char *child_argv[] = { NULL, NULL };
2816 fprintf(stderr, "Executing: %s\n", command_line);
2817 child_argv[0] = command_line;
2818 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2819 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2820 absolute_path(get_git_work_tree()));
2821 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2824 /* force re-reading of the cache */
2825 if (discard_cache() < 0 || read_cache() < 0)
2826 return error(_("could not read index"));
2828 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2831 warning(_("execution failed: %s\n%s"
2832 "You can fix the problem, and then run\n"
2834 " git rebase --continue\n"
2837 dirty ? N_("and made changes to the index and/or the "
2838 "working tree\n") : "");
2840 /* command not found */
2843 warning(_("execution succeeded: %s\nbut "
2844 "left changes to the index and/or the working tree\n"
2845 "Commit or stash your changes, and then run\n"
2847 " git rebase --continue\n"
2848 "\n"), command_line);
2852 argv_array_clear(&child_env);
2857 static int safe_append(const char *filename, const char *fmt, ...)
2860 struct lock_file lock = LOCK_INIT;
2861 int fd = hold_lock_file_for_update(&lock, filename,
2862 LOCK_REPORT_ON_ERROR);
2863 struct strbuf buf = STRBUF_INIT;
2868 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2869 error_errno(_("could not read '%s'"), filename);
2870 rollback_lock_file(&lock);
2873 strbuf_complete(&buf, '\n');
2875 strbuf_vaddf(&buf, fmt, ap);
2878 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2879 error_errno(_("could not write to '%s'"), filename);
2880 strbuf_release(&buf);
2881 rollback_lock_file(&lock);
2884 if (commit_lock_file(&lock) < 0) {
2885 strbuf_release(&buf);
2886 rollback_lock_file(&lock);
2887 return error(_("failed to finalize '%s'"), filename);
2890 strbuf_release(&buf);
2894 static int do_label(const char *name, int len)
2896 struct ref_store *refs = get_main_ref_store(the_repository);
2897 struct ref_transaction *transaction;
2898 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2899 struct strbuf msg = STRBUF_INIT;
2901 struct object_id head_oid;
2903 if (len == 1 && *name == '#')
2904 return error(_("illegal label name: '%.*s'"), len, name);
2906 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2907 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2909 transaction = ref_store_transaction_begin(refs, &err);
2911 error("%s", err.buf);
2913 } else if (get_oid("HEAD", &head_oid)) {
2914 error(_("could not read HEAD"));
2916 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2917 NULL, 0, msg.buf, &err) < 0 ||
2918 ref_transaction_commit(transaction, &err)) {
2919 error("%s", err.buf);
2922 ref_transaction_free(transaction);
2923 strbuf_release(&err);
2924 strbuf_release(&msg);
2927 ret = safe_append(rebase_path_refs_to_delete(),
2928 "%s\n", ref_name.buf);
2929 strbuf_release(&ref_name);
2934 static const char *reflog_message(struct replay_opts *opts,
2935 const char *sub_action, const char *fmt, ...);
2937 static int do_reset(const char *name, int len, struct replay_opts *opts)
2939 struct strbuf ref_name = STRBUF_INIT;
2940 struct object_id oid;
2941 struct lock_file lock = LOCK_INIT;
2942 struct tree_desc desc;
2944 struct unpack_trees_options unpack_tree_opts;
2947 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2950 if (len == 10 && !strncmp("[new root]", name, len)) {
2951 if (!opts->have_squash_onto) {
2953 if (commit_tree("", 0, the_hash_algo->empty_tree,
2954 NULL, &opts->squash_onto,
2956 return error(_("writing fake root commit"));
2957 opts->have_squash_onto = 1;
2958 hex = oid_to_hex(&opts->squash_onto);
2959 if (write_message(hex, strlen(hex),
2960 rebase_path_squash_onto(), 0))
2961 return error(_("writing squash-onto"));
2963 oidcpy(&oid, &opts->squash_onto);
2967 /* Determine the length of the label */
2968 for (i = 0; i < len; i++)
2969 if (isspace(name[i]))
2973 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2974 if (get_oid(ref_name.buf, &oid) &&
2975 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2976 error(_("could not read '%s'"), ref_name.buf);
2977 rollback_lock_file(&lock);
2978 strbuf_release(&ref_name);
2983 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2984 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2985 unpack_tree_opts.head_idx = 1;
2986 unpack_tree_opts.src_index = &the_index;
2987 unpack_tree_opts.dst_index = &the_index;
2988 unpack_tree_opts.fn = oneway_merge;
2989 unpack_tree_opts.merge = 1;
2990 unpack_tree_opts.update = 1;
2992 if (read_cache_unmerged()) {
2993 rollback_lock_file(&lock);
2994 strbuf_release(&ref_name);
2995 return error_resolve_conflict(_(action_name(opts)));
2998 if (!fill_tree_descriptor(&desc, &oid)) {
2999 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3000 rollback_lock_file(&lock);
3001 free((void *)desc.buffer);
3002 strbuf_release(&ref_name);
3006 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3007 rollback_lock_file(&lock);
3008 free((void *)desc.buffer);
3009 strbuf_release(&ref_name);
3013 tree = parse_tree_indirect(&oid);
3014 prime_cache_tree(&the_index, tree);
3016 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
3017 ret = error(_("could not write index"));
3018 free((void *)desc.buffer);
3021 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3022 len, name), "HEAD", &oid,
3023 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3025 strbuf_release(&ref_name);
3029 static struct commit *lookup_label(const char *label, int len,
3032 struct commit *commit;
3035 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3036 commit = lookup_commit_reference_by_name(buf->buf);
3038 /* fall back to non-rewritten ref or commit */
3039 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3040 commit = lookup_commit_reference_by_name(buf->buf);
3044 error(_("could not resolve '%s'"), buf->buf);
3049 static int do_merge(struct commit *commit, const char *arg, int arg_len,
3050 int flags, struct replay_opts *opts)
3052 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3053 EDIT_MSG | VERIFY_MSG : 0;
3054 struct strbuf ref_name = STRBUF_INIT;
3055 struct commit *head_commit, *merge_commit, *i;
3056 struct commit_list *bases, *j, *reversed = NULL;
3057 struct commit_list *to_merge = NULL, **tail = &to_merge;
3058 struct merge_options o;
3059 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3060 static struct lock_file lock;
3063 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
3068 head_commit = lookup_commit_reference_by_name("HEAD");
3070 ret = error(_("cannot merge without a current revision"));
3075 * For octopus merges, the arg starts with the list of revisions to be
3076 * merged. The list is optionally followed by '#' and the oneline.
3078 merge_arg_len = oneline_offset = arg_len;
3079 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3082 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3083 p += 1 + strspn(p + 1, " \t\n");
3084 oneline_offset = p - arg;
3087 k = strcspn(p, " \t\n");
3090 merge_commit = lookup_label(p, k, &ref_name);
3091 if (!merge_commit) {
3092 ret = error(_("unable to parse '%.*s'"), k, p);
3095 tail = &commit_list_insert(merge_commit, tail)->next;
3097 merge_arg_len = p - arg;
3101 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3105 if (opts->have_squash_onto &&
3106 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3108 * When the user tells us to "merge" something into a
3109 * "[new root]", let's simply fast-forward to the merge head.
3111 rollback_lock_file(&lock);
3113 ret = error(_("octopus merge cannot be executed on "
3114 "top of a [new root]"));
3116 ret = fast_forward_to(&to_merge->item->object.oid,
3117 &head_commit->object.oid, 0,
3123 const char *message = get_commit_buffer(commit, NULL);
3128 ret = error(_("could not get commit message of '%s'"),
3129 oid_to_hex(&commit->object.oid));
3132 write_author_script(message);
3133 find_commit_subject(message, &body);
3135 ret = write_message(body, len, git_path_merge_msg(the_repository), 0);
3136 unuse_commit_buffer(commit, message);
3138 error_errno(_("could not write '%s'"),
3139 git_path_merge_msg(the_repository));
3143 struct strbuf buf = STRBUF_INIT;
3146 strbuf_addf(&buf, "author %s", git_author_info(0));
3147 write_author_script(buf.buf);
3150 if (oneline_offset < arg_len) {
3151 p = arg + oneline_offset;
3152 len = arg_len - oneline_offset;
3154 strbuf_addf(&buf, "Merge %s '%.*s'",
3155 to_merge->next ? "branches" : "branch",
3156 merge_arg_len, arg);
3161 ret = write_message(p, len, git_path_merge_msg(the_repository), 0);
3162 strbuf_release(&buf);
3164 error_errno(_("could not write '%s'"),
3165 git_path_merge_msg(the_repository));
3171 * If HEAD is not identical to the first parent of the original merge
3172 * commit, we cannot fast-forward.
3174 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3175 oideq(&commit->parents->item->object.oid,
3176 &head_commit->object.oid);
3179 * If any merge head is different from the original one, we cannot
3182 if (can_fast_forward) {
3183 struct commit_list *p = commit->parents->next;
3185 for (j = to_merge; j && p; j = j->next, p = p->next)
3186 if (!oideq(&j->item->object.oid,
3187 &p->item->object.oid)) {
3188 can_fast_forward = 0;
3192 * If the number of merge heads differs from the original merge
3193 * commit, we cannot fast-forward.
3196 can_fast_forward = 0;
3199 if (can_fast_forward) {
3200 rollback_lock_file(&lock);
3201 ret = fast_forward_to(&commit->object.oid,
3202 &head_commit->object.oid, 0, opts);
3206 if (to_merge->next) {
3208 struct child_process cmd = CHILD_PROCESS_INIT;
3210 if (read_env_script(&cmd.env_array)) {
3211 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3213 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3218 argv_array_push(&cmd.args, "merge");
3219 argv_array_push(&cmd.args, "-s");
3220 argv_array_push(&cmd.args, "octopus");
3221 argv_array_push(&cmd.args, "--no-edit");
3222 argv_array_push(&cmd.args, "--no-ff");
3223 argv_array_push(&cmd.args, "--no-log");
3224 argv_array_push(&cmd.args, "--no-stat");
3225 argv_array_push(&cmd.args, "-F");
3226 argv_array_push(&cmd.args, git_path_merge_msg(the_repository));
3228 argv_array_push(&cmd.args, opts->gpg_sign);
3230 /* Add the tips to be merged */
3231 for (j = to_merge; j; j = j->next)
3232 argv_array_push(&cmd.args,
3233 oid_to_hex(&j->item->object.oid));
3235 strbuf_release(&ref_name);
3236 unlink(git_path_cherry_pick_head(the_repository));
3237 rollback_lock_file(&lock);
3239 rollback_lock_file(&lock);
3240 ret = run_command(&cmd);
3242 /* force re-reading of the cache */
3243 if (!ret && (discard_cache() < 0 || read_cache() < 0))
3244 ret = error(_("could not read index"));
3248 merge_commit = to_merge->item;
3249 bases = get_merge_bases(head_commit, merge_commit);
3250 if (bases && oideq(&merge_commit->object.oid,
3251 &bases->item->object.oid)) {
3253 /* skip merging an ancestor of HEAD */
3257 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3258 git_path_merge_head(the_repository), 0);
3259 write_message("no-ff", 5, git_path_merge_mode(the_repository), 0);
3261 for (j = bases; j; j = j->next)
3262 commit_list_insert(j->item, &reversed);
3263 free_commit_list(bases);
3266 init_merge_options(&o);
3268 o.branch2 = ref_name.buf;
3269 o.buffer_output = 2;
3271 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3273 fputs(o.obuf.buf, stdout);
3274 strbuf_release(&o.obuf);
3276 error(_("could not even attempt to merge '%.*s'"),
3277 merge_arg_len, arg);
3281 * The return value of merge_recursive() is 1 on clean, and 0 on
3284 * Let's reverse that, so that do_merge() returns 0 upon success and
3285 * 1 upon failed merge (keeping the return value -1 for the cases where
3286 * we will want to reschedule the `merge` command).
3290 if (active_cache_changed &&
3291 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
3292 ret = error(_("merge: Unable to write new index file"));
3296 rollback_lock_file(&lock);
3298 repo_rerere(the_repository, opts->allow_rerere_auto);
3301 * In case of problems, we now want to return a positive
3302 * value (a negative one would indicate that the `merge`
3303 * command needs to be rescheduled).
3305 ret = !!run_git_commit(git_path_merge_msg(the_repository), opts,
3309 strbuf_release(&ref_name);
3310 rollback_lock_file(&lock);
3311 free_commit_list(to_merge);
3315 static int is_final_fixup(struct todo_list *todo_list)
3317 int i = todo_list->current;
3319 if (!is_fixup(todo_list->items[i].command))
3322 while (++i < todo_list->nr)
3323 if (is_fixup(todo_list->items[i].command))
3325 else if (!is_noop(todo_list->items[i].command))
3330 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3334 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3335 if (!is_noop(todo_list->items[i].command))
3336 return todo_list->items[i].command;
3341 static int apply_autostash(struct replay_opts *opts)
3343 struct strbuf stash_sha1 = STRBUF_INIT;
3344 struct child_process child = CHILD_PROCESS_INIT;
3347 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3348 strbuf_release(&stash_sha1);
3351 strbuf_trim(&stash_sha1);
3354 child.no_stdout = 1;
3355 child.no_stderr = 1;
3356 argv_array_push(&child.args, "stash");
3357 argv_array_push(&child.args, "apply");
3358 argv_array_push(&child.args, stash_sha1.buf);
3359 if (!run_command(&child))
3360 fprintf(stderr, _("Applied autostash.\n"));
3362 struct child_process store = CHILD_PROCESS_INIT;
3365 argv_array_push(&store.args, "stash");
3366 argv_array_push(&store.args, "store");
3367 argv_array_push(&store.args, "-m");
3368 argv_array_push(&store.args, "autostash");
3369 argv_array_push(&store.args, "-q");
3370 argv_array_push(&store.args, stash_sha1.buf);
3371 if (run_command(&store))
3372 ret = error(_("cannot store %s"), stash_sha1.buf);
3375 _("Applying autostash resulted in conflicts.\n"
3376 "Your changes are safe in the stash.\n"
3377 "You can run \"git stash pop\" or"
3378 " \"git stash drop\" at any time.\n"));
3381 strbuf_release(&stash_sha1);
3385 static const char *reflog_message(struct replay_opts *opts,
3386 const char *sub_action, const char *fmt, ...)
3389 static struct strbuf buf = STRBUF_INIT;
3393 strbuf_addstr(&buf, action_name(opts));
3395 strbuf_addf(&buf, " (%s)", sub_action);
3397 strbuf_addstr(&buf, ": ");
3398 strbuf_vaddf(&buf, fmt, ap);
3405 static int run_git_checkout(struct replay_opts *opts, const char *commit,
3408 struct child_process cmd = CHILD_PROCESS_INIT;
3412 argv_array_push(&cmd.args, "checkout");
3413 argv_array_push(&cmd.args, commit);
3414 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3417 return run_command(&cmd);
3419 return run_command_silent_on_success(&cmd);
3422 int prepare_branch_to_be_rebased(struct replay_opts *opts, const char *commit)
3426 if (commit && *commit) {
3427 action = reflog_message(opts, "start", "checkout %s", commit);
3428 if (run_git_checkout(opts, commit, action))
3429 return error(_("could not checkout %s"), commit);
3435 static int checkout_onto(struct replay_opts *opts,
3436 const char *onto_name, const char *onto,
3437 const char *orig_head)
3439 struct object_id oid;
3440 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3442 if (get_oid(orig_head, &oid))
3443 return error(_("%s: not a valid OID"), orig_head);
3445 if (run_git_checkout(opts, onto, action)) {
3446 apply_autostash(opts);
3447 sequencer_remove_state(opts);
3448 return error(_("could not detach HEAD"));
3451 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3454 static int stopped_at_head(void)
3456 struct object_id head;
3457 struct commit *commit;
3458 struct commit_message message;
3460 if (get_oid("HEAD", &head) ||
3461 !(commit = lookup_commit(the_repository, &head)) ||
3462 parse_commit(commit) || get_message(commit, &message))
3463 fprintf(stderr, _("Stopped at HEAD\n"));
3465 fprintf(stderr, _("Stopped at %s\n"), message.label);
3466 free_message(commit, &message);
3472 static const char rescheduled_advice[] =
3473 N_("Could not execute the todo command\n"
3477 "It has been rescheduled; To edit the command before continuing, please\n"
3478 "edit the todo list first:\n"
3480 " git rebase --edit-todo\n"
3481 " git rebase --continue\n");
3483 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
3485 int res = 0, reschedule = 0;
3487 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3489 assert(!(opts->signoff || opts->no_commit ||
3490 opts->record_origin || opts->edit));
3491 if (read_and_refresh_cache(opts))
3494 while (todo_list->current < todo_list->nr) {
3495 struct todo_item *item = todo_list->items + todo_list->current;
3496 if (save_todo(todo_list, opts))
3498 if (is_rebase_i(opts)) {
3499 if (item->command != TODO_COMMENT) {
3500 FILE *f = fopen(rebase_path_msgnum(), "w");
3502 todo_list->done_nr++;
3505 fprintf(f, "%d\n", todo_list->done_nr);
3508 fprintf(stderr, "Rebasing (%d/%d)%s",
3510 todo_list->total_nr,
3511 opts->verbose ? "\n" : "\r");
3513 unlink(rebase_path_message());
3514 unlink(rebase_path_author_script());
3515 unlink(rebase_path_stopped_sha());
3516 unlink(rebase_path_amend());
3517 unlink(git_path_merge_head(the_repository));
3518 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3520 if (item->command == TODO_BREAK)
3521 return stopped_at_head();
3523 if (item->command <= TODO_SQUASH) {
3524 if (is_rebase_i(opts))
3525 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3526 command_to_string(item->command), NULL),
3528 res = do_pick_commit(item->command, item->commit,
3529 opts, is_final_fixup(todo_list));
3530 if (is_rebase_i(opts) && res < 0) {
3532 advise(_(rescheduled_advice),
3533 get_item_line_length(todo_list,
3534 todo_list->current),
3535 get_item_line(todo_list,
3536 todo_list->current));
3537 todo_list->current--;
3538 if (save_todo(todo_list, opts))
3541 if (item->command == TODO_EDIT) {
3542 struct commit *commit = item->commit;
3545 _("Stopped at %s... %.*s\n"),
3546 short_commit_name(commit),
3547 item->arg_len, item->arg);
3548 return error_with_patch(commit,
3549 item->arg, item->arg_len, opts, res,
3552 if (is_rebase_i(opts) && !res)
3553 record_in_rewritten(&item->commit->object.oid,
3554 peek_command(todo_list, 1));
3555 if (res && is_fixup(item->command)) {
3558 return error_failed_squash(item->commit, opts,
3559 item->arg_len, item->arg);
3560 } else if (res && is_rebase_i(opts) && item->commit) {
3562 struct object_id oid;
3565 * If we are rewording and have either
3566 * fast-forwarded already, or are about to
3567 * create a new root commit, we want to amend,
3568 * otherwise we do not.
3570 if (item->command == TODO_REWORD &&
3571 !get_oid("HEAD", &oid) &&
3572 (oideq(&item->commit->object.oid, &oid) ||
3573 (opts->have_squash_onto &&
3574 oideq(&opts->squash_onto, &oid))))
3577 return res | error_with_patch(item->commit,
3578 item->arg, item->arg_len, opts,
3581 } else if (item->command == TODO_EXEC) {
3582 char *end_of_arg = (char *)(item->arg + item->arg_len);
3583 int saved = *end_of_arg;
3587 res = do_exec(item->arg);
3588 *end_of_arg = saved;
3590 /* Reread the todo file if it has changed. */
3592 ; /* fall through */
3593 else if (stat(get_todo_path(opts), &st))
3594 res = error_errno(_("could not stat '%s'"),
3595 get_todo_path(opts));
3596 else if (match_stat_data(&todo_list->stat, &st)) {
3597 todo_list_release(todo_list);
3598 if (read_populate_todo(todo_list, opts))
3599 res = -1; /* message was printed */
3600 /* `current` will be incremented below */
3601 todo_list->current = -1;
3603 } else if (item->command == TODO_LABEL) {
3604 if ((res = do_label(item->arg, item->arg_len)))
3606 } else if (item->command == TODO_RESET) {
3607 if ((res = do_reset(item->arg, item->arg_len, opts)))
3609 } else if (item->command == TODO_MERGE) {
3610 if ((res = do_merge(item->commit,
3611 item->arg, item->arg_len,
3612 item->flags, opts)) < 0)
3614 else if (item->commit)
3615 record_in_rewritten(&item->commit->object.oid,
3616 peek_command(todo_list, 1));
3618 /* failed with merge conflicts */
3619 return error_with_patch(item->commit,
3621 item->arg_len, opts,
3623 } else if (!is_noop(item->command))
3624 return error(_("unknown command %d"), item->command);
3627 advise(_(rescheduled_advice),
3628 get_item_line_length(todo_list,
3629 todo_list->current),
3630 get_item_line(todo_list, todo_list->current));
3631 todo_list->current--;
3632 if (save_todo(todo_list, opts))
3635 return error_with_patch(item->commit,
3637 item->arg_len, opts,
3641 todo_list->current++;
3646 if (is_rebase_i(opts)) {
3647 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3650 /* Stopped in the middle, as planned? */
3651 if (todo_list->current < todo_list->nr)
3654 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3655 starts_with(head_ref.buf, "refs/")) {
3657 struct object_id head, orig;
3660 if (get_oid("HEAD", &head)) {
3661 res = error(_("cannot read HEAD"));
3663 strbuf_release(&head_ref);
3664 strbuf_release(&buf);
3667 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3668 get_oid_hex(buf.buf, &orig)) {
3669 res = error(_("could not read orig-head"));
3670 goto cleanup_head_ref;
3673 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3674 res = error(_("could not read 'onto'"));
3675 goto cleanup_head_ref;
3677 msg = reflog_message(opts, "finish", "%s onto %s",
3678 head_ref.buf, buf.buf);
3679 if (update_ref(msg, head_ref.buf, &head, &orig,
3680 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3681 res = error(_("could not update %s"),
3683 goto cleanup_head_ref;
3685 msg = reflog_message(opts, "finish", "returning to %s",
3687 if (create_symref("HEAD", head_ref.buf, msg)) {
3688 res = error(_("could not update HEAD to %s"),
3690 goto cleanup_head_ref;
3695 if (opts->verbose) {
3696 struct rev_info log_tree_opt;
3697 struct object_id orig, head;
3699 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3700 repo_init_revisions(the_repository, &log_tree_opt, NULL);
3701 log_tree_opt.diff = 1;
3702 log_tree_opt.diffopt.output_format =
3703 DIFF_FORMAT_DIFFSTAT;
3704 log_tree_opt.disable_stdin = 1;
3706 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3707 !get_oid(buf.buf, &orig) &&
3708 !get_oid("HEAD", &head)) {
3709 diff_tree_oid(&orig, &head, "",
3710 &log_tree_opt.diffopt);
3711 log_tree_diff_flush(&log_tree_opt);
3714 flush_rewritten_pending();
3715 if (!stat(rebase_path_rewritten_list(), &st) &&
3717 struct child_process child = CHILD_PROCESS_INIT;
3718 const char *post_rewrite_hook =
3719 find_hook("post-rewrite");
3721 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3723 argv_array_push(&child.args, "notes");
3724 argv_array_push(&child.args, "copy");
3725 argv_array_push(&child.args, "--for-rewrite=rebase");
3726 /* we don't care if this copying failed */
3727 run_command(&child);
3729 if (post_rewrite_hook) {
3730 struct child_process hook = CHILD_PROCESS_INIT;
3732 hook.in = open(rebase_path_rewritten_list(),
3734 hook.stdout_to_stderr = 1;
3735 argv_array_push(&hook.args, post_rewrite_hook);
3736 argv_array_push(&hook.args, "rebase");
3737 /* we don't care if this hook failed */
3741 apply_autostash(opts);
3743 fprintf(stderr, "Successfully rebased and updated %s.\n",
3746 strbuf_release(&buf);
3747 strbuf_release(&head_ref);
3751 * Sequence of picks finished successfully; cleanup by
3752 * removing the .git/sequencer directory
3754 return sequencer_remove_state(opts);
3757 static int continue_single_pick(void)
3759 const char *argv[] = { "commit", NULL };
3761 if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
3762 !file_exists(git_path_revert_head(the_repository)))
3763 return error(_("no cherry-pick or revert in progress"));
3764 return run_command_v_opt(argv, RUN_GIT_CMD);
3767 static int commit_staged_changes(struct replay_opts *opts,
3768 struct todo_list *todo_list)
3770 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3771 unsigned int final_fixup = 0, is_clean;
3773 if (has_unstaged_changes(1))
3774 return error(_("cannot rebase: You have unstaged changes."));
3776 is_clean = !has_uncommitted_changes(0);
3778 if (file_exists(rebase_path_amend())) {
3779 struct strbuf rev = STRBUF_INIT;
3780 struct object_id head, to_amend;
3782 if (get_oid("HEAD", &head))
3783 return error(_("cannot amend non-existing commit"));
3784 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3785 return error(_("invalid file: '%s'"), rebase_path_amend());
3786 if (get_oid_hex(rev.buf, &to_amend))
3787 return error(_("invalid contents: '%s'"),
3788 rebase_path_amend());
3789 if (!is_clean && !oideq(&head, &to_amend))
3790 return error(_("\nYou have uncommitted changes in your "
3791 "working tree. Please, commit them\n"
3792 "first and then run 'git rebase "
3793 "--continue' again."));
3795 * When skipping a failed fixup/squash, we need to edit the
3796 * commit message, the current fixup list and count, and if it
3797 * was the last fixup/squash in the chain, we need to clean up
3798 * the commit message and if there was a squash, let the user
3801 if (!is_clean || !opts->current_fixup_count)
3802 ; /* this is not the final fixup */
3803 else if (!oideq(&head, &to_amend) ||
3804 !file_exists(rebase_path_stopped_sha())) {
3805 /* was a final fixup or squash done manually? */
3806 if (!is_fixup(peek_command(todo_list, 0))) {
3807 unlink(rebase_path_fixup_msg());
3808 unlink(rebase_path_squash_msg());
3809 unlink(rebase_path_current_fixups());
3810 strbuf_reset(&opts->current_fixups);
3811 opts->current_fixup_count = 0;
3814 /* we are in a fixup/squash chain */
3815 const char *p = opts->current_fixups.buf;
3816 int len = opts->current_fixups.len;
3818 opts->current_fixup_count--;
3820 BUG("Incorrect current_fixups:\n%s", p);
3821 while (len && p[len - 1] != '\n')
3823 strbuf_setlen(&opts->current_fixups, len);
3824 if (write_message(p, len, rebase_path_current_fixups(),
3826 return error(_("could not write file: '%s'"),
3827 rebase_path_current_fixups());
3830 * If a fixup/squash in a fixup/squash chain failed, the
3831 * commit message is already correct, no need to commit
3834 * Only if it is the final command in the fixup/squash
3835 * chain, and only if the chain is longer than a single
3836 * fixup/squash command (which was just skipped), do we
3837 * actually need to re-commit with a cleaned up commit
3840 if (opts->current_fixup_count > 0 &&
3841 !is_fixup(peek_command(todo_list, 0))) {
3844 * If there was not a single "squash" in the
3845 * chain, we only need to clean up the commit
3846 * message, no need to bother the user with
3847 * opening the commit message in the editor.
3849 if (!starts_with(p, "squash ") &&
3850 !strstr(p, "\nsquash "))
3851 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3852 } else if (is_fixup(peek_command(todo_list, 0))) {
3854 * We need to update the squash message to skip
3855 * the latest commit message.
3857 struct commit *commit;
3858 const char *path = rebase_path_squash_msg();
3860 if (parse_head(&commit) ||
3861 !(p = get_commit_buffer(commit, NULL)) ||
3862 write_message(p, strlen(p), path, 0)) {
3863 unuse_commit_buffer(commit, p);
3864 return error(_("could not write file: "
3867 unuse_commit_buffer(commit, p);
3871 strbuf_release(&rev);
3876 const char *cherry_pick_head = git_path_cherry_pick_head(the_repository);
3878 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3879 return error(_("could not remove CHERRY_PICK_HEAD"));
3884 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
3886 return error(_("could not commit staged changes."));
3887 unlink(rebase_path_amend());
3888 unlink(git_path_merge_head(the_repository));
3890 unlink(rebase_path_fixup_msg());
3891 unlink(rebase_path_squash_msg());
3893 if (opts->current_fixup_count > 0) {
3895 * Whether final fixup or not, we just cleaned up the commit
3898 unlink(rebase_path_current_fixups());
3899 strbuf_reset(&opts->current_fixups);
3900 opts->current_fixup_count = 0;
3905 int sequencer_continue(struct replay_opts *opts)
3907 struct todo_list todo_list = TODO_LIST_INIT;
3910 if (read_and_refresh_cache(opts))
3913 if (read_populate_opts(opts))
3915 if (is_rebase_i(opts)) {
3916 if ((res = read_populate_todo(&todo_list, opts)))
3917 goto release_todo_list;
3918 if (commit_staged_changes(opts, &todo_list))
3920 } else if (!file_exists(get_todo_path(opts)))
3921 return continue_single_pick();
3922 else if ((res = read_populate_todo(&todo_list, opts)))
3923 goto release_todo_list;
3925 if (!is_rebase_i(opts)) {
3926 /* Verify that the conflict has been resolved */
3927 if (file_exists(git_path_cherry_pick_head(the_repository)) ||
3928 file_exists(git_path_revert_head(the_repository))) {
3929 res = continue_single_pick();
3931 goto release_todo_list;
3933 if (index_differs_from("HEAD", NULL, 0)) {
3934 res = error_dirty_index(opts);
3935 goto release_todo_list;
3937 todo_list.current++;
3938 } else if (file_exists(rebase_path_stopped_sha())) {
3939 struct strbuf buf = STRBUF_INIT;
3940 struct object_id oid;
3942 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3943 !get_oid_committish(buf.buf, &oid))
3944 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3945 strbuf_release(&buf);
3948 res = pick_commits(&todo_list, opts);
3950 todo_list_release(&todo_list);
3954 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3956 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3957 return do_pick_commit(opts->action == REPLAY_PICK ?
3958 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3961 int sequencer_pick_revisions(struct replay_opts *opts)
3963 struct todo_list todo_list = TODO_LIST_INIT;
3964 struct object_id oid;
3968 if (read_and_refresh_cache(opts))
3971 for (i = 0; i < opts->revs->pending.nr; i++) {
3972 struct object_id oid;
3973 const char *name = opts->revs->pending.objects[i].name;
3975 /* This happens when using --stdin. */
3979 if (!get_oid(name, &oid)) {
3980 if (!lookup_commit_reference_gently(the_repository, &oid, 1)) {
3981 enum object_type type = oid_object_info(the_repository,
3984 return error(_("%s: can't cherry-pick a %s"),
3985 name, type_name(type));
3988 return error(_("%s: bad revision"), name);
3992 * If we were called as "git cherry-pick <commit>", just
3993 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3994 * REVERT_HEAD, and don't touch the sequencer state.
3995 * This means it is possible to cherry-pick in the middle
3996 * of a cherry-pick sequence.
3998 if (opts->revs->cmdline.nr == 1 &&
3999 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4000 opts->revs->no_walk &&
4001 !opts->revs->cmdline.rev->flags) {
4002 struct commit *cmit;
4003 if (prepare_revision_walk(opts->revs))
4004 return error(_("revision walk setup failed"));
4005 cmit = get_revision(opts->revs);
4007 return error(_("empty commit set passed"));
4008 if (get_revision(opts->revs))
4009 BUG("unexpected extra commit from walk");
4010 return single_pick(cmit, opts);
4014 * Start a new cherry-pick/ revert sequence; but
4015 * first, make sure that an existing one isn't in
4019 if (walk_revs_populate_todo(&todo_list, opts) ||
4020 create_seq_dir() < 0)
4022 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4023 return error(_("can't revert as initial commit"));
4024 if (save_head(oid_to_hex(&oid)))
4026 if (save_opts(opts))
4028 update_abort_safety_file();
4029 res = pick_commits(&todo_list, opts);
4030 todo_list_release(&todo_list);
4034 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4036 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4037 struct strbuf sob = STRBUF_INIT;
4040 strbuf_addstr(&sob, sign_off_header);
4041 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
4042 getenv("GIT_COMMITTER_EMAIL")));
4043 strbuf_addch(&sob, '\n');
4046 strbuf_complete_line(msgbuf);
4049 * If the whole message buffer is equal to the sob, pretend that we
4050 * found a conforming footer with a matching sob
4052 if (msgbuf->len - ignore_footer == sob.len &&
4053 !strncmp(msgbuf->buf, sob.buf, sob.len))
4056 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4059 const char *append_newlines = NULL;
4060 size_t len = msgbuf->len - ignore_footer;
4064 * The buffer is completely empty. Leave foom for
4065 * the title and body to be filled in by the user.
4067 append_newlines = "\n\n";
4068 } else if (len == 1) {
4070 * Buffer contains a single newline. Add another
4071 * so that we leave room for the title and body.
4073 append_newlines = "\n";
4074 } else if (msgbuf->buf[len - 2] != '\n') {
4076 * Buffer ends with a single newline. Add another
4077 * so that there is an empty line between the message
4080 append_newlines = "\n";
4081 } /* else, the buffer already ends with two newlines. */
4083 if (append_newlines)
4084 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4085 append_newlines, strlen(append_newlines));
4088 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4089 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4092 strbuf_release(&sob);
4095 struct labels_entry {
4096 struct hashmap_entry entry;
4097 char label[FLEX_ARRAY];
4100 static int labels_cmp(const void *fndata, const struct labels_entry *a,
4101 const struct labels_entry *b, const void *key)
4103 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4106 struct string_entry {
4107 struct oidmap_entry entry;
4108 char string[FLEX_ARRAY];
4111 struct label_state {
4112 struct oidmap commit2label;
4113 struct hashmap labels;
4117 static const char *label_oid(struct object_id *oid, const char *label,
4118 struct label_state *state)
4120 struct labels_entry *labels_entry;
4121 struct string_entry *string_entry;
4122 struct object_id dummy;
4126 string_entry = oidmap_get(&state->commit2label, oid);
4128 return string_entry->string;
4131 * For "uninteresting" commits, i.e. commits that are not to be
4132 * rebased, and which can therefore not be labeled, we use a unique
4133 * abbreviation of the commit name. This is slightly more complicated
4134 * than calling find_unique_abbrev() because we also need to make
4135 * sure that the abbreviation does not conflict with any other
4138 * We disallow "interesting" commits to be labeled by a string that
4139 * is a valid full-length hash, to ensure that we always can find an
4140 * abbreviation for any uninteresting commit's names that does not
4141 * clash with any other label.
4146 strbuf_reset(&state->buf);
4147 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4148 label = p = state->buf.buf;
4150 find_unique_abbrev_r(p, oid, default_abbrev);
4153 * We may need to extend the abbreviated hash so that there is
4154 * no conflicting label.
4156 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4157 size_t i = strlen(p) + 1;
4159 oid_to_hex_r(p, oid);
4160 for (; i < GIT_SHA1_HEXSZ; i++) {
4163 if (!hashmap_get_from_hash(&state->labels,
4169 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
4170 !get_oid_hex(label, &dummy)) ||
4171 (len == 1 && *label == '#') ||
4172 hashmap_get_from_hash(&state->labels,
4173 strihash(label), label)) {
4175 * If the label already exists, or if the label is a valid full
4176 * OID, or the label is a '#' (which we use as a separator
4177 * between merge heads and oneline), we append a dash and a
4178 * number to make it unique.
4180 struct strbuf *buf = &state->buf;
4183 strbuf_add(buf, label, len);
4185 for (i = 2; ; i++) {
4186 strbuf_setlen(buf, len);
4187 strbuf_addf(buf, "-%d", i);
4188 if (!hashmap_get_from_hash(&state->labels,
4197 FLEX_ALLOC_STR(labels_entry, label, label);
4198 hashmap_entry_init(labels_entry, strihash(label));
4199 hashmap_add(&state->labels, labels_entry);
4201 FLEX_ALLOC_STR(string_entry, string, label);
4202 oidcpy(&string_entry->entry.oid, oid);
4203 oidmap_put(&state->commit2label, string_entry);
4205 return string_entry->string;
4208 static int make_script_with_merges(struct pretty_print_context *pp,
4209 struct rev_info *revs, FILE *out,
4212 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4213 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4214 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4215 struct strbuf label = STRBUF_INIT;
4216 struct commit_list *commits = NULL, **tail = &commits, *iter;
4217 struct commit_list *tips = NULL, **tips_tail = &tips;
4218 struct commit *commit;
4219 struct oidmap commit2todo = OIDMAP_INIT;
4220 struct string_entry *entry;
4221 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4222 shown = OIDSET_INIT;
4223 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4225 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4226 const char *cmd_pick = abbr ? "p" : "pick",
4227 *cmd_label = abbr ? "l" : "label",
4228 *cmd_reset = abbr ? "t" : "reset",
4229 *cmd_merge = abbr ? "m" : "merge";
4231 oidmap_init(&commit2todo, 0);
4232 oidmap_init(&state.commit2label, 0);
4233 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4234 strbuf_init(&state.buf, 32);
4236 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4237 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4238 FLEX_ALLOC_STR(entry, string, "onto");
4239 oidcpy(&entry->entry.oid, oid);
4240 oidmap_put(&state.commit2label, entry);
4245 * - get onelines for all commits
4246 * - gather all branch tips (i.e. 2nd or later parents of merges)
4247 * - label all branch tips
4249 while ((commit = get_revision(revs))) {
4250 struct commit_list *to_merge;
4251 const char *p1, *p2;
4252 struct object_id *oid;
4255 tail = &commit_list_insert(commit, tail)->next;
4256 oidset_insert(&interesting, &commit->object.oid);
4258 is_empty = is_original_commit_empty(commit);
4259 if (!is_empty && (commit->object.flags & PATCHSAME))
4262 strbuf_reset(&oneline);
4263 pretty_print_commit(pp, commit, &oneline);
4265 to_merge = commit->parents ? commit->parents->next : NULL;
4267 /* non-merge commit: easy case */
4269 if (!keep_empty && is_empty)
4270 strbuf_addf(&buf, "%c ", comment_line_char);
4271 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4272 oid_to_hex(&commit->object.oid),
4275 FLEX_ALLOC_STR(entry, string, buf.buf);
4276 oidcpy(&entry->entry.oid, &commit->object.oid);
4277 oidmap_put(&commit2todo, entry);
4282 /* Create a label */
4283 strbuf_reset(&label);
4284 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4285 (p1 = strchr(p1, '\'')) &&
4286 (p2 = strchr(++p1, '\'')))
4287 strbuf_add(&label, p1, p2 - p1);
4288 else if (skip_prefix(oneline.buf, "Merge pull request ",
4290 (p1 = strstr(p1, " from ")))
4291 strbuf_addstr(&label, p1 + strlen(" from "));
4293 strbuf_addbuf(&label, &oneline);
4295 for (p1 = label.buf; *p1; p1++)
4300 strbuf_addf(&buf, "%s -C %s",
4301 cmd_merge, oid_to_hex(&commit->object.oid));
4303 /* label the tips of merged branches */
4304 for (; to_merge; to_merge = to_merge->next) {
4305 oid = &to_merge->item->object.oid;
4306 strbuf_addch(&buf, ' ');
4308 if (!oidset_contains(&interesting, oid)) {
4309 strbuf_addstr(&buf, label_oid(oid, NULL,
4314 tips_tail = &commit_list_insert(to_merge->item,
4317 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4319 strbuf_addf(&buf, " # %s", oneline.buf);
4321 FLEX_ALLOC_STR(entry, string, buf.buf);
4322 oidcpy(&entry->entry.oid, &commit->object.oid);
4323 oidmap_put(&commit2todo, entry);
4328 * - label branch points
4329 * - add HEAD to the branch tips
4331 for (iter = commits; iter; iter = iter->next) {
4332 struct commit_list *parent = iter->item->parents;
4333 for (; parent; parent = parent->next) {
4334 struct object_id *oid = &parent->item->object.oid;
4335 if (!oidset_contains(&interesting, oid))
4337 if (oidset_insert(&child_seen, oid))
4338 label_oid(oid, "branch-point", &state);
4341 /* Add HEAD as implict "tip of branch" */
4343 tips_tail = &commit_list_insert(iter->item,
4348 * Third phase: output the todo list. This is a bit tricky, as we
4349 * want to avoid jumping back and forth between revisions. To
4350 * accomplish that goal, we walk backwards from the branch tips,
4351 * gathering commits not yet shown, reversing the list on the fly,
4352 * then outputting that list (labeling revisions as needed).
4354 fprintf(out, "%s onto\n", cmd_label);
4355 for (iter = tips; iter; iter = iter->next) {
4356 struct commit_list *list = NULL, *iter2;
4358 commit = iter->item;
4359 if (oidset_contains(&shown, &commit->object.oid))
4361 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4364 fprintf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4368 while (oidset_contains(&interesting, &commit->object.oid) &&
4369 !oidset_contains(&shown, &commit->object.oid)) {
4370 commit_list_insert(commit, &list);
4371 if (!commit->parents) {
4375 commit = commit->parents->item;
4379 fprintf(out, "%s %s\n", cmd_reset,
4380 rebase_cousins ? "onto" : "[new root]");
4382 const char *to = NULL;
4384 entry = oidmap_get(&state.commit2label,
4385 &commit->object.oid);
4388 else if (!rebase_cousins)
4389 to = label_oid(&commit->object.oid, NULL,
4392 if (!to || !strcmp(to, "onto"))
4393 fprintf(out, "%s onto\n", cmd_reset);
4395 strbuf_reset(&oneline);
4396 pretty_print_commit(pp, commit, &oneline);
4397 fprintf(out, "%s %s # %s\n",
4398 cmd_reset, to, oneline.buf);
4402 for (iter2 = list; iter2; iter2 = iter2->next) {
4403 struct object_id *oid = &iter2->item->object.oid;
4404 entry = oidmap_get(&commit2todo, oid);
4405 /* only show if not already upstream */
4407 fprintf(out, "%s\n", entry->string);
4408 entry = oidmap_get(&state.commit2label, oid);
4410 fprintf(out, "%s %s\n",
4411 cmd_label, entry->string);
4412 oidset_insert(&shown, oid);
4415 free_commit_list(list);
4418 free_commit_list(commits);
4419 free_commit_list(tips);
4421 strbuf_release(&label);
4422 strbuf_release(&oneline);
4423 strbuf_release(&buf);
4425 oidmap_free(&commit2todo, 1);
4426 oidmap_free(&state.commit2label, 1);
4427 hashmap_free(&state.labels, 1);
4428 strbuf_release(&state.buf);
4433 int sequencer_make_script(FILE *out, int argc, const char **argv,
4436 char *format = NULL;
4437 struct pretty_print_context pp = {0};
4438 struct strbuf buf = STRBUF_INIT;
4439 struct rev_info revs;
4440 struct commit *commit;
4441 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4442 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4443 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4445 repo_init_revisions(the_repository, &revs, NULL);
4446 revs.verbose_header = 1;
4448 revs.max_parents = 1;
4449 revs.cherry_mark = 1;
4452 revs.right_only = 1;
4453 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4454 revs.topo_order = 1;
4456 revs.pretty_given = 1;
4457 git_config_get_string("rebase.instructionFormat", &format);
4458 if (!format || !*format) {
4460 format = xstrdup("%s");
4462 get_commit_format(format, &revs);
4464 pp.fmt = revs.commit_format;
4465 pp.output_encoding = get_log_output_encoding();
4467 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4468 return error(_("make_script: unhandled options"));
4470 if (prepare_revision_walk(&revs) < 0)
4471 return error(_("make_script: error preparing revisions"));
4474 return make_script_with_merges(&pp, &revs, out, flags);
4476 while ((commit = get_revision(&revs))) {
4477 int is_empty = is_original_commit_empty(commit);
4479 if (!is_empty && (commit->object.flags & PATCHSAME))
4482 if (!keep_empty && is_empty)
4483 strbuf_addf(&buf, "%c ", comment_line_char);
4484 strbuf_addf(&buf, "%s %s ", insn,
4485 oid_to_hex(&commit->object.oid));
4486 pretty_print_commit(&pp, commit, &buf);
4487 strbuf_addch(&buf, '\n');
4488 fputs(buf.buf, out);
4490 strbuf_release(&buf);
4495 * Add commands after pick and (series of) squash/fixup commands
4498 int sequencer_add_exec_commands(const char *commands)
4500 const char *todo_file = rebase_path_todo();
4501 struct todo_list todo_list = TODO_LIST_INIT;
4502 struct strbuf *buf = &todo_list.buf;
4503 size_t offset = 0, commands_len = strlen(commands);
4506 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4507 return error(_("could not read '%s'."), todo_file);
4509 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4510 todo_list_release(&todo_list);
4511 return error(_("unusable todo list: '%s'"), todo_file);
4515 * Insert <commands> after every pick. Here, fixup/squash chains
4516 * are considered part of the pick, so we insert the commands *after*
4517 * those chains if there are any.
4520 for (i = 0; i < todo_list.nr; i++) {
4521 enum todo_command command = todo_list.items[i].command;
4524 /* skip fixup/squash chains */
4525 if (command == TODO_COMMENT)
4527 else if (is_fixup(command)) {
4532 todo_list.items[insert].offset_in_buf +
4533 offset, commands, commands_len);
4534 offset += commands_len;
4538 if (command == TODO_PICK || command == TODO_MERGE)
4542 /* insert or append final <commands> */
4543 if (insert >= 0 && insert < todo_list.nr)
4544 strbuf_insert(buf, todo_list.items[insert].offset_in_buf +
4545 offset, commands, commands_len);
4546 else if (insert >= 0 || !offset)
4547 strbuf_add(buf, commands, commands_len);
4549 i = write_message(buf->buf, buf->len, todo_file, 0);
4550 todo_list_release(&todo_list);
4554 int transform_todos(unsigned flags)
4556 const char *todo_file = rebase_path_todo();
4557 struct todo_list todo_list = TODO_LIST_INIT;
4558 struct strbuf buf = STRBUF_INIT;
4559 struct todo_item *item;
4562 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4563 return error(_("could not read '%s'."), todo_file);
4565 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4566 todo_list_release(&todo_list);
4567 return error(_("unusable todo list: '%s'"), todo_file);
4570 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4571 /* if the item is not a command write it and continue */
4572 if (item->command >= TODO_COMMENT) {
4573 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4577 /* add command to the buffer */
4578 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4579 strbuf_addch(&buf, command_to_char(item->command));
4581 strbuf_addstr(&buf, command_to_string(item->command));
4585 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4586 short_commit_name(item->commit) :
4587 oid_to_hex(&item->commit->object.oid);
4589 if (item->command == TODO_MERGE) {
4590 if (item->flags & TODO_EDIT_MERGE_MSG)
4591 strbuf_addstr(&buf, " -c");
4593 strbuf_addstr(&buf, " -C");
4596 strbuf_addf(&buf, " %s", oid);
4599 /* add all the rest */
4601 strbuf_addch(&buf, '\n');
4603 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4606 i = write_message(buf.buf, buf.len, todo_file, 0);
4607 todo_list_release(&todo_list);
4611 enum missing_commit_check_level get_missing_commit_check_level(void)
4615 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4616 !strcasecmp("ignore", value))
4617 return MISSING_COMMIT_CHECK_IGNORE;
4618 if (!strcasecmp("warn", value))
4619 return MISSING_COMMIT_CHECK_WARN;
4620 if (!strcasecmp("error", value))
4621 return MISSING_COMMIT_CHECK_ERROR;
4622 warning(_("unrecognized setting %s for option "
4623 "rebase.missingCommitsCheck. Ignoring."), value);
4624 return MISSING_COMMIT_CHECK_IGNORE;
4627 define_commit_slab(commit_seen, unsigned char);
4629 * Check if the user dropped some commits by mistake
4630 * Behaviour determined by rebase.missingCommitsCheck.
4631 * Check if there is an unrecognized command or a
4632 * bad SHA-1 in a command.
4634 int check_todo_list(void)
4636 enum missing_commit_check_level check_level = get_missing_commit_check_level();
4637 struct strbuf todo_file = STRBUF_INIT;
4638 struct todo_list todo_list = TODO_LIST_INIT;
4639 struct strbuf missing = STRBUF_INIT;
4640 int advise_to_edit_todo = 0, res = 0, i;
4641 struct commit_seen commit_seen;
4643 init_commit_seen(&commit_seen);
4645 strbuf_addstr(&todo_file, rebase_path_todo());
4646 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4650 advise_to_edit_todo = res =
4651 parse_insn_buffer(todo_list.buf.buf, &todo_list);
4653 if (res || check_level == MISSING_COMMIT_CHECK_IGNORE)
4656 /* Mark the commits in git-rebase-todo as seen */
4657 for (i = 0; i < todo_list.nr; i++) {
4658 struct commit *commit = todo_list.items[i].commit;
4660 *commit_seen_at(&commit_seen, commit) = 1;
4663 todo_list_release(&todo_list);
4664 strbuf_addstr(&todo_file, ".backup");
4665 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4669 strbuf_release(&todo_file);
4670 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4672 /* Find commits in git-rebase-todo.backup yet unseen */
4673 for (i = todo_list.nr - 1; i >= 0; i--) {
4674 struct todo_item *item = todo_list.items + i;
4675 struct commit *commit = item->commit;
4676 if (commit && !*commit_seen_at(&commit_seen, commit)) {
4677 strbuf_addf(&missing, " - %s %.*s\n",
4678 short_commit_name(commit),
4679 item->arg_len, item->arg);
4680 *commit_seen_at(&commit_seen, commit) = 1;
4684 /* Warn about missing commits */
4688 if (check_level == MISSING_COMMIT_CHECK_ERROR)
4689 advise_to_edit_todo = res = 1;
4692 _("Warning: some commits may have been dropped accidentally.\n"
4693 "Dropped commits (newer to older):\n"));
4695 /* Make the list user-friendly and display */
4696 fputs(missing.buf, stderr);
4697 strbuf_release(&missing);
4699 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4700 "explicitly remove a commit.\n\n"
4701 "Use 'git config rebase.missingCommitsCheck' to change "
4702 "the level of warnings.\n"
4703 "The possible behaviours are: ignore, warn, error.\n\n"));
4706 clear_commit_seen(&commit_seen);
4707 strbuf_release(&todo_file);
4708 todo_list_release(&todo_list);
4710 if (advise_to_edit_todo)
4712 _("You can fix this with 'git rebase --edit-todo' "
4713 "and then run 'git rebase --continue'.\n"
4714 "Or you can abort the rebase with 'git rebase"
4720 static int rewrite_file(const char *path, const char *buf, size_t len)
4723 int fd = open(path, O_WRONLY | O_TRUNC);
4725 return error_errno(_("could not open '%s' for writing"), path);
4726 if (write_in_full(fd, buf, len) < 0)
4727 rc = error_errno(_("could not write to '%s'"), path);
4728 if (close(fd) && !rc)
4729 rc = error_errno(_("could not close '%s'"), path);
4733 /* skip picking commits whose parents are unchanged */
4734 static int skip_unnecessary_picks(struct object_id *output_oid)
4736 const char *todo_file = rebase_path_todo();
4737 struct strbuf buf = STRBUF_INIT;
4738 struct todo_list todo_list = TODO_LIST_INIT;
4739 struct object_id *parent_oid;
4742 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4743 return error(_("could not read 'onto'"));
4744 if (get_oid(buf.buf, output_oid)) {
4745 strbuf_release(&buf);
4746 return error(_("need a HEAD to fixup"));
4748 strbuf_release(&buf);
4750 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4752 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4753 todo_list_release(&todo_list);
4757 for (i = 0; i < todo_list.nr; i++) {
4758 struct todo_item *item = todo_list.items + i;
4760 if (item->command >= TODO_NOOP)
4762 if (item->command != TODO_PICK)
4764 if (parse_commit(item->commit)) {
4765 todo_list_release(&todo_list);
4766 return error(_("could not parse commit '%s'"),
4767 oid_to_hex(&item->commit->object.oid));
4769 if (!item->commit->parents)
4770 break; /* root commit */
4771 if (item->commit->parents->next)
4772 break; /* merge commit */
4773 parent_oid = &item->commit->parents->item->object.oid;
4774 if (!oideq(parent_oid, output_oid))
4776 oidcpy(output_oid, &item->commit->object.oid);
4779 int offset = get_item_line_offset(&todo_list, i);
4780 const char *done_path = rebase_path_done();
4782 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4784 error_errno(_("could not open '%s' for writing"),
4786 todo_list_release(&todo_list);
4789 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4790 error_errno(_("could not write to '%s'"), done_path);
4791 todo_list_release(&todo_list);
4797 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4798 todo_list.buf.len - offset) < 0) {
4799 todo_list_release(&todo_list);
4803 todo_list.current = i;
4804 if (is_fixup(peek_command(&todo_list, 0)))
4805 record_in_rewritten(output_oid, peek_command(&todo_list, 0));
4808 todo_list_release(&todo_list);
4813 int complete_action(struct replay_opts *opts, unsigned flags,
4814 const char *shortrevisions, const char *onto_name,
4815 const char *onto, const char *orig_head, const char *cmd,
4816 unsigned autosquash)
4818 const char *shortonto, *todo_file = rebase_path_todo();
4819 struct todo_list todo_list = TODO_LIST_INIT;
4820 struct strbuf *buf = &(todo_list.buf);
4821 struct object_id oid;
4824 get_oid(onto, &oid);
4825 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4827 if (!lstat(todo_file, &st) && st.st_size == 0 &&
4828 write_message("noop\n", 5, todo_file, 0))
4831 if (autosquash && rearrange_squash())
4835 sequencer_add_exec_commands(cmd);
4837 if (strbuf_read_file(buf, todo_file, 0) < 0)
4838 return error_errno(_("could not read '%s'."), todo_file);
4840 if (parse_insn_buffer(buf->buf, &todo_list)) {
4841 todo_list_release(&todo_list);
4842 return error(_("unusable todo list: '%s'"), todo_file);
4845 if (count_commands(&todo_list) == 0) {
4846 apply_autostash(opts);
4847 sequencer_remove_state(opts);
4848 todo_list_release(&todo_list);
4850 return error(_("nothing to do"));
4853 strbuf_addch(buf, '\n');
4854 strbuf_commented_addf(buf, Q_("Rebase %s onto %s (%d command)",
4855 "Rebase %s onto %s (%d commands)",
4856 count_commands(&todo_list)),
4857 shortrevisions, shortonto, count_commands(&todo_list));
4858 append_todo_help(0, flags & TODO_LIST_KEEP_EMPTY, buf);
4860 if (write_message(buf->buf, buf->len, todo_file, 0)) {
4861 todo_list_release(&todo_list);
4865 if (copy_file(rebase_path_todo_backup(), todo_file, 0666))
4866 return error(_("could not copy '%s' to '%s'."), todo_file,
4867 rebase_path_todo_backup());
4869 if (transform_todos(flags | TODO_LIST_SHORTEN_IDS))
4870 return error(_("could not transform the todo list"));
4874 if (launch_sequence_editor(todo_file, buf, NULL)) {
4875 apply_autostash(opts);
4876 sequencer_remove_state(opts);
4877 todo_list_release(&todo_list);
4882 strbuf_stripspace(buf, 1);
4883 if (buf->len == 0) {
4884 apply_autostash(opts);
4885 sequencer_remove_state(opts);
4886 todo_list_release(&todo_list);
4888 return error(_("nothing to do"));
4891 todo_list_release(&todo_list);
4893 if (check_todo_list()) {
4894 checkout_onto(opts, onto_name, onto, orig_head);
4898 if (transform_todos(flags & ~(TODO_LIST_SHORTEN_IDS)))
4899 return error(_("could not transform the todo list"));
4901 if (opts->allow_ff && skip_unnecessary_picks(&oid))
4902 return error(_("could not skip unnecessary pick commands"));
4904 if (checkout_onto(opts, onto_name, oid_to_hex(&oid), orig_head))
4907 if (require_clean_work_tree("rebase", "", 1, 1))
4910 return sequencer_continue(opts);
4913 struct subject2item_entry {
4914 struct hashmap_entry entry;
4916 char subject[FLEX_ARRAY];
4919 static int subject2item_cmp(const void *fndata,
4920 const struct subject2item_entry *a,
4921 const struct subject2item_entry *b, const void *key)
4923 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4926 define_commit_slab(commit_todo_item, struct todo_item *);
4929 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4930 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4931 * after the former, and change "pick" to "fixup"/"squash".
4933 * Note that if the config has specified a custom instruction format, each log
4934 * message will have to be retrieved from the commit (as the oneline in the
4935 * script cannot be trusted) in order to normalize the autosquash arrangement.
4937 int rearrange_squash(void)
4939 const char *todo_file = rebase_path_todo();
4940 struct todo_list todo_list = TODO_LIST_INIT;
4941 struct hashmap subject2item;
4942 int res = 0, rearranged = 0, *next, *tail, i;
4944 struct commit_todo_item commit_todo;
4946 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4948 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4949 todo_list_release(&todo_list);
4953 init_commit_todo_item(&commit_todo);
4955 * The hashmap maps onelines to the respective todo list index.
4957 * If any items need to be rearranged, the next[i] value will indicate
4958 * which item was moved directly after the i'th.
4960 * In that case, last[i] will indicate the index of the latest item to
4961 * be moved to appear after the i'th.
4963 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4964 NULL, todo_list.nr);
4965 ALLOC_ARRAY(next, todo_list.nr);
4966 ALLOC_ARRAY(tail, todo_list.nr);
4967 ALLOC_ARRAY(subjects, todo_list.nr);
4968 for (i = 0; i < todo_list.nr; i++) {
4969 struct strbuf buf = STRBUF_INIT;
4970 struct todo_item *item = todo_list.items + i;
4971 const char *commit_buffer, *subject, *p;
4974 struct subject2item_entry *entry;
4976 next[i] = tail[i] = -1;
4977 if (!item->commit || item->command == TODO_DROP) {
4982 if (is_fixup(item->command)) {
4983 todo_list_release(&todo_list);
4984 clear_commit_todo_item(&commit_todo);
4985 return error(_("the script was already rearranged."));
4988 *commit_todo_item_at(&commit_todo, item->commit) = item;
4990 parse_commit(item->commit);
4991 commit_buffer = get_commit_buffer(item->commit, NULL);
4992 find_commit_subject(commit_buffer, &subject);
4993 format_subject(&buf, subject, " ");
4994 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4995 unuse_commit_buffer(item->commit, commit_buffer);
4996 if ((skip_prefix(subject, "fixup! ", &p) ||
4997 skip_prefix(subject, "squash! ", &p))) {
4998 struct commit *commit2;
5003 if (!skip_prefix(p, "fixup! ", &p) &&
5004 !skip_prefix(p, "squash! ", &p))
5008 if ((entry = hashmap_get_from_hash(&subject2item,
5010 /* found by title */
5012 else if (!strchr(p, ' ') &&
5014 lookup_commit_reference_by_name(p)) &&
5015 *commit_todo_item_at(&commit_todo, commit2))
5016 /* found by commit name */
5017 i2 = *commit_todo_item_at(&commit_todo, commit2)
5020 /* copy can be a prefix of the commit subject */
5021 for (i2 = 0; i2 < i; i2++)
5023 starts_with(subjects[i2], p))
5031 todo_list.items[i].command =
5032 starts_with(subject, "fixup!") ?
5033 TODO_FIXUP : TODO_SQUASH;
5039 } else if (!hashmap_get_from_hash(&subject2item,
5040 strhash(subject), subject)) {
5041 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5043 hashmap_entry_init(entry, strhash(entry->subject));
5044 hashmap_put(&subject2item, entry);
5049 struct strbuf buf = STRBUF_INIT;
5051 for (i = 0; i < todo_list.nr; i++) {
5052 enum todo_command command = todo_list.items[i].command;
5056 * Initially, all commands are 'pick's. If it is a
5057 * fixup or a squash now, we have rearranged it.
5059 if (is_fixup(command))
5064 get_item_line(&todo_list, cur);
5066 get_item_line(&todo_list, cur + 1);
5068 /* replace 'pick', by 'fixup' or 'squash' */
5069 command = todo_list.items[cur].command;
5070 if (is_fixup(command)) {
5072 todo_command_info[command].str);
5073 bol += strcspn(bol, " \t");
5076 strbuf_add(&buf, bol, eol - bol);
5082 res = rewrite_file(todo_file, buf.buf, buf.len);
5083 strbuf_release(&buf);
5088 for (i = 0; i < todo_list.nr; i++)
5091 hashmap_free(&subject2item, 1);
5092 todo_list_release(&todo_list);
5094 clear_commit_todo_item(&commit_todo);