5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-recursive.h"
19 #include "argv-array.h"
23 #include "wt-status.h"
25 #include "notes-utils.h"
27 #include "unpack-trees.h"
31 #include "commit-slab.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
43 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
61 * The rebase command lines that have already been processed. A line
62 * is moved here when it is first handled, before any associated user
65 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
67 * The file to keep track of how many commands were already processed (e.g.
70 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
72 * The file to keep track of how many commands are to be processed in total
73 * (e.g. for the prompt).
75 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
77 * The commit message that is planned to be used for any changes that
78 * need to be committed following a user interaction.
80 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
82 * The file into which is accumulated the suggested commit message for
83 * squash/fixup commands. When the first of a series of squash/fixups
84 * is seen, the file is created and the commit message from the
85 * previous commit and from the first squash/fixup commit are written
86 * to it. The commit message for each subsequent squash/fixup commit
87 * is appended to the file as it is processed.
89 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
91 * If the current series of squash/fixups has not yet included a squash
92 * command, then this file exists and holds the commit message of the
93 * original "pick" commit. (If the series ends without a "squash"
94 * command, then this can be used as the commit message of the combined
95 * commit without opening the editor.)
97 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
99 * This file contains the list fixup/squash commands that have been
100 * accumulated into message-fixup or message-squash so far.
102 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
104 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
105 * GIT_AUTHOR_DATE that will be used for the commit that is currently
108 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
110 * When an "edit" rebase command is being processed, the SHA1 of the
111 * commit to be edited is recorded in this file. When "git rebase
112 * --continue" is executed, if there are any staged changes then they
113 * will be amended to the HEAD commit, but only provided the HEAD
114 * commit is still the commit to be edited. When any other rebase
115 * command is processed, this file is deleted.
117 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
119 * When we stop at a given patch via the "edit" command, this file contains
120 * the abbreviated commit name of the corresponding patch.
122 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
124 * For the post-rewrite hook, we make a list of rewritten commits and
125 * their new sha1s. The rewritten-pending list keeps the sha1s of
126 * commits that have been processed, but not committed yet,
127 * e.g. because they are waiting for a 'squash' command.
129 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
130 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
131 "rebase-merge/rewritten-pending")
134 * The path of the file containig the OID of the "squash onto" commit, i.e.
135 * the dummy commit used for `reset [new root]`.
137 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
140 * The path of the file listing refs that need to be deleted after the rebase
141 * finishes. This is used by the `label` command to record the need for cleanup.
143 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
146 * The following files are written by git-rebase just after parsing the
149 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
150 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
151 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
152 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
153 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
154 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
155 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
156 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
157 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
158 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
159 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
160 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
162 static int git_sequencer_config(const char *k, const char *v, void *cb)
164 struct replay_opts *opts = cb;
167 if (!strcmp(k, "commit.cleanup")) {
170 status = git_config_string(&s, k, v);
174 if (!strcmp(s, "verbatim")) {
175 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
176 opts->explicit_cleanup = 1;
177 } else if (!strcmp(s, "whitespace")) {
178 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
179 opts->explicit_cleanup = 1;
180 } else if (!strcmp(s, "strip")) {
181 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
182 opts->explicit_cleanup = 1;
183 } else if (!strcmp(s, "scissors")) {
184 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
185 opts->explicit_cleanup = 1;
187 warning(_("invalid commit message cleanup mode '%s'"),
195 if (!strcmp(k, "commit.gpgsign")) {
196 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
200 status = git_gpg_config(k, v, NULL);
204 return git_diff_basic_config(k, v, NULL);
207 void sequencer_init_config(struct replay_opts *opts)
209 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
210 git_config(git_sequencer_config, opts);
213 static inline int is_rebase_i(const struct replay_opts *opts)
215 return opts->action == REPLAY_INTERACTIVE_REBASE;
218 static const char *get_dir(const struct replay_opts *opts)
220 if (is_rebase_i(opts))
221 return rebase_path();
222 return git_path_seq_dir();
225 static const char *get_todo_path(const struct replay_opts *opts)
227 if (is_rebase_i(opts))
228 return rebase_path_todo();
229 return git_path_todo_file();
233 * Returns 0 for non-conforming footer
234 * Returns 1 for conforming footer
235 * Returns 2 when sob exists within conforming footer
236 * Returns 3 when sob exists within conforming footer as last entry
238 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
239 size_t ignore_footer)
241 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
242 struct trailer_info info;
244 int found_sob = 0, found_sob_last = 0;
248 trailer_info_get(&info, sb->buf, &opts);
250 if (info.trailer_start == info.trailer_end)
253 for (i = 0; i < info.trailer_nr; i++)
254 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
256 if (i == info.trailer_nr - 1)
260 trailer_info_release(&info);
269 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
271 static struct strbuf buf = STRBUF_INIT;
275 sq_quotef(&buf, "-S%s", opts->gpg_sign);
279 int sequencer_remove_state(struct replay_opts *opts)
281 struct strbuf buf = STRBUF_INIT;
284 if (is_rebase_i(opts) &&
285 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
288 char *eol = strchr(p, '\n');
291 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0) {
292 warning(_("could not delete '%s'"), p);
301 free(opts->gpg_sign);
302 free(opts->strategy);
303 for (i = 0; i < opts->xopts_nr; i++)
304 free(opts->xopts[i]);
306 strbuf_release(&opts->current_fixups);
309 strbuf_addstr(&buf, get_dir(opts));
310 if (remove_dir_recursively(&buf, 0))
311 ret = error(_("could not remove '%s'"), buf.buf);
312 strbuf_release(&buf);
317 static const char *action_name(const struct replay_opts *opts)
319 switch (opts->action) {
323 return N_("cherry-pick");
324 case REPLAY_INTERACTIVE_REBASE:
325 return N_("rebase -i");
327 die(_("unknown action: %d"), opts->action);
330 struct commit_message {
337 static const char *short_commit_name(struct commit *commit)
339 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
342 static int get_message(struct commit *commit, struct commit_message *out)
344 const char *abbrev, *subject;
347 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
348 abbrev = short_commit_name(commit);
350 subject_len = find_commit_subject(out->message, &subject);
352 out->subject = xmemdupz(subject, subject_len);
353 out->label = xstrfmt("%s... %s", abbrev, out->subject);
354 out->parent_label = xstrfmt("parent of %s", out->label);
359 static void free_message(struct commit *commit, struct commit_message *msg)
361 free(msg->parent_label);
364 unuse_commit_buffer(commit, msg->message);
367 static void print_advice(struct repository *r, int show_hint,
368 struct replay_opts *opts)
370 char *msg = getenv("GIT_CHERRY_PICK_HELP");
373 fprintf(stderr, "%s\n", msg);
375 * A conflict has occurred but the porcelain
376 * (typically rebase --interactive) wants to take care
377 * of the commit itself so remove CHERRY_PICK_HEAD
379 unlink(git_path_cherry_pick_head(r));
385 advise(_("after resolving the conflicts, mark the corrected paths\n"
386 "with 'git add <paths>' or 'git rm <paths>'"));
388 advise(_("after resolving the conflicts, mark the corrected paths\n"
389 "with 'git add <paths>' or 'git rm <paths>'\n"
390 "and commit the result with 'git commit'"));
394 static int write_message(const void *buf, size_t len, const char *filename,
397 struct lock_file msg_file = LOCK_INIT;
399 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
401 return error_errno(_("could not lock '%s'"), filename);
402 if (write_in_full(msg_fd, buf, len) < 0) {
403 error_errno(_("could not write to '%s'"), filename);
404 rollback_lock_file(&msg_file);
407 if (append_eol && write(msg_fd, "\n", 1) < 0) {
408 error_errno(_("could not write eol to '%s'"), filename);
409 rollback_lock_file(&msg_file);
412 if (commit_lock_file(&msg_file) < 0)
413 return error(_("failed to finalize '%s'"), filename);
419 * Reads a file that was presumably written by a shell script, i.e. with an
420 * end-of-line marker that needs to be stripped.
422 * Note that only the last end-of-line marker is stripped, consistent with the
423 * behavior of "$(cat path)" in a shell script.
425 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
427 static int read_oneliner(struct strbuf *buf,
428 const char *path, int skip_if_empty)
430 int orig_len = buf->len;
432 if (!file_exists(path))
435 if (strbuf_read_file(buf, path, 0) < 0) {
436 warning_errno(_("could not read '%s'"), path);
440 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
441 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
443 buf->buf[buf->len] = '\0';
446 if (skip_if_empty && buf->len == orig_len)
452 static struct tree *empty_tree(struct repository *r)
454 return lookup_tree(r, the_hash_algo->empty_tree);
457 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
459 if (repo_read_index_unmerged(repo))
460 return error_resolve_conflict(_(action_name(opts)));
462 error(_("your local changes would be overwritten by %s."),
463 _(action_name(opts)));
465 if (advice_commit_before_merge)
466 advise(_("commit your changes or stash them to proceed."));
470 static void update_abort_safety_file(void)
472 struct object_id head;
474 /* Do nothing on a single-pick */
475 if (!file_exists(git_path_seq_dir()))
478 if (!get_oid("HEAD", &head))
479 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
481 write_file(git_path_abort_safety_file(), "%s", "");
484 static int fast_forward_to(struct repository *r,
485 const struct object_id *to,
486 const struct object_id *from,
488 struct replay_opts *opts)
490 struct ref_transaction *transaction;
491 struct strbuf sb = STRBUF_INIT;
492 struct strbuf err = STRBUF_INIT;
495 if (checkout_fast_forward(r, from, to, 1))
496 return -1; /* the callee should have complained already */
498 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
500 transaction = ref_transaction_begin(&err);
502 ref_transaction_update(transaction, "HEAD",
503 to, unborn && !is_rebase_i(opts) ?
506 ref_transaction_commit(transaction, &err)) {
507 ref_transaction_free(transaction);
508 error("%s", err.buf);
510 strbuf_release(&err);
515 strbuf_release(&err);
516 ref_transaction_free(transaction);
517 update_abort_safety_file();
521 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
524 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
525 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
526 COMMIT_MSG_CLEANUP_SPACE;
527 else if (!strcmp(cleanup_arg, "verbatim"))
528 return COMMIT_MSG_CLEANUP_NONE;
529 else if (!strcmp(cleanup_arg, "whitespace"))
530 return COMMIT_MSG_CLEANUP_SPACE;
531 else if (!strcmp(cleanup_arg, "strip"))
532 return COMMIT_MSG_CLEANUP_ALL;
533 else if (!strcmp(cleanup_arg, "scissors"))
534 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
535 COMMIT_MSG_CLEANUP_SPACE;
537 die(_("Invalid cleanup mode %s"), cleanup_arg);
541 * NB using int rather than enum cleanup_mode to stop clang's
542 * -Wtautological-constant-out-of-range-compare complaining that the comparison
545 static const char *describe_cleanup_mode(int cleanup_mode)
547 static const char *modes[] = { "whitespace",
552 if (cleanup_mode < ARRAY_SIZE(modes))
553 return modes[cleanup_mode];
555 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
558 void append_conflicts_hint(struct index_state *istate,
559 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
563 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
564 strbuf_addch(msgbuf, '\n');
565 wt_status_append_cut_line(msgbuf);
566 strbuf_addch(msgbuf, comment_line_char);
569 strbuf_addch(msgbuf, '\n');
570 strbuf_commented_addf(msgbuf, "Conflicts:\n");
571 for (i = 0; i < istate->cache_nr;) {
572 const struct cache_entry *ce = istate->cache[i++];
574 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
575 while (i < istate->cache_nr &&
576 !strcmp(ce->name, istate->cache[i]->name))
582 static int do_recursive_merge(struct repository *r,
583 struct commit *base, struct commit *next,
584 const char *base_label, const char *next_label,
585 struct object_id *head, struct strbuf *msgbuf,
586 struct replay_opts *opts)
588 struct merge_options o;
589 struct tree *result, *next_tree, *base_tree, *head_tree;
592 struct lock_file index_lock = LOCK_INIT;
594 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
599 init_merge_options(&o, r);
600 o.ancestor = base ? base_label : "(empty tree)";
602 o.branch2 = next ? next_label : "(empty tree)";
603 if (is_rebase_i(opts))
605 o.show_rename_progress = 1;
607 head_tree = parse_tree_indirect(head);
608 next_tree = next ? get_commit_tree(next) : empty_tree(r);
609 base_tree = base ? get_commit_tree(base) : empty_tree(r);
611 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
612 parse_merge_opt(&o, *xopt);
614 clean = merge_trees(&o,
616 next_tree, base_tree, &result);
617 if (is_rebase_i(opts) && clean <= 0)
618 fputs(o.obuf.buf, stdout);
619 strbuf_release(&o.obuf);
620 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
622 rollback_lock_file(&index_lock);
626 if (write_locked_index(r->index, &index_lock,
627 COMMIT_LOCK | SKIP_IF_UNCHANGED))
629 * TRANSLATORS: %s will be "revert", "cherry-pick" or
632 return error(_("%s: Unable to write new index file"),
633 _(action_name(opts)));
636 append_conflicts_hint(r->index, msgbuf,
637 opts->default_msg_cleanup);
642 static struct object_id *get_cache_tree_oid(struct index_state *istate)
644 if (!istate->cache_tree)
645 istate->cache_tree = cache_tree();
647 if (!cache_tree_fully_valid(istate->cache_tree))
648 if (cache_tree_update(istate, 0)) {
649 error(_("unable to update cache tree"));
653 return &istate->cache_tree->oid;
656 static int is_index_unchanged(struct repository *r)
658 struct object_id head_oid, *cache_tree_oid;
659 struct commit *head_commit;
660 struct index_state *istate = r->index;
662 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
663 return error(_("could not resolve HEAD commit"));
665 head_commit = lookup_commit(r, &head_oid);
668 * If head_commit is NULL, check_commit, called from
669 * lookup_commit, would have indicated that head_commit is not
670 * a commit object already. parse_commit() will return failure
671 * without further complaints in such a case. Otherwise, if
672 * the commit is invalid, parse_commit() will complain. So
673 * there is nothing for us to say here. Just return failure.
675 if (parse_commit(head_commit))
678 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
681 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
684 static int write_author_script(const char *message)
686 struct strbuf buf = STRBUF_INIT;
691 if (!*message || starts_with(message, "\n")) {
693 /* Missing 'author' line? */
694 unlink(rebase_path_author_script());
696 } else if (skip_prefix(message, "author ", &message))
698 else if ((eol = strchr(message, '\n')))
703 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
704 while (*message && *message != '\n' && *message != '\r')
705 if (skip_prefix(message, " <", &message))
707 else if (*message != '\'')
708 strbuf_addch(&buf, *(message++));
710 strbuf_addf(&buf, "'\\%c'", *(message++));
711 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
712 while (*message && *message != '\n' && *message != '\r')
713 if (skip_prefix(message, "> ", &message))
715 else if (*message != '\'')
716 strbuf_addch(&buf, *(message++));
718 strbuf_addf(&buf, "'\\%c'", *(message++));
719 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
720 while (*message && *message != '\n' && *message != '\r')
721 if (*message != '\'')
722 strbuf_addch(&buf, *(message++));
724 strbuf_addf(&buf, "'\\%c'", *(message++));
725 strbuf_addch(&buf, '\'');
726 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
727 strbuf_release(&buf);
732 * Take a series of KEY='VALUE' lines where VALUE part is
733 * sq-quoted, and append <KEY, VALUE> at the end of the string list
735 static int parse_key_value_squoted(char *buf, struct string_list *list)
738 struct string_list_item *item;
740 char *cp = strchr(buf, '=');
742 np = strchrnul(buf, '\n');
743 return error(_("no key present in '%.*s'"),
744 (int) (np - buf), buf);
746 np = strchrnul(cp, '\n');
748 item = string_list_append(list, buf);
750 buf = np + (*np == '\n');
754 return error(_("unable to dequote value of '%s'"),
756 item->util = xstrdup(cp);
762 * Reads and parses the state directory's "author-script" file, and sets name,
763 * email and date accordingly.
764 * Returns 0 on success, -1 if the file could not be parsed.
766 * The author script is of the format:
768 * GIT_AUTHOR_NAME='$author_name'
769 * GIT_AUTHOR_EMAIL='$author_email'
770 * GIT_AUTHOR_DATE='$author_date'
772 * where $author_name, $author_email and $author_date are quoted. We are strict
773 * with our parsing, as the file was meant to be eval'd in the old
774 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
775 * from what this function expects, it is better to bail out than to do
776 * something that the user does not expect.
778 int read_author_script(const char *path, char **name, char **email, char **date,
781 struct strbuf buf = STRBUF_INIT;
782 struct string_list kv = STRING_LIST_INIT_DUP;
783 int retval = -1; /* assume failure */
784 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
786 if (strbuf_read_file(&buf, path, 256) <= 0) {
787 strbuf_release(&buf);
788 if (errno == ENOENT && allow_missing)
791 return error_errno(_("could not open '%s' for reading"),
795 if (parse_key_value_squoted(buf.buf, &kv))
798 for (i = 0; i < kv.nr; i++) {
799 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
801 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
804 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
806 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
809 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
811 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
815 err = error(_("unknown variable '%s'"),
820 error(_("missing 'GIT_AUTHOR_NAME'"));
822 error(_("missing 'GIT_AUTHOR_EMAIL'"));
824 error(_("missing 'GIT_AUTHOR_DATE'"));
825 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
829 *name = kv.items[name_i].util;
831 free(kv.items[name_i].util);
833 *email = kv.items[email_i].util;
835 free(kv.items[email_i].util);
837 *date = kv.items[date_i].util;
839 free(kv.items[date_i].util);
842 string_list_clear(&kv, !!retval);
843 strbuf_release(&buf);
848 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
849 * file with shell quoting into struct argv_array. Returns -1 on
850 * error, 0 otherwise.
852 static int read_env_script(struct argv_array *env)
854 char *name, *email, *date;
856 if (read_author_script(rebase_path_author_script(),
857 &name, &email, &date, 0))
860 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
861 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
862 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
870 static char *get_author(const char *message)
875 a = find_commit_header(message, "author", &len);
877 return xmemdupz(a, len);
882 static const char staged_changes_advice[] =
883 N_("you have staged changes in your working tree\n"
884 "If these changes are meant to be squashed into the previous commit, run:\n"
886 " git commit --amend %s\n"
888 "If they are meant to go into a new commit, run:\n"
892 "In both cases, once you're done, continue with:\n"
894 " git rebase --continue\n");
896 #define ALLOW_EMPTY (1<<0)
897 #define EDIT_MSG (1<<1)
898 #define AMEND_MSG (1<<2)
899 #define CLEANUP_MSG (1<<3)
900 #define VERIFY_MSG (1<<4)
901 #define CREATE_ROOT_COMMIT (1<<5)
903 static int run_command_silent_on_success(struct child_process *cmd)
905 struct strbuf buf = STRBUF_INIT;
908 cmd->stdout_to_stderr = 1;
909 rc = pipe_command(cmd,
915 fputs(buf.buf, stderr);
916 strbuf_release(&buf);
921 * If we are cherry-pick, and if the merge did not result in
922 * hand-editing, we will hit this commit and inherit the original
923 * author date and name.
925 * If we are revert, or if our cherry-pick results in a hand merge,
926 * we had better say that the current user is responsible for that.
928 * An exception is when run_git_commit() is called during an
929 * interactive rebase: in that case, we will want to retain the
932 static int run_git_commit(struct repository *r,
934 struct replay_opts *opts,
937 struct child_process cmd = CHILD_PROCESS_INIT;
941 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
942 const char *gpg_opt = gpg_sign_opt_quoted(opts);
944 return error(_(staged_changes_advice),
948 argv_array_push(&cmd.args, "commit");
950 if (!(flags & VERIFY_MSG))
951 argv_array_push(&cmd.args, "-n");
952 if ((flags & AMEND_MSG))
953 argv_array_push(&cmd.args, "--amend");
955 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
957 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
958 else if (!(flags & EDIT_MSG))
959 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
960 if ((flags & CLEANUP_MSG))
961 argv_array_push(&cmd.args, "--cleanup=strip");
962 if ((flags & EDIT_MSG))
963 argv_array_push(&cmd.args, "-e");
964 else if (!(flags & CLEANUP_MSG) &&
965 !opts->signoff && !opts->record_origin &&
966 !opts->explicit_cleanup)
967 argv_array_push(&cmd.args, "--cleanup=verbatim");
969 if ((flags & ALLOW_EMPTY))
970 argv_array_push(&cmd.args, "--allow-empty");
972 if (!(flags & EDIT_MSG))
973 argv_array_push(&cmd.args, "--allow-empty-message");
975 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
976 return run_command_silent_on_success(&cmd);
978 return run_command(&cmd);
981 static int rest_is_empty(const struct strbuf *sb, int start)
986 /* Check if the rest is just whitespace and Signed-off-by's. */
987 for (i = start; i < sb->len; i++) {
988 nl = memchr(sb->buf + i, '\n', sb->len - i);
994 if (strlen(sign_off_header) <= eol - i &&
995 starts_with(sb->buf + i, sign_off_header)) {
1000 if (!isspace(sb->buf[i++]))
1007 void cleanup_message(struct strbuf *msgbuf,
1008 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1010 if (verbose || /* Truncate the message just before the diff, if any. */
1011 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1012 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1013 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1014 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1018 * Find out if the message in the strbuf contains only whitespace and
1019 * Signed-off-by lines.
1021 int message_is_empty(const struct strbuf *sb,
1022 enum commit_msg_cleanup_mode cleanup_mode)
1024 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1026 return rest_is_empty(sb, 0);
1030 * See if the user edited the message in the editor or left what
1031 * was in the template intact
1033 int template_untouched(const struct strbuf *sb, const char *template_file,
1034 enum commit_msg_cleanup_mode cleanup_mode)
1036 struct strbuf tmpl = STRBUF_INIT;
1039 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1042 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1045 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1046 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1048 strbuf_release(&tmpl);
1049 return rest_is_empty(sb, start - sb->buf);
1052 int update_head_with_reflog(const struct commit *old_head,
1053 const struct object_id *new_head,
1054 const char *action, const struct strbuf *msg,
1057 struct ref_transaction *transaction;
1058 struct strbuf sb = STRBUF_INIT;
1063 strbuf_addstr(&sb, action);
1064 strbuf_addstr(&sb, ": ");
1067 nl = strchr(msg->buf, '\n');
1069 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1071 strbuf_addbuf(&sb, msg);
1072 strbuf_addch(&sb, '\n');
1075 transaction = ref_transaction_begin(err);
1077 ref_transaction_update(transaction, "HEAD", new_head,
1078 old_head ? &old_head->object.oid : &null_oid,
1080 ref_transaction_commit(transaction, err)) {
1083 ref_transaction_free(transaction);
1084 strbuf_release(&sb);
1089 static int run_rewrite_hook(const struct object_id *oldoid,
1090 const struct object_id *newoid)
1092 struct child_process proc = CHILD_PROCESS_INIT;
1093 const char *argv[3];
1095 struct strbuf sb = STRBUF_INIT;
1097 argv[0] = find_hook("post-rewrite");
1106 proc.stdout_to_stderr = 1;
1107 proc.trace2_hook_name = "post-rewrite";
1109 code = start_command(&proc);
1112 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1113 sigchain_push(SIGPIPE, SIG_IGN);
1114 write_in_full(proc.in, sb.buf, sb.len);
1116 strbuf_release(&sb);
1117 sigchain_pop(SIGPIPE);
1118 return finish_command(&proc);
1121 void commit_post_rewrite(struct repository *r,
1122 const struct commit *old_head,
1123 const struct object_id *new_head)
1125 struct notes_rewrite_cfg *cfg;
1127 cfg = init_copy_notes_for_rewrite("amend");
1129 /* we are amending, so old_head is not NULL */
1130 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1131 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1133 run_rewrite_hook(&old_head->object.oid, new_head);
1136 static int run_prepare_commit_msg_hook(struct repository *r,
1140 struct argv_array hook_env = ARGV_ARRAY_INIT;
1144 name = git_path_commit_editmsg();
1145 if (write_message(msg->buf, msg->len, name, 0))
1148 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
1149 argv_array_push(&hook_env, "GIT_EDITOR=:");
1151 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1152 "commit", commit, NULL);
1154 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1157 ret = error(_("'prepare-commit-msg' hook failed"));
1158 argv_array_clear(&hook_env);
1163 static const char implicit_ident_advice_noconfig[] =
1164 N_("Your name and email address were configured automatically based\n"
1165 "on your username and hostname. Please check that they are accurate.\n"
1166 "You can suppress this message by setting them explicitly. Run the\n"
1167 "following command and follow the instructions in your editor to edit\n"
1168 "your configuration file:\n"
1170 " git config --global --edit\n"
1172 "After doing this, you may fix the identity used for this commit with:\n"
1174 " git commit --amend --reset-author\n");
1176 static const char implicit_ident_advice_config[] =
1177 N_("Your name and email address were configured automatically based\n"
1178 "on your username and hostname. Please check that they are accurate.\n"
1179 "You can suppress this message by setting them explicitly:\n"
1181 " git config --global user.name \"Your Name\"\n"
1182 " git config --global user.email you@example.com\n"
1184 "After doing this, you may fix the identity used for this commit with:\n"
1186 " git commit --amend --reset-author\n");
1188 static const char *implicit_ident_advice(void)
1190 char *user_config = expand_user_path("~/.gitconfig", 0);
1191 char *xdg_config = xdg_config_home("config");
1192 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1198 return _(implicit_ident_advice_config);
1200 return _(implicit_ident_advice_noconfig);
1204 void print_commit_summary(struct repository *r,
1206 const struct object_id *oid,
1209 struct rev_info rev;
1210 struct commit *commit;
1211 struct strbuf format = STRBUF_INIT;
1213 struct pretty_print_context pctx = {0};
1214 struct strbuf author_ident = STRBUF_INIT;
1215 struct strbuf committer_ident = STRBUF_INIT;
1217 commit = lookup_commit(r, oid);
1219 die(_("couldn't look up newly created commit"));
1220 if (parse_commit(commit))
1221 die(_("could not parse newly created commit"));
1223 strbuf_addstr(&format, "format:%h] %s");
1225 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1226 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1227 if (strbuf_cmp(&author_ident, &committer_ident)) {
1228 strbuf_addstr(&format, "\n Author: ");
1229 strbuf_addbuf_percentquote(&format, &author_ident);
1231 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1232 struct strbuf date = STRBUF_INIT;
1234 format_commit_message(commit, "%ad", &date, &pctx);
1235 strbuf_addstr(&format, "\n Date: ");
1236 strbuf_addbuf_percentquote(&format, &date);
1237 strbuf_release(&date);
1239 if (!committer_ident_sufficiently_given()) {
1240 strbuf_addstr(&format, "\n Committer: ");
1241 strbuf_addbuf_percentquote(&format, &committer_ident);
1242 if (advice_implicit_identity) {
1243 strbuf_addch(&format, '\n');
1244 strbuf_addstr(&format, implicit_ident_advice());
1247 strbuf_release(&author_ident);
1248 strbuf_release(&committer_ident);
1250 repo_init_revisions(r, &rev, prefix);
1251 setup_revisions(0, NULL, &rev, NULL);
1254 rev.diffopt.output_format =
1255 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1257 rev.verbose_header = 1;
1258 rev.show_root_diff = 1;
1259 get_commit_format(format.buf, &rev);
1260 rev.always_show_header = 0;
1261 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1262 rev.diffopt.break_opt = 0;
1263 diff_setup_done(&rev.diffopt);
1265 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1267 die_errno(_("unable to resolve HEAD after creating commit"));
1268 if (!strcmp(head, "HEAD"))
1269 head = _("detached HEAD");
1271 skip_prefix(head, "refs/heads/", &head);
1272 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1273 _(" (root-commit)") : "");
1275 if (!log_tree_commit(&rev, commit)) {
1276 rev.always_show_header = 1;
1277 rev.use_terminator = 1;
1278 log_tree_commit(&rev, commit);
1281 strbuf_release(&format);
1284 static int parse_head(struct repository *r, struct commit **head)
1286 struct commit *current_head;
1287 struct object_id oid;
1289 if (get_oid("HEAD", &oid)) {
1290 current_head = NULL;
1292 current_head = lookup_commit_reference(r, &oid);
1294 return error(_("could not parse HEAD"));
1295 if (!oideq(&oid, ¤t_head->object.oid)) {
1296 warning(_("HEAD %s is not a commit!"),
1299 if (parse_commit(current_head))
1300 return error(_("could not parse HEAD commit"));
1302 *head = current_head;
1308 * Try to commit without forking 'git commit'. In some cases we need
1309 * to run 'git commit' to display an error message
1312 * -1 - error unable to commit
1314 * 1 - run 'git commit'
1316 static int try_to_commit(struct repository *r,
1317 struct strbuf *msg, const char *author,
1318 struct replay_opts *opts, unsigned int flags,
1319 struct object_id *oid)
1321 struct object_id tree;
1322 struct commit *current_head = NULL;
1323 struct commit_list *parents = NULL;
1324 struct commit_extra_header *extra = NULL;
1325 struct strbuf err = STRBUF_INIT;
1326 struct strbuf commit_msg = STRBUF_INIT;
1327 char *amend_author = NULL;
1328 const char *hook_commit = NULL;
1329 enum commit_msg_cleanup_mode cleanup;
1332 if (parse_head(r, ¤t_head))
1335 if (flags & AMEND_MSG) {
1336 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1337 const char *out_enc = get_commit_output_encoding();
1338 const char *message = logmsg_reencode(current_head, NULL,
1342 const char *orig_message = NULL;
1344 find_commit_subject(message, &orig_message);
1346 strbuf_addstr(msg, orig_message);
1347 hook_commit = "HEAD";
1349 author = amend_author = get_author(message);
1350 unuse_commit_buffer(current_head, message);
1352 res = error(_("unable to parse commit author"));
1355 parents = copy_commit_list(current_head->parents);
1356 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1357 } else if (current_head &&
1358 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1359 commit_list_insert(current_head, &parents);
1362 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1363 res = error(_("git write-tree failed to write a tree"));
1367 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1368 get_commit_tree_oid(current_head) :
1369 the_hash_algo->empty_tree, &tree)) {
1370 res = 1; /* run 'git commit' to display error message */
1374 if (find_hook("prepare-commit-msg")) {
1375 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1378 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1380 res = error_errno(_("unable to read commit message "
1382 git_path_commit_editmsg());
1388 if (flags & CLEANUP_MSG)
1389 cleanup = COMMIT_MSG_CLEANUP_ALL;
1390 else if ((opts->signoff || opts->record_origin) &&
1391 !opts->explicit_cleanup)
1392 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1394 cleanup = opts->default_msg_cleanup;
1396 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1397 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1398 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1399 res = 1; /* run 'git commit' to display error message */
1405 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1406 oid, author, opts->gpg_sign, extra)) {
1407 res = error(_("failed to write commit object"));
1411 if (update_head_with_reflog(current_head, oid,
1412 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1413 res = error("%s", err.buf);
1417 if (flags & AMEND_MSG)
1418 commit_post_rewrite(r, current_head, oid);
1421 free_commit_extra_headers(extra);
1422 strbuf_release(&err);
1423 strbuf_release(&commit_msg);
1429 static int do_commit(struct repository *r,
1430 const char *msg_file, const char *author,
1431 struct replay_opts *opts, unsigned int flags)
1435 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1436 struct object_id oid;
1437 struct strbuf sb = STRBUF_INIT;
1439 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1440 return error_errno(_("unable to read commit message "
1444 res = try_to_commit(r, msg_file ? &sb : NULL,
1445 author, opts, flags, &oid);
1446 strbuf_release(&sb);
1448 unlink(git_path_cherry_pick_head(r));
1449 unlink(git_path_merge_msg(r));
1450 if (!is_rebase_i(opts))
1451 print_commit_summary(r, NULL, &oid,
1452 SUMMARY_SHOW_AUTHOR_DATE);
1457 return run_git_commit(r, msg_file, opts, flags);
1462 static int is_original_commit_empty(struct commit *commit)
1464 const struct object_id *ptree_oid;
1466 if (parse_commit(commit))
1467 return error(_("could not parse commit %s"),
1468 oid_to_hex(&commit->object.oid));
1469 if (commit->parents) {
1470 struct commit *parent = commit->parents->item;
1471 if (parse_commit(parent))
1472 return error(_("could not parse parent commit %s"),
1473 oid_to_hex(&parent->object.oid));
1474 ptree_oid = get_commit_tree_oid(parent);
1476 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1479 return oideq(ptree_oid, get_commit_tree_oid(commit));
1483 * Do we run "git commit" with "--allow-empty"?
1485 static int allow_empty(struct repository *r,
1486 struct replay_opts *opts,
1487 struct commit *commit)
1489 int index_unchanged, empty_commit;
1494 * (1) we do not allow empty at all and error out.
1496 * (2) we allow ones that were initially empty, but
1497 * forbid the ones that become empty;
1499 * (3) we allow both.
1501 if (!opts->allow_empty)
1502 return 0; /* let "git commit" barf as necessary */
1504 index_unchanged = is_index_unchanged(r);
1505 if (index_unchanged < 0)
1506 return index_unchanged;
1507 if (!index_unchanged)
1508 return 0; /* we do not have to say --allow-empty */
1510 if (opts->keep_redundant_commits)
1513 empty_commit = is_original_commit_empty(commit);
1514 if (empty_commit < 0)
1515 return empty_commit;
1525 } todo_command_info[] = {
1542 static const char *command_to_string(const enum todo_command command)
1544 if (command < TODO_COMMENT)
1545 return todo_command_info[command].str;
1546 die(_("unknown command: %d"), command);
1549 static char command_to_char(const enum todo_command command)
1551 if (command < TODO_COMMENT && todo_command_info[command].c)
1552 return todo_command_info[command].c;
1553 return comment_line_char;
1556 static int is_noop(const enum todo_command command)
1558 return TODO_NOOP <= command;
1561 static int is_fixup(enum todo_command command)
1563 return command == TODO_FIXUP || command == TODO_SQUASH;
1566 /* Does this command create a (non-merge) commit? */
1567 static int is_pick_or_similar(enum todo_command command)
1582 static int update_squash_messages(struct repository *r,
1583 enum todo_command command,
1584 struct commit *commit,
1585 struct replay_opts *opts)
1587 struct strbuf buf = STRBUF_INIT;
1589 const char *message, *body;
1591 if (opts->current_fixup_count > 0) {
1592 struct strbuf header = STRBUF_INIT;
1595 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1596 return error(_("could not read '%s'"),
1597 rebase_path_squash_msg());
1599 eol = buf.buf[0] != comment_line_char ?
1600 buf.buf : strchrnul(buf.buf, '\n');
1602 strbuf_addf(&header, "%c ", comment_line_char);
1603 strbuf_addf(&header, _("This is a combination of %d commits."),
1604 opts->current_fixup_count + 2);
1605 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1606 strbuf_release(&header);
1608 struct object_id head;
1609 struct commit *head_commit;
1610 const char *head_message, *body;
1612 if (get_oid("HEAD", &head))
1613 return error(_("need a HEAD to fixup"));
1614 if (!(head_commit = lookup_commit_reference(r, &head)))
1615 return error(_("could not read HEAD"));
1616 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1617 return error(_("could not read HEAD's commit message"));
1619 find_commit_subject(head_message, &body);
1620 if (write_message(body, strlen(body),
1621 rebase_path_fixup_msg(), 0)) {
1622 unuse_commit_buffer(head_commit, head_message);
1623 return error(_("cannot write '%s'"),
1624 rebase_path_fixup_msg());
1627 strbuf_addf(&buf, "%c ", comment_line_char);
1628 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1629 strbuf_addf(&buf, "\n%c ", comment_line_char);
1630 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1631 strbuf_addstr(&buf, "\n\n");
1632 strbuf_addstr(&buf, body);
1634 unuse_commit_buffer(head_commit, head_message);
1637 if (!(message = get_commit_buffer(commit, NULL)))
1638 return error(_("could not read commit message of %s"),
1639 oid_to_hex(&commit->object.oid));
1640 find_commit_subject(message, &body);
1642 if (command == TODO_SQUASH) {
1643 unlink(rebase_path_fixup_msg());
1644 strbuf_addf(&buf, "\n%c ", comment_line_char);
1645 strbuf_addf(&buf, _("This is the commit message #%d:"),
1646 ++opts->current_fixup_count + 1);
1647 strbuf_addstr(&buf, "\n\n");
1648 strbuf_addstr(&buf, body);
1649 } else if (command == TODO_FIXUP) {
1650 strbuf_addf(&buf, "\n%c ", comment_line_char);
1651 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1652 ++opts->current_fixup_count + 1);
1653 strbuf_addstr(&buf, "\n\n");
1654 strbuf_add_commented_lines(&buf, body, strlen(body));
1656 return error(_("unknown command: %d"), command);
1657 unuse_commit_buffer(commit, message);
1659 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1660 strbuf_release(&buf);
1663 strbuf_addf(&opts->current_fixups, "%s%s %s",
1664 opts->current_fixups.len ? "\n" : "",
1665 command_to_string(command),
1666 oid_to_hex(&commit->object.oid));
1667 res = write_message(opts->current_fixups.buf,
1668 opts->current_fixups.len,
1669 rebase_path_current_fixups(), 0);
1675 static void flush_rewritten_pending(void)
1677 struct strbuf buf = STRBUF_INIT;
1678 struct object_id newoid;
1681 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1682 !get_oid("HEAD", &newoid) &&
1683 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1684 char *bol = buf.buf, *eol;
1687 eol = strchrnul(bol, '\n');
1688 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1689 bol, oid_to_hex(&newoid));
1695 unlink(rebase_path_rewritten_pending());
1697 strbuf_release(&buf);
1700 static void record_in_rewritten(struct object_id *oid,
1701 enum todo_command next_command)
1703 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1708 fprintf(out, "%s\n", oid_to_hex(oid));
1711 if (!is_fixup(next_command))
1712 flush_rewritten_pending();
1715 static int do_pick_commit(struct repository *r,
1716 enum todo_command command,
1717 struct commit *commit,
1718 struct replay_opts *opts,
1719 int final_fixup, int *check_todo)
1721 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1722 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1723 struct object_id head;
1724 struct commit *base, *next, *parent;
1725 const char *base_label, *next_label;
1726 char *author = NULL;
1727 struct commit_message msg = { NULL, NULL, NULL, NULL };
1728 struct strbuf msgbuf = STRBUF_INIT;
1729 int res, unborn = 0, reword = 0, allow;
1731 if (opts->no_commit) {
1733 * We do not intend to commit immediately. We just want to
1734 * merge the differences in, so let's compute the tree
1735 * that represents the "current" state for merge-recursive
1738 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1739 return error(_("your index file is unmerged."));
1741 unborn = get_oid("HEAD", &head);
1742 /* Do we want to generate a root commit? */
1743 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1744 oideq(&head, &opts->squash_onto)) {
1745 if (is_fixup(command))
1746 return error(_("cannot fixup root commit"));
1747 flags |= CREATE_ROOT_COMMIT;
1750 oidcpy(&head, the_hash_algo->empty_tree);
1751 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1753 return error_dirty_index(r, opts);
1755 discard_index(r->index);
1757 if (!commit->parents)
1759 else if (commit->parents->next) {
1760 /* Reverting or cherry-picking a merge commit */
1762 struct commit_list *p;
1764 if (!opts->mainline)
1765 return error(_("commit %s is a merge but no -m option was given."),
1766 oid_to_hex(&commit->object.oid));
1768 for (cnt = 1, p = commit->parents;
1769 cnt != opts->mainline && p;
1772 if (cnt != opts->mainline || !p)
1773 return error(_("commit %s does not have parent %d"),
1774 oid_to_hex(&commit->object.oid), opts->mainline);
1776 } else if (1 < opts->mainline)
1778 * Non-first parent explicitly specified as mainline for
1781 return error(_("commit %s does not have parent %d"),
1782 oid_to_hex(&commit->object.oid), opts->mainline);
1784 parent = commit->parents->item;
1786 if (get_message(commit, &msg) != 0)
1787 return error(_("cannot get commit message for %s"),
1788 oid_to_hex(&commit->object.oid));
1790 if (opts->allow_ff && !is_fixup(command) &&
1791 ((parent && oideq(&parent->object.oid, &head)) ||
1792 (!parent && unborn))) {
1793 if (is_rebase_i(opts))
1794 write_author_script(msg.message);
1795 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1797 if (res || command != TODO_REWORD)
1801 goto fast_forward_edit;
1803 if (parent && parse_commit(parent) < 0)
1804 /* TRANSLATORS: The first %s will be a "todo" command like
1805 "revert" or "pick", the second %s a SHA1. */
1806 return error(_("%s: cannot parse parent commit %s"),
1807 command_to_string(command),
1808 oid_to_hex(&parent->object.oid));
1811 * "commit" is an existing commit. We would want to apply
1812 * the difference it introduces since its first parent "prev"
1813 * on top of the current HEAD if we are cherry-pick. Or the
1814 * reverse of it if we are revert.
1817 if (command == TODO_REVERT) {
1819 base_label = msg.label;
1821 next_label = msg.parent_label;
1822 strbuf_addstr(&msgbuf, "Revert \"");
1823 strbuf_addstr(&msgbuf, msg.subject);
1824 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1825 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1827 if (commit->parents && commit->parents->next) {
1828 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1829 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1831 strbuf_addstr(&msgbuf, ".\n");
1836 base_label = msg.parent_label;
1838 next_label = msg.label;
1840 /* Append the commit log message to msgbuf. */
1841 if (find_commit_subject(msg.message, &p))
1842 strbuf_addstr(&msgbuf, p);
1844 if (opts->record_origin) {
1845 strbuf_complete_line(&msgbuf);
1846 if (!has_conforming_footer(&msgbuf, NULL, 0))
1847 strbuf_addch(&msgbuf, '\n');
1848 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1849 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1850 strbuf_addstr(&msgbuf, ")\n");
1852 if (!is_fixup(command))
1853 author = get_author(msg.message);
1856 if (command == TODO_REWORD)
1858 else if (is_fixup(command)) {
1859 if (update_squash_messages(r, command, commit, opts))
1863 msg_file = rebase_path_squash_msg();
1864 else if (file_exists(rebase_path_fixup_msg())) {
1865 flags |= CLEANUP_MSG;
1866 msg_file = rebase_path_fixup_msg();
1868 const char *dest = git_path_squash_msg(r);
1870 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1871 return error(_("could not rename '%s' to '%s'"),
1872 rebase_path_squash_msg(), dest);
1873 unlink(git_path_merge_msg(r));
1879 if (opts->signoff && !is_fixup(command))
1880 append_signoff(&msgbuf, 0, 0);
1882 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1884 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1885 res = do_recursive_merge(r, base, next, base_label, next_label,
1886 &head, &msgbuf, opts);
1890 res |= write_message(msgbuf.buf, msgbuf.len,
1891 git_path_merge_msg(r), 0);
1893 struct commit_list *common = NULL;
1894 struct commit_list *remotes = NULL;
1896 res = write_message(msgbuf.buf, msgbuf.len,
1897 git_path_merge_msg(r), 0);
1899 commit_list_insert(base, &common);
1900 commit_list_insert(next, &remotes);
1901 res |= try_merge_command(r, opts->strategy,
1902 opts->xopts_nr, (const char **)opts->xopts,
1903 common, oid_to_hex(&head), remotes);
1904 free_commit_list(common);
1905 free_commit_list(remotes);
1907 strbuf_release(&msgbuf);
1910 * If the merge was clean or if it failed due to conflict, we write
1911 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1912 * However, if the merge did not even start, then we don't want to
1915 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1916 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1917 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1919 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1920 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1921 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1925 error(command == TODO_REVERT
1926 ? _("could not revert %s... %s")
1927 : _("could not apply %s... %s"),
1928 short_commit_name(commit), msg.subject);
1929 print_advice(r, res == 1, opts);
1930 repo_rerere(r, opts->allow_rerere_auto);
1934 allow = allow_empty(r, opts, commit);
1939 flags |= ALLOW_EMPTY;
1940 if (!opts->no_commit) {
1941 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1942 res = do_commit(r, msg_file, author, opts, flags);
1944 res = error(_("unable to parse commit author"));
1945 *check_todo = !!(flags & EDIT_MSG);
1946 if (!res && reword) {
1948 res = run_git_commit(r, NULL, opts, EDIT_MSG |
1949 VERIFY_MSG | AMEND_MSG |
1950 (flags & ALLOW_EMPTY));
1956 if (!res && final_fixup) {
1957 unlink(rebase_path_fixup_msg());
1958 unlink(rebase_path_squash_msg());
1959 unlink(rebase_path_current_fixups());
1960 strbuf_reset(&opts->current_fixups);
1961 opts->current_fixup_count = 0;
1965 free_message(commit, &msg);
1967 update_abort_safety_file();
1972 static int prepare_revs(struct replay_opts *opts)
1975 * picking (but not reverting) ranges (but not individual revisions)
1976 * should be done in reverse
1978 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1979 opts->revs->reverse ^= 1;
1981 if (prepare_revision_walk(opts->revs))
1982 return error(_("revision walk setup failed"));
1987 static int read_and_refresh_cache(struct repository *r,
1988 struct replay_opts *opts)
1990 struct lock_file index_lock = LOCK_INIT;
1991 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
1992 if (repo_read_index(r) < 0) {
1993 rollback_lock_file(&index_lock);
1994 return error(_("git %s: failed to read the index"),
1995 _(action_name(opts)));
1997 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1998 if (index_fd >= 0) {
1999 if (write_locked_index(r->index, &index_lock,
2000 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2001 return error(_("git %s: failed to refresh the index"),
2002 _(action_name(opts)));
2008 enum todo_item_flags {
2009 TODO_EDIT_MERGE_MSG = 1
2012 void todo_list_release(struct todo_list *todo_list)
2014 strbuf_release(&todo_list->buf);
2015 FREE_AND_NULL(todo_list->items);
2016 todo_list->nr = todo_list->alloc = 0;
2019 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2021 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2022 return todo_list->items + todo_list->nr++;
2025 const char *todo_item_get_arg(struct todo_list *todo_list,
2026 struct todo_item *item)
2028 return todo_list->buf.buf + item->arg_offset;
2031 static int parse_insn_line(struct repository *r, struct todo_item *item,
2032 const char *buf, const char *bol, char *eol)
2034 struct object_id commit_oid;
2035 char *end_of_object_name;
2036 int i, saved, status, padding;
2041 bol += strspn(bol, " \t");
2043 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2044 item->command = TODO_COMMENT;
2045 item->commit = NULL;
2046 item->arg_offset = bol - buf;
2047 item->arg_len = eol - bol;
2051 for (i = 0; i < TODO_COMMENT; i++)
2052 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2055 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2056 *bol == todo_command_info[i].c) {
2061 if (i >= TODO_COMMENT)
2064 /* Eat up extra spaces/ tabs before object name */
2065 padding = strspn(bol, " \t");
2068 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2070 return error(_("%s does not accept arguments: '%s'"),
2071 command_to_string(item->command), bol);
2072 item->commit = NULL;
2073 item->arg_offset = bol - buf;
2074 item->arg_len = eol - bol;
2079 return error(_("missing arguments for %s"),
2080 command_to_string(item->command));
2082 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2083 item->command == TODO_RESET) {
2084 item->commit = NULL;
2085 item->arg_offset = bol - buf;
2086 item->arg_len = (int)(eol - bol);
2090 if (item->command == TODO_MERGE) {
2091 if (skip_prefix(bol, "-C", &bol))
2092 bol += strspn(bol, " \t");
2093 else if (skip_prefix(bol, "-c", &bol)) {
2094 bol += strspn(bol, " \t");
2095 item->flags |= TODO_EDIT_MERGE_MSG;
2097 item->flags |= TODO_EDIT_MERGE_MSG;
2098 item->commit = NULL;
2099 item->arg_offset = bol - buf;
2100 item->arg_len = (int)(eol - bol);
2105 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2106 saved = *end_of_object_name;
2107 *end_of_object_name = '\0';
2108 status = get_oid(bol, &commit_oid);
2109 *end_of_object_name = saved;
2111 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2112 item->arg_offset = bol - buf;
2113 item->arg_len = (int)(eol - bol);
2116 return error(_("could not parse '%.*s'"),
2117 (int)(end_of_object_name - bol), bol);
2119 item->commit = lookup_commit_reference(r, &commit_oid);
2120 return !item->commit;
2123 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2125 struct todo_item item;
2127 const char *todo_file;
2128 struct strbuf buf = STRBUF_INIT;
2131 todo_file = git_path_todo_file();
2132 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2133 if (errno == ENOENT)
2136 return error_errno("unable to open '%s'", todo_file);
2138 eol = strchrnul(buf.buf, '\n');
2139 if (buf.buf != eol && eol[-1] == '\r')
2140 eol--; /* strip Carriage Return */
2141 if (parse_insn_line(r, &item, buf.buf, buf.buf, eol))
2143 if (item.command == TODO_PICK)
2144 *action = REPLAY_PICK;
2145 else if (item.command == TODO_REVERT)
2146 *action = REPLAY_REVERT;
2153 strbuf_release(&buf);
2158 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2159 struct todo_list *todo_list)
2161 struct todo_item *item;
2162 char *p = buf, *next_p;
2163 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2165 todo_list->current = todo_list->nr = 0;
2167 for (i = 1; *p; i++, p = next_p) {
2168 char *eol = strchrnul(p, '\n');
2170 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2172 if (p != eol && eol[-1] == '\r')
2173 eol--; /* strip Carriage Return */
2175 item = append_new_todo(todo_list);
2176 item->offset_in_buf = p - todo_list->buf.buf;
2177 if (parse_insn_line(r, item, buf, p, eol)) {
2178 res = error(_("invalid line %d: %.*s"),
2179 i, (int)(eol - p), p);
2180 item->command = TODO_COMMENT + 1;
2181 item->arg_offset = p - buf;
2182 item->arg_len = (int)(eol - p);
2183 item->commit = NULL;
2188 else if (is_fixup(item->command))
2189 return error(_("cannot '%s' without a previous commit"),
2190 command_to_string(item->command));
2191 else if (!is_noop(item->command))
2198 static int count_commands(struct todo_list *todo_list)
2202 for (i = 0; i < todo_list->nr; i++)
2203 if (todo_list->items[i].command != TODO_COMMENT)
2209 static int get_item_line_offset(struct todo_list *todo_list, int index)
2211 return index < todo_list->nr ?
2212 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2215 static const char *get_item_line(struct todo_list *todo_list, int index)
2217 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2220 static int get_item_line_length(struct todo_list *todo_list, int index)
2222 return get_item_line_offset(todo_list, index + 1)
2223 - get_item_line_offset(todo_list, index);
2226 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2231 fd = open(path, O_RDONLY);
2233 return error_errno(_("could not open '%s'"), path);
2234 len = strbuf_read(sb, fd, 0);
2237 return error(_("could not read '%s'."), path);
2241 static int have_finished_the_last_pick(void)
2243 struct strbuf buf = STRBUF_INIT;
2245 const char *todo_path = git_path_todo_file();
2248 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2249 if (errno == ENOENT) {
2252 error_errno("unable to open '%s'", todo_path);
2256 /* If there is only one line then we are done */
2257 eol = strchr(buf.buf, '\n');
2258 if (!eol || !eol[1])
2261 strbuf_release(&buf);
2266 void sequencer_post_commit_cleanup(struct repository *r)
2268 struct replay_opts opts = REPLAY_OPTS_INIT;
2269 int need_cleanup = 0;
2271 if (file_exists(git_path_cherry_pick_head(r))) {
2272 unlink(git_path_cherry_pick_head(r));
2273 opts.action = REPLAY_PICK;
2277 if (file_exists(git_path_revert_head(r))) {
2278 unlink(git_path_revert_head(r));
2279 opts.action = REPLAY_REVERT;
2286 if (!have_finished_the_last_pick())
2289 sequencer_remove_state(&opts);
2292 static int read_populate_todo(struct repository *r,
2293 struct todo_list *todo_list,
2294 struct replay_opts *opts)
2297 const char *todo_file = get_todo_path(opts);
2300 strbuf_reset(&todo_list->buf);
2301 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2304 res = stat(todo_file, &st);
2306 return error(_("could not stat '%s'"), todo_file);
2307 fill_stat_data(&todo_list->stat, &st);
2309 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2311 if (is_rebase_i(opts))
2312 return error(_("please fix this using "
2313 "'git rebase --edit-todo'."));
2314 return error(_("unusable instruction sheet: '%s'"), todo_file);
2317 if (!todo_list->nr &&
2318 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2319 return error(_("no commits parsed."));
2321 if (!is_rebase_i(opts)) {
2322 enum todo_command valid =
2323 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2326 for (i = 0; i < todo_list->nr; i++)
2327 if (valid == todo_list->items[i].command)
2329 else if (valid == TODO_PICK)
2330 return error(_("cannot cherry-pick during a revert."));
2332 return error(_("cannot revert during a cherry-pick."));
2335 if (is_rebase_i(opts)) {
2336 struct todo_list done = TODO_LIST_INIT;
2337 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2339 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2340 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2341 todo_list->done_nr = count_commands(&done);
2343 todo_list->done_nr = 0;
2345 todo_list->total_nr = todo_list->done_nr
2346 + count_commands(todo_list);
2347 todo_list_release(&done);
2350 fprintf(f, "%d\n", todo_list->total_nr);
2358 static int git_config_string_dup(char **dest,
2359 const char *var, const char *value)
2362 return config_error_nonbool(var);
2364 *dest = xstrdup(value);
2368 static int populate_opts_cb(const char *key, const char *value, void *data)
2370 struct replay_opts *opts = data;
2375 else if (!strcmp(key, "options.no-commit"))
2376 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2377 else if (!strcmp(key, "options.edit"))
2378 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2379 else if (!strcmp(key, "options.allow-empty"))
2381 git_config_bool_or_int(key, value, &error_flag);
2382 else if (!strcmp(key, "options.allow-empty-message"))
2383 opts->allow_empty_message =
2384 git_config_bool_or_int(key, value, &error_flag);
2385 else if (!strcmp(key, "options.keep-redundant-commits"))
2386 opts->keep_redundant_commits =
2387 git_config_bool_or_int(key, value, &error_flag);
2388 else if (!strcmp(key, "options.signoff"))
2389 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2390 else if (!strcmp(key, "options.record-origin"))
2391 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2392 else if (!strcmp(key, "options.allow-ff"))
2393 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2394 else if (!strcmp(key, "options.mainline"))
2395 opts->mainline = git_config_int(key, value);
2396 else if (!strcmp(key, "options.strategy"))
2397 git_config_string_dup(&opts->strategy, key, value);
2398 else if (!strcmp(key, "options.gpg-sign"))
2399 git_config_string_dup(&opts->gpg_sign, key, value);
2400 else if (!strcmp(key, "options.strategy-option")) {
2401 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2402 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2403 } else if (!strcmp(key, "options.allow-rerere-auto"))
2404 opts->allow_rerere_auto =
2405 git_config_bool_or_int(key, value, &error_flag) ?
2406 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2407 else if (!strcmp(key, "options.default-msg-cleanup")) {
2408 opts->explicit_cleanup = 1;
2409 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2411 return error(_("invalid key: %s"), key);
2414 return error(_("invalid value for %s: %s"), key, value);
2419 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2422 char *strategy_opts_string = raw_opts;
2424 if (*strategy_opts_string == ' ')
2425 strategy_opts_string++;
2427 opts->xopts_nr = split_cmdline(strategy_opts_string,
2428 (const char ***)&opts->xopts);
2429 for (i = 0; i < opts->xopts_nr; i++) {
2430 const char *arg = opts->xopts[i];
2432 skip_prefix(arg, "--", &arg);
2433 opts->xopts[i] = xstrdup(arg);
2437 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2440 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2442 opts->strategy = strbuf_detach(buf, NULL);
2443 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2446 parse_strategy_opts(opts, buf->buf);
2449 static int read_populate_opts(struct replay_opts *opts)
2451 if (is_rebase_i(opts)) {
2452 struct strbuf buf = STRBUF_INIT;
2454 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2455 if (!starts_with(buf.buf, "-S"))
2458 free(opts->gpg_sign);
2459 opts->gpg_sign = xstrdup(buf.buf + 2);
2464 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2465 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2466 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2467 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2468 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2472 if (file_exists(rebase_path_verbose()))
2475 if (file_exists(rebase_path_quiet()))
2478 if (file_exists(rebase_path_signoff())) {
2483 if (file_exists(rebase_path_reschedule_failed_exec()))
2484 opts->reschedule_failed_exec = 1;
2486 read_strategy_opts(opts, &buf);
2487 strbuf_release(&buf);
2489 if (read_oneliner(&opts->current_fixups,
2490 rebase_path_current_fixups(), 1)) {
2491 const char *p = opts->current_fixups.buf;
2492 opts->current_fixup_count = 1;
2493 while ((p = strchr(p, '\n'))) {
2494 opts->current_fixup_count++;
2499 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2500 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2501 return error(_("unusable squash-onto"));
2502 opts->have_squash_onto = 1;
2508 if (!file_exists(git_path_opts_file()))
2511 * The function git_parse_source(), called from git_config_from_file(),
2512 * may die() in case of a syntactically incorrect file. We do not care
2513 * about this case, though, because we wrote that file ourselves, so we
2514 * are pretty certain that it is syntactically correct.
2516 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2517 return error(_("malformed options sheet: '%s'"),
2518 git_path_opts_file());
2522 static void write_strategy_opts(struct replay_opts *opts)
2525 struct strbuf buf = STRBUF_INIT;
2527 for (i = 0; i < opts->xopts_nr; ++i)
2528 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2530 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2531 strbuf_release(&buf);
2534 int write_basic_state(struct replay_opts *opts, const char *head_name,
2535 struct commit *onto, const char *orig_head)
2537 const char *quiet = getenv("GIT_QUIET");
2540 write_file(rebase_path_head_name(), "%s\n", head_name);
2542 write_file(rebase_path_onto(), "%s\n",
2543 oid_to_hex(&onto->object.oid));
2545 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2548 write_file(rebase_path_quiet(), "%s\n", quiet);
2550 write_file(rebase_path_verbose(), "%s", "");
2552 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2553 if (opts->xopts_nr > 0)
2554 write_strategy_opts(opts);
2556 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2557 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2558 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2559 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2562 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2564 write_file(rebase_path_signoff(), "--signoff\n");
2565 if (opts->reschedule_failed_exec)
2566 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2571 static int walk_revs_populate_todo(struct todo_list *todo_list,
2572 struct replay_opts *opts)
2574 enum todo_command command = opts->action == REPLAY_PICK ?
2575 TODO_PICK : TODO_REVERT;
2576 const char *command_string = todo_command_info[command].str;
2577 struct commit *commit;
2579 if (prepare_revs(opts))
2582 while ((commit = get_revision(opts->revs))) {
2583 struct todo_item *item = append_new_todo(todo_list);
2584 const char *commit_buffer = get_commit_buffer(commit, NULL);
2585 const char *subject;
2588 item->command = command;
2589 item->commit = commit;
2590 item->arg_offset = 0;
2592 item->offset_in_buf = todo_list->buf.len;
2593 subject_len = find_commit_subject(commit_buffer, &subject);
2594 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2595 short_commit_name(commit), subject_len, subject);
2596 unuse_commit_buffer(commit, commit_buffer);
2600 return error(_("empty commit set passed"));
2605 static int create_seq_dir(void)
2607 if (file_exists(git_path_seq_dir())) {
2608 error(_("a cherry-pick or revert is already in progress"));
2609 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2611 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2612 return error_errno(_("could not create sequencer directory '%s'"),
2613 git_path_seq_dir());
2617 static int save_head(const char *head)
2619 struct lock_file head_lock = LOCK_INIT;
2620 struct strbuf buf = STRBUF_INIT;
2624 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2626 return error_errno(_("could not lock HEAD"));
2627 strbuf_addf(&buf, "%s\n", head);
2628 written = write_in_full(fd, buf.buf, buf.len);
2629 strbuf_release(&buf);
2631 error_errno(_("could not write to '%s'"), git_path_head_file());
2632 rollback_lock_file(&head_lock);
2635 if (commit_lock_file(&head_lock) < 0)
2636 return error(_("failed to finalize '%s'"), git_path_head_file());
2640 static int rollback_is_safe(void)
2642 struct strbuf sb = STRBUF_INIT;
2643 struct object_id expected_head, actual_head;
2645 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2647 if (get_oid_hex(sb.buf, &expected_head)) {
2648 strbuf_release(&sb);
2649 die(_("could not parse %s"), git_path_abort_safety_file());
2651 strbuf_release(&sb);
2653 else if (errno == ENOENT)
2654 oidclr(&expected_head);
2656 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2658 if (get_oid("HEAD", &actual_head))
2659 oidclr(&actual_head);
2661 return oideq(&actual_head, &expected_head);
2664 static int reset_for_rollback(const struct object_id *oid)
2666 const char *argv[4]; /* reset --merge <arg> + NULL */
2669 argv[1] = "--merge";
2670 argv[2] = oid_to_hex(oid);
2672 return run_command_v_opt(argv, RUN_GIT_CMD);
2675 static int rollback_single_pick(struct repository *r)
2677 struct object_id head_oid;
2679 if (!file_exists(git_path_cherry_pick_head(r)) &&
2680 !file_exists(git_path_revert_head(r)))
2681 return error(_("no cherry-pick or revert in progress"));
2682 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2683 return error(_("cannot resolve HEAD"));
2684 if (is_null_oid(&head_oid))
2685 return error(_("cannot abort from a branch yet to be born"));
2686 return reset_for_rollback(&head_oid);
2689 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2692 struct object_id oid;
2693 struct strbuf buf = STRBUF_INIT;
2696 f = fopen(git_path_head_file(), "r");
2697 if (!f && errno == ENOENT) {
2699 * There is no multiple-cherry-pick in progress.
2700 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2701 * a single-cherry-pick in progress, abort that.
2703 return rollback_single_pick(r);
2706 return error_errno(_("cannot open '%s'"), git_path_head_file());
2707 if (strbuf_getline_lf(&buf, f)) {
2708 error(_("cannot read '%s': %s"), git_path_head_file(),
2709 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2714 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2715 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2716 git_path_head_file());
2719 if (is_null_oid(&oid)) {
2720 error(_("cannot abort from a branch yet to be born"));
2724 if (!rollback_is_safe()) {
2725 /* Do not error, just do not rollback */
2726 warning(_("You seem to have moved HEAD. "
2727 "Not rewinding, check your HEAD!"));
2729 if (reset_for_rollback(&oid))
2731 strbuf_release(&buf);
2732 return sequencer_remove_state(opts);
2734 strbuf_release(&buf);
2738 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2740 struct lock_file todo_lock = LOCK_INIT;
2741 const char *todo_path = get_todo_path(opts);
2742 int next = todo_list->current, offset, fd;
2745 * rebase -i writes "git-rebase-todo" without the currently executing
2746 * command, appending it to "done" instead.
2748 if (is_rebase_i(opts))
2751 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2753 return error_errno(_("could not lock '%s'"), todo_path);
2754 offset = get_item_line_offset(todo_list, next);
2755 if (write_in_full(fd, todo_list->buf.buf + offset,
2756 todo_list->buf.len - offset) < 0)
2757 return error_errno(_("could not write to '%s'"), todo_path);
2758 if (commit_lock_file(&todo_lock) < 0)
2759 return error(_("failed to finalize '%s'"), todo_path);
2761 if (is_rebase_i(opts) && next > 0) {
2762 const char *done = rebase_path_done();
2763 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2768 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2769 get_item_line_length(todo_list, next - 1))
2771 ret = error_errno(_("could not write to '%s'"), done);
2773 ret = error_errno(_("failed to finalize '%s'"), done);
2779 static int save_opts(struct replay_opts *opts)
2781 const char *opts_file = git_path_opts_file();
2784 if (opts->no_commit)
2785 res |= git_config_set_in_file_gently(opts_file,
2786 "options.no-commit", "true");
2788 res |= git_config_set_in_file_gently(opts_file,
2789 "options.edit", "true");
2790 if (opts->allow_empty)
2791 res |= git_config_set_in_file_gently(opts_file,
2792 "options.allow-empty", "true");
2793 if (opts->allow_empty_message)
2794 res |= git_config_set_in_file_gently(opts_file,
2795 "options.allow-empty-message", "true");
2796 if (opts->keep_redundant_commits)
2797 res |= git_config_set_in_file_gently(opts_file,
2798 "options.keep-redundant-commits", "true");
2800 res |= git_config_set_in_file_gently(opts_file,
2801 "options.signoff", "true");
2802 if (opts->record_origin)
2803 res |= git_config_set_in_file_gently(opts_file,
2804 "options.record-origin", "true");
2806 res |= git_config_set_in_file_gently(opts_file,
2807 "options.allow-ff", "true");
2808 if (opts->mainline) {
2809 struct strbuf buf = STRBUF_INIT;
2810 strbuf_addf(&buf, "%d", opts->mainline);
2811 res |= git_config_set_in_file_gently(opts_file,
2812 "options.mainline", buf.buf);
2813 strbuf_release(&buf);
2816 res |= git_config_set_in_file_gently(opts_file,
2817 "options.strategy", opts->strategy);
2819 res |= git_config_set_in_file_gently(opts_file,
2820 "options.gpg-sign", opts->gpg_sign);
2823 for (i = 0; i < opts->xopts_nr; i++)
2824 res |= git_config_set_multivar_in_file_gently(opts_file,
2825 "options.strategy-option",
2826 opts->xopts[i], "^$", 0);
2828 if (opts->allow_rerere_auto)
2829 res |= git_config_set_in_file_gently(opts_file,
2830 "options.allow-rerere-auto",
2831 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2834 if (opts->explicit_cleanup)
2835 res |= git_config_set_in_file_gently(opts_file,
2836 "options.default-msg-cleanup",
2837 describe_cleanup_mode(opts->default_msg_cleanup));
2841 static int make_patch(struct repository *r,
2842 struct commit *commit,
2843 struct replay_opts *opts)
2845 struct strbuf buf = STRBUF_INIT;
2846 struct rev_info log_tree_opt;
2847 const char *subject, *p;
2850 p = short_commit_name(commit);
2851 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2853 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2854 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2855 res |= error(_("could not update %s"), "REBASE_HEAD");
2857 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2858 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2859 repo_init_revisions(r, &log_tree_opt, NULL);
2860 log_tree_opt.abbrev = 0;
2861 log_tree_opt.diff = 1;
2862 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2863 log_tree_opt.disable_stdin = 1;
2864 log_tree_opt.no_commit_id = 1;
2865 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2866 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2867 if (!log_tree_opt.diffopt.file)
2868 res |= error_errno(_("could not open '%s'"), buf.buf);
2870 res |= log_tree_commit(&log_tree_opt, commit);
2871 fclose(log_tree_opt.diffopt.file);
2875 strbuf_addf(&buf, "%s/message", get_dir(opts));
2876 if (!file_exists(buf.buf)) {
2877 const char *commit_buffer = get_commit_buffer(commit, NULL);
2878 find_commit_subject(commit_buffer, &subject);
2879 res |= write_message(subject, strlen(subject), buf.buf, 1);
2880 unuse_commit_buffer(commit, commit_buffer);
2882 strbuf_release(&buf);
2887 static int intend_to_amend(void)
2889 struct object_id head;
2892 if (get_oid("HEAD", &head))
2893 return error(_("cannot read HEAD"));
2895 p = oid_to_hex(&head);
2896 return write_message(p, strlen(p), rebase_path_amend(), 1);
2899 static int error_with_patch(struct repository *r,
2900 struct commit *commit,
2901 const char *subject, int subject_len,
2902 struct replay_opts *opts,
2903 int exit_code, int to_amend)
2906 if (make_patch(r, commit, opts))
2908 } else if (copy_file(rebase_path_message(),
2909 git_path_merge_msg(r), 0666))
2910 return error(_("unable to copy '%s' to '%s'"),
2911 git_path_merge_msg(r), rebase_path_message());
2914 if (intend_to_amend())
2918 _("You can amend the commit now, with\n"
2920 " git commit --amend %s\n"
2922 "Once you are satisfied with your changes, run\n"
2924 " git rebase --continue\n"),
2925 gpg_sign_opt_quoted(opts));
2926 } else if (exit_code) {
2928 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2929 short_commit_name(commit), subject_len, subject);
2932 * We don't have the hash of the parent so
2933 * just print the line from the todo file.
2935 fprintf_ln(stderr, _("Could not merge %.*s"),
2936 subject_len, subject);
2942 static int error_failed_squash(struct repository *r,
2943 struct commit *commit,
2944 struct replay_opts *opts,
2946 const char *subject)
2948 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2949 return error(_("could not copy '%s' to '%s'"),
2950 rebase_path_squash_msg(), rebase_path_message());
2951 unlink(git_path_merge_msg(r));
2952 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
2953 return error(_("could not copy '%s' to '%s'"),
2954 rebase_path_message(),
2955 git_path_merge_msg(r));
2956 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
2959 static int do_exec(struct repository *r, const char *command_line)
2961 struct argv_array child_env = ARGV_ARRAY_INIT;
2962 const char *child_argv[] = { NULL, NULL };
2965 fprintf(stderr, "Executing: %s\n", command_line);
2966 child_argv[0] = command_line;
2967 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2968 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2969 absolute_path(get_git_work_tree()));
2970 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2973 /* force re-reading of the cache */
2974 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
2975 return error(_("could not read index"));
2977 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
2980 warning(_("execution failed: %s\n%s"
2981 "You can fix the problem, and then run\n"
2983 " git rebase --continue\n"
2986 dirty ? N_("and made changes to the index and/or the "
2987 "working tree\n") : "");
2989 /* command not found */
2992 warning(_("execution succeeded: %s\nbut "
2993 "left changes to the index and/or the working tree\n"
2994 "Commit or stash your changes, and then run\n"
2996 " git rebase --continue\n"
2997 "\n"), command_line);
3001 argv_array_clear(&child_env);
3006 static int safe_append(const char *filename, const char *fmt, ...)
3009 struct lock_file lock = LOCK_INIT;
3010 int fd = hold_lock_file_for_update(&lock, filename,
3011 LOCK_REPORT_ON_ERROR);
3012 struct strbuf buf = STRBUF_INIT;
3017 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3018 error_errno(_("could not read '%s'"), filename);
3019 rollback_lock_file(&lock);
3022 strbuf_complete(&buf, '\n');
3024 strbuf_vaddf(&buf, fmt, ap);
3027 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3028 error_errno(_("could not write to '%s'"), filename);
3029 strbuf_release(&buf);
3030 rollback_lock_file(&lock);
3033 if (commit_lock_file(&lock) < 0) {
3034 strbuf_release(&buf);
3035 rollback_lock_file(&lock);
3036 return error(_("failed to finalize '%s'"), filename);
3039 strbuf_release(&buf);
3043 static int do_label(struct repository *r, const char *name, int len)
3045 struct ref_store *refs = get_main_ref_store(r);
3046 struct ref_transaction *transaction;
3047 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3048 struct strbuf msg = STRBUF_INIT;
3050 struct object_id head_oid;
3052 if (len == 1 && *name == '#')
3053 return error(_("illegal label name: '%.*s'"), len, name);
3055 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3056 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
3058 transaction = ref_store_transaction_begin(refs, &err);
3060 error("%s", err.buf);
3062 } else if (get_oid("HEAD", &head_oid)) {
3063 error(_("could not read HEAD"));
3065 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3066 NULL, 0, msg.buf, &err) < 0 ||
3067 ref_transaction_commit(transaction, &err)) {
3068 error("%s", err.buf);
3071 ref_transaction_free(transaction);
3072 strbuf_release(&err);
3073 strbuf_release(&msg);
3076 ret = safe_append(rebase_path_refs_to_delete(),
3077 "%s\n", ref_name.buf);
3078 strbuf_release(&ref_name);
3083 static const char *reflog_message(struct replay_opts *opts,
3084 const char *sub_action, const char *fmt, ...);
3086 static int do_reset(struct repository *r,
3087 const char *name, int len,
3088 struct replay_opts *opts)
3090 struct strbuf ref_name = STRBUF_INIT;
3091 struct object_id oid;
3092 struct lock_file lock = LOCK_INIT;
3093 struct tree_desc desc;
3095 struct unpack_trees_options unpack_tree_opts;
3098 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3101 if (len == 10 && !strncmp("[new root]", name, len)) {
3102 if (!opts->have_squash_onto) {
3104 if (commit_tree("", 0, the_hash_algo->empty_tree,
3105 NULL, &opts->squash_onto,
3107 return error(_("writing fake root commit"));
3108 opts->have_squash_onto = 1;
3109 hex = oid_to_hex(&opts->squash_onto);
3110 if (write_message(hex, strlen(hex),
3111 rebase_path_squash_onto(), 0))
3112 return error(_("writing squash-onto"));
3114 oidcpy(&oid, &opts->squash_onto);
3118 /* Determine the length of the label */
3119 for (i = 0; i < len; i++)
3120 if (isspace(name[i]))
3124 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3125 if (get_oid(ref_name.buf, &oid) &&
3126 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3127 error(_("could not read '%s'"), ref_name.buf);
3128 rollback_lock_file(&lock);
3129 strbuf_release(&ref_name);
3134 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3135 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3136 unpack_tree_opts.head_idx = 1;
3137 unpack_tree_opts.src_index = r->index;
3138 unpack_tree_opts.dst_index = r->index;
3139 unpack_tree_opts.fn = oneway_merge;
3140 unpack_tree_opts.merge = 1;
3141 unpack_tree_opts.update = 1;
3143 if (repo_read_index_unmerged(r)) {
3144 rollback_lock_file(&lock);
3145 strbuf_release(&ref_name);
3146 return error_resolve_conflict(_(action_name(opts)));
3149 if (!fill_tree_descriptor(&desc, &oid)) {
3150 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3151 rollback_lock_file(&lock);
3152 free((void *)desc.buffer);
3153 strbuf_release(&ref_name);
3157 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3158 rollback_lock_file(&lock);
3159 free((void *)desc.buffer);
3160 strbuf_release(&ref_name);
3164 tree = parse_tree_indirect(&oid);
3165 prime_cache_tree(r, r->index, tree);
3167 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3168 ret = error(_("could not write index"));
3169 free((void *)desc.buffer);
3172 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3173 len, name), "HEAD", &oid,
3174 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3176 strbuf_release(&ref_name);
3180 static struct commit *lookup_label(const char *label, int len,
3183 struct commit *commit;
3186 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3187 commit = lookup_commit_reference_by_name(buf->buf);
3189 /* fall back to non-rewritten ref or commit */
3190 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3191 commit = lookup_commit_reference_by_name(buf->buf);
3195 error(_("could not resolve '%s'"), buf->buf);
3200 static int do_merge(struct repository *r,
3201 struct commit *commit,
3202 const char *arg, int arg_len,
3203 int flags, struct replay_opts *opts)
3205 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3206 EDIT_MSG | VERIFY_MSG : 0;
3207 struct strbuf ref_name = STRBUF_INIT;
3208 struct commit *head_commit, *merge_commit, *i;
3209 struct commit_list *bases, *j, *reversed = NULL;
3210 struct commit_list *to_merge = NULL, **tail = &to_merge;
3211 struct merge_options o;
3212 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3213 static struct lock_file lock;
3216 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3221 head_commit = lookup_commit_reference_by_name("HEAD");
3223 ret = error(_("cannot merge without a current revision"));
3228 * For octopus merges, the arg starts with the list of revisions to be
3229 * merged. The list is optionally followed by '#' and the oneline.
3231 merge_arg_len = oneline_offset = arg_len;
3232 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3235 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3236 p += 1 + strspn(p + 1, " \t\n");
3237 oneline_offset = p - arg;
3240 k = strcspn(p, " \t\n");
3243 merge_commit = lookup_label(p, k, &ref_name);
3244 if (!merge_commit) {
3245 ret = error(_("unable to parse '%.*s'"), k, p);
3248 tail = &commit_list_insert(merge_commit, tail)->next;
3250 merge_arg_len = p - arg;
3254 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3258 if (opts->have_squash_onto &&
3259 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3261 * When the user tells us to "merge" something into a
3262 * "[new root]", let's simply fast-forward to the merge head.
3264 rollback_lock_file(&lock);
3266 ret = error(_("octopus merge cannot be executed on "
3267 "top of a [new root]"));
3269 ret = fast_forward_to(r, &to_merge->item->object.oid,
3270 &head_commit->object.oid, 0,
3276 const char *message = get_commit_buffer(commit, NULL);
3281 ret = error(_("could not get commit message of '%s'"),
3282 oid_to_hex(&commit->object.oid));
3285 write_author_script(message);
3286 find_commit_subject(message, &body);
3288 ret = write_message(body, len, git_path_merge_msg(r), 0);
3289 unuse_commit_buffer(commit, message);
3291 error_errno(_("could not write '%s'"),
3292 git_path_merge_msg(r));
3296 struct strbuf buf = STRBUF_INIT;
3299 strbuf_addf(&buf, "author %s", git_author_info(0));
3300 write_author_script(buf.buf);
3303 if (oneline_offset < arg_len) {
3304 p = arg + oneline_offset;
3305 len = arg_len - oneline_offset;
3307 strbuf_addf(&buf, "Merge %s '%.*s'",
3308 to_merge->next ? "branches" : "branch",
3309 merge_arg_len, arg);
3314 ret = write_message(p, len, git_path_merge_msg(r), 0);
3315 strbuf_release(&buf);
3317 error_errno(_("could not write '%s'"),
3318 git_path_merge_msg(r));
3324 * If HEAD is not identical to the first parent of the original merge
3325 * commit, we cannot fast-forward.
3327 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3328 oideq(&commit->parents->item->object.oid,
3329 &head_commit->object.oid);
3332 * If any merge head is different from the original one, we cannot
3335 if (can_fast_forward) {
3336 struct commit_list *p = commit->parents->next;
3338 for (j = to_merge; j && p; j = j->next, p = p->next)
3339 if (!oideq(&j->item->object.oid,
3340 &p->item->object.oid)) {
3341 can_fast_forward = 0;
3345 * If the number of merge heads differs from the original merge
3346 * commit, we cannot fast-forward.
3349 can_fast_forward = 0;
3352 if (can_fast_forward) {
3353 rollback_lock_file(&lock);
3354 ret = fast_forward_to(r, &commit->object.oid,
3355 &head_commit->object.oid, 0, opts);
3359 if (to_merge->next) {
3361 struct child_process cmd = CHILD_PROCESS_INIT;
3363 if (read_env_script(&cmd.env_array)) {
3364 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3366 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3371 argv_array_push(&cmd.args, "merge");
3372 argv_array_push(&cmd.args, "-s");
3373 argv_array_push(&cmd.args, "octopus");
3374 argv_array_push(&cmd.args, "--no-edit");
3375 argv_array_push(&cmd.args, "--no-ff");
3376 argv_array_push(&cmd.args, "--no-log");
3377 argv_array_push(&cmd.args, "--no-stat");
3378 argv_array_push(&cmd.args, "-F");
3379 argv_array_push(&cmd.args, git_path_merge_msg(r));
3381 argv_array_push(&cmd.args, opts->gpg_sign);
3383 /* Add the tips to be merged */
3384 for (j = to_merge; j; j = j->next)
3385 argv_array_push(&cmd.args,
3386 oid_to_hex(&j->item->object.oid));
3388 strbuf_release(&ref_name);
3389 unlink(git_path_cherry_pick_head(r));
3390 rollback_lock_file(&lock);
3392 rollback_lock_file(&lock);
3393 ret = run_command(&cmd);
3395 /* force re-reading of the cache */
3396 if (!ret && (discard_index(r->index) < 0 ||
3397 repo_read_index(r) < 0))
3398 ret = error(_("could not read index"));
3402 merge_commit = to_merge->item;
3403 bases = get_merge_bases(head_commit, merge_commit);
3404 if (bases && oideq(&merge_commit->object.oid,
3405 &bases->item->object.oid)) {
3407 /* skip merging an ancestor of HEAD */
3411 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3412 git_path_merge_head(r), 0);
3413 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3415 for (j = bases; j; j = j->next)
3416 commit_list_insert(j->item, &reversed);
3417 free_commit_list(bases);
3420 init_merge_options(&o, r);
3422 o.branch2 = ref_name.buf;
3423 o.buffer_output = 2;
3425 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3427 fputs(o.obuf.buf, stdout);
3428 strbuf_release(&o.obuf);
3430 error(_("could not even attempt to merge '%.*s'"),
3431 merge_arg_len, arg);
3435 * The return value of merge_recursive() is 1 on clean, and 0 on
3438 * Let's reverse that, so that do_merge() returns 0 upon success and
3439 * 1 upon failed merge (keeping the return value -1 for the cases where
3440 * we will want to reschedule the `merge` command).
3444 if (r->index->cache_changed &&
3445 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3446 ret = error(_("merge: Unable to write new index file"));
3450 rollback_lock_file(&lock);
3452 repo_rerere(r, opts->allow_rerere_auto);
3455 * In case of problems, we now want to return a positive
3456 * value (a negative one would indicate that the `merge`
3457 * command needs to be rescheduled).
3459 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3463 strbuf_release(&ref_name);
3464 rollback_lock_file(&lock);
3465 free_commit_list(to_merge);
3469 static int is_final_fixup(struct todo_list *todo_list)
3471 int i = todo_list->current;
3473 if (!is_fixup(todo_list->items[i].command))
3476 while (++i < todo_list->nr)
3477 if (is_fixup(todo_list->items[i].command))
3479 else if (!is_noop(todo_list->items[i].command))
3484 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3488 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3489 if (!is_noop(todo_list->items[i].command))
3490 return todo_list->items[i].command;
3495 static int apply_autostash(struct replay_opts *opts)
3497 struct strbuf stash_sha1 = STRBUF_INIT;
3498 struct child_process child = CHILD_PROCESS_INIT;
3501 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3502 strbuf_release(&stash_sha1);
3505 strbuf_trim(&stash_sha1);
3508 child.no_stdout = 1;
3509 child.no_stderr = 1;
3510 argv_array_push(&child.args, "stash");
3511 argv_array_push(&child.args, "apply");
3512 argv_array_push(&child.args, stash_sha1.buf);
3513 if (!run_command(&child))
3514 fprintf(stderr, _("Applied autostash.\n"));
3516 struct child_process store = CHILD_PROCESS_INIT;
3519 argv_array_push(&store.args, "stash");
3520 argv_array_push(&store.args, "store");
3521 argv_array_push(&store.args, "-m");
3522 argv_array_push(&store.args, "autostash");
3523 argv_array_push(&store.args, "-q");
3524 argv_array_push(&store.args, stash_sha1.buf);
3525 if (run_command(&store))
3526 ret = error(_("cannot store %s"), stash_sha1.buf);
3529 _("Applying autostash resulted in conflicts.\n"
3530 "Your changes are safe in the stash.\n"
3531 "You can run \"git stash pop\" or"
3532 " \"git stash drop\" at any time.\n"));
3535 strbuf_release(&stash_sha1);
3539 static const char *reflog_message(struct replay_opts *opts,
3540 const char *sub_action, const char *fmt, ...)
3543 static struct strbuf buf = STRBUF_INIT;
3547 strbuf_addstr(&buf, action_name(opts));
3549 strbuf_addf(&buf, " (%s)", sub_action);
3551 strbuf_addstr(&buf, ": ");
3552 strbuf_vaddf(&buf, fmt, ap);
3559 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3560 const char *commit, const char *action)
3562 struct child_process cmd = CHILD_PROCESS_INIT;
3567 argv_array_push(&cmd.args, "checkout");
3568 argv_array_push(&cmd.args, commit);
3569 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3572 ret = run_command(&cmd);
3574 ret = run_command_silent_on_success(&cmd);
3577 discard_index(r->index);
3582 int prepare_branch_to_be_rebased(struct repository *r, struct replay_opts *opts,
3587 if (commit && *commit) {
3588 action = reflog_message(opts, "start", "checkout %s", commit);
3589 if (run_git_checkout(r, opts, commit, action))
3590 return error(_("could not checkout %s"), commit);
3596 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3597 const char *onto_name, const struct object_id *onto,
3598 const char *orig_head)
3600 struct object_id oid;
3601 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3603 if (get_oid(orig_head, &oid))
3604 return error(_("%s: not a valid OID"), orig_head);
3606 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3607 apply_autostash(opts);
3608 sequencer_remove_state(opts);
3609 return error(_("could not detach HEAD"));
3612 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3615 static int stopped_at_head(struct repository *r)
3617 struct object_id head;
3618 struct commit *commit;
3619 struct commit_message message;
3621 if (get_oid("HEAD", &head) ||
3622 !(commit = lookup_commit(r, &head)) ||
3623 parse_commit(commit) || get_message(commit, &message))
3624 fprintf(stderr, _("Stopped at HEAD\n"));
3626 fprintf(stderr, _("Stopped at %s\n"), message.label);
3627 free_message(commit, &message);
3633 static const char rescheduled_advice[] =
3634 N_("Could not execute the todo command\n"
3638 "It has been rescheduled; To edit the command before continuing, please\n"
3639 "edit the todo list first:\n"
3641 " git rebase --edit-todo\n"
3642 " git rebase --continue\n");
3644 static int pick_commits(struct repository *r,
3645 struct todo_list *todo_list,
3646 struct replay_opts *opts)
3648 int res = 0, reschedule = 0;
3650 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3652 assert(!(opts->signoff || opts->no_commit ||
3653 opts->record_origin || opts->edit));
3654 if (read_and_refresh_cache(r, opts))
3657 while (todo_list->current < todo_list->nr) {
3658 struct todo_item *item = todo_list->items + todo_list->current;
3659 const char *arg = todo_item_get_arg(todo_list, item);
3662 if (save_todo(todo_list, opts))
3664 if (is_rebase_i(opts)) {
3665 if (item->command != TODO_COMMENT) {
3666 FILE *f = fopen(rebase_path_msgnum(), "w");
3668 todo_list->done_nr++;
3671 fprintf(f, "%d\n", todo_list->done_nr);
3675 fprintf(stderr, "Rebasing (%d/%d)%s",
3677 todo_list->total_nr,
3678 opts->verbose ? "\n" : "\r");
3680 unlink(rebase_path_message());
3681 unlink(rebase_path_author_script());
3682 unlink(rebase_path_stopped_sha());
3683 unlink(rebase_path_amend());
3684 unlink(git_path_merge_head(the_repository));
3685 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3687 if (item->command == TODO_BREAK) {
3690 return stopped_at_head(r);
3693 if (item->command <= TODO_SQUASH) {
3694 if (is_rebase_i(opts))
3695 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3696 command_to_string(item->command), NULL),
3698 res = do_pick_commit(r, item->command, item->commit,
3699 opts, is_final_fixup(todo_list),
3701 if (is_rebase_i(opts) && res < 0) {
3703 advise(_(rescheduled_advice),
3704 get_item_line_length(todo_list,
3705 todo_list->current),
3706 get_item_line(todo_list,
3707 todo_list->current));
3708 todo_list->current--;
3709 if (save_todo(todo_list, opts))
3712 if (item->command == TODO_EDIT) {
3713 struct commit *commit = item->commit;
3718 _("Stopped at %s... %.*s\n"),
3719 short_commit_name(commit),
3720 item->arg_len, arg);
3722 return error_with_patch(r, commit,
3723 arg, item->arg_len, opts, res, !res);
3725 if (is_rebase_i(opts) && !res)
3726 record_in_rewritten(&item->commit->object.oid,
3727 peek_command(todo_list, 1));
3728 if (res && is_fixup(item->command)) {
3731 return error_failed_squash(r, item->commit, opts,
3732 item->arg_len, arg);
3733 } else if (res && is_rebase_i(opts) && item->commit) {
3735 struct object_id oid;
3738 * If we are rewording and have either
3739 * fast-forwarded already, or are about to
3740 * create a new root commit, we want to amend,
3741 * otherwise we do not.
3743 if (item->command == TODO_REWORD &&
3744 !get_oid("HEAD", &oid) &&
3745 (oideq(&item->commit->object.oid, &oid) ||
3746 (opts->have_squash_onto &&
3747 oideq(&opts->squash_onto, &oid))))
3750 return res | error_with_patch(r, item->commit,
3751 arg, item->arg_len, opts,
3754 } else if (item->command == TODO_EXEC) {
3755 char *end_of_arg = (char *)(arg + item->arg_len);
3756 int saved = *end_of_arg;
3761 res = do_exec(r, arg);
3762 *end_of_arg = saved;
3765 if (opts->reschedule_failed_exec)
3769 } else if (item->command == TODO_LABEL) {
3770 if ((res = do_label(r, arg, item->arg_len)))
3772 } else if (item->command == TODO_RESET) {
3773 if ((res = do_reset(r, arg, item->arg_len, opts)))
3775 } else if (item->command == TODO_MERGE) {
3776 if ((res = do_merge(r, item->commit,
3778 item->flags, opts)) < 0)
3780 else if (item->commit)
3781 record_in_rewritten(&item->commit->object.oid,
3782 peek_command(todo_list, 1));
3784 /* failed with merge conflicts */
3785 return error_with_patch(r, item->commit,
3788 } else if (!is_noop(item->command))
3789 return error(_("unknown command %d"), item->command);
3792 advise(_(rescheduled_advice),
3793 get_item_line_length(todo_list,
3794 todo_list->current),
3795 get_item_line(todo_list, todo_list->current));
3796 todo_list->current--;
3797 if (save_todo(todo_list, opts))
3800 return error_with_patch(r,
3804 } else if (check_todo && !res) {
3807 if (stat(get_todo_path(opts), &st)) {
3808 res = error_errno(_("could not stat '%s'"),
3809 get_todo_path(opts));
3810 } else if (match_stat_data(&todo_list->stat, &st)) {
3811 /* Reread the todo file if it has changed. */
3812 todo_list_release(todo_list);
3813 if (read_populate_todo(r, todo_list, opts))
3814 res = -1; /* message was printed */
3815 /* `current` will be incremented below */
3816 todo_list->current = -1;
3820 todo_list->current++;
3825 if (is_rebase_i(opts)) {
3826 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3829 /* Stopped in the middle, as planned? */
3830 if (todo_list->current < todo_list->nr)
3833 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3834 starts_with(head_ref.buf, "refs/")) {
3836 struct object_id head, orig;
3839 if (get_oid("HEAD", &head)) {
3840 res = error(_("cannot read HEAD"));
3842 strbuf_release(&head_ref);
3843 strbuf_release(&buf);
3846 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3847 get_oid_hex(buf.buf, &orig)) {
3848 res = error(_("could not read orig-head"));
3849 goto cleanup_head_ref;
3852 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3853 res = error(_("could not read 'onto'"));
3854 goto cleanup_head_ref;
3856 msg = reflog_message(opts, "finish", "%s onto %s",
3857 head_ref.buf, buf.buf);
3858 if (update_ref(msg, head_ref.buf, &head, &orig,
3859 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3860 res = error(_("could not update %s"),
3862 goto cleanup_head_ref;
3864 msg = reflog_message(opts, "finish", "returning to %s",
3866 if (create_symref("HEAD", head_ref.buf, msg)) {
3867 res = error(_("could not update HEAD to %s"),
3869 goto cleanup_head_ref;
3874 if (opts->verbose) {
3875 struct rev_info log_tree_opt;
3876 struct object_id orig, head;
3878 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3879 repo_init_revisions(r, &log_tree_opt, NULL);
3880 log_tree_opt.diff = 1;
3881 log_tree_opt.diffopt.output_format =
3882 DIFF_FORMAT_DIFFSTAT;
3883 log_tree_opt.disable_stdin = 1;
3885 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3886 !get_oid(buf.buf, &orig) &&
3887 !get_oid("HEAD", &head)) {
3888 diff_tree_oid(&orig, &head, "",
3889 &log_tree_opt.diffopt);
3890 log_tree_diff_flush(&log_tree_opt);
3893 flush_rewritten_pending();
3894 if (!stat(rebase_path_rewritten_list(), &st) &&
3896 struct child_process child = CHILD_PROCESS_INIT;
3897 const char *post_rewrite_hook =
3898 find_hook("post-rewrite");
3900 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3902 argv_array_push(&child.args, "notes");
3903 argv_array_push(&child.args, "copy");
3904 argv_array_push(&child.args, "--for-rewrite=rebase");
3905 /* we don't care if this copying failed */
3906 run_command(&child);
3908 if (post_rewrite_hook) {
3909 struct child_process hook = CHILD_PROCESS_INIT;
3911 hook.in = open(rebase_path_rewritten_list(),
3913 hook.stdout_to_stderr = 1;
3914 hook.trace2_hook_name = "post-rewrite";
3915 argv_array_push(&hook.args, post_rewrite_hook);
3916 argv_array_push(&hook.args, "rebase");
3917 /* we don't care if this hook failed */
3921 apply_autostash(opts);
3927 "Successfully rebased and updated %s.\n",
3931 strbuf_release(&buf);
3932 strbuf_release(&head_ref);
3936 * Sequence of picks finished successfully; cleanup by
3937 * removing the .git/sequencer directory
3939 return sequencer_remove_state(opts);
3942 static int continue_single_pick(struct repository *r)
3944 const char *argv[] = { "commit", NULL };
3946 if (!file_exists(git_path_cherry_pick_head(r)) &&
3947 !file_exists(git_path_revert_head(r)))
3948 return error(_("no cherry-pick or revert in progress"));
3949 return run_command_v_opt(argv, RUN_GIT_CMD);
3952 static int commit_staged_changes(struct repository *r,
3953 struct replay_opts *opts,
3954 struct todo_list *todo_list)
3956 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3957 unsigned int final_fixup = 0, is_clean;
3959 if (has_unstaged_changes(r, 1))
3960 return error(_("cannot rebase: You have unstaged changes."));
3962 is_clean = !has_uncommitted_changes(r, 0);
3964 if (file_exists(rebase_path_amend())) {
3965 struct strbuf rev = STRBUF_INIT;
3966 struct object_id head, to_amend;
3968 if (get_oid("HEAD", &head))
3969 return error(_("cannot amend non-existing commit"));
3970 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3971 return error(_("invalid file: '%s'"), rebase_path_amend());
3972 if (get_oid_hex(rev.buf, &to_amend))
3973 return error(_("invalid contents: '%s'"),
3974 rebase_path_amend());
3975 if (!is_clean && !oideq(&head, &to_amend))
3976 return error(_("\nYou have uncommitted changes in your "
3977 "working tree. Please, commit them\n"
3978 "first and then run 'git rebase "
3979 "--continue' again."));
3981 * When skipping a failed fixup/squash, we need to edit the
3982 * commit message, the current fixup list and count, and if it
3983 * was the last fixup/squash in the chain, we need to clean up
3984 * the commit message and if there was a squash, let the user
3987 if (!is_clean || !opts->current_fixup_count)
3988 ; /* this is not the final fixup */
3989 else if (!oideq(&head, &to_amend) ||
3990 !file_exists(rebase_path_stopped_sha())) {
3991 /* was a final fixup or squash done manually? */
3992 if (!is_fixup(peek_command(todo_list, 0))) {
3993 unlink(rebase_path_fixup_msg());
3994 unlink(rebase_path_squash_msg());
3995 unlink(rebase_path_current_fixups());
3996 strbuf_reset(&opts->current_fixups);
3997 opts->current_fixup_count = 0;
4000 /* we are in a fixup/squash chain */
4001 const char *p = opts->current_fixups.buf;
4002 int len = opts->current_fixups.len;
4004 opts->current_fixup_count--;
4006 BUG("Incorrect current_fixups:\n%s", p);
4007 while (len && p[len - 1] != '\n')
4009 strbuf_setlen(&opts->current_fixups, len);
4010 if (write_message(p, len, rebase_path_current_fixups(),
4012 return error(_("could not write file: '%s'"),
4013 rebase_path_current_fixups());
4016 * If a fixup/squash in a fixup/squash chain failed, the
4017 * commit message is already correct, no need to commit
4020 * Only if it is the final command in the fixup/squash
4021 * chain, and only if the chain is longer than a single
4022 * fixup/squash command (which was just skipped), do we
4023 * actually need to re-commit with a cleaned up commit
4026 if (opts->current_fixup_count > 0 &&
4027 !is_fixup(peek_command(todo_list, 0))) {
4030 * If there was not a single "squash" in the
4031 * chain, we only need to clean up the commit
4032 * message, no need to bother the user with
4033 * opening the commit message in the editor.
4035 if (!starts_with(p, "squash ") &&
4036 !strstr(p, "\nsquash "))
4037 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4038 } else if (is_fixup(peek_command(todo_list, 0))) {
4040 * We need to update the squash message to skip
4041 * the latest commit message.
4043 struct commit *commit;
4044 const char *path = rebase_path_squash_msg();
4046 if (parse_head(r, &commit) ||
4047 !(p = get_commit_buffer(commit, NULL)) ||
4048 write_message(p, strlen(p), path, 0)) {
4049 unuse_commit_buffer(commit, p);
4050 return error(_("could not write file: "
4053 unuse_commit_buffer(commit, p);
4057 strbuf_release(&rev);
4062 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4064 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4065 return error(_("could not remove CHERRY_PICK_HEAD"));
4070 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4072 return error(_("could not commit staged changes."));
4073 unlink(rebase_path_amend());
4074 unlink(git_path_merge_head(the_repository));
4076 unlink(rebase_path_fixup_msg());
4077 unlink(rebase_path_squash_msg());
4079 if (opts->current_fixup_count > 0) {
4081 * Whether final fixup or not, we just cleaned up the commit
4084 unlink(rebase_path_current_fixups());
4085 strbuf_reset(&opts->current_fixups);
4086 opts->current_fixup_count = 0;
4091 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4093 struct todo_list todo_list = TODO_LIST_INIT;
4096 if (read_and_refresh_cache(r, opts))
4099 if (read_populate_opts(opts))
4101 if (is_rebase_i(opts)) {
4102 if ((res = read_populate_todo(r, &todo_list, opts)))
4103 goto release_todo_list;
4104 if (commit_staged_changes(r, opts, &todo_list))
4106 } else if (!file_exists(get_todo_path(opts)))
4107 return continue_single_pick(r);
4108 else if ((res = read_populate_todo(r, &todo_list, opts)))
4109 goto release_todo_list;
4111 if (!is_rebase_i(opts)) {
4112 /* Verify that the conflict has been resolved */
4113 if (file_exists(git_path_cherry_pick_head(r)) ||
4114 file_exists(git_path_revert_head(r))) {
4115 res = continue_single_pick(r);
4117 goto release_todo_list;
4119 if (index_differs_from(r, "HEAD", NULL, 0)) {
4120 res = error_dirty_index(r, opts);
4121 goto release_todo_list;
4123 todo_list.current++;
4124 } else if (file_exists(rebase_path_stopped_sha())) {
4125 struct strbuf buf = STRBUF_INIT;
4126 struct object_id oid;
4128 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4129 !get_oid_committish(buf.buf, &oid))
4130 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4131 strbuf_release(&buf);
4134 res = pick_commits(r, &todo_list, opts);
4136 todo_list_release(&todo_list);
4140 static int single_pick(struct repository *r,
4141 struct commit *cmit,
4142 struct replay_opts *opts)
4146 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4147 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4148 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4152 int sequencer_pick_revisions(struct repository *r,
4153 struct replay_opts *opts)
4155 struct todo_list todo_list = TODO_LIST_INIT;
4156 struct object_id oid;
4160 if (read_and_refresh_cache(r, opts))
4163 for (i = 0; i < opts->revs->pending.nr; i++) {
4164 struct object_id oid;
4165 const char *name = opts->revs->pending.objects[i].name;
4167 /* This happens when using --stdin. */
4171 if (!get_oid(name, &oid)) {
4172 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4173 enum object_type type = oid_object_info(r,
4176 return error(_("%s: can't cherry-pick a %s"),
4177 name, type_name(type));
4180 return error(_("%s: bad revision"), name);
4184 * If we were called as "git cherry-pick <commit>", just
4185 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4186 * REVERT_HEAD, and don't touch the sequencer state.
4187 * This means it is possible to cherry-pick in the middle
4188 * of a cherry-pick sequence.
4190 if (opts->revs->cmdline.nr == 1 &&
4191 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4192 opts->revs->no_walk &&
4193 !opts->revs->cmdline.rev->flags) {
4194 struct commit *cmit;
4195 if (prepare_revision_walk(opts->revs))
4196 return error(_("revision walk setup failed"));
4197 cmit = get_revision(opts->revs);
4199 return error(_("empty commit set passed"));
4200 if (get_revision(opts->revs))
4201 BUG("unexpected extra commit from walk");
4202 return single_pick(r, cmit, opts);
4206 * Start a new cherry-pick/ revert sequence; but
4207 * first, make sure that an existing one isn't in
4211 if (walk_revs_populate_todo(&todo_list, opts) ||
4212 create_seq_dir() < 0)
4214 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4215 return error(_("can't revert as initial commit"));
4216 if (save_head(oid_to_hex(&oid)))
4218 if (save_opts(opts))
4220 update_abort_safety_file();
4221 res = pick_commits(r, &todo_list, opts);
4222 todo_list_release(&todo_list);
4226 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4228 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4229 struct strbuf sob = STRBUF_INIT;
4232 strbuf_addstr(&sob, sign_off_header);
4233 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4234 strbuf_addch(&sob, '\n');
4237 strbuf_complete_line(msgbuf);
4240 * If the whole message buffer is equal to the sob, pretend that we
4241 * found a conforming footer with a matching sob
4243 if (msgbuf->len - ignore_footer == sob.len &&
4244 !strncmp(msgbuf->buf, sob.buf, sob.len))
4247 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4250 const char *append_newlines = NULL;
4251 size_t len = msgbuf->len - ignore_footer;
4255 * The buffer is completely empty. Leave foom for
4256 * the title and body to be filled in by the user.
4258 append_newlines = "\n\n";
4259 } else if (len == 1) {
4261 * Buffer contains a single newline. Add another
4262 * so that we leave room for the title and body.
4264 append_newlines = "\n";
4265 } else if (msgbuf->buf[len - 2] != '\n') {
4267 * Buffer ends with a single newline. Add another
4268 * so that there is an empty line between the message
4271 append_newlines = "\n";
4272 } /* else, the buffer already ends with two newlines. */
4274 if (append_newlines)
4275 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4276 append_newlines, strlen(append_newlines));
4279 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4280 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4283 strbuf_release(&sob);
4286 struct labels_entry {
4287 struct hashmap_entry entry;
4288 char label[FLEX_ARRAY];
4291 static int labels_cmp(const void *fndata, const struct labels_entry *a,
4292 const struct labels_entry *b, const void *key)
4294 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4297 struct string_entry {
4298 struct oidmap_entry entry;
4299 char string[FLEX_ARRAY];
4302 struct label_state {
4303 struct oidmap commit2label;
4304 struct hashmap labels;
4308 static const char *label_oid(struct object_id *oid, const char *label,
4309 struct label_state *state)
4311 struct labels_entry *labels_entry;
4312 struct string_entry *string_entry;
4313 struct object_id dummy;
4317 string_entry = oidmap_get(&state->commit2label, oid);
4319 return string_entry->string;
4322 * For "uninteresting" commits, i.e. commits that are not to be
4323 * rebased, and which can therefore not be labeled, we use a unique
4324 * abbreviation of the commit name. This is slightly more complicated
4325 * than calling find_unique_abbrev() because we also need to make
4326 * sure that the abbreviation does not conflict with any other
4329 * We disallow "interesting" commits to be labeled by a string that
4330 * is a valid full-length hash, to ensure that we always can find an
4331 * abbreviation for any uninteresting commit's names that does not
4332 * clash with any other label.
4337 strbuf_reset(&state->buf);
4338 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4339 label = p = state->buf.buf;
4341 find_unique_abbrev_r(p, oid, default_abbrev);
4344 * We may need to extend the abbreviated hash so that there is
4345 * no conflicting label.
4347 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4348 size_t i = strlen(p) + 1;
4350 oid_to_hex_r(p, oid);
4351 for (; i < GIT_SHA1_HEXSZ; i++) {
4354 if (!hashmap_get_from_hash(&state->labels,
4360 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
4361 !get_oid_hex(label, &dummy)) ||
4362 (len == 1 && *label == '#') ||
4363 hashmap_get_from_hash(&state->labels,
4364 strihash(label), label)) {
4366 * If the label already exists, or if the label is a valid full
4367 * OID, or the label is a '#' (which we use as a separator
4368 * between merge heads and oneline), we append a dash and a
4369 * number to make it unique.
4371 struct strbuf *buf = &state->buf;
4374 strbuf_add(buf, label, len);
4376 for (i = 2; ; i++) {
4377 strbuf_setlen(buf, len);
4378 strbuf_addf(buf, "-%d", i);
4379 if (!hashmap_get_from_hash(&state->labels,
4388 FLEX_ALLOC_STR(labels_entry, label, label);
4389 hashmap_entry_init(labels_entry, strihash(label));
4390 hashmap_add(&state->labels, labels_entry);
4392 FLEX_ALLOC_STR(string_entry, string, label);
4393 oidcpy(&string_entry->entry.oid, oid);
4394 oidmap_put(&state->commit2label, string_entry);
4396 return string_entry->string;
4399 static int make_script_with_merges(struct pretty_print_context *pp,
4400 struct rev_info *revs, struct strbuf *out,
4403 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4404 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4405 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4406 struct strbuf label = STRBUF_INIT;
4407 struct commit_list *commits = NULL, **tail = &commits, *iter;
4408 struct commit_list *tips = NULL, **tips_tail = &tips;
4409 struct commit *commit;
4410 struct oidmap commit2todo = OIDMAP_INIT;
4411 struct string_entry *entry;
4412 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4413 shown = OIDSET_INIT;
4414 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4416 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4417 const char *cmd_pick = abbr ? "p" : "pick",
4418 *cmd_label = abbr ? "l" : "label",
4419 *cmd_reset = abbr ? "t" : "reset",
4420 *cmd_merge = abbr ? "m" : "merge";
4422 oidmap_init(&commit2todo, 0);
4423 oidmap_init(&state.commit2label, 0);
4424 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4425 strbuf_init(&state.buf, 32);
4427 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4428 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4429 FLEX_ALLOC_STR(entry, string, "onto");
4430 oidcpy(&entry->entry.oid, oid);
4431 oidmap_put(&state.commit2label, entry);
4436 * - get onelines for all commits
4437 * - gather all branch tips (i.e. 2nd or later parents of merges)
4438 * - label all branch tips
4440 while ((commit = get_revision(revs))) {
4441 struct commit_list *to_merge;
4442 const char *p1, *p2;
4443 struct object_id *oid;
4446 tail = &commit_list_insert(commit, tail)->next;
4447 oidset_insert(&interesting, &commit->object.oid);
4449 is_empty = is_original_commit_empty(commit);
4450 if (!is_empty && (commit->object.flags & PATCHSAME))
4453 strbuf_reset(&oneline);
4454 pretty_print_commit(pp, commit, &oneline);
4456 to_merge = commit->parents ? commit->parents->next : NULL;
4458 /* non-merge commit: easy case */
4460 if (!keep_empty && is_empty)
4461 strbuf_addf(&buf, "%c ", comment_line_char);
4462 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4463 oid_to_hex(&commit->object.oid),
4466 FLEX_ALLOC_STR(entry, string, buf.buf);
4467 oidcpy(&entry->entry.oid, &commit->object.oid);
4468 oidmap_put(&commit2todo, entry);
4473 /* Create a label */
4474 strbuf_reset(&label);
4475 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4476 (p1 = strchr(p1, '\'')) &&
4477 (p2 = strchr(++p1, '\'')))
4478 strbuf_add(&label, p1, p2 - p1);
4479 else if (skip_prefix(oneline.buf, "Merge pull request ",
4481 (p1 = strstr(p1, " from ")))
4482 strbuf_addstr(&label, p1 + strlen(" from "));
4484 strbuf_addbuf(&label, &oneline);
4486 for (p1 = label.buf; *p1; p1++)
4491 strbuf_addf(&buf, "%s -C %s",
4492 cmd_merge, oid_to_hex(&commit->object.oid));
4494 /* label the tips of merged branches */
4495 for (; to_merge; to_merge = to_merge->next) {
4496 oid = &to_merge->item->object.oid;
4497 strbuf_addch(&buf, ' ');
4499 if (!oidset_contains(&interesting, oid)) {
4500 strbuf_addstr(&buf, label_oid(oid, NULL,
4505 tips_tail = &commit_list_insert(to_merge->item,
4508 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4510 strbuf_addf(&buf, " # %s", oneline.buf);
4512 FLEX_ALLOC_STR(entry, string, buf.buf);
4513 oidcpy(&entry->entry.oid, &commit->object.oid);
4514 oidmap_put(&commit2todo, entry);
4519 * - label branch points
4520 * - add HEAD to the branch tips
4522 for (iter = commits; iter; iter = iter->next) {
4523 struct commit_list *parent = iter->item->parents;
4524 for (; parent; parent = parent->next) {
4525 struct object_id *oid = &parent->item->object.oid;
4526 if (!oidset_contains(&interesting, oid))
4528 if (oidset_insert(&child_seen, oid))
4529 label_oid(oid, "branch-point", &state);
4532 /* Add HEAD as implict "tip of branch" */
4534 tips_tail = &commit_list_insert(iter->item,
4539 * Third phase: output the todo list. This is a bit tricky, as we
4540 * want to avoid jumping back and forth between revisions. To
4541 * accomplish that goal, we walk backwards from the branch tips,
4542 * gathering commits not yet shown, reversing the list on the fly,
4543 * then outputting that list (labeling revisions as needed).
4545 strbuf_addf(out, "%s onto\n", cmd_label);
4546 for (iter = tips; iter; iter = iter->next) {
4547 struct commit_list *list = NULL, *iter2;
4549 commit = iter->item;
4550 if (oidset_contains(&shown, &commit->object.oid))
4552 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4555 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4557 strbuf_addch(out, '\n');
4559 while (oidset_contains(&interesting, &commit->object.oid) &&
4560 !oidset_contains(&shown, &commit->object.oid)) {
4561 commit_list_insert(commit, &list);
4562 if (!commit->parents) {
4566 commit = commit->parents->item;
4570 strbuf_addf(out, "%s %s\n", cmd_reset,
4571 rebase_cousins ? "onto" : "[new root]");
4573 const char *to = NULL;
4575 entry = oidmap_get(&state.commit2label,
4576 &commit->object.oid);
4579 else if (!rebase_cousins)
4580 to = label_oid(&commit->object.oid, NULL,
4583 if (!to || !strcmp(to, "onto"))
4584 strbuf_addf(out, "%s onto\n", cmd_reset);
4586 strbuf_reset(&oneline);
4587 pretty_print_commit(pp, commit, &oneline);
4588 strbuf_addf(out, "%s %s # %s\n",
4589 cmd_reset, to, oneline.buf);
4593 for (iter2 = list; iter2; iter2 = iter2->next) {
4594 struct object_id *oid = &iter2->item->object.oid;
4595 entry = oidmap_get(&commit2todo, oid);
4596 /* only show if not already upstream */
4598 strbuf_addf(out, "%s\n", entry->string);
4599 entry = oidmap_get(&state.commit2label, oid);
4601 strbuf_addf(out, "%s %s\n",
4602 cmd_label, entry->string);
4603 oidset_insert(&shown, oid);
4606 free_commit_list(list);
4609 free_commit_list(commits);
4610 free_commit_list(tips);
4612 strbuf_release(&label);
4613 strbuf_release(&oneline);
4614 strbuf_release(&buf);
4616 oidmap_free(&commit2todo, 1);
4617 oidmap_free(&state.commit2label, 1);
4618 hashmap_free(&state.labels, 1);
4619 strbuf_release(&state.buf);
4624 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4625 const char **argv, unsigned flags)
4627 char *format = NULL;
4628 struct pretty_print_context pp = {0};
4629 struct rev_info revs;
4630 struct commit *commit;
4631 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4632 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4633 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4635 repo_init_revisions(r, &revs, NULL);
4636 revs.verbose_header = 1;
4638 revs.max_parents = 1;
4639 revs.cherry_mark = 1;
4642 revs.right_only = 1;
4643 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4644 revs.topo_order = 1;
4646 revs.pretty_given = 1;
4647 git_config_get_string("rebase.instructionFormat", &format);
4648 if (!format || !*format) {
4650 format = xstrdup("%s");
4652 get_commit_format(format, &revs);
4654 pp.fmt = revs.commit_format;
4655 pp.output_encoding = get_log_output_encoding();
4657 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4658 return error(_("make_script: unhandled options"));
4660 if (prepare_revision_walk(&revs) < 0)
4661 return error(_("make_script: error preparing revisions"));
4664 return make_script_with_merges(&pp, &revs, out, flags);
4666 while ((commit = get_revision(&revs))) {
4667 int is_empty = is_original_commit_empty(commit);
4669 if (!is_empty && (commit->object.flags & PATCHSAME))
4671 if (!keep_empty && is_empty)
4672 strbuf_addf(out, "%c ", comment_line_char);
4673 strbuf_addf(out, "%s %s ", insn,
4674 oid_to_hex(&commit->object.oid));
4675 pretty_print_commit(&pp, commit, out);
4676 strbuf_addch(out, '\n');
4682 * Add commands after pick and (series of) squash/fixup commands
4685 void todo_list_add_exec_commands(struct todo_list *todo_list,
4686 struct string_list *commands)
4688 struct strbuf *buf = &todo_list->buf;
4689 size_t base_offset = buf->len;
4690 int i, insert, nr = 0, alloc = 0;
4691 struct todo_item *items = NULL, *base_items = NULL;
4693 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4694 for (i = 0; i < commands->nr; i++) {
4695 size_t command_len = strlen(commands->items[i].string);
4697 strbuf_addstr(buf, commands->items[i].string);
4698 strbuf_addch(buf, '\n');
4700 base_items[i].command = TODO_EXEC;
4701 base_items[i].offset_in_buf = base_offset;
4702 base_items[i].arg_offset = base_offset + strlen("exec ");
4703 base_items[i].arg_len = command_len - strlen("exec ");
4705 base_offset += command_len + 1;
4709 * Insert <commands> after every pick. Here, fixup/squash chains
4710 * are considered part of the pick, so we insert the commands *after*
4711 * those chains if there are any.
4713 * As we insert the exec commands immediatly after rearranging
4714 * any fixups and before the user edits the list, a fixup chain
4715 * can never contain comments (any comments are empty picks that
4716 * have been commented out because the user did not specify
4717 * --keep-empty). So, it is safe to insert an exec command
4718 * without looking at the command following a comment.
4721 for (i = 0; i < todo_list->nr; i++) {
4722 enum todo_command command = todo_list->items[i].command;
4723 if (insert && !is_fixup(command)) {
4724 ALLOC_GROW(items, nr + commands->nr, alloc);
4725 COPY_ARRAY(items + nr, base_items, commands->nr);
4731 ALLOC_GROW(items, nr + 1, alloc);
4732 items[nr++] = todo_list->items[i];
4734 if (command == TODO_PICK || command == TODO_MERGE)
4738 /* insert or append final <commands> */
4739 if (insert || nr == todo_list->nr) {
4740 ALLOC_GROW(items, nr + commands->nr, alloc);
4741 COPY_ARRAY(items + nr, base_items, commands->nr);
4746 FREE_AND_NULL(todo_list->items);
4747 todo_list->items = items;
4749 todo_list->alloc = alloc;
4752 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4753 struct strbuf *buf, int num, unsigned flags)
4755 struct todo_item *item;
4756 int i, max = todo_list->nr;
4758 if (num > 0 && num < max)
4761 for (item = todo_list->items, i = 0; i < max; i++, item++) {
4762 /* if the item is not a command write it and continue */
4763 if (item->command >= TODO_COMMENT) {
4764 strbuf_addf(buf, "%.*s\n", item->arg_len,
4765 todo_item_get_arg(todo_list, item));
4769 /* add command to the buffer */
4770 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4771 strbuf_addch(buf, command_to_char(item->command));
4773 strbuf_addstr(buf, command_to_string(item->command));
4777 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4778 short_commit_name(item->commit) :
4779 oid_to_hex(&item->commit->object.oid);
4781 if (item->command == TODO_MERGE) {
4782 if (item->flags & TODO_EDIT_MERGE_MSG)
4783 strbuf_addstr(buf, " -c");
4785 strbuf_addstr(buf, " -C");
4788 strbuf_addf(buf, " %s", oid);
4791 /* add all the rest */
4793 strbuf_addch(buf, '\n');
4795 strbuf_addf(buf, " %.*s\n", item->arg_len,
4796 todo_item_get_arg(todo_list, item));
4800 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
4801 const char *file, const char *shortrevisions,
4802 const char *shortonto, int num, unsigned flags)
4805 struct strbuf buf = STRBUF_INIT;
4807 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
4808 if (flags & TODO_LIST_APPEND_TODO_HELP)
4809 append_todo_help(flags & TODO_LIST_KEEP_EMPTY, count_commands(todo_list),
4810 shortrevisions, shortonto, &buf);
4812 res = write_message(buf.buf, buf.len, file, 0);
4813 strbuf_release(&buf);
4818 static const char edit_todo_list_advice[] =
4819 N_("You can fix this with 'git rebase --edit-todo' "
4820 "and then run 'git rebase --continue'.\n"
4821 "Or you can abort the rebase with 'git rebase"
4824 int check_todo_list_from_file(struct repository *r)
4826 struct todo_list old_todo = TODO_LIST_INIT, new_todo = TODO_LIST_INIT;
4829 if (strbuf_read_file_or_whine(&new_todo.buf, rebase_path_todo()) < 0) {
4834 if (strbuf_read_file_or_whine(&old_todo.buf, rebase_path_todo_backup()) < 0) {
4839 res = todo_list_parse_insn_buffer(r, old_todo.buf.buf, &old_todo);
4841 res = todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo);
4843 res = todo_list_check(&old_todo, &new_todo);
4845 fprintf(stderr, _(edit_todo_list_advice));
4847 todo_list_release(&old_todo);
4848 todo_list_release(&new_todo);
4853 /* skip picking commits whose parents are unchanged */
4854 static int skip_unnecessary_picks(struct repository *r,
4855 struct todo_list *todo_list,
4856 struct object_id *base_oid)
4858 struct object_id *parent_oid;
4861 for (i = 0; i < todo_list->nr; i++) {
4862 struct todo_item *item = todo_list->items + i;
4864 if (item->command >= TODO_NOOP)
4866 if (item->command != TODO_PICK)
4868 if (parse_commit(item->commit)) {
4869 return error(_("could not parse commit '%s'"),
4870 oid_to_hex(&item->commit->object.oid));
4872 if (!item->commit->parents)
4873 break; /* root commit */
4874 if (item->commit->parents->next)
4875 break; /* merge commit */
4876 parent_oid = &item->commit->parents->item->object.oid;
4877 if (!oideq(parent_oid, base_oid))
4879 oidcpy(base_oid, &item->commit->object.oid);
4882 const char *done_path = rebase_path_done();
4884 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
4885 error_errno(_("could not write to '%s'"), done_path);
4889 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
4891 todo_list->current = 0;
4893 if (is_fixup(peek_command(todo_list, 0)))
4894 record_in_rewritten(base_oid, peek_command(todo_list, 0));
4900 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
4901 const char *shortrevisions, const char *onto_name,
4902 struct commit *onto, const char *orig_head,
4903 struct string_list *commands, unsigned autosquash,
4904 struct todo_list *todo_list)
4906 const char *shortonto, *todo_file = rebase_path_todo();
4907 struct todo_list new_todo = TODO_LIST_INIT;
4908 struct strbuf *buf = &todo_list->buf;
4909 struct object_id oid = onto->object.oid;
4912 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4914 if (buf->len == 0) {
4915 struct todo_item *item = append_new_todo(todo_list);
4916 item->command = TODO_NOOP;
4917 item->commit = NULL;
4918 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
4921 if (autosquash && todo_list_rearrange_squash(todo_list))
4925 todo_list_add_exec_commands(todo_list, commands);
4927 if (count_commands(todo_list) == 0) {
4928 apply_autostash(opts);
4929 sequencer_remove_state(opts);
4931 return error(_("nothing to do"));
4934 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
4938 else if (res == -2) {
4939 apply_autostash(opts);
4940 sequencer_remove_state(opts);
4943 } else if (res == -3) {
4944 apply_autostash(opts);
4945 sequencer_remove_state(opts);
4946 todo_list_release(&new_todo);
4948 return error(_("nothing to do"));
4951 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) ||
4952 todo_list_check(todo_list, &new_todo)) {
4953 fprintf(stderr, _(edit_todo_list_advice));
4954 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
4955 todo_list_release(&new_todo);
4960 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
4961 todo_list_release(&new_todo);
4962 return error(_("could not skip unnecessary pick commands"));
4965 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
4966 flags & ~(TODO_LIST_SHORTEN_IDS))) {
4967 todo_list_release(&new_todo);
4968 return error_errno(_("could not write '%s'"), todo_file);
4971 todo_list_release(&new_todo);
4973 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
4976 if (require_clean_work_tree(r, "rebase", "", 1, 1))
4979 return sequencer_continue(r, opts);
4982 struct subject2item_entry {
4983 struct hashmap_entry entry;
4985 char subject[FLEX_ARRAY];
4988 static int subject2item_cmp(const void *fndata,
4989 const struct subject2item_entry *a,
4990 const struct subject2item_entry *b, const void *key)
4992 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4995 define_commit_slab(commit_todo_item, struct todo_item *);
4998 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4999 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5000 * after the former, and change "pick" to "fixup"/"squash".
5002 * Note that if the config has specified a custom instruction format, each log
5003 * message will have to be retrieved from the commit (as the oneline in the
5004 * script cannot be trusted) in order to normalize the autosquash arrangement.
5006 int todo_list_rearrange_squash(struct todo_list *todo_list)
5008 struct hashmap subject2item;
5009 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5011 struct commit_todo_item commit_todo;
5012 struct todo_item *items = NULL;
5014 init_commit_todo_item(&commit_todo);
5016 * The hashmap maps onelines to the respective todo list index.
5018 * If any items need to be rearranged, the next[i] value will indicate
5019 * which item was moved directly after the i'th.
5021 * In that case, last[i] will indicate the index of the latest item to
5022 * be moved to appear after the i'th.
5024 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
5025 NULL, todo_list->nr);
5026 ALLOC_ARRAY(next, todo_list->nr);
5027 ALLOC_ARRAY(tail, todo_list->nr);
5028 ALLOC_ARRAY(subjects, todo_list->nr);
5029 for (i = 0; i < todo_list->nr; i++) {
5030 struct strbuf buf = STRBUF_INIT;
5031 struct todo_item *item = todo_list->items + i;
5032 const char *commit_buffer, *subject, *p;
5035 struct subject2item_entry *entry;
5037 next[i] = tail[i] = -1;
5038 if (!item->commit || item->command == TODO_DROP) {
5043 if (is_fixup(item->command)) {
5044 clear_commit_todo_item(&commit_todo);
5045 return error(_("the script was already rearranged."));
5048 *commit_todo_item_at(&commit_todo, item->commit) = item;
5050 parse_commit(item->commit);
5051 commit_buffer = get_commit_buffer(item->commit, NULL);
5052 find_commit_subject(commit_buffer, &subject);
5053 format_subject(&buf, subject, " ");
5054 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5055 unuse_commit_buffer(item->commit, commit_buffer);
5056 if ((skip_prefix(subject, "fixup! ", &p) ||
5057 skip_prefix(subject, "squash! ", &p))) {
5058 struct commit *commit2;
5063 if (!skip_prefix(p, "fixup! ", &p) &&
5064 !skip_prefix(p, "squash! ", &p))
5068 if ((entry = hashmap_get_from_hash(&subject2item,
5070 /* found by title */
5072 else if (!strchr(p, ' ') &&
5074 lookup_commit_reference_by_name(p)) &&
5075 *commit_todo_item_at(&commit_todo, commit2))
5076 /* found by commit name */
5077 i2 = *commit_todo_item_at(&commit_todo, commit2)
5080 /* copy can be a prefix of the commit subject */
5081 for (i2 = 0; i2 < i; i2++)
5083 starts_with(subjects[i2], p))
5091 todo_list->items[i].command =
5092 starts_with(subject, "fixup!") ?
5093 TODO_FIXUP : TODO_SQUASH;
5099 } else if (!hashmap_get_from_hash(&subject2item,
5100 strhash(subject), subject)) {
5101 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5103 hashmap_entry_init(entry, strhash(entry->subject));
5104 hashmap_put(&subject2item, entry);
5109 for (i = 0; i < todo_list->nr; i++) {
5110 enum todo_command command = todo_list->items[i].command;
5114 * Initially, all commands are 'pick's. If it is a
5115 * fixup or a squash now, we have rearranged it.
5117 if (is_fixup(command))
5121 ALLOC_GROW(items, nr + 1, alloc);
5122 items[nr++] = todo_list->items[cur];
5127 FREE_AND_NULL(todo_list->items);
5128 todo_list->items = items;
5130 todo_list->alloc = alloc;
5135 for (i = 0; i < todo_list->nr; i++)
5138 hashmap_free(&subject2item, 1);
5140 clear_commit_todo_item(&commit_todo);