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")
60 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
63 * The rebase command lines that have already been processed. A line
64 * is moved here when it is first handled, before any associated user
67 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
69 * The file to keep track of how many commands were already processed (e.g.
72 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
74 * The file to keep track of how many commands are to be processed in total
75 * (e.g. for the prompt).
77 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
79 * The commit message that is planned to be used for any changes that
80 * need to be committed following a user interaction.
82 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
84 * The file into which is accumulated the suggested commit message for
85 * squash/fixup commands. When the first of a series of squash/fixups
86 * is seen, the file is created and the commit message from the
87 * previous commit and from the first squash/fixup commit are written
88 * to it. The commit message for each subsequent squash/fixup commit
89 * is appended to the file as it is processed.
91 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
93 * If the current series of squash/fixups has not yet included a squash
94 * command, then this file exists and holds the commit message of the
95 * original "pick" commit. (If the series ends without a "squash"
96 * command, then this can be used as the commit message of the combined
97 * commit without opening the editor.)
99 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
101 * This file contains the list fixup/squash commands that have been
102 * accumulated into message-fixup or message-squash so far.
104 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
106 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
107 * GIT_AUTHOR_DATE that will be used for the commit that is currently
110 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
112 * When an "edit" rebase command is being processed, the SHA1 of the
113 * commit to be edited is recorded in this file. When "git rebase
114 * --continue" is executed, if there are any staged changes then they
115 * will be amended to the HEAD commit, but only provided the HEAD
116 * commit is still the commit to be edited. When any other rebase
117 * command is processed, this file is deleted.
119 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
121 * When we stop at a given patch via the "edit" command, this file contains
122 * the abbreviated commit name of the corresponding patch.
124 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
126 * For the post-rewrite hook, we make a list of rewritten commits and
127 * their new sha1s. The rewritten-pending list keeps the sha1s of
128 * commits that have been processed, but not committed yet,
129 * e.g. because they are waiting for a 'squash' command.
131 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
132 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
133 "rebase-merge/rewritten-pending")
136 * The path of the file containing the OID of the "squash onto" commit, i.e.
137 * the dummy commit used for `reset [new root]`.
139 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
142 * The path of the file listing refs that need to be deleted after the rebase
143 * finishes. This is used by the `label` command to record the need for cleanup.
145 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
148 * The following files are written by git-rebase just after parsing the
151 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
152 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
153 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
154 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
155 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
156 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
157 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
158 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
159 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
160 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
161 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
162 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
163 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
164 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
166 static int git_sequencer_config(const char *k, const char *v, void *cb)
168 struct replay_opts *opts = cb;
171 if (!strcmp(k, "commit.cleanup")) {
174 status = git_config_string(&s, k, v);
178 if (!strcmp(s, "verbatim")) {
179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
180 opts->explicit_cleanup = 1;
181 } else if (!strcmp(s, "whitespace")) {
182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "strip")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "scissors")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
189 opts->explicit_cleanup = 1;
191 warning(_("invalid commit message cleanup mode '%s'"),
199 if (!strcmp(k, "commit.gpgsign")) {
200 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
204 status = git_gpg_config(k, v, NULL);
208 return git_diff_basic_config(k, v, NULL);
211 void sequencer_init_config(struct replay_opts *opts)
213 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
214 git_config(git_sequencer_config, opts);
217 static inline int is_rebase_i(const struct replay_opts *opts)
219 return opts->action == REPLAY_INTERACTIVE_REBASE;
222 static const char *get_dir(const struct replay_opts *opts)
224 if (is_rebase_i(opts))
225 return rebase_path();
226 return git_path_seq_dir();
229 static const char *get_todo_path(const struct replay_opts *opts)
231 if (is_rebase_i(opts))
232 return rebase_path_todo();
233 return git_path_todo_file();
237 * Returns 0 for non-conforming footer
238 * Returns 1 for conforming footer
239 * Returns 2 when sob exists within conforming footer
240 * Returns 3 when sob exists within conforming footer as last entry
242 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
243 size_t ignore_footer)
245 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
246 struct trailer_info info;
248 int found_sob = 0, found_sob_last = 0;
252 trailer_info_get(&info, sb->buf, &opts);
254 if (info.trailer_start == info.trailer_end)
257 for (i = 0; i < info.trailer_nr; i++)
258 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
260 if (i == info.trailer_nr - 1)
264 trailer_info_release(&info);
273 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
275 static struct strbuf buf = STRBUF_INIT;
279 sq_quotef(&buf, "-S%s", opts->gpg_sign);
283 int sequencer_remove_state(struct replay_opts *opts)
285 struct strbuf buf = STRBUF_INIT;
288 if (is_rebase_i(opts) &&
289 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
292 char *eol = strchr(p, '\n');
295 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
296 warning(_("could not delete '%s'"), p);
305 free(opts->gpg_sign);
306 free(opts->strategy);
307 for (i = 0; i < opts->xopts_nr; i++)
308 free(opts->xopts[i]);
310 strbuf_release(&opts->current_fixups);
313 strbuf_addstr(&buf, get_dir(opts));
314 if (remove_dir_recursively(&buf, 0))
315 ret = error(_("could not remove '%s'"), buf.buf);
316 strbuf_release(&buf);
321 static const char *action_name(const struct replay_opts *opts)
323 switch (opts->action) {
327 return N_("cherry-pick");
328 case REPLAY_INTERACTIVE_REBASE:
331 die(_("unknown action: %d"), opts->action);
334 struct commit_message {
341 static const char *short_commit_name(struct commit *commit)
343 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
346 static int get_message(struct commit *commit, struct commit_message *out)
348 const char *abbrev, *subject;
351 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
352 abbrev = short_commit_name(commit);
354 subject_len = find_commit_subject(out->message, &subject);
356 out->subject = xmemdupz(subject, subject_len);
357 out->label = xstrfmt("%s... %s", abbrev, out->subject);
358 out->parent_label = xstrfmt("parent of %s", out->label);
363 static void free_message(struct commit *commit, struct commit_message *msg)
365 free(msg->parent_label);
368 unuse_commit_buffer(commit, msg->message);
371 static void print_advice(struct repository *r, int show_hint,
372 struct replay_opts *opts)
374 char *msg = getenv("GIT_CHERRY_PICK_HELP");
377 fprintf(stderr, "%s\n", msg);
379 * A conflict has occurred but the porcelain
380 * (typically rebase --interactive) wants to take care
381 * of the commit itself so remove CHERRY_PICK_HEAD
383 unlink(git_path_cherry_pick_head(r));
389 advise(_("after resolving the conflicts, mark the corrected paths\n"
390 "with 'git add <paths>' or 'git rm <paths>'"));
392 advise(_("after resolving the conflicts, mark the corrected paths\n"
393 "with 'git add <paths>' or 'git rm <paths>'\n"
394 "and commit the result with 'git commit'"));
398 static int write_message(const void *buf, size_t len, const char *filename,
401 struct lock_file msg_file = LOCK_INIT;
403 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
405 return error_errno(_("could not lock '%s'"), filename);
406 if (write_in_full(msg_fd, buf, len) < 0) {
407 error_errno(_("could not write to '%s'"), filename);
408 rollback_lock_file(&msg_file);
411 if (append_eol && write(msg_fd, "\n", 1) < 0) {
412 error_errno(_("could not write eol to '%s'"), filename);
413 rollback_lock_file(&msg_file);
416 if (commit_lock_file(&msg_file) < 0)
417 return error(_("failed to finalize '%s'"), filename);
422 #define READ_ONELINER_SKIP_IF_EMPTY (1 << 0)
425 * Reads a file that was presumably written by a shell script, i.e. with an
426 * end-of-line marker that needs to be stripped.
428 * Note that only the last end-of-line marker is stripped, consistent with the
429 * behavior of "$(cat path)" in a shell script.
431 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
433 static int read_oneliner(struct strbuf *buf,
434 const char *path, unsigned flags)
436 int orig_len = buf->len;
438 if (strbuf_read_file(buf, path, 0) < 0) {
439 if (errno != ENOENT && errno != ENOTDIR)
440 warning_errno(_("could not read '%s'"), path);
444 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
445 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
447 buf->buf[buf->len] = '\0';
450 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
456 static struct tree *empty_tree(struct repository *r)
458 return lookup_tree(r, the_hash_algo->empty_tree);
461 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
463 if (repo_read_index_unmerged(repo))
464 return error_resolve_conflict(_(action_name(opts)));
466 error(_("your local changes would be overwritten by %s."),
467 _(action_name(opts)));
469 if (advice_commit_before_merge)
470 advise(_("commit your changes or stash them to proceed."));
474 static void update_abort_safety_file(void)
476 struct object_id head;
478 /* Do nothing on a single-pick */
479 if (!file_exists(git_path_seq_dir()))
482 if (!get_oid("HEAD", &head))
483 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
485 write_file(git_path_abort_safety_file(), "%s", "");
488 static int fast_forward_to(struct repository *r,
489 const struct object_id *to,
490 const struct object_id *from,
492 struct replay_opts *opts)
494 struct ref_transaction *transaction;
495 struct strbuf sb = STRBUF_INIT;
496 struct strbuf err = STRBUF_INIT;
499 if (checkout_fast_forward(r, from, to, 1))
500 return -1; /* the callee should have complained already */
502 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
504 transaction = ref_transaction_begin(&err);
506 ref_transaction_update(transaction, "HEAD",
507 to, unborn && !is_rebase_i(opts) ?
510 ref_transaction_commit(transaction, &err)) {
511 ref_transaction_free(transaction);
512 error("%s", err.buf);
514 strbuf_release(&err);
519 strbuf_release(&err);
520 ref_transaction_free(transaction);
521 update_abort_safety_file();
525 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
528 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
529 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
530 COMMIT_MSG_CLEANUP_SPACE;
531 else if (!strcmp(cleanup_arg, "verbatim"))
532 return COMMIT_MSG_CLEANUP_NONE;
533 else if (!strcmp(cleanup_arg, "whitespace"))
534 return COMMIT_MSG_CLEANUP_SPACE;
535 else if (!strcmp(cleanup_arg, "strip"))
536 return COMMIT_MSG_CLEANUP_ALL;
537 else if (!strcmp(cleanup_arg, "scissors"))
538 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
539 COMMIT_MSG_CLEANUP_SPACE;
541 die(_("Invalid cleanup mode %s"), cleanup_arg);
545 * NB using int rather than enum cleanup_mode to stop clang's
546 * -Wtautological-constant-out-of-range-compare complaining that the comparison
549 static const char *describe_cleanup_mode(int cleanup_mode)
551 static const char *modes[] = { "whitespace",
556 if (cleanup_mode < ARRAY_SIZE(modes))
557 return modes[cleanup_mode];
559 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
562 void append_conflicts_hint(struct index_state *istate,
563 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
567 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
568 strbuf_addch(msgbuf, '\n');
569 wt_status_append_cut_line(msgbuf);
570 strbuf_addch(msgbuf, comment_line_char);
573 strbuf_addch(msgbuf, '\n');
574 strbuf_commented_addf(msgbuf, "Conflicts:\n");
575 for (i = 0; i < istate->cache_nr;) {
576 const struct cache_entry *ce = istate->cache[i++];
578 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
579 while (i < istate->cache_nr &&
580 !strcmp(ce->name, istate->cache[i]->name))
586 static int do_recursive_merge(struct repository *r,
587 struct commit *base, struct commit *next,
588 const char *base_label, const char *next_label,
589 struct object_id *head, struct strbuf *msgbuf,
590 struct replay_opts *opts)
592 struct merge_options o;
593 struct tree *next_tree, *base_tree, *head_tree;
596 struct lock_file index_lock = LOCK_INIT;
598 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
603 init_merge_options(&o, r);
604 o.ancestor = base ? base_label : "(empty tree)";
606 o.branch2 = next ? next_label : "(empty tree)";
607 if (is_rebase_i(opts))
609 o.show_rename_progress = 1;
611 head_tree = parse_tree_indirect(head);
612 next_tree = next ? get_commit_tree(next) : empty_tree(r);
613 base_tree = base ? get_commit_tree(base) : empty_tree(r);
615 for (i = 0; i < opts->xopts_nr; i++)
616 parse_merge_opt(&o, opts->xopts[i]);
618 clean = merge_trees(&o,
620 next_tree, base_tree);
621 if (is_rebase_i(opts) && clean <= 0)
622 fputs(o.obuf.buf, stdout);
623 strbuf_release(&o.obuf);
625 rollback_lock_file(&index_lock);
629 if (write_locked_index(r->index, &index_lock,
630 COMMIT_LOCK | SKIP_IF_UNCHANGED))
632 * TRANSLATORS: %s will be "revert", "cherry-pick" or
635 return error(_("%s: Unable to write new index file"),
636 _(action_name(opts)));
639 append_conflicts_hint(r->index, msgbuf,
640 opts->default_msg_cleanup);
645 static struct object_id *get_cache_tree_oid(struct index_state *istate)
647 if (!istate->cache_tree)
648 istate->cache_tree = cache_tree();
650 if (!cache_tree_fully_valid(istate->cache_tree))
651 if (cache_tree_update(istate, 0)) {
652 error(_("unable to update cache tree"));
656 return &istate->cache_tree->oid;
659 static int is_index_unchanged(struct repository *r)
661 struct object_id head_oid, *cache_tree_oid;
662 struct commit *head_commit;
663 struct index_state *istate = r->index;
665 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
666 return error(_("could not resolve HEAD commit"));
668 head_commit = lookup_commit(r, &head_oid);
671 * If head_commit is NULL, check_commit, called from
672 * lookup_commit, would have indicated that head_commit is not
673 * a commit object already. parse_commit() will return failure
674 * without further complaints in such a case. Otherwise, if
675 * the commit is invalid, parse_commit() will complain. So
676 * there is nothing for us to say here. Just return failure.
678 if (parse_commit(head_commit))
681 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
684 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
687 static int write_author_script(const char *message)
689 struct strbuf buf = STRBUF_INIT;
694 if (!*message || starts_with(message, "\n")) {
696 /* Missing 'author' line? */
697 unlink(rebase_path_author_script());
699 } else if (skip_prefix(message, "author ", &message))
701 else if ((eol = strchr(message, '\n')))
706 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
707 while (*message && *message != '\n' && *message != '\r')
708 if (skip_prefix(message, " <", &message))
710 else if (*message != '\'')
711 strbuf_addch(&buf, *(message++));
713 strbuf_addf(&buf, "'\\%c'", *(message++));
714 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
715 while (*message && *message != '\n' && *message != '\r')
716 if (skip_prefix(message, "> ", &message))
718 else if (*message != '\'')
719 strbuf_addch(&buf, *(message++));
721 strbuf_addf(&buf, "'\\%c'", *(message++));
722 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
723 while (*message && *message != '\n' && *message != '\r')
724 if (*message != '\'')
725 strbuf_addch(&buf, *(message++));
727 strbuf_addf(&buf, "'\\%c'", *(message++));
728 strbuf_addch(&buf, '\'');
729 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
730 strbuf_release(&buf);
735 * Take a series of KEY='VALUE' lines where VALUE part is
736 * sq-quoted, and append <KEY, VALUE> at the end of the string list
738 static int parse_key_value_squoted(char *buf, struct string_list *list)
741 struct string_list_item *item;
743 char *cp = strchr(buf, '=');
745 np = strchrnul(buf, '\n');
746 return error(_("no key present in '%.*s'"),
747 (int) (np - buf), buf);
749 np = strchrnul(cp, '\n');
751 item = string_list_append(list, buf);
753 buf = np + (*np == '\n');
757 return error(_("unable to dequote value of '%s'"),
759 item->util = xstrdup(cp);
765 * Reads and parses the state directory's "author-script" file, and sets name,
766 * email and date accordingly.
767 * Returns 0 on success, -1 if the file could not be parsed.
769 * The author script is of the format:
771 * GIT_AUTHOR_NAME='$author_name'
772 * GIT_AUTHOR_EMAIL='$author_email'
773 * GIT_AUTHOR_DATE='$author_date'
775 * where $author_name, $author_email and $author_date are quoted. We are strict
776 * with our parsing, as the file was meant to be eval'd in the now-removed
777 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
778 * from what this function expects, it is better to bail out than to do
779 * something that the user does not expect.
781 int read_author_script(const char *path, char **name, char **email, char **date,
784 struct strbuf buf = STRBUF_INIT;
785 struct string_list kv = STRING_LIST_INIT_DUP;
786 int retval = -1; /* assume failure */
787 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
789 if (strbuf_read_file(&buf, path, 256) <= 0) {
790 strbuf_release(&buf);
791 if (errno == ENOENT && allow_missing)
794 return error_errno(_("could not open '%s' for reading"),
798 if (parse_key_value_squoted(buf.buf, &kv))
801 for (i = 0; i < kv.nr; i++) {
802 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
804 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
807 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
809 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
812 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
814 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
818 err = error(_("unknown variable '%s'"),
823 error(_("missing 'GIT_AUTHOR_NAME'"));
825 error(_("missing 'GIT_AUTHOR_EMAIL'"));
827 error(_("missing 'GIT_AUTHOR_DATE'"));
828 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
830 *name = kv.items[name_i].util;
831 *email = kv.items[email_i].util;
832 *date = kv.items[date_i].util;
835 string_list_clear(&kv, !!retval);
836 strbuf_release(&buf);
841 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
842 * file with shell quoting into struct argv_array. Returns -1 on
843 * error, 0 otherwise.
845 static int read_env_script(struct argv_array *env)
847 char *name, *email, *date;
849 if (read_author_script(rebase_path_author_script(),
850 &name, &email, &date, 0))
853 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
854 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
855 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
863 static char *get_author(const char *message)
868 a = find_commit_header(message, "author", &len);
870 return xmemdupz(a, len);
875 static const char staged_changes_advice[] =
876 N_("you have staged changes in your working tree\n"
877 "If these changes are meant to be squashed into the previous commit, run:\n"
879 " git commit --amend %s\n"
881 "If they are meant to go into a new commit, run:\n"
885 "In both cases, once you're done, continue with:\n"
887 " git rebase --continue\n");
889 #define ALLOW_EMPTY (1<<0)
890 #define EDIT_MSG (1<<1)
891 #define AMEND_MSG (1<<2)
892 #define CLEANUP_MSG (1<<3)
893 #define VERIFY_MSG (1<<4)
894 #define CREATE_ROOT_COMMIT (1<<5)
896 static int run_command_silent_on_success(struct child_process *cmd)
898 struct strbuf buf = STRBUF_INIT;
901 cmd->stdout_to_stderr = 1;
902 rc = pipe_command(cmd,
908 fputs(buf.buf, stderr);
909 strbuf_release(&buf);
914 * If we are cherry-pick, and if the merge did not result in
915 * hand-editing, we will hit this commit and inherit the original
916 * author date and name.
918 * If we are revert, or if our cherry-pick results in a hand merge,
919 * we had better say that the current user is responsible for that.
921 * An exception is when run_git_commit() is called during an
922 * interactive rebase: in that case, we will want to retain the
925 static int run_git_commit(struct repository *r,
927 struct replay_opts *opts,
930 struct child_process cmd = CHILD_PROCESS_INIT;
934 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
935 const char *gpg_opt = gpg_sign_opt_quoted(opts);
937 return error(_(staged_changes_advice),
941 argv_array_push(&cmd.args, "commit");
943 if (!(flags & VERIFY_MSG))
944 argv_array_push(&cmd.args, "-n");
945 if ((flags & AMEND_MSG))
946 argv_array_push(&cmd.args, "--amend");
948 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
950 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
951 else if (!(flags & EDIT_MSG))
952 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
953 if ((flags & CLEANUP_MSG))
954 argv_array_push(&cmd.args, "--cleanup=strip");
955 if ((flags & EDIT_MSG))
956 argv_array_push(&cmd.args, "-e");
957 else if (!(flags & CLEANUP_MSG) &&
958 !opts->signoff && !opts->record_origin &&
959 !opts->explicit_cleanup)
960 argv_array_push(&cmd.args, "--cleanup=verbatim");
962 if ((flags & ALLOW_EMPTY))
963 argv_array_push(&cmd.args, "--allow-empty");
965 if (!(flags & EDIT_MSG))
966 argv_array_push(&cmd.args, "--allow-empty-message");
968 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
969 return run_command_silent_on_success(&cmd);
971 return run_command(&cmd);
974 static int rest_is_empty(const struct strbuf *sb, int start)
979 /* Check if the rest is just whitespace and Signed-off-by's. */
980 for (i = start; i < sb->len; i++) {
981 nl = memchr(sb->buf + i, '\n', sb->len - i);
987 if (strlen(sign_off_header) <= eol - i &&
988 starts_with(sb->buf + i, sign_off_header)) {
993 if (!isspace(sb->buf[i++]))
1000 void cleanup_message(struct strbuf *msgbuf,
1001 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1003 if (verbose || /* Truncate the message just before the diff, if any. */
1004 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1005 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1006 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1007 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1011 * Find out if the message in the strbuf contains only whitespace and
1012 * Signed-off-by lines.
1014 int message_is_empty(const struct strbuf *sb,
1015 enum commit_msg_cleanup_mode cleanup_mode)
1017 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1019 return rest_is_empty(sb, 0);
1023 * See if the user edited the message in the editor or left what
1024 * was in the template intact
1026 int template_untouched(const struct strbuf *sb, const char *template_file,
1027 enum commit_msg_cleanup_mode cleanup_mode)
1029 struct strbuf tmpl = STRBUF_INIT;
1032 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1035 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1038 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1039 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1041 strbuf_release(&tmpl);
1042 return rest_is_empty(sb, start - sb->buf);
1045 int update_head_with_reflog(const struct commit *old_head,
1046 const struct object_id *new_head,
1047 const char *action, const struct strbuf *msg,
1050 struct ref_transaction *transaction;
1051 struct strbuf sb = STRBUF_INIT;
1056 strbuf_addstr(&sb, action);
1057 strbuf_addstr(&sb, ": ");
1060 nl = strchr(msg->buf, '\n');
1062 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1064 strbuf_addbuf(&sb, msg);
1065 strbuf_addch(&sb, '\n');
1068 transaction = ref_transaction_begin(err);
1070 ref_transaction_update(transaction, "HEAD", new_head,
1071 old_head ? &old_head->object.oid : &null_oid,
1073 ref_transaction_commit(transaction, err)) {
1076 ref_transaction_free(transaction);
1077 strbuf_release(&sb);
1082 static int run_rewrite_hook(const struct object_id *oldoid,
1083 const struct object_id *newoid)
1085 struct child_process proc = CHILD_PROCESS_INIT;
1086 const char *argv[3];
1088 struct strbuf sb = STRBUF_INIT;
1090 argv[0] = find_hook("post-rewrite");
1099 proc.stdout_to_stderr = 1;
1100 proc.trace2_hook_name = "post-rewrite";
1102 code = start_command(&proc);
1105 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1106 sigchain_push(SIGPIPE, SIG_IGN);
1107 write_in_full(proc.in, sb.buf, sb.len);
1109 strbuf_release(&sb);
1110 sigchain_pop(SIGPIPE);
1111 return finish_command(&proc);
1114 void commit_post_rewrite(struct repository *r,
1115 const struct commit *old_head,
1116 const struct object_id *new_head)
1118 struct notes_rewrite_cfg *cfg;
1120 cfg = init_copy_notes_for_rewrite("amend");
1122 /* we are amending, so old_head is not NULL */
1123 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1124 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1126 run_rewrite_hook(&old_head->object.oid, new_head);
1129 static int run_prepare_commit_msg_hook(struct repository *r,
1134 const char *name, *arg1 = NULL, *arg2 = NULL;
1136 name = git_path_commit_editmsg();
1137 if (write_message(msg->buf, msg->len, name, 0))
1146 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1148 ret = error(_("'prepare-commit-msg' hook failed"));
1153 static const char implicit_ident_advice_noconfig[] =
1154 N_("Your name and email address were configured automatically based\n"
1155 "on your username and hostname. Please check that they are accurate.\n"
1156 "You can suppress this message by setting them explicitly. Run the\n"
1157 "following command and follow the instructions in your editor to edit\n"
1158 "your configuration file:\n"
1160 " git config --global --edit\n"
1162 "After doing this, you may fix the identity used for this commit with:\n"
1164 " git commit --amend --reset-author\n");
1166 static const char implicit_ident_advice_config[] =
1167 N_("Your name and email address were configured automatically based\n"
1168 "on your username and hostname. Please check that they are accurate.\n"
1169 "You can suppress this message by setting them explicitly:\n"
1171 " git config --global user.name \"Your Name\"\n"
1172 " git config --global user.email you@example.com\n"
1174 "After doing this, you may fix the identity used for this commit with:\n"
1176 " git commit --amend --reset-author\n");
1178 static const char *implicit_ident_advice(void)
1180 char *user_config = expand_user_path("~/.gitconfig", 0);
1181 char *xdg_config = xdg_config_home("config");
1182 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1188 return _(implicit_ident_advice_config);
1190 return _(implicit_ident_advice_noconfig);
1194 void print_commit_summary(struct repository *r,
1196 const struct object_id *oid,
1199 struct rev_info rev;
1200 struct commit *commit;
1201 struct strbuf format = STRBUF_INIT;
1203 struct pretty_print_context pctx = {0};
1204 struct strbuf author_ident = STRBUF_INIT;
1205 struct strbuf committer_ident = STRBUF_INIT;
1207 commit = lookup_commit(r, oid);
1209 die(_("couldn't look up newly created commit"));
1210 if (parse_commit(commit))
1211 die(_("could not parse newly created commit"));
1213 strbuf_addstr(&format, "format:%h] %s");
1215 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1216 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1217 if (strbuf_cmp(&author_ident, &committer_ident)) {
1218 strbuf_addstr(&format, "\n Author: ");
1219 strbuf_addbuf_percentquote(&format, &author_ident);
1221 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1222 struct strbuf date = STRBUF_INIT;
1224 format_commit_message(commit, "%ad", &date, &pctx);
1225 strbuf_addstr(&format, "\n Date: ");
1226 strbuf_addbuf_percentquote(&format, &date);
1227 strbuf_release(&date);
1229 if (!committer_ident_sufficiently_given()) {
1230 strbuf_addstr(&format, "\n Committer: ");
1231 strbuf_addbuf_percentquote(&format, &committer_ident);
1232 if (advice_implicit_identity) {
1233 strbuf_addch(&format, '\n');
1234 strbuf_addstr(&format, implicit_ident_advice());
1237 strbuf_release(&author_ident);
1238 strbuf_release(&committer_ident);
1240 repo_init_revisions(r, &rev, prefix);
1241 setup_revisions(0, NULL, &rev, NULL);
1244 rev.diffopt.output_format =
1245 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1247 rev.verbose_header = 1;
1248 rev.show_root_diff = 1;
1249 get_commit_format(format.buf, &rev);
1250 rev.always_show_header = 0;
1251 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1252 rev.diffopt.break_opt = 0;
1253 diff_setup_done(&rev.diffopt);
1255 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1257 die_errno(_("unable to resolve HEAD after creating commit"));
1258 if (!strcmp(head, "HEAD"))
1259 head = _("detached HEAD");
1261 skip_prefix(head, "refs/heads/", &head);
1262 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1263 _(" (root-commit)") : "");
1265 if (!log_tree_commit(&rev, commit)) {
1266 rev.always_show_header = 1;
1267 rev.use_terminator = 1;
1268 log_tree_commit(&rev, commit);
1271 strbuf_release(&format);
1274 static int parse_head(struct repository *r, struct commit **head)
1276 struct commit *current_head;
1277 struct object_id oid;
1279 if (get_oid("HEAD", &oid)) {
1280 current_head = NULL;
1282 current_head = lookup_commit_reference(r, &oid);
1284 return error(_("could not parse HEAD"));
1285 if (!oideq(&oid, ¤t_head->object.oid)) {
1286 warning(_("HEAD %s is not a commit!"),
1289 if (parse_commit(current_head))
1290 return error(_("could not parse HEAD commit"));
1292 *head = current_head;
1298 * Try to commit without forking 'git commit'. In some cases we need
1299 * to run 'git commit' to display an error message
1302 * -1 - error unable to commit
1304 * 1 - run 'git commit'
1306 static int try_to_commit(struct repository *r,
1307 struct strbuf *msg, const char *author,
1308 struct replay_opts *opts, unsigned int flags,
1309 struct object_id *oid)
1311 struct object_id tree;
1312 struct commit *current_head = NULL;
1313 struct commit_list *parents = NULL;
1314 struct commit_extra_header *extra = NULL;
1315 struct strbuf err = STRBUF_INIT;
1316 struct strbuf commit_msg = STRBUF_INIT;
1317 char *amend_author = NULL;
1318 const char *hook_commit = NULL;
1319 enum commit_msg_cleanup_mode cleanup;
1322 if (parse_head(r, ¤t_head))
1325 if (flags & AMEND_MSG) {
1326 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1327 const char *out_enc = get_commit_output_encoding();
1328 const char *message = logmsg_reencode(current_head, NULL,
1332 const char *orig_message = NULL;
1334 find_commit_subject(message, &orig_message);
1336 strbuf_addstr(msg, orig_message);
1337 hook_commit = "HEAD";
1339 author = amend_author = get_author(message);
1340 unuse_commit_buffer(current_head, message);
1342 res = error(_("unable to parse commit author"));
1345 parents = copy_commit_list(current_head->parents);
1346 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1347 } else if (current_head &&
1348 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1349 commit_list_insert(current_head, &parents);
1352 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1353 res = error(_("git write-tree failed to write a tree"));
1357 if (!(flags & ALLOW_EMPTY)) {
1358 struct commit *first_parent = current_head;
1360 if (flags & AMEND_MSG) {
1361 if (current_head->parents) {
1362 first_parent = current_head->parents->item;
1363 if (repo_parse_commit(r, first_parent)) {
1364 res = error(_("could not parse HEAD commit"));
1368 first_parent = NULL;
1371 if (oideq(first_parent
1372 ? get_commit_tree_oid(first_parent)
1373 : the_hash_algo->empty_tree,
1375 res = 1; /* run 'git commit' to display error message */
1380 if (find_hook("prepare-commit-msg")) {
1381 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1384 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1386 res = error_errno(_("unable to read commit message "
1388 git_path_commit_editmsg());
1394 if (flags & CLEANUP_MSG)
1395 cleanup = COMMIT_MSG_CLEANUP_ALL;
1396 else if ((opts->signoff || opts->record_origin) &&
1397 !opts->explicit_cleanup)
1398 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1400 cleanup = opts->default_msg_cleanup;
1402 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1403 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1404 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1405 res = 1; /* run 'git commit' to display error message */
1411 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1412 oid, author, opts->gpg_sign, extra)) {
1413 res = error(_("failed to write commit object"));
1417 if (update_head_with_reflog(current_head, oid,
1418 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1419 res = error("%s", err.buf);
1423 run_commit_hook(0, r->index_file, "post-commit", NULL);
1424 if (flags & AMEND_MSG)
1425 commit_post_rewrite(r, current_head, oid);
1428 free_commit_extra_headers(extra);
1429 strbuf_release(&err);
1430 strbuf_release(&commit_msg);
1436 static int do_commit(struct repository *r,
1437 const char *msg_file, const char *author,
1438 struct replay_opts *opts, unsigned int flags)
1442 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1443 struct object_id oid;
1444 struct strbuf sb = STRBUF_INIT;
1446 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1447 return error_errno(_("unable to read commit message "
1451 res = try_to_commit(r, msg_file ? &sb : NULL,
1452 author, opts, flags, &oid);
1453 strbuf_release(&sb);
1455 unlink(git_path_cherry_pick_head(r));
1456 unlink(git_path_merge_msg(r));
1457 if (!is_rebase_i(opts))
1458 print_commit_summary(r, NULL, &oid,
1459 SUMMARY_SHOW_AUTHOR_DATE);
1464 return run_git_commit(r, msg_file, opts, flags);
1469 static int is_original_commit_empty(struct commit *commit)
1471 const struct object_id *ptree_oid;
1473 if (parse_commit(commit))
1474 return error(_("could not parse commit %s"),
1475 oid_to_hex(&commit->object.oid));
1476 if (commit->parents) {
1477 struct commit *parent = commit->parents->item;
1478 if (parse_commit(parent))
1479 return error(_("could not parse parent commit %s"),
1480 oid_to_hex(&parent->object.oid));
1481 ptree_oid = get_commit_tree_oid(parent);
1483 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1486 return oideq(ptree_oid, get_commit_tree_oid(commit));
1490 * Should empty commits be allowed? Return status:
1491 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1492 * 0: Halt on empty commit
1493 * 1: Allow empty commit
1494 * 2: Drop empty commit
1496 static int allow_empty(struct repository *r,
1497 struct replay_opts *opts,
1498 struct commit *commit)
1500 int index_unchanged, originally_empty;
1505 * (1) we do not allow empty at all and error out.
1507 * (2) we allow ones that were initially empty, and
1508 * just drop the ones that become empty
1510 * (3) we allow ones that were initially empty, but
1511 * halt for the ones that become empty;
1513 * (4) we allow both.
1515 if (!opts->allow_empty)
1516 return 0; /* let "git commit" barf as necessary */
1518 index_unchanged = is_index_unchanged(r);
1519 if (index_unchanged < 0)
1520 return index_unchanged;
1521 if (!index_unchanged)
1522 return 0; /* we do not have to say --allow-empty */
1524 if (opts->keep_redundant_commits)
1527 originally_empty = is_original_commit_empty(commit);
1528 if (originally_empty < 0)
1529 return originally_empty;
1530 if (originally_empty)
1532 else if (opts->drop_redundant_commits)
1541 } todo_command_info[] = {
1558 static const char *command_to_string(const enum todo_command command)
1560 if (command < TODO_COMMENT)
1561 return todo_command_info[command].str;
1562 die(_("unknown command: %d"), command);
1565 static char command_to_char(const enum todo_command command)
1567 if (command < TODO_COMMENT && todo_command_info[command].c)
1568 return todo_command_info[command].c;
1569 return comment_line_char;
1572 static int is_noop(const enum todo_command command)
1574 return TODO_NOOP <= command;
1577 static int is_fixup(enum todo_command command)
1579 return command == TODO_FIXUP || command == TODO_SQUASH;
1582 /* Does this command create a (non-merge) commit? */
1583 static int is_pick_or_similar(enum todo_command command)
1598 static int update_squash_messages(struct repository *r,
1599 enum todo_command command,
1600 struct commit *commit,
1601 struct replay_opts *opts)
1603 struct strbuf buf = STRBUF_INIT;
1605 const char *message, *body;
1606 const char *encoding = get_commit_output_encoding();
1608 if (opts->current_fixup_count > 0) {
1609 struct strbuf header = STRBUF_INIT;
1612 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1613 return error(_("could not read '%s'"),
1614 rebase_path_squash_msg());
1616 eol = buf.buf[0] != comment_line_char ?
1617 buf.buf : strchrnul(buf.buf, '\n');
1619 strbuf_addf(&header, "%c ", comment_line_char);
1620 strbuf_addf(&header, _("This is a combination of %d commits."),
1621 opts->current_fixup_count + 2);
1622 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1623 strbuf_release(&header);
1625 struct object_id head;
1626 struct commit *head_commit;
1627 const char *head_message, *body;
1629 if (get_oid("HEAD", &head))
1630 return error(_("need a HEAD to fixup"));
1631 if (!(head_commit = lookup_commit_reference(r, &head)))
1632 return error(_("could not read HEAD"));
1633 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1634 return error(_("could not read HEAD's commit message"));
1636 find_commit_subject(head_message, &body);
1637 if (write_message(body, strlen(body),
1638 rebase_path_fixup_msg(), 0)) {
1639 unuse_commit_buffer(head_commit, head_message);
1640 return error(_("cannot write '%s'"),
1641 rebase_path_fixup_msg());
1644 strbuf_addf(&buf, "%c ", comment_line_char);
1645 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1646 strbuf_addf(&buf, "\n%c ", comment_line_char);
1647 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1648 strbuf_addstr(&buf, "\n\n");
1649 strbuf_addstr(&buf, body);
1651 unuse_commit_buffer(head_commit, head_message);
1654 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1655 return error(_("could not read commit message of %s"),
1656 oid_to_hex(&commit->object.oid));
1657 find_commit_subject(message, &body);
1659 if (command == TODO_SQUASH) {
1660 unlink(rebase_path_fixup_msg());
1661 strbuf_addf(&buf, "\n%c ", comment_line_char);
1662 strbuf_addf(&buf, _("This is the commit message #%d:"),
1663 ++opts->current_fixup_count + 1);
1664 strbuf_addstr(&buf, "\n\n");
1665 strbuf_addstr(&buf, body);
1666 } else if (command == TODO_FIXUP) {
1667 strbuf_addf(&buf, "\n%c ", comment_line_char);
1668 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1669 ++opts->current_fixup_count + 1);
1670 strbuf_addstr(&buf, "\n\n");
1671 strbuf_add_commented_lines(&buf, body, strlen(body));
1673 return error(_("unknown command: %d"), command);
1674 unuse_commit_buffer(commit, message);
1676 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1677 strbuf_release(&buf);
1680 strbuf_addf(&opts->current_fixups, "%s%s %s",
1681 opts->current_fixups.len ? "\n" : "",
1682 command_to_string(command),
1683 oid_to_hex(&commit->object.oid));
1684 res = write_message(opts->current_fixups.buf,
1685 opts->current_fixups.len,
1686 rebase_path_current_fixups(), 0);
1692 static void flush_rewritten_pending(void)
1694 struct strbuf buf = STRBUF_INIT;
1695 struct object_id newoid;
1698 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1699 !get_oid("HEAD", &newoid) &&
1700 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1701 char *bol = buf.buf, *eol;
1704 eol = strchrnul(bol, '\n');
1705 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1706 bol, oid_to_hex(&newoid));
1712 unlink(rebase_path_rewritten_pending());
1714 strbuf_release(&buf);
1717 static void record_in_rewritten(struct object_id *oid,
1718 enum todo_command next_command)
1720 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1725 fprintf(out, "%s\n", oid_to_hex(oid));
1728 if (!is_fixup(next_command))
1729 flush_rewritten_pending();
1732 static int do_pick_commit(struct repository *r,
1733 enum todo_command command,
1734 struct commit *commit,
1735 struct replay_opts *opts,
1736 int final_fixup, int *check_todo)
1738 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1739 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1740 struct object_id head;
1741 struct commit *base, *next, *parent;
1742 const char *base_label, *next_label;
1743 char *author = NULL;
1744 struct commit_message msg = { NULL, NULL, NULL, NULL };
1745 struct strbuf msgbuf = STRBUF_INIT;
1746 int res, unborn = 0, reword = 0, allow, drop_commit;
1748 if (opts->no_commit) {
1750 * We do not intend to commit immediately. We just want to
1751 * merge the differences in, so let's compute the tree
1752 * that represents the "current" state for merge-recursive
1755 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1756 return error(_("your index file is unmerged."));
1758 unborn = get_oid("HEAD", &head);
1759 /* Do we want to generate a root commit? */
1760 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1761 oideq(&head, &opts->squash_onto)) {
1762 if (is_fixup(command))
1763 return error(_("cannot fixup root commit"));
1764 flags |= CREATE_ROOT_COMMIT;
1767 oidcpy(&head, the_hash_algo->empty_tree);
1768 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1770 return error_dirty_index(r, opts);
1772 discard_index(r->index);
1774 if (!commit->parents)
1776 else if (commit->parents->next) {
1777 /* Reverting or cherry-picking a merge commit */
1779 struct commit_list *p;
1781 if (!opts->mainline)
1782 return error(_("commit %s is a merge but no -m option was given."),
1783 oid_to_hex(&commit->object.oid));
1785 for (cnt = 1, p = commit->parents;
1786 cnt != opts->mainline && p;
1789 if (cnt != opts->mainline || !p)
1790 return error(_("commit %s does not have parent %d"),
1791 oid_to_hex(&commit->object.oid), opts->mainline);
1793 } else if (1 < opts->mainline)
1795 * Non-first parent explicitly specified as mainline for
1798 return error(_("commit %s does not have parent %d"),
1799 oid_to_hex(&commit->object.oid), opts->mainline);
1801 parent = commit->parents->item;
1803 if (get_message(commit, &msg) != 0)
1804 return error(_("cannot get commit message for %s"),
1805 oid_to_hex(&commit->object.oid));
1807 if (opts->allow_ff && !is_fixup(command) &&
1808 ((parent && oideq(&parent->object.oid, &head)) ||
1809 (!parent && unborn))) {
1810 if (is_rebase_i(opts))
1811 write_author_script(msg.message);
1812 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1814 if (res || command != TODO_REWORD)
1818 goto fast_forward_edit;
1820 if (parent && parse_commit(parent) < 0)
1821 /* TRANSLATORS: The first %s will be a "todo" command like
1822 "revert" or "pick", the second %s a SHA1. */
1823 return error(_("%s: cannot parse parent commit %s"),
1824 command_to_string(command),
1825 oid_to_hex(&parent->object.oid));
1828 * "commit" is an existing commit. We would want to apply
1829 * the difference it introduces since its first parent "prev"
1830 * on top of the current HEAD if we are cherry-pick. Or the
1831 * reverse of it if we are revert.
1834 if (command == TODO_REVERT) {
1836 base_label = msg.label;
1838 next_label = msg.parent_label;
1839 strbuf_addstr(&msgbuf, "Revert \"");
1840 strbuf_addstr(&msgbuf, msg.subject);
1841 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1842 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1844 if (commit->parents && commit->parents->next) {
1845 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1846 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1848 strbuf_addstr(&msgbuf, ".\n");
1853 base_label = msg.parent_label;
1855 next_label = msg.label;
1857 /* Append the commit log message to msgbuf. */
1858 if (find_commit_subject(msg.message, &p))
1859 strbuf_addstr(&msgbuf, p);
1861 if (opts->record_origin) {
1862 strbuf_complete_line(&msgbuf);
1863 if (!has_conforming_footer(&msgbuf, NULL, 0))
1864 strbuf_addch(&msgbuf, '\n');
1865 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1866 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1867 strbuf_addstr(&msgbuf, ")\n");
1869 if (!is_fixup(command))
1870 author = get_author(msg.message);
1873 if (command == TODO_REWORD)
1875 else if (is_fixup(command)) {
1876 if (update_squash_messages(r, command, commit, opts))
1880 msg_file = rebase_path_squash_msg();
1881 else if (file_exists(rebase_path_fixup_msg())) {
1882 flags |= CLEANUP_MSG;
1883 msg_file = rebase_path_fixup_msg();
1885 const char *dest = git_path_squash_msg(r);
1887 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1888 return error(_("could not rename '%s' to '%s'"),
1889 rebase_path_squash_msg(), dest);
1890 unlink(git_path_merge_msg(r));
1896 if (opts->signoff && !is_fixup(command))
1897 append_signoff(&msgbuf, 0, 0);
1899 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1901 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1902 res = do_recursive_merge(r, base, next, base_label, next_label,
1903 &head, &msgbuf, opts);
1907 res |= write_message(msgbuf.buf, msgbuf.len,
1908 git_path_merge_msg(r), 0);
1910 struct commit_list *common = NULL;
1911 struct commit_list *remotes = NULL;
1913 res = write_message(msgbuf.buf, msgbuf.len,
1914 git_path_merge_msg(r), 0);
1916 commit_list_insert(base, &common);
1917 commit_list_insert(next, &remotes);
1918 res |= try_merge_command(r, opts->strategy,
1919 opts->xopts_nr, (const char **)opts->xopts,
1920 common, oid_to_hex(&head), remotes);
1921 free_commit_list(common);
1922 free_commit_list(remotes);
1924 strbuf_release(&msgbuf);
1927 * If the merge was clean or if it failed due to conflict, we write
1928 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1929 * However, if the merge did not even start, then we don't want to
1932 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1933 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1934 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1936 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1937 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1938 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1942 error(command == TODO_REVERT
1943 ? _("could not revert %s... %s")
1944 : _("could not apply %s... %s"),
1945 short_commit_name(commit), msg.subject);
1946 print_advice(r, res == 1, opts);
1947 repo_rerere(r, opts->allow_rerere_auto);
1952 allow = allow_empty(r, opts, commit);
1956 } else if (allow == 1) {
1957 flags |= ALLOW_EMPTY;
1958 } else if (allow == 2) {
1960 unlink(git_path_cherry_pick_head(r));
1961 unlink(git_path_merge_msg(r));
1963 _("dropping %s %s -- patch contents already upstream\n"),
1964 oid_to_hex(&commit->object.oid), msg.subject);
1965 } /* else allow == 0 and there's nothing special to do */
1966 if (!opts->no_commit && !drop_commit) {
1967 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1968 res = do_commit(r, msg_file, author, opts, flags);
1970 res = error(_("unable to parse commit author"));
1971 *check_todo = !!(flags & EDIT_MSG);
1972 if (!res && reword) {
1974 res = run_git_commit(r, NULL, opts, EDIT_MSG |
1975 VERIFY_MSG | AMEND_MSG |
1976 (flags & ALLOW_EMPTY));
1982 if (!res && final_fixup) {
1983 unlink(rebase_path_fixup_msg());
1984 unlink(rebase_path_squash_msg());
1985 unlink(rebase_path_current_fixups());
1986 strbuf_reset(&opts->current_fixups);
1987 opts->current_fixup_count = 0;
1991 free_message(commit, &msg);
1993 update_abort_safety_file();
1998 static int prepare_revs(struct replay_opts *opts)
2001 * picking (but not reverting) ranges (but not individual revisions)
2002 * should be done in reverse
2004 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2005 opts->revs->reverse ^= 1;
2007 if (prepare_revision_walk(opts->revs))
2008 return error(_("revision walk setup failed"));
2013 static int read_and_refresh_cache(struct repository *r,
2014 struct replay_opts *opts)
2016 struct lock_file index_lock = LOCK_INIT;
2017 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2018 if (repo_read_index(r) < 0) {
2019 rollback_lock_file(&index_lock);
2020 return error(_("git %s: failed to read the index"),
2021 _(action_name(opts)));
2023 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2024 if (index_fd >= 0) {
2025 if (write_locked_index(r->index, &index_lock,
2026 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2027 return error(_("git %s: failed to refresh the index"),
2028 _(action_name(opts)));
2034 enum todo_item_flags {
2035 TODO_EDIT_MERGE_MSG = 1
2038 void todo_list_release(struct todo_list *todo_list)
2040 strbuf_release(&todo_list->buf);
2041 FREE_AND_NULL(todo_list->items);
2042 todo_list->nr = todo_list->alloc = 0;
2045 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2047 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2048 todo_list->total_nr++;
2049 return todo_list->items + todo_list->nr++;
2052 const char *todo_item_get_arg(struct todo_list *todo_list,
2053 struct todo_item *item)
2055 return todo_list->buf.buf + item->arg_offset;
2058 static int is_command(enum todo_command command, const char **bol)
2060 const char *str = todo_command_info[command].str;
2061 const char nick = todo_command_info[command].c;
2062 const char *p = *bol + 1;
2064 return skip_prefix(*bol, str, bol) ||
2065 ((nick && **bol == nick) &&
2066 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2070 static int parse_insn_line(struct repository *r, struct todo_item *item,
2071 const char *buf, const char *bol, char *eol)
2073 struct object_id commit_oid;
2074 char *end_of_object_name;
2075 int i, saved, status, padding;
2080 bol += strspn(bol, " \t");
2082 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2083 item->command = TODO_COMMENT;
2084 item->commit = NULL;
2085 item->arg_offset = bol - buf;
2086 item->arg_len = eol - bol;
2090 for (i = 0; i < TODO_COMMENT; i++)
2091 if (is_command(i, &bol)) {
2095 if (i >= TODO_COMMENT)
2098 /* Eat up extra spaces/ tabs before object name */
2099 padding = strspn(bol, " \t");
2102 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2104 return error(_("%s does not accept arguments: '%s'"),
2105 command_to_string(item->command), bol);
2106 item->commit = NULL;
2107 item->arg_offset = bol - buf;
2108 item->arg_len = eol - bol;
2113 return error(_("missing arguments for %s"),
2114 command_to_string(item->command));
2116 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2117 item->command == TODO_RESET) {
2118 item->commit = NULL;
2119 item->arg_offset = bol - buf;
2120 item->arg_len = (int)(eol - bol);
2124 if (item->command == TODO_MERGE) {
2125 if (skip_prefix(bol, "-C", &bol))
2126 bol += strspn(bol, " \t");
2127 else if (skip_prefix(bol, "-c", &bol)) {
2128 bol += strspn(bol, " \t");
2129 item->flags |= TODO_EDIT_MERGE_MSG;
2131 item->flags |= TODO_EDIT_MERGE_MSG;
2132 item->commit = NULL;
2133 item->arg_offset = bol - buf;
2134 item->arg_len = (int)(eol - bol);
2139 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2140 saved = *end_of_object_name;
2141 *end_of_object_name = '\0';
2142 status = get_oid(bol, &commit_oid);
2144 error(_("could not parse '%s'"), bol); /* return later */
2145 *end_of_object_name = saved;
2147 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2148 item->arg_offset = bol - buf;
2149 item->arg_len = (int)(eol - bol);
2154 item->commit = lookup_commit_reference(r, &commit_oid);
2155 return item->commit ? 0 : -1;
2158 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2160 const char *todo_file, *bol;
2161 struct strbuf buf = STRBUF_INIT;
2164 todo_file = git_path_todo_file();
2165 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2166 if (errno == ENOENT || errno == ENOTDIR)
2169 return error_errno("unable to open '%s'", todo_file);
2171 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2172 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2173 *action = REPLAY_PICK;
2174 else if (is_command(TODO_REVERT, &bol) &&
2175 (*bol == ' ' || *bol == '\t'))
2176 *action = REPLAY_REVERT;
2180 strbuf_release(&buf);
2185 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2186 struct todo_list *todo_list)
2188 struct todo_item *item;
2189 char *p = buf, *next_p;
2190 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2192 todo_list->current = todo_list->nr = 0;
2194 for (i = 1; *p; i++, p = next_p) {
2195 char *eol = strchrnul(p, '\n');
2197 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2199 if (p != eol && eol[-1] == '\r')
2200 eol--; /* strip Carriage Return */
2202 item = append_new_todo(todo_list);
2203 item->offset_in_buf = p - todo_list->buf.buf;
2204 if (parse_insn_line(r, item, buf, p, eol)) {
2205 res = error(_("invalid line %d: %.*s"),
2206 i, (int)(eol - p), p);
2207 item->command = TODO_COMMENT + 1;
2208 item->arg_offset = p - buf;
2209 item->arg_len = (int)(eol - p);
2210 item->commit = NULL;
2215 else if (is_fixup(item->command))
2216 return error(_("cannot '%s' without a previous commit"),
2217 command_to_string(item->command));
2218 else if (!is_noop(item->command))
2225 static int count_commands(struct todo_list *todo_list)
2229 for (i = 0; i < todo_list->nr; i++)
2230 if (todo_list->items[i].command != TODO_COMMENT)
2236 static int get_item_line_offset(struct todo_list *todo_list, int index)
2238 return index < todo_list->nr ?
2239 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2242 static const char *get_item_line(struct todo_list *todo_list, int index)
2244 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2247 static int get_item_line_length(struct todo_list *todo_list, int index)
2249 return get_item_line_offset(todo_list, index + 1)
2250 - get_item_line_offset(todo_list, index);
2253 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2258 fd = open(path, O_RDONLY);
2260 return error_errno(_("could not open '%s'"), path);
2261 len = strbuf_read(sb, fd, 0);
2264 return error(_("could not read '%s'."), path);
2268 static int have_finished_the_last_pick(void)
2270 struct strbuf buf = STRBUF_INIT;
2272 const char *todo_path = git_path_todo_file();
2275 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2276 if (errno == ENOENT) {
2279 error_errno("unable to open '%s'", todo_path);
2283 /* If there is only one line then we are done */
2284 eol = strchr(buf.buf, '\n');
2285 if (!eol || !eol[1])
2288 strbuf_release(&buf);
2293 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2295 struct replay_opts opts = REPLAY_OPTS_INIT;
2296 int need_cleanup = 0;
2298 if (file_exists(git_path_cherry_pick_head(r))) {
2299 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2300 warning(_("cancelling a cherry picking in progress"));
2301 opts.action = REPLAY_PICK;
2305 if (file_exists(git_path_revert_head(r))) {
2306 if (!unlink(git_path_revert_head(r)) && verbose)
2307 warning(_("cancelling a revert in progress"));
2308 opts.action = REPLAY_REVERT;
2315 if (!have_finished_the_last_pick())
2318 sequencer_remove_state(&opts);
2321 static void todo_list_write_total_nr(struct todo_list *todo_list)
2323 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2326 fprintf(f, "%d\n", todo_list->total_nr);
2331 static int read_populate_todo(struct repository *r,
2332 struct todo_list *todo_list,
2333 struct replay_opts *opts)
2336 const char *todo_file = get_todo_path(opts);
2339 strbuf_reset(&todo_list->buf);
2340 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2343 res = stat(todo_file, &st);
2345 return error(_("could not stat '%s'"), todo_file);
2346 fill_stat_data(&todo_list->stat, &st);
2348 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2350 if (is_rebase_i(opts))
2351 return error(_("please fix this using "
2352 "'git rebase --edit-todo'."));
2353 return error(_("unusable instruction sheet: '%s'"), todo_file);
2356 if (!todo_list->nr &&
2357 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2358 return error(_("no commits parsed."));
2360 if (!is_rebase_i(opts)) {
2361 enum todo_command valid =
2362 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2365 for (i = 0; i < todo_list->nr; i++)
2366 if (valid == todo_list->items[i].command)
2368 else if (valid == TODO_PICK)
2369 return error(_("cannot cherry-pick during a revert."));
2371 return error(_("cannot revert during a cherry-pick."));
2374 if (is_rebase_i(opts)) {
2375 struct todo_list done = TODO_LIST_INIT;
2377 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2378 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2379 todo_list->done_nr = count_commands(&done);
2381 todo_list->done_nr = 0;
2383 todo_list->total_nr = todo_list->done_nr
2384 + count_commands(todo_list);
2385 todo_list_release(&done);
2387 todo_list_write_total_nr(todo_list);
2393 static int git_config_string_dup(char **dest,
2394 const char *var, const char *value)
2397 return config_error_nonbool(var);
2399 *dest = xstrdup(value);
2403 static int populate_opts_cb(const char *key, const char *value, void *data)
2405 struct replay_opts *opts = data;
2410 else if (!strcmp(key, "options.no-commit"))
2411 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2412 else if (!strcmp(key, "options.edit"))
2413 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2414 else if (!strcmp(key, "options.allow-empty"))
2416 git_config_bool_or_int(key, value, &error_flag);
2417 else if (!strcmp(key, "options.allow-empty-message"))
2418 opts->allow_empty_message =
2419 git_config_bool_or_int(key, value, &error_flag);
2420 else if (!strcmp(key, "options.keep-redundant-commits"))
2421 opts->keep_redundant_commits =
2422 git_config_bool_or_int(key, value, &error_flag);
2423 else if (!strcmp(key, "options.signoff"))
2424 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2425 else if (!strcmp(key, "options.record-origin"))
2426 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2427 else if (!strcmp(key, "options.allow-ff"))
2428 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2429 else if (!strcmp(key, "options.mainline"))
2430 opts->mainline = git_config_int(key, value);
2431 else if (!strcmp(key, "options.strategy"))
2432 git_config_string_dup(&opts->strategy, key, value);
2433 else if (!strcmp(key, "options.gpg-sign"))
2434 git_config_string_dup(&opts->gpg_sign, key, value);
2435 else if (!strcmp(key, "options.strategy-option")) {
2436 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2437 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2438 } else if (!strcmp(key, "options.allow-rerere-auto"))
2439 opts->allow_rerere_auto =
2440 git_config_bool_or_int(key, value, &error_flag) ?
2441 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2442 else if (!strcmp(key, "options.default-msg-cleanup")) {
2443 opts->explicit_cleanup = 1;
2444 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2446 return error(_("invalid key: %s"), key);
2449 return error(_("invalid value for %s: %s"), key, value);
2454 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2457 char *strategy_opts_string = raw_opts;
2459 if (*strategy_opts_string == ' ')
2460 strategy_opts_string++;
2462 opts->xopts_nr = split_cmdline(strategy_opts_string,
2463 (const char ***)&opts->xopts);
2464 for (i = 0; i < opts->xopts_nr; i++) {
2465 const char *arg = opts->xopts[i];
2467 skip_prefix(arg, "--", &arg);
2468 opts->xopts[i] = xstrdup(arg);
2472 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2475 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2477 opts->strategy = strbuf_detach(buf, NULL);
2478 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2481 parse_strategy_opts(opts, buf->buf);
2484 static int read_populate_opts(struct replay_opts *opts)
2486 if (is_rebase_i(opts)) {
2487 struct strbuf buf = STRBUF_INIT;
2490 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2491 READ_ONELINER_SKIP_IF_EMPTY)) {
2492 if (!starts_with(buf.buf, "-S"))
2495 free(opts->gpg_sign);
2496 opts->gpg_sign = xstrdup(buf.buf + 2);
2501 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2502 READ_ONELINER_SKIP_IF_EMPTY)) {
2503 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2504 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2505 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2506 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2510 if (file_exists(rebase_path_verbose()))
2513 if (file_exists(rebase_path_quiet()))
2516 if (file_exists(rebase_path_signoff())) {
2521 if (file_exists(rebase_path_reschedule_failed_exec()))
2522 opts->reschedule_failed_exec = 1;
2524 if (file_exists(rebase_path_drop_redundant_commits()))
2525 opts->drop_redundant_commits = 1;
2527 if (file_exists(rebase_path_keep_redundant_commits()))
2528 opts->keep_redundant_commits = 1;
2530 read_strategy_opts(opts, &buf);
2533 if (read_oneliner(&opts->current_fixups,
2534 rebase_path_current_fixups(),
2535 READ_ONELINER_SKIP_IF_EMPTY)) {
2536 const char *p = opts->current_fixups.buf;
2537 opts->current_fixup_count = 1;
2538 while ((p = strchr(p, '\n'))) {
2539 opts->current_fixup_count++;
2544 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2545 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0) {
2546 ret = error(_("unusable squash-onto"));
2549 opts->have_squash_onto = 1;
2553 strbuf_release(&buf);
2557 if (!file_exists(git_path_opts_file()))
2560 * The function git_parse_source(), called from git_config_from_file(),
2561 * may die() in case of a syntactically incorrect file. We do not care
2562 * about this case, though, because we wrote that file ourselves, so we
2563 * are pretty certain that it is syntactically correct.
2565 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2566 return error(_("malformed options sheet: '%s'"),
2567 git_path_opts_file());
2571 static void write_strategy_opts(struct replay_opts *opts)
2574 struct strbuf buf = STRBUF_INIT;
2576 for (i = 0; i < opts->xopts_nr; ++i)
2577 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2579 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2580 strbuf_release(&buf);
2583 int write_basic_state(struct replay_opts *opts, const char *head_name,
2584 struct commit *onto, const char *orig_head)
2587 write_file(rebase_path_head_name(), "%s\n", head_name);
2589 write_file(rebase_path_onto(), "%s\n",
2590 oid_to_hex(&onto->object.oid));
2592 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2595 write_file(rebase_path_quiet(), "%s", "");
2597 write_file(rebase_path_verbose(), "%s", "");
2599 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2600 if (opts->xopts_nr > 0)
2601 write_strategy_opts(opts);
2603 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2604 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2605 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2606 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2609 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2611 write_file(rebase_path_signoff(), "--signoff\n");
2612 if (opts->drop_redundant_commits)
2613 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2614 if (opts->keep_redundant_commits)
2615 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2616 if (opts->reschedule_failed_exec)
2617 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2622 static int walk_revs_populate_todo(struct todo_list *todo_list,
2623 struct replay_opts *opts)
2625 enum todo_command command = opts->action == REPLAY_PICK ?
2626 TODO_PICK : TODO_REVERT;
2627 const char *command_string = todo_command_info[command].str;
2628 const char *encoding;
2629 struct commit *commit;
2631 if (prepare_revs(opts))
2634 encoding = get_log_output_encoding();
2636 while ((commit = get_revision(opts->revs))) {
2637 struct todo_item *item = append_new_todo(todo_list);
2638 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2639 const char *subject;
2642 item->command = command;
2643 item->commit = commit;
2644 item->arg_offset = 0;
2646 item->offset_in_buf = todo_list->buf.len;
2647 subject_len = find_commit_subject(commit_buffer, &subject);
2648 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2649 short_commit_name(commit), subject_len, subject);
2650 unuse_commit_buffer(commit, commit_buffer);
2654 return error(_("empty commit set passed"));
2659 static int create_seq_dir(struct repository *r)
2661 enum replay_action action;
2662 const char *in_progress_error = NULL;
2663 const char *in_progress_advice = NULL;
2664 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2665 file_exists(git_path_cherry_pick_head(r));
2667 if (!sequencer_get_last_command(r, &action)) {
2670 in_progress_error = _("revert is already in progress");
2671 in_progress_advice =
2672 _("try \"git revert (--continue | %s--abort | --quit)\"");
2675 in_progress_error = _("cherry-pick is already in progress");
2676 in_progress_advice =
2677 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2680 BUG("unexpected action in create_seq_dir");
2683 if (in_progress_error) {
2684 error("%s", in_progress_error);
2685 if (advice_sequencer_in_use)
2686 advise(in_progress_advice,
2687 advise_skip ? "--skip | " : "");
2690 if (mkdir(git_path_seq_dir(), 0777) < 0)
2691 return error_errno(_("could not create sequencer directory '%s'"),
2692 git_path_seq_dir());
2697 static int save_head(const char *head)
2699 struct lock_file head_lock = LOCK_INIT;
2700 struct strbuf buf = STRBUF_INIT;
2704 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2706 return error_errno(_("could not lock HEAD"));
2707 strbuf_addf(&buf, "%s\n", head);
2708 written = write_in_full(fd, buf.buf, buf.len);
2709 strbuf_release(&buf);
2711 error_errno(_("could not write to '%s'"), git_path_head_file());
2712 rollback_lock_file(&head_lock);
2715 if (commit_lock_file(&head_lock) < 0)
2716 return error(_("failed to finalize '%s'"), git_path_head_file());
2720 static int rollback_is_safe(void)
2722 struct strbuf sb = STRBUF_INIT;
2723 struct object_id expected_head, actual_head;
2725 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2727 if (get_oid_hex(sb.buf, &expected_head)) {
2728 strbuf_release(&sb);
2729 die(_("could not parse %s"), git_path_abort_safety_file());
2731 strbuf_release(&sb);
2733 else if (errno == ENOENT)
2734 oidclr(&expected_head);
2736 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2738 if (get_oid("HEAD", &actual_head))
2739 oidclr(&actual_head);
2741 return oideq(&actual_head, &expected_head);
2744 static int reset_merge(const struct object_id *oid)
2747 struct argv_array argv = ARGV_ARRAY_INIT;
2749 argv_array_pushl(&argv, "reset", "--merge", NULL);
2751 if (!is_null_oid(oid))
2752 argv_array_push(&argv, oid_to_hex(oid));
2754 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2755 argv_array_clear(&argv);
2760 static int rollback_single_pick(struct repository *r)
2762 struct object_id head_oid;
2764 if (!file_exists(git_path_cherry_pick_head(r)) &&
2765 !file_exists(git_path_revert_head(r)))
2766 return error(_("no cherry-pick or revert in progress"));
2767 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2768 return error(_("cannot resolve HEAD"));
2769 if (is_null_oid(&head_oid))
2770 return error(_("cannot abort from a branch yet to be born"));
2771 return reset_merge(&head_oid);
2774 static int skip_single_pick(void)
2776 struct object_id head;
2778 if (read_ref_full("HEAD", 0, &head, NULL))
2779 return error(_("cannot resolve HEAD"));
2780 return reset_merge(&head);
2783 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2786 struct object_id oid;
2787 struct strbuf buf = STRBUF_INIT;
2790 f = fopen(git_path_head_file(), "r");
2791 if (!f && errno == ENOENT) {
2793 * There is no multiple-cherry-pick in progress.
2794 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2795 * a single-cherry-pick in progress, abort that.
2797 return rollback_single_pick(r);
2800 return error_errno(_("cannot open '%s'"), git_path_head_file());
2801 if (strbuf_getline_lf(&buf, f)) {
2802 error(_("cannot read '%s': %s"), git_path_head_file(),
2803 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2808 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2809 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2810 git_path_head_file());
2813 if (is_null_oid(&oid)) {
2814 error(_("cannot abort from a branch yet to be born"));
2818 if (!rollback_is_safe()) {
2819 /* Do not error, just do not rollback */
2820 warning(_("You seem to have moved HEAD. "
2821 "Not rewinding, check your HEAD!"));
2823 if (reset_merge(&oid))
2825 strbuf_release(&buf);
2826 return sequencer_remove_state(opts);
2828 strbuf_release(&buf);
2832 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2834 enum replay_action action = -1;
2835 sequencer_get_last_command(r, &action);
2838 * Check whether the subcommand requested to skip the commit is actually
2839 * in progress and that it's safe to skip the commit.
2841 * opts->action tells us which subcommand requested to skip the commit.
2842 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2843 * action is in progress and we can skip the commit.
2845 * Otherwise we check that the last instruction was related to the
2846 * particular subcommand we're trying to execute and barf if that's not
2849 * Finally we check that the rollback is "safe", i.e., has the HEAD
2850 * moved? In this case, it doesn't make sense to "reset the merge" and
2851 * "skip the commit" as the user already handled this by committing. But
2852 * we'd not want to barf here, instead give advice on how to proceed. We
2853 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2854 * it gets removed when the user commits, so if it still exists we're
2855 * sure the user can't have committed before.
2857 switch (opts->action) {
2859 if (!file_exists(git_path_revert_head(r))) {
2860 if (action != REPLAY_REVERT)
2861 return error(_("no revert in progress"));
2862 if (!rollback_is_safe())
2867 if (!file_exists(git_path_cherry_pick_head(r))) {
2868 if (action != REPLAY_PICK)
2869 return error(_("no cherry-pick in progress"));
2870 if (!rollback_is_safe())
2875 BUG("unexpected action in sequencer_skip");
2878 if (skip_single_pick())
2879 return error(_("failed to skip the commit"));
2880 if (!is_directory(git_path_seq_dir()))
2883 return sequencer_continue(r, opts);
2886 error(_("there is nothing to skip"));
2888 if (advice_resolve_conflict) {
2889 advise(_("have you committed already?\n"
2890 "try \"git %s --continue\""),
2891 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2896 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2898 struct lock_file todo_lock = LOCK_INIT;
2899 const char *todo_path = get_todo_path(opts);
2900 int next = todo_list->current, offset, fd;
2903 * rebase -i writes "git-rebase-todo" without the currently executing
2904 * command, appending it to "done" instead.
2906 if (is_rebase_i(opts))
2909 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2911 return error_errno(_("could not lock '%s'"), todo_path);
2912 offset = get_item_line_offset(todo_list, next);
2913 if (write_in_full(fd, todo_list->buf.buf + offset,
2914 todo_list->buf.len - offset) < 0)
2915 return error_errno(_("could not write to '%s'"), todo_path);
2916 if (commit_lock_file(&todo_lock) < 0)
2917 return error(_("failed to finalize '%s'"), todo_path);
2919 if (is_rebase_i(opts) && next > 0) {
2920 const char *done = rebase_path_done();
2921 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2926 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2927 get_item_line_length(todo_list, next - 1))
2929 ret = error_errno(_("could not write to '%s'"), done);
2931 ret = error_errno(_("failed to finalize '%s'"), done);
2937 static int save_opts(struct replay_opts *opts)
2939 const char *opts_file = git_path_opts_file();
2942 if (opts->no_commit)
2943 res |= git_config_set_in_file_gently(opts_file,
2944 "options.no-commit", "true");
2946 res |= git_config_set_in_file_gently(opts_file,
2947 "options.edit", "true");
2948 if (opts->allow_empty)
2949 res |= git_config_set_in_file_gently(opts_file,
2950 "options.allow-empty", "true");
2951 if (opts->allow_empty_message)
2952 res |= git_config_set_in_file_gently(opts_file,
2953 "options.allow-empty-message", "true");
2954 if (opts->keep_redundant_commits)
2955 res |= git_config_set_in_file_gently(opts_file,
2956 "options.keep-redundant-commits", "true");
2958 res |= git_config_set_in_file_gently(opts_file,
2959 "options.signoff", "true");
2960 if (opts->record_origin)
2961 res |= git_config_set_in_file_gently(opts_file,
2962 "options.record-origin", "true");
2964 res |= git_config_set_in_file_gently(opts_file,
2965 "options.allow-ff", "true");
2966 if (opts->mainline) {
2967 struct strbuf buf = STRBUF_INIT;
2968 strbuf_addf(&buf, "%d", opts->mainline);
2969 res |= git_config_set_in_file_gently(opts_file,
2970 "options.mainline", buf.buf);
2971 strbuf_release(&buf);
2974 res |= git_config_set_in_file_gently(opts_file,
2975 "options.strategy", opts->strategy);
2977 res |= git_config_set_in_file_gently(opts_file,
2978 "options.gpg-sign", opts->gpg_sign);
2981 for (i = 0; i < opts->xopts_nr; i++)
2982 res |= git_config_set_multivar_in_file_gently(opts_file,
2983 "options.strategy-option",
2984 opts->xopts[i], "^$", 0);
2986 if (opts->allow_rerere_auto)
2987 res |= git_config_set_in_file_gently(opts_file,
2988 "options.allow-rerere-auto",
2989 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2992 if (opts->explicit_cleanup)
2993 res |= git_config_set_in_file_gently(opts_file,
2994 "options.default-msg-cleanup",
2995 describe_cleanup_mode(opts->default_msg_cleanup));
2999 static int make_patch(struct repository *r,
3000 struct commit *commit,
3001 struct replay_opts *opts)
3003 struct strbuf buf = STRBUF_INIT;
3004 struct rev_info log_tree_opt;
3005 const char *subject, *p;
3008 p = short_commit_name(commit);
3009 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3011 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
3012 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
3013 res |= error(_("could not update %s"), "REBASE_HEAD");
3015 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3016 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3017 repo_init_revisions(r, &log_tree_opt, NULL);
3018 log_tree_opt.abbrev = 0;
3019 log_tree_opt.diff = 1;
3020 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3021 log_tree_opt.disable_stdin = 1;
3022 log_tree_opt.no_commit_id = 1;
3023 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3024 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3025 if (!log_tree_opt.diffopt.file)
3026 res |= error_errno(_("could not open '%s'"), buf.buf);
3028 res |= log_tree_commit(&log_tree_opt, commit);
3029 fclose(log_tree_opt.diffopt.file);
3033 strbuf_addf(&buf, "%s/message", get_dir(opts));
3034 if (!file_exists(buf.buf)) {
3035 const char *encoding = get_commit_output_encoding();
3036 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3037 find_commit_subject(commit_buffer, &subject);
3038 res |= write_message(subject, strlen(subject), buf.buf, 1);
3039 unuse_commit_buffer(commit, commit_buffer);
3041 strbuf_release(&buf);
3046 static int intend_to_amend(void)
3048 struct object_id head;
3051 if (get_oid("HEAD", &head))
3052 return error(_("cannot read HEAD"));
3054 p = oid_to_hex(&head);
3055 return write_message(p, strlen(p), rebase_path_amend(), 1);
3058 static int error_with_patch(struct repository *r,
3059 struct commit *commit,
3060 const char *subject, int subject_len,
3061 struct replay_opts *opts,
3062 int exit_code, int to_amend)
3065 if (make_patch(r, commit, opts))
3067 } else if (copy_file(rebase_path_message(),
3068 git_path_merge_msg(r), 0666))
3069 return error(_("unable to copy '%s' to '%s'"),
3070 git_path_merge_msg(r), rebase_path_message());
3073 if (intend_to_amend())
3077 _("You can amend the commit now, with\n"
3079 " git commit --amend %s\n"
3081 "Once you are satisfied with your changes, run\n"
3083 " git rebase --continue\n"),
3084 gpg_sign_opt_quoted(opts));
3085 } else if (exit_code) {
3087 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3088 short_commit_name(commit), subject_len, subject);
3091 * We don't have the hash of the parent so
3092 * just print the line from the todo file.
3094 fprintf_ln(stderr, _("Could not merge %.*s"),
3095 subject_len, subject);
3101 static int error_failed_squash(struct repository *r,
3102 struct commit *commit,
3103 struct replay_opts *opts,
3105 const char *subject)
3107 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3108 return error(_("could not copy '%s' to '%s'"),
3109 rebase_path_squash_msg(), rebase_path_message());
3110 unlink(git_path_merge_msg(r));
3111 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3112 return error(_("could not copy '%s' to '%s'"),
3113 rebase_path_message(),
3114 git_path_merge_msg(r));
3115 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3118 static int do_exec(struct repository *r, const char *command_line)
3120 struct argv_array child_env = ARGV_ARRAY_INIT;
3121 const char *child_argv[] = { NULL, NULL };
3124 fprintf(stderr, "Executing: %s\n", command_line);
3125 child_argv[0] = command_line;
3126 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3127 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3128 absolute_path(get_git_work_tree()));
3129 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3132 /* force re-reading of the cache */
3133 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3134 return error(_("could not read index"));
3136 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3139 warning(_("execution failed: %s\n%s"
3140 "You can fix the problem, and then run\n"
3142 " git rebase --continue\n"
3145 dirty ? N_("and made changes to the index and/or the "
3146 "working tree\n") : "");
3148 /* command not found */
3151 warning(_("execution succeeded: %s\nbut "
3152 "left changes to the index and/or the working tree\n"
3153 "Commit or stash your changes, and then run\n"
3155 " git rebase --continue\n"
3156 "\n"), command_line);
3160 argv_array_clear(&child_env);
3165 static int safe_append(const char *filename, const char *fmt, ...)
3168 struct lock_file lock = LOCK_INIT;
3169 int fd = hold_lock_file_for_update(&lock, filename,
3170 LOCK_REPORT_ON_ERROR);
3171 struct strbuf buf = STRBUF_INIT;
3176 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3177 error_errno(_("could not read '%s'"), filename);
3178 rollback_lock_file(&lock);
3181 strbuf_complete(&buf, '\n');
3183 strbuf_vaddf(&buf, fmt, ap);
3186 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3187 error_errno(_("could not write to '%s'"), filename);
3188 strbuf_release(&buf);
3189 rollback_lock_file(&lock);
3192 if (commit_lock_file(&lock) < 0) {
3193 strbuf_release(&buf);
3194 rollback_lock_file(&lock);
3195 return error(_("failed to finalize '%s'"), filename);
3198 strbuf_release(&buf);
3202 static int do_label(struct repository *r, const char *name, int len)
3204 struct ref_store *refs = get_main_ref_store(r);
3205 struct ref_transaction *transaction;
3206 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3207 struct strbuf msg = STRBUF_INIT;
3209 struct object_id head_oid;
3211 if (len == 1 && *name == '#')
3212 return error(_("illegal label name: '%.*s'"), len, name);
3214 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3215 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3217 transaction = ref_store_transaction_begin(refs, &err);
3219 error("%s", err.buf);
3221 } else if (get_oid("HEAD", &head_oid)) {
3222 error(_("could not read HEAD"));
3224 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3225 NULL, 0, msg.buf, &err) < 0 ||
3226 ref_transaction_commit(transaction, &err)) {
3227 error("%s", err.buf);
3230 ref_transaction_free(transaction);
3231 strbuf_release(&err);
3232 strbuf_release(&msg);
3235 ret = safe_append(rebase_path_refs_to_delete(),
3236 "%s\n", ref_name.buf);
3237 strbuf_release(&ref_name);
3242 static const char *reflog_message(struct replay_opts *opts,
3243 const char *sub_action, const char *fmt, ...);
3245 static int do_reset(struct repository *r,
3246 const char *name, int len,
3247 struct replay_opts *opts)
3249 struct strbuf ref_name = STRBUF_INIT;
3250 struct object_id oid;
3251 struct lock_file lock = LOCK_INIT;
3252 struct tree_desc desc;
3254 struct unpack_trees_options unpack_tree_opts;
3257 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3260 if (len == 10 && !strncmp("[new root]", name, len)) {
3261 if (!opts->have_squash_onto) {
3263 if (commit_tree("", 0, the_hash_algo->empty_tree,
3264 NULL, &opts->squash_onto,
3266 return error(_("writing fake root commit"));
3267 opts->have_squash_onto = 1;
3268 hex = oid_to_hex(&opts->squash_onto);
3269 if (write_message(hex, strlen(hex),
3270 rebase_path_squash_onto(), 0))
3271 return error(_("writing squash-onto"));
3273 oidcpy(&oid, &opts->squash_onto);
3277 /* Determine the length of the label */
3278 for (i = 0; i < len; i++)
3279 if (isspace(name[i]))
3283 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3284 if (get_oid(ref_name.buf, &oid) &&
3285 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3286 error(_("could not read '%s'"), ref_name.buf);
3287 rollback_lock_file(&lock);
3288 strbuf_release(&ref_name);
3293 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3294 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3295 unpack_tree_opts.head_idx = 1;
3296 unpack_tree_opts.src_index = r->index;
3297 unpack_tree_opts.dst_index = r->index;
3298 unpack_tree_opts.fn = oneway_merge;
3299 unpack_tree_opts.merge = 1;
3300 unpack_tree_opts.update = 1;
3302 if (repo_read_index_unmerged(r)) {
3303 rollback_lock_file(&lock);
3304 strbuf_release(&ref_name);
3305 return error_resolve_conflict(_(action_name(opts)));
3308 if (!fill_tree_descriptor(r, &desc, &oid)) {
3309 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3310 rollback_lock_file(&lock);
3311 free((void *)desc.buffer);
3312 strbuf_release(&ref_name);
3316 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3317 rollback_lock_file(&lock);
3318 free((void *)desc.buffer);
3319 strbuf_release(&ref_name);
3323 tree = parse_tree_indirect(&oid);
3324 prime_cache_tree(r, r->index, tree);
3326 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3327 ret = error(_("could not write index"));
3328 free((void *)desc.buffer);
3331 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3332 len, name), "HEAD", &oid,
3333 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3335 strbuf_release(&ref_name);
3339 static struct commit *lookup_label(const char *label, int len,
3342 struct commit *commit;
3345 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3346 commit = lookup_commit_reference_by_name(buf->buf);
3348 /* fall back to non-rewritten ref or commit */
3349 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3350 commit = lookup_commit_reference_by_name(buf->buf);
3354 error(_("could not resolve '%s'"), buf->buf);
3359 static int do_merge(struct repository *r,
3360 struct commit *commit,
3361 const char *arg, int arg_len,
3362 int flags, struct replay_opts *opts)
3364 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3365 EDIT_MSG | VERIFY_MSG : 0;
3366 struct strbuf ref_name = STRBUF_INIT;
3367 struct commit *head_commit, *merge_commit, *i;
3368 struct commit_list *bases, *j, *reversed = NULL;
3369 struct commit_list *to_merge = NULL, **tail = &to_merge;
3370 const char *strategy = !opts->xopts_nr &&
3371 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3372 NULL : opts->strategy;
3373 struct merge_options o;
3374 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3375 static struct lock_file lock;
3378 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3383 head_commit = lookup_commit_reference_by_name("HEAD");
3385 ret = error(_("cannot merge without a current revision"));
3390 * For octopus merges, the arg starts with the list of revisions to be
3391 * merged. The list is optionally followed by '#' and the oneline.
3393 merge_arg_len = oneline_offset = arg_len;
3394 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3397 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3398 p += 1 + strspn(p + 1, " \t\n");
3399 oneline_offset = p - arg;
3402 k = strcspn(p, " \t\n");
3405 merge_commit = lookup_label(p, k, &ref_name);
3406 if (!merge_commit) {
3407 ret = error(_("unable to parse '%.*s'"), k, p);
3410 tail = &commit_list_insert(merge_commit, tail)->next;
3412 merge_arg_len = p - arg;
3416 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3420 if (opts->have_squash_onto &&
3421 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3423 * When the user tells us to "merge" something into a
3424 * "[new root]", let's simply fast-forward to the merge head.
3426 rollback_lock_file(&lock);
3428 ret = error(_("octopus merge cannot be executed on "
3429 "top of a [new root]"));
3431 ret = fast_forward_to(r, &to_merge->item->object.oid,
3432 &head_commit->object.oid, 0,
3438 const char *encoding = get_commit_output_encoding();
3439 const char *message = logmsg_reencode(commit, NULL, encoding);
3444 ret = error(_("could not get commit message of '%s'"),
3445 oid_to_hex(&commit->object.oid));
3448 write_author_script(message);
3449 find_commit_subject(message, &body);
3451 ret = write_message(body, len, git_path_merge_msg(r), 0);
3452 unuse_commit_buffer(commit, message);
3454 error_errno(_("could not write '%s'"),
3455 git_path_merge_msg(r));
3459 struct strbuf buf = STRBUF_INIT;
3462 strbuf_addf(&buf, "author %s", git_author_info(0));
3463 write_author_script(buf.buf);
3466 if (oneline_offset < arg_len) {
3467 p = arg + oneline_offset;
3468 len = arg_len - oneline_offset;
3470 strbuf_addf(&buf, "Merge %s '%.*s'",
3471 to_merge->next ? "branches" : "branch",
3472 merge_arg_len, arg);
3477 ret = write_message(p, len, git_path_merge_msg(r), 0);
3478 strbuf_release(&buf);
3480 error_errno(_("could not write '%s'"),
3481 git_path_merge_msg(r));
3487 * If HEAD is not identical to the first parent of the original merge
3488 * commit, we cannot fast-forward.
3490 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3491 oideq(&commit->parents->item->object.oid,
3492 &head_commit->object.oid);
3495 * If any merge head is different from the original one, we cannot
3498 if (can_fast_forward) {
3499 struct commit_list *p = commit->parents->next;
3501 for (j = to_merge; j && p; j = j->next, p = p->next)
3502 if (!oideq(&j->item->object.oid,
3503 &p->item->object.oid)) {
3504 can_fast_forward = 0;
3508 * If the number of merge heads differs from the original merge
3509 * commit, we cannot fast-forward.
3512 can_fast_forward = 0;
3515 if (can_fast_forward) {
3516 rollback_lock_file(&lock);
3517 ret = fast_forward_to(r, &commit->object.oid,
3518 &head_commit->object.oid, 0, opts);
3519 if (flags & TODO_EDIT_MERGE_MSG) {
3520 run_commit_flags |= AMEND_MSG;
3521 goto fast_forward_edit;
3526 if (strategy || to_merge->next) {
3528 struct child_process cmd = CHILD_PROCESS_INIT;
3530 if (read_env_script(&cmd.env_array)) {
3531 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3533 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3538 argv_array_push(&cmd.args, "merge");
3539 argv_array_push(&cmd.args, "-s");
3541 argv_array_push(&cmd.args, "octopus");
3543 argv_array_push(&cmd.args, strategy);
3544 for (k = 0; k < opts->xopts_nr; k++)
3545 argv_array_pushf(&cmd.args,
3546 "-X%s", opts->xopts[k]);
3548 argv_array_push(&cmd.args, "--no-edit");
3549 argv_array_push(&cmd.args, "--no-ff");
3550 argv_array_push(&cmd.args, "--no-log");
3551 argv_array_push(&cmd.args, "--no-stat");
3552 argv_array_push(&cmd.args, "-F");
3553 argv_array_push(&cmd.args, git_path_merge_msg(r));
3555 argv_array_push(&cmd.args, opts->gpg_sign);
3557 /* Add the tips to be merged */
3558 for (j = to_merge; j; j = j->next)
3559 argv_array_push(&cmd.args,
3560 oid_to_hex(&j->item->object.oid));
3562 strbuf_release(&ref_name);
3563 unlink(git_path_cherry_pick_head(r));
3564 rollback_lock_file(&lock);
3566 rollback_lock_file(&lock);
3567 ret = run_command(&cmd);
3569 /* force re-reading of the cache */
3570 if (!ret && (discard_index(r->index) < 0 ||
3571 repo_read_index(r) < 0))
3572 ret = error(_("could not read index"));
3576 merge_commit = to_merge->item;
3577 bases = get_merge_bases(head_commit, merge_commit);
3578 if (bases && oideq(&merge_commit->object.oid,
3579 &bases->item->object.oid)) {
3581 /* skip merging an ancestor of HEAD */
3585 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3586 git_path_merge_head(r), 0);
3587 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3589 for (j = bases; j; j = j->next)
3590 commit_list_insert(j->item, &reversed);
3591 free_commit_list(bases);
3594 init_merge_options(&o, r);
3596 o.branch2 = ref_name.buf;
3597 o.buffer_output = 2;
3599 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3601 fputs(o.obuf.buf, stdout);
3602 strbuf_release(&o.obuf);
3604 error(_("could not even attempt to merge '%.*s'"),
3605 merge_arg_len, arg);
3609 * The return value of merge_recursive() is 1 on clean, and 0 on
3612 * Let's reverse that, so that do_merge() returns 0 upon success and
3613 * 1 upon failed merge (keeping the return value -1 for the cases where
3614 * we will want to reschedule the `merge` command).
3618 if (r->index->cache_changed &&
3619 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3620 ret = error(_("merge: Unable to write new index file"));
3624 rollback_lock_file(&lock);
3626 repo_rerere(r, opts->allow_rerere_auto);
3629 * In case of problems, we now want to return a positive
3630 * value (a negative one would indicate that the `merge`
3631 * command needs to be rescheduled).
3634 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3638 strbuf_release(&ref_name);
3639 rollback_lock_file(&lock);
3640 free_commit_list(to_merge);
3644 static int is_final_fixup(struct todo_list *todo_list)
3646 int i = todo_list->current;
3648 if (!is_fixup(todo_list->items[i].command))
3651 while (++i < todo_list->nr)
3652 if (is_fixup(todo_list->items[i].command))
3654 else if (!is_noop(todo_list->items[i].command))
3659 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3663 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3664 if (!is_noop(todo_list->items[i].command))
3665 return todo_list->items[i].command;
3670 static int apply_autostash(struct replay_opts *opts)
3672 struct strbuf stash_sha1 = STRBUF_INIT;
3673 struct child_process child = CHILD_PROCESS_INIT;
3676 if (!read_oneliner(&stash_sha1, rebase_path_autostash(),
3677 READ_ONELINER_SKIP_IF_EMPTY)) {
3678 strbuf_release(&stash_sha1);
3681 strbuf_trim(&stash_sha1);
3684 child.no_stdout = 1;
3685 child.no_stderr = 1;
3686 argv_array_push(&child.args, "stash");
3687 argv_array_push(&child.args, "apply");
3688 argv_array_push(&child.args, stash_sha1.buf);
3689 if (!run_command(&child))
3690 fprintf(stderr, _("Applied autostash.\n"));
3692 struct child_process store = CHILD_PROCESS_INIT;
3695 argv_array_push(&store.args, "stash");
3696 argv_array_push(&store.args, "store");
3697 argv_array_push(&store.args, "-m");
3698 argv_array_push(&store.args, "autostash");
3699 argv_array_push(&store.args, "-q");
3700 argv_array_push(&store.args, stash_sha1.buf);
3701 if (run_command(&store))
3702 ret = error(_("cannot store %s"), stash_sha1.buf);
3705 _("Applying autostash resulted in conflicts.\n"
3706 "Your changes are safe in the stash.\n"
3707 "You can run \"git stash pop\" or"
3708 " \"git stash drop\" at any time.\n"));
3711 strbuf_release(&stash_sha1);
3715 static const char *reflog_message(struct replay_opts *opts,
3716 const char *sub_action, const char *fmt, ...)
3719 static struct strbuf buf = STRBUF_INIT;
3723 strbuf_addstr(&buf, action_name(opts));
3725 strbuf_addf(&buf, " (%s)", sub_action);
3727 strbuf_addstr(&buf, ": ");
3728 strbuf_vaddf(&buf, fmt, ap);
3735 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3736 const char *commit, const char *action)
3738 struct child_process cmd = CHILD_PROCESS_INIT;
3743 argv_array_push(&cmd.args, "checkout");
3744 argv_array_push(&cmd.args, commit);
3745 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3748 ret = run_command(&cmd);
3750 ret = run_command_silent_on_success(&cmd);
3753 discard_index(r->index);
3758 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3759 const char *onto_name, const struct object_id *onto,
3760 const char *orig_head)
3762 struct object_id oid;
3763 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3765 if (get_oid(orig_head, &oid))
3766 return error(_("%s: not a valid OID"), orig_head);
3768 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3769 apply_autostash(opts);
3770 sequencer_remove_state(opts);
3771 return error(_("could not detach HEAD"));
3774 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3777 static int stopped_at_head(struct repository *r)
3779 struct object_id head;
3780 struct commit *commit;
3781 struct commit_message message;
3783 if (get_oid("HEAD", &head) ||
3784 !(commit = lookup_commit(r, &head)) ||
3785 parse_commit(commit) || get_message(commit, &message))
3786 fprintf(stderr, _("Stopped at HEAD\n"));
3788 fprintf(stderr, _("Stopped at %s\n"), message.label);
3789 free_message(commit, &message);
3795 static const char rescheduled_advice[] =
3796 N_("Could not execute the todo command\n"
3800 "It has been rescheduled; To edit the command before continuing, please\n"
3801 "edit the todo list first:\n"
3803 " git rebase --edit-todo\n"
3804 " git rebase --continue\n");
3806 static int pick_commits(struct repository *r,
3807 struct todo_list *todo_list,
3808 struct replay_opts *opts)
3810 int res = 0, reschedule = 0;
3812 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3814 assert(!(opts->signoff || opts->no_commit ||
3815 opts->record_origin || opts->edit));
3816 if (read_and_refresh_cache(r, opts))
3819 while (todo_list->current < todo_list->nr) {
3820 struct todo_item *item = todo_list->items + todo_list->current;
3821 const char *arg = todo_item_get_arg(todo_list, item);
3824 if (save_todo(todo_list, opts))
3826 if (is_rebase_i(opts)) {
3827 if (item->command != TODO_COMMENT) {
3828 FILE *f = fopen(rebase_path_msgnum(), "w");
3830 todo_list->done_nr++;
3833 fprintf(f, "%d\n", todo_list->done_nr);
3837 fprintf(stderr, "Rebasing (%d/%d)%s",
3839 todo_list->total_nr,
3840 opts->verbose ? "\n" : "\r");
3842 unlink(rebase_path_message());
3843 unlink(rebase_path_author_script());
3844 unlink(rebase_path_stopped_sha());
3845 unlink(rebase_path_amend());
3846 unlink(git_path_merge_head(r));
3847 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3849 if (item->command == TODO_BREAK) {
3852 return stopped_at_head(r);
3855 if (item->command <= TODO_SQUASH) {
3856 if (is_rebase_i(opts))
3857 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3858 command_to_string(item->command), NULL),
3860 res = do_pick_commit(r, item->command, item->commit,
3861 opts, is_final_fixup(todo_list),
3863 if (is_rebase_i(opts) && res < 0) {
3865 advise(_(rescheduled_advice),
3866 get_item_line_length(todo_list,
3867 todo_list->current),
3868 get_item_line(todo_list,
3869 todo_list->current));
3870 todo_list->current--;
3871 if (save_todo(todo_list, opts))
3874 if (item->command == TODO_EDIT) {
3875 struct commit *commit = item->commit;
3880 _("Stopped at %s... %.*s\n"),
3881 short_commit_name(commit),
3882 item->arg_len, arg);
3884 return error_with_patch(r, commit,
3885 arg, item->arg_len, opts, res, !res);
3887 if (is_rebase_i(opts) && !res)
3888 record_in_rewritten(&item->commit->object.oid,
3889 peek_command(todo_list, 1));
3890 if (res && is_fixup(item->command)) {
3893 return error_failed_squash(r, item->commit, opts,
3894 item->arg_len, arg);
3895 } else if (res && is_rebase_i(opts) && item->commit) {
3897 struct object_id oid;
3900 * If we are rewording and have either
3901 * fast-forwarded already, or are about to
3902 * create a new root commit, we want to amend,
3903 * otherwise we do not.
3905 if (item->command == TODO_REWORD &&
3906 !get_oid("HEAD", &oid) &&
3907 (oideq(&item->commit->object.oid, &oid) ||
3908 (opts->have_squash_onto &&
3909 oideq(&opts->squash_onto, &oid))))
3912 return res | error_with_patch(r, item->commit,
3913 arg, item->arg_len, opts,
3916 } else if (item->command == TODO_EXEC) {
3917 char *end_of_arg = (char *)(arg + item->arg_len);
3918 int saved = *end_of_arg;
3923 res = do_exec(r, arg);
3924 *end_of_arg = saved;
3927 if (opts->reschedule_failed_exec)
3931 } else if (item->command == TODO_LABEL) {
3932 if ((res = do_label(r, arg, item->arg_len)))
3934 } else if (item->command == TODO_RESET) {
3935 if ((res = do_reset(r, arg, item->arg_len, opts)))
3937 } else if (item->command == TODO_MERGE) {
3938 if ((res = do_merge(r, item->commit,
3940 item->flags, opts)) < 0)
3942 else if (item->commit)
3943 record_in_rewritten(&item->commit->object.oid,
3944 peek_command(todo_list, 1));
3946 /* failed with merge conflicts */
3947 return error_with_patch(r, item->commit,
3950 } else if (!is_noop(item->command))
3951 return error(_("unknown command %d"), item->command);
3954 advise(_(rescheduled_advice),
3955 get_item_line_length(todo_list,
3956 todo_list->current),
3957 get_item_line(todo_list, todo_list->current));
3958 todo_list->current--;
3959 if (save_todo(todo_list, opts))
3962 return error_with_patch(r,
3966 } else if (is_rebase_i(opts) && check_todo && !res) {
3969 if (stat(get_todo_path(opts), &st)) {
3970 res = error_errno(_("could not stat '%s'"),
3971 get_todo_path(opts));
3972 } else if (match_stat_data(&todo_list->stat, &st)) {
3973 /* Reread the todo file if it has changed. */
3974 todo_list_release(todo_list);
3975 if (read_populate_todo(r, todo_list, opts))
3976 res = -1; /* message was printed */
3977 /* `current` will be incremented below */
3978 todo_list->current = -1;
3982 todo_list->current++;
3987 if (is_rebase_i(opts)) {
3988 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3991 /* Stopped in the middle, as planned? */
3992 if (todo_list->current < todo_list->nr)
3995 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3996 starts_with(head_ref.buf, "refs/")) {
3998 struct object_id head, orig;
4001 if (get_oid("HEAD", &head)) {
4002 res = error(_("cannot read HEAD"));
4004 strbuf_release(&head_ref);
4005 strbuf_release(&buf);
4008 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4009 get_oid_hex(buf.buf, &orig)) {
4010 res = error(_("could not read orig-head"));
4011 goto cleanup_head_ref;
4014 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4015 res = error(_("could not read 'onto'"));
4016 goto cleanup_head_ref;
4018 msg = reflog_message(opts, "finish", "%s onto %s",
4019 head_ref.buf, buf.buf);
4020 if (update_ref(msg, head_ref.buf, &head, &orig,
4021 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4022 res = error(_("could not update %s"),
4024 goto cleanup_head_ref;
4026 msg = reflog_message(opts, "finish", "returning to %s",
4028 if (create_symref("HEAD", head_ref.buf, msg)) {
4029 res = error(_("could not update HEAD to %s"),
4031 goto cleanup_head_ref;
4036 if (opts->verbose) {
4037 struct rev_info log_tree_opt;
4038 struct object_id orig, head;
4040 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4041 repo_init_revisions(r, &log_tree_opt, NULL);
4042 log_tree_opt.diff = 1;
4043 log_tree_opt.diffopt.output_format =
4044 DIFF_FORMAT_DIFFSTAT;
4045 log_tree_opt.disable_stdin = 1;
4047 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4048 !get_oid(buf.buf, &orig) &&
4049 !get_oid("HEAD", &head)) {
4050 diff_tree_oid(&orig, &head, "",
4051 &log_tree_opt.diffopt);
4052 log_tree_diff_flush(&log_tree_opt);
4055 flush_rewritten_pending();
4056 if (!stat(rebase_path_rewritten_list(), &st) &&
4058 struct child_process child = CHILD_PROCESS_INIT;
4059 const char *post_rewrite_hook =
4060 find_hook("post-rewrite");
4062 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4064 argv_array_push(&child.args, "notes");
4065 argv_array_push(&child.args, "copy");
4066 argv_array_push(&child.args, "--for-rewrite=rebase");
4067 /* we don't care if this copying failed */
4068 run_command(&child);
4070 if (post_rewrite_hook) {
4071 struct child_process hook = CHILD_PROCESS_INIT;
4073 hook.in = open(rebase_path_rewritten_list(),
4075 hook.stdout_to_stderr = 1;
4076 hook.trace2_hook_name = "post-rewrite";
4077 argv_array_push(&hook.args, post_rewrite_hook);
4078 argv_array_push(&hook.args, "rebase");
4079 /* we don't care if this hook failed */
4083 apply_autostash(opts);
4089 "Successfully rebased and updated %s.\n",
4093 strbuf_release(&buf);
4094 strbuf_release(&head_ref);
4098 * Sequence of picks finished successfully; cleanup by
4099 * removing the .git/sequencer directory
4101 return sequencer_remove_state(opts);
4104 static int continue_single_pick(struct repository *r)
4106 const char *argv[] = { "commit", NULL };
4108 if (!file_exists(git_path_cherry_pick_head(r)) &&
4109 !file_exists(git_path_revert_head(r)))
4110 return error(_("no cherry-pick or revert in progress"));
4111 return run_command_v_opt(argv, RUN_GIT_CMD);
4114 static int commit_staged_changes(struct repository *r,
4115 struct replay_opts *opts,
4116 struct todo_list *todo_list)
4118 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4119 unsigned int final_fixup = 0, is_clean;
4121 if (has_unstaged_changes(r, 1))
4122 return error(_("cannot rebase: You have unstaged changes."));
4124 is_clean = !has_uncommitted_changes(r, 0);
4126 if (file_exists(rebase_path_amend())) {
4127 struct strbuf rev = STRBUF_INIT;
4128 struct object_id head, to_amend;
4130 if (get_oid("HEAD", &head))
4131 return error(_("cannot amend non-existing commit"));
4132 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4133 return error(_("invalid file: '%s'"), rebase_path_amend());
4134 if (get_oid_hex(rev.buf, &to_amend))
4135 return error(_("invalid contents: '%s'"),
4136 rebase_path_amend());
4137 if (!is_clean && !oideq(&head, &to_amend))
4138 return error(_("\nYou have uncommitted changes in your "
4139 "working tree. Please, commit them\n"
4140 "first and then run 'git rebase "
4141 "--continue' again."));
4143 * When skipping a failed fixup/squash, we need to edit the
4144 * commit message, the current fixup list and count, and if it
4145 * was the last fixup/squash in the chain, we need to clean up
4146 * the commit message and if there was a squash, let the user
4149 if (!is_clean || !opts->current_fixup_count)
4150 ; /* this is not the final fixup */
4151 else if (!oideq(&head, &to_amend) ||
4152 !file_exists(rebase_path_stopped_sha())) {
4153 /* was a final fixup or squash done manually? */
4154 if (!is_fixup(peek_command(todo_list, 0))) {
4155 unlink(rebase_path_fixup_msg());
4156 unlink(rebase_path_squash_msg());
4157 unlink(rebase_path_current_fixups());
4158 strbuf_reset(&opts->current_fixups);
4159 opts->current_fixup_count = 0;
4162 /* we are in a fixup/squash chain */
4163 const char *p = opts->current_fixups.buf;
4164 int len = opts->current_fixups.len;
4166 opts->current_fixup_count--;
4168 BUG("Incorrect current_fixups:\n%s", p);
4169 while (len && p[len - 1] != '\n')
4171 strbuf_setlen(&opts->current_fixups, len);
4172 if (write_message(p, len, rebase_path_current_fixups(),
4174 return error(_("could not write file: '%s'"),
4175 rebase_path_current_fixups());
4178 * If a fixup/squash in a fixup/squash chain failed, the
4179 * commit message is already correct, no need to commit
4182 * Only if it is the final command in the fixup/squash
4183 * chain, and only if the chain is longer than a single
4184 * fixup/squash command (which was just skipped), do we
4185 * actually need to re-commit with a cleaned up commit
4188 if (opts->current_fixup_count > 0 &&
4189 !is_fixup(peek_command(todo_list, 0))) {
4192 * If there was not a single "squash" in the
4193 * chain, we only need to clean up the commit
4194 * message, no need to bother the user with
4195 * opening the commit message in the editor.
4197 if (!starts_with(p, "squash ") &&
4198 !strstr(p, "\nsquash "))
4199 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4200 } else if (is_fixup(peek_command(todo_list, 0))) {
4202 * We need to update the squash message to skip
4203 * the latest commit message.
4205 struct commit *commit;
4206 const char *path = rebase_path_squash_msg();
4207 const char *encoding = get_commit_output_encoding();
4209 if (parse_head(r, &commit) ||
4210 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4211 write_message(p, strlen(p), path, 0)) {
4212 unuse_commit_buffer(commit, p);
4213 return error(_("could not write file: "
4216 unuse_commit_buffer(commit, p);
4220 strbuf_release(&rev);
4225 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4227 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4228 return error(_("could not remove CHERRY_PICK_HEAD"));
4233 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4235 return error(_("could not commit staged changes."));
4236 unlink(rebase_path_amend());
4237 unlink(git_path_merge_head(r));
4239 unlink(rebase_path_fixup_msg());
4240 unlink(rebase_path_squash_msg());
4242 if (opts->current_fixup_count > 0) {
4244 * Whether final fixup or not, we just cleaned up the commit
4247 unlink(rebase_path_current_fixups());
4248 strbuf_reset(&opts->current_fixups);
4249 opts->current_fixup_count = 0;
4254 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4256 struct todo_list todo_list = TODO_LIST_INIT;
4259 if (read_and_refresh_cache(r, opts))
4262 if (read_populate_opts(opts))
4264 if (is_rebase_i(opts)) {
4265 if ((res = read_populate_todo(r, &todo_list, opts)))
4266 goto release_todo_list;
4268 if (file_exists(rebase_path_dropped())) {
4269 if ((res = todo_list_check_against_backup(r, &todo_list)))
4270 goto release_todo_list;
4272 unlink(rebase_path_dropped());
4275 if (commit_staged_changes(r, opts, &todo_list)) {
4277 goto release_todo_list;
4279 } else if (!file_exists(get_todo_path(opts)))
4280 return continue_single_pick(r);
4281 else if ((res = read_populate_todo(r, &todo_list, opts)))
4282 goto release_todo_list;
4284 if (!is_rebase_i(opts)) {
4285 /* Verify that the conflict has been resolved */
4286 if (file_exists(git_path_cherry_pick_head(r)) ||
4287 file_exists(git_path_revert_head(r))) {
4288 res = continue_single_pick(r);
4290 goto release_todo_list;
4292 if (index_differs_from(r, "HEAD", NULL, 0)) {
4293 res = error_dirty_index(r, opts);
4294 goto release_todo_list;
4296 todo_list.current++;
4297 } else if (file_exists(rebase_path_stopped_sha())) {
4298 struct strbuf buf = STRBUF_INIT;
4299 struct object_id oid;
4301 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4302 READ_ONELINER_SKIP_IF_EMPTY) &&
4303 !get_oid_committish(buf.buf, &oid))
4304 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4305 strbuf_release(&buf);
4308 res = pick_commits(r, &todo_list, opts);
4310 todo_list_release(&todo_list);
4314 static int single_pick(struct repository *r,
4315 struct commit *cmit,
4316 struct replay_opts *opts)
4320 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4321 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4322 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4326 int sequencer_pick_revisions(struct repository *r,
4327 struct replay_opts *opts)
4329 struct todo_list todo_list = TODO_LIST_INIT;
4330 struct object_id oid;
4334 if (read_and_refresh_cache(r, opts))
4337 for (i = 0; i < opts->revs->pending.nr; i++) {
4338 struct object_id oid;
4339 const char *name = opts->revs->pending.objects[i].name;
4341 /* This happens when using --stdin. */
4345 if (!get_oid(name, &oid)) {
4346 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4347 enum object_type type = oid_object_info(r,
4350 return error(_("%s: can't cherry-pick a %s"),
4351 name, type_name(type));
4354 return error(_("%s: bad revision"), name);
4358 * If we were called as "git cherry-pick <commit>", just
4359 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4360 * REVERT_HEAD, and don't touch the sequencer state.
4361 * This means it is possible to cherry-pick in the middle
4362 * of a cherry-pick sequence.
4364 if (opts->revs->cmdline.nr == 1 &&
4365 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4366 opts->revs->no_walk &&
4367 !opts->revs->cmdline.rev->flags) {
4368 struct commit *cmit;
4369 if (prepare_revision_walk(opts->revs))
4370 return error(_("revision walk setup failed"));
4371 cmit = get_revision(opts->revs);
4373 return error(_("empty commit set passed"));
4374 if (get_revision(opts->revs))
4375 BUG("unexpected extra commit from walk");
4376 return single_pick(r, cmit, opts);
4380 * Start a new cherry-pick/ revert sequence; but
4381 * first, make sure that an existing one isn't in
4385 if (walk_revs_populate_todo(&todo_list, opts) ||
4386 create_seq_dir(r) < 0)
4388 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4389 return error(_("can't revert as initial commit"));
4390 if (save_head(oid_to_hex(&oid)))
4392 if (save_opts(opts))
4394 update_abort_safety_file();
4395 res = pick_commits(r, &todo_list, opts);
4396 todo_list_release(&todo_list);
4400 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4402 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4403 struct strbuf sob = STRBUF_INIT;
4406 strbuf_addstr(&sob, sign_off_header);
4407 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4408 strbuf_addch(&sob, '\n');
4411 strbuf_complete_line(msgbuf);
4414 * If the whole message buffer is equal to the sob, pretend that we
4415 * found a conforming footer with a matching sob
4417 if (msgbuf->len - ignore_footer == sob.len &&
4418 !strncmp(msgbuf->buf, sob.buf, sob.len))
4421 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4424 const char *append_newlines = NULL;
4425 size_t len = msgbuf->len - ignore_footer;
4429 * The buffer is completely empty. Leave foom for
4430 * the title and body to be filled in by the user.
4432 append_newlines = "\n\n";
4433 } else if (len == 1) {
4435 * Buffer contains a single newline. Add another
4436 * so that we leave room for the title and body.
4438 append_newlines = "\n";
4439 } else if (msgbuf->buf[len - 2] != '\n') {
4441 * Buffer ends with a single newline. Add another
4442 * so that there is an empty line between the message
4445 append_newlines = "\n";
4446 } /* else, the buffer already ends with two newlines. */
4448 if (append_newlines)
4449 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4450 append_newlines, strlen(append_newlines));
4453 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4454 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4457 strbuf_release(&sob);
4460 struct labels_entry {
4461 struct hashmap_entry entry;
4462 char label[FLEX_ARRAY];
4465 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4466 const struct hashmap_entry *entry_or_key, const void *key)
4468 const struct labels_entry *a, *b;
4470 a = container_of(eptr, const struct labels_entry, entry);
4471 b = container_of(entry_or_key, const struct labels_entry, entry);
4473 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4476 struct string_entry {
4477 struct oidmap_entry entry;
4478 char string[FLEX_ARRAY];
4481 struct label_state {
4482 struct oidmap commit2label;
4483 struct hashmap labels;
4487 static const char *label_oid(struct object_id *oid, const char *label,
4488 struct label_state *state)
4490 struct labels_entry *labels_entry;
4491 struct string_entry *string_entry;
4492 struct object_id dummy;
4495 string_entry = oidmap_get(&state->commit2label, oid);
4497 return string_entry->string;
4500 * For "uninteresting" commits, i.e. commits that are not to be
4501 * rebased, and which can therefore not be labeled, we use a unique
4502 * abbreviation of the commit name. This is slightly more complicated
4503 * than calling find_unique_abbrev() because we also need to make
4504 * sure that the abbreviation does not conflict with any other
4507 * We disallow "interesting" commits to be labeled by a string that
4508 * is a valid full-length hash, to ensure that we always can find an
4509 * abbreviation for any uninteresting commit's names that does not
4510 * clash with any other label.
4512 strbuf_reset(&state->buf);
4516 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4517 label = p = state->buf.buf;
4519 find_unique_abbrev_r(p, oid, default_abbrev);
4522 * We may need to extend the abbreviated hash so that there is
4523 * no conflicting label.
4525 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4526 size_t i = strlen(p) + 1;
4528 oid_to_hex_r(p, oid);
4529 for (; i < the_hash_algo->hexsz; i++) {
4532 if (!hashmap_get_from_hash(&state->labels,
4539 struct strbuf *buf = &state->buf;
4542 * Sanitize labels by replacing non-alpha-numeric characters
4543 * (including white-space ones) by dashes, as they might be
4544 * illegal in file names (and hence in ref names).
4546 * Note that we retain non-ASCII UTF-8 characters (identified
4547 * via the most significant bit). They should be all acceptable
4548 * in file names. We do not validate the UTF-8 here, that's not
4549 * the job of this function.
4551 for (; *label; label++)
4552 if ((*label & 0x80) || isalnum(*label))
4553 strbuf_addch(buf, *label);
4554 /* avoid leading dash and double-dashes */
4555 else if (buf->len && buf->buf[buf->len - 1] != '-')
4556 strbuf_addch(buf, '-');
4558 strbuf_addstr(buf, "rev-");
4559 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4563 if ((buf->len == the_hash_algo->hexsz &&
4564 !get_oid_hex(label, &dummy)) ||
4565 (buf->len == 1 && *label == '#') ||
4566 hashmap_get_from_hash(&state->labels,
4567 strihash(label), label)) {
4569 * If the label already exists, or if the label is a
4570 * valid full OID, or the label is a '#' (which we use
4571 * as a separator between merge heads and oneline), we
4572 * append a dash and a number to make it unique.
4574 size_t len = buf->len;
4576 for (i = 2; ; i++) {
4577 strbuf_setlen(buf, len);
4578 strbuf_addf(buf, "-%d", i);
4579 if (!hashmap_get_from_hash(&state->labels,
4589 FLEX_ALLOC_STR(labels_entry, label, label);
4590 hashmap_entry_init(&labels_entry->entry, strihash(label));
4591 hashmap_add(&state->labels, &labels_entry->entry);
4593 FLEX_ALLOC_STR(string_entry, string, label);
4594 oidcpy(&string_entry->entry.oid, oid);
4595 oidmap_put(&state->commit2label, string_entry);
4597 return string_entry->string;
4600 static int make_script_with_merges(struct pretty_print_context *pp,
4601 struct rev_info *revs, struct strbuf *out,
4604 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4605 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4606 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4607 struct strbuf label = STRBUF_INIT;
4608 struct commit_list *commits = NULL, **tail = &commits, *iter;
4609 struct commit_list *tips = NULL, **tips_tail = &tips;
4610 struct commit *commit;
4611 struct oidmap commit2todo = OIDMAP_INIT;
4612 struct string_entry *entry;
4613 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4614 shown = OIDSET_INIT;
4615 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4617 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4618 const char *cmd_pick = abbr ? "p" : "pick",
4619 *cmd_label = abbr ? "l" : "label",
4620 *cmd_reset = abbr ? "t" : "reset",
4621 *cmd_merge = abbr ? "m" : "merge";
4623 oidmap_init(&commit2todo, 0);
4624 oidmap_init(&state.commit2label, 0);
4625 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4626 strbuf_init(&state.buf, 32);
4628 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4629 struct labels_entry *onto_label_entry;
4630 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4631 FLEX_ALLOC_STR(entry, string, "onto");
4632 oidcpy(&entry->entry.oid, oid);
4633 oidmap_put(&state.commit2label, entry);
4635 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4636 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4637 hashmap_add(&state.labels, &onto_label_entry->entry);
4642 * - get onelines for all commits
4643 * - gather all branch tips (i.e. 2nd or later parents of merges)
4644 * - label all branch tips
4646 while ((commit = get_revision(revs))) {
4647 struct commit_list *to_merge;
4648 const char *p1, *p2;
4649 struct object_id *oid;
4652 tail = &commit_list_insert(commit, tail)->next;
4653 oidset_insert(&interesting, &commit->object.oid);
4655 is_empty = is_original_commit_empty(commit);
4656 if (!is_empty && (commit->object.flags & PATCHSAME))
4659 strbuf_reset(&oneline);
4660 pretty_print_commit(pp, commit, &oneline);
4662 to_merge = commit->parents ? commit->parents->next : NULL;
4664 /* non-merge commit: easy case */
4666 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4667 oid_to_hex(&commit->object.oid),
4670 FLEX_ALLOC_STR(entry, string, buf.buf);
4671 oidcpy(&entry->entry.oid, &commit->object.oid);
4672 oidmap_put(&commit2todo, entry);
4677 /* Create a label */
4678 strbuf_reset(&label);
4679 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4680 (p1 = strchr(p1, '\'')) &&
4681 (p2 = strchr(++p1, '\'')))
4682 strbuf_add(&label, p1, p2 - p1);
4683 else if (skip_prefix(oneline.buf, "Merge pull request ",
4685 (p1 = strstr(p1, " from ")))
4686 strbuf_addstr(&label, p1 + strlen(" from "));
4688 strbuf_addbuf(&label, &oneline);
4691 strbuf_addf(&buf, "%s -C %s",
4692 cmd_merge, oid_to_hex(&commit->object.oid));
4694 /* label the tips of merged branches */
4695 for (; to_merge; to_merge = to_merge->next) {
4696 oid = &to_merge->item->object.oid;
4697 strbuf_addch(&buf, ' ');
4699 if (!oidset_contains(&interesting, oid)) {
4700 strbuf_addstr(&buf, label_oid(oid, NULL,
4705 tips_tail = &commit_list_insert(to_merge->item,
4708 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4710 strbuf_addf(&buf, " # %s", oneline.buf);
4712 FLEX_ALLOC_STR(entry, string, buf.buf);
4713 oidcpy(&entry->entry.oid, &commit->object.oid);
4714 oidmap_put(&commit2todo, entry);
4719 * - label branch points
4720 * - add HEAD to the branch tips
4722 for (iter = commits; iter; iter = iter->next) {
4723 struct commit_list *parent = iter->item->parents;
4724 for (; parent; parent = parent->next) {
4725 struct object_id *oid = &parent->item->object.oid;
4726 if (!oidset_contains(&interesting, oid))
4728 if (oidset_insert(&child_seen, oid))
4729 label_oid(oid, "branch-point", &state);
4732 /* Add HEAD as implicit "tip of branch" */
4734 tips_tail = &commit_list_insert(iter->item,
4739 * Third phase: output the todo list. This is a bit tricky, as we
4740 * want to avoid jumping back and forth between revisions. To
4741 * accomplish that goal, we walk backwards from the branch tips,
4742 * gathering commits not yet shown, reversing the list on the fly,
4743 * then outputting that list (labeling revisions as needed).
4745 strbuf_addf(out, "%s onto\n", cmd_label);
4746 for (iter = tips; iter; iter = iter->next) {
4747 struct commit_list *list = NULL, *iter2;
4749 commit = iter->item;
4750 if (oidset_contains(&shown, &commit->object.oid))
4752 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4755 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4757 strbuf_addch(out, '\n');
4759 while (oidset_contains(&interesting, &commit->object.oid) &&
4760 !oidset_contains(&shown, &commit->object.oid)) {
4761 commit_list_insert(commit, &list);
4762 if (!commit->parents) {
4766 commit = commit->parents->item;
4770 strbuf_addf(out, "%s %s\n", cmd_reset,
4771 rebase_cousins || root_with_onto ?
4772 "onto" : "[new root]");
4774 const char *to = NULL;
4776 entry = oidmap_get(&state.commit2label,
4777 &commit->object.oid);
4780 else if (!rebase_cousins)
4781 to = label_oid(&commit->object.oid, NULL,
4784 if (!to || !strcmp(to, "onto"))
4785 strbuf_addf(out, "%s onto\n", cmd_reset);
4787 strbuf_reset(&oneline);
4788 pretty_print_commit(pp, commit, &oneline);
4789 strbuf_addf(out, "%s %s # %s\n",
4790 cmd_reset, to, oneline.buf);
4794 for (iter2 = list; iter2; iter2 = iter2->next) {
4795 struct object_id *oid = &iter2->item->object.oid;
4796 entry = oidmap_get(&commit2todo, oid);
4797 /* only show if not already upstream */
4799 strbuf_addf(out, "%s\n", entry->string);
4800 entry = oidmap_get(&state.commit2label, oid);
4802 strbuf_addf(out, "%s %s\n",
4803 cmd_label, entry->string);
4804 oidset_insert(&shown, oid);
4807 free_commit_list(list);
4810 free_commit_list(commits);
4811 free_commit_list(tips);
4813 strbuf_release(&label);
4814 strbuf_release(&oneline);
4815 strbuf_release(&buf);
4817 oidmap_free(&commit2todo, 1);
4818 oidmap_free(&state.commit2label, 1);
4819 hashmap_free_entries(&state.labels, struct labels_entry, entry);
4820 strbuf_release(&state.buf);
4825 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4826 const char **argv, unsigned flags)
4828 char *format = NULL;
4829 struct pretty_print_context pp = {0};
4830 struct rev_info revs;
4831 struct commit *commit;
4832 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4833 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4835 repo_init_revisions(r, &revs, NULL);
4836 revs.verbose_header = 1;
4838 revs.max_parents = 1;
4839 revs.cherry_mark = 1;
4842 revs.right_only = 1;
4843 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4844 revs.topo_order = 1;
4846 revs.pretty_given = 1;
4847 git_config_get_string("rebase.instructionFormat", &format);
4848 if (!format || !*format) {
4850 format = xstrdup("%s");
4852 get_commit_format(format, &revs);
4854 pp.fmt = revs.commit_format;
4855 pp.output_encoding = get_log_output_encoding();
4857 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4858 return error(_("make_script: unhandled options"));
4860 if (prepare_revision_walk(&revs) < 0)
4861 return error(_("make_script: error preparing revisions"));
4864 return make_script_with_merges(&pp, &revs, out, flags);
4866 while ((commit = get_revision(&revs))) {
4867 int is_empty = is_original_commit_empty(commit);
4869 if (!is_empty && (commit->object.flags & PATCHSAME))
4871 strbuf_addf(out, "%s %s ", insn,
4872 oid_to_hex(&commit->object.oid));
4873 pretty_print_commit(&pp, commit, out);
4874 strbuf_addch(out, '\n');
4880 * Add commands after pick and (series of) squash/fixup commands
4883 void todo_list_add_exec_commands(struct todo_list *todo_list,
4884 struct string_list *commands)
4886 struct strbuf *buf = &todo_list->buf;
4887 size_t base_offset = buf->len;
4888 int i, insert, nr = 0, alloc = 0;
4889 struct todo_item *items = NULL, *base_items = NULL;
4891 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4892 for (i = 0; i < commands->nr; i++) {
4893 size_t command_len = strlen(commands->items[i].string);
4895 strbuf_addstr(buf, commands->items[i].string);
4896 strbuf_addch(buf, '\n');
4898 base_items[i].command = TODO_EXEC;
4899 base_items[i].offset_in_buf = base_offset;
4900 base_items[i].arg_offset = base_offset + strlen("exec ");
4901 base_items[i].arg_len = command_len - strlen("exec ");
4903 base_offset += command_len + 1;
4907 * Insert <commands> after every pick. Here, fixup/squash chains
4908 * are considered part of the pick, so we insert the commands *after*
4909 * those chains if there are any.
4911 * As we insert the exec commands immediately after rearranging
4912 * any fixups and before the user edits the list, a fixup chain
4913 * can never contain comments (any comments are empty picks that
4914 * have been commented out because the user did not specify
4915 * --keep-empty). So, it is safe to insert an exec command
4916 * without looking at the command following a comment.
4919 for (i = 0; i < todo_list->nr; i++) {
4920 enum todo_command command = todo_list->items[i].command;
4921 if (insert && !is_fixup(command)) {
4922 ALLOC_GROW(items, nr + commands->nr, alloc);
4923 COPY_ARRAY(items + nr, base_items, commands->nr);
4929 ALLOC_GROW(items, nr + 1, alloc);
4930 items[nr++] = todo_list->items[i];
4932 if (command == TODO_PICK || command == TODO_MERGE)
4936 /* insert or append final <commands> */
4937 if (insert || nr == todo_list->nr) {
4938 ALLOC_GROW(items, nr + commands->nr, alloc);
4939 COPY_ARRAY(items + nr, base_items, commands->nr);
4944 FREE_AND_NULL(todo_list->items);
4945 todo_list->items = items;
4947 todo_list->alloc = alloc;
4950 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4951 struct strbuf *buf, int num, unsigned flags)
4953 struct todo_item *item;
4954 int i, max = todo_list->nr;
4956 if (num > 0 && num < max)
4959 for (item = todo_list->items, i = 0; i < max; i++, item++) {
4960 /* if the item is not a command write it and continue */
4961 if (item->command >= TODO_COMMENT) {
4962 strbuf_addf(buf, "%.*s\n", item->arg_len,
4963 todo_item_get_arg(todo_list, item));
4967 /* add command to the buffer */
4968 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4969 strbuf_addch(buf, command_to_char(item->command));
4971 strbuf_addstr(buf, command_to_string(item->command));
4975 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4976 short_commit_name(item->commit) :
4977 oid_to_hex(&item->commit->object.oid);
4979 if (item->command == TODO_MERGE) {
4980 if (item->flags & TODO_EDIT_MERGE_MSG)
4981 strbuf_addstr(buf, " -c");
4983 strbuf_addstr(buf, " -C");
4986 strbuf_addf(buf, " %s", oid);
4989 /* add all the rest */
4991 strbuf_addch(buf, '\n');
4993 strbuf_addf(buf, " %.*s\n", item->arg_len,
4994 todo_item_get_arg(todo_list, item));
4998 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
4999 const char *file, const char *shortrevisions,
5000 const char *shortonto, int num, unsigned flags)
5003 struct strbuf buf = STRBUF_INIT;
5005 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5006 if (flags & TODO_LIST_APPEND_TODO_HELP)
5007 append_todo_help(count_commands(todo_list),
5008 shortrevisions, shortonto, &buf);
5010 res = write_message(buf.buf, buf.len, file, 0);
5011 strbuf_release(&buf);
5016 /* skip picking commits whose parents are unchanged */
5017 static int skip_unnecessary_picks(struct repository *r,
5018 struct todo_list *todo_list,
5019 struct object_id *base_oid)
5021 struct object_id *parent_oid;
5024 for (i = 0; i < todo_list->nr; i++) {
5025 struct todo_item *item = todo_list->items + i;
5027 if (item->command >= TODO_NOOP)
5029 if (item->command != TODO_PICK)
5031 if (parse_commit(item->commit)) {
5032 return error(_("could not parse commit '%s'"),
5033 oid_to_hex(&item->commit->object.oid));
5035 if (!item->commit->parents)
5036 break; /* root commit */
5037 if (item->commit->parents->next)
5038 break; /* merge commit */
5039 parent_oid = &item->commit->parents->item->object.oid;
5040 if (!oideq(parent_oid, base_oid))
5042 oidcpy(base_oid, &item->commit->object.oid);
5045 const char *done_path = rebase_path_done();
5047 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5048 error_errno(_("could not write to '%s'"), done_path);
5052 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5054 todo_list->current = 0;
5055 todo_list->done_nr += i;
5057 if (is_fixup(peek_command(todo_list, 0)))
5058 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5064 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5065 const char *shortrevisions, const char *onto_name,
5066 struct commit *onto, const char *orig_head,
5067 struct string_list *commands, unsigned autosquash,
5068 struct todo_list *todo_list)
5070 const char *shortonto, *todo_file = rebase_path_todo();
5071 struct todo_list new_todo = TODO_LIST_INIT;
5072 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5073 struct object_id oid = onto->object.oid;
5076 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5078 if (buf->len == 0) {
5079 struct todo_item *item = append_new_todo(todo_list);
5080 item->command = TODO_NOOP;
5081 item->commit = NULL;
5082 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5085 if (autosquash && todo_list_rearrange_squash(todo_list))
5089 todo_list_add_exec_commands(todo_list, commands);
5091 if (count_commands(todo_list) == 0) {
5092 apply_autostash(opts);
5093 sequencer_remove_state(opts);
5095 return error(_("nothing to do"));
5098 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5102 else if (res == -2) {
5103 apply_autostash(opts);
5104 sequencer_remove_state(opts);
5107 } else if (res == -3) {
5108 apply_autostash(opts);
5109 sequencer_remove_state(opts);
5110 todo_list_release(&new_todo);
5112 return error(_("nothing to do"));
5113 } else if (res == -4) {
5114 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5115 todo_list_release(&new_todo);
5120 /* Expand the commit IDs */
5121 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5122 strbuf_swap(&new_todo.buf, &buf2);
5123 strbuf_release(&buf2);
5124 new_todo.total_nr -= new_todo.nr;
5125 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5126 BUG("invalid todo list after expanding IDs:\n%s",
5129 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5130 todo_list_release(&new_todo);
5131 return error(_("could not skip unnecessary pick commands"));
5134 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5135 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5136 todo_list_release(&new_todo);
5137 return error_errno(_("could not write '%s'"), todo_file);
5142 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5145 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5148 todo_list_write_total_nr(&new_todo);
5149 res = pick_commits(r, &new_todo, opts);
5152 todo_list_release(&new_todo);
5157 struct subject2item_entry {
5158 struct hashmap_entry entry;
5160 char subject[FLEX_ARRAY];
5163 static int subject2item_cmp(const void *fndata,
5164 const struct hashmap_entry *eptr,
5165 const struct hashmap_entry *entry_or_key,
5168 const struct subject2item_entry *a, *b;
5170 a = container_of(eptr, const struct subject2item_entry, entry);
5171 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5173 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5176 define_commit_slab(commit_todo_item, struct todo_item *);
5179 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5180 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5181 * after the former, and change "pick" to "fixup"/"squash".
5183 * Note that if the config has specified a custom instruction format, each log
5184 * message will have to be retrieved from the commit (as the oneline in the
5185 * script cannot be trusted) in order to normalize the autosquash arrangement.
5187 int todo_list_rearrange_squash(struct todo_list *todo_list)
5189 struct hashmap subject2item;
5190 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5192 struct commit_todo_item commit_todo;
5193 struct todo_item *items = NULL;
5195 init_commit_todo_item(&commit_todo);
5197 * The hashmap maps onelines to the respective todo list index.
5199 * If any items need to be rearranged, the next[i] value will indicate
5200 * which item was moved directly after the i'th.
5202 * In that case, last[i] will indicate the index of the latest item to
5203 * be moved to appear after the i'th.
5205 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5206 ALLOC_ARRAY(next, todo_list->nr);
5207 ALLOC_ARRAY(tail, todo_list->nr);
5208 ALLOC_ARRAY(subjects, todo_list->nr);
5209 for (i = 0; i < todo_list->nr; i++) {
5210 struct strbuf buf = STRBUF_INIT;
5211 struct todo_item *item = todo_list->items + i;
5212 const char *commit_buffer, *subject, *p;
5215 struct subject2item_entry *entry;
5217 next[i] = tail[i] = -1;
5218 if (!item->commit || item->command == TODO_DROP) {
5223 if (is_fixup(item->command)) {
5224 clear_commit_todo_item(&commit_todo);
5225 return error(_("the script was already rearranged."));
5228 *commit_todo_item_at(&commit_todo, item->commit) = item;
5230 parse_commit(item->commit);
5231 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5232 find_commit_subject(commit_buffer, &subject);
5233 format_subject(&buf, subject, " ");
5234 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5235 unuse_commit_buffer(item->commit, commit_buffer);
5236 if ((skip_prefix(subject, "fixup! ", &p) ||
5237 skip_prefix(subject, "squash! ", &p))) {
5238 struct commit *commit2;
5243 if (!skip_prefix(p, "fixup! ", &p) &&
5244 !skip_prefix(p, "squash! ", &p))
5248 entry = hashmap_get_entry_from_hash(&subject2item,
5250 struct subject2item_entry,
5253 /* found by title */
5255 else if (!strchr(p, ' ') &&
5257 lookup_commit_reference_by_name(p)) &&
5258 *commit_todo_item_at(&commit_todo, commit2))
5259 /* found by commit name */
5260 i2 = *commit_todo_item_at(&commit_todo, commit2)
5263 /* copy can be a prefix of the commit subject */
5264 for (i2 = 0; i2 < i; i2++)
5266 starts_with(subjects[i2], p))
5274 todo_list->items[i].command =
5275 starts_with(subject, "fixup!") ?
5276 TODO_FIXUP : TODO_SQUASH;
5282 } else if (!hashmap_get_from_hash(&subject2item,
5283 strhash(subject), subject)) {
5284 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5286 hashmap_entry_init(&entry->entry,
5287 strhash(entry->subject));
5288 hashmap_put(&subject2item, &entry->entry);
5293 for (i = 0; i < todo_list->nr; i++) {
5294 enum todo_command command = todo_list->items[i].command;
5298 * Initially, all commands are 'pick's. If it is a
5299 * fixup or a squash now, we have rearranged it.
5301 if (is_fixup(command))
5305 ALLOC_GROW(items, nr + 1, alloc);
5306 items[nr++] = todo_list->items[cur];
5311 FREE_AND_NULL(todo_list->items);
5312 todo_list->items = items;
5314 todo_list->alloc = alloc;
5319 for (i = 0; i < todo_list->nr; i++)
5322 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5324 clear_commit_todo_item(&commit_todo);