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"
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
29 const char sign_off_header[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
32 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
34 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
36 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
37 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
38 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
39 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
41 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
43 * The file containing rebase commands, comments, and empty lines.
44 * This file is created by "git rebase -i" then edited by the user. As
45 * the lines are processed, they are removed from the front of this
46 * file and written to the tail of 'done'.
48 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
50 * The rebase command lines that have already been processed. A line
51 * is moved here when it is first handled, before any associated user
54 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
56 * The file to keep track of how many commands were already processed (e.g.
59 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
61 * The file to keep track of how many commands are to be processed in total
62 * (e.g. for the prompt).
64 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
66 * The commit message that is planned to be used for any changes that
67 * need to be committed following a user interaction.
69 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
71 * The file into which is accumulated the suggested commit message for
72 * squash/fixup commands. When the first of a series of squash/fixups
73 * is seen, the file is created and the commit message from the
74 * previous commit and from the first squash/fixup commit are written
75 * to it. The commit message for each subsequent squash/fixup commit
76 * is appended to the file as it is processed.
78 * The first line of the file is of the form
79 * # This is a combination of $count commits.
80 * where $count is the number of commits whose messages have been
81 * written to the file so far (including the initial "pick" commit).
82 * Each time that a commit message is processed, this line is read and
83 * updated. It is deleted just before the combined commit is made.
85 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
87 * If the current series of squash/fixups has not yet included a squash
88 * command, then this file exists and holds the commit message of the
89 * original "pick" commit. (If the series ends without a "squash"
90 * command, then this can be used as the commit message of the combined
91 * commit without opening the editor.)
93 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
95 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
96 * GIT_AUTHOR_DATE that will be used for the commit that is currently
99 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
101 * When an "edit" rebase command is being processed, the SHA1 of the
102 * commit to be edited is recorded in this file. When "git rebase
103 * --continue" is executed, if there are any staged changes then they
104 * will be amended to the HEAD commit, but only provided the HEAD
105 * commit is still the commit to be edited. When any other rebase
106 * command is processed, this file is deleted.
108 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
110 * When we stop at a given patch via the "edit" command, this file contains
111 * the abbreviated commit name of the corresponding patch.
113 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
115 * For the post-rewrite hook, we make a list of rewritten commits and
116 * their new sha1s. The rewritten-pending list keeps the sha1s of
117 * commits that have been processed, but not committed yet,
118 * e.g. because they are waiting for a 'squash' command.
120 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
121 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
122 "rebase-merge/rewritten-pending")
124 * The following files are written by git-rebase just after parsing the
125 * command-line (and are only consumed, not modified, by the sequencer).
127 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
128 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
129 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
130 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
131 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
132 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
133 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
134 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
135 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
136 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
138 static int git_sequencer_config(const char *k, const char *v, void *cb)
140 struct replay_opts *opts = cb;
143 if (!strcmp(k, "commit.cleanup")) {
146 status = git_config_string(&s, k, v);
150 if (!strcmp(s, "verbatim"))
151 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
152 else if (!strcmp(s, "whitespace"))
153 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
154 else if (!strcmp(s, "strip"))
155 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
156 else if (!strcmp(s, "scissors"))
157 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
159 warning(_("invalid commit message cleanup mode '%s'"),
165 if (!strcmp(k, "commit.gpgsign")) {
166 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
170 status = git_gpg_config(k, v, NULL);
174 return git_diff_basic_config(k, v, NULL);
177 void sequencer_init_config(struct replay_opts *opts)
179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
180 git_config(git_sequencer_config, opts);
183 static inline int is_rebase_i(const struct replay_opts *opts)
185 return opts->action == REPLAY_INTERACTIVE_REBASE;
188 static const char *get_dir(const struct replay_opts *opts)
190 if (is_rebase_i(opts))
191 return rebase_path();
192 return git_path_seq_dir();
195 static const char *get_todo_path(const struct replay_opts *opts)
197 if (is_rebase_i(opts))
198 return rebase_path_todo();
199 return git_path_todo_file();
203 * Returns 0 for non-conforming footer
204 * Returns 1 for conforming footer
205 * Returns 2 when sob exists within conforming footer
206 * Returns 3 when sob exists within conforming footer as last entry
208 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
211 struct trailer_info info;
213 int found_sob = 0, found_sob_last = 0;
215 trailer_info_get(&info, sb->buf);
217 if (info.trailer_start == info.trailer_end)
220 for (i = 0; i < info.trailer_nr; i++)
221 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
223 if (i == info.trailer_nr - 1)
227 trailer_info_release(&info);
236 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
238 static struct strbuf buf = STRBUF_INIT;
242 sq_quotef(&buf, "-S%s", opts->gpg_sign);
246 int sequencer_remove_state(struct replay_opts *opts)
248 struct strbuf dir = STRBUF_INIT;
251 free(opts->gpg_sign);
252 free(opts->strategy);
253 for (i = 0; i < opts->xopts_nr; i++)
254 free(opts->xopts[i]);
257 strbuf_addstr(&dir, get_dir(opts));
258 remove_dir_recursively(&dir, 0);
259 strbuf_release(&dir);
264 static const char *action_name(const struct replay_opts *opts)
266 switch (opts->action) {
270 return N_("cherry-pick");
271 case REPLAY_INTERACTIVE_REBASE:
272 return N_("rebase -i");
274 die(_("Unknown action: %d"), opts->action);
277 struct commit_message {
284 static const char *short_commit_name(struct commit *commit)
286 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
289 static int get_message(struct commit *commit, struct commit_message *out)
291 const char *abbrev, *subject;
294 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
295 abbrev = short_commit_name(commit);
297 subject_len = find_commit_subject(out->message, &subject);
299 out->subject = xmemdupz(subject, subject_len);
300 out->label = xstrfmt("%s... %s", abbrev, out->subject);
301 out->parent_label = xstrfmt("parent of %s", out->label);
306 static void free_message(struct commit *commit, struct commit_message *msg)
308 free(msg->parent_label);
311 unuse_commit_buffer(commit, msg->message);
314 static void print_advice(int show_hint, struct replay_opts *opts)
316 char *msg = getenv("GIT_CHERRY_PICK_HELP");
319 fprintf(stderr, "%s\n", msg);
321 * A conflict has occurred but the porcelain
322 * (typically rebase --interactive) wants to take care
323 * of the commit itself so remove CHERRY_PICK_HEAD
325 unlink(git_path_cherry_pick_head());
331 advise(_("after resolving the conflicts, mark the corrected paths\n"
332 "with 'git add <paths>' or 'git rm <paths>'"));
334 advise(_("after resolving the conflicts, mark the corrected paths\n"
335 "with 'git add <paths>' or 'git rm <paths>'\n"
336 "and commit the result with 'git commit'"));
340 static int write_message(const void *buf, size_t len, const char *filename,
343 struct lock_file msg_file = LOCK_INIT;
345 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
347 return error_errno(_("could not lock '%s'"), filename);
348 if (write_in_full(msg_fd, buf, len) < 0) {
349 error_errno(_("could not write to '%s'"), filename);
350 rollback_lock_file(&msg_file);
353 if (append_eol && write(msg_fd, "\n", 1) < 0) {
354 error_errno(_("could not write eol to '%s'"), filename);
355 rollback_lock_file(&msg_file);
358 if (commit_lock_file(&msg_file) < 0)
359 return error(_("failed to finalize '%s'"), filename);
365 * Reads a file that was presumably written by a shell script, i.e. with an
366 * end-of-line marker that needs to be stripped.
368 * Note that only the last end-of-line marker is stripped, consistent with the
369 * behavior of "$(cat path)" in a shell script.
371 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
373 static int read_oneliner(struct strbuf *buf,
374 const char *path, int skip_if_empty)
376 int orig_len = buf->len;
378 if (!file_exists(path))
381 if (strbuf_read_file(buf, path, 0) < 0) {
382 warning_errno(_("could not read '%s'"), path);
386 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
387 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
389 buf->buf[buf->len] = '\0';
392 if (skip_if_empty && buf->len == orig_len)
398 static struct tree *empty_tree(void)
400 return lookup_tree(the_hash_algo->empty_tree);
403 static int error_dirty_index(struct replay_opts *opts)
405 if (read_cache_unmerged())
406 return error_resolve_conflict(_(action_name(opts)));
408 error(_("your local changes would be overwritten by %s."),
409 _(action_name(opts)));
411 if (advice_commit_before_merge)
412 advise(_("commit your changes or stash them to proceed."));
416 static void update_abort_safety_file(void)
418 struct object_id head;
420 /* Do nothing on a single-pick */
421 if (!file_exists(git_path_seq_dir()))
424 if (!get_oid("HEAD", &head))
425 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
427 write_file(git_path_abort_safety_file(), "%s", "");
430 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
431 int unborn, struct replay_opts *opts)
433 struct ref_transaction *transaction;
434 struct strbuf sb = STRBUF_INIT;
435 struct strbuf err = STRBUF_INIT;
438 if (checkout_fast_forward(from, to, 1))
439 return -1; /* the callee should have complained already */
441 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
443 transaction = ref_transaction_begin(&err);
445 ref_transaction_update(transaction, "HEAD",
446 to, unborn ? &null_oid : from,
448 ref_transaction_commit(transaction, &err)) {
449 ref_transaction_free(transaction);
450 error("%s", err.buf);
452 strbuf_release(&err);
457 strbuf_release(&err);
458 ref_transaction_free(transaction);
459 update_abort_safety_file();
463 void append_conflicts_hint(struct strbuf *msgbuf)
467 strbuf_addch(msgbuf, '\n');
468 strbuf_commented_addf(msgbuf, "Conflicts:\n");
469 for (i = 0; i < active_nr;) {
470 const struct cache_entry *ce = active_cache[i++];
472 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
473 while (i < active_nr && !strcmp(ce->name,
474 active_cache[i]->name))
480 static int do_recursive_merge(struct commit *base, struct commit *next,
481 const char *base_label, const char *next_label,
482 struct object_id *head, struct strbuf *msgbuf,
483 struct replay_opts *opts)
485 struct merge_options o;
486 struct tree *result, *next_tree, *base_tree, *head_tree;
489 struct lock_file index_lock = LOCK_INIT;
491 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
496 init_merge_options(&o);
497 o.ancestor = base ? base_label : "(empty tree)";
499 o.branch2 = next ? next_label : "(empty tree)";
500 if (is_rebase_i(opts))
502 o.show_rename_progress = 1;
504 head_tree = parse_tree_indirect(head);
505 next_tree = next ? next->tree : empty_tree();
506 base_tree = base ? base->tree : empty_tree();
508 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
509 parse_merge_opt(&o, *xopt);
511 clean = merge_trees(&o,
513 next_tree, base_tree, &result);
514 if (is_rebase_i(opts) && clean <= 0)
515 fputs(o.obuf.buf, stdout);
516 strbuf_release(&o.obuf);
517 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
519 rollback_lock_file(&index_lock);
523 if (write_locked_index(&the_index, &index_lock,
524 COMMIT_LOCK | SKIP_IF_UNCHANGED))
526 * TRANSLATORS: %s will be "revert", "cherry-pick" or
529 return error(_("%s: Unable to write new index file"),
530 _(action_name(opts)));
533 append_conflicts_hint(msgbuf);
538 static int is_index_unchanged(void)
540 struct object_id head_oid;
541 struct commit *head_commit;
543 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
544 return error(_("could not resolve HEAD commit"));
546 head_commit = lookup_commit(&head_oid);
549 * If head_commit is NULL, check_commit, called from
550 * lookup_commit, would have indicated that head_commit is not
551 * a commit object already. parse_commit() will return failure
552 * without further complaints in such a case. Otherwise, if
553 * the commit is invalid, parse_commit() will complain. So
554 * there is nothing for us to say here. Just return failure.
556 if (parse_commit(head_commit))
559 if (!active_cache_tree)
560 active_cache_tree = cache_tree();
562 if (!cache_tree_fully_valid(active_cache_tree))
563 if (cache_tree_update(&the_index, 0))
564 return error(_("unable to update cache tree"));
566 return !oidcmp(&active_cache_tree->oid,
567 &head_commit->tree->object.oid);
570 static int write_author_script(const char *message)
572 struct strbuf buf = STRBUF_INIT;
577 if (!*message || starts_with(message, "\n")) {
579 /* Missing 'author' line? */
580 unlink(rebase_path_author_script());
582 } else if (skip_prefix(message, "author ", &message))
584 else if ((eol = strchr(message, '\n')))
589 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
590 while (*message && *message != '\n' && *message != '\r')
591 if (skip_prefix(message, " <", &message))
593 else if (*message != '\'')
594 strbuf_addch(&buf, *(message++));
596 strbuf_addf(&buf, "'\\\\%c'", *(message++));
597 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
598 while (*message && *message != '\n' && *message != '\r')
599 if (skip_prefix(message, "> ", &message))
601 else if (*message != '\'')
602 strbuf_addch(&buf, *(message++));
604 strbuf_addf(&buf, "'\\\\%c'", *(message++));
605 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
606 while (*message && *message != '\n' && *message != '\r')
607 if (*message != '\'')
608 strbuf_addch(&buf, *(message++));
610 strbuf_addf(&buf, "'\\\\%c'", *(message++));
611 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
612 strbuf_release(&buf);
617 * Read a list of environment variable assignments (such as the author-script
618 * file) into an environment block. Returns -1 on error, 0 otherwise.
620 static int read_env_script(struct argv_array *env)
622 struct strbuf script = STRBUF_INIT;
626 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
629 for (p = script.buf; *p; p++)
630 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
631 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
633 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
634 else if (*p == '\n') {
639 for (i = 0, p = script.buf; i < count; i++) {
640 argv_array_push(env, p);
647 static char *get_author(const char *message)
652 a = find_commit_header(message, "author", &len);
654 return xmemdupz(a, len);
659 static const char staged_changes_advice[] =
660 N_("you have staged changes in your working tree\n"
661 "If these changes are meant to be squashed into the previous commit, run:\n"
663 " git commit --amend %s\n"
665 "If they are meant to go into a new commit, run:\n"
669 "In both cases, once you're done, continue with:\n"
671 " git rebase --continue\n");
673 #define ALLOW_EMPTY (1<<0)
674 #define EDIT_MSG (1<<1)
675 #define AMEND_MSG (1<<2)
676 #define CLEANUP_MSG (1<<3)
677 #define VERIFY_MSG (1<<4)
680 * If we are cherry-pick, and if the merge did not result in
681 * hand-editing, we will hit this commit and inherit the original
682 * author date and name.
684 * If we are revert, or if our cherry-pick results in a hand merge,
685 * we had better say that the current user is responsible for that.
687 * An exception is when run_git_commit() is called during an
688 * interactive rebase: in that case, we will want to retain the
691 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
694 struct child_process cmd = CHILD_PROCESS_INIT;
699 if (is_rebase_i(opts)) {
700 if (!(flags & EDIT_MSG)) {
701 cmd.stdout_to_stderr = 1;
705 if (read_env_script(&cmd.env_array)) {
706 const char *gpg_opt = gpg_sign_opt_quoted(opts);
708 return error(_(staged_changes_advice),
713 argv_array_push(&cmd.args, "commit");
715 if (!(flags & VERIFY_MSG))
716 argv_array_push(&cmd.args, "-n");
717 if ((flags & AMEND_MSG))
718 argv_array_push(&cmd.args, "--amend");
720 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
722 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
723 if ((flags & CLEANUP_MSG))
724 argv_array_push(&cmd.args, "--cleanup=strip");
725 if ((flags & EDIT_MSG))
726 argv_array_push(&cmd.args, "-e");
727 else if (!(flags & CLEANUP_MSG) &&
728 !opts->signoff && !opts->record_origin &&
729 git_config_get_value("commit.cleanup", &value))
730 argv_array_push(&cmd.args, "--cleanup=verbatim");
732 if ((flags & ALLOW_EMPTY))
733 argv_array_push(&cmd.args, "--allow-empty");
735 if (opts->allow_empty_message)
736 argv_array_push(&cmd.args, "--allow-empty-message");
739 /* hide stderr on success */
740 struct strbuf buf = STRBUF_INIT;
741 int rc = pipe_command(&cmd,
743 /* stdout is already redirected */
747 fputs(buf.buf, stderr);
748 strbuf_release(&buf);
752 return run_command(&cmd);
755 static int rest_is_empty(const struct strbuf *sb, int start)
760 /* Check if the rest is just whitespace and Signed-off-by's. */
761 for (i = start; i < sb->len; i++) {
762 nl = memchr(sb->buf + i, '\n', sb->len - i);
768 if (strlen(sign_off_header) <= eol - i &&
769 starts_with(sb->buf + i, sign_off_header)) {
774 if (!isspace(sb->buf[i++]))
782 * Find out if the message in the strbuf contains only whitespace and
783 * Signed-off-by lines.
785 int message_is_empty(const struct strbuf *sb,
786 enum commit_msg_cleanup_mode cleanup_mode)
788 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
790 return rest_is_empty(sb, 0);
794 * See if the user edited the message in the editor or left what
795 * was in the template intact
797 int template_untouched(const struct strbuf *sb, const char *template_file,
798 enum commit_msg_cleanup_mode cleanup_mode)
800 struct strbuf tmpl = STRBUF_INIT;
803 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
806 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
809 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
810 if (!skip_prefix(sb->buf, tmpl.buf, &start))
812 strbuf_release(&tmpl);
813 return rest_is_empty(sb, start - sb->buf);
816 int update_head_with_reflog(const struct commit *old_head,
817 const struct object_id *new_head,
818 const char *action, const struct strbuf *msg,
821 struct ref_transaction *transaction;
822 struct strbuf sb = STRBUF_INIT;
827 strbuf_addstr(&sb, action);
828 strbuf_addstr(&sb, ": ");
831 nl = strchr(msg->buf, '\n');
833 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
835 strbuf_addbuf(&sb, msg);
836 strbuf_addch(&sb, '\n');
839 transaction = ref_transaction_begin(err);
841 ref_transaction_update(transaction, "HEAD", new_head,
842 old_head ? &old_head->object.oid : &null_oid,
844 ref_transaction_commit(transaction, err)) {
847 ref_transaction_free(transaction);
853 static int run_rewrite_hook(const struct object_id *oldoid,
854 const struct object_id *newoid)
856 struct child_process proc = CHILD_PROCESS_INIT;
859 struct strbuf sb = STRBUF_INIT;
861 argv[0] = find_hook("post-rewrite");
870 proc.stdout_to_stderr = 1;
872 code = start_command(&proc);
875 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
876 sigchain_push(SIGPIPE, SIG_IGN);
877 write_in_full(proc.in, sb.buf, sb.len);
880 sigchain_pop(SIGPIPE);
881 return finish_command(&proc);
884 void commit_post_rewrite(const struct commit *old_head,
885 const struct object_id *new_head)
887 struct notes_rewrite_cfg *cfg;
889 cfg = init_copy_notes_for_rewrite("amend");
891 /* we are amending, so old_head is not NULL */
892 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
893 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
895 run_rewrite_hook(&old_head->object.oid, new_head);
898 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
900 struct argv_array hook_env = ARGV_ARRAY_INIT;
904 name = git_path_commit_editmsg();
905 if (write_message(msg->buf, msg->len, name, 0))
908 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
909 argv_array_push(&hook_env, "GIT_EDITOR=:");
911 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
912 "commit", commit, NULL);
914 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
917 ret = error(_("'prepare-commit-msg' hook failed"));
918 argv_array_clear(&hook_env);
923 static const char implicit_ident_advice_noconfig[] =
924 N_("Your name and email address were configured automatically based\n"
925 "on your username and hostname. Please check that they are accurate.\n"
926 "You can suppress this message by setting them explicitly. Run the\n"
927 "following command and follow the instructions in your editor to edit\n"
928 "your configuration file:\n"
930 " git config --global --edit\n"
932 "After doing this, you may fix the identity used for this commit with:\n"
934 " git commit --amend --reset-author\n");
936 static const char implicit_ident_advice_config[] =
937 N_("Your name and email address were configured automatically based\n"
938 "on your username and hostname. Please check that they are accurate.\n"
939 "You can suppress this message by setting them explicitly:\n"
941 " git config --global user.name \"Your Name\"\n"
942 " git config --global user.email you@example.com\n"
944 "After doing this, you may fix the identity used for this commit with:\n"
946 " git commit --amend --reset-author\n");
948 static const char *implicit_ident_advice(void)
950 char *user_config = expand_user_path("~/.gitconfig", 0);
951 char *xdg_config = xdg_config_home("config");
952 int config_exists = file_exists(user_config) || file_exists(xdg_config);
958 return _(implicit_ident_advice_config);
960 return _(implicit_ident_advice_noconfig);
964 void print_commit_summary(const char *prefix, const struct object_id *oid,
968 struct commit *commit;
969 struct strbuf format = STRBUF_INIT;
971 struct pretty_print_context pctx = {0};
972 struct strbuf author_ident = STRBUF_INIT;
973 struct strbuf committer_ident = STRBUF_INIT;
975 commit = lookup_commit(oid);
977 die(_("couldn't look up newly created commit"));
978 if (parse_commit(commit))
979 die(_("could not parse newly created commit"));
981 strbuf_addstr(&format, "format:%h] %s");
983 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
984 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
985 if (strbuf_cmp(&author_ident, &committer_ident)) {
986 strbuf_addstr(&format, "\n Author: ");
987 strbuf_addbuf_percentquote(&format, &author_ident);
989 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
990 struct strbuf date = STRBUF_INIT;
992 format_commit_message(commit, "%ad", &date, &pctx);
993 strbuf_addstr(&format, "\n Date: ");
994 strbuf_addbuf_percentquote(&format, &date);
995 strbuf_release(&date);
997 if (!committer_ident_sufficiently_given()) {
998 strbuf_addstr(&format, "\n Committer: ");
999 strbuf_addbuf_percentquote(&format, &committer_ident);
1000 if (advice_implicit_identity) {
1001 strbuf_addch(&format, '\n');
1002 strbuf_addstr(&format, implicit_ident_advice());
1005 strbuf_release(&author_ident);
1006 strbuf_release(&committer_ident);
1008 init_revisions(&rev, prefix);
1009 setup_revisions(0, NULL, &rev, NULL);
1012 rev.diffopt.output_format =
1013 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1015 rev.verbose_header = 1;
1016 rev.show_root_diff = 1;
1017 get_commit_format(format.buf, &rev);
1018 rev.always_show_header = 0;
1019 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1020 rev.diffopt.break_opt = 0;
1021 diff_setup_done(&rev.diffopt);
1023 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1025 die_errno(_("unable to resolve HEAD after creating commit"));
1026 if (!strcmp(head, "HEAD"))
1027 head = _("detached HEAD");
1029 skip_prefix(head, "refs/heads/", &head);
1030 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1031 _(" (root-commit)") : "");
1033 if (!log_tree_commit(&rev, commit)) {
1034 rev.always_show_header = 1;
1035 rev.use_terminator = 1;
1036 log_tree_commit(&rev, commit);
1039 strbuf_release(&format);
1042 static int parse_head(struct commit **head)
1044 struct commit *current_head;
1045 struct object_id oid;
1047 if (get_oid("HEAD", &oid)) {
1048 current_head = NULL;
1050 current_head = lookup_commit_reference(&oid);
1052 return error(_("could not parse HEAD"));
1053 if (oidcmp(&oid, ¤t_head->object.oid)) {
1054 warning(_("HEAD %s is not a commit!"),
1057 if (parse_commit(current_head))
1058 return error(_("could not parse HEAD commit"));
1060 *head = current_head;
1066 * Try to commit without forking 'git commit'. In some cases we need
1067 * to run 'git commit' to display an error message
1070 * -1 - error unable to commit
1072 * 1 - run 'git commit'
1074 static int try_to_commit(struct strbuf *msg, const char *author,
1075 struct replay_opts *opts, unsigned int flags,
1076 struct object_id *oid)
1078 struct object_id tree;
1079 struct commit *current_head;
1080 struct commit_list *parents = NULL;
1081 struct commit_extra_header *extra = NULL;
1082 struct strbuf err = STRBUF_INIT;
1083 struct strbuf commit_msg = STRBUF_INIT;
1084 char *amend_author = NULL;
1085 const char *hook_commit = NULL;
1086 enum commit_msg_cleanup_mode cleanup;
1089 if (parse_head(¤t_head))
1092 if (flags & AMEND_MSG) {
1093 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1094 const char *out_enc = get_commit_output_encoding();
1095 const char *message = logmsg_reencode(current_head, NULL,
1099 const char *orig_message = NULL;
1101 find_commit_subject(message, &orig_message);
1103 strbuf_addstr(msg, orig_message);
1104 hook_commit = "HEAD";
1106 author = amend_author = get_author(message);
1107 unuse_commit_buffer(current_head, message);
1109 res = error(_("unable to parse commit author"));
1112 parents = copy_commit_list(current_head->parents);
1113 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1114 } else if (current_head) {
1115 commit_list_insert(current_head, &parents);
1118 if (write_cache_as_tree(&tree, 0, NULL)) {
1119 res = error(_("git write-tree failed to write a tree"));
1123 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1124 ¤t_head->tree->object.oid :
1125 &empty_tree_oid, &tree)) {
1126 res = 1; /* run 'git commit' to display error message */
1130 if (find_hook("prepare-commit-msg")) {
1131 res = run_prepare_commit_msg_hook(msg, hook_commit);
1134 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1136 res = error_errno(_("unable to read commit message "
1138 git_path_commit_editmsg());
1144 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1145 opts->default_msg_cleanup;
1147 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1148 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1149 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1150 res = 1; /* run 'git commit' to display error message */
1154 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1155 oid, author, opts->gpg_sign, extra)) {
1156 res = error(_("failed to write commit object"));
1160 if (update_head_with_reflog(current_head, oid,
1161 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1162 res = error("%s", err.buf);
1166 if (flags & AMEND_MSG)
1167 commit_post_rewrite(current_head, oid);
1170 free_commit_extra_headers(extra);
1171 strbuf_release(&err);
1172 strbuf_release(&commit_msg);
1178 static int do_commit(const char *msg_file, const char *author,
1179 struct replay_opts *opts, unsigned int flags)
1183 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1184 struct object_id oid;
1185 struct strbuf sb = STRBUF_INIT;
1187 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1188 return error_errno(_("unable to read commit message "
1192 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1194 strbuf_release(&sb);
1196 unlink(git_path_cherry_pick_head());
1197 unlink(git_path_merge_msg());
1198 if (!is_rebase_i(opts))
1199 print_commit_summary(NULL, &oid,
1200 SUMMARY_SHOW_AUTHOR_DATE);
1205 return run_git_commit(msg_file, opts, flags);
1210 static int is_original_commit_empty(struct commit *commit)
1212 const struct object_id *ptree_oid;
1214 if (parse_commit(commit))
1215 return error(_("could not parse commit %s"),
1216 oid_to_hex(&commit->object.oid));
1217 if (commit->parents) {
1218 struct commit *parent = commit->parents->item;
1219 if (parse_commit(parent))
1220 return error(_("could not parse parent commit %s"),
1221 oid_to_hex(&parent->object.oid));
1222 ptree_oid = &parent->tree->object.oid;
1224 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1227 return !oidcmp(ptree_oid, &commit->tree->object.oid);
1231 * Do we run "git commit" with "--allow-empty"?
1233 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1235 int index_unchanged, empty_commit;
1240 * (1) we do not allow empty at all and error out.
1242 * (2) we allow ones that were initially empty, but
1243 * forbid the ones that become empty;
1245 * (3) we allow both.
1247 if (!opts->allow_empty)
1248 return 0; /* let "git commit" barf as necessary */
1250 index_unchanged = is_index_unchanged();
1251 if (index_unchanged < 0)
1252 return index_unchanged;
1253 if (!index_unchanged)
1254 return 0; /* we do not have to say --allow-empty */
1256 if (opts->keep_redundant_commits)
1259 empty_commit = is_original_commit_empty(commit);
1260 if (empty_commit < 0)
1261 return empty_commit;
1269 * Note that ordering matters in this enum. Not only must it match the mapping
1270 * below, it is also divided into several sections that matter. When adding
1271 * new commands, make sure you add it in the right section.
1274 /* commands that handle commits */
1281 /* commands that do something else than handling a single commit */
1283 /* commands that do nothing but are counted for reporting progress */
1286 /* comments (not counted for reporting progress) */
1293 } todo_command_info[] = {
1306 static const char *command_to_string(const enum todo_command command)
1308 if (command < TODO_COMMENT)
1309 return todo_command_info[command].str;
1310 die("Unknown command: %d", command);
1313 static char command_to_char(const enum todo_command command)
1315 if (command < TODO_COMMENT && todo_command_info[command].c)
1316 return todo_command_info[command].c;
1317 return comment_line_char;
1320 static int is_noop(const enum todo_command command)
1322 return TODO_NOOP <= command;
1325 static int is_fixup(enum todo_command command)
1327 return command == TODO_FIXUP || command == TODO_SQUASH;
1330 static int update_squash_messages(enum todo_command command,
1331 struct commit *commit, struct replay_opts *opts)
1333 struct strbuf buf = STRBUF_INIT;
1335 const char *message, *body;
1337 if (file_exists(rebase_path_squash_msg())) {
1338 struct strbuf header = STRBUF_INIT;
1341 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1342 return error(_("could not read '%s'"),
1343 rebase_path_squash_msg());
1346 eol = strchrnul(buf.buf, '\n');
1347 if (buf.buf[0] != comment_line_char ||
1348 (p += strcspn(p, "0123456789\n")) == eol)
1349 return error(_("unexpected 1st line of squash message:"
1351 (int)(eol - buf.buf), buf.buf);
1352 count = strtol(p, NULL, 10);
1355 return error(_("invalid 1st line of squash message:\n"
1357 (int)(eol - buf.buf), buf.buf);
1359 strbuf_addf(&header, "%c ", comment_line_char);
1360 strbuf_addf(&header,
1361 _("This is a combination of %d commits."), ++count);
1362 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1363 strbuf_release(&header);
1365 struct object_id head;
1366 struct commit *head_commit;
1367 const char *head_message, *body;
1369 if (get_oid("HEAD", &head))
1370 return error(_("need a HEAD to fixup"));
1371 if (!(head_commit = lookup_commit_reference(&head)))
1372 return error(_("could not read HEAD"));
1373 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1374 return error(_("could not read HEAD's commit message"));
1376 find_commit_subject(head_message, &body);
1377 if (write_message(body, strlen(body),
1378 rebase_path_fixup_msg(), 0)) {
1379 unuse_commit_buffer(head_commit, head_message);
1380 return error(_("cannot write '%s'"),
1381 rebase_path_fixup_msg());
1385 strbuf_addf(&buf, "%c ", comment_line_char);
1386 strbuf_addf(&buf, _("This is a combination of %d commits."),
1388 strbuf_addf(&buf, "\n%c ", comment_line_char);
1389 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1390 strbuf_addstr(&buf, "\n\n");
1391 strbuf_addstr(&buf, body);
1393 unuse_commit_buffer(head_commit, head_message);
1396 if (!(message = get_commit_buffer(commit, NULL)))
1397 return error(_("could not read commit message of %s"),
1398 oid_to_hex(&commit->object.oid));
1399 find_commit_subject(message, &body);
1401 if (command == TODO_SQUASH) {
1402 unlink(rebase_path_fixup_msg());
1403 strbuf_addf(&buf, "\n%c ", comment_line_char);
1404 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1405 strbuf_addstr(&buf, "\n\n");
1406 strbuf_addstr(&buf, body);
1407 } else if (command == TODO_FIXUP) {
1408 strbuf_addf(&buf, "\n%c ", comment_line_char);
1409 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1411 strbuf_addstr(&buf, "\n\n");
1412 strbuf_add_commented_lines(&buf, body, strlen(body));
1414 return error(_("unknown command: %d"), command);
1415 unuse_commit_buffer(commit, message);
1417 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1418 strbuf_release(&buf);
1422 static void flush_rewritten_pending(void) {
1423 struct strbuf buf = STRBUF_INIT;
1424 struct object_id newoid;
1427 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1428 !get_oid("HEAD", &newoid) &&
1429 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1430 char *bol = buf.buf, *eol;
1433 eol = strchrnul(bol, '\n');
1434 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1435 bol, oid_to_hex(&newoid));
1441 unlink(rebase_path_rewritten_pending());
1443 strbuf_release(&buf);
1446 static void record_in_rewritten(struct object_id *oid,
1447 enum todo_command next_command) {
1448 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1453 fprintf(out, "%s\n", oid_to_hex(oid));
1456 if (!is_fixup(next_command))
1457 flush_rewritten_pending();
1460 static int do_pick_commit(enum todo_command command, struct commit *commit,
1461 struct replay_opts *opts, int final_fixup)
1463 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1464 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1465 struct object_id head;
1466 struct commit *base, *next, *parent;
1467 const char *base_label, *next_label;
1468 char *author = NULL;
1469 struct commit_message msg = { NULL, NULL, NULL, NULL };
1470 struct strbuf msgbuf = STRBUF_INIT;
1471 int res, unborn = 0, allow;
1473 if (opts->no_commit) {
1475 * We do not intend to commit immediately. We just want to
1476 * merge the differences in, so let's compute the tree
1477 * that represents the "current" state for merge-recursive
1480 if (write_cache_as_tree(&head, 0, NULL))
1481 return error(_("your index file is unmerged."));
1483 unborn = get_oid("HEAD", &head);
1485 oidcpy(&head, the_hash_algo->empty_tree);
1486 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1488 return error_dirty_index(opts);
1492 if (!commit->parents)
1494 else if (commit->parents->next) {
1495 /* Reverting or cherry-picking a merge commit */
1497 struct commit_list *p;
1499 if (!opts->mainline)
1500 return error(_("commit %s is a merge but no -m option was given."),
1501 oid_to_hex(&commit->object.oid));
1503 for (cnt = 1, p = commit->parents;
1504 cnt != opts->mainline && p;
1507 if (cnt != opts->mainline || !p)
1508 return error(_("commit %s does not have parent %d"),
1509 oid_to_hex(&commit->object.oid), opts->mainline);
1511 } else if (0 < opts->mainline)
1512 return error(_("mainline was specified but commit %s is not a merge."),
1513 oid_to_hex(&commit->object.oid));
1515 parent = commit->parents->item;
1517 if (get_message(commit, &msg) != 0)
1518 return error(_("cannot get commit message for %s"),
1519 oid_to_hex(&commit->object.oid));
1521 if (opts->allow_ff && !is_fixup(command) &&
1522 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1523 (!parent && unborn))) {
1524 if (is_rebase_i(opts))
1525 write_author_script(msg.message);
1526 res = fast_forward_to(&commit->object.oid, &head, unborn,
1528 if (res || command != TODO_REWORD)
1530 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1532 goto fast_forward_edit;
1534 if (parent && parse_commit(parent) < 0)
1535 /* TRANSLATORS: The first %s will be a "todo" command like
1536 "revert" or "pick", the second %s a SHA1. */
1537 return error(_("%s: cannot parse parent commit %s"),
1538 command_to_string(command),
1539 oid_to_hex(&parent->object.oid));
1542 * "commit" is an existing commit. We would want to apply
1543 * the difference it introduces since its first parent "prev"
1544 * on top of the current HEAD if we are cherry-pick. Or the
1545 * reverse of it if we are revert.
1548 if (command == TODO_REVERT) {
1550 base_label = msg.label;
1552 next_label = msg.parent_label;
1553 strbuf_addstr(&msgbuf, "Revert \"");
1554 strbuf_addstr(&msgbuf, msg.subject);
1555 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1556 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1558 if (commit->parents && commit->parents->next) {
1559 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1560 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1562 strbuf_addstr(&msgbuf, ".\n");
1567 base_label = msg.parent_label;
1569 next_label = msg.label;
1571 /* Append the commit log message to msgbuf. */
1572 if (find_commit_subject(msg.message, &p))
1573 strbuf_addstr(&msgbuf, p);
1575 if (opts->record_origin) {
1576 strbuf_complete_line(&msgbuf);
1577 if (!has_conforming_footer(&msgbuf, NULL, 0))
1578 strbuf_addch(&msgbuf, '\n');
1579 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1580 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1581 strbuf_addstr(&msgbuf, ")\n");
1583 if (!is_fixup(command))
1584 author = get_author(msg.message);
1587 if (command == TODO_REWORD)
1588 flags |= EDIT_MSG | VERIFY_MSG;
1589 else if (is_fixup(command)) {
1590 if (update_squash_messages(command, commit, opts))
1594 msg_file = rebase_path_squash_msg();
1595 else if (file_exists(rebase_path_fixup_msg())) {
1596 flags |= CLEANUP_MSG;
1597 msg_file = rebase_path_fixup_msg();
1599 const char *dest = git_path_squash_msg();
1601 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1602 return error(_("could not rename '%s' to '%s'"),
1603 rebase_path_squash_msg(), dest);
1604 unlink(git_path_merge_msg());
1610 if (opts->signoff && !is_fixup(command))
1611 append_signoff(&msgbuf, 0, 0);
1613 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1615 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1616 res = do_recursive_merge(base, next, base_label, next_label,
1617 &head, &msgbuf, opts);
1620 res |= write_message(msgbuf.buf, msgbuf.len,
1621 git_path_merge_msg(), 0);
1623 struct commit_list *common = NULL;
1624 struct commit_list *remotes = NULL;
1626 res = write_message(msgbuf.buf, msgbuf.len,
1627 git_path_merge_msg(), 0);
1629 commit_list_insert(base, &common);
1630 commit_list_insert(next, &remotes);
1631 res |= try_merge_command(opts->strategy,
1632 opts->xopts_nr, (const char **)opts->xopts,
1633 common, oid_to_hex(&head), remotes);
1634 free_commit_list(common);
1635 free_commit_list(remotes);
1637 strbuf_release(&msgbuf);
1640 * If the merge was clean or if it failed due to conflict, we write
1641 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1642 * However, if the merge did not even start, then we don't want to
1645 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1646 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1647 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1649 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1650 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1651 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1655 error(command == TODO_REVERT
1656 ? _("could not revert %s... %s")
1657 : _("could not apply %s... %s"),
1658 short_commit_name(commit), msg.subject);
1659 print_advice(res == 1, opts);
1660 rerere(opts->allow_rerere_auto);
1664 allow = allow_empty(opts, commit);
1669 flags |= ALLOW_EMPTY;
1670 if (!opts->no_commit) {
1672 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1673 res = do_commit(msg_file, author, opts, flags);
1675 res = error(_("unable to parse commit author"));
1678 if (!res && final_fixup) {
1679 unlink(rebase_path_fixup_msg());
1680 unlink(rebase_path_squash_msg());
1684 free_message(commit, &msg);
1686 update_abort_safety_file();
1691 static int prepare_revs(struct replay_opts *opts)
1694 * picking (but not reverting) ranges (but not individual revisions)
1695 * should be done in reverse
1697 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1698 opts->revs->reverse ^= 1;
1700 if (prepare_revision_walk(opts->revs))
1701 return error(_("revision walk setup failed"));
1703 if (!opts->revs->commits)
1704 return error(_("empty commit set passed"));
1708 static int read_and_refresh_cache(struct replay_opts *opts)
1710 struct lock_file index_lock = LOCK_INIT;
1711 int index_fd = hold_locked_index(&index_lock, 0);
1712 if (read_index_preload(&the_index, NULL) < 0) {
1713 rollback_lock_file(&index_lock);
1714 return error(_("git %s: failed to read the index"),
1715 _(action_name(opts)));
1717 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1718 if (index_fd >= 0) {
1719 if (write_locked_index(&the_index, &index_lock,
1720 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1721 return error(_("git %s: failed to refresh the index"),
1722 _(action_name(opts)));
1729 enum todo_command command;
1730 struct commit *commit;
1733 size_t offset_in_buf;
1738 struct todo_item *items;
1739 int nr, alloc, current;
1740 int done_nr, total_nr;
1741 struct stat_data stat;
1744 #define TODO_LIST_INIT { STRBUF_INIT }
1746 static void todo_list_release(struct todo_list *todo_list)
1748 strbuf_release(&todo_list->buf);
1749 FREE_AND_NULL(todo_list->items);
1750 todo_list->nr = todo_list->alloc = 0;
1753 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1755 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1756 return todo_list->items + todo_list->nr++;
1759 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1761 struct object_id commit_oid;
1762 char *end_of_object_name;
1763 int i, saved, status, padding;
1766 bol += strspn(bol, " \t");
1768 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1769 item->command = TODO_COMMENT;
1770 item->commit = NULL;
1772 item->arg_len = eol - bol;
1776 for (i = 0; i < TODO_COMMENT; i++)
1777 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1780 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1785 if (i >= TODO_COMMENT)
1788 /* Eat up extra spaces/ tabs before object name */
1789 padding = strspn(bol, " \t");
1792 if (item->command == TODO_NOOP) {
1794 return error(_("%s does not accept arguments: '%s'"),
1795 command_to_string(item->command), bol);
1796 item->commit = NULL;
1798 item->arg_len = eol - bol;
1803 return error(_("missing arguments for %s"),
1804 command_to_string(item->command));
1806 if (item->command == TODO_EXEC) {
1807 item->commit = NULL;
1809 item->arg_len = (int)(eol - bol);
1813 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1814 saved = *end_of_object_name;
1815 *end_of_object_name = '\0';
1816 status = get_oid(bol, &commit_oid);
1817 *end_of_object_name = saved;
1819 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1820 item->arg_len = (int)(eol - item->arg);
1825 item->commit = lookup_commit_reference(&commit_oid);
1826 return !item->commit;
1829 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1831 struct todo_item *item;
1832 char *p = buf, *next_p;
1833 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1835 for (i = 1; *p; i++, p = next_p) {
1836 char *eol = strchrnul(p, '\n');
1838 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1840 if (p != eol && eol[-1] == '\r')
1841 eol--; /* strip Carriage Return */
1843 item = append_new_todo(todo_list);
1844 item->offset_in_buf = p - todo_list->buf.buf;
1845 if (parse_insn_line(item, p, eol)) {
1846 res = error(_("invalid line %d: %.*s"),
1847 i, (int)(eol - p), p);
1848 item->command = TODO_NOOP;
1853 else if (is_fixup(item->command))
1854 return error(_("cannot '%s' without a previous commit"),
1855 command_to_string(item->command));
1856 else if (!is_noop(item->command))
1863 static int count_commands(struct todo_list *todo_list)
1867 for (i = 0; i < todo_list->nr; i++)
1868 if (todo_list->items[i].command != TODO_COMMENT)
1874 static int get_item_line_offset(struct todo_list *todo_list, int index)
1876 return index < todo_list->nr ?
1877 todo_list->items[index].offset_in_buf : todo_list->buf.len;
1880 static const char *get_item_line(struct todo_list *todo_list, int index)
1882 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
1885 static int get_item_line_length(struct todo_list *todo_list, int index)
1887 return get_item_line_offset(todo_list, index + 1)
1888 - get_item_line_offset(todo_list, index);
1891 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
1896 fd = open(path, O_RDONLY);
1898 return error_errno(_("could not open '%s'"), path);
1899 len = strbuf_read(sb, fd, 0);
1902 return error(_("could not read '%s'."), path);
1906 static int read_populate_todo(struct todo_list *todo_list,
1907 struct replay_opts *opts)
1910 const char *todo_file = get_todo_path(opts);
1913 strbuf_reset(&todo_list->buf);
1914 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
1917 res = stat(todo_file, &st);
1919 return error(_("could not stat '%s'"), todo_file);
1920 fill_stat_data(&todo_list->stat, &st);
1922 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1924 if (is_rebase_i(opts))
1925 return error(_("please fix this using "
1926 "'git rebase --edit-todo'."));
1927 return error(_("unusable instruction sheet: '%s'"), todo_file);
1930 if (!todo_list->nr &&
1931 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1932 return error(_("no commits parsed."));
1934 if (!is_rebase_i(opts)) {
1935 enum todo_command valid =
1936 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1939 for (i = 0; i < todo_list->nr; i++)
1940 if (valid == todo_list->items[i].command)
1942 else if (valid == TODO_PICK)
1943 return error(_("cannot cherry-pick during a revert."));
1945 return error(_("cannot revert during a cherry-pick."));
1948 if (is_rebase_i(opts)) {
1949 struct todo_list done = TODO_LIST_INIT;
1950 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1952 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1953 !parse_insn_buffer(done.buf.buf, &done))
1954 todo_list->done_nr = count_commands(&done);
1956 todo_list->done_nr = 0;
1958 todo_list->total_nr = todo_list->done_nr
1959 + count_commands(todo_list);
1960 todo_list_release(&done);
1963 fprintf(f, "%d\n", todo_list->total_nr);
1971 static int git_config_string_dup(char **dest,
1972 const char *var, const char *value)
1975 return config_error_nonbool(var);
1977 *dest = xstrdup(value);
1981 static int populate_opts_cb(const char *key, const char *value, void *data)
1983 struct replay_opts *opts = data;
1988 else if (!strcmp(key, "options.no-commit"))
1989 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1990 else if (!strcmp(key, "options.edit"))
1991 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1992 else if (!strcmp(key, "options.signoff"))
1993 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1994 else if (!strcmp(key, "options.record-origin"))
1995 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1996 else if (!strcmp(key, "options.allow-ff"))
1997 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1998 else if (!strcmp(key, "options.mainline"))
1999 opts->mainline = git_config_int(key, value);
2000 else if (!strcmp(key, "options.strategy"))
2001 git_config_string_dup(&opts->strategy, key, value);
2002 else if (!strcmp(key, "options.gpg-sign"))
2003 git_config_string_dup(&opts->gpg_sign, key, value);
2004 else if (!strcmp(key, "options.strategy-option")) {
2005 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2006 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2007 } else if (!strcmp(key, "options.allow-rerere-auto"))
2008 opts->allow_rerere_auto =
2009 git_config_bool_or_int(key, value, &error_flag) ?
2010 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2012 return error(_("invalid key: %s"), key);
2015 return error(_("invalid value for %s: %s"), key, value);
2020 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2025 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2027 opts->strategy = strbuf_detach(buf, NULL);
2028 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2031 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2032 for (i = 0; i < opts->xopts_nr; i++) {
2033 const char *arg = opts->xopts[i];
2035 skip_prefix(arg, "--", &arg);
2036 opts->xopts[i] = xstrdup(arg);
2040 static int read_populate_opts(struct replay_opts *opts)
2042 if (is_rebase_i(opts)) {
2043 struct strbuf buf = STRBUF_INIT;
2045 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2046 if (!starts_with(buf.buf, "-S"))
2049 free(opts->gpg_sign);
2050 opts->gpg_sign = xstrdup(buf.buf + 2);
2055 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2056 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2057 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2058 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2059 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2063 if (file_exists(rebase_path_verbose()))
2066 if (file_exists(rebase_path_signoff())) {
2071 read_strategy_opts(opts, &buf);
2072 strbuf_release(&buf);
2077 if (!file_exists(git_path_opts_file()))
2080 * The function git_parse_source(), called from git_config_from_file(),
2081 * may die() in case of a syntactically incorrect file. We do not care
2082 * about this case, though, because we wrote that file ourselves, so we
2083 * are pretty certain that it is syntactically correct.
2085 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2086 return error(_("malformed options sheet: '%s'"),
2087 git_path_opts_file());
2091 static int walk_revs_populate_todo(struct todo_list *todo_list,
2092 struct replay_opts *opts)
2094 enum todo_command command = opts->action == REPLAY_PICK ?
2095 TODO_PICK : TODO_REVERT;
2096 const char *command_string = todo_command_info[command].str;
2097 struct commit *commit;
2099 if (prepare_revs(opts))
2102 while ((commit = get_revision(opts->revs))) {
2103 struct todo_item *item = append_new_todo(todo_list);
2104 const char *commit_buffer = get_commit_buffer(commit, NULL);
2105 const char *subject;
2108 item->command = command;
2109 item->commit = commit;
2112 item->offset_in_buf = todo_list->buf.len;
2113 subject_len = find_commit_subject(commit_buffer, &subject);
2114 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2115 short_commit_name(commit), subject_len, subject);
2116 unuse_commit_buffer(commit, commit_buffer);
2121 static int create_seq_dir(void)
2123 if (file_exists(git_path_seq_dir())) {
2124 error(_("a cherry-pick or revert is already in progress"));
2125 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2127 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2128 return error_errno(_("could not create sequencer directory '%s'"),
2129 git_path_seq_dir());
2133 static int save_head(const char *head)
2135 struct lock_file head_lock = LOCK_INIT;
2136 struct strbuf buf = STRBUF_INIT;
2140 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2142 return error_errno(_("could not lock HEAD"));
2143 strbuf_addf(&buf, "%s\n", head);
2144 written = write_in_full(fd, buf.buf, buf.len);
2145 strbuf_release(&buf);
2147 error_errno(_("could not write to '%s'"), git_path_head_file());
2148 rollback_lock_file(&head_lock);
2151 if (commit_lock_file(&head_lock) < 0)
2152 return error(_("failed to finalize '%s'"), git_path_head_file());
2156 static int rollback_is_safe(void)
2158 struct strbuf sb = STRBUF_INIT;
2159 struct object_id expected_head, actual_head;
2161 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2163 if (get_oid_hex(sb.buf, &expected_head)) {
2164 strbuf_release(&sb);
2165 die(_("could not parse %s"), git_path_abort_safety_file());
2167 strbuf_release(&sb);
2169 else if (errno == ENOENT)
2170 oidclr(&expected_head);
2172 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2174 if (get_oid("HEAD", &actual_head))
2175 oidclr(&actual_head);
2177 return !oidcmp(&actual_head, &expected_head);
2180 static int reset_for_rollback(const struct object_id *oid)
2182 const char *argv[4]; /* reset --merge <arg> + NULL */
2185 argv[1] = "--merge";
2186 argv[2] = oid_to_hex(oid);
2188 return run_command_v_opt(argv, RUN_GIT_CMD);
2191 static int rollback_single_pick(void)
2193 struct object_id head_oid;
2195 if (!file_exists(git_path_cherry_pick_head()) &&
2196 !file_exists(git_path_revert_head()))
2197 return error(_("no cherry-pick or revert in progress"));
2198 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2199 return error(_("cannot resolve HEAD"));
2200 if (is_null_oid(&head_oid))
2201 return error(_("cannot abort from a branch yet to be born"));
2202 return reset_for_rollback(&head_oid);
2205 int sequencer_rollback(struct replay_opts *opts)
2208 struct object_id oid;
2209 struct strbuf buf = STRBUF_INIT;
2212 f = fopen(git_path_head_file(), "r");
2213 if (!f && errno == ENOENT) {
2215 * There is no multiple-cherry-pick in progress.
2216 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2217 * a single-cherry-pick in progress, abort that.
2219 return rollback_single_pick();
2222 return error_errno(_("cannot open '%s'"), git_path_head_file());
2223 if (strbuf_getline_lf(&buf, f)) {
2224 error(_("cannot read '%s': %s"), git_path_head_file(),
2225 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2230 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2231 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2232 git_path_head_file());
2235 if (is_null_oid(&oid)) {
2236 error(_("cannot abort from a branch yet to be born"));
2240 if (!rollback_is_safe()) {
2241 /* Do not error, just do not rollback */
2242 warning(_("You seem to have moved HEAD. "
2243 "Not rewinding, check your HEAD!"));
2245 if (reset_for_rollback(&oid))
2247 strbuf_release(&buf);
2248 return sequencer_remove_state(opts);
2250 strbuf_release(&buf);
2254 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2256 struct lock_file todo_lock = LOCK_INIT;
2257 const char *todo_path = get_todo_path(opts);
2258 int next = todo_list->current, offset, fd;
2261 * rebase -i writes "git-rebase-todo" without the currently executing
2262 * command, appending it to "done" instead.
2264 if (is_rebase_i(opts))
2267 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2269 return error_errno(_("could not lock '%s'"), todo_path);
2270 offset = get_item_line_offset(todo_list, next);
2271 if (write_in_full(fd, todo_list->buf.buf + offset,
2272 todo_list->buf.len - offset) < 0)
2273 return error_errno(_("could not write to '%s'"), todo_path);
2274 if (commit_lock_file(&todo_lock) < 0)
2275 return error(_("failed to finalize '%s'"), todo_path);
2277 if (is_rebase_i(opts) && next > 0) {
2278 const char *done = rebase_path_done();
2279 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2284 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2285 get_item_line_length(todo_list, next - 1))
2287 ret = error_errno(_("could not write to '%s'"), done);
2289 ret = error_errno(_("failed to finalize '%s'"), done);
2295 static int save_opts(struct replay_opts *opts)
2297 const char *opts_file = git_path_opts_file();
2300 if (opts->no_commit)
2301 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2303 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2305 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2306 if (opts->record_origin)
2307 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2309 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2310 if (opts->mainline) {
2311 struct strbuf buf = STRBUF_INIT;
2312 strbuf_addf(&buf, "%d", opts->mainline);
2313 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2314 strbuf_release(&buf);
2317 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2319 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2322 for (i = 0; i < opts->xopts_nr; i++)
2323 res |= git_config_set_multivar_in_file_gently(opts_file,
2324 "options.strategy-option",
2325 opts->xopts[i], "^$", 0);
2327 if (opts->allow_rerere_auto)
2328 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2329 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2334 static int make_patch(struct commit *commit, struct replay_opts *opts)
2336 struct strbuf buf = STRBUF_INIT;
2337 struct rev_info log_tree_opt;
2338 const char *subject, *p;
2341 p = short_commit_name(commit);
2342 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2344 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2345 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2346 res |= error(_("could not update %s"), "REBASE_HEAD");
2348 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2349 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2350 init_revisions(&log_tree_opt, NULL);
2351 log_tree_opt.abbrev = 0;
2352 log_tree_opt.diff = 1;
2353 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2354 log_tree_opt.disable_stdin = 1;
2355 log_tree_opt.no_commit_id = 1;
2356 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2357 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2358 if (!log_tree_opt.diffopt.file)
2359 res |= error_errno(_("could not open '%s'"), buf.buf);
2361 res |= log_tree_commit(&log_tree_opt, commit);
2362 fclose(log_tree_opt.diffopt.file);
2366 strbuf_addf(&buf, "%s/message", get_dir(opts));
2367 if (!file_exists(buf.buf)) {
2368 const char *commit_buffer = get_commit_buffer(commit, NULL);
2369 find_commit_subject(commit_buffer, &subject);
2370 res |= write_message(subject, strlen(subject), buf.buf, 1);
2371 unuse_commit_buffer(commit, commit_buffer);
2373 strbuf_release(&buf);
2378 static int intend_to_amend(void)
2380 struct object_id head;
2383 if (get_oid("HEAD", &head))
2384 return error(_("cannot read HEAD"));
2386 p = oid_to_hex(&head);
2387 return write_message(p, strlen(p), rebase_path_amend(), 1);
2390 static int error_with_patch(struct commit *commit,
2391 const char *subject, int subject_len,
2392 struct replay_opts *opts, int exit_code, int to_amend)
2394 if (make_patch(commit, opts))
2398 if (intend_to_amend())
2401 fprintf(stderr, "You can amend the commit now, with\n"
2403 " git commit --amend %s\n"
2405 "Once you are satisfied with your changes, run\n"
2407 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2408 } else if (exit_code)
2409 fprintf(stderr, "Could not apply %s... %.*s\n",
2410 short_commit_name(commit), subject_len, subject);
2415 static int error_failed_squash(struct commit *commit,
2416 struct replay_opts *opts, int subject_len, const char *subject)
2418 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2419 return error(_("could not rename '%s' to '%s'"),
2420 rebase_path_squash_msg(), rebase_path_message());
2421 unlink(rebase_path_fixup_msg());
2422 unlink(git_path_merge_msg());
2423 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2424 return error(_("could not copy '%s' to '%s'"),
2425 rebase_path_message(), git_path_merge_msg());
2426 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2429 static int do_exec(const char *command_line)
2431 struct argv_array child_env = ARGV_ARRAY_INIT;
2432 const char *child_argv[] = { NULL, NULL };
2435 fprintf(stderr, "Executing: %s\n", command_line);
2436 child_argv[0] = command_line;
2437 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2438 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2441 /* force re-reading of the cache */
2442 if (discard_cache() < 0 || read_cache() < 0)
2443 return error(_("could not read index"));
2445 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2448 warning(_("execution failed: %s\n%s"
2449 "You can fix the problem, and then run\n"
2451 " git rebase --continue\n"
2454 dirty ? N_("and made changes to the index and/or the "
2455 "working tree\n") : "");
2457 /* command not found */
2460 warning(_("execution succeeded: %s\nbut "
2461 "left changes to the index and/or the working tree\n"
2462 "Commit or stash your changes, and then run\n"
2464 " git rebase --continue\n"
2465 "\n"), command_line);
2469 argv_array_clear(&child_env);
2474 static int is_final_fixup(struct todo_list *todo_list)
2476 int i = todo_list->current;
2478 if (!is_fixup(todo_list->items[i].command))
2481 while (++i < todo_list->nr)
2482 if (is_fixup(todo_list->items[i].command))
2484 else if (!is_noop(todo_list->items[i].command))
2489 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2493 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2494 if (!is_noop(todo_list->items[i].command))
2495 return todo_list->items[i].command;
2500 static int apply_autostash(struct replay_opts *opts)
2502 struct strbuf stash_sha1 = STRBUF_INIT;
2503 struct child_process child = CHILD_PROCESS_INIT;
2506 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2507 strbuf_release(&stash_sha1);
2510 strbuf_trim(&stash_sha1);
2513 child.no_stdout = 1;
2514 child.no_stderr = 1;
2515 argv_array_push(&child.args, "stash");
2516 argv_array_push(&child.args, "apply");
2517 argv_array_push(&child.args, stash_sha1.buf);
2518 if (!run_command(&child))
2519 fprintf(stderr, _("Applied autostash.\n"));
2521 struct child_process store = CHILD_PROCESS_INIT;
2524 argv_array_push(&store.args, "stash");
2525 argv_array_push(&store.args, "store");
2526 argv_array_push(&store.args, "-m");
2527 argv_array_push(&store.args, "autostash");
2528 argv_array_push(&store.args, "-q");
2529 argv_array_push(&store.args, stash_sha1.buf);
2530 if (run_command(&store))
2531 ret = error(_("cannot store %s"), stash_sha1.buf);
2534 _("Applying autostash resulted in conflicts.\n"
2535 "Your changes are safe in the stash.\n"
2536 "You can run \"git stash pop\" or"
2537 " \"git stash drop\" at any time.\n"));
2540 strbuf_release(&stash_sha1);
2544 static const char *reflog_message(struct replay_opts *opts,
2545 const char *sub_action, const char *fmt, ...)
2548 static struct strbuf buf = STRBUF_INIT;
2552 strbuf_addstr(&buf, action_name(opts));
2554 strbuf_addf(&buf, " (%s)", sub_action);
2556 strbuf_addstr(&buf, ": ");
2557 strbuf_vaddf(&buf, fmt, ap);
2564 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2568 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2570 assert(!(opts->signoff || opts->no_commit ||
2571 opts->record_origin || opts->edit));
2572 if (read_and_refresh_cache(opts))
2575 while (todo_list->current < todo_list->nr) {
2576 struct todo_item *item = todo_list->items + todo_list->current;
2577 if (save_todo(todo_list, opts))
2579 if (is_rebase_i(opts)) {
2580 if (item->command != TODO_COMMENT) {
2581 FILE *f = fopen(rebase_path_msgnum(), "w");
2583 todo_list->done_nr++;
2586 fprintf(f, "%d\n", todo_list->done_nr);
2589 fprintf(stderr, "Rebasing (%d/%d)%s",
2591 todo_list->total_nr,
2592 opts->verbose ? "\n" : "\r");
2594 unlink(rebase_path_message());
2595 unlink(rebase_path_author_script());
2596 unlink(rebase_path_stopped_sha());
2597 unlink(rebase_path_amend());
2598 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
2600 if (item->command <= TODO_SQUASH) {
2601 if (is_rebase_i(opts))
2602 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2603 command_to_string(item->command), NULL),
2605 res = do_pick_commit(item->command, item->commit,
2606 opts, is_final_fixup(todo_list));
2607 if (is_rebase_i(opts) && res < 0) {
2609 todo_list->current--;
2610 if (save_todo(todo_list, opts))
2613 if (item->command == TODO_EDIT) {
2614 struct commit *commit = item->commit;
2617 _("Stopped at %s... %.*s\n"),
2618 short_commit_name(commit),
2619 item->arg_len, item->arg);
2620 return error_with_patch(commit,
2621 item->arg, item->arg_len, opts, res,
2624 if (is_rebase_i(opts) && !res)
2625 record_in_rewritten(&item->commit->object.oid,
2626 peek_command(todo_list, 1));
2627 if (res && is_fixup(item->command)) {
2630 return error_failed_squash(item->commit, opts,
2631 item->arg_len, item->arg);
2632 } else if (res && is_rebase_i(opts))
2633 return res | error_with_patch(item->commit,
2634 item->arg, item->arg_len, opts, res,
2635 item->command == TODO_REWORD);
2636 } else if (item->command == TODO_EXEC) {
2637 char *end_of_arg = (char *)(item->arg + item->arg_len);
2638 int saved = *end_of_arg;
2642 res = do_exec(item->arg);
2643 *end_of_arg = saved;
2645 /* Reread the todo file if it has changed. */
2647 ; /* fall through */
2648 else if (stat(get_todo_path(opts), &st))
2649 res = error_errno(_("could not stat '%s'"),
2650 get_todo_path(opts));
2651 else if (match_stat_data(&todo_list->stat, &st)) {
2652 todo_list_release(todo_list);
2653 if (read_populate_todo(todo_list, opts))
2654 res = -1; /* message was printed */
2655 /* `current` will be incremented below */
2656 todo_list->current = -1;
2658 } else if (!is_noop(item->command))
2659 return error(_("unknown command %d"), item->command);
2661 todo_list->current++;
2666 if (is_rebase_i(opts)) {
2667 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2670 /* Stopped in the middle, as planned? */
2671 if (todo_list->current < todo_list->nr)
2674 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2675 starts_with(head_ref.buf, "refs/")) {
2677 struct object_id head, orig;
2680 if (get_oid("HEAD", &head)) {
2681 res = error(_("cannot read HEAD"));
2683 strbuf_release(&head_ref);
2684 strbuf_release(&buf);
2687 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2688 get_oid_hex(buf.buf, &orig)) {
2689 res = error(_("could not read orig-head"));
2690 goto cleanup_head_ref;
2693 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2694 res = error(_("could not read 'onto'"));
2695 goto cleanup_head_ref;
2697 msg = reflog_message(opts, "finish", "%s onto %s",
2698 head_ref.buf, buf.buf);
2699 if (update_ref(msg, head_ref.buf, &head, &orig,
2700 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
2701 res = error(_("could not update %s"),
2703 goto cleanup_head_ref;
2705 msg = reflog_message(opts, "finish", "returning to %s",
2707 if (create_symref("HEAD", head_ref.buf, msg)) {
2708 res = error(_("could not update HEAD to %s"),
2710 goto cleanup_head_ref;
2715 if (opts->verbose) {
2716 struct rev_info log_tree_opt;
2717 struct object_id orig, head;
2719 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2720 init_revisions(&log_tree_opt, NULL);
2721 log_tree_opt.diff = 1;
2722 log_tree_opt.diffopt.output_format =
2723 DIFF_FORMAT_DIFFSTAT;
2724 log_tree_opt.disable_stdin = 1;
2726 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2727 !get_oid(buf.buf, &orig) &&
2728 !get_oid("HEAD", &head)) {
2729 diff_tree_oid(&orig, &head, "",
2730 &log_tree_opt.diffopt);
2731 log_tree_diff_flush(&log_tree_opt);
2734 flush_rewritten_pending();
2735 if (!stat(rebase_path_rewritten_list(), &st) &&
2737 struct child_process child = CHILD_PROCESS_INIT;
2738 const char *post_rewrite_hook =
2739 find_hook("post-rewrite");
2741 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2743 argv_array_push(&child.args, "notes");
2744 argv_array_push(&child.args, "copy");
2745 argv_array_push(&child.args, "--for-rewrite=rebase");
2746 /* we don't care if this copying failed */
2747 run_command(&child);
2749 if (post_rewrite_hook) {
2750 struct child_process hook = CHILD_PROCESS_INIT;
2752 hook.in = open(rebase_path_rewritten_list(),
2754 hook.stdout_to_stderr = 1;
2755 argv_array_push(&hook.args, post_rewrite_hook);
2756 argv_array_push(&hook.args, "rebase");
2757 /* we don't care if this hook failed */
2761 apply_autostash(opts);
2763 fprintf(stderr, "Successfully rebased and updated %s.\n",
2766 strbuf_release(&buf);
2767 strbuf_release(&head_ref);
2771 * Sequence of picks finished successfully; cleanup by
2772 * removing the .git/sequencer directory
2774 return sequencer_remove_state(opts);
2777 static int continue_single_pick(void)
2779 const char *argv[] = { "commit", NULL };
2781 if (!file_exists(git_path_cherry_pick_head()) &&
2782 !file_exists(git_path_revert_head()))
2783 return error(_("no cherry-pick or revert in progress"));
2784 return run_command_v_opt(argv, RUN_GIT_CMD);
2787 static int commit_staged_changes(struct replay_opts *opts)
2789 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2791 if (has_unstaged_changes(1))
2792 return error(_("cannot rebase: You have unstaged changes."));
2793 if (!has_uncommitted_changes(0)) {
2794 const char *cherry_pick_head = git_path_cherry_pick_head();
2796 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2797 return error(_("could not remove CHERRY_PICK_HEAD"));
2801 if (file_exists(rebase_path_amend())) {
2802 struct strbuf rev = STRBUF_INIT;
2803 struct object_id head, to_amend;
2805 if (get_oid("HEAD", &head))
2806 return error(_("cannot amend non-existing commit"));
2807 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2808 return error(_("invalid file: '%s'"), rebase_path_amend());
2809 if (get_oid_hex(rev.buf, &to_amend))
2810 return error(_("invalid contents: '%s'"),
2811 rebase_path_amend());
2812 if (oidcmp(&head, &to_amend))
2813 return error(_("\nYou have uncommitted changes in your "
2814 "working tree. Please, commit them\n"
2815 "first and then run 'git rebase "
2816 "--continue' again."));
2818 strbuf_release(&rev);
2822 if (run_git_commit(rebase_path_message(), opts, flags))
2823 return error(_("could not commit staged changes."));
2824 unlink(rebase_path_amend());
2828 int sequencer_continue(struct replay_opts *opts)
2830 struct todo_list todo_list = TODO_LIST_INIT;
2833 if (read_and_refresh_cache(opts))
2836 if (is_rebase_i(opts)) {
2837 if (commit_staged_changes(opts))
2839 } else if (!file_exists(get_todo_path(opts)))
2840 return continue_single_pick();
2841 if (read_populate_opts(opts))
2843 if ((res = read_populate_todo(&todo_list, opts)))
2844 goto release_todo_list;
2846 if (!is_rebase_i(opts)) {
2847 /* Verify that the conflict has been resolved */
2848 if (file_exists(git_path_cherry_pick_head()) ||
2849 file_exists(git_path_revert_head())) {
2850 res = continue_single_pick();
2852 goto release_todo_list;
2854 if (index_differs_from("HEAD", NULL, 0)) {
2855 res = error_dirty_index(opts);
2856 goto release_todo_list;
2858 todo_list.current++;
2859 } else if (file_exists(rebase_path_stopped_sha())) {
2860 struct strbuf buf = STRBUF_INIT;
2861 struct object_id oid;
2863 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2864 !get_oid_committish(buf.buf, &oid))
2865 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2866 strbuf_release(&buf);
2869 res = pick_commits(&todo_list, opts);
2871 todo_list_release(&todo_list);
2875 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2877 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2878 return do_pick_commit(opts->action == REPLAY_PICK ?
2879 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2882 int sequencer_pick_revisions(struct replay_opts *opts)
2884 struct todo_list todo_list = TODO_LIST_INIT;
2885 struct object_id oid;
2889 if (read_and_refresh_cache(opts))
2892 for (i = 0; i < opts->revs->pending.nr; i++) {
2893 struct object_id oid;
2894 const char *name = opts->revs->pending.objects[i].name;
2896 /* This happens when using --stdin. */
2900 if (!get_oid(name, &oid)) {
2901 if (!lookup_commit_reference_gently(&oid, 1)) {
2902 enum object_type type = oid_object_info(&oid,
2904 return error(_("%s: can't cherry-pick a %s"),
2905 name, type_name(type));
2908 return error(_("%s: bad revision"), name);
2912 * If we were called as "git cherry-pick <commit>", just
2913 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2914 * REVERT_HEAD, and don't touch the sequencer state.
2915 * This means it is possible to cherry-pick in the middle
2916 * of a cherry-pick sequence.
2918 if (opts->revs->cmdline.nr == 1 &&
2919 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2920 opts->revs->no_walk &&
2921 !opts->revs->cmdline.rev->flags) {
2922 struct commit *cmit;
2923 if (prepare_revision_walk(opts->revs))
2924 return error(_("revision walk setup failed"));
2925 cmit = get_revision(opts->revs);
2926 if (!cmit || get_revision(opts->revs))
2927 return error("BUG: expected exactly one commit from walk");
2928 return single_pick(cmit, opts);
2932 * Start a new cherry-pick/ revert sequence; but
2933 * first, make sure that an existing one isn't in
2937 if (walk_revs_populate_todo(&todo_list, opts) ||
2938 create_seq_dir() < 0)
2940 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2941 return error(_("can't revert as initial commit"));
2942 if (save_head(oid_to_hex(&oid)))
2944 if (save_opts(opts))
2946 update_abort_safety_file();
2947 res = pick_commits(&todo_list, opts);
2948 todo_list_release(&todo_list);
2952 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2954 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2955 struct strbuf sob = STRBUF_INIT;
2958 strbuf_addstr(&sob, sign_off_header);
2959 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2960 getenv("GIT_COMMITTER_EMAIL")));
2961 strbuf_addch(&sob, '\n');
2964 strbuf_complete_line(msgbuf);
2967 * If the whole message buffer is equal to the sob, pretend that we
2968 * found a conforming footer with a matching sob
2970 if (msgbuf->len - ignore_footer == sob.len &&
2971 !strncmp(msgbuf->buf, sob.buf, sob.len))
2974 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2977 const char *append_newlines = NULL;
2978 size_t len = msgbuf->len - ignore_footer;
2982 * The buffer is completely empty. Leave foom for
2983 * the title and body to be filled in by the user.
2985 append_newlines = "\n\n";
2986 } else if (len == 1) {
2988 * Buffer contains a single newline. Add another
2989 * so that we leave room for the title and body.
2991 append_newlines = "\n";
2992 } else if (msgbuf->buf[len - 2] != '\n') {
2994 * Buffer ends with a single newline. Add another
2995 * so that there is an empty line between the message
2998 append_newlines = "\n";
2999 } /* else, the buffer already ends with two newlines. */
3001 if (append_newlines)
3002 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3003 append_newlines, strlen(append_newlines));
3006 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3007 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3010 strbuf_release(&sob);
3013 int sequencer_make_script(FILE *out, int argc, const char **argv,
3016 char *format = NULL;
3017 struct pretty_print_context pp = {0};
3018 struct strbuf buf = STRBUF_INIT;
3019 struct rev_info revs;
3020 struct commit *commit;
3021 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3022 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
3024 init_revisions(&revs, NULL);
3025 revs.verbose_header = 1;
3026 revs.max_parents = 1;
3027 revs.cherry_mark = 1;
3030 revs.right_only = 1;
3031 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3032 revs.topo_order = 1;
3034 revs.pretty_given = 1;
3035 git_config_get_string("rebase.instructionFormat", &format);
3036 if (!format || !*format) {
3038 format = xstrdup("%s");
3040 get_commit_format(format, &revs);
3042 pp.fmt = revs.commit_format;
3043 pp.output_encoding = get_log_output_encoding();
3045 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3046 return error(_("make_script: unhandled options"));
3048 if (prepare_revision_walk(&revs) < 0)
3049 return error(_("make_script: error preparing revisions"));
3051 while ((commit = get_revision(&revs))) {
3052 int is_empty = is_original_commit_empty(commit);
3054 if (!is_empty && (commit->object.flags & PATCHSAME))
3057 if (!keep_empty && is_empty)
3058 strbuf_addf(&buf, "%c ", comment_line_char);
3059 strbuf_addf(&buf, "%s %s ", insn,
3060 oid_to_hex(&commit->object.oid));
3061 pretty_print_commit(&pp, commit, &buf);
3062 strbuf_addch(&buf, '\n');
3063 fputs(buf.buf, out);
3065 strbuf_release(&buf);
3070 * Add commands after pick and (series of) squash/fixup commands
3073 int sequencer_add_exec_commands(const char *commands)
3075 const char *todo_file = rebase_path_todo();
3076 struct todo_list todo_list = TODO_LIST_INIT;
3077 struct todo_item *item;
3078 struct strbuf *buf = &todo_list.buf;
3079 size_t offset = 0, commands_len = strlen(commands);
3082 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3083 return error(_("could not read '%s'."), todo_file);
3085 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3086 todo_list_release(&todo_list);
3087 return error(_("unusable todo list: '%s'"), todo_file);
3091 /* insert <commands> before every pick except the first one */
3092 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3093 if (item->command == TODO_PICK && !first) {
3094 strbuf_insert(buf, item->offset_in_buf + offset,
3095 commands, commands_len);
3096 offset += commands_len;
3101 /* append final <commands> */
3102 strbuf_add(buf, commands, commands_len);
3104 i = write_message(buf->buf, buf->len, todo_file, 0);
3105 todo_list_release(&todo_list);
3109 int transform_todos(unsigned flags)
3111 const char *todo_file = rebase_path_todo();
3112 struct todo_list todo_list = TODO_LIST_INIT;
3113 struct strbuf buf = STRBUF_INIT;
3114 struct todo_item *item;
3117 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3118 return error(_("could not read '%s'."), todo_file);
3120 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3121 todo_list_release(&todo_list);
3122 return error(_("unusable todo list: '%s'"), todo_file);
3125 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3126 /* if the item is not a command write it and continue */
3127 if (item->command >= TODO_COMMENT) {
3128 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3132 /* add command to the buffer */
3133 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3134 strbuf_addch(&buf, command_to_char(item->command));
3136 strbuf_addstr(&buf, command_to_string(item->command));
3140 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3141 short_commit_name(item->commit) :
3142 oid_to_hex(&item->commit->object.oid);
3144 strbuf_addf(&buf, " %s", oid);
3146 /* add all the rest */
3148 strbuf_addch(&buf, '\n');
3150 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3153 i = write_message(buf.buf, buf.len, todo_file, 0);
3154 todo_list_release(&todo_list);
3159 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3162 static enum check_level get_missing_commit_check_level(void)
3166 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3167 !strcasecmp("ignore", value))
3168 return CHECK_IGNORE;
3169 if (!strcasecmp("warn", value))
3171 if (!strcasecmp("error", value))
3173 warning(_("unrecognized setting %s for option "
3174 "rebase.missingCommitsCheck. Ignoring."), value);
3175 return CHECK_IGNORE;
3179 * Check if the user dropped some commits by mistake
3180 * Behaviour determined by rebase.missingCommitsCheck.
3181 * Check if there is an unrecognized command or a
3182 * bad SHA-1 in a command.
3184 int check_todo_list(void)
3186 enum check_level check_level = get_missing_commit_check_level();
3187 struct strbuf todo_file = STRBUF_INIT;
3188 struct todo_list todo_list = TODO_LIST_INIT;
3189 struct strbuf missing = STRBUF_INIT;
3190 int advise_to_edit_todo = 0, res = 0, i;
3192 strbuf_addstr(&todo_file, rebase_path_todo());
3193 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3197 advise_to_edit_todo = res =
3198 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3200 if (res || check_level == CHECK_IGNORE)
3203 /* Mark the commits in git-rebase-todo as seen */
3204 for (i = 0; i < todo_list.nr; i++) {
3205 struct commit *commit = todo_list.items[i].commit;
3207 commit->util = (void *)1;
3210 todo_list_release(&todo_list);
3211 strbuf_addstr(&todo_file, ".backup");
3212 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3216 strbuf_release(&todo_file);
3217 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3219 /* Find commits in git-rebase-todo.backup yet unseen */
3220 for (i = todo_list.nr - 1; i >= 0; i--) {
3221 struct todo_item *item = todo_list.items + i;
3222 struct commit *commit = item->commit;
3223 if (commit && !commit->util) {
3224 strbuf_addf(&missing, " - %s %.*s\n",
3225 short_commit_name(commit),
3226 item->arg_len, item->arg);
3227 commit->util = (void *)1;
3231 /* Warn about missing commits */
3235 if (check_level == CHECK_ERROR)
3236 advise_to_edit_todo = res = 1;
3239 _("Warning: some commits may have been dropped accidentally.\n"
3240 "Dropped commits (newer to older):\n"));
3242 /* Make the list user-friendly and display */
3243 fputs(missing.buf, stderr);
3244 strbuf_release(&missing);
3246 fprintf(stderr, _("To avoid this message, use \"drop\" to "
3247 "explicitly remove a commit.\n\n"
3248 "Use 'git config rebase.missingCommitsCheck' to change "
3249 "the level of warnings.\n"
3250 "The possible behaviours are: ignore, warn, error.\n\n"));
3253 strbuf_release(&todo_file);
3254 todo_list_release(&todo_list);
3256 if (advise_to_edit_todo)
3258 _("You can fix this with 'git rebase --edit-todo' "
3259 "and then run 'git rebase --continue'.\n"
3260 "Or you can abort the rebase with 'git rebase"
3266 static int rewrite_file(const char *path, const char *buf, size_t len)
3269 int fd = open(path, O_WRONLY | O_TRUNC);
3271 return error_errno(_("could not open '%s' for writing"), path);
3272 if (write_in_full(fd, buf, len) < 0)
3273 rc = error_errno(_("could not write to '%s'"), path);
3274 if (close(fd) && !rc)
3275 rc = error_errno(_("could not close '%s'"), path);
3279 /* skip picking commits whose parents are unchanged */
3280 int skip_unnecessary_picks(void)
3282 const char *todo_file = rebase_path_todo();
3283 struct strbuf buf = STRBUF_INIT;
3284 struct todo_list todo_list = TODO_LIST_INIT;
3285 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3288 if (!read_oneliner(&buf, rebase_path_onto(), 0))
3289 return error(_("could not read 'onto'"));
3290 if (get_oid(buf.buf, &onto_oid)) {
3291 strbuf_release(&buf);
3292 return error(_("need a HEAD to fixup"));
3294 strbuf_release(&buf);
3296 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
3298 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3299 todo_list_release(&todo_list);
3303 for (i = 0; i < todo_list.nr; i++) {
3304 struct todo_item *item = todo_list.items + i;
3306 if (item->command >= TODO_NOOP)
3308 if (item->command != TODO_PICK)
3310 if (parse_commit(item->commit)) {
3311 todo_list_release(&todo_list);
3312 return error(_("could not parse commit '%s'"),
3313 oid_to_hex(&item->commit->object.oid));
3315 if (!item->commit->parents)
3316 break; /* root commit */
3317 if (item->commit->parents->next)
3318 break; /* merge commit */
3319 parent_oid = &item->commit->parents->item->object.oid;
3320 if (hashcmp(parent_oid->hash, oid->hash))
3322 oid = &item->commit->object.oid;
3325 int offset = get_item_line_offset(&todo_list, i);
3326 const char *done_path = rebase_path_done();
3328 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3330 error_errno(_("could not open '%s' for writing"),
3332 todo_list_release(&todo_list);
3335 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3336 error_errno(_("could not write to '%s'"), done_path);
3337 todo_list_release(&todo_list);
3343 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
3344 todo_list.buf.len - offset) < 0) {
3345 todo_list_release(&todo_list);
3349 todo_list.current = i;
3350 if (is_fixup(peek_command(&todo_list, 0)))
3351 record_in_rewritten(oid, peek_command(&todo_list, 0));
3354 todo_list_release(&todo_list);
3355 printf("%s\n", oid_to_hex(oid));
3360 struct subject2item_entry {
3361 struct hashmap_entry entry;
3363 char subject[FLEX_ARRAY];
3366 static int subject2item_cmp(const void *fndata,
3367 const struct subject2item_entry *a,
3368 const struct subject2item_entry *b, const void *key)
3370 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3374 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3375 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3376 * after the former, and change "pick" to "fixup"/"squash".
3378 * Note that if the config has specified a custom instruction format, each log
3379 * message will have to be retrieved from the commit (as the oneline in the
3380 * script cannot be trusted) in order to normalize the autosquash arrangement.
3382 int rearrange_squash(void)
3384 const char *todo_file = rebase_path_todo();
3385 struct todo_list todo_list = TODO_LIST_INIT;
3386 struct hashmap subject2item;
3387 int res = 0, rearranged = 0, *next, *tail, i;
3390 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
3392 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3393 todo_list_release(&todo_list);
3398 * The hashmap maps onelines to the respective todo list index.
3400 * If any items need to be rearranged, the next[i] value will indicate
3401 * which item was moved directly after the i'th.
3403 * In that case, last[i] will indicate the index of the latest item to
3404 * be moved to appear after the i'th.
3406 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3407 NULL, todo_list.nr);
3408 ALLOC_ARRAY(next, todo_list.nr);
3409 ALLOC_ARRAY(tail, todo_list.nr);
3410 ALLOC_ARRAY(subjects, todo_list.nr);
3411 for (i = 0; i < todo_list.nr; i++) {
3412 struct strbuf buf = STRBUF_INIT;
3413 struct todo_item *item = todo_list.items + i;
3414 const char *commit_buffer, *subject, *p;
3417 struct subject2item_entry *entry;
3419 next[i] = tail[i] = -1;
3420 if (!item->commit || item->command == TODO_DROP) {
3425 if (is_fixup(item->command)) {
3426 todo_list_release(&todo_list);
3427 return error(_("the script was already rearranged."));
3430 item->commit->util = item;
3432 parse_commit(item->commit);
3433 commit_buffer = get_commit_buffer(item->commit, NULL);
3434 find_commit_subject(commit_buffer, &subject);
3435 format_subject(&buf, subject, " ");
3436 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3437 unuse_commit_buffer(item->commit, commit_buffer);
3438 if ((skip_prefix(subject, "fixup! ", &p) ||
3439 skip_prefix(subject, "squash! ", &p))) {
3440 struct commit *commit2;
3445 if (!skip_prefix(p, "fixup! ", &p) &&
3446 !skip_prefix(p, "squash! ", &p))
3450 if ((entry = hashmap_get_from_hash(&subject2item,
3452 /* found by title */
3454 else if (!strchr(p, ' ') &&
3456 lookup_commit_reference_by_name(p)) &&
3458 /* found by commit name */
3459 i2 = (struct todo_item *)commit2->util
3462 /* copy can be a prefix of the commit subject */
3463 for (i2 = 0; i2 < i; i2++)
3465 starts_with(subjects[i2], p))
3473 todo_list.items[i].command =
3474 starts_with(subject, "fixup!") ?
3475 TODO_FIXUP : TODO_SQUASH;
3481 } else if (!hashmap_get_from_hash(&subject2item,
3482 strhash(subject), subject)) {
3483 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3485 hashmap_entry_init(entry, strhash(entry->subject));
3486 hashmap_put(&subject2item, entry);
3491 struct strbuf buf = STRBUF_INIT;
3493 for (i = 0; i < todo_list.nr; i++) {
3494 enum todo_command command = todo_list.items[i].command;
3498 * Initially, all commands are 'pick's. If it is a
3499 * fixup or a squash now, we have rearranged it.
3501 if (is_fixup(command))
3506 get_item_line(&todo_list, cur);
3508 get_item_line(&todo_list, cur + 1);
3510 /* replace 'pick', by 'fixup' or 'squash' */
3511 command = todo_list.items[cur].command;
3512 if (is_fixup(command)) {
3514 todo_command_info[command].str);
3515 bol += strcspn(bol, " \t");
3518 strbuf_add(&buf, bol, eol - bol);
3524 res = rewrite_file(todo_file, buf.buf, buf.len);
3525 strbuf_release(&buf);
3530 for (i = 0; i < todo_list.nr; i++)
3533 hashmap_free(&subject2item, 1);
3534 todo_list_release(&todo_list);