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"
29 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
31 const char sign_off_header[] = "Signed-off-by: ";
32 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
34 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
36 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
38 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
39 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
40 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
41 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
43 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
45 * The file containing rebase commands, comments, and empty lines.
46 * This file is created by "git rebase -i" then edited by the user. As
47 * the lines are processed, they are removed from the front of this
48 * file and written to the tail of 'done'.
50 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
52 * The rebase command lines that have already been processed. A line
53 * is moved here when it is first handled, before any associated user
56 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
58 * The file to keep track of how many commands were already processed (e.g.
61 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
63 * The file to keep track of how many commands are to be processed in total
64 * (e.g. for the prompt).
66 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
68 * The commit message that is planned to be used for any changes that
69 * need to be committed following a user interaction.
71 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
73 * The file into which is accumulated the suggested commit message for
74 * squash/fixup commands. When the first of a series of squash/fixups
75 * is seen, the file is created and the commit message from the
76 * previous commit and from the first squash/fixup commit are written
77 * to it. The commit message for each subsequent squash/fixup commit
78 * is appended to the file as it is processed.
80 * The first line of the file is of the form
81 * # This is a combination of $count commits.
82 * where $count is the number of commits whose messages have been
83 * written to the file so far (including the initial "pick" commit).
84 * Each time that a commit message is processed, this line is read and
85 * updated. It is deleted just before the combined commit is made.
87 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
89 * If the current series of squash/fixups has not yet included a squash
90 * command, then this file exists and holds the commit message of the
91 * original "pick" commit. (If the series ends without a "squash"
92 * command, then this can be used as the commit message of the combined
93 * commit without opening the editor.)
95 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
97 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
98 * GIT_AUTHOR_DATE that will be used for the commit that is currently
101 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
103 * When an "edit" rebase command is being processed, the SHA1 of the
104 * commit to be edited is recorded in this file. When "git rebase
105 * --continue" is executed, if there are any staged changes then they
106 * will be amended to the HEAD commit, but only provided the HEAD
107 * commit is still the commit to be edited. When any other rebase
108 * command is processed, this file is deleted.
110 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
112 * When we stop at a given patch via the "edit" command, this file contains
113 * the abbreviated commit name of the corresponding patch.
115 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
117 * For the post-rewrite hook, we make a list of rewritten commits and
118 * their new sha1s. The rewritten-pending list keeps the sha1s of
119 * commits that have been processed, but not committed yet,
120 * e.g. because they are waiting for a 'squash' command.
122 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
123 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
124 "rebase-merge/rewritten-pending")
127 * The path of the file listing refs that need to be deleted after the rebase
128 * finishes. This is used by the `label` command to record the need for cleanup.
130 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
133 * The following files are written by git-rebase just after parsing the
134 * command-line (and are only consumed, not modified, by the sequencer).
136 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
137 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
138 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
139 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
140 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
141 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
142 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
143 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
144 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
145 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
147 static int git_sequencer_config(const char *k, const char *v, void *cb)
149 struct replay_opts *opts = cb;
152 if (!strcmp(k, "commit.cleanup")) {
155 status = git_config_string(&s, k, v);
159 if (!strcmp(s, "verbatim"))
160 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
161 else if (!strcmp(s, "whitespace"))
162 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
163 else if (!strcmp(s, "strip"))
164 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
165 else if (!strcmp(s, "scissors"))
166 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
168 warning(_("invalid commit message cleanup mode '%s'"),
174 if (!strcmp(k, "commit.gpgsign")) {
175 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
179 status = git_gpg_config(k, v, NULL);
183 return git_diff_basic_config(k, v, NULL);
186 void sequencer_init_config(struct replay_opts *opts)
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
189 git_config(git_sequencer_config, opts);
192 static inline int is_rebase_i(const struct replay_opts *opts)
194 return opts->action == REPLAY_INTERACTIVE_REBASE;
197 static const char *get_dir(const struct replay_opts *opts)
199 if (is_rebase_i(opts))
200 return rebase_path();
201 return git_path_seq_dir();
204 static const char *get_todo_path(const struct replay_opts *opts)
206 if (is_rebase_i(opts))
207 return rebase_path_todo();
208 return git_path_todo_file();
212 * Returns 0 for non-conforming footer
213 * Returns 1 for conforming footer
214 * Returns 2 when sob exists within conforming footer
215 * Returns 3 when sob exists within conforming footer as last entry
217 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
220 struct trailer_info info;
222 int found_sob = 0, found_sob_last = 0;
224 trailer_info_get(&info, sb->buf);
226 if (info.trailer_start == info.trailer_end)
229 for (i = 0; i < info.trailer_nr; i++)
230 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
232 if (i == info.trailer_nr - 1)
236 trailer_info_release(&info);
245 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
247 static struct strbuf buf = STRBUF_INIT;
251 sq_quotef(&buf, "-S%s", opts->gpg_sign);
255 int sequencer_remove_state(struct replay_opts *opts)
257 struct strbuf buf = STRBUF_INIT;
260 if (is_rebase_i(opts) &&
261 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
264 char *eol = strchr(p, '\n');
267 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
268 warning(_("could not delete '%s'"), p);
275 free(opts->gpg_sign);
276 free(opts->strategy);
277 for (i = 0; i < opts->xopts_nr; i++)
278 free(opts->xopts[i]);
282 strbuf_addstr(&buf, get_dir(opts));
283 remove_dir_recursively(&buf, 0);
284 strbuf_release(&buf);
289 static const char *action_name(const struct replay_opts *opts)
291 switch (opts->action) {
295 return N_("cherry-pick");
296 case REPLAY_INTERACTIVE_REBASE:
297 return N_("rebase -i");
299 die(_("Unknown action: %d"), opts->action);
302 struct commit_message {
309 static const char *short_commit_name(struct commit *commit)
311 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
314 static int get_message(struct commit *commit, struct commit_message *out)
316 const char *abbrev, *subject;
319 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
320 abbrev = short_commit_name(commit);
322 subject_len = find_commit_subject(out->message, &subject);
324 out->subject = xmemdupz(subject, subject_len);
325 out->label = xstrfmt("%s... %s", abbrev, out->subject);
326 out->parent_label = xstrfmt("parent of %s", out->label);
331 static void free_message(struct commit *commit, struct commit_message *msg)
333 free(msg->parent_label);
336 unuse_commit_buffer(commit, msg->message);
339 static void print_advice(int show_hint, struct replay_opts *opts)
341 char *msg = getenv("GIT_CHERRY_PICK_HELP");
344 fprintf(stderr, "%s\n", msg);
346 * A conflict has occurred but the porcelain
347 * (typically rebase --interactive) wants to take care
348 * of the commit itself so remove CHERRY_PICK_HEAD
350 unlink(git_path_cherry_pick_head());
356 advise(_("after resolving the conflicts, mark the corrected paths\n"
357 "with 'git add <paths>' or 'git rm <paths>'"));
359 advise(_("after resolving the conflicts, mark the corrected paths\n"
360 "with 'git add <paths>' or 'git rm <paths>'\n"
361 "and commit the result with 'git commit'"));
365 static int write_message(const void *buf, size_t len, const char *filename,
368 struct lock_file msg_file = LOCK_INIT;
370 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
372 return error_errno(_("could not lock '%s'"), filename);
373 if (write_in_full(msg_fd, buf, len) < 0) {
374 error_errno(_("could not write to '%s'"), filename);
375 rollback_lock_file(&msg_file);
378 if (append_eol && write(msg_fd, "\n", 1) < 0) {
379 error_errno(_("could not write eol to '%s'"), filename);
380 rollback_lock_file(&msg_file);
383 if (commit_lock_file(&msg_file) < 0)
384 return error(_("failed to finalize '%s'"), filename);
390 * Reads a file that was presumably written by a shell script, i.e. with an
391 * end-of-line marker that needs to be stripped.
393 * Note that only the last end-of-line marker is stripped, consistent with the
394 * behavior of "$(cat path)" in a shell script.
396 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
398 static int read_oneliner(struct strbuf *buf,
399 const char *path, int skip_if_empty)
401 int orig_len = buf->len;
403 if (!file_exists(path))
406 if (strbuf_read_file(buf, path, 0) < 0) {
407 warning_errno(_("could not read '%s'"), path);
411 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
412 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
414 buf->buf[buf->len] = '\0';
417 if (skip_if_empty && buf->len == orig_len)
423 static struct tree *empty_tree(void)
425 return lookup_tree(the_hash_algo->empty_tree);
428 static int error_dirty_index(struct replay_opts *opts)
430 if (read_cache_unmerged())
431 return error_resolve_conflict(_(action_name(opts)));
433 error(_("your local changes would be overwritten by %s."),
434 _(action_name(opts)));
436 if (advice_commit_before_merge)
437 advise(_("commit your changes or stash them to proceed."));
441 static void update_abort_safety_file(void)
443 struct object_id head;
445 /* Do nothing on a single-pick */
446 if (!file_exists(git_path_seq_dir()))
449 if (!get_oid("HEAD", &head))
450 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
452 write_file(git_path_abort_safety_file(), "%s", "");
455 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
456 int unborn, struct replay_opts *opts)
458 struct ref_transaction *transaction;
459 struct strbuf sb = STRBUF_INIT;
460 struct strbuf err = STRBUF_INIT;
463 if (checkout_fast_forward(from, to, 1))
464 return -1; /* the callee should have complained already */
466 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
468 transaction = ref_transaction_begin(&err);
470 ref_transaction_update(transaction, "HEAD",
471 to, unborn ? &null_oid : from,
473 ref_transaction_commit(transaction, &err)) {
474 ref_transaction_free(transaction);
475 error("%s", err.buf);
477 strbuf_release(&err);
482 strbuf_release(&err);
483 ref_transaction_free(transaction);
484 update_abort_safety_file();
488 void append_conflicts_hint(struct strbuf *msgbuf)
492 strbuf_addch(msgbuf, '\n');
493 strbuf_commented_addf(msgbuf, "Conflicts:\n");
494 for (i = 0; i < active_nr;) {
495 const struct cache_entry *ce = active_cache[i++];
497 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
498 while (i < active_nr && !strcmp(ce->name,
499 active_cache[i]->name))
505 static int do_recursive_merge(struct commit *base, struct commit *next,
506 const char *base_label, const char *next_label,
507 struct object_id *head, struct strbuf *msgbuf,
508 struct replay_opts *opts)
510 struct merge_options o;
511 struct tree *result, *next_tree, *base_tree, *head_tree;
514 struct lock_file index_lock = LOCK_INIT;
516 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
521 init_merge_options(&o);
522 o.ancestor = base ? base_label : "(empty tree)";
524 o.branch2 = next ? next_label : "(empty tree)";
525 if (is_rebase_i(opts))
527 o.show_rename_progress = 1;
529 head_tree = parse_tree_indirect(head);
530 next_tree = next ? next->tree : empty_tree();
531 base_tree = base ? base->tree : empty_tree();
533 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
534 parse_merge_opt(&o, *xopt);
536 clean = merge_trees(&o,
538 next_tree, base_tree, &result);
539 if (is_rebase_i(opts) && clean <= 0)
540 fputs(o.obuf.buf, stdout);
541 strbuf_release(&o.obuf);
542 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
544 rollback_lock_file(&index_lock);
548 if (write_locked_index(&the_index, &index_lock,
549 COMMIT_LOCK | SKIP_IF_UNCHANGED))
551 * TRANSLATORS: %s will be "revert", "cherry-pick" or
554 return error(_("%s: Unable to write new index file"),
555 _(action_name(opts)));
558 append_conflicts_hint(msgbuf);
563 static int is_index_unchanged(void)
565 struct object_id head_oid;
566 struct commit *head_commit;
568 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
569 return error(_("could not resolve HEAD commit"));
571 head_commit = lookup_commit(&head_oid);
574 * If head_commit is NULL, check_commit, called from
575 * lookup_commit, would have indicated that head_commit is not
576 * a commit object already. parse_commit() will return failure
577 * without further complaints in such a case. Otherwise, if
578 * the commit is invalid, parse_commit() will complain. So
579 * there is nothing for us to say here. Just return failure.
581 if (parse_commit(head_commit))
584 if (!active_cache_tree)
585 active_cache_tree = cache_tree();
587 if (!cache_tree_fully_valid(active_cache_tree))
588 if (cache_tree_update(&the_index, 0))
589 return error(_("unable to update cache tree"));
591 return !oidcmp(&active_cache_tree->oid,
592 &head_commit->tree->object.oid);
595 static int write_author_script(const char *message)
597 struct strbuf buf = STRBUF_INIT;
602 if (!*message || starts_with(message, "\n")) {
604 /* Missing 'author' line? */
605 unlink(rebase_path_author_script());
607 } else if (skip_prefix(message, "author ", &message))
609 else if ((eol = strchr(message, '\n')))
614 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
615 while (*message && *message != '\n' && *message != '\r')
616 if (skip_prefix(message, " <", &message))
618 else if (*message != '\'')
619 strbuf_addch(&buf, *(message++));
621 strbuf_addf(&buf, "'\\\\%c'", *(message++));
622 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
623 while (*message && *message != '\n' && *message != '\r')
624 if (skip_prefix(message, "> ", &message))
626 else if (*message != '\'')
627 strbuf_addch(&buf, *(message++));
629 strbuf_addf(&buf, "'\\\\%c'", *(message++));
630 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
631 while (*message && *message != '\n' && *message != '\r')
632 if (*message != '\'')
633 strbuf_addch(&buf, *(message++));
635 strbuf_addf(&buf, "'\\\\%c'", *(message++));
636 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
637 strbuf_release(&buf);
642 * Read a list of environment variable assignments (such as the author-script
643 * file) into an environment block. Returns -1 on error, 0 otherwise.
645 static int read_env_script(struct argv_array *env)
647 struct strbuf script = STRBUF_INIT;
651 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
654 for (p = script.buf; *p; p++)
655 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
656 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
658 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
659 else if (*p == '\n') {
664 for (i = 0, p = script.buf; i < count; i++) {
665 argv_array_push(env, p);
672 static char *get_author(const char *message)
677 a = find_commit_header(message, "author", &len);
679 return xmemdupz(a, len);
684 static const char staged_changes_advice[] =
685 N_("you have staged changes in your working tree\n"
686 "If these changes are meant to be squashed into the previous commit, run:\n"
688 " git commit --amend %s\n"
690 "If they are meant to go into a new commit, run:\n"
694 "In both cases, once you're done, continue with:\n"
696 " git rebase --continue\n");
698 #define ALLOW_EMPTY (1<<0)
699 #define EDIT_MSG (1<<1)
700 #define AMEND_MSG (1<<2)
701 #define CLEANUP_MSG (1<<3)
702 #define VERIFY_MSG (1<<4)
705 * If we are cherry-pick, and if the merge did not result in
706 * hand-editing, we will hit this commit and inherit the original
707 * author date and name.
709 * If we are revert, or if our cherry-pick results in a hand merge,
710 * we had better say that the current user is responsible for that.
712 * An exception is when run_git_commit() is called during an
713 * interactive rebase: in that case, we will want to retain the
716 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
719 struct child_process cmd = CHILD_PROCESS_INIT;
724 if (is_rebase_i(opts)) {
725 if (!(flags & EDIT_MSG)) {
726 cmd.stdout_to_stderr = 1;
730 if (read_env_script(&cmd.env_array)) {
731 const char *gpg_opt = gpg_sign_opt_quoted(opts);
733 return error(_(staged_changes_advice),
738 argv_array_push(&cmd.args, "commit");
740 if (!(flags & VERIFY_MSG))
741 argv_array_push(&cmd.args, "-n");
742 if ((flags & AMEND_MSG))
743 argv_array_push(&cmd.args, "--amend");
745 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
747 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
748 if ((flags & CLEANUP_MSG))
749 argv_array_push(&cmd.args, "--cleanup=strip");
750 if ((flags & EDIT_MSG))
751 argv_array_push(&cmd.args, "-e");
752 else if (!(flags & CLEANUP_MSG) &&
753 !opts->signoff && !opts->record_origin &&
754 git_config_get_value("commit.cleanup", &value))
755 argv_array_push(&cmd.args, "--cleanup=verbatim");
757 if ((flags & ALLOW_EMPTY))
758 argv_array_push(&cmd.args, "--allow-empty");
760 if (opts->allow_empty_message)
761 argv_array_push(&cmd.args, "--allow-empty-message");
764 /* hide stderr on success */
765 struct strbuf buf = STRBUF_INIT;
766 int rc = pipe_command(&cmd,
768 /* stdout is already redirected */
772 fputs(buf.buf, stderr);
773 strbuf_release(&buf);
777 return run_command(&cmd);
780 static int rest_is_empty(const struct strbuf *sb, int start)
785 /* Check if the rest is just whitespace and Signed-off-by's. */
786 for (i = start; i < sb->len; i++) {
787 nl = memchr(sb->buf + i, '\n', sb->len - i);
793 if (strlen(sign_off_header) <= eol - i &&
794 starts_with(sb->buf + i, sign_off_header)) {
799 if (!isspace(sb->buf[i++]))
807 * Find out if the message in the strbuf contains only whitespace and
808 * Signed-off-by lines.
810 int message_is_empty(const struct strbuf *sb,
811 enum commit_msg_cleanup_mode cleanup_mode)
813 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
815 return rest_is_empty(sb, 0);
819 * See if the user edited the message in the editor or left what
820 * was in the template intact
822 int template_untouched(const struct strbuf *sb, const char *template_file,
823 enum commit_msg_cleanup_mode cleanup_mode)
825 struct strbuf tmpl = STRBUF_INIT;
828 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
831 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
834 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
835 if (!skip_prefix(sb->buf, tmpl.buf, &start))
837 strbuf_release(&tmpl);
838 return rest_is_empty(sb, start - sb->buf);
841 int update_head_with_reflog(const struct commit *old_head,
842 const struct object_id *new_head,
843 const char *action, const struct strbuf *msg,
846 struct ref_transaction *transaction;
847 struct strbuf sb = STRBUF_INIT;
852 strbuf_addstr(&sb, action);
853 strbuf_addstr(&sb, ": ");
856 nl = strchr(msg->buf, '\n');
858 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
860 strbuf_addbuf(&sb, msg);
861 strbuf_addch(&sb, '\n');
864 transaction = ref_transaction_begin(err);
866 ref_transaction_update(transaction, "HEAD", new_head,
867 old_head ? &old_head->object.oid : &null_oid,
869 ref_transaction_commit(transaction, err)) {
872 ref_transaction_free(transaction);
878 static int run_rewrite_hook(const struct object_id *oldoid,
879 const struct object_id *newoid)
881 struct child_process proc = CHILD_PROCESS_INIT;
884 struct strbuf sb = STRBUF_INIT;
886 argv[0] = find_hook("post-rewrite");
895 proc.stdout_to_stderr = 1;
897 code = start_command(&proc);
900 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
901 sigchain_push(SIGPIPE, SIG_IGN);
902 write_in_full(proc.in, sb.buf, sb.len);
905 sigchain_pop(SIGPIPE);
906 return finish_command(&proc);
909 void commit_post_rewrite(const struct commit *old_head,
910 const struct object_id *new_head)
912 struct notes_rewrite_cfg *cfg;
914 cfg = init_copy_notes_for_rewrite("amend");
916 /* we are amending, so old_head is not NULL */
917 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
918 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
920 run_rewrite_hook(&old_head->object.oid, new_head);
923 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
925 struct argv_array hook_env = ARGV_ARRAY_INIT;
929 name = git_path_commit_editmsg();
930 if (write_message(msg->buf, msg->len, name, 0))
933 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
934 argv_array_push(&hook_env, "GIT_EDITOR=:");
936 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
937 "commit", commit, NULL);
939 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
942 ret = error(_("'prepare-commit-msg' hook failed"));
943 argv_array_clear(&hook_env);
948 static const char implicit_ident_advice_noconfig[] =
949 N_("Your name and email address were configured automatically based\n"
950 "on your username and hostname. Please check that they are accurate.\n"
951 "You can suppress this message by setting them explicitly. Run the\n"
952 "following command and follow the instructions in your editor to edit\n"
953 "your configuration file:\n"
955 " git config --global --edit\n"
957 "After doing this, you may fix the identity used for this commit with:\n"
959 " git commit --amend --reset-author\n");
961 static const char implicit_ident_advice_config[] =
962 N_("Your name and email address were configured automatically based\n"
963 "on your username and hostname. Please check that they are accurate.\n"
964 "You can suppress this message by setting them explicitly:\n"
966 " git config --global user.name \"Your Name\"\n"
967 " git config --global user.email you@example.com\n"
969 "After doing this, you may fix the identity used for this commit with:\n"
971 " git commit --amend --reset-author\n");
973 static const char *implicit_ident_advice(void)
975 char *user_config = expand_user_path("~/.gitconfig", 0);
976 char *xdg_config = xdg_config_home("config");
977 int config_exists = file_exists(user_config) || file_exists(xdg_config);
983 return _(implicit_ident_advice_config);
985 return _(implicit_ident_advice_noconfig);
989 void print_commit_summary(const char *prefix, const struct object_id *oid,
993 struct commit *commit;
994 struct strbuf format = STRBUF_INIT;
996 struct pretty_print_context pctx = {0};
997 struct strbuf author_ident = STRBUF_INIT;
998 struct strbuf committer_ident = STRBUF_INIT;
1000 commit = lookup_commit(oid);
1002 die(_("couldn't look up newly created commit"));
1003 if (parse_commit(commit))
1004 die(_("could not parse newly created commit"));
1006 strbuf_addstr(&format, "format:%h] %s");
1008 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1009 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1010 if (strbuf_cmp(&author_ident, &committer_ident)) {
1011 strbuf_addstr(&format, "\n Author: ");
1012 strbuf_addbuf_percentquote(&format, &author_ident);
1014 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1015 struct strbuf date = STRBUF_INIT;
1017 format_commit_message(commit, "%ad", &date, &pctx);
1018 strbuf_addstr(&format, "\n Date: ");
1019 strbuf_addbuf_percentquote(&format, &date);
1020 strbuf_release(&date);
1022 if (!committer_ident_sufficiently_given()) {
1023 strbuf_addstr(&format, "\n Committer: ");
1024 strbuf_addbuf_percentquote(&format, &committer_ident);
1025 if (advice_implicit_identity) {
1026 strbuf_addch(&format, '\n');
1027 strbuf_addstr(&format, implicit_ident_advice());
1030 strbuf_release(&author_ident);
1031 strbuf_release(&committer_ident);
1033 init_revisions(&rev, prefix);
1034 setup_revisions(0, NULL, &rev, NULL);
1037 rev.diffopt.output_format =
1038 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1040 rev.verbose_header = 1;
1041 rev.show_root_diff = 1;
1042 get_commit_format(format.buf, &rev);
1043 rev.always_show_header = 0;
1044 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1045 rev.diffopt.break_opt = 0;
1046 diff_setup_done(&rev.diffopt);
1048 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1050 die_errno(_("unable to resolve HEAD after creating commit"));
1051 if (!strcmp(head, "HEAD"))
1052 head = _("detached HEAD");
1054 skip_prefix(head, "refs/heads/", &head);
1055 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1056 _(" (root-commit)") : "");
1058 if (!log_tree_commit(&rev, commit)) {
1059 rev.always_show_header = 1;
1060 rev.use_terminator = 1;
1061 log_tree_commit(&rev, commit);
1064 strbuf_release(&format);
1067 static int parse_head(struct commit **head)
1069 struct commit *current_head;
1070 struct object_id oid;
1072 if (get_oid("HEAD", &oid)) {
1073 current_head = NULL;
1075 current_head = lookup_commit_reference(&oid);
1077 return error(_("could not parse HEAD"));
1078 if (oidcmp(&oid, ¤t_head->object.oid)) {
1079 warning(_("HEAD %s is not a commit!"),
1082 if (parse_commit(current_head))
1083 return error(_("could not parse HEAD commit"));
1085 *head = current_head;
1091 * Try to commit without forking 'git commit'. In some cases we need
1092 * to run 'git commit' to display an error message
1095 * -1 - error unable to commit
1097 * 1 - run 'git commit'
1099 static int try_to_commit(struct strbuf *msg, const char *author,
1100 struct replay_opts *opts, unsigned int flags,
1101 struct object_id *oid)
1103 struct object_id tree;
1104 struct commit *current_head;
1105 struct commit_list *parents = NULL;
1106 struct commit_extra_header *extra = NULL;
1107 struct strbuf err = STRBUF_INIT;
1108 struct strbuf commit_msg = STRBUF_INIT;
1109 char *amend_author = NULL;
1110 const char *hook_commit = NULL;
1111 enum commit_msg_cleanup_mode cleanup;
1114 if (parse_head(¤t_head))
1117 if (flags & AMEND_MSG) {
1118 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1119 const char *out_enc = get_commit_output_encoding();
1120 const char *message = logmsg_reencode(current_head, NULL,
1124 const char *orig_message = NULL;
1126 find_commit_subject(message, &orig_message);
1128 strbuf_addstr(msg, orig_message);
1129 hook_commit = "HEAD";
1131 author = amend_author = get_author(message);
1132 unuse_commit_buffer(current_head, message);
1134 res = error(_("unable to parse commit author"));
1137 parents = copy_commit_list(current_head->parents);
1138 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1139 } else if (current_head) {
1140 commit_list_insert(current_head, &parents);
1143 if (write_cache_as_tree(&tree, 0, NULL)) {
1144 res = error(_("git write-tree failed to write a tree"));
1148 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1149 ¤t_head->tree->object.oid :
1150 &empty_tree_oid, &tree)) {
1151 res = 1; /* run 'git commit' to display error message */
1155 if (find_hook("prepare-commit-msg")) {
1156 res = run_prepare_commit_msg_hook(msg, hook_commit);
1159 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1161 res = error_errno(_("unable to read commit message "
1163 git_path_commit_editmsg());
1169 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1170 opts->default_msg_cleanup;
1172 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1173 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1174 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1175 res = 1; /* run 'git commit' to display error message */
1179 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1180 oid, author, opts->gpg_sign, extra)) {
1181 res = error(_("failed to write commit object"));
1185 if (update_head_with_reflog(current_head, oid,
1186 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1187 res = error("%s", err.buf);
1191 if (flags & AMEND_MSG)
1192 commit_post_rewrite(current_head, oid);
1195 free_commit_extra_headers(extra);
1196 strbuf_release(&err);
1197 strbuf_release(&commit_msg);
1203 static int do_commit(const char *msg_file, const char *author,
1204 struct replay_opts *opts, unsigned int flags)
1208 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1209 struct object_id oid;
1210 struct strbuf sb = STRBUF_INIT;
1212 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1213 return error_errno(_("unable to read commit message "
1217 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1219 strbuf_release(&sb);
1221 unlink(git_path_cherry_pick_head());
1222 unlink(git_path_merge_msg());
1223 if (!is_rebase_i(opts))
1224 print_commit_summary(NULL, &oid,
1225 SUMMARY_SHOW_AUTHOR_DATE);
1230 return run_git_commit(msg_file, opts, flags);
1235 static int is_original_commit_empty(struct commit *commit)
1237 const struct object_id *ptree_oid;
1239 if (parse_commit(commit))
1240 return error(_("could not parse commit %s"),
1241 oid_to_hex(&commit->object.oid));
1242 if (commit->parents) {
1243 struct commit *parent = commit->parents->item;
1244 if (parse_commit(parent))
1245 return error(_("could not parse parent commit %s"),
1246 oid_to_hex(&parent->object.oid));
1247 ptree_oid = &parent->tree->object.oid;
1249 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1252 return !oidcmp(ptree_oid, &commit->tree->object.oid);
1256 * Do we run "git commit" with "--allow-empty"?
1258 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1260 int index_unchanged, empty_commit;
1265 * (1) we do not allow empty at all and error out.
1267 * (2) we allow ones that were initially empty, but
1268 * forbid the ones that become empty;
1270 * (3) we allow both.
1272 if (!opts->allow_empty)
1273 return 0; /* let "git commit" barf as necessary */
1275 index_unchanged = is_index_unchanged();
1276 if (index_unchanged < 0)
1277 return index_unchanged;
1278 if (!index_unchanged)
1279 return 0; /* we do not have to say --allow-empty */
1281 if (opts->keep_redundant_commits)
1284 empty_commit = is_original_commit_empty(commit);
1285 if (empty_commit < 0)
1286 return empty_commit;
1294 * Note that ordering matters in this enum. Not only must it match the mapping
1295 * below, it is also divided into several sections that matter. When adding
1296 * new commands, make sure you add it in the right section.
1299 /* commands that handle commits */
1306 /* commands that do something else than handling a single commit */
1311 /* commands that do nothing but are counted for reporting progress */
1314 /* comments (not counted for reporting progress) */
1321 } todo_command_info[] = {
1337 static const char *command_to_string(const enum todo_command command)
1339 if (command < TODO_COMMENT)
1340 return todo_command_info[command].str;
1341 die("Unknown command: %d", command);
1344 static char command_to_char(const enum todo_command command)
1346 if (command < TODO_COMMENT && todo_command_info[command].c)
1347 return todo_command_info[command].c;
1348 return comment_line_char;
1351 static int is_noop(const enum todo_command command)
1353 return TODO_NOOP <= command;
1356 static int is_fixup(enum todo_command command)
1358 return command == TODO_FIXUP || command == TODO_SQUASH;
1361 static int update_squash_messages(enum todo_command command,
1362 struct commit *commit, struct replay_opts *opts)
1364 struct strbuf buf = STRBUF_INIT;
1366 const char *message, *body;
1368 if (file_exists(rebase_path_squash_msg())) {
1369 struct strbuf header = STRBUF_INIT;
1372 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1373 return error(_("could not read '%s'"),
1374 rebase_path_squash_msg());
1377 eol = strchrnul(buf.buf, '\n');
1378 if (buf.buf[0] != comment_line_char ||
1379 (p += strcspn(p, "0123456789\n")) == eol)
1380 return error(_("unexpected 1st line of squash message:"
1382 (int)(eol - buf.buf), buf.buf);
1383 count = strtol(p, NULL, 10);
1386 return error(_("invalid 1st line of squash message:\n"
1388 (int)(eol - buf.buf), buf.buf);
1390 strbuf_addf(&header, "%c ", comment_line_char);
1391 strbuf_addf(&header,
1392 _("This is a combination of %d commits."), ++count);
1393 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1394 strbuf_release(&header);
1396 struct object_id head;
1397 struct commit *head_commit;
1398 const char *head_message, *body;
1400 if (get_oid("HEAD", &head))
1401 return error(_("need a HEAD to fixup"));
1402 if (!(head_commit = lookup_commit_reference(&head)))
1403 return error(_("could not read HEAD"));
1404 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1405 return error(_("could not read HEAD's commit message"));
1407 find_commit_subject(head_message, &body);
1408 if (write_message(body, strlen(body),
1409 rebase_path_fixup_msg(), 0)) {
1410 unuse_commit_buffer(head_commit, head_message);
1411 return error(_("cannot write '%s'"),
1412 rebase_path_fixup_msg());
1416 strbuf_addf(&buf, "%c ", comment_line_char);
1417 strbuf_addf(&buf, _("This is a combination of %d commits."),
1419 strbuf_addf(&buf, "\n%c ", comment_line_char);
1420 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1421 strbuf_addstr(&buf, "\n\n");
1422 strbuf_addstr(&buf, body);
1424 unuse_commit_buffer(head_commit, head_message);
1427 if (!(message = get_commit_buffer(commit, NULL)))
1428 return error(_("could not read commit message of %s"),
1429 oid_to_hex(&commit->object.oid));
1430 find_commit_subject(message, &body);
1432 if (command == TODO_SQUASH) {
1433 unlink(rebase_path_fixup_msg());
1434 strbuf_addf(&buf, "\n%c ", comment_line_char);
1435 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1436 strbuf_addstr(&buf, "\n\n");
1437 strbuf_addstr(&buf, body);
1438 } else if (command == TODO_FIXUP) {
1439 strbuf_addf(&buf, "\n%c ", comment_line_char);
1440 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1442 strbuf_addstr(&buf, "\n\n");
1443 strbuf_add_commented_lines(&buf, body, strlen(body));
1445 return error(_("unknown command: %d"), command);
1446 unuse_commit_buffer(commit, message);
1448 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1449 strbuf_release(&buf);
1453 static void flush_rewritten_pending(void) {
1454 struct strbuf buf = STRBUF_INIT;
1455 struct object_id newoid;
1458 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1459 !get_oid("HEAD", &newoid) &&
1460 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1461 char *bol = buf.buf, *eol;
1464 eol = strchrnul(bol, '\n');
1465 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1466 bol, oid_to_hex(&newoid));
1472 unlink(rebase_path_rewritten_pending());
1474 strbuf_release(&buf);
1477 static void record_in_rewritten(struct object_id *oid,
1478 enum todo_command next_command) {
1479 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1484 fprintf(out, "%s\n", oid_to_hex(oid));
1487 if (!is_fixup(next_command))
1488 flush_rewritten_pending();
1491 static int do_pick_commit(enum todo_command command, struct commit *commit,
1492 struct replay_opts *opts, int final_fixup)
1494 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1495 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1496 struct object_id head;
1497 struct commit *base, *next, *parent;
1498 const char *base_label, *next_label;
1499 char *author = NULL;
1500 struct commit_message msg = { NULL, NULL, NULL, NULL };
1501 struct strbuf msgbuf = STRBUF_INIT;
1502 int res, unborn = 0, allow;
1504 if (opts->no_commit) {
1506 * We do not intend to commit immediately. We just want to
1507 * merge the differences in, so let's compute the tree
1508 * that represents the "current" state for merge-recursive
1511 if (write_cache_as_tree(&head, 0, NULL))
1512 return error(_("your index file is unmerged."));
1514 unborn = get_oid("HEAD", &head);
1516 oidcpy(&head, the_hash_algo->empty_tree);
1517 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1519 return error_dirty_index(opts);
1523 if (!commit->parents)
1525 else if (commit->parents->next) {
1526 /* Reverting or cherry-picking a merge commit */
1528 struct commit_list *p;
1530 if (!opts->mainline)
1531 return error(_("commit %s is a merge but no -m option was given."),
1532 oid_to_hex(&commit->object.oid));
1534 for (cnt = 1, p = commit->parents;
1535 cnt != opts->mainline && p;
1538 if (cnt != opts->mainline || !p)
1539 return error(_("commit %s does not have parent %d"),
1540 oid_to_hex(&commit->object.oid), opts->mainline);
1542 } else if (0 < opts->mainline)
1543 return error(_("mainline was specified but commit %s is not a merge."),
1544 oid_to_hex(&commit->object.oid));
1546 parent = commit->parents->item;
1548 if (get_message(commit, &msg) != 0)
1549 return error(_("cannot get commit message for %s"),
1550 oid_to_hex(&commit->object.oid));
1552 if (opts->allow_ff && !is_fixup(command) &&
1553 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1554 (!parent && unborn))) {
1555 if (is_rebase_i(opts))
1556 write_author_script(msg.message);
1557 res = fast_forward_to(&commit->object.oid, &head, unborn,
1559 if (res || command != TODO_REWORD)
1561 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1563 goto fast_forward_edit;
1565 if (parent && parse_commit(parent) < 0)
1566 /* TRANSLATORS: The first %s will be a "todo" command like
1567 "revert" or "pick", the second %s a SHA1. */
1568 return error(_("%s: cannot parse parent commit %s"),
1569 command_to_string(command),
1570 oid_to_hex(&parent->object.oid));
1573 * "commit" is an existing commit. We would want to apply
1574 * the difference it introduces since its first parent "prev"
1575 * on top of the current HEAD if we are cherry-pick. Or the
1576 * reverse of it if we are revert.
1579 if (command == TODO_REVERT) {
1581 base_label = msg.label;
1583 next_label = msg.parent_label;
1584 strbuf_addstr(&msgbuf, "Revert \"");
1585 strbuf_addstr(&msgbuf, msg.subject);
1586 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1587 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1589 if (commit->parents && commit->parents->next) {
1590 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1591 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1593 strbuf_addstr(&msgbuf, ".\n");
1598 base_label = msg.parent_label;
1600 next_label = msg.label;
1602 /* Append the commit log message to msgbuf. */
1603 if (find_commit_subject(msg.message, &p))
1604 strbuf_addstr(&msgbuf, p);
1606 if (opts->record_origin) {
1607 strbuf_complete_line(&msgbuf);
1608 if (!has_conforming_footer(&msgbuf, NULL, 0))
1609 strbuf_addch(&msgbuf, '\n');
1610 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1611 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1612 strbuf_addstr(&msgbuf, ")\n");
1614 if (!is_fixup(command))
1615 author = get_author(msg.message);
1618 if (command == TODO_REWORD)
1619 flags |= EDIT_MSG | VERIFY_MSG;
1620 else if (is_fixup(command)) {
1621 if (update_squash_messages(command, commit, opts))
1625 msg_file = rebase_path_squash_msg();
1626 else if (file_exists(rebase_path_fixup_msg())) {
1627 flags |= CLEANUP_MSG;
1628 msg_file = rebase_path_fixup_msg();
1630 const char *dest = git_path_squash_msg();
1632 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1633 return error(_("could not rename '%s' to '%s'"),
1634 rebase_path_squash_msg(), dest);
1635 unlink(git_path_merge_msg());
1641 if (opts->signoff && !is_fixup(command))
1642 append_signoff(&msgbuf, 0, 0);
1644 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1646 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1647 res = do_recursive_merge(base, next, base_label, next_label,
1648 &head, &msgbuf, opts);
1651 res |= write_message(msgbuf.buf, msgbuf.len,
1652 git_path_merge_msg(), 0);
1654 struct commit_list *common = NULL;
1655 struct commit_list *remotes = NULL;
1657 res = write_message(msgbuf.buf, msgbuf.len,
1658 git_path_merge_msg(), 0);
1660 commit_list_insert(base, &common);
1661 commit_list_insert(next, &remotes);
1662 res |= try_merge_command(opts->strategy,
1663 opts->xopts_nr, (const char **)opts->xopts,
1664 common, oid_to_hex(&head), remotes);
1665 free_commit_list(common);
1666 free_commit_list(remotes);
1668 strbuf_release(&msgbuf);
1671 * If the merge was clean or if it failed due to conflict, we write
1672 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1673 * However, if the merge did not even start, then we don't want to
1676 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1677 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1678 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1680 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1681 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1682 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1686 error(command == TODO_REVERT
1687 ? _("could not revert %s... %s")
1688 : _("could not apply %s... %s"),
1689 short_commit_name(commit), msg.subject);
1690 print_advice(res == 1, opts);
1691 rerere(opts->allow_rerere_auto);
1695 allow = allow_empty(opts, commit);
1700 flags |= ALLOW_EMPTY;
1701 if (!opts->no_commit) {
1703 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1704 res = do_commit(msg_file, author, opts, flags);
1706 res = error(_("unable to parse commit author"));
1709 if (!res && final_fixup) {
1710 unlink(rebase_path_fixup_msg());
1711 unlink(rebase_path_squash_msg());
1715 free_message(commit, &msg);
1717 update_abort_safety_file();
1722 static int prepare_revs(struct replay_opts *opts)
1725 * picking (but not reverting) ranges (but not individual revisions)
1726 * should be done in reverse
1728 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1729 opts->revs->reverse ^= 1;
1731 if (prepare_revision_walk(opts->revs))
1732 return error(_("revision walk setup failed"));
1734 if (!opts->revs->commits)
1735 return error(_("empty commit set passed"));
1739 static int read_and_refresh_cache(struct replay_opts *opts)
1741 struct lock_file index_lock = LOCK_INIT;
1742 int index_fd = hold_locked_index(&index_lock, 0);
1743 if (read_index_preload(&the_index, NULL) < 0) {
1744 rollback_lock_file(&index_lock);
1745 return error(_("git %s: failed to read the index"),
1746 _(action_name(opts)));
1748 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1749 if (index_fd >= 0) {
1750 if (write_locked_index(&the_index, &index_lock,
1751 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1752 return error(_("git %s: failed to refresh the index"),
1753 _(action_name(opts)));
1759 enum todo_item_flags {
1760 TODO_EDIT_MERGE_MSG = 1
1764 enum todo_command command;
1765 struct commit *commit;
1769 size_t offset_in_buf;
1774 struct todo_item *items;
1775 int nr, alloc, current;
1776 int done_nr, total_nr;
1777 struct stat_data stat;
1780 #define TODO_LIST_INIT { STRBUF_INIT }
1782 static void todo_list_release(struct todo_list *todo_list)
1784 strbuf_release(&todo_list->buf);
1785 FREE_AND_NULL(todo_list->items);
1786 todo_list->nr = todo_list->alloc = 0;
1789 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1791 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1792 return todo_list->items + todo_list->nr++;
1795 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1797 struct object_id commit_oid;
1798 char *end_of_object_name;
1799 int i, saved, status, padding;
1804 bol += strspn(bol, " \t");
1806 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1807 item->command = TODO_COMMENT;
1808 item->commit = NULL;
1810 item->arg_len = eol - bol;
1814 for (i = 0; i < TODO_COMMENT; i++)
1815 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1818 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1823 if (i >= TODO_COMMENT)
1826 /* Eat up extra spaces/ tabs before object name */
1827 padding = strspn(bol, " \t");
1830 if (item->command == TODO_NOOP) {
1832 return error(_("%s does not accept arguments: '%s'"),
1833 command_to_string(item->command), bol);
1834 item->commit = NULL;
1836 item->arg_len = eol - bol;
1841 return error(_("missing arguments for %s"),
1842 command_to_string(item->command));
1844 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1845 item->command == TODO_RESET) {
1846 item->commit = NULL;
1848 item->arg_len = (int)(eol - bol);
1852 if (item->command == TODO_MERGE) {
1853 if (skip_prefix(bol, "-C", &bol))
1854 bol += strspn(bol, " \t");
1855 else if (skip_prefix(bol, "-c", &bol)) {
1856 bol += strspn(bol, " \t");
1857 item->flags |= TODO_EDIT_MERGE_MSG;
1859 item->flags |= TODO_EDIT_MERGE_MSG;
1860 item->commit = NULL;
1862 item->arg_len = (int)(eol - bol);
1867 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1868 saved = *end_of_object_name;
1869 *end_of_object_name = '\0';
1870 status = get_oid(bol, &commit_oid);
1871 *end_of_object_name = saved;
1873 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1874 item->arg_len = (int)(eol - item->arg);
1879 item->commit = lookup_commit_reference(&commit_oid);
1880 return !item->commit;
1883 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1885 struct todo_item *item;
1886 char *p = buf, *next_p;
1887 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1889 for (i = 1; *p; i++, p = next_p) {
1890 char *eol = strchrnul(p, '\n');
1892 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1894 if (p != eol && eol[-1] == '\r')
1895 eol--; /* strip Carriage Return */
1897 item = append_new_todo(todo_list);
1898 item->offset_in_buf = p - todo_list->buf.buf;
1899 if (parse_insn_line(item, p, eol)) {
1900 res = error(_("invalid line %d: %.*s"),
1901 i, (int)(eol - p), p);
1902 item->command = TODO_NOOP;
1907 else if (is_fixup(item->command))
1908 return error(_("cannot '%s' without a previous commit"),
1909 command_to_string(item->command));
1910 else if (!is_noop(item->command))
1917 static int count_commands(struct todo_list *todo_list)
1921 for (i = 0; i < todo_list->nr; i++)
1922 if (todo_list->items[i].command != TODO_COMMENT)
1928 static int get_item_line_offset(struct todo_list *todo_list, int index)
1930 return index < todo_list->nr ?
1931 todo_list->items[index].offset_in_buf : todo_list->buf.len;
1934 static const char *get_item_line(struct todo_list *todo_list, int index)
1936 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
1939 static int get_item_line_length(struct todo_list *todo_list, int index)
1941 return get_item_line_offset(todo_list, index + 1)
1942 - get_item_line_offset(todo_list, index);
1945 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
1950 fd = open(path, O_RDONLY);
1952 return error_errno(_("could not open '%s'"), path);
1953 len = strbuf_read(sb, fd, 0);
1956 return error(_("could not read '%s'."), path);
1960 static int read_populate_todo(struct todo_list *todo_list,
1961 struct replay_opts *opts)
1964 const char *todo_file = get_todo_path(opts);
1967 strbuf_reset(&todo_list->buf);
1968 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
1971 res = stat(todo_file, &st);
1973 return error(_("could not stat '%s'"), todo_file);
1974 fill_stat_data(&todo_list->stat, &st);
1976 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1978 if (is_rebase_i(opts))
1979 return error(_("please fix this using "
1980 "'git rebase --edit-todo'."));
1981 return error(_("unusable instruction sheet: '%s'"), todo_file);
1984 if (!todo_list->nr &&
1985 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1986 return error(_("no commits parsed."));
1988 if (!is_rebase_i(opts)) {
1989 enum todo_command valid =
1990 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1993 for (i = 0; i < todo_list->nr; i++)
1994 if (valid == todo_list->items[i].command)
1996 else if (valid == TODO_PICK)
1997 return error(_("cannot cherry-pick during a revert."));
1999 return error(_("cannot revert during a cherry-pick."));
2002 if (is_rebase_i(opts)) {
2003 struct todo_list done = TODO_LIST_INIT;
2004 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2006 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2007 !parse_insn_buffer(done.buf.buf, &done))
2008 todo_list->done_nr = count_commands(&done);
2010 todo_list->done_nr = 0;
2012 todo_list->total_nr = todo_list->done_nr
2013 + count_commands(todo_list);
2014 todo_list_release(&done);
2017 fprintf(f, "%d\n", todo_list->total_nr);
2025 static int git_config_string_dup(char **dest,
2026 const char *var, const char *value)
2029 return config_error_nonbool(var);
2031 *dest = xstrdup(value);
2035 static int populate_opts_cb(const char *key, const char *value, void *data)
2037 struct replay_opts *opts = data;
2042 else if (!strcmp(key, "options.no-commit"))
2043 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2044 else if (!strcmp(key, "options.edit"))
2045 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2046 else if (!strcmp(key, "options.signoff"))
2047 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2048 else if (!strcmp(key, "options.record-origin"))
2049 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2050 else if (!strcmp(key, "options.allow-ff"))
2051 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2052 else if (!strcmp(key, "options.mainline"))
2053 opts->mainline = git_config_int(key, value);
2054 else if (!strcmp(key, "options.strategy"))
2055 git_config_string_dup(&opts->strategy, key, value);
2056 else if (!strcmp(key, "options.gpg-sign"))
2057 git_config_string_dup(&opts->gpg_sign, key, value);
2058 else if (!strcmp(key, "options.strategy-option")) {
2059 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2060 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2061 } else if (!strcmp(key, "options.allow-rerere-auto"))
2062 opts->allow_rerere_auto =
2063 git_config_bool_or_int(key, value, &error_flag) ?
2064 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2066 return error(_("invalid key: %s"), key);
2069 return error(_("invalid value for %s: %s"), key, value);
2074 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2079 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2081 opts->strategy = strbuf_detach(buf, NULL);
2082 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2085 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2086 for (i = 0; i < opts->xopts_nr; i++) {
2087 const char *arg = opts->xopts[i];
2089 skip_prefix(arg, "--", &arg);
2090 opts->xopts[i] = xstrdup(arg);
2094 static int read_populate_opts(struct replay_opts *opts)
2096 if (is_rebase_i(opts)) {
2097 struct strbuf buf = STRBUF_INIT;
2099 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2100 if (!starts_with(buf.buf, "-S"))
2103 free(opts->gpg_sign);
2104 opts->gpg_sign = xstrdup(buf.buf + 2);
2109 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2110 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2111 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2112 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2113 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2117 if (file_exists(rebase_path_verbose()))
2120 if (file_exists(rebase_path_signoff())) {
2125 read_strategy_opts(opts, &buf);
2126 strbuf_release(&buf);
2131 if (!file_exists(git_path_opts_file()))
2134 * The function git_parse_source(), called from git_config_from_file(),
2135 * may die() in case of a syntactically incorrect file. We do not care
2136 * about this case, though, because we wrote that file ourselves, so we
2137 * are pretty certain that it is syntactically correct.
2139 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2140 return error(_("malformed options sheet: '%s'"),
2141 git_path_opts_file());
2145 static int walk_revs_populate_todo(struct todo_list *todo_list,
2146 struct replay_opts *opts)
2148 enum todo_command command = opts->action == REPLAY_PICK ?
2149 TODO_PICK : TODO_REVERT;
2150 const char *command_string = todo_command_info[command].str;
2151 struct commit *commit;
2153 if (prepare_revs(opts))
2156 while ((commit = get_revision(opts->revs))) {
2157 struct todo_item *item = append_new_todo(todo_list);
2158 const char *commit_buffer = get_commit_buffer(commit, NULL);
2159 const char *subject;
2162 item->command = command;
2163 item->commit = commit;
2166 item->offset_in_buf = todo_list->buf.len;
2167 subject_len = find_commit_subject(commit_buffer, &subject);
2168 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2169 short_commit_name(commit), subject_len, subject);
2170 unuse_commit_buffer(commit, commit_buffer);
2175 static int create_seq_dir(void)
2177 if (file_exists(git_path_seq_dir())) {
2178 error(_("a cherry-pick or revert is already in progress"));
2179 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2181 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2182 return error_errno(_("could not create sequencer directory '%s'"),
2183 git_path_seq_dir());
2187 static int save_head(const char *head)
2189 struct lock_file head_lock = LOCK_INIT;
2190 struct strbuf buf = STRBUF_INIT;
2194 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2196 return error_errno(_("could not lock HEAD"));
2197 strbuf_addf(&buf, "%s\n", head);
2198 written = write_in_full(fd, buf.buf, buf.len);
2199 strbuf_release(&buf);
2201 error_errno(_("could not write to '%s'"), git_path_head_file());
2202 rollback_lock_file(&head_lock);
2205 if (commit_lock_file(&head_lock) < 0)
2206 return error(_("failed to finalize '%s'"), git_path_head_file());
2210 static int rollback_is_safe(void)
2212 struct strbuf sb = STRBUF_INIT;
2213 struct object_id expected_head, actual_head;
2215 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2217 if (get_oid_hex(sb.buf, &expected_head)) {
2218 strbuf_release(&sb);
2219 die(_("could not parse %s"), git_path_abort_safety_file());
2221 strbuf_release(&sb);
2223 else if (errno == ENOENT)
2224 oidclr(&expected_head);
2226 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2228 if (get_oid("HEAD", &actual_head))
2229 oidclr(&actual_head);
2231 return !oidcmp(&actual_head, &expected_head);
2234 static int reset_for_rollback(const struct object_id *oid)
2236 const char *argv[4]; /* reset --merge <arg> + NULL */
2239 argv[1] = "--merge";
2240 argv[2] = oid_to_hex(oid);
2242 return run_command_v_opt(argv, RUN_GIT_CMD);
2245 static int rollback_single_pick(void)
2247 struct object_id head_oid;
2249 if (!file_exists(git_path_cherry_pick_head()) &&
2250 !file_exists(git_path_revert_head()))
2251 return error(_("no cherry-pick or revert in progress"));
2252 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2253 return error(_("cannot resolve HEAD"));
2254 if (is_null_oid(&head_oid))
2255 return error(_("cannot abort from a branch yet to be born"));
2256 return reset_for_rollback(&head_oid);
2259 int sequencer_rollback(struct replay_opts *opts)
2262 struct object_id oid;
2263 struct strbuf buf = STRBUF_INIT;
2266 f = fopen(git_path_head_file(), "r");
2267 if (!f && errno == ENOENT) {
2269 * There is no multiple-cherry-pick in progress.
2270 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2271 * a single-cherry-pick in progress, abort that.
2273 return rollback_single_pick();
2276 return error_errno(_("cannot open '%s'"), git_path_head_file());
2277 if (strbuf_getline_lf(&buf, f)) {
2278 error(_("cannot read '%s': %s"), git_path_head_file(),
2279 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2284 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2285 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2286 git_path_head_file());
2289 if (is_null_oid(&oid)) {
2290 error(_("cannot abort from a branch yet to be born"));
2294 if (!rollback_is_safe()) {
2295 /* Do not error, just do not rollback */
2296 warning(_("You seem to have moved HEAD. "
2297 "Not rewinding, check your HEAD!"));
2299 if (reset_for_rollback(&oid))
2301 strbuf_release(&buf);
2302 return sequencer_remove_state(opts);
2304 strbuf_release(&buf);
2308 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2310 struct lock_file todo_lock = LOCK_INIT;
2311 const char *todo_path = get_todo_path(opts);
2312 int next = todo_list->current, offset, fd;
2315 * rebase -i writes "git-rebase-todo" without the currently executing
2316 * command, appending it to "done" instead.
2318 if (is_rebase_i(opts))
2321 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2323 return error_errno(_("could not lock '%s'"), todo_path);
2324 offset = get_item_line_offset(todo_list, next);
2325 if (write_in_full(fd, todo_list->buf.buf + offset,
2326 todo_list->buf.len - offset) < 0)
2327 return error_errno(_("could not write to '%s'"), todo_path);
2328 if (commit_lock_file(&todo_lock) < 0)
2329 return error(_("failed to finalize '%s'"), todo_path);
2331 if (is_rebase_i(opts) && next > 0) {
2332 const char *done = rebase_path_done();
2333 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2338 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2339 get_item_line_length(todo_list, next - 1))
2341 ret = error_errno(_("could not write to '%s'"), done);
2343 ret = error_errno(_("failed to finalize '%s'"), done);
2349 static int save_opts(struct replay_opts *opts)
2351 const char *opts_file = git_path_opts_file();
2354 if (opts->no_commit)
2355 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2357 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2359 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2360 if (opts->record_origin)
2361 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2363 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2364 if (opts->mainline) {
2365 struct strbuf buf = STRBUF_INIT;
2366 strbuf_addf(&buf, "%d", opts->mainline);
2367 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2368 strbuf_release(&buf);
2371 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2373 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2376 for (i = 0; i < opts->xopts_nr; i++)
2377 res |= git_config_set_multivar_in_file_gently(opts_file,
2378 "options.strategy-option",
2379 opts->xopts[i], "^$", 0);
2381 if (opts->allow_rerere_auto)
2382 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2383 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2388 static int make_patch(struct commit *commit, struct replay_opts *opts)
2390 struct strbuf buf = STRBUF_INIT;
2391 struct rev_info log_tree_opt;
2392 const char *subject, *p;
2395 p = short_commit_name(commit);
2396 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2398 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2399 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2400 res |= error(_("could not update %s"), "REBASE_HEAD");
2402 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2403 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2404 init_revisions(&log_tree_opt, NULL);
2405 log_tree_opt.abbrev = 0;
2406 log_tree_opt.diff = 1;
2407 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2408 log_tree_opt.disable_stdin = 1;
2409 log_tree_opt.no_commit_id = 1;
2410 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2411 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2412 if (!log_tree_opt.diffopt.file)
2413 res |= error_errno(_("could not open '%s'"), buf.buf);
2415 res |= log_tree_commit(&log_tree_opt, commit);
2416 fclose(log_tree_opt.diffopt.file);
2420 strbuf_addf(&buf, "%s/message", get_dir(opts));
2421 if (!file_exists(buf.buf)) {
2422 const char *commit_buffer = get_commit_buffer(commit, NULL);
2423 find_commit_subject(commit_buffer, &subject);
2424 res |= write_message(subject, strlen(subject), buf.buf, 1);
2425 unuse_commit_buffer(commit, commit_buffer);
2427 strbuf_release(&buf);
2432 static int intend_to_amend(void)
2434 struct object_id head;
2437 if (get_oid("HEAD", &head))
2438 return error(_("cannot read HEAD"));
2440 p = oid_to_hex(&head);
2441 return write_message(p, strlen(p), rebase_path_amend(), 1);
2444 static int error_with_patch(struct commit *commit,
2445 const char *subject, int subject_len,
2446 struct replay_opts *opts, int exit_code, int to_amend)
2448 if (make_patch(commit, opts))
2452 if (intend_to_amend())
2455 fprintf(stderr, "You can amend the commit now, with\n"
2457 " git commit --amend %s\n"
2459 "Once you are satisfied with your changes, run\n"
2461 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2462 } else if (exit_code)
2463 fprintf(stderr, "Could not apply %s... %.*s\n",
2464 short_commit_name(commit), subject_len, subject);
2469 static int error_failed_squash(struct commit *commit,
2470 struct replay_opts *opts, int subject_len, const char *subject)
2472 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2473 return error(_("could not rename '%s' to '%s'"),
2474 rebase_path_squash_msg(), rebase_path_message());
2475 unlink(rebase_path_fixup_msg());
2476 unlink(git_path_merge_msg());
2477 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2478 return error(_("could not copy '%s' to '%s'"),
2479 rebase_path_message(), git_path_merge_msg());
2480 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2483 static int do_exec(const char *command_line)
2485 struct argv_array child_env = ARGV_ARRAY_INIT;
2486 const char *child_argv[] = { NULL, NULL };
2489 fprintf(stderr, "Executing: %s\n", command_line);
2490 child_argv[0] = command_line;
2491 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2492 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2495 /* force re-reading of the cache */
2496 if (discard_cache() < 0 || read_cache() < 0)
2497 return error(_("could not read index"));
2499 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2502 warning(_("execution failed: %s\n%s"
2503 "You can fix the problem, and then run\n"
2505 " git rebase --continue\n"
2508 dirty ? N_("and made changes to the index and/or the "
2509 "working tree\n") : "");
2511 /* command not found */
2514 warning(_("execution succeeded: %s\nbut "
2515 "left changes to the index and/or the working tree\n"
2516 "Commit or stash your changes, and then run\n"
2518 " git rebase --continue\n"
2519 "\n"), command_line);
2523 argv_array_clear(&child_env);
2528 static int safe_append(const char *filename, const char *fmt, ...)
2531 struct lock_file lock = LOCK_INIT;
2532 int fd = hold_lock_file_for_update(&lock, filename,
2533 LOCK_REPORT_ON_ERROR);
2534 struct strbuf buf = STRBUF_INIT;
2539 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2540 error_errno(_("could not read '%s'"), filename);
2541 rollback_lock_file(&lock);
2544 strbuf_complete(&buf, '\n');
2546 strbuf_vaddf(&buf, fmt, ap);
2549 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2550 error_errno(_("could not write to '%s'"), filename);
2551 strbuf_release(&buf);
2552 rollback_lock_file(&lock);
2555 if (commit_lock_file(&lock) < 0) {
2556 strbuf_release(&buf);
2557 rollback_lock_file(&lock);
2558 return error(_("failed to finalize '%s'"), filename);
2561 strbuf_release(&buf);
2565 static int do_label(const char *name, int len)
2567 struct ref_store *refs = get_main_ref_store();
2568 struct ref_transaction *transaction;
2569 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2570 struct strbuf msg = STRBUF_INIT;
2572 struct object_id head_oid;
2574 if (len == 1 && *name == '#')
2575 return error("Illegal label name: '%.*s'", len, name);
2577 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2578 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2580 transaction = ref_store_transaction_begin(refs, &err);
2582 error("%s", err.buf);
2584 } else if (get_oid("HEAD", &head_oid)) {
2585 error(_("could not read HEAD"));
2587 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2588 NULL, 0, msg.buf, &err) < 0 ||
2589 ref_transaction_commit(transaction, &err)) {
2590 error("%s", err.buf);
2593 ref_transaction_free(transaction);
2594 strbuf_release(&err);
2595 strbuf_release(&msg);
2598 ret = safe_append(rebase_path_refs_to_delete(),
2599 "%s\n", ref_name.buf);
2600 strbuf_release(&ref_name);
2605 static const char *reflog_message(struct replay_opts *opts,
2606 const char *sub_action, const char *fmt, ...);
2608 static int do_reset(const char *name, int len, struct replay_opts *opts)
2610 struct strbuf ref_name = STRBUF_INIT;
2611 struct object_id oid;
2612 struct lock_file lock = LOCK_INIT;
2613 struct tree_desc desc;
2615 struct unpack_trees_options unpack_tree_opts;
2618 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2621 /* Determine the length of the label */
2622 for (i = 0; i < len; i++)
2623 if (isspace(name[i]))
2626 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2627 if (get_oid(ref_name.buf, &oid) &&
2628 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2629 error(_("could not read '%s'"), ref_name.buf);
2630 rollback_lock_file(&lock);
2631 strbuf_release(&ref_name);
2635 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2636 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2637 unpack_tree_opts.head_idx = 1;
2638 unpack_tree_opts.src_index = &the_index;
2639 unpack_tree_opts.dst_index = &the_index;
2640 unpack_tree_opts.fn = oneway_merge;
2641 unpack_tree_opts.merge = 1;
2642 unpack_tree_opts.update = 1;
2644 if (read_cache_unmerged()) {
2645 rollback_lock_file(&lock);
2646 strbuf_release(&ref_name);
2647 return error_resolve_conflict(_(action_name(opts)));
2650 if (!fill_tree_descriptor(&desc, &oid)) {
2651 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2652 rollback_lock_file(&lock);
2653 free((void *)desc.buffer);
2654 strbuf_release(&ref_name);
2658 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2659 rollback_lock_file(&lock);
2660 free((void *)desc.buffer);
2661 strbuf_release(&ref_name);
2665 tree = parse_tree_indirect(&oid);
2666 prime_cache_tree(&the_index, tree);
2668 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2669 ret = error(_("could not write index"));
2670 free((void *)desc.buffer);
2673 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2674 len, name), "HEAD", &oid,
2675 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2677 strbuf_release(&ref_name);
2681 static int do_merge(struct commit *commit, const char *arg, int arg_len,
2682 int flags, struct replay_opts *opts)
2684 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2685 EDIT_MSG | VERIFY_MSG : 0;
2686 struct strbuf ref_name = STRBUF_INIT;
2687 struct commit *head_commit, *merge_commit, *i;
2688 struct commit_list *bases, *j, *reversed = NULL;
2689 struct merge_options o;
2690 int merge_arg_len, oneline_offset, can_fast_forward, ret;
2691 static struct lock_file lock;
2694 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2699 head_commit = lookup_commit_reference_by_name("HEAD");
2701 ret = error(_("cannot merge without a current revision"));
2705 oneline_offset = arg_len;
2706 merge_arg_len = strcspn(arg, " \t\n");
2707 p = arg + merge_arg_len;
2708 p += strspn(p, " \t\n");
2709 if (*p == '#' && (!p[1] || isspace(p[1]))) {
2710 p += 1 + strspn(p + 1, " \t\n");
2711 oneline_offset = p - arg;
2712 } else if (p - arg < arg_len)
2713 BUG("octopus merges are not supported yet: '%s'", p);
2715 strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg);
2716 merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2717 if (!merge_commit) {
2718 /* fall back to non-rewritten ref or commit */
2719 strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0);
2720 merge_commit = lookup_commit_reference_by_name(ref_name.buf);
2723 if (!merge_commit) {
2724 ret = error(_("could not resolve '%s'"), ref_name.buf);
2729 const char *message = get_commit_buffer(commit, NULL);
2734 ret = error(_("could not get commit message of '%s'"),
2735 oid_to_hex(&commit->object.oid));
2738 write_author_script(message);
2739 find_commit_subject(message, &body);
2741 ret = write_message(body, len, git_path_merge_msg(), 0);
2742 unuse_commit_buffer(commit, message);
2744 error_errno(_("could not write '%s'"),
2745 git_path_merge_msg());
2749 struct strbuf buf = STRBUF_INIT;
2752 strbuf_addf(&buf, "author %s", git_author_info(0));
2753 write_author_script(buf.buf);
2756 if (oneline_offset < arg_len) {
2757 p = arg + oneline_offset;
2758 len = arg_len - oneline_offset;
2760 strbuf_addf(&buf, "Merge branch '%.*s'",
2761 merge_arg_len, arg);
2766 ret = write_message(p, len, git_path_merge_msg(), 0);
2767 strbuf_release(&buf);
2769 error_errno(_("could not write '%s'"),
2770 git_path_merge_msg());
2776 * If HEAD is not identical to the first parent of the original merge
2777 * commit, we cannot fast-forward.
2779 can_fast_forward = opts->allow_ff && commit && commit->parents &&
2780 !oidcmp(&commit->parents->item->object.oid,
2781 &head_commit->object.oid);
2784 * If the merge head is different from the original one, we cannot
2787 if (can_fast_forward) {
2788 struct commit_list *second_parent = commit->parents->next;
2790 if (second_parent && !second_parent->next &&
2791 oidcmp(&merge_commit->object.oid,
2792 &second_parent->item->object.oid))
2793 can_fast_forward = 0;
2796 if (can_fast_forward && commit->parents->next &&
2797 !commit->parents->next->next &&
2798 !oidcmp(&commit->parents->next->item->object.oid,
2799 &merge_commit->object.oid)) {
2800 rollback_lock_file(&lock);
2801 ret = fast_forward_to(&commit->object.oid,
2802 &head_commit->object.oid, 0, opts);
2806 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
2807 git_path_merge_head(), 0);
2808 write_message("no-ff", 5, git_path_merge_mode(), 0);
2810 bases = get_merge_bases(head_commit, merge_commit);
2811 for (j = bases; j; j = j->next)
2812 commit_list_insert(j->item, &reversed);
2813 free_commit_list(bases);
2816 init_merge_options(&o);
2818 o.branch2 = ref_name.buf;
2819 o.buffer_output = 2;
2821 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
2823 fputs(o.obuf.buf, stdout);
2824 strbuf_release(&o.obuf);
2826 error(_("could not even attempt to merge '%.*s'"),
2827 merge_arg_len, arg);
2831 * The return value of merge_recursive() is 1 on clean, and 0 on
2834 * Let's reverse that, so that do_merge() returns 0 upon success and
2835 * 1 upon failed merge (keeping the return value -1 for the cases where
2836 * we will want to reschedule the `merge` command).
2840 if (active_cache_changed &&
2841 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
2842 ret = error(_("merge: Unable to write new index file"));
2846 rollback_lock_file(&lock);
2848 rerere(opts->allow_rerere_auto);
2851 * In case of problems, we now want to return a positive
2852 * value (a negative one would indicate that the `merge`
2853 * command needs to be rescheduled).
2855 ret = !!run_git_commit(git_path_merge_msg(), opts,
2859 strbuf_release(&ref_name);
2860 rollback_lock_file(&lock);
2864 static int is_final_fixup(struct todo_list *todo_list)
2866 int i = todo_list->current;
2868 if (!is_fixup(todo_list->items[i].command))
2871 while (++i < todo_list->nr)
2872 if (is_fixup(todo_list->items[i].command))
2874 else if (!is_noop(todo_list->items[i].command))
2879 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2883 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2884 if (!is_noop(todo_list->items[i].command))
2885 return todo_list->items[i].command;
2890 static int apply_autostash(struct replay_opts *opts)
2892 struct strbuf stash_sha1 = STRBUF_INIT;
2893 struct child_process child = CHILD_PROCESS_INIT;
2896 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2897 strbuf_release(&stash_sha1);
2900 strbuf_trim(&stash_sha1);
2903 child.no_stdout = 1;
2904 child.no_stderr = 1;
2905 argv_array_push(&child.args, "stash");
2906 argv_array_push(&child.args, "apply");
2907 argv_array_push(&child.args, stash_sha1.buf);
2908 if (!run_command(&child))
2909 fprintf(stderr, _("Applied autostash.\n"));
2911 struct child_process store = CHILD_PROCESS_INIT;
2914 argv_array_push(&store.args, "stash");
2915 argv_array_push(&store.args, "store");
2916 argv_array_push(&store.args, "-m");
2917 argv_array_push(&store.args, "autostash");
2918 argv_array_push(&store.args, "-q");
2919 argv_array_push(&store.args, stash_sha1.buf);
2920 if (run_command(&store))
2921 ret = error(_("cannot store %s"), stash_sha1.buf);
2924 _("Applying autostash resulted in conflicts.\n"
2925 "Your changes are safe in the stash.\n"
2926 "You can run \"git stash pop\" or"
2927 " \"git stash drop\" at any time.\n"));
2930 strbuf_release(&stash_sha1);
2934 static const char *reflog_message(struct replay_opts *opts,
2935 const char *sub_action, const char *fmt, ...)
2938 static struct strbuf buf = STRBUF_INIT;
2942 strbuf_addstr(&buf, action_name(opts));
2944 strbuf_addf(&buf, " (%s)", sub_action);
2946 strbuf_addstr(&buf, ": ");
2947 strbuf_vaddf(&buf, fmt, ap);
2954 static const char rescheduled_advice[] =
2955 N_("Could not execute the todo command\n"
2959 "It has been rescheduled; To edit the command before continuing, please\n"
2960 "edit the todo list first:\n"
2962 " git rebase --edit-todo\n"
2963 " git rebase --continue\n");
2965 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2967 int res = 0, reschedule = 0;
2969 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2971 assert(!(opts->signoff || opts->no_commit ||
2972 opts->record_origin || opts->edit));
2973 if (read_and_refresh_cache(opts))
2976 while (todo_list->current < todo_list->nr) {
2977 struct todo_item *item = todo_list->items + todo_list->current;
2978 if (save_todo(todo_list, opts))
2980 if (is_rebase_i(opts)) {
2981 if (item->command != TODO_COMMENT) {
2982 FILE *f = fopen(rebase_path_msgnum(), "w");
2984 todo_list->done_nr++;
2987 fprintf(f, "%d\n", todo_list->done_nr);
2990 fprintf(stderr, "Rebasing (%d/%d)%s",
2992 todo_list->total_nr,
2993 opts->verbose ? "\n" : "\r");
2995 unlink(rebase_path_message());
2996 unlink(rebase_path_author_script());
2997 unlink(rebase_path_stopped_sha());
2998 unlink(rebase_path_amend());
2999 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3001 if (item->command <= TODO_SQUASH) {
3002 if (is_rebase_i(opts))
3003 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3004 command_to_string(item->command), NULL),
3006 res = do_pick_commit(item->command, item->commit,
3007 opts, is_final_fixup(todo_list));
3008 if (is_rebase_i(opts) && res < 0) {
3010 advise(_(rescheduled_advice),
3011 get_item_line_length(todo_list,
3012 todo_list->current),
3013 get_item_line(todo_list,
3014 todo_list->current));
3015 todo_list->current--;
3016 if (save_todo(todo_list, opts))
3019 if (item->command == TODO_EDIT) {
3020 struct commit *commit = item->commit;
3023 _("Stopped at %s... %.*s\n"),
3024 short_commit_name(commit),
3025 item->arg_len, item->arg);
3026 return error_with_patch(commit,
3027 item->arg, item->arg_len, opts, res,
3030 if (is_rebase_i(opts) && !res)
3031 record_in_rewritten(&item->commit->object.oid,
3032 peek_command(todo_list, 1));
3033 if (res && is_fixup(item->command)) {
3036 return error_failed_squash(item->commit, opts,
3037 item->arg_len, item->arg);
3038 } else if (res && is_rebase_i(opts) && item->commit)
3039 return res | error_with_patch(item->commit,
3040 item->arg, item->arg_len, opts, res,
3041 item->command == TODO_REWORD);
3042 } else if (item->command == TODO_EXEC) {
3043 char *end_of_arg = (char *)(item->arg + item->arg_len);
3044 int saved = *end_of_arg;
3048 res = do_exec(item->arg);
3049 *end_of_arg = saved;
3051 /* Reread the todo file if it has changed. */
3053 ; /* fall through */
3054 else if (stat(get_todo_path(opts), &st))
3055 res = error_errno(_("could not stat '%s'"),
3056 get_todo_path(opts));
3057 else if (match_stat_data(&todo_list->stat, &st)) {
3058 todo_list_release(todo_list);
3059 if (read_populate_todo(todo_list, opts))
3060 res = -1; /* message was printed */
3061 /* `current` will be incremented below */
3062 todo_list->current = -1;
3064 } else if (item->command == TODO_LABEL) {
3065 if ((res = do_label(item->arg, item->arg_len)))
3067 } else if (item->command == TODO_RESET) {
3068 if ((res = do_reset(item->arg, item->arg_len, opts)))
3070 } else if (item->command == TODO_MERGE) {
3071 if ((res = do_merge(item->commit,
3072 item->arg, item->arg_len,
3073 item->flags, opts)) < 0)
3076 /* failed with merge conflicts */
3077 return error_with_patch(item->commit,
3079 item->arg_len, opts,
3081 } else if (!is_noop(item->command))
3082 return error(_("unknown command %d"), item->command);
3085 advise(_(rescheduled_advice),
3086 get_item_line_length(todo_list,
3087 todo_list->current),
3088 get_item_line(todo_list, todo_list->current));
3089 todo_list->current--;
3090 if (save_todo(todo_list, opts))
3093 return error_with_patch(item->commit,
3095 item->arg_len, opts,
3099 todo_list->current++;
3104 if (is_rebase_i(opts)) {
3105 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3108 /* Stopped in the middle, as planned? */
3109 if (todo_list->current < todo_list->nr)
3112 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3113 starts_with(head_ref.buf, "refs/")) {
3115 struct object_id head, orig;
3118 if (get_oid("HEAD", &head)) {
3119 res = error(_("cannot read HEAD"));
3121 strbuf_release(&head_ref);
3122 strbuf_release(&buf);
3125 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3126 get_oid_hex(buf.buf, &orig)) {
3127 res = error(_("could not read orig-head"));
3128 goto cleanup_head_ref;
3131 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3132 res = error(_("could not read 'onto'"));
3133 goto cleanup_head_ref;
3135 msg = reflog_message(opts, "finish", "%s onto %s",
3136 head_ref.buf, buf.buf);
3137 if (update_ref(msg, head_ref.buf, &head, &orig,
3138 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3139 res = error(_("could not update %s"),
3141 goto cleanup_head_ref;
3143 msg = reflog_message(opts, "finish", "returning to %s",
3145 if (create_symref("HEAD", head_ref.buf, msg)) {
3146 res = error(_("could not update HEAD to %s"),
3148 goto cleanup_head_ref;
3153 if (opts->verbose) {
3154 struct rev_info log_tree_opt;
3155 struct object_id orig, head;
3157 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3158 init_revisions(&log_tree_opt, NULL);
3159 log_tree_opt.diff = 1;
3160 log_tree_opt.diffopt.output_format =
3161 DIFF_FORMAT_DIFFSTAT;
3162 log_tree_opt.disable_stdin = 1;
3164 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3165 !get_oid(buf.buf, &orig) &&
3166 !get_oid("HEAD", &head)) {
3167 diff_tree_oid(&orig, &head, "",
3168 &log_tree_opt.diffopt);
3169 log_tree_diff_flush(&log_tree_opt);
3172 flush_rewritten_pending();
3173 if (!stat(rebase_path_rewritten_list(), &st) &&
3175 struct child_process child = CHILD_PROCESS_INIT;
3176 const char *post_rewrite_hook =
3177 find_hook("post-rewrite");
3179 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3181 argv_array_push(&child.args, "notes");
3182 argv_array_push(&child.args, "copy");
3183 argv_array_push(&child.args, "--for-rewrite=rebase");
3184 /* we don't care if this copying failed */
3185 run_command(&child);
3187 if (post_rewrite_hook) {
3188 struct child_process hook = CHILD_PROCESS_INIT;
3190 hook.in = open(rebase_path_rewritten_list(),
3192 hook.stdout_to_stderr = 1;
3193 argv_array_push(&hook.args, post_rewrite_hook);
3194 argv_array_push(&hook.args, "rebase");
3195 /* we don't care if this hook failed */
3199 apply_autostash(opts);
3201 fprintf(stderr, "Successfully rebased and updated %s.\n",
3204 strbuf_release(&buf);
3205 strbuf_release(&head_ref);
3209 * Sequence of picks finished successfully; cleanup by
3210 * removing the .git/sequencer directory
3212 return sequencer_remove_state(opts);
3215 static int continue_single_pick(void)
3217 const char *argv[] = { "commit", NULL };
3219 if (!file_exists(git_path_cherry_pick_head()) &&
3220 !file_exists(git_path_revert_head()))
3221 return error(_("no cherry-pick or revert in progress"));
3222 return run_command_v_opt(argv, RUN_GIT_CMD);
3225 static int commit_staged_changes(struct replay_opts *opts)
3227 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3229 if (has_unstaged_changes(1))
3230 return error(_("cannot rebase: You have unstaged changes."));
3231 if (!has_uncommitted_changes(0)) {
3232 const char *cherry_pick_head = git_path_cherry_pick_head();
3234 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3235 return error(_("could not remove CHERRY_PICK_HEAD"));
3239 if (file_exists(rebase_path_amend())) {
3240 struct strbuf rev = STRBUF_INIT;
3241 struct object_id head, to_amend;
3243 if (get_oid("HEAD", &head))
3244 return error(_("cannot amend non-existing commit"));
3245 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3246 return error(_("invalid file: '%s'"), rebase_path_amend());
3247 if (get_oid_hex(rev.buf, &to_amend))
3248 return error(_("invalid contents: '%s'"),
3249 rebase_path_amend());
3250 if (oidcmp(&head, &to_amend))
3251 return error(_("\nYou have uncommitted changes in your "
3252 "working tree. Please, commit them\n"
3253 "first and then run 'git rebase "
3254 "--continue' again."));
3256 strbuf_release(&rev);
3260 if (run_git_commit(rebase_path_message(), opts, flags))
3261 return error(_("could not commit staged changes."));
3262 unlink(rebase_path_amend());
3266 int sequencer_continue(struct replay_opts *opts)
3268 struct todo_list todo_list = TODO_LIST_INIT;
3271 if (read_and_refresh_cache(opts))
3274 if (is_rebase_i(opts)) {
3275 if (commit_staged_changes(opts))
3277 } else if (!file_exists(get_todo_path(opts)))
3278 return continue_single_pick();
3279 if (read_populate_opts(opts))
3281 if ((res = read_populate_todo(&todo_list, opts)))
3282 goto release_todo_list;
3284 if (!is_rebase_i(opts)) {
3285 /* Verify that the conflict has been resolved */
3286 if (file_exists(git_path_cherry_pick_head()) ||
3287 file_exists(git_path_revert_head())) {
3288 res = continue_single_pick();
3290 goto release_todo_list;
3292 if (index_differs_from("HEAD", NULL, 0)) {
3293 res = error_dirty_index(opts);
3294 goto release_todo_list;
3296 todo_list.current++;
3297 } else if (file_exists(rebase_path_stopped_sha())) {
3298 struct strbuf buf = STRBUF_INIT;
3299 struct object_id oid;
3301 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3302 !get_oid_committish(buf.buf, &oid))
3303 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3304 strbuf_release(&buf);
3307 res = pick_commits(&todo_list, opts);
3309 todo_list_release(&todo_list);
3313 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3315 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3316 return do_pick_commit(opts->action == REPLAY_PICK ?
3317 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3320 int sequencer_pick_revisions(struct replay_opts *opts)
3322 struct todo_list todo_list = TODO_LIST_INIT;
3323 struct object_id oid;
3327 if (read_and_refresh_cache(opts))
3330 for (i = 0; i < opts->revs->pending.nr; i++) {
3331 struct object_id oid;
3332 const char *name = opts->revs->pending.objects[i].name;
3334 /* This happens when using --stdin. */
3338 if (!get_oid(name, &oid)) {
3339 if (!lookup_commit_reference_gently(&oid, 1)) {
3340 enum object_type type = oid_object_info(&oid,
3342 return error(_("%s: can't cherry-pick a %s"),
3343 name, type_name(type));
3346 return error(_("%s: bad revision"), name);
3350 * If we were called as "git cherry-pick <commit>", just
3351 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3352 * REVERT_HEAD, and don't touch the sequencer state.
3353 * This means it is possible to cherry-pick in the middle
3354 * of a cherry-pick sequence.
3356 if (opts->revs->cmdline.nr == 1 &&
3357 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3358 opts->revs->no_walk &&
3359 !opts->revs->cmdline.rev->flags) {
3360 struct commit *cmit;
3361 if (prepare_revision_walk(opts->revs))
3362 return error(_("revision walk setup failed"));
3363 cmit = get_revision(opts->revs);
3364 if (!cmit || get_revision(opts->revs))
3365 return error("BUG: expected exactly one commit from walk");
3366 return single_pick(cmit, opts);
3370 * Start a new cherry-pick/ revert sequence; but
3371 * first, make sure that an existing one isn't in
3375 if (walk_revs_populate_todo(&todo_list, opts) ||
3376 create_seq_dir() < 0)
3378 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3379 return error(_("can't revert as initial commit"));
3380 if (save_head(oid_to_hex(&oid)))
3382 if (save_opts(opts))
3384 update_abort_safety_file();
3385 res = pick_commits(&todo_list, opts);
3386 todo_list_release(&todo_list);
3390 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3392 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3393 struct strbuf sob = STRBUF_INIT;
3396 strbuf_addstr(&sob, sign_off_header);
3397 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3398 getenv("GIT_COMMITTER_EMAIL")));
3399 strbuf_addch(&sob, '\n');
3402 strbuf_complete_line(msgbuf);
3405 * If the whole message buffer is equal to the sob, pretend that we
3406 * found a conforming footer with a matching sob
3408 if (msgbuf->len - ignore_footer == sob.len &&
3409 !strncmp(msgbuf->buf, sob.buf, sob.len))
3412 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3415 const char *append_newlines = NULL;
3416 size_t len = msgbuf->len - ignore_footer;
3420 * The buffer is completely empty. Leave foom for
3421 * the title and body to be filled in by the user.
3423 append_newlines = "\n\n";
3424 } else if (len == 1) {
3426 * Buffer contains a single newline. Add another
3427 * so that we leave room for the title and body.
3429 append_newlines = "\n";
3430 } else if (msgbuf->buf[len - 2] != '\n') {
3432 * Buffer ends with a single newline. Add another
3433 * so that there is an empty line between the message
3436 append_newlines = "\n";
3437 } /* else, the buffer already ends with two newlines. */
3439 if (append_newlines)
3440 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3441 append_newlines, strlen(append_newlines));
3444 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3445 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3448 strbuf_release(&sob);
3451 int sequencer_make_script(FILE *out, int argc, const char **argv,
3454 char *format = NULL;
3455 struct pretty_print_context pp = {0};
3456 struct strbuf buf = STRBUF_INIT;
3457 struct rev_info revs;
3458 struct commit *commit;
3459 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3460 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
3462 init_revisions(&revs, NULL);
3463 revs.verbose_header = 1;
3464 revs.max_parents = 1;
3465 revs.cherry_mark = 1;
3468 revs.right_only = 1;
3469 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3470 revs.topo_order = 1;
3472 revs.pretty_given = 1;
3473 git_config_get_string("rebase.instructionFormat", &format);
3474 if (!format || !*format) {
3476 format = xstrdup("%s");
3478 get_commit_format(format, &revs);
3480 pp.fmt = revs.commit_format;
3481 pp.output_encoding = get_log_output_encoding();
3483 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3484 return error(_("make_script: unhandled options"));
3486 if (prepare_revision_walk(&revs) < 0)
3487 return error(_("make_script: error preparing revisions"));
3489 while ((commit = get_revision(&revs))) {
3490 int is_empty = is_original_commit_empty(commit);
3492 if (!is_empty && (commit->object.flags & PATCHSAME))
3495 if (!keep_empty && is_empty)
3496 strbuf_addf(&buf, "%c ", comment_line_char);
3497 strbuf_addf(&buf, "%s %s ", insn,
3498 oid_to_hex(&commit->object.oid));
3499 pretty_print_commit(&pp, commit, &buf);
3500 strbuf_addch(&buf, '\n');
3501 fputs(buf.buf, out);
3503 strbuf_release(&buf);
3508 * Add commands after pick and (series of) squash/fixup commands
3511 int sequencer_add_exec_commands(const char *commands)
3513 const char *todo_file = rebase_path_todo();
3514 struct todo_list todo_list = TODO_LIST_INIT;
3515 struct todo_item *item;
3516 struct strbuf *buf = &todo_list.buf;
3517 size_t offset = 0, commands_len = strlen(commands);
3520 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3521 return error(_("could not read '%s'."), todo_file);
3523 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3524 todo_list_release(&todo_list);
3525 return error(_("unusable todo list: '%s'"), todo_file);
3529 /* insert <commands> before every pick except the first one */
3530 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3531 if (item->command == TODO_PICK && !first) {
3532 strbuf_insert(buf, item->offset_in_buf + offset,
3533 commands, commands_len);
3534 offset += commands_len;
3539 /* append final <commands> */
3540 strbuf_add(buf, commands, commands_len);
3542 i = write_message(buf->buf, buf->len, todo_file, 0);
3543 todo_list_release(&todo_list);
3547 int transform_todos(unsigned flags)
3549 const char *todo_file = rebase_path_todo();
3550 struct todo_list todo_list = TODO_LIST_INIT;
3551 struct strbuf buf = STRBUF_INIT;
3552 struct todo_item *item;
3555 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3556 return error(_("could not read '%s'."), todo_file);
3558 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3559 todo_list_release(&todo_list);
3560 return error(_("unusable todo list: '%s'"), todo_file);
3563 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3564 /* if the item is not a command write it and continue */
3565 if (item->command >= TODO_COMMENT) {
3566 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3570 /* add command to the buffer */
3571 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3572 strbuf_addch(&buf, command_to_char(item->command));
3574 strbuf_addstr(&buf, command_to_string(item->command));
3578 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3579 short_commit_name(item->commit) :
3580 oid_to_hex(&item->commit->object.oid);
3582 if (item->command == TODO_MERGE) {
3583 if (item->flags & TODO_EDIT_MERGE_MSG)
3584 strbuf_addstr(&buf, " -c");
3586 strbuf_addstr(&buf, " -C");
3589 strbuf_addf(&buf, " %s", oid);
3592 /* add all the rest */
3594 strbuf_addch(&buf, '\n');
3596 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3599 i = write_message(buf.buf, buf.len, todo_file, 0);
3600 todo_list_release(&todo_list);
3605 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3608 static enum check_level get_missing_commit_check_level(void)
3612 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3613 !strcasecmp("ignore", value))
3614 return CHECK_IGNORE;
3615 if (!strcasecmp("warn", value))
3617 if (!strcasecmp("error", value))
3619 warning(_("unrecognized setting %s for option "
3620 "rebase.missingCommitsCheck. Ignoring."), value);
3621 return CHECK_IGNORE;
3625 * Check if the user dropped some commits by mistake
3626 * Behaviour determined by rebase.missingCommitsCheck.
3627 * Check if there is an unrecognized command or a
3628 * bad SHA-1 in a command.
3630 int check_todo_list(void)
3632 enum check_level check_level = get_missing_commit_check_level();
3633 struct strbuf todo_file = STRBUF_INIT;
3634 struct todo_list todo_list = TODO_LIST_INIT;
3635 struct strbuf missing = STRBUF_INIT;
3636 int advise_to_edit_todo = 0, res = 0, i;
3638 strbuf_addstr(&todo_file, rebase_path_todo());
3639 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3643 advise_to_edit_todo = res =
3644 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3646 if (res || check_level == CHECK_IGNORE)
3649 /* Mark the commits in git-rebase-todo as seen */
3650 for (i = 0; i < todo_list.nr; i++) {
3651 struct commit *commit = todo_list.items[i].commit;
3653 commit->util = (void *)1;
3656 todo_list_release(&todo_list);
3657 strbuf_addstr(&todo_file, ".backup");
3658 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3662 strbuf_release(&todo_file);
3663 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3665 /* Find commits in git-rebase-todo.backup yet unseen */
3666 for (i = todo_list.nr - 1; i >= 0; i--) {
3667 struct todo_item *item = todo_list.items + i;
3668 struct commit *commit = item->commit;
3669 if (commit && !commit->util) {
3670 strbuf_addf(&missing, " - %s %.*s\n",
3671 short_commit_name(commit),
3672 item->arg_len, item->arg);
3673 commit->util = (void *)1;
3677 /* Warn about missing commits */
3681 if (check_level == CHECK_ERROR)
3682 advise_to_edit_todo = res = 1;
3685 _("Warning: some commits may have been dropped accidentally.\n"
3686 "Dropped commits (newer to older):\n"));
3688 /* Make the list user-friendly and display */
3689 fputs(missing.buf, stderr);
3690 strbuf_release(&missing);
3692 fprintf(stderr, _("To avoid this message, use \"drop\" to "
3693 "explicitly remove a commit.\n\n"
3694 "Use 'git config rebase.missingCommitsCheck' to change "
3695 "the level of warnings.\n"
3696 "The possible behaviours are: ignore, warn, error.\n\n"));
3699 strbuf_release(&todo_file);
3700 todo_list_release(&todo_list);
3702 if (advise_to_edit_todo)
3704 _("You can fix this with 'git rebase --edit-todo' "
3705 "and then run 'git rebase --continue'.\n"
3706 "Or you can abort the rebase with 'git rebase"
3712 static int rewrite_file(const char *path, const char *buf, size_t len)
3715 int fd = open(path, O_WRONLY | O_TRUNC);
3717 return error_errno(_("could not open '%s' for writing"), path);
3718 if (write_in_full(fd, buf, len) < 0)
3719 rc = error_errno(_("could not write to '%s'"), path);
3720 if (close(fd) && !rc)
3721 rc = error_errno(_("could not close '%s'"), path);
3725 /* skip picking commits whose parents are unchanged */
3726 int skip_unnecessary_picks(void)
3728 const char *todo_file = rebase_path_todo();
3729 struct strbuf buf = STRBUF_INIT;
3730 struct todo_list todo_list = TODO_LIST_INIT;
3731 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3734 if (!read_oneliner(&buf, rebase_path_onto(), 0))
3735 return error(_("could not read 'onto'"));
3736 if (get_oid(buf.buf, &onto_oid)) {
3737 strbuf_release(&buf);
3738 return error(_("need a HEAD to fixup"));
3740 strbuf_release(&buf);
3742 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
3744 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3745 todo_list_release(&todo_list);
3749 for (i = 0; i < todo_list.nr; i++) {
3750 struct todo_item *item = todo_list.items + i;
3752 if (item->command >= TODO_NOOP)
3754 if (item->command != TODO_PICK)
3756 if (parse_commit(item->commit)) {
3757 todo_list_release(&todo_list);
3758 return error(_("could not parse commit '%s'"),
3759 oid_to_hex(&item->commit->object.oid));
3761 if (!item->commit->parents)
3762 break; /* root commit */
3763 if (item->commit->parents->next)
3764 break; /* merge commit */
3765 parent_oid = &item->commit->parents->item->object.oid;
3766 if (hashcmp(parent_oid->hash, oid->hash))
3768 oid = &item->commit->object.oid;
3771 int offset = get_item_line_offset(&todo_list, i);
3772 const char *done_path = rebase_path_done();
3774 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3776 error_errno(_("could not open '%s' for writing"),
3778 todo_list_release(&todo_list);
3781 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3782 error_errno(_("could not write to '%s'"), done_path);
3783 todo_list_release(&todo_list);
3789 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
3790 todo_list.buf.len - offset) < 0) {
3791 todo_list_release(&todo_list);
3795 todo_list.current = i;
3796 if (is_fixup(peek_command(&todo_list, 0)))
3797 record_in_rewritten(oid, peek_command(&todo_list, 0));
3800 todo_list_release(&todo_list);
3801 printf("%s\n", oid_to_hex(oid));
3806 struct subject2item_entry {
3807 struct hashmap_entry entry;
3809 char subject[FLEX_ARRAY];
3812 static int subject2item_cmp(const void *fndata,
3813 const struct subject2item_entry *a,
3814 const struct subject2item_entry *b, const void *key)
3816 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3820 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3821 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3822 * after the former, and change "pick" to "fixup"/"squash".
3824 * Note that if the config has specified a custom instruction format, each log
3825 * message will have to be retrieved from the commit (as the oneline in the
3826 * script cannot be trusted) in order to normalize the autosquash arrangement.
3828 int rearrange_squash(void)
3830 const char *todo_file = rebase_path_todo();
3831 struct todo_list todo_list = TODO_LIST_INIT;
3832 struct hashmap subject2item;
3833 int res = 0, rearranged = 0, *next, *tail, i;
3836 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
3838 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3839 todo_list_release(&todo_list);
3844 * The hashmap maps onelines to the respective todo list index.
3846 * If any items need to be rearranged, the next[i] value will indicate
3847 * which item was moved directly after the i'th.
3849 * In that case, last[i] will indicate the index of the latest item to
3850 * be moved to appear after the i'th.
3852 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3853 NULL, todo_list.nr);
3854 ALLOC_ARRAY(next, todo_list.nr);
3855 ALLOC_ARRAY(tail, todo_list.nr);
3856 ALLOC_ARRAY(subjects, todo_list.nr);
3857 for (i = 0; i < todo_list.nr; i++) {
3858 struct strbuf buf = STRBUF_INIT;
3859 struct todo_item *item = todo_list.items + i;
3860 const char *commit_buffer, *subject, *p;
3863 struct subject2item_entry *entry;
3865 next[i] = tail[i] = -1;
3866 if (!item->commit || item->command == TODO_DROP) {
3871 if (is_fixup(item->command)) {
3872 todo_list_release(&todo_list);
3873 return error(_("the script was already rearranged."));
3876 item->commit->util = item;
3878 parse_commit(item->commit);
3879 commit_buffer = get_commit_buffer(item->commit, NULL);
3880 find_commit_subject(commit_buffer, &subject);
3881 format_subject(&buf, subject, " ");
3882 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3883 unuse_commit_buffer(item->commit, commit_buffer);
3884 if ((skip_prefix(subject, "fixup! ", &p) ||
3885 skip_prefix(subject, "squash! ", &p))) {
3886 struct commit *commit2;
3891 if (!skip_prefix(p, "fixup! ", &p) &&
3892 !skip_prefix(p, "squash! ", &p))
3896 if ((entry = hashmap_get_from_hash(&subject2item,
3898 /* found by title */
3900 else if (!strchr(p, ' ') &&
3902 lookup_commit_reference_by_name(p)) &&
3904 /* found by commit name */
3905 i2 = (struct todo_item *)commit2->util
3908 /* copy can be a prefix of the commit subject */
3909 for (i2 = 0; i2 < i; i2++)
3911 starts_with(subjects[i2], p))
3919 todo_list.items[i].command =
3920 starts_with(subject, "fixup!") ?
3921 TODO_FIXUP : TODO_SQUASH;
3927 } else if (!hashmap_get_from_hash(&subject2item,
3928 strhash(subject), subject)) {
3929 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3931 hashmap_entry_init(entry, strhash(entry->subject));
3932 hashmap_put(&subject2item, entry);
3937 struct strbuf buf = STRBUF_INIT;
3939 for (i = 0; i < todo_list.nr; i++) {
3940 enum todo_command command = todo_list.items[i].command;
3944 * Initially, all commands are 'pick's. If it is a
3945 * fixup or a squash now, we have rearranged it.
3947 if (is_fixup(command))
3952 get_item_line(&todo_list, cur);
3954 get_item_line(&todo_list, cur + 1);
3956 /* replace 'pick', by 'fixup' or 'squash' */
3957 command = todo_list.items[cur].command;
3958 if (is_fixup(command)) {
3960 todo_command_info[command].str);
3961 bol += strcspn(bol, " \t");
3964 strbuf_add(&buf, bol, eol - bol);
3970 res = rewrite_file(todo_file, buf.buf, buf.len);
3971 strbuf_release(&buf);
3976 for (i = 0; i < todo_list.nr; i++)
3979 hashmap_free(&subject2item, 1);
3980 todo_list_release(&todo_list);