9 #include "run-command.h"
12 #include "cache-tree.h"
16 #include "merge-recursive.h"
18 #include "argv-array.h"
22 #include "wt-status.h"
24 #include "notes-utils.h"
26 #include "unpack-trees.h"
31 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
33 const char sign_off_header[] = "Signed-off-by: ";
34 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
36 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
38 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
40 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
41 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
42 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
43 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
45 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
47 * The file containing rebase commands, comments, and empty lines.
48 * This file is created by "git rebase -i" then edited by the user. As
49 * the lines are processed, they are removed from the front of this
50 * file and written to the tail of 'done'.
52 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
54 * The rebase command lines that have already been processed. A line
55 * is moved here when it is first handled, before any associated user
58 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
60 * The file to keep track of how many commands were already processed (e.g.
63 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
65 * The file to keep track of how many commands are to be processed in total
66 * (e.g. for the prompt).
68 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
70 * The commit message that is planned to be used for any changes that
71 * need to be committed following a user interaction.
73 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
75 * The file into which is accumulated the suggested commit message for
76 * squash/fixup commands. When the first of a series of squash/fixups
77 * is seen, the file is created and the commit message from the
78 * previous commit and from the first squash/fixup commit are written
79 * to it. The commit message for each subsequent squash/fixup commit
80 * is appended to the file as it is processed.
82 * The first line of the file is of the form
83 * # This is a combination of $count commits.
84 * where $count is the number of commits whose messages have been
85 * written to the file so far (including the initial "pick" commit).
86 * Each time that a commit message is processed, this line is read and
87 * updated. It is deleted just before the combined commit is made.
89 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
91 * If the current series of squash/fixups has not yet included a squash
92 * command, then this file exists and holds the commit message of the
93 * original "pick" commit. (If the series ends without a "squash"
94 * command, then this can be used as the commit message of the combined
95 * commit without opening the editor.)
97 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
99 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
100 * GIT_AUTHOR_DATE that will be used for the commit that is currently
103 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
105 * When an "edit" rebase command is being processed, the SHA1 of the
106 * commit to be edited is recorded in this file. When "git rebase
107 * --continue" is executed, if there are any staged changes then they
108 * will be amended to the HEAD commit, but only provided the HEAD
109 * commit is still the commit to be edited. When any other rebase
110 * command is processed, this file is deleted.
112 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
114 * When we stop at a given patch via the "edit" command, this file contains
115 * the abbreviated commit name of the corresponding patch.
117 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
119 * For the post-rewrite hook, we make a list of rewritten commits and
120 * their new sha1s. The rewritten-pending list keeps the sha1s of
121 * commits that have been processed, but not committed yet,
122 * e.g. because they are waiting for a 'squash' command.
124 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
125 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
126 "rebase-merge/rewritten-pending")
129 * The path of the file listing refs that need to be deleted after the rebase
130 * finishes. This is used by the `label` command to record the need for cleanup.
132 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
135 * The following files are written by git-rebase just after parsing the
136 * command-line (and are only consumed, not modified, by the sequencer).
138 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
139 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
140 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
141 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
142 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
143 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
144 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
145 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
146 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
147 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
149 static int git_sequencer_config(const char *k, const char *v, void *cb)
151 struct replay_opts *opts = cb;
154 if (!strcmp(k, "commit.cleanup")) {
157 status = git_config_string(&s, k, v);
161 if (!strcmp(s, "verbatim"))
162 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
163 else if (!strcmp(s, "whitespace"))
164 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
165 else if (!strcmp(s, "strip"))
166 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
167 else if (!strcmp(s, "scissors"))
168 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
170 warning(_("invalid commit message cleanup mode '%s'"),
176 if (!strcmp(k, "commit.gpgsign")) {
177 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
181 status = git_gpg_config(k, v, NULL);
185 return git_diff_basic_config(k, v, NULL);
188 void sequencer_init_config(struct replay_opts *opts)
190 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
191 git_config(git_sequencer_config, opts);
194 static inline int is_rebase_i(const struct replay_opts *opts)
196 return opts->action == REPLAY_INTERACTIVE_REBASE;
199 static const char *get_dir(const struct replay_opts *opts)
201 if (is_rebase_i(opts))
202 return rebase_path();
203 return git_path_seq_dir();
206 static const char *get_todo_path(const struct replay_opts *opts)
208 if (is_rebase_i(opts))
209 return rebase_path_todo();
210 return git_path_todo_file();
214 * Returns 0 for non-conforming footer
215 * Returns 1 for conforming footer
216 * Returns 2 when sob exists within conforming footer
217 * Returns 3 when sob exists within conforming footer as last entry
219 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
222 struct trailer_info info;
224 int found_sob = 0, found_sob_last = 0;
226 trailer_info_get(&info, sb->buf);
228 if (info.trailer_start == info.trailer_end)
231 for (i = 0; i < info.trailer_nr; i++)
232 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
234 if (i == info.trailer_nr - 1)
238 trailer_info_release(&info);
247 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
249 static struct strbuf buf = STRBUF_INIT;
253 sq_quotef(&buf, "-S%s", opts->gpg_sign);
257 int sequencer_remove_state(struct replay_opts *opts)
259 struct strbuf buf = STRBUF_INIT;
262 if (is_rebase_i(opts) &&
263 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
266 char *eol = strchr(p, '\n');
269 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
270 warning(_("could not delete '%s'"), p);
277 free(opts->gpg_sign);
278 free(opts->strategy);
279 for (i = 0; i < opts->xopts_nr; i++)
280 free(opts->xopts[i]);
284 strbuf_addstr(&buf, get_dir(opts));
285 remove_dir_recursively(&buf, 0);
286 strbuf_release(&buf);
291 static const char *action_name(const struct replay_opts *opts)
293 switch (opts->action) {
297 return N_("cherry-pick");
298 case REPLAY_INTERACTIVE_REBASE:
299 return N_("rebase -i");
301 die(_("Unknown action: %d"), opts->action);
304 struct commit_message {
311 static const char *short_commit_name(struct commit *commit)
313 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
316 static int get_message(struct commit *commit, struct commit_message *out)
318 const char *abbrev, *subject;
321 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
322 abbrev = short_commit_name(commit);
324 subject_len = find_commit_subject(out->message, &subject);
326 out->subject = xmemdupz(subject, subject_len);
327 out->label = xstrfmt("%s... %s", abbrev, out->subject);
328 out->parent_label = xstrfmt("parent of %s", out->label);
333 static void free_message(struct commit *commit, struct commit_message *msg)
335 free(msg->parent_label);
338 unuse_commit_buffer(commit, msg->message);
341 static void print_advice(int show_hint, struct replay_opts *opts)
343 char *msg = getenv("GIT_CHERRY_PICK_HELP");
346 fprintf(stderr, "%s\n", msg);
348 * A conflict has occurred but the porcelain
349 * (typically rebase --interactive) wants to take care
350 * of the commit itself so remove CHERRY_PICK_HEAD
352 unlink(git_path_cherry_pick_head());
358 advise(_("after resolving the conflicts, mark the corrected paths\n"
359 "with 'git add <paths>' or 'git rm <paths>'"));
361 advise(_("after resolving the conflicts, mark the corrected paths\n"
362 "with 'git add <paths>' or 'git rm <paths>'\n"
363 "and commit the result with 'git commit'"));
367 static int write_message(const void *buf, size_t len, const char *filename,
370 struct lock_file msg_file = LOCK_INIT;
372 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
374 return error_errno(_("could not lock '%s'"), filename);
375 if (write_in_full(msg_fd, buf, len) < 0) {
376 error_errno(_("could not write to '%s'"), filename);
377 rollback_lock_file(&msg_file);
380 if (append_eol && write(msg_fd, "\n", 1) < 0) {
381 error_errno(_("could not write eol to '%s'"), filename);
382 rollback_lock_file(&msg_file);
385 if (commit_lock_file(&msg_file) < 0)
386 return error(_("failed to finalize '%s'"), filename);
392 * Reads a file that was presumably written by a shell script, i.e. with an
393 * end-of-line marker that needs to be stripped.
395 * Note that only the last end-of-line marker is stripped, consistent with the
396 * behavior of "$(cat path)" in a shell script.
398 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
400 static int read_oneliner(struct strbuf *buf,
401 const char *path, int skip_if_empty)
403 int orig_len = buf->len;
405 if (!file_exists(path))
408 if (strbuf_read_file(buf, path, 0) < 0) {
409 warning_errno(_("could not read '%s'"), path);
413 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
414 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
416 buf->buf[buf->len] = '\0';
419 if (skip_if_empty && buf->len == orig_len)
425 static struct tree *empty_tree(void)
427 return lookup_tree(the_hash_algo->empty_tree);
430 static int error_dirty_index(struct replay_opts *opts)
432 if (read_cache_unmerged())
433 return error_resolve_conflict(_(action_name(opts)));
435 error(_("your local changes would be overwritten by %s."),
436 _(action_name(opts)));
438 if (advice_commit_before_merge)
439 advise(_("commit your changes or stash them to proceed."));
443 static void update_abort_safety_file(void)
445 struct object_id head;
447 /* Do nothing on a single-pick */
448 if (!file_exists(git_path_seq_dir()))
451 if (!get_oid("HEAD", &head))
452 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
454 write_file(git_path_abort_safety_file(), "%s", "");
457 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
458 int unborn, struct replay_opts *opts)
460 struct ref_transaction *transaction;
461 struct strbuf sb = STRBUF_INIT;
462 struct strbuf err = STRBUF_INIT;
465 if (checkout_fast_forward(from, to, 1))
466 return -1; /* the callee should have complained already */
468 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
470 transaction = ref_transaction_begin(&err);
472 ref_transaction_update(transaction, "HEAD",
473 to, unborn ? &null_oid : from,
475 ref_transaction_commit(transaction, &err)) {
476 ref_transaction_free(transaction);
477 error("%s", err.buf);
479 strbuf_release(&err);
484 strbuf_release(&err);
485 ref_transaction_free(transaction);
486 update_abort_safety_file();
490 void append_conflicts_hint(struct strbuf *msgbuf)
494 strbuf_addch(msgbuf, '\n');
495 strbuf_commented_addf(msgbuf, "Conflicts:\n");
496 for (i = 0; i < active_nr;) {
497 const struct cache_entry *ce = active_cache[i++];
499 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
500 while (i < active_nr && !strcmp(ce->name,
501 active_cache[i]->name))
507 static int do_recursive_merge(struct commit *base, struct commit *next,
508 const char *base_label, const char *next_label,
509 struct object_id *head, struct strbuf *msgbuf,
510 struct replay_opts *opts)
512 struct merge_options o;
513 struct tree *result, *next_tree, *base_tree, *head_tree;
516 struct lock_file index_lock = LOCK_INIT;
518 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
523 init_merge_options(&o);
524 o.ancestor = base ? base_label : "(empty tree)";
526 o.branch2 = next ? next_label : "(empty tree)";
527 if (is_rebase_i(opts))
529 o.show_rename_progress = 1;
531 head_tree = parse_tree_indirect(head);
532 next_tree = next ? next->tree : empty_tree();
533 base_tree = base ? base->tree : empty_tree();
535 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
536 parse_merge_opt(&o, *xopt);
538 clean = merge_trees(&o,
540 next_tree, base_tree, &result);
541 if (is_rebase_i(opts) && clean <= 0)
542 fputs(o.obuf.buf, stdout);
543 strbuf_release(&o.obuf);
544 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
546 rollback_lock_file(&index_lock);
550 if (write_locked_index(&the_index, &index_lock,
551 COMMIT_LOCK | SKIP_IF_UNCHANGED))
553 * TRANSLATORS: %s will be "revert", "cherry-pick" or
556 return error(_("%s: Unable to write new index file"),
557 _(action_name(opts)));
560 append_conflicts_hint(msgbuf);
565 static int is_index_unchanged(void)
567 struct object_id head_oid;
568 struct commit *head_commit;
570 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
571 return error(_("could not resolve HEAD commit"));
573 head_commit = lookup_commit(&head_oid);
576 * If head_commit is NULL, check_commit, called from
577 * lookup_commit, would have indicated that head_commit is not
578 * a commit object already. parse_commit() will return failure
579 * without further complaints in such a case. Otherwise, if
580 * the commit is invalid, parse_commit() will complain. So
581 * there is nothing for us to say here. Just return failure.
583 if (parse_commit(head_commit))
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 return error(_("unable to update cache tree"));
593 return !oidcmp(&active_cache_tree->oid,
594 &head_commit->tree->object.oid);
597 static int write_author_script(const char *message)
599 struct strbuf buf = STRBUF_INIT;
604 if (!*message || starts_with(message, "\n")) {
606 /* Missing 'author' line? */
607 unlink(rebase_path_author_script());
609 } else if (skip_prefix(message, "author ", &message))
611 else if ((eol = strchr(message, '\n')))
616 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
617 while (*message && *message != '\n' && *message != '\r')
618 if (skip_prefix(message, " <", &message))
620 else if (*message != '\'')
621 strbuf_addch(&buf, *(message++));
623 strbuf_addf(&buf, "'\\\\%c'", *(message++));
624 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
625 while (*message && *message != '\n' && *message != '\r')
626 if (skip_prefix(message, "> ", &message))
628 else if (*message != '\'')
629 strbuf_addch(&buf, *(message++));
631 strbuf_addf(&buf, "'\\\\%c'", *(message++));
632 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
633 while (*message && *message != '\n' && *message != '\r')
634 if (*message != '\'')
635 strbuf_addch(&buf, *(message++));
637 strbuf_addf(&buf, "'\\\\%c'", *(message++));
638 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
639 strbuf_release(&buf);
644 * Read a list of environment variable assignments (such as the author-script
645 * file) into an environment block. Returns -1 on error, 0 otherwise.
647 static int read_env_script(struct argv_array *env)
649 struct strbuf script = STRBUF_INIT;
653 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
656 for (p = script.buf; *p; p++)
657 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
658 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
660 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
661 else if (*p == '\n') {
666 for (i = 0, p = script.buf; i < count; i++) {
667 argv_array_push(env, p);
674 static char *get_author(const char *message)
679 a = find_commit_header(message, "author", &len);
681 return xmemdupz(a, len);
686 static const char staged_changes_advice[] =
687 N_("you have staged changes in your working tree\n"
688 "If these changes are meant to be squashed into the previous commit, run:\n"
690 " git commit --amend %s\n"
692 "If they are meant to go into a new commit, run:\n"
696 "In both cases, once you're done, continue with:\n"
698 " git rebase --continue\n");
700 #define ALLOW_EMPTY (1<<0)
701 #define EDIT_MSG (1<<1)
702 #define AMEND_MSG (1<<2)
703 #define CLEANUP_MSG (1<<3)
704 #define VERIFY_MSG (1<<4)
707 * If we are cherry-pick, and if the merge did not result in
708 * hand-editing, we will hit this commit and inherit the original
709 * author date and name.
711 * If we are revert, or if our cherry-pick results in a hand merge,
712 * we had better say that the current user is responsible for that.
714 * An exception is when run_git_commit() is called during an
715 * interactive rebase: in that case, we will want to retain the
718 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
721 struct child_process cmd = CHILD_PROCESS_INIT;
726 if (is_rebase_i(opts)) {
727 if (!(flags & EDIT_MSG)) {
728 cmd.stdout_to_stderr = 1;
732 if (read_env_script(&cmd.env_array)) {
733 const char *gpg_opt = gpg_sign_opt_quoted(opts);
735 return error(_(staged_changes_advice),
740 argv_array_push(&cmd.args, "commit");
742 if (!(flags & VERIFY_MSG))
743 argv_array_push(&cmd.args, "-n");
744 if ((flags & AMEND_MSG))
745 argv_array_push(&cmd.args, "--amend");
747 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
749 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
750 if ((flags & CLEANUP_MSG))
751 argv_array_push(&cmd.args, "--cleanup=strip");
752 if ((flags & EDIT_MSG))
753 argv_array_push(&cmd.args, "-e");
754 else if (!(flags & CLEANUP_MSG) &&
755 !opts->signoff && !opts->record_origin &&
756 git_config_get_value("commit.cleanup", &value))
757 argv_array_push(&cmd.args, "--cleanup=verbatim");
759 if ((flags & ALLOW_EMPTY))
760 argv_array_push(&cmd.args, "--allow-empty");
762 if (opts->allow_empty_message)
763 argv_array_push(&cmd.args, "--allow-empty-message");
766 /* hide stderr on success */
767 struct strbuf buf = STRBUF_INIT;
768 int rc = pipe_command(&cmd,
770 /* stdout is already redirected */
774 fputs(buf.buf, stderr);
775 strbuf_release(&buf);
779 return run_command(&cmd);
782 static int rest_is_empty(const struct strbuf *sb, int start)
787 /* Check if the rest is just whitespace and Signed-off-by's. */
788 for (i = start; i < sb->len; i++) {
789 nl = memchr(sb->buf + i, '\n', sb->len - i);
795 if (strlen(sign_off_header) <= eol - i &&
796 starts_with(sb->buf + i, sign_off_header)) {
801 if (!isspace(sb->buf[i++]))
809 * Find out if the message in the strbuf contains only whitespace and
810 * Signed-off-by lines.
812 int message_is_empty(const struct strbuf *sb,
813 enum commit_msg_cleanup_mode cleanup_mode)
815 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
817 return rest_is_empty(sb, 0);
821 * See if the user edited the message in the editor or left what
822 * was in the template intact
824 int template_untouched(const struct strbuf *sb, const char *template_file,
825 enum commit_msg_cleanup_mode cleanup_mode)
827 struct strbuf tmpl = STRBUF_INIT;
830 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
833 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
836 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
837 if (!skip_prefix(sb->buf, tmpl.buf, &start))
839 strbuf_release(&tmpl);
840 return rest_is_empty(sb, start - sb->buf);
843 int update_head_with_reflog(const struct commit *old_head,
844 const struct object_id *new_head,
845 const char *action, const struct strbuf *msg,
848 struct ref_transaction *transaction;
849 struct strbuf sb = STRBUF_INIT;
854 strbuf_addstr(&sb, action);
855 strbuf_addstr(&sb, ": ");
858 nl = strchr(msg->buf, '\n');
860 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
862 strbuf_addbuf(&sb, msg);
863 strbuf_addch(&sb, '\n');
866 transaction = ref_transaction_begin(err);
868 ref_transaction_update(transaction, "HEAD", new_head,
869 old_head ? &old_head->object.oid : &null_oid,
871 ref_transaction_commit(transaction, err)) {
874 ref_transaction_free(transaction);
880 static int run_rewrite_hook(const struct object_id *oldoid,
881 const struct object_id *newoid)
883 struct child_process proc = CHILD_PROCESS_INIT;
886 struct strbuf sb = STRBUF_INIT;
888 argv[0] = find_hook("post-rewrite");
897 proc.stdout_to_stderr = 1;
899 code = start_command(&proc);
902 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
903 sigchain_push(SIGPIPE, SIG_IGN);
904 write_in_full(proc.in, sb.buf, sb.len);
907 sigchain_pop(SIGPIPE);
908 return finish_command(&proc);
911 void commit_post_rewrite(const struct commit *old_head,
912 const struct object_id *new_head)
914 struct notes_rewrite_cfg *cfg;
916 cfg = init_copy_notes_for_rewrite("amend");
918 /* we are amending, so old_head is not NULL */
919 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
920 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
922 run_rewrite_hook(&old_head->object.oid, new_head);
925 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
927 struct argv_array hook_env = ARGV_ARRAY_INIT;
931 name = git_path_commit_editmsg();
932 if (write_message(msg->buf, msg->len, name, 0))
935 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
936 argv_array_push(&hook_env, "GIT_EDITOR=:");
938 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
939 "commit", commit, NULL);
941 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
944 ret = error(_("'prepare-commit-msg' hook failed"));
945 argv_array_clear(&hook_env);
950 static const char implicit_ident_advice_noconfig[] =
951 N_("Your name and email address were configured automatically based\n"
952 "on your username and hostname. Please check that they are accurate.\n"
953 "You can suppress this message by setting them explicitly. Run the\n"
954 "following command and follow the instructions in your editor to edit\n"
955 "your configuration file:\n"
957 " git config --global --edit\n"
959 "After doing this, you may fix the identity used for this commit with:\n"
961 " git commit --amend --reset-author\n");
963 static const char implicit_ident_advice_config[] =
964 N_("Your name and email address were configured automatically based\n"
965 "on your username and hostname. Please check that they are accurate.\n"
966 "You can suppress this message by setting them explicitly:\n"
968 " git config --global user.name \"Your Name\"\n"
969 " git config --global user.email you@example.com\n"
971 "After doing this, you may fix the identity used for this commit with:\n"
973 " git commit --amend --reset-author\n");
975 static const char *implicit_ident_advice(void)
977 char *user_config = expand_user_path("~/.gitconfig", 0);
978 char *xdg_config = xdg_config_home("config");
979 int config_exists = file_exists(user_config) || file_exists(xdg_config);
985 return _(implicit_ident_advice_config);
987 return _(implicit_ident_advice_noconfig);
991 void print_commit_summary(const char *prefix, const struct object_id *oid,
995 struct commit *commit;
996 struct strbuf format = STRBUF_INIT;
998 struct pretty_print_context pctx = {0};
999 struct strbuf author_ident = STRBUF_INIT;
1000 struct strbuf committer_ident = STRBUF_INIT;
1002 commit = lookup_commit(oid);
1004 die(_("couldn't look up newly created commit"));
1005 if (parse_commit(commit))
1006 die(_("could not parse newly created commit"));
1008 strbuf_addstr(&format, "format:%h] %s");
1010 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1011 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1012 if (strbuf_cmp(&author_ident, &committer_ident)) {
1013 strbuf_addstr(&format, "\n Author: ");
1014 strbuf_addbuf_percentquote(&format, &author_ident);
1016 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1017 struct strbuf date = STRBUF_INIT;
1019 format_commit_message(commit, "%ad", &date, &pctx);
1020 strbuf_addstr(&format, "\n Date: ");
1021 strbuf_addbuf_percentquote(&format, &date);
1022 strbuf_release(&date);
1024 if (!committer_ident_sufficiently_given()) {
1025 strbuf_addstr(&format, "\n Committer: ");
1026 strbuf_addbuf_percentquote(&format, &committer_ident);
1027 if (advice_implicit_identity) {
1028 strbuf_addch(&format, '\n');
1029 strbuf_addstr(&format, implicit_ident_advice());
1032 strbuf_release(&author_ident);
1033 strbuf_release(&committer_ident);
1035 init_revisions(&rev, prefix);
1036 setup_revisions(0, NULL, &rev, NULL);
1039 rev.diffopt.output_format =
1040 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1042 rev.verbose_header = 1;
1043 rev.show_root_diff = 1;
1044 get_commit_format(format.buf, &rev);
1045 rev.always_show_header = 0;
1046 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1047 rev.diffopt.break_opt = 0;
1048 diff_setup_done(&rev.diffopt);
1050 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1052 die_errno(_("unable to resolve HEAD after creating commit"));
1053 if (!strcmp(head, "HEAD"))
1054 head = _("detached HEAD");
1056 skip_prefix(head, "refs/heads/", &head);
1057 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1058 _(" (root-commit)") : "");
1060 if (!log_tree_commit(&rev, commit)) {
1061 rev.always_show_header = 1;
1062 rev.use_terminator = 1;
1063 log_tree_commit(&rev, commit);
1066 strbuf_release(&format);
1069 static int parse_head(struct commit **head)
1071 struct commit *current_head;
1072 struct object_id oid;
1074 if (get_oid("HEAD", &oid)) {
1075 current_head = NULL;
1077 current_head = lookup_commit_reference(&oid);
1079 return error(_("could not parse HEAD"));
1080 if (oidcmp(&oid, ¤t_head->object.oid)) {
1081 warning(_("HEAD %s is not a commit!"),
1084 if (parse_commit(current_head))
1085 return error(_("could not parse HEAD commit"));
1087 *head = current_head;
1093 * Try to commit without forking 'git commit'. In some cases we need
1094 * to run 'git commit' to display an error message
1097 * -1 - error unable to commit
1099 * 1 - run 'git commit'
1101 static int try_to_commit(struct strbuf *msg, const char *author,
1102 struct replay_opts *opts, unsigned int flags,
1103 struct object_id *oid)
1105 struct object_id tree;
1106 struct commit *current_head;
1107 struct commit_list *parents = NULL;
1108 struct commit_extra_header *extra = NULL;
1109 struct strbuf err = STRBUF_INIT;
1110 struct strbuf commit_msg = STRBUF_INIT;
1111 char *amend_author = NULL;
1112 const char *hook_commit = NULL;
1113 enum commit_msg_cleanup_mode cleanup;
1116 if (parse_head(¤t_head))
1119 if (flags & AMEND_MSG) {
1120 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1121 const char *out_enc = get_commit_output_encoding();
1122 const char *message = logmsg_reencode(current_head, NULL,
1126 const char *orig_message = NULL;
1128 find_commit_subject(message, &orig_message);
1130 strbuf_addstr(msg, orig_message);
1131 hook_commit = "HEAD";
1133 author = amend_author = get_author(message);
1134 unuse_commit_buffer(current_head, message);
1136 res = error(_("unable to parse commit author"));
1139 parents = copy_commit_list(current_head->parents);
1140 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1141 } else if (current_head) {
1142 commit_list_insert(current_head, &parents);
1145 if (write_cache_as_tree(&tree, 0, NULL)) {
1146 res = error(_("git write-tree failed to write a tree"));
1150 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1151 ¤t_head->tree->object.oid :
1152 &empty_tree_oid, &tree)) {
1153 res = 1; /* run 'git commit' to display error message */
1157 if (find_hook("prepare-commit-msg")) {
1158 res = run_prepare_commit_msg_hook(msg, hook_commit);
1161 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1163 res = error_errno(_("unable to read commit message "
1165 git_path_commit_editmsg());
1171 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1172 opts->default_msg_cleanup;
1174 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1175 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1176 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1177 res = 1; /* run 'git commit' to display error message */
1181 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1182 oid, author, opts->gpg_sign, extra)) {
1183 res = error(_("failed to write commit object"));
1187 if (update_head_with_reflog(current_head, oid,
1188 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1189 res = error("%s", err.buf);
1193 if (flags & AMEND_MSG)
1194 commit_post_rewrite(current_head, oid);
1197 free_commit_extra_headers(extra);
1198 strbuf_release(&err);
1199 strbuf_release(&commit_msg);
1205 static int do_commit(const char *msg_file, const char *author,
1206 struct replay_opts *opts, unsigned int flags)
1210 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1211 struct object_id oid;
1212 struct strbuf sb = STRBUF_INIT;
1214 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1215 return error_errno(_("unable to read commit message "
1219 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1221 strbuf_release(&sb);
1223 unlink(git_path_cherry_pick_head());
1224 unlink(git_path_merge_msg());
1225 if (!is_rebase_i(opts))
1226 print_commit_summary(NULL, &oid,
1227 SUMMARY_SHOW_AUTHOR_DATE);
1232 return run_git_commit(msg_file, opts, flags);
1237 static int is_original_commit_empty(struct commit *commit)
1239 const struct object_id *ptree_oid;
1241 if (parse_commit(commit))
1242 return error(_("could not parse commit %s"),
1243 oid_to_hex(&commit->object.oid));
1244 if (commit->parents) {
1245 struct commit *parent = commit->parents->item;
1246 if (parse_commit(parent))
1247 return error(_("could not parse parent commit %s"),
1248 oid_to_hex(&parent->object.oid));
1249 ptree_oid = &parent->tree->object.oid;
1251 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1254 return !oidcmp(ptree_oid, &commit->tree->object.oid);
1258 * Do we run "git commit" with "--allow-empty"?
1260 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1262 int index_unchanged, empty_commit;
1267 * (1) we do not allow empty at all and error out.
1269 * (2) we allow ones that were initially empty, but
1270 * forbid the ones that become empty;
1272 * (3) we allow both.
1274 if (!opts->allow_empty)
1275 return 0; /* let "git commit" barf as necessary */
1277 index_unchanged = is_index_unchanged();
1278 if (index_unchanged < 0)
1279 return index_unchanged;
1280 if (!index_unchanged)
1281 return 0; /* we do not have to say --allow-empty */
1283 if (opts->keep_redundant_commits)
1286 empty_commit = is_original_commit_empty(commit);
1287 if (empty_commit < 0)
1288 return empty_commit;
1296 * Note that ordering matters in this enum. Not only must it match the mapping
1297 * below, it is also divided into several sections that matter. When adding
1298 * new commands, make sure you add it in the right section.
1301 /* commands that handle commits */
1308 /* commands that do something else than handling a single commit */
1313 /* commands that do nothing but are counted for reporting progress */
1316 /* comments (not counted for reporting progress) */
1323 } todo_command_info[] = {
1339 static const char *command_to_string(const enum todo_command command)
1341 if (command < TODO_COMMENT)
1342 return todo_command_info[command].str;
1343 die("Unknown command: %d", command);
1346 static char command_to_char(const enum todo_command command)
1348 if (command < TODO_COMMENT && todo_command_info[command].c)
1349 return todo_command_info[command].c;
1350 return comment_line_char;
1353 static int is_noop(const enum todo_command command)
1355 return TODO_NOOP <= command;
1358 static int is_fixup(enum todo_command command)
1360 return command == TODO_FIXUP || command == TODO_SQUASH;
1363 static int update_squash_messages(enum todo_command command,
1364 struct commit *commit, struct replay_opts *opts)
1366 struct strbuf buf = STRBUF_INIT;
1368 const char *message, *body;
1370 if (file_exists(rebase_path_squash_msg())) {
1371 struct strbuf header = STRBUF_INIT;
1374 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1375 return error(_("could not read '%s'"),
1376 rebase_path_squash_msg());
1379 eol = strchrnul(buf.buf, '\n');
1380 if (buf.buf[0] != comment_line_char ||
1381 (p += strcspn(p, "0123456789\n")) == eol)
1382 return error(_("unexpected 1st line of squash message:"
1384 (int)(eol - buf.buf), buf.buf);
1385 count = strtol(p, NULL, 10);
1388 return error(_("invalid 1st line of squash message:\n"
1390 (int)(eol - buf.buf), buf.buf);
1392 strbuf_addf(&header, "%c ", comment_line_char);
1393 strbuf_addf(&header,
1394 _("This is a combination of %d commits."), ++count);
1395 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1396 strbuf_release(&header);
1398 struct object_id head;
1399 struct commit *head_commit;
1400 const char *head_message, *body;
1402 if (get_oid("HEAD", &head))
1403 return error(_("need a HEAD to fixup"));
1404 if (!(head_commit = lookup_commit_reference(&head)))
1405 return error(_("could not read HEAD"));
1406 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1407 return error(_("could not read HEAD's commit message"));
1409 find_commit_subject(head_message, &body);
1410 if (write_message(body, strlen(body),
1411 rebase_path_fixup_msg(), 0)) {
1412 unuse_commit_buffer(head_commit, head_message);
1413 return error(_("cannot write '%s'"),
1414 rebase_path_fixup_msg());
1418 strbuf_addf(&buf, "%c ", comment_line_char);
1419 strbuf_addf(&buf, _("This is a combination of %d commits."),
1421 strbuf_addf(&buf, "\n%c ", comment_line_char);
1422 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1423 strbuf_addstr(&buf, "\n\n");
1424 strbuf_addstr(&buf, body);
1426 unuse_commit_buffer(head_commit, head_message);
1429 if (!(message = get_commit_buffer(commit, NULL)))
1430 return error(_("could not read commit message of %s"),
1431 oid_to_hex(&commit->object.oid));
1432 find_commit_subject(message, &body);
1434 if (command == TODO_SQUASH) {
1435 unlink(rebase_path_fixup_msg());
1436 strbuf_addf(&buf, "\n%c ", comment_line_char);
1437 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1438 strbuf_addstr(&buf, "\n\n");
1439 strbuf_addstr(&buf, body);
1440 } else if (command == TODO_FIXUP) {
1441 strbuf_addf(&buf, "\n%c ", comment_line_char);
1442 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1444 strbuf_addstr(&buf, "\n\n");
1445 strbuf_add_commented_lines(&buf, body, strlen(body));
1447 return error(_("unknown command: %d"), command);
1448 unuse_commit_buffer(commit, message);
1450 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1451 strbuf_release(&buf);
1455 static void flush_rewritten_pending(void) {
1456 struct strbuf buf = STRBUF_INIT;
1457 struct object_id newoid;
1460 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1461 !get_oid("HEAD", &newoid) &&
1462 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1463 char *bol = buf.buf, *eol;
1466 eol = strchrnul(bol, '\n');
1467 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1468 bol, oid_to_hex(&newoid));
1474 unlink(rebase_path_rewritten_pending());
1476 strbuf_release(&buf);
1479 static void record_in_rewritten(struct object_id *oid,
1480 enum todo_command next_command) {
1481 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1486 fprintf(out, "%s\n", oid_to_hex(oid));
1489 if (!is_fixup(next_command))
1490 flush_rewritten_pending();
1493 static int do_pick_commit(enum todo_command command, struct commit *commit,
1494 struct replay_opts *opts, int final_fixup)
1496 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1497 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1498 struct object_id head;
1499 struct commit *base, *next, *parent;
1500 const char *base_label, *next_label;
1501 char *author = NULL;
1502 struct commit_message msg = { NULL, NULL, NULL, NULL };
1503 struct strbuf msgbuf = STRBUF_INIT;
1504 int res, unborn = 0, allow;
1506 if (opts->no_commit) {
1508 * We do not intend to commit immediately. We just want to
1509 * merge the differences in, so let's compute the tree
1510 * that represents the "current" state for merge-recursive
1513 if (write_cache_as_tree(&head, 0, NULL))
1514 return error(_("your index file is unmerged."));
1516 unborn = get_oid("HEAD", &head);
1518 oidcpy(&head, the_hash_algo->empty_tree);
1519 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1521 return error_dirty_index(opts);
1525 if (!commit->parents)
1527 else if (commit->parents->next) {
1528 /* Reverting or cherry-picking a merge commit */
1530 struct commit_list *p;
1532 if (!opts->mainline)
1533 return error(_("commit %s is a merge but no -m option was given."),
1534 oid_to_hex(&commit->object.oid));
1536 for (cnt = 1, p = commit->parents;
1537 cnt != opts->mainline && p;
1540 if (cnt != opts->mainline || !p)
1541 return error(_("commit %s does not have parent %d"),
1542 oid_to_hex(&commit->object.oid), opts->mainline);
1544 } else if (0 < opts->mainline)
1545 return error(_("mainline was specified but commit %s is not a merge."),
1546 oid_to_hex(&commit->object.oid));
1548 parent = commit->parents->item;
1550 if (get_message(commit, &msg) != 0)
1551 return error(_("cannot get commit message for %s"),
1552 oid_to_hex(&commit->object.oid));
1554 if (opts->allow_ff && !is_fixup(command) &&
1555 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1556 (!parent && unborn))) {
1557 if (is_rebase_i(opts))
1558 write_author_script(msg.message);
1559 res = fast_forward_to(&commit->object.oid, &head, unborn,
1561 if (res || command != TODO_REWORD)
1563 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1565 goto fast_forward_edit;
1567 if (parent && parse_commit(parent) < 0)
1568 /* TRANSLATORS: The first %s will be a "todo" command like
1569 "revert" or "pick", the second %s a SHA1. */
1570 return error(_("%s: cannot parse parent commit %s"),
1571 command_to_string(command),
1572 oid_to_hex(&parent->object.oid));
1575 * "commit" is an existing commit. We would want to apply
1576 * the difference it introduces since its first parent "prev"
1577 * on top of the current HEAD if we are cherry-pick. Or the
1578 * reverse of it if we are revert.
1581 if (command == TODO_REVERT) {
1583 base_label = msg.label;
1585 next_label = msg.parent_label;
1586 strbuf_addstr(&msgbuf, "Revert \"");
1587 strbuf_addstr(&msgbuf, msg.subject);
1588 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1589 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1591 if (commit->parents && commit->parents->next) {
1592 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1593 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1595 strbuf_addstr(&msgbuf, ".\n");
1600 base_label = msg.parent_label;
1602 next_label = msg.label;
1604 /* Append the commit log message to msgbuf. */
1605 if (find_commit_subject(msg.message, &p))
1606 strbuf_addstr(&msgbuf, p);
1608 if (opts->record_origin) {
1609 strbuf_complete_line(&msgbuf);
1610 if (!has_conforming_footer(&msgbuf, NULL, 0))
1611 strbuf_addch(&msgbuf, '\n');
1612 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1613 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1614 strbuf_addstr(&msgbuf, ")\n");
1616 if (!is_fixup(command))
1617 author = get_author(msg.message);
1620 if (command == TODO_REWORD)
1621 flags |= EDIT_MSG | VERIFY_MSG;
1622 else if (is_fixup(command)) {
1623 if (update_squash_messages(command, commit, opts))
1627 msg_file = rebase_path_squash_msg();
1628 else if (file_exists(rebase_path_fixup_msg())) {
1629 flags |= CLEANUP_MSG;
1630 msg_file = rebase_path_fixup_msg();
1632 const char *dest = git_path_squash_msg();
1634 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1635 return error(_("could not rename '%s' to '%s'"),
1636 rebase_path_squash_msg(), dest);
1637 unlink(git_path_merge_msg());
1643 if (opts->signoff && !is_fixup(command))
1644 append_signoff(&msgbuf, 0, 0);
1646 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1648 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1649 res = do_recursive_merge(base, next, base_label, next_label,
1650 &head, &msgbuf, opts);
1653 res |= write_message(msgbuf.buf, msgbuf.len,
1654 git_path_merge_msg(), 0);
1656 struct commit_list *common = NULL;
1657 struct commit_list *remotes = NULL;
1659 res = write_message(msgbuf.buf, msgbuf.len,
1660 git_path_merge_msg(), 0);
1662 commit_list_insert(base, &common);
1663 commit_list_insert(next, &remotes);
1664 res |= try_merge_command(opts->strategy,
1665 opts->xopts_nr, (const char **)opts->xopts,
1666 common, oid_to_hex(&head), remotes);
1667 free_commit_list(common);
1668 free_commit_list(remotes);
1670 strbuf_release(&msgbuf);
1673 * If the merge was clean or if it failed due to conflict, we write
1674 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1675 * However, if the merge did not even start, then we don't want to
1678 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1679 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1680 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1682 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1683 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1684 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1688 error(command == TODO_REVERT
1689 ? _("could not revert %s... %s")
1690 : _("could not apply %s... %s"),
1691 short_commit_name(commit), msg.subject);
1692 print_advice(res == 1, opts);
1693 rerere(opts->allow_rerere_auto);
1697 allow = allow_empty(opts, commit);
1702 flags |= ALLOW_EMPTY;
1703 if (!opts->no_commit) {
1705 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1706 res = do_commit(msg_file, author, opts, flags);
1708 res = error(_("unable to parse commit author"));
1711 if (!res && final_fixup) {
1712 unlink(rebase_path_fixup_msg());
1713 unlink(rebase_path_squash_msg());
1717 free_message(commit, &msg);
1719 update_abort_safety_file();
1724 static int prepare_revs(struct replay_opts *opts)
1727 * picking (but not reverting) ranges (but not individual revisions)
1728 * should be done in reverse
1730 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1731 opts->revs->reverse ^= 1;
1733 if (prepare_revision_walk(opts->revs))
1734 return error(_("revision walk setup failed"));
1736 if (!opts->revs->commits)
1737 return error(_("empty commit set passed"));
1741 static int read_and_refresh_cache(struct replay_opts *opts)
1743 struct lock_file index_lock = LOCK_INIT;
1744 int index_fd = hold_locked_index(&index_lock, 0);
1745 if (read_index_preload(&the_index, NULL) < 0) {
1746 rollback_lock_file(&index_lock);
1747 return error(_("git %s: failed to read the index"),
1748 _(action_name(opts)));
1750 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1751 if (index_fd >= 0) {
1752 if (write_locked_index(&the_index, &index_lock,
1753 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1754 return error(_("git %s: failed to refresh the index"),
1755 _(action_name(opts)));
1761 enum todo_item_flags {
1762 TODO_EDIT_MERGE_MSG = 1
1766 enum todo_command command;
1767 struct commit *commit;
1771 size_t offset_in_buf;
1776 struct todo_item *items;
1777 int nr, alloc, current;
1778 int done_nr, total_nr;
1779 struct stat_data stat;
1782 #define TODO_LIST_INIT { STRBUF_INIT }
1784 static void todo_list_release(struct todo_list *todo_list)
1786 strbuf_release(&todo_list->buf);
1787 FREE_AND_NULL(todo_list->items);
1788 todo_list->nr = todo_list->alloc = 0;
1791 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1793 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1794 return todo_list->items + todo_list->nr++;
1797 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1799 struct object_id commit_oid;
1800 char *end_of_object_name;
1801 int i, saved, status, padding;
1806 bol += strspn(bol, " \t");
1808 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1809 item->command = TODO_COMMENT;
1810 item->commit = NULL;
1812 item->arg_len = eol - bol;
1816 for (i = 0; i < TODO_COMMENT; i++)
1817 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1820 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1825 if (i >= TODO_COMMENT)
1828 /* Eat up extra spaces/ tabs before object name */
1829 padding = strspn(bol, " \t");
1832 if (item->command == TODO_NOOP) {
1834 return error(_("%s does not accept arguments: '%s'"),
1835 command_to_string(item->command), bol);
1836 item->commit = NULL;
1838 item->arg_len = eol - bol;
1843 return error(_("missing arguments for %s"),
1844 command_to_string(item->command));
1846 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1847 item->command == TODO_RESET) {
1848 item->commit = NULL;
1850 item->arg_len = (int)(eol - bol);
1854 if (item->command == TODO_MERGE) {
1855 if (skip_prefix(bol, "-C", &bol))
1856 bol += strspn(bol, " \t");
1857 else if (skip_prefix(bol, "-c", &bol)) {
1858 bol += strspn(bol, " \t");
1859 item->flags |= TODO_EDIT_MERGE_MSG;
1861 item->flags |= TODO_EDIT_MERGE_MSG;
1862 item->commit = NULL;
1864 item->arg_len = (int)(eol - bol);
1869 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1870 saved = *end_of_object_name;
1871 *end_of_object_name = '\0';
1872 status = get_oid(bol, &commit_oid);
1873 *end_of_object_name = saved;
1875 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1876 item->arg_len = (int)(eol - item->arg);
1881 item->commit = lookup_commit_reference(&commit_oid);
1882 return !item->commit;
1885 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1887 struct todo_item *item;
1888 char *p = buf, *next_p;
1889 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1891 for (i = 1; *p; i++, p = next_p) {
1892 char *eol = strchrnul(p, '\n');
1894 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1896 if (p != eol && eol[-1] == '\r')
1897 eol--; /* strip Carriage Return */
1899 item = append_new_todo(todo_list);
1900 item->offset_in_buf = p - todo_list->buf.buf;
1901 if (parse_insn_line(item, p, eol)) {
1902 res = error(_("invalid line %d: %.*s"),
1903 i, (int)(eol - p), p);
1904 item->command = TODO_NOOP;
1909 else if (is_fixup(item->command))
1910 return error(_("cannot '%s' without a previous commit"),
1911 command_to_string(item->command));
1912 else if (!is_noop(item->command))
1919 static int count_commands(struct todo_list *todo_list)
1923 for (i = 0; i < todo_list->nr; i++)
1924 if (todo_list->items[i].command != TODO_COMMENT)
1930 static int get_item_line_offset(struct todo_list *todo_list, int index)
1932 return index < todo_list->nr ?
1933 todo_list->items[index].offset_in_buf : todo_list->buf.len;
1936 static const char *get_item_line(struct todo_list *todo_list, int index)
1938 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
1941 static int get_item_line_length(struct todo_list *todo_list, int index)
1943 return get_item_line_offset(todo_list, index + 1)
1944 - get_item_line_offset(todo_list, index);
1947 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
1952 fd = open(path, O_RDONLY);
1954 return error_errno(_("could not open '%s'"), path);
1955 len = strbuf_read(sb, fd, 0);
1958 return error(_("could not read '%s'."), path);
1962 static int read_populate_todo(struct todo_list *todo_list,
1963 struct replay_opts *opts)
1966 const char *todo_file = get_todo_path(opts);
1969 strbuf_reset(&todo_list->buf);
1970 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
1973 res = stat(todo_file, &st);
1975 return error(_("could not stat '%s'"), todo_file);
1976 fill_stat_data(&todo_list->stat, &st);
1978 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1980 if (is_rebase_i(opts))
1981 return error(_("please fix this using "
1982 "'git rebase --edit-todo'."));
1983 return error(_("unusable instruction sheet: '%s'"), todo_file);
1986 if (!todo_list->nr &&
1987 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1988 return error(_("no commits parsed."));
1990 if (!is_rebase_i(opts)) {
1991 enum todo_command valid =
1992 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1995 for (i = 0; i < todo_list->nr; i++)
1996 if (valid == todo_list->items[i].command)
1998 else if (valid == TODO_PICK)
1999 return error(_("cannot cherry-pick during a revert."));
2001 return error(_("cannot revert during a cherry-pick."));
2004 if (is_rebase_i(opts)) {
2005 struct todo_list done = TODO_LIST_INIT;
2006 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2008 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2009 !parse_insn_buffer(done.buf.buf, &done))
2010 todo_list->done_nr = count_commands(&done);
2012 todo_list->done_nr = 0;
2014 todo_list->total_nr = todo_list->done_nr
2015 + count_commands(todo_list);
2016 todo_list_release(&done);
2019 fprintf(f, "%d\n", todo_list->total_nr);
2027 static int git_config_string_dup(char **dest,
2028 const char *var, const char *value)
2031 return config_error_nonbool(var);
2033 *dest = xstrdup(value);
2037 static int populate_opts_cb(const char *key, const char *value, void *data)
2039 struct replay_opts *opts = data;
2044 else if (!strcmp(key, "options.no-commit"))
2045 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2046 else if (!strcmp(key, "options.edit"))
2047 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2048 else if (!strcmp(key, "options.signoff"))
2049 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2050 else if (!strcmp(key, "options.record-origin"))
2051 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2052 else if (!strcmp(key, "options.allow-ff"))
2053 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2054 else if (!strcmp(key, "options.mainline"))
2055 opts->mainline = git_config_int(key, value);
2056 else if (!strcmp(key, "options.strategy"))
2057 git_config_string_dup(&opts->strategy, key, value);
2058 else if (!strcmp(key, "options.gpg-sign"))
2059 git_config_string_dup(&opts->gpg_sign, key, value);
2060 else if (!strcmp(key, "options.strategy-option")) {
2061 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2062 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2063 } else if (!strcmp(key, "options.allow-rerere-auto"))
2064 opts->allow_rerere_auto =
2065 git_config_bool_or_int(key, value, &error_flag) ?
2066 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2068 return error(_("invalid key: %s"), key);
2071 return error(_("invalid value for %s: %s"), key, value);
2076 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2081 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2083 opts->strategy = strbuf_detach(buf, NULL);
2084 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2087 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2088 for (i = 0; i < opts->xopts_nr; i++) {
2089 const char *arg = opts->xopts[i];
2091 skip_prefix(arg, "--", &arg);
2092 opts->xopts[i] = xstrdup(arg);
2096 static int read_populate_opts(struct replay_opts *opts)
2098 if (is_rebase_i(opts)) {
2099 struct strbuf buf = STRBUF_INIT;
2101 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2102 if (!starts_with(buf.buf, "-S"))
2105 free(opts->gpg_sign);
2106 opts->gpg_sign = xstrdup(buf.buf + 2);
2111 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2112 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2113 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2114 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2115 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2119 if (file_exists(rebase_path_verbose()))
2122 if (file_exists(rebase_path_signoff())) {
2127 read_strategy_opts(opts, &buf);
2128 strbuf_release(&buf);
2133 if (!file_exists(git_path_opts_file()))
2136 * The function git_parse_source(), called from git_config_from_file(),
2137 * may die() in case of a syntactically incorrect file. We do not care
2138 * about this case, though, because we wrote that file ourselves, so we
2139 * are pretty certain that it is syntactically correct.
2141 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2142 return error(_("malformed options sheet: '%s'"),
2143 git_path_opts_file());
2147 static int walk_revs_populate_todo(struct todo_list *todo_list,
2148 struct replay_opts *opts)
2150 enum todo_command command = opts->action == REPLAY_PICK ?
2151 TODO_PICK : TODO_REVERT;
2152 const char *command_string = todo_command_info[command].str;
2153 struct commit *commit;
2155 if (prepare_revs(opts))
2158 while ((commit = get_revision(opts->revs))) {
2159 struct todo_item *item = append_new_todo(todo_list);
2160 const char *commit_buffer = get_commit_buffer(commit, NULL);
2161 const char *subject;
2164 item->command = command;
2165 item->commit = commit;
2168 item->offset_in_buf = todo_list->buf.len;
2169 subject_len = find_commit_subject(commit_buffer, &subject);
2170 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2171 short_commit_name(commit), subject_len, subject);
2172 unuse_commit_buffer(commit, commit_buffer);
2177 static int create_seq_dir(void)
2179 if (file_exists(git_path_seq_dir())) {
2180 error(_("a cherry-pick or revert is already in progress"));
2181 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2183 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2184 return error_errno(_("could not create sequencer directory '%s'"),
2185 git_path_seq_dir());
2189 static int save_head(const char *head)
2191 struct lock_file head_lock = LOCK_INIT;
2192 struct strbuf buf = STRBUF_INIT;
2196 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2198 return error_errno(_("could not lock HEAD"));
2199 strbuf_addf(&buf, "%s\n", head);
2200 written = write_in_full(fd, buf.buf, buf.len);
2201 strbuf_release(&buf);
2203 error_errno(_("could not write to '%s'"), git_path_head_file());
2204 rollback_lock_file(&head_lock);
2207 if (commit_lock_file(&head_lock) < 0)
2208 return error(_("failed to finalize '%s'"), git_path_head_file());
2212 static int rollback_is_safe(void)
2214 struct strbuf sb = STRBUF_INIT;
2215 struct object_id expected_head, actual_head;
2217 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2219 if (get_oid_hex(sb.buf, &expected_head)) {
2220 strbuf_release(&sb);
2221 die(_("could not parse %s"), git_path_abort_safety_file());
2223 strbuf_release(&sb);
2225 else if (errno == ENOENT)
2226 oidclr(&expected_head);
2228 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2230 if (get_oid("HEAD", &actual_head))
2231 oidclr(&actual_head);
2233 return !oidcmp(&actual_head, &expected_head);
2236 static int reset_for_rollback(const struct object_id *oid)
2238 const char *argv[4]; /* reset --merge <arg> + NULL */
2241 argv[1] = "--merge";
2242 argv[2] = oid_to_hex(oid);
2244 return run_command_v_opt(argv, RUN_GIT_CMD);
2247 static int rollback_single_pick(void)
2249 struct object_id head_oid;
2251 if (!file_exists(git_path_cherry_pick_head()) &&
2252 !file_exists(git_path_revert_head()))
2253 return error(_("no cherry-pick or revert in progress"));
2254 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2255 return error(_("cannot resolve HEAD"));
2256 if (is_null_oid(&head_oid))
2257 return error(_("cannot abort from a branch yet to be born"));
2258 return reset_for_rollback(&head_oid);
2261 int sequencer_rollback(struct replay_opts *opts)
2264 struct object_id oid;
2265 struct strbuf buf = STRBUF_INIT;
2268 f = fopen(git_path_head_file(), "r");
2269 if (!f && errno == ENOENT) {
2271 * There is no multiple-cherry-pick in progress.
2272 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2273 * a single-cherry-pick in progress, abort that.
2275 return rollback_single_pick();
2278 return error_errno(_("cannot open '%s'"), git_path_head_file());
2279 if (strbuf_getline_lf(&buf, f)) {
2280 error(_("cannot read '%s': %s"), git_path_head_file(),
2281 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2286 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2287 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2288 git_path_head_file());
2291 if (is_null_oid(&oid)) {
2292 error(_("cannot abort from a branch yet to be born"));
2296 if (!rollback_is_safe()) {
2297 /* Do not error, just do not rollback */
2298 warning(_("You seem to have moved HEAD. "
2299 "Not rewinding, check your HEAD!"));
2301 if (reset_for_rollback(&oid))
2303 strbuf_release(&buf);
2304 return sequencer_remove_state(opts);
2306 strbuf_release(&buf);
2310 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2312 struct lock_file todo_lock = LOCK_INIT;
2313 const char *todo_path = get_todo_path(opts);
2314 int next = todo_list->current, offset, fd;
2317 * rebase -i writes "git-rebase-todo" without the currently executing
2318 * command, appending it to "done" instead.
2320 if (is_rebase_i(opts))
2323 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2325 return error_errno(_("could not lock '%s'"), todo_path);
2326 offset = get_item_line_offset(todo_list, next);
2327 if (write_in_full(fd, todo_list->buf.buf + offset,
2328 todo_list->buf.len - offset) < 0)
2329 return error_errno(_("could not write to '%s'"), todo_path);
2330 if (commit_lock_file(&todo_lock) < 0)
2331 return error(_("failed to finalize '%s'"), todo_path);
2333 if (is_rebase_i(opts) && next > 0) {
2334 const char *done = rebase_path_done();
2335 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2340 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2341 get_item_line_length(todo_list, next - 1))
2343 ret = error_errno(_("could not write to '%s'"), done);
2345 ret = error_errno(_("failed to finalize '%s'"), done);
2351 static int save_opts(struct replay_opts *opts)
2353 const char *opts_file = git_path_opts_file();
2356 if (opts->no_commit)
2357 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2359 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2361 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2362 if (opts->record_origin)
2363 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2365 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2366 if (opts->mainline) {
2367 struct strbuf buf = STRBUF_INIT;
2368 strbuf_addf(&buf, "%d", opts->mainline);
2369 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2370 strbuf_release(&buf);
2373 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2375 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2378 for (i = 0; i < opts->xopts_nr; i++)
2379 res |= git_config_set_multivar_in_file_gently(opts_file,
2380 "options.strategy-option",
2381 opts->xopts[i], "^$", 0);
2383 if (opts->allow_rerere_auto)
2384 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2385 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2390 static int make_patch(struct commit *commit, struct replay_opts *opts)
2392 struct strbuf buf = STRBUF_INIT;
2393 struct rev_info log_tree_opt;
2394 const char *subject, *p;
2397 p = short_commit_name(commit);
2398 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2400 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2401 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2402 res |= error(_("could not update %s"), "REBASE_HEAD");
2404 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2405 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2406 init_revisions(&log_tree_opt, NULL);
2407 log_tree_opt.abbrev = 0;
2408 log_tree_opt.diff = 1;
2409 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2410 log_tree_opt.disable_stdin = 1;
2411 log_tree_opt.no_commit_id = 1;
2412 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2413 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2414 if (!log_tree_opt.diffopt.file)
2415 res |= error_errno(_("could not open '%s'"), buf.buf);
2417 res |= log_tree_commit(&log_tree_opt, commit);
2418 fclose(log_tree_opt.diffopt.file);
2422 strbuf_addf(&buf, "%s/message", get_dir(opts));
2423 if (!file_exists(buf.buf)) {
2424 const char *commit_buffer = get_commit_buffer(commit, NULL);
2425 find_commit_subject(commit_buffer, &subject);
2426 res |= write_message(subject, strlen(subject), buf.buf, 1);
2427 unuse_commit_buffer(commit, commit_buffer);
2429 strbuf_release(&buf);
2434 static int intend_to_amend(void)
2436 struct object_id head;
2439 if (get_oid("HEAD", &head))
2440 return error(_("cannot read HEAD"));
2442 p = oid_to_hex(&head);
2443 return write_message(p, strlen(p), rebase_path_amend(), 1);
2446 static int error_with_patch(struct commit *commit,
2447 const char *subject, int subject_len,
2448 struct replay_opts *opts, int exit_code, int to_amend)
2450 if (make_patch(commit, opts))
2454 if (intend_to_amend())
2457 fprintf(stderr, "You can amend the commit now, with\n"
2459 " git commit --amend %s\n"
2461 "Once you are satisfied with your changes, run\n"
2463 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2464 } else if (exit_code)
2465 fprintf(stderr, "Could not apply %s... %.*s\n",
2466 short_commit_name(commit), subject_len, subject);
2471 static int error_failed_squash(struct commit *commit,
2472 struct replay_opts *opts, int subject_len, const char *subject)
2474 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2475 return error(_("could not rename '%s' to '%s'"),
2476 rebase_path_squash_msg(), rebase_path_message());
2477 unlink(rebase_path_fixup_msg());
2478 unlink(git_path_merge_msg());
2479 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2480 return error(_("could not copy '%s' to '%s'"),
2481 rebase_path_message(), git_path_merge_msg());
2482 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2485 static int do_exec(const char *command_line)
2487 struct argv_array child_env = ARGV_ARRAY_INIT;
2488 const char *child_argv[] = { NULL, NULL };
2491 fprintf(stderr, "Executing: %s\n", command_line);
2492 child_argv[0] = command_line;
2493 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2494 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2497 /* force re-reading of the cache */
2498 if (discard_cache() < 0 || read_cache() < 0)
2499 return error(_("could not read index"));
2501 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2504 warning(_("execution failed: %s\n%s"
2505 "You can fix the problem, and then run\n"
2507 " git rebase --continue\n"
2510 dirty ? N_("and made changes to the index and/or the "
2511 "working tree\n") : "");
2513 /* command not found */
2516 warning(_("execution succeeded: %s\nbut "
2517 "left changes to the index and/or the working tree\n"
2518 "Commit or stash your changes, and then run\n"
2520 " git rebase --continue\n"
2521 "\n"), command_line);
2525 argv_array_clear(&child_env);
2530 static int safe_append(const char *filename, const char *fmt, ...)
2533 struct lock_file lock = LOCK_INIT;
2534 int fd = hold_lock_file_for_update(&lock, filename,
2535 LOCK_REPORT_ON_ERROR);
2536 struct strbuf buf = STRBUF_INIT;
2541 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2542 error_errno(_("could not read '%s'"), filename);
2543 rollback_lock_file(&lock);
2546 strbuf_complete(&buf, '\n');
2548 strbuf_vaddf(&buf, fmt, ap);
2551 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2552 error_errno(_("could not write to '%s'"), filename);
2553 strbuf_release(&buf);
2554 rollback_lock_file(&lock);
2557 if (commit_lock_file(&lock) < 0) {
2558 strbuf_release(&buf);
2559 rollback_lock_file(&lock);
2560 return error(_("failed to finalize '%s'"), filename);
2563 strbuf_release(&buf);
2567 static int do_label(const char *name, int len)
2569 struct ref_store *refs = get_main_ref_store();
2570 struct ref_transaction *transaction;
2571 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2572 struct strbuf msg = STRBUF_INIT;
2574 struct object_id head_oid;
2576 if (len == 1 && *name == '#')
2577 return error("Illegal label name: '%.*s'", len, name);
2579 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2580 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2582 transaction = ref_store_transaction_begin(refs, &err);
2584 error("%s", err.buf);
2586 } else if (get_oid("HEAD", &head_oid)) {
2587 error(_("could not read HEAD"));
2589 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2590 NULL, 0, msg.buf, &err) < 0 ||
2591 ref_transaction_commit(transaction, &err)) {
2592 error("%s", err.buf);
2595 ref_transaction_free(transaction);
2596 strbuf_release(&err);
2597 strbuf_release(&msg);
2600 ret = safe_append(rebase_path_refs_to_delete(),
2601 "%s\n", ref_name.buf);
2602 strbuf_release(&ref_name);
2607 static const char *reflog_message(struct replay_opts *opts,
2608 const char *sub_action, const char *fmt, ...);
2610 static int do_reset(const char *name, int len, struct replay_opts *opts)
2612 struct strbuf ref_name = STRBUF_INIT;
2613 struct object_id oid;
2614 struct lock_file lock = LOCK_INIT;
2615 struct tree_desc desc;
2617 struct unpack_trees_options unpack_tree_opts;
2620 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2623 /* Determine the length of the label */
2624 for (i = 0; i < len; i++)
2625 if (isspace(name[i]))
2628 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2629 if (get_oid(ref_name.buf, &oid) &&
2630 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2631 error(_("could not read '%s'"), ref_name.buf);
2632 rollback_lock_file(&lock);
2633 strbuf_release(&ref_name);
2637 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2638 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2639 unpack_tree_opts.head_idx = 1;
2640 unpack_tree_opts.src_index = &the_index;
2641 unpack_tree_opts.dst_index = &the_index;
2642 unpack_tree_opts.fn = oneway_merge;
2643 unpack_tree_opts.merge = 1;
2644 unpack_tree_opts.update = 1;
2646 if (read_cache_unmerged()) {
2647 rollback_lock_file(&lock);
2648 strbuf_release(&ref_name);
2649 return error_resolve_conflict(_(action_name(opts)));
2652 if (!fill_tree_descriptor(&desc, &oid)) {
2653 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2654 rollback_lock_file(&lock);
2655 free((void *)desc.buffer);
2656 strbuf_release(&ref_name);
2660 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2661 rollback_lock_file(&lock);
2662 free((void *)desc.buffer);
2663 strbuf_release(&ref_name);
2667 tree = parse_tree_indirect(&oid);
2668 prime_cache_tree(&the_index, tree);
2670 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2671 ret = error(_("could not write index"));
2672 free((void *)desc.buffer);
2675 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2676 len, name), "HEAD", &oid,
2677 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2679 strbuf_release(&ref_name);
2683 static int do_merge(struct commit *commit, const char *arg, int arg_len,
2684 int flags, struct replay_opts *opts)
2686 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2687 EDIT_MSG | VERIFY_MSG : 0;
2688 struct strbuf ref_name = STRBUF_INIT;
2689 struct commit *head_commit, *merge_commit, *i;
2690 struct commit_list *bases, *j, *reversed = NULL;
2691 struct merge_options o;
2692 int merge_arg_len, oneline_offset, can_fast_forward, ret;
2693 static struct lock_file lock;
2696 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2701 head_commit = lookup_commit_reference_by_name("HEAD");
2703 ret = error(_("cannot merge without a current revision"));
2707 oneline_offset = arg_len;
2708 merge_arg_len = strcspn(arg, " \t\n");
2709 p = arg + merge_arg_len;
2710 p += strspn(p, " \t\n");
2711 if (*p == '#' && (!p[1] || isspace(p[1]))) {
2712 p += 1 + strspn(p + 1, " \t\n");
2713 oneline_offset = p - arg;
2714 } else if (p - arg < arg_len)
2715 BUG("octopus merges are not supported yet: '%s'", p);
2717 strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg);
2718 merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2719 if (!merge_commit) {
2720 /* fall back to non-rewritten ref or commit */
2721 strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0);
2722 merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2725 if (!merge_commit) {
2726 ret = error(_("could not resolve '%s'"), ref_name.buf);
2731 const char *message = get_commit_buffer(commit, NULL);
2736 ret = error(_("could not get commit message of '%s'"),
2737 oid_to_hex(&commit->object.oid));
2740 write_author_script(message);
2741 find_commit_subject(message, &body);
2743 ret = write_message(body, len, git_path_merge_msg(), 0);
2744 unuse_commit_buffer(commit, message);
2746 error_errno(_("could not write '%s'"),
2747 git_path_merge_msg());
2751 struct strbuf buf = STRBUF_INIT;
2754 strbuf_addf(&buf, "author %s", git_author_info(0));
2755 write_author_script(buf.buf);
2758 if (oneline_offset < arg_len) {
2759 p = arg + oneline_offset;
2760 len = arg_len - oneline_offset;
2762 strbuf_addf(&buf, "Merge branch '%.*s'",
2763 merge_arg_len, arg);
2768 ret = write_message(p, len, git_path_merge_msg(), 0);
2769 strbuf_release(&buf);
2771 error_errno(_("could not write '%s'"),
2772 git_path_merge_msg());
2778 * If HEAD is not identical to the first parent of the original merge
2779 * commit, we cannot fast-forward.
2781 can_fast_forward = opts->allow_ff && commit && commit->parents &&
2782 !oidcmp(&commit->parents->item->object.oid,
2783 &head_commit->object.oid);
2786 * If the merge head is different from the original one, we cannot
2789 if (can_fast_forward) {
2790 struct commit_list *second_parent = commit->parents->next;
2792 if (second_parent && !second_parent->next &&
2793 oidcmp(&merge_commit->object.oid,
2794 &second_parent->item->object.oid))
2795 can_fast_forward = 0;
2798 if (can_fast_forward && commit->parents->next &&
2799 !commit->parents->next->next &&
2800 !oidcmp(&commit->parents->next->item->object.oid,
2801 &merge_commit->object.oid)) {
2802 rollback_lock_file(&lock);
2803 ret = fast_forward_to(&commit->object.oid,
2804 &head_commit->object.oid, 0, opts);
2808 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
2809 git_path_merge_head(), 0);
2810 write_message("no-ff", 5, git_path_merge_mode(), 0);
2812 bases = get_merge_bases(head_commit, merge_commit);
2813 if (bases && !oidcmp(&merge_commit->object.oid,
2814 &bases->item->object.oid)) {
2816 /* skip merging an ancestor of HEAD */
2820 for (j = bases; j; j = j->next)
2821 commit_list_insert(j->item, &reversed);
2822 free_commit_list(bases);
2825 init_merge_options(&o);
2827 o.branch2 = ref_name.buf;
2828 o.buffer_output = 2;
2830 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
2832 fputs(o.obuf.buf, stdout);
2833 strbuf_release(&o.obuf);
2835 error(_("could not even attempt to merge '%.*s'"),
2836 merge_arg_len, arg);
2840 * The return value of merge_recursive() is 1 on clean, and 0 on
2843 * Let's reverse that, so that do_merge() returns 0 upon success and
2844 * 1 upon failed merge (keeping the return value -1 for the cases where
2845 * we will want to reschedule the `merge` command).
2849 if (active_cache_changed &&
2850 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
2851 ret = error(_("merge: Unable to write new index file"));
2855 rollback_lock_file(&lock);
2857 rerere(opts->allow_rerere_auto);
2860 * In case of problems, we now want to return a positive
2861 * value (a negative one would indicate that the `merge`
2862 * command needs to be rescheduled).
2864 ret = !!run_git_commit(git_path_merge_msg(), opts,
2868 strbuf_release(&ref_name);
2869 rollback_lock_file(&lock);
2873 static int is_final_fixup(struct todo_list *todo_list)
2875 int i = todo_list->current;
2877 if (!is_fixup(todo_list->items[i].command))
2880 while (++i < todo_list->nr)
2881 if (is_fixup(todo_list->items[i].command))
2883 else if (!is_noop(todo_list->items[i].command))
2888 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2892 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2893 if (!is_noop(todo_list->items[i].command))
2894 return todo_list->items[i].command;
2899 static int apply_autostash(struct replay_opts *opts)
2901 struct strbuf stash_sha1 = STRBUF_INIT;
2902 struct child_process child = CHILD_PROCESS_INIT;
2905 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2906 strbuf_release(&stash_sha1);
2909 strbuf_trim(&stash_sha1);
2912 child.no_stdout = 1;
2913 child.no_stderr = 1;
2914 argv_array_push(&child.args, "stash");
2915 argv_array_push(&child.args, "apply");
2916 argv_array_push(&child.args, stash_sha1.buf);
2917 if (!run_command(&child))
2918 fprintf(stderr, _("Applied autostash.\n"));
2920 struct child_process store = CHILD_PROCESS_INIT;
2923 argv_array_push(&store.args, "stash");
2924 argv_array_push(&store.args, "store");
2925 argv_array_push(&store.args, "-m");
2926 argv_array_push(&store.args, "autostash");
2927 argv_array_push(&store.args, "-q");
2928 argv_array_push(&store.args, stash_sha1.buf);
2929 if (run_command(&store))
2930 ret = error(_("cannot store %s"), stash_sha1.buf);
2933 _("Applying autostash resulted in conflicts.\n"
2934 "Your changes are safe in the stash.\n"
2935 "You can run \"git stash pop\" or"
2936 " \"git stash drop\" at any time.\n"));
2939 strbuf_release(&stash_sha1);
2943 static const char *reflog_message(struct replay_opts *opts,
2944 const char *sub_action, const char *fmt, ...)
2947 static struct strbuf buf = STRBUF_INIT;
2951 strbuf_addstr(&buf, action_name(opts));
2953 strbuf_addf(&buf, " (%s)", sub_action);
2955 strbuf_addstr(&buf, ": ");
2956 strbuf_vaddf(&buf, fmt, ap);
2963 static const char rescheduled_advice[] =
2964 N_("Could not execute the todo command\n"
2968 "It has been rescheduled; To edit the command before continuing, please\n"
2969 "edit the todo list first:\n"
2971 " git rebase --edit-todo\n"
2972 " git rebase --continue\n");
2974 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2976 int res = 0, reschedule = 0;
2978 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2980 assert(!(opts->signoff || opts->no_commit ||
2981 opts->record_origin || opts->edit));
2982 if (read_and_refresh_cache(opts))
2985 while (todo_list->current < todo_list->nr) {
2986 struct todo_item *item = todo_list->items + todo_list->current;
2987 if (save_todo(todo_list, opts))
2989 if (is_rebase_i(opts)) {
2990 if (item->command != TODO_COMMENT) {
2991 FILE *f = fopen(rebase_path_msgnum(), "w");
2993 todo_list->done_nr++;
2996 fprintf(f, "%d\n", todo_list->done_nr);
2999 fprintf(stderr, "Rebasing (%d/%d)%s",
3001 todo_list->total_nr,
3002 opts->verbose ? "\n" : "\r");
3004 unlink(rebase_path_message());
3005 unlink(rebase_path_author_script());
3006 unlink(rebase_path_stopped_sha());
3007 unlink(rebase_path_amend());
3008 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3010 if (item->command <= TODO_SQUASH) {
3011 if (is_rebase_i(opts))
3012 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3013 command_to_string(item->command), NULL),
3015 res = do_pick_commit(item->command, item->commit,
3016 opts, is_final_fixup(todo_list));
3017 if (is_rebase_i(opts) && res < 0) {
3019 advise(_(rescheduled_advice),
3020 get_item_line_length(todo_list,
3021 todo_list->current),
3022 get_item_line(todo_list,
3023 todo_list->current));
3024 todo_list->current--;
3025 if (save_todo(todo_list, opts))
3028 if (item->command == TODO_EDIT) {
3029 struct commit *commit = item->commit;
3032 _("Stopped at %s... %.*s\n"),
3033 short_commit_name(commit),
3034 item->arg_len, item->arg);
3035 return error_with_patch(commit,
3036 item->arg, item->arg_len, opts, res,
3039 if (is_rebase_i(opts) && !res)
3040 record_in_rewritten(&item->commit->object.oid,
3041 peek_command(todo_list, 1));
3042 if (res && is_fixup(item->command)) {
3045 return error_failed_squash(item->commit, opts,
3046 item->arg_len, item->arg);
3047 } else if (res && is_rebase_i(opts) && item->commit)
3048 return res | error_with_patch(item->commit,
3049 item->arg, item->arg_len, opts, res,
3050 item->command == TODO_REWORD);
3051 } else if (item->command == TODO_EXEC) {
3052 char *end_of_arg = (char *)(item->arg + item->arg_len);
3053 int saved = *end_of_arg;
3057 res = do_exec(item->arg);
3058 *end_of_arg = saved;
3060 /* Reread the todo file if it has changed. */
3062 ; /* fall through */
3063 else if (stat(get_todo_path(opts), &st))
3064 res = error_errno(_("could not stat '%s'"),
3065 get_todo_path(opts));
3066 else if (match_stat_data(&todo_list->stat, &st)) {
3067 todo_list_release(todo_list);
3068 if (read_populate_todo(todo_list, opts))
3069 res = -1; /* message was printed */
3070 /* `current` will be incremented below */
3071 todo_list->current = -1;
3073 } else if (item->command == TODO_LABEL) {
3074 if ((res = do_label(item->arg, item->arg_len)))
3076 } else if (item->command == TODO_RESET) {
3077 if ((res = do_reset(item->arg, item->arg_len, opts)))
3079 } else if (item->command == TODO_MERGE) {
3080 if ((res = do_merge(item->commit,
3081 item->arg, item->arg_len,
3082 item->flags, opts)) < 0)
3084 else if (item->commit)
3085 record_in_rewritten(&item->commit->object.oid,
3086 peek_command(todo_list, 1));
3088 /* failed with merge conflicts */
3089 return error_with_patch(item->commit,
3091 item->arg_len, opts,
3093 } else if (!is_noop(item->command))
3094 return error(_("unknown command %d"), item->command);
3097 advise(_(rescheduled_advice),
3098 get_item_line_length(todo_list,
3099 todo_list->current),
3100 get_item_line(todo_list, todo_list->current));
3101 todo_list->current--;
3102 if (save_todo(todo_list, opts))
3105 return error_with_patch(item->commit,
3107 item->arg_len, opts,
3111 todo_list->current++;
3116 if (is_rebase_i(opts)) {
3117 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3120 /* Stopped in the middle, as planned? */
3121 if (todo_list->current < todo_list->nr)
3124 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3125 starts_with(head_ref.buf, "refs/")) {
3127 struct object_id head, orig;
3130 if (get_oid("HEAD", &head)) {
3131 res = error(_("cannot read HEAD"));
3133 strbuf_release(&head_ref);
3134 strbuf_release(&buf);
3137 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3138 get_oid_hex(buf.buf, &orig)) {
3139 res = error(_("could not read orig-head"));
3140 goto cleanup_head_ref;
3143 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3144 res = error(_("could not read 'onto'"));
3145 goto cleanup_head_ref;
3147 msg = reflog_message(opts, "finish", "%s onto %s",
3148 head_ref.buf, buf.buf);
3149 if (update_ref(msg, head_ref.buf, &head, &orig,
3150 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3151 res = error(_("could not update %s"),
3153 goto cleanup_head_ref;
3155 msg = reflog_message(opts, "finish", "returning to %s",
3157 if (create_symref("HEAD", head_ref.buf, msg)) {
3158 res = error(_("could not update HEAD to %s"),
3160 goto cleanup_head_ref;
3165 if (opts->verbose) {
3166 struct rev_info log_tree_opt;
3167 struct object_id orig, head;
3169 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3170 init_revisions(&log_tree_opt, NULL);
3171 log_tree_opt.diff = 1;
3172 log_tree_opt.diffopt.output_format =
3173 DIFF_FORMAT_DIFFSTAT;
3174 log_tree_opt.disable_stdin = 1;
3176 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3177 !get_oid(buf.buf, &orig) &&
3178 !get_oid("HEAD", &head)) {
3179 diff_tree_oid(&orig, &head, "",
3180 &log_tree_opt.diffopt);
3181 log_tree_diff_flush(&log_tree_opt);
3184 flush_rewritten_pending();
3185 if (!stat(rebase_path_rewritten_list(), &st) &&
3187 struct child_process child = CHILD_PROCESS_INIT;
3188 const char *post_rewrite_hook =
3189 find_hook("post-rewrite");
3191 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3193 argv_array_push(&child.args, "notes");
3194 argv_array_push(&child.args, "copy");
3195 argv_array_push(&child.args, "--for-rewrite=rebase");
3196 /* we don't care if this copying failed */
3197 run_command(&child);
3199 if (post_rewrite_hook) {
3200 struct child_process hook = CHILD_PROCESS_INIT;
3202 hook.in = open(rebase_path_rewritten_list(),
3204 hook.stdout_to_stderr = 1;
3205 argv_array_push(&hook.args, post_rewrite_hook);
3206 argv_array_push(&hook.args, "rebase");
3207 /* we don't care if this hook failed */
3211 apply_autostash(opts);
3213 fprintf(stderr, "Successfully rebased and updated %s.\n",
3216 strbuf_release(&buf);
3217 strbuf_release(&head_ref);
3221 * Sequence of picks finished successfully; cleanup by
3222 * removing the .git/sequencer directory
3224 return sequencer_remove_state(opts);
3227 static int continue_single_pick(void)
3229 const char *argv[] = { "commit", NULL };
3231 if (!file_exists(git_path_cherry_pick_head()) &&
3232 !file_exists(git_path_revert_head()))
3233 return error(_("no cherry-pick or revert in progress"));
3234 return run_command_v_opt(argv, RUN_GIT_CMD);
3237 static int commit_staged_changes(struct replay_opts *opts)
3239 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3241 if (has_unstaged_changes(1))
3242 return error(_("cannot rebase: You have unstaged changes."));
3243 if (!has_uncommitted_changes(0)) {
3244 const char *cherry_pick_head = git_path_cherry_pick_head();
3246 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3247 return error(_("could not remove CHERRY_PICK_HEAD"));
3251 if (file_exists(rebase_path_amend())) {
3252 struct strbuf rev = STRBUF_INIT;
3253 struct object_id head, to_amend;
3255 if (get_oid("HEAD", &head))
3256 return error(_("cannot amend non-existing commit"));
3257 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3258 return error(_("invalid file: '%s'"), rebase_path_amend());
3259 if (get_oid_hex(rev.buf, &to_amend))
3260 return error(_("invalid contents: '%s'"),
3261 rebase_path_amend());
3262 if (oidcmp(&head, &to_amend))
3263 return error(_("\nYou have uncommitted changes in your "
3264 "working tree. Please, commit them\n"
3265 "first and then run 'git rebase "
3266 "--continue' again."));
3268 strbuf_release(&rev);
3272 if (run_git_commit(rebase_path_message(), opts, flags))
3273 return error(_("could not commit staged changes."));
3274 unlink(rebase_path_amend());
3278 int sequencer_continue(struct replay_opts *opts)
3280 struct todo_list todo_list = TODO_LIST_INIT;
3283 if (read_and_refresh_cache(opts))
3286 if (is_rebase_i(opts)) {
3287 if (commit_staged_changes(opts))
3289 } else if (!file_exists(get_todo_path(opts)))
3290 return continue_single_pick();
3291 if (read_populate_opts(opts))
3293 if ((res = read_populate_todo(&todo_list, opts)))
3294 goto release_todo_list;
3296 if (!is_rebase_i(opts)) {
3297 /* Verify that the conflict has been resolved */
3298 if (file_exists(git_path_cherry_pick_head()) ||
3299 file_exists(git_path_revert_head())) {
3300 res = continue_single_pick();
3302 goto release_todo_list;
3304 if (index_differs_from("HEAD", NULL, 0)) {
3305 res = error_dirty_index(opts);
3306 goto release_todo_list;
3308 todo_list.current++;
3309 } else if (file_exists(rebase_path_stopped_sha())) {
3310 struct strbuf buf = STRBUF_INIT;
3311 struct object_id oid;
3313 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3314 !get_oid_committish(buf.buf, &oid))
3315 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3316 strbuf_release(&buf);
3319 res = pick_commits(&todo_list, opts);
3321 todo_list_release(&todo_list);
3325 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3327 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3328 return do_pick_commit(opts->action == REPLAY_PICK ?
3329 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3332 int sequencer_pick_revisions(struct replay_opts *opts)
3334 struct todo_list todo_list = TODO_LIST_INIT;
3335 struct object_id oid;
3339 if (read_and_refresh_cache(opts))
3342 for (i = 0; i < opts->revs->pending.nr; i++) {
3343 struct object_id oid;
3344 const char *name = opts->revs->pending.objects[i].name;
3346 /* This happens when using --stdin. */
3350 if (!get_oid(name, &oid)) {
3351 if (!lookup_commit_reference_gently(&oid, 1)) {
3352 enum object_type type = oid_object_info(&oid,
3354 return error(_("%s: can't cherry-pick a %s"),
3355 name, type_name(type));
3358 return error(_("%s: bad revision"), name);
3362 * If we were called as "git cherry-pick <commit>", just
3363 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3364 * REVERT_HEAD, and don't touch the sequencer state.
3365 * This means it is possible to cherry-pick in the middle
3366 * of a cherry-pick sequence.
3368 if (opts->revs->cmdline.nr == 1 &&
3369 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3370 opts->revs->no_walk &&
3371 !opts->revs->cmdline.rev->flags) {
3372 struct commit *cmit;
3373 if (prepare_revision_walk(opts->revs))
3374 return error(_("revision walk setup failed"));
3375 cmit = get_revision(opts->revs);
3376 if (!cmit || get_revision(opts->revs))
3377 return error("BUG: expected exactly one commit from walk");
3378 return single_pick(cmit, opts);
3382 * Start a new cherry-pick/ revert sequence; but
3383 * first, make sure that an existing one isn't in
3387 if (walk_revs_populate_todo(&todo_list, opts) ||
3388 create_seq_dir() < 0)
3390 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3391 return error(_("can't revert as initial commit"));
3392 if (save_head(oid_to_hex(&oid)))
3394 if (save_opts(opts))
3396 update_abort_safety_file();
3397 res = pick_commits(&todo_list, opts);
3398 todo_list_release(&todo_list);
3402 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3404 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3405 struct strbuf sob = STRBUF_INIT;
3408 strbuf_addstr(&sob, sign_off_header);
3409 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3410 getenv("GIT_COMMITTER_EMAIL")));
3411 strbuf_addch(&sob, '\n');
3414 strbuf_complete_line(msgbuf);
3417 * If the whole message buffer is equal to the sob, pretend that we
3418 * found a conforming footer with a matching sob
3420 if (msgbuf->len - ignore_footer == sob.len &&
3421 !strncmp(msgbuf->buf, sob.buf, sob.len))
3424 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3427 const char *append_newlines = NULL;
3428 size_t len = msgbuf->len - ignore_footer;
3432 * The buffer is completely empty. Leave foom for
3433 * the title and body to be filled in by the user.
3435 append_newlines = "\n\n";
3436 } else if (len == 1) {
3438 * Buffer contains a single newline. Add another
3439 * so that we leave room for the title and body.
3441 append_newlines = "\n";
3442 } else if (msgbuf->buf[len - 2] != '\n') {
3444 * Buffer ends with a single newline. Add another
3445 * so that there is an empty line between the message
3448 append_newlines = "\n";
3449 } /* else, the buffer already ends with two newlines. */
3451 if (append_newlines)
3452 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3453 append_newlines, strlen(append_newlines));
3456 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3457 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3460 strbuf_release(&sob);
3463 struct labels_entry {
3464 struct hashmap_entry entry;
3465 char label[FLEX_ARRAY];
3468 static int labels_cmp(const void *fndata, const struct labels_entry *a,
3469 const struct labels_entry *b, const void *key)
3471 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3474 struct string_entry {
3475 struct oidmap_entry entry;
3476 char string[FLEX_ARRAY];
3479 struct label_state {
3480 struct oidmap commit2label;
3481 struct hashmap labels;
3485 static const char *label_oid(struct object_id *oid, const char *label,
3486 struct label_state *state)
3488 struct labels_entry *labels_entry;
3489 struct string_entry *string_entry;
3490 struct object_id dummy;
3494 string_entry = oidmap_get(&state->commit2label, oid);
3496 return string_entry->string;
3499 * For "uninteresting" commits, i.e. commits that are not to be
3500 * rebased, and which can therefore not be labeled, we use a unique
3501 * abbreviation of the commit name. This is slightly more complicated
3502 * than calling find_unique_abbrev() because we also need to make
3503 * sure that the abbreviation does not conflict with any other
3506 * We disallow "interesting" commits to be labeled by a string that
3507 * is a valid full-length hash, to ensure that we always can find an
3508 * abbreviation for any uninteresting commit's names that does not
3509 * clash with any other label.
3514 strbuf_reset(&state->buf);
3515 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3516 label = p = state->buf.buf;
3518 find_unique_abbrev_r(p, oid, default_abbrev);
3521 * We may need to extend the abbreviated hash so that there is
3522 * no conflicting label.
3524 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3525 size_t i = strlen(p) + 1;
3527 oid_to_hex_r(p, oid);
3528 for (; i < GIT_SHA1_HEXSZ; i++) {
3531 if (!hashmap_get_from_hash(&state->labels,
3537 } else if (((len = strlen(label)) == GIT_SHA1_RAWSZ &&
3538 !get_oid_hex(label, &dummy)) ||
3539 (len == 1 && *label == '#') ||
3540 hashmap_get_from_hash(&state->labels,
3541 strihash(label), label)) {
3543 * If the label already exists, or if the label is a valid full
3544 * OID, or the label is a '#' (which we use as a separator
3545 * between merge heads and oneline), we append a dash and a
3546 * number to make it unique.
3548 struct strbuf *buf = &state->buf;
3551 strbuf_add(buf, label, len);
3553 for (i = 2; ; i++) {
3554 strbuf_setlen(buf, len);
3555 strbuf_addf(buf, "-%d", i);
3556 if (!hashmap_get_from_hash(&state->labels,
3565 FLEX_ALLOC_STR(labels_entry, label, label);
3566 hashmap_entry_init(labels_entry, strihash(label));
3567 hashmap_add(&state->labels, labels_entry);
3569 FLEX_ALLOC_STR(string_entry, string, label);
3570 oidcpy(&string_entry->entry.oid, oid);
3571 oidmap_put(&state->commit2label, string_entry);
3573 return string_entry->string;
3576 static int make_script_with_merges(struct pretty_print_context *pp,
3577 struct rev_info *revs, FILE *out,
3580 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3581 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
3582 struct strbuf label = STRBUF_INIT;
3583 struct commit_list *commits = NULL, **tail = &commits, *iter;
3584 struct commit_list *tips = NULL, **tips_tail = &tips;
3585 struct commit *commit;
3586 struct oidmap commit2todo = OIDMAP_INIT;
3587 struct string_entry *entry;
3588 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
3589 shown = OIDSET_INIT;
3590 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
3592 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
3593 const char *cmd_pick = abbr ? "p" : "pick",
3594 *cmd_label = abbr ? "l" : "label",
3595 *cmd_reset = abbr ? "t" : "reset",
3596 *cmd_merge = abbr ? "m" : "merge";
3598 oidmap_init(&commit2todo, 0);
3599 oidmap_init(&state.commit2label, 0);
3600 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
3601 strbuf_init(&state.buf, 32);
3603 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
3604 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
3605 FLEX_ALLOC_STR(entry, string, "onto");
3606 oidcpy(&entry->entry.oid, oid);
3607 oidmap_put(&state.commit2label, entry);
3612 * - get onelines for all commits
3613 * - gather all branch tips (i.e. 2nd or later parents of merges)
3614 * - label all branch tips
3616 while ((commit = get_revision(revs))) {
3617 struct commit_list *to_merge;
3619 const char *p1, *p2;
3620 struct object_id *oid;
3623 tail = &commit_list_insert(commit, tail)->next;
3624 oidset_insert(&interesting, &commit->object.oid);
3626 is_empty = is_original_commit_empty(commit);
3627 if (!is_empty && (commit->object.flags & PATCHSAME))
3630 strbuf_reset(&oneline);
3631 pretty_print_commit(pp, commit, &oneline);
3633 to_merge = commit->parents ? commit->parents->next : NULL;
3635 /* non-merge commit: easy case */
3637 if (!keep_empty && is_empty)
3638 strbuf_addf(&buf, "%c ", comment_line_char);
3639 strbuf_addf(&buf, "%s %s %s", cmd_pick,
3640 oid_to_hex(&commit->object.oid),
3643 FLEX_ALLOC_STR(entry, string, buf.buf);
3644 oidcpy(&entry->entry.oid, &commit->object.oid);
3645 oidmap_put(&commit2todo, entry);
3650 is_octopus = to_merge && to_merge->next;
3653 BUG("Octopus merges not yet supported");
3655 /* Create a label */
3656 strbuf_reset(&label);
3657 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
3658 (p1 = strchr(p1, '\'')) &&
3659 (p2 = strchr(++p1, '\'')))
3660 strbuf_add(&label, p1, p2 - p1);
3661 else if (skip_prefix(oneline.buf, "Merge pull request ",
3663 (p1 = strstr(p1, " from ")))
3664 strbuf_addstr(&label, p1 + strlen(" from "));
3666 strbuf_addbuf(&label, &oneline);
3668 for (p1 = label.buf; *p1; p1++)
3673 strbuf_addf(&buf, "%s -C %s",
3674 cmd_merge, oid_to_hex(&commit->object.oid));
3676 /* label the tip of merged branch */
3677 oid = &to_merge->item->object.oid;
3678 strbuf_addch(&buf, ' ');
3680 if (!oidset_contains(&interesting, oid))
3681 strbuf_addstr(&buf, label_oid(oid, NULL, &state));
3683 tips_tail = &commit_list_insert(to_merge->item,
3686 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
3688 strbuf_addf(&buf, " # %s", oneline.buf);
3690 FLEX_ALLOC_STR(entry, string, buf.buf);
3691 oidcpy(&entry->entry.oid, &commit->object.oid);
3692 oidmap_put(&commit2todo, entry);
3697 * - label branch points
3698 * - add HEAD to the branch tips
3700 for (iter = commits; iter; iter = iter->next) {
3701 struct commit_list *parent = iter->item->parents;
3702 for (; parent; parent = parent->next) {
3703 struct object_id *oid = &parent->item->object.oid;
3704 if (!oidset_contains(&interesting, oid))
3706 if (!oidset_contains(&child_seen, oid))
3707 oidset_insert(&child_seen, oid);
3709 label_oid(oid, "branch-point", &state);
3712 /* Add HEAD as implict "tip of branch" */
3714 tips_tail = &commit_list_insert(iter->item,
3719 * Third phase: output the todo list. This is a bit tricky, as we
3720 * want to avoid jumping back and forth between revisions. To
3721 * accomplish that goal, we walk backwards from the branch tips,
3722 * gathering commits not yet shown, reversing the list on the fly,
3723 * then outputting that list (labeling revisions as needed).
3725 fprintf(out, "%s onto\n", cmd_label);
3726 for (iter = tips; iter; iter = iter->next) {
3727 struct commit_list *list = NULL, *iter2;
3729 commit = iter->item;
3730 if (oidset_contains(&shown, &commit->object.oid))
3732 entry = oidmap_get(&state.commit2label, &commit->object.oid);
3735 fprintf(out, "\n# Branch %s\n", entry->string);
3739 while (oidset_contains(&interesting, &commit->object.oid) &&
3740 !oidset_contains(&shown, &commit->object.oid)) {
3741 commit_list_insert(commit, &list);
3742 if (!commit->parents) {
3746 commit = commit->parents->item;
3750 fprintf(out, "%s onto\n", cmd_reset);
3752 const char *to = NULL;
3754 entry = oidmap_get(&state.commit2label,
3755 &commit->object.oid);
3759 if (!to || !strcmp(to, "onto"))
3760 fprintf(out, "%s onto\n", cmd_reset);
3762 strbuf_reset(&oneline);
3763 pretty_print_commit(pp, commit, &oneline);
3764 fprintf(out, "%s %s # %s\n",
3765 cmd_reset, to, oneline.buf);
3769 for (iter2 = list; iter2; iter2 = iter2->next) {
3770 struct object_id *oid = &iter2->item->object.oid;
3771 entry = oidmap_get(&commit2todo, oid);
3772 /* only show if not already upstream */
3774 fprintf(out, "%s\n", entry->string);
3775 entry = oidmap_get(&state.commit2label, oid);
3777 fprintf(out, "%s %s\n",
3778 cmd_label, entry->string);
3779 oidset_insert(&shown, oid);
3782 free_commit_list(list);
3785 free_commit_list(commits);
3786 free_commit_list(tips);
3788 strbuf_release(&label);
3789 strbuf_release(&oneline);
3790 strbuf_release(&buf);
3792 oidmap_free(&commit2todo, 1);
3793 oidmap_free(&state.commit2label, 1);
3794 hashmap_free(&state.labels, 1);
3795 strbuf_release(&state.buf);
3800 int sequencer_make_script(FILE *out, int argc, const char **argv,
3803 char *format = NULL;
3804 struct pretty_print_context pp = {0};
3805 struct strbuf buf = STRBUF_INIT;
3806 struct rev_info revs;
3807 struct commit *commit;
3808 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3809 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
3810 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
3812 init_revisions(&revs, NULL);
3813 revs.verbose_header = 1;
3815 revs.max_parents = 1;
3816 revs.cherry_mark = 1;
3819 revs.right_only = 1;
3820 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3821 revs.topo_order = 1;
3823 revs.pretty_given = 1;
3824 git_config_get_string("rebase.instructionFormat", &format);
3825 if (!format || !*format) {
3827 format = xstrdup("%s");
3829 get_commit_format(format, &revs);
3831 pp.fmt = revs.commit_format;
3832 pp.output_encoding = get_log_output_encoding();
3834 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3835 return error(_("make_script: unhandled options"));
3837 if (prepare_revision_walk(&revs) < 0)
3838 return error(_("make_script: error preparing revisions"));
3841 return make_script_with_merges(&pp, &revs, out, flags);
3843 while ((commit = get_revision(&revs))) {
3844 int is_empty = is_original_commit_empty(commit);
3846 if (!is_empty && (commit->object.flags & PATCHSAME))
3849 if (!keep_empty && is_empty)
3850 strbuf_addf(&buf, "%c ", comment_line_char);
3851 strbuf_addf(&buf, "%s %s ", insn,
3852 oid_to_hex(&commit->object.oid));
3853 pretty_print_commit(&pp, commit, &buf);
3854 strbuf_addch(&buf, '\n');
3855 fputs(buf.buf, out);
3857 strbuf_release(&buf);
3862 * Add commands after pick and (series of) squash/fixup commands
3865 int sequencer_add_exec_commands(const char *commands)
3867 const char *todo_file = rebase_path_todo();
3868 struct todo_list todo_list = TODO_LIST_INIT;
3869 struct todo_item *item;
3870 struct strbuf *buf = &todo_list.buf;
3871 size_t offset = 0, commands_len = strlen(commands);
3874 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3875 return error(_("could not read '%s'."), todo_file);
3877 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3878 todo_list_release(&todo_list);
3879 return error(_("unusable todo list: '%s'"), todo_file);
3883 /* insert <commands> before every pick except the first one */
3884 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3885 if (item->command == TODO_PICK && !first) {
3886 strbuf_insert(buf, item->offset_in_buf + offset,
3887 commands, commands_len);
3888 offset += commands_len;
3893 /* append final <commands> */
3894 strbuf_add(buf, commands, commands_len);
3896 i = write_message(buf->buf, buf->len, todo_file, 0);
3897 todo_list_release(&todo_list);
3901 int transform_todos(unsigned flags)
3903 const char *todo_file = rebase_path_todo();
3904 struct todo_list todo_list = TODO_LIST_INIT;
3905 struct strbuf buf = STRBUF_INIT;
3906 struct todo_item *item;
3909 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3910 return error(_("could not read '%s'."), todo_file);
3912 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3913 todo_list_release(&todo_list);
3914 return error(_("unusable todo list: '%s'"), todo_file);
3917 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3918 /* if the item is not a command write it and continue */
3919 if (item->command >= TODO_COMMENT) {
3920 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3924 /* add command to the buffer */
3925 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3926 strbuf_addch(&buf, command_to_char(item->command));
3928 strbuf_addstr(&buf, command_to_string(item->command));
3932 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3933 short_commit_name(item->commit) :
3934 oid_to_hex(&item->commit->object.oid);
3936 if (item->command == TODO_MERGE) {
3937 if (item->flags & TODO_EDIT_MERGE_MSG)
3938 strbuf_addstr(&buf, " -c");
3940 strbuf_addstr(&buf, " -C");
3943 strbuf_addf(&buf, " %s", oid);
3946 /* add all the rest */
3948 strbuf_addch(&buf, '\n');
3950 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3953 i = write_message(buf.buf, buf.len, todo_file, 0);
3954 todo_list_release(&todo_list);
3959 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3962 static enum check_level get_missing_commit_check_level(void)
3966 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3967 !strcasecmp("ignore", value))
3968 return CHECK_IGNORE;
3969 if (!strcasecmp("warn", value))
3971 if (!strcasecmp("error", value))
3973 warning(_("unrecognized setting %s for option "
3974 "rebase.missingCommitsCheck. Ignoring."), value);
3975 return CHECK_IGNORE;
3979 * Check if the user dropped some commits by mistake
3980 * Behaviour determined by rebase.missingCommitsCheck.
3981 * Check if there is an unrecognized command or a
3982 * bad SHA-1 in a command.
3984 int check_todo_list(void)
3986 enum check_level check_level = get_missing_commit_check_level();
3987 struct strbuf todo_file = STRBUF_INIT;
3988 struct todo_list todo_list = TODO_LIST_INIT;
3989 struct strbuf missing = STRBUF_INIT;
3990 int advise_to_edit_todo = 0, res = 0, i;
3992 strbuf_addstr(&todo_file, rebase_path_todo());
3993 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3997 advise_to_edit_todo = res =
3998 parse_insn_buffer(todo_list.buf.buf, &todo_list);
4000 if (res || check_level == CHECK_IGNORE)
4003 /* Mark the commits in git-rebase-todo as seen */
4004 for (i = 0; i < todo_list.nr; i++) {
4005 struct commit *commit = todo_list.items[i].commit;
4007 commit->util = (void *)1;
4010 todo_list_release(&todo_list);
4011 strbuf_addstr(&todo_file, ".backup");
4012 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4016 strbuf_release(&todo_file);
4017 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4019 /* Find commits in git-rebase-todo.backup yet unseen */
4020 for (i = todo_list.nr - 1; i >= 0; i--) {
4021 struct todo_item *item = todo_list.items + i;
4022 struct commit *commit = item->commit;
4023 if (commit && !commit->util) {
4024 strbuf_addf(&missing, " - %s %.*s\n",
4025 short_commit_name(commit),
4026 item->arg_len, item->arg);
4027 commit->util = (void *)1;
4031 /* Warn about missing commits */
4035 if (check_level == CHECK_ERROR)
4036 advise_to_edit_todo = res = 1;
4039 _("Warning: some commits may have been dropped accidentally.\n"
4040 "Dropped commits (newer to older):\n"));
4042 /* Make the list user-friendly and display */
4043 fputs(missing.buf, stderr);
4044 strbuf_release(&missing);
4046 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4047 "explicitly remove a commit.\n\n"
4048 "Use 'git config rebase.missingCommitsCheck' to change "
4049 "the level of warnings.\n"
4050 "The possible behaviours are: ignore, warn, error.\n\n"));
4053 strbuf_release(&todo_file);
4054 todo_list_release(&todo_list);
4056 if (advise_to_edit_todo)
4058 _("You can fix this with 'git rebase --edit-todo' "
4059 "and then run 'git rebase --continue'.\n"
4060 "Or you can abort the rebase with 'git rebase"
4066 static int rewrite_file(const char *path, const char *buf, size_t len)
4069 int fd = open(path, O_WRONLY | O_TRUNC);
4071 return error_errno(_("could not open '%s' for writing"), path);
4072 if (write_in_full(fd, buf, len) < 0)
4073 rc = error_errno(_("could not write to '%s'"), path);
4074 if (close(fd) && !rc)
4075 rc = error_errno(_("could not close '%s'"), path);
4079 /* skip picking commits whose parents are unchanged */
4080 int skip_unnecessary_picks(void)
4082 const char *todo_file = rebase_path_todo();
4083 struct strbuf buf = STRBUF_INIT;
4084 struct todo_list todo_list = TODO_LIST_INIT;
4085 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4088 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4089 return error(_("could not read 'onto'"));
4090 if (get_oid(buf.buf, &onto_oid)) {
4091 strbuf_release(&buf);
4092 return error(_("need a HEAD to fixup"));
4094 strbuf_release(&buf);
4096 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4098 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4099 todo_list_release(&todo_list);
4103 for (i = 0; i < todo_list.nr; i++) {
4104 struct todo_item *item = todo_list.items + i;
4106 if (item->command >= TODO_NOOP)
4108 if (item->command != TODO_PICK)
4110 if (parse_commit(item->commit)) {
4111 todo_list_release(&todo_list);
4112 return error(_("could not parse commit '%s'"),
4113 oid_to_hex(&item->commit->object.oid));
4115 if (!item->commit->parents)
4116 break; /* root commit */
4117 if (item->commit->parents->next)
4118 break; /* merge commit */
4119 parent_oid = &item->commit->parents->item->object.oid;
4120 if (hashcmp(parent_oid->hash, oid->hash))
4122 oid = &item->commit->object.oid;
4125 int offset = get_item_line_offset(&todo_list, i);
4126 const char *done_path = rebase_path_done();
4128 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4130 error_errno(_("could not open '%s' for writing"),
4132 todo_list_release(&todo_list);
4135 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4136 error_errno(_("could not write to '%s'"), done_path);
4137 todo_list_release(&todo_list);
4143 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4144 todo_list.buf.len - offset) < 0) {
4145 todo_list_release(&todo_list);
4149 todo_list.current = i;
4150 if (is_fixup(peek_command(&todo_list, 0)))
4151 record_in_rewritten(oid, peek_command(&todo_list, 0));
4154 todo_list_release(&todo_list);
4155 printf("%s\n", oid_to_hex(oid));
4160 struct subject2item_entry {
4161 struct hashmap_entry entry;
4163 char subject[FLEX_ARRAY];
4166 static int subject2item_cmp(const void *fndata,
4167 const struct subject2item_entry *a,
4168 const struct subject2item_entry *b, const void *key)
4170 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4174 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4175 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4176 * after the former, and change "pick" to "fixup"/"squash".
4178 * Note that if the config has specified a custom instruction format, each log
4179 * message will have to be retrieved from the commit (as the oneline in the
4180 * script cannot be trusted) in order to normalize the autosquash arrangement.
4182 int rearrange_squash(void)
4184 const char *todo_file = rebase_path_todo();
4185 struct todo_list todo_list = TODO_LIST_INIT;
4186 struct hashmap subject2item;
4187 int res = 0, rearranged = 0, *next, *tail, i;
4190 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4192 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4193 todo_list_release(&todo_list);
4198 * The hashmap maps onelines to the respective todo list index.
4200 * If any items need to be rearranged, the next[i] value will indicate
4201 * which item was moved directly after the i'th.
4203 * In that case, last[i] will indicate the index of the latest item to
4204 * be moved to appear after the i'th.
4206 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4207 NULL, todo_list.nr);
4208 ALLOC_ARRAY(next, todo_list.nr);
4209 ALLOC_ARRAY(tail, todo_list.nr);
4210 ALLOC_ARRAY(subjects, todo_list.nr);
4211 for (i = 0; i < todo_list.nr; i++) {
4212 struct strbuf buf = STRBUF_INIT;
4213 struct todo_item *item = todo_list.items + i;
4214 const char *commit_buffer, *subject, *p;
4217 struct subject2item_entry *entry;
4219 next[i] = tail[i] = -1;
4220 if (!item->commit || item->command == TODO_DROP) {
4225 if (is_fixup(item->command)) {
4226 todo_list_release(&todo_list);
4227 return error(_("the script was already rearranged."));
4230 item->commit->util = item;
4232 parse_commit(item->commit);
4233 commit_buffer = get_commit_buffer(item->commit, NULL);
4234 find_commit_subject(commit_buffer, &subject);
4235 format_subject(&buf, subject, " ");
4236 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4237 unuse_commit_buffer(item->commit, commit_buffer);
4238 if ((skip_prefix(subject, "fixup! ", &p) ||
4239 skip_prefix(subject, "squash! ", &p))) {
4240 struct commit *commit2;
4245 if (!skip_prefix(p, "fixup! ", &p) &&
4246 !skip_prefix(p, "squash! ", &p))
4250 if ((entry = hashmap_get_from_hash(&subject2item,
4252 /* found by title */
4254 else if (!strchr(p, ' ') &&
4256 lookup_commit_reference_by_name(p)) &&
4258 /* found by commit name */
4259 i2 = (struct todo_item *)commit2->util
4262 /* copy can be a prefix of the commit subject */
4263 for (i2 = 0; i2 < i; i2++)
4265 starts_with(subjects[i2], p))
4273 todo_list.items[i].command =
4274 starts_with(subject, "fixup!") ?
4275 TODO_FIXUP : TODO_SQUASH;
4281 } else if (!hashmap_get_from_hash(&subject2item,
4282 strhash(subject), subject)) {
4283 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4285 hashmap_entry_init(entry, strhash(entry->subject));
4286 hashmap_put(&subject2item, entry);
4291 struct strbuf buf = STRBUF_INIT;
4293 for (i = 0; i < todo_list.nr; i++) {
4294 enum todo_command command = todo_list.items[i].command;
4298 * Initially, all commands are 'pick's. If it is a
4299 * fixup or a squash now, we have rearranged it.
4301 if (is_fixup(command))
4306 get_item_line(&todo_list, cur);
4308 get_item_line(&todo_list, cur + 1);
4310 /* replace 'pick', by 'fixup' or 'squash' */
4311 command = todo_list.items[cur].command;
4312 if (is_fixup(command)) {
4314 todo_command_info[command].str);
4315 bol += strcspn(bol, " \t");
4318 strbuf_add(&buf, bol, eol - bol);
4324 res = rewrite_file(todo_file, buf.buf, buf.len);
4325 strbuf_release(&buf);
4330 for (i = 0; i < todo_list.nr; i++)
4333 hashmap_free(&subject2item, 1);
4334 todo_list_release(&todo_list);