5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-ort.h"
18 #include "merge-ort-wrappers.h"
24 #include "wt-status.h"
26 #include "notes-utils.h"
28 #include "unpack-trees.h"
32 #include "commit-slab.h"
34 #include "commit-reach.h"
35 #include "rebase-interactive.h"
38 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40 static const char sign_off_header[] = "Signed-off-by: ";
41 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
48 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
49 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
50 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 * The file containing rebase commands, comments, and empty lines.
55 * This file is created by "git rebase -i" then edited by the user. As
56 * the lines are processed, they are removed from the front of this
57 * file and written to the tail of 'done'.
59 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
60 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65 * The rebase command lines that have already been processed. A line
66 * is moved here when it is first handled, before any associated user
69 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 * The file to keep track of how many commands were already processed (e.g.
74 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 * The file to keep track of how many commands are to be processed in total
77 * (e.g. for the prompt).
79 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 * The commit message that is planned to be used for any changes that
82 * need to be committed following a user interaction.
84 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 * The file into which is accumulated the suggested commit message for
87 * squash/fixup commands. When the first of a series of squash/fixups
88 * is seen, the file is created and the commit message from the
89 * previous commit and from the first squash/fixup commit are written
90 * to it. The commit message for each subsequent squash/fixup commit
91 * is appended to the file as it is processed.
93 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 * If the current series of squash/fixups has not yet included a squash
96 * command, then this file exists and holds the commit message of the
97 * original "pick" commit. (If the series ends without a "squash"
98 * command, then this can be used as the commit message of the combined
99 * commit without opening the editor.)
101 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 * This file contains the list fixup/squash commands that have been
104 * accumulated into message-fixup or message-squash so far.
106 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
109 * GIT_AUTHOR_DATE that will be used for the commit that is currently
112 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 * When an "edit" rebase command is being processed, the SHA1 of the
115 * commit to be edited is recorded in this file. When "git rebase
116 * --continue" is executed, if there are any staged changes then they
117 * will be amended to the HEAD commit, but only provided the HEAD
118 * commit is still the commit to be edited. When any other rebase
119 * command is processed, this file is deleted.
121 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 * When we stop at a given patch via the "edit" command, this file contains
124 * the commit object name of the corresponding patch.
126 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 * For the post-rewrite hook, we make a list of rewritten commits and
129 * their new sha1s. The rewritten-pending list keeps the sha1s of
130 * commits that have been processed, but not committed yet,
131 * e.g. because they are waiting for a 'squash' command.
133 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
134 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
135 "rebase-merge/rewritten-pending")
138 * The path of the file containing the OID of the "squash onto" commit, i.e.
139 * the dummy commit used for `reset [new root]`.
141 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144 * The path of the file listing refs that need to be deleted after the rebase
145 * finishes. This is used by the `label` command to record the need for cleanup.
147 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150 * The following files are written by git-rebase just after parsing the
153 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
154 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
155 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
156 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
157 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
158 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
159 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
160 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
161 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
162 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
163 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
164 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
165 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
166 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
167 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
168 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
170 static int git_sequencer_config(const char *k, const char *v, void *cb)
172 struct replay_opts *opts = cb;
175 if (!strcmp(k, "commit.cleanup")) {
178 status = git_config_string(&s, k, v);
182 if (!strcmp(s, "verbatim")) {
183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "whitespace")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
187 opts->explicit_cleanup = 1;
188 } else if (!strcmp(s, "strip")) {
189 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
190 opts->explicit_cleanup = 1;
191 } else if (!strcmp(s, "scissors")) {
192 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
193 opts->explicit_cleanup = 1;
195 warning(_("invalid commit message cleanup mode '%s'"),
203 if (!strcmp(k, "commit.gpgsign")) {
204 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
208 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
209 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
212 * pull.twohead is allowed to be multi-valued; we only
213 * care about the first value.
215 char *tmp = strchr(opts->default_strategy, ' ');
222 status = git_gpg_config(k, v, NULL);
226 return git_diff_basic_config(k, v, NULL);
229 void sequencer_init_config(struct replay_opts *opts)
231 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
232 git_config(git_sequencer_config, opts);
235 static inline int is_rebase_i(const struct replay_opts *opts)
237 return opts->action == REPLAY_INTERACTIVE_REBASE;
240 static const char *get_dir(const struct replay_opts *opts)
242 if (is_rebase_i(opts))
243 return rebase_path();
244 return git_path_seq_dir();
247 static const char *get_todo_path(const struct replay_opts *opts)
249 if (is_rebase_i(opts))
250 return rebase_path_todo();
251 return git_path_todo_file();
255 * Returns 0 for non-conforming footer
256 * Returns 1 for conforming footer
257 * Returns 2 when sob exists within conforming footer
258 * Returns 3 when sob exists within conforming footer as last entry
260 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
261 size_t ignore_footer)
263 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
264 struct trailer_info info;
266 int found_sob = 0, found_sob_last = 0;
272 saved_char = sb->buf[sb->len - ignore_footer];
273 sb->buf[sb->len - ignore_footer] = '\0';
276 trailer_info_get(&info, sb->buf, &opts);
279 sb->buf[sb->len - ignore_footer] = saved_char;
281 if (info.trailer_start == info.trailer_end)
284 for (i = 0; i < info.trailer_nr; i++)
285 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
287 if (i == info.trailer_nr - 1)
291 trailer_info_release(&info);
300 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
302 static struct strbuf buf = STRBUF_INIT;
306 sq_quotef(&buf, "-S%s", opts->gpg_sign);
310 int sequencer_remove_state(struct replay_opts *opts)
312 struct strbuf buf = STRBUF_INIT;
315 if (is_rebase_i(opts) &&
316 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
319 char *eol = strchr(p, '\n');
322 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
323 warning(_("could not delete '%s'"), p);
332 free(opts->gpg_sign);
333 free(opts->default_strategy);
334 free(opts->strategy);
335 for (i = 0; i < opts->xopts_nr; i++)
336 free(opts->xopts[i]);
338 strbuf_release(&opts->current_fixups);
341 strbuf_addstr(&buf, get_dir(opts));
342 if (remove_dir_recursively(&buf, 0))
343 ret = error(_("could not remove '%s'"), buf.buf);
344 strbuf_release(&buf);
349 static const char *action_name(const struct replay_opts *opts)
351 switch (opts->action) {
355 return N_("cherry-pick");
356 case REPLAY_INTERACTIVE_REBASE:
359 die(_("unknown action: %d"), opts->action);
362 struct commit_message {
369 static const char *short_commit_name(struct commit *commit)
371 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
374 static int get_message(struct commit *commit, struct commit_message *out)
376 const char *abbrev, *subject;
379 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
380 abbrev = short_commit_name(commit);
382 subject_len = find_commit_subject(out->message, &subject);
384 out->subject = xmemdupz(subject, subject_len);
385 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
386 out->parent_label = xstrfmt("parent of %s", out->label);
391 static void free_message(struct commit *commit, struct commit_message *msg)
393 free(msg->parent_label);
396 unuse_commit_buffer(commit, msg->message);
399 static void print_advice(struct repository *r, int show_hint,
400 struct replay_opts *opts)
402 char *msg = getenv("GIT_CHERRY_PICK_HELP");
405 fprintf(stderr, "%s\n", msg);
407 * A conflict has occurred but the porcelain
408 * (typically rebase --interactive) wants to take care
409 * of the commit itself so remove CHERRY_PICK_HEAD
411 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
418 advise(_("after resolving the conflicts, mark the corrected paths\n"
419 "with 'git add <paths>' or 'git rm <paths>'"));
421 advise(_("after resolving the conflicts, mark the corrected paths\n"
422 "with 'git add <paths>' or 'git rm <paths>'\n"
423 "and commit the result with 'git commit'"));
427 static int write_message(const void *buf, size_t len, const char *filename,
430 struct lock_file msg_file = LOCK_INIT;
432 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
434 return error_errno(_("could not lock '%s'"), filename);
435 if (write_in_full(msg_fd, buf, len) < 0) {
436 error_errno(_("could not write to '%s'"), filename);
437 rollback_lock_file(&msg_file);
440 if (append_eol && write(msg_fd, "\n", 1) < 0) {
441 error_errno(_("could not write eol to '%s'"), filename);
442 rollback_lock_file(&msg_file);
445 if (commit_lock_file(&msg_file) < 0)
446 return error(_("failed to finalize '%s'"), filename);
451 int read_oneliner(struct strbuf *buf,
452 const char *path, unsigned flags)
454 int orig_len = buf->len;
456 if (strbuf_read_file(buf, path, 0) < 0) {
457 if ((flags & READ_ONELINER_WARN_MISSING) ||
458 (errno != ENOENT && errno != ENOTDIR))
459 warning_errno(_("could not read '%s'"), path);
463 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
464 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
466 buf->buf[buf->len] = '\0';
469 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
475 static struct tree *empty_tree(struct repository *r)
477 return lookup_tree(r, the_hash_algo->empty_tree);
480 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
482 if (repo_read_index_unmerged(repo))
483 return error_resolve_conflict(_(action_name(opts)));
485 error(_("your local changes would be overwritten by %s."),
486 _(action_name(opts)));
488 if (advice_commit_before_merge)
489 advise(_("commit your changes or stash them to proceed."));
493 static void update_abort_safety_file(void)
495 struct object_id head;
497 /* Do nothing on a single-pick */
498 if (!file_exists(git_path_seq_dir()))
501 if (!get_oid("HEAD", &head))
502 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
504 write_file(git_path_abort_safety_file(), "%s", "");
507 static int fast_forward_to(struct repository *r,
508 const struct object_id *to,
509 const struct object_id *from,
511 struct replay_opts *opts)
513 struct ref_transaction *transaction;
514 struct strbuf sb = STRBUF_INIT;
515 struct strbuf err = STRBUF_INIT;
518 if (checkout_fast_forward(r, from, to, 1))
519 return -1; /* the callee should have complained already */
521 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
523 transaction = ref_transaction_begin(&err);
525 ref_transaction_update(transaction, "HEAD",
526 to, unborn && !is_rebase_i(opts) ?
529 ref_transaction_commit(transaction, &err)) {
530 ref_transaction_free(transaction);
531 error("%s", err.buf);
533 strbuf_release(&err);
538 strbuf_release(&err);
539 ref_transaction_free(transaction);
540 update_abort_safety_file();
544 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
547 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
548 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
549 COMMIT_MSG_CLEANUP_SPACE;
550 else if (!strcmp(cleanup_arg, "verbatim"))
551 return COMMIT_MSG_CLEANUP_NONE;
552 else if (!strcmp(cleanup_arg, "whitespace"))
553 return COMMIT_MSG_CLEANUP_SPACE;
554 else if (!strcmp(cleanup_arg, "strip"))
555 return COMMIT_MSG_CLEANUP_ALL;
556 else if (!strcmp(cleanup_arg, "scissors"))
557 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
558 COMMIT_MSG_CLEANUP_SPACE;
560 die(_("Invalid cleanup mode %s"), cleanup_arg);
564 * NB using int rather than enum cleanup_mode to stop clang's
565 * -Wtautological-constant-out-of-range-compare complaining that the comparison
568 static const char *describe_cleanup_mode(int cleanup_mode)
570 static const char *modes[] = { "whitespace",
575 if (cleanup_mode < ARRAY_SIZE(modes))
576 return modes[cleanup_mode];
578 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
581 void append_conflicts_hint(struct index_state *istate,
582 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
586 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
587 strbuf_addch(msgbuf, '\n');
588 wt_status_append_cut_line(msgbuf);
589 strbuf_addch(msgbuf, comment_line_char);
592 strbuf_addch(msgbuf, '\n');
593 strbuf_commented_addf(msgbuf, "Conflicts:\n");
594 for (i = 0; i < istate->cache_nr;) {
595 const struct cache_entry *ce = istate->cache[i++];
597 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
598 while (i < istate->cache_nr &&
599 !strcmp(ce->name, istate->cache[i]->name))
605 static int do_recursive_merge(struct repository *r,
606 struct commit *base, struct commit *next,
607 const char *base_label, const char *next_label,
608 struct object_id *head, struct strbuf *msgbuf,
609 struct replay_opts *opts)
611 struct merge_options o;
612 struct merge_result result;
613 struct tree *next_tree, *base_tree, *head_tree;
614 int clean, show_output;
616 struct lock_file index_lock = LOCK_INIT;
618 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
623 init_merge_options(&o, r);
624 o.ancestor = base ? base_label : "(empty tree)";
626 o.branch2 = next ? next_label : "(empty tree)";
627 if (is_rebase_i(opts))
629 o.show_rename_progress = 1;
631 head_tree = parse_tree_indirect(head);
632 next_tree = next ? get_commit_tree(next) : empty_tree(r);
633 base_tree = base ? get_commit_tree(base) : empty_tree(r);
635 for (i = 0; i < opts->xopts_nr; i++)
636 parse_merge_opt(&o, opts->xopts[i]);
638 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
639 memset(&result, 0, sizeof(result));
640 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
642 show_output = !is_rebase_i(opts) || !result.clean;
644 * TODO: merge_switch_to_result will update index/working tree;
645 * we only really want to do that if !result.clean || this is
646 * the final patch to be picked. But determining this is the
647 * final patch would take some work, and "head_tree" would need
648 * to be replace with the tree the index matched before we
649 * started doing any picks.
651 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
652 clean = result.clean;
654 clean = merge_trees(&o, head_tree, next_tree, base_tree);
655 if (is_rebase_i(opts) && clean <= 0)
656 fputs(o.obuf.buf, stdout);
657 strbuf_release(&o.obuf);
660 rollback_lock_file(&index_lock);
664 if (write_locked_index(r->index, &index_lock,
665 COMMIT_LOCK | SKIP_IF_UNCHANGED))
667 * TRANSLATORS: %s will be "revert", "cherry-pick" or
670 return error(_("%s: Unable to write new index file"),
671 _(action_name(opts)));
674 append_conflicts_hint(r->index, msgbuf,
675 opts->default_msg_cleanup);
680 static struct object_id *get_cache_tree_oid(struct index_state *istate)
682 if (!istate->cache_tree)
683 istate->cache_tree = cache_tree();
685 if (!cache_tree_fully_valid(istate->cache_tree))
686 if (cache_tree_update(istate, 0)) {
687 error(_("unable to update cache tree"));
691 return &istate->cache_tree->oid;
694 static int is_index_unchanged(struct repository *r)
696 struct object_id head_oid, *cache_tree_oid;
697 struct commit *head_commit;
698 struct index_state *istate = r->index;
700 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
701 return error(_("could not resolve HEAD commit"));
703 head_commit = lookup_commit(r, &head_oid);
706 * If head_commit is NULL, check_commit, called from
707 * lookup_commit, would have indicated that head_commit is not
708 * a commit object already. parse_commit() will return failure
709 * without further complaints in such a case. Otherwise, if
710 * the commit is invalid, parse_commit() will complain. So
711 * there is nothing for us to say here. Just return failure.
713 if (parse_commit(head_commit))
716 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
719 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
722 static int write_author_script(const char *message)
724 struct strbuf buf = STRBUF_INIT;
729 if (!*message || starts_with(message, "\n")) {
731 /* Missing 'author' line? */
732 unlink(rebase_path_author_script());
734 } else if (skip_prefix(message, "author ", &message))
736 else if ((eol = strchr(message, '\n')))
741 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
742 while (*message && *message != '\n' && *message != '\r')
743 if (skip_prefix(message, " <", &message))
745 else if (*message != '\'')
746 strbuf_addch(&buf, *(message++));
748 strbuf_addf(&buf, "'\\%c'", *(message++));
749 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
750 while (*message && *message != '\n' && *message != '\r')
751 if (skip_prefix(message, "> ", &message))
753 else if (*message != '\'')
754 strbuf_addch(&buf, *(message++));
756 strbuf_addf(&buf, "'\\%c'", *(message++));
757 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
758 while (*message && *message != '\n' && *message != '\r')
759 if (*message != '\'')
760 strbuf_addch(&buf, *(message++));
762 strbuf_addf(&buf, "'\\%c'", *(message++));
763 strbuf_addch(&buf, '\'');
764 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
765 strbuf_release(&buf);
770 * Take a series of KEY='VALUE' lines where VALUE part is
771 * sq-quoted, and append <KEY, VALUE> at the end of the string list
773 static int parse_key_value_squoted(char *buf, struct string_list *list)
776 struct string_list_item *item;
778 char *cp = strchr(buf, '=');
780 np = strchrnul(buf, '\n');
781 return error(_("no key present in '%.*s'"),
782 (int) (np - buf), buf);
784 np = strchrnul(cp, '\n');
786 item = string_list_append(list, buf);
788 buf = np + (*np == '\n');
792 return error(_("unable to dequote value of '%s'"),
794 item->util = xstrdup(cp);
800 * Reads and parses the state directory's "author-script" file, and sets name,
801 * email and date accordingly.
802 * Returns 0 on success, -1 if the file could not be parsed.
804 * The author script is of the format:
806 * GIT_AUTHOR_NAME='$author_name'
807 * GIT_AUTHOR_EMAIL='$author_email'
808 * GIT_AUTHOR_DATE='$author_date'
810 * where $author_name, $author_email and $author_date are quoted. We are strict
811 * with our parsing, as the file was meant to be eval'd in the now-removed
812 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
813 * from what this function expects, it is better to bail out than to do
814 * something that the user does not expect.
816 int read_author_script(const char *path, char **name, char **email, char **date,
819 struct strbuf buf = STRBUF_INIT;
820 struct string_list kv = STRING_LIST_INIT_DUP;
821 int retval = -1; /* assume failure */
822 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
824 if (strbuf_read_file(&buf, path, 256) <= 0) {
825 strbuf_release(&buf);
826 if (errno == ENOENT && allow_missing)
829 return error_errno(_("could not open '%s' for reading"),
833 if (parse_key_value_squoted(buf.buf, &kv))
836 for (i = 0; i < kv.nr; i++) {
837 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
839 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
842 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
844 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
847 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
849 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
853 err = error(_("unknown variable '%s'"),
858 error(_("missing 'GIT_AUTHOR_NAME'"));
860 error(_("missing 'GIT_AUTHOR_EMAIL'"));
862 error(_("missing 'GIT_AUTHOR_DATE'"));
863 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
865 *name = kv.items[name_i].util;
866 *email = kv.items[email_i].util;
867 *date = kv.items[date_i].util;
870 string_list_clear(&kv, !!retval);
871 strbuf_release(&buf);
876 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
877 * file with shell quoting into struct strvec. Returns -1 on
878 * error, 0 otherwise.
880 static int read_env_script(struct strvec *env)
882 char *name, *email, *date;
884 if (read_author_script(rebase_path_author_script(),
885 &name, &email, &date, 0))
888 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
889 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
890 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
898 static char *get_author(const char *message)
903 a = find_commit_header(message, "author", &len);
905 return xmemdupz(a, len);
910 static const char *author_date_from_env_array(const struct strvec *env)
915 for (i = 0; i < env->nr; i++)
916 if (skip_prefix(env->v[i],
917 "GIT_AUTHOR_DATE=", &date))
920 * If GIT_AUTHOR_DATE is missing we should have already errored out when
923 BUG("GIT_AUTHOR_DATE missing from author script");
926 static const char staged_changes_advice[] =
927 N_("you have staged changes in your working tree\n"
928 "If these changes are meant to be squashed into the previous commit, run:\n"
930 " git commit --amend %s\n"
932 "If they are meant to go into a new commit, run:\n"
936 "In both cases, once you're done, continue with:\n"
938 " git rebase --continue\n");
940 #define ALLOW_EMPTY (1<<0)
941 #define EDIT_MSG (1<<1)
942 #define AMEND_MSG (1<<2)
943 #define CLEANUP_MSG (1<<3)
944 #define VERIFY_MSG (1<<4)
945 #define CREATE_ROOT_COMMIT (1<<5)
947 static int run_command_silent_on_success(struct child_process *cmd)
949 struct strbuf buf = STRBUF_INIT;
952 cmd->stdout_to_stderr = 1;
953 rc = pipe_command(cmd,
959 fputs(buf.buf, stderr);
960 strbuf_release(&buf);
965 * If we are cherry-pick, and if the merge did not result in
966 * hand-editing, we will hit this commit and inherit the original
967 * author date and name.
969 * If we are revert, or if our cherry-pick results in a hand merge,
970 * we had better say that the current user is responsible for that.
972 * An exception is when run_git_commit() is called during an
973 * interactive rebase: in that case, we will want to retain the
976 static int run_git_commit(const char *defmsg,
977 struct replay_opts *opts,
980 struct child_process cmd = CHILD_PROCESS_INIT;
984 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
985 const char *gpg_opt = gpg_sign_opt_quoted(opts);
987 return error(_(staged_changes_advice),
991 if (opts->committer_date_is_author_date)
992 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
995 author_date_from_env_array(&cmd.env_array));
996 if (opts->ignore_date)
997 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
999 strvec_push(&cmd.args, "commit");
1001 if (!(flags & VERIFY_MSG))
1002 strvec_push(&cmd.args, "-n");
1003 if ((flags & AMEND_MSG))
1004 strvec_push(&cmd.args, "--amend");
1006 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1008 strvec_push(&cmd.args, "--no-gpg-sign");
1010 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1011 else if (!(flags & EDIT_MSG))
1012 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1013 if ((flags & CLEANUP_MSG))
1014 strvec_push(&cmd.args, "--cleanup=strip");
1015 if ((flags & EDIT_MSG))
1016 strvec_push(&cmd.args, "-e");
1017 else if (!(flags & CLEANUP_MSG) &&
1018 !opts->signoff && !opts->record_origin &&
1019 !opts->explicit_cleanup)
1020 strvec_push(&cmd.args, "--cleanup=verbatim");
1022 if ((flags & ALLOW_EMPTY))
1023 strvec_push(&cmd.args, "--allow-empty");
1025 if (!(flags & EDIT_MSG))
1026 strvec_push(&cmd.args, "--allow-empty-message");
1028 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1029 return run_command_silent_on_success(&cmd);
1031 return run_command(&cmd);
1034 static int rest_is_empty(const struct strbuf *sb, int start)
1039 /* Check if the rest is just whitespace and Signed-off-by's. */
1040 for (i = start; i < sb->len; i++) {
1041 nl = memchr(sb->buf + i, '\n', sb->len - i);
1047 if (strlen(sign_off_header) <= eol - i &&
1048 starts_with(sb->buf + i, sign_off_header)) {
1053 if (!isspace(sb->buf[i++]))
1060 void cleanup_message(struct strbuf *msgbuf,
1061 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1063 if (verbose || /* Truncate the message just before the diff, if any. */
1064 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1065 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1066 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1067 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1071 * Find out if the message in the strbuf contains only whitespace and
1072 * Signed-off-by lines.
1074 int message_is_empty(const struct strbuf *sb,
1075 enum commit_msg_cleanup_mode cleanup_mode)
1077 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1079 return rest_is_empty(sb, 0);
1083 * See if the user edited the message in the editor or left what
1084 * was in the template intact
1086 int template_untouched(const struct strbuf *sb, const char *template_file,
1087 enum commit_msg_cleanup_mode cleanup_mode)
1089 struct strbuf tmpl = STRBUF_INIT;
1092 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1095 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1098 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1099 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1101 strbuf_release(&tmpl);
1102 return rest_is_empty(sb, start - sb->buf);
1105 int update_head_with_reflog(const struct commit *old_head,
1106 const struct object_id *new_head,
1107 const char *action, const struct strbuf *msg,
1110 struct ref_transaction *transaction;
1111 struct strbuf sb = STRBUF_INIT;
1116 strbuf_addstr(&sb, action);
1117 strbuf_addstr(&sb, ": ");
1120 nl = strchr(msg->buf, '\n');
1122 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1124 strbuf_addbuf(&sb, msg);
1125 strbuf_addch(&sb, '\n');
1128 transaction = ref_transaction_begin(err);
1130 ref_transaction_update(transaction, "HEAD", new_head,
1131 old_head ? &old_head->object.oid : &null_oid,
1133 ref_transaction_commit(transaction, err)) {
1136 ref_transaction_free(transaction);
1137 strbuf_release(&sb);
1142 static int run_rewrite_hook(const struct object_id *oldoid,
1143 const struct object_id *newoid)
1145 struct child_process proc = CHILD_PROCESS_INIT;
1146 const char *argv[3];
1148 struct strbuf sb = STRBUF_INIT;
1150 argv[0] = find_hook("post-rewrite");
1159 proc.stdout_to_stderr = 1;
1160 proc.trace2_hook_name = "post-rewrite";
1162 code = start_command(&proc);
1165 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1166 sigchain_push(SIGPIPE, SIG_IGN);
1167 write_in_full(proc.in, sb.buf, sb.len);
1169 strbuf_release(&sb);
1170 sigchain_pop(SIGPIPE);
1171 return finish_command(&proc);
1174 void commit_post_rewrite(struct repository *r,
1175 const struct commit *old_head,
1176 const struct object_id *new_head)
1178 struct notes_rewrite_cfg *cfg;
1180 cfg = init_copy_notes_for_rewrite("amend");
1182 /* we are amending, so old_head is not NULL */
1183 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1184 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1186 run_rewrite_hook(&old_head->object.oid, new_head);
1189 static int run_prepare_commit_msg_hook(struct repository *r,
1194 const char *name, *arg1 = NULL, *arg2 = NULL;
1196 name = git_path_commit_editmsg();
1197 if (write_message(msg->buf, msg->len, name, 0))
1206 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1208 ret = error(_("'prepare-commit-msg' hook failed"));
1213 static const char implicit_ident_advice_noconfig[] =
1214 N_("Your name and email address were configured automatically based\n"
1215 "on your username and hostname. Please check that they are accurate.\n"
1216 "You can suppress this message by setting them explicitly. Run the\n"
1217 "following command and follow the instructions in your editor to edit\n"
1218 "your configuration file:\n"
1220 " git config --global --edit\n"
1222 "After doing this, you may fix the identity used for this commit with:\n"
1224 " git commit --amend --reset-author\n");
1226 static const char implicit_ident_advice_config[] =
1227 N_("Your name and email address were configured automatically based\n"
1228 "on your username and hostname. Please check that they are accurate.\n"
1229 "You can suppress this message by setting them explicitly:\n"
1231 " git config --global user.name \"Your Name\"\n"
1232 " git config --global user.email you@example.com\n"
1234 "After doing this, you may fix the identity used for this commit with:\n"
1236 " git commit --amend --reset-author\n");
1238 static const char *implicit_ident_advice(void)
1240 char *user_config = expand_user_path("~/.gitconfig", 0);
1241 char *xdg_config = xdg_config_home("config");
1242 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1248 return _(implicit_ident_advice_config);
1250 return _(implicit_ident_advice_noconfig);
1254 void print_commit_summary(struct repository *r,
1256 const struct object_id *oid,
1259 struct rev_info rev;
1260 struct commit *commit;
1261 struct strbuf format = STRBUF_INIT;
1263 struct pretty_print_context pctx = {0};
1264 struct strbuf author_ident = STRBUF_INIT;
1265 struct strbuf committer_ident = STRBUF_INIT;
1267 commit = lookup_commit(r, oid);
1269 die(_("couldn't look up newly created commit"));
1270 if (parse_commit(commit))
1271 die(_("could not parse newly created commit"));
1273 strbuf_addstr(&format, "format:%h] %s");
1275 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1276 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1277 if (strbuf_cmp(&author_ident, &committer_ident)) {
1278 strbuf_addstr(&format, "\n Author: ");
1279 strbuf_addbuf_percentquote(&format, &author_ident);
1281 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1282 struct strbuf date = STRBUF_INIT;
1284 format_commit_message(commit, "%ad", &date, &pctx);
1285 strbuf_addstr(&format, "\n Date: ");
1286 strbuf_addbuf_percentquote(&format, &date);
1287 strbuf_release(&date);
1289 if (!committer_ident_sufficiently_given()) {
1290 strbuf_addstr(&format, "\n Committer: ");
1291 strbuf_addbuf_percentquote(&format, &committer_ident);
1292 if (advice_implicit_identity) {
1293 strbuf_addch(&format, '\n');
1294 strbuf_addstr(&format, implicit_ident_advice());
1297 strbuf_release(&author_ident);
1298 strbuf_release(&committer_ident);
1300 repo_init_revisions(r, &rev, prefix);
1301 setup_revisions(0, NULL, &rev, NULL);
1304 rev.diffopt.output_format =
1305 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1307 rev.verbose_header = 1;
1308 rev.show_root_diff = 1;
1309 get_commit_format(format.buf, &rev);
1310 rev.always_show_header = 0;
1311 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1312 rev.diffopt.break_opt = 0;
1313 diff_setup_done(&rev.diffopt);
1315 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1317 die_errno(_("unable to resolve HEAD after creating commit"));
1318 if (!strcmp(head, "HEAD"))
1319 head = _("detached HEAD");
1321 skip_prefix(head, "refs/heads/", &head);
1322 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1323 _(" (root-commit)") : "");
1325 if (!log_tree_commit(&rev, commit)) {
1326 rev.always_show_header = 1;
1327 rev.use_terminator = 1;
1328 log_tree_commit(&rev, commit);
1331 strbuf_release(&format);
1334 static int parse_head(struct repository *r, struct commit **head)
1336 struct commit *current_head;
1337 struct object_id oid;
1339 if (get_oid("HEAD", &oid)) {
1340 current_head = NULL;
1342 current_head = lookup_commit_reference(r, &oid);
1344 return error(_("could not parse HEAD"));
1345 if (!oideq(&oid, ¤t_head->object.oid)) {
1346 warning(_("HEAD %s is not a commit!"),
1349 if (parse_commit(current_head))
1350 return error(_("could not parse HEAD commit"));
1352 *head = current_head;
1358 * Try to commit without forking 'git commit'. In some cases we need
1359 * to run 'git commit' to display an error message
1362 * -1 - error unable to commit
1364 * 1 - run 'git commit'
1366 static int try_to_commit(struct repository *r,
1367 struct strbuf *msg, const char *author,
1368 struct replay_opts *opts, unsigned int flags,
1369 struct object_id *oid)
1371 struct object_id tree;
1372 struct commit *current_head = NULL;
1373 struct commit_list *parents = NULL;
1374 struct commit_extra_header *extra = NULL;
1375 struct strbuf err = STRBUF_INIT;
1376 struct strbuf commit_msg = STRBUF_INIT;
1377 char *amend_author = NULL;
1378 const char *committer = NULL;
1379 const char *hook_commit = NULL;
1380 enum commit_msg_cleanup_mode cleanup;
1383 if (parse_head(r, ¤t_head))
1386 if (flags & AMEND_MSG) {
1387 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1388 const char *out_enc = get_commit_output_encoding();
1389 const char *message = logmsg_reencode(current_head, NULL,
1393 const char *orig_message = NULL;
1395 find_commit_subject(message, &orig_message);
1397 strbuf_addstr(msg, orig_message);
1398 hook_commit = "HEAD";
1400 author = amend_author = get_author(message);
1401 unuse_commit_buffer(current_head, message);
1403 res = error(_("unable to parse commit author"));
1406 parents = copy_commit_list(current_head->parents);
1407 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1408 } else if (current_head &&
1409 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1410 commit_list_insert(current_head, &parents);
1413 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1414 res = error(_("git write-tree failed to write a tree"));
1418 if (!(flags & ALLOW_EMPTY)) {
1419 struct commit *first_parent = current_head;
1421 if (flags & AMEND_MSG) {
1422 if (current_head->parents) {
1423 first_parent = current_head->parents->item;
1424 if (repo_parse_commit(r, first_parent)) {
1425 res = error(_("could not parse HEAD commit"));
1429 first_parent = NULL;
1432 if (oideq(first_parent
1433 ? get_commit_tree_oid(first_parent)
1434 : the_hash_algo->empty_tree,
1436 res = 1; /* run 'git commit' to display error message */
1441 if (find_hook("prepare-commit-msg")) {
1442 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1445 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1447 res = error_errno(_("unable to read commit message "
1449 git_path_commit_editmsg());
1455 if (flags & CLEANUP_MSG)
1456 cleanup = COMMIT_MSG_CLEANUP_ALL;
1457 else if ((opts->signoff || opts->record_origin) &&
1458 !opts->explicit_cleanup)
1459 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1461 cleanup = opts->default_msg_cleanup;
1463 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1464 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1465 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1466 res = 1; /* run 'git commit' to display error message */
1470 if (opts->committer_date_is_author_date) {
1471 struct ident_split id;
1472 struct strbuf date = STRBUF_INIT;
1474 if (!opts->ignore_date) {
1475 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1476 res = error(_("invalid author identity '%s'"),
1480 if (!id.date_begin) {
1482 "corrupt author: missing date information"));
1485 strbuf_addf(&date, "@%.*s %.*s",
1486 (int)(id.date_end - id.date_begin),
1488 (int)(id.tz_end - id.tz_begin),
1493 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1494 getenv("GIT_COMMITTER_EMAIL"),
1495 WANT_COMMITTER_IDENT,
1496 opts->ignore_date ? NULL : date.buf,
1498 strbuf_release(&date);
1503 if (opts->ignore_date) {
1504 struct ident_split id;
1507 if (split_ident_line(&id, author, strlen(author)) < 0) {
1508 error(_("invalid author identity '%s'"), author);
1511 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1512 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1513 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1519 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1520 author, committer, opts->gpg_sign, extra)) {
1521 res = error(_("failed to write commit object"));
1525 if (update_head_with_reflog(current_head, oid,
1526 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1527 res = error("%s", err.buf);
1531 run_commit_hook(0, r->index_file, "post-commit", NULL);
1532 if (flags & AMEND_MSG)
1533 commit_post_rewrite(r, current_head, oid);
1536 free_commit_extra_headers(extra);
1537 strbuf_release(&err);
1538 strbuf_release(&commit_msg);
1544 static int write_rebase_head(struct object_id *oid)
1546 if (update_ref("rebase", "REBASE_HEAD", oid,
1547 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1548 return error(_("could not update %s"), "REBASE_HEAD");
1553 static int do_commit(struct repository *r,
1554 const char *msg_file, const char *author,
1555 struct replay_opts *opts, unsigned int flags,
1556 struct object_id *oid)
1560 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1561 struct object_id oid;
1562 struct strbuf sb = STRBUF_INIT;
1564 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1565 return error_errno(_("unable to read commit message "
1569 res = try_to_commit(r, msg_file ? &sb : NULL,
1570 author, opts, flags, &oid);
1571 strbuf_release(&sb);
1573 refs_delete_ref(get_main_ref_store(r), "",
1574 "CHERRY_PICK_HEAD", NULL, 0);
1575 unlink(git_path_merge_msg(r));
1576 if (!is_rebase_i(opts))
1577 print_commit_summary(r, NULL, &oid,
1578 SUMMARY_SHOW_AUTHOR_DATE);
1583 if (is_rebase_i(opts) && oid)
1584 if (write_rebase_head(oid))
1586 return run_git_commit(msg_file, opts, flags);
1592 static int is_original_commit_empty(struct commit *commit)
1594 const struct object_id *ptree_oid;
1596 if (parse_commit(commit))
1597 return error(_("could not parse commit %s"),
1598 oid_to_hex(&commit->object.oid));
1599 if (commit->parents) {
1600 struct commit *parent = commit->parents->item;
1601 if (parse_commit(parent))
1602 return error(_("could not parse parent commit %s"),
1603 oid_to_hex(&parent->object.oid));
1604 ptree_oid = get_commit_tree_oid(parent);
1606 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1609 return oideq(ptree_oid, get_commit_tree_oid(commit));
1613 * Should empty commits be allowed? Return status:
1614 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1615 * 0: Halt on empty commit
1616 * 1: Allow empty commit
1617 * 2: Drop empty commit
1619 static int allow_empty(struct repository *r,
1620 struct replay_opts *opts,
1621 struct commit *commit)
1623 int index_unchanged, originally_empty;
1628 * (1) we do not allow empty at all and error out.
1630 * (2) we allow ones that were initially empty, and
1631 * just drop the ones that become empty
1633 * (3) we allow ones that were initially empty, but
1634 * halt for the ones that become empty;
1636 * (4) we allow both.
1638 if (!opts->allow_empty)
1639 return 0; /* let "git commit" barf as necessary */
1641 index_unchanged = is_index_unchanged(r);
1642 if (index_unchanged < 0)
1643 return index_unchanged;
1644 if (!index_unchanged)
1645 return 0; /* we do not have to say --allow-empty */
1647 if (opts->keep_redundant_commits)
1650 originally_empty = is_original_commit_empty(commit);
1651 if (originally_empty < 0)
1652 return originally_empty;
1653 if (originally_empty)
1655 else if (opts->drop_redundant_commits)
1664 } todo_command_info[] = {
1681 static const char *command_to_string(const enum todo_command command)
1683 if (command < TODO_COMMENT)
1684 return todo_command_info[command].str;
1685 die(_("unknown command: %d"), command);
1688 static char command_to_char(const enum todo_command command)
1690 if (command < TODO_COMMENT)
1691 return todo_command_info[command].c;
1692 return comment_line_char;
1695 static int is_noop(const enum todo_command command)
1697 return TODO_NOOP <= command;
1700 static int is_fixup(enum todo_command command)
1702 return command == TODO_FIXUP || command == TODO_SQUASH;
1705 /* Does this command create a (non-merge) commit? */
1706 static int is_pick_or_similar(enum todo_command command)
1721 enum todo_item_flags {
1722 TODO_EDIT_MERGE_MSG = (1 << 0),
1723 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1724 TODO_EDIT_FIXUP_MSG = (1 << 2),
1727 static size_t subject_length(const char *body)
1729 const char *p = body;
1731 const char *next = skip_blank_lines(p);
1734 p = strchrnul(p, '\n');
1741 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1742 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1743 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1744 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1745 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1747 static int check_fixup_flag(enum todo_command command,
1748 enum todo_item_flags flag)
1750 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1751 (flag & TODO_EDIT_FIXUP_MSG));
1755 * Wrapper around strbuf_add_commented_lines() which avoids double
1756 * commenting commit subjects.
1758 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1760 const char *s = str;
1761 while (len > 0 && s[0] == comment_line_char) {
1763 const char *n = memchr(s, '\n', len);
1768 strbuf_add(buf, s, count);
1772 strbuf_add_commented_lines(buf, s, len);
1775 /* Does the current fixup chain contain a squash command? */
1776 static int seen_squash(struct replay_opts *opts)
1778 return starts_with(opts->current_fixups.buf, "squash") ||
1779 strstr(opts->current_fixups.buf, "\nsquash");
1782 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1784 strbuf_setlen(buf1, 2);
1785 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1786 strbuf_addch(buf1, '\n');
1787 strbuf_setlen(buf2, 2);
1788 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1789 strbuf_addch(buf2, '\n');
1793 * Comment out any un-commented commit messages, updating the message comments
1794 * to say they will be skipped but do not comment out the empty lines that
1795 * surround commit messages and their comments.
1797 static void update_squash_message_for_fixup(struct strbuf *msg)
1799 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1800 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1801 const char *s, *start;
1803 size_t orig_msg_len;
1806 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1807 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1808 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1812 if (skip_prefix(s, buf1.buf, &next)) {
1814 * Copy the last message, preserving the blank line
1815 * preceding the current line
1817 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1818 copy_lines(msg, start, s - start - off);
1820 strbuf_addch(msg, '\n');
1822 * The next message needs to be commented out but the
1823 * message header is already commented out so just copy
1824 * it and the blank line that follows it.
1826 strbuf_addbuf(msg, &buf2);
1828 strbuf_addch(msg, *next++);
1830 copy_lines = add_commented_lines;
1831 update_comment_bufs(&buf1, &buf2, ++i);
1832 } else if (skip_prefix(s, buf2.buf, &next)) {
1833 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1834 copy_lines(msg, start, s - start - off);
1837 copy_lines = strbuf_add;
1838 update_comment_bufs(&buf1, &buf2, ++i);
1840 s = strchr(s, '\n');
1845 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1847 strbuf_release(&buf1);
1848 strbuf_release(&buf2);
1851 static int append_squash_message(struct strbuf *buf, const char *body,
1852 enum todo_command command, struct replay_opts *opts,
1853 enum todo_item_flags flag)
1855 const char *fixup_msg;
1856 size_t commented_len = 0, fixup_off;
1858 * amend is non-interactive and not normally used with fixup!
1859 * or squash! commits, so only comment out those subjects when
1860 * squashing commit messages.
1862 if (starts_with(body, "amend!") ||
1863 ((command == TODO_SQUASH || seen_squash(opts)) &&
1864 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1865 commented_len = subject_length(body);
1867 strbuf_addf(buf, "\n%c ", comment_line_char);
1868 strbuf_addf(buf, _(nth_commit_msg_fmt),
1869 ++opts->current_fixup_count + 1);
1870 strbuf_addstr(buf, "\n\n");
1871 strbuf_add_commented_lines(buf, body, commented_len);
1872 /* buf->buf may be reallocated so store an offset into the buffer */
1873 fixup_off = buf->len;
1874 strbuf_addstr(buf, body + commented_len);
1876 /* fixup -C after squash behaves like squash */
1877 if (check_fixup_flag(command, flag) && !seen_squash(opts)) {
1879 * We're replacing the commit message so we need to
1880 * append the Signed-off-by: trailer if the user
1881 * requested '--signoff'.
1884 append_signoff(buf, 0, 0);
1886 if ((command == TODO_FIXUP) &&
1887 (flag & TODO_REPLACE_FIXUP_MSG) &&
1888 (file_exists(rebase_path_fixup_msg()) ||
1889 !file_exists(rebase_path_squash_msg()))) {
1890 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1891 if (write_message(fixup_msg, strlen(fixup_msg),
1892 rebase_path_fixup_msg(), 0) < 0)
1893 return error(_("cannot write '%s'"),
1894 rebase_path_fixup_msg());
1896 unlink(rebase_path_fixup_msg());
1899 unlink(rebase_path_fixup_msg());
1905 static int update_squash_messages(struct repository *r,
1906 enum todo_command command,
1907 struct commit *commit,
1908 struct replay_opts *opts,
1909 enum todo_item_flags flag)
1911 struct strbuf buf = STRBUF_INIT;
1913 const char *message, *body;
1914 const char *encoding = get_commit_output_encoding();
1916 if (opts->current_fixup_count > 0) {
1917 struct strbuf header = STRBUF_INIT;
1920 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1921 return error(_("could not read '%s'"),
1922 rebase_path_squash_msg());
1924 eol = buf.buf[0] != comment_line_char ?
1925 buf.buf : strchrnul(buf.buf, '\n');
1927 strbuf_addf(&header, "%c ", comment_line_char);
1928 strbuf_addf(&header, _(combined_commit_msg_fmt),
1929 opts->current_fixup_count + 2);
1930 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1931 strbuf_release(&header);
1932 if (check_fixup_flag(command, flag) && !seen_squash(opts))
1933 update_squash_message_for_fixup(&buf);
1935 struct object_id head;
1936 struct commit *head_commit;
1937 const char *head_message, *body;
1939 if (get_oid("HEAD", &head))
1940 return error(_("need a HEAD to fixup"));
1941 if (!(head_commit = lookup_commit_reference(r, &head)))
1942 return error(_("could not read HEAD"));
1943 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1944 return error(_("could not read HEAD's commit message"));
1946 find_commit_subject(head_message, &body);
1947 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1948 rebase_path_fixup_msg(), 0) < 0) {
1949 unuse_commit_buffer(head_commit, head_message);
1950 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1952 strbuf_addf(&buf, "%c ", comment_line_char);
1953 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1954 strbuf_addf(&buf, "\n%c ", comment_line_char);
1955 strbuf_addstr(&buf, check_fixup_flag(command, flag) ?
1956 _(skip_first_commit_msg_str) :
1957 _(first_commit_msg_str));
1958 strbuf_addstr(&buf, "\n\n");
1959 if (check_fixup_flag(command, flag))
1960 strbuf_add_commented_lines(&buf, body, strlen(body));
1962 strbuf_addstr(&buf, body);
1964 unuse_commit_buffer(head_commit, head_message);
1967 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1968 return error(_("could not read commit message of %s"),
1969 oid_to_hex(&commit->object.oid));
1970 find_commit_subject(message, &body);
1972 if (command == TODO_SQUASH || check_fixup_flag(command, flag)) {
1973 res = append_squash_message(&buf, body, command, opts, flag);
1974 } else if (command == TODO_FIXUP) {
1975 strbuf_addf(&buf, "\n%c ", comment_line_char);
1976 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1977 ++opts->current_fixup_count + 1);
1978 strbuf_addstr(&buf, "\n\n");
1979 strbuf_add_commented_lines(&buf, body, strlen(body));
1981 return error(_("unknown command: %d"), command);
1982 unuse_commit_buffer(commit, message);
1985 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1987 strbuf_release(&buf);
1990 strbuf_addf(&opts->current_fixups, "%s%s %s",
1991 opts->current_fixups.len ? "\n" : "",
1992 command_to_string(command),
1993 oid_to_hex(&commit->object.oid));
1994 res = write_message(opts->current_fixups.buf,
1995 opts->current_fixups.len,
1996 rebase_path_current_fixups(), 0);
2002 static void flush_rewritten_pending(void)
2004 struct strbuf buf = STRBUF_INIT;
2005 struct object_id newoid;
2008 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2009 !get_oid("HEAD", &newoid) &&
2010 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2011 char *bol = buf.buf, *eol;
2014 eol = strchrnul(bol, '\n');
2015 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2016 bol, oid_to_hex(&newoid));
2022 unlink(rebase_path_rewritten_pending());
2024 strbuf_release(&buf);
2027 static void record_in_rewritten(struct object_id *oid,
2028 enum todo_command next_command)
2030 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2035 fprintf(out, "%s\n", oid_to_hex(oid));
2038 if (!is_fixup(next_command))
2039 flush_rewritten_pending();
2042 static int do_pick_commit(struct repository *r,
2043 struct todo_item *item,
2044 struct replay_opts *opts,
2045 int final_fixup, int *check_todo)
2047 unsigned int flags = opts->edit ? EDIT_MSG : 0;
2048 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
2049 struct object_id head;
2050 struct commit *base, *next, *parent;
2051 const char *base_label, *next_label;
2052 char *author = NULL;
2053 struct commit_message msg = { NULL, NULL, NULL, NULL };
2054 struct strbuf msgbuf = STRBUF_INIT;
2055 int res, unborn = 0, reword = 0, allow, drop_commit;
2056 enum todo_command command = item->command;
2057 struct commit *commit = item->commit;
2059 if (opts->no_commit) {
2061 * We do not intend to commit immediately. We just want to
2062 * merge the differences in, so let's compute the tree
2063 * that represents the "current" state for merge-recursive
2066 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2067 return error(_("your index file is unmerged."));
2069 unborn = get_oid("HEAD", &head);
2070 /* Do we want to generate a root commit? */
2071 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2072 oideq(&head, &opts->squash_onto)) {
2073 if (is_fixup(command))
2074 return error(_("cannot fixup root commit"));
2075 flags |= CREATE_ROOT_COMMIT;
2078 oidcpy(&head, the_hash_algo->empty_tree);
2079 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2081 return error_dirty_index(r, opts);
2083 discard_index(r->index);
2085 if (!commit->parents)
2087 else if (commit->parents->next) {
2088 /* Reverting or cherry-picking a merge commit */
2090 struct commit_list *p;
2092 if (!opts->mainline)
2093 return error(_("commit %s is a merge but no -m option was given."),
2094 oid_to_hex(&commit->object.oid));
2096 for (cnt = 1, p = commit->parents;
2097 cnt != opts->mainline && p;
2100 if (cnt != opts->mainline || !p)
2101 return error(_("commit %s does not have parent %d"),
2102 oid_to_hex(&commit->object.oid), opts->mainline);
2104 } else if (1 < opts->mainline)
2106 * Non-first parent explicitly specified as mainline for
2109 return error(_("commit %s does not have parent %d"),
2110 oid_to_hex(&commit->object.oid), opts->mainline);
2112 parent = commit->parents->item;
2114 if (get_message(commit, &msg) != 0)
2115 return error(_("cannot get commit message for %s"),
2116 oid_to_hex(&commit->object.oid));
2118 if (opts->allow_ff && !is_fixup(command) &&
2119 ((parent && oideq(&parent->object.oid, &head)) ||
2120 (!parent && unborn))) {
2121 if (is_rebase_i(opts))
2122 write_author_script(msg.message);
2123 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2125 if (res || command != TODO_REWORD)
2129 goto fast_forward_edit;
2131 if (parent && parse_commit(parent) < 0)
2132 /* TRANSLATORS: The first %s will be a "todo" command like
2133 "revert" or "pick", the second %s a SHA1. */
2134 return error(_("%s: cannot parse parent commit %s"),
2135 command_to_string(command),
2136 oid_to_hex(&parent->object.oid));
2139 * "commit" is an existing commit. We would want to apply
2140 * the difference it introduces since its first parent "prev"
2141 * on top of the current HEAD if we are cherry-pick. Or the
2142 * reverse of it if we are revert.
2145 if (command == TODO_REVERT) {
2147 base_label = msg.label;
2149 next_label = msg.parent_label;
2150 strbuf_addstr(&msgbuf, "Revert \"");
2151 strbuf_addstr(&msgbuf, msg.subject);
2152 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2153 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2155 if (commit->parents && commit->parents->next) {
2156 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2157 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2159 strbuf_addstr(&msgbuf, ".\n");
2164 base_label = msg.parent_label;
2166 next_label = msg.label;
2168 /* Append the commit log message to msgbuf. */
2169 if (find_commit_subject(msg.message, &p))
2170 strbuf_addstr(&msgbuf, p);
2172 if (opts->record_origin) {
2173 strbuf_complete_line(&msgbuf);
2174 if (!has_conforming_footer(&msgbuf, NULL, 0))
2175 strbuf_addch(&msgbuf, '\n');
2176 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2177 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2178 strbuf_addstr(&msgbuf, ")\n");
2180 if (!is_fixup(command))
2181 author = get_author(msg.message);
2184 if (command == TODO_REWORD)
2186 else if (is_fixup(command)) {
2187 if (update_squash_messages(r, command, commit,
2192 msg_file = rebase_path_squash_msg();
2193 else if (file_exists(rebase_path_fixup_msg())) {
2194 flags |= CLEANUP_MSG;
2195 msg_file = rebase_path_fixup_msg();
2197 const char *dest = git_path_squash_msg(r);
2199 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2200 return error(_("could not rename '%s' to '%s'"),
2201 rebase_path_squash_msg(), dest);
2202 unlink(git_path_merge_msg(r));
2208 if (opts->signoff && !is_fixup(command))
2209 append_signoff(&msgbuf, 0, 0);
2211 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2213 else if (!opts->strategy ||
2214 !strcmp(opts->strategy, "recursive") ||
2215 !strcmp(opts->strategy, "ort") ||
2216 command == TODO_REVERT) {
2217 res = do_recursive_merge(r, base, next, base_label, next_label,
2218 &head, &msgbuf, opts);
2222 res |= write_message(msgbuf.buf, msgbuf.len,
2223 git_path_merge_msg(r), 0);
2225 struct commit_list *common = NULL;
2226 struct commit_list *remotes = NULL;
2228 res = write_message(msgbuf.buf, msgbuf.len,
2229 git_path_merge_msg(r), 0);
2231 commit_list_insert(base, &common);
2232 commit_list_insert(next, &remotes);
2233 res |= try_merge_command(r, opts->strategy,
2234 opts->xopts_nr, (const char **)opts->xopts,
2235 common, oid_to_hex(&head), remotes);
2236 free_commit_list(common);
2237 free_commit_list(remotes);
2239 strbuf_release(&msgbuf);
2242 * If the merge was clean or if it failed due to conflict, we write
2243 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2244 * However, if the merge did not even start, then we don't want to
2247 if ((command == TODO_PICK || command == TODO_REWORD ||
2248 command == TODO_EDIT) && !opts->no_commit &&
2249 (res == 0 || res == 1) &&
2250 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2251 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2253 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2254 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2255 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2259 error(command == TODO_REVERT
2260 ? _("could not revert %s... %s")
2261 : _("could not apply %s... %s"),
2262 short_commit_name(commit), msg.subject);
2263 print_advice(r, res == 1, opts);
2264 repo_rerere(r, opts->allow_rerere_auto);
2269 allow = allow_empty(r, opts, commit);
2273 } else if (allow == 1) {
2274 flags |= ALLOW_EMPTY;
2275 } else if (allow == 2) {
2277 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2279 unlink(git_path_merge_msg(r));
2281 _("dropping %s %s -- patch contents already upstream\n"),
2282 oid_to_hex(&commit->object.oid), msg.subject);
2283 } /* else allow == 0 and there's nothing special to do */
2284 if (!opts->no_commit && !drop_commit) {
2285 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2286 res = do_commit(r, msg_file, author, opts, flags,
2287 commit? &commit->object.oid : NULL);
2289 res = error(_("unable to parse commit author"));
2290 *check_todo = !!(flags & EDIT_MSG);
2291 if (!res && reword) {
2293 res = run_git_commit(NULL, opts, EDIT_MSG |
2294 VERIFY_MSG | AMEND_MSG |
2295 (flags & ALLOW_EMPTY));
2301 if (!res && final_fixup) {
2302 unlink(rebase_path_fixup_msg());
2303 unlink(rebase_path_squash_msg());
2304 unlink(rebase_path_current_fixups());
2305 strbuf_reset(&opts->current_fixups);
2306 opts->current_fixup_count = 0;
2310 free_message(commit, &msg);
2312 update_abort_safety_file();
2317 static int prepare_revs(struct replay_opts *opts)
2320 * picking (but not reverting) ranges (but not individual revisions)
2321 * should be done in reverse
2323 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2324 opts->revs->reverse ^= 1;
2326 if (prepare_revision_walk(opts->revs))
2327 return error(_("revision walk setup failed"));
2332 static int read_and_refresh_cache(struct repository *r,
2333 struct replay_opts *opts)
2335 struct lock_file index_lock = LOCK_INIT;
2336 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2337 if (repo_read_index(r) < 0) {
2338 rollback_lock_file(&index_lock);
2339 return error(_("git %s: failed to read the index"),
2340 _(action_name(opts)));
2342 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2343 if (index_fd >= 0) {
2344 if (write_locked_index(r->index, &index_lock,
2345 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2346 return error(_("git %s: failed to refresh the index"),
2347 _(action_name(opts)));
2353 void todo_list_release(struct todo_list *todo_list)
2355 strbuf_release(&todo_list->buf);
2356 FREE_AND_NULL(todo_list->items);
2357 todo_list->nr = todo_list->alloc = 0;
2360 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2362 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2363 todo_list->total_nr++;
2364 return todo_list->items + todo_list->nr++;
2367 const char *todo_item_get_arg(struct todo_list *todo_list,
2368 struct todo_item *item)
2370 return todo_list->buf.buf + item->arg_offset;
2373 static int is_command(enum todo_command command, const char **bol)
2375 const char *str = todo_command_info[command].str;
2376 const char nick = todo_command_info[command].c;
2377 const char *p = *bol + 1;
2379 return skip_prefix(*bol, str, bol) ||
2380 ((nick && **bol == nick) &&
2381 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2385 static int parse_insn_line(struct repository *r, struct todo_item *item,
2386 const char *buf, const char *bol, char *eol)
2388 struct object_id commit_oid;
2389 char *end_of_object_name;
2390 int i, saved, status, padding;
2395 bol += strspn(bol, " \t");
2397 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2398 item->command = TODO_COMMENT;
2399 item->commit = NULL;
2400 item->arg_offset = bol - buf;
2401 item->arg_len = eol - bol;
2405 for (i = 0; i < TODO_COMMENT; i++)
2406 if (is_command(i, &bol)) {
2410 if (i >= TODO_COMMENT)
2413 /* Eat up extra spaces/ tabs before object name */
2414 padding = strspn(bol, " \t");
2417 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2419 return error(_("%s does not accept arguments: '%s'"),
2420 command_to_string(item->command), bol);
2421 item->commit = NULL;
2422 item->arg_offset = bol - buf;
2423 item->arg_len = eol - bol;
2428 return error(_("missing arguments for %s"),
2429 command_to_string(item->command));
2431 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2432 item->command == TODO_RESET) {
2433 item->commit = NULL;
2434 item->arg_offset = bol - buf;
2435 item->arg_len = (int)(eol - bol);
2439 if (item->command == TODO_FIXUP) {
2440 if (skip_prefix(bol, "-C", &bol) &&
2441 (*bol == ' ' || *bol == '\t')) {
2442 bol += strspn(bol, " \t");
2443 item->flags |= TODO_REPLACE_FIXUP_MSG;
2444 } else if (skip_prefix(bol, "-c", &bol) &&
2445 (*bol == ' ' || *bol == '\t')) {
2446 bol += strspn(bol, " \t");
2447 item->flags |= TODO_EDIT_FIXUP_MSG;
2451 if (item->command == TODO_MERGE) {
2452 if (skip_prefix(bol, "-C", &bol))
2453 bol += strspn(bol, " \t");
2454 else if (skip_prefix(bol, "-c", &bol)) {
2455 bol += strspn(bol, " \t");
2456 item->flags |= TODO_EDIT_MERGE_MSG;
2458 item->flags |= TODO_EDIT_MERGE_MSG;
2459 item->commit = NULL;
2460 item->arg_offset = bol - buf;
2461 item->arg_len = (int)(eol - bol);
2466 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2467 saved = *end_of_object_name;
2468 *end_of_object_name = '\0';
2469 status = get_oid(bol, &commit_oid);
2471 error(_("could not parse '%s'"), bol); /* return later */
2472 *end_of_object_name = saved;
2474 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2475 item->arg_offset = bol - buf;
2476 item->arg_len = (int)(eol - bol);
2481 item->commit = lookup_commit_reference(r, &commit_oid);
2482 return item->commit ? 0 : -1;
2485 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2487 const char *todo_file, *bol;
2488 struct strbuf buf = STRBUF_INIT;
2491 todo_file = git_path_todo_file();
2492 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2493 if (errno == ENOENT || errno == ENOTDIR)
2496 return error_errno("unable to open '%s'", todo_file);
2498 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2499 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2500 *action = REPLAY_PICK;
2501 else if (is_command(TODO_REVERT, &bol) &&
2502 (*bol == ' ' || *bol == '\t'))
2503 *action = REPLAY_REVERT;
2507 strbuf_release(&buf);
2512 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2513 struct todo_list *todo_list)
2515 struct todo_item *item;
2516 char *p = buf, *next_p;
2517 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2519 todo_list->current = todo_list->nr = 0;
2521 for (i = 1; *p; i++, p = next_p) {
2522 char *eol = strchrnul(p, '\n');
2524 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2526 if (p != eol && eol[-1] == '\r')
2527 eol--; /* strip Carriage Return */
2529 item = append_new_todo(todo_list);
2530 item->offset_in_buf = p - todo_list->buf.buf;
2531 if (parse_insn_line(r, item, buf, p, eol)) {
2532 res = error(_("invalid line %d: %.*s"),
2533 i, (int)(eol - p), p);
2534 item->command = TODO_COMMENT + 1;
2535 item->arg_offset = p - buf;
2536 item->arg_len = (int)(eol - p);
2537 item->commit = NULL;
2542 else if (is_fixup(item->command))
2543 return error(_("cannot '%s' without a previous commit"),
2544 command_to_string(item->command));
2545 else if (!is_noop(item->command))
2552 static int count_commands(struct todo_list *todo_list)
2556 for (i = 0; i < todo_list->nr; i++)
2557 if (todo_list->items[i].command != TODO_COMMENT)
2563 static int get_item_line_offset(struct todo_list *todo_list, int index)
2565 return index < todo_list->nr ?
2566 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2569 static const char *get_item_line(struct todo_list *todo_list, int index)
2571 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2574 static int get_item_line_length(struct todo_list *todo_list, int index)
2576 return get_item_line_offset(todo_list, index + 1)
2577 - get_item_line_offset(todo_list, index);
2580 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2585 fd = open(path, O_RDONLY);
2587 return error_errno(_("could not open '%s'"), path);
2588 len = strbuf_read(sb, fd, 0);
2591 return error(_("could not read '%s'."), path);
2595 static int have_finished_the_last_pick(void)
2597 struct strbuf buf = STRBUF_INIT;
2599 const char *todo_path = git_path_todo_file();
2602 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2603 if (errno == ENOENT) {
2606 error_errno("unable to open '%s'", todo_path);
2610 /* If there is only one line then we are done */
2611 eol = strchr(buf.buf, '\n');
2612 if (!eol || !eol[1])
2615 strbuf_release(&buf);
2620 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2622 struct replay_opts opts = REPLAY_OPTS_INIT;
2623 int need_cleanup = 0;
2625 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2626 if (!refs_delete_ref(get_main_ref_store(r), "",
2627 "CHERRY_PICK_HEAD", NULL, 0) &&
2629 warning(_("cancelling a cherry picking in progress"));
2630 opts.action = REPLAY_PICK;
2634 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2635 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2638 warning(_("cancelling a revert in progress"));
2639 opts.action = REPLAY_REVERT;
2646 if (!have_finished_the_last_pick())
2649 sequencer_remove_state(&opts);
2652 static void todo_list_write_total_nr(struct todo_list *todo_list)
2654 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2657 fprintf(f, "%d\n", todo_list->total_nr);
2662 static int read_populate_todo(struct repository *r,
2663 struct todo_list *todo_list,
2664 struct replay_opts *opts)
2667 const char *todo_file = get_todo_path(opts);
2670 strbuf_reset(&todo_list->buf);
2671 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2674 res = stat(todo_file, &st);
2676 return error(_("could not stat '%s'"), todo_file);
2677 fill_stat_data(&todo_list->stat, &st);
2679 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2681 if (is_rebase_i(opts))
2682 return error(_("please fix this using "
2683 "'git rebase --edit-todo'."));
2684 return error(_("unusable instruction sheet: '%s'"), todo_file);
2687 if (!todo_list->nr &&
2688 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2689 return error(_("no commits parsed."));
2691 if (!is_rebase_i(opts)) {
2692 enum todo_command valid =
2693 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2696 for (i = 0; i < todo_list->nr; i++)
2697 if (valid == todo_list->items[i].command)
2699 else if (valid == TODO_PICK)
2700 return error(_("cannot cherry-pick during a revert."));
2702 return error(_("cannot revert during a cherry-pick."));
2705 if (is_rebase_i(opts)) {
2706 struct todo_list done = TODO_LIST_INIT;
2708 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2709 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2710 todo_list->done_nr = count_commands(&done);
2712 todo_list->done_nr = 0;
2714 todo_list->total_nr = todo_list->done_nr
2715 + count_commands(todo_list);
2716 todo_list_release(&done);
2718 todo_list_write_total_nr(todo_list);
2724 static int git_config_string_dup(char **dest,
2725 const char *var, const char *value)
2728 return config_error_nonbool(var);
2730 *dest = xstrdup(value);
2734 static int populate_opts_cb(const char *key, const char *value, void *data)
2736 struct replay_opts *opts = data;
2741 else if (!strcmp(key, "options.no-commit"))
2742 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2743 else if (!strcmp(key, "options.edit"))
2744 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2745 else if (!strcmp(key, "options.allow-empty"))
2747 git_config_bool_or_int(key, value, &error_flag);
2748 else if (!strcmp(key, "options.allow-empty-message"))
2749 opts->allow_empty_message =
2750 git_config_bool_or_int(key, value, &error_flag);
2751 else if (!strcmp(key, "options.keep-redundant-commits"))
2752 opts->keep_redundant_commits =
2753 git_config_bool_or_int(key, value, &error_flag);
2754 else if (!strcmp(key, "options.signoff"))
2755 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2756 else if (!strcmp(key, "options.record-origin"))
2757 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2758 else if (!strcmp(key, "options.allow-ff"))
2759 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2760 else if (!strcmp(key, "options.mainline"))
2761 opts->mainline = git_config_int(key, value);
2762 else if (!strcmp(key, "options.strategy"))
2763 git_config_string_dup(&opts->strategy, key, value);
2764 else if (!strcmp(key, "options.gpg-sign"))
2765 git_config_string_dup(&opts->gpg_sign, key, value);
2766 else if (!strcmp(key, "options.strategy-option")) {
2767 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2768 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2769 } else if (!strcmp(key, "options.allow-rerere-auto"))
2770 opts->allow_rerere_auto =
2771 git_config_bool_or_int(key, value, &error_flag) ?
2772 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2773 else if (!strcmp(key, "options.default-msg-cleanup")) {
2774 opts->explicit_cleanup = 1;
2775 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2777 return error(_("invalid key: %s"), key);
2780 return error(_("invalid value for %s: %s"), key, value);
2785 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2788 char *strategy_opts_string = raw_opts;
2790 if (*strategy_opts_string == ' ')
2791 strategy_opts_string++;
2793 opts->xopts_nr = split_cmdline(strategy_opts_string,
2794 (const char ***)&opts->xopts);
2795 for (i = 0; i < opts->xopts_nr; i++) {
2796 const char *arg = opts->xopts[i];
2798 skip_prefix(arg, "--", &arg);
2799 opts->xopts[i] = xstrdup(arg);
2803 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2806 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2808 opts->strategy = strbuf_detach(buf, NULL);
2809 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2812 parse_strategy_opts(opts, buf->buf);
2815 static int read_populate_opts(struct replay_opts *opts)
2817 if (is_rebase_i(opts)) {
2818 struct strbuf buf = STRBUF_INIT;
2821 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2822 READ_ONELINER_SKIP_IF_EMPTY)) {
2823 if (!starts_with(buf.buf, "-S"))
2826 free(opts->gpg_sign);
2827 opts->gpg_sign = xstrdup(buf.buf + 2);
2832 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2833 READ_ONELINER_SKIP_IF_EMPTY)) {
2834 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2835 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2836 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2837 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2841 if (file_exists(rebase_path_verbose()))
2844 if (file_exists(rebase_path_quiet()))
2847 if (file_exists(rebase_path_signoff())) {
2852 if (file_exists(rebase_path_cdate_is_adate())) {
2854 opts->committer_date_is_author_date = 1;
2857 if (file_exists(rebase_path_ignore_date())) {
2859 opts->ignore_date = 1;
2862 if (file_exists(rebase_path_reschedule_failed_exec()))
2863 opts->reschedule_failed_exec = 1;
2865 if (file_exists(rebase_path_drop_redundant_commits()))
2866 opts->drop_redundant_commits = 1;
2868 if (file_exists(rebase_path_keep_redundant_commits()))
2869 opts->keep_redundant_commits = 1;
2871 read_strategy_opts(opts, &buf);
2874 if (read_oneliner(&opts->current_fixups,
2875 rebase_path_current_fixups(),
2876 READ_ONELINER_SKIP_IF_EMPTY)) {
2877 const char *p = opts->current_fixups.buf;
2878 opts->current_fixup_count = 1;
2879 while ((p = strchr(p, '\n'))) {
2880 opts->current_fixup_count++;
2885 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2886 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2887 ret = error(_("unusable squash-onto"));
2890 opts->have_squash_onto = 1;
2894 strbuf_release(&buf);
2898 if (!file_exists(git_path_opts_file()))
2901 * The function git_parse_source(), called from git_config_from_file(),
2902 * may die() in case of a syntactically incorrect file. We do not care
2903 * about this case, though, because we wrote that file ourselves, so we
2904 * are pretty certain that it is syntactically correct.
2906 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2907 return error(_("malformed options sheet: '%s'"),
2908 git_path_opts_file());
2912 static void write_strategy_opts(struct replay_opts *opts)
2915 struct strbuf buf = STRBUF_INIT;
2917 for (i = 0; i < opts->xopts_nr; ++i)
2918 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2920 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2921 strbuf_release(&buf);
2924 int write_basic_state(struct replay_opts *opts, const char *head_name,
2925 struct commit *onto, const struct object_id *orig_head)
2928 write_file(rebase_path_head_name(), "%s\n", head_name);
2930 write_file(rebase_path_onto(), "%s\n",
2931 oid_to_hex(&onto->object.oid));
2933 write_file(rebase_path_orig_head(), "%s\n",
2934 oid_to_hex(orig_head));
2937 write_file(rebase_path_quiet(), "%s", "");
2939 write_file(rebase_path_verbose(), "%s", "");
2941 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2942 if (opts->xopts_nr > 0)
2943 write_strategy_opts(opts);
2945 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2946 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2947 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2948 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2951 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2953 write_file(rebase_path_signoff(), "--signoff\n");
2954 if (opts->drop_redundant_commits)
2955 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2956 if (opts->keep_redundant_commits)
2957 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2958 if (opts->committer_date_is_author_date)
2959 write_file(rebase_path_cdate_is_adate(), "%s", "");
2960 if (opts->ignore_date)
2961 write_file(rebase_path_ignore_date(), "%s", "");
2962 if (opts->reschedule_failed_exec)
2963 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2968 static int walk_revs_populate_todo(struct todo_list *todo_list,
2969 struct replay_opts *opts)
2971 enum todo_command command = opts->action == REPLAY_PICK ?
2972 TODO_PICK : TODO_REVERT;
2973 const char *command_string = todo_command_info[command].str;
2974 const char *encoding;
2975 struct commit *commit;
2977 if (prepare_revs(opts))
2980 encoding = get_log_output_encoding();
2982 while ((commit = get_revision(opts->revs))) {
2983 struct todo_item *item = append_new_todo(todo_list);
2984 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2985 const char *subject;
2988 item->command = command;
2989 item->commit = commit;
2990 item->arg_offset = 0;
2992 item->offset_in_buf = todo_list->buf.len;
2993 subject_len = find_commit_subject(commit_buffer, &subject);
2994 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2995 short_commit_name(commit), subject_len, subject);
2996 unuse_commit_buffer(commit, commit_buffer);
3000 return error(_("empty commit set passed"));
3005 static int create_seq_dir(struct repository *r)
3007 enum replay_action action;
3008 const char *in_progress_error = NULL;
3009 const char *in_progress_advice = NULL;
3010 unsigned int advise_skip =
3011 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3012 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3014 if (!sequencer_get_last_command(r, &action)) {
3017 in_progress_error = _("revert is already in progress");
3018 in_progress_advice =
3019 _("try \"git revert (--continue | %s--abort | --quit)\"");
3022 in_progress_error = _("cherry-pick is already in progress");
3023 in_progress_advice =
3024 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3027 BUG("unexpected action in create_seq_dir");
3030 if (in_progress_error) {
3031 error("%s", in_progress_error);
3032 if (advice_sequencer_in_use)
3033 advise(in_progress_advice,
3034 advise_skip ? "--skip | " : "");
3037 if (mkdir(git_path_seq_dir(), 0777) < 0)
3038 return error_errno(_("could not create sequencer directory '%s'"),
3039 git_path_seq_dir());
3044 static int save_head(const char *head)
3046 struct lock_file head_lock = LOCK_INIT;
3047 struct strbuf buf = STRBUF_INIT;
3051 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3053 return error_errno(_("could not lock HEAD"));
3054 strbuf_addf(&buf, "%s\n", head);
3055 written = write_in_full(fd, buf.buf, buf.len);
3056 strbuf_release(&buf);
3058 error_errno(_("could not write to '%s'"), git_path_head_file());
3059 rollback_lock_file(&head_lock);
3062 if (commit_lock_file(&head_lock) < 0)
3063 return error(_("failed to finalize '%s'"), git_path_head_file());
3067 static int rollback_is_safe(void)
3069 struct strbuf sb = STRBUF_INIT;
3070 struct object_id expected_head, actual_head;
3072 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3074 if (get_oid_hex(sb.buf, &expected_head)) {
3075 strbuf_release(&sb);
3076 die(_("could not parse %s"), git_path_abort_safety_file());
3078 strbuf_release(&sb);
3080 else if (errno == ENOENT)
3081 oidclr(&expected_head);
3083 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3085 if (get_oid("HEAD", &actual_head))
3086 oidclr(&actual_head);
3088 return oideq(&actual_head, &expected_head);
3091 static int reset_merge(const struct object_id *oid)
3094 struct strvec argv = STRVEC_INIT;
3096 strvec_pushl(&argv, "reset", "--merge", NULL);
3098 if (!is_null_oid(oid))
3099 strvec_push(&argv, oid_to_hex(oid));
3101 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3102 strvec_clear(&argv);
3107 static int rollback_single_pick(struct repository *r)
3109 struct object_id head_oid;
3111 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3112 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3113 return error(_("no cherry-pick or revert in progress"));
3114 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3115 return error(_("cannot resolve HEAD"));
3116 if (is_null_oid(&head_oid))
3117 return error(_("cannot abort from a branch yet to be born"));
3118 return reset_merge(&head_oid);
3121 static int skip_single_pick(void)
3123 struct object_id head;
3125 if (read_ref_full("HEAD", 0, &head, NULL))
3126 return error(_("cannot resolve HEAD"));
3127 return reset_merge(&head);
3130 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3133 struct object_id oid;
3134 struct strbuf buf = STRBUF_INIT;
3137 f = fopen(git_path_head_file(), "r");
3138 if (!f && errno == ENOENT) {
3140 * There is no multiple-cherry-pick in progress.
3141 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3142 * a single-cherry-pick in progress, abort that.
3144 return rollback_single_pick(r);
3147 return error_errno(_("cannot open '%s'"), git_path_head_file());
3148 if (strbuf_getline_lf(&buf, f)) {
3149 error(_("cannot read '%s': %s"), git_path_head_file(),
3150 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3155 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3156 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3157 git_path_head_file());
3160 if (is_null_oid(&oid)) {
3161 error(_("cannot abort from a branch yet to be born"));
3165 if (!rollback_is_safe()) {
3166 /* Do not error, just do not rollback */
3167 warning(_("You seem to have moved HEAD. "
3168 "Not rewinding, check your HEAD!"));
3170 if (reset_merge(&oid))
3172 strbuf_release(&buf);
3173 return sequencer_remove_state(opts);
3175 strbuf_release(&buf);
3179 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3181 enum replay_action action = -1;
3182 sequencer_get_last_command(r, &action);
3185 * Check whether the subcommand requested to skip the commit is actually
3186 * in progress and that it's safe to skip the commit.
3188 * opts->action tells us which subcommand requested to skip the commit.
3189 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3190 * action is in progress and we can skip the commit.
3192 * Otherwise we check that the last instruction was related to the
3193 * particular subcommand we're trying to execute and barf if that's not
3196 * Finally we check that the rollback is "safe", i.e., has the HEAD
3197 * moved? In this case, it doesn't make sense to "reset the merge" and
3198 * "skip the commit" as the user already handled this by committing. But
3199 * we'd not want to barf here, instead give advice on how to proceed. We
3200 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3201 * it gets removed when the user commits, so if it still exists we're
3202 * sure the user can't have committed before.
3204 switch (opts->action) {
3206 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3207 if (action != REPLAY_REVERT)
3208 return error(_("no revert in progress"));
3209 if (!rollback_is_safe())
3214 if (!refs_ref_exists(get_main_ref_store(r),
3215 "CHERRY_PICK_HEAD")) {
3216 if (action != REPLAY_PICK)
3217 return error(_("no cherry-pick in progress"));
3218 if (!rollback_is_safe())
3223 BUG("unexpected action in sequencer_skip");
3226 if (skip_single_pick())
3227 return error(_("failed to skip the commit"));
3228 if (!is_directory(git_path_seq_dir()))
3231 return sequencer_continue(r, opts);
3234 error(_("there is nothing to skip"));
3236 if (advice_resolve_conflict) {
3237 advise(_("have you committed already?\n"
3238 "try \"git %s --continue\""),
3239 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3244 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3246 struct lock_file todo_lock = LOCK_INIT;
3247 const char *todo_path = get_todo_path(opts);
3248 int next = todo_list->current, offset, fd;
3251 * rebase -i writes "git-rebase-todo" without the currently executing
3252 * command, appending it to "done" instead.
3254 if (is_rebase_i(opts))
3257 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3259 return error_errno(_("could not lock '%s'"), todo_path);
3260 offset = get_item_line_offset(todo_list, next);
3261 if (write_in_full(fd, todo_list->buf.buf + offset,
3262 todo_list->buf.len - offset) < 0)
3263 return error_errno(_("could not write to '%s'"), todo_path);
3264 if (commit_lock_file(&todo_lock) < 0)
3265 return error(_("failed to finalize '%s'"), todo_path);
3267 if (is_rebase_i(opts) && next > 0) {
3268 const char *done = rebase_path_done();
3269 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3274 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3275 get_item_line_length(todo_list, next - 1))
3277 ret = error_errno(_("could not write to '%s'"), done);
3279 ret = error_errno(_("failed to finalize '%s'"), done);
3285 static int save_opts(struct replay_opts *opts)
3287 const char *opts_file = git_path_opts_file();
3290 if (opts->no_commit)
3291 res |= git_config_set_in_file_gently(opts_file,
3292 "options.no-commit", "true");
3294 res |= git_config_set_in_file_gently(opts_file,
3295 "options.edit", "true");
3296 if (opts->allow_empty)
3297 res |= git_config_set_in_file_gently(opts_file,
3298 "options.allow-empty", "true");
3299 if (opts->allow_empty_message)
3300 res |= git_config_set_in_file_gently(opts_file,
3301 "options.allow-empty-message", "true");
3302 if (opts->keep_redundant_commits)
3303 res |= git_config_set_in_file_gently(opts_file,
3304 "options.keep-redundant-commits", "true");
3306 res |= git_config_set_in_file_gently(opts_file,
3307 "options.signoff", "true");
3308 if (opts->record_origin)
3309 res |= git_config_set_in_file_gently(opts_file,
3310 "options.record-origin", "true");
3312 res |= git_config_set_in_file_gently(opts_file,
3313 "options.allow-ff", "true");
3314 if (opts->mainline) {
3315 struct strbuf buf = STRBUF_INIT;
3316 strbuf_addf(&buf, "%d", opts->mainline);
3317 res |= git_config_set_in_file_gently(opts_file,
3318 "options.mainline", buf.buf);
3319 strbuf_release(&buf);
3322 res |= git_config_set_in_file_gently(opts_file,
3323 "options.strategy", opts->strategy);
3325 res |= git_config_set_in_file_gently(opts_file,
3326 "options.gpg-sign", opts->gpg_sign);
3329 for (i = 0; i < opts->xopts_nr; i++)
3330 res |= git_config_set_multivar_in_file_gently(opts_file,
3331 "options.strategy-option",
3332 opts->xopts[i], "^$", 0);
3334 if (opts->allow_rerere_auto)
3335 res |= git_config_set_in_file_gently(opts_file,
3336 "options.allow-rerere-auto",
3337 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3340 if (opts->explicit_cleanup)
3341 res |= git_config_set_in_file_gently(opts_file,
3342 "options.default-msg-cleanup",
3343 describe_cleanup_mode(opts->default_msg_cleanup));
3347 static int make_patch(struct repository *r,
3348 struct commit *commit,
3349 struct replay_opts *opts)
3351 struct strbuf buf = STRBUF_INIT;
3352 struct rev_info log_tree_opt;
3353 const char *subject;
3354 char hex[GIT_MAX_HEXSZ + 1];
3357 oid_to_hex_r(hex, &commit->object.oid);
3358 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3360 res |= write_rebase_head(&commit->object.oid);
3362 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3363 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3364 repo_init_revisions(r, &log_tree_opt, NULL);
3365 log_tree_opt.abbrev = 0;
3366 log_tree_opt.diff = 1;
3367 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3368 log_tree_opt.disable_stdin = 1;
3369 log_tree_opt.no_commit_id = 1;
3370 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3371 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3372 if (!log_tree_opt.diffopt.file)
3373 res |= error_errno(_("could not open '%s'"), buf.buf);
3375 res |= log_tree_commit(&log_tree_opt, commit);
3376 fclose(log_tree_opt.diffopt.file);
3380 strbuf_addf(&buf, "%s/message", get_dir(opts));
3381 if (!file_exists(buf.buf)) {
3382 const char *encoding = get_commit_output_encoding();
3383 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3384 find_commit_subject(commit_buffer, &subject);
3385 res |= write_message(subject, strlen(subject), buf.buf, 1);
3386 unuse_commit_buffer(commit, commit_buffer);
3388 strbuf_release(&buf);
3393 static int intend_to_amend(void)
3395 struct object_id head;
3398 if (get_oid("HEAD", &head))
3399 return error(_("cannot read HEAD"));
3401 p = oid_to_hex(&head);
3402 return write_message(p, strlen(p), rebase_path_amend(), 1);
3405 static int error_with_patch(struct repository *r,
3406 struct commit *commit,
3407 const char *subject, int subject_len,
3408 struct replay_opts *opts,
3409 int exit_code, int to_amend)
3412 if (make_patch(r, commit, opts))
3414 } else if (copy_file(rebase_path_message(),
3415 git_path_merge_msg(r), 0666))
3416 return error(_("unable to copy '%s' to '%s'"),
3417 git_path_merge_msg(r), rebase_path_message());
3420 if (intend_to_amend())
3424 _("You can amend the commit now, with\n"
3426 " git commit --amend %s\n"
3428 "Once you are satisfied with your changes, run\n"
3430 " git rebase --continue\n"),
3431 gpg_sign_opt_quoted(opts));
3432 } else if (exit_code) {
3434 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3435 short_commit_name(commit), subject_len, subject);
3438 * We don't have the hash of the parent so
3439 * just print the line from the todo file.
3441 fprintf_ln(stderr, _("Could not merge %.*s"),
3442 subject_len, subject);
3448 static int error_failed_squash(struct repository *r,
3449 struct commit *commit,
3450 struct replay_opts *opts,
3452 const char *subject)
3454 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3455 return error(_("could not copy '%s' to '%s'"),
3456 rebase_path_squash_msg(), rebase_path_message());
3457 unlink(git_path_merge_msg(r));
3458 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3459 return error(_("could not copy '%s' to '%s'"),
3460 rebase_path_message(),
3461 git_path_merge_msg(r));
3462 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3465 static int do_exec(struct repository *r, const char *command_line)
3467 struct strvec child_env = STRVEC_INIT;
3468 const char *child_argv[] = { NULL, NULL };
3471 fprintf(stderr, _("Executing: %s\n"), command_line);
3472 child_argv[0] = command_line;
3473 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3474 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3475 absolute_path(get_git_work_tree()));
3476 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3479 /* force re-reading of the cache */
3480 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3481 return error(_("could not read index"));
3483 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3486 warning(_("execution failed: %s\n%s"
3487 "You can fix the problem, and then run\n"
3489 " git rebase --continue\n"
3492 dirty ? N_("and made changes to the index and/or the "
3493 "working tree\n") : "");
3495 /* command not found */
3498 warning(_("execution succeeded: %s\nbut "
3499 "left changes to the index and/or the working tree\n"
3500 "Commit or stash your changes, and then run\n"
3502 " git rebase --continue\n"
3503 "\n"), command_line);
3507 strvec_clear(&child_env);
3512 static int safe_append(const char *filename, const char *fmt, ...)
3515 struct lock_file lock = LOCK_INIT;
3516 int fd = hold_lock_file_for_update(&lock, filename,
3517 LOCK_REPORT_ON_ERROR);
3518 struct strbuf buf = STRBUF_INIT;
3523 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3524 error_errno(_("could not read '%s'"), filename);
3525 rollback_lock_file(&lock);
3528 strbuf_complete(&buf, '\n');
3530 strbuf_vaddf(&buf, fmt, ap);
3533 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3534 error_errno(_("could not write to '%s'"), filename);
3535 strbuf_release(&buf);
3536 rollback_lock_file(&lock);
3539 if (commit_lock_file(&lock) < 0) {
3540 strbuf_release(&buf);
3541 rollback_lock_file(&lock);
3542 return error(_("failed to finalize '%s'"), filename);
3545 strbuf_release(&buf);
3549 static int do_label(struct repository *r, const char *name, int len)
3551 struct ref_store *refs = get_main_ref_store(r);
3552 struct ref_transaction *transaction;
3553 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3554 struct strbuf msg = STRBUF_INIT;
3556 struct object_id head_oid;
3558 if (len == 1 && *name == '#')
3559 return error(_("illegal label name: '%.*s'"), len, name);
3561 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3562 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3564 transaction = ref_store_transaction_begin(refs, &err);
3566 error("%s", err.buf);
3568 } else if (get_oid("HEAD", &head_oid)) {
3569 error(_("could not read HEAD"));
3571 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3572 NULL, 0, msg.buf, &err) < 0 ||
3573 ref_transaction_commit(transaction, &err)) {
3574 error("%s", err.buf);
3577 ref_transaction_free(transaction);
3578 strbuf_release(&err);
3579 strbuf_release(&msg);
3582 ret = safe_append(rebase_path_refs_to_delete(),
3583 "%s\n", ref_name.buf);
3584 strbuf_release(&ref_name);
3589 static const char *reflog_message(struct replay_opts *opts,
3590 const char *sub_action, const char *fmt, ...);
3592 static int do_reset(struct repository *r,
3593 const char *name, int len,
3594 struct replay_opts *opts)
3596 struct strbuf ref_name = STRBUF_INIT;
3597 struct object_id oid;
3598 struct lock_file lock = LOCK_INIT;
3599 struct tree_desc desc;
3601 struct unpack_trees_options unpack_tree_opts;
3604 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3607 if (len == 10 && !strncmp("[new root]", name, len)) {
3608 if (!opts->have_squash_onto) {
3610 if (commit_tree("", 0, the_hash_algo->empty_tree,
3611 NULL, &opts->squash_onto,
3613 return error(_("writing fake root commit"));
3614 opts->have_squash_onto = 1;
3615 hex = oid_to_hex(&opts->squash_onto);
3616 if (write_message(hex, strlen(hex),
3617 rebase_path_squash_onto(), 0))
3618 return error(_("writing squash-onto"));
3620 oidcpy(&oid, &opts->squash_onto);
3624 /* Determine the length of the label */
3625 for (i = 0; i < len; i++)
3626 if (isspace(name[i]))
3630 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3631 if (get_oid(ref_name.buf, &oid) &&
3632 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3633 error(_("could not read '%s'"), ref_name.buf);
3634 rollback_lock_file(&lock);
3635 strbuf_release(&ref_name);
3640 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3641 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3642 unpack_tree_opts.head_idx = 1;
3643 unpack_tree_opts.src_index = r->index;
3644 unpack_tree_opts.dst_index = r->index;
3645 unpack_tree_opts.fn = oneway_merge;
3646 unpack_tree_opts.merge = 1;
3647 unpack_tree_opts.update = 1;
3648 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3650 if (repo_read_index_unmerged(r)) {
3651 rollback_lock_file(&lock);
3652 strbuf_release(&ref_name);
3653 return error_resolve_conflict(_(action_name(opts)));
3656 if (!fill_tree_descriptor(r, &desc, &oid)) {
3657 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3658 rollback_lock_file(&lock);
3659 free((void *)desc.buffer);
3660 strbuf_release(&ref_name);
3664 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3665 rollback_lock_file(&lock);
3666 free((void *)desc.buffer);
3667 strbuf_release(&ref_name);
3671 tree = parse_tree_indirect(&oid);
3672 prime_cache_tree(r, r->index, tree);
3674 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3675 ret = error(_("could not write index"));
3676 free((void *)desc.buffer);
3679 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3680 len, name), "HEAD", &oid,
3681 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3683 strbuf_release(&ref_name);
3687 static struct commit *lookup_label(const char *label, int len,
3690 struct commit *commit;
3693 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3694 commit = lookup_commit_reference_by_name(buf->buf);
3696 /* fall back to non-rewritten ref or commit */
3697 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3698 commit = lookup_commit_reference_by_name(buf->buf);
3702 error(_("could not resolve '%s'"), buf->buf);
3707 static int do_merge(struct repository *r,
3708 struct commit *commit,
3709 const char *arg, int arg_len,
3710 int flags, struct replay_opts *opts)
3712 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3713 EDIT_MSG | VERIFY_MSG : 0;
3714 struct strbuf ref_name = STRBUF_INIT;
3715 struct commit *head_commit, *merge_commit, *i;
3716 struct commit_list *bases, *j, *reversed = NULL;
3717 struct commit_list *to_merge = NULL, **tail = &to_merge;
3718 const char *strategy = !opts->xopts_nr &&
3720 !strcmp(opts->strategy, "recursive") ||
3721 !strcmp(opts->strategy, "ort")) ?
3722 NULL : opts->strategy;
3723 struct merge_options o;
3724 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3725 static struct lock_file lock;
3728 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3733 head_commit = lookup_commit_reference_by_name("HEAD");
3735 ret = error(_("cannot merge without a current revision"));
3740 * For octopus merges, the arg starts with the list of revisions to be
3741 * merged. The list is optionally followed by '#' and the oneline.
3743 merge_arg_len = oneline_offset = arg_len;
3744 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3747 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3748 p += 1 + strspn(p + 1, " \t\n");
3749 oneline_offset = p - arg;
3752 k = strcspn(p, " \t\n");
3755 merge_commit = lookup_label(p, k, &ref_name);
3756 if (!merge_commit) {
3757 ret = error(_("unable to parse '%.*s'"), k, p);
3760 tail = &commit_list_insert(merge_commit, tail)->next;
3762 merge_arg_len = p - arg;
3766 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3770 if (opts->have_squash_onto &&
3771 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3773 * When the user tells us to "merge" something into a
3774 * "[new root]", let's simply fast-forward to the merge head.
3776 rollback_lock_file(&lock);
3778 ret = error(_("octopus merge cannot be executed on "
3779 "top of a [new root]"));
3781 ret = fast_forward_to(r, &to_merge->item->object.oid,
3782 &head_commit->object.oid, 0,
3788 const char *encoding = get_commit_output_encoding();
3789 const char *message = logmsg_reencode(commit, NULL, encoding);
3794 ret = error(_("could not get commit message of '%s'"),
3795 oid_to_hex(&commit->object.oid));
3798 write_author_script(message);
3799 find_commit_subject(message, &body);
3801 ret = write_message(body, len, git_path_merge_msg(r), 0);
3802 unuse_commit_buffer(commit, message);
3804 error_errno(_("could not write '%s'"),
3805 git_path_merge_msg(r));
3809 struct strbuf buf = STRBUF_INIT;
3812 strbuf_addf(&buf, "author %s", git_author_info(0));
3813 write_author_script(buf.buf);
3816 if (oneline_offset < arg_len) {
3817 p = arg + oneline_offset;
3818 len = arg_len - oneline_offset;
3820 strbuf_addf(&buf, "Merge %s '%.*s'",
3821 to_merge->next ? "branches" : "branch",
3822 merge_arg_len, arg);
3827 ret = write_message(p, len, git_path_merge_msg(r), 0);
3828 strbuf_release(&buf);
3830 error_errno(_("could not write '%s'"),
3831 git_path_merge_msg(r));
3837 * If HEAD is not identical to the first parent of the original merge
3838 * commit, we cannot fast-forward.
3840 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3841 oideq(&commit->parents->item->object.oid,
3842 &head_commit->object.oid);
3845 * If any merge head is different from the original one, we cannot
3848 if (can_fast_forward) {
3849 struct commit_list *p = commit->parents->next;
3851 for (j = to_merge; j && p; j = j->next, p = p->next)
3852 if (!oideq(&j->item->object.oid,
3853 &p->item->object.oid)) {
3854 can_fast_forward = 0;
3858 * If the number of merge heads differs from the original merge
3859 * commit, we cannot fast-forward.
3862 can_fast_forward = 0;
3865 if (can_fast_forward) {
3866 rollback_lock_file(&lock);
3867 ret = fast_forward_to(r, &commit->object.oid,
3868 &head_commit->object.oid, 0, opts);
3869 if (flags & TODO_EDIT_MERGE_MSG) {
3870 run_commit_flags |= AMEND_MSG;
3871 goto fast_forward_edit;
3876 if (strategy || to_merge->next) {
3878 struct child_process cmd = CHILD_PROCESS_INIT;
3880 if (read_env_script(&cmd.env_array)) {
3881 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3883 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3887 if (opts->committer_date_is_author_date)
3888 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3891 author_date_from_env_array(&cmd.env_array));
3892 if (opts->ignore_date)
3893 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3896 strvec_push(&cmd.args, "merge");
3897 strvec_push(&cmd.args, "-s");
3899 strvec_push(&cmd.args, "octopus");
3901 strvec_push(&cmd.args, strategy);
3902 for (k = 0; k < opts->xopts_nr; k++)
3903 strvec_pushf(&cmd.args,
3904 "-X%s", opts->xopts[k]);
3906 strvec_push(&cmd.args, "--no-edit");
3907 strvec_push(&cmd.args, "--no-ff");
3908 strvec_push(&cmd.args, "--no-log");
3909 strvec_push(&cmd.args, "--no-stat");
3910 strvec_push(&cmd.args, "-F");
3911 strvec_push(&cmd.args, git_path_merge_msg(r));
3913 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3915 strvec_push(&cmd.args, "--no-gpg-sign");
3917 /* Add the tips to be merged */
3918 for (j = to_merge; j; j = j->next)
3919 strvec_push(&cmd.args,
3920 oid_to_hex(&j->item->object.oid));
3922 strbuf_release(&ref_name);
3923 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3925 rollback_lock_file(&lock);
3927 ret = run_command(&cmd);
3929 /* force re-reading of the cache */
3930 if (!ret && (discard_index(r->index) < 0 ||
3931 repo_read_index(r) < 0))
3932 ret = error(_("could not read index"));
3936 merge_commit = to_merge->item;
3937 bases = get_merge_bases(head_commit, merge_commit);
3938 if (bases && oideq(&merge_commit->object.oid,
3939 &bases->item->object.oid)) {
3941 /* skip merging an ancestor of HEAD */
3945 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3946 git_path_merge_head(r), 0);
3947 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3949 for (j = bases; j; j = j->next)
3950 commit_list_insert(j->item, &reversed);
3951 free_commit_list(bases);
3954 init_merge_options(&o, r);
3956 o.branch2 = ref_name.buf;
3957 o.buffer_output = 2;
3959 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3961 * TODO: Should use merge_incore_recursive() and
3962 * merge_switch_to_result(), skipping the call to
3963 * merge_switch_to_result() when we don't actually need to
3964 * update the index and working copy immediately.
3966 ret = merge_ort_recursive(&o,
3967 head_commit, merge_commit, reversed,
3970 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3974 fputs(o.obuf.buf, stdout);
3975 strbuf_release(&o.obuf);
3977 error(_("could not even attempt to merge '%.*s'"),
3978 merge_arg_len, arg);
3982 * The return value of merge_recursive() is 1 on clean, and 0 on
3985 * Let's reverse that, so that do_merge() returns 0 upon success and
3986 * 1 upon failed merge (keeping the return value -1 for the cases where
3987 * we will want to reschedule the `merge` command).
3991 if (r->index->cache_changed &&
3992 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3993 ret = error(_("merge: Unable to write new index file"));
3997 rollback_lock_file(&lock);
3999 repo_rerere(r, opts->allow_rerere_auto);
4002 * In case of problems, we now want to return a positive
4003 * value (a negative one would indicate that the `merge`
4004 * command needs to be rescheduled).
4007 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4011 strbuf_release(&ref_name);
4012 rollback_lock_file(&lock);
4013 free_commit_list(to_merge);
4017 static int is_final_fixup(struct todo_list *todo_list)
4019 int i = todo_list->current;
4021 if (!is_fixup(todo_list->items[i].command))
4024 while (++i < todo_list->nr)
4025 if (is_fixup(todo_list->items[i].command))
4027 else if (!is_noop(todo_list->items[i].command))
4032 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4036 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4037 if (!is_noop(todo_list->items[i].command))
4038 return todo_list->items[i].command;
4043 void create_autostash(struct repository *r, const char *path,
4044 const char *default_reflog_action)
4046 struct strbuf buf = STRBUF_INIT;
4047 struct lock_file lock_file = LOCK_INIT;
4050 fd = repo_hold_locked_index(r, &lock_file, 0);
4051 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4053 repo_update_index_if_able(r, &lock_file);
4054 rollback_lock_file(&lock_file);
4056 if (has_unstaged_changes(r, 1) ||
4057 has_uncommitted_changes(r, 1)) {
4058 struct child_process stash = CHILD_PROCESS_INIT;
4059 struct object_id oid;
4061 strvec_pushl(&stash.args,
4062 "stash", "create", "autostash", NULL);
4066 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4067 die(_("Cannot autostash"));
4068 strbuf_trim_trailing_newline(&buf);
4069 if (get_oid(buf.buf, &oid))
4070 die(_("Unexpected stash response: '%s'"),
4073 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4075 if (safe_create_leading_directories_const(path))
4076 die(_("Could not create directory for '%s'"),
4078 write_file(path, "%s", oid_to_hex(&oid));
4079 printf(_("Created autostash: %s\n"), buf.buf);
4080 if (reset_head(r, NULL, "reset --hard",
4081 NULL, RESET_HEAD_HARD, NULL, NULL,
4082 default_reflog_action) < 0)
4083 die(_("could not reset --hard"));
4085 if (discard_index(r->index) < 0 ||
4086 repo_read_index(r) < 0)
4087 die(_("could not read index"));
4089 strbuf_release(&buf);
4092 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4094 struct child_process child = CHILD_PROCESS_INIT;
4097 if (attempt_apply) {
4099 child.no_stdout = 1;
4100 child.no_stderr = 1;
4101 strvec_push(&child.args, "stash");
4102 strvec_push(&child.args, "apply");
4103 strvec_push(&child.args, stash_oid);
4104 ret = run_command(&child);
4107 if (attempt_apply && !ret)
4108 fprintf(stderr, _("Applied autostash.\n"));
4110 struct child_process store = CHILD_PROCESS_INIT;
4113 strvec_push(&store.args, "stash");
4114 strvec_push(&store.args, "store");
4115 strvec_push(&store.args, "-m");
4116 strvec_push(&store.args, "autostash");
4117 strvec_push(&store.args, "-q");
4118 strvec_push(&store.args, stash_oid);
4119 if (run_command(&store))
4120 ret = error(_("cannot store %s"), stash_oid);
4124 "Your changes are safe in the stash.\n"
4125 "You can run \"git stash pop\" or"
4126 " \"git stash drop\" at any time.\n"),
4128 _("Applying autostash resulted in conflicts.") :
4129 _("Autostash exists; creating a new stash entry."));
4135 static int apply_save_autostash(const char *path, int attempt_apply)
4137 struct strbuf stash_oid = STRBUF_INIT;
4140 if (!read_oneliner(&stash_oid, path,
4141 READ_ONELINER_SKIP_IF_EMPTY)) {
4142 strbuf_release(&stash_oid);
4145 strbuf_trim(&stash_oid);
4147 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4150 strbuf_release(&stash_oid);
4154 int save_autostash(const char *path)
4156 return apply_save_autostash(path, 0);
4159 int apply_autostash(const char *path)
4161 return apply_save_autostash(path, 1);
4164 int apply_autostash_oid(const char *stash_oid)
4166 return apply_save_autostash_oid(stash_oid, 1);
4169 static const char *reflog_message(struct replay_opts *opts,
4170 const char *sub_action, const char *fmt, ...)
4173 static struct strbuf buf = STRBUF_INIT;
4174 char *reflog_action = getenv(GIT_REFLOG_ACTION);
4178 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
4180 strbuf_addf(&buf, " (%s)", sub_action);
4182 strbuf_addstr(&buf, ": ");
4183 strbuf_vaddf(&buf, fmt, ap);
4190 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4191 const char *commit, const char *action)
4193 struct child_process cmd = CHILD_PROCESS_INIT;
4198 strvec_push(&cmd.args, "checkout");
4199 strvec_push(&cmd.args, commit);
4200 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4203 ret = run_command(&cmd);
4205 ret = run_command_silent_on_success(&cmd);
4208 discard_index(r->index);
4213 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4214 const char *onto_name, const struct object_id *onto,
4215 const struct object_id *orig_head)
4217 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4219 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4220 apply_autostash(rebase_path_autostash());
4221 sequencer_remove_state(opts);
4222 return error(_("could not detach HEAD"));
4225 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4228 static int stopped_at_head(struct repository *r)
4230 struct object_id head;
4231 struct commit *commit;
4232 struct commit_message message;
4234 if (get_oid("HEAD", &head) ||
4235 !(commit = lookup_commit(r, &head)) ||
4236 parse_commit(commit) || get_message(commit, &message))
4237 fprintf(stderr, _("Stopped at HEAD\n"));
4239 fprintf(stderr, _("Stopped at %s\n"), message.label);
4240 free_message(commit, &message);
4246 static const char rescheduled_advice[] =
4247 N_("Could not execute the todo command\n"
4251 "It has been rescheduled; To edit the command before continuing, please\n"
4252 "edit the todo list first:\n"
4254 " git rebase --edit-todo\n"
4255 " git rebase --continue\n");
4257 static int pick_commits(struct repository *r,
4258 struct todo_list *todo_list,
4259 struct replay_opts *opts)
4261 int res = 0, reschedule = 0;
4262 char *prev_reflog_action;
4264 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4265 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4266 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4268 assert(!(opts->signoff || opts->no_commit ||
4269 opts->record_origin || opts->edit ||
4270 opts->committer_date_is_author_date ||
4271 opts->ignore_date));
4272 if (read_and_refresh_cache(r, opts))
4275 while (todo_list->current < todo_list->nr) {
4276 struct todo_item *item = todo_list->items + todo_list->current;
4277 const char *arg = todo_item_get_arg(todo_list, item);
4280 if (save_todo(todo_list, opts))
4282 if (is_rebase_i(opts)) {
4283 if (item->command != TODO_COMMENT) {
4284 FILE *f = fopen(rebase_path_msgnum(), "w");
4286 todo_list->done_nr++;
4289 fprintf(f, "%d\n", todo_list->done_nr);
4293 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4295 todo_list->total_nr,
4296 opts->verbose ? "\n" : "\r");
4298 unlink(rebase_path_message());
4299 unlink(rebase_path_author_script());
4300 unlink(rebase_path_stopped_sha());
4301 unlink(rebase_path_amend());
4302 unlink(git_path_merge_head(r));
4303 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4305 if (item->command == TODO_BREAK) {
4308 return stopped_at_head(r);
4311 if (item->command <= TODO_SQUASH) {
4312 if (is_rebase_i(opts))
4313 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4314 command_to_string(item->command), NULL),
4316 res = do_pick_commit(r, item, opts,
4317 is_final_fixup(todo_list),
4319 if (is_rebase_i(opts))
4320 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4321 if (is_rebase_i(opts) && res < 0) {
4323 advise(_(rescheduled_advice),
4324 get_item_line_length(todo_list,
4325 todo_list->current),
4326 get_item_line(todo_list,
4327 todo_list->current));
4328 todo_list->current--;
4329 if (save_todo(todo_list, opts))
4332 if (item->command == TODO_EDIT) {
4333 struct commit *commit = item->commit;
4338 _("Stopped at %s... %.*s\n"),
4339 short_commit_name(commit),
4340 item->arg_len, arg);
4342 return error_with_patch(r, commit,
4343 arg, item->arg_len, opts, res, !res);
4345 if (is_rebase_i(opts) && !res)
4346 record_in_rewritten(&item->commit->object.oid,
4347 peek_command(todo_list, 1));
4348 if (res && is_fixup(item->command)) {
4351 return error_failed_squash(r, item->commit, opts,
4352 item->arg_len, arg);
4353 } else if (res && is_rebase_i(opts) && item->commit) {
4355 struct object_id oid;
4358 * If we are rewording and have either
4359 * fast-forwarded already, or are about to
4360 * create a new root commit, we want to amend,
4361 * otherwise we do not.
4363 if (item->command == TODO_REWORD &&
4364 !get_oid("HEAD", &oid) &&
4365 (oideq(&item->commit->object.oid, &oid) ||
4366 (opts->have_squash_onto &&
4367 oideq(&opts->squash_onto, &oid))))
4370 return res | error_with_patch(r, item->commit,
4371 arg, item->arg_len, opts,
4374 } else if (item->command == TODO_EXEC) {
4375 char *end_of_arg = (char *)(arg + item->arg_len);
4376 int saved = *end_of_arg;
4381 res = do_exec(r, arg);
4382 *end_of_arg = saved;
4385 if (opts->reschedule_failed_exec)
4389 } else if (item->command == TODO_LABEL) {
4390 if ((res = do_label(r, arg, item->arg_len)))
4392 } else if (item->command == TODO_RESET) {
4393 if ((res = do_reset(r, arg, item->arg_len, opts)))
4395 } else if (item->command == TODO_MERGE) {
4396 if ((res = do_merge(r, item->commit,
4398 item->flags, opts)) < 0)
4400 else if (item->commit)
4401 record_in_rewritten(&item->commit->object.oid,
4402 peek_command(todo_list, 1));
4404 /* failed with merge conflicts */
4405 return error_with_patch(r, item->commit,
4408 } else if (!is_noop(item->command))
4409 return error(_("unknown command %d"), item->command);
4412 advise(_(rescheduled_advice),
4413 get_item_line_length(todo_list,
4414 todo_list->current),
4415 get_item_line(todo_list, todo_list->current));
4416 todo_list->current--;
4417 if (save_todo(todo_list, opts))
4420 return error_with_patch(r,
4424 } else if (is_rebase_i(opts) && check_todo && !res) {
4427 if (stat(get_todo_path(opts), &st)) {
4428 res = error_errno(_("could not stat '%s'"),
4429 get_todo_path(opts));
4430 } else if (match_stat_data(&todo_list->stat, &st)) {
4431 /* Reread the todo file if it has changed. */
4432 todo_list_release(todo_list);
4433 if (read_populate_todo(r, todo_list, opts))
4434 res = -1; /* message was printed */
4435 /* `current` will be incremented below */
4436 todo_list->current = -1;
4440 todo_list->current++;
4445 if (is_rebase_i(opts)) {
4446 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4449 /* Stopped in the middle, as planned? */
4450 if (todo_list->current < todo_list->nr)
4453 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4454 starts_with(head_ref.buf, "refs/")) {
4456 struct object_id head, orig;
4459 if (get_oid("HEAD", &head)) {
4460 res = error(_("cannot read HEAD"));
4462 strbuf_release(&head_ref);
4463 strbuf_release(&buf);
4466 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4467 get_oid_hex(buf.buf, &orig)) {
4468 res = error(_("could not read orig-head"));
4469 goto cleanup_head_ref;
4472 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4473 res = error(_("could not read 'onto'"));
4474 goto cleanup_head_ref;
4476 msg = reflog_message(opts, "finish", "%s onto %s",
4477 head_ref.buf, buf.buf);
4478 if (update_ref(msg, head_ref.buf, &head, &orig,
4479 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4480 res = error(_("could not update %s"),
4482 goto cleanup_head_ref;
4484 msg = reflog_message(opts, "finish", "returning to %s",
4486 if (create_symref("HEAD", head_ref.buf, msg)) {
4487 res = error(_("could not update HEAD to %s"),
4489 goto cleanup_head_ref;
4494 if (opts->verbose) {
4495 struct rev_info log_tree_opt;
4496 struct object_id orig, head;
4498 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4499 repo_init_revisions(r, &log_tree_opt, NULL);
4500 log_tree_opt.diff = 1;
4501 log_tree_opt.diffopt.output_format =
4502 DIFF_FORMAT_DIFFSTAT;
4503 log_tree_opt.disable_stdin = 1;
4505 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4506 !get_oid(buf.buf, &orig) &&
4507 !get_oid("HEAD", &head)) {
4508 diff_tree_oid(&orig, &head, "",
4509 &log_tree_opt.diffopt);
4510 log_tree_diff_flush(&log_tree_opt);
4513 flush_rewritten_pending();
4514 if (!stat(rebase_path_rewritten_list(), &st) &&
4516 struct child_process child = CHILD_PROCESS_INIT;
4517 const char *post_rewrite_hook =
4518 find_hook("post-rewrite");
4520 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4522 strvec_push(&child.args, "notes");
4523 strvec_push(&child.args, "copy");
4524 strvec_push(&child.args, "--for-rewrite=rebase");
4525 /* we don't care if this copying failed */
4526 run_command(&child);
4528 if (post_rewrite_hook) {
4529 struct child_process hook = CHILD_PROCESS_INIT;
4531 hook.in = open(rebase_path_rewritten_list(),
4533 hook.stdout_to_stderr = 1;
4534 hook.trace2_hook_name = "post-rewrite";
4535 strvec_push(&hook.args, post_rewrite_hook);
4536 strvec_push(&hook.args, "rebase");
4537 /* we don't care if this hook failed */
4541 apply_autostash(rebase_path_autostash());
4547 _("Successfully rebased and updated %s.\n"),
4551 strbuf_release(&buf);
4552 strbuf_release(&head_ref);
4556 * Sequence of picks finished successfully; cleanup by
4557 * removing the .git/sequencer directory
4559 return sequencer_remove_state(opts);
4562 static int continue_single_pick(struct repository *r)
4564 const char *argv[] = { "commit", NULL };
4566 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4567 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4568 return error(_("no cherry-pick or revert in progress"));
4569 return run_command_v_opt(argv, RUN_GIT_CMD);
4572 static int commit_staged_changes(struct repository *r,
4573 struct replay_opts *opts,
4574 struct todo_list *todo_list)
4576 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4577 unsigned int final_fixup = 0, is_clean;
4579 if (has_unstaged_changes(r, 1))
4580 return error(_("cannot rebase: You have unstaged changes."));
4582 is_clean = !has_uncommitted_changes(r, 0);
4584 if (file_exists(rebase_path_amend())) {
4585 struct strbuf rev = STRBUF_INIT;
4586 struct object_id head, to_amend;
4588 if (get_oid("HEAD", &head))
4589 return error(_("cannot amend non-existing commit"));
4590 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4591 return error(_("invalid file: '%s'"), rebase_path_amend());
4592 if (get_oid_hex(rev.buf, &to_amend))
4593 return error(_("invalid contents: '%s'"),
4594 rebase_path_amend());
4595 if (!is_clean && !oideq(&head, &to_amend))
4596 return error(_("\nYou have uncommitted changes in your "
4597 "working tree. Please, commit them\n"
4598 "first and then run 'git rebase "
4599 "--continue' again."));
4601 * When skipping a failed fixup/squash, we need to edit the
4602 * commit message, the current fixup list and count, and if it
4603 * was the last fixup/squash in the chain, we need to clean up
4604 * the commit message and if there was a squash, let the user
4607 if (!is_clean || !opts->current_fixup_count)
4608 ; /* this is not the final fixup */
4609 else if (!oideq(&head, &to_amend) ||
4610 !file_exists(rebase_path_stopped_sha())) {
4611 /* was a final fixup or squash done manually? */
4612 if (!is_fixup(peek_command(todo_list, 0))) {
4613 unlink(rebase_path_fixup_msg());
4614 unlink(rebase_path_squash_msg());
4615 unlink(rebase_path_current_fixups());
4616 strbuf_reset(&opts->current_fixups);
4617 opts->current_fixup_count = 0;
4620 /* we are in a fixup/squash chain */
4621 const char *p = opts->current_fixups.buf;
4622 int len = opts->current_fixups.len;
4624 opts->current_fixup_count--;
4626 BUG("Incorrect current_fixups:\n%s", p);
4627 while (len && p[len - 1] != '\n')
4629 strbuf_setlen(&opts->current_fixups, len);
4630 if (write_message(p, len, rebase_path_current_fixups(),
4632 return error(_("could not write file: '%s'"),
4633 rebase_path_current_fixups());
4636 * If a fixup/squash in a fixup/squash chain failed, the
4637 * commit message is already correct, no need to commit
4640 * Only if it is the final command in the fixup/squash
4641 * chain, and only if the chain is longer than a single
4642 * fixup/squash command (which was just skipped), do we
4643 * actually need to re-commit with a cleaned up commit
4646 if (opts->current_fixup_count > 0 &&
4647 !is_fixup(peek_command(todo_list, 0))) {
4650 * If there was not a single "squash" in the
4651 * chain, we only need to clean up the commit
4652 * message, no need to bother the user with
4653 * opening the commit message in the editor.
4655 if (!starts_with(p, "squash ") &&
4656 !strstr(p, "\nsquash "))
4657 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4658 } else if (is_fixup(peek_command(todo_list, 0))) {
4660 * We need to update the squash message to skip
4661 * the latest commit message.
4663 struct commit *commit;
4664 const char *path = rebase_path_squash_msg();
4665 const char *encoding = get_commit_output_encoding();
4667 if (parse_head(r, &commit) ||
4668 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4669 write_message(p, strlen(p), path, 0)) {
4670 unuse_commit_buffer(commit, p);
4671 return error(_("could not write file: "
4674 unuse_commit_buffer(commit, p);
4678 strbuf_release(&rev);
4683 if (refs_ref_exists(get_main_ref_store(r),
4684 "CHERRY_PICK_HEAD") &&
4685 refs_delete_ref(get_main_ref_store(r), "",
4686 "CHERRY_PICK_HEAD", NULL, 0))
4687 return error(_("could not remove CHERRY_PICK_HEAD"));
4692 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4694 return error(_("could not commit staged changes."));
4695 unlink(rebase_path_amend());
4696 unlink(git_path_merge_head(r));
4698 unlink(rebase_path_fixup_msg());
4699 unlink(rebase_path_squash_msg());
4701 if (opts->current_fixup_count > 0) {
4703 * Whether final fixup or not, we just cleaned up the commit
4706 unlink(rebase_path_current_fixups());
4707 strbuf_reset(&opts->current_fixups);
4708 opts->current_fixup_count = 0;
4713 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4715 struct todo_list todo_list = TODO_LIST_INIT;
4718 if (read_and_refresh_cache(r, opts))
4721 if (read_populate_opts(opts))
4723 if (is_rebase_i(opts)) {
4724 if ((res = read_populate_todo(r, &todo_list, opts)))
4725 goto release_todo_list;
4727 if (file_exists(rebase_path_dropped())) {
4728 if ((res = todo_list_check_against_backup(r, &todo_list)))
4729 goto release_todo_list;
4731 unlink(rebase_path_dropped());
4734 if (commit_staged_changes(r, opts, &todo_list)) {
4736 goto release_todo_list;
4738 } else if (!file_exists(get_todo_path(opts)))
4739 return continue_single_pick(r);
4740 else if ((res = read_populate_todo(r, &todo_list, opts)))
4741 goto release_todo_list;
4743 if (!is_rebase_i(opts)) {
4744 /* Verify that the conflict has been resolved */
4745 if (refs_ref_exists(get_main_ref_store(r),
4746 "CHERRY_PICK_HEAD") ||
4747 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4748 res = continue_single_pick(r);
4750 goto release_todo_list;
4752 if (index_differs_from(r, "HEAD", NULL, 0)) {
4753 res = error_dirty_index(r, opts);
4754 goto release_todo_list;
4756 todo_list.current++;
4757 } else if (file_exists(rebase_path_stopped_sha())) {
4758 struct strbuf buf = STRBUF_INIT;
4759 struct object_id oid;
4761 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4762 READ_ONELINER_SKIP_IF_EMPTY) &&
4763 !get_oid_hex(buf.buf, &oid))
4764 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4765 strbuf_release(&buf);
4768 res = pick_commits(r, &todo_list, opts);
4770 todo_list_release(&todo_list);
4774 static int single_pick(struct repository *r,
4775 struct commit *cmit,
4776 struct replay_opts *opts)
4779 struct todo_item item;
4781 item.command = opts->action == REPLAY_PICK ?
4782 TODO_PICK : TODO_REVERT;
4785 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4786 return do_pick_commit(r, &item, opts, 0, &check_todo);
4789 int sequencer_pick_revisions(struct repository *r,
4790 struct replay_opts *opts)
4792 struct todo_list todo_list = TODO_LIST_INIT;
4793 struct object_id oid;
4797 if (read_and_refresh_cache(r, opts))
4800 for (i = 0; i < opts->revs->pending.nr; i++) {
4801 struct object_id oid;
4802 const char *name = opts->revs->pending.objects[i].name;
4804 /* This happens when using --stdin. */
4808 if (!get_oid(name, &oid)) {
4809 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4810 enum object_type type = oid_object_info(r,
4813 return error(_("%s: can't cherry-pick a %s"),
4814 name, type_name(type));
4817 return error(_("%s: bad revision"), name);
4821 * If we were called as "git cherry-pick <commit>", just
4822 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4823 * REVERT_HEAD, and don't touch the sequencer state.
4824 * This means it is possible to cherry-pick in the middle
4825 * of a cherry-pick sequence.
4827 if (opts->revs->cmdline.nr == 1 &&
4828 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4829 opts->revs->no_walk &&
4830 !opts->revs->cmdline.rev->flags) {
4831 struct commit *cmit;
4832 if (prepare_revision_walk(opts->revs))
4833 return error(_("revision walk setup failed"));
4834 cmit = get_revision(opts->revs);
4836 return error(_("empty commit set passed"));
4837 if (get_revision(opts->revs))
4838 BUG("unexpected extra commit from walk");
4839 return single_pick(r, cmit, opts);
4843 * Start a new cherry-pick/ revert sequence; but
4844 * first, make sure that an existing one isn't in
4848 if (walk_revs_populate_todo(&todo_list, opts) ||
4849 create_seq_dir(r) < 0)
4851 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4852 return error(_("can't revert as initial commit"));
4853 if (save_head(oid_to_hex(&oid)))
4855 if (save_opts(opts))
4857 update_abort_safety_file();
4858 res = pick_commits(r, &todo_list, opts);
4859 todo_list_release(&todo_list);
4863 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4865 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4866 struct strbuf sob = STRBUF_INIT;
4869 strbuf_addstr(&sob, sign_off_header);
4870 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4871 strbuf_addch(&sob, '\n');
4874 strbuf_complete_line(msgbuf);
4877 * If the whole message buffer is equal to the sob, pretend that we
4878 * found a conforming footer with a matching sob
4880 if (msgbuf->len - ignore_footer == sob.len &&
4881 !strncmp(msgbuf->buf, sob.buf, sob.len))
4884 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4887 const char *append_newlines = NULL;
4888 size_t len = msgbuf->len - ignore_footer;
4892 * The buffer is completely empty. Leave foom for
4893 * the title and body to be filled in by the user.
4895 append_newlines = "\n\n";
4896 } else if (len == 1) {
4898 * Buffer contains a single newline. Add another
4899 * so that we leave room for the title and body.
4901 append_newlines = "\n";
4902 } else if (msgbuf->buf[len - 2] != '\n') {
4904 * Buffer ends with a single newline. Add another
4905 * so that there is an empty line between the message
4908 append_newlines = "\n";
4909 } /* else, the buffer already ends with two newlines. */
4911 if (append_newlines)
4912 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4913 append_newlines, strlen(append_newlines));
4916 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4917 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4920 strbuf_release(&sob);
4923 struct labels_entry {
4924 struct hashmap_entry entry;
4925 char label[FLEX_ARRAY];
4928 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4929 const struct hashmap_entry *entry_or_key, const void *key)
4931 const struct labels_entry *a, *b;
4933 a = container_of(eptr, const struct labels_entry, entry);
4934 b = container_of(entry_or_key, const struct labels_entry, entry);
4936 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4939 struct string_entry {
4940 struct oidmap_entry entry;
4941 char string[FLEX_ARRAY];
4944 struct label_state {
4945 struct oidmap commit2label;
4946 struct hashmap labels;
4950 static const char *label_oid(struct object_id *oid, const char *label,
4951 struct label_state *state)
4953 struct labels_entry *labels_entry;
4954 struct string_entry *string_entry;
4955 struct object_id dummy;
4958 string_entry = oidmap_get(&state->commit2label, oid);
4960 return string_entry->string;
4963 * For "uninteresting" commits, i.e. commits that are not to be
4964 * rebased, and which can therefore not be labeled, we use a unique
4965 * abbreviation of the commit name. This is slightly more complicated
4966 * than calling find_unique_abbrev() because we also need to make
4967 * sure that the abbreviation does not conflict with any other
4970 * We disallow "interesting" commits to be labeled by a string that
4971 * is a valid full-length hash, to ensure that we always can find an
4972 * abbreviation for any uninteresting commit's names that does not
4973 * clash with any other label.
4975 strbuf_reset(&state->buf);
4979 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4980 label = p = state->buf.buf;
4982 find_unique_abbrev_r(p, oid, default_abbrev);
4985 * We may need to extend the abbreviated hash so that there is
4986 * no conflicting label.
4988 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4989 size_t i = strlen(p) + 1;
4991 oid_to_hex_r(p, oid);
4992 for (; i < the_hash_algo->hexsz; i++) {
4995 if (!hashmap_get_from_hash(&state->labels,
5002 struct strbuf *buf = &state->buf;
5005 * Sanitize labels by replacing non-alpha-numeric characters
5006 * (including white-space ones) by dashes, as they might be
5007 * illegal in file names (and hence in ref names).
5009 * Note that we retain non-ASCII UTF-8 characters (identified
5010 * via the most significant bit). They should be all acceptable
5011 * in file names. We do not validate the UTF-8 here, that's not
5012 * the job of this function.
5014 for (; *label; label++)
5015 if ((*label & 0x80) || isalnum(*label))
5016 strbuf_addch(buf, *label);
5017 /* avoid leading dash and double-dashes */
5018 else if (buf->len && buf->buf[buf->len - 1] != '-')
5019 strbuf_addch(buf, '-');
5021 strbuf_addstr(buf, "rev-");
5022 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5026 if ((buf->len == the_hash_algo->hexsz &&
5027 !get_oid_hex(label, &dummy)) ||
5028 (buf->len == 1 && *label == '#') ||
5029 hashmap_get_from_hash(&state->labels,
5030 strihash(label), label)) {
5032 * If the label already exists, or if the label is a
5033 * valid full OID, or the label is a '#' (which we use
5034 * as a separator between merge heads and oneline), we
5035 * append a dash and a number to make it unique.
5037 size_t len = buf->len;
5039 for (i = 2; ; i++) {
5040 strbuf_setlen(buf, len);
5041 strbuf_addf(buf, "-%d", i);
5042 if (!hashmap_get_from_hash(&state->labels,
5052 FLEX_ALLOC_STR(labels_entry, label, label);
5053 hashmap_entry_init(&labels_entry->entry, strihash(label));
5054 hashmap_add(&state->labels, &labels_entry->entry);
5056 FLEX_ALLOC_STR(string_entry, string, label);
5057 oidcpy(&string_entry->entry.oid, oid);
5058 oidmap_put(&state->commit2label, string_entry);
5060 return string_entry->string;
5063 static int make_script_with_merges(struct pretty_print_context *pp,
5064 struct rev_info *revs, struct strbuf *out,
5067 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5068 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5069 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5070 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5071 struct strbuf label = STRBUF_INIT;
5072 struct commit_list *commits = NULL, **tail = &commits, *iter;
5073 struct commit_list *tips = NULL, **tips_tail = &tips;
5074 struct commit *commit;
5075 struct oidmap commit2todo = OIDMAP_INIT;
5076 struct string_entry *entry;
5077 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5078 shown = OIDSET_INIT;
5079 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5081 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5082 const char *cmd_pick = abbr ? "p" : "pick",
5083 *cmd_label = abbr ? "l" : "label",
5084 *cmd_reset = abbr ? "t" : "reset",
5085 *cmd_merge = abbr ? "m" : "merge";
5087 oidmap_init(&commit2todo, 0);
5088 oidmap_init(&state.commit2label, 0);
5089 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5090 strbuf_init(&state.buf, 32);
5092 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5093 struct labels_entry *onto_label_entry;
5094 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5095 FLEX_ALLOC_STR(entry, string, "onto");
5096 oidcpy(&entry->entry.oid, oid);
5097 oidmap_put(&state.commit2label, entry);
5099 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5100 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5101 hashmap_add(&state.labels, &onto_label_entry->entry);
5106 * - get onelines for all commits
5107 * - gather all branch tips (i.e. 2nd or later parents of merges)
5108 * - label all branch tips
5110 while ((commit = get_revision(revs))) {
5111 struct commit_list *to_merge;
5112 const char *p1, *p2;
5113 struct object_id *oid;
5116 tail = &commit_list_insert(commit, tail)->next;
5117 oidset_insert(&interesting, &commit->object.oid);
5119 is_empty = is_original_commit_empty(commit);
5120 if (!is_empty && (commit->object.flags & PATCHSAME))
5122 if (is_empty && !keep_empty)
5125 strbuf_reset(&oneline);
5126 pretty_print_commit(pp, commit, &oneline);
5128 to_merge = commit->parents ? commit->parents->next : NULL;
5130 /* non-merge commit: easy case */
5132 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5133 oid_to_hex(&commit->object.oid),
5136 strbuf_addf(&buf, " %c empty",
5139 FLEX_ALLOC_STR(entry, string, buf.buf);
5140 oidcpy(&entry->entry.oid, &commit->object.oid);
5141 oidmap_put(&commit2todo, entry);
5146 /* Create a label */
5147 strbuf_reset(&label);
5148 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5149 (p1 = strchr(p1, '\'')) &&
5150 (p2 = strchr(++p1, '\'')))
5151 strbuf_add(&label, p1, p2 - p1);
5152 else if (skip_prefix(oneline.buf, "Merge pull request ",
5154 (p1 = strstr(p1, " from ")))
5155 strbuf_addstr(&label, p1 + strlen(" from "));
5157 strbuf_addbuf(&label, &oneline);
5160 strbuf_addf(&buf, "%s -C %s",
5161 cmd_merge, oid_to_hex(&commit->object.oid));
5163 /* label the tips of merged branches */
5164 for (; to_merge; to_merge = to_merge->next) {
5165 oid = &to_merge->item->object.oid;
5166 strbuf_addch(&buf, ' ');
5168 if (!oidset_contains(&interesting, oid)) {
5169 strbuf_addstr(&buf, label_oid(oid, NULL,
5174 tips_tail = &commit_list_insert(to_merge->item,
5177 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5179 strbuf_addf(&buf, " # %s", oneline.buf);
5181 FLEX_ALLOC_STR(entry, string, buf.buf);
5182 oidcpy(&entry->entry.oid, &commit->object.oid);
5183 oidmap_put(&commit2todo, entry);
5188 * - label branch points
5189 * - add HEAD to the branch tips
5191 for (iter = commits; iter; iter = iter->next) {
5192 struct commit_list *parent = iter->item->parents;
5193 for (; parent; parent = parent->next) {
5194 struct object_id *oid = &parent->item->object.oid;
5195 if (!oidset_contains(&interesting, oid))
5197 if (oidset_insert(&child_seen, oid))
5198 label_oid(oid, "branch-point", &state);
5201 /* Add HEAD as implicit "tip of branch" */
5203 tips_tail = &commit_list_insert(iter->item,
5208 * Third phase: output the todo list. This is a bit tricky, as we
5209 * want to avoid jumping back and forth between revisions. To
5210 * accomplish that goal, we walk backwards from the branch tips,
5211 * gathering commits not yet shown, reversing the list on the fly,
5212 * then outputting that list (labeling revisions as needed).
5214 strbuf_addf(out, "%s onto\n", cmd_label);
5215 for (iter = tips; iter; iter = iter->next) {
5216 struct commit_list *list = NULL, *iter2;
5218 commit = iter->item;
5219 if (oidset_contains(&shown, &commit->object.oid))
5221 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5224 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5226 strbuf_addch(out, '\n');
5228 while (oidset_contains(&interesting, &commit->object.oid) &&
5229 !oidset_contains(&shown, &commit->object.oid)) {
5230 commit_list_insert(commit, &list);
5231 if (!commit->parents) {
5235 commit = commit->parents->item;
5239 strbuf_addf(out, "%s %s\n", cmd_reset,
5240 rebase_cousins || root_with_onto ?
5241 "onto" : "[new root]");
5243 const char *to = NULL;
5245 entry = oidmap_get(&state.commit2label,
5246 &commit->object.oid);
5249 else if (!rebase_cousins)
5250 to = label_oid(&commit->object.oid, NULL,
5253 if (!to || !strcmp(to, "onto"))
5254 strbuf_addf(out, "%s onto\n", cmd_reset);
5256 strbuf_reset(&oneline);
5257 pretty_print_commit(pp, commit, &oneline);
5258 strbuf_addf(out, "%s %s # %s\n",
5259 cmd_reset, to, oneline.buf);
5263 for (iter2 = list; iter2; iter2 = iter2->next) {
5264 struct object_id *oid = &iter2->item->object.oid;
5265 entry = oidmap_get(&commit2todo, oid);
5266 /* only show if not already upstream */
5268 strbuf_addf(out, "%s\n", entry->string);
5269 entry = oidmap_get(&state.commit2label, oid);
5271 strbuf_addf(out, "%s %s\n",
5272 cmd_label, entry->string);
5273 oidset_insert(&shown, oid);
5276 free_commit_list(list);
5279 free_commit_list(commits);
5280 free_commit_list(tips);
5282 strbuf_release(&label);
5283 strbuf_release(&oneline);
5284 strbuf_release(&buf);
5286 oidmap_free(&commit2todo, 1);
5287 oidmap_free(&state.commit2label, 1);
5288 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5289 strbuf_release(&state.buf);
5294 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5295 const char **argv, unsigned flags)
5297 char *format = NULL;
5298 struct pretty_print_context pp = {0};
5299 struct rev_info revs;
5300 struct commit *commit;
5301 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5302 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5303 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5304 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5306 repo_init_revisions(r, &revs, NULL);
5307 revs.verbose_header = 1;
5309 revs.max_parents = 1;
5310 revs.cherry_mark = !reapply_cherry_picks;
5313 revs.right_only = 1;
5314 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5315 revs.topo_order = 1;
5317 revs.pretty_given = 1;
5318 git_config_get_string("rebase.instructionFormat", &format);
5319 if (!format || !*format) {
5321 format = xstrdup("%s");
5323 get_commit_format(format, &revs);
5325 pp.fmt = revs.commit_format;
5326 pp.output_encoding = get_log_output_encoding();
5328 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5329 return error(_("make_script: unhandled options"));
5331 if (prepare_revision_walk(&revs) < 0)
5332 return error(_("make_script: error preparing revisions"));
5335 return make_script_with_merges(&pp, &revs, out, flags);
5337 while ((commit = get_revision(&revs))) {
5338 int is_empty = is_original_commit_empty(commit);
5340 if (!is_empty && (commit->object.flags & PATCHSAME))
5342 if (is_empty && !keep_empty)
5344 strbuf_addf(out, "%s %s ", insn,
5345 oid_to_hex(&commit->object.oid));
5346 pretty_print_commit(&pp, commit, out);
5348 strbuf_addf(out, " %c empty", comment_line_char);
5349 strbuf_addch(out, '\n');
5355 * Add commands after pick and (series of) squash/fixup commands
5358 void todo_list_add_exec_commands(struct todo_list *todo_list,
5359 struct string_list *commands)
5361 struct strbuf *buf = &todo_list->buf;
5362 size_t base_offset = buf->len;
5363 int i, insert, nr = 0, alloc = 0;
5364 struct todo_item *items = NULL, *base_items = NULL;
5366 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
5367 for (i = 0; i < commands->nr; i++) {
5368 size_t command_len = strlen(commands->items[i].string);
5370 strbuf_addstr(buf, commands->items[i].string);
5371 strbuf_addch(buf, '\n');
5373 base_items[i].command = TODO_EXEC;
5374 base_items[i].offset_in_buf = base_offset;
5375 base_items[i].arg_offset = base_offset + strlen("exec ");
5376 base_items[i].arg_len = command_len - strlen("exec ");
5378 base_offset += command_len + 1;
5382 * Insert <commands> after every pick. Here, fixup/squash chains
5383 * are considered part of the pick, so we insert the commands *after*
5384 * those chains if there are any.
5386 * As we insert the exec commands immediately after rearranging
5387 * any fixups and before the user edits the list, a fixup chain
5388 * can never contain comments (any comments are empty picks that
5389 * have been commented out because the user did not specify
5390 * --keep-empty). So, it is safe to insert an exec command
5391 * without looking at the command following a comment.
5394 for (i = 0; i < todo_list->nr; i++) {
5395 enum todo_command command = todo_list->items[i].command;
5396 if (insert && !is_fixup(command)) {
5397 ALLOC_GROW(items, nr + commands->nr, alloc);
5398 COPY_ARRAY(items + nr, base_items, commands->nr);
5404 ALLOC_GROW(items, nr + 1, alloc);
5405 items[nr++] = todo_list->items[i];
5407 if (command == TODO_PICK || command == TODO_MERGE)
5411 /* insert or append final <commands> */
5412 if (insert || nr == todo_list->nr) {
5413 ALLOC_GROW(items, nr + commands->nr, alloc);
5414 COPY_ARRAY(items + nr, base_items, commands->nr);
5419 FREE_AND_NULL(todo_list->items);
5420 todo_list->items = items;
5422 todo_list->alloc = alloc;
5425 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5426 struct strbuf *buf, int num, unsigned flags)
5428 struct todo_item *item;
5429 int i, max = todo_list->nr;
5431 if (num > 0 && num < max)
5434 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5437 /* if the item is not a command write it and continue */
5438 if (item->command >= TODO_COMMENT) {
5439 strbuf_addf(buf, "%.*s\n", item->arg_len,
5440 todo_item_get_arg(todo_list, item));
5444 /* add command to the buffer */
5445 cmd = command_to_char(item->command);
5446 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5447 strbuf_addch(buf, cmd);
5449 strbuf_addstr(buf, command_to_string(item->command));
5453 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5454 short_commit_name(item->commit) :
5455 oid_to_hex(&item->commit->object.oid);
5457 if (item->command == TODO_FIXUP) {
5458 if (item->flags & TODO_EDIT_FIXUP_MSG)
5459 strbuf_addstr(buf, " -c");
5460 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5461 strbuf_addstr(buf, " -C");
5465 if (item->command == TODO_MERGE) {
5466 if (item->flags & TODO_EDIT_MERGE_MSG)
5467 strbuf_addstr(buf, " -c");
5469 strbuf_addstr(buf, " -C");
5472 strbuf_addf(buf, " %s", oid);
5475 /* add all the rest */
5477 strbuf_addch(buf, '\n');
5479 strbuf_addf(buf, " %.*s\n", item->arg_len,
5480 todo_item_get_arg(todo_list, item));
5484 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5485 const char *file, const char *shortrevisions,
5486 const char *shortonto, int num, unsigned flags)
5489 struct strbuf buf = STRBUF_INIT;
5491 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5492 if (flags & TODO_LIST_APPEND_TODO_HELP)
5493 append_todo_help(count_commands(todo_list),
5494 shortrevisions, shortonto, &buf);
5496 res = write_message(buf.buf, buf.len, file, 0);
5497 strbuf_release(&buf);
5502 /* skip picking commits whose parents are unchanged */
5503 static int skip_unnecessary_picks(struct repository *r,
5504 struct todo_list *todo_list,
5505 struct object_id *base_oid)
5507 struct object_id *parent_oid;
5510 for (i = 0; i < todo_list->nr; i++) {
5511 struct todo_item *item = todo_list->items + i;
5513 if (item->command >= TODO_NOOP)
5515 if (item->command != TODO_PICK)
5517 if (parse_commit(item->commit)) {
5518 return error(_("could not parse commit '%s'"),
5519 oid_to_hex(&item->commit->object.oid));
5521 if (!item->commit->parents)
5522 break; /* root commit */
5523 if (item->commit->parents->next)
5524 break; /* merge commit */
5525 parent_oid = &item->commit->parents->item->object.oid;
5526 if (!oideq(parent_oid, base_oid))
5528 oidcpy(base_oid, &item->commit->object.oid);
5531 const char *done_path = rebase_path_done();
5533 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5534 error_errno(_("could not write to '%s'"), done_path);
5538 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5540 todo_list->current = 0;
5541 todo_list->done_nr += i;
5543 if (is_fixup(peek_command(todo_list, 0)))
5544 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5550 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5551 const char *shortrevisions, const char *onto_name,
5552 struct commit *onto, const struct object_id *orig_head,
5553 struct string_list *commands, unsigned autosquash,
5554 struct todo_list *todo_list)
5556 char shortonto[GIT_MAX_HEXSZ + 1];
5557 const char *todo_file = rebase_path_todo();
5558 struct todo_list new_todo = TODO_LIST_INIT;
5559 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5560 struct object_id oid = onto->object.oid;
5563 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5565 if (buf->len == 0) {
5566 struct todo_item *item = append_new_todo(todo_list);
5567 item->command = TODO_NOOP;
5568 item->commit = NULL;
5569 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5572 if (autosquash && todo_list_rearrange_squash(todo_list))
5576 todo_list_add_exec_commands(todo_list, commands);
5578 if (count_commands(todo_list) == 0) {
5579 apply_autostash(rebase_path_autostash());
5580 sequencer_remove_state(opts);
5582 return error(_("nothing to do"));
5585 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5589 else if (res == -2) {
5590 apply_autostash(rebase_path_autostash());
5591 sequencer_remove_state(opts);
5594 } else if (res == -3) {
5595 apply_autostash(rebase_path_autostash());
5596 sequencer_remove_state(opts);
5597 todo_list_release(&new_todo);
5599 return error(_("nothing to do"));
5600 } else if (res == -4) {
5601 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5602 todo_list_release(&new_todo);
5607 /* Expand the commit IDs */
5608 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5609 strbuf_swap(&new_todo.buf, &buf2);
5610 strbuf_release(&buf2);
5611 new_todo.total_nr -= new_todo.nr;
5612 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5613 BUG("invalid todo list after expanding IDs:\n%s",
5616 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5617 todo_list_release(&new_todo);
5618 return error(_("could not skip unnecessary pick commands"));
5621 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5622 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5623 todo_list_release(&new_todo);
5624 return error_errno(_("could not write '%s'"), todo_file);
5629 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5632 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5635 todo_list_write_total_nr(&new_todo);
5636 res = pick_commits(r, &new_todo, opts);
5639 todo_list_release(&new_todo);
5644 struct subject2item_entry {
5645 struct hashmap_entry entry;
5647 char subject[FLEX_ARRAY];
5650 static int subject2item_cmp(const void *fndata,
5651 const struct hashmap_entry *eptr,
5652 const struct hashmap_entry *entry_or_key,
5655 const struct subject2item_entry *a, *b;
5657 a = container_of(eptr, const struct subject2item_entry, entry);
5658 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5660 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5663 define_commit_slab(commit_todo_item, struct todo_item *);
5665 static inline int skip_fixup_amend_squash(const char *subject, const char **p) {
5666 return skip_prefix(subject, "fixup! ", p) ||
5667 skip_prefix(subject, "amend! ", p) ||
5668 skip_prefix(subject, "squash! ", p);
5672 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5673 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5674 * after the former, and change "pick" to "fixup"/"squash".
5676 * Note that if the config has specified a custom instruction format, each log
5677 * message will have to be retrieved from the commit (as the oneline in the
5678 * script cannot be trusted) in order to normalize the autosquash arrangement.
5680 int todo_list_rearrange_squash(struct todo_list *todo_list)
5682 struct hashmap subject2item;
5683 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5685 struct commit_todo_item commit_todo;
5686 struct todo_item *items = NULL;
5688 init_commit_todo_item(&commit_todo);
5690 * The hashmap maps onelines to the respective todo list index.
5692 * If any items need to be rearranged, the next[i] value will indicate
5693 * which item was moved directly after the i'th.
5695 * In that case, last[i] will indicate the index of the latest item to
5696 * be moved to appear after the i'th.
5698 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5699 ALLOC_ARRAY(next, todo_list->nr);
5700 ALLOC_ARRAY(tail, todo_list->nr);
5701 ALLOC_ARRAY(subjects, todo_list->nr);
5702 for (i = 0; i < todo_list->nr; i++) {
5703 struct strbuf buf = STRBUF_INIT;
5704 struct todo_item *item = todo_list->items + i;
5705 const char *commit_buffer, *subject, *p;
5708 struct subject2item_entry *entry;
5710 next[i] = tail[i] = -1;
5711 if (!item->commit || item->command == TODO_DROP) {
5716 if (is_fixup(item->command)) {
5717 clear_commit_todo_item(&commit_todo);
5718 return error(_("the script was already rearranged."));
5721 *commit_todo_item_at(&commit_todo, item->commit) = item;
5723 parse_commit(item->commit);
5724 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5725 find_commit_subject(commit_buffer, &subject);
5726 format_subject(&buf, subject, " ");
5727 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5728 unuse_commit_buffer(item->commit, commit_buffer);
5729 if (skip_fixup_amend_squash(subject, &p)) {
5730 struct commit *commit2;
5735 if (!skip_fixup_amend_squash(p, &p))
5739 entry = hashmap_get_entry_from_hash(&subject2item,
5741 struct subject2item_entry,
5744 /* found by title */
5746 else if (!strchr(p, ' ') &&
5748 lookup_commit_reference_by_name(p)) &&
5749 *commit_todo_item_at(&commit_todo, commit2))
5750 /* found by commit name */
5751 i2 = *commit_todo_item_at(&commit_todo, commit2)
5754 /* copy can be a prefix of the commit subject */
5755 for (i2 = 0; i2 < i; i2++)
5757 starts_with(subjects[i2], p))
5765 if (starts_with(subject, "fixup!")) {
5766 todo_list->items[i].command = TODO_FIXUP;
5767 } else if (starts_with(subject, "amend!")) {
5768 todo_list->items[i].command = TODO_FIXUP;
5769 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5771 todo_list->items[i].command = TODO_SQUASH;
5777 next[i] = next[tail[i2]];
5781 } else if (!hashmap_get_from_hash(&subject2item,
5782 strhash(subject), subject)) {
5783 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5785 hashmap_entry_init(&entry->entry,
5786 strhash(entry->subject));
5787 hashmap_put(&subject2item, &entry->entry);
5792 for (i = 0; i < todo_list->nr; i++) {
5793 enum todo_command command = todo_list->items[i].command;
5797 * Initially, all commands are 'pick's. If it is a
5798 * fixup or a squash now, we have rearranged it.
5800 if (is_fixup(command))
5804 ALLOC_GROW(items, nr + 1, alloc);
5805 items[nr++] = todo_list->items[cur];
5810 FREE_AND_NULL(todo_list->items);
5811 todo_list->items = items;
5813 todo_list->alloc = alloc;
5818 for (i = 0; i < todo_list->nr; i++)
5821 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5823 clear_commit_todo_item(&commit_todo);
5828 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5830 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5831 struct object_id cherry_pick_head, rebase_head;
5833 if (file_exists(git_path_seq_dir()))
5834 *whence = FROM_CHERRY_PICK_MULTI;
5835 if (file_exists(rebase_path()) &&
5836 !get_oid("REBASE_HEAD", &rebase_head) &&
5837 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5838 oideq(&rebase_head, &cherry_pick_head))
5839 *whence = FROM_REBASE_PICK;
5841 *whence = FROM_CHERRY_PICK_SINGLE;