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 */
1310 /* commands that do nothing but are counted for reporting progress */
1313 /* comments (not counted for reporting progress) */
1320 } todo_command_info[] = {
1335 static const char *command_to_string(const enum todo_command command)
1337 if (command < TODO_COMMENT)
1338 return todo_command_info[command].str;
1339 die("Unknown command: %d", command);
1342 static char command_to_char(const enum todo_command command)
1344 if (command < TODO_COMMENT && todo_command_info[command].c)
1345 return todo_command_info[command].c;
1346 return comment_line_char;
1349 static int is_noop(const enum todo_command command)
1351 return TODO_NOOP <= command;
1354 static int is_fixup(enum todo_command command)
1356 return command == TODO_FIXUP || command == TODO_SQUASH;
1359 static int update_squash_messages(enum todo_command command,
1360 struct commit *commit, struct replay_opts *opts)
1362 struct strbuf buf = STRBUF_INIT;
1364 const char *message, *body;
1366 if (file_exists(rebase_path_squash_msg())) {
1367 struct strbuf header = STRBUF_INIT;
1370 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1371 return error(_("could not read '%s'"),
1372 rebase_path_squash_msg());
1375 eol = strchrnul(buf.buf, '\n');
1376 if (buf.buf[0] != comment_line_char ||
1377 (p += strcspn(p, "0123456789\n")) == eol)
1378 return error(_("unexpected 1st line of squash message:"
1380 (int)(eol - buf.buf), buf.buf);
1381 count = strtol(p, NULL, 10);
1384 return error(_("invalid 1st line of squash message:\n"
1386 (int)(eol - buf.buf), buf.buf);
1388 strbuf_addf(&header, "%c ", comment_line_char);
1389 strbuf_addf(&header,
1390 _("This is a combination of %d commits."), ++count);
1391 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1392 strbuf_release(&header);
1394 struct object_id head;
1395 struct commit *head_commit;
1396 const char *head_message, *body;
1398 if (get_oid("HEAD", &head))
1399 return error(_("need a HEAD to fixup"));
1400 if (!(head_commit = lookup_commit_reference(&head)))
1401 return error(_("could not read HEAD"));
1402 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1403 return error(_("could not read HEAD's commit message"));
1405 find_commit_subject(head_message, &body);
1406 if (write_message(body, strlen(body),
1407 rebase_path_fixup_msg(), 0)) {
1408 unuse_commit_buffer(head_commit, head_message);
1409 return error(_("cannot write '%s'"),
1410 rebase_path_fixup_msg());
1414 strbuf_addf(&buf, "%c ", comment_line_char);
1415 strbuf_addf(&buf, _("This is a combination of %d commits."),
1417 strbuf_addf(&buf, "\n%c ", comment_line_char);
1418 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1419 strbuf_addstr(&buf, "\n\n");
1420 strbuf_addstr(&buf, body);
1422 unuse_commit_buffer(head_commit, head_message);
1425 if (!(message = get_commit_buffer(commit, NULL)))
1426 return error(_("could not read commit message of %s"),
1427 oid_to_hex(&commit->object.oid));
1428 find_commit_subject(message, &body);
1430 if (command == TODO_SQUASH) {
1431 unlink(rebase_path_fixup_msg());
1432 strbuf_addf(&buf, "\n%c ", comment_line_char);
1433 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1434 strbuf_addstr(&buf, "\n\n");
1435 strbuf_addstr(&buf, body);
1436 } else if (command == TODO_FIXUP) {
1437 strbuf_addf(&buf, "\n%c ", comment_line_char);
1438 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1440 strbuf_addstr(&buf, "\n\n");
1441 strbuf_add_commented_lines(&buf, body, strlen(body));
1443 return error(_("unknown command: %d"), command);
1444 unuse_commit_buffer(commit, message);
1446 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1447 strbuf_release(&buf);
1451 static void flush_rewritten_pending(void) {
1452 struct strbuf buf = STRBUF_INIT;
1453 struct object_id newoid;
1456 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1457 !get_oid("HEAD", &newoid) &&
1458 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1459 char *bol = buf.buf, *eol;
1462 eol = strchrnul(bol, '\n');
1463 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1464 bol, oid_to_hex(&newoid));
1470 unlink(rebase_path_rewritten_pending());
1472 strbuf_release(&buf);
1475 static void record_in_rewritten(struct object_id *oid,
1476 enum todo_command next_command) {
1477 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1482 fprintf(out, "%s\n", oid_to_hex(oid));
1485 if (!is_fixup(next_command))
1486 flush_rewritten_pending();
1489 static int do_pick_commit(enum todo_command command, struct commit *commit,
1490 struct replay_opts *opts, int final_fixup)
1492 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1493 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1494 struct object_id head;
1495 struct commit *base, *next, *parent;
1496 const char *base_label, *next_label;
1497 char *author = NULL;
1498 struct commit_message msg = { NULL, NULL, NULL, NULL };
1499 struct strbuf msgbuf = STRBUF_INIT;
1500 int res, unborn = 0, allow;
1502 if (opts->no_commit) {
1504 * We do not intend to commit immediately. We just want to
1505 * merge the differences in, so let's compute the tree
1506 * that represents the "current" state for merge-recursive
1509 if (write_cache_as_tree(&head, 0, NULL))
1510 return error(_("your index file is unmerged."));
1512 unborn = get_oid("HEAD", &head);
1514 oidcpy(&head, the_hash_algo->empty_tree);
1515 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1517 return error_dirty_index(opts);
1521 if (!commit->parents)
1523 else if (commit->parents->next) {
1524 /* Reverting or cherry-picking a merge commit */
1526 struct commit_list *p;
1528 if (!opts->mainline)
1529 return error(_("commit %s is a merge but no -m option was given."),
1530 oid_to_hex(&commit->object.oid));
1532 for (cnt = 1, p = commit->parents;
1533 cnt != opts->mainline && p;
1536 if (cnt != opts->mainline || !p)
1537 return error(_("commit %s does not have parent %d"),
1538 oid_to_hex(&commit->object.oid), opts->mainline);
1540 } else if (0 < opts->mainline)
1541 return error(_("mainline was specified but commit %s is not a merge."),
1542 oid_to_hex(&commit->object.oid));
1544 parent = commit->parents->item;
1546 if (get_message(commit, &msg) != 0)
1547 return error(_("cannot get commit message for %s"),
1548 oid_to_hex(&commit->object.oid));
1550 if (opts->allow_ff && !is_fixup(command) &&
1551 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1552 (!parent && unborn))) {
1553 if (is_rebase_i(opts))
1554 write_author_script(msg.message);
1555 res = fast_forward_to(&commit->object.oid, &head, unborn,
1557 if (res || command != TODO_REWORD)
1559 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1561 goto fast_forward_edit;
1563 if (parent && parse_commit(parent) < 0)
1564 /* TRANSLATORS: The first %s will be a "todo" command like
1565 "revert" or "pick", the second %s a SHA1. */
1566 return error(_("%s: cannot parse parent commit %s"),
1567 command_to_string(command),
1568 oid_to_hex(&parent->object.oid));
1571 * "commit" is an existing commit. We would want to apply
1572 * the difference it introduces since its first parent "prev"
1573 * on top of the current HEAD if we are cherry-pick. Or the
1574 * reverse of it if we are revert.
1577 if (command == TODO_REVERT) {
1579 base_label = msg.label;
1581 next_label = msg.parent_label;
1582 strbuf_addstr(&msgbuf, "Revert \"");
1583 strbuf_addstr(&msgbuf, msg.subject);
1584 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1585 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1587 if (commit->parents && commit->parents->next) {
1588 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1589 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1591 strbuf_addstr(&msgbuf, ".\n");
1596 base_label = msg.parent_label;
1598 next_label = msg.label;
1600 /* Append the commit log message to msgbuf. */
1601 if (find_commit_subject(msg.message, &p))
1602 strbuf_addstr(&msgbuf, p);
1604 if (opts->record_origin) {
1605 strbuf_complete_line(&msgbuf);
1606 if (!has_conforming_footer(&msgbuf, NULL, 0))
1607 strbuf_addch(&msgbuf, '\n');
1608 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1609 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1610 strbuf_addstr(&msgbuf, ")\n");
1612 if (!is_fixup(command))
1613 author = get_author(msg.message);
1616 if (command == TODO_REWORD)
1617 flags |= EDIT_MSG | VERIFY_MSG;
1618 else if (is_fixup(command)) {
1619 if (update_squash_messages(command, commit, opts))
1623 msg_file = rebase_path_squash_msg();
1624 else if (file_exists(rebase_path_fixup_msg())) {
1625 flags |= CLEANUP_MSG;
1626 msg_file = rebase_path_fixup_msg();
1628 const char *dest = git_path_squash_msg();
1630 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1631 return error(_("could not rename '%s' to '%s'"),
1632 rebase_path_squash_msg(), dest);
1633 unlink(git_path_merge_msg());
1639 if (opts->signoff && !is_fixup(command))
1640 append_signoff(&msgbuf, 0, 0);
1642 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1644 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1645 res = do_recursive_merge(base, next, base_label, next_label,
1646 &head, &msgbuf, opts);
1649 res |= write_message(msgbuf.buf, msgbuf.len,
1650 git_path_merge_msg(), 0);
1652 struct commit_list *common = NULL;
1653 struct commit_list *remotes = NULL;
1655 res = write_message(msgbuf.buf, msgbuf.len,
1656 git_path_merge_msg(), 0);
1658 commit_list_insert(base, &common);
1659 commit_list_insert(next, &remotes);
1660 res |= try_merge_command(opts->strategy,
1661 opts->xopts_nr, (const char **)opts->xopts,
1662 common, oid_to_hex(&head), remotes);
1663 free_commit_list(common);
1664 free_commit_list(remotes);
1666 strbuf_release(&msgbuf);
1669 * If the merge was clean or if it failed due to conflict, we write
1670 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1671 * However, if the merge did not even start, then we don't want to
1674 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1675 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1676 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1678 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1679 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1680 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1684 error(command == TODO_REVERT
1685 ? _("could not revert %s... %s")
1686 : _("could not apply %s... %s"),
1687 short_commit_name(commit), msg.subject);
1688 print_advice(res == 1, opts);
1689 rerere(opts->allow_rerere_auto);
1693 allow = allow_empty(opts, commit);
1698 flags |= ALLOW_EMPTY;
1699 if (!opts->no_commit) {
1701 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1702 res = do_commit(msg_file, author, opts, flags);
1704 res = error(_("unable to parse commit author"));
1707 if (!res && final_fixup) {
1708 unlink(rebase_path_fixup_msg());
1709 unlink(rebase_path_squash_msg());
1713 free_message(commit, &msg);
1715 update_abort_safety_file();
1720 static int prepare_revs(struct replay_opts *opts)
1723 * picking (but not reverting) ranges (but not individual revisions)
1724 * should be done in reverse
1726 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1727 opts->revs->reverse ^= 1;
1729 if (prepare_revision_walk(opts->revs))
1730 return error(_("revision walk setup failed"));
1732 if (!opts->revs->commits)
1733 return error(_("empty commit set passed"));
1737 static int read_and_refresh_cache(struct replay_opts *opts)
1739 struct lock_file index_lock = LOCK_INIT;
1740 int index_fd = hold_locked_index(&index_lock, 0);
1741 if (read_index_preload(&the_index, NULL) < 0) {
1742 rollback_lock_file(&index_lock);
1743 return error(_("git %s: failed to read the index"),
1744 _(action_name(opts)));
1746 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1747 if (index_fd >= 0) {
1748 if (write_locked_index(&the_index, &index_lock,
1749 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1750 return error(_("git %s: failed to refresh the index"),
1751 _(action_name(opts)));
1758 enum todo_command command;
1759 struct commit *commit;
1762 size_t offset_in_buf;
1767 struct todo_item *items;
1768 int nr, alloc, current;
1769 int done_nr, total_nr;
1770 struct stat_data stat;
1773 #define TODO_LIST_INIT { STRBUF_INIT }
1775 static void todo_list_release(struct todo_list *todo_list)
1777 strbuf_release(&todo_list->buf);
1778 FREE_AND_NULL(todo_list->items);
1779 todo_list->nr = todo_list->alloc = 0;
1782 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1784 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1785 return todo_list->items + todo_list->nr++;
1788 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1790 struct object_id commit_oid;
1791 char *end_of_object_name;
1792 int i, saved, status, padding;
1795 bol += strspn(bol, " \t");
1797 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1798 item->command = TODO_COMMENT;
1799 item->commit = NULL;
1801 item->arg_len = eol - bol;
1805 for (i = 0; i < TODO_COMMENT; i++)
1806 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1809 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1814 if (i >= TODO_COMMENT)
1817 /* Eat up extra spaces/ tabs before object name */
1818 padding = strspn(bol, " \t");
1821 if (item->command == TODO_NOOP) {
1823 return error(_("%s does not accept arguments: '%s'"),
1824 command_to_string(item->command), bol);
1825 item->commit = NULL;
1827 item->arg_len = eol - bol;
1832 return error(_("missing arguments for %s"),
1833 command_to_string(item->command));
1835 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1836 item->command == TODO_RESET) {
1837 item->commit = NULL;
1839 item->arg_len = (int)(eol - bol);
1843 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1844 saved = *end_of_object_name;
1845 *end_of_object_name = '\0';
1846 status = get_oid(bol, &commit_oid);
1847 *end_of_object_name = saved;
1849 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1850 item->arg_len = (int)(eol - item->arg);
1855 item->commit = lookup_commit_reference(&commit_oid);
1856 return !item->commit;
1859 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1861 struct todo_item *item;
1862 char *p = buf, *next_p;
1863 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1865 for (i = 1; *p; i++, p = next_p) {
1866 char *eol = strchrnul(p, '\n');
1868 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1870 if (p != eol && eol[-1] == '\r')
1871 eol--; /* strip Carriage Return */
1873 item = append_new_todo(todo_list);
1874 item->offset_in_buf = p - todo_list->buf.buf;
1875 if (parse_insn_line(item, p, eol)) {
1876 res = error(_("invalid line %d: %.*s"),
1877 i, (int)(eol - p), p);
1878 item->command = TODO_NOOP;
1883 else if (is_fixup(item->command))
1884 return error(_("cannot '%s' without a previous commit"),
1885 command_to_string(item->command));
1886 else if (!is_noop(item->command))
1893 static int count_commands(struct todo_list *todo_list)
1897 for (i = 0; i < todo_list->nr; i++)
1898 if (todo_list->items[i].command != TODO_COMMENT)
1904 static int get_item_line_offset(struct todo_list *todo_list, int index)
1906 return index < todo_list->nr ?
1907 todo_list->items[index].offset_in_buf : todo_list->buf.len;
1910 static const char *get_item_line(struct todo_list *todo_list, int index)
1912 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
1915 static int get_item_line_length(struct todo_list *todo_list, int index)
1917 return get_item_line_offset(todo_list, index + 1)
1918 - get_item_line_offset(todo_list, index);
1921 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
1926 fd = open(path, O_RDONLY);
1928 return error_errno(_("could not open '%s'"), path);
1929 len = strbuf_read(sb, fd, 0);
1932 return error(_("could not read '%s'."), path);
1936 static int read_populate_todo(struct todo_list *todo_list,
1937 struct replay_opts *opts)
1940 const char *todo_file = get_todo_path(opts);
1943 strbuf_reset(&todo_list->buf);
1944 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
1947 res = stat(todo_file, &st);
1949 return error(_("could not stat '%s'"), todo_file);
1950 fill_stat_data(&todo_list->stat, &st);
1952 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1954 if (is_rebase_i(opts))
1955 return error(_("please fix this using "
1956 "'git rebase --edit-todo'."));
1957 return error(_("unusable instruction sheet: '%s'"), todo_file);
1960 if (!todo_list->nr &&
1961 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1962 return error(_("no commits parsed."));
1964 if (!is_rebase_i(opts)) {
1965 enum todo_command valid =
1966 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1969 for (i = 0; i < todo_list->nr; i++)
1970 if (valid == todo_list->items[i].command)
1972 else if (valid == TODO_PICK)
1973 return error(_("cannot cherry-pick during a revert."));
1975 return error(_("cannot revert during a cherry-pick."));
1978 if (is_rebase_i(opts)) {
1979 struct todo_list done = TODO_LIST_INIT;
1980 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1982 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1983 !parse_insn_buffer(done.buf.buf, &done))
1984 todo_list->done_nr = count_commands(&done);
1986 todo_list->done_nr = 0;
1988 todo_list->total_nr = todo_list->done_nr
1989 + count_commands(todo_list);
1990 todo_list_release(&done);
1993 fprintf(f, "%d\n", todo_list->total_nr);
2001 static int git_config_string_dup(char **dest,
2002 const char *var, const char *value)
2005 return config_error_nonbool(var);
2007 *dest = xstrdup(value);
2011 static int populate_opts_cb(const char *key, const char *value, void *data)
2013 struct replay_opts *opts = data;
2018 else if (!strcmp(key, "options.no-commit"))
2019 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2020 else if (!strcmp(key, "options.edit"))
2021 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2022 else if (!strcmp(key, "options.signoff"))
2023 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2024 else if (!strcmp(key, "options.record-origin"))
2025 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2026 else if (!strcmp(key, "options.allow-ff"))
2027 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2028 else if (!strcmp(key, "options.mainline"))
2029 opts->mainline = git_config_int(key, value);
2030 else if (!strcmp(key, "options.strategy"))
2031 git_config_string_dup(&opts->strategy, key, value);
2032 else if (!strcmp(key, "options.gpg-sign"))
2033 git_config_string_dup(&opts->gpg_sign, key, value);
2034 else if (!strcmp(key, "options.strategy-option")) {
2035 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2036 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2037 } else if (!strcmp(key, "options.allow-rerere-auto"))
2038 opts->allow_rerere_auto =
2039 git_config_bool_or_int(key, value, &error_flag) ?
2040 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2042 return error(_("invalid key: %s"), key);
2045 return error(_("invalid value for %s: %s"), key, value);
2050 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2055 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2057 opts->strategy = strbuf_detach(buf, NULL);
2058 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2061 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2062 for (i = 0; i < opts->xopts_nr; i++) {
2063 const char *arg = opts->xopts[i];
2065 skip_prefix(arg, "--", &arg);
2066 opts->xopts[i] = xstrdup(arg);
2070 static int read_populate_opts(struct replay_opts *opts)
2072 if (is_rebase_i(opts)) {
2073 struct strbuf buf = STRBUF_INIT;
2075 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2076 if (!starts_with(buf.buf, "-S"))
2079 free(opts->gpg_sign);
2080 opts->gpg_sign = xstrdup(buf.buf + 2);
2085 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2086 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2087 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2088 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2089 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2093 if (file_exists(rebase_path_verbose()))
2096 if (file_exists(rebase_path_signoff())) {
2101 read_strategy_opts(opts, &buf);
2102 strbuf_release(&buf);
2107 if (!file_exists(git_path_opts_file()))
2110 * The function git_parse_source(), called from git_config_from_file(),
2111 * may die() in case of a syntactically incorrect file. We do not care
2112 * about this case, though, because we wrote that file ourselves, so we
2113 * are pretty certain that it is syntactically correct.
2115 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2116 return error(_("malformed options sheet: '%s'"),
2117 git_path_opts_file());
2121 static int walk_revs_populate_todo(struct todo_list *todo_list,
2122 struct replay_opts *opts)
2124 enum todo_command command = opts->action == REPLAY_PICK ?
2125 TODO_PICK : TODO_REVERT;
2126 const char *command_string = todo_command_info[command].str;
2127 struct commit *commit;
2129 if (prepare_revs(opts))
2132 while ((commit = get_revision(opts->revs))) {
2133 struct todo_item *item = append_new_todo(todo_list);
2134 const char *commit_buffer = get_commit_buffer(commit, NULL);
2135 const char *subject;
2138 item->command = command;
2139 item->commit = commit;
2142 item->offset_in_buf = todo_list->buf.len;
2143 subject_len = find_commit_subject(commit_buffer, &subject);
2144 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2145 short_commit_name(commit), subject_len, subject);
2146 unuse_commit_buffer(commit, commit_buffer);
2151 static int create_seq_dir(void)
2153 if (file_exists(git_path_seq_dir())) {
2154 error(_("a cherry-pick or revert is already in progress"));
2155 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2157 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2158 return error_errno(_("could not create sequencer directory '%s'"),
2159 git_path_seq_dir());
2163 static int save_head(const char *head)
2165 struct lock_file head_lock = LOCK_INIT;
2166 struct strbuf buf = STRBUF_INIT;
2170 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2172 return error_errno(_("could not lock HEAD"));
2173 strbuf_addf(&buf, "%s\n", head);
2174 written = write_in_full(fd, buf.buf, buf.len);
2175 strbuf_release(&buf);
2177 error_errno(_("could not write to '%s'"), git_path_head_file());
2178 rollback_lock_file(&head_lock);
2181 if (commit_lock_file(&head_lock) < 0)
2182 return error(_("failed to finalize '%s'"), git_path_head_file());
2186 static int rollback_is_safe(void)
2188 struct strbuf sb = STRBUF_INIT;
2189 struct object_id expected_head, actual_head;
2191 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2193 if (get_oid_hex(sb.buf, &expected_head)) {
2194 strbuf_release(&sb);
2195 die(_("could not parse %s"), git_path_abort_safety_file());
2197 strbuf_release(&sb);
2199 else if (errno == ENOENT)
2200 oidclr(&expected_head);
2202 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2204 if (get_oid("HEAD", &actual_head))
2205 oidclr(&actual_head);
2207 return !oidcmp(&actual_head, &expected_head);
2210 static int reset_for_rollback(const struct object_id *oid)
2212 const char *argv[4]; /* reset --merge <arg> + NULL */
2215 argv[1] = "--merge";
2216 argv[2] = oid_to_hex(oid);
2218 return run_command_v_opt(argv, RUN_GIT_CMD);
2221 static int rollback_single_pick(void)
2223 struct object_id head_oid;
2225 if (!file_exists(git_path_cherry_pick_head()) &&
2226 !file_exists(git_path_revert_head()))
2227 return error(_("no cherry-pick or revert in progress"));
2228 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2229 return error(_("cannot resolve HEAD"));
2230 if (is_null_oid(&head_oid))
2231 return error(_("cannot abort from a branch yet to be born"));
2232 return reset_for_rollback(&head_oid);
2235 int sequencer_rollback(struct replay_opts *opts)
2238 struct object_id oid;
2239 struct strbuf buf = STRBUF_INIT;
2242 f = fopen(git_path_head_file(), "r");
2243 if (!f && errno == ENOENT) {
2245 * There is no multiple-cherry-pick in progress.
2246 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2247 * a single-cherry-pick in progress, abort that.
2249 return rollback_single_pick();
2252 return error_errno(_("cannot open '%s'"), git_path_head_file());
2253 if (strbuf_getline_lf(&buf, f)) {
2254 error(_("cannot read '%s': %s"), git_path_head_file(),
2255 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2260 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2261 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2262 git_path_head_file());
2265 if (is_null_oid(&oid)) {
2266 error(_("cannot abort from a branch yet to be born"));
2270 if (!rollback_is_safe()) {
2271 /* Do not error, just do not rollback */
2272 warning(_("You seem to have moved HEAD. "
2273 "Not rewinding, check your HEAD!"));
2275 if (reset_for_rollback(&oid))
2277 strbuf_release(&buf);
2278 return sequencer_remove_state(opts);
2280 strbuf_release(&buf);
2284 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2286 struct lock_file todo_lock = LOCK_INIT;
2287 const char *todo_path = get_todo_path(opts);
2288 int next = todo_list->current, offset, fd;
2291 * rebase -i writes "git-rebase-todo" without the currently executing
2292 * command, appending it to "done" instead.
2294 if (is_rebase_i(opts))
2297 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2299 return error_errno(_("could not lock '%s'"), todo_path);
2300 offset = get_item_line_offset(todo_list, next);
2301 if (write_in_full(fd, todo_list->buf.buf + offset,
2302 todo_list->buf.len - offset) < 0)
2303 return error_errno(_("could not write to '%s'"), todo_path);
2304 if (commit_lock_file(&todo_lock) < 0)
2305 return error(_("failed to finalize '%s'"), todo_path);
2307 if (is_rebase_i(opts) && next > 0) {
2308 const char *done = rebase_path_done();
2309 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2314 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2315 get_item_line_length(todo_list, next - 1))
2317 ret = error_errno(_("could not write to '%s'"), done);
2319 ret = error_errno(_("failed to finalize '%s'"), done);
2325 static int save_opts(struct replay_opts *opts)
2327 const char *opts_file = git_path_opts_file();
2330 if (opts->no_commit)
2331 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2333 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2335 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2336 if (opts->record_origin)
2337 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2339 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2340 if (opts->mainline) {
2341 struct strbuf buf = STRBUF_INIT;
2342 strbuf_addf(&buf, "%d", opts->mainline);
2343 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2344 strbuf_release(&buf);
2347 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2349 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2352 for (i = 0; i < opts->xopts_nr; i++)
2353 res |= git_config_set_multivar_in_file_gently(opts_file,
2354 "options.strategy-option",
2355 opts->xopts[i], "^$", 0);
2357 if (opts->allow_rerere_auto)
2358 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2359 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2364 static int make_patch(struct commit *commit, struct replay_opts *opts)
2366 struct strbuf buf = STRBUF_INIT;
2367 struct rev_info log_tree_opt;
2368 const char *subject, *p;
2371 p = short_commit_name(commit);
2372 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2374 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2375 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2376 res |= error(_("could not update %s"), "REBASE_HEAD");
2378 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2379 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2380 init_revisions(&log_tree_opt, NULL);
2381 log_tree_opt.abbrev = 0;
2382 log_tree_opt.diff = 1;
2383 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2384 log_tree_opt.disable_stdin = 1;
2385 log_tree_opt.no_commit_id = 1;
2386 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2387 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2388 if (!log_tree_opt.diffopt.file)
2389 res |= error_errno(_("could not open '%s'"), buf.buf);
2391 res |= log_tree_commit(&log_tree_opt, commit);
2392 fclose(log_tree_opt.diffopt.file);
2396 strbuf_addf(&buf, "%s/message", get_dir(opts));
2397 if (!file_exists(buf.buf)) {
2398 const char *commit_buffer = get_commit_buffer(commit, NULL);
2399 find_commit_subject(commit_buffer, &subject);
2400 res |= write_message(subject, strlen(subject), buf.buf, 1);
2401 unuse_commit_buffer(commit, commit_buffer);
2403 strbuf_release(&buf);
2408 static int intend_to_amend(void)
2410 struct object_id head;
2413 if (get_oid("HEAD", &head))
2414 return error(_("cannot read HEAD"));
2416 p = oid_to_hex(&head);
2417 return write_message(p, strlen(p), rebase_path_amend(), 1);
2420 static int error_with_patch(struct commit *commit,
2421 const char *subject, int subject_len,
2422 struct replay_opts *opts, int exit_code, int to_amend)
2424 if (make_patch(commit, opts))
2428 if (intend_to_amend())
2431 fprintf(stderr, "You can amend the commit now, with\n"
2433 " git commit --amend %s\n"
2435 "Once you are satisfied with your changes, run\n"
2437 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
2438 } else if (exit_code)
2439 fprintf(stderr, "Could not apply %s... %.*s\n",
2440 short_commit_name(commit), subject_len, subject);
2445 static int error_failed_squash(struct commit *commit,
2446 struct replay_opts *opts, int subject_len, const char *subject)
2448 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2449 return error(_("could not rename '%s' to '%s'"),
2450 rebase_path_squash_msg(), rebase_path_message());
2451 unlink(rebase_path_fixup_msg());
2452 unlink(git_path_merge_msg());
2453 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2454 return error(_("could not copy '%s' to '%s'"),
2455 rebase_path_message(), git_path_merge_msg());
2456 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2459 static int do_exec(const char *command_line)
2461 struct argv_array child_env = ARGV_ARRAY_INIT;
2462 const char *child_argv[] = { NULL, NULL };
2465 fprintf(stderr, "Executing: %s\n", command_line);
2466 child_argv[0] = command_line;
2467 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2468 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2471 /* force re-reading of the cache */
2472 if (discard_cache() < 0 || read_cache() < 0)
2473 return error(_("could not read index"));
2475 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2478 warning(_("execution failed: %s\n%s"
2479 "You can fix the problem, and then run\n"
2481 " git rebase --continue\n"
2484 dirty ? N_("and made changes to the index and/or the "
2485 "working tree\n") : "");
2487 /* command not found */
2490 warning(_("execution succeeded: %s\nbut "
2491 "left changes to the index and/or the working tree\n"
2492 "Commit or stash your changes, and then run\n"
2494 " git rebase --continue\n"
2495 "\n"), command_line);
2499 argv_array_clear(&child_env);
2504 static int safe_append(const char *filename, const char *fmt, ...)
2507 struct lock_file lock = LOCK_INIT;
2508 int fd = hold_lock_file_for_update(&lock, filename,
2509 LOCK_REPORT_ON_ERROR);
2510 struct strbuf buf = STRBUF_INIT;
2515 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2516 error_errno(_("could not read '%s'"), filename);
2517 rollback_lock_file(&lock);
2520 strbuf_complete(&buf, '\n');
2522 strbuf_vaddf(&buf, fmt, ap);
2525 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2526 error_errno(_("could not write to '%s'"), filename);
2527 strbuf_release(&buf);
2528 rollback_lock_file(&lock);
2531 if (commit_lock_file(&lock) < 0) {
2532 strbuf_release(&buf);
2533 rollback_lock_file(&lock);
2534 return error(_("failed to finalize '%s'"), filename);
2537 strbuf_release(&buf);
2541 static int do_label(const char *name, int len)
2543 struct ref_store *refs = get_main_ref_store();
2544 struct ref_transaction *transaction;
2545 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2546 struct strbuf msg = STRBUF_INIT;
2548 struct object_id head_oid;
2550 if (len == 1 && *name == '#')
2551 return error("Illegal label name: '%.*s'", len, name);
2553 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2554 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2556 transaction = ref_store_transaction_begin(refs, &err);
2558 error("%s", err.buf);
2560 } else if (get_oid("HEAD", &head_oid)) {
2561 error(_("could not read HEAD"));
2563 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2564 NULL, 0, msg.buf, &err) < 0 ||
2565 ref_transaction_commit(transaction, &err)) {
2566 error("%s", err.buf);
2569 ref_transaction_free(transaction);
2570 strbuf_release(&err);
2571 strbuf_release(&msg);
2574 ret = safe_append(rebase_path_refs_to_delete(),
2575 "%s\n", ref_name.buf);
2576 strbuf_release(&ref_name);
2581 static const char *reflog_message(struct replay_opts *opts,
2582 const char *sub_action, const char *fmt, ...);
2584 static int do_reset(const char *name, int len, struct replay_opts *opts)
2586 struct strbuf ref_name = STRBUF_INIT;
2587 struct object_id oid;
2588 struct lock_file lock = LOCK_INIT;
2589 struct tree_desc desc;
2591 struct unpack_trees_options unpack_tree_opts;
2594 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2597 /* Determine the length of the label */
2598 for (i = 0; i < len; i++)
2599 if (isspace(name[i]))
2602 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2603 if (get_oid(ref_name.buf, &oid) &&
2604 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2605 error(_("could not read '%s'"), ref_name.buf);
2606 rollback_lock_file(&lock);
2607 strbuf_release(&ref_name);
2611 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2612 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2613 unpack_tree_opts.head_idx = 1;
2614 unpack_tree_opts.src_index = &the_index;
2615 unpack_tree_opts.dst_index = &the_index;
2616 unpack_tree_opts.fn = oneway_merge;
2617 unpack_tree_opts.merge = 1;
2618 unpack_tree_opts.update = 1;
2620 if (read_cache_unmerged()) {
2621 rollback_lock_file(&lock);
2622 strbuf_release(&ref_name);
2623 return error_resolve_conflict(_(action_name(opts)));
2626 if (!fill_tree_descriptor(&desc, &oid)) {
2627 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2628 rollback_lock_file(&lock);
2629 free((void *)desc.buffer);
2630 strbuf_release(&ref_name);
2634 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2635 rollback_lock_file(&lock);
2636 free((void *)desc.buffer);
2637 strbuf_release(&ref_name);
2641 tree = parse_tree_indirect(&oid);
2642 prime_cache_tree(&the_index, tree);
2644 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2645 ret = error(_("could not write index"));
2646 free((void *)desc.buffer);
2649 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2650 len, name), "HEAD", &oid,
2651 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2653 strbuf_release(&ref_name);
2657 static int is_final_fixup(struct todo_list *todo_list)
2659 int i = todo_list->current;
2661 if (!is_fixup(todo_list->items[i].command))
2664 while (++i < todo_list->nr)
2665 if (is_fixup(todo_list->items[i].command))
2667 else if (!is_noop(todo_list->items[i].command))
2672 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2676 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2677 if (!is_noop(todo_list->items[i].command))
2678 return todo_list->items[i].command;
2683 static int apply_autostash(struct replay_opts *opts)
2685 struct strbuf stash_sha1 = STRBUF_INIT;
2686 struct child_process child = CHILD_PROCESS_INIT;
2689 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2690 strbuf_release(&stash_sha1);
2693 strbuf_trim(&stash_sha1);
2696 child.no_stdout = 1;
2697 child.no_stderr = 1;
2698 argv_array_push(&child.args, "stash");
2699 argv_array_push(&child.args, "apply");
2700 argv_array_push(&child.args, stash_sha1.buf);
2701 if (!run_command(&child))
2702 fprintf(stderr, _("Applied autostash.\n"));
2704 struct child_process store = CHILD_PROCESS_INIT;
2707 argv_array_push(&store.args, "stash");
2708 argv_array_push(&store.args, "store");
2709 argv_array_push(&store.args, "-m");
2710 argv_array_push(&store.args, "autostash");
2711 argv_array_push(&store.args, "-q");
2712 argv_array_push(&store.args, stash_sha1.buf);
2713 if (run_command(&store))
2714 ret = error(_("cannot store %s"), stash_sha1.buf);
2717 _("Applying autostash resulted in conflicts.\n"
2718 "Your changes are safe in the stash.\n"
2719 "You can run \"git stash pop\" or"
2720 " \"git stash drop\" at any time.\n"));
2723 strbuf_release(&stash_sha1);
2727 static const char *reflog_message(struct replay_opts *opts,
2728 const char *sub_action, const char *fmt, ...)
2731 static struct strbuf buf = STRBUF_INIT;
2735 strbuf_addstr(&buf, action_name(opts));
2737 strbuf_addf(&buf, " (%s)", sub_action);
2739 strbuf_addstr(&buf, ": ");
2740 strbuf_vaddf(&buf, fmt, ap);
2747 static const char rescheduled_advice[] =
2748 N_("Could not execute the todo command\n"
2752 "It has been rescheduled; To edit the command before continuing, please\n"
2753 "edit the todo list first:\n"
2755 " git rebase --edit-todo\n"
2756 " git rebase --continue\n");
2758 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2760 int res = 0, reschedule = 0;
2762 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2764 assert(!(opts->signoff || opts->no_commit ||
2765 opts->record_origin || opts->edit));
2766 if (read_and_refresh_cache(opts))
2769 while (todo_list->current < todo_list->nr) {
2770 struct todo_item *item = todo_list->items + todo_list->current;
2771 if (save_todo(todo_list, opts))
2773 if (is_rebase_i(opts)) {
2774 if (item->command != TODO_COMMENT) {
2775 FILE *f = fopen(rebase_path_msgnum(), "w");
2777 todo_list->done_nr++;
2780 fprintf(f, "%d\n", todo_list->done_nr);
2783 fprintf(stderr, "Rebasing (%d/%d)%s",
2785 todo_list->total_nr,
2786 opts->verbose ? "\n" : "\r");
2788 unlink(rebase_path_message());
2789 unlink(rebase_path_author_script());
2790 unlink(rebase_path_stopped_sha());
2791 unlink(rebase_path_amend());
2792 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
2794 if (item->command <= TODO_SQUASH) {
2795 if (is_rebase_i(opts))
2796 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2797 command_to_string(item->command), NULL),
2799 res = do_pick_commit(item->command, item->commit,
2800 opts, is_final_fixup(todo_list));
2801 if (is_rebase_i(opts) && res < 0) {
2803 advise(_(rescheduled_advice),
2804 get_item_line_length(todo_list,
2805 todo_list->current),
2806 get_item_line(todo_list,
2807 todo_list->current));
2808 todo_list->current--;
2809 if (save_todo(todo_list, opts))
2812 if (item->command == TODO_EDIT) {
2813 struct commit *commit = item->commit;
2816 _("Stopped at %s... %.*s\n"),
2817 short_commit_name(commit),
2818 item->arg_len, item->arg);
2819 return error_with_patch(commit,
2820 item->arg, item->arg_len, opts, res,
2823 if (is_rebase_i(opts) && !res)
2824 record_in_rewritten(&item->commit->object.oid,
2825 peek_command(todo_list, 1));
2826 if (res && is_fixup(item->command)) {
2829 return error_failed_squash(item->commit, opts,
2830 item->arg_len, item->arg);
2831 } else if (res && is_rebase_i(opts) && item->commit)
2832 return res | error_with_patch(item->commit,
2833 item->arg, item->arg_len, opts, res,
2834 item->command == TODO_REWORD);
2835 } else if (item->command == TODO_EXEC) {
2836 char *end_of_arg = (char *)(item->arg + item->arg_len);
2837 int saved = *end_of_arg;
2841 res = do_exec(item->arg);
2842 *end_of_arg = saved;
2844 /* Reread the todo file if it has changed. */
2846 ; /* fall through */
2847 else if (stat(get_todo_path(opts), &st))
2848 res = error_errno(_("could not stat '%s'"),
2849 get_todo_path(opts));
2850 else if (match_stat_data(&todo_list->stat, &st)) {
2851 todo_list_release(todo_list);
2852 if (read_populate_todo(todo_list, opts))
2853 res = -1; /* message was printed */
2854 /* `current` will be incremented below */
2855 todo_list->current = -1;
2857 } else if (item->command == TODO_LABEL) {
2858 if ((res = do_label(item->arg, item->arg_len)))
2860 } else if (item->command == TODO_RESET) {
2861 if ((res = do_reset(item->arg, item->arg_len, opts)))
2863 } else if (!is_noop(item->command))
2864 return error(_("unknown command %d"), item->command);
2867 advise(_(rescheduled_advice),
2868 get_item_line_length(todo_list,
2869 todo_list->current),
2870 get_item_line(todo_list, todo_list->current));
2871 todo_list->current--;
2872 if (save_todo(todo_list, opts))
2876 todo_list->current++;
2881 if (is_rebase_i(opts)) {
2882 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2885 /* Stopped in the middle, as planned? */
2886 if (todo_list->current < todo_list->nr)
2889 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2890 starts_with(head_ref.buf, "refs/")) {
2892 struct object_id head, orig;
2895 if (get_oid("HEAD", &head)) {
2896 res = error(_("cannot read HEAD"));
2898 strbuf_release(&head_ref);
2899 strbuf_release(&buf);
2902 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2903 get_oid_hex(buf.buf, &orig)) {
2904 res = error(_("could not read orig-head"));
2905 goto cleanup_head_ref;
2908 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2909 res = error(_("could not read 'onto'"));
2910 goto cleanup_head_ref;
2912 msg = reflog_message(opts, "finish", "%s onto %s",
2913 head_ref.buf, buf.buf);
2914 if (update_ref(msg, head_ref.buf, &head, &orig,
2915 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
2916 res = error(_("could not update %s"),
2918 goto cleanup_head_ref;
2920 msg = reflog_message(opts, "finish", "returning to %s",
2922 if (create_symref("HEAD", head_ref.buf, msg)) {
2923 res = error(_("could not update HEAD to %s"),
2925 goto cleanup_head_ref;
2930 if (opts->verbose) {
2931 struct rev_info log_tree_opt;
2932 struct object_id orig, head;
2934 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2935 init_revisions(&log_tree_opt, NULL);
2936 log_tree_opt.diff = 1;
2937 log_tree_opt.diffopt.output_format =
2938 DIFF_FORMAT_DIFFSTAT;
2939 log_tree_opt.disable_stdin = 1;
2941 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2942 !get_oid(buf.buf, &orig) &&
2943 !get_oid("HEAD", &head)) {
2944 diff_tree_oid(&orig, &head, "",
2945 &log_tree_opt.diffopt);
2946 log_tree_diff_flush(&log_tree_opt);
2949 flush_rewritten_pending();
2950 if (!stat(rebase_path_rewritten_list(), &st) &&
2952 struct child_process child = CHILD_PROCESS_INIT;
2953 const char *post_rewrite_hook =
2954 find_hook("post-rewrite");
2956 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2958 argv_array_push(&child.args, "notes");
2959 argv_array_push(&child.args, "copy");
2960 argv_array_push(&child.args, "--for-rewrite=rebase");
2961 /* we don't care if this copying failed */
2962 run_command(&child);
2964 if (post_rewrite_hook) {
2965 struct child_process hook = CHILD_PROCESS_INIT;
2967 hook.in = open(rebase_path_rewritten_list(),
2969 hook.stdout_to_stderr = 1;
2970 argv_array_push(&hook.args, post_rewrite_hook);
2971 argv_array_push(&hook.args, "rebase");
2972 /* we don't care if this hook failed */
2976 apply_autostash(opts);
2978 fprintf(stderr, "Successfully rebased and updated %s.\n",
2981 strbuf_release(&buf);
2982 strbuf_release(&head_ref);
2986 * Sequence of picks finished successfully; cleanup by
2987 * removing the .git/sequencer directory
2989 return sequencer_remove_state(opts);
2992 static int continue_single_pick(void)
2994 const char *argv[] = { "commit", NULL };
2996 if (!file_exists(git_path_cherry_pick_head()) &&
2997 !file_exists(git_path_revert_head()))
2998 return error(_("no cherry-pick or revert in progress"));
2999 return run_command_v_opt(argv, RUN_GIT_CMD);
3002 static int commit_staged_changes(struct replay_opts *opts)
3004 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3006 if (has_unstaged_changes(1))
3007 return error(_("cannot rebase: You have unstaged changes."));
3008 if (!has_uncommitted_changes(0)) {
3009 const char *cherry_pick_head = git_path_cherry_pick_head();
3011 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3012 return error(_("could not remove CHERRY_PICK_HEAD"));
3016 if (file_exists(rebase_path_amend())) {
3017 struct strbuf rev = STRBUF_INIT;
3018 struct object_id head, to_amend;
3020 if (get_oid("HEAD", &head))
3021 return error(_("cannot amend non-existing commit"));
3022 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3023 return error(_("invalid file: '%s'"), rebase_path_amend());
3024 if (get_oid_hex(rev.buf, &to_amend))
3025 return error(_("invalid contents: '%s'"),
3026 rebase_path_amend());
3027 if (oidcmp(&head, &to_amend))
3028 return error(_("\nYou have uncommitted changes in your "
3029 "working tree. Please, commit them\n"
3030 "first and then run 'git rebase "
3031 "--continue' again."));
3033 strbuf_release(&rev);
3037 if (run_git_commit(rebase_path_message(), opts, flags))
3038 return error(_("could not commit staged changes."));
3039 unlink(rebase_path_amend());
3043 int sequencer_continue(struct replay_opts *opts)
3045 struct todo_list todo_list = TODO_LIST_INIT;
3048 if (read_and_refresh_cache(opts))
3051 if (is_rebase_i(opts)) {
3052 if (commit_staged_changes(opts))
3054 } else if (!file_exists(get_todo_path(opts)))
3055 return continue_single_pick();
3056 if (read_populate_opts(opts))
3058 if ((res = read_populate_todo(&todo_list, opts)))
3059 goto release_todo_list;
3061 if (!is_rebase_i(opts)) {
3062 /* Verify that the conflict has been resolved */
3063 if (file_exists(git_path_cherry_pick_head()) ||
3064 file_exists(git_path_revert_head())) {
3065 res = continue_single_pick();
3067 goto release_todo_list;
3069 if (index_differs_from("HEAD", NULL, 0)) {
3070 res = error_dirty_index(opts);
3071 goto release_todo_list;
3073 todo_list.current++;
3074 } else if (file_exists(rebase_path_stopped_sha())) {
3075 struct strbuf buf = STRBUF_INIT;
3076 struct object_id oid;
3078 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3079 !get_oid_committish(buf.buf, &oid))
3080 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3081 strbuf_release(&buf);
3084 res = pick_commits(&todo_list, opts);
3086 todo_list_release(&todo_list);
3090 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3092 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3093 return do_pick_commit(opts->action == REPLAY_PICK ?
3094 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3097 int sequencer_pick_revisions(struct replay_opts *opts)
3099 struct todo_list todo_list = TODO_LIST_INIT;
3100 struct object_id oid;
3104 if (read_and_refresh_cache(opts))
3107 for (i = 0; i < opts->revs->pending.nr; i++) {
3108 struct object_id oid;
3109 const char *name = opts->revs->pending.objects[i].name;
3111 /* This happens when using --stdin. */
3115 if (!get_oid(name, &oid)) {
3116 if (!lookup_commit_reference_gently(&oid, 1)) {
3117 enum object_type type = oid_object_info(&oid,
3119 return error(_("%s: can't cherry-pick a %s"),
3120 name, type_name(type));
3123 return error(_("%s: bad revision"), name);
3127 * If we were called as "git cherry-pick <commit>", just
3128 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3129 * REVERT_HEAD, and don't touch the sequencer state.
3130 * This means it is possible to cherry-pick in the middle
3131 * of a cherry-pick sequence.
3133 if (opts->revs->cmdline.nr == 1 &&
3134 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3135 opts->revs->no_walk &&
3136 !opts->revs->cmdline.rev->flags) {
3137 struct commit *cmit;
3138 if (prepare_revision_walk(opts->revs))
3139 return error(_("revision walk setup failed"));
3140 cmit = get_revision(opts->revs);
3141 if (!cmit || get_revision(opts->revs))
3142 return error("BUG: expected exactly one commit from walk");
3143 return single_pick(cmit, opts);
3147 * Start a new cherry-pick/ revert sequence; but
3148 * first, make sure that an existing one isn't in
3152 if (walk_revs_populate_todo(&todo_list, opts) ||
3153 create_seq_dir() < 0)
3155 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3156 return error(_("can't revert as initial commit"));
3157 if (save_head(oid_to_hex(&oid)))
3159 if (save_opts(opts))
3161 update_abort_safety_file();
3162 res = pick_commits(&todo_list, opts);
3163 todo_list_release(&todo_list);
3167 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3169 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3170 struct strbuf sob = STRBUF_INIT;
3173 strbuf_addstr(&sob, sign_off_header);
3174 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3175 getenv("GIT_COMMITTER_EMAIL")));
3176 strbuf_addch(&sob, '\n');
3179 strbuf_complete_line(msgbuf);
3182 * If the whole message buffer is equal to the sob, pretend that we
3183 * found a conforming footer with a matching sob
3185 if (msgbuf->len - ignore_footer == sob.len &&
3186 !strncmp(msgbuf->buf, sob.buf, sob.len))
3189 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3192 const char *append_newlines = NULL;
3193 size_t len = msgbuf->len - ignore_footer;
3197 * The buffer is completely empty. Leave foom for
3198 * the title and body to be filled in by the user.
3200 append_newlines = "\n\n";
3201 } else if (len == 1) {
3203 * Buffer contains a single newline. Add another
3204 * so that we leave room for the title and body.
3206 append_newlines = "\n";
3207 } else if (msgbuf->buf[len - 2] != '\n') {
3209 * Buffer ends with a single newline. Add another
3210 * so that there is an empty line between the message
3213 append_newlines = "\n";
3214 } /* else, the buffer already ends with two newlines. */
3216 if (append_newlines)
3217 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3218 append_newlines, strlen(append_newlines));
3221 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3222 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3225 strbuf_release(&sob);
3228 int sequencer_make_script(FILE *out, int argc, const char **argv,
3231 char *format = NULL;
3232 struct pretty_print_context pp = {0};
3233 struct strbuf buf = STRBUF_INIT;
3234 struct rev_info revs;
3235 struct commit *commit;
3236 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3237 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
3239 init_revisions(&revs, NULL);
3240 revs.verbose_header = 1;
3241 revs.max_parents = 1;
3242 revs.cherry_mark = 1;
3245 revs.right_only = 1;
3246 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3247 revs.topo_order = 1;
3249 revs.pretty_given = 1;
3250 git_config_get_string("rebase.instructionFormat", &format);
3251 if (!format || !*format) {
3253 format = xstrdup("%s");
3255 get_commit_format(format, &revs);
3257 pp.fmt = revs.commit_format;
3258 pp.output_encoding = get_log_output_encoding();
3260 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3261 return error(_("make_script: unhandled options"));
3263 if (prepare_revision_walk(&revs) < 0)
3264 return error(_("make_script: error preparing revisions"));
3266 while ((commit = get_revision(&revs))) {
3267 int is_empty = is_original_commit_empty(commit);
3269 if (!is_empty && (commit->object.flags & PATCHSAME))
3272 if (!keep_empty && is_empty)
3273 strbuf_addf(&buf, "%c ", comment_line_char);
3274 strbuf_addf(&buf, "%s %s ", insn,
3275 oid_to_hex(&commit->object.oid));
3276 pretty_print_commit(&pp, commit, &buf);
3277 strbuf_addch(&buf, '\n');
3278 fputs(buf.buf, out);
3280 strbuf_release(&buf);
3285 * Add commands after pick and (series of) squash/fixup commands
3288 int sequencer_add_exec_commands(const char *commands)
3290 const char *todo_file = rebase_path_todo();
3291 struct todo_list todo_list = TODO_LIST_INIT;
3292 struct todo_item *item;
3293 struct strbuf *buf = &todo_list.buf;
3294 size_t offset = 0, commands_len = strlen(commands);
3297 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3298 return error(_("could not read '%s'."), todo_file);
3300 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3301 todo_list_release(&todo_list);
3302 return error(_("unusable todo list: '%s'"), todo_file);
3306 /* insert <commands> before every pick except the first one */
3307 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3308 if (item->command == TODO_PICK && !first) {
3309 strbuf_insert(buf, item->offset_in_buf + offset,
3310 commands, commands_len);
3311 offset += commands_len;
3316 /* append final <commands> */
3317 strbuf_add(buf, commands, commands_len);
3319 i = write_message(buf->buf, buf->len, todo_file, 0);
3320 todo_list_release(&todo_list);
3324 int transform_todos(unsigned flags)
3326 const char *todo_file = rebase_path_todo();
3327 struct todo_list todo_list = TODO_LIST_INIT;
3328 struct strbuf buf = STRBUF_INIT;
3329 struct todo_item *item;
3332 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3333 return error(_("could not read '%s'."), todo_file);
3335 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3336 todo_list_release(&todo_list);
3337 return error(_("unusable todo list: '%s'"), todo_file);
3340 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3341 /* if the item is not a command write it and continue */
3342 if (item->command >= TODO_COMMENT) {
3343 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3347 /* add command to the buffer */
3348 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3349 strbuf_addch(&buf, command_to_char(item->command));
3351 strbuf_addstr(&buf, command_to_string(item->command));
3355 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3356 short_commit_name(item->commit) :
3357 oid_to_hex(&item->commit->object.oid);
3359 strbuf_addf(&buf, " %s", oid);
3361 /* add all the rest */
3363 strbuf_addch(&buf, '\n');
3365 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3368 i = write_message(buf.buf, buf.len, todo_file, 0);
3369 todo_list_release(&todo_list);
3374 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3377 static enum check_level get_missing_commit_check_level(void)
3381 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3382 !strcasecmp("ignore", value))
3383 return CHECK_IGNORE;
3384 if (!strcasecmp("warn", value))
3386 if (!strcasecmp("error", value))
3388 warning(_("unrecognized setting %s for option "
3389 "rebase.missingCommitsCheck. Ignoring."), value);
3390 return CHECK_IGNORE;
3394 * Check if the user dropped some commits by mistake
3395 * Behaviour determined by rebase.missingCommitsCheck.
3396 * Check if there is an unrecognized command or a
3397 * bad SHA-1 in a command.
3399 int check_todo_list(void)
3401 enum check_level check_level = get_missing_commit_check_level();
3402 struct strbuf todo_file = STRBUF_INIT;
3403 struct todo_list todo_list = TODO_LIST_INIT;
3404 struct strbuf missing = STRBUF_INIT;
3405 int advise_to_edit_todo = 0, res = 0, i;
3407 strbuf_addstr(&todo_file, rebase_path_todo());
3408 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3412 advise_to_edit_todo = res =
3413 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3415 if (res || check_level == CHECK_IGNORE)
3418 /* Mark the commits in git-rebase-todo as seen */
3419 for (i = 0; i < todo_list.nr; i++) {
3420 struct commit *commit = todo_list.items[i].commit;
3422 commit->util = (void *)1;
3425 todo_list_release(&todo_list);
3426 strbuf_addstr(&todo_file, ".backup");
3427 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3431 strbuf_release(&todo_file);
3432 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3434 /* Find commits in git-rebase-todo.backup yet unseen */
3435 for (i = todo_list.nr - 1; i >= 0; i--) {
3436 struct todo_item *item = todo_list.items + i;
3437 struct commit *commit = item->commit;
3438 if (commit && !commit->util) {
3439 strbuf_addf(&missing, " - %s %.*s\n",
3440 short_commit_name(commit),
3441 item->arg_len, item->arg);
3442 commit->util = (void *)1;
3446 /* Warn about missing commits */
3450 if (check_level == CHECK_ERROR)
3451 advise_to_edit_todo = res = 1;
3454 _("Warning: some commits may have been dropped accidentally.\n"
3455 "Dropped commits (newer to older):\n"));
3457 /* Make the list user-friendly and display */
3458 fputs(missing.buf, stderr);
3459 strbuf_release(&missing);
3461 fprintf(stderr, _("To avoid this message, use \"drop\" to "
3462 "explicitly remove a commit.\n\n"
3463 "Use 'git config rebase.missingCommitsCheck' to change "
3464 "the level of warnings.\n"
3465 "The possible behaviours are: ignore, warn, error.\n\n"));
3468 strbuf_release(&todo_file);
3469 todo_list_release(&todo_list);
3471 if (advise_to_edit_todo)
3473 _("You can fix this with 'git rebase --edit-todo' "
3474 "and then run 'git rebase --continue'.\n"
3475 "Or you can abort the rebase with 'git rebase"
3481 static int rewrite_file(const char *path, const char *buf, size_t len)
3484 int fd = open(path, O_WRONLY | O_TRUNC);
3486 return error_errno(_("could not open '%s' for writing"), path);
3487 if (write_in_full(fd, buf, len) < 0)
3488 rc = error_errno(_("could not write to '%s'"), path);
3489 if (close(fd) && !rc)
3490 rc = error_errno(_("could not close '%s'"), path);
3494 /* skip picking commits whose parents are unchanged */
3495 int skip_unnecessary_picks(void)
3497 const char *todo_file = rebase_path_todo();
3498 struct strbuf buf = STRBUF_INIT;
3499 struct todo_list todo_list = TODO_LIST_INIT;
3500 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3503 if (!read_oneliner(&buf, rebase_path_onto(), 0))
3504 return error(_("could not read 'onto'"));
3505 if (get_oid(buf.buf, &onto_oid)) {
3506 strbuf_release(&buf);
3507 return error(_("need a HEAD to fixup"));
3509 strbuf_release(&buf);
3511 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
3513 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3514 todo_list_release(&todo_list);
3518 for (i = 0; i < todo_list.nr; i++) {
3519 struct todo_item *item = todo_list.items + i;
3521 if (item->command >= TODO_NOOP)
3523 if (item->command != TODO_PICK)
3525 if (parse_commit(item->commit)) {
3526 todo_list_release(&todo_list);
3527 return error(_("could not parse commit '%s'"),
3528 oid_to_hex(&item->commit->object.oid));
3530 if (!item->commit->parents)
3531 break; /* root commit */
3532 if (item->commit->parents->next)
3533 break; /* merge commit */
3534 parent_oid = &item->commit->parents->item->object.oid;
3535 if (hashcmp(parent_oid->hash, oid->hash))
3537 oid = &item->commit->object.oid;
3540 int offset = get_item_line_offset(&todo_list, i);
3541 const char *done_path = rebase_path_done();
3543 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3545 error_errno(_("could not open '%s' for writing"),
3547 todo_list_release(&todo_list);
3550 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3551 error_errno(_("could not write to '%s'"), done_path);
3552 todo_list_release(&todo_list);
3558 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
3559 todo_list.buf.len - offset) < 0) {
3560 todo_list_release(&todo_list);
3564 todo_list.current = i;
3565 if (is_fixup(peek_command(&todo_list, 0)))
3566 record_in_rewritten(oid, peek_command(&todo_list, 0));
3569 todo_list_release(&todo_list);
3570 printf("%s\n", oid_to_hex(oid));
3575 struct subject2item_entry {
3576 struct hashmap_entry entry;
3578 char subject[FLEX_ARRAY];
3581 static int subject2item_cmp(const void *fndata,
3582 const struct subject2item_entry *a,
3583 const struct subject2item_entry *b, const void *key)
3585 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3589 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3590 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3591 * after the former, and change "pick" to "fixup"/"squash".
3593 * Note that if the config has specified a custom instruction format, each log
3594 * message will have to be retrieved from the commit (as the oneline in the
3595 * script cannot be trusted) in order to normalize the autosquash arrangement.
3597 int rearrange_squash(void)
3599 const char *todo_file = rebase_path_todo();
3600 struct todo_list todo_list = TODO_LIST_INIT;
3601 struct hashmap subject2item;
3602 int res = 0, rearranged = 0, *next, *tail, i;
3605 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
3607 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3608 todo_list_release(&todo_list);
3613 * The hashmap maps onelines to the respective todo list index.
3615 * If any items need to be rearranged, the next[i] value will indicate
3616 * which item was moved directly after the i'th.
3618 * In that case, last[i] will indicate the index of the latest item to
3619 * be moved to appear after the i'th.
3621 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3622 NULL, todo_list.nr);
3623 ALLOC_ARRAY(next, todo_list.nr);
3624 ALLOC_ARRAY(tail, todo_list.nr);
3625 ALLOC_ARRAY(subjects, todo_list.nr);
3626 for (i = 0; i < todo_list.nr; i++) {
3627 struct strbuf buf = STRBUF_INIT;
3628 struct todo_item *item = todo_list.items + i;
3629 const char *commit_buffer, *subject, *p;
3632 struct subject2item_entry *entry;
3634 next[i] = tail[i] = -1;
3635 if (!item->commit || item->command == TODO_DROP) {
3640 if (is_fixup(item->command)) {
3641 todo_list_release(&todo_list);
3642 return error(_("the script was already rearranged."));
3645 item->commit->util = item;
3647 parse_commit(item->commit);
3648 commit_buffer = get_commit_buffer(item->commit, NULL);
3649 find_commit_subject(commit_buffer, &subject);
3650 format_subject(&buf, subject, " ");
3651 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3652 unuse_commit_buffer(item->commit, commit_buffer);
3653 if ((skip_prefix(subject, "fixup! ", &p) ||
3654 skip_prefix(subject, "squash! ", &p))) {
3655 struct commit *commit2;
3660 if (!skip_prefix(p, "fixup! ", &p) &&
3661 !skip_prefix(p, "squash! ", &p))
3665 if ((entry = hashmap_get_from_hash(&subject2item,
3667 /* found by title */
3669 else if (!strchr(p, ' ') &&
3671 lookup_commit_reference_by_name(p)) &&
3673 /* found by commit name */
3674 i2 = (struct todo_item *)commit2->util
3677 /* copy can be a prefix of the commit subject */
3678 for (i2 = 0; i2 < i; i2++)
3680 starts_with(subjects[i2], p))
3688 todo_list.items[i].command =
3689 starts_with(subject, "fixup!") ?
3690 TODO_FIXUP : TODO_SQUASH;
3696 } else if (!hashmap_get_from_hash(&subject2item,
3697 strhash(subject), subject)) {
3698 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3700 hashmap_entry_init(entry, strhash(entry->subject));
3701 hashmap_put(&subject2item, entry);
3706 struct strbuf buf = STRBUF_INIT;
3708 for (i = 0; i < todo_list.nr; i++) {
3709 enum todo_command command = todo_list.items[i].command;
3713 * Initially, all commands are 'pick's. If it is a
3714 * fixup or a squash now, we have rearranged it.
3716 if (is_fixup(command))
3721 get_item_line(&todo_list, cur);
3723 get_item_line(&todo_list, cur + 1);
3725 /* replace 'pick', by 'fixup' or 'squash' */
3726 command = todo_list.items[cur].command;
3727 if (is_fixup(command)) {
3729 todo_command_info[command].str);
3730 bol += strcspn(bol, " \t");
3733 strbuf_add(&buf, bol, eol - bol);
3739 res = rewrite_file(todo_file, buf.buf, buf.len);
3740 strbuf_release(&buf);
3745 for (i = 0; i < todo_list.nr; i++)
3748 hashmap_free(&subject2item, 1);
3749 todo_list_release(&todo_list);