5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-recursive.h"
19 #include "argv-array.h"
23 #include "wt-status.h"
25 #include "notes-utils.h"
27 #include "unpack-trees.h"
31 #include "commit-slab.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
43 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
61 * The rebase command lines that have already been processed. A line
62 * is moved here when it is first handled, before any associated user
65 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
67 * The file to keep track of how many commands were already processed (e.g.
70 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
72 * The file to keep track of how many commands are to be processed in total
73 * (e.g. for the prompt).
75 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
77 * The commit message that is planned to be used for any changes that
78 * need to be committed following a user interaction.
80 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
82 * The file into which is accumulated the suggested commit message for
83 * squash/fixup commands. When the first of a series of squash/fixups
84 * is seen, the file is created and the commit message from the
85 * previous commit and from the first squash/fixup commit are written
86 * to it. The commit message for each subsequent squash/fixup commit
87 * is appended to the file as it is processed.
89 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
91 * If the current series of squash/fixups has not yet included a squash
92 * command, then this file exists and holds the commit message of the
93 * original "pick" commit. (If the series ends without a "squash"
94 * command, then this can be used as the commit message of the combined
95 * commit without opening the editor.)
97 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
99 * This file contains the list fixup/squash commands that have been
100 * accumulated into message-fixup or message-squash so far.
102 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
104 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
105 * GIT_AUTHOR_DATE that will be used for the commit that is currently
108 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
110 * When an "edit" rebase command is being processed, the SHA1 of the
111 * commit to be edited is recorded in this file. When "git rebase
112 * --continue" is executed, if there are any staged changes then they
113 * will be amended to the HEAD commit, but only provided the HEAD
114 * commit is still the commit to be edited. When any other rebase
115 * command is processed, this file is deleted.
117 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
119 * When we stop at a given patch via the "edit" command, this file contains
120 * the abbreviated commit name of the corresponding patch.
122 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
124 * For the post-rewrite hook, we make a list of rewritten commits and
125 * their new sha1s. The rewritten-pending list keeps the sha1s of
126 * commits that have been processed, but not committed yet,
127 * e.g. because they are waiting for a 'squash' command.
129 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
130 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
131 "rebase-merge/rewritten-pending")
134 * The path of the file containig the OID of the "squash onto" commit, i.e.
135 * the dummy commit used for `reset [new root]`.
137 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
140 * The path of the file listing refs that need to be deleted after the rebase
141 * finishes. This is used by the `label` command to record the need for cleanup.
143 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
146 * The following files are written by git-rebase just after parsing the
149 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
150 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
151 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
152 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
153 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
154 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
155 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
156 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
157 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
158 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
159 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
160 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
161 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
162 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
164 static int git_sequencer_config(const char *k, const char *v, void *cb)
166 struct replay_opts *opts = cb;
169 if (!strcmp(k, "commit.cleanup")) {
172 status = git_config_string(&s, k, v);
176 if (!strcmp(s, "verbatim")) {
177 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
178 opts->explicit_cleanup = 1;
179 } else if (!strcmp(s, "whitespace")) {
180 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
181 opts->explicit_cleanup = 1;
182 } else if (!strcmp(s, "strip")) {
183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "scissors")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
187 opts->explicit_cleanup = 1;
189 warning(_("invalid commit message cleanup mode '%s'"),
197 if (!strcmp(k, "commit.gpgsign")) {
198 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
202 status = git_gpg_config(k, v, NULL);
206 return git_diff_basic_config(k, v, NULL);
209 void sequencer_init_config(struct replay_opts *opts)
211 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
212 git_config(git_sequencer_config, opts);
215 static inline int is_rebase_i(const struct replay_opts *opts)
217 return opts->action == REPLAY_INTERACTIVE_REBASE;
220 static const char *get_dir(const struct replay_opts *opts)
222 if (is_rebase_i(opts))
223 return rebase_path();
224 return git_path_seq_dir();
227 static const char *get_todo_path(const struct replay_opts *opts)
229 if (is_rebase_i(opts))
230 return rebase_path_todo();
231 return git_path_todo_file();
235 * Returns 0 for non-conforming footer
236 * Returns 1 for conforming footer
237 * Returns 2 when sob exists within conforming footer
238 * Returns 3 when sob exists within conforming footer as last entry
240 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
241 size_t ignore_footer)
243 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
244 struct trailer_info info;
246 int found_sob = 0, found_sob_last = 0;
250 trailer_info_get(&info, sb->buf, &opts);
252 if (info.trailer_start == info.trailer_end)
255 for (i = 0; i < info.trailer_nr; i++)
256 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
258 if (i == info.trailer_nr - 1)
262 trailer_info_release(&info);
271 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
273 static struct strbuf buf = STRBUF_INIT;
277 sq_quotef(&buf, "-S%s", opts->gpg_sign);
281 int sequencer_remove_state(struct replay_opts *opts)
283 struct strbuf buf = STRBUF_INIT;
286 if (is_rebase_i(opts) &&
287 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
290 char *eol = strchr(p, '\n');
293 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0) {
294 warning(_("could not delete '%s'"), p);
303 free(opts->gpg_sign);
304 free(opts->strategy);
305 for (i = 0; i < opts->xopts_nr; i++)
306 free(opts->xopts[i]);
308 strbuf_release(&opts->current_fixups);
311 strbuf_addstr(&buf, get_dir(opts));
312 if (remove_dir_recursively(&buf, 0))
313 ret = error(_("could not remove '%s'"), buf.buf);
314 strbuf_release(&buf);
319 static const char *action_name(const struct replay_opts *opts)
321 switch (opts->action) {
325 return N_("cherry-pick");
326 case REPLAY_INTERACTIVE_REBASE:
327 return N_("rebase -i");
329 die(_("unknown action: %d"), opts->action);
332 struct commit_message {
339 static const char *short_commit_name(struct commit *commit)
341 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
344 static int get_message(struct commit *commit, struct commit_message *out)
346 const char *abbrev, *subject;
349 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
350 abbrev = short_commit_name(commit);
352 subject_len = find_commit_subject(out->message, &subject);
354 out->subject = xmemdupz(subject, subject_len);
355 out->label = xstrfmt("%s... %s", abbrev, out->subject);
356 out->parent_label = xstrfmt("parent of %s", out->label);
361 static void free_message(struct commit *commit, struct commit_message *msg)
363 free(msg->parent_label);
366 unuse_commit_buffer(commit, msg->message);
369 static void print_advice(struct repository *r, int show_hint,
370 struct replay_opts *opts)
372 char *msg = getenv("GIT_CHERRY_PICK_HELP");
375 fprintf(stderr, "%s\n", msg);
377 * A conflict has occurred but the porcelain
378 * (typically rebase --interactive) wants to take care
379 * of the commit itself so remove CHERRY_PICK_HEAD
381 unlink(git_path_cherry_pick_head(r));
387 advise(_("after resolving the conflicts, mark the corrected paths\n"
388 "with 'git add <paths>' or 'git rm <paths>'"));
390 advise(_("after resolving the conflicts, mark the corrected paths\n"
391 "with 'git add <paths>' or 'git rm <paths>'\n"
392 "and commit the result with 'git commit'"));
396 static int write_message(const void *buf, size_t len, const char *filename,
399 struct lock_file msg_file = LOCK_INIT;
401 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
403 return error_errno(_("could not lock '%s'"), filename);
404 if (write_in_full(msg_fd, buf, len) < 0) {
405 error_errno(_("could not write to '%s'"), filename);
406 rollback_lock_file(&msg_file);
409 if (append_eol && write(msg_fd, "\n", 1) < 0) {
410 error_errno(_("could not write eol to '%s'"), filename);
411 rollback_lock_file(&msg_file);
414 if (commit_lock_file(&msg_file) < 0)
415 return error(_("failed to finalize '%s'"), filename);
421 * Reads a file that was presumably written by a shell script, i.e. with an
422 * end-of-line marker that needs to be stripped.
424 * Note that only the last end-of-line marker is stripped, consistent with the
425 * behavior of "$(cat path)" in a shell script.
427 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
429 static int read_oneliner(struct strbuf *buf,
430 const char *path, int skip_if_empty)
432 int orig_len = buf->len;
434 if (!file_exists(path))
437 if (strbuf_read_file(buf, path, 0) < 0) {
438 warning_errno(_("could not read '%s'"), path);
442 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
443 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
445 buf->buf[buf->len] = '\0';
448 if (skip_if_empty && buf->len == orig_len)
454 static struct tree *empty_tree(struct repository *r)
456 return lookup_tree(r, the_hash_algo->empty_tree);
459 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
461 if (repo_read_index_unmerged(repo))
462 return error_resolve_conflict(_(action_name(opts)));
464 error(_("your local changes would be overwritten by %s."),
465 _(action_name(opts)));
467 if (advice_commit_before_merge)
468 advise(_("commit your changes or stash them to proceed."));
472 static void update_abort_safety_file(void)
474 struct object_id head;
476 /* Do nothing on a single-pick */
477 if (!file_exists(git_path_seq_dir()))
480 if (!get_oid("HEAD", &head))
481 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
483 write_file(git_path_abort_safety_file(), "%s", "");
486 static int fast_forward_to(struct repository *r,
487 const struct object_id *to,
488 const struct object_id *from,
490 struct replay_opts *opts)
492 struct ref_transaction *transaction;
493 struct strbuf sb = STRBUF_INIT;
494 struct strbuf err = STRBUF_INIT;
497 if (checkout_fast_forward(r, from, to, 1))
498 return -1; /* the callee should have complained already */
500 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
502 transaction = ref_transaction_begin(&err);
504 ref_transaction_update(transaction, "HEAD",
505 to, unborn && !is_rebase_i(opts) ?
508 ref_transaction_commit(transaction, &err)) {
509 ref_transaction_free(transaction);
510 error("%s", err.buf);
512 strbuf_release(&err);
517 strbuf_release(&err);
518 ref_transaction_free(transaction);
519 update_abort_safety_file();
523 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
526 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
527 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
528 COMMIT_MSG_CLEANUP_SPACE;
529 else if (!strcmp(cleanup_arg, "verbatim"))
530 return COMMIT_MSG_CLEANUP_NONE;
531 else if (!strcmp(cleanup_arg, "whitespace"))
532 return COMMIT_MSG_CLEANUP_SPACE;
533 else if (!strcmp(cleanup_arg, "strip"))
534 return COMMIT_MSG_CLEANUP_ALL;
535 else if (!strcmp(cleanup_arg, "scissors"))
536 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
537 COMMIT_MSG_CLEANUP_SPACE;
539 die(_("Invalid cleanup mode %s"), cleanup_arg);
543 * NB using int rather than enum cleanup_mode to stop clang's
544 * -Wtautological-constant-out-of-range-compare complaining that the comparison
547 static const char *describe_cleanup_mode(int cleanup_mode)
549 static const char *modes[] = { "whitespace",
554 if (cleanup_mode < ARRAY_SIZE(modes))
555 return modes[cleanup_mode];
557 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
560 void append_conflicts_hint(struct index_state *istate,
561 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
565 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
566 strbuf_addch(msgbuf, '\n');
567 wt_status_append_cut_line(msgbuf);
568 strbuf_addch(msgbuf, comment_line_char);
571 strbuf_addch(msgbuf, '\n');
572 strbuf_commented_addf(msgbuf, "Conflicts:\n");
573 for (i = 0; i < istate->cache_nr;) {
574 const struct cache_entry *ce = istate->cache[i++];
576 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
577 while (i < istate->cache_nr &&
578 !strcmp(ce->name, istate->cache[i]->name))
584 static int do_recursive_merge(struct repository *r,
585 struct commit *base, struct commit *next,
586 const char *base_label, const char *next_label,
587 struct object_id *head, struct strbuf *msgbuf,
588 struct replay_opts *opts)
590 struct merge_options o;
591 struct tree *result, *next_tree, *base_tree, *head_tree;
594 struct lock_file index_lock = LOCK_INIT;
596 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
601 init_merge_options(&o, r);
602 o.ancestor = base ? base_label : "(empty tree)";
604 o.branch2 = next ? next_label : "(empty tree)";
605 if (is_rebase_i(opts))
607 o.show_rename_progress = 1;
609 head_tree = parse_tree_indirect(head);
610 next_tree = next ? get_commit_tree(next) : empty_tree(r);
611 base_tree = base ? get_commit_tree(base) : empty_tree(r);
613 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
614 parse_merge_opt(&o, *xopt);
616 clean = merge_trees(&o,
618 next_tree, base_tree, &result);
619 if (is_rebase_i(opts) && clean <= 0)
620 fputs(o.obuf.buf, stdout);
621 strbuf_release(&o.obuf);
622 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
624 rollback_lock_file(&index_lock);
628 if (write_locked_index(r->index, &index_lock,
629 COMMIT_LOCK | SKIP_IF_UNCHANGED))
631 * TRANSLATORS: %s will be "revert", "cherry-pick" or
634 return error(_("%s: Unable to write new index file"),
635 _(action_name(opts)));
638 append_conflicts_hint(r->index, msgbuf,
639 opts->default_msg_cleanup);
644 static struct object_id *get_cache_tree_oid(struct index_state *istate)
646 if (!istate->cache_tree)
647 istate->cache_tree = cache_tree();
649 if (!cache_tree_fully_valid(istate->cache_tree))
650 if (cache_tree_update(istate, 0)) {
651 error(_("unable to update cache tree"));
655 return &istate->cache_tree->oid;
658 static int is_index_unchanged(struct repository *r)
660 struct object_id head_oid, *cache_tree_oid;
661 struct commit *head_commit;
662 struct index_state *istate = r->index;
664 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
665 return error(_("could not resolve HEAD commit"));
667 head_commit = lookup_commit(r, &head_oid);
670 * If head_commit is NULL, check_commit, called from
671 * lookup_commit, would have indicated that head_commit is not
672 * a commit object already. parse_commit() will return failure
673 * without further complaints in such a case. Otherwise, if
674 * the commit is invalid, parse_commit() will complain. So
675 * there is nothing for us to say here. Just return failure.
677 if (parse_commit(head_commit))
680 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
683 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
686 static int write_author_script(const char *message)
688 struct strbuf buf = STRBUF_INIT;
693 if (!*message || starts_with(message, "\n")) {
695 /* Missing 'author' line? */
696 unlink(rebase_path_author_script());
698 } else if (skip_prefix(message, "author ", &message))
700 else if ((eol = strchr(message, '\n')))
705 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
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_EMAIL='");
714 while (*message && *message != '\n' && *message != '\r')
715 if (skip_prefix(message, "> ", &message))
717 else if (*message != '\'')
718 strbuf_addch(&buf, *(message++));
720 strbuf_addf(&buf, "'\\%c'", *(message++));
721 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
722 while (*message && *message != '\n' && *message != '\r')
723 if (*message != '\'')
724 strbuf_addch(&buf, *(message++));
726 strbuf_addf(&buf, "'\\%c'", *(message++));
727 strbuf_addch(&buf, '\'');
728 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
729 strbuf_release(&buf);
734 * Take a series of KEY='VALUE' lines where VALUE part is
735 * sq-quoted, and append <KEY, VALUE> at the end of the string list
737 static int parse_key_value_squoted(char *buf, struct string_list *list)
740 struct string_list_item *item;
742 char *cp = strchr(buf, '=');
744 np = strchrnul(buf, '\n');
745 return error(_("no key present in '%.*s'"),
746 (int) (np - buf), buf);
748 np = strchrnul(cp, '\n');
750 item = string_list_append(list, buf);
752 buf = np + (*np == '\n');
756 return error(_("unable to dequote value of '%s'"),
758 item->util = xstrdup(cp);
764 * Reads and parses the state directory's "author-script" file, and sets name,
765 * email and date accordingly.
766 * Returns 0 on success, -1 if the file could not be parsed.
768 * The author script is of the format:
770 * GIT_AUTHOR_NAME='$author_name'
771 * GIT_AUTHOR_EMAIL='$author_email'
772 * GIT_AUTHOR_DATE='$author_date'
774 * where $author_name, $author_email and $author_date are quoted. We are strict
775 * with our parsing, as the file was meant to be eval'd in the old
776 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
777 * from what this function expects, it is better to bail out than to do
778 * something that the user does not expect.
780 int read_author_script(const char *path, char **name, char **email, char **date,
783 struct strbuf buf = STRBUF_INIT;
784 struct string_list kv = STRING_LIST_INIT_DUP;
785 int retval = -1; /* assume failure */
786 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
788 if (strbuf_read_file(&buf, path, 256) <= 0) {
789 strbuf_release(&buf);
790 if (errno == ENOENT && allow_missing)
793 return error_errno(_("could not open '%s' for reading"),
797 if (parse_key_value_squoted(buf.buf, &kv))
800 for (i = 0; i < kv.nr; i++) {
801 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
803 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
806 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
808 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
811 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
813 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
817 err = error(_("unknown variable '%s'"),
822 error(_("missing 'GIT_AUTHOR_NAME'"));
824 error(_("missing 'GIT_AUTHOR_EMAIL'"));
826 error(_("missing 'GIT_AUTHOR_DATE'"));
827 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
831 *name = kv.items[name_i].util;
833 free(kv.items[name_i].util);
835 *email = kv.items[email_i].util;
837 free(kv.items[email_i].util);
839 *date = kv.items[date_i].util;
841 free(kv.items[date_i].util);
844 string_list_clear(&kv, !!retval);
845 strbuf_release(&buf);
850 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
851 * file with shell quoting into struct argv_array. Returns -1 on
852 * error, 0 otherwise.
854 static int read_env_script(struct argv_array *env)
856 char *name, *email, *date;
858 if (read_author_script(rebase_path_author_script(),
859 &name, &email, &date, 0))
862 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
863 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
864 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
872 static char *get_author(const char *message)
877 a = find_commit_header(message, "author", &len);
879 return xmemdupz(a, len);
884 /* Returns a "date" string that needs to be free()'d by the caller */
885 static char *read_author_date_or_null(void)
889 if (read_author_script(rebase_path_author_script(),
890 NULL, NULL, &date, 0))
895 /* Construct a free()able author string with current time as the author date */
896 static char *ignore_author_date(const char *author)
898 int len = strlen(author);
899 struct ident_split ident;
900 struct strbuf new_author = STRBUF_INIT;
902 if (split_ident_line(&ident, author, len) < 0) {
903 error(_("malformed ident line"));
906 len = ident.mail_end - ident.name_begin + 1;
908 strbuf_addf(&new_author, "%.*s ", len, ident.name_begin);
909 datestamp(&new_author);
910 return strbuf_detach(&new_author, NULL);
913 static void push_dates(struct child_process *child, int change_committer_date)
915 time_t now = time(NULL);
916 struct strbuf date = STRBUF_INIT;
918 strbuf_addf(&date, "@%"PRIuMAX, (uintmax_t)now);
919 argv_array_pushf(&child->env_array, "GIT_AUTHOR_DATE=%s", date.buf);
920 if (change_committer_date)
921 argv_array_pushf(&child->env_array, "GIT_COMMITTER_DATE=%s", date.buf);
922 strbuf_release(&date);
925 static const char staged_changes_advice[] =
926 N_("you have staged changes in your working tree\n"
927 "If these changes are meant to be squashed into the previous commit, run:\n"
929 " git commit --amend %s\n"
931 "If they are meant to go into a new commit, run:\n"
935 "In both cases, once you're done, continue with:\n"
937 " git rebase --continue\n");
939 #define ALLOW_EMPTY (1<<0)
940 #define EDIT_MSG (1<<1)
941 #define AMEND_MSG (1<<2)
942 #define CLEANUP_MSG (1<<3)
943 #define VERIFY_MSG (1<<4)
944 #define CREATE_ROOT_COMMIT (1<<5)
946 static int run_command_silent_on_success(struct child_process *cmd)
948 struct strbuf buf = STRBUF_INIT;
951 cmd->stdout_to_stderr = 1;
952 rc = pipe_command(cmd,
958 fputs(buf.buf, stderr);
959 strbuf_release(&buf);
964 * If we are cherry-pick, and if the merge did not result in
965 * hand-editing, we will hit this commit and inherit the original
966 * author date and name.
968 * If we are revert, or if our cherry-pick results in a hand merge,
969 * we had better say that the current user is responsible for that.
971 * An exception is when run_git_commit() is called during an
972 * interactive rebase: in that case, we will want to retain the
975 static int run_git_commit(struct repository *r,
977 struct replay_opts *opts,
980 struct child_process cmd = CHILD_PROCESS_INIT;
984 if (opts->committer_date_is_author_date) {
986 struct strbuf datebuf = STRBUF_INIT;
987 char *date = read_author_date_or_null();
992 strbuf_addf(&datebuf, "@%s", date);
993 res = setenv("GIT_COMMITTER_DATE",
994 opts->ignore_date ? "" : datebuf.buf, 1);
996 strbuf_release(&datebuf);
1003 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
1004 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1006 return error(_(staged_changes_advice),
1010 argv_array_push(&cmd.args, "commit");
1012 if (!(flags & VERIFY_MSG))
1013 argv_array_push(&cmd.args, "-n");
1014 if ((flags & AMEND_MSG))
1015 argv_array_push(&cmd.args, "--amend");
1017 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1018 if (opts->ignore_date)
1019 push_dates(&cmd, opts->committer_date_is_author_date);
1021 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
1022 else if (!(flags & EDIT_MSG))
1023 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
1024 if ((flags & CLEANUP_MSG))
1025 argv_array_push(&cmd.args, "--cleanup=strip");
1026 if ((flags & EDIT_MSG))
1027 argv_array_push(&cmd.args, "-e");
1028 else if (!(flags & CLEANUP_MSG) &&
1029 !opts->signoff && !opts->record_origin &&
1030 !opts->explicit_cleanup)
1031 argv_array_push(&cmd.args, "--cleanup=verbatim");
1033 if ((flags & ALLOW_EMPTY))
1034 argv_array_push(&cmd.args, "--allow-empty");
1036 if (!(flags & EDIT_MSG))
1037 argv_array_push(&cmd.args, "--allow-empty-message");
1039 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1040 return run_command_silent_on_success(&cmd);
1042 return run_command(&cmd);
1045 static int rest_is_empty(const struct strbuf *sb, int start)
1050 /* Check if the rest is just whitespace and Signed-off-by's. */
1051 for (i = start; i < sb->len; i++) {
1052 nl = memchr(sb->buf + i, '\n', sb->len - i);
1058 if (strlen(sign_off_header) <= eol - i &&
1059 starts_with(sb->buf + i, sign_off_header)) {
1064 if (!isspace(sb->buf[i++]))
1071 void cleanup_message(struct strbuf *msgbuf,
1072 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1074 if (verbose || /* Truncate the message just before the diff, if any. */
1075 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1076 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1077 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1078 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1082 * Find out if the message in the strbuf contains only whitespace and
1083 * Signed-off-by lines.
1085 int message_is_empty(const struct strbuf *sb,
1086 enum commit_msg_cleanup_mode cleanup_mode)
1088 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1090 return rest_is_empty(sb, 0);
1094 * See if the user edited the message in the editor or left what
1095 * was in the template intact
1097 int template_untouched(const struct strbuf *sb, const char *template_file,
1098 enum commit_msg_cleanup_mode cleanup_mode)
1100 struct strbuf tmpl = STRBUF_INIT;
1103 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1106 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1109 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1110 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1112 strbuf_release(&tmpl);
1113 return rest_is_empty(sb, start - sb->buf);
1116 int update_head_with_reflog(const struct commit *old_head,
1117 const struct object_id *new_head,
1118 const char *action, const struct strbuf *msg,
1121 struct ref_transaction *transaction;
1122 struct strbuf sb = STRBUF_INIT;
1127 strbuf_addstr(&sb, action);
1128 strbuf_addstr(&sb, ": ");
1131 nl = strchr(msg->buf, '\n');
1133 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1135 strbuf_addbuf(&sb, msg);
1136 strbuf_addch(&sb, '\n');
1139 transaction = ref_transaction_begin(err);
1141 ref_transaction_update(transaction, "HEAD", new_head,
1142 old_head ? &old_head->object.oid : &null_oid,
1144 ref_transaction_commit(transaction, err)) {
1147 ref_transaction_free(transaction);
1148 strbuf_release(&sb);
1153 static int run_rewrite_hook(const struct object_id *oldoid,
1154 const struct object_id *newoid)
1156 struct child_process proc = CHILD_PROCESS_INIT;
1157 const char *argv[3];
1159 struct strbuf sb = STRBUF_INIT;
1161 argv[0] = find_hook("post-rewrite");
1170 proc.stdout_to_stderr = 1;
1171 proc.trace2_hook_name = "post-rewrite";
1173 code = start_command(&proc);
1176 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1177 sigchain_push(SIGPIPE, SIG_IGN);
1178 write_in_full(proc.in, sb.buf, sb.len);
1180 strbuf_release(&sb);
1181 sigchain_pop(SIGPIPE);
1182 return finish_command(&proc);
1185 void commit_post_rewrite(struct repository *r,
1186 const struct commit *old_head,
1187 const struct object_id *new_head)
1189 struct notes_rewrite_cfg *cfg;
1191 cfg = init_copy_notes_for_rewrite("amend");
1193 /* we are amending, so old_head is not NULL */
1194 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1195 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1197 run_rewrite_hook(&old_head->object.oid, new_head);
1200 static int run_prepare_commit_msg_hook(struct repository *r,
1204 struct argv_array hook_env = ARGV_ARRAY_INIT;
1208 name = git_path_commit_editmsg();
1209 if (write_message(msg->buf, msg->len, name, 0))
1212 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
1213 argv_array_push(&hook_env, "GIT_EDITOR=:");
1215 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1216 "commit", commit, NULL);
1218 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1221 ret = error(_("'prepare-commit-msg' hook failed"));
1222 argv_array_clear(&hook_env);
1227 static const char implicit_ident_advice_noconfig[] =
1228 N_("Your name and email address were configured automatically based\n"
1229 "on your username and hostname. Please check that they are accurate.\n"
1230 "You can suppress this message by setting them explicitly. Run the\n"
1231 "following command and follow the instructions in your editor to edit\n"
1232 "your configuration file:\n"
1234 " git config --global --edit\n"
1236 "After doing this, you may fix the identity used for this commit with:\n"
1238 " git commit --amend --reset-author\n");
1240 static const char implicit_ident_advice_config[] =
1241 N_("Your name and email address were configured automatically based\n"
1242 "on your username and hostname. Please check that they are accurate.\n"
1243 "You can suppress this message by setting them explicitly:\n"
1245 " git config --global user.name \"Your Name\"\n"
1246 " git config --global user.email you@example.com\n"
1248 "After doing this, you may fix the identity used for this commit with:\n"
1250 " git commit --amend --reset-author\n");
1252 static const char *implicit_ident_advice(void)
1254 char *user_config = expand_user_path("~/.gitconfig", 0);
1255 char *xdg_config = xdg_config_home("config");
1256 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1262 return _(implicit_ident_advice_config);
1264 return _(implicit_ident_advice_noconfig);
1268 void print_commit_summary(struct repository *r,
1270 const struct object_id *oid,
1273 struct rev_info rev;
1274 struct commit *commit;
1275 struct strbuf format = STRBUF_INIT;
1277 struct pretty_print_context pctx = {0};
1278 struct strbuf author_ident = STRBUF_INIT;
1279 struct strbuf committer_ident = STRBUF_INIT;
1281 commit = lookup_commit(r, oid);
1283 die(_("couldn't look up newly created commit"));
1284 if (parse_commit(commit))
1285 die(_("could not parse newly created commit"));
1287 strbuf_addstr(&format, "format:%h] %s");
1289 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1290 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1291 if (strbuf_cmp(&author_ident, &committer_ident)) {
1292 strbuf_addstr(&format, "\n Author: ");
1293 strbuf_addbuf_percentquote(&format, &author_ident);
1295 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1296 struct strbuf date = STRBUF_INIT;
1298 format_commit_message(commit, "%ad", &date, &pctx);
1299 strbuf_addstr(&format, "\n Date: ");
1300 strbuf_addbuf_percentquote(&format, &date);
1301 strbuf_release(&date);
1303 if (!committer_ident_sufficiently_given()) {
1304 strbuf_addstr(&format, "\n Committer: ");
1305 strbuf_addbuf_percentquote(&format, &committer_ident);
1306 if (advice_implicit_identity) {
1307 strbuf_addch(&format, '\n');
1308 strbuf_addstr(&format, implicit_ident_advice());
1311 strbuf_release(&author_ident);
1312 strbuf_release(&committer_ident);
1314 repo_init_revisions(r, &rev, prefix);
1315 setup_revisions(0, NULL, &rev, NULL);
1318 rev.diffopt.output_format =
1319 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1321 rev.verbose_header = 1;
1322 rev.show_root_diff = 1;
1323 get_commit_format(format.buf, &rev);
1324 rev.always_show_header = 0;
1325 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1326 rev.diffopt.break_opt = 0;
1327 diff_setup_done(&rev.diffopt);
1329 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1331 die_errno(_("unable to resolve HEAD after creating commit"));
1332 if (!strcmp(head, "HEAD"))
1333 head = _("detached HEAD");
1335 skip_prefix(head, "refs/heads/", &head);
1336 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1337 _(" (root-commit)") : "");
1339 if (!log_tree_commit(&rev, commit)) {
1340 rev.always_show_header = 1;
1341 rev.use_terminator = 1;
1342 log_tree_commit(&rev, commit);
1345 strbuf_release(&format);
1348 static int parse_head(struct repository *r, struct commit **head)
1350 struct commit *current_head;
1351 struct object_id oid;
1353 if (get_oid("HEAD", &oid)) {
1354 current_head = NULL;
1356 current_head = lookup_commit_reference(r, &oid);
1358 return error(_("could not parse HEAD"));
1359 if (!oideq(&oid, ¤t_head->object.oid)) {
1360 warning(_("HEAD %s is not a commit!"),
1363 if (parse_commit(current_head))
1364 return error(_("could not parse HEAD commit"));
1366 *head = current_head;
1372 * Try to commit without forking 'git commit'. In some cases we need
1373 * to run 'git commit' to display an error message
1376 * -1 - error unable to commit
1378 * 1 - run 'git commit'
1380 static int try_to_commit(struct repository *r,
1381 struct strbuf *msg, const char *author,
1382 struct replay_opts *opts, unsigned int flags,
1383 struct object_id *oid)
1385 struct object_id tree;
1386 struct commit *current_head = NULL;
1387 struct commit_list *parents = NULL;
1388 struct commit_extra_header *extra = NULL;
1389 struct strbuf err = STRBUF_INIT;
1390 struct strbuf commit_msg = STRBUF_INIT;
1391 char *author_to_free = NULL;
1392 const char *hook_commit = NULL;
1393 enum commit_msg_cleanup_mode cleanup;
1396 if (parse_head(r, ¤t_head))
1398 if (flags & AMEND_MSG) {
1399 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1400 const char *out_enc = get_commit_output_encoding();
1401 const char *message = logmsg_reencode(current_head, NULL,
1405 const char *orig_message = NULL;
1407 find_commit_subject(message, &orig_message);
1409 strbuf_addstr(msg, orig_message);
1410 hook_commit = "HEAD";
1412 author = author_to_free = get_author(message);
1413 unuse_commit_buffer(current_head, message);
1415 res = error(_("unable to parse commit author"));
1418 parents = copy_commit_list(current_head->parents);
1419 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1420 } else if (current_head &&
1421 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1422 commit_list_insert(current_head, &parents);
1425 if (opts->committer_date_is_author_date) {
1426 int len = strlen(author);
1427 struct ident_split ident;
1428 struct strbuf date = STRBUF_INIT;
1430 if (split_ident_line(&ident, author, len) < 0) {
1431 res = error(_("malformed ident line"));
1434 if (!ident.date_begin) {
1435 res = error(_("corrupted author without date information"));
1439 strbuf_addf(&date, "@%.*s %.*s",
1440 (int)(ident.date_end - ident.date_begin), ident.date_begin,
1441 (int)(ident.tz_end - ident.tz_begin), ident.tz_begin);
1442 res = setenv("GIT_COMMITTER_DATE",
1443 opts->ignore_date ? "" : date.buf, 1);
1444 strbuf_release(&date);
1450 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1451 res = error(_("git write-tree failed to write a tree"));
1455 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1456 get_commit_tree_oid(current_head) :
1457 the_hash_algo->empty_tree, &tree)) {
1458 res = 1; /* run 'git commit' to display error message */
1462 if (find_hook("prepare-commit-msg")) {
1463 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1466 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1468 res = error_errno(_("unable to read commit message "
1470 git_path_commit_editmsg());
1476 if (flags & CLEANUP_MSG)
1477 cleanup = COMMIT_MSG_CLEANUP_ALL;
1478 else if ((opts->signoff || opts->record_origin) &&
1479 !opts->explicit_cleanup)
1480 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1482 cleanup = opts->default_msg_cleanup;
1484 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1485 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1486 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1487 res = 1; /* run 'git commit' to display error message */
1493 if (opts->ignore_date) {
1494 author = ignore_author_date(author);
1499 free(author_to_free);
1500 author_to_free = (char *)author;
1502 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1503 oid, author, opts->gpg_sign, extra)) {
1504 res = error(_("failed to write commit object"));
1508 if (update_head_with_reflog(current_head, oid,
1509 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1510 res = error("%s", err.buf);
1514 if (flags & AMEND_MSG)
1515 commit_post_rewrite(r, current_head, oid);
1518 free_commit_extra_headers(extra);
1519 strbuf_release(&err);
1520 strbuf_release(&commit_msg);
1521 free(author_to_free);
1526 static int do_commit(struct repository *r,
1527 const char *msg_file, const char *author,
1528 struct replay_opts *opts, unsigned int flags)
1532 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1533 struct object_id oid;
1534 struct strbuf sb = STRBUF_INIT;
1536 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1537 return error_errno(_("unable to read commit message "
1541 res = try_to_commit(r, msg_file ? &sb : NULL,
1542 author, opts, flags, &oid);
1543 strbuf_release(&sb);
1545 unlink(git_path_cherry_pick_head(r));
1546 unlink(git_path_merge_msg(r));
1547 if (!is_rebase_i(opts))
1548 print_commit_summary(r, NULL, &oid,
1549 SUMMARY_SHOW_AUTHOR_DATE);
1554 return run_git_commit(r, msg_file, opts, flags);
1559 static int is_original_commit_empty(struct commit *commit)
1561 const struct object_id *ptree_oid;
1563 if (parse_commit(commit))
1564 return error(_("could not parse commit %s"),
1565 oid_to_hex(&commit->object.oid));
1566 if (commit->parents) {
1567 struct commit *parent = commit->parents->item;
1568 if (parse_commit(parent))
1569 return error(_("could not parse parent commit %s"),
1570 oid_to_hex(&parent->object.oid));
1571 ptree_oid = get_commit_tree_oid(parent);
1573 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1576 return oideq(ptree_oid, get_commit_tree_oid(commit));
1580 * Do we run "git commit" with "--allow-empty"?
1582 static int allow_empty(struct repository *r,
1583 struct replay_opts *opts,
1584 struct commit *commit)
1586 int index_unchanged, empty_commit;
1591 * (1) we do not allow empty at all and error out.
1593 * (2) we allow ones that were initially empty, but
1594 * forbid the ones that become empty;
1596 * (3) we allow both.
1598 if (!opts->allow_empty)
1599 return 0; /* let "git commit" barf as necessary */
1601 index_unchanged = is_index_unchanged(r);
1602 if (index_unchanged < 0)
1603 return index_unchanged;
1604 if (!index_unchanged)
1605 return 0; /* we do not have to say --allow-empty */
1607 if (opts->keep_redundant_commits)
1610 empty_commit = is_original_commit_empty(commit);
1611 if (empty_commit < 0)
1612 return empty_commit;
1622 } todo_command_info[] = {
1639 static const char *command_to_string(const enum todo_command command)
1641 if (command < TODO_COMMENT)
1642 return todo_command_info[command].str;
1643 die(_("unknown command: %d"), command);
1646 static char command_to_char(const enum todo_command command)
1648 if (command < TODO_COMMENT && todo_command_info[command].c)
1649 return todo_command_info[command].c;
1650 return comment_line_char;
1653 static int is_noop(const enum todo_command command)
1655 return TODO_NOOP <= command;
1658 static int is_fixup(enum todo_command command)
1660 return command == TODO_FIXUP || command == TODO_SQUASH;
1663 /* Does this command create a (non-merge) commit? */
1664 static int is_pick_or_similar(enum todo_command command)
1679 static int update_squash_messages(struct repository *r,
1680 enum todo_command command,
1681 struct commit *commit,
1682 struct replay_opts *opts)
1684 struct strbuf buf = STRBUF_INIT;
1686 const char *message, *body;
1688 if (opts->current_fixup_count > 0) {
1689 struct strbuf header = STRBUF_INIT;
1692 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1693 return error(_("could not read '%s'"),
1694 rebase_path_squash_msg());
1696 eol = buf.buf[0] != comment_line_char ?
1697 buf.buf : strchrnul(buf.buf, '\n');
1699 strbuf_addf(&header, "%c ", comment_line_char);
1700 strbuf_addf(&header, _("This is a combination of %d commits."),
1701 opts->current_fixup_count + 2);
1702 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1703 strbuf_release(&header);
1705 struct object_id head;
1706 struct commit *head_commit;
1707 const char *head_message, *body;
1709 if (get_oid("HEAD", &head))
1710 return error(_("need a HEAD to fixup"));
1711 if (!(head_commit = lookup_commit_reference(r, &head)))
1712 return error(_("could not read HEAD"));
1713 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1714 return error(_("could not read HEAD's commit message"));
1716 find_commit_subject(head_message, &body);
1717 if (write_message(body, strlen(body),
1718 rebase_path_fixup_msg(), 0)) {
1719 unuse_commit_buffer(head_commit, head_message);
1720 return error(_("cannot write '%s'"),
1721 rebase_path_fixup_msg());
1724 strbuf_addf(&buf, "%c ", comment_line_char);
1725 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1726 strbuf_addf(&buf, "\n%c ", comment_line_char);
1727 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1728 strbuf_addstr(&buf, "\n\n");
1729 strbuf_addstr(&buf, body);
1731 unuse_commit_buffer(head_commit, head_message);
1734 if (!(message = get_commit_buffer(commit, NULL)))
1735 return error(_("could not read commit message of %s"),
1736 oid_to_hex(&commit->object.oid));
1737 find_commit_subject(message, &body);
1739 if (command == TODO_SQUASH) {
1740 unlink(rebase_path_fixup_msg());
1741 strbuf_addf(&buf, "\n%c ", comment_line_char);
1742 strbuf_addf(&buf, _("This is the commit message #%d:"),
1743 ++opts->current_fixup_count + 1);
1744 strbuf_addstr(&buf, "\n\n");
1745 strbuf_addstr(&buf, body);
1746 } else if (command == TODO_FIXUP) {
1747 strbuf_addf(&buf, "\n%c ", comment_line_char);
1748 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1749 ++opts->current_fixup_count + 1);
1750 strbuf_addstr(&buf, "\n\n");
1751 strbuf_add_commented_lines(&buf, body, strlen(body));
1753 return error(_("unknown command: %d"), command);
1754 unuse_commit_buffer(commit, message);
1756 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1757 strbuf_release(&buf);
1760 strbuf_addf(&opts->current_fixups, "%s%s %s",
1761 opts->current_fixups.len ? "\n" : "",
1762 command_to_string(command),
1763 oid_to_hex(&commit->object.oid));
1764 res = write_message(opts->current_fixups.buf,
1765 opts->current_fixups.len,
1766 rebase_path_current_fixups(), 0);
1772 static void flush_rewritten_pending(void)
1774 struct strbuf buf = STRBUF_INIT;
1775 struct object_id newoid;
1778 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1779 !get_oid("HEAD", &newoid) &&
1780 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1781 char *bol = buf.buf, *eol;
1784 eol = strchrnul(bol, '\n');
1785 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1786 bol, oid_to_hex(&newoid));
1792 unlink(rebase_path_rewritten_pending());
1794 strbuf_release(&buf);
1797 static void record_in_rewritten(struct object_id *oid,
1798 enum todo_command next_command)
1800 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1805 fprintf(out, "%s\n", oid_to_hex(oid));
1808 if (!is_fixup(next_command))
1809 flush_rewritten_pending();
1812 static int do_pick_commit(struct repository *r,
1813 enum todo_command command,
1814 struct commit *commit,
1815 struct replay_opts *opts,
1816 int final_fixup, int *check_todo)
1818 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1819 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1820 struct object_id head;
1821 struct commit *base, *next, *parent;
1822 const char *base_label, *next_label;
1823 char *author = NULL;
1824 struct commit_message msg = { NULL, NULL, NULL, NULL };
1825 struct strbuf msgbuf = STRBUF_INIT;
1826 int res, unborn = 0, reword = 0, allow;
1828 if (opts->no_commit) {
1830 * We do not intend to commit immediately. We just want to
1831 * merge the differences in, so let's compute the tree
1832 * that represents the "current" state for merge-recursive
1835 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1836 return error(_("your index file is unmerged."));
1838 unborn = get_oid("HEAD", &head);
1839 /* Do we want to generate a root commit? */
1840 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1841 oideq(&head, &opts->squash_onto)) {
1842 if (is_fixup(command))
1843 return error(_("cannot fixup root commit"));
1844 flags |= CREATE_ROOT_COMMIT;
1847 oidcpy(&head, the_hash_algo->empty_tree);
1848 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1850 return error_dirty_index(r, opts);
1852 discard_index(r->index);
1854 if (!commit->parents)
1856 else if (commit->parents->next) {
1857 /* Reverting or cherry-picking a merge commit */
1859 struct commit_list *p;
1861 if (!opts->mainline)
1862 return error(_("commit %s is a merge but no -m option was given."),
1863 oid_to_hex(&commit->object.oid));
1865 for (cnt = 1, p = commit->parents;
1866 cnt != opts->mainline && p;
1869 if (cnt != opts->mainline || !p)
1870 return error(_("commit %s does not have parent %d"),
1871 oid_to_hex(&commit->object.oid), opts->mainline);
1873 } else if (1 < opts->mainline)
1875 * Non-first parent explicitly specified as mainline for
1878 return error(_("commit %s does not have parent %d"),
1879 oid_to_hex(&commit->object.oid), opts->mainline);
1881 parent = commit->parents->item;
1883 if (get_message(commit, &msg) != 0)
1884 return error(_("cannot get commit message for %s"),
1885 oid_to_hex(&commit->object.oid));
1887 if (opts->allow_ff && !is_fixup(command) &&
1888 ((parent && oideq(&parent->object.oid, &head)) ||
1889 (!parent && unborn))) {
1890 if (is_rebase_i(opts))
1891 write_author_script(msg.message);
1892 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1894 if (res || command != TODO_REWORD)
1898 goto fast_forward_edit;
1900 if (parent && parse_commit(parent) < 0)
1901 /* TRANSLATORS: The first %s will be a "todo" command like
1902 "revert" or "pick", the second %s a SHA1. */
1903 return error(_("%s: cannot parse parent commit %s"),
1904 command_to_string(command),
1905 oid_to_hex(&parent->object.oid));
1908 * "commit" is an existing commit. We would want to apply
1909 * the difference it introduces since its first parent "prev"
1910 * on top of the current HEAD if we are cherry-pick. Or the
1911 * reverse of it if we are revert.
1914 if (command == TODO_REVERT) {
1916 base_label = msg.label;
1918 next_label = msg.parent_label;
1919 strbuf_addstr(&msgbuf, "Revert \"");
1920 strbuf_addstr(&msgbuf, msg.subject);
1921 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1922 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1924 if (commit->parents && commit->parents->next) {
1925 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1926 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1928 strbuf_addstr(&msgbuf, ".\n");
1933 base_label = msg.parent_label;
1935 next_label = msg.label;
1937 /* Append the commit log message to msgbuf. */
1938 if (find_commit_subject(msg.message, &p))
1939 strbuf_addstr(&msgbuf, p);
1941 if (opts->record_origin) {
1942 strbuf_complete_line(&msgbuf);
1943 if (!has_conforming_footer(&msgbuf, NULL, 0))
1944 strbuf_addch(&msgbuf, '\n');
1945 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1946 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1947 strbuf_addstr(&msgbuf, ")\n");
1949 if (!is_fixup(command))
1950 author = get_author(msg.message);
1953 if (command == TODO_REWORD)
1955 else if (is_fixup(command)) {
1956 if (update_squash_messages(r, command, commit, opts))
1960 msg_file = rebase_path_squash_msg();
1961 else if (file_exists(rebase_path_fixup_msg())) {
1962 flags |= CLEANUP_MSG;
1963 msg_file = rebase_path_fixup_msg();
1965 const char *dest = git_path_squash_msg(r);
1967 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1968 return error(_("could not rename '%s' to '%s'"),
1969 rebase_path_squash_msg(), dest);
1970 unlink(git_path_merge_msg(r));
1976 if (opts->signoff && !is_fixup(command))
1977 append_signoff(&msgbuf, 0, 0);
1979 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1981 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1982 res = do_recursive_merge(r, base, next, base_label, next_label,
1983 &head, &msgbuf, opts);
1987 res |= write_message(msgbuf.buf, msgbuf.len,
1988 git_path_merge_msg(r), 0);
1990 struct commit_list *common = NULL;
1991 struct commit_list *remotes = NULL;
1993 res = write_message(msgbuf.buf, msgbuf.len,
1994 git_path_merge_msg(r), 0);
1996 commit_list_insert(base, &common);
1997 commit_list_insert(next, &remotes);
1998 res |= try_merge_command(r, opts->strategy,
1999 opts->xopts_nr, (const char **)opts->xopts,
2000 common, oid_to_hex(&head), remotes);
2001 free_commit_list(common);
2002 free_commit_list(remotes);
2004 strbuf_release(&msgbuf);
2007 * If the merge was clean or if it failed due to conflict, we write
2008 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2009 * However, if the merge did not even start, then we don't want to
2012 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
2013 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2014 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2016 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2017 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2018 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2022 error(command == TODO_REVERT
2023 ? _("could not revert %s... %s")
2024 : _("could not apply %s... %s"),
2025 short_commit_name(commit), msg.subject);
2026 print_advice(r, res == 1, opts);
2027 repo_rerere(r, opts->allow_rerere_auto);
2031 allow = allow_empty(r, opts, commit);
2036 flags |= ALLOW_EMPTY;
2037 if (!opts->no_commit) {
2038 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2039 res = do_commit(r, msg_file, author, opts, flags);
2041 res = error(_("unable to parse commit author"));
2042 *check_todo = !!(flags & EDIT_MSG);
2043 if (!res && reword) {
2045 res = run_git_commit(r, NULL, opts, EDIT_MSG |
2046 VERIFY_MSG | AMEND_MSG |
2047 (flags & ALLOW_EMPTY));
2053 if (!res && final_fixup) {
2054 unlink(rebase_path_fixup_msg());
2055 unlink(rebase_path_squash_msg());
2056 unlink(rebase_path_current_fixups());
2057 strbuf_reset(&opts->current_fixups);
2058 opts->current_fixup_count = 0;
2062 free_message(commit, &msg);
2064 update_abort_safety_file();
2069 static int prepare_revs(struct replay_opts *opts)
2072 * picking (but not reverting) ranges (but not individual revisions)
2073 * should be done in reverse
2075 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2076 opts->revs->reverse ^= 1;
2078 if (prepare_revision_walk(opts->revs))
2079 return error(_("revision walk setup failed"));
2084 static int read_and_refresh_cache(struct repository *r,
2085 struct replay_opts *opts)
2087 struct lock_file index_lock = LOCK_INIT;
2088 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2089 if (repo_read_index(r) < 0) {
2090 rollback_lock_file(&index_lock);
2091 return error(_("git %s: failed to read the index"),
2092 _(action_name(opts)));
2094 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2095 if (index_fd >= 0) {
2096 if (write_locked_index(r->index, &index_lock,
2097 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2098 return error(_("git %s: failed to refresh the index"),
2099 _(action_name(opts)));
2105 enum todo_item_flags {
2106 TODO_EDIT_MERGE_MSG = 1
2109 void todo_list_release(struct todo_list *todo_list)
2111 strbuf_release(&todo_list->buf);
2112 FREE_AND_NULL(todo_list->items);
2113 todo_list->nr = todo_list->alloc = 0;
2116 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2118 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2119 return todo_list->items + todo_list->nr++;
2122 const char *todo_item_get_arg(struct todo_list *todo_list,
2123 struct todo_item *item)
2125 return todo_list->buf.buf + item->arg_offset;
2128 static int parse_insn_line(struct repository *r, struct todo_item *item,
2129 const char *buf, const char *bol, char *eol)
2131 struct object_id commit_oid;
2132 char *end_of_object_name;
2133 int i, saved, status, padding;
2138 bol += strspn(bol, " \t");
2140 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2141 item->command = TODO_COMMENT;
2142 item->commit = NULL;
2143 item->arg_offset = bol - buf;
2144 item->arg_len = eol - bol;
2148 for (i = 0; i < TODO_COMMENT; i++)
2149 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2152 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2153 *bol == todo_command_info[i].c) {
2158 if (i >= TODO_COMMENT)
2161 /* Eat up extra spaces/ tabs before object name */
2162 padding = strspn(bol, " \t");
2165 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2167 return error(_("%s does not accept arguments: '%s'"),
2168 command_to_string(item->command), bol);
2169 item->commit = NULL;
2170 item->arg_offset = bol - buf;
2171 item->arg_len = eol - bol;
2176 return error(_("missing arguments for %s"),
2177 command_to_string(item->command));
2179 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2180 item->command == TODO_RESET) {
2181 item->commit = NULL;
2182 item->arg_offset = bol - buf;
2183 item->arg_len = (int)(eol - bol);
2187 if (item->command == TODO_MERGE) {
2188 if (skip_prefix(bol, "-C", &bol))
2189 bol += strspn(bol, " \t");
2190 else if (skip_prefix(bol, "-c", &bol)) {
2191 bol += strspn(bol, " \t");
2192 item->flags |= TODO_EDIT_MERGE_MSG;
2194 item->flags |= TODO_EDIT_MERGE_MSG;
2195 item->commit = NULL;
2196 item->arg_offset = bol - buf;
2197 item->arg_len = (int)(eol - bol);
2202 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2203 saved = *end_of_object_name;
2204 *end_of_object_name = '\0';
2205 status = get_oid(bol, &commit_oid);
2206 *end_of_object_name = saved;
2208 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2209 item->arg_offset = bol - buf;
2210 item->arg_len = (int)(eol - bol);
2213 return error(_("could not parse '%.*s'"),
2214 (int)(end_of_object_name - bol), bol);
2216 item->commit = lookup_commit_reference(r, &commit_oid);
2217 return !item->commit;
2220 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2222 struct todo_item item;
2224 const char *todo_file;
2225 struct strbuf buf = STRBUF_INIT;
2228 todo_file = git_path_todo_file();
2229 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2230 if (errno == ENOENT)
2233 return error_errno("unable to open '%s'", todo_file);
2235 eol = strchrnul(buf.buf, '\n');
2236 if (buf.buf != eol && eol[-1] == '\r')
2237 eol--; /* strip Carriage Return */
2238 if (parse_insn_line(r, &item, buf.buf, buf.buf, eol))
2240 if (item.command == TODO_PICK)
2241 *action = REPLAY_PICK;
2242 else if (item.command == TODO_REVERT)
2243 *action = REPLAY_REVERT;
2250 strbuf_release(&buf);
2255 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2256 struct todo_list *todo_list)
2258 struct todo_item *item;
2259 char *p = buf, *next_p;
2260 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2262 todo_list->current = todo_list->nr = 0;
2264 for (i = 1; *p; i++, p = next_p) {
2265 char *eol = strchrnul(p, '\n');
2267 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2269 if (p != eol && eol[-1] == '\r')
2270 eol--; /* strip Carriage Return */
2272 item = append_new_todo(todo_list);
2273 item->offset_in_buf = p - todo_list->buf.buf;
2274 if (parse_insn_line(r, item, buf, p, eol)) {
2275 res = error(_("invalid line %d: %.*s"),
2276 i, (int)(eol - p), p);
2277 item->command = TODO_COMMENT + 1;
2278 item->arg_offset = p - buf;
2279 item->arg_len = (int)(eol - p);
2280 item->commit = NULL;
2285 else if (is_fixup(item->command))
2286 return error(_("cannot '%s' without a previous commit"),
2287 command_to_string(item->command));
2288 else if (!is_noop(item->command))
2295 static int count_commands(struct todo_list *todo_list)
2299 for (i = 0; i < todo_list->nr; i++)
2300 if (todo_list->items[i].command != TODO_COMMENT)
2306 static int get_item_line_offset(struct todo_list *todo_list, int index)
2308 return index < todo_list->nr ?
2309 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2312 static const char *get_item_line(struct todo_list *todo_list, int index)
2314 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2317 static int get_item_line_length(struct todo_list *todo_list, int index)
2319 return get_item_line_offset(todo_list, index + 1)
2320 - get_item_line_offset(todo_list, index);
2323 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2328 fd = open(path, O_RDONLY);
2330 return error_errno(_("could not open '%s'"), path);
2331 len = strbuf_read(sb, fd, 0);
2334 return error(_("could not read '%s'."), path);
2338 static int have_finished_the_last_pick(void)
2340 struct strbuf buf = STRBUF_INIT;
2342 const char *todo_path = git_path_todo_file();
2345 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2346 if (errno == ENOENT) {
2349 error_errno("unable to open '%s'", todo_path);
2353 /* If there is only one line then we are done */
2354 eol = strchr(buf.buf, '\n');
2355 if (!eol || !eol[1])
2358 strbuf_release(&buf);
2363 void sequencer_post_commit_cleanup(struct repository *r)
2365 struct replay_opts opts = REPLAY_OPTS_INIT;
2366 int need_cleanup = 0;
2368 if (file_exists(git_path_cherry_pick_head(r))) {
2369 unlink(git_path_cherry_pick_head(r));
2370 opts.action = REPLAY_PICK;
2374 if (file_exists(git_path_revert_head(r))) {
2375 unlink(git_path_revert_head(r));
2376 opts.action = REPLAY_REVERT;
2383 if (!have_finished_the_last_pick())
2386 sequencer_remove_state(&opts);
2389 static int read_populate_todo(struct repository *r,
2390 struct todo_list *todo_list,
2391 struct replay_opts *opts)
2394 const char *todo_file = get_todo_path(opts);
2397 strbuf_reset(&todo_list->buf);
2398 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2401 res = stat(todo_file, &st);
2403 return error(_("could not stat '%s'"), todo_file);
2404 fill_stat_data(&todo_list->stat, &st);
2406 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2408 if (is_rebase_i(opts))
2409 return error(_("please fix this using "
2410 "'git rebase --edit-todo'."));
2411 return error(_("unusable instruction sheet: '%s'"), todo_file);
2414 if (!todo_list->nr &&
2415 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2416 return error(_("no commits parsed."));
2418 if (!is_rebase_i(opts)) {
2419 enum todo_command valid =
2420 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2423 for (i = 0; i < todo_list->nr; i++)
2424 if (valid == todo_list->items[i].command)
2426 else if (valid == TODO_PICK)
2427 return error(_("cannot cherry-pick during a revert."));
2429 return error(_("cannot revert during a cherry-pick."));
2432 if (is_rebase_i(opts)) {
2433 struct todo_list done = TODO_LIST_INIT;
2434 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2436 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2437 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2438 todo_list->done_nr = count_commands(&done);
2440 todo_list->done_nr = 0;
2442 todo_list->total_nr = todo_list->done_nr
2443 + count_commands(todo_list);
2444 todo_list_release(&done);
2447 fprintf(f, "%d\n", todo_list->total_nr);
2455 static int git_config_string_dup(char **dest,
2456 const char *var, const char *value)
2459 return config_error_nonbool(var);
2461 *dest = xstrdup(value);
2465 static int populate_opts_cb(const char *key, const char *value, void *data)
2467 struct replay_opts *opts = data;
2472 else if (!strcmp(key, "options.no-commit"))
2473 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2474 else if (!strcmp(key, "options.edit"))
2475 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2476 else if (!strcmp(key, "options.allow-empty"))
2478 git_config_bool_or_int(key, value, &error_flag);
2479 else if (!strcmp(key, "options.allow-empty-message"))
2480 opts->allow_empty_message =
2481 git_config_bool_or_int(key, value, &error_flag);
2482 else if (!strcmp(key, "options.keep-redundant-commits"))
2483 opts->keep_redundant_commits =
2484 git_config_bool_or_int(key, value, &error_flag);
2485 else if (!strcmp(key, "options.signoff"))
2486 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2487 else if (!strcmp(key, "options.record-origin"))
2488 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2489 else if (!strcmp(key, "options.allow-ff"))
2490 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2491 else if (!strcmp(key, "options.mainline"))
2492 opts->mainline = git_config_int(key, value);
2493 else if (!strcmp(key, "options.strategy"))
2494 git_config_string_dup(&opts->strategy, key, value);
2495 else if (!strcmp(key, "options.gpg-sign"))
2496 git_config_string_dup(&opts->gpg_sign, key, value);
2497 else if (!strcmp(key, "options.strategy-option")) {
2498 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2499 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2500 } else if (!strcmp(key, "options.allow-rerere-auto"))
2501 opts->allow_rerere_auto =
2502 git_config_bool_or_int(key, value, &error_flag) ?
2503 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2504 else if (!strcmp(key, "options.default-msg-cleanup")) {
2505 opts->explicit_cleanup = 1;
2506 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2508 return error(_("invalid key: %s"), key);
2511 return error(_("invalid value for %s: %s"), key, value);
2516 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2519 char *strategy_opts_string = raw_opts;
2521 if (*strategy_opts_string == ' ')
2522 strategy_opts_string++;
2524 opts->xopts_nr = split_cmdline(strategy_opts_string,
2525 (const char ***)&opts->xopts);
2526 for (i = 0; i < opts->xopts_nr; i++) {
2527 const char *arg = opts->xopts[i];
2529 skip_prefix(arg, "--", &arg);
2530 opts->xopts[i] = xstrdup(arg);
2534 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2537 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2539 opts->strategy = strbuf_detach(buf, NULL);
2540 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2543 parse_strategy_opts(opts, buf->buf);
2546 static int read_populate_opts(struct replay_opts *opts)
2548 if (is_rebase_i(opts)) {
2549 struct strbuf buf = STRBUF_INIT;
2551 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2552 if (!starts_with(buf.buf, "-S"))
2555 free(opts->gpg_sign);
2556 opts->gpg_sign = xstrdup(buf.buf + 2);
2561 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2562 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2563 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2564 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2565 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2569 if (file_exists(rebase_path_verbose()))
2572 if (file_exists(rebase_path_quiet()))
2575 if (file_exists(rebase_path_signoff())) {
2580 if (file_exists(rebase_path_cdate_is_adate())) {
2582 opts->committer_date_is_author_date = 1;
2585 if (file_exists(rebase_path_ignore_date())) {
2587 opts->ignore_date = 1;
2590 if (file_exists(rebase_path_reschedule_failed_exec()))
2591 opts->reschedule_failed_exec = 1;
2593 read_strategy_opts(opts, &buf);
2594 strbuf_release(&buf);
2596 if (read_oneliner(&opts->current_fixups,
2597 rebase_path_current_fixups(), 1)) {
2598 const char *p = opts->current_fixups.buf;
2599 opts->current_fixup_count = 1;
2600 while ((p = strchr(p, '\n'))) {
2601 opts->current_fixup_count++;
2606 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2607 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2608 return error(_("unusable squash-onto"));
2609 opts->have_squash_onto = 1;
2615 if (!file_exists(git_path_opts_file()))
2618 * The function git_parse_source(), called from git_config_from_file(),
2619 * may die() in case of a syntactically incorrect file. We do not care
2620 * about this case, though, because we wrote that file ourselves, so we
2621 * are pretty certain that it is syntactically correct.
2623 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2624 return error(_("malformed options sheet: '%s'"),
2625 git_path_opts_file());
2629 static void write_strategy_opts(struct replay_opts *opts)
2632 struct strbuf buf = STRBUF_INIT;
2634 for (i = 0; i < opts->xopts_nr; ++i)
2635 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2637 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2638 strbuf_release(&buf);
2641 int write_basic_state(struct replay_opts *opts, const char *head_name,
2642 struct commit *onto, const char *orig_head)
2644 const char *quiet = getenv("GIT_QUIET");
2647 write_file(rebase_path_head_name(), "%s\n", head_name);
2649 write_file(rebase_path_onto(), "%s\n",
2650 oid_to_hex(&onto->object.oid));
2652 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2655 write_file(rebase_path_quiet(), "%s\n", quiet);
2657 write_file(rebase_path_verbose(), "%s", "");
2659 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2660 if (opts->xopts_nr > 0)
2661 write_strategy_opts(opts);
2663 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2664 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2665 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2666 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2669 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2671 write_file(rebase_path_signoff(), "--signoff\n");
2672 if (opts->committer_date_is_author_date)
2673 write_file(rebase_path_cdate_is_adate(), "%s", "");
2674 if (opts->ignore_date)
2675 write_file(rebase_path_ignore_date(), "%s", "");
2676 if (opts->reschedule_failed_exec)
2677 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2682 static int walk_revs_populate_todo(struct todo_list *todo_list,
2683 struct replay_opts *opts)
2685 enum todo_command command = opts->action == REPLAY_PICK ?
2686 TODO_PICK : TODO_REVERT;
2687 const char *command_string = todo_command_info[command].str;
2688 struct commit *commit;
2690 if (prepare_revs(opts))
2693 while ((commit = get_revision(opts->revs))) {
2694 struct todo_item *item = append_new_todo(todo_list);
2695 const char *commit_buffer = get_commit_buffer(commit, NULL);
2696 const char *subject;
2699 item->command = command;
2700 item->commit = commit;
2701 item->arg_offset = 0;
2703 item->offset_in_buf = todo_list->buf.len;
2704 subject_len = find_commit_subject(commit_buffer, &subject);
2705 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2706 short_commit_name(commit), subject_len, subject);
2707 unuse_commit_buffer(commit, commit_buffer);
2711 return error(_("empty commit set passed"));
2716 static int create_seq_dir(void)
2718 if (file_exists(git_path_seq_dir())) {
2719 error(_("a cherry-pick or revert is already in progress"));
2720 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2722 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2723 return error_errno(_("could not create sequencer directory '%s'"),
2724 git_path_seq_dir());
2728 static int save_head(const char *head)
2730 struct lock_file head_lock = LOCK_INIT;
2731 struct strbuf buf = STRBUF_INIT;
2735 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2737 return error_errno(_("could not lock HEAD"));
2738 strbuf_addf(&buf, "%s\n", head);
2739 written = write_in_full(fd, buf.buf, buf.len);
2740 strbuf_release(&buf);
2742 error_errno(_("could not write to '%s'"), git_path_head_file());
2743 rollback_lock_file(&head_lock);
2746 if (commit_lock_file(&head_lock) < 0)
2747 return error(_("failed to finalize '%s'"), git_path_head_file());
2751 static int rollback_is_safe(void)
2753 struct strbuf sb = STRBUF_INIT;
2754 struct object_id expected_head, actual_head;
2756 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2758 if (get_oid_hex(sb.buf, &expected_head)) {
2759 strbuf_release(&sb);
2760 die(_("could not parse %s"), git_path_abort_safety_file());
2762 strbuf_release(&sb);
2764 else if (errno == ENOENT)
2765 oidclr(&expected_head);
2767 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2769 if (get_oid("HEAD", &actual_head))
2770 oidclr(&actual_head);
2772 return oideq(&actual_head, &expected_head);
2775 static int reset_for_rollback(const struct object_id *oid)
2777 const char *argv[4]; /* reset --merge <arg> + NULL */
2780 argv[1] = "--merge";
2781 argv[2] = oid_to_hex(oid);
2783 return run_command_v_opt(argv, RUN_GIT_CMD);
2786 static int rollback_single_pick(struct repository *r)
2788 struct object_id head_oid;
2790 if (!file_exists(git_path_cherry_pick_head(r)) &&
2791 !file_exists(git_path_revert_head(r)))
2792 return error(_("no cherry-pick or revert in progress"));
2793 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2794 return error(_("cannot resolve HEAD"));
2795 if (is_null_oid(&head_oid))
2796 return error(_("cannot abort from a branch yet to be born"));
2797 return reset_for_rollback(&head_oid);
2800 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2803 struct object_id oid;
2804 struct strbuf buf = STRBUF_INIT;
2807 f = fopen(git_path_head_file(), "r");
2808 if (!f && errno == ENOENT) {
2810 * There is no multiple-cherry-pick in progress.
2811 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2812 * a single-cherry-pick in progress, abort that.
2814 return rollback_single_pick(r);
2817 return error_errno(_("cannot open '%s'"), git_path_head_file());
2818 if (strbuf_getline_lf(&buf, f)) {
2819 error(_("cannot read '%s': %s"), git_path_head_file(),
2820 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2825 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2826 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2827 git_path_head_file());
2830 if (is_null_oid(&oid)) {
2831 error(_("cannot abort from a branch yet to be born"));
2835 if (!rollback_is_safe()) {
2836 /* Do not error, just do not rollback */
2837 warning(_("You seem to have moved HEAD. "
2838 "Not rewinding, check your HEAD!"));
2840 if (reset_for_rollback(&oid))
2842 strbuf_release(&buf);
2843 return sequencer_remove_state(opts);
2845 strbuf_release(&buf);
2849 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2851 struct lock_file todo_lock = LOCK_INIT;
2852 const char *todo_path = get_todo_path(opts);
2853 int next = todo_list->current, offset, fd;
2856 * rebase -i writes "git-rebase-todo" without the currently executing
2857 * command, appending it to "done" instead.
2859 if (is_rebase_i(opts))
2862 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2864 return error_errno(_("could not lock '%s'"), todo_path);
2865 offset = get_item_line_offset(todo_list, next);
2866 if (write_in_full(fd, todo_list->buf.buf + offset,
2867 todo_list->buf.len - offset) < 0)
2868 return error_errno(_("could not write to '%s'"), todo_path);
2869 if (commit_lock_file(&todo_lock) < 0)
2870 return error(_("failed to finalize '%s'"), todo_path);
2872 if (is_rebase_i(opts) && next > 0) {
2873 const char *done = rebase_path_done();
2874 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2879 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2880 get_item_line_length(todo_list, next - 1))
2882 ret = error_errno(_("could not write to '%s'"), done);
2884 ret = error_errno(_("failed to finalize '%s'"), done);
2890 static int save_opts(struct replay_opts *opts)
2892 const char *opts_file = git_path_opts_file();
2895 if (opts->no_commit)
2896 res |= git_config_set_in_file_gently(opts_file,
2897 "options.no-commit", "true");
2899 res |= git_config_set_in_file_gently(opts_file,
2900 "options.edit", "true");
2901 if (opts->allow_empty)
2902 res |= git_config_set_in_file_gently(opts_file,
2903 "options.allow-empty", "true");
2904 if (opts->allow_empty_message)
2905 res |= git_config_set_in_file_gently(opts_file,
2906 "options.allow-empty-message", "true");
2907 if (opts->keep_redundant_commits)
2908 res |= git_config_set_in_file_gently(opts_file,
2909 "options.keep-redundant-commits", "true");
2911 res |= git_config_set_in_file_gently(opts_file,
2912 "options.signoff", "true");
2913 if (opts->record_origin)
2914 res |= git_config_set_in_file_gently(opts_file,
2915 "options.record-origin", "true");
2917 res |= git_config_set_in_file_gently(opts_file,
2918 "options.allow-ff", "true");
2919 if (opts->mainline) {
2920 struct strbuf buf = STRBUF_INIT;
2921 strbuf_addf(&buf, "%d", opts->mainline);
2922 res |= git_config_set_in_file_gently(opts_file,
2923 "options.mainline", buf.buf);
2924 strbuf_release(&buf);
2927 res |= git_config_set_in_file_gently(opts_file,
2928 "options.strategy", opts->strategy);
2930 res |= git_config_set_in_file_gently(opts_file,
2931 "options.gpg-sign", opts->gpg_sign);
2934 for (i = 0; i < opts->xopts_nr; i++)
2935 res |= git_config_set_multivar_in_file_gently(opts_file,
2936 "options.strategy-option",
2937 opts->xopts[i], "^$", 0);
2939 if (opts->allow_rerere_auto)
2940 res |= git_config_set_in_file_gently(opts_file,
2941 "options.allow-rerere-auto",
2942 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2945 if (opts->explicit_cleanup)
2946 res |= git_config_set_in_file_gently(opts_file,
2947 "options.default-msg-cleanup",
2948 describe_cleanup_mode(opts->default_msg_cleanup));
2952 static int make_patch(struct repository *r,
2953 struct commit *commit,
2954 struct replay_opts *opts)
2956 struct strbuf buf = STRBUF_INIT;
2957 struct rev_info log_tree_opt;
2958 const char *subject, *p;
2961 p = short_commit_name(commit);
2962 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2964 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2965 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2966 res |= error(_("could not update %s"), "REBASE_HEAD");
2968 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2969 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2970 repo_init_revisions(r, &log_tree_opt, NULL);
2971 log_tree_opt.abbrev = 0;
2972 log_tree_opt.diff = 1;
2973 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2974 log_tree_opt.disable_stdin = 1;
2975 log_tree_opt.no_commit_id = 1;
2976 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2977 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2978 if (!log_tree_opt.diffopt.file)
2979 res |= error_errno(_("could not open '%s'"), buf.buf);
2981 res |= log_tree_commit(&log_tree_opt, commit);
2982 fclose(log_tree_opt.diffopt.file);
2986 strbuf_addf(&buf, "%s/message", get_dir(opts));
2987 if (!file_exists(buf.buf)) {
2988 const char *commit_buffer = get_commit_buffer(commit, NULL);
2989 find_commit_subject(commit_buffer, &subject);
2990 res |= write_message(subject, strlen(subject), buf.buf, 1);
2991 unuse_commit_buffer(commit, commit_buffer);
2993 strbuf_release(&buf);
2998 static int intend_to_amend(void)
3000 struct object_id head;
3003 if (get_oid("HEAD", &head))
3004 return error(_("cannot read HEAD"));
3006 p = oid_to_hex(&head);
3007 return write_message(p, strlen(p), rebase_path_amend(), 1);
3010 static int error_with_patch(struct repository *r,
3011 struct commit *commit,
3012 const char *subject, int subject_len,
3013 struct replay_opts *opts,
3014 int exit_code, int to_amend)
3017 if (make_patch(r, commit, opts))
3019 } else if (copy_file(rebase_path_message(),
3020 git_path_merge_msg(r), 0666))
3021 return error(_("unable to copy '%s' to '%s'"),
3022 git_path_merge_msg(r), rebase_path_message());
3025 if (intend_to_amend())
3029 _("You can amend the commit now, with\n"
3031 " git commit --amend %s\n"
3033 "Once you are satisfied with your changes, run\n"
3035 " git rebase --continue\n"),
3036 gpg_sign_opt_quoted(opts));
3037 } else if (exit_code) {
3039 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3040 short_commit_name(commit), subject_len, subject);
3043 * We don't have the hash of the parent so
3044 * just print the line from the todo file.
3046 fprintf_ln(stderr, _("Could not merge %.*s"),
3047 subject_len, subject);
3053 static int error_failed_squash(struct repository *r,
3054 struct commit *commit,
3055 struct replay_opts *opts,
3057 const char *subject)
3059 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3060 return error(_("could not copy '%s' to '%s'"),
3061 rebase_path_squash_msg(), rebase_path_message());
3062 unlink(git_path_merge_msg(r));
3063 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3064 return error(_("could not copy '%s' to '%s'"),
3065 rebase_path_message(),
3066 git_path_merge_msg(r));
3067 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3070 static int do_exec(struct repository *r, const char *command_line)
3072 struct argv_array child_env = ARGV_ARRAY_INIT;
3073 const char *child_argv[] = { NULL, NULL };
3076 fprintf(stderr, "Executing: %s\n", command_line);
3077 child_argv[0] = command_line;
3078 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3079 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3080 absolute_path(get_git_work_tree()));
3081 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3084 /* force re-reading of the cache */
3085 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3086 return error(_("could not read index"));
3088 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3091 warning(_("execution failed: %s\n%s"
3092 "You can fix the problem, and then run\n"
3094 " git rebase --continue\n"
3097 dirty ? N_("and made changes to the index and/or the "
3098 "working tree\n") : "");
3100 /* command not found */
3103 warning(_("execution succeeded: %s\nbut "
3104 "left changes to the index and/or the working tree\n"
3105 "Commit or stash your changes, and then run\n"
3107 " git rebase --continue\n"
3108 "\n"), command_line);
3112 argv_array_clear(&child_env);
3117 static int safe_append(const char *filename, const char *fmt, ...)
3120 struct lock_file lock = LOCK_INIT;
3121 int fd = hold_lock_file_for_update(&lock, filename,
3122 LOCK_REPORT_ON_ERROR);
3123 struct strbuf buf = STRBUF_INIT;
3128 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3129 error_errno(_("could not read '%s'"), filename);
3130 rollback_lock_file(&lock);
3133 strbuf_complete(&buf, '\n');
3135 strbuf_vaddf(&buf, fmt, ap);
3138 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3139 error_errno(_("could not write to '%s'"), filename);
3140 strbuf_release(&buf);
3141 rollback_lock_file(&lock);
3144 if (commit_lock_file(&lock) < 0) {
3145 strbuf_release(&buf);
3146 rollback_lock_file(&lock);
3147 return error(_("failed to finalize '%s'"), filename);
3150 strbuf_release(&buf);
3154 static int do_label(struct repository *r, const char *name, int len)
3156 struct ref_store *refs = get_main_ref_store(r);
3157 struct ref_transaction *transaction;
3158 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3159 struct strbuf msg = STRBUF_INIT;
3161 struct object_id head_oid;
3163 if (len == 1 && *name == '#')
3164 return error(_("illegal label name: '%.*s'"), len, name);
3166 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3167 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
3169 transaction = ref_store_transaction_begin(refs, &err);
3171 error("%s", err.buf);
3173 } else if (get_oid("HEAD", &head_oid)) {
3174 error(_("could not read HEAD"));
3176 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3177 NULL, 0, msg.buf, &err) < 0 ||
3178 ref_transaction_commit(transaction, &err)) {
3179 error("%s", err.buf);
3182 ref_transaction_free(transaction);
3183 strbuf_release(&err);
3184 strbuf_release(&msg);
3187 ret = safe_append(rebase_path_refs_to_delete(),
3188 "%s\n", ref_name.buf);
3189 strbuf_release(&ref_name);
3194 static const char *reflog_message(struct replay_opts *opts,
3195 const char *sub_action, const char *fmt, ...);
3197 static int do_reset(struct repository *r,
3198 const char *name, int len,
3199 struct replay_opts *opts)
3201 struct strbuf ref_name = STRBUF_INIT;
3202 struct object_id oid;
3203 struct lock_file lock = LOCK_INIT;
3204 struct tree_desc desc;
3206 struct unpack_trees_options unpack_tree_opts;
3209 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3212 if (len == 10 && !strncmp("[new root]", name, len)) {
3213 if (!opts->have_squash_onto) {
3215 if (commit_tree("", 0, the_hash_algo->empty_tree,
3216 NULL, &opts->squash_onto,
3218 return error(_("writing fake root commit"));
3219 opts->have_squash_onto = 1;
3220 hex = oid_to_hex(&opts->squash_onto);
3221 if (write_message(hex, strlen(hex),
3222 rebase_path_squash_onto(), 0))
3223 return error(_("writing squash-onto"));
3225 oidcpy(&oid, &opts->squash_onto);
3229 /* Determine the length of the label */
3230 for (i = 0; i < len; i++)
3231 if (isspace(name[i]))
3235 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3236 if (get_oid(ref_name.buf, &oid) &&
3237 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3238 error(_("could not read '%s'"), ref_name.buf);
3239 rollback_lock_file(&lock);
3240 strbuf_release(&ref_name);
3245 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3246 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3247 unpack_tree_opts.head_idx = 1;
3248 unpack_tree_opts.src_index = r->index;
3249 unpack_tree_opts.dst_index = r->index;
3250 unpack_tree_opts.fn = oneway_merge;
3251 unpack_tree_opts.merge = 1;
3252 unpack_tree_opts.update = 1;
3254 if (repo_read_index_unmerged(r)) {
3255 rollback_lock_file(&lock);
3256 strbuf_release(&ref_name);
3257 return error_resolve_conflict(_(action_name(opts)));
3260 if (!fill_tree_descriptor(&desc, &oid)) {
3261 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3262 rollback_lock_file(&lock);
3263 free((void *)desc.buffer);
3264 strbuf_release(&ref_name);
3268 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3269 rollback_lock_file(&lock);
3270 free((void *)desc.buffer);
3271 strbuf_release(&ref_name);
3275 tree = parse_tree_indirect(&oid);
3276 prime_cache_tree(r, r->index, tree);
3278 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3279 ret = error(_("could not write index"));
3280 free((void *)desc.buffer);
3283 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3284 len, name), "HEAD", &oid,
3285 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3287 strbuf_release(&ref_name);
3291 static struct commit *lookup_label(const char *label, int len,
3294 struct commit *commit;
3297 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3298 commit = lookup_commit_reference_by_name(buf->buf);
3300 /* fall back to non-rewritten ref or commit */
3301 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3302 commit = lookup_commit_reference_by_name(buf->buf);
3306 error(_("could not resolve '%s'"), buf->buf);
3311 static int do_merge(struct repository *r,
3312 struct commit *commit,
3313 const char *arg, int arg_len,
3314 int flags, struct replay_opts *opts)
3316 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3317 EDIT_MSG | VERIFY_MSG : 0;
3318 struct strbuf ref_name = STRBUF_INIT;
3319 struct commit *head_commit, *merge_commit, *i;
3320 struct commit_list *bases, *j, *reversed = NULL;
3321 struct commit_list *to_merge = NULL, **tail = &to_merge;
3322 struct merge_options o;
3323 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3324 static struct lock_file lock;
3327 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3332 head_commit = lookup_commit_reference_by_name("HEAD");
3334 ret = error(_("cannot merge without a current revision"));
3339 * For octopus merges, the arg starts with the list of revisions to be
3340 * merged. The list is optionally followed by '#' and the oneline.
3342 merge_arg_len = oneline_offset = arg_len;
3343 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3346 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3347 p += 1 + strspn(p + 1, " \t\n");
3348 oneline_offset = p - arg;
3351 k = strcspn(p, " \t\n");
3354 merge_commit = lookup_label(p, k, &ref_name);
3355 if (!merge_commit) {
3356 ret = error(_("unable to parse '%.*s'"), k, p);
3359 tail = &commit_list_insert(merge_commit, tail)->next;
3361 merge_arg_len = p - arg;
3365 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3369 if (opts->have_squash_onto &&
3370 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3372 * When the user tells us to "merge" something into a
3373 * "[new root]", let's simply fast-forward to the merge head.
3375 rollback_lock_file(&lock);
3377 ret = error(_("octopus merge cannot be executed on "
3378 "top of a [new root]"));
3380 ret = fast_forward_to(r, &to_merge->item->object.oid,
3381 &head_commit->object.oid, 0,
3387 const char *message = get_commit_buffer(commit, NULL);
3392 ret = error(_("could not get commit message of '%s'"),
3393 oid_to_hex(&commit->object.oid));
3396 write_author_script(message);
3397 find_commit_subject(message, &body);
3399 ret = write_message(body, len, git_path_merge_msg(r), 0);
3400 unuse_commit_buffer(commit, message);
3402 error_errno(_("could not write '%s'"),
3403 git_path_merge_msg(r));
3407 struct strbuf buf = STRBUF_INIT;
3410 strbuf_addf(&buf, "author %s", git_author_info(0));
3411 write_author_script(buf.buf);
3414 if (oneline_offset < arg_len) {
3415 p = arg + oneline_offset;
3416 len = arg_len - oneline_offset;
3418 strbuf_addf(&buf, "Merge %s '%.*s'",
3419 to_merge->next ? "branches" : "branch",
3420 merge_arg_len, arg);
3425 ret = write_message(p, len, git_path_merge_msg(r), 0);
3426 strbuf_release(&buf);
3428 error_errno(_("could not write '%s'"),
3429 git_path_merge_msg(r));
3435 * If HEAD is not identical to the first parent of the original merge
3436 * commit, we cannot fast-forward.
3438 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3439 oideq(&commit->parents->item->object.oid,
3440 &head_commit->object.oid);
3443 * If any merge head is different from the original one, we cannot
3446 if (can_fast_forward) {
3447 struct commit_list *p = commit->parents->next;
3449 for (j = to_merge; j && p; j = j->next, p = p->next)
3450 if (!oideq(&j->item->object.oid,
3451 &p->item->object.oid)) {
3452 can_fast_forward = 0;
3456 * If the number of merge heads differs from the original merge
3457 * commit, we cannot fast-forward.
3460 can_fast_forward = 0;
3463 if (can_fast_forward) {
3464 rollback_lock_file(&lock);
3465 ret = fast_forward_to(r, &commit->object.oid,
3466 &head_commit->object.oid, 0, opts);
3470 if (to_merge->next) {
3472 struct child_process cmd = CHILD_PROCESS_INIT;
3474 if (read_env_script(&cmd.env_array)) {
3475 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3477 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3482 argv_array_push(&cmd.args, "merge");
3483 argv_array_push(&cmd.args, "-s");
3484 argv_array_push(&cmd.args, "octopus");
3485 argv_array_push(&cmd.args, "--no-edit");
3486 argv_array_push(&cmd.args, "--no-ff");
3487 argv_array_push(&cmd.args, "--no-log");
3488 argv_array_push(&cmd.args, "--no-stat");
3489 argv_array_push(&cmd.args, "-F");
3490 argv_array_push(&cmd.args, git_path_merge_msg(r));
3492 argv_array_push(&cmd.args, opts->gpg_sign);
3493 if (opts->ignore_date)
3494 push_dates(&cmd, opts->committer_date_is_author_date);
3496 /* Add the tips to be merged */
3497 for (j = to_merge; j; j = j->next)
3498 argv_array_push(&cmd.args,
3499 oid_to_hex(&j->item->object.oid));
3501 strbuf_release(&ref_name);
3502 unlink(git_path_cherry_pick_head(r));
3503 rollback_lock_file(&lock);
3505 rollback_lock_file(&lock);
3506 ret = run_command(&cmd);
3508 /* force re-reading of the cache */
3509 if (!ret && (discard_index(r->index) < 0 ||
3510 repo_read_index(r) < 0))
3511 ret = error(_("could not read index"));
3515 merge_commit = to_merge->item;
3516 bases = get_merge_bases(head_commit, merge_commit);
3517 if (bases && oideq(&merge_commit->object.oid,
3518 &bases->item->object.oid)) {
3520 /* skip merging an ancestor of HEAD */
3524 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3525 git_path_merge_head(r), 0);
3526 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3528 for (j = bases; j; j = j->next)
3529 commit_list_insert(j->item, &reversed);
3530 free_commit_list(bases);
3533 init_merge_options(&o, r);
3535 o.branch2 = ref_name.buf;
3536 o.buffer_output = 2;
3538 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3540 fputs(o.obuf.buf, stdout);
3541 strbuf_release(&o.obuf);
3543 error(_("could not even attempt to merge '%.*s'"),
3544 merge_arg_len, arg);
3548 * The return value of merge_recursive() is 1 on clean, and 0 on
3551 * Let's reverse that, so that do_merge() returns 0 upon success and
3552 * 1 upon failed merge (keeping the return value -1 for the cases where
3553 * we will want to reschedule the `merge` command).
3557 if (r->index->cache_changed &&
3558 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3559 ret = error(_("merge: Unable to write new index file"));
3563 rollback_lock_file(&lock);
3565 repo_rerere(r, opts->allow_rerere_auto);
3568 * In case of problems, we now want to return a positive
3569 * value (a negative one would indicate that the `merge`
3570 * command needs to be rescheduled).
3572 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3576 strbuf_release(&ref_name);
3577 rollback_lock_file(&lock);
3578 free_commit_list(to_merge);
3582 static int is_final_fixup(struct todo_list *todo_list)
3584 int i = todo_list->current;
3586 if (!is_fixup(todo_list->items[i].command))
3589 while (++i < todo_list->nr)
3590 if (is_fixup(todo_list->items[i].command))
3592 else if (!is_noop(todo_list->items[i].command))
3597 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3601 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3602 if (!is_noop(todo_list->items[i].command))
3603 return todo_list->items[i].command;
3608 static int apply_autostash(struct replay_opts *opts)
3610 struct strbuf stash_sha1 = STRBUF_INIT;
3611 struct child_process child = CHILD_PROCESS_INIT;
3614 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3615 strbuf_release(&stash_sha1);
3618 strbuf_trim(&stash_sha1);
3621 child.no_stdout = 1;
3622 child.no_stderr = 1;
3623 argv_array_push(&child.args, "stash");
3624 argv_array_push(&child.args, "apply");
3625 argv_array_push(&child.args, stash_sha1.buf);
3626 if (!run_command(&child))
3627 fprintf(stderr, _("Applied autostash.\n"));
3629 struct child_process store = CHILD_PROCESS_INIT;
3632 argv_array_push(&store.args, "stash");
3633 argv_array_push(&store.args, "store");
3634 argv_array_push(&store.args, "-m");
3635 argv_array_push(&store.args, "autostash");
3636 argv_array_push(&store.args, "-q");
3637 argv_array_push(&store.args, stash_sha1.buf);
3638 if (run_command(&store))
3639 ret = error(_("cannot store %s"), stash_sha1.buf);
3642 _("Applying autostash resulted in conflicts.\n"
3643 "Your changes are safe in the stash.\n"
3644 "You can run \"git stash pop\" or"
3645 " \"git stash drop\" at any time.\n"));
3648 strbuf_release(&stash_sha1);
3652 static const char *reflog_message(struct replay_opts *opts,
3653 const char *sub_action, const char *fmt, ...)
3656 static struct strbuf buf = STRBUF_INIT;
3660 strbuf_addstr(&buf, action_name(opts));
3662 strbuf_addf(&buf, " (%s)", sub_action);
3664 strbuf_addstr(&buf, ": ");
3665 strbuf_vaddf(&buf, fmt, ap);
3672 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3673 const char *commit, const char *action)
3675 struct child_process cmd = CHILD_PROCESS_INIT;
3680 argv_array_push(&cmd.args, "checkout");
3681 argv_array_push(&cmd.args, commit);
3682 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3685 ret = run_command(&cmd);
3687 ret = run_command_silent_on_success(&cmd);
3690 discard_index(r->index);
3695 int prepare_branch_to_be_rebased(struct repository *r, struct replay_opts *opts,
3700 if (commit && *commit) {
3701 action = reflog_message(opts, "start", "checkout %s", commit);
3702 if (run_git_checkout(r, opts, commit, action))
3703 return error(_("could not checkout %s"), commit);
3709 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3710 const char *onto_name, const struct object_id *onto,
3711 const char *orig_head)
3713 struct object_id oid;
3714 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3716 if (get_oid(orig_head, &oid))
3717 return error(_("%s: not a valid OID"), orig_head);
3719 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3720 apply_autostash(opts);
3721 sequencer_remove_state(opts);
3722 return error(_("could not detach HEAD"));
3725 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3728 static int stopped_at_head(struct repository *r)
3730 struct object_id head;
3731 struct commit *commit;
3732 struct commit_message message;
3734 if (get_oid("HEAD", &head) ||
3735 !(commit = lookup_commit(r, &head)) ||
3736 parse_commit(commit) || get_message(commit, &message))
3737 fprintf(stderr, _("Stopped at HEAD\n"));
3739 fprintf(stderr, _("Stopped at %s\n"), message.label);
3740 free_message(commit, &message);
3746 static const char rescheduled_advice[] =
3747 N_("Could not execute the todo command\n"
3751 "It has been rescheduled; To edit the command before continuing, please\n"
3752 "edit the todo list first:\n"
3754 " git rebase --edit-todo\n"
3755 " git rebase --continue\n");
3757 static int pick_commits(struct repository *r,
3758 struct todo_list *todo_list,
3759 struct replay_opts *opts)
3761 int res = 0, reschedule = 0;
3763 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3765 assert(!(opts->signoff || opts->no_commit ||
3766 opts->record_origin || opts->edit ||
3767 opts->committer_date_is_author_date ||
3768 opts->ignore_date));
3769 if (read_and_refresh_cache(r, opts))
3772 while (todo_list->current < todo_list->nr) {
3773 struct todo_item *item = todo_list->items + todo_list->current;
3774 const char *arg = todo_item_get_arg(todo_list, item);
3777 if (save_todo(todo_list, opts))
3779 if (is_rebase_i(opts)) {
3780 if (item->command != TODO_COMMENT) {
3781 FILE *f = fopen(rebase_path_msgnum(), "w");
3783 todo_list->done_nr++;
3786 fprintf(f, "%d\n", todo_list->done_nr);
3790 fprintf(stderr, "Rebasing (%d/%d)%s",
3792 todo_list->total_nr,
3793 opts->verbose ? "\n" : "\r");
3795 unlink(rebase_path_message());
3796 unlink(rebase_path_author_script());
3797 unlink(rebase_path_stopped_sha());
3798 unlink(rebase_path_amend());
3799 unlink(git_path_merge_head(the_repository));
3800 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3802 if (item->command == TODO_BREAK) {
3805 return stopped_at_head(r);
3808 if (item->command <= TODO_SQUASH) {
3809 if (is_rebase_i(opts))
3810 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3811 command_to_string(item->command), NULL),
3813 res = do_pick_commit(r, item->command, item->commit,
3814 opts, is_final_fixup(todo_list),
3816 if (is_rebase_i(opts) && res < 0) {
3818 advise(_(rescheduled_advice),
3819 get_item_line_length(todo_list,
3820 todo_list->current),
3821 get_item_line(todo_list,
3822 todo_list->current));
3823 todo_list->current--;
3824 if (save_todo(todo_list, opts))
3827 if (item->command == TODO_EDIT) {
3828 struct commit *commit = item->commit;
3833 _("Stopped at %s... %.*s\n"),
3834 short_commit_name(commit),
3835 item->arg_len, arg);
3837 return error_with_patch(r, commit,
3838 arg, item->arg_len, opts, res, !res);
3840 if (is_rebase_i(opts) && !res)
3841 record_in_rewritten(&item->commit->object.oid,
3842 peek_command(todo_list, 1));
3843 if (res && is_fixup(item->command)) {
3846 return error_failed_squash(r, item->commit, opts,
3847 item->arg_len, arg);
3848 } else if (res && is_rebase_i(opts) && item->commit) {
3850 struct object_id oid;
3853 * If we are rewording and have either
3854 * fast-forwarded already, or are about to
3855 * create a new root commit, we want to amend,
3856 * otherwise we do not.
3858 if (item->command == TODO_REWORD &&
3859 !get_oid("HEAD", &oid) &&
3860 (oideq(&item->commit->object.oid, &oid) ||
3861 (opts->have_squash_onto &&
3862 oideq(&opts->squash_onto, &oid))))
3865 return res | error_with_patch(r, item->commit,
3866 arg, item->arg_len, opts,
3869 } else if (item->command == TODO_EXEC) {
3870 char *end_of_arg = (char *)(arg + item->arg_len);
3871 int saved = *end_of_arg;
3876 res = do_exec(r, arg);
3877 *end_of_arg = saved;
3880 if (opts->reschedule_failed_exec)
3884 } else if (item->command == TODO_LABEL) {
3885 if ((res = do_label(r, arg, item->arg_len)))
3887 } else if (item->command == TODO_RESET) {
3888 if ((res = do_reset(r, arg, item->arg_len, opts)))
3890 } else if (item->command == TODO_MERGE) {
3891 if ((res = do_merge(r, item->commit,
3893 item->flags, opts)) < 0)
3895 else if (item->commit)
3896 record_in_rewritten(&item->commit->object.oid,
3897 peek_command(todo_list, 1));
3899 /* failed with merge conflicts */
3900 return error_with_patch(r, item->commit,
3903 } else if (!is_noop(item->command))
3904 return error(_("unknown command %d"), item->command);
3907 advise(_(rescheduled_advice),
3908 get_item_line_length(todo_list,
3909 todo_list->current),
3910 get_item_line(todo_list, todo_list->current));
3911 todo_list->current--;
3912 if (save_todo(todo_list, opts))
3915 return error_with_patch(r,
3919 } else if (check_todo && !res) {
3922 if (stat(get_todo_path(opts), &st)) {
3923 res = error_errno(_("could not stat '%s'"),
3924 get_todo_path(opts));
3925 } else if (match_stat_data(&todo_list->stat, &st)) {
3926 /* Reread the todo file if it has changed. */
3927 todo_list_release(todo_list);
3928 if (read_populate_todo(r, todo_list, opts))
3929 res = -1; /* message was printed */
3930 /* `current` will be incremented below */
3931 todo_list->current = -1;
3935 todo_list->current++;
3940 if (is_rebase_i(opts)) {
3941 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3944 /* Stopped in the middle, as planned? */
3945 if (todo_list->current < todo_list->nr)
3948 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3949 starts_with(head_ref.buf, "refs/")) {
3951 struct object_id head, orig;
3954 if (get_oid("HEAD", &head)) {
3955 res = error(_("cannot read HEAD"));
3957 strbuf_release(&head_ref);
3958 strbuf_release(&buf);
3961 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3962 get_oid_hex(buf.buf, &orig)) {
3963 res = error(_("could not read orig-head"));
3964 goto cleanup_head_ref;
3967 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3968 res = error(_("could not read 'onto'"));
3969 goto cleanup_head_ref;
3971 msg = reflog_message(opts, "finish", "%s onto %s",
3972 head_ref.buf, buf.buf);
3973 if (update_ref(msg, head_ref.buf, &head, &orig,
3974 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3975 res = error(_("could not update %s"),
3977 goto cleanup_head_ref;
3979 msg = reflog_message(opts, "finish", "returning to %s",
3981 if (create_symref("HEAD", head_ref.buf, msg)) {
3982 res = error(_("could not update HEAD to %s"),
3984 goto cleanup_head_ref;
3989 if (opts->verbose) {
3990 struct rev_info log_tree_opt;
3991 struct object_id orig, head;
3993 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3994 repo_init_revisions(r, &log_tree_opt, NULL);
3995 log_tree_opt.diff = 1;
3996 log_tree_opt.diffopt.output_format =
3997 DIFF_FORMAT_DIFFSTAT;
3998 log_tree_opt.disable_stdin = 1;
4000 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4001 !get_oid(buf.buf, &orig) &&
4002 !get_oid("HEAD", &head)) {
4003 diff_tree_oid(&orig, &head, "",
4004 &log_tree_opt.diffopt);
4005 log_tree_diff_flush(&log_tree_opt);
4008 flush_rewritten_pending();
4009 if (!stat(rebase_path_rewritten_list(), &st) &&
4011 struct child_process child = CHILD_PROCESS_INIT;
4012 const char *post_rewrite_hook =
4013 find_hook("post-rewrite");
4015 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4017 argv_array_push(&child.args, "notes");
4018 argv_array_push(&child.args, "copy");
4019 argv_array_push(&child.args, "--for-rewrite=rebase");
4020 /* we don't care if this copying failed */
4021 run_command(&child);
4023 if (post_rewrite_hook) {
4024 struct child_process hook = CHILD_PROCESS_INIT;
4026 hook.in = open(rebase_path_rewritten_list(),
4028 hook.stdout_to_stderr = 1;
4029 hook.trace2_hook_name = "post-rewrite";
4030 argv_array_push(&hook.args, post_rewrite_hook);
4031 argv_array_push(&hook.args, "rebase");
4032 /* we don't care if this hook failed */
4036 apply_autostash(opts);
4042 "Successfully rebased and updated %s.\n",
4046 strbuf_release(&buf);
4047 strbuf_release(&head_ref);
4051 * Sequence of picks finished successfully; cleanup by
4052 * removing the .git/sequencer directory
4054 return sequencer_remove_state(opts);
4057 static int continue_single_pick(struct repository *r)
4059 const char *argv[] = { "commit", NULL };
4061 if (!file_exists(git_path_cherry_pick_head(r)) &&
4062 !file_exists(git_path_revert_head(r)))
4063 return error(_("no cherry-pick or revert in progress"));
4064 return run_command_v_opt(argv, RUN_GIT_CMD);
4067 static int commit_staged_changes(struct repository *r,
4068 struct replay_opts *opts,
4069 struct todo_list *todo_list)
4071 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4072 unsigned int final_fixup = 0, is_clean;
4074 if (has_unstaged_changes(r, 1))
4075 return error(_("cannot rebase: You have unstaged changes."));
4077 is_clean = !has_uncommitted_changes(r, 0);
4079 if (file_exists(rebase_path_amend())) {
4080 struct strbuf rev = STRBUF_INIT;
4081 struct object_id head, to_amend;
4083 if (get_oid("HEAD", &head))
4084 return error(_("cannot amend non-existing commit"));
4085 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4086 return error(_("invalid file: '%s'"), rebase_path_amend());
4087 if (get_oid_hex(rev.buf, &to_amend))
4088 return error(_("invalid contents: '%s'"),
4089 rebase_path_amend());
4090 if (!is_clean && !oideq(&head, &to_amend))
4091 return error(_("\nYou have uncommitted changes in your "
4092 "working tree. Please, commit them\n"
4093 "first and then run 'git rebase "
4094 "--continue' again."));
4096 * When skipping a failed fixup/squash, we need to edit the
4097 * commit message, the current fixup list and count, and if it
4098 * was the last fixup/squash in the chain, we need to clean up
4099 * the commit message and if there was a squash, let the user
4102 if (!is_clean || !opts->current_fixup_count)
4103 ; /* this is not the final fixup */
4104 else if (!oideq(&head, &to_amend) ||
4105 !file_exists(rebase_path_stopped_sha())) {
4106 /* was a final fixup or squash done manually? */
4107 if (!is_fixup(peek_command(todo_list, 0))) {
4108 unlink(rebase_path_fixup_msg());
4109 unlink(rebase_path_squash_msg());
4110 unlink(rebase_path_current_fixups());
4111 strbuf_reset(&opts->current_fixups);
4112 opts->current_fixup_count = 0;
4115 /* we are in a fixup/squash chain */
4116 const char *p = opts->current_fixups.buf;
4117 int len = opts->current_fixups.len;
4119 opts->current_fixup_count--;
4121 BUG("Incorrect current_fixups:\n%s", p);
4122 while (len && p[len - 1] != '\n')
4124 strbuf_setlen(&opts->current_fixups, len);
4125 if (write_message(p, len, rebase_path_current_fixups(),
4127 return error(_("could not write file: '%s'"),
4128 rebase_path_current_fixups());
4131 * If a fixup/squash in a fixup/squash chain failed, the
4132 * commit message is already correct, no need to commit
4135 * Only if it is the final command in the fixup/squash
4136 * chain, and only if the chain is longer than a single
4137 * fixup/squash command (which was just skipped), do we
4138 * actually need to re-commit with a cleaned up commit
4141 if (opts->current_fixup_count > 0 &&
4142 !is_fixup(peek_command(todo_list, 0))) {
4145 * If there was not a single "squash" in the
4146 * chain, we only need to clean up the commit
4147 * message, no need to bother the user with
4148 * opening the commit message in the editor.
4150 if (!starts_with(p, "squash ") &&
4151 !strstr(p, "\nsquash "))
4152 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4153 } else if (is_fixup(peek_command(todo_list, 0))) {
4155 * We need to update the squash message to skip
4156 * the latest commit message.
4158 struct commit *commit;
4159 const char *path = rebase_path_squash_msg();
4161 if (parse_head(r, &commit) ||
4162 !(p = get_commit_buffer(commit, NULL)) ||
4163 write_message(p, strlen(p), path, 0)) {
4164 unuse_commit_buffer(commit, p);
4165 return error(_("could not write file: "
4168 unuse_commit_buffer(commit, p);
4172 strbuf_release(&rev);
4177 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4179 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4180 return error(_("could not remove CHERRY_PICK_HEAD"));
4185 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4187 return error(_("could not commit staged changes."));
4188 unlink(rebase_path_amend());
4189 unlink(git_path_merge_head(the_repository));
4191 unlink(rebase_path_fixup_msg());
4192 unlink(rebase_path_squash_msg());
4194 if (opts->current_fixup_count > 0) {
4196 * Whether final fixup or not, we just cleaned up the commit
4199 unlink(rebase_path_current_fixups());
4200 strbuf_reset(&opts->current_fixups);
4201 opts->current_fixup_count = 0;
4206 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4208 struct todo_list todo_list = TODO_LIST_INIT;
4211 if (read_and_refresh_cache(r, opts))
4214 if (read_populate_opts(opts))
4216 if (is_rebase_i(opts)) {
4217 if ((res = read_populate_todo(r, &todo_list, opts)))
4218 goto release_todo_list;
4219 if (commit_staged_changes(r, opts, &todo_list))
4221 } else if (!file_exists(get_todo_path(opts)))
4222 return continue_single_pick(r);
4223 else if ((res = read_populate_todo(r, &todo_list, opts)))
4224 goto release_todo_list;
4226 if (!is_rebase_i(opts)) {
4227 /* Verify that the conflict has been resolved */
4228 if (file_exists(git_path_cherry_pick_head(r)) ||
4229 file_exists(git_path_revert_head(r))) {
4230 res = continue_single_pick(r);
4232 goto release_todo_list;
4234 if (index_differs_from(r, "HEAD", NULL, 0)) {
4235 res = error_dirty_index(r, opts);
4236 goto release_todo_list;
4238 todo_list.current++;
4239 } else if (file_exists(rebase_path_stopped_sha())) {
4240 struct strbuf buf = STRBUF_INIT;
4241 struct object_id oid;
4243 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4244 !get_oid_committish(buf.buf, &oid))
4245 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4246 strbuf_release(&buf);
4249 res = pick_commits(r, &todo_list, opts);
4251 todo_list_release(&todo_list);
4255 static int single_pick(struct repository *r,
4256 struct commit *cmit,
4257 struct replay_opts *opts)
4261 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4262 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4263 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4267 int sequencer_pick_revisions(struct repository *r,
4268 struct replay_opts *opts)
4270 struct todo_list todo_list = TODO_LIST_INIT;
4271 struct object_id oid;
4275 if (read_and_refresh_cache(r, opts))
4278 for (i = 0; i < opts->revs->pending.nr; i++) {
4279 struct object_id oid;
4280 const char *name = opts->revs->pending.objects[i].name;
4282 /* This happens when using --stdin. */
4286 if (!get_oid(name, &oid)) {
4287 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4288 enum object_type type = oid_object_info(r,
4291 return error(_("%s: can't cherry-pick a %s"),
4292 name, type_name(type));
4295 return error(_("%s: bad revision"), name);
4299 * If we were called as "git cherry-pick <commit>", just
4300 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4301 * REVERT_HEAD, and don't touch the sequencer state.
4302 * This means it is possible to cherry-pick in the middle
4303 * of a cherry-pick sequence.
4305 if (opts->revs->cmdline.nr == 1 &&
4306 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4307 opts->revs->no_walk &&
4308 !opts->revs->cmdline.rev->flags) {
4309 struct commit *cmit;
4310 if (prepare_revision_walk(opts->revs))
4311 return error(_("revision walk setup failed"));
4312 cmit = get_revision(opts->revs);
4314 return error(_("empty commit set passed"));
4315 if (get_revision(opts->revs))
4316 BUG("unexpected extra commit from walk");
4317 return single_pick(r, cmit, opts);
4321 * Start a new cherry-pick/ revert sequence; but
4322 * first, make sure that an existing one isn't in
4326 if (walk_revs_populate_todo(&todo_list, opts) ||
4327 create_seq_dir() < 0)
4329 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4330 return error(_("can't revert as initial commit"));
4331 if (save_head(oid_to_hex(&oid)))
4333 if (save_opts(opts))
4335 update_abort_safety_file();
4336 res = pick_commits(r, &todo_list, opts);
4337 todo_list_release(&todo_list);
4341 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4343 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4344 struct strbuf sob = STRBUF_INIT;
4347 strbuf_addstr(&sob, sign_off_header);
4348 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4349 strbuf_addch(&sob, '\n');
4352 strbuf_complete_line(msgbuf);
4355 * If the whole message buffer is equal to the sob, pretend that we
4356 * found a conforming footer with a matching sob
4358 if (msgbuf->len - ignore_footer == sob.len &&
4359 !strncmp(msgbuf->buf, sob.buf, sob.len))
4362 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4365 const char *append_newlines = NULL;
4366 size_t len = msgbuf->len - ignore_footer;
4370 * The buffer is completely empty. Leave foom for
4371 * the title and body to be filled in by the user.
4373 append_newlines = "\n\n";
4374 } else if (len == 1) {
4376 * Buffer contains a single newline. Add another
4377 * so that we leave room for the title and body.
4379 append_newlines = "\n";
4380 } else if (msgbuf->buf[len - 2] != '\n') {
4382 * Buffer ends with a single newline. Add another
4383 * so that there is an empty line between the message
4386 append_newlines = "\n";
4387 } /* else, the buffer already ends with two newlines. */
4389 if (append_newlines)
4390 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4391 append_newlines, strlen(append_newlines));
4394 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4395 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4398 strbuf_release(&sob);
4401 struct labels_entry {
4402 struct hashmap_entry entry;
4403 char label[FLEX_ARRAY];
4406 static int labels_cmp(const void *fndata, const struct labels_entry *a,
4407 const struct labels_entry *b, const void *key)
4409 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4412 struct string_entry {
4413 struct oidmap_entry entry;
4414 char string[FLEX_ARRAY];
4417 struct label_state {
4418 struct oidmap commit2label;
4419 struct hashmap labels;
4423 static const char *label_oid(struct object_id *oid, const char *label,
4424 struct label_state *state)
4426 struct labels_entry *labels_entry;
4427 struct string_entry *string_entry;
4428 struct object_id dummy;
4432 string_entry = oidmap_get(&state->commit2label, oid);
4434 return string_entry->string;
4437 * For "uninteresting" commits, i.e. commits that are not to be
4438 * rebased, and which can therefore not be labeled, we use a unique
4439 * abbreviation of the commit name. This is slightly more complicated
4440 * than calling find_unique_abbrev() because we also need to make
4441 * sure that the abbreviation does not conflict with any other
4444 * We disallow "interesting" commits to be labeled by a string that
4445 * is a valid full-length hash, to ensure that we always can find an
4446 * abbreviation for any uninteresting commit's names that does not
4447 * clash with any other label.
4452 strbuf_reset(&state->buf);
4453 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4454 label = p = state->buf.buf;
4456 find_unique_abbrev_r(p, oid, default_abbrev);
4459 * We may need to extend the abbreviated hash so that there is
4460 * no conflicting label.
4462 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4463 size_t i = strlen(p) + 1;
4465 oid_to_hex_r(p, oid);
4466 for (; i < GIT_SHA1_HEXSZ; i++) {
4469 if (!hashmap_get_from_hash(&state->labels,
4475 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
4476 !get_oid_hex(label, &dummy)) ||
4477 (len == 1 && *label == '#') ||
4478 hashmap_get_from_hash(&state->labels,
4479 strihash(label), label)) {
4481 * If the label already exists, or if the label is a valid full
4482 * OID, or the label is a '#' (which we use as a separator
4483 * between merge heads and oneline), we append a dash and a
4484 * number to make it unique.
4486 struct strbuf *buf = &state->buf;
4489 strbuf_add(buf, label, len);
4491 for (i = 2; ; i++) {
4492 strbuf_setlen(buf, len);
4493 strbuf_addf(buf, "-%d", i);
4494 if (!hashmap_get_from_hash(&state->labels,
4503 FLEX_ALLOC_STR(labels_entry, label, label);
4504 hashmap_entry_init(labels_entry, strihash(label));
4505 hashmap_add(&state->labels, labels_entry);
4507 FLEX_ALLOC_STR(string_entry, string, label);
4508 oidcpy(&string_entry->entry.oid, oid);
4509 oidmap_put(&state->commit2label, string_entry);
4511 return string_entry->string;
4514 static int make_script_with_merges(struct pretty_print_context *pp,
4515 struct rev_info *revs, struct strbuf *out,
4518 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4519 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4520 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4521 struct strbuf label = STRBUF_INIT;
4522 struct commit_list *commits = NULL, **tail = &commits, *iter;
4523 struct commit_list *tips = NULL, **tips_tail = &tips;
4524 struct commit *commit;
4525 struct oidmap commit2todo = OIDMAP_INIT;
4526 struct string_entry *entry;
4527 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4528 shown = OIDSET_INIT;
4529 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4531 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4532 const char *cmd_pick = abbr ? "p" : "pick",
4533 *cmd_label = abbr ? "l" : "label",
4534 *cmd_reset = abbr ? "t" : "reset",
4535 *cmd_merge = abbr ? "m" : "merge";
4537 oidmap_init(&commit2todo, 0);
4538 oidmap_init(&state.commit2label, 0);
4539 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4540 strbuf_init(&state.buf, 32);
4542 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4543 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4544 FLEX_ALLOC_STR(entry, string, "onto");
4545 oidcpy(&entry->entry.oid, oid);
4546 oidmap_put(&state.commit2label, entry);
4551 * - get onelines for all commits
4552 * - gather all branch tips (i.e. 2nd or later parents of merges)
4553 * - label all branch tips
4555 while ((commit = get_revision(revs))) {
4556 struct commit_list *to_merge;
4557 const char *p1, *p2;
4558 struct object_id *oid;
4561 tail = &commit_list_insert(commit, tail)->next;
4562 oidset_insert(&interesting, &commit->object.oid);
4564 is_empty = is_original_commit_empty(commit);
4565 if (!is_empty && (commit->object.flags & PATCHSAME))
4568 strbuf_reset(&oneline);
4569 pretty_print_commit(pp, commit, &oneline);
4571 to_merge = commit->parents ? commit->parents->next : NULL;
4573 /* non-merge commit: easy case */
4575 if (!keep_empty && is_empty)
4576 strbuf_addf(&buf, "%c ", comment_line_char);
4577 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4578 oid_to_hex(&commit->object.oid),
4581 FLEX_ALLOC_STR(entry, string, buf.buf);
4582 oidcpy(&entry->entry.oid, &commit->object.oid);
4583 oidmap_put(&commit2todo, entry);
4588 /* Create a label */
4589 strbuf_reset(&label);
4590 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4591 (p1 = strchr(p1, '\'')) &&
4592 (p2 = strchr(++p1, '\'')))
4593 strbuf_add(&label, p1, p2 - p1);
4594 else if (skip_prefix(oneline.buf, "Merge pull request ",
4596 (p1 = strstr(p1, " from ")))
4597 strbuf_addstr(&label, p1 + strlen(" from "));
4599 strbuf_addbuf(&label, &oneline);
4601 for (p1 = label.buf; *p1; p1++)
4606 strbuf_addf(&buf, "%s -C %s",
4607 cmd_merge, oid_to_hex(&commit->object.oid));
4609 /* label the tips of merged branches */
4610 for (; to_merge; to_merge = to_merge->next) {
4611 oid = &to_merge->item->object.oid;
4612 strbuf_addch(&buf, ' ');
4614 if (!oidset_contains(&interesting, oid)) {
4615 strbuf_addstr(&buf, label_oid(oid, NULL,
4620 tips_tail = &commit_list_insert(to_merge->item,
4623 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4625 strbuf_addf(&buf, " # %s", oneline.buf);
4627 FLEX_ALLOC_STR(entry, string, buf.buf);
4628 oidcpy(&entry->entry.oid, &commit->object.oid);
4629 oidmap_put(&commit2todo, entry);
4634 * - label branch points
4635 * - add HEAD to the branch tips
4637 for (iter = commits; iter; iter = iter->next) {
4638 struct commit_list *parent = iter->item->parents;
4639 for (; parent; parent = parent->next) {
4640 struct object_id *oid = &parent->item->object.oid;
4641 if (!oidset_contains(&interesting, oid))
4643 if (oidset_insert(&child_seen, oid))
4644 label_oid(oid, "branch-point", &state);
4647 /* Add HEAD as implict "tip of branch" */
4649 tips_tail = &commit_list_insert(iter->item,
4654 * Third phase: output the todo list. This is a bit tricky, as we
4655 * want to avoid jumping back and forth between revisions. To
4656 * accomplish that goal, we walk backwards from the branch tips,
4657 * gathering commits not yet shown, reversing the list on the fly,
4658 * then outputting that list (labeling revisions as needed).
4660 strbuf_addf(out, "%s onto\n", cmd_label);
4661 for (iter = tips; iter; iter = iter->next) {
4662 struct commit_list *list = NULL, *iter2;
4664 commit = iter->item;
4665 if (oidset_contains(&shown, &commit->object.oid))
4667 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4670 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4672 strbuf_addch(out, '\n');
4674 while (oidset_contains(&interesting, &commit->object.oid) &&
4675 !oidset_contains(&shown, &commit->object.oid)) {
4676 commit_list_insert(commit, &list);
4677 if (!commit->parents) {
4681 commit = commit->parents->item;
4685 strbuf_addf(out, "%s %s\n", cmd_reset,
4686 rebase_cousins ? "onto" : "[new root]");
4688 const char *to = NULL;
4690 entry = oidmap_get(&state.commit2label,
4691 &commit->object.oid);
4694 else if (!rebase_cousins)
4695 to = label_oid(&commit->object.oid, NULL,
4698 if (!to || !strcmp(to, "onto"))
4699 strbuf_addf(out, "%s onto\n", cmd_reset);
4701 strbuf_reset(&oneline);
4702 pretty_print_commit(pp, commit, &oneline);
4703 strbuf_addf(out, "%s %s # %s\n",
4704 cmd_reset, to, oneline.buf);
4708 for (iter2 = list; iter2; iter2 = iter2->next) {
4709 struct object_id *oid = &iter2->item->object.oid;
4710 entry = oidmap_get(&commit2todo, oid);
4711 /* only show if not already upstream */
4713 strbuf_addf(out, "%s\n", entry->string);
4714 entry = oidmap_get(&state.commit2label, oid);
4716 strbuf_addf(out, "%s %s\n",
4717 cmd_label, entry->string);
4718 oidset_insert(&shown, oid);
4721 free_commit_list(list);
4724 free_commit_list(commits);
4725 free_commit_list(tips);
4727 strbuf_release(&label);
4728 strbuf_release(&oneline);
4729 strbuf_release(&buf);
4731 oidmap_free(&commit2todo, 1);
4732 oidmap_free(&state.commit2label, 1);
4733 hashmap_free(&state.labels, 1);
4734 strbuf_release(&state.buf);
4739 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4740 const char **argv, unsigned flags)
4742 char *format = NULL;
4743 struct pretty_print_context pp = {0};
4744 struct rev_info revs;
4745 struct commit *commit;
4746 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4747 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4748 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4750 repo_init_revisions(r, &revs, NULL);
4751 revs.verbose_header = 1;
4753 revs.max_parents = 1;
4754 revs.cherry_mark = 1;
4757 revs.right_only = 1;
4758 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4759 revs.topo_order = 1;
4761 revs.pretty_given = 1;
4762 git_config_get_string("rebase.instructionFormat", &format);
4763 if (!format || !*format) {
4765 format = xstrdup("%s");
4767 get_commit_format(format, &revs);
4769 pp.fmt = revs.commit_format;
4770 pp.output_encoding = get_log_output_encoding();
4772 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4773 return error(_("make_script: unhandled options"));
4775 if (prepare_revision_walk(&revs) < 0)
4776 return error(_("make_script: error preparing revisions"));
4779 return make_script_with_merges(&pp, &revs, out, flags);
4781 while ((commit = get_revision(&revs))) {
4782 int is_empty = is_original_commit_empty(commit);
4784 if (!is_empty && (commit->object.flags & PATCHSAME))
4786 if (!keep_empty && is_empty)
4787 strbuf_addf(out, "%c ", comment_line_char);
4788 strbuf_addf(out, "%s %s ", insn,
4789 oid_to_hex(&commit->object.oid));
4790 pretty_print_commit(&pp, commit, out);
4791 strbuf_addch(out, '\n');
4797 * Add commands after pick and (series of) squash/fixup commands
4800 void todo_list_add_exec_commands(struct todo_list *todo_list,
4801 struct string_list *commands)
4803 struct strbuf *buf = &todo_list->buf;
4804 size_t base_offset = buf->len;
4805 int i, insert, nr = 0, alloc = 0;
4806 struct todo_item *items = NULL, *base_items = NULL;
4808 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4809 for (i = 0; i < commands->nr; i++) {
4810 size_t command_len = strlen(commands->items[i].string);
4812 strbuf_addstr(buf, commands->items[i].string);
4813 strbuf_addch(buf, '\n');
4815 base_items[i].command = TODO_EXEC;
4816 base_items[i].offset_in_buf = base_offset;
4817 base_items[i].arg_offset = base_offset + strlen("exec ");
4818 base_items[i].arg_len = command_len - strlen("exec ");
4820 base_offset += command_len + 1;
4824 * Insert <commands> after every pick. Here, fixup/squash chains
4825 * are considered part of the pick, so we insert the commands *after*
4826 * those chains if there are any.
4828 * As we insert the exec commands immediatly after rearranging
4829 * any fixups and before the user edits the list, a fixup chain
4830 * can never contain comments (any comments are empty picks that
4831 * have been commented out because the user did not specify
4832 * --keep-empty). So, it is safe to insert an exec command
4833 * without looking at the command following a comment.
4836 for (i = 0; i < todo_list->nr; i++) {
4837 enum todo_command command = todo_list->items[i].command;
4838 if (insert && !is_fixup(command)) {
4839 ALLOC_GROW(items, nr + commands->nr, alloc);
4840 COPY_ARRAY(items + nr, base_items, commands->nr);
4846 ALLOC_GROW(items, nr + 1, alloc);
4847 items[nr++] = todo_list->items[i];
4849 if (command == TODO_PICK || command == TODO_MERGE)
4853 /* insert or append final <commands> */
4854 if (insert || nr == todo_list->nr) {
4855 ALLOC_GROW(items, nr + commands->nr, alloc);
4856 COPY_ARRAY(items + nr, base_items, commands->nr);
4861 FREE_AND_NULL(todo_list->items);
4862 todo_list->items = items;
4864 todo_list->alloc = alloc;
4867 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4868 struct strbuf *buf, int num, unsigned flags)
4870 struct todo_item *item;
4871 int i, max = todo_list->nr;
4873 if (num > 0 && num < max)
4876 for (item = todo_list->items, i = 0; i < max; i++, item++) {
4877 /* if the item is not a command write it and continue */
4878 if (item->command >= TODO_COMMENT) {
4879 strbuf_addf(buf, "%.*s\n", item->arg_len,
4880 todo_item_get_arg(todo_list, item));
4884 /* add command to the buffer */
4885 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4886 strbuf_addch(buf, command_to_char(item->command));
4888 strbuf_addstr(buf, command_to_string(item->command));
4892 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4893 short_commit_name(item->commit) :
4894 oid_to_hex(&item->commit->object.oid);
4896 if (item->command == TODO_MERGE) {
4897 if (item->flags & TODO_EDIT_MERGE_MSG)
4898 strbuf_addstr(buf, " -c");
4900 strbuf_addstr(buf, " -C");
4903 strbuf_addf(buf, " %s", oid);
4906 /* add all the rest */
4908 strbuf_addch(buf, '\n');
4910 strbuf_addf(buf, " %.*s\n", item->arg_len,
4911 todo_item_get_arg(todo_list, item));
4915 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
4916 const char *file, const char *shortrevisions,
4917 const char *shortonto, int num, unsigned flags)
4920 struct strbuf buf = STRBUF_INIT;
4922 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
4923 if (flags & TODO_LIST_APPEND_TODO_HELP)
4924 append_todo_help(flags & TODO_LIST_KEEP_EMPTY, count_commands(todo_list),
4925 shortrevisions, shortonto, &buf);
4927 res = write_message(buf.buf, buf.len, file, 0);
4928 strbuf_release(&buf);
4933 static const char edit_todo_list_advice[] =
4934 N_("You can fix this with 'git rebase --edit-todo' "
4935 "and then run 'git rebase --continue'.\n"
4936 "Or you can abort the rebase with 'git rebase"
4939 int check_todo_list_from_file(struct repository *r)
4941 struct todo_list old_todo = TODO_LIST_INIT, new_todo = TODO_LIST_INIT;
4944 if (strbuf_read_file_or_whine(&new_todo.buf, rebase_path_todo()) < 0) {
4949 if (strbuf_read_file_or_whine(&old_todo.buf, rebase_path_todo_backup()) < 0) {
4954 res = todo_list_parse_insn_buffer(r, old_todo.buf.buf, &old_todo);
4956 res = todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo);
4958 res = todo_list_check(&old_todo, &new_todo);
4960 fprintf(stderr, _(edit_todo_list_advice));
4962 todo_list_release(&old_todo);
4963 todo_list_release(&new_todo);
4968 /* skip picking commits whose parents are unchanged */
4969 static int skip_unnecessary_picks(struct repository *r,
4970 struct todo_list *todo_list,
4971 struct object_id *base_oid)
4973 struct object_id *parent_oid;
4976 for (i = 0; i < todo_list->nr; i++) {
4977 struct todo_item *item = todo_list->items + i;
4979 if (item->command >= TODO_NOOP)
4981 if (item->command != TODO_PICK)
4983 if (parse_commit(item->commit)) {
4984 return error(_("could not parse commit '%s'"),
4985 oid_to_hex(&item->commit->object.oid));
4987 if (!item->commit->parents)
4988 break; /* root commit */
4989 if (item->commit->parents->next)
4990 break; /* merge commit */
4991 parent_oid = &item->commit->parents->item->object.oid;
4992 if (!oideq(parent_oid, base_oid))
4994 oidcpy(base_oid, &item->commit->object.oid);
4997 const char *done_path = rebase_path_done();
4999 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5000 error_errno(_("could not write to '%s'"), done_path);
5004 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5006 todo_list->current = 0;
5008 if (is_fixup(peek_command(todo_list, 0)))
5009 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5015 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5016 const char *shortrevisions, const char *onto_name,
5017 struct commit *onto, const char *orig_head,
5018 struct string_list *commands, unsigned autosquash,
5019 struct todo_list *todo_list)
5021 const char *shortonto, *todo_file = rebase_path_todo();
5022 struct todo_list new_todo = TODO_LIST_INIT;
5023 struct strbuf *buf = &todo_list->buf;
5024 struct object_id oid = onto->object.oid;
5027 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5029 if (buf->len == 0) {
5030 struct todo_item *item = append_new_todo(todo_list);
5031 item->command = TODO_NOOP;
5032 item->commit = NULL;
5033 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5036 if (autosquash && todo_list_rearrange_squash(todo_list))
5040 todo_list_add_exec_commands(todo_list, commands);
5042 if (count_commands(todo_list) == 0) {
5043 apply_autostash(opts);
5044 sequencer_remove_state(opts);
5046 return error(_("nothing to do"));
5049 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5053 else if (res == -2) {
5054 apply_autostash(opts);
5055 sequencer_remove_state(opts);
5058 } else if (res == -3) {
5059 apply_autostash(opts);
5060 sequencer_remove_state(opts);
5061 todo_list_release(&new_todo);
5063 return error(_("nothing to do"));
5066 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) ||
5067 todo_list_check(todo_list, &new_todo)) {
5068 fprintf(stderr, _(edit_todo_list_advice));
5069 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5070 todo_list_release(&new_todo);
5075 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5076 todo_list_release(&new_todo);
5077 return error(_("could not skip unnecessary pick commands"));
5080 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5081 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5082 todo_list_release(&new_todo);
5083 return error_errno(_("could not write '%s'"), todo_file);
5086 todo_list_release(&new_todo);
5088 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5091 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5094 return sequencer_continue(r, opts);
5097 struct subject2item_entry {
5098 struct hashmap_entry entry;
5100 char subject[FLEX_ARRAY];
5103 static int subject2item_cmp(const void *fndata,
5104 const struct subject2item_entry *a,
5105 const struct subject2item_entry *b, const void *key)
5107 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5110 define_commit_slab(commit_todo_item, struct todo_item *);
5113 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5114 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5115 * after the former, and change "pick" to "fixup"/"squash".
5117 * Note that if the config has specified a custom instruction format, each log
5118 * message will have to be retrieved from the commit (as the oneline in the
5119 * script cannot be trusted) in order to normalize the autosquash arrangement.
5121 int todo_list_rearrange_squash(struct todo_list *todo_list)
5123 struct hashmap subject2item;
5124 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5126 struct commit_todo_item commit_todo;
5127 struct todo_item *items = NULL;
5129 init_commit_todo_item(&commit_todo);
5131 * The hashmap maps onelines to the respective todo list index.
5133 * If any items need to be rearranged, the next[i] value will indicate
5134 * which item was moved directly after the i'th.
5136 * In that case, last[i] will indicate the index of the latest item to
5137 * be moved to appear after the i'th.
5139 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
5140 NULL, todo_list->nr);
5141 ALLOC_ARRAY(next, todo_list->nr);
5142 ALLOC_ARRAY(tail, todo_list->nr);
5143 ALLOC_ARRAY(subjects, todo_list->nr);
5144 for (i = 0; i < todo_list->nr; i++) {
5145 struct strbuf buf = STRBUF_INIT;
5146 struct todo_item *item = todo_list->items + i;
5147 const char *commit_buffer, *subject, *p;
5150 struct subject2item_entry *entry;
5152 next[i] = tail[i] = -1;
5153 if (!item->commit || item->command == TODO_DROP) {
5158 if (is_fixup(item->command)) {
5159 clear_commit_todo_item(&commit_todo);
5160 return error(_("the script was already rearranged."));
5163 *commit_todo_item_at(&commit_todo, item->commit) = item;
5165 parse_commit(item->commit);
5166 commit_buffer = get_commit_buffer(item->commit, NULL);
5167 find_commit_subject(commit_buffer, &subject);
5168 format_subject(&buf, subject, " ");
5169 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5170 unuse_commit_buffer(item->commit, commit_buffer);
5171 if ((skip_prefix(subject, "fixup! ", &p) ||
5172 skip_prefix(subject, "squash! ", &p))) {
5173 struct commit *commit2;
5178 if (!skip_prefix(p, "fixup! ", &p) &&
5179 !skip_prefix(p, "squash! ", &p))
5183 if ((entry = hashmap_get_from_hash(&subject2item,
5185 /* found by title */
5187 else if (!strchr(p, ' ') &&
5189 lookup_commit_reference_by_name(p)) &&
5190 *commit_todo_item_at(&commit_todo, commit2))
5191 /* found by commit name */
5192 i2 = *commit_todo_item_at(&commit_todo, commit2)
5195 /* copy can be a prefix of the commit subject */
5196 for (i2 = 0; i2 < i; i2++)
5198 starts_with(subjects[i2], p))
5206 todo_list->items[i].command =
5207 starts_with(subject, "fixup!") ?
5208 TODO_FIXUP : TODO_SQUASH;
5214 } else if (!hashmap_get_from_hash(&subject2item,
5215 strhash(subject), subject)) {
5216 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5218 hashmap_entry_init(entry, strhash(entry->subject));
5219 hashmap_put(&subject2item, entry);
5224 for (i = 0; i < todo_list->nr; i++) {
5225 enum todo_command command = todo_list->items[i].command;
5229 * Initially, all commands are 'pick's. If it is a
5230 * fixup or a squash now, we have rearranged it.
5232 if (is_fixup(command))
5236 ALLOC_GROW(items, nr + 1, alloc);
5237 items[nr++] = todo_list->items[cur];
5242 FREE_AND_NULL(todo_list->items);
5243 todo_list->items = items;
5245 todo_list->alloc = alloc;
5250 for (i = 0; i < todo_list->nr; i++)
5253 hashmap_free(&subject2item, 1);
5255 clear_commit_todo_item(&commit_todo);