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"
37 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
39 static const char sign_off_header[] = "Signed-off-by: ";
40 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
42 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
44 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
46 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
47 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
48 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
49 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
51 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
53 * The file containing rebase commands, comments, and empty lines.
54 * This file is created by "git rebase -i" then edited by the user. As
55 * the lines are processed, they are removed from the front of this
56 * file and written to the tail of 'done'.
58 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
59 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
61 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
64 * The rebase command lines that have already been processed. A line
65 * is moved here when it is first handled, before any associated user
68 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
70 * The file to keep track of how many commands were already processed (e.g.
73 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
75 * The file to keep track of how many commands are to be processed in total
76 * (e.g. for the prompt).
78 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
80 * The commit message that is planned to be used for any changes that
81 * need to be committed following a user interaction.
83 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
85 * The file into which is accumulated the suggested commit message for
86 * squash/fixup commands. When the first of a series of squash/fixups
87 * is seen, the file is created and the commit message from the
88 * previous commit and from the first squash/fixup commit are written
89 * to it. The commit message for each subsequent squash/fixup commit
90 * is appended to the file as it is processed.
92 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
94 * If the current series of squash/fixups has not yet included a squash
95 * command, then this file exists and holds the commit message of the
96 * original "pick" commit. (If the series ends without a "squash"
97 * command, then this can be used as the commit message of the combined
98 * commit without opening the editor.)
100 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
102 * This file contains the list fixup/squash commands that have been
103 * accumulated into message-fixup or message-squash so far.
105 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
107 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
108 * GIT_AUTHOR_DATE that will be used for the commit that is currently
111 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
113 * When an "edit" rebase command is being processed, the SHA1 of the
114 * commit to be edited is recorded in this file. When "git rebase
115 * --continue" is executed, if there are any staged changes then they
116 * will be amended to the HEAD commit, but only provided the HEAD
117 * commit is still the commit to be edited. When any other rebase
118 * command is processed, this file is deleted.
120 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
122 * When we stop at a given patch via the "edit" command, this file contains
123 * the abbreviated commit name of the corresponding patch.
125 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
127 * For the post-rewrite hook, we make a list of rewritten commits and
128 * their new sha1s. The rewritten-pending list keeps the sha1s of
129 * commits that have been processed, but not committed yet,
130 * e.g. because they are waiting for a 'squash' command.
132 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
133 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
134 "rebase-merge/rewritten-pending")
137 * The path of the file containing the OID of the "squash onto" commit, i.e.
138 * the dummy commit used for `reset [new root]`.
140 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
143 * The path of the file listing refs that need to be deleted after the rebase
144 * finishes. This is used by the `label` command to record the need for cleanup.
146 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
149 * The following files are written by git-rebase just after parsing the
152 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
153 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
154 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
155 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
156 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
157 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
158 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
159 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
160 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
161 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
162 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
163 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
164 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
165 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
167 static int git_sequencer_config(const char *k, const char *v, void *cb)
169 struct replay_opts *opts = cb;
172 if (!strcmp(k, "commit.cleanup")) {
175 status = git_config_string(&s, k, v);
179 if (!strcmp(s, "verbatim")) {
180 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
181 opts->explicit_cleanup = 1;
182 } else if (!strcmp(s, "whitespace")) {
183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "strip")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
187 opts->explicit_cleanup = 1;
188 } else if (!strcmp(s, "scissors")) {
189 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
190 opts->explicit_cleanup = 1;
192 warning(_("invalid commit message cleanup mode '%s'"),
200 if (!strcmp(k, "commit.gpgsign")) {
201 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
205 status = git_gpg_config(k, v, NULL);
209 return git_diff_basic_config(k, v, NULL);
212 void sequencer_init_config(struct replay_opts *opts)
214 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
215 git_config(git_sequencer_config, opts);
218 static inline int is_rebase_i(const struct replay_opts *opts)
220 return opts->action == REPLAY_INTERACTIVE_REBASE;
223 static const char *get_dir(const struct replay_opts *opts)
225 if (is_rebase_i(opts))
226 return rebase_path();
227 return git_path_seq_dir();
230 static const char *get_todo_path(const struct replay_opts *opts)
232 if (is_rebase_i(opts))
233 return rebase_path_todo();
234 return git_path_todo_file();
238 * Returns 0 for non-conforming footer
239 * Returns 1 for conforming footer
240 * Returns 2 when sob exists within conforming footer
241 * Returns 3 when sob exists within conforming footer as last entry
243 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
244 size_t ignore_footer)
246 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
247 struct trailer_info info;
249 int found_sob = 0, found_sob_last = 0;
253 trailer_info_get(&info, sb->buf, &opts);
255 if (info.trailer_start == info.trailer_end)
258 for (i = 0; i < info.trailer_nr; i++)
259 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
261 if (i == info.trailer_nr - 1)
265 trailer_info_release(&info);
274 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
276 static struct strbuf buf = STRBUF_INIT;
280 sq_quotef(&buf, "-S%s", opts->gpg_sign);
284 int sequencer_remove_state(struct replay_opts *opts)
286 struct strbuf buf = STRBUF_INIT;
289 if (is_rebase_i(opts) &&
290 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
293 char *eol = strchr(p, '\n');
296 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
297 warning(_("could not delete '%s'"), p);
306 free(opts->gpg_sign);
307 free(opts->strategy);
308 for (i = 0; i < opts->xopts_nr; i++)
309 free(opts->xopts[i]);
311 strbuf_release(&opts->current_fixups);
314 strbuf_addstr(&buf, get_dir(opts));
315 if (remove_dir_recursively(&buf, 0))
316 ret = error(_("could not remove '%s'"), buf.buf);
317 strbuf_release(&buf);
322 static const char *action_name(const struct replay_opts *opts)
324 switch (opts->action) {
328 return N_("cherry-pick");
329 case REPLAY_INTERACTIVE_REBASE:
332 die(_("unknown action: %d"), opts->action);
335 struct commit_message {
342 static const char *short_commit_name(struct commit *commit)
344 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
347 static int get_message(struct commit *commit, struct commit_message *out)
349 const char *abbrev, *subject;
352 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
353 abbrev = short_commit_name(commit);
355 subject_len = find_commit_subject(out->message, &subject);
357 out->subject = xmemdupz(subject, subject_len);
358 out->label = xstrfmt("%s... %s", abbrev, out->subject);
359 out->parent_label = xstrfmt("parent of %s", out->label);
364 static void free_message(struct commit *commit, struct commit_message *msg)
366 free(msg->parent_label);
369 unuse_commit_buffer(commit, msg->message);
372 static void print_advice(struct repository *r, int show_hint,
373 struct replay_opts *opts)
375 char *msg = getenv("GIT_CHERRY_PICK_HELP");
378 fprintf(stderr, "%s\n", msg);
380 * A conflict has occurred but the porcelain
381 * (typically rebase --interactive) wants to take care
382 * of the commit itself so remove CHERRY_PICK_HEAD
384 unlink(git_path_cherry_pick_head(r));
390 advise(_("after resolving the conflicts, mark the corrected paths\n"
391 "with 'git add <paths>' or 'git rm <paths>'"));
393 advise(_("after resolving the conflicts, mark the corrected paths\n"
394 "with 'git add <paths>' or 'git rm <paths>'\n"
395 "and commit the result with 'git commit'"));
399 static int write_message(const void *buf, size_t len, const char *filename,
402 struct lock_file msg_file = LOCK_INIT;
404 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
406 return error_errno(_("could not lock '%s'"), filename);
407 if (write_in_full(msg_fd, buf, len) < 0) {
408 error_errno(_("could not write to '%s'"), filename);
409 rollback_lock_file(&msg_file);
412 if (append_eol && write(msg_fd, "\n", 1) < 0) {
413 error_errno(_("could not write eol to '%s'"), filename);
414 rollback_lock_file(&msg_file);
417 if (commit_lock_file(&msg_file) < 0)
418 return error(_("failed to finalize '%s'"), filename);
423 int read_oneliner(struct strbuf *buf,
424 const char *path, unsigned flags)
426 int orig_len = buf->len;
428 if (strbuf_read_file(buf, path, 0) < 0) {
429 if ((flags & READ_ONELINER_WARN_MISSING) ||
430 (errno != ENOENT && errno != ENOTDIR))
431 warning_errno(_("could not read '%s'"), path);
435 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
436 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
438 buf->buf[buf->len] = '\0';
441 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
447 static struct tree *empty_tree(struct repository *r)
449 return lookup_tree(r, the_hash_algo->empty_tree);
452 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
454 if (repo_read_index_unmerged(repo))
455 return error_resolve_conflict(_(action_name(opts)));
457 error(_("your local changes would be overwritten by %s."),
458 _(action_name(opts)));
460 if (advice_commit_before_merge)
461 advise(_("commit your changes or stash them to proceed."));
465 static void update_abort_safety_file(void)
467 struct object_id head;
469 /* Do nothing on a single-pick */
470 if (!file_exists(git_path_seq_dir()))
473 if (!get_oid("HEAD", &head))
474 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
476 write_file(git_path_abort_safety_file(), "%s", "");
479 static int fast_forward_to(struct repository *r,
480 const struct object_id *to,
481 const struct object_id *from,
483 struct replay_opts *opts)
485 struct ref_transaction *transaction;
486 struct strbuf sb = STRBUF_INIT;
487 struct strbuf err = STRBUF_INIT;
490 if (checkout_fast_forward(r, from, to, 1))
491 return -1; /* the callee should have complained already */
493 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
495 transaction = ref_transaction_begin(&err);
497 ref_transaction_update(transaction, "HEAD",
498 to, unborn && !is_rebase_i(opts) ?
501 ref_transaction_commit(transaction, &err)) {
502 ref_transaction_free(transaction);
503 error("%s", err.buf);
505 strbuf_release(&err);
510 strbuf_release(&err);
511 ref_transaction_free(transaction);
512 update_abort_safety_file();
516 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
519 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
520 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
521 COMMIT_MSG_CLEANUP_SPACE;
522 else if (!strcmp(cleanup_arg, "verbatim"))
523 return COMMIT_MSG_CLEANUP_NONE;
524 else if (!strcmp(cleanup_arg, "whitespace"))
525 return COMMIT_MSG_CLEANUP_SPACE;
526 else if (!strcmp(cleanup_arg, "strip"))
527 return COMMIT_MSG_CLEANUP_ALL;
528 else if (!strcmp(cleanup_arg, "scissors"))
529 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
530 COMMIT_MSG_CLEANUP_SPACE;
532 die(_("Invalid cleanup mode %s"), cleanup_arg);
536 * NB using int rather than enum cleanup_mode to stop clang's
537 * -Wtautological-constant-out-of-range-compare complaining that the comparison
540 static const char *describe_cleanup_mode(int cleanup_mode)
542 static const char *modes[] = { "whitespace",
547 if (cleanup_mode < ARRAY_SIZE(modes))
548 return modes[cleanup_mode];
550 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
553 void append_conflicts_hint(struct index_state *istate,
554 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
558 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
559 strbuf_addch(msgbuf, '\n');
560 wt_status_append_cut_line(msgbuf);
561 strbuf_addch(msgbuf, comment_line_char);
564 strbuf_addch(msgbuf, '\n');
565 strbuf_commented_addf(msgbuf, "Conflicts:\n");
566 for (i = 0; i < istate->cache_nr;) {
567 const struct cache_entry *ce = istate->cache[i++];
569 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
570 while (i < istate->cache_nr &&
571 !strcmp(ce->name, istate->cache[i]->name))
577 static int do_recursive_merge(struct repository *r,
578 struct commit *base, struct commit *next,
579 const char *base_label, const char *next_label,
580 struct object_id *head, struct strbuf *msgbuf,
581 struct replay_opts *opts)
583 struct merge_options o;
584 struct tree *next_tree, *base_tree, *head_tree;
587 struct lock_file index_lock = LOCK_INIT;
589 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
594 init_merge_options(&o, r);
595 o.ancestor = base ? base_label : "(empty tree)";
597 o.branch2 = next ? next_label : "(empty tree)";
598 if (is_rebase_i(opts))
600 o.show_rename_progress = 1;
602 head_tree = parse_tree_indirect(head);
603 next_tree = next ? get_commit_tree(next) : empty_tree(r);
604 base_tree = base ? get_commit_tree(base) : empty_tree(r);
606 for (i = 0; i < opts->xopts_nr; i++)
607 parse_merge_opt(&o, opts->xopts[i]);
609 clean = merge_trees(&o,
611 next_tree, base_tree);
612 if (is_rebase_i(opts) && clean <= 0)
613 fputs(o.obuf.buf, stdout);
614 strbuf_release(&o.obuf);
616 rollback_lock_file(&index_lock);
620 if (write_locked_index(r->index, &index_lock,
621 COMMIT_LOCK | SKIP_IF_UNCHANGED))
623 * TRANSLATORS: %s will be "revert", "cherry-pick" or
626 return error(_("%s: Unable to write new index file"),
627 _(action_name(opts)));
630 append_conflicts_hint(r->index, msgbuf,
631 opts->default_msg_cleanup);
636 static struct object_id *get_cache_tree_oid(struct index_state *istate)
638 if (!istate->cache_tree)
639 istate->cache_tree = cache_tree();
641 if (!cache_tree_fully_valid(istate->cache_tree))
642 if (cache_tree_update(istate, 0)) {
643 error(_("unable to update cache tree"));
647 return &istate->cache_tree->oid;
650 static int is_index_unchanged(struct repository *r)
652 struct object_id head_oid, *cache_tree_oid;
653 struct commit *head_commit;
654 struct index_state *istate = r->index;
656 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
657 return error(_("could not resolve HEAD commit"));
659 head_commit = lookup_commit(r, &head_oid);
662 * If head_commit is NULL, check_commit, called from
663 * lookup_commit, would have indicated that head_commit is not
664 * a commit object already. parse_commit() will return failure
665 * without further complaints in such a case. Otherwise, if
666 * the commit is invalid, parse_commit() will complain. So
667 * there is nothing for us to say here. Just return failure.
669 if (parse_commit(head_commit))
672 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
675 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
678 static int write_author_script(const char *message)
680 struct strbuf buf = STRBUF_INIT;
685 if (!*message || starts_with(message, "\n")) {
687 /* Missing 'author' line? */
688 unlink(rebase_path_author_script());
690 } else if (skip_prefix(message, "author ", &message))
692 else if ((eol = strchr(message, '\n')))
697 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
698 while (*message && *message != '\n' && *message != '\r')
699 if (skip_prefix(message, " <", &message))
701 else if (*message != '\'')
702 strbuf_addch(&buf, *(message++));
704 strbuf_addf(&buf, "'\\%c'", *(message++));
705 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
706 while (*message && *message != '\n' && *message != '\r')
707 if (skip_prefix(message, "> ", &message))
709 else if (*message != '\'')
710 strbuf_addch(&buf, *(message++));
712 strbuf_addf(&buf, "'\\%c'", *(message++));
713 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
714 while (*message && *message != '\n' && *message != '\r')
715 if (*message != '\'')
716 strbuf_addch(&buf, *(message++));
718 strbuf_addf(&buf, "'\\%c'", *(message++));
719 strbuf_addch(&buf, '\'');
720 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
721 strbuf_release(&buf);
726 * Take a series of KEY='VALUE' lines where VALUE part is
727 * sq-quoted, and append <KEY, VALUE> at the end of the string list
729 static int parse_key_value_squoted(char *buf, struct string_list *list)
732 struct string_list_item *item;
734 char *cp = strchr(buf, '=');
736 np = strchrnul(buf, '\n');
737 return error(_("no key present in '%.*s'"),
738 (int) (np - buf), buf);
740 np = strchrnul(cp, '\n');
742 item = string_list_append(list, buf);
744 buf = np + (*np == '\n');
748 return error(_("unable to dequote value of '%s'"),
750 item->util = xstrdup(cp);
756 * Reads and parses the state directory's "author-script" file, and sets name,
757 * email and date accordingly.
758 * Returns 0 on success, -1 if the file could not be parsed.
760 * The author script is of the format:
762 * GIT_AUTHOR_NAME='$author_name'
763 * GIT_AUTHOR_EMAIL='$author_email'
764 * GIT_AUTHOR_DATE='$author_date'
766 * where $author_name, $author_email and $author_date are quoted. We are strict
767 * with our parsing, as the file was meant to be eval'd in the now-removed
768 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
769 * from what this function expects, it is better to bail out than to do
770 * something that the user does not expect.
772 int read_author_script(const char *path, char **name, char **email, char **date,
775 struct strbuf buf = STRBUF_INIT;
776 struct string_list kv = STRING_LIST_INIT_DUP;
777 int retval = -1; /* assume failure */
778 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
780 if (strbuf_read_file(&buf, path, 256) <= 0) {
781 strbuf_release(&buf);
782 if (errno == ENOENT && allow_missing)
785 return error_errno(_("could not open '%s' for reading"),
789 if (parse_key_value_squoted(buf.buf, &kv))
792 for (i = 0; i < kv.nr; i++) {
793 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
795 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
798 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
800 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
803 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
805 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
809 err = error(_("unknown variable '%s'"),
814 error(_("missing 'GIT_AUTHOR_NAME'"));
816 error(_("missing 'GIT_AUTHOR_EMAIL'"));
818 error(_("missing 'GIT_AUTHOR_DATE'"));
819 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
821 *name = kv.items[name_i].util;
822 *email = kv.items[email_i].util;
823 *date = kv.items[date_i].util;
826 string_list_clear(&kv, !!retval);
827 strbuf_release(&buf);
832 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
833 * file with shell quoting into struct argv_array. Returns -1 on
834 * error, 0 otherwise.
836 static int read_env_script(struct argv_array *env)
838 char *name, *email, *date;
840 if (read_author_script(rebase_path_author_script(),
841 &name, &email, &date, 0))
844 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
845 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
846 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
854 static char *get_author(const char *message)
859 a = find_commit_header(message, "author", &len);
861 return xmemdupz(a, len);
866 static const char staged_changes_advice[] =
867 N_("you have staged changes in your working tree\n"
868 "If these changes are meant to be squashed into the previous commit, run:\n"
870 " git commit --amend %s\n"
872 "If they are meant to go into a new commit, run:\n"
876 "In both cases, once you're done, continue with:\n"
878 " git rebase --continue\n");
880 #define ALLOW_EMPTY (1<<0)
881 #define EDIT_MSG (1<<1)
882 #define AMEND_MSG (1<<2)
883 #define CLEANUP_MSG (1<<3)
884 #define VERIFY_MSG (1<<4)
885 #define CREATE_ROOT_COMMIT (1<<5)
887 static int run_command_silent_on_success(struct child_process *cmd)
889 struct strbuf buf = STRBUF_INIT;
892 cmd->stdout_to_stderr = 1;
893 rc = pipe_command(cmd,
899 fputs(buf.buf, stderr);
900 strbuf_release(&buf);
905 * If we are cherry-pick, and if the merge did not result in
906 * hand-editing, we will hit this commit and inherit the original
907 * author date and name.
909 * If we are revert, or if our cherry-pick results in a hand merge,
910 * we had better say that the current user is responsible for that.
912 * An exception is when run_git_commit() is called during an
913 * interactive rebase: in that case, we will want to retain the
916 static int run_git_commit(struct repository *r,
918 struct replay_opts *opts,
921 struct child_process cmd = CHILD_PROCESS_INIT;
925 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
926 const char *gpg_opt = gpg_sign_opt_quoted(opts);
928 return error(_(staged_changes_advice),
932 argv_array_push(&cmd.args, "commit");
934 if (!(flags & VERIFY_MSG))
935 argv_array_push(&cmd.args, "-n");
936 if ((flags & AMEND_MSG))
937 argv_array_push(&cmd.args, "--amend");
939 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
941 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
942 else if (!(flags & EDIT_MSG))
943 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
944 if ((flags & CLEANUP_MSG))
945 argv_array_push(&cmd.args, "--cleanup=strip");
946 if ((flags & EDIT_MSG))
947 argv_array_push(&cmd.args, "-e");
948 else if (!(flags & CLEANUP_MSG) &&
949 !opts->signoff && !opts->record_origin &&
950 !opts->explicit_cleanup)
951 argv_array_push(&cmd.args, "--cleanup=verbatim");
953 if ((flags & ALLOW_EMPTY))
954 argv_array_push(&cmd.args, "--allow-empty");
956 if (!(flags & EDIT_MSG))
957 argv_array_push(&cmd.args, "--allow-empty-message");
959 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
960 return run_command_silent_on_success(&cmd);
962 return run_command(&cmd);
965 static int rest_is_empty(const struct strbuf *sb, int start)
970 /* Check if the rest is just whitespace and Signed-off-by's. */
971 for (i = start; i < sb->len; i++) {
972 nl = memchr(sb->buf + i, '\n', sb->len - i);
978 if (strlen(sign_off_header) <= eol - i &&
979 starts_with(sb->buf + i, sign_off_header)) {
984 if (!isspace(sb->buf[i++]))
991 void cleanup_message(struct strbuf *msgbuf,
992 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
994 if (verbose || /* Truncate the message just before the diff, if any. */
995 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
996 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
997 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
998 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1002 * Find out if the message in the strbuf contains only whitespace and
1003 * Signed-off-by lines.
1005 int message_is_empty(const struct strbuf *sb,
1006 enum commit_msg_cleanup_mode cleanup_mode)
1008 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1010 return rest_is_empty(sb, 0);
1014 * See if the user edited the message in the editor or left what
1015 * was in the template intact
1017 int template_untouched(const struct strbuf *sb, const char *template_file,
1018 enum commit_msg_cleanup_mode cleanup_mode)
1020 struct strbuf tmpl = STRBUF_INIT;
1023 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1026 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1029 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1030 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1032 strbuf_release(&tmpl);
1033 return rest_is_empty(sb, start - sb->buf);
1036 int update_head_with_reflog(const struct commit *old_head,
1037 const struct object_id *new_head,
1038 const char *action, const struct strbuf *msg,
1041 struct ref_transaction *transaction;
1042 struct strbuf sb = STRBUF_INIT;
1047 strbuf_addstr(&sb, action);
1048 strbuf_addstr(&sb, ": ");
1051 nl = strchr(msg->buf, '\n');
1053 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1055 strbuf_addbuf(&sb, msg);
1056 strbuf_addch(&sb, '\n');
1059 transaction = ref_transaction_begin(err);
1061 ref_transaction_update(transaction, "HEAD", new_head,
1062 old_head ? &old_head->object.oid : &null_oid,
1064 ref_transaction_commit(transaction, err)) {
1067 ref_transaction_free(transaction);
1068 strbuf_release(&sb);
1073 static int run_rewrite_hook(const struct object_id *oldoid,
1074 const struct object_id *newoid)
1076 struct child_process proc = CHILD_PROCESS_INIT;
1077 const char *argv[3];
1079 struct strbuf sb = STRBUF_INIT;
1081 argv[0] = find_hook("post-rewrite");
1090 proc.stdout_to_stderr = 1;
1091 proc.trace2_hook_name = "post-rewrite";
1093 code = start_command(&proc);
1096 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1097 sigchain_push(SIGPIPE, SIG_IGN);
1098 write_in_full(proc.in, sb.buf, sb.len);
1100 strbuf_release(&sb);
1101 sigchain_pop(SIGPIPE);
1102 return finish_command(&proc);
1105 void commit_post_rewrite(struct repository *r,
1106 const struct commit *old_head,
1107 const struct object_id *new_head)
1109 struct notes_rewrite_cfg *cfg;
1111 cfg = init_copy_notes_for_rewrite("amend");
1113 /* we are amending, so old_head is not NULL */
1114 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1115 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1117 run_rewrite_hook(&old_head->object.oid, new_head);
1120 static int run_prepare_commit_msg_hook(struct repository *r,
1125 const char *name, *arg1 = NULL, *arg2 = NULL;
1127 name = git_path_commit_editmsg();
1128 if (write_message(msg->buf, msg->len, name, 0))
1137 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1139 ret = error(_("'prepare-commit-msg' hook failed"));
1144 static const char implicit_ident_advice_noconfig[] =
1145 N_("Your name and email address were configured automatically based\n"
1146 "on your username and hostname. Please check that they are accurate.\n"
1147 "You can suppress this message by setting them explicitly. Run the\n"
1148 "following command and follow the instructions in your editor to edit\n"
1149 "your configuration file:\n"
1151 " git config --global --edit\n"
1153 "After doing this, you may fix the identity used for this commit with:\n"
1155 " git commit --amend --reset-author\n");
1157 static const char implicit_ident_advice_config[] =
1158 N_("Your name and email address were configured automatically based\n"
1159 "on your username and hostname. Please check that they are accurate.\n"
1160 "You can suppress this message by setting them explicitly:\n"
1162 " git config --global user.name \"Your Name\"\n"
1163 " git config --global user.email you@example.com\n"
1165 "After doing this, you may fix the identity used for this commit with:\n"
1167 " git commit --amend --reset-author\n");
1169 static const char *implicit_ident_advice(void)
1171 char *user_config = expand_user_path("~/.gitconfig", 0);
1172 char *xdg_config = xdg_config_home("config");
1173 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1179 return _(implicit_ident_advice_config);
1181 return _(implicit_ident_advice_noconfig);
1185 void print_commit_summary(struct repository *r,
1187 const struct object_id *oid,
1190 struct rev_info rev;
1191 struct commit *commit;
1192 struct strbuf format = STRBUF_INIT;
1194 struct pretty_print_context pctx = {0};
1195 struct strbuf author_ident = STRBUF_INIT;
1196 struct strbuf committer_ident = STRBUF_INIT;
1198 commit = lookup_commit(r, oid);
1200 die(_("couldn't look up newly created commit"));
1201 if (parse_commit(commit))
1202 die(_("could not parse newly created commit"));
1204 strbuf_addstr(&format, "format:%h] %s");
1206 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1207 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1208 if (strbuf_cmp(&author_ident, &committer_ident)) {
1209 strbuf_addstr(&format, "\n Author: ");
1210 strbuf_addbuf_percentquote(&format, &author_ident);
1212 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1213 struct strbuf date = STRBUF_INIT;
1215 format_commit_message(commit, "%ad", &date, &pctx);
1216 strbuf_addstr(&format, "\n Date: ");
1217 strbuf_addbuf_percentquote(&format, &date);
1218 strbuf_release(&date);
1220 if (!committer_ident_sufficiently_given()) {
1221 strbuf_addstr(&format, "\n Committer: ");
1222 strbuf_addbuf_percentquote(&format, &committer_ident);
1223 if (advice_implicit_identity) {
1224 strbuf_addch(&format, '\n');
1225 strbuf_addstr(&format, implicit_ident_advice());
1228 strbuf_release(&author_ident);
1229 strbuf_release(&committer_ident);
1231 repo_init_revisions(r, &rev, prefix);
1232 setup_revisions(0, NULL, &rev, NULL);
1235 rev.diffopt.output_format =
1236 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1238 rev.verbose_header = 1;
1239 rev.show_root_diff = 1;
1240 get_commit_format(format.buf, &rev);
1241 rev.always_show_header = 0;
1242 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1243 rev.diffopt.break_opt = 0;
1244 diff_setup_done(&rev.diffopt);
1246 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1248 die_errno(_("unable to resolve HEAD after creating commit"));
1249 if (!strcmp(head, "HEAD"))
1250 head = _("detached HEAD");
1252 skip_prefix(head, "refs/heads/", &head);
1253 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1254 _(" (root-commit)") : "");
1256 if (!log_tree_commit(&rev, commit)) {
1257 rev.always_show_header = 1;
1258 rev.use_terminator = 1;
1259 log_tree_commit(&rev, commit);
1262 strbuf_release(&format);
1265 static int parse_head(struct repository *r, struct commit **head)
1267 struct commit *current_head;
1268 struct object_id oid;
1270 if (get_oid("HEAD", &oid)) {
1271 current_head = NULL;
1273 current_head = lookup_commit_reference(r, &oid);
1275 return error(_("could not parse HEAD"));
1276 if (!oideq(&oid, ¤t_head->object.oid)) {
1277 warning(_("HEAD %s is not a commit!"),
1280 if (parse_commit(current_head))
1281 return error(_("could not parse HEAD commit"));
1283 *head = current_head;
1289 * Try to commit without forking 'git commit'. In some cases we need
1290 * to run 'git commit' to display an error message
1293 * -1 - error unable to commit
1295 * 1 - run 'git commit'
1297 static int try_to_commit(struct repository *r,
1298 struct strbuf *msg, const char *author,
1299 struct replay_opts *opts, unsigned int flags,
1300 struct object_id *oid)
1302 struct object_id tree;
1303 struct commit *current_head = NULL;
1304 struct commit_list *parents = NULL;
1305 struct commit_extra_header *extra = NULL;
1306 struct strbuf err = STRBUF_INIT;
1307 struct strbuf commit_msg = STRBUF_INIT;
1308 char *amend_author = NULL;
1309 const char *hook_commit = NULL;
1310 enum commit_msg_cleanup_mode cleanup;
1313 if (parse_head(r, ¤t_head))
1316 if (flags & AMEND_MSG) {
1317 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1318 const char *out_enc = get_commit_output_encoding();
1319 const char *message = logmsg_reencode(current_head, NULL,
1323 const char *orig_message = NULL;
1325 find_commit_subject(message, &orig_message);
1327 strbuf_addstr(msg, orig_message);
1328 hook_commit = "HEAD";
1330 author = amend_author = get_author(message);
1331 unuse_commit_buffer(current_head, message);
1333 res = error(_("unable to parse commit author"));
1336 parents = copy_commit_list(current_head->parents);
1337 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1338 } else if (current_head &&
1339 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1340 commit_list_insert(current_head, &parents);
1343 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1344 res = error(_("git write-tree failed to write a tree"));
1348 if (!(flags & ALLOW_EMPTY)) {
1349 struct commit *first_parent = current_head;
1351 if (flags & AMEND_MSG) {
1352 if (current_head->parents) {
1353 first_parent = current_head->parents->item;
1354 if (repo_parse_commit(r, first_parent)) {
1355 res = error(_("could not parse HEAD commit"));
1359 first_parent = NULL;
1362 if (oideq(first_parent
1363 ? get_commit_tree_oid(first_parent)
1364 : the_hash_algo->empty_tree,
1366 res = 1; /* run 'git commit' to display error message */
1371 if (find_hook("prepare-commit-msg")) {
1372 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1375 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1377 res = error_errno(_("unable to read commit message "
1379 git_path_commit_editmsg());
1385 if (flags & CLEANUP_MSG)
1386 cleanup = COMMIT_MSG_CLEANUP_ALL;
1387 else if ((opts->signoff || opts->record_origin) &&
1388 !opts->explicit_cleanup)
1389 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1391 cleanup = opts->default_msg_cleanup;
1393 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1394 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1395 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1396 res = 1; /* run 'git commit' to display error message */
1402 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1403 oid, author, opts->gpg_sign, extra)) {
1404 res = error(_("failed to write commit object"));
1408 if (update_head_with_reflog(current_head, oid,
1409 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1410 res = error("%s", err.buf);
1414 run_commit_hook(0, r->index_file, "post-commit", NULL);
1415 if (flags & AMEND_MSG)
1416 commit_post_rewrite(r, current_head, oid);
1419 free_commit_extra_headers(extra);
1420 strbuf_release(&err);
1421 strbuf_release(&commit_msg);
1427 static int do_commit(struct repository *r,
1428 const char *msg_file, const char *author,
1429 struct replay_opts *opts, unsigned int flags)
1433 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1434 struct object_id oid;
1435 struct strbuf sb = STRBUF_INIT;
1437 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1438 return error_errno(_("unable to read commit message "
1442 res = try_to_commit(r, msg_file ? &sb : NULL,
1443 author, opts, flags, &oid);
1444 strbuf_release(&sb);
1446 unlink(git_path_cherry_pick_head(r));
1447 unlink(git_path_merge_msg(r));
1448 if (!is_rebase_i(opts))
1449 print_commit_summary(r, NULL, &oid,
1450 SUMMARY_SHOW_AUTHOR_DATE);
1455 return run_git_commit(r, msg_file, opts, flags);
1460 static int is_original_commit_empty(struct commit *commit)
1462 const struct object_id *ptree_oid;
1464 if (parse_commit(commit))
1465 return error(_("could not parse commit %s"),
1466 oid_to_hex(&commit->object.oid));
1467 if (commit->parents) {
1468 struct commit *parent = commit->parents->item;
1469 if (parse_commit(parent))
1470 return error(_("could not parse parent commit %s"),
1471 oid_to_hex(&parent->object.oid));
1472 ptree_oid = get_commit_tree_oid(parent);
1474 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1477 return oideq(ptree_oid, get_commit_tree_oid(commit));
1481 * Should empty commits be allowed? Return status:
1482 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1483 * 0: Halt on empty commit
1484 * 1: Allow empty commit
1485 * 2: Drop empty commit
1487 static int allow_empty(struct repository *r,
1488 struct replay_opts *opts,
1489 struct commit *commit)
1491 int index_unchanged, originally_empty;
1496 * (1) we do not allow empty at all and error out.
1498 * (2) we allow ones that were initially empty, and
1499 * just drop the ones that become empty
1501 * (3) we allow ones that were initially empty, but
1502 * halt for the ones that become empty;
1504 * (4) we allow both.
1506 if (!opts->allow_empty)
1507 return 0; /* let "git commit" barf as necessary */
1509 index_unchanged = is_index_unchanged(r);
1510 if (index_unchanged < 0)
1511 return index_unchanged;
1512 if (!index_unchanged)
1513 return 0; /* we do not have to say --allow-empty */
1515 if (opts->keep_redundant_commits)
1518 originally_empty = is_original_commit_empty(commit);
1519 if (originally_empty < 0)
1520 return originally_empty;
1521 if (originally_empty)
1523 else if (opts->drop_redundant_commits)
1532 } todo_command_info[] = {
1549 static const char *command_to_string(const enum todo_command command)
1551 if (command < TODO_COMMENT)
1552 return todo_command_info[command].str;
1553 die(_("unknown command: %d"), command);
1556 static char command_to_char(const enum todo_command command)
1558 if (command < TODO_COMMENT && todo_command_info[command].c)
1559 return todo_command_info[command].c;
1560 return comment_line_char;
1563 static int is_noop(const enum todo_command command)
1565 return TODO_NOOP <= command;
1568 static int is_fixup(enum todo_command command)
1570 return command == TODO_FIXUP || command == TODO_SQUASH;
1573 /* Does this command create a (non-merge) commit? */
1574 static int is_pick_or_similar(enum todo_command command)
1589 static int update_squash_messages(struct repository *r,
1590 enum todo_command command,
1591 struct commit *commit,
1592 struct replay_opts *opts)
1594 struct strbuf buf = STRBUF_INIT;
1596 const char *message, *body;
1597 const char *encoding = get_commit_output_encoding();
1599 if (opts->current_fixup_count > 0) {
1600 struct strbuf header = STRBUF_INIT;
1603 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1604 return error(_("could not read '%s'"),
1605 rebase_path_squash_msg());
1607 eol = buf.buf[0] != comment_line_char ?
1608 buf.buf : strchrnul(buf.buf, '\n');
1610 strbuf_addf(&header, "%c ", comment_line_char);
1611 strbuf_addf(&header, _("This is a combination of %d commits."),
1612 opts->current_fixup_count + 2);
1613 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1614 strbuf_release(&header);
1616 struct object_id head;
1617 struct commit *head_commit;
1618 const char *head_message, *body;
1620 if (get_oid("HEAD", &head))
1621 return error(_("need a HEAD to fixup"));
1622 if (!(head_commit = lookup_commit_reference(r, &head)))
1623 return error(_("could not read HEAD"));
1624 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1625 return error(_("could not read HEAD's commit message"));
1627 find_commit_subject(head_message, &body);
1628 if (write_message(body, strlen(body),
1629 rebase_path_fixup_msg(), 0)) {
1630 unuse_commit_buffer(head_commit, head_message);
1631 return error(_("cannot write '%s'"),
1632 rebase_path_fixup_msg());
1635 strbuf_addf(&buf, "%c ", comment_line_char);
1636 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1637 strbuf_addf(&buf, "\n%c ", comment_line_char);
1638 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1639 strbuf_addstr(&buf, "\n\n");
1640 strbuf_addstr(&buf, body);
1642 unuse_commit_buffer(head_commit, head_message);
1645 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1646 return error(_("could not read commit message of %s"),
1647 oid_to_hex(&commit->object.oid));
1648 find_commit_subject(message, &body);
1650 if (command == TODO_SQUASH) {
1651 unlink(rebase_path_fixup_msg());
1652 strbuf_addf(&buf, "\n%c ", comment_line_char);
1653 strbuf_addf(&buf, _("This is the commit message #%d:"),
1654 ++opts->current_fixup_count + 1);
1655 strbuf_addstr(&buf, "\n\n");
1656 strbuf_addstr(&buf, body);
1657 } else if (command == TODO_FIXUP) {
1658 strbuf_addf(&buf, "\n%c ", comment_line_char);
1659 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1660 ++opts->current_fixup_count + 1);
1661 strbuf_addstr(&buf, "\n\n");
1662 strbuf_add_commented_lines(&buf, body, strlen(body));
1664 return error(_("unknown command: %d"), command);
1665 unuse_commit_buffer(commit, message);
1667 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1668 strbuf_release(&buf);
1671 strbuf_addf(&opts->current_fixups, "%s%s %s",
1672 opts->current_fixups.len ? "\n" : "",
1673 command_to_string(command),
1674 oid_to_hex(&commit->object.oid));
1675 res = write_message(opts->current_fixups.buf,
1676 opts->current_fixups.len,
1677 rebase_path_current_fixups(), 0);
1683 static void flush_rewritten_pending(void)
1685 struct strbuf buf = STRBUF_INIT;
1686 struct object_id newoid;
1689 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1690 !get_oid("HEAD", &newoid) &&
1691 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1692 char *bol = buf.buf, *eol;
1695 eol = strchrnul(bol, '\n');
1696 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1697 bol, oid_to_hex(&newoid));
1703 unlink(rebase_path_rewritten_pending());
1705 strbuf_release(&buf);
1708 static void record_in_rewritten(struct object_id *oid,
1709 enum todo_command next_command)
1711 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1716 fprintf(out, "%s\n", oid_to_hex(oid));
1719 if (!is_fixup(next_command))
1720 flush_rewritten_pending();
1723 static int do_pick_commit(struct repository *r,
1724 enum todo_command command,
1725 struct commit *commit,
1726 struct replay_opts *opts,
1727 int final_fixup, int *check_todo)
1729 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1730 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1731 struct object_id head;
1732 struct commit *base, *next, *parent;
1733 const char *base_label, *next_label;
1734 char *author = NULL;
1735 struct commit_message msg = { NULL, NULL, NULL, NULL };
1736 struct strbuf msgbuf = STRBUF_INIT;
1737 int res, unborn = 0, reword = 0, allow, drop_commit;
1739 if (opts->no_commit) {
1741 * We do not intend to commit immediately. We just want to
1742 * merge the differences in, so let's compute the tree
1743 * that represents the "current" state for merge-recursive
1746 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1747 return error(_("your index file is unmerged."));
1749 unborn = get_oid("HEAD", &head);
1750 /* Do we want to generate a root commit? */
1751 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1752 oideq(&head, &opts->squash_onto)) {
1753 if (is_fixup(command))
1754 return error(_("cannot fixup root commit"));
1755 flags |= CREATE_ROOT_COMMIT;
1758 oidcpy(&head, the_hash_algo->empty_tree);
1759 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1761 return error_dirty_index(r, opts);
1763 discard_index(r->index);
1765 if (!commit->parents)
1767 else if (commit->parents->next) {
1768 /* Reverting or cherry-picking a merge commit */
1770 struct commit_list *p;
1772 if (!opts->mainline)
1773 return error(_("commit %s is a merge but no -m option was given."),
1774 oid_to_hex(&commit->object.oid));
1776 for (cnt = 1, p = commit->parents;
1777 cnt != opts->mainline && p;
1780 if (cnt != opts->mainline || !p)
1781 return error(_("commit %s does not have parent %d"),
1782 oid_to_hex(&commit->object.oid), opts->mainline);
1784 } else if (1 < opts->mainline)
1786 * Non-first parent explicitly specified as mainline for
1789 return error(_("commit %s does not have parent %d"),
1790 oid_to_hex(&commit->object.oid), opts->mainline);
1792 parent = commit->parents->item;
1794 if (get_message(commit, &msg) != 0)
1795 return error(_("cannot get commit message for %s"),
1796 oid_to_hex(&commit->object.oid));
1798 if (opts->allow_ff && !is_fixup(command) &&
1799 ((parent && oideq(&parent->object.oid, &head)) ||
1800 (!parent && unborn))) {
1801 if (is_rebase_i(opts))
1802 write_author_script(msg.message);
1803 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1805 if (res || command != TODO_REWORD)
1809 goto fast_forward_edit;
1811 if (parent && parse_commit(parent) < 0)
1812 /* TRANSLATORS: The first %s will be a "todo" command like
1813 "revert" or "pick", the second %s a SHA1. */
1814 return error(_("%s: cannot parse parent commit %s"),
1815 command_to_string(command),
1816 oid_to_hex(&parent->object.oid));
1819 * "commit" is an existing commit. We would want to apply
1820 * the difference it introduces since its first parent "prev"
1821 * on top of the current HEAD if we are cherry-pick. Or the
1822 * reverse of it if we are revert.
1825 if (command == TODO_REVERT) {
1827 base_label = msg.label;
1829 next_label = msg.parent_label;
1830 strbuf_addstr(&msgbuf, "Revert \"");
1831 strbuf_addstr(&msgbuf, msg.subject);
1832 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1833 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1835 if (commit->parents && commit->parents->next) {
1836 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1837 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1839 strbuf_addstr(&msgbuf, ".\n");
1844 base_label = msg.parent_label;
1846 next_label = msg.label;
1848 /* Append the commit log message to msgbuf. */
1849 if (find_commit_subject(msg.message, &p))
1850 strbuf_addstr(&msgbuf, p);
1852 if (opts->record_origin) {
1853 strbuf_complete_line(&msgbuf);
1854 if (!has_conforming_footer(&msgbuf, NULL, 0))
1855 strbuf_addch(&msgbuf, '\n');
1856 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1857 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1858 strbuf_addstr(&msgbuf, ")\n");
1860 if (!is_fixup(command))
1861 author = get_author(msg.message);
1864 if (command == TODO_REWORD)
1866 else if (is_fixup(command)) {
1867 if (update_squash_messages(r, command, commit, opts))
1871 msg_file = rebase_path_squash_msg();
1872 else if (file_exists(rebase_path_fixup_msg())) {
1873 flags |= CLEANUP_MSG;
1874 msg_file = rebase_path_fixup_msg();
1876 const char *dest = git_path_squash_msg(r);
1878 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1879 return error(_("could not rename '%s' to '%s'"),
1880 rebase_path_squash_msg(), dest);
1881 unlink(git_path_merge_msg(r));
1887 if (opts->signoff && !is_fixup(command))
1888 append_signoff(&msgbuf, 0, 0);
1890 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1892 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1893 res = do_recursive_merge(r, base, next, base_label, next_label,
1894 &head, &msgbuf, opts);
1898 res |= write_message(msgbuf.buf, msgbuf.len,
1899 git_path_merge_msg(r), 0);
1901 struct commit_list *common = NULL;
1902 struct commit_list *remotes = NULL;
1904 res = write_message(msgbuf.buf, msgbuf.len,
1905 git_path_merge_msg(r), 0);
1907 commit_list_insert(base, &common);
1908 commit_list_insert(next, &remotes);
1909 res |= try_merge_command(r, opts->strategy,
1910 opts->xopts_nr, (const char **)opts->xopts,
1911 common, oid_to_hex(&head), remotes);
1912 free_commit_list(common);
1913 free_commit_list(remotes);
1915 strbuf_release(&msgbuf);
1918 * If the merge was clean or if it failed due to conflict, we write
1919 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1920 * However, if the merge did not even start, then we don't want to
1923 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1924 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1925 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1927 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1928 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1929 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1933 error(command == TODO_REVERT
1934 ? _("could not revert %s... %s")
1935 : _("could not apply %s... %s"),
1936 short_commit_name(commit), msg.subject);
1937 print_advice(r, res == 1, opts);
1938 repo_rerere(r, opts->allow_rerere_auto);
1943 allow = allow_empty(r, opts, commit);
1947 } else if (allow == 1) {
1948 flags |= ALLOW_EMPTY;
1949 } else if (allow == 2) {
1951 unlink(git_path_cherry_pick_head(r));
1952 unlink(git_path_merge_msg(r));
1954 _("dropping %s %s -- patch contents already upstream\n"),
1955 oid_to_hex(&commit->object.oid), msg.subject);
1956 } /* else allow == 0 and there's nothing special to do */
1957 if (!opts->no_commit && !drop_commit) {
1958 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1959 res = do_commit(r, msg_file, author, opts, flags);
1961 res = error(_("unable to parse commit author"));
1962 *check_todo = !!(flags & EDIT_MSG);
1963 if (!res && reword) {
1965 res = run_git_commit(r, NULL, opts, EDIT_MSG |
1966 VERIFY_MSG | AMEND_MSG |
1967 (flags & ALLOW_EMPTY));
1973 if (!res && final_fixup) {
1974 unlink(rebase_path_fixup_msg());
1975 unlink(rebase_path_squash_msg());
1976 unlink(rebase_path_current_fixups());
1977 strbuf_reset(&opts->current_fixups);
1978 opts->current_fixup_count = 0;
1982 free_message(commit, &msg);
1984 update_abort_safety_file();
1989 static int prepare_revs(struct replay_opts *opts)
1992 * picking (but not reverting) ranges (but not individual revisions)
1993 * should be done in reverse
1995 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1996 opts->revs->reverse ^= 1;
1998 if (prepare_revision_walk(opts->revs))
1999 return error(_("revision walk setup failed"));
2004 static int read_and_refresh_cache(struct repository *r,
2005 struct replay_opts *opts)
2007 struct lock_file index_lock = LOCK_INIT;
2008 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2009 if (repo_read_index(r) < 0) {
2010 rollback_lock_file(&index_lock);
2011 return error(_("git %s: failed to read the index"),
2012 _(action_name(opts)));
2014 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2015 if (index_fd >= 0) {
2016 if (write_locked_index(r->index, &index_lock,
2017 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2018 return error(_("git %s: failed to refresh the index"),
2019 _(action_name(opts)));
2025 enum todo_item_flags {
2026 TODO_EDIT_MERGE_MSG = 1
2029 void todo_list_release(struct todo_list *todo_list)
2031 strbuf_release(&todo_list->buf);
2032 FREE_AND_NULL(todo_list->items);
2033 todo_list->nr = todo_list->alloc = 0;
2036 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2038 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2039 todo_list->total_nr++;
2040 return todo_list->items + todo_list->nr++;
2043 const char *todo_item_get_arg(struct todo_list *todo_list,
2044 struct todo_item *item)
2046 return todo_list->buf.buf + item->arg_offset;
2049 static int is_command(enum todo_command command, const char **bol)
2051 const char *str = todo_command_info[command].str;
2052 const char nick = todo_command_info[command].c;
2053 const char *p = *bol + 1;
2055 return skip_prefix(*bol, str, bol) ||
2056 ((nick && **bol == nick) &&
2057 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2061 static int parse_insn_line(struct repository *r, struct todo_item *item,
2062 const char *buf, const char *bol, char *eol)
2064 struct object_id commit_oid;
2065 char *end_of_object_name;
2066 int i, saved, status, padding;
2071 bol += strspn(bol, " \t");
2073 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2074 item->command = TODO_COMMENT;
2075 item->commit = NULL;
2076 item->arg_offset = bol - buf;
2077 item->arg_len = eol - bol;
2081 for (i = 0; i < TODO_COMMENT; i++)
2082 if (is_command(i, &bol)) {
2086 if (i >= TODO_COMMENT)
2089 /* Eat up extra spaces/ tabs before object name */
2090 padding = strspn(bol, " \t");
2093 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2095 return error(_("%s does not accept arguments: '%s'"),
2096 command_to_string(item->command), bol);
2097 item->commit = NULL;
2098 item->arg_offset = bol - buf;
2099 item->arg_len = eol - bol;
2104 return error(_("missing arguments for %s"),
2105 command_to_string(item->command));
2107 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2108 item->command == TODO_RESET) {
2109 item->commit = NULL;
2110 item->arg_offset = bol - buf;
2111 item->arg_len = (int)(eol - bol);
2115 if (item->command == TODO_MERGE) {
2116 if (skip_prefix(bol, "-C", &bol))
2117 bol += strspn(bol, " \t");
2118 else if (skip_prefix(bol, "-c", &bol)) {
2119 bol += strspn(bol, " \t");
2120 item->flags |= TODO_EDIT_MERGE_MSG;
2122 item->flags |= TODO_EDIT_MERGE_MSG;
2123 item->commit = NULL;
2124 item->arg_offset = bol - buf;
2125 item->arg_len = (int)(eol - bol);
2130 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2131 saved = *end_of_object_name;
2132 *end_of_object_name = '\0';
2133 status = get_oid(bol, &commit_oid);
2135 error(_("could not parse '%s'"), bol); /* return later */
2136 *end_of_object_name = saved;
2138 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2139 item->arg_offset = bol - buf;
2140 item->arg_len = (int)(eol - bol);
2145 item->commit = lookup_commit_reference(r, &commit_oid);
2146 return item->commit ? 0 : -1;
2149 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2151 const char *todo_file, *bol;
2152 struct strbuf buf = STRBUF_INIT;
2155 todo_file = git_path_todo_file();
2156 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2157 if (errno == ENOENT || errno == ENOTDIR)
2160 return error_errno("unable to open '%s'", todo_file);
2162 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2163 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2164 *action = REPLAY_PICK;
2165 else if (is_command(TODO_REVERT, &bol) &&
2166 (*bol == ' ' || *bol == '\t'))
2167 *action = REPLAY_REVERT;
2171 strbuf_release(&buf);
2176 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2177 struct todo_list *todo_list)
2179 struct todo_item *item;
2180 char *p = buf, *next_p;
2181 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2183 todo_list->current = todo_list->nr = 0;
2185 for (i = 1; *p; i++, p = next_p) {
2186 char *eol = strchrnul(p, '\n');
2188 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2190 if (p != eol && eol[-1] == '\r')
2191 eol--; /* strip Carriage Return */
2193 item = append_new_todo(todo_list);
2194 item->offset_in_buf = p - todo_list->buf.buf;
2195 if (parse_insn_line(r, item, buf, p, eol)) {
2196 res = error(_("invalid line %d: %.*s"),
2197 i, (int)(eol - p), p);
2198 item->command = TODO_COMMENT + 1;
2199 item->arg_offset = p - buf;
2200 item->arg_len = (int)(eol - p);
2201 item->commit = NULL;
2206 else if (is_fixup(item->command))
2207 return error(_("cannot '%s' without a previous commit"),
2208 command_to_string(item->command));
2209 else if (!is_noop(item->command))
2216 static int count_commands(struct todo_list *todo_list)
2220 for (i = 0; i < todo_list->nr; i++)
2221 if (todo_list->items[i].command != TODO_COMMENT)
2227 static int get_item_line_offset(struct todo_list *todo_list, int index)
2229 return index < todo_list->nr ?
2230 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2233 static const char *get_item_line(struct todo_list *todo_list, int index)
2235 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2238 static int get_item_line_length(struct todo_list *todo_list, int index)
2240 return get_item_line_offset(todo_list, index + 1)
2241 - get_item_line_offset(todo_list, index);
2244 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2249 fd = open(path, O_RDONLY);
2251 return error_errno(_("could not open '%s'"), path);
2252 len = strbuf_read(sb, fd, 0);
2255 return error(_("could not read '%s'."), path);
2259 static int have_finished_the_last_pick(void)
2261 struct strbuf buf = STRBUF_INIT;
2263 const char *todo_path = git_path_todo_file();
2266 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2267 if (errno == ENOENT) {
2270 error_errno("unable to open '%s'", todo_path);
2274 /* If there is only one line then we are done */
2275 eol = strchr(buf.buf, '\n');
2276 if (!eol || !eol[1])
2279 strbuf_release(&buf);
2284 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2286 struct replay_opts opts = REPLAY_OPTS_INIT;
2287 int need_cleanup = 0;
2289 if (file_exists(git_path_cherry_pick_head(r))) {
2290 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2291 warning(_("cancelling a cherry picking in progress"));
2292 opts.action = REPLAY_PICK;
2296 if (file_exists(git_path_revert_head(r))) {
2297 if (!unlink(git_path_revert_head(r)) && verbose)
2298 warning(_("cancelling a revert in progress"));
2299 opts.action = REPLAY_REVERT;
2306 if (!have_finished_the_last_pick())
2309 sequencer_remove_state(&opts);
2312 static void todo_list_write_total_nr(struct todo_list *todo_list)
2314 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2317 fprintf(f, "%d\n", todo_list->total_nr);
2322 static int read_populate_todo(struct repository *r,
2323 struct todo_list *todo_list,
2324 struct replay_opts *opts)
2327 const char *todo_file = get_todo_path(opts);
2330 strbuf_reset(&todo_list->buf);
2331 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2334 res = stat(todo_file, &st);
2336 return error(_("could not stat '%s'"), todo_file);
2337 fill_stat_data(&todo_list->stat, &st);
2339 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2341 if (is_rebase_i(opts))
2342 return error(_("please fix this using "
2343 "'git rebase --edit-todo'."));
2344 return error(_("unusable instruction sheet: '%s'"), todo_file);
2347 if (!todo_list->nr &&
2348 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2349 return error(_("no commits parsed."));
2351 if (!is_rebase_i(opts)) {
2352 enum todo_command valid =
2353 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2356 for (i = 0; i < todo_list->nr; i++)
2357 if (valid == todo_list->items[i].command)
2359 else if (valid == TODO_PICK)
2360 return error(_("cannot cherry-pick during a revert."));
2362 return error(_("cannot revert during a cherry-pick."));
2365 if (is_rebase_i(opts)) {
2366 struct todo_list done = TODO_LIST_INIT;
2368 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2369 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2370 todo_list->done_nr = count_commands(&done);
2372 todo_list->done_nr = 0;
2374 todo_list->total_nr = todo_list->done_nr
2375 + count_commands(todo_list);
2376 todo_list_release(&done);
2378 todo_list_write_total_nr(todo_list);
2384 static int git_config_string_dup(char **dest,
2385 const char *var, const char *value)
2388 return config_error_nonbool(var);
2390 *dest = xstrdup(value);
2394 static int populate_opts_cb(const char *key, const char *value, void *data)
2396 struct replay_opts *opts = data;
2401 else if (!strcmp(key, "options.no-commit"))
2402 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2403 else if (!strcmp(key, "options.edit"))
2404 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2405 else if (!strcmp(key, "options.allow-empty"))
2407 git_config_bool_or_int(key, value, &error_flag);
2408 else if (!strcmp(key, "options.allow-empty-message"))
2409 opts->allow_empty_message =
2410 git_config_bool_or_int(key, value, &error_flag);
2411 else if (!strcmp(key, "options.keep-redundant-commits"))
2412 opts->keep_redundant_commits =
2413 git_config_bool_or_int(key, value, &error_flag);
2414 else if (!strcmp(key, "options.signoff"))
2415 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2416 else if (!strcmp(key, "options.record-origin"))
2417 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2418 else if (!strcmp(key, "options.allow-ff"))
2419 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2420 else if (!strcmp(key, "options.mainline"))
2421 opts->mainline = git_config_int(key, value);
2422 else if (!strcmp(key, "options.strategy"))
2423 git_config_string_dup(&opts->strategy, key, value);
2424 else if (!strcmp(key, "options.gpg-sign"))
2425 git_config_string_dup(&opts->gpg_sign, key, value);
2426 else if (!strcmp(key, "options.strategy-option")) {
2427 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2428 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2429 } else if (!strcmp(key, "options.allow-rerere-auto"))
2430 opts->allow_rerere_auto =
2431 git_config_bool_or_int(key, value, &error_flag) ?
2432 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2433 else if (!strcmp(key, "options.default-msg-cleanup")) {
2434 opts->explicit_cleanup = 1;
2435 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2437 return error(_("invalid key: %s"), key);
2440 return error(_("invalid value for %s: %s"), key, value);
2445 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2448 char *strategy_opts_string = raw_opts;
2450 if (*strategy_opts_string == ' ')
2451 strategy_opts_string++;
2453 opts->xopts_nr = split_cmdline(strategy_opts_string,
2454 (const char ***)&opts->xopts);
2455 for (i = 0; i < opts->xopts_nr; i++) {
2456 const char *arg = opts->xopts[i];
2458 skip_prefix(arg, "--", &arg);
2459 opts->xopts[i] = xstrdup(arg);
2463 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2466 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2468 opts->strategy = strbuf_detach(buf, NULL);
2469 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2472 parse_strategy_opts(opts, buf->buf);
2475 static int read_populate_opts(struct replay_opts *opts)
2477 if (is_rebase_i(opts)) {
2478 struct strbuf buf = STRBUF_INIT;
2481 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2482 READ_ONELINER_SKIP_IF_EMPTY)) {
2483 if (!starts_with(buf.buf, "-S"))
2486 free(opts->gpg_sign);
2487 opts->gpg_sign = xstrdup(buf.buf + 2);
2492 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2493 READ_ONELINER_SKIP_IF_EMPTY)) {
2494 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2495 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2496 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2497 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2501 if (file_exists(rebase_path_verbose()))
2504 if (file_exists(rebase_path_quiet()))
2507 if (file_exists(rebase_path_signoff())) {
2512 if (file_exists(rebase_path_reschedule_failed_exec()))
2513 opts->reschedule_failed_exec = 1;
2515 if (file_exists(rebase_path_drop_redundant_commits()))
2516 opts->drop_redundant_commits = 1;
2518 if (file_exists(rebase_path_keep_redundant_commits()))
2519 opts->keep_redundant_commits = 1;
2521 read_strategy_opts(opts, &buf);
2524 if (read_oneliner(&opts->current_fixups,
2525 rebase_path_current_fixups(),
2526 READ_ONELINER_SKIP_IF_EMPTY)) {
2527 const char *p = opts->current_fixups.buf;
2528 opts->current_fixup_count = 1;
2529 while ((p = strchr(p, '\n'))) {
2530 opts->current_fixup_count++;
2535 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2536 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0) {
2537 ret = error(_("unusable squash-onto"));
2540 opts->have_squash_onto = 1;
2544 strbuf_release(&buf);
2548 if (!file_exists(git_path_opts_file()))
2551 * The function git_parse_source(), called from git_config_from_file(),
2552 * may die() in case of a syntactically incorrect file. We do not care
2553 * about this case, though, because we wrote that file ourselves, so we
2554 * are pretty certain that it is syntactically correct.
2556 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2557 return error(_("malformed options sheet: '%s'"),
2558 git_path_opts_file());
2562 static void write_strategy_opts(struct replay_opts *opts)
2565 struct strbuf buf = STRBUF_INIT;
2567 for (i = 0; i < opts->xopts_nr; ++i)
2568 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2570 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2571 strbuf_release(&buf);
2574 int write_basic_state(struct replay_opts *opts, const char *head_name,
2575 struct commit *onto, const char *orig_head)
2578 write_file(rebase_path_head_name(), "%s\n", head_name);
2580 write_file(rebase_path_onto(), "%s\n",
2581 oid_to_hex(&onto->object.oid));
2583 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2586 write_file(rebase_path_quiet(), "%s", "");
2588 write_file(rebase_path_verbose(), "%s", "");
2590 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2591 if (opts->xopts_nr > 0)
2592 write_strategy_opts(opts);
2594 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2595 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2596 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2597 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2600 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2602 write_file(rebase_path_signoff(), "--signoff\n");
2603 if (opts->drop_redundant_commits)
2604 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2605 if (opts->keep_redundant_commits)
2606 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2607 if (opts->reschedule_failed_exec)
2608 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2613 static int walk_revs_populate_todo(struct todo_list *todo_list,
2614 struct replay_opts *opts)
2616 enum todo_command command = opts->action == REPLAY_PICK ?
2617 TODO_PICK : TODO_REVERT;
2618 const char *command_string = todo_command_info[command].str;
2619 const char *encoding;
2620 struct commit *commit;
2622 if (prepare_revs(opts))
2625 encoding = get_log_output_encoding();
2627 while ((commit = get_revision(opts->revs))) {
2628 struct todo_item *item = append_new_todo(todo_list);
2629 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2630 const char *subject;
2633 item->command = command;
2634 item->commit = commit;
2635 item->arg_offset = 0;
2637 item->offset_in_buf = todo_list->buf.len;
2638 subject_len = find_commit_subject(commit_buffer, &subject);
2639 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2640 short_commit_name(commit), subject_len, subject);
2641 unuse_commit_buffer(commit, commit_buffer);
2645 return error(_("empty commit set passed"));
2650 static int create_seq_dir(struct repository *r)
2652 enum replay_action action;
2653 const char *in_progress_error = NULL;
2654 const char *in_progress_advice = NULL;
2655 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2656 file_exists(git_path_cherry_pick_head(r));
2658 if (!sequencer_get_last_command(r, &action)) {
2661 in_progress_error = _("revert is already in progress");
2662 in_progress_advice =
2663 _("try \"git revert (--continue | %s--abort | --quit)\"");
2666 in_progress_error = _("cherry-pick is already in progress");
2667 in_progress_advice =
2668 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2671 BUG("unexpected action in create_seq_dir");
2674 if (in_progress_error) {
2675 error("%s", in_progress_error);
2676 if (advice_sequencer_in_use)
2677 advise(in_progress_advice,
2678 advise_skip ? "--skip | " : "");
2681 if (mkdir(git_path_seq_dir(), 0777) < 0)
2682 return error_errno(_("could not create sequencer directory '%s'"),
2683 git_path_seq_dir());
2688 static int save_head(const char *head)
2690 struct lock_file head_lock = LOCK_INIT;
2691 struct strbuf buf = STRBUF_INIT;
2695 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2697 return error_errno(_("could not lock HEAD"));
2698 strbuf_addf(&buf, "%s\n", head);
2699 written = write_in_full(fd, buf.buf, buf.len);
2700 strbuf_release(&buf);
2702 error_errno(_("could not write to '%s'"), git_path_head_file());
2703 rollback_lock_file(&head_lock);
2706 if (commit_lock_file(&head_lock) < 0)
2707 return error(_("failed to finalize '%s'"), git_path_head_file());
2711 static int rollback_is_safe(void)
2713 struct strbuf sb = STRBUF_INIT;
2714 struct object_id expected_head, actual_head;
2716 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2718 if (get_oid_hex(sb.buf, &expected_head)) {
2719 strbuf_release(&sb);
2720 die(_("could not parse %s"), git_path_abort_safety_file());
2722 strbuf_release(&sb);
2724 else if (errno == ENOENT)
2725 oidclr(&expected_head);
2727 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2729 if (get_oid("HEAD", &actual_head))
2730 oidclr(&actual_head);
2732 return oideq(&actual_head, &expected_head);
2735 static int reset_merge(const struct object_id *oid)
2738 struct argv_array argv = ARGV_ARRAY_INIT;
2740 argv_array_pushl(&argv, "reset", "--merge", NULL);
2742 if (!is_null_oid(oid))
2743 argv_array_push(&argv, oid_to_hex(oid));
2745 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2746 argv_array_clear(&argv);
2751 static int rollback_single_pick(struct repository *r)
2753 struct object_id head_oid;
2755 if (!file_exists(git_path_cherry_pick_head(r)) &&
2756 !file_exists(git_path_revert_head(r)))
2757 return error(_("no cherry-pick or revert in progress"));
2758 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2759 return error(_("cannot resolve HEAD"));
2760 if (is_null_oid(&head_oid))
2761 return error(_("cannot abort from a branch yet to be born"));
2762 return reset_merge(&head_oid);
2765 static int skip_single_pick(void)
2767 struct object_id head;
2769 if (read_ref_full("HEAD", 0, &head, NULL))
2770 return error(_("cannot resolve HEAD"));
2771 return reset_merge(&head);
2774 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2777 struct object_id oid;
2778 struct strbuf buf = STRBUF_INIT;
2781 f = fopen(git_path_head_file(), "r");
2782 if (!f && errno == ENOENT) {
2784 * There is no multiple-cherry-pick in progress.
2785 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2786 * a single-cherry-pick in progress, abort that.
2788 return rollback_single_pick(r);
2791 return error_errno(_("cannot open '%s'"), git_path_head_file());
2792 if (strbuf_getline_lf(&buf, f)) {
2793 error(_("cannot read '%s': %s"), git_path_head_file(),
2794 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2799 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2800 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2801 git_path_head_file());
2804 if (is_null_oid(&oid)) {
2805 error(_("cannot abort from a branch yet to be born"));
2809 if (!rollback_is_safe()) {
2810 /* Do not error, just do not rollback */
2811 warning(_("You seem to have moved HEAD. "
2812 "Not rewinding, check your HEAD!"));
2814 if (reset_merge(&oid))
2816 strbuf_release(&buf);
2817 return sequencer_remove_state(opts);
2819 strbuf_release(&buf);
2823 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2825 enum replay_action action = -1;
2826 sequencer_get_last_command(r, &action);
2829 * Check whether the subcommand requested to skip the commit is actually
2830 * in progress and that it's safe to skip the commit.
2832 * opts->action tells us which subcommand requested to skip the commit.
2833 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2834 * action is in progress and we can skip the commit.
2836 * Otherwise we check that the last instruction was related to the
2837 * particular subcommand we're trying to execute and barf if that's not
2840 * Finally we check that the rollback is "safe", i.e., has the HEAD
2841 * moved? In this case, it doesn't make sense to "reset the merge" and
2842 * "skip the commit" as the user already handled this by committing. But
2843 * we'd not want to barf here, instead give advice on how to proceed. We
2844 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2845 * it gets removed when the user commits, so if it still exists we're
2846 * sure the user can't have committed before.
2848 switch (opts->action) {
2850 if (!file_exists(git_path_revert_head(r))) {
2851 if (action != REPLAY_REVERT)
2852 return error(_("no revert in progress"));
2853 if (!rollback_is_safe())
2858 if (!file_exists(git_path_cherry_pick_head(r))) {
2859 if (action != REPLAY_PICK)
2860 return error(_("no cherry-pick in progress"));
2861 if (!rollback_is_safe())
2866 BUG("unexpected action in sequencer_skip");
2869 if (skip_single_pick())
2870 return error(_("failed to skip the commit"));
2871 if (!is_directory(git_path_seq_dir()))
2874 return sequencer_continue(r, opts);
2877 error(_("there is nothing to skip"));
2879 if (advice_resolve_conflict) {
2880 advise(_("have you committed already?\n"
2881 "try \"git %s --continue\""),
2882 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2887 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2889 struct lock_file todo_lock = LOCK_INIT;
2890 const char *todo_path = get_todo_path(opts);
2891 int next = todo_list->current, offset, fd;
2894 * rebase -i writes "git-rebase-todo" without the currently executing
2895 * command, appending it to "done" instead.
2897 if (is_rebase_i(opts))
2900 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2902 return error_errno(_("could not lock '%s'"), todo_path);
2903 offset = get_item_line_offset(todo_list, next);
2904 if (write_in_full(fd, todo_list->buf.buf + offset,
2905 todo_list->buf.len - offset) < 0)
2906 return error_errno(_("could not write to '%s'"), todo_path);
2907 if (commit_lock_file(&todo_lock) < 0)
2908 return error(_("failed to finalize '%s'"), todo_path);
2910 if (is_rebase_i(opts) && next > 0) {
2911 const char *done = rebase_path_done();
2912 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2917 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2918 get_item_line_length(todo_list, next - 1))
2920 ret = error_errno(_("could not write to '%s'"), done);
2922 ret = error_errno(_("failed to finalize '%s'"), done);
2928 static int save_opts(struct replay_opts *opts)
2930 const char *opts_file = git_path_opts_file();
2933 if (opts->no_commit)
2934 res |= git_config_set_in_file_gently(opts_file,
2935 "options.no-commit", "true");
2937 res |= git_config_set_in_file_gently(opts_file,
2938 "options.edit", "true");
2939 if (opts->allow_empty)
2940 res |= git_config_set_in_file_gently(opts_file,
2941 "options.allow-empty", "true");
2942 if (opts->allow_empty_message)
2943 res |= git_config_set_in_file_gently(opts_file,
2944 "options.allow-empty-message", "true");
2945 if (opts->keep_redundant_commits)
2946 res |= git_config_set_in_file_gently(opts_file,
2947 "options.keep-redundant-commits", "true");
2949 res |= git_config_set_in_file_gently(opts_file,
2950 "options.signoff", "true");
2951 if (opts->record_origin)
2952 res |= git_config_set_in_file_gently(opts_file,
2953 "options.record-origin", "true");
2955 res |= git_config_set_in_file_gently(opts_file,
2956 "options.allow-ff", "true");
2957 if (opts->mainline) {
2958 struct strbuf buf = STRBUF_INIT;
2959 strbuf_addf(&buf, "%d", opts->mainline);
2960 res |= git_config_set_in_file_gently(opts_file,
2961 "options.mainline", buf.buf);
2962 strbuf_release(&buf);
2965 res |= git_config_set_in_file_gently(opts_file,
2966 "options.strategy", opts->strategy);
2968 res |= git_config_set_in_file_gently(opts_file,
2969 "options.gpg-sign", opts->gpg_sign);
2972 for (i = 0; i < opts->xopts_nr; i++)
2973 res |= git_config_set_multivar_in_file_gently(opts_file,
2974 "options.strategy-option",
2975 opts->xopts[i], "^$", 0);
2977 if (opts->allow_rerere_auto)
2978 res |= git_config_set_in_file_gently(opts_file,
2979 "options.allow-rerere-auto",
2980 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2983 if (opts->explicit_cleanup)
2984 res |= git_config_set_in_file_gently(opts_file,
2985 "options.default-msg-cleanup",
2986 describe_cleanup_mode(opts->default_msg_cleanup));
2990 static int make_patch(struct repository *r,
2991 struct commit *commit,
2992 struct replay_opts *opts)
2994 struct strbuf buf = STRBUF_INIT;
2995 struct rev_info log_tree_opt;
2996 const char *subject, *p;
2999 p = short_commit_name(commit);
3000 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3002 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
3003 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
3004 res |= error(_("could not update %s"), "REBASE_HEAD");
3006 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3007 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3008 repo_init_revisions(r, &log_tree_opt, NULL);
3009 log_tree_opt.abbrev = 0;
3010 log_tree_opt.diff = 1;
3011 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3012 log_tree_opt.disable_stdin = 1;
3013 log_tree_opt.no_commit_id = 1;
3014 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3015 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3016 if (!log_tree_opt.diffopt.file)
3017 res |= error_errno(_("could not open '%s'"), buf.buf);
3019 res |= log_tree_commit(&log_tree_opt, commit);
3020 fclose(log_tree_opt.diffopt.file);
3024 strbuf_addf(&buf, "%s/message", get_dir(opts));
3025 if (!file_exists(buf.buf)) {
3026 const char *encoding = get_commit_output_encoding();
3027 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3028 find_commit_subject(commit_buffer, &subject);
3029 res |= write_message(subject, strlen(subject), buf.buf, 1);
3030 unuse_commit_buffer(commit, commit_buffer);
3032 strbuf_release(&buf);
3037 static int intend_to_amend(void)
3039 struct object_id head;
3042 if (get_oid("HEAD", &head))
3043 return error(_("cannot read HEAD"));
3045 p = oid_to_hex(&head);
3046 return write_message(p, strlen(p), rebase_path_amend(), 1);
3049 static int error_with_patch(struct repository *r,
3050 struct commit *commit,
3051 const char *subject, int subject_len,
3052 struct replay_opts *opts,
3053 int exit_code, int to_amend)
3056 if (make_patch(r, commit, opts))
3058 } else if (copy_file(rebase_path_message(),
3059 git_path_merge_msg(r), 0666))
3060 return error(_("unable to copy '%s' to '%s'"),
3061 git_path_merge_msg(r), rebase_path_message());
3064 if (intend_to_amend())
3068 _("You can amend the commit now, with\n"
3070 " git commit --amend %s\n"
3072 "Once you are satisfied with your changes, run\n"
3074 " git rebase --continue\n"),
3075 gpg_sign_opt_quoted(opts));
3076 } else if (exit_code) {
3078 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3079 short_commit_name(commit), subject_len, subject);
3082 * We don't have the hash of the parent so
3083 * just print the line from the todo file.
3085 fprintf_ln(stderr, _("Could not merge %.*s"),
3086 subject_len, subject);
3092 static int error_failed_squash(struct repository *r,
3093 struct commit *commit,
3094 struct replay_opts *opts,
3096 const char *subject)
3098 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3099 return error(_("could not copy '%s' to '%s'"),
3100 rebase_path_squash_msg(), rebase_path_message());
3101 unlink(git_path_merge_msg(r));
3102 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3103 return error(_("could not copy '%s' to '%s'"),
3104 rebase_path_message(),
3105 git_path_merge_msg(r));
3106 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3109 static int do_exec(struct repository *r, const char *command_line)
3111 struct argv_array child_env = ARGV_ARRAY_INIT;
3112 const char *child_argv[] = { NULL, NULL };
3115 fprintf(stderr, "Executing: %s\n", command_line);
3116 child_argv[0] = command_line;
3117 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3118 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3119 absolute_path(get_git_work_tree()));
3120 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3123 /* force re-reading of the cache */
3124 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3125 return error(_("could not read index"));
3127 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3130 warning(_("execution failed: %s\n%s"
3131 "You can fix the problem, and then run\n"
3133 " git rebase --continue\n"
3136 dirty ? N_("and made changes to the index and/or the "
3137 "working tree\n") : "");
3139 /* command not found */
3142 warning(_("execution succeeded: %s\nbut "
3143 "left changes to the index and/or the working tree\n"
3144 "Commit or stash your changes, and then run\n"
3146 " git rebase --continue\n"
3147 "\n"), command_line);
3151 argv_array_clear(&child_env);
3156 static int safe_append(const char *filename, const char *fmt, ...)
3159 struct lock_file lock = LOCK_INIT;
3160 int fd = hold_lock_file_for_update(&lock, filename,
3161 LOCK_REPORT_ON_ERROR);
3162 struct strbuf buf = STRBUF_INIT;
3167 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3168 error_errno(_("could not read '%s'"), filename);
3169 rollback_lock_file(&lock);
3172 strbuf_complete(&buf, '\n');
3174 strbuf_vaddf(&buf, fmt, ap);
3177 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3178 error_errno(_("could not write to '%s'"), filename);
3179 strbuf_release(&buf);
3180 rollback_lock_file(&lock);
3183 if (commit_lock_file(&lock) < 0) {
3184 strbuf_release(&buf);
3185 rollback_lock_file(&lock);
3186 return error(_("failed to finalize '%s'"), filename);
3189 strbuf_release(&buf);
3193 static int do_label(struct repository *r, const char *name, int len)
3195 struct ref_store *refs = get_main_ref_store(r);
3196 struct ref_transaction *transaction;
3197 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3198 struct strbuf msg = STRBUF_INIT;
3200 struct object_id head_oid;
3202 if (len == 1 && *name == '#')
3203 return error(_("illegal label name: '%.*s'"), len, name);
3205 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3206 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3208 transaction = ref_store_transaction_begin(refs, &err);
3210 error("%s", err.buf);
3212 } else if (get_oid("HEAD", &head_oid)) {
3213 error(_("could not read HEAD"));
3215 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3216 NULL, 0, msg.buf, &err) < 0 ||
3217 ref_transaction_commit(transaction, &err)) {
3218 error("%s", err.buf);
3221 ref_transaction_free(transaction);
3222 strbuf_release(&err);
3223 strbuf_release(&msg);
3226 ret = safe_append(rebase_path_refs_to_delete(),
3227 "%s\n", ref_name.buf);
3228 strbuf_release(&ref_name);
3233 static const char *reflog_message(struct replay_opts *opts,
3234 const char *sub_action, const char *fmt, ...);
3236 static int do_reset(struct repository *r,
3237 const char *name, int len,
3238 struct replay_opts *opts)
3240 struct strbuf ref_name = STRBUF_INIT;
3241 struct object_id oid;
3242 struct lock_file lock = LOCK_INIT;
3243 struct tree_desc desc;
3245 struct unpack_trees_options unpack_tree_opts;
3248 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3251 if (len == 10 && !strncmp("[new root]", name, len)) {
3252 if (!opts->have_squash_onto) {
3254 if (commit_tree("", 0, the_hash_algo->empty_tree,
3255 NULL, &opts->squash_onto,
3257 return error(_("writing fake root commit"));
3258 opts->have_squash_onto = 1;
3259 hex = oid_to_hex(&opts->squash_onto);
3260 if (write_message(hex, strlen(hex),
3261 rebase_path_squash_onto(), 0))
3262 return error(_("writing squash-onto"));
3264 oidcpy(&oid, &opts->squash_onto);
3268 /* Determine the length of the label */
3269 for (i = 0; i < len; i++)
3270 if (isspace(name[i]))
3274 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3275 if (get_oid(ref_name.buf, &oid) &&
3276 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3277 error(_("could not read '%s'"), ref_name.buf);
3278 rollback_lock_file(&lock);
3279 strbuf_release(&ref_name);
3284 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3285 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3286 unpack_tree_opts.head_idx = 1;
3287 unpack_tree_opts.src_index = r->index;
3288 unpack_tree_opts.dst_index = r->index;
3289 unpack_tree_opts.fn = oneway_merge;
3290 unpack_tree_opts.merge = 1;
3291 unpack_tree_opts.update = 1;
3293 if (repo_read_index_unmerged(r)) {
3294 rollback_lock_file(&lock);
3295 strbuf_release(&ref_name);
3296 return error_resolve_conflict(_(action_name(opts)));
3299 if (!fill_tree_descriptor(r, &desc, &oid)) {
3300 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3301 rollback_lock_file(&lock);
3302 free((void *)desc.buffer);
3303 strbuf_release(&ref_name);
3307 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3308 rollback_lock_file(&lock);
3309 free((void *)desc.buffer);
3310 strbuf_release(&ref_name);
3314 tree = parse_tree_indirect(&oid);
3315 prime_cache_tree(r, r->index, tree);
3317 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3318 ret = error(_("could not write index"));
3319 free((void *)desc.buffer);
3322 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3323 len, name), "HEAD", &oid,
3324 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3326 strbuf_release(&ref_name);
3330 static struct commit *lookup_label(const char *label, int len,
3333 struct commit *commit;
3336 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3337 commit = lookup_commit_reference_by_name(buf->buf);
3339 /* fall back to non-rewritten ref or commit */
3340 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3341 commit = lookup_commit_reference_by_name(buf->buf);
3345 error(_("could not resolve '%s'"), buf->buf);
3350 static int do_merge(struct repository *r,
3351 struct commit *commit,
3352 const char *arg, int arg_len,
3353 int flags, struct replay_opts *opts)
3355 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3356 EDIT_MSG | VERIFY_MSG : 0;
3357 struct strbuf ref_name = STRBUF_INIT;
3358 struct commit *head_commit, *merge_commit, *i;
3359 struct commit_list *bases, *j, *reversed = NULL;
3360 struct commit_list *to_merge = NULL, **tail = &to_merge;
3361 const char *strategy = !opts->xopts_nr &&
3362 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3363 NULL : opts->strategy;
3364 struct merge_options o;
3365 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3366 static struct lock_file lock;
3369 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3374 head_commit = lookup_commit_reference_by_name("HEAD");
3376 ret = error(_("cannot merge without a current revision"));
3381 * For octopus merges, the arg starts with the list of revisions to be
3382 * merged. The list is optionally followed by '#' and the oneline.
3384 merge_arg_len = oneline_offset = arg_len;
3385 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3388 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3389 p += 1 + strspn(p + 1, " \t\n");
3390 oneline_offset = p - arg;
3393 k = strcspn(p, " \t\n");
3396 merge_commit = lookup_label(p, k, &ref_name);
3397 if (!merge_commit) {
3398 ret = error(_("unable to parse '%.*s'"), k, p);
3401 tail = &commit_list_insert(merge_commit, tail)->next;
3403 merge_arg_len = p - arg;
3407 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3411 if (opts->have_squash_onto &&
3412 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3414 * When the user tells us to "merge" something into a
3415 * "[new root]", let's simply fast-forward to the merge head.
3417 rollback_lock_file(&lock);
3419 ret = error(_("octopus merge cannot be executed on "
3420 "top of a [new root]"));
3422 ret = fast_forward_to(r, &to_merge->item->object.oid,
3423 &head_commit->object.oid, 0,
3429 const char *encoding = get_commit_output_encoding();
3430 const char *message = logmsg_reencode(commit, NULL, encoding);
3435 ret = error(_("could not get commit message of '%s'"),
3436 oid_to_hex(&commit->object.oid));
3439 write_author_script(message);
3440 find_commit_subject(message, &body);
3442 ret = write_message(body, len, git_path_merge_msg(r), 0);
3443 unuse_commit_buffer(commit, message);
3445 error_errno(_("could not write '%s'"),
3446 git_path_merge_msg(r));
3450 struct strbuf buf = STRBUF_INIT;
3453 strbuf_addf(&buf, "author %s", git_author_info(0));
3454 write_author_script(buf.buf);
3457 if (oneline_offset < arg_len) {
3458 p = arg + oneline_offset;
3459 len = arg_len - oneline_offset;
3461 strbuf_addf(&buf, "Merge %s '%.*s'",
3462 to_merge->next ? "branches" : "branch",
3463 merge_arg_len, arg);
3468 ret = write_message(p, len, git_path_merge_msg(r), 0);
3469 strbuf_release(&buf);
3471 error_errno(_("could not write '%s'"),
3472 git_path_merge_msg(r));
3478 * If HEAD is not identical to the first parent of the original merge
3479 * commit, we cannot fast-forward.
3481 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3482 oideq(&commit->parents->item->object.oid,
3483 &head_commit->object.oid);
3486 * If any merge head is different from the original one, we cannot
3489 if (can_fast_forward) {
3490 struct commit_list *p = commit->parents->next;
3492 for (j = to_merge; j && p; j = j->next, p = p->next)
3493 if (!oideq(&j->item->object.oid,
3494 &p->item->object.oid)) {
3495 can_fast_forward = 0;
3499 * If the number of merge heads differs from the original merge
3500 * commit, we cannot fast-forward.
3503 can_fast_forward = 0;
3506 if (can_fast_forward) {
3507 rollback_lock_file(&lock);
3508 ret = fast_forward_to(r, &commit->object.oid,
3509 &head_commit->object.oid, 0, opts);
3510 if (flags & TODO_EDIT_MERGE_MSG) {
3511 run_commit_flags |= AMEND_MSG;
3512 goto fast_forward_edit;
3517 if (strategy || to_merge->next) {
3519 struct child_process cmd = CHILD_PROCESS_INIT;
3521 if (read_env_script(&cmd.env_array)) {
3522 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3524 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3529 argv_array_push(&cmd.args, "merge");
3530 argv_array_push(&cmd.args, "-s");
3532 argv_array_push(&cmd.args, "octopus");
3534 argv_array_push(&cmd.args, strategy);
3535 for (k = 0; k < opts->xopts_nr; k++)
3536 argv_array_pushf(&cmd.args,
3537 "-X%s", opts->xopts[k]);
3539 argv_array_push(&cmd.args, "--no-edit");
3540 argv_array_push(&cmd.args, "--no-ff");
3541 argv_array_push(&cmd.args, "--no-log");
3542 argv_array_push(&cmd.args, "--no-stat");
3543 argv_array_push(&cmd.args, "-F");
3544 argv_array_push(&cmd.args, git_path_merge_msg(r));
3546 argv_array_push(&cmd.args, opts->gpg_sign);
3548 /* Add the tips to be merged */
3549 for (j = to_merge; j; j = j->next)
3550 argv_array_push(&cmd.args,
3551 oid_to_hex(&j->item->object.oid));
3553 strbuf_release(&ref_name);
3554 unlink(git_path_cherry_pick_head(r));
3555 rollback_lock_file(&lock);
3557 rollback_lock_file(&lock);
3558 ret = run_command(&cmd);
3560 /* force re-reading of the cache */
3561 if (!ret && (discard_index(r->index) < 0 ||
3562 repo_read_index(r) < 0))
3563 ret = error(_("could not read index"));
3567 merge_commit = to_merge->item;
3568 bases = get_merge_bases(head_commit, merge_commit);
3569 if (bases && oideq(&merge_commit->object.oid,
3570 &bases->item->object.oid)) {
3572 /* skip merging an ancestor of HEAD */
3576 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3577 git_path_merge_head(r), 0);
3578 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3580 for (j = bases; j; j = j->next)
3581 commit_list_insert(j->item, &reversed);
3582 free_commit_list(bases);
3585 init_merge_options(&o, r);
3587 o.branch2 = ref_name.buf;
3588 o.buffer_output = 2;
3590 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3592 fputs(o.obuf.buf, stdout);
3593 strbuf_release(&o.obuf);
3595 error(_("could not even attempt to merge '%.*s'"),
3596 merge_arg_len, arg);
3600 * The return value of merge_recursive() is 1 on clean, and 0 on
3603 * Let's reverse that, so that do_merge() returns 0 upon success and
3604 * 1 upon failed merge (keeping the return value -1 for the cases where
3605 * we will want to reschedule the `merge` command).
3609 if (r->index->cache_changed &&
3610 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3611 ret = error(_("merge: Unable to write new index file"));
3615 rollback_lock_file(&lock);
3617 repo_rerere(r, opts->allow_rerere_auto);
3620 * In case of problems, we now want to return a positive
3621 * value (a negative one would indicate that the `merge`
3622 * command needs to be rescheduled).
3625 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3629 strbuf_release(&ref_name);
3630 rollback_lock_file(&lock);
3631 free_commit_list(to_merge);
3635 static int is_final_fixup(struct todo_list *todo_list)
3637 int i = todo_list->current;
3639 if (!is_fixup(todo_list->items[i].command))
3642 while (++i < todo_list->nr)
3643 if (is_fixup(todo_list->items[i].command))
3645 else if (!is_noop(todo_list->items[i].command))
3650 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3654 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3655 if (!is_noop(todo_list->items[i].command))
3656 return todo_list->items[i].command;
3661 void create_autostash(struct repository *r, const char *path,
3662 const char *default_reflog_action)
3664 struct strbuf buf = STRBUF_INIT;
3665 struct lock_file lock_file = LOCK_INIT;
3668 fd = repo_hold_locked_index(r, &lock_file, 0);
3669 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
3671 repo_update_index_if_able(r, &lock_file);
3672 rollback_lock_file(&lock_file);
3674 if (has_unstaged_changes(r, 1) ||
3675 has_uncommitted_changes(r, 1)) {
3676 struct child_process stash = CHILD_PROCESS_INIT;
3677 struct object_id oid;
3679 argv_array_pushl(&stash.args,
3680 "stash", "create", "autostash", NULL);
3684 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
3685 die(_("Cannot autostash"));
3686 strbuf_trim_trailing_newline(&buf);
3687 if (get_oid(buf.buf, &oid))
3688 die(_("Unexpected stash response: '%s'"),
3691 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
3693 if (safe_create_leading_directories_const(path))
3694 die(_("Could not create directory for '%s'"),
3696 write_file(path, "%s", oid_to_hex(&oid));
3697 printf(_("Created autostash: %s\n"), buf.buf);
3698 if (reset_head(r, NULL, "reset --hard",
3699 NULL, RESET_HEAD_HARD, NULL, NULL,
3700 default_reflog_action) < 0)
3701 die(_("could not reset --hard"));
3703 if (discard_index(r->index) < 0 ||
3704 repo_read_index(r) < 0)
3705 die(_("could not read index"));
3707 strbuf_release(&buf);
3710 int apply_autostash(const char *path)
3712 struct strbuf stash_oid = STRBUF_INIT;
3713 struct child_process child = CHILD_PROCESS_INIT;
3716 if (!read_oneliner(&stash_oid, path,
3717 READ_ONELINER_SKIP_IF_EMPTY)) {
3718 strbuf_release(&stash_oid);
3721 strbuf_trim(&stash_oid);
3724 child.no_stdout = 1;
3725 child.no_stderr = 1;
3726 argv_array_push(&child.args, "stash");
3727 argv_array_push(&child.args, "apply");
3728 argv_array_push(&child.args, stash_oid.buf);
3729 if (!run_command(&child))
3730 fprintf(stderr, _("Applied autostash.\n"));
3732 struct child_process store = CHILD_PROCESS_INIT;
3735 argv_array_push(&store.args, "stash");
3736 argv_array_push(&store.args, "store");
3737 argv_array_push(&store.args, "-m");
3738 argv_array_push(&store.args, "autostash");
3739 argv_array_push(&store.args, "-q");
3740 argv_array_push(&store.args, stash_oid.buf);
3741 if (run_command(&store))
3742 ret = error(_("cannot store %s"), stash_oid.buf);
3745 _("Applying autostash resulted in conflicts.\n"
3746 "Your changes are safe in the stash.\n"
3747 "You can run \"git stash pop\" or"
3748 " \"git stash drop\" at any time.\n"));
3752 strbuf_release(&stash_oid);
3756 static const char *reflog_message(struct replay_opts *opts,
3757 const char *sub_action, const char *fmt, ...)
3760 static struct strbuf buf = STRBUF_INIT;
3764 strbuf_addstr(&buf, action_name(opts));
3766 strbuf_addf(&buf, " (%s)", sub_action);
3768 strbuf_addstr(&buf, ": ");
3769 strbuf_vaddf(&buf, fmt, ap);
3776 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3777 const char *commit, const char *action)
3779 struct child_process cmd = CHILD_PROCESS_INIT;
3784 argv_array_push(&cmd.args, "checkout");
3785 argv_array_push(&cmd.args, commit);
3786 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3789 ret = run_command(&cmd);
3791 ret = run_command_silent_on_success(&cmd);
3794 discard_index(r->index);
3799 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3800 const char *onto_name, const struct object_id *onto,
3801 const char *orig_head)
3803 struct object_id oid;
3804 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3806 if (get_oid(orig_head, &oid))
3807 return error(_("%s: not a valid OID"), orig_head);
3809 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3810 apply_autostash(rebase_path_autostash());
3811 sequencer_remove_state(opts);
3812 return error(_("could not detach HEAD"));
3815 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3818 static int stopped_at_head(struct repository *r)
3820 struct object_id head;
3821 struct commit *commit;
3822 struct commit_message message;
3824 if (get_oid("HEAD", &head) ||
3825 !(commit = lookup_commit(r, &head)) ||
3826 parse_commit(commit) || get_message(commit, &message))
3827 fprintf(stderr, _("Stopped at HEAD\n"));
3829 fprintf(stderr, _("Stopped at %s\n"), message.label);
3830 free_message(commit, &message);
3836 static const char rescheduled_advice[] =
3837 N_("Could not execute the todo command\n"
3841 "It has been rescheduled; To edit the command before continuing, please\n"
3842 "edit the todo list first:\n"
3844 " git rebase --edit-todo\n"
3845 " git rebase --continue\n");
3847 static int pick_commits(struct repository *r,
3848 struct todo_list *todo_list,
3849 struct replay_opts *opts)
3851 int res = 0, reschedule = 0;
3853 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3855 assert(!(opts->signoff || opts->no_commit ||
3856 opts->record_origin || opts->edit));
3857 if (read_and_refresh_cache(r, opts))
3860 while (todo_list->current < todo_list->nr) {
3861 struct todo_item *item = todo_list->items + todo_list->current;
3862 const char *arg = todo_item_get_arg(todo_list, item);
3865 if (save_todo(todo_list, opts))
3867 if (is_rebase_i(opts)) {
3868 if (item->command != TODO_COMMENT) {
3869 FILE *f = fopen(rebase_path_msgnum(), "w");
3871 todo_list->done_nr++;
3874 fprintf(f, "%d\n", todo_list->done_nr);
3878 fprintf(stderr, "Rebasing (%d/%d)%s",
3880 todo_list->total_nr,
3881 opts->verbose ? "\n" : "\r");
3883 unlink(rebase_path_message());
3884 unlink(rebase_path_author_script());
3885 unlink(rebase_path_stopped_sha());
3886 unlink(rebase_path_amend());
3887 unlink(git_path_merge_head(r));
3888 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3890 if (item->command == TODO_BREAK) {
3893 return stopped_at_head(r);
3896 if (item->command <= TODO_SQUASH) {
3897 if (is_rebase_i(opts))
3898 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3899 command_to_string(item->command), NULL),
3901 res = do_pick_commit(r, item->command, item->commit,
3902 opts, is_final_fixup(todo_list),
3904 if (is_rebase_i(opts) && res < 0) {
3906 advise(_(rescheduled_advice),
3907 get_item_line_length(todo_list,
3908 todo_list->current),
3909 get_item_line(todo_list,
3910 todo_list->current));
3911 todo_list->current--;
3912 if (save_todo(todo_list, opts))
3915 if (item->command == TODO_EDIT) {
3916 struct commit *commit = item->commit;
3921 _("Stopped at %s... %.*s\n"),
3922 short_commit_name(commit),
3923 item->arg_len, arg);
3925 return error_with_patch(r, commit,
3926 arg, item->arg_len, opts, res, !res);
3928 if (is_rebase_i(opts) && !res)
3929 record_in_rewritten(&item->commit->object.oid,
3930 peek_command(todo_list, 1));
3931 if (res && is_fixup(item->command)) {
3934 return error_failed_squash(r, item->commit, opts,
3935 item->arg_len, arg);
3936 } else if (res && is_rebase_i(opts) && item->commit) {
3938 struct object_id oid;
3941 * If we are rewording and have either
3942 * fast-forwarded already, or are about to
3943 * create a new root commit, we want to amend,
3944 * otherwise we do not.
3946 if (item->command == TODO_REWORD &&
3947 !get_oid("HEAD", &oid) &&
3948 (oideq(&item->commit->object.oid, &oid) ||
3949 (opts->have_squash_onto &&
3950 oideq(&opts->squash_onto, &oid))))
3953 return res | error_with_patch(r, item->commit,
3954 arg, item->arg_len, opts,
3957 } else if (item->command == TODO_EXEC) {
3958 char *end_of_arg = (char *)(arg + item->arg_len);
3959 int saved = *end_of_arg;
3964 res = do_exec(r, arg);
3965 *end_of_arg = saved;
3968 if (opts->reschedule_failed_exec)
3972 } else if (item->command == TODO_LABEL) {
3973 if ((res = do_label(r, arg, item->arg_len)))
3975 } else if (item->command == TODO_RESET) {
3976 if ((res = do_reset(r, arg, item->arg_len, opts)))
3978 } else if (item->command == TODO_MERGE) {
3979 if ((res = do_merge(r, item->commit,
3981 item->flags, opts)) < 0)
3983 else if (item->commit)
3984 record_in_rewritten(&item->commit->object.oid,
3985 peek_command(todo_list, 1));
3987 /* failed with merge conflicts */
3988 return error_with_patch(r, item->commit,
3991 } else if (!is_noop(item->command))
3992 return error(_("unknown command %d"), item->command);
3995 advise(_(rescheduled_advice),
3996 get_item_line_length(todo_list,
3997 todo_list->current),
3998 get_item_line(todo_list, todo_list->current));
3999 todo_list->current--;
4000 if (save_todo(todo_list, opts))
4003 return error_with_patch(r,
4007 } else if (is_rebase_i(opts) && check_todo && !res) {
4010 if (stat(get_todo_path(opts), &st)) {
4011 res = error_errno(_("could not stat '%s'"),
4012 get_todo_path(opts));
4013 } else if (match_stat_data(&todo_list->stat, &st)) {
4014 /* Reread the todo file if it has changed. */
4015 todo_list_release(todo_list);
4016 if (read_populate_todo(r, todo_list, opts))
4017 res = -1; /* message was printed */
4018 /* `current` will be incremented below */
4019 todo_list->current = -1;
4023 todo_list->current++;
4028 if (is_rebase_i(opts)) {
4029 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4032 /* Stopped in the middle, as planned? */
4033 if (todo_list->current < todo_list->nr)
4036 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4037 starts_with(head_ref.buf, "refs/")) {
4039 struct object_id head, orig;
4042 if (get_oid("HEAD", &head)) {
4043 res = error(_("cannot read HEAD"));
4045 strbuf_release(&head_ref);
4046 strbuf_release(&buf);
4049 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4050 get_oid_hex(buf.buf, &orig)) {
4051 res = error(_("could not read orig-head"));
4052 goto cleanup_head_ref;
4055 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4056 res = error(_("could not read 'onto'"));
4057 goto cleanup_head_ref;
4059 msg = reflog_message(opts, "finish", "%s onto %s",
4060 head_ref.buf, buf.buf);
4061 if (update_ref(msg, head_ref.buf, &head, &orig,
4062 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4063 res = error(_("could not update %s"),
4065 goto cleanup_head_ref;
4067 msg = reflog_message(opts, "finish", "returning to %s",
4069 if (create_symref("HEAD", head_ref.buf, msg)) {
4070 res = error(_("could not update HEAD to %s"),
4072 goto cleanup_head_ref;
4077 if (opts->verbose) {
4078 struct rev_info log_tree_opt;
4079 struct object_id orig, head;
4081 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4082 repo_init_revisions(r, &log_tree_opt, NULL);
4083 log_tree_opt.diff = 1;
4084 log_tree_opt.diffopt.output_format =
4085 DIFF_FORMAT_DIFFSTAT;
4086 log_tree_opt.disable_stdin = 1;
4088 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4089 !get_oid(buf.buf, &orig) &&
4090 !get_oid("HEAD", &head)) {
4091 diff_tree_oid(&orig, &head, "",
4092 &log_tree_opt.diffopt);
4093 log_tree_diff_flush(&log_tree_opt);
4096 flush_rewritten_pending();
4097 if (!stat(rebase_path_rewritten_list(), &st) &&
4099 struct child_process child = CHILD_PROCESS_INIT;
4100 const char *post_rewrite_hook =
4101 find_hook("post-rewrite");
4103 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4105 argv_array_push(&child.args, "notes");
4106 argv_array_push(&child.args, "copy");
4107 argv_array_push(&child.args, "--for-rewrite=rebase");
4108 /* we don't care if this copying failed */
4109 run_command(&child);
4111 if (post_rewrite_hook) {
4112 struct child_process hook = CHILD_PROCESS_INIT;
4114 hook.in = open(rebase_path_rewritten_list(),
4116 hook.stdout_to_stderr = 1;
4117 hook.trace2_hook_name = "post-rewrite";
4118 argv_array_push(&hook.args, post_rewrite_hook);
4119 argv_array_push(&hook.args, "rebase");
4120 /* we don't care if this hook failed */
4124 apply_autostash(rebase_path_autostash());
4130 "Successfully rebased and updated %s.\n",
4134 strbuf_release(&buf);
4135 strbuf_release(&head_ref);
4139 * Sequence of picks finished successfully; cleanup by
4140 * removing the .git/sequencer directory
4142 return sequencer_remove_state(opts);
4145 static int continue_single_pick(struct repository *r)
4147 const char *argv[] = { "commit", NULL };
4149 if (!file_exists(git_path_cherry_pick_head(r)) &&
4150 !file_exists(git_path_revert_head(r)))
4151 return error(_("no cherry-pick or revert in progress"));
4152 return run_command_v_opt(argv, RUN_GIT_CMD);
4155 static int commit_staged_changes(struct repository *r,
4156 struct replay_opts *opts,
4157 struct todo_list *todo_list)
4159 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4160 unsigned int final_fixup = 0, is_clean;
4162 if (has_unstaged_changes(r, 1))
4163 return error(_("cannot rebase: You have unstaged changes."));
4165 is_clean = !has_uncommitted_changes(r, 0);
4167 if (file_exists(rebase_path_amend())) {
4168 struct strbuf rev = STRBUF_INIT;
4169 struct object_id head, to_amend;
4171 if (get_oid("HEAD", &head))
4172 return error(_("cannot amend non-existing commit"));
4173 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4174 return error(_("invalid file: '%s'"), rebase_path_amend());
4175 if (get_oid_hex(rev.buf, &to_amend))
4176 return error(_("invalid contents: '%s'"),
4177 rebase_path_amend());
4178 if (!is_clean && !oideq(&head, &to_amend))
4179 return error(_("\nYou have uncommitted changes in your "
4180 "working tree. Please, commit them\n"
4181 "first and then run 'git rebase "
4182 "--continue' again."));
4184 * When skipping a failed fixup/squash, we need to edit the
4185 * commit message, the current fixup list and count, and if it
4186 * was the last fixup/squash in the chain, we need to clean up
4187 * the commit message and if there was a squash, let the user
4190 if (!is_clean || !opts->current_fixup_count)
4191 ; /* this is not the final fixup */
4192 else if (!oideq(&head, &to_amend) ||
4193 !file_exists(rebase_path_stopped_sha())) {
4194 /* was a final fixup or squash done manually? */
4195 if (!is_fixup(peek_command(todo_list, 0))) {
4196 unlink(rebase_path_fixup_msg());
4197 unlink(rebase_path_squash_msg());
4198 unlink(rebase_path_current_fixups());
4199 strbuf_reset(&opts->current_fixups);
4200 opts->current_fixup_count = 0;
4203 /* we are in a fixup/squash chain */
4204 const char *p = opts->current_fixups.buf;
4205 int len = opts->current_fixups.len;
4207 opts->current_fixup_count--;
4209 BUG("Incorrect current_fixups:\n%s", p);
4210 while (len && p[len - 1] != '\n')
4212 strbuf_setlen(&opts->current_fixups, len);
4213 if (write_message(p, len, rebase_path_current_fixups(),
4215 return error(_("could not write file: '%s'"),
4216 rebase_path_current_fixups());
4219 * If a fixup/squash in a fixup/squash chain failed, the
4220 * commit message is already correct, no need to commit
4223 * Only if it is the final command in the fixup/squash
4224 * chain, and only if the chain is longer than a single
4225 * fixup/squash command (which was just skipped), do we
4226 * actually need to re-commit with a cleaned up commit
4229 if (opts->current_fixup_count > 0 &&
4230 !is_fixup(peek_command(todo_list, 0))) {
4233 * If there was not a single "squash" in the
4234 * chain, we only need to clean up the commit
4235 * message, no need to bother the user with
4236 * opening the commit message in the editor.
4238 if (!starts_with(p, "squash ") &&
4239 !strstr(p, "\nsquash "))
4240 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4241 } else if (is_fixup(peek_command(todo_list, 0))) {
4243 * We need to update the squash message to skip
4244 * the latest commit message.
4246 struct commit *commit;
4247 const char *path = rebase_path_squash_msg();
4248 const char *encoding = get_commit_output_encoding();
4250 if (parse_head(r, &commit) ||
4251 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4252 write_message(p, strlen(p), path, 0)) {
4253 unuse_commit_buffer(commit, p);
4254 return error(_("could not write file: "
4257 unuse_commit_buffer(commit, p);
4261 strbuf_release(&rev);
4266 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4268 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4269 return error(_("could not remove CHERRY_PICK_HEAD"));
4274 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4276 return error(_("could not commit staged changes."));
4277 unlink(rebase_path_amend());
4278 unlink(git_path_merge_head(r));
4280 unlink(rebase_path_fixup_msg());
4281 unlink(rebase_path_squash_msg());
4283 if (opts->current_fixup_count > 0) {
4285 * Whether final fixup or not, we just cleaned up the commit
4288 unlink(rebase_path_current_fixups());
4289 strbuf_reset(&opts->current_fixups);
4290 opts->current_fixup_count = 0;
4295 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4297 struct todo_list todo_list = TODO_LIST_INIT;
4300 if (read_and_refresh_cache(r, opts))
4303 if (read_populate_opts(opts))
4305 if (is_rebase_i(opts)) {
4306 if ((res = read_populate_todo(r, &todo_list, opts)))
4307 goto release_todo_list;
4309 if (file_exists(rebase_path_dropped())) {
4310 if ((res = todo_list_check_against_backup(r, &todo_list)))
4311 goto release_todo_list;
4313 unlink(rebase_path_dropped());
4316 if (commit_staged_changes(r, opts, &todo_list)) {
4318 goto release_todo_list;
4320 } else if (!file_exists(get_todo_path(opts)))
4321 return continue_single_pick(r);
4322 else if ((res = read_populate_todo(r, &todo_list, opts)))
4323 goto release_todo_list;
4325 if (!is_rebase_i(opts)) {
4326 /* Verify that the conflict has been resolved */
4327 if (file_exists(git_path_cherry_pick_head(r)) ||
4328 file_exists(git_path_revert_head(r))) {
4329 res = continue_single_pick(r);
4331 goto release_todo_list;
4333 if (index_differs_from(r, "HEAD", NULL, 0)) {
4334 res = error_dirty_index(r, opts);
4335 goto release_todo_list;
4337 todo_list.current++;
4338 } else if (file_exists(rebase_path_stopped_sha())) {
4339 struct strbuf buf = STRBUF_INIT;
4340 struct object_id oid;
4342 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4343 READ_ONELINER_SKIP_IF_EMPTY) &&
4344 !get_oid_committish(buf.buf, &oid))
4345 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4346 strbuf_release(&buf);
4349 res = pick_commits(r, &todo_list, opts);
4351 todo_list_release(&todo_list);
4355 static int single_pick(struct repository *r,
4356 struct commit *cmit,
4357 struct replay_opts *opts)
4361 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4362 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4363 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4367 int sequencer_pick_revisions(struct repository *r,
4368 struct replay_opts *opts)
4370 struct todo_list todo_list = TODO_LIST_INIT;
4371 struct object_id oid;
4375 if (read_and_refresh_cache(r, opts))
4378 for (i = 0; i < opts->revs->pending.nr; i++) {
4379 struct object_id oid;
4380 const char *name = opts->revs->pending.objects[i].name;
4382 /* This happens when using --stdin. */
4386 if (!get_oid(name, &oid)) {
4387 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4388 enum object_type type = oid_object_info(r,
4391 return error(_("%s: can't cherry-pick a %s"),
4392 name, type_name(type));
4395 return error(_("%s: bad revision"), name);
4399 * If we were called as "git cherry-pick <commit>", just
4400 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4401 * REVERT_HEAD, and don't touch the sequencer state.
4402 * This means it is possible to cherry-pick in the middle
4403 * of a cherry-pick sequence.
4405 if (opts->revs->cmdline.nr == 1 &&
4406 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4407 opts->revs->no_walk &&
4408 !opts->revs->cmdline.rev->flags) {
4409 struct commit *cmit;
4410 if (prepare_revision_walk(opts->revs))
4411 return error(_("revision walk setup failed"));
4412 cmit = get_revision(opts->revs);
4414 return error(_("empty commit set passed"));
4415 if (get_revision(opts->revs))
4416 BUG("unexpected extra commit from walk");
4417 return single_pick(r, cmit, opts);
4421 * Start a new cherry-pick/ revert sequence; but
4422 * first, make sure that an existing one isn't in
4426 if (walk_revs_populate_todo(&todo_list, opts) ||
4427 create_seq_dir(r) < 0)
4429 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4430 return error(_("can't revert as initial commit"));
4431 if (save_head(oid_to_hex(&oid)))
4433 if (save_opts(opts))
4435 update_abort_safety_file();
4436 res = pick_commits(r, &todo_list, opts);
4437 todo_list_release(&todo_list);
4441 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4443 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4444 struct strbuf sob = STRBUF_INIT;
4447 strbuf_addstr(&sob, sign_off_header);
4448 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4449 strbuf_addch(&sob, '\n');
4452 strbuf_complete_line(msgbuf);
4455 * If the whole message buffer is equal to the sob, pretend that we
4456 * found a conforming footer with a matching sob
4458 if (msgbuf->len - ignore_footer == sob.len &&
4459 !strncmp(msgbuf->buf, sob.buf, sob.len))
4462 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4465 const char *append_newlines = NULL;
4466 size_t len = msgbuf->len - ignore_footer;
4470 * The buffer is completely empty. Leave foom for
4471 * the title and body to be filled in by the user.
4473 append_newlines = "\n\n";
4474 } else if (len == 1) {
4476 * Buffer contains a single newline. Add another
4477 * so that we leave room for the title and body.
4479 append_newlines = "\n";
4480 } else if (msgbuf->buf[len - 2] != '\n') {
4482 * Buffer ends with a single newline. Add another
4483 * so that there is an empty line between the message
4486 append_newlines = "\n";
4487 } /* else, the buffer already ends with two newlines. */
4489 if (append_newlines)
4490 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4491 append_newlines, strlen(append_newlines));
4494 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4495 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4498 strbuf_release(&sob);
4501 struct labels_entry {
4502 struct hashmap_entry entry;
4503 char label[FLEX_ARRAY];
4506 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4507 const struct hashmap_entry *entry_or_key, const void *key)
4509 const struct labels_entry *a, *b;
4511 a = container_of(eptr, const struct labels_entry, entry);
4512 b = container_of(entry_or_key, const struct labels_entry, entry);
4514 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4517 struct string_entry {
4518 struct oidmap_entry entry;
4519 char string[FLEX_ARRAY];
4522 struct label_state {
4523 struct oidmap commit2label;
4524 struct hashmap labels;
4528 static const char *label_oid(struct object_id *oid, const char *label,
4529 struct label_state *state)
4531 struct labels_entry *labels_entry;
4532 struct string_entry *string_entry;
4533 struct object_id dummy;
4536 string_entry = oidmap_get(&state->commit2label, oid);
4538 return string_entry->string;
4541 * For "uninteresting" commits, i.e. commits that are not to be
4542 * rebased, and which can therefore not be labeled, we use a unique
4543 * abbreviation of the commit name. This is slightly more complicated
4544 * than calling find_unique_abbrev() because we also need to make
4545 * sure that the abbreviation does not conflict with any other
4548 * We disallow "interesting" commits to be labeled by a string that
4549 * is a valid full-length hash, to ensure that we always can find an
4550 * abbreviation for any uninteresting commit's names that does not
4551 * clash with any other label.
4553 strbuf_reset(&state->buf);
4557 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4558 label = p = state->buf.buf;
4560 find_unique_abbrev_r(p, oid, default_abbrev);
4563 * We may need to extend the abbreviated hash so that there is
4564 * no conflicting label.
4566 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4567 size_t i = strlen(p) + 1;
4569 oid_to_hex_r(p, oid);
4570 for (; i < the_hash_algo->hexsz; i++) {
4573 if (!hashmap_get_from_hash(&state->labels,
4580 struct strbuf *buf = &state->buf;
4583 * Sanitize labels by replacing non-alpha-numeric characters
4584 * (including white-space ones) by dashes, as they might be
4585 * illegal in file names (and hence in ref names).
4587 * Note that we retain non-ASCII UTF-8 characters (identified
4588 * via the most significant bit). They should be all acceptable
4589 * in file names. We do not validate the UTF-8 here, that's not
4590 * the job of this function.
4592 for (; *label; label++)
4593 if ((*label & 0x80) || isalnum(*label))
4594 strbuf_addch(buf, *label);
4595 /* avoid leading dash and double-dashes */
4596 else if (buf->len && buf->buf[buf->len - 1] != '-')
4597 strbuf_addch(buf, '-');
4599 strbuf_addstr(buf, "rev-");
4600 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4604 if ((buf->len == the_hash_algo->hexsz &&
4605 !get_oid_hex(label, &dummy)) ||
4606 (buf->len == 1 && *label == '#') ||
4607 hashmap_get_from_hash(&state->labels,
4608 strihash(label), label)) {
4610 * If the label already exists, or if the label is a
4611 * valid full OID, or the label is a '#' (which we use
4612 * as a separator between merge heads and oneline), we
4613 * append a dash and a number to make it unique.
4615 size_t len = buf->len;
4617 for (i = 2; ; i++) {
4618 strbuf_setlen(buf, len);
4619 strbuf_addf(buf, "-%d", i);
4620 if (!hashmap_get_from_hash(&state->labels,
4630 FLEX_ALLOC_STR(labels_entry, label, label);
4631 hashmap_entry_init(&labels_entry->entry, strihash(label));
4632 hashmap_add(&state->labels, &labels_entry->entry);
4634 FLEX_ALLOC_STR(string_entry, string, label);
4635 oidcpy(&string_entry->entry.oid, oid);
4636 oidmap_put(&state->commit2label, string_entry);
4638 return string_entry->string;
4641 static int make_script_with_merges(struct pretty_print_context *pp,
4642 struct rev_info *revs, struct strbuf *out,
4645 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4646 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4647 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4648 struct strbuf label = STRBUF_INIT;
4649 struct commit_list *commits = NULL, **tail = &commits, *iter;
4650 struct commit_list *tips = NULL, **tips_tail = &tips;
4651 struct commit *commit;
4652 struct oidmap commit2todo = OIDMAP_INIT;
4653 struct string_entry *entry;
4654 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4655 shown = OIDSET_INIT;
4656 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4658 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4659 const char *cmd_pick = abbr ? "p" : "pick",
4660 *cmd_label = abbr ? "l" : "label",
4661 *cmd_reset = abbr ? "t" : "reset",
4662 *cmd_merge = abbr ? "m" : "merge";
4664 oidmap_init(&commit2todo, 0);
4665 oidmap_init(&state.commit2label, 0);
4666 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4667 strbuf_init(&state.buf, 32);
4669 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4670 struct labels_entry *onto_label_entry;
4671 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4672 FLEX_ALLOC_STR(entry, string, "onto");
4673 oidcpy(&entry->entry.oid, oid);
4674 oidmap_put(&state.commit2label, entry);
4676 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4677 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4678 hashmap_add(&state.labels, &onto_label_entry->entry);
4683 * - get onelines for all commits
4684 * - gather all branch tips (i.e. 2nd or later parents of merges)
4685 * - label all branch tips
4687 while ((commit = get_revision(revs))) {
4688 struct commit_list *to_merge;
4689 const char *p1, *p2;
4690 struct object_id *oid;
4693 tail = &commit_list_insert(commit, tail)->next;
4694 oidset_insert(&interesting, &commit->object.oid);
4696 is_empty = is_original_commit_empty(commit);
4697 if (!is_empty && (commit->object.flags & PATCHSAME))
4700 strbuf_reset(&oneline);
4701 pretty_print_commit(pp, commit, &oneline);
4703 to_merge = commit->parents ? commit->parents->next : NULL;
4705 /* non-merge commit: easy case */
4707 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4708 oid_to_hex(&commit->object.oid),
4711 FLEX_ALLOC_STR(entry, string, buf.buf);
4712 oidcpy(&entry->entry.oid, &commit->object.oid);
4713 oidmap_put(&commit2todo, entry);
4718 /* Create a label */
4719 strbuf_reset(&label);
4720 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4721 (p1 = strchr(p1, '\'')) &&
4722 (p2 = strchr(++p1, '\'')))
4723 strbuf_add(&label, p1, p2 - p1);
4724 else if (skip_prefix(oneline.buf, "Merge pull request ",
4726 (p1 = strstr(p1, " from ")))
4727 strbuf_addstr(&label, p1 + strlen(" from "));
4729 strbuf_addbuf(&label, &oneline);
4732 strbuf_addf(&buf, "%s -C %s",
4733 cmd_merge, oid_to_hex(&commit->object.oid));
4735 /* label the tips of merged branches */
4736 for (; to_merge; to_merge = to_merge->next) {
4737 oid = &to_merge->item->object.oid;
4738 strbuf_addch(&buf, ' ');
4740 if (!oidset_contains(&interesting, oid)) {
4741 strbuf_addstr(&buf, label_oid(oid, NULL,
4746 tips_tail = &commit_list_insert(to_merge->item,
4749 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4751 strbuf_addf(&buf, " # %s", oneline.buf);
4753 FLEX_ALLOC_STR(entry, string, buf.buf);
4754 oidcpy(&entry->entry.oid, &commit->object.oid);
4755 oidmap_put(&commit2todo, entry);
4760 * - label branch points
4761 * - add HEAD to the branch tips
4763 for (iter = commits; iter; iter = iter->next) {
4764 struct commit_list *parent = iter->item->parents;
4765 for (; parent; parent = parent->next) {
4766 struct object_id *oid = &parent->item->object.oid;
4767 if (!oidset_contains(&interesting, oid))
4769 if (oidset_insert(&child_seen, oid))
4770 label_oid(oid, "branch-point", &state);
4773 /* Add HEAD as implicit "tip of branch" */
4775 tips_tail = &commit_list_insert(iter->item,
4780 * Third phase: output the todo list. This is a bit tricky, as we
4781 * want to avoid jumping back and forth between revisions. To
4782 * accomplish that goal, we walk backwards from the branch tips,
4783 * gathering commits not yet shown, reversing the list on the fly,
4784 * then outputting that list (labeling revisions as needed).
4786 strbuf_addf(out, "%s onto\n", cmd_label);
4787 for (iter = tips; iter; iter = iter->next) {
4788 struct commit_list *list = NULL, *iter2;
4790 commit = iter->item;
4791 if (oidset_contains(&shown, &commit->object.oid))
4793 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4796 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4798 strbuf_addch(out, '\n');
4800 while (oidset_contains(&interesting, &commit->object.oid) &&
4801 !oidset_contains(&shown, &commit->object.oid)) {
4802 commit_list_insert(commit, &list);
4803 if (!commit->parents) {
4807 commit = commit->parents->item;
4811 strbuf_addf(out, "%s %s\n", cmd_reset,
4812 rebase_cousins || root_with_onto ?
4813 "onto" : "[new root]");
4815 const char *to = NULL;
4817 entry = oidmap_get(&state.commit2label,
4818 &commit->object.oid);
4821 else if (!rebase_cousins)
4822 to = label_oid(&commit->object.oid, NULL,
4825 if (!to || !strcmp(to, "onto"))
4826 strbuf_addf(out, "%s onto\n", cmd_reset);
4828 strbuf_reset(&oneline);
4829 pretty_print_commit(pp, commit, &oneline);
4830 strbuf_addf(out, "%s %s # %s\n",
4831 cmd_reset, to, oneline.buf);
4835 for (iter2 = list; iter2; iter2 = iter2->next) {
4836 struct object_id *oid = &iter2->item->object.oid;
4837 entry = oidmap_get(&commit2todo, oid);
4838 /* only show if not already upstream */
4840 strbuf_addf(out, "%s\n", entry->string);
4841 entry = oidmap_get(&state.commit2label, oid);
4843 strbuf_addf(out, "%s %s\n",
4844 cmd_label, entry->string);
4845 oidset_insert(&shown, oid);
4848 free_commit_list(list);
4851 free_commit_list(commits);
4852 free_commit_list(tips);
4854 strbuf_release(&label);
4855 strbuf_release(&oneline);
4856 strbuf_release(&buf);
4858 oidmap_free(&commit2todo, 1);
4859 oidmap_free(&state.commit2label, 1);
4860 hashmap_free_entries(&state.labels, struct labels_entry, entry);
4861 strbuf_release(&state.buf);
4866 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4867 const char **argv, unsigned flags)
4869 char *format = NULL;
4870 struct pretty_print_context pp = {0};
4871 struct rev_info revs;
4872 struct commit *commit;
4873 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4874 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4876 repo_init_revisions(r, &revs, NULL);
4877 revs.verbose_header = 1;
4879 revs.max_parents = 1;
4880 revs.cherry_mark = 1;
4883 revs.right_only = 1;
4884 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4885 revs.topo_order = 1;
4887 revs.pretty_given = 1;
4888 git_config_get_string("rebase.instructionFormat", &format);
4889 if (!format || !*format) {
4891 format = xstrdup("%s");
4893 get_commit_format(format, &revs);
4895 pp.fmt = revs.commit_format;
4896 pp.output_encoding = get_log_output_encoding();
4898 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4899 return error(_("make_script: unhandled options"));
4901 if (prepare_revision_walk(&revs) < 0)
4902 return error(_("make_script: error preparing revisions"));
4905 return make_script_with_merges(&pp, &revs, out, flags);
4907 while ((commit = get_revision(&revs))) {
4908 int is_empty = is_original_commit_empty(commit);
4910 if (!is_empty && (commit->object.flags & PATCHSAME))
4912 strbuf_addf(out, "%s %s ", insn,
4913 oid_to_hex(&commit->object.oid));
4914 pretty_print_commit(&pp, commit, out);
4915 strbuf_addch(out, '\n');
4921 * Add commands after pick and (series of) squash/fixup commands
4924 void todo_list_add_exec_commands(struct todo_list *todo_list,
4925 struct string_list *commands)
4927 struct strbuf *buf = &todo_list->buf;
4928 size_t base_offset = buf->len;
4929 int i, insert, nr = 0, alloc = 0;
4930 struct todo_item *items = NULL, *base_items = NULL;
4932 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4933 for (i = 0; i < commands->nr; i++) {
4934 size_t command_len = strlen(commands->items[i].string);
4936 strbuf_addstr(buf, commands->items[i].string);
4937 strbuf_addch(buf, '\n');
4939 base_items[i].command = TODO_EXEC;
4940 base_items[i].offset_in_buf = base_offset;
4941 base_items[i].arg_offset = base_offset + strlen("exec ");
4942 base_items[i].arg_len = command_len - strlen("exec ");
4944 base_offset += command_len + 1;
4948 * Insert <commands> after every pick. Here, fixup/squash chains
4949 * are considered part of the pick, so we insert the commands *after*
4950 * those chains if there are any.
4952 * As we insert the exec commands immediately after rearranging
4953 * any fixups and before the user edits the list, a fixup chain
4954 * can never contain comments (any comments are empty picks that
4955 * have been commented out because the user did not specify
4956 * --keep-empty). So, it is safe to insert an exec command
4957 * without looking at the command following a comment.
4960 for (i = 0; i < todo_list->nr; i++) {
4961 enum todo_command command = todo_list->items[i].command;
4962 if (insert && !is_fixup(command)) {
4963 ALLOC_GROW(items, nr + commands->nr, alloc);
4964 COPY_ARRAY(items + nr, base_items, commands->nr);
4970 ALLOC_GROW(items, nr + 1, alloc);
4971 items[nr++] = todo_list->items[i];
4973 if (command == TODO_PICK || command == TODO_MERGE)
4977 /* insert or append final <commands> */
4978 if (insert || nr == todo_list->nr) {
4979 ALLOC_GROW(items, nr + commands->nr, alloc);
4980 COPY_ARRAY(items + nr, base_items, commands->nr);
4985 FREE_AND_NULL(todo_list->items);
4986 todo_list->items = items;
4988 todo_list->alloc = alloc;
4991 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4992 struct strbuf *buf, int num, unsigned flags)
4994 struct todo_item *item;
4995 int i, max = todo_list->nr;
4997 if (num > 0 && num < max)
5000 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5001 /* if the item is not a command write it and continue */
5002 if (item->command >= TODO_COMMENT) {
5003 strbuf_addf(buf, "%.*s\n", item->arg_len,
5004 todo_item_get_arg(todo_list, item));
5008 /* add command to the buffer */
5009 if (flags & TODO_LIST_ABBREVIATE_CMDS)
5010 strbuf_addch(buf, command_to_char(item->command));
5012 strbuf_addstr(buf, command_to_string(item->command));
5016 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5017 short_commit_name(item->commit) :
5018 oid_to_hex(&item->commit->object.oid);
5020 if (item->command == TODO_MERGE) {
5021 if (item->flags & TODO_EDIT_MERGE_MSG)
5022 strbuf_addstr(buf, " -c");
5024 strbuf_addstr(buf, " -C");
5027 strbuf_addf(buf, " %s", oid);
5030 /* add all the rest */
5032 strbuf_addch(buf, '\n');
5034 strbuf_addf(buf, " %.*s\n", item->arg_len,
5035 todo_item_get_arg(todo_list, item));
5039 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5040 const char *file, const char *shortrevisions,
5041 const char *shortonto, int num, unsigned flags)
5044 struct strbuf buf = STRBUF_INIT;
5046 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5047 if (flags & TODO_LIST_APPEND_TODO_HELP)
5048 append_todo_help(count_commands(todo_list),
5049 shortrevisions, shortonto, &buf);
5051 res = write_message(buf.buf, buf.len, file, 0);
5052 strbuf_release(&buf);
5057 /* skip picking commits whose parents are unchanged */
5058 static int skip_unnecessary_picks(struct repository *r,
5059 struct todo_list *todo_list,
5060 struct object_id *base_oid)
5062 struct object_id *parent_oid;
5065 for (i = 0; i < todo_list->nr; i++) {
5066 struct todo_item *item = todo_list->items + i;
5068 if (item->command >= TODO_NOOP)
5070 if (item->command != TODO_PICK)
5072 if (parse_commit(item->commit)) {
5073 return error(_("could not parse commit '%s'"),
5074 oid_to_hex(&item->commit->object.oid));
5076 if (!item->commit->parents)
5077 break; /* root commit */
5078 if (item->commit->parents->next)
5079 break; /* merge commit */
5080 parent_oid = &item->commit->parents->item->object.oid;
5081 if (!oideq(parent_oid, base_oid))
5083 oidcpy(base_oid, &item->commit->object.oid);
5086 const char *done_path = rebase_path_done();
5088 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5089 error_errno(_("could not write to '%s'"), done_path);
5093 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5095 todo_list->current = 0;
5096 todo_list->done_nr += i;
5098 if (is_fixup(peek_command(todo_list, 0)))
5099 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5105 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5106 const char *shortrevisions, const char *onto_name,
5107 struct commit *onto, const char *orig_head,
5108 struct string_list *commands, unsigned autosquash,
5109 struct todo_list *todo_list)
5111 const char *shortonto, *todo_file = rebase_path_todo();
5112 struct todo_list new_todo = TODO_LIST_INIT;
5113 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5114 struct object_id oid = onto->object.oid;
5117 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5119 if (buf->len == 0) {
5120 struct todo_item *item = append_new_todo(todo_list);
5121 item->command = TODO_NOOP;
5122 item->commit = NULL;
5123 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5126 if (autosquash && todo_list_rearrange_squash(todo_list))
5130 todo_list_add_exec_commands(todo_list, commands);
5132 if (count_commands(todo_list) == 0) {
5133 apply_autostash(rebase_path_autostash());
5134 sequencer_remove_state(opts);
5136 return error(_("nothing to do"));
5139 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5143 else if (res == -2) {
5144 apply_autostash(rebase_path_autostash());
5145 sequencer_remove_state(opts);
5148 } else if (res == -3) {
5149 apply_autostash(rebase_path_autostash());
5150 sequencer_remove_state(opts);
5151 todo_list_release(&new_todo);
5153 return error(_("nothing to do"));
5154 } else if (res == -4) {
5155 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5156 todo_list_release(&new_todo);
5161 /* Expand the commit IDs */
5162 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5163 strbuf_swap(&new_todo.buf, &buf2);
5164 strbuf_release(&buf2);
5165 new_todo.total_nr -= new_todo.nr;
5166 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5167 BUG("invalid todo list after expanding IDs:\n%s",
5170 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5171 todo_list_release(&new_todo);
5172 return error(_("could not skip unnecessary pick commands"));
5175 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5176 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5177 todo_list_release(&new_todo);
5178 return error_errno(_("could not write '%s'"), todo_file);
5183 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5186 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5189 todo_list_write_total_nr(&new_todo);
5190 res = pick_commits(r, &new_todo, opts);
5193 todo_list_release(&new_todo);
5198 struct subject2item_entry {
5199 struct hashmap_entry entry;
5201 char subject[FLEX_ARRAY];
5204 static int subject2item_cmp(const void *fndata,
5205 const struct hashmap_entry *eptr,
5206 const struct hashmap_entry *entry_or_key,
5209 const struct subject2item_entry *a, *b;
5211 a = container_of(eptr, const struct subject2item_entry, entry);
5212 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5214 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5217 define_commit_slab(commit_todo_item, struct todo_item *);
5220 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5221 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5222 * after the former, and change "pick" to "fixup"/"squash".
5224 * Note that if the config has specified a custom instruction format, each log
5225 * message will have to be retrieved from the commit (as the oneline in the
5226 * script cannot be trusted) in order to normalize the autosquash arrangement.
5228 int todo_list_rearrange_squash(struct todo_list *todo_list)
5230 struct hashmap subject2item;
5231 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5233 struct commit_todo_item commit_todo;
5234 struct todo_item *items = NULL;
5236 init_commit_todo_item(&commit_todo);
5238 * The hashmap maps onelines to the respective todo list index.
5240 * If any items need to be rearranged, the next[i] value will indicate
5241 * which item was moved directly after the i'th.
5243 * In that case, last[i] will indicate the index of the latest item to
5244 * be moved to appear after the i'th.
5246 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5247 ALLOC_ARRAY(next, todo_list->nr);
5248 ALLOC_ARRAY(tail, todo_list->nr);
5249 ALLOC_ARRAY(subjects, todo_list->nr);
5250 for (i = 0; i < todo_list->nr; i++) {
5251 struct strbuf buf = STRBUF_INIT;
5252 struct todo_item *item = todo_list->items + i;
5253 const char *commit_buffer, *subject, *p;
5256 struct subject2item_entry *entry;
5258 next[i] = tail[i] = -1;
5259 if (!item->commit || item->command == TODO_DROP) {
5264 if (is_fixup(item->command)) {
5265 clear_commit_todo_item(&commit_todo);
5266 return error(_("the script was already rearranged."));
5269 *commit_todo_item_at(&commit_todo, item->commit) = item;
5271 parse_commit(item->commit);
5272 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5273 find_commit_subject(commit_buffer, &subject);
5274 format_subject(&buf, subject, " ");
5275 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5276 unuse_commit_buffer(item->commit, commit_buffer);
5277 if ((skip_prefix(subject, "fixup! ", &p) ||
5278 skip_prefix(subject, "squash! ", &p))) {
5279 struct commit *commit2;
5284 if (!skip_prefix(p, "fixup! ", &p) &&
5285 !skip_prefix(p, "squash! ", &p))
5289 entry = hashmap_get_entry_from_hash(&subject2item,
5291 struct subject2item_entry,
5294 /* found by title */
5296 else if (!strchr(p, ' ') &&
5298 lookup_commit_reference_by_name(p)) &&
5299 *commit_todo_item_at(&commit_todo, commit2))
5300 /* found by commit name */
5301 i2 = *commit_todo_item_at(&commit_todo, commit2)
5304 /* copy can be a prefix of the commit subject */
5305 for (i2 = 0; i2 < i; i2++)
5307 starts_with(subjects[i2], p))
5315 todo_list->items[i].command =
5316 starts_with(subject, "fixup!") ?
5317 TODO_FIXUP : TODO_SQUASH;
5323 } else if (!hashmap_get_from_hash(&subject2item,
5324 strhash(subject), subject)) {
5325 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5327 hashmap_entry_init(&entry->entry,
5328 strhash(entry->subject));
5329 hashmap_put(&subject2item, &entry->entry);
5334 for (i = 0; i < todo_list->nr; i++) {
5335 enum todo_command command = todo_list->items[i].command;
5339 * Initially, all commands are 'pick's. If it is a
5340 * fixup or a squash now, we have rearranged it.
5342 if (is_fixup(command))
5346 ALLOC_GROW(items, nr + 1, alloc);
5347 items[nr++] = todo_list->items[cur];
5352 FREE_AND_NULL(todo_list->items);
5353 todo_list->items = items;
5355 todo_list->alloc = alloc;
5360 for (i = 0; i < todo_list->nr; i++)
5363 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5365 clear_commit_todo_item(&commit_todo);