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 containig the OID of the "squash onto" commit, i.e.
130 * the dummy commit used for `reset [new root]`.
132 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
135 * The path of the file listing refs that need to be deleted after the rebase
136 * finishes. This is used by the `label` command to record the need for cleanup.
138 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
141 * The following files are written by git-rebase just after parsing the
142 * command-line (and are only consumed, not modified, by the sequencer).
144 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
145 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
146 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
147 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
148 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
149 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
150 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
151 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
152 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
153 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
155 static int git_sequencer_config(const char *k, const char *v, void *cb)
157 struct replay_opts *opts = cb;
160 if (!strcmp(k, "commit.cleanup")) {
163 status = git_config_string(&s, k, v);
167 if (!strcmp(s, "verbatim"))
168 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
169 else if (!strcmp(s, "whitespace"))
170 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
171 else if (!strcmp(s, "strip"))
172 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
173 else if (!strcmp(s, "scissors"))
174 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
176 warning(_("invalid commit message cleanup mode '%s'"),
182 if (!strcmp(k, "commit.gpgsign")) {
183 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
187 status = git_gpg_config(k, v, NULL);
191 return git_diff_basic_config(k, v, NULL);
194 void sequencer_init_config(struct replay_opts *opts)
196 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
197 git_config(git_sequencer_config, opts);
200 static inline int is_rebase_i(const struct replay_opts *opts)
202 return opts->action == REPLAY_INTERACTIVE_REBASE;
205 static const char *get_dir(const struct replay_opts *opts)
207 if (is_rebase_i(opts))
208 return rebase_path();
209 return git_path_seq_dir();
212 static const char *get_todo_path(const struct replay_opts *opts)
214 if (is_rebase_i(opts))
215 return rebase_path_todo();
216 return git_path_todo_file();
220 * Returns 0 for non-conforming footer
221 * Returns 1 for conforming footer
222 * Returns 2 when sob exists within conforming footer
223 * Returns 3 when sob exists within conforming footer as last entry
225 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
228 struct trailer_info info;
230 int found_sob = 0, found_sob_last = 0;
232 trailer_info_get(&info, sb->buf);
234 if (info.trailer_start == info.trailer_end)
237 for (i = 0; i < info.trailer_nr; i++)
238 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
240 if (i == info.trailer_nr - 1)
244 trailer_info_release(&info);
253 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
255 static struct strbuf buf = STRBUF_INIT;
259 sq_quotef(&buf, "-S%s", opts->gpg_sign);
263 int sequencer_remove_state(struct replay_opts *opts)
265 struct strbuf buf = STRBUF_INIT;
268 if (is_rebase_i(opts) &&
269 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
272 char *eol = strchr(p, '\n');
275 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
276 warning(_("could not delete '%s'"), p);
283 free(opts->gpg_sign);
284 free(opts->strategy);
285 for (i = 0; i < opts->xopts_nr; i++)
286 free(opts->xopts[i]);
290 strbuf_addstr(&buf, get_dir(opts));
291 remove_dir_recursively(&buf, 0);
292 strbuf_release(&buf);
297 static const char *action_name(const struct replay_opts *opts)
299 switch (opts->action) {
303 return N_("cherry-pick");
304 case REPLAY_INTERACTIVE_REBASE:
305 return N_("rebase -i");
307 die(_("Unknown action: %d"), opts->action);
310 struct commit_message {
317 static const char *short_commit_name(struct commit *commit)
319 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
322 static int get_message(struct commit *commit, struct commit_message *out)
324 const char *abbrev, *subject;
327 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
328 abbrev = short_commit_name(commit);
330 subject_len = find_commit_subject(out->message, &subject);
332 out->subject = xmemdupz(subject, subject_len);
333 out->label = xstrfmt("%s... %s", abbrev, out->subject);
334 out->parent_label = xstrfmt("parent of %s", out->label);
339 static void free_message(struct commit *commit, struct commit_message *msg)
341 free(msg->parent_label);
344 unuse_commit_buffer(commit, msg->message);
347 static void print_advice(int show_hint, struct replay_opts *opts)
349 char *msg = getenv("GIT_CHERRY_PICK_HELP");
352 fprintf(stderr, "%s\n", msg);
354 * A conflict has occurred but the porcelain
355 * (typically rebase --interactive) wants to take care
356 * of the commit itself so remove CHERRY_PICK_HEAD
358 unlink(git_path_cherry_pick_head());
364 advise(_("after resolving the conflicts, mark the corrected paths\n"
365 "with 'git add <paths>' or 'git rm <paths>'"));
367 advise(_("after resolving the conflicts, mark the corrected paths\n"
368 "with 'git add <paths>' or 'git rm <paths>'\n"
369 "and commit the result with 'git commit'"));
373 static int write_message(const void *buf, size_t len, const char *filename,
376 struct lock_file msg_file = LOCK_INIT;
378 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
380 return error_errno(_("could not lock '%s'"), filename);
381 if (write_in_full(msg_fd, buf, len) < 0) {
382 error_errno(_("could not write to '%s'"), filename);
383 rollback_lock_file(&msg_file);
386 if (append_eol && write(msg_fd, "\n", 1) < 0) {
387 error_errno(_("could not write eol to '%s'"), filename);
388 rollback_lock_file(&msg_file);
391 if (commit_lock_file(&msg_file) < 0)
392 return error(_("failed to finalize '%s'"), filename);
398 * Reads a file that was presumably written by a shell script, i.e. with an
399 * end-of-line marker that needs to be stripped.
401 * Note that only the last end-of-line marker is stripped, consistent with the
402 * behavior of "$(cat path)" in a shell script.
404 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
406 static int read_oneliner(struct strbuf *buf,
407 const char *path, int skip_if_empty)
409 int orig_len = buf->len;
411 if (!file_exists(path))
414 if (strbuf_read_file(buf, path, 0) < 0) {
415 warning_errno(_("could not read '%s'"), path);
419 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
420 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
422 buf->buf[buf->len] = '\0';
425 if (skip_if_empty && buf->len == orig_len)
431 static struct tree *empty_tree(void)
433 return lookup_tree(the_hash_algo->empty_tree);
436 static int error_dirty_index(struct replay_opts *opts)
438 if (read_cache_unmerged())
439 return error_resolve_conflict(_(action_name(opts)));
441 error(_("your local changes would be overwritten by %s."),
442 _(action_name(opts)));
444 if (advice_commit_before_merge)
445 advise(_("commit your changes or stash them to proceed."));
449 static void update_abort_safety_file(void)
451 struct object_id head;
453 /* Do nothing on a single-pick */
454 if (!file_exists(git_path_seq_dir()))
457 if (!get_oid("HEAD", &head))
458 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
460 write_file(git_path_abort_safety_file(), "%s", "");
463 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
464 int unborn, struct replay_opts *opts)
466 struct ref_transaction *transaction;
467 struct strbuf sb = STRBUF_INIT;
468 struct strbuf err = STRBUF_INIT;
471 if (checkout_fast_forward(from, to, 1))
472 return -1; /* the callee should have complained already */
474 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
476 transaction = ref_transaction_begin(&err);
478 ref_transaction_update(transaction, "HEAD",
479 to, unborn && !is_rebase_i(opts) ?
482 ref_transaction_commit(transaction, &err)) {
483 ref_transaction_free(transaction);
484 error("%s", err.buf);
486 strbuf_release(&err);
491 strbuf_release(&err);
492 ref_transaction_free(transaction);
493 update_abort_safety_file();
497 void append_conflicts_hint(struct strbuf *msgbuf)
501 strbuf_addch(msgbuf, '\n');
502 strbuf_commented_addf(msgbuf, "Conflicts:\n");
503 for (i = 0; i < active_nr;) {
504 const struct cache_entry *ce = active_cache[i++];
506 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
507 while (i < active_nr && !strcmp(ce->name,
508 active_cache[i]->name))
514 static int do_recursive_merge(struct commit *base, struct commit *next,
515 const char *base_label, const char *next_label,
516 struct object_id *head, struct strbuf *msgbuf,
517 struct replay_opts *opts)
519 struct merge_options o;
520 struct tree *result, *next_tree, *base_tree, *head_tree;
523 struct lock_file index_lock = LOCK_INIT;
525 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
530 init_merge_options(&o);
531 o.ancestor = base ? base_label : "(empty tree)";
533 o.branch2 = next ? next_label : "(empty tree)";
534 if (is_rebase_i(opts))
536 o.show_rename_progress = 1;
538 head_tree = parse_tree_indirect(head);
539 next_tree = next ? next->tree : empty_tree();
540 base_tree = base ? base->tree : empty_tree();
542 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
543 parse_merge_opt(&o, *xopt);
545 clean = merge_trees(&o,
547 next_tree, base_tree, &result);
548 if (is_rebase_i(opts) && clean <= 0)
549 fputs(o.obuf.buf, stdout);
550 strbuf_release(&o.obuf);
551 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
553 rollback_lock_file(&index_lock);
557 if (write_locked_index(&the_index, &index_lock,
558 COMMIT_LOCK | SKIP_IF_UNCHANGED))
560 * TRANSLATORS: %s will be "revert", "cherry-pick" or
563 return error(_("%s: Unable to write new index file"),
564 _(action_name(opts)));
567 append_conflicts_hint(msgbuf);
572 static struct object_id *get_cache_tree_oid(void)
574 if (!active_cache_tree)
575 active_cache_tree = cache_tree();
577 if (!cache_tree_fully_valid(active_cache_tree))
578 if (cache_tree_update(&the_index, 0)) {
579 error(_("unable to update cache tree"));
583 return &active_cache_tree->oid;
586 static int is_index_unchanged(void)
588 struct object_id head_oid, *cache_tree_oid;
589 struct commit *head_commit;
591 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
592 return error(_("could not resolve HEAD commit"));
594 head_commit = lookup_commit(&head_oid);
597 * If head_commit is NULL, check_commit, called from
598 * lookup_commit, would have indicated that head_commit is not
599 * a commit object already. parse_commit() will return failure
600 * without further complaints in such a case. Otherwise, if
601 * the commit is invalid, parse_commit() will complain. So
602 * there is nothing for us to say here. Just return failure.
604 if (parse_commit(head_commit))
607 if (!(cache_tree_oid = get_cache_tree_oid()))
610 return !oidcmp(cache_tree_oid, &head_commit->tree->object.oid);
613 static int write_author_script(const char *message)
615 struct strbuf buf = STRBUF_INIT;
620 if (!*message || starts_with(message, "\n")) {
622 /* Missing 'author' line? */
623 unlink(rebase_path_author_script());
625 } else if (skip_prefix(message, "author ", &message))
627 else if ((eol = strchr(message, '\n')))
632 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
633 while (*message && *message != '\n' && *message != '\r')
634 if (skip_prefix(message, " <", &message))
636 else if (*message != '\'')
637 strbuf_addch(&buf, *(message++));
639 strbuf_addf(&buf, "'\\\\%c'", *(message++));
640 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
641 while (*message && *message != '\n' && *message != '\r')
642 if (skip_prefix(message, "> ", &message))
644 else if (*message != '\'')
645 strbuf_addch(&buf, *(message++));
647 strbuf_addf(&buf, "'\\\\%c'", *(message++));
648 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
649 while (*message && *message != '\n' && *message != '\r')
650 if (*message != '\'')
651 strbuf_addch(&buf, *(message++));
653 strbuf_addf(&buf, "'\\\\%c'", *(message++));
654 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
655 strbuf_release(&buf);
660 * Read a list of environment variable assignments (such as the author-script
661 * file) into an environment block. Returns -1 on error, 0 otherwise.
663 static int read_env_script(struct argv_array *env)
665 struct strbuf script = STRBUF_INIT;
669 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
672 for (p = script.buf; *p; p++)
673 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
674 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
676 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
677 else if (*p == '\n') {
682 for (i = 0, p = script.buf; i < count; i++) {
683 argv_array_push(env, p);
690 static char *get_author(const char *message)
695 a = find_commit_header(message, "author", &len);
697 return xmemdupz(a, len);
702 /* Read author-script and return an ident line (author <email> timestamp) */
703 static const char *read_author_ident(struct strbuf *buf)
705 const char *keys[] = {
706 "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
708 char *in, *out, *eol;
711 if (strbuf_read_file(buf, rebase_path_author_script(), 256) <= 0)
714 /* dequote values and construct ident line in-place */
715 for (in = out = buf->buf; i < 3 && in - buf->buf < buf->len; i++) {
716 if (!skip_prefix(in, keys[i], (const char **)&in)) {
717 warning("could not parse '%s' (looking for '%s'",
718 rebase_path_author_script(), keys[i]);
722 eol = strchrnul(in, '\n');
727 if (i > 0) /* separate values by spaces */
729 if (i == 1) /* email needs to be surrounded by <...> */
731 memmove(out, in, len);
733 if (i == 1) /* email needs to be surrounded by <...> */
739 warning("could not parse '%s' (looking for '%s')",
740 rebase_path_author_script(), keys[i]);
744 buf->len = out - buf->buf;
748 static const char staged_changes_advice[] =
749 N_("you have staged changes in your working tree\n"
750 "If these changes are meant to be squashed into the previous commit, run:\n"
752 " git commit --amend %s\n"
754 "If they are meant to go into a new commit, run:\n"
758 "In both cases, once you're done, continue with:\n"
760 " git rebase --continue\n");
762 #define ALLOW_EMPTY (1<<0)
763 #define EDIT_MSG (1<<1)
764 #define AMEND_MSG (1<<2)
765 #define CLEANUP_MSG (1<<3)
766 #define VERIFY_MSG (1<<4)
767 #define CREATE_ROOT_COMMIT (1<<5)
770 * If we are cherry-pick, and if the merge did not result in
771 * hand-editing, we will hit this commit and inherit the original
772 * author date and name.
774 * If we are revert, or if our cherry-pick results in a hand merge,
775 * we had better say that the current user is responsible for that.
777 * An exception is when run_git_commit() is called during an
778 * interactive rebase: in that case, we will want to retain the
781 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
784 struct child_process cmd = CHILD_PROCESS_INIT;
787 if (flags & CREATE_ROOT_COMMIT) {
788 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
789 const char *author = is_rebase_i(opts) ?
790 read_author_ident(&script) : NULL;
791 struct object_id root_commit, *cache_tree_oid;
795 BUG("root commit without message");
797 if (!(cache_tree_oid = get_cache_tree_oid()))
801 res = strbuf_read_file(&msg, defmsg, 0);
804 res = error_errno(_("could not read '%s'"), defmsg);
806 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
807 NULL, &root_commit, author,
810 strbuf_release(&msg);
811 strbuf_release(&script);
813 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
814 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
815 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
816 UPDATE_REFS_MSG_ON_ERR);
818 return res < 0 ? error(_("writing root commit")) : 0;
823 if (is_rebase_i(opts)) {
824 if (!(flags & EDIT_MSG)) {
825 cmd.stdout_to_stderr = 1;
829 if (read_env_script(&cmd.env_array)) {
830 const char *gpg_opt = gpg_sign_opt_quoted(opts);
832 return error(_(staged_changes_advice),
837 argv_array_push(&cmd.args, "commit");
839 if (!(flags & VERIFY_MSG))
840 argv_array_push(&cmd.args, "-n");
841 if ((flags & AMEND_MSG))
842 argv_array_push(&cmd.args, "--amend");
844 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
846 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
847 if ((flags & CLEANUP_MSG))
848 argv_array_push(&cmd.args, "--cleanup=strip");
849 if ((flags & EDIT_MSG))
850 argv_array_push(&cmd.args, "-e");
851 else if (!(flags & CLEANUP_MSG) &&
852 !opts->signoff && !opts->record_origin &&
853 git_config_get_value("commit.cleanup", &value))
854 argv_array_push(&cmd.args, "--cleanup=verbatim");
856 if ((flags & ALLOW_EMPTY))
857 argv_array_push(&cmd.args, "--allow-empty");
859 if (opts->allow_empty_message)
860 argv_array_push(&cmd.args, "--allow-empty-message");
863 /* hide stderr on success */
864 struct strbuf buf = STRBUF_INIT;
865 int rc = pipe_command(&cmd,
867 /* stdout is already redirected */
871 fputs(buf.buf, stderr);
872 strbuf_release(&buf);
876 return run_command(&cmd);
879 static int rest_is_empty(const struct strbuf *sb, int start)
884 /* Check if the rest is just whitespace and Signed-off-by's. */
885 for (i = start; i < sb->len; i++) {
886 nl = memchr(sb->buf + i, '\n', sb->len - i);
892 if (strlen(sign_off_header) <= eol - i &&
893 starts_with(sb->buf + i, sign_off_header)) {
898 if (!isspace(sb->buf[i++]))
906 * Find out if the message in the strbuf contains only whitespace and
907 * Signed-off-by lines.
909 int message_is_empty(const struct strbuf *sb,
910 enum commit_msg_cleanup_mode cleanup_mode)
912 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
914 return rest_is_empty(sb, 0);
918 * See if the user edited the message in the editor or left what
919 * was in the template intact
921 int template_untouched(const struct strbuf *sb, const char *template_file,
922 enum commit_msg_cleanup_mode cleanup_mode)
924 struct strbuf tmpl = STRBUF_INIT;
927 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
930 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
933 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
934 if (!skip_prefix(sb->buf, tmpl.buf, &start))
936 strbuf_release(&tmpl);
937 return rest_is_empty(sb, start - sb->buf);
940 int update_head_with_reflog(const struct commit *old_head,
941 const struct object_id *new_head,
942 const char *action, const struct strbuf *msg,
945 struct ref_transaction *transaction;
946 struct strbuf sb = STRBUF_INIT;
951 strbuf_addstr(&sb, action);
952 strbuf_addstr(&sb, ": ");
955 nl = strchr(msg->buf, '\n');
957 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
959 strbuf_addbuf(&sb, msg);
960 strbuf_addch(&sb, '\n');
963 transaction = ref_transaction_begin(err);
965 ref_transaction_update(transaction, "HEAD", new_head,
966 old_head ? &old_head->object.oid : &null_oid,
968 ref_transaction_commit(transaction, err)) {
971 ref_transaction_free(transaction);
977 static int run_rewrite_hook(const struct object_id *oldoid,
978 const struct object_id *newoid)
980 struct child_process proc = CHILD_PROCESS_INIT;
983 struct strbuf sb = STRBUF_INIT;
985 argv[0] = find_hook("post-rewrite");
994 proc.stdout_to_stderr = 1;
996 code = start_command(&proc);
999 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1000 sigchain_push(SIGPIPE, SIG_IGN);
1001 write_in_full(proc.in, sb.buf, sb.len);
1003 strbuf_release(&sb);
1004 sigchain_pop(SIGPIPE);
1005 return finish_command(&proc);
1008 void commit_post_rewrite(const struct commit *old_head,
1009 const struct object_id *new_head)
1011 struct notes_rewrite_cfg *cfg;
1013 cfg = init_copy_notes_for_rewrite("amend");
1015 /* we are amending, so old_head is not NULL */
1016 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1017 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1019 run_rewrite_hook(&old_head->object.oid, new_head);
1022 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
1024 struct argv_array hook_env = ARGV_ARRAY_INIT;
1028 name = git_path_commit_editmsg();
1029 if (write_message(msg->buf, msg->len, name, 0))
1032 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
1033 argv_array_push(&hook_env, "GIT_EDITOR=:");
1035 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1036 "commit", commit, NULL);
1038 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1041 ret = error(_("'prepare-commit-msg' hook failed"));
1042 argv_array_clear(&hook_env);
1047 static const char implicit_ident_advice_noconfig[] =
1048 N_("Your name and email address were configured automatically based\n"
1049 "on your username and hostname. Please check that they are accurate.\n"
1050 "You can suppress this message by setting them explicitly. Run the\n"
1051 "following command and follow the instructions in your editor to edit\n"
1052 "your configuration file:\n"
1054 " git config --global --edit\n"
1056 "After doing this, you may fix the identity used for this commit with:\n"
1058 " git commit --amend --reset-author\n");
1060 static const char implicit_ident_advice_config[] =
1061 N_("Your name and email address were configured automatically based\n"
1062 "on your username and hostname. Please check that they are accurate.\n"
1063 "You can suppress this message by setting them explicitly:\n"
1065 " git config --global user.name \"Your Name\"\n"
1066 " git config --global user.email you@example.com\n"
1068 "After doing this, you may fix the identity used for this commit with:\n"
1070 " git commit --amend --reset-author\n");
1072 static const char *implicit_ident_advice(void)
1074 char *user_config = expand_user_path("~/.gitconfig", 0);
1075 char *xdg_config = xdg_config_home("config");
1076 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1082 return _(implicit_ident_advice_config);
1084 return _(implicit_ident_advice_noconfig);
1088 void print_commit_summary(const char *prefix, const struct object_id *oid,
1091 struct rev_info rev;
1092 struct commit *commit;
1093 struct strbuf format = STRBUF_INIT;
1095 struct pretty_print_context pctx = {0};
1096 struct strbuf author_ident = STRBUF_INIT;
1097 struct strbuf committer_ident = STRBUF_INIT;
1099 commit = lookup_commit(oid);
1101 die(_("couldn't look up newly created commit"));
1102 if (parse_commit(commit))
1103 die(_("could not parse newly created commit"));
1105 strbuf_addstr(&format, "format:%h] %s");
1107 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1108 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1109 if (strbuf_cmp(&author_ident, &committer_ident)) {
1110 strbuf_addstr(&format, "\n Author: ");
1111 strbuf_addbuf_percentquote(&format, &author_ident);
1113 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1114 struct strbuf date = STRBUF_INIT;
1116 format_commit_message(commit, "%ad", &date, &pctx);
1117 strbuf_addstr(&format, "\n Date: ");
1118 strbuf_addbuf_percentquote(&format, &date);
1119 strbuf_release(&date);
1121 if (!committer_ident_sufficiently_given()) {
1122 strbuf_addstr(&format, "\n Committer: ");
1123 strbuf_addbuf_percentquote(&format, &committer_ident);
1124 if (advice_implicit_identity) {
1125 strbuf_addch(&format, '\n');
1126 strbuf_addstr(&format, implicit_ident_advice());
1129 strbuf_release(&author_ident);
1130 strbuf_release(&committer_ident);
1132 init_revisions(&rev, prefix);
1133 setup_revisions(0, NULL, &rev, NULL);
1136 rev.diffopt.output_format =
1137 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1139 rev.verbose_header = 1;
1140 rev.show_root_diff = 1;
1141 get_commit_format(format.buf, &rev);
1142 rev.always_show_header = 0;
1143 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1144 rev.diffopt.break_opt = 0;
1145 diff_setup_done(&rev.diffopt);
1147 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1149 die_errno(_("unable to resolve HEAD after creating commit"));
1150 if (!strcmp(head, "HEAD"))
1151 head = _("detached HEAD");
1153 skip_prefix(head, "refs/heads/", &head);
1154 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1155 _(" (root-commit)") : "");
1157 if (!log_tree_commit(&rev, commit)) {
1158 rev.always_show_header = 1;
1159 rev.use_terminator = 1;
1160 log_tree_commit(&rev, commit);
1163 strbuf_release(&format);
1166 static int parse_head(struct commit **head)
1168 struct commit *current_head;
1169 struct object_id oid;
1171 if (get_oid("HEAD", &oid)) {
1172 current_head = NULL;
1174 current_head = lookup_commit_reference(&oid);
1176 return error(_("could not parse HEAD"));
1177 if (oidcmp(&oid, ¤t_head->object.oid)) {
1178 warning(_("HEAD %s is not a commit!"),
1181 if (parse_commit(current_head))
1182 return error(_("could not parse HEAD commit"));
1184 *head = current_head;
1190 * Try to commit without forking 'git commit'. In some cases we need
1191 * to run 'git commit' to display an error message
1194 * -1 - error unable to commit
1196 * 1 - run 'git commit'
1198 static int try_to_commit(struct strbuf *msg, const char *author,
1199 struct replay_opts *opts, unsigned int flags,
1200 struct object_id *oid)
1202 struct object_id tree;
1203 struct commit *current_head;
1204 struct commit_list *parents = NULL;
1205 struct commit_extra_header *extra = NULL;
1206 struct strbuf err = STRBUF_INIT;
1207 struct strbuf commit_msg = STRBUF_INIT;
1208 char *amend_author = NULL;
1209 const char *hook_commit = NULL;
1210 enum commit_msg_cleanup_mode cleanup;
1213 if (parse_head(¤t_head))
1216 if (flags & AMEND_MSG) {
1217 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1218 const char *out_enc = get_commit_output_encoding();
1219 const char *message = logmsg_reencode(current_head, NULL,
1223 const char *orig_message = NULL;
1225 find_commit_subject(message, &orig_message);
1227 strbuf_addstr(msg, orig_message);
1228 hook_commit = "HEAD";
1230 author = amend_author = get_author(message);
1231 unuse_commit_buffer(current_head, message);
1233 res = error(_("unable to parse commit author"));
1236 parents = copy_commit_list(current_head->parents);
1237 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1238 } else if (current_head) {
1239 commit_list_insert(current_head, &parents);
1242 if (write_cache_as_tree(&tree, 0, NULL)) {
1243 res = error(_("git write-tree failed to write a tree"));
1247 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1248 ¤t_head->tree->object.oid :
1249 &empty_tree_oid, &tree)) {
1250 res = 1; /* run 'git commit' to display error message */
1254 if (find_hook("prepare-commit-msg")) {
1255 res = run_prepare_commit_msg_hook(msg, hook_commit);
1258 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1260 res = error_errno(_("unable to read commit message "
1262 git_path_commit_editmsg());
1268 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1269 opts->default_msg_cleanup;
1271 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1272 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1273 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1274 res = 1; /* run 'git commit' to display error message */
1278 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1279 oid, author, opts->gpg_sign, extra)) {
1280 res = error(_("failed to write commit object"));
1284 if (update_head_with_reflog(current_head, oid,
1285 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1286 res = error("%s", err.buf);
1290 if (flags & AMEND_MSG)
1291 commit_post_rewrite(current_head, oid);
1294 free_commit_extra_headers(extra);
1295 strbuf_release(&err);
1296 strbuf_release(&commit_msg);
1302 static int do_commit(const char *msg_file, const char *author,
1303 struct replay_opts *opts, unsigned int flags)
1307 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1308 !(flags & CREATE_ROOT_COMMIT)) {
1309 struct object_id oid;
1310 struct strbuf sb = STRBUF_INIT;
1312 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1313 return error_errno(_("unable to read commit message "
1317 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1319 strbuf_release(&sb);
1321 unlink(git_path_cherry_pick_head());
1322 unlink(git_path_merge_msg());
1323 if (!is_rebase_i(opts))
1324 print_commit_summary(NULL, &oid,
1325 SUMMARY_SHOW_AUTHOR_DATE);
1330 return run_git_commit(msg_file, opts, flags);
1335 static int is_original_commit_empty(struct commit *commit)
1337 const struct object_id *ptree_oid;
1339 if (parse_commit(commit))
1340 return error(_("could not parse commit %s"),
1341 oid_to_hex(&commit->object.oid));
1342 if (commit->parents) {
1343 struct commit *parent = commit->parents->item;
1344 if (parse_commit(parent))
1345 return error(_("could not parse parent commit %s"),
1346 oid_to_hex(&parent->object.oid));
1347 ptree_oid = &parent->tree->object.oid;
1349 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1352 return !oidcmp(ptree_oid, &commit->tree->object.oid);
1356 * Do we run "git commit" with "--allow-empty"?
1358 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1360 int index_unchanged, empty_commit;
1365 * (1) we do not allow empty at all and error out.
1367 * (2) we allow ones that were initially empty, but
1368 * forbid the ones that become empty;
1370 * (3) we allow both.
1372 if (!opts->allow_empty)
1373 return 0; /* let "git commit" barf as necessary */
1375 index_unchanged = is_index_unchanged();
1376 if (index_unchanged < 0)
1377 return index_unchanged;
1378 if (!index_unchanged)
1379 return 0; /* we do not have to say --allow-empty */
1381 if (opts->keep_redundant_commits)
1384 empty_commit = is_original_commit_empty(commit);
1385 if (empty_commit < 0)
1386 return empty_commit;
1394 * Note that ordering matters in this enum. Not only must it match the mapping
1395 * below, it is also divided into several sections that matter. When adding
1396 * new commands, make sure you add it in the right section.
1399 /* commands that handle commits */
1406 /* commands that do something else than handling a single commit */
1411 /* commands that do nothing but are counted for reporting progress */
1414 /* comments (not counted for reporting progress) */
1421 } todo_command_info[] = {
1437 static const char *command_to_string(const enum todo_command command)
1439 if (command < TODO_COMMENT)
1440 return todo_command_info[command].str;
1441 die("Unknown command: %d", command);
1444 static char command_to_char(const enum todo_command command)
1446 if (command < TODO_COMMENT && todo_command_info[command].c)
1447 return todo_command_info[command].c;
1448 return comment_line_char;
1451 static int is_noop(const enum todo_command command)
1453 return TODO_NOOP <= command;
1456 static int is_fixup(enum todo_command command)
1458 return command == TODO_FIXUP || command == TODO_SQUASH;
1461 /* Does this command create a (non-merge) commit? */
1462 static int is_pick_or_similar(enum todo_command command)
1477 static int update_squash_messages(enum todo_command command,
1478 struct commit *commit, struct replay_opts *opts)
1480 struct strbuf buf = STRBUF_INIT;
1482 const char *message, *body;
1484 if (file_exists(rebase_path_squash_msg())) {
1485 struct strbuf header = STRBUF_INIT;
1488 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1489 return error(_("could not read '%s'"),
1490 rebase_path_squash_msg());
1493 eol = strchrnul(buf.buf, '\n');
1494 if (buf.buf[0] != comment_line_char ||
1495 (p += strcspn(p, "0123456789\n")) == eol)
1496 return error(_("unexpected 1st line of squash message:"
1498 (int)(eol - buf.buf), buf.buf);
1499 count = strtol(p, NULL, 10);
1502 return error(_("invalid 1st line of squash message:\n"
1504 (int)(eol - buf.buf), buf.buf);
1506 strbuf_addf(&header, "%c ", comment_line_char);
1507 strbuf_addf(&header,
1508 _("This is a combination of %d commits."), ++count);
1509 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1510 strbuf_release(&header);
1512 struct object_id head;
1513 struct commit *head_commit;
1514 const char *head_message, *body;
1516 if (get_oid("HEAD", &head))
1517 return error(_("need a HEAD to fixup"));
1518 if (!(head_commit = lookup_commit_reference(&head)))
1519 return error(_("could not read HEAD"));
1520 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1521 return error(_("could not read HEAD's commit message"));
1523 find_commit_subject(head_message, &body);
1524 if (write_message(body, strlen(body),
1525 rebase_path_fixup_msg(), 0)) {
1526 unuse_commit_buffer(head_commit, head_message);
1527 return error(_("cannot write '%s'"),
1528 rebase_path_fixup_msg());
1532 strbuf_addf(&buf, "%c ", comment_line_char);
1533 strbuf_addf(&buf, _("This is a combination of %d commits."),
1535 strbuf_addf(&buf, "\n%c ", comment_line_char);
1536 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1537 strbuf_addstr(&buf, "\n\n");
1538 strbuf_addstr(&buf, body);
1540 unuse_commit_buffer(head_commit, head_message);
1543 if (!(message = get_commit_buffer(commit, NULL)))
1544 return error(_("could not read commit message of %s"),
1545 oid_to_hex(&commit->object.oid));
1546 find_commit_subject(message, &body);
1548 if (command == TODO_SQUASH) {
1549 unlink(rebase_path_fixup_msg());
1550 strbuf_addf(&buf, "\n%c ", comment_line_char);
1551 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1552 strbuf_addstr(&buf, "\n\n");
1553 strbuf_addstr(&buf, body);
1554 } else if (command == TODO_FIXUP) {
1555 strbuf_addf(&buf, "\n%c ", comment_line_char);
1556 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1558 strbuf_addstr(&buf, "\n\n");
1559 strbuf_add_commented_lines(&buf, body, strlen(body));
1561 return error(_("unknown command: %d"), command);
1562 unuse_commit_buffer(commit, message);
1564 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1565 strbuf_release(&buf);
1569 static void flush_rewritten_pending(void) {
1570 struct strbuf buf = STRBUF_INIT;
1571 struct object_id newoid;
1574 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1575 !get_oid("HEAD", &newoid) &&
1576 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1577 char *bol = buf.buf, *eol;
1580 eol = strchrnul(bol, '\n');
1581 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1582 bol, oid_to_hex(&newoid));
1588 unlink(rebase_path_rewritten_pending());
1590 strbuf_release(&buf);
1593 static void record_in_rewritten(struct object_id *oid,
1594 enum todo_command next_command) {
1595 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1600 fprintf(out, "%s\n", oid_to_hex(oid));
1603 if (!is_fixup(next_command))
1604 flush_rewritten_pending();
1607 static int do_pick_commit(enum todo_command command, struct commit *commit,
1608 struct replay_opts *opts, int final_fixup)
1610 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1611 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1612 struct object_id head;
1613 struct commit *base, *next, *parent;
1614 const char *base_label, *next_label;
1615 char *author = NULL;
1616 struct commit_message msg = { NULL, NULL, NULL, NULL };
1617 struct strbuf msgbuf = STRBUF_INIT;
1618 int res, unborn = 0, allow;
1620 if (opts->no_commit) {
1622 * We do not intend to commit immediately. We just want to
1623 * merge the differences in, so let's compute the tree
1624 * that represents the "current" state for merge-recursive
1627 if (write_cache_as_tree(&head, 0, NULL))
1628 return error(_("your index file is unmerged."));
1630 unborn = get_oid("HEAD", &head);
1631 /* Do we want to generate a root commit? */
1632 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1633 !oidcmp(&head, &opts->squash_onto)) {
1634 if (is_fixup(command))
1635 return error(_("cannot fixup root commit"));
1636 flags |= CREATE_ROOT_COMMIT;
1639 oidcpy(&head, the_hash_algo->empty_tree);
1640 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1642 return error_dirty_index(opts);
1646 if (!commit->parents)
1648 else if (commit->parents->next) {
1649 /* Reverting or cherry-picking a merge commit */
1651 struct commit_list *p;
1653 if (!opts->mainline)
1654 return error(_("commit %s is a merge but no -m option was given."),
1655 oid_to_hex(&commit->object.oid));
1657 for (cnt = 1, p = commit->parents;
1658 cnt != opts->mainline && p;
1661 if (cnt != opts->mainline || !p)
1662 return error(_("commit %s does not have parent %d"),
1663 oid_to_hex(&commit->object.oid), opts->mainline);
1665 } else if (0 < opts->mainline)
1666 return error(_("mainline was specified but commit %s is not a merge."),
1667 oid_to_hex(&commit->object.oid));
1669 parent = commit->parents->item;
1671 if (get_message(commit, &msg) != 0)
1672 return error(_("cannot get commit message for %s"),
1673 oid_to_hex(&commit->object.oid));
1675 if (opts->allow_ff && !is_fixup(command) &&
1676 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1677 (!parent && unborn))) {
1678 if (is_rebase_i(opts))
1679 write_author_script(msg.message);
1680 res = fast_forward_to(&commit->object.oid, &head, unborn,
1682 if (res || command != TODO_REWORD)
1684 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1686 goto fast_forward_edit;
1688 if (parent && parse_commit(parent) < 0)
1689 /* TRANSLATORS: The first %s will be a "todo" command like
1690 "revert" or "pick", the second %s a SHA1. */
1691 return error(_("%s: cannot parse parent commit %s"),
1692 command_to_string(command),
1693 oid_to_hex(&parent->object.oid));
1696 * "commit" is an existing commit. We would want to apply
1697 * the difference it introduces since its first parent "prev"
1698 * on top of the current HEAD if we are cherry-pick. Or the
1699 * reverse of it if we are revert.
1702 if (command == TODO_REVERT) {
1704 base_label = msg.label;
1706 next_label = msg.parent_label;
1707 strbuf_addstr(&msgbuf, "Revert \"");
1708 strbuf_addstr(&msgbuf, msg.subject);
1709 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1710 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1712 if (commit->parents && commit->parents->next) {
1713 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1714 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1716 strbuf_addstr(&msgbuf, ".\n");
1721 base_label = msg.parent_label;
1723 next_label = msg.label;
1725 /* Append the commit log message to msgbuf. */
1726 if (find_commit_subject(msg.message, &p))
1727 strbuf_addstr(&msgbuf, p);
1729 if (opts->record_origin) {
1730 strbuf_complete_line(&msgbuf);
1731 if (!has_conforming_footer(&msgbuf, NULL, 0))
1732 strbuf_addch(&msgbuf, '\n');
1733 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1734 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1735 strbuf_addstr(&msgbuf, ")\n");
1737 if (!is_fixup(command))
1738 author = get_author(msg.message);
1741 if (command == TODO_REWORD)
1742 flags |= EDIT_MSG | VERIFY_MSG;
1743 else if (is_fixup(command)) {
1744 if (update_squash_messages(command, commit, opts))
1748 msg_file = rebase_path_squash_msg();
1749 else if (file_exists(rebase_path_fixup_msg())) {
1750 flags |= CLEANUP_MSG;
1751 msg_file = rebase_path_fixup_msg();
1753 const char *dest = git_path_squash_msg();
1755 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1756 return error(_("could not rename '%s' to '%s'"),
1757 rebase_path_squash_msg(), dest);
1758 unlink(git_path_merge_msg());
1764 if (opts->signoff && !is_fixup(command))
1765 append_signoff(&msgbuf, 0, 0);
1767 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1769 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1770 res = do_recursive_merge(base, next, base_label, next_label,
1771 &head, &msgbuf, opts);
1774 res |= write_message(msgbuf.buf, msgbuf.len,
1775 git_path_merge_msg(), 0);
1777 struct commit_list *common = NULL;
1778 struct commit_list *remotes = NULL;
1780 res = write_message(msgbuf.buf, msgbuf.len,
1781 git_path_merge_msg(), 0);
1783 commit_list_insert(base, &common);
1784 commit_list_insert(next, &remotes);
1785 res |= try_merge_command(opts->strategy,
1786 opts->xopts_nr, (const char **)opts->xopts,
1787 common, oid_to_hex(&head), remotes);
1788 free_commit_list(common);
1789 free_commit_list(remotes);
1791 strbuf_release(&msgbuf);
1794 * If the merge was clean or if it failed due to conflict, we write
1795 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1796 * However, if the merge did not even start, then we don't want to
1799 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1800 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1801 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1803 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1804 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1805 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1809 error(command == TODO_REVERT
1810 ? _("could not revert %s... %s")
1811 : _("could not apply %s... %s"),
1812 short_commit_name(commit), msg.subject);
1813 print_advice(res == 1, opts);
1814 rerere(opts->allow_rerere_auto);
1818 allow = allow_empty(opts, commit);
1823 flags |= ALLOW_EMPTY;
1824 if (!opts->no_commit) {
1826 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1827 res = do_commit(msg_file, author, opts, flags);
1829 res = error(_("unable to parse commit author"));
1832 if (!res && final_fixup) {
1833 unlink(rebase_path_fixup_msg());
1834 unlink(rebase_path_squash_msg());
1838 free_message(commit, &msg);
1840 update_abort_safety_file();
1845 static int prepare_revs(struct replay_opts *opts)
1848 * picking (but not reverting) ranges (but not individual revisions)
1849 * should be done in reverse
1851 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1852 opts->revs->reverse ^= 1;
1854 if (prepare_revision_walk(opts->revs))
1855 return error(_("revision walk setup failed"));
1857 if (!opts->revs->commits)
1858 return error(_("empty commit set passed"));
1862 static int read_and_refresh_cache(struct replay_opts *opts)
1864 struct lock_file index_lock = LOCK_INIT;
1865 int index_fd = hold_locked_index(&index_lock, 0);
1866 if (read_index_preload(&the_index, NULL) < 0) {
1867 rollback_lock_file(&index_lock);
1868 return error(_("git %s: failed to read the index"),
1869 _(action_name(opts)));
1871 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1872 if (index_fd >= 0) {
1873 if (write_locked_index(&the_index, &index_lock,
1874 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1875 return error(_("git %s: failed to refresh the index"),
1876 _(action_name(opts)));
1882 enum todo_item_flags {
1883 TODO_EDIT_MERGE_MSG = 1
1887 enum todo_command command;
1888 struct commit *commit;
1892 size_t offset_in_buf;
1897 struct todo_item *items;
1898 int nr, alloc, current;
1899 int done_nr, total_nr;
1900 struct stat_data stat;
1903 #define TODO_LIST_INIT { STRBUF_INIT }
1905 static void todo_list_release(struct todo_list *todo_list)
1907 strbuf_release(&todo_list->buf);
1908 FREE_AND_NULL(todo_list->items);
1909 todo_list->nr = todo_list->alloc = 0;
1912 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1914 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1915 return todo_list->items + todo_list->nr++;
1918 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1920 struct object_id commit_oid;
1921 char *end_of_object_name;
1922 int i, saved, status, padding;
1927 bol += strspn(bol, " \t");
1929 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1930 item->command = TODO_COMMENT;
1931 item->commit = NULL;
1933 item->arg_len = eol - bol;
1937 for (i = 0; i < TODO_COMMENT; i++)
1938 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1941 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1946 if (i >= TODO_COMMENT)
1949 /* Eat up extra spaces/ tabs before object name */
1950 padding = strspn(bol, " \t");
1953 if (item->command == TODO_NOOP) {
1955 return error(_("%s does not accept arguments: '%s'"),
1956 command_to_string(item->command), bol);
1957 item->commit = NULL;
1959 item->arg_len = eol - bol;
1964 return error(_("missing arguments for %s"),
1965 command_to_string(item->command));
1967 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1968 item->command == TODO_RESET) {
1969 item->commit = NULL;
1971 item->arg_len = (int)(eol - bol);
1975 if (item->command == TODO_MERGE) {
1976 if (skip_prefix(bol, "-C", &bol))
1977 bol += strspn(bol, " \t");
1978 else if (skip_prefix(bol, "-c", &bol)) {
1979 bol += strspn(bol, " \t");
1980 item->flags |= TODO_EDIT_MERGE_MSG;
1982 item->flags |= TODO_EDIT_MERGE_MSG;
1983 item->commit = NULL;
1985 item->arg_len = (int)(eol - bol);
1990 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1991 saved = *end_of_object_name;
1992 *end_of_object_name = '\0';
1993 status = get_oid(bol, &commit_oid);
1994 *end_of_object_name = saved;
1996 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1997 item->arg_len = (int)(eol - item->arg);
2002 item->commit = lookup_commit_reference(&commit_oid);
2003 return !item->commit;
2006 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
2008 struct todo_item *item;
2009 char *p = buf, *next_p;
2010 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2012 for (i = 1; *p; i++, p = next_p) {
2013 char *eol = strchrnul(p, '\n');
2015 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2017 if (p != eol && eol[-1] == '\r')
2018 eol--; /* strip Carriage Return */
2020 item = append_new_todo(todo_list);
2021 item->offset_in_buf = p - todo_list->buf.buf;
2022 if (parse_insn_line(item, p, eol)) {
2023 res = error(_("invalid line %d: %.*s"),
2024 i, (int)(eol - p), p);
2025 item->command = TODO_NOOP;
2030 else if (is_fixup(item->command))
2031 return error(_("cannot '%s' without a previous commit"),
2032 command_to_string(item->command));
2033 else if (!is_noop(item->command))
2040 static int count_commands(struct todo_list *todo_list)
2044 for (i = 0; i < todo_list->nr; i++)
2045 if (todo_list->items[i].command != TODO_COMMENT)
2051 static int get_item_line_offset(struct todo_list *todo_list, int index)
2053 return index < todo_list->nr ?
2054 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2057 static const char *get_item_line(struct todo_list *todo_list, int index)
2059 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2062 static int get_item_line_length(struct todo_list *todo_list, int index)
2064 return get_item_line_offset(todo_list, index + 1)
2065 - get_item_line_offset(todo_list, index);
2068 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2073 fd = open(path, O_RDONLY);
2075 return error_errno(_("could not open '%s'"), path);
2076 len = strbuf_read(sb, fd, 0);
2079 return error(_("could not read '%s'."), path);
2083 static int read_populate_todo(struct todo_list *todo_list,
2084 struct replay_opts *opts)
2087 const char *todo_file = get_todo_path(opts);
2090 strbuf_reset(&todo_list->buf);
2091 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2094 res = stat(todo_file, &st);
2096 return error(_("could not stat '%s'"), todo_file);
2097 fill_stat_data(&todo_list->stat, &st);
2099 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2101 if (is_rebase_i(opts))
2102 return error(_("please fix this using "
2103 "'git rebase --edit-todo'."));
2104 return error(_("unusable instruction sheet: '%s'"), todo_file);
2107 if (!todo_list->nr &&
2108 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2109 return error(_("no commits parsed."));
2111 if (!is_rebase_i(opts)) {
2112 enum todo_command valid =
2113 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2116 for (i = 0; i < todo_list->nr; i++)
2117 if (valid == todo_list->items[i].command)
2119 else if (valid == TODO_PICK)
2120 return error(_("cannot cherry-pick during a revert."));
2122 return error(_("cannot revert during a cherry-pick."));
2125 if (is_rebase_i(opts)) {
2126 struct todo_list done = TODO_LIST_INIT;
2127 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2129 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2130 !parse_insn_buffer(done.buf.buf, &done))
2131 todo_list->done_nr = count_commands(&done);
2133 todo_list->done_nr = 0;
2135 todo_list->total_nr = todo_list->done_nr
2136 + count_commands(todo_list);
2137 todo_list_release(&done);
2140 fprintf(f, "%d\n", todo_list->total_nr);
2148 static int git_config_string_dup(char **dest,
2149 const char *var, const char *value)
2152 return config_error_nonbool(var);
2154 *dest = xstrdup(value);
2158 static int populate_opts_cb(const char *key, const char *value, void *data)
2160 struct replay_opts *opts = data;
2165 else if (!strcmp(key, "options.no-commit"))
2166 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2167 else if (!strcmp(key, "options.edit"))
2168 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2169 else if (!strcmp(key, "options.signoff"))
2170 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2171 else if (!strcmp(key, "options.record-origin"))
2172 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2173 else if (!strcmp(key, "options.allow-ff"))
2174 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2175 else if (!strcmp(key, "options.mainline"))
2176 opts->mainline = git_config_int(key, value);
2177 else if (!strcmp(key, "options.strategy"))
2178 git_config_string_dup(&opts->strategy, key, value);
2179 else if (!strcmp(key, "options.gpg-sign"))
2180 git_config_string_dup(&opts->gpg_sign, key, value);
2181 else if (!strcmp(key, "options.strategy-option")) {
2182 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2183 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2184 } else if (!strcmp(key, "options.allow-rerere-auto"))
2185 opts->allow_rerere_auto =
2186 git_config_bool_or_int(key, value, &error_flag) ?
2187 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2189 return error(_("invalid key: %s"), key);
2192 return error(_("invalid value for %s: %s"), key, value);
2197 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2202 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2204 opts->strategy = strbuf_detach(buf, NULL);
2205 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2208 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2209 for (i = 0; i < opts->xopts_nr; i++) {
2210 const char *arg = opts->xopts[i];
2212 skip_prefix(arg, "--", &arg);
2213 opts->xopts[i] = xstrdup(arg);
2217 static int read_populate_opts(struct replay_opts *opts)
2219 if (is_rebase_i(opts)) {
2220 struct strbuf buf = STRBUF_INIT;
2222 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2223 if (!starts_with(buf.buf, "-S"))
2226 free(opts->gpg_sign);
2227 opts->gpg_sign = xstrdup(buf.buf + 2);
2232 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2233 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2234 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2235 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2236 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2240 if (file_exists(rebase_path_verbose()))
2243 if (file_exists(rebase_path_signoff())) {
2248 read_strategy_opts(opts, &buf);
2249 strbuf_release(&buf);
2251 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2252 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2253 return error(_("unusable squash-onto"));
2254 opts->have_squash_onto = 1;
2260 if (!file_exists(git_path_opts_file()))
2263 * The function git_parse_source(), called from git_config_from_file(),
2264 * may die() in case of a syntactically incorrect file. We do not care
2265 * about this case, though, because we wrote that file ourselves, so we
2266 * are pretty certain that it is syntactically correct.
2268 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2269 return error(_("malformed options sheet: '%s'"),
2270 git_path_opts_file());
2274 static int walk_revs_populate_todo(struct todo_list *todo_list,
2275 struct replay_opts *opts)
2277 enum todo_command command = opts->action == REPLAY_PICK ?
2278 TODO_PICK : TODO_REVERT;
2279 const char *command_string = todo_command_info[command].str;
2280 struct commit *commit;
2282 if (prepare_revs(opts))
2285 while ((commit = get_revision(opts->revs))) {
2286 struct todo_item *item = append_new_todo(todo_list);
2287 const char *commit_buffer = get_commit_buffer(commit, NULL);
2288 const char *subject;
2291 item->command = command;
2292 item->commit = commit;
2295 item->offset_in_buf = todo_list->buf.len;
2296 subject_len = find_commit_subject(commit_buffer, &subject);
2297 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2298 short_commit_name(commit), subject_len, subject);
2299 unuse_commit_buffer(commit, commit_buffer);
2304 static int create_seq_dir(void)
2306 if (file_exists(git_path_seq_dir())) {
2307 error(_("a cherry-pick or revert is already in progress"));
2308 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2310 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2311 return error_errno(_("could not create sequencer directory '%s'"),
2312 git_path_seq_dir());
2316 static int save_head(const char *head)
2318 struct lock_file head_lock = LOCK_INIT;
2319 struct strbuf buf = STRBUF_INIT;
2323 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2325 return error_errno(_("could not lock HEAD"));
2326 strbuf_addf(&buf, "%s\n", head);
2327 written = write_in_full(fd, buf.buf, buf.len);
2328 strbuf_release(&buf);
2330 error_errno(_("could not write to '%s'"), git_path_head_file());
2331 rollback_lock_file(&head_lock);
2334 if (commit_lock_file(&head_lock) < 0)
2335 return error(_("failed to finalize '%s'"), git_path_head_file());
2339 static int rollback_is_safe(void)
2341 struct strbuf sb = STRBUF_INIT;
2342 struct object_id expected_head, actual_head;
2344 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2346 if (get_oid_hex(sb.buf, &expected_head)) {
2347 strbuf_release(&sb);
2348 die(_("could not parse %s"), git_path_abort_safety_file());
2350 strbuf_release(&sb);
2352 else if (errno == ENOENT)
2353 oidclr(&expected_head);
2355 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2357 if (get_oid("HEAD", &actual_head))
2358 oidclr(&actual_head);
2360 return !oidcmp(&actual_head, &expected_head);
2363 static int reset_for_rollback(const struct object_id *oid)
2365 const char *argv[4]; /* reset --merge <arg> + NULL */
2368 argv[1] = "--merge";
2369 argv[2] = oid_to_hex(oid);
2371 return run_command_v_opt(argv, RUN_GIT_CMD);
2374 static int rollback_single_pick(void)
2376 struct object_id head_oid;
2378 if (!file_exists(git_path_cherry_pick_head()) &&
2379 !file_exists(git_path_revert_head()))
2380 return error(_("no cherry-pick or revert in progress"));
2381 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2382 return error(_("cannot resolve HEAD"));
2383 if (is_null_oid(&head_oid))
2384 return error(_("cannot abort from a branch yet to be born"));
2385 return reset_for_rollback(&head_oid);
2388 int sequencer_rollback(struct replay_opts *opts)
2391 struct object_id oid;
2392 struct strbuf buf = STRBUF_INIT;
2395 f = fopen(git_path_head_file(), "r");
2396 if (!f && errno == ENOENT) {
2398 * There is no multiple-cherry-pick in progress.
2399 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2400 * a single-cherry-pick in progress, abort that.
2402 return rollback_single_pick();
2405 return error_errno(_("cannot open '%s'"), git_path_head_file());
2406 if (strbuf_getline_lf(&buf, f)) {
2407 error(_("cannot read '%s': %s"), git_path_head_file(),
2408 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2413 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2414 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2415 git_path_head_file());
2418 if (is_null_oid(&oid)) {
2419 error(_("cannot abort from a branch yet to be born"));
2423 if (!rollback_is_safe()) {
2424 /* Do not error, just do not rollback */
2425 warning(_("You seem to have moved HEAD. "
2426 "Not rewinding, check your HEAD!"));
2428 if (reset_for_rollback(&oid))
2430 strbuf_release(&buf);
2431 return sequencer_remove_state(opts);
2433 strbuf_release(&buf);
2437 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2439 struct lock_file todo_lock = LOCK_INIT;
2440 const char *todo_path = get_todo_path(opts);
2441 int next = todo_list->current, offset, fd;
2444 * rebase -i writes "git-rebase-todo" without the currently executing
2445 * command, appending it to "done" instead.
2447 if (is_rebase_i(opts))
2450 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2452 return error_errno(_("could not lock '%s'"), todo_path);
2453 offset = get_item_line_offset(todo_list, next);
2454 if (write_in_full(fd, todo_list->buf.buf + offset,
2455 todo_list->buf.len - offset) < 0)
2456 return error_errno(_("could not write to '%s'"), todo_path);
2457 if (commit_lock_file(&todo_lock) < 0)
2458 return error(_("failed to finalize '%s'"), todo_path);
2460 if (is_rebase_i(opts) && next > 0) {
2461 const char *done = rebase_path_done();
2462 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2467 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2468 get_item_line_length(todo_list, next - 1))
2470 ret = error_errno(_("could not write to '%s'"), done);
2472 ret = error_errno(_("failed to finalize '%s'"), done);
2478 static int save_opts(struct replay_opts *opts)
2480 const char *opts_file = git_path_opts_file();
2483 if (opts->no_commit)
2484 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2486 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2488 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2489 if (opts->record_origin)
2490 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2492 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2493 if (opts->mainline) {
2494 struct strbuf buf = STRBUF_INIT;
2495 strbuf_addf(&buf, "%d", opts->mainline);
2496 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2497 strbuf_release(&buf);
2500 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2502 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2505 for (i = 0; i < opts->xopts_nr; i++)
2506 res |= git_config_set_multivar_in_file_gently(opts_file,
2507 "options.strategy-option",
2508 opts->xopts[i], "^$", 0);
2510 if (opts->allow_rerere_auto)
2511 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2512 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2517 static int make_patch(struct commit *commit, struct replay_opts *opts)
2519 struct strbuf buf = STRBUF_INIT;
2520 struct rev_info log_tree_opt;
2521 const char *subject, *p;
2524 p = short_commit_name(commit);
2525 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2527 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2528 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2529 res |= error(_("could not update %s"), "REBASE_HEAD");
2531 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2532 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2533 init_revisions(&log_tree_opt, NULL);
2534 log_tree_opt.abbrev = 0;
2535 log_tree_opt.diff = 1;
2536 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2537 log_tree_opt.disable_stdin = 1;
2538 log_tree_opt.no_commit_id = 1;
2539 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2540 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2541 if (!log_tree_opt.diffopt.file)
2542 res |= error_errno(_("could not open '%s'"), buf.buf);
2544 res |= log_tree_commit(&log_tree_opt, commit);
2545 fclose(log_tree_opt.diffopt.file);
2549 strbuf_addf(&buf, "%s/message", get_dir(opts));
2550 if (!file_exists(buf.buf)) {
2551 const char *commit_buffer = get_commit_buffer(commit, NULL);
2552 find_commit_subject(commit_buffer, &subject);
2553 res |= write_message(subject, strlen(subject), buf.buf, 1);
2554 unuse_commit_buffer(commit, commit_buffer);
2556 strbuf_release(&buf);
2561 static int intend_to_amend(void)
2563 struct object_id head;
2566 if (get_oid("HEAD", &head))
2567 return error(_("cannot read HEAD"));
2569 p = oid_to_hex(&head);
2570 return write_message(p, strlen(p), rebase_path_amend(), 1);
2573 static int error_with_patch(struct commit *commit,
2574 const char *subject, int subject_len,
2575 struct replay_opts *opts, int exit_code, int to_amend)
2577 if (make_patch(commit, opts))
2581 if (intend_to_amend())
2584 fprintf(stderr, "You can amend the commit now, with\n"
2586 " git commit --amend %s\n"
2588 "Once you are satisfied with your changes, run\n"
2590 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2591 } else if (exit_code)
2592 fprintf(stderr, "Could not apply %s... %.*s\n",
2593 short_commit_name(commit), subject_len, subject);
2598 static int error_failed_squash(struct commit *commit,
2599 struct replay_opts *opts, int subject_len, const char *subject)
2601 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2602 return error(_("could not rename '%s' to '%s'"),
2603 rebase_path_squash_msg(), rebase_path_message());
2604 unlink(rebase_path_fixup_msg());
2605 unlink(git_path_merge_msg());
2606 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2607 return error(_("could not copy '%s' to '%s'"),
2608 rebase_path_message(), git_path_merge_msg());
2609 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2612 static int do_exec(const char *command_line)
2614 struct argv_array child_env = ARGV_ARRAY_INIT;
2615 const char *child_argv[] = { NULL, NULL };
2618 fprintf(stderr, "Executing: %s\n", command_line);
2619 child_argv[0] = command_line;
2620 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2621 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2624 /* force re-reading of the cache */
2625 if (discard_cache() < 0 || read_cache() < 0)
2626 return error(_("could not read index"));
2628 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2631 warning(_("execution failed: %s\n%s"
2632 "You can fix the problem, and then run\n"
2634 " git rebase --continue\n"
2637 dirty ? N_("and made changes to the index and/or the "
2638 "working tree\n") : "");
2640 /* command not found */
2643 warning(_("execution succeeded: %s\nbut "
2644 "left changes to the index and/or the working tree\n"
2645 "Commit or stash your changes, and then run\n"
2647 " git rebase --continue\n"
2648 "\n"), command_line);
2652 argv_array_clear(&child_env);
2657 static int safe_append(const char *filename, const char *fmt, ...)
2660 struct lock_file lock = LOCK_INIT;
2661 int fd = hold_lock_file_for_update(&lock, filename,
2662 LOCK_REPORT_ON_ERROR);
2663 struct strbuf buf = STRBUF_INIT;
2668 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2669 error_errno(_("could not read '%s'"), filename);
2670 rollback_lock_file(&lock);
2673 strbuf_complete(&buf, '\n');
2675 strbuf_vaddf(&buf, fmt, ap);
2678 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2679 error_errno(_("could not write to '%s'"), filename);
2680 strbuf_release(&buf);
2681 rollback_lock_file(&lock);
2684 if (commit_lock_file(&lock) < 0) {
2685 strbuf_release(&buf);
2686 rollback_lock_file(&lock);
2687 return error(_("failed to finalize '%s'"), filename);
2690 strbuf_release(&buf);
2694 static int do_label(const char *name, int len)
2696 struct ref_store *refs = get_main_ref_store();
2697 struct ref_transaction *transaction;
2698 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2699 struct strbuf msg = STRBUF_INIT;
2701 struct object_id head_oid;
2703 if (len == 1 && *name == '#')
2704 return error("Illegal label name: '%.*s'", len, name);
2706 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2707 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2709 transaction = ref_store_transaction_begin(refs, &err);
2711 error("%s", err.buf);
2713 } else if (get_oid("HEAD", &head_oid)) {
2714 error(_("could not read HEAD"));
2716 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2717 NULL, 0, msg.buf, &err) < 0 ||
2718 ref_transaction_commit(transaction, &err)) {
2719 error("%s", err.buf);
2722 ref_transaction_free(transaction);
2723 strbuf_release(&err);
2724 strbuf_release(&msg);
2727 ret = safe_append(rebase_path_refs_to_delete(),
2728 "%s\n", ref_name.buf);
2729 strbuf_release(&ref_name);
2734 static const char *reflog_message(struct replay_opts *opts,
2735 const char *sub_action, const char *fmt, ...);
2737 static int do_reset(const char *name, int len, struct replay_opts *opts)
2739 struct strbuf ref_name = STRBUF_INIT;
2740 struct object_id oid;
2741 struct lock_file lock = LOCK_INIT;
2742 struct tree_desc desc;
2744 struct unpack_trees_options unpack_tree_opts;
2747 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2750 if (len == 10 && !strncmp("[new root]", name, len)) {
2751 if (!opts->have_squash_onto) {
2753 if (commit_tree("", 0, the_hash_algo->empty_tree,
2754 NULL, &opts->squash_onto,
2756 return error(_("writing fake root commit"));
2757 opts->have_squash_onto = 1;
2758 hex = oid_to_hex(&opts->squash_onto);
2759 if (write_message(hex, strlen(hex),
2760 rebase_path_squash_onto(), 0))
2761 return error(_("writing squash-onto"));
2763 oidcpy(&oid, &opts->squash_onto);
2765 /* Determine the length of the label */
2766 for (i = 0; i < len; i++)
2767 if (isspace(name[i]))
2770 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2771 if (get_oid(ref_name.buf, &oid) &&
2772 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2773 error(_("could not read '%s'"), ref_name.buf);
2774 rollback_lock_file(&lock);
2775 strbuf_release(&ref_name);
2780 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2781 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2782 unpack_tree_opts.head_idx = 1;
2783 unpack_tree_opts.src_index = &the_index;
2784 unpack_tree_opts.dst_index = &the_index;
2785 unpack_tree_opts.fn = oneway_merge;
2786 unpack_tree_opts.merge = 1;
2787 unpack_tree_opts.update = 1;
2789 if (read_cache_unmerged()) {
2790 rollback_lock_file(&lock);
2791 strbuf_release(&ref_name);
2792 return error_resolve_conflict(_(action_name(opts)));
2795 if (!fill_tree_descriptor(&desc, &oid)) {
2796 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2797 rollback_lock_file(&lock);
2798 free((void *)desc.buffer);
2799 strbuf_release(&ref_name);
2803 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2804 rollback_lock_file(&lock);
2805 free((void *)desc.buffer);
2806 strbuf_release(&ref_name);
2810 tree = parse_tree_indirect(&oid);
2811 prime_cache_tree(&the_index, tree);
2813 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2814 ret = error(_("could not write index"));
2815 free((void *)desc.buffer);
2818 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2819 len, name), "HEAD", &oid,
2820 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2822 strbuf_release(&ref_name);
2826 static int do_merge(struct commit *commit, const char *arg, int arg_len,
2827 int flags, struct replay_opts *opts)
2829 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2830 EDIT_MSG | VERIFY_MSG : 0;
2831 struct strbuf ref_name = STRBUF_INIT;
2832 struct commit *head_commit, *merge_commit, *i;
2833 struct commit_list *bases, *j, *reversed = NULL;
2834 struct merge_options o;
2835 int merge_arg_len, oneline_offset, can_fast_forward, ret;
2836 static struct lock_file lock;
2839 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2844 head_commit = lookup_commit_reference_by_name("HEAD");
2846 ret = error(_("cannot merge without a current revision"));
2850 oneline_offset = arg_len;
2851 merge_arg_len = strcspn(arg, " \t\n");
2852 p = arg + merge_arg_len;
2853 p += strspn(p, " \t\n");
2854 if (*p == '#' && (!p[1] || isspace(p[1]))) {
2855 p += 1 + strspn(p + 1, " \t\n");
2856 oneline_offset = p - arg;
2857 } else if (p - arg < arg_len)
2858 BUG("octopus merges are not supported yet: '%s'", p);
2860 strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg);
2861 merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2862 if (!merge_commit) {
2863 /* fall back to non-rewritten ref or commit */
2864 strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0);
2865 merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2868 if (!merge_commit) {
2869 ret = error(_("could not resolve '%s'"), ref_name.buf);
2874 const char *message = get_commit_buffer(commit, NULL);
2879 ret = error(_("could not get commit message of '%s'"),
2880 oid_to_hex(&commit->object.oid));
2883 write_author_script(message);
2884 find_commit_subject(message, &body);
2886 ret = write_message(body, len, git_path_merge_msg(), 0);
2887 unuse_commit_buffer(commit, message);
2889 error_errno(_("could not write '%s'"),
2890 git_path_merge_msg());
2894 struct strbuf buf = STRBUF_INIT;
2897 strbuf_addf(&buf, "author %s", git_author_info(0));
2898 write_author_script(buf.buf);
2901 if (oneline_offset < arg_len) {
2902 p = arg + oneline_offset;
2903 len = arg_len - oneline_offset;
2905 strbuf_addf(&buf, "Merge branch '%.*s'",
2906 merge_arg_len, arg);
2911 ret = write_message(p, len, git_path_merge_msg(), 0);
2912 strbuf_release(&buf);
2914 error_errno(_("could not write '%s'"),
2915 git_path_merge_msg());
2921 * If HEAD is not identical to the first parent of the original merge
2922 * commit, we cannot fast-forward.
2924 can_fast_forward = opts->allow_ff && commit && commit->parents &&
2925 !oidcmp(&commit->parents->item->object.oid,
2926 &head_commit->object.oid);
2929 * If the merge head is different from the original one, we cannot
2932 if (can_fast_forward) {
2933 struct commit_list *second_parent = commit->parents->next;
2935 if (second_parent && !second_parent->next &&
2936 oidcmp(&merge_commit->object.oid,
2937 &second_parent->item->object.oid))
2938 can_fast_forward = 0;
2941 if (can_fast_forward && commit->parents->next &&
2942 !commit->parents->next->next &&
2943 !oidcmp(&commit->parents->next->item->object.oid,
2944 &merge_commit->object.oid)) {
2945 rollback_lock_file(&lock);
2946 ret = fast_forward_to(&commit->object.oid,
2947 &head_commit->object.oid, 0, opts);
2951 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
2952 git_path_merge_head(), 0);
2953 write_message("no-ff", 5, git_path_merge_mode(), 0);
2955 bases = get_merge_bases(head_commit, merge_commit);
2956 if (bases && !oidcmp(&merge_commit->object.oid,
2957 &bases->item->object.oid)) {
2959 /* skip merging an ancestor of HEAD */
2963 for (j = bases; j; j = j->next)
2964 commit_list_insert(j->item, &reversed);
2965 free_commit_list(bases);
2968 init_merge_options(&o);
2970 o.branch2 = ref_name.buf;
2971 o.buffer_output = 2;
2973 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
2975 fputs(o.obuf.buf, stdout);
2976 strbuf_release(&o.obuf);
2978 error(_("could not even attempt to merge '%.*s'"),
2979 merge_arg_len, arg);
2983 * The return value of merge_recursive() is 1 on clean, and 0 on
2986 * Let's reverse that, so that do_merge() returns 0 upon success and
2987 * 1 upon failed merge (keeping the return value -1 for the cases where
2988 * we will want to reschedule the `merge` command).
2992 if (active_cache_changed &&
2993 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
2994 ret = error(_("merge: Unable to write new index file"));
2998 rollback_lock_file(&lock);
3000 rerere(opts->allow_rerere_auto);
3003 * In case of problems, we now want to return a positive
3004 * value (a negative one would indicate that the `merge`
3005 * command needs to be rescheduled).
3007 ret = !!run_git_commit(git_path_merge_msg(), opts,
3011 strbuf_release(&ref_name);
3012 rollback_lock_file(&lock);
3016 static int is_final_fixup(struct todo_list *todo_list)
3018 int i = todo_list->current;
3020 if (!is_fixup(todo_list->items[i].command))
3023 while (++i < todo_list->nr)
3024 if (is_fixup(todo_list->items[i].command))
3026 else if (!is_noop(todo_list->items[i].command))
3031 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3035 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3036 if (!is_noop(todo_list->items[i].command))
3037 return todo_list->items[i].command;
3042 static int apply_autostash(struct replay_opts *opts)
3044 struct strbuf stash_sha1 = STRBUF_INIT;
3045 struct child_process child = CHILD_PROCESS_INIT;
3048 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3049 strbuf_release(&stash_sha1);
3052 strbuf_trim(&stash_sha1);
3055 child.no_stdout = 1;
3056 child.no_stderr = 1;
3057 argv_array_push(&child.args, "stash");
3058 argv_array_push(&child.args, "apply");
3059 argv_array_push(&child.args, stash_sha1.buf);
3060 if (!run_command(&child))
3061 fprintf(stderr, _("Applied autostash.\n"));
3063 struct child_process store = CHILD_PROCESS_INIT;
3066 argv_array_push(&store.args, "stash");
3067 argv_array_push(&store.args, "store");
3068 argv_array_push(&store.args, "-m");
3069 argv_array_push(&store.args, "autostash");
3070 argv_array_push(&store.args, "-q");
3071 argv_array_push(&store.args, stash_sha1.buf);
3072 if (run_command(&store))
3073 ret = error(_("cannot store %s"), stash_sha1.buf);
3076 _("Applying autostash resulted in conflicts.\n"
3077 "Your changes are safe in the stash.\n"
3078 "You can run \"git stash pop\" or"
3079 " \"git stash drop\" at any time.\n"));
3082 strbuf_release(&stash_sha1);
3086 static const char *reflog_message(struct replay_opts *opts,
3087 const char *sub_action, const char *fmt, ...)
3090 static struct strbuf buf = STRBUF_INIT;
3094 strbuf_addstr(&buf, action_name(opts));
3096 strbuf_addf(&buf, " (%s)", sub_action);
3098 strbuf_addstr(&buf, ": ");
3099 strbuf_vaddf(&buf, fmt, ap);
3106 static const char rescheduled_advice[] =
3107 N_("Could not execute the todo command\n"
3111 "It has been rescheduled; To edit the command before continuing, please\n"
3112 "edit the todo list first:\n"
3114 " git rebase --edit-todo\n"
3115 " git rebase --continue\n");
3117 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
3119 int res = 0, reschedule = 0;
3121 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3123 assert(!(opts->signoff || opts->no_commit ||
3124 opts->record_origin || opts->edit));
3125 if (read_and_refresh_cache(opts))
3128 while (todo_list->current < todo_list->nr) {
3129 struct todo_item *item = todo_list->items + todo_list->current;
3130 if (save_todo(todo_list, opts))
3132 if (is_rebase_i(opts)) {
3133 if (item->command != TODO_COMMENT) {
3134 FILE *f = fopen(rebase_path_msgnum(), "w");
3136 todo_list->done_nr++;
3139 fprintf(f, "%d\n", todo_list->done_nr);
3142 fprintf(stderr, "Rebasing (%d/%d)%s",
3144 todo_list->total_nr,
3145 opts->verbose ? "\n" : "\r");
3147 unlink(rebase_path_message());
3148 unlink(rebase_path_author_script());
3149 unlink(rebase_path_stopped_sha());
3150 unlink(rebase_path_amend());
3151 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3153 if (item->command <= TODO_SQUASH) {
3154 if (is_rebase_i(opts))
3155 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3156 command_to_string(item->command), NULL),
3158 res = do_pick_commit(item->command, item->commit,
3159 opts, is_final_fixup(todo_list));
3160 if (is_rebase_i(opts) && res < 0) {
3162 advise(_(rescheduled_advice),
3163 get_item_line_length(todo_list,
3164 todo_list->current),
3165 get_item_line(todo_list,
3166 todo_list->current));
3167 todo_list->current--;
3168 if (save_todo(todo_list, opts))
3171 if (item->command == TODO_EDIT) {
3172 struct commit *commit = item->commit;
3175 _("Stopped at %s... %.*s\n"),
3176 short_commit_name(commit),
3177 item->arg_len, item->arg);
3178 return error_with_patch(commit,
3179 item->arg, item->arg_len, opts, res,
3182 if (is_rebase_i(opts) && !res)
3183 record_in_rewritten(&item->commit->object.oid,
3184 peek_command(todo_list, 1));
3185 if (res && is_fixup(item->command)) {
3188 return error_failed_squash(item->commit, opts,
3189 item->arg_len, item->arg);
3190 } else if (res && is_rebase_i(opts) && item->commit)
3191 return res | error_with_patch(item->commit,
3192 item->arg, item->arg_len, opts, res,
3193 item->command == TODO_REWORD);
3194 } else if (item->command == TODO_EXEC) {
3195 char *end_of_arg = (char *)(item->arg + item->arg_len);
3196 int saved = *end_of_arg;
3200 res = do_exec(item->arg);
3201 *end_of_arg = saved;
3203 /* Reread the todo file if it has changed. */
3205 ; /* fall through */
3206 else if (stat(get_todo_path(opts), &st))
3207 res = error_errno(_("could not stat '%s'"),
3208 get_todo_path(opts));
3209 else if (match_stat_data(&todo_list->stat, &st)) {
3210 todo_list_release(todo_list);
3211 if (read_populate_todo(todo_list, opts))
3212 res = -1; /* message was printed */
3213 /* `current` will be incremented below */
3214 todo_list->current = -1;
3216 } else if (item->command == TODO_LABEL) {
3217 if ((res = do_label(item->arg, item->arg_len)))
3219 } else if (item->command == TODO_RESET) {
3220 if ((res = do_reset(item->arg, item->arg_len, opts)))
3222 } else if (item->command == TODO_MERGE) {
3223 if ((res = do_merge(item->commit,
3224 item->arg, item->arg_len,
3225 item->flags, opts)) < 0)
3227 else if (item->commit)
3228 record_in_rewritten(&item->commit->object.oid,
3229 peek_command(todo_list, 1));
3231 /* failed with merge conflicts */
3232 return error_with_patch(item->commit,
3234 item->arg_len, opts,
3236 } else if (!is_noop(item->command))
3237 return error(_("unknown command %d"), item->command);
3240 advise(_(rescheduled_advice),
3241 get_item_line_length(todo_list,
3242 todo_list->current),
3243 get_item_line(todo_list, todo_list->current));
3244 todo_list->current--;
3245 if (save_todo(todo_list, opts))
3248 return error_with_patch(item->commit,
3250 item->arg_len, opts,
3254 todo_list->current++;
3259 if (is_rebase_i(opts)) {
3260 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3263 /* Stopped in the middle, as planned? */
3264 if (todo_list->current < todo_list->nr)
3267 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3268 starts_with(head_ref.buf, "refs/")) {
3270 struct object_id head, orig;
3273 if (get_oid("HEAD", &head)) {
3274 res = error(_("cannot read HEAD"));
3276 strbuf_release(&head_ref);
3277 strbuf_release(&buf);
3280 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3281 get_oid_hex(buf.buf, &orig)) {
3282 res = error(_("could not read orig-head"));
3283 goto cleanup_head_ref;
3286 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3287 res = error(_("could not read 'onto'"));
3288 goto cleanup_head_ref;
3290 msg = reflog_message(opts, "finish", "%s onto %s",
3291 head_ref.buf, buf.buf);
3292 if (update_ref(msg, head_ref.buf, &head, &orig,
3293 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3294 res = error(_("could not update %s"),
3296 goto cleanup_head_ref;
3298 msg = reflog_message(opts, "finish", "returning to %s",
3300 if (create_symref("HEAD", head_ref.buf, msg)) {
3301 res = error(_("could not update HEAD to %s"),
3303 goto cleanup_head_ref;
3308 if (opts->verbose) {
3309 struct rev_info log_tree_opt;
3310 struct object_id orig, head;
3312 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3313 init_revisions(&log_tree_opt, NULL);
3314 log_tree_opt.diff = 1;
3315 log_tree_opt.diffopt.output_format =
3316 DIFF_FORMAT_DIFFSTAT;
3317 log_tree_opt.disable_stdin = 1;
3319 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3320 !get_oid(buf.buf, &orig) &&
3321 !get_oid("HEAD", &head)) {
3322 diff_tree_oid(&orig, &head, "",
3323 &log_tree_opt.diffopt);
3324 log_tree_diff_flush(&log_tree_opt);
3327 flush_rewritten_pending();
3328 if (!stat(rebase_path_rewritten_list(), &st) &&
3330 struct child_process child = CHILD_PROCESS_INIT;
3331 const char *post_rewrite_hook =
3332 find_hook("post-rewrite");
3334 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3336 argv_array_push(&child.args, "notes");
3337 argv_array_push(&child.args, "copy");
3338 argv_array_push(&child.args, "--for-rewrite=rebase");
3339 /* we don't care if this copying failed */
3340 run_command(&child);
3342 if (post_rewrite_hook) {
3343 struct child_process hook = CHILD_PROCESS_INIT;
3345 hook.in = open(rebase_path_rewritten_list(),
3347 hook.stdout_to_stderr = 1;
3348 argv_array_push(&hook.args, post_rewrite_hook);
3349 argv_array_push(&hook.args, "rebase");
3350 /* we don't care if this hook failed */
3354 apply_autostash(opts);
3356 fprintf(stderr, "Successfully rebased and updated %s.\n",
3359 strbuf_release(&buf);
3360 strbuf_release(&head_ref);
3364 * Sequence of picks finished successfully; cleanup by
3365 * removing the .git/sequencer directory
3367 return sequencer_remove_state(opts);
3370 static int continue_single_pick(void)
3372 const char *argv[] = { "commit", NULL };
3374 if (!file_exists(git_path_cherry_pick_head()) &&
3375 !file_exists(git_path_revert_head()))
3376 return error(_("no cherry-pick or revert in progress"));
3377 return run_command_v_opt(argv, RUN_GIT_CMD);
3380 static int commit_staged_changes(struct replay_opts *opts)
3382 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3384 if (has_unstaged_changes(1))
3385 return error(_("cannot rebase: You have unstaged changes."));
3386 if (!has_uncommitted_changes(0)) {
3387 const char *cherry_pick_head = git_path_cherry_pick_head();
3389 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3390 return error(_("could not remove CHERRY_PICK_HEAD"));
3394 if (file_exists(rebase_path_amend())) {
3395 struct strbuf rev = STRBUF_INIT;
3396 struct object_id head, to_amend;
3398 if (get_oid("HEAD", &head))
3399 return error(_("cannot amend non-existing commit"));
3400 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3401 return error(_("invalid file: '%s'"), rebase_path_amend());
3402 if (get_oid_hex(rev.buf, &to_amend))
3403 return error(_("invalid contents: '%s'"),
3404 rebase_path_amend());
3405 if (oidcmp(&head, &to_amend))
3406 return error(_("\nYou have uncommitted changes in your "
3407 "working tree. Please, commit them\n"
3408 "first and then run 'git rebase "
3409 "--continue' again."));
3411 strbuf_release(&rev);
3415 if (run_git_commit(rebase_path_message(), opts, flags))
3416 return error(_("could not commit staged changes."));
3417 unlink(rebase_path_amend());
3421 int sequencer_continue(struct replay_opts *opts)
3423 struct todo_list todo_list = TODO_LIST_INIT;
3426 if (read_and_refresh_cache(opts))
3429 if (is_rebase_i(opts)) {
3430 if (commit_staged_changes(opts))
3432 } else if (!file_exists(get_todo_path(opts)))
3433 return continue_single_pick();
3434 if (read_populate_opts(opts))
3436 if ((res = read_populate_todo(&todo_list, opts)))
3437 goto release_todo_list;
3439 if (!is_rebase_i(opts)) {
3440 /* Verify that the conflict has been resolved */
3441 if (file_exists(git_path_cherry_pick_head()) ||
3442 file_exists(git_path_revert_head())) {
3443 res = continue_single_pick();
3445 goto release_todo_list;
3447 if (index_differs_from("HEAD", NULL, 0)) {
3448 res = error_dirty_index(opts);
3449 goto release_todo_list;
3451 todo_list.current++;
3452 } else if (file_exists(rebase_path_stopped_sha())) {
3453 struct strbuf buf = STRBUF_INIT;
3454 struct object_id oid;
3456 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3457 !get_oid_committish(buf.buf, &oid))
3458 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3459 strbuf_release(&buf);
3462 res = pick_commits(&todo_list, opts);
3464 todo_list_release(&todo_list);
3468 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3470 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3471 return do_pick_commit(opts->action == REPLAY_PICK ?
3472 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3475 int sequencer_pick_revisions(struct replay_opts *opts)
3477 struct todo_list todo_list = TODO_LIST_INIT;
3478 struct object_id oid;
3482 if (read_and_refresh_cache(opts))
3485 for (i = 0; i < opts->revs->pending.nr; i++) {
3486 struct object_id oid;
3487 const char *name = opts->revs->pending.objects[i].name;
3489 /* This happens when using --stdin. */
3493 if (!get_oid(name, &oid)) {
3494 if (!lookup_commit_reference_gently(&oid, 1)) {
3495 enum object_type type = oid_object_info(&oid,
3497 return error(_("%s: can't cherry-pick a %s"),
3498 name, type_name(type));
3501 return error(_("%s: bad revision"), name);
3505 * If we were called as "git cherry-pick <commit>", just
3506 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3507 * REVERT_HEAD, and don't touch the sequencer state.
3508 * This means it is possible to cherry-pick in the middle
3509 * of a cherry-pick sequence.
3511 if (opts->revs->cmdline.nr == 1 &&
3512 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3513 opts->revs->no_walk &&
3514 !opts->revs->cmdline.rev->flags) {
3515 struct commit *cmit;
3516 if (prepare_revision_walk(opts->revs))
3517 return error(_("revision walk setup failed"));
3518 cmit = get_revision(opts->revs);
3519 if (!cmit || get_revision(opts->revs))
3520 return error("BUG: expected exactly one commit from walk");
3521 return single_pick(cmit, opts);
3525 * Start a new cherry-pick/ revert sequence; but
3526 * first, make sure that an existing one isn't in
3530 if (walk_revs_populate_todo(&todo_list, opts) ||
3531 create_seq_dir() < 0)
3533 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3534 return error(_("can't revert as initial commit"));
3535 if (save_head(oid_to_hex(&oid)))
3537 if (save_opts(opts))
3539 update_abort_safety_file();
3540 res = pick_commits(&todo_list, opts);
3541 todo_list_release(&todo_list);
3545 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3547 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3548 struct strbuf sob = STRBUF_INIT;
3551 strbuf_addstr(&sob, sign_off_header);
3552 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3553 getenv("GIT_COMMITTER_EMAIL")));
3554 strbuf_addch(&sob, '\n');
3557 strbuf_complete_line(msgbuf);
3560 * If the whole message buffer is equal to the sob, pretend that we
3561 * found a conforming footer with a matching sob
3563 if (msgbuf->len - ignore_footer == sob.len &&
3564 !strncmp(msgbuf->buf, sob.buf, sob.len))
3567 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3570 const char *append_newlines = NULL;
3571 size_t len = msgbuf->len - ignore_footer;
3575 * The buffer is completely empty. Leave foom for
3576 * the title and body to be filled in by the user.
3578 append_newlines = "\n\n";
3579 } else if (len == 1) {
3581 * Buffer contains a single newline. Add another
3582 * so that we leave room for the title and body.
3584 append_newlines = "\n";
3585 } else if (msgbuf->buf[len - 2] != '\n') {
3587 * Buffer ends with a single newline. Add another
3588 * so that there is an empty line between the message
3591 append_newlines = "\n";
3592 } /* else, the buffer already ends with two newlines. */
3594 if (append_newlines)
3595 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3596 append_newlines, strlen(append_newlines));
3599 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3600 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3603 strbuf_release(&sob);
3606 struct labels_entry {
3607 struct hashmap_entry entry;
3608 char label[FLEX_ARRAY];
3611 static int labels_cmp(const void *fndata, const struct labels_entry *a,
3612 const struct labels_entry *b, const void *key)
3614 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3617 struct string_entry {
3618 struct oidmap_entry entry;
3619 char string[FLEX_ARRAY];
3622 struct label_state {
3623 struct oidmap commit2label;
3624 struct hashmap labels;
3628 static const char *label_oid(struct object_id *oid, const char *label,
3629 struct label_state *state)
3631 struct labels_entry *labels_entry;
3632 struct string_entry *string_entry;
3633 struct object_id dummy;
3637 string_entry = oidmap_get(&state->commit2label, oid);
3639 return string_entry->string;
3642 * For "uninteresting" commits, i.e. commits that are not to be
3643 * rebased, and which can therefore not be labeled, we use a unique
3644 * abbreviation of the commit name. This is slightly more complicated
3645 * than calling find_unique_abbrev() because we also need to make
3646 * sure that the abbreviation does not conflict with any other
3649 * We disallow "interesting" commits to be labeled by a string that
3650 * is a valid full-length hash, to ensure that we always can find an
3651 * abbreviation for any uninteresting commit's names that does not
3652 * clash with any other label.
3657 strbuf_reset(&state->buf);
3658 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3659 label = p = state->buf.buf;
3661 find_unique_abbrev_r(p, oid, default_abbrev);
3664 * We may need to extend the abbreviated hash so that there is
3665 * no conflicting label.
3667 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3668 size_t i = strlen(p) + 1;
3670 oid_to_hex_r(p, oid);
3671 for (; i < GIT_SHA1_HEXSZ; i++) {
3674 if (!hashmap_get_from_hash(&state->labels,
3680 } else if (((len = strlen(label)) == GIT_SHA1_RAWSZ &&
3681 !get_oid_hex(label, &dummy)) ||
3682 (len == 1 && *label == '#') ||
3683 hashmap_get_from_hash(&state->labels,
3684 strihash(label), label)) {
3686 * If the label already exists, or if the label is a valid full
3687 * OID, or the label is a '#' (which we use as a separator
3688 * between merge heads and oneline), we append a dash and a
3689 * number to make it unique.
3691 struct strbuf *buf = &state->buf;
3694 strbuf_add(buf, label, len);
3696 for (i = 2; ; i++) {
3697 strbuf_setlen(buf, len);
3698 strbuf_addf(buf, "-%d", i);
3699 if (!hashmap_get_from_hash(&state->labels,
3708 FLEX_ALLOC_STR(labels_entry, label, label);
3709 hashmap_entry_init(labels_entry, strihash(label));
3710 hashmap_add(&state->labels, labels_entry);
3712 FLEX_ALLOC_STR(string_entry, string, label);
3713 oidcpy(&string_entry->entry.oid, oid);
3714 oidmap_put(&state->commit2label, string_entry);
3716 return string_entry->string;
3719 static int make_script_with_merges(struct pretty_print_context *pp,
3720 struct rev_info *revs, FILE *out,
3723 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3724 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
3725 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
3726 struct strbuf label = STRBUF_INIT;
3727 struct commit_list *commits = NULL, **tail = &commits, *iter;
3728 struct commit_list *tips = NULL, **tips_tail = &tips;
3729 struct commit *commit;
3730 struct oidmap commit2todo = OIDMAP_INIT;
3731 struct string_entry *entry;
3732 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
3733 shown = OIDSET_INIT;
3734 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
3736 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
3737 const char *cmd_pick = abbr ? "p" : "pick",
3738 *cmd_label = abbr ? "l" : "label",
3739 *cmd_reset = abbr ? "t" : "reset",
3740 *cmd_merge = abbr ? "m" : "merge";
3742 oidmap_init(&commit2todo, 0);
3743 oidmap_init(&state.commit2label, 0);
3744 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
3745 strbuf_init(&state.buf, 32);
3747 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
3748 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
3749 FLEX_ALLOC_STR(entry, string, "onto");
3750 oidcpy(&entry->entry.oid, oid);
3751 oidmap_put(&state.commit2label, entry);
3756 * - get onelines for all commits
3757 * - gather all branch tips (i.e. 2nd or later parents of merges)
3758 * - label all branch tips
3760 while ((commit = get_revision(revs))) {
3761 struct commit_list *to_merge;
3763 const char *p1, *p2;
3764 struct object_id *oid;
3767 tail = &commit_list_insert(commit, tail)->next;
3768 oidset_insert(&interesting, &commit->object.oid);
3770 is_empty = is_original_commit_empty(commit);
3771 if (!is_empty && (commit->object.flags & PATCHSAME))
3774 strbuf_reset(&oneline);
3775 pretty_print_commit(pp, commit, &oneline);
3777 to_merge = commit->parents ? commit->parents->next : NULL;
3779 /* non-merge commit: easy case */
3781 if (!keep_empty && is_empty)
3782 strbuf_addf(&buf, "%c ", comment_line_char);
3783 strbuf_addf(&buf, "%s %s %s", cmd_pick,
3784 oid_to_hex(&commit->object.oid),
3787 FLEX_ALLOC_STR(entry, string, buf.buf);
3788 oidcpy(&entry->entry.oid, &commit->object.oid);
3789 oidmap_put(&commit2todo, entry);
3794 is_octopus = to_merge && to_merge->next;
3797 BUG("Octopus merges not yet supported");
3799 /* Create a label */
3800 strbuf_reset(&label);
3801 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
3802 (p1 = strchr(p1, '\'')) &&
3803 (p2 = strchr(++p1, '\'')))
3804 strbuf_add(&label, p1, p2 - p1);
3805 else if (skip_prefix(oneline.buf, "Merge pull request ",
3807 (p1 = strstr(p1, " from ")))
3808 strbuf_addstr(&label, p1 + strlen(" from "));
3810 strbuf_addbuf(&label, &oneline);
3812 for (p1 = label.buf; *p1; p1++)
3817 strbuf_addf(&buf, "%s -C %s",
3818 cmd_merge, oid_to_hex(&commit->object.oid));
3820 /* label the tip of merged branch */
3821 oid = &to_merge->item->object.oid;
3822 strbuf_addch(&buf, ' ');
3824 if (!oidset_contains(&interesting, oid))
3825 strbuf_addstr(&buf, label_oid(oid, NULL, &state));
3827 tips_tail = &commit_list_insert(to_merge->item,
3830 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
3832 strbuf_addf(&buf, " # %s", oneline.buf);
3834 FLEX_ALLOC_STR(entry, string, buf.buf);
3835 oidcpy(&entry->entry.oid, &commit->object.oid);
3836 oidmap_put(&commit2todo, entry);
3841 * - label branch points
3842 * - add HEAD to the branch tips
3844 for (iter = commits; iter; iter = iter->next) {
3845 struct commit_list *parent = iter->item->parents;
3846 for (; parent; parent = parent->next) {
3847 struct object_id *oid = &parent->item->object.oid;
3848 if (!oidset_contains(&interesting, oid))
3850 if (!oidset_contains(&child_seen, oid))
3851 oidset_insert(&child_seen, oid);
3853 label_oid(oid, "branch-point", &state);
3856 /* Add HEAD as implict "tip of branch" */
3858 tips_tail = &commit_list_insert(iter->item,
3863 * Third phase: output the todo list. This is a bit tricky, as we
3864 * want to avoid jumping back and forth between revisions. To
3865 * accomplish that goal, we walk backwards from the branch tips,
3866 * gathering commits not yet shown, reversing the list on the fly,
3867 * then outputting that list (labeling revisions as needed).
3869 fprintf(out, "%s onto\n", cmd_label);
3870 for (iter = tips; iter; iter = iter->next) {
3871 struct commit_list *list = NULL, *iter2;
3873 commit = iter->item;
3874 if (oidset_contains(&shown, &commit->object.oid))
3876 entry = oidmap_get(&state.commit2label, &commit->object.oid);
3879 fprintf(out, "\n# Branch %s\n", entry->string);
3883 while (oidset_contains(&interesting, &commit->object.oid) &&
3884 !oidset_contains(&shown, &commit->object.oid)) {
3885 commit_list_insert(commit, &list);
3886 if (!commit->parents) {
3890 commit = commit->parents->item;
3894 fprintf(out, "%s onto\n", cmd_reset);
3896 const char *to = NULL;
3898 entry = oidmap_get(&state.commit2label,
3899 &commit->object.oid);
3902 else if (!rebase_cousins)
3903 to = label_oid(&commit->object.oid, NULL,
3906 if (!to || !strcmp(to, "onto"))
3907 fprintf(out, "%s onto\n", cmd_reset);
3909 strbuf_reset(&oneline);
3910 pretty_print_commit(pp, commit, &oneline);
3911 fprintf(out, "%s %s # %s\n",
3912 cmd_reset, to, oneline.buf);
3916 for (iter2 = list; iter2; iter2 = iter2->next) {
3917 struct object_id *oid = &iter2->item->object.oid;
3918 entry = oidmap_get(&commit2todo, oid);
3919 /* only show if not already upstream */
3921 fprintf(out, "%s\n", entry->string);
3922 entry = oidmap_get(&state.commit2label, oid);
3924 fprintf(out, "%s %s\n",
3925 cmd_label, entry->string);
3926 oidset_insert(&shown, oid);
3929 free_commit_list(list);
3932 free_commit_list(commits);
3933 free_commit_list(tips);
3935 strbuf_release(&label);
3936 strbuf_release(&oneline);
3937 strbuf_release(&buf);
3939 oidmap_free(&commit2todo, 1);
3940 oidmap_free(&state.commit2label, 1);
3941 hashmap_free(&state.labels, 1);
3942 strbuf_release(&state.buf);
3947 int sequencer_make_script(FILE *out, int argc, const char **argv,
3950 char *format = NULL;
3951 struct pretty_print_context pp = {0};
3952 struct strbuf buf = STRBUF_INIT;
3953 struct rev_info revs;
3954 struct commit *commit;
3955 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3956 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
3957 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
3959 init_revisions(&revs, NULL);
3960 revs.verbose_header = 1;
3962 revs.max_parents = 1;
3963 revs.cherry_mark = 1;
3966 revs.right_only = 1;
3967 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3968 revs.topo_order = 1;
3970 revs.pretty_given = 1;
3971 git_config_get_string("rebase.instructionFormat", &format);
3972 if (!format || !*format) {
3974 format = xstrdup("%s");
3976 get_commit_format(format, &revs);
3978 pp.fmt = revs.commit_format;
3979 pp.output_encoding = get_log_output_encoding();
3981 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3982 return error(_("make_script: unhandled options"));
3984 if (prepare_revision_walk(&revs) < 0)
3985 return error(_("make_script: error preparing revisions"));
3988 return make_script_with_merges(&pp, &revs, out, flags);
3990 while ((commit = get_revision(&revs))) {
3991 int is_empty = is_original_commit_empty(commit);
3993 if (!is_empty && (commit->object.flags & PATCHSAME))
3996 if (!keep_empty && is_empty)
3997 strbuf_addf(&buf, "%c ", comment_line_char);
3998 strbuf_addf(&buf, "%s %s ", insn,
3999 oid_to_hex(&commit->object.oid));
4000 pretty_print_commit(&pp, commit, &buf);
4001 strbuf_addch(&buf, '\n');
4002 fputs(buf.buf, out);
4004 strbuf_release(&buf);
4009 * Add commands after pick and (series of) squash/fixup commands
4012 int sequencer_add_exec_commands(const char *commands)
4014 const char *todo_file = rebase_path_todo();
4015 struct todo_list todo_list = TODO_LIST_INIT;
4016 struct todo_item *item;
4017 struct strbuf *buf = &todo_list.buf;
4018 size_t offset = 0, commands_len = strlen(commands);
4021 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4022 return error(_("could not read '%s'."), todo_file);
4024 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4025 todo_list_release(&todo_list);
4026 return error(_("unusable todo list: '%s'"), todo_file);
4030 /* insert <commands> before every pick except the first one */
4031 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4032 if (item->command == TODO_PICK && !first) {
4033 strbuf_insert(buf, item->offset_in_buf + offset,
4034 commands, commands_len);
4035 offset += commands_len;
4040 /* append final <commands> */
4041 strbuf_add(buf, commands, commands_len);
4043 i = write_message(buf->buf, buf->len, todo_file, 0);
4044 todo_list_release(&todo_list);
4048 int transform_todos(unsigned flags)
4050 const char *todo_file = rebase_path_todo();
4051 struct todo_list todo_list = TODO_LIST_INIT;
4052 struct strbuf buf = STRBUF_INIT;
4053 struct todo_item *item;
4056 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4057 return error(_("could not read '%s'."), todo_file);
4059 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4060 todo_list_release(&todo_list);
4061 return error(_("unusable todo list: '%s'"), todo_file);
4064 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4065 /* if the item is not a command write it and continue */
4066 if (item->command >= TODO_COMMENT) {
4067 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4071 /* add command to the buffer */
4072 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4073 strbuf_addch(&buf, command_to_char(item->command));
4075 strbuf_addstr(&buf, command_to_string(item->command));
4079 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4080 short_commit_name(item->commit) :
4081 oid_to_hex(&item->commit->object.oid);
4083 if (item->command == TODO_MERGE) {
4084 if (item->flags & TODO_EDIT_MERGE_MSG)
4085 strbuf_addstr(&buf, " -c");
4087 strbuf_addstr(&buf, " -C");
4090 strbuf_addf(&buf, " %s", oid);
4093 /* add all the rest */
4095 strbuf_addch(&buf, '\n');
4097 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4100 i = write_message(buf.buf, buf.len, todo_file, 0);
4101 todo_list_release(&todo_list);
4106 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
4109 static enum check_level get_missing_commit_check_level(void)
4113 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4114 !strcasecmp("ignore", value))
4115 return CHECK_IGNORE;
4116 if (!strcasecmp("warn", value))
4118 if (!strcasecmp("error", value))
4120 warning(_("unrecognized setting %s for option "
4121 "rebase.missingCommitsCheck. Ignoring."), value);
4122 return CHECK_IGNORE;
4126 * Check if the user dropped some commits by mistake
4127 * Behaviour determined by rebase.missingCommitsCheck.
4128 * Check if there is an unrecognized command or a
4129 * bad SHA-1 in a command.
4131 int check_todo_list(void)
4133 enum check_level check_level = get_missing_commit_check_level();
4134 struct strbuf todo_file = STRBUF_INIT;
4135 struct todo_list todo_list = TODO_LIST_INIT;
4136 struct strbuf missing = STRBUF_INIT;
4137 int advise_to_edit_todo = 0, res = 0, i;
4139 strbuf_addstr(&todo_file, rebase_path_todo());
4140 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4144 advise_to_edit_todo = res =
4145 parse_insn_buffer(todo_list.buf.buf, &todo_list);
4147 if (res || check_level == CHECK_IGNORE)
4150 /* Mark the commits in git-rebase-todo as seen */
4151 for (i = 0; i < todo_list.nr; i++) {
4152 struct commit *commit = todo_list.items[i].commit;
4154 commit->util = (void *)1;
4157 todo_list_release(&todo_list);
4158 strbuf_addstr(&todo_file, ".backup");
4159 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4163 strbuf_release(&todo_file);
4164 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4166 /* Find commits in git-rebase-todo.backup yet unseen */
4167 for (i = todo_list.nr - 1; i >= 0; i--) {
4168 struct todo_item *item = todo_list.items + i;
4169 struct commit *commit = item->commit;
4170 if (commit && !commit->util) {
4171 strbuf_addf(&missing, " - %s %.*s\n",
4172 short_commit_name(commit),
4173 item->arg_len, item->arg);
4174 commit->util = (void *)1;
4178 /* Warn about missing commits */
4182 if (check_level == CHECK_ERROR)
4183 advise_to_edit_todo = res = 1;
4186 _("Warning: some commits may have been dropped accidentally.\n"
4187 "Dropped commits (newer to older):\n"));
4189 /* Make the list user-friendly and display */
4190 fputs(missing.buf, stderr);
4191 strbuf_release(&missing);
4193 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4194 "explicitly remove a commit.\n\n"
4195 "Use 'git config rebase.missingCommitsCheck' to change "
4196 "the level of warnings.\n"
4197 "The possible behaviours are: ignore, warn, error.\n\n"));
4200 strbuf_release(&todo_file);
4201 todo_list_release(&todo_list);
4203 if (advise_to_edit_todo)
4205 _("You can fix this with 'git rebase --edit-todo' "
4206 "and then run 'git rebase --continue'.\n"
4207 "Or you can abort the rebase with 'git rebase"
4213 static int rewrite_file(const char *path, const char *buf, size_t len)
4216 int fd = open(path, O_WRONLY | O_TRUNC);
4218 return error_errno(_("could not open '%s' for writing"), path);
4219 if (write_in_full(fd, buf, len) < 0)
4220 rc = error_errno(_("could not write to '%s'"), path);
4221 if (close(fd) && !rc)
4222 rc = error_errno(_("could not close '%s'"), path);
4226 /* skip picking commits whose parents are unchanged */
4227 int skip_unnecessary_picks(void)
4229 const char *todo_file = rebase_path_todo();
4230 struct strbuf buf = STRBUF_INIT;
4231 struct todo_list todo_list = TODO_LIST_INIT;
4232 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4235 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4236 return error(_("could not read 'onto'"));
4237 if (get_oid(buf.buf, &onto_oid)) {
4238 strbuf_release(&buf);
4239 return error(_("need a HEAD to fixup"));
4241 strbuf_release(&buf);
4243 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4245 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4246 todo_list_release(&todo_list);
4250 for (i = 0; i < todo_list.nr; i++) {
4251 struct todo_item *item = todo_list.items + i;
4253 if (item->command >= TODO_NOOP)
4255 if (item->command != TODO_PICK)
4257 if (parse_commit(item->commit)) {
4258 todo_list_release(&todo_list);
4259 return error(_("could not parse commit '%s'"),
4260 oid_to_hex(&item->commit->object.oid));
4262 if (!item->commit->parents)
4263 break; /* root commit */
4264 if (item->commit->parents->next)
4265 break; /* merge commit */
4266 parent_oid = &item->commit->parents->item->object.oid;
4267 if (hashcmp(parent_oid->hash, oid->hash))
4269 oid = &item->commit->object.oid;
4272 int offset = get_item_line_offset(&todo_list, i);
4273 const char *done_path = rebase_path_done();
4275 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4277 error_errno(_("could not open '%s' for writing"),
4279 todo_list_release(&todo_list);
4282 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4283 error_errno(_("could not write to '%s'"), done_path);
4284 todo_list_release(&todo_list);
4290 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4291 todo_list.buf.len - offset) < 0) {
4292 todo_list_release(&todo_list);
4296 todo_list.current = i;
4297 if (is_fixup(peek_command(&todo_list, 0)))
4298 record_in_rewritten(oid, peek_command(&todo_list, 0));
4301 todo_list_release(&todo_list);
4302 printf("%s\n", oid_to_hex(oid));
4307 struct subject2item_entry {
4308 struct hashmap_entry entry;
4310 char subject[FLEX_ARRAY];
4313 static int subject2item_cmp(const void *fndata,
4314 const struct subject2item_entry *a,
4315 const struct subject2item_entry *b, const void *key)
4317 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4321 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4322 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4323 * after the former, and change "pick" to "fixup"/"squash".
4325 * Note that if the config has specified a custom instruction format, each log
4326 * message will have to be retrieved from the commit (as the oneline in the
4327 * script cannot be trusted) in order to normalize the autosquash arrangement.
4329 int rearrange_squash(void)
4331 const char *todo_file = rebase_path_todo();
4332 struct todo_list todo_list = TODO_LIST_INIT;
4333 struct hashmap subject2item;
4334 int res = 0, rearranged = 0, *next, *tail, i;
4337 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4339 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4340 todo_list_release(&todo_list);
4345 * The hashmap maps onelines to the respective todo list index.
4347 * If any items need to be rearranged, the next[i] value will indicate
4348 * which item was moved directly after the i'th.
4350 * In that case, last[i] will indicate the index of the latest item to
4351 * be moved to appear after the i'th.
4353 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4354 NULL, todo_list.nr);
4355 ALLOC_ARRAY(next, todo_list.nr);
4356 ALLOC_ARRAY(tail, todo_list.nr);
4357 ALLOC_ARRAY(subjects, todo_list.nr);
4358 for (i = 0; i < todo_list.nr; i++) {
4359 struct strbuf buf = STRBUF_INIT;
4360 struct todo_item *item = todo_list.items + i;
4361 const char *commit_buffer, *subject, *p;
4364 struct subject2item_entry *entry;
4366 next[i] = tail[i] = -1;
4367 if (!item->commit || item->command == TODO_DROP) {
4372 if (is_fixup(item->command)) {
4373 todo_list_release(&todo_list);
4374 return error(_("the script was already rearranged."));
4377 item->commit->util = item;
4379 parse_commit(item->commit);
4380 commit_buffer = get_commit_buffer(item->commit, NULL);
4381 find_commit_subject(commit_buffer, &subject);
4382 format_subject(&buf, subject, " ");
4383 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4384 unuse_commit_buffer(item->commit, commit_buffer);
4385 if ((skip_prefix(subject, "fixup! ", &p) ||
4386 skip_prefix(subject, "squash! ", &p))) {
4387 struct commit *commit2;
4392 if (!skip_prefix(p, "fixup! ", &p) &&
4393 !skip_prefix(p, "squash! ", &p))
4397 if ((entry = hashmap_get_from_hash(&subject2item,
4399 /* found by title */
4401 else if (!strchr(p, ' ') &&
4403 lookup_commit_reference_by_name(p)) &&
4405 /* found by commit name */
4406 i2 = (struct todo_item *)commit2->util
4409 /* copy can be a prefix of the commit subject */
4410 for (i2 = 0; i2 < i; i2++)
4412 starts_with(subjects[i2], p))
4420 todo_list.items[i].command =
4421 starts_with(subject, "fixup!") ?
4422 TODO_FIXUP : TODO_SQUASH;
4428 } else if (!hashmap_get_from_hash(&subject2item,
4429 strhash(subject), subject)) {
4430 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4432 hashmap_entry_init(entry, strhash(entry->subject));
4433 hashmap_put(&subject2item, entry);
4438 struct strbuf buf = STRBUF_INIT;
4440 for (i = 0; i < todo_list.nr; i++) {
4441 enum todo_command command = todo_list.items[i].command;
4445 * Initially, all commands are 'pick's. If it is a
4446 * fixup or a squash now, we have rearranged it.
4448 if (is_fixup(command))
4453 get_item_line(&todo_list, cur);
4455 get_item_line(&todo_list, cur + 1);
4457 /* replace 'pick', by 'fixup' or 'squash' */
4458 command = todo_list.items[cur].command;
4459 if (is_fixup(command)) {
4461 todo_command_info[command].str);
4462 bol += strcspn(bol, " \t");
4465 strbuf_add(&buf, bol, eol - bol);
4471 res = rewrite_file(todo_file, buf.buf, buf.len);
4472 strbuf_release(&buf);
4477 for (i = 0; i < todo_list.nr; i++)
4480 hashmap_free(&subject2item, 1);
4481 todo_list_release(&todo_list);