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 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
60 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
63 * The rebase command lines that have already been processed. A line
64 * is moved here when it is first handled, before any associated user
67 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
69 * The file to keep track of how many commands were already processed (e.g.
72 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
74 * The file to keep track of how many commands are to be processed in total
75 * (e.g. for the prompt).
77 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
79 * The commit message that is planned to be used for any changes that
80 * need to be committed following a user interaction.
82 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
84 * The file into which is accumulated the suggested commit message for
85 * squash/fixup commands. When the first of a series of squash/fixups
86 * is seen, the file is created and the commit message from the
87 * previous commit and from the first squash/fixup commit are written
88 * to it. The commit message for each subsequent squash/fixup commit
89 * is appended to the file as it is processed.
91 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
93 * If the current series of squash/fixups has not yet included a squash
94 * command, then this file exists and holds the commit message of the
95 * original "pick" commit. (If the series ends without a "squash"
96 * command, then this can be used as the commit message of the combined
97 * commit without opening the editor.)
99 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
101 * This file contains the list fixup/squash commands that have been
102 * accumulated into message-fixup or message-squash so far.
104 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
106 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
107 * GIT_AUTHOR_DATE that will be used for the commit that is currently
110 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
112 * When an "edit" rebase command is being processed, the SHA1 of the
113 * commit to be edited is recorded in this file. When "git rebase
114 * --continue" is executed, if there are any staged changes then they
115 * will be amended to the HEAD commit, but only provided the HEAD
116 * commit is still the commit to be edited. When any other rebase
117 * command is processed, this file is deleted.
119 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
121 * When we stop at a given patch via the "edit" command, this file contains
122 * the abbreviated commit name of the corresponding patch.
124 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
126 * For the post-rewrite hook, we make a list of rewritten commits and
127 * their new sha1s. The rewritten-pending list keeps the sha1s of
128 * commits that have been processed, but not committed yet,
129 * e.g. because they are waiting for a 'squash' command.
131 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
132 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
133 "rebase-merge/rewritten-pending")
136 * The path of the file containing the OID of the "squash onto" commit, i.e.
137 * the dummy commit used for `reset [new root]`.
139 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
142 * The path of the file listing refs that need to be deleted after the rebase
143 * finishes. This is used by the `label` command to record the need for cleanup.
145 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
148 * The following files are written by git-rebase just after parsing the
151 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
152 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
153 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
154 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
155 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
156 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
157 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
158 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
159 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
160 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
161 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
162 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
163 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
164 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
165 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
166 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
168 static int git_sequencer_config(const char *k, const char *v, void *cb)
170 struct replay_opts *opts = cb;
173 if (!strcmp(k, "commit.cleanup")) {
176 status = git_config_string(&s, k, v);
180 if (!strcmp(s, "verbatim")) {
181 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
182 opts->explicit_cleanup = 1;
183 } else if (!strcmp(s, "whitespace")) {
184 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
185 opts->explicit_cleanup = 1;
186 } else if (!strcmp(s, "strip")) {
187 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
188 opts->explicit_cleanup = 1;
189 } else if (!strcmp(s, "scissors")) {
190 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
191 opts->explicit_cleanup = 1;
193 warning(_("invalid commit message cleanup mode '%s'"),
201 if (!strcmp(k, "commit.gpgsign")) {
202 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
206 status = git_gpg_config(k, v, NULL);
210 return git_diff_basic_config(k, v, NULL);
213 void sequencer_init_config(struct replay_opts *opts)
215 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
216 git_config(git_sequencer_config, opts);
219 static inline int is_rebase_i(const struct replay_opts *opts)
221 return opts->action == REPLAY_INTERACTIVE_REBASE;
224 static const char *get_dir(const struct replay_opts *opts)
226 if (is_rebase_i(opts))
227 return rebase_path();
228 return git_path_seq_dir();
231 static const char *get_todo_path(const struct replay_opts *opts)
233 if (is_rebase_i(opts))
234 return rebase_path_todo();
235 return git_path_todo_file();
239 * Returns 0 for non-conforming footer
240 * Returns 1 for conforming footer
241 * Returns 2 when sob exists within conforming footer
242 * Returns 3 when sob exists within conforming footer as last entry
244 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
245 size_t ignore_footer)
247 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
248 struct trailer_info info;
250 int found_sob = 0, found_sob_last = 0;
254 trailer_info_get(&info, sb->buf, &opts);
256 if (info.trailer_start == info.trailer_end)
259 for (i = 0; i < info.trailer_nr; i++)
260 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
262 if (i == info.trailer_nr - 1)
266 trailer_info_release(&info);
275 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
277 static struct strbuf buf = STRBUF_INIT;
281 sq_quotef(&buf, "-S%s", opts->gpg_sign);
285 int sequencer_remove_state(struct replay_opts *opts)
287 struct strbuf buf = STRBUF_INIT;
290 if (is_rebase_i(opts) &&
291 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
294 char *eol = strchr(p, '\n');
297 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
298 warning(_("could not delete '%s'"), p);
307 free(opts->gpg_sign);
308 free(opts->strategy);
309 for (i = 0; i < opts->xopts_nr; i++)
310 free(opts->xopts[i]);
312 strbuf_release(&opts->current_fixups);
315 strbuf_addstr(&buf, get_dir(opts));
316 if (remove_dir_recursively(&buf, 0))
317 ret = error(_("could not remove '%s'"), buf.buf);
318 strbuf_release(&buf);
323 static const char *action_name(const struct replay_opts *opts)
325 switch (opts->action) {
329 return N_("cherry-pick");
330 case REPLAY_INTERACTIVE_REBASE:
333 die(_("unknown action: %d"), opts->action);
336 struct commit_message {
343 static const char *short_commit_name(struct commit *commit)
345 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
348 static int get_message(struct commit *commit, struct commit_message *out)
350 const char *abbrev, *subject;
353 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
354 abbrev = short_commit_name(commit);
356 subject_len = find_commit_subject(out->message, &subject);
358 out->subject = xmemdupz(subject, subject_len);
359 out->label = xstrfmt("%s... %s", abbrev, out->subject);
360 out->parent_label = xstrfmt("parent of %s", out->label);
365 static void free_message(struct commit *commit, struct commit_message *msg)
367 free(msg->parent_label);
370 unuse_commit_buffer(commit, msg->message);
373 static void print_advice(struct repository *r, int show_hint,
374 struct replay_opts *opts)
376 char *msg = getenv("GIT_CHERRY_PICK_HELP");
379 fprintf(stderr, "%s\n", msg);
381 * A conflict has occurred but the porcelain
382 * (typically rebase --interactive) wants to take care
383 * of the commit itself so remove CHERRY_PICK_HEAD
385 unlink(git_path_cherry_pick_head(r));
391 advise(_("after resolving the conflicts, mark the corrected paths\n"
392 "with 'git add <paths>' or 'git rm <paths>'"));
394 advise(_("after resolving the conflicts, mark the corrected paths\n"
395 "with 'git add <paths>' or 'git rm <paths>'\n"
396 "and commit the result with 'git commit'"));
400 static int write_message(const void *buf, size_t len, const char *filename,
403 struct lock_file msg_file = LOCK_INIT;
405 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
407 return error_errno(_("could not lock '%s'"), filename);
408 if (write_in_full(msg_fd, buf, len) < 0) {
409 error_errno(_("could not write to '%s'"), filename);
410 rollback_lock_file(&msg_file);
413 if (append_eol && write(msg_fd, "\n", 1) < 0) {
414 error_errno(_("could not write eol to '%s'"), filename);
415 rollback_lock_file(&msg_file);
418 if (commit_lock_file(&msg_file) < 0)
419 return error(_("failed to finalize '%s'"), filename);
425 * Reads a file that was presumably written by a shell script, i.e. with an
426 * end-of-line marker that needs to be stripped.
428 * Note that only the last end-of-line marker is stripped, consistent with the
429 * behavior of "$(cat path)" in a shell script.
431 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
433 static int read_oneliner(struct strbuf *buf,
434 const char *path, int skip_if_empty)
436 int orig_len = buf->len;
438 if (!file_exists(path))
441 if (strbuf_read_file(buf, path, 0) < 0) {
442 warning_errno(_("could not read '%s'"), path);
446 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
447 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
449 buf->buf[buf->len] = '\0';
452 if (skip_if_empty && buf->len == orig_len)
458 static struct tree *empty_tree(struct repository *r)
460 return lookup_tree(r, the_hash_algo->empty_tree);
463 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
465 if (repo_read_index_unmerged(repo))
466 return error_resolve_conflict(_(action_name(opts)));
468 error(_("your local changes would be overwritten by %s."),
469 _(action_name(opts)));
471 if (advice_commit_before_merge)
472 advise(_("commit your changes or stash them to proceed."));
476 static void update_abort_safety_file(void)
478 struct object_id head;
480 /* Do nothing on a single-pick */
481 if (!file_exists(git_path_seq_dir()))
484 if (!get_oid("HEAD", &head))
485 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
487 write_file(git_path_abort_safety_file(), "%s", "");
490 static int fast_forward_to(struct repository *r,
491 const struct object_id *to,
492 const struct object_id *from,
494 struct replay_opts *opts)
496 struct ref_transaction *transaction;
497 struct strbuf sb = STRBUF_INIT;
498 struct strbuf err = STRBUF_INIT;
501 if (checkout_fast_forward(r, from, to, 1))
502 return -1; /* the callee should have complained already */
504 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
506 transaction = ref_transaction_begin(&err);
508 ref_transaction_update(transaction, "HEAD",
509 to, unborn && !is_rebase_i(opts) ?
512 ref_transaction_commit(transaction, &err)) {
513 ref_transaction_free(transaction);
514 error("%s", err.buf);
516 strbuf_release(&err);
521 strbuf_release(&err);
522 ref_transaction_free(transaction);
523 update_abort_safety_file();
527 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
530 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
531 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
532 COMMIT_MSG_CLEANUP_SPACE;
533 else if (!strcmp(cleanup_arg, "verbatim"))
534 return COMMIT_MSG_CLEANUP_NONE;
535 else if (!strcmp(cleanup_arg, "whitespace"))
536 return COMMIT_MSG_CLEANUP_SPACE;
537 else if (!strcmp(cleanup_arg, "strip"))
538 return COMMIT_MSG_CLEANUP_ALL;
539 else if (!strcmp(cleanup_arg, "scissors"))
540 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
541 COMMIT_MSG_CLEANUP_SPACE;
543 die(_("Invalid cleanup mode %s"), cleanup_arg);
547 * NB using int rather than enum cleanup_mode to stop clang's
548 * -Wtautological-constant-out-of-range-compare complaining that the comparison
551 static const char *describe_cleanup_mode(int cleanup_mode)
553 static const char *modes[] = { "whitespace",
558 if (cleanup_mode < ARRAY_SIZE(modes))
559 return modes[cleanup_mode];
561 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
564 void append_conflicts_hint(struct index_state *istate,
565 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
569 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
570 strbuf_addch(msgbuf, '\n');
571 wt_status_append_cut_line(msgbuf);
572 strbuf_addch(msgbuf, comment_line_char);
575 strbuf_addch(msgbuf, '\n');
576 strbuf_commented_addf(msgbuf, "Conflicts:\n");
577 for (i = 0; i < istate->cache_nr;) {
578 const struct cache_entry *ce = istate->cache[i++];
580 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
581 while (i < istate->cache_nr &&
582 !strcmp(ce->name, istate->cache[i]->name))
588 static int do_recursive_merge(struct repository *r,
589 struct commit *base, struct commit *next,
590 const char *base_label, const char *next_label,
591 struct object_id *head, struct strbuf *msgbuf,
592 struct replay_opts *opts)
594 struct merge_options o;
595 struct tree *next_tree, *base_tree, *head_tree;
598 struct lock_file index_lock = LOCK_INIT;
600 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
605 init_merge_options(&o, r);
606 o.ancestor = base ? base_label : "(empty tree)";
608 o.branch2 = next ? next_label : "(empty tree)";
609 if (is_rebase_i(opts))
611 o.show_rename_progress = 1;
613 head_tree = parse_tree_indirect(head);
614 next_tree = next ? get_commit_tree(next) : empty_tree(r);
615 base_tree = base ? get_commit_tree(base) : empty_tree(r);
617 for (i = 0; i < opts->xopts_nr; i++)
618 parse_merge_opt(&o, opts->xopts[i]);
620 clean = merge_trees(&o,
622 next_tree, base_tree);
623 if (is_rebase_i(opts) && clean <= 0)
624 fputs(o.obuf.buf, stdout);
625 strbuf_release(&o.obuf);
627 rollback_lock_file(&index_lock);
631 if (write_locked_index(r->index, &index_lock,
632 COMMIT_LOCK | SKIP_IF_UNCHANGED))
634 * TRANSLATORS: %s will be "revert", "cherry-pick" or
637 return error(_("%s: Unable to write new index file"),
638 _(action_name(opts)));
641 append_conflicts_hint(r->index, msgbuf,
642 opts->default_msg_cleanup);
647 static struct object_id *get_cache_tree_oid(struct index_state *istate)
649 if (!istate->cache_tree)
650 istate->cache_tree = cache_tree();
652 if (!cache_tree_fully_valid(istate->cache_tree))
653 if (cache_tree_update(istate, 0)) {
654 error(_("unable to update cache tree"));
658 return &istate->cache_tree->oid;
661 static int is_index_unchanged(struct repository *r)
663 struct object_id head_oid, *cache_tree_oid;
664 struct commit *head_commit;
665 struct index_state *istate = r->index;
667 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
668 return error(_("could not resolve HEAD commit"));
670 head_commit = lookup_commit(r, &head_oid);
673 * If head_commit is NULL, check_commit, called from
674 * lookup_commit, would have indicated that head_commit is not
675 * a commit object already. parse_commit() will return failure
676 * without further complaints in such a case. Otherwise, if
677 * the commit is invalid, parse_commit() will complain. So
678 * there is nothing for us to say here. Just return failure.
680 if (parse_commit(head_commit))
683 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
686 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
689 static int write_author_script(const char *message)
691 struct strbuf buf = STRBUF_INIT;
696 if (!*message || starts_with(message, "\n")) {
698 /* Missing 'author' line? */
699 unlink(rebase_path_author_script());
701 } else if (skip_prefix(message, "author ", &message))
703 else if ((eol = strchr(message, '\n')))
708 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
709 while (*message && *message != '\n' && *message != '\r')
710 if (skip_prefix(message, " <", &message))
712 else if (*message != '\'')
713 strbuf_addch(&buf, *(message++));
715 strbuf_addf(&buf, "'\\%c'", *(message++));
716 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
717 while (*message && *message != '\n' && *message != '\r')
718 if (skip_prefix(message, "> ", &message))
720 else if (*message != '\'')
721 strbuf_addch(&buf, *(message++));
723 strbuf_addf(&buf, "'\\%c'", *(message++));
724 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
725 while (*message && *message != '\n' && *message != '\r')
726 if (*message != '\'')
727 strbuf_addch(&buf, *(message++));
729 strbuf_addf(&buf, "'\\%c'", *(message++));
730 strbuf_addch(&buf, '\'');
731 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
732 strbuf_release(&buf);
737 * Take a series of KEY='VALUE' lines where VALUE part is
738 * sq-quoted, and append <KEY, VALUE> at the end of the string list
740 static int parse_key_value_squoted(char *buf, struct string_list *list)
743 struct string_list_item *item;
745 char *cp = strchr(buf, '=');
747 np = strchrnul(buf, '\n');
748 return error(_("no key present in '%.*s'"),
749 (int) (np - buf), buf);
751 np = strchrnul(cp, '\n');
753 item = string_list_append(list, buf);
755 buf = np + (*np == '\n');
759 return error(_("unable to dequote value of '%s'"),
761 item->util = xstrdup(cp);
767 * Reads and parses the state directory's "author-script" file, and sets name,
768 * email and date accordingly.
769 * Returns 0 on success, -1 if the file could not be parsed.
771 * The author script is of the format:
773 * GIT_AUTHOR_NAME='$author_name'
774 * GIT_AUTHOR_EMAIL='$author_email'
775 * GIT_AUTHOR_DATE='$author_date'
777 * where $author_name, $author_email and $author_date are quoted. We are strict
778 * with our parsing, as the file was meant to be eval'd in the now-removed
779 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
780 * from what this function expects, it is better to bail out than to do
781 * something that the user does not expect.
783 int read_author_script(const char *path, char **name, char **email, char **date,
786 struct strbuf buf = STRBUF_INIT;
787 struct string_list kv = STRING_LIST_INIT_DUP;
788 int retval = -1; /* assume failure */
789 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
791 if (strbuf_read_file(&buf, path, 256) <= 0) {
792 strbuf_release(&buf);
793 if (errno == ENOENT && allow_missing)
796 return error_errno(_("could not open '%s' for reading"),
800 if (parse_key_value_squoted(buf.buf, &kv))
803 for (i = 0; i < kv.nr; i++) {
804 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
806 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
809 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
811 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
814 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
816 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
820 err = error(_("unknown variable '%s'"),
825 error(_("missing 'GIT_AUTHOR_NAME'"));
827 error(_("missing 'GIT_AUTHOR_EMAIL'"));
829 error(_("missing 'GIT_AUTHOR_DATE'"));
830 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
832 *name = kv.items[name_i].util;
833 *email = kv.items[email_i].util;
834 *date = kv.items[date_i].util;
837 string_list_clear(&kv, !!retval);
838 strbuf_release(&buf);
843 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
844 * file with shell quoting into struct argv_array. Returns -1 on
845 * error, 0 otherwise.
847 static int read_env_script(struct argv_array *env)
849 char *name, *email, *date;
851 if (read_author_script(rebase_path_author_script(),
852 &name, &email, &date, 0))
855 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
856 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
857 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
865 static char *get_author(const char *message)
870 a = find_commit_header(message, "author", &len);
872 return xmemdupz(a, len);
877 static const char *author_date_from_env_array(const struct argv_array *env)
882 for (i = 0; i < env->argc; i++)
883 if (skip_prefix(env->argv[i],
884 "GIT_AUTHOR_DATE=", &date))
887 * If GIT_AUTHOR_DATE is missing we should have already errored out when
890 BUG("GIT_AUTHOR_DATE missing from author script");
893 static const char staged_changes_advice[] =
894 N_("you have staged changes in your working tree\n"
895 "If these changes are meant to be squashed into the previous commit, run:\n"
897 " git commit --amend %s\n"
899 "If they are meant to go into a new commit, run:\n"
903 "In both cases, once you're done, continue with:\n"
905 " git rebase --continue\n");
907 #define ALLOW_EMPTY (1<<0)
908 #define EDIT_MSG (1<<1)
909 #define AMEND_MSG (1<<2)
910 #define CLEANUP_MSG (1<<3)
911 #define VERIFY_MSG (1<<4)
912 #define CREATE_ROOT_COMMIT (1<<5)
914 static int run_command_silent_on_success(struct child_process *cmd)
916 struct strbuf buf = STRBUF_INIT;
919 cmd->stdout_to_stderr = 1;
920 rc = pipe_command(cmd,
926 fputs(buf.buf, stderr);
927 strbuf_release(&buf);
932 * If we are cherry-pick, and if the merge did not result in
933 * hand-editing, we will hit this commit and inherit the original
934 * author date and name.
936 * If we are revert, or if our cherry-pick results in a hand merge,
937 * we had better say that the current user is responsible for that.
939 * An exception is when run_git_commit() is called during an
940 * interactive rebase: in that case, we will want to retain the
943 static int run_git_commit(struct repository *r,
945 struct replay_opts *opts,
948 struct child_process cmd = CHILD_PROCESS_INIT;
952 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
953 const char *gpg_opt = gpg_sign_opt_quoted(opts);
955 return error(_(staged_changes_advice),
959 if (opts->committer_date_is_author_date)
960 argv_array_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
963 author_date_from_env_array(&cmd.env_array));
964 if (opts->ignore_date)
965 argv_array_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
967 argv_array_push(&cmd.args, "commit");
969 if (!(flags & VERIFY_MSG))
970 argv_array_push(&cmd.args, "-n");
971 if ((flags & AMEND_MSG))
972 argv_array_push(&cmd.args, "--amend");
974 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
976 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
977 else if (!(flags & EDIT_MSG))
978 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
979 if ((flags & CLEANUP_MSG))
980 argv_array_push(&cmd.args, "--cleanup=strip");
981 if ((flags & EDIT_MSG))
982 argv_array_push(&cmd.args, "-e");
983 else if (!(flags & CLEANUP_MSG) &&
984 !opts->signoff && !opts->record_origin &&
985 !opts->explicit_cleanup)
986 argv_array_push(&cmd.args, "--cleanup=verbatim");
988 if ((flags & ALLOW_EMPTY))
989 argv_array_push(&cmd.args, "--allow-empty");
991 if (!(flags & EDIT_MSG))
992 argv_array_push(&cmd.args, "--allow-empty-message");
994 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
995 return run_command_silent_on_success(&cmd);
997 return run_command(&cmd);
1000 static int rest_is_empty(const struct strbuf *sb, int start)
1005 /* Check if the rest is just whitespace and Signed-off-by's. */
1006 for (i = start; i < sb->len; i++) {
1007 nl = memchr(sb->buf + i, '\n', sb->len - i);
1013 if (strlen(sign_off_header) <= eol - i &&
1014 starts_with(sb->buf + i, sign_off_header)) {
1019 if (!isspace(sb->buf[i++]))
1026 void cleanup_message(struct strbuf *msgbuf,
1027 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1029 if (verbose || /* Truncate the message just before the diff, if any. */
1030 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1031 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1032 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1033 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1037 * Find out if the message in the strbuf contains only whitespace and
1038 * Signed-off-by lines.
1040 int message_is_empty(const struct strbuf *sb,
1041 enum commit_msg_cleanup_mode cleanup_mode)
1043 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1045 return rest_is_empty(sb, 0);
1049 * See if the user edited the message in the editor or left what
1050 * was in the template intact
1052 int template_untouched(const struct strbuf *sb, const char *template_file,
1053 enum commit_msg_cleanup_mode cleanup_mode)
1055 struct strbuf tmpl = STRBUF_INIT;
1058 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1061 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1064 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1065 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1067 strbuf_release(&tmpl);
1068 return rest_is_empty(sb, start - sb->buf);
1071 int update_head_with_reflog(const struct commit *old_head,
1072 const struct object_id *new_head,
1073 const char *action, const struct strbuf *msg,
1076 struct ref_transaction *transaction;
1077 struct strbuf sb = STRBUF_INIT;
1082 strbuf_addstr(&sb, action);
1083 strbuf_addstr(&sb, ": ");
1086 nl = strchr(msg->buf, '\n');
1088 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1090 strbuf_addbuf(&sb, msg);
1091 strbuf_addch(&sb, '\n');
1094 transaction = ref_transaction_begin(err);
1096 ref_transaction_update(transaction, "HEAD", new_head,
1097 old_head ? &old_head->object.oid : &null_oid,
1099 ref_transaction_commit(transaction, err)) {
1102 ref_transaction_free(transaction);
1103 strbuf_release(&sb);
1108 static int run_rewrite_hook(const struct object_id *oldoid,
1109 const struct object_id *newoid)
1111 struct child_process proc = CHILD_PROCESS_INIT;
1112 const char *argv[3];
1114 struct strbuf sb = STRBUF_INIT;
1116 argv[0] = find_hook("post-rewrite");
1125 proc.stdout_to_stderr = 1;
1126 proc.trace2_hook_name = "post-rewrite";
1128 code = start_command(&proc);
1131 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1132 sigchain_push(SIGPIPE, SIG_IGN);
1133 write_in_full(proc.in, sb.buf, sb.len);
1135 strbuf_release(&sb);
1136 sigchain_pop(SIGPIPE);
1137 return finish_command(&proc);
1140 void commit_post_rewrite(struct repository *r,
1141 const struct commit *old_head,
1142 const struct object_id *new_head)
1144 struct notes_rewrite_cfg *cfg;
1146 cfg = init_copy_notes_for_rewrite("amend");
1148 /* we are amending, so old_head is not NULL */
1149 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1150 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1152 run_rewrite_hook(&old_head->object.oid, new_head);
1155 static int run_prepare_commit_msg_hook(struct repository *r,
1160 const char *name, *arg1 = NULL, *arg2 = NULL;
1162 name = git_path_commit_editmsg();
1163 if (write_message(msg->buf, msg->len, name, 0))
1172 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1174 ret = error(_("'prepare-commit-msg' hook failed"));
1179 static const char implicit_ident_advice_noconfig[] =
1180 N_("Your name and email address were configured automatically based\n"
1181 "on your username and hostname. Please check that they are accurate.\n"
1182 "You can suppress this message by setting them explicitly. Run the\n"
1183 "following command and follow the instructions in your editor to edit\n"
1184 "your configuration file:\n"
1186 " git config --global --edit\n"
1188 "After doing this, you may fix the identity used for this commit with:\n"
1190 " git commit --amend --reset-author\n");
1192 static const char implicit_ident_advice_config[] =
1193 N_("Your name and email address were configured automatically based\n"
1194 "on your username and hostname. Please check that they are accurate.\n"
1195 "You can suppress this message by setting them explicitly:\n"
1197 " git config --global user.name \"Your Name\"\n"
1198 " git config --global user.email you@example.com\n"
1200 "After doing this, you may fix the identity used for this commit with:\n"
1202 " git commit --amend --reset-author\n");
1204 static const char *implicit_ident_advice(void)
1206 char *user_config = expand_user_path("~/.gitconfig", 0);
1207 char *xdg_config = xdg_config_home("config");
1208 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1214 return _(implicit_ident_advice_config);
1216 return _(implicit_ident_advice_noconfig);
1220 void print_commit_summary(struct repository *r,
1222 const struct object_id *oid,
1225 struct rev_info rev;
1226 struct commit *commit;
1227 struct strbuf format = STRBUF_INIT;
1229 struct pretty_print_context pctx = {0};
1230 struct strbuf author_ident = STRBUF_INIT;
1231 struct strbuf committer_ident = STRBUF_INIT;
1233 commit = lookup_commit(r, oid);
1235 die(_("couldn't look up newly created commit"));
1236 if (parse_commit(commit))
1237 die(_("could not parse newly created commit"));
1239 strbuf_addstr(&format, "format:%h] %s");
1241 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1242 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1243 if (strbuf_cmp(&author_ident, &committer_ident)) {
1244 strbuf_addstr(&format, "\n Author: ");
1245 strbuf_addbuf_percentquote(&format, &author_ident);
1247 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1248 struct strbuf date = STRBUF_INIT;
1250 format_commit_message(commit, "%ad", &date, &pctx);
1251 strbuf_addstr(&format, "\n Date: ");
1252 strbuf_addbuf_percentquote(&format, &date);
1253 strbuf_release(&date);
1255 if (!committer_ident_sufficiently_given()) {
1256 strbuf_addstr(&format, "\n Committer: ");
1257 strbuf_addbuf_percentquote(&format, &committer_ident);
1258 if (advice_implicit_identity) {
1259 strbuf_addch(&format, '\n');
1260 strbuf_addstr(&format, implicit_ident_advice());
1263 strbuf_release(&author_ident);
1264 strbuf_release(&committer_ident);
1266 repo_init_revisions(r, &rev, prefix);
1267 setup_revisions(0, NULL, &rev, NULL);
1270 rev.diffopt.output_format =
1271 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1273 rev.verbose_header = 1;
1274 rev.show_root_diff = 1;
1275 get_commit_format(format.buf, &rev);
1276 rev.always_show_header = 0;
1277 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1278 rev.diffopt.break_opt = 0;
1279 diff_setup_done(&rev.diffopt);
1281 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1283 die_errno(_("unable to resolve HEAD after creating commit"));
1284 if (!strcmp(head, "HEAD"))
1285 head = _("detached HEAD");
1287 skip_prefix(head, "refs/heads/", &head);
1288 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1289 _(" (root-commit)") : "");
1291 if (!log_tree_commit(&rev, commit)) {
1292 rev.always_show_header = 1;
1293 rev.use_terminator = 1;
1294 log_tree_commit(&rev, commit);
1297 strbuf_release(&format);
1300 static int parse_head(struct repository *r, struct commit **head)
1302 struct commit *current_head;
1303 struct object_id oid;
1305 if (get_oid("HEAD", &oid)) {
1306 current_head = NULL;
1308 current_head = lookup_commit_reference(r, &oid);
1310 return error(_("could not parse HEAD"));
1311 if (!oideq(&oid, ¤t_head->object.oid)) {
1312 warning(_("HEAD %s is not a commit!"),
1315 if (parse_commit(current_head))
1316 return error(_("could not parse HEAD commit"));
1318 *head = current_head;
1324 * Try to commit without forking 'git commit'. In some cases we need
1325 * to run 'git commit' to display an error message
1328 * -1 - error unable to commit
1330 * 1 - run 'git commit'
1332 static int try_to_commit(struct repository *r,
1333 struct strbuf *msg, const char *author,
1334 struct replay_opts *opts, unsigned int flags,
1335 struct object_id *oid)
1337 struct object_id tree;
1338 struct commit *current_head = NULL;
1339 struct commit_list *parents = NULL;
1340 struct commit_extra_header *extra = NULL;
1341 struct strbuf err = STRBUF_INIT;
1342 struct strbuf commit_msg = STRBUF_INIT;
1343 char *amend_author = NULL;
1344 const char *committer = NULL;
1345 const char *hook_commit = NULL;
1346 enum commit_msg_cleanup_mode cleanup;
1349 if (parse_head(r, ¤t_head))
1352 if (flags & AMEND_MSG) {
1353 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1354 const char *out_enc = get_commit_output_encoding();
1355 const char *message = logmsg_reencode(current_head, NULL,
1359 const char *orig_message = NULL;
1361 find_commit_subject(message, &orig_message);
1363 strbuf_addstr(msg, orig_message);
1364 hook_commit = "HEAD";
1366 author = amend_author = get_author(message);
1367 unuse_commit_buffer(current_head, message);
1369 res = error(_("unable to parse commit author"));
1372 parents = copy_commit_list(current_head->parents);
1373 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1374 } else if (current_head &&
1375 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1376 commit_list_insert(current_head, &parents);
1379 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1380 res = error(_("git write-tree failed to write a tree"));
1384 if (!(flags & ALLOW_EMPTY)) {
1385 struct commit *first_parent = current_head;
1387 if (flags & AMEND_MSG) {
1388 if (current_head->parents) {
1389 first_parent = current_head->parents->item;
1390 if (repo_parse_commit(r, first_parent)) {
1391 res = error(_("could not parse HEAD commit"));
1395 first_parent = NULL;
1398 if (oideq(first_parent
1399 ? get_commit_tree_oid(first_parent)
1400 : the_hash_algo->empty_tree,
1402 res = 1; /* run 'git commit' to display error message */
1407 if (find_hook("prepare-commit-msg")) {
1408 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1411 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1413 res = error_errno(_("unable to read commit message "
1415 git_path_commit_editmsg());
1421 if (flags & CLEANUP_MSG)
1422 cleanup = COMMIT_MSG_CLEANUP_ALL;
1423 else if ((opts->signoff || opts->record_origin) &&
1424 !opts->explicit_cleanup)
1425 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1427 cleanup = opts->default_msg_cleanup;
1429 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1430 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1431 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1432 res = 1; /* run 'git commit' to display error message */
1436 if (opts->committer_date_is_author_date) {
1437 struct ident_split id;
1438 struct strbuf date = STRBUF_INIT;
1440 if (!opts->ignore_date) {
1441 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1442 res = error(_("invalid author identity '%s'"),
1446 if (!id.date_begin) {
1448 "corrupt author: missing date information"));
1451 strbuf_addf(&date, "@%.*s %.*s",
1452 (int)(id.date_end - id.date_begin),
1454 (int)(id.tz_end - id.tz_begin),
1459 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1460 getenv("GIT_COMMITTER_EMAIL"),
1461 WANT_COMMITTER_IDENT,
1462 opts->ignore_date ? NULL : date.buf,
1464 strbuf_release(&date);
1469 if (opts->ignore_date) {
1470 struct ident_split id;
1473 if (split_ident_line(&id, author, strlen(author)) < 0) {
1474 error(_("invalid author identity '%s'"), author);
1477 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1478 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1479 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1485 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1486 author, committer, opts->gpg_sign, extra)) {
1487 res = error(_("failed to write commit object"));
1491 if (update_head_with_reflog(current_head, oid,
1492 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1493 res = error("%s", err.buf);
1497 run_commit_hook(0, r->index_file, "post-commit", NULL);
1498 if (flags & AMEND_MSG)
1499 commit_post_rewrite(r, current_head, oid);
1502 free_commit_extra_headers(extra);
1503 strbuf_release(&err);
1504 strbuf_release(&commit_msg);
1510 static int write_rebase_head(struct object_id *oid)
1512 if (update_ref("rebase", "REBASE_HEAD", oid,
1513 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1514 return error(_("could not update %s"), "REBASE_HEAD");
1519 static int do_commit(struct repository *r,
1520 const char *msg_file, const char *author,
1521 struct replay_opts *opts, unsigned int flags,
1522 struct object_id *oid)
1526 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1527 struct object_id oid;
1528 struct strbuf sb = STRBUF_INIT;
1530 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1531 return error_errno(_("unable to read commit message "
1535 res = try_to_commit(r, msg_file ? &sb : NULL,
1536 author, opts, flags, &oid);
1537 strbuf_release(&sb);
1539 unlink(git_path_cherry_pick_head(r));
1540 unlink(git_path_merge_msg(r));
1541 if (!is_rebase_i(opts))
1542 print_commit_summary(r, NULL, &oid,
1543 SUMMARY_SHOW_AUTHOR_DATE);
1548 if (is_rebase_i(opts) && oid)
1549 if (write_rebase_head(oid))
1551 return run_git_commit(r, msg_file, opts, flags);
1557 static int is_original_commit_empty(struct commit *commit)
1559 const struct object_id *ptree_oid;
1561 if (parse_commit(commit))
1562 return error(_("could not parse commit %s"),
1563 oid_to_hex(&commit->object.oid));
1564 if (commit->parents) {
1565 struct commit *parent = commit->parents->item;
1566 if (parse_commit(parent))
1567 return error(_("could not parse parent commit %s"),
1568 oid_to_hex(&parent->object.oid));
1569 ptree_oid = get_commit_tree_oid(parent);
1571 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1574 return oideq(ptree_oid, get_commit_tree_oid(commit));
1578 * Should empty commits be allowed? Return status:
1579 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1580 * 0: Halt on empty commit
1581 * 1: Allow empty commit
1582 * 2: Drop empty commit
1584 static int allow_empty(struct repository *r,
1585 struct replay_opts *opts,
1586 struct commit *commit)
1588 int index_unchanged, originally_empty;
1593 * (1) we do not allow empty at all and error out.
1595 * (2) we allow ones that were initially empty, and
1596 * just drop the ones that become empty
1598 * (3) we allow ones that were initially empty, but
1599 * halt for the ones that become empty;
1601 * (4) we allow both.
1603 if (!opts->allow_empty)
1604 return 0; /* let "git commit" barf as necessary */
1606 index_unchanged = is_index_unchanged(r);
1607 if (index_unchanged < 0)
1608 return index_unchanged;
1609 if (!index_unchanged)
1610 return 0; /* we do not have to say --allow-empty */
1612 if (opts->keep_redundant_commits)
1615 originally_empty = is_original_commit_empty(commit);
1616 if (originally_empty < 0)
1617 return originally_empty;
1618 if (originally_empty)
1620 else if (opts->drop_redundant_commits)
1629 } todo_command_info[] = {
1646 static const char *command_to_string(const enum todo_command command)
1648 if (command < TODO_COMMENT)
1649 return todo_command_info[command].str;
1650 die(_("unknown command: %d"), command);
1653 static char command_to_char(const enum todo_command command)
1655 if (command < TODO_COMMENT && todo_command_info[command].c)
1656 return todo_command_info[command].c;
1657 return comment_line_char;
1660 static int is_noop(const enum todo_command command)
1662 return TODO_NOOP <= command;
1665 static int is_fixup(enum todo_command command)
1667 return command == TODO_FIXUP || command == TODO_SQUASH;
1670 /* Does this command create a (non-merge) commit? */
1671 static int is_pick_or_similar(enum todo_command command)
1686 static int update_squash_messages(struct repository *r,
1687 enum todo_command command,
1688 struct commit *commit,
1689 struct replay_opts *opts)
1691 struct strbuf buf = STRBUF_INIT;
1693 const char *message, *body;
1694 const char *encoding = get_commit_output_encoding();
1696 if (opts->current_fixup_count > 0) {
1697 struct strbuf header = STRBUF_INIT;
1700 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1701 return error(_("could not read '%s'"),
1702 rebase_path_squash_msg());
1704 eol = buf.buf[0] != comment_line_char ?
1705 buf.buf : strchrnul(buf.buf, '\n');
1707 strbuf_addf(&header, "%c ", comment_line_char);
1708 strbuf_addf(&header, _("This is a combination of %d commits."),
1709 opts->current_fixup_count + 2);
1710 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1711 strbuf_release(&header);
1713 struct object_id head;
1714 struct commit *head_commit;
1715 const char *head_message, *body;
1717 if (get_oid("HEAD", &head))
1718 return error(_("need a HEAD to fixup"));
1719 if (!(head_commit = lookup_commit_reference(r, &head)))
1720 return error(_("could not read HEAD"));
1721 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1722 return error(_("could not read HEAD's commit message"));
1724 find_commit_subject(head_message, &body);
1725 if (write_message(body, strlen(body),
1726 rebase_path_fixup_msg(), 0)) {
1727 unuse_commit_buffer(head_commit, head_message);
1728 return error(_("cannot write '%s'"),
1729 rebase_path_fixup_msg());
1732 strbuf_addf(&buf, "%c ", comment_line_char);
1733 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1734 strbuf_addf(&buf, "\n%c ", comment_line_char);
1735 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1736 strbuf_addstr(&buf, "\n\n");
1737 strbuf_addstr(&buf, body);
1739 unuse_commit_buffer(head_commit, head_message);
1742 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1743 return error(_("could not read commit message of %s"),
1744 oid_to_hex(&commit->object.oid));
1745 find_commit_subject(message, &body);
1747 if (command == TODO_SQUASH) {
1748 unlink(rebase_path_fixup_msg());
1749 strbuf_addf(&buf, "\n%c ", comment_line_char);
1750 strbuf_addf(&buf, _("This is the commit message #%d:"),
1751 ++opts->current_fixup_count + 1);
1752 strbuf_addstr(&buf, "\n\n");
1753 strbuf_addstr(&buf, body);
1754 } else if (command == TODO_FIXUP) {
1755 strbuf_addf(&buf, "\n%c ", comment_line_char);
1756 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1757 ++opts->current_fixup_count + 1);
1758 strbuf_addstr(&buf, "\n\n");
1759 strbuf_add_commented_lines(&buf, body, strlen(body));
1761 return error(_("unknown command: %d"), command);
1762 unuse_commit_buffer(commit, message);
1764 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1765 strbuf_release(&buf);
1768 strbuf_addf(&opts->current_fixups, "%s%s %s",
1769 opts->current_fixups.len ? "\n" : "",
1770 command_to_string(command),
1771 oid_to_hex(&commit->object.oid));
1772 res = write_message(opts->current_fixups.buf,
1773 opts->current_fixups.len,
1774 rebase_path_current_fixups(), 0);
1780 static void flush_rewritten_pending(void)
1782 struct strbuf buf = STRBUF_INIT;
1783 struct object_id newoid;
1786 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1787 !get_oid("HEAD", &newoid) &&
1788 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1789 char *bol = buf.buf, *eol;
1792 eol = strchrnul(bol, '\n');
1793 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1794 bol, oid_to_hex(&newoid));
1800 unlink(rebase_path_rewritten_pending());
1802 strbuf_release(&buf);
1805 static void record_in_rewritten(struct object_id *oid,
1806 enum todo_command next_command)
1808 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1813 fprintf(out, "%s\n", oid_to_hex(oid));
1816 if (!is_fixup(next_command))
1817 flush_rewritten_pending();
1820 static int do_pick_commit(struct repository *r,
1821 enum todo_command command,
1822 struct commit *commit,
1823 struct replay_opts *opts,
1824 int final_fixup, int *check_todo)
1826 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1827 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1828 struct object_id head;
1829 struct commit *base, *next, *parent;
1830 const char *base_label, *next_label;
1831 char *author = NULL;
1832 struct commit_message msg = { NULL, NULL, NULL, NULL };
1833 struct strbuf msgbuf = STRBUF_INIT;
1834 int res, unborn = 0, reword = 0, allow, drop_commit;
1836 if (opts->no_commit) {
1838 * We do not intend to commit immediately. We just want to
1839 * merge the differences in, so let's compute the tree
1840 * that represents the "current" state for merge-recursive
1843 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1844 return error(_("your index file is unmerged."));
1846 unborn = get_oid("HEAD", &head);
1847 /* Do we want to generate a root commit? */
1848 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1849 oideq(&head, &opts->squash_onto)) {
1850 if (is_fixup(command))
1851 return error(_("cannot fixup root commit"));
1852 flags |= CREATE_ROOT_COMMIT;
1855 oidcpy(&head, the_hash_algo->empty_tree);
1856 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1858 return error_dirty_index(r, opts);
1860 discard_index(r->index);
1862 if (!commit->parents)
1864 else if (commit->parents->next) {
1865 /* Reverting or cherry-picking a merge commit */
1867 struct commit_list *p;
1869 if (!opts->mainline)
1870 return error(_("commit %s is a merge but no -m option was given."),
1871 oid_to_hex(&commit->object.oid));
1873 for (cnt = 1, p = commit->parents;
1874 cnt != opts->mainline && p;
1877 if (cnt != opts->mainline || !p)
1878 return error(_("commit %s does not have parent %d"),
1879 oid_to_hex(&commit->object.oid), opts->mainline);
1881 } else if (1 < opts->mainline)
1883 * Non-first parent explicitly specified as mainline for
1886 return error(_("commit %s does not have parent %d"),
1887 oid_to_hex(&commit->object.oid), opts->mainline);
1889 parent = commit->parents->item;
1891 if (get_message(commit, &msg) != 0)
1892 return error(_("cannot get commit message for %s"),
1893 oid_to_hex(&commit->object.oid));
1895 if (opts->allow_ff && !is_fixup(command) &&
1896 ((parent && oideq(&parent->object.oid, &head)) ||
1897 (!parent && unborn))) {
1898 if (is_rebase_i(opts))
1899 write_author_script(msg.message);
1900 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1902 if (res || command != TODO_REWORD)
1906 goto fast_forward_edit;
1908 if (parent && parse_commit(parent) < 0)
1909 /* TRANSLATORS: The first %s will be a "todo" command like
1910 "revert" or "pick", the second %s a SHA1. */
1911 return error(_("%s: cannot parse parent commit %s"),
1912 command_to_string(command),
1913 oid_to_hex(&parent->object.oid));
1916 * "commit" is an existing commit. We would want to apply
1917 * the difference it introduces since its first parent "prev"
1918 * on top of the current HEAD if we are cherry-pick. Or the
1919 * reverse of it if we are revert.
1922 if (command == TODO_REVERT) {
1924 base_label = msg.label;
1926 next_label = msg.parent_label;
1927 strbuf_addstr(&msgbuf, "Revert \"");
1928 strbuf_addstr(&msgbuf, msg.subject);
1929 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1930 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1932 if (commit->parents && commit->parents->next) {
1933 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1934 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1936 strbuf_addstr(&msgbuf, ".\n");
1941 base_label = msg.parent_label;
1943 next_label = msg.label;
1945 /* Append the commit log message to msgbuf. */
1946 if (find_commit_subject(msg.message, &p))
1947 strbuf_addstr(&msgbuf, p);
1949 if (opts->record_origin) {
1950 strbuf_complete_line(&msgbuf);
1951 if (!has_conforming_footer(&msgbuf, NULL, 0))
1952 strbuf_addch(&msgbuf, '\n');
1953 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1954 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1955 strbuf_addstr(&msgbuf, ")\n");
1957 if (!is_fixup(command))
1958 author = get_author(msg.message);
1961 if (command == TODO_REWORD)
1963 else if (is_fixup(command)) {
1964 if (update_squash_messages(r, command, commit, opts))
1968 msg_file = rebase_path_squash_msg();
1969 else if (file_exists(rebase_path_fixup_msg())) {
1970 flags |= CLEANUP_MSG;
1971 msg_file = rebase_path_fixup_msg();
1973 const char *dest = git_path_squash_msg(r);
1975 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1976 return error(_("could not rename '%s' to '%s'"),
1977 rebase_path_squash_msg(), dest);
1978 unlink(git_path_merge_msg(r));
1984 if (opts->signoff && !is_fixup(command))
1985 append_signoff(&msgbuf, 0, 0);
1987 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1989 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1990 res = do_recursive_merge(r, base, next, base_label, next_label,
1991 &head, &msgbuf, opts);
1995 res |= write_message(msgbuf.buf, msgbuf.len,
1996 git_path_merge_msg(r), 0);
1998 struct commit_list *common = NULL;
1999 struct commit_list *remotes = NULL;
2001 res = write_message(msgbuf.buf, msgbuf.len,
2002 git_path_merge_msg(r), 0);
2004 commit_list_insert(base, &common);
2005 commit_list_insert(next, &remotes);
2006 res |= try_merge_command(r, opts->strategy,
2007 opts->xopts_nr, (const char **)opts->xopts,
2008 common, oid_to_hex(&head), remotes);
2009 free_commit_list(common);
2010 free_commit_list(remotes);
2012 strbuf_release(&msgbuf);
2015 * If the merge was clean or if it failed due to conflict, we write
2016 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2017 * However, if the merge did not even start, then we don't want to
2020 if ((command == TODO_PICK || command == TODO_REWORD ||
2021 command == TODO_EDIT) && !opts->no_commit &&
2022 (res == 0 || res == 1) &&
2023 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2024 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2026 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2027 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2028 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2032 error(command == TODO_REVERT
2033 ? _("could not revert %s... %s")
2034 : _("could not apply %s... %s"),
2035 short_commit_name(commit), msg.subject);
2036 print_advice(r, res == 1, opts);
2037 repo_rerere(r, opts->allow_rerere_auto);
2042 allow = allow_empty(r, opts, commit);
2046 } else if (allow == 1) {
2047 flags |= ALLOW_EMPTY;
2048 } else if (allow == 2) {
2050 unlink(git_path_cherry_pick_head(r));
2051 unlink(git_path_merge_msg(r));
2053 _("dropping %s %s -- patch contents already upstream\n"),
2054 oid_to_hex(&commit->object.oid), msg.subject);
2055 } /* else allow == 0 and there's nothing special to do */
2056 if (!opts->no_commit && !drop_commit) {
2057 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2058 res = do_commit(r, msg_file, author, opts, flags,
2059 commit? &commit->object.oid : NULL);
2061 res = error(_("unable to parse commit author"));
2062 *check_todo = !!(flags & EDIT_MSG);
2063 if (!res && reword) {
2065 res = run_git_commit(r, NULL, opts, EDIT_MSG |
2066 VERIFY_MSG | AMEND_MSG |
2067 (flags & ALLOW_EMPTY));
2073 if (!res && final_fixup) {
2074 unlink(rebase_path_fixup_msg());
2075 unlink(rebase_path_squash_msg());
2076 unlink(rebase_path_current_fixups());
2077 strbuf_reset(&opts->current_fixups);
2078 opts->current_fixup_count = 0;
2082 free_message(commit, &msg);
2084 update_abort_safety_file();
2089 static int prepare_revs(struct replay_opts *opts)
2092 * picking (but not reverting) ranges (but not individual revisions)
2093 * should be done in reverse
2095 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2096 opts->revs->reverse ^= 1;
2098 if (prepare_revision_walk(opts->revs))
2099 return error(_("revision walk setup failed"));
2104 static int read_and_refresh_cache(struct repository *r,
2105 struct replay_opts *opts)
2107 struct lock_file index_lock = LOCK_INIT;
2108 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2109 if (repo_read_index(r) < 0) {
2110 rollback_lock_file(&index_lock);
2111 return error(_("git %s: failed to read the index"),
2112 _(action_name(opts)));
2114 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2115 if (index_fd >= 0) {
2116 if (write_locked_index(r->index, &index_lock,
2117 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2118 return error(_("git %s: failed to refresh the index"),
2119 _(action_name(opts)));
2125 enum todo_item_flags {
2126 TODO_EDIT_MERGE_MSG = 1
2129 void todo_list_release(struct todo_list *todo_list)
2131 strbuf_release(&todo_list->buf);
2132 FREE_AND_NULL(todo_list->items);
2133 todo_list->nr = todo_list->alloc = 0;
2136 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2138 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2139 todo_list->total_nr++;
2140 return todo_list->items + todo_list->nr++;
2143 const char *todo_item_get_arg(struct todo_list *todo_list,
2144 struct todo_item *item)
2146 return todo_list->buf.buf + item->arg_offset;
2149 static int is_command(enum todo_command command, const char **bol)
2151 const char *str = todo_command_info[command].str;
2152 const char nick = todo_command_info[command].c;
2153 const char *p = *bol + 1;
2155 return skip_prefix(*bol, str, bol) ||
2156 ((nick && **bol == nick) &&
2157 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2161 static int parse_insn_line(struct repository *r, struct todo_item *item,
2162 const char *buf, const char *bol, char *eol)
2164 struct object_id commit_oid;
2165 char *end_of_object_name;
2166 int i, saved, status, padding;
2171 bol += strspn(bol, " \t");
2173 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2174 item->command = TODO_COMMENT;
2175 item->commit = NULL;
2176 item->arg_offset = bol - buf;
2177 item->arg_len = eol - bol;
2181 for (i = 0; i < TODO_COMMENT; i++)
2182 if (is_command(i, &bol)) {
2186 if (i >= TODO_COMMENT)
2189 /* Eat up extra spaces/ tabs before object name */
2190 padding = strspn(bol, " \t");
2193 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2195 return error(_("%s does not accept arguments: '%s'"),
2196 command_to_string(item->command), bol);
2197 item->commit = NULL;
2198 item->arg_offset = bol - buf;
2199 item->arg_len = eol - bol;
2204 return error(_("missing arguments for %s"),
2205 command_to_string(item->command));
2207 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2208 item->command == TODO_RESET) {
2209 item->commit = NULL;
2210 item->arg_offset = bol - buf;
2211 item->arg_len = (int)(eol - bol);
2215 if (item->command == TODO_MERGE) {
2216 if (skip_prefix(bol, "-C", &bol))
2217 bol += strspn(bol, " \t");
2218 else if (skip_prefix(bol, "-c", &bol)) {
2219 bol += strspn(bol, " \t");
2220 item->flags |= TODO_EDIT_MERGE_MSG;
2222 item->flags |= TODO_EDIT_MERGE_MSG;
2223 item->commit = NULL;
2224 item->arg_offset = bol - buf;
2225 item->arg_len = (int)(eol - bol);
2230 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2231 saved = *end_of_object_name;
2232 *end_of_object_name = '\0';
2233 status = get_oid(bol, &commit_oid);
2235 error(_("could not parse '%s'"), bol); /* return later */
2236 *end_of_object_name = saved;
2238 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2239 item->arg_offset = bol - buf;
2240 item->arg_len = (int)(eol - bol);
2245 item->commit = lookup_commit_reference(r, &commit_oid);
2246 return item->commit ? 0 : -1;
2249 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2251 const char *todo_file, *bol;
2252 struct strbuf buf = STRBUF_INIT;
2255 todo_file = git_path_todo_file();
2256 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2257 if (errno == ENOENT || errno == ENOTDIR)
2260 return error_errno("unable to open '%s'", todo_file);
2262 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2263 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2264 *action = REPLAY_PICK;
2265 else if (is_command(TODO_REVERT, &bol) &&
2266 (*bol == ' ' || *bol == '\t'))
2267 *action = REPLAY_REVERT;
2271 strbuf_release(&buf);
2276 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2277 struct todo_list *todo_list)
2279 struct todo_item *item;
2280 char *p = buf, *next_p;
2281 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2283 todo_list->current = todo_list->nr = 0;
2285 for (i = 1; *p; i++, p = next_p) {
2286 char *eol = strchrnul(p, '\n');
2288 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2290 if (p != eol && eol[-1] == '\r')
2291 eol--; /* strip Carriage Return */
2293 item = append_new_todo(todo_list);
2294 item->offset_in_buf = p - todo_list->buf.buf;
2295 if (parse_insn_line(r, item, buf, p, eol)) {
2296 res = error(_("invalid line %d: %.*s"),
2297 i, (int)(eol - p), p);
2298 item->command = TODO_COMMENT + 1;
2299 item->arg_offset = p - buf;
2300 item->arg_len = (int)(eol - p);
2301 item->commit = NULL;
2306 else if (is_fixup(item->command))
2307 return error(_("cannot '%s' without a previous commit"),
2308 command_to_string(item->command));
2309 else if (!is_noop(item->command))
2316 static int count_commands(struct todo_list *todo_list)
2320 for (i = 0; i < todo_list->nr; i++)
2321 if (todo_list->items[i].command != TODO_COMMENT)
2327 static int get_item_line_offset(struct todo_list *todo_list, int index)
2329 return index < todo_list->nr ?
2330 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2333 static const char *get_item_line(struct todo_list *todo_list, int index)
2335 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2338 static int get_item_line_length(struct todo_list *todo_list, int index)
2340 return get_item_line_offset(todo_list, index + 1)
2341 - get_item_line_offset(todo_list, index);
2344 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2349 fd = open(path, O_RDONLY);
2351 return error_errno(_("could not open '%s'"), path);
2352 len = strbuf_read(sb, fd, 0);
2355 return error(_("could not read '%s'."), path);
2359 static int have_finished_the_last_pick(void)
2361 struct strbuf buf = STRBUF_INIT;
2363 const char *todo_path = git_path_todo_file();
2366 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2367 if (errno == ENOENT) {
2370 error_errno("unable to open '%s'", todo_path);
2374 /* If there is only one line then we are done */
2375 eol = strchr(buf.buf, '\n');
2376 if (!eol || !eol[1])
2379 strbuf_release(&buf);
2384 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2386 struct replay_opts opts = REPLAY_OPTS_INIT;
2387 int need_cleanup = 0;
2389 if (file_exists(git_path_cherry_pick_head(r))) {
2390 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2391 warning(_("cancelling a cherry picking in progress"));
2392 opts.action = REPLAY_PICK;
2396 if (file_exists(git_path_revert_head(r))) {
2397 if (!unlink(git_path_revert_head(r)) && verbose)
2398 warning(_("cancelling a revert in progress"));
2399 opts.action = REPLAY_REVERT;
2406 if (!have_finished_the_last_pick())
2409 sequencer_remove_state(&opts);
2412 static void todo_list_write_total_nr(struct todo_list *todo_list)
2414 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2417 fprintf(f, "%d\n", todo_list->total_nr);
2422 static int read_populate_todo(struct repository *r,
2423 struct todo_list *todo_list,
2424 struct replay_opts *opts)
2427 const char *todo_file = get_todo_path(opts);
2430 strbuf_reset(&todo_list->buf);
2431 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2434 res = stat(todo_file, &st);
2436 return error(_("could not stat '%s'"), todo_file);
2437 fill_stat_data(&todo_list->stat, &st);
2439 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2441 if (is_rebase_i(opts))
2442 return error(_("please fix this using "
2443 "'git rebase --edit-todo'."));
2444 return error(_("unusable instruction sheet: '%s'"), todo_file);
2447 if (!todo_list->nr &&
2448 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2449 return error(_("no commits parsed."));
2451 if (!is_rebase_i(opts)) {
2452 enum todo_command valid =
2453 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2456 for (i = 0; i < todo_list->nr; i++)
2457 if (valid == todo_list->items[i].command)
2459 else if (valid == TODO_PICK)
2460 return error(_("cannot cherry-pick during a revert."));
2462 return error(_("cannot revert during a cherry-pick."));
2465 if (is_rebase_i(opts)) {
2466 struct todo_list done = TODO_LIST_INIT;
2468 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2469 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2470 todo_list->done_nr = count_commands(&done);
2472 todo_list->done_nr = 0;
2474 todo_list->total_nr = todo_list->done_nr
2475 + count_commands(todo_list);
2476 todo_list_release(&done);
2478 todo_list_write_total_nr(todo_list);
2484 static int git_config_string_dup(char **dest,
2485 const char *var, const char *value)
2488 return config_error_nonbool(var);
2490 *dest = xstrdup(value);
2494 static int populate_opts_cb(const char *key, const char *value, void *data)
2496 struct replay_opts *opts = data;
2501 else if (!strcmp(key, "options.no-commit"))
2502 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2503 else if (!strcmp(key, "options.edit"))
2504 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2505 else if (!strcmp(key, "options.allow-empty"))
2507 git_config_bool_or_int(key, value, &error_flag);
2508 else if (!strcmp(key, "options.allow-empty-message"))
2509 opts->allow_empty_message =
2510 git_config_bool_or_int(key, value, &error_flag);
2511 else if (!strcmp(key, "options.keep-redundant-commits"))
2512 opts->keep_redundant_commits =
2513 git_config_bool_or_int(key, value, &error_flag);
2514 else if (!strcmp(key, "options.signoff"))
2515 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2516 else if (!strcmp(key, "options.record-origin"))
2517 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2518 else if (!strcmp(key, "options.allow-ff"))
2519 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2520 else if (!strcmp(key, "options.mainline"))
2521 opts->mainline = git_config_int(key, value);
2522 else if (!strcmp(key, "options.strategy"))
2523 git_config_string_dup(&opts->strategy, key, value);
2524 else if (!strcmp(key, "options.gpg-sign"))
2525 git_config_string_dup(&opts->gpg_sign, key, value);
2526 else if (!strcmp(key, "options.strategy-option")) {
2527 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2528 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2529 } else if (!strcmp(key, "options.allow-rerere-auto"))
2530 opts->allow_rerere_auto =
2531 git_config_bool_or_int(key, value, &error_flag) ?
2532 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2533 else if (!strcmp(key, "options.default-msg-cleanup")) {
2534 opts->explicit_cleanup = 1;
2535 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2537 return error(_("invalid key: %s"), key);
2540 return error(_("invalid value for %s: %s"), key, value);
2545 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2548 char *strategy_opts_string = raw_opts;
2550 if (*strategy_opts_string == ' ')
2551 strategy_opts_string++;
2553 opts->xopts_nr = split_cmdline(strategy_opts_string,
2554 (const char ***)&opts->xopts);
2555 for (i = 0; i < opts->xopts_nr; i++) {
2556 const char *arg = opts->xopts[i];
2558 skip_prefix(arg, "--", &arg);
2559 opts->xopts[i] = xstrdup(arg);
2563 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2566 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2568 opts->strategy = strbuf_detach(buf, NULL);
2569 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2572 parse_strategy_opts(opts, buf->buf);
2575 static int read_populate_opts(struct replay_opts *opts)
2577 if (is_rebase_i(opts)) {
2578 struct strbuf buf = STRBUF_INIT;
2580 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2581 if (!starts_with(buf.buf, "-S"))
2584 free(opts->gpg_sign);
2585 opts->gpg_sign = xstrdup(buf.buf + 2);
2590 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2591 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2592 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2593 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2594 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2598 if (file_exists(rebase_path_verbose()))
2601 if (file_exists(rebase_path_quiet()))
2604 if (file_exists(rebase_path_signoff())) {
2609 if (file_exists(rebase_path_cdate_is_adate())) {
2611 opts->committer_date_is_author_date = 1;
2614 if (file_exists(rebase_path_ignore_date())) {
2616 opts->ignore_date = 1;
2619 if (file_exists(rebase_path_reschedule_failed_exec()))
2620 opts->reschedule_failed_exec = 1;
2622 if (file_exists(rebase_path_drop_redundant_commits()))
2623 opts->drop_redundant_commits = 1;
2625 if (file_exists(rebase_path_keep_redundant_commits()))
2626 opts->keep_redundant_commits = 1;
2628 read_strategy_opts(opts, &buf);
2629 strbuf_release(&buf);
2631 if (read_oneliner(&opts->current_fixups,
2632 rebase_path_current_fixups(), 1)) {
2633 const char *p = opts->current_fixups.buf;
2634 opts->current_fixup_count = 1;
2635 while ((p = strchr(p, '\n'))) {
2636 opts->current_fixup_count++;
2641 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2642 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2643 return error(_("unusable squash-onto"));
2644 opts->have_squash_onto = 1;
2650 if (!file_exists(git_path_opts_file()))
2653 * The function git_parse_source(), called from git_config_from_file(),
2654 * may die() in case of a syntactically incorrect file. We do not care
2655 * about this case, though, because we wrote that file ourselves, so we
2656 * are pretty certain that it is syntactically correct.
2658 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2659 return error(_("malformed options sheet: '%s'"),
2660 git_path_opts_file());
2664 static void write_strategy_opts(struct replay_opts *opts)
2667 struct strbuf buf = STRBUF_INIT;
2669 for (i = 0; i < opts->xopts_nr; ++i)
2670 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2672 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2673 strbuf_release(&buf);
2676 int write_basic_state(struct replay_opts *opts, const char *head_name,
2677 struct commit *onto, const char *orig_head)
2680 write_file(rebase_path_head_name(), "%s\n", head_name);
2682 write_file(rebase_path_onto(), "%s\n",
2683 oid_to_hex(&onto->object.oid));
2685 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2688 write_file(rebase_path_quiet(), "%s", "");
2690 write_file(rebase_path_verbose(), "%s", "");
2692 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2693 if (opts->xopts_nr > 0)
2694 write_strategy_opts(opts);
2696 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2697 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2698 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2699 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2702 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2704 write_file(rebase_path_signoff(), "--signoff\n");
2705 if (opts->drop_redundant_commits)
2706 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2707 if (opts->keep_redundant_commits)
2708 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2709 if (opts->committer_date_is_author_date)
2710 write_file(rebase_path_cdate_is_adate(), "%s", "");
2711 if (opts->ignore_date)
2712 write_file(rebase_path_ignore_date(), "%s", "");
2713 if (opts->reschedule_failed_exec)
2714 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2719 static int walk_revs_populate_todo(struct todo_list *todo_list,
2720 struct replay_opts *opts)
2722 enum todo_command command = opts->action == REPLAY_PICK ?
2723 TODO_PICK : TODO_REVERT;
2724 const char *command_string = todo_command_info[command].str;
2725 const char *encoding;
2726 struct commit *commit;
2728 if (prepare_revs(opts))
2731 encoding = get_log_output_encoding();
2733 while ((commit = get_revision(opts->revs))) {
2734 struct todo_item *item = append_new_todo(todo_list);
2735 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2736 const char *subject;
2739 item->command = command;
2740 item->commit = commit;
2741 item->arg_offset = 0;
2743 item->offset_in_buf = todo_list->buf.len;
2744 subject_len = find_commit_subject(commit_buffer, &subject);
2745 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2746 short_commit_name(commit), subject_len, subject);
2747 unuse_commit_buffer(commit, commit_buffer);
2751 return error(_("empty commit set passed"));
2756 static int create_seq_dir(struct repository *r)
2758 enum replay_action action;
2759 const char *in_progress_error = NULL;
2760 const char *in_progress_advice = NULL;
2761 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2762 file_exists(git_path_cherry_pick_head(r));
2764 if (!sequencer_get_last_command(r, &action)) {
2767 in_progress_error = _("revert is already in progress");
2768 in_progress_advice =
2769 _("try \"git revert (--continue | %s--abort | --quit)\"");
2772 in_progress_error = _("cherry-pick is already in progress");
2773 in_progress_advice =
2774 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2777 BUG("unexpected action in create_seq_dir");
2780 if (in_progress_error) {
2781 error("%s", in_progress_error);
2782 if (advice_sequencer_in_use)
2783 advise(in_progress_advice,
2784 advise_skip ? "--skip | " : "");
2787 if (mkdir(git_path_seq_dir(), 0777) < 0)
2788 return error_errno(_("could not create sequencer directory '%s'"),
2789 git_path_seq_dir());
2794 static int save_head(const char *head)
2796 struct lock_file head_lock = LOCK_INIT;
2797 struct strbuf buf = STRBUF_INIT;
2801 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2803 return error_errno(_("could not lock HEAD"));
2804 strbuf_addf(&buf, "%s\n", head);
2805 written = write_in_full(fd, buf.buf, buf.len);
2806 strbuf_release(&buf);
2808 error_errno(_("could not write to '%s'"), git_path_head_file());
2809 rollback_lock_file(&head_lock);
2812 if (commit_lock_file(&head_lock) < 0)
2813 return error(_("failed to finalize '%s'"), git_path_head_file());
2817 static int rollback_is_safe(void)
2819 struct strbuf sb = STRBUF_INIT;
2820 struct object_id expected_head, actual_head;
2822 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2824 if (get_oid_hex(sb.buf, &expected_head)) {
2825 strbuf_release(&sb);
2826 die(_("could not parse %s"), git_path_abort_safety_file());
2828 strbuf_release(&sb);
2830 else if (errno == ENOENT)
2831 oidclr(&expected_head);
2833 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2835 if (get_oid("HEAD", &actual_head))
2836 oidclr(&actual_head);
2838 return oideq(&actual_head, &expected_head);
2841 static int reset_merge(const struct object_id *oid)
2844 struct argv_array argv = ARGV_ARRAY_INIT;
2846 argv_array_pushl(&argv, "reset", "--merge", NULL);
2848 if (!is_null_oid(oid))
2849 argv_array_push(&argv, oid_to_hex(oid));
2851 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2852 argv_array_clear(&argv);
2857 static int rollback_single_pick(struct repository *r)
2859 struct object_id head_oid;
2861 if (!file_exists(git_path_cherry_pick_head(r)) &&
2862 !file_exists(git_path_revert_head(r)))
2863 return error(_("no cherry-pick or revert in progress"));
2864 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2865 return error(_("cannot resolve HEAD"));
2866 if (is_null_oid(&head_oid))
2867 return error(_("cannot abort from a branch yet to be born"));
2868 return reset_merge(&head_oid);
2871 static int skip_single_pick(void)
2873 struct object_id head;
2875 if (read_ref_full("HEAD", 0, &head, NULL))
2876 return error(_("cannot resolve HEAD"));
2877 return reset_merge(&head);
2880 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2883 struct object_id oid;
2884 struct strbuf buf = STRBUF_INIT;
2887 f = fopen(git_path_head_file(), "r");
2888 if (!f && errno == ENOENT) {
2890 * There is no multiple-cherry-pick in progress.
2891 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2892 * a single-cherry-pick in progress, abort that.
2894 return rollback_single_pick(r);
2897 return error_errno(_("cannot open '%s'"), git_path_head_file());
2898 if (strbuf_getline_lf(&buf, f)) {
2899 error(_("cannot read '%s': %s"), git_path_head_file(),
2900 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2905 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2906 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2907 git_path_head_file());
2910 if (is_null_oid(&oid)) {
2911 error(_("cannot abort from a branch yet to be born"));
2915 if (!rollback_is_safe()) {
2916 /* Do not error, just do not rollback */
2917 warning(_("You seem to have moved HEAD. "
2918 "Not rewinding, check your HEAD!"));
2920 if (reset_merge(&oid))
2922 strbuf_release(&buf);
2923 return sequencer_remove_state(opts);
2925 strbuf_release(&buf);
2929 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2931 enum replay_action action = -1;
2932 sequencer_get_last_command(r, &action);
2935 * Check whether the subcommand requested to skip the commit is actually
2936 * in progress and that it's safe to skip the commit.
2938 * opts->action tells us which subcommand requested to skip the commit.
2939 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2940 * action is in progress and we can skip the commit.
2942 * Otherwise we check that the last instruction was related to the
2943 * particular subcommand we're trying to execute and barf if that's not
2946 * Finally we check that the rollback is "safe", i.e., has the HEAD
2947 * moved? In this case, it doesn't make sense to "reset the merge" and
2948 * "skip the commit" as the user already handled this by committing. But
2949 * we'd not want to barf here, instead give advice on how to proceed. We
2950 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2951 * it gets removed when the user commits, so if it still exists we're
2952 * sure the user can't have committed before.
2954 switch (opts->action) {
2956 if (!file_exists(git_path_revert_head(r))) {
2957 if (action != REPLAY_REVERT)
2958 return error(_("no revert in progress"));
2959 if (!rollback_is_safe())
2964 if (!file_exists(git_path_cherry_pick_head(r))) {
2965 if (action != REPLAY_PICK)
2966 return error(_("no cherry-pick in progress"));
2967 if (!rollback_is_safe())
2972 BUG("unexpected action in sequencer_skip");
2975 if (skip_single_pick())
2976 return error(_("failed to skip the commit"));
2977 if (!is_directory(git_path_seq_dir()))
2980 return sequencer_continue(r, opts);
2983 error(_("there is nothing to skip"));
2985 if (advice_resolve_conflict) {
2986 advise(_("have you committed already?\n"
2987 "try \"git %s --continue\""),
2988 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2993 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2995 struct lock_file todo_lock = LOCK_INIT;
2996 const char *todo_path = get_todo_path(opts);
2997 int next = todo_list->current, offset, fd;
3000 * rebase -i writes "git-rebase-todo" without the currently executing
3001 * command, appending it to "done" instead.
3003 if (is_rebase_i(opts))
3006 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3008 return error_errno(_("could not lock '%s'"), todo_path);
3009 offset = get_item_line_offset(todo_list, next);
3010 if (write_in_full(fd, todo_list->buf.buf + offset,
3011 todo_list->buf.len - offset) < 0)
3012 return error_errno(_("could not write to '%s'"), todo_path);
3013 if (commit_lock_file(&todo_lock) < 0)
3014 return error(_("failed to finalize '%s'"), todo_path);
3016 if (is_rebase_i(opts) && next > 0) {
3017 const char *done = rebase_path_done();
3018 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3023 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3024 get_item_line_length(todo_list, next - 1))
3026 ret = error_errno(_("could not write to '%s'"), done);
3028 ret = error_errno(_("failed to finalize '%s'"), done);
3034 static int save_opts(struct replay_opts *opts)
3036 const char *opts_file = git_path_opts_file();
3039 if (opts->no_commit)
3040 res |= git_config_set_in_file_gently(opts_file,
3041 "options.no-commit", "true");
3043 res |= git_config_set_in_file_gently(opts_file,
3044 "options.edit", "true");
3045 if (opts->allow_empty)
3046 res |= git_config_set_in_file_gently(opts_file,
3047 "options.allow-empty", "true");
3048 if (opts->allow_empty_message)
3049 res |= git_config_set_in_file_gently(opts_file,
3050 "options.allow-empty-message", "true");
3051 if (opts->keep_redundant_commits)
3052 res |= git_config_set_in_file_gently(opts_file,
3053 "options.keep-redundant-commits", "true");
3055 res |= git_config_set_in_file_gently(opts_file,
3056 "options.signoff", "true");
3057 if (opts->record_origin)
3058 res |= git_config_set_in_file_gently(opts_file,
3059 "options.record-origin", "true");
3061 res |= git_config_set_in_file_gently(opts_file,
3062 "options.allow-ff", "true");
3063 if (opts->mainline) {
3064 struct strbuf buf = STRBUF_INIT;
3065 strbuf_addf(&buf, "%d", opts->mainline);
3066 res |= git_config_set_in_file_gently(opts_file,
3067 "options.mainline", buf.buf);
3068 strbuf_release(&buf);
3071 res |= git_config_set_in_file_gently(opts_file,
3072 "options.strategy", opts->strategy);
3074 res |= git_config_set_in_file_gently(opts_file,
3075 "options.gpg-sign", opts->gpg_sign);
3078 for (i = 0; i < opts->xopts_nr; i++)
3079 res |= git_config_set_multivar_in_file_gently(opts_file,
3080 "options.strategy-option",
3081 opts->xopts[i], "^$", 0);
3083 if (opts->allow_rerere_auto)
3084 res |= git_config_set_in_file_gently(opts_file,
3085 "options.allow-rerere-auto",
3086 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3089 if (opts->explicit_cleanup)
3090 res |= git_config_set_in_file_gently(opts_file,
3091 "options.default-msg-cleanup",
3092 describe_cleanup_mode(opts->default_msg_cleanup));
3096 static int make_patch(struct repository *r,
3097 struct commit *commit,
3098 struct replay_opts *opts)
3100 struct strbuf buf = STRBUF_INIT;
3101 struct rev_info log_tree_opt;
3102 const char *subject, *p;
3105 p = short_commit_name(commit);
3106 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3108 res |= write_rebase_head(&commit->object.oid);
3110 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3111 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3112 repo_init_revisions(r, &log_tree_opt, NULL);
3113 log_tree_opt.abbrev = 0;
3114 log_tree_opt.diff = 1;
3115 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3116 log_tree_opt.disable_stdin = 1;
3117 log_tree_opt.no_commit_id = 1;
3118 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3119 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3120 if (!log_tree_opt.diffopt.file)
3121 res |= error_errno(_("could not open '%s'"), buf.buf);
3123 res |= log_tree_commit(&log_tree_opt, commit);
3124 fclose(log_tree_opt.diffopt.file);
3128 strbuf_addf(&buf, "%s/message", get_dir(opts));
3129 if (!file_exists(buf.buf)) {
3130 const char *encoding = get_commit_output_encoding();
3131 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3132 find_commit_subject(commit_buffer, &subject);
3133 res |= write_message(subject, strlen(subject), buf.buf, 1);
3134 unuse_commit_buffer(commit, commit_buffer);
3136 strbuf_release(&buf);
3141 static int intend_to_amend(void)
3143 struct object_id head;
3146 if (get_oid("HEAD", &head))
3147 return error(_("cannot read HEAD"));
3149 p = oid_to_hex(&head);
3150 return write_message(p, strlen(p), rebase_path_amend(), 1);
3153 static int error_with_patch(struct repository *r,
3154 struct commit *commit,
3155 const char *subject, int subject_len,
3156 struct replay_opts *opts,
3157 int exit_code, int to_amend)
3160 if (make_patch(r, commit, opts))
3162 } else if (copy_file(rebase_path_message(),
3163 git_path_merge_msg(r), 0666))
3164 return error(_("unable to copy '%s' to '%s'"),
3165 git_path_merge_msg(r), rebase_path_message());
3168 if (intend_to_amend())
3172 _("You can amend the commit now, with\n"
3174 " git commit --amend %s\n"
3176 "Once you are satisfied with your changes, run\n"
3178 " git rebase --continue\n"),
3179 gpg_sign_opt_quoted(opts));
3180 } else if (exit_code) {
3182 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3183 short_commit_name(commit), subject_len, subject);
3186 * We don't have the hash of the parent so
3187 * just print the line from the todo file.
3189 fprintf_ln(stderr, _("Could not merge %.*s"),
3190 subject_len, subject);
3196 static int error_failed_squash(struct repository *r,
3197 struct commit *commit,
3198 struct replay_opts *opts,
3200 const char *subject)
3202 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3203 return error(_("could not copy '%s' to '%s'"),
3204 rebase_path_squash_msg(), rebase_path_message());
3205 unlink(git_path_merge_msg(r));
3206 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3207 return error(_("could not copy '%s' to '%s'"),
3208 rebase_path_message(),
3209 git_path_merge_msg(r));
3210 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3213 static int do_exec(struct repository *r, const char *command_line)
3215 struct argv_array child_env = ARGV_ARRAY_INIT;
3216 const char *child_argv[] = { NULL, NULL };
3219 fprintf(stderr, "Executing: %s\n", command_line);
3220 child_argv[0] = command_line;
3221 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3222 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3223 absolute_path(get_git_work_tree()));
3224 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3227 /* force re-reading of the cache */
3228 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3229 return error(_("could not read index"));
3231 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3234 warning(_("execution failed: %s\n%s"
3235 "You can fix the problem, and then run\n"
3237 " git rebase --continue\n"
3240 dirty ? N_("and made changes to the index and/or the "
3241 "working tree\n") : "");
3243 /* command not found */
3246 warning(_("execution succeeded: %s\nbut "
3247 "left changes to the index and/or the working tree\n"
3248 "Commit or stash your changes, and then run\n"
3250 " git rebase --continue\n"
3251 "\n"), command_line);
3255 argv_array_clear(&child_env);
3260 static int safe_append(const char *filename, const char *fmt, ...)
3263 struct lock_file lock = LOCK_INIT;
3264 int fd = hold_lock_file_for_update(&lock, filename,
3265 LOCK_REPORT_ON_ERROR);
3266 struct strbuf buf = STRBUF_INIT;
3271 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3272 error_errno(_("could not read '%s'"), filename);
3273 rollback_lock_file(&lock);
3276 strbuf_complete(&buf, '\n');
3278 strbuf_vaddf(&buf, fmt, ap);
3281 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3282 error_errno(_("could not write to '%s'"), filename);
3283 strbuf_release(&buf);
3284 rollback_lock_file(&lock);
3287 if (commit_lock_file(&lock) < 0) {
3288 strbuf_release(&buf);
3289 rollback_lock_file(&lock);
3290 return error(_("failed to finalize '%s'"), filename);
3293 strbuf_release(&buf);
3297 static int do_label(struct repository *r, const char *name, int len)
3299 struct ref_store *refs = get_main_ref_store(r);
3300 struct ref_transaction *transaction;
3301 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3302 struct strbuf msg = STRBUF_INIT;
3304 struct object_id head_oid;
3306 if (len == 1 && *name == '#')
3307 return error(_("illegal label name: '%.*s'"), len, name);
3309 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3310 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3312 transaction = ref_store_transaction_begin(refs, &err);
3314 error("%s", err.buf);
3316 } else if (get_oid("HEAD", &head_oid)) {
3317 error(_("could not read HEAD"));
3319 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3320 NULL, 0, msg.buf, &err) < 0 ||
3321 ref_transaction_commit(transaction, &err)) {
3322 error("%s", err.buf);
3325 ref_transaction_free(transaction);
3326 strbuf_release(&err);
3327 strbuf_release(&msg);
3330 ret = safe_append(rebase_path_refs_to_delete(),
3331 "%s\n", ref_name.buf);
3332 strbuf_release(&ref_name);
3337 static const char *reflog_message(struct replay_opts *opts,
3338 const char *sub_action, const char *fmt, ...);
3340 static int do_reset(struct repository *r,
3341 const char *name, int len,
3342 struct replay_opts *opts)
3344 struct strbuf ref_name = STRBUF_INIT;
3345 struct object_id oid;
3346 struct lock_file lock = LOCK_INIT;
3347 struct tree_desc desc;
3349 struct unpack_trees_options unpack_tree_opts;
3352 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3355 if (len == 10 && !strncmp("[new root]", name, len)) {
3356 if (!opts->have_squash_onto) {
3358 if (commit_tree("", 0, the_hash_algo->empty_tree,
3359 NULL, &opts->squash_onto,
3361 return error(_("writing fake root commit"));
3362 opts->have_squash_onto = 1;
3363 hex = oid_to_hex(&opts->squash_onto);
3364 if (write_message(hex, strlen(hex),
3365 rebase_path_squash_onto(), 0))
3366 return error(_("writing squash-onto"));
3368 oidcpy(&oid, &opts->squash_onto);
3372 /* Determine the length of the label */
3373 for (i = 0; i < len; i++)
3374 if (isspace(name[i]))
3378 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3379 if (get_oid(ref_name.buf, &oid) &&
3380 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3381 error(_("could not read '%s'"), ref_name.buf);
3382 rollback_lock_file(&lock);
3383 strbuf_release(&ref_name);
3388 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3389 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3390 unpack_tree_opts.head_idx = 1;
3391 unpack_tree_opts.src_index = r->index;
3392 unpack_tree_opts.dst_index = r->index;
3393 unpack_tree_opts.fn = oneway_merge;
3394 unpack_tree_opts.merge = 1;
3395 unpack_tree_opts.update = 1;
3396 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3398 if (repo_read_index_unmerged(r)) {
3399 rollback_lock_file(&lock);
3400 strbuf_release(&ref_name);
3401 return error_resolve_conflict(_(action_name(opts)));
3404 if (!fill_tree_descriptor(r, &desc, &oid)) {
3405 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3406 rollback_lock_file(&lock);
3407 free((void *)desc.buffer);
3408 strbuf_release(&ref_name);
3412 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3413 rollback_lock_file(&lock);
3414 free((void *)desc.buffer);
3415 strbuf_release(&ref_name);
3419 tree = parse_tree_indirect(&oid);
3420 prime_cache_tree(r, r->index, tree);
3422 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3423 ret = error(_("could not write index"));
3424 free((void *)desc.buffer);
3427 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3428 len, name), "HEAD", &oid,
3429 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3431 strbuf_release(&ref_name);
3435 static struct commit *lookup_label(const char *label, int len,
3438 struct commit *commit;
3441 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3442 commit = lookup_commit_reference_by_name(buf->buf);
3444 /* fall back to non-rewritten ref or commit */
3445 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3446 commit = lookup_commit_reference_by_name(buf->buf);
3450 error(_("could not resolve '%s'"), buf->buf);
3455 static int do_merge(struct repository *r,
3456 struct commit *commit,
3457 const char *arg, int arg_len,
3458 int flags, struct replay_opts *opts)
3460 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3461 EDIT_MSG | VERIFY_MSG : 0;
3462 struct strbuf ref_name = STRBUF_INIT;
3463 struct commit *head_commit, *merge_commit, *i;
3464 struct commit_list *bases, *j, *reversed = NULL;
3465 struct commit_list *to_merge = NULL, **tail = &to_merge;
3466 const char *strategy = !opts->xopts_nr &&
3467 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3468 NULL : opts->strategy;
3469 struct merge_options o;
3470 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3471 static struct lock_file lock;
3474 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3479 head_commit = lookup_commit_reference_by_name("HEAD");
3481 ret = error(_("cannot merge without a current revision"));
3486 * For octopus merges, the arg starts with the list of revisions to be
3487 * merged. The list is optionally followed by '#' and the oneline.
3489 merge_arg_len = oneline_offset = arg_len;
3490 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3493 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3494 p += 1 + strspn(p + 1, " \t\n");
3495 oneline_offset = p - arg;
3498 k = strcspn(p, " \t\n");
3501 merge_commit = lookup_label(p, k, &ref_name);
3502 if (!merge_commit) {
3503 ret = error(_("unable to parse '%.*s'"), k, p);
3506 tail = &commit_list_insert(merge_commit, tail)->next;
3508 merge_arg_len = p - arg;
3512 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3516 if (opts->have_squash_onto &&
3517 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3519 * When the user tells us to "merge" something into a
3520 * "[new root]", let's simply fast-forward to the merge head.
3522 rollback_lock_file(&lock);
3524 ret = error(_("octopus merge cannot be executed on "
3525 "top of a [new root]"));
3527 ret = fast_forward_to(r, &to_merge->item->object.oid,
3528 &head_commit->object.oid, 0,
3534 const char *encoding = get_commit_output_encoding();
3535 const char *message = logmsg_reencode(commit, NULL, encoding);
3540 ret = error(_("could not get commit message of '%s'"),
3541 oid_to_hex(&commit->object.oid));
3544 write_author_script(message);
3545 find_commit_subject(message, &body);
3547 ret = write_message(body, len, git_path_merge_msg(r), 0);
3548 unuse_commit_buffer(commit, message);
3550 error_errno(_("could not write '%s'"),
3551 git_path_merge_msg(r));
3555 struct strbuf buf = STRBUF_INIT;
3558 strbuf_addf(&buf, "author %s", git_author_info(0));
3559 write_author_script(buf.buf);
3562 if (oneline_offset < arg_len) {
3563 p = arg + oneline_offset;
3564 len = arg_len - oneline_offset;
3566 strbuf_addf(&buf, "Merge %s '%.*s'",
3567 to_merge->next ? "branches" : "branch",
3568 merge_arg_len, arg);
3573 ret = write_message(p, len, git_path_merge_msg(r), 0);
3574 strbuf_release(&buf);
3576 error_errno(_("could not write '%s'"),
3577 git_path_merge_msg(r));
3583 * If HEAD is not identical to the first parent of the original merge
3584 * commit, we cannot fast-forward.
3586 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3587 oideq(&commit->parents->item->object.oid,
3588 &head_commit->object.oid);
3591 * If any merge head is different from the original one, we cannot
3594 if (can_fast_forward) {
3595 struct commit_list *p = commit->parents->next;
3597 for (j = to_merge; j && p; j = j->next, p = p->next)
3598 if (!oideq(&j->item->object.oid,
3599 &p->item->object.oid)) {
3600 can_fast_forward = 0;
3604 * If the number of merge heads differs from the original merge
3605 * commit, we cannot fast-forward.
3608 can_fast_forward = 0;
3611 if (can_fast_forward) {
3612 rollback_lock_file(&lock);
3613 ret = fast_forward_to(r, &commit->object.oid,
3614 &head_commit->object.oid, 0, opts);
3615 if (flags & TODO_EDIT_MERGE_MSG) {
3616 run_commit_flags |= AMEND_MSG;
3617 goto fast_forward_edit;
3622 if (strategy || to_merge->next) {
3624 struct child_process cmd = CHILD_PROCESS_INIT;
3626 if (read_env_script(&cmd.env_array)) {
3627 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3629 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3633 if (opts->committer_date_is_author_date)
3634 argv_array_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3637 author_date_from_env_array(&cmd.env_array));
3638 if (opts->ignore_date)
3639 argv_array_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3642 argv_array_push(&cmd.args, "merge");
3643 argv_array_push(&cmd.args, "-s");
3645 argv_array_push(&cmd.args, "octopus");
3647 argv_array_push(&cmd.args, strategy);
3648 for (k = 0; k < opts->xopts_nr; k++)
3649 argv_array_pushf(&cmd.args,
3650 "-X%s", opts->xopts[k]);
3652 argv_array_push(&cmd.args, "--no-edit");
3653 argv_array_push(&cmd.args, "--no-ff");
3654 argv_array_push(&cmd.args, "--no-log");
3655 argv_array_push(&cmd.args, "--no-stat");
3656 argv_array_push(&cmd.args, "-F");
3657 argv_array_push(&cmd.args, git_path_merge_msg(r));
3659 argv_array_push(&cmd.args, opts->gpg_sign);
3661 /* Add the tips to be merged */
3662 for (j = to_merge; j; j = j->next)
3663 argv_array_push(&cmd.args,
3664 oid_to_hex(&j->item->object.oid));
3666 strbuf_release(&ref_name);
3667 unlink(git_path_cherry_pick_head(r));
3668 rollback_lock_file(&lock);
3670 rollback_lock_file(&lock);
3671 ret = run_command(&cmd);
3673 /* force re-reading of the cache */
3674 if (!ret && (discard_index(r->index) < 0 ||
3675 repo_read_index(r) < 0))
3676 ret = error(_("could not read index"));
3680 merge_commit = to_merge->item;
3681 bases = get_merge_bases(head_commit, merge_commit);
3682 if (bases && oideq(&merge_commit->object.oid,
3683 &bases->item->object.oid)) {
3685 /* skip merging an ancestor of HEAD */
3689 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3690 git_path_merge_head(r), 0);
3691 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3693 for (j = bases; j; j = j->next)
3694 commit_list_insert(j->item, &reversed);
3695 free_commit_list(bases);
3698 init_merge_options(&o, r);
3700 o.branch2 = ref_name.buf;
3701 o.buffer_output = 2;
3703 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3705 fputs(o.obuf.buf, stdout);
3706 strbuf_release(&o.obuf);
3708 error(_("could not even attempt to merge '%.*s'"),
3709 merge_arg_len, arg);
3713 * The return value of merge_recursive() is 1 on clean, and 0 on
3716 * Let's reverse that, so that do_merge() returns 0 upon success and
3717 * 1 upon failed merge (keeping the return value -1 for the cases where
3718 * we will want to reschedule the `merge` command).
3722 if (r->index->cache_changed &&
3723 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3724 ret = error(_("merge: Unable to write new index file"));
3728 rollback_lock_file(&lock);
3730 repo_rerere(r, opts->allow_rerere_auto);
3733 * In case of problems, we now want to return a positive
3734 * value (a negative one would indicate that the `merge`
3735 * command needs to be rescheduled).
3738 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3742 strbuf_release(&ref_name);
3743 rollback_lock_file(&lock);
3744 free_commit_list(to_merge);
3748 static int is_final_fixup(struct todo_list *todo_list)
3750 int i = todo_list->current;
3752 if (!is_fixup(todo_list->items[i].command))
3755 while (++i < todo_list->nr)
3756 if (is_fixup(todo_list->items[i].command))
3758 else if (!is_noop(todo_list->items[i].command))
3763 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3767 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3768 if (!is_noop(todo_list->items[i].command))
3769 return todo_list->items[i].command;
3774 static int apply_autostash(struct replay_opts *opts)
3776 struct strbuf stash_sha1 = STRBUF_INIT;
3777 struct child_process child = CHILD_PROCESS_INIT;
3780 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3781 strbuf_release(&stash_sha1);
3784 strbuf_trim(&stash_sha1);
3787 child.no_stdout = 1;
3788 child.no_stderr = 1;
3789 argv_array_push(&child.args, "stash");
3790 argv_array_push(&child.args, "apply");
3791 argv_array_push(&child.args, stash_sha1.buf);
3792 if (!run_command(&child))
3793 fprintf(stderr, _("Applied autostash.\n"));
3795 struct child_process store = CHILD_PROCESS_INIT;
3798 argv_array_push(&store.args, "stash");
3799 argv_array_push(&store.args, "store");
3800 argv_array_push(&store.args, "-m");
3801 argv_array_push(&store.args, "autostash");
3802 argv_array_push(&store.args, "-q");
3803 argv_array_push(&store.args, stash_sha1.buf);
3804 if (run_command(&store))
3805 ret = error(_("cannot store %s"), stash_sha1.buf);
3808 _("Applying autostash resulted in conflicts.\n"
3809 "Your changes are safe in the stash.\n"
3810 "You can run \"git stash pop\" or"
3811 " \"git stash drop\" at any time.\n"));
3814 strbuf_release(&stash_sha1);
3818 static const char *reflog_message(struct replay_opts *opts,
3819 const char *sub_action, const char *fmt, ...)
3822 static struct strbuf buf = STRBUF_INIT;
3826 strbuf_addstr(&buf, action_name(opts));
3828 strbuf_addf(&buf, " (%s)", sub_action);
3830 strbuf_addstr(&buf, ": ");
3831 strbuf_vaddf(&buf, fmt, ap);
3838 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3839 const char *commit, const char *action)
3841 struct child_process cmd = CHILD_PROCESS_INIT;
3846 argv_array_push(&cmd.args, "checkout");
3847 argv_array_push(&cmd.args, commit);
3848 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3851 ret = run_command(&cmd);
3853 ret = run_command_silent_on_success(&cmd);
3856 discard_index(r->index);
3861 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3862 const char *onto_name, const struct object_id *onto,
3863 const char *orig_head)
3865 struct object_id oid;
3866 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3868 if (get_oid(orig_head, &oid))
3869 return error(_("%s: not a valid OID"), orig_head);
3871 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3872 apply_autostash(opts);
3873 sequencer_remove_state(opts);
3874 return error(_("could not detach HEAD"));
3877 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3880 static int stopped_at_head(struct repository *r)
3882 struct object_id head;
3883 struct commit *commit;
3884 struct commit_message message;
3886 if (get_oid("HEAD", &head) ||
3887 !(commit = lookup_commit(r, &head)) ||
3888 parse_commit(commit) || get_message(commit, &message))
3889 fprintf(stderr, _("Stopped at HEAD\n"));
3891 fprintf(stderr, _("Stopped at %s\n"), message.label);
3892 free_message(commit, &message);
3898 static const char rescheduled_advice[] =
3899 N_("Could not execute the todo command\n"
3903 "It has been rescheduled; To edit the command before continuing, please\n"
3904 "edit the todo list first:\n"
3906 " git rebase --edit-todo\n"
3907 " git rebase --continue\n");
3909 static int pick_commits(struct repository *r,
3910 struct todo_list *todo_list,
3911 struct replay_opts *opts)
3913 int res = 0, reschedule = 0;
3915 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3917 assert(!(opts->signoff || opts->no_commit ||
3918 opts->record_origin || opts->edit ||
3919 opts->committer_date_is_author_date ||
3920 opts->ignore_date));
3921 if (read_and_refresh_cache(r, opts))
3924 while (todo_list->current < todo_list->nr) {
3925 struct todo_item *item = todo_list->items + todo_list->current;
3926 const char *arg = todo_item_get_arg(todo_list, item);
3929 if (save_todo(todo_list, opts))
3931 if (is_rebase_i(opts)) {
3932 if (item->command != TODO_COMMENT) {
3933 FILE *f = fopen(rebase_path_msgnum(), "w");
3935 todo_list->done_nr++;
3938 fprintf(f, "%d\n", todo_list->done_nr);
3942 fprintf(stderr, "Rebasing (%d/%d)%s",
3944 todo_list->total_nr,
3945 opts->verbose ? "\n" : "\r");
3947 unlink(rebase_path_message());
3948 unlink(rebase_path_author_script());
3949 unlink(rebase_path_stopped_sha());
3950 unlink(rebase_path_amend());
3951 unlink(git_path_merge_head(r));
3952 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3954 if (item->command == TODO_BREAK) {
3957 return stopped_at_head(r);
3960 if (item->command <= TODO_SQUASH) {
3961 if (is_rebase_i(opts))
3962 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3963 command_to_string(item->command), NULL),
3965 res = do_pick_commit(r, item->command, item->commit,
3966 opts, is_final_fixup(todo_list),
3968 if (is_rebase_i(opts) && res < 0) {
3970 advise(_(rescheduled_advice),
3971 get_item_line_length(todo_list,
3972 todo_list->current),
3973 get_item_line(todo_list,
3974 todo_list->current));
3975 todo_list->current--;
3976 if (save_todo(todo_list, opts))
3979 if (item->command == TODO_EDIT) {
3980 struct commit *commit = item->commit;
3985 _("Stopped at %s... %.*s\n"),
3986 short_commit_name(commit),
3987 item->arg_len, arg);
3989 return error_with_patch(r, commit,
3990 arg, item->arg_len, opts, res, !res);
3992 if (is_rebase_i(opts) && !res)
3993 record_in_rewritten(&item->commit->object.oid,
3994 peek_command(todo_list, 1));
3995 if (res && is_fixup(item->command)) {
3998 return error_failed_squash(r, item->commit, opts,
3999 item->arg_len, arg);
4000 } else if (res && is_rebase_i(opts) && item->commit) {
4002 struct object_id oid;
4005 * If we are rewording and have either
4006 * fast-forwarded already, or are about to
4007 * create a new root commit, we want to amend,
4008 * otherwise we do not.
4010 if (item->command == TODO_REWORD &&
4011 !get_oid("HEAD", &oid) &&
4012 (oideq(&item->commit->object.oid, &oid) ||
4013 (opts->have_squash_onto &&
4014 oideq(&opts->squash_onto, &oid))))
4017 return res | error_with_patch(r, item->commit,
4018 arg, item->arg_len, opts,
4021 } else if (item->command == TODO_EXEC) {
4022 char *end_of_arg = (char *)(arg + item->arg_len);
4023 int saved = *end_of_arg;
4028 res = do_exec(r, arg);
4029 *end_of_arg = saved;
4032 if (opts->reschedule_failed_exec)
4036 } else if (item->command == TODO_LABEL) {
4037 if ((res = do_label(r, arg, item->arg_len)))
4039 } else if (item->command == TODO_RESET) {
4040 if ((res = do_reset(r, arg, item->arg_len, opts)))
4042 } else if (item->command == TODO_MERGE) {
4043 if ((res = do_merge(r, item->commit,
4045 item->flags, opts)) < 0)
4047 else if (item->commit)
4048 record_in_rewritten(&item->commit->object.oid,
4049 peek_command(todo_list, 1));
4051 /* failed with merge conflicts */
4052 return error_with_patch(r, item->commit,
4055 } else if (!is_noop(item->command))
4056 return error(_("unknown command %d"), item->command);
4059 advise(_(rescheduled_advice),
4060 get_item_line_length(todo_list,
4061 todo_list->current),
4062 get_item_line(todo_list, todo_list->current));
4063 todo_list->current--;
4064 if (save_todo(todo_list, opts))
4067 return error_with_patch(r,
4071 } else if (is_rebase_i(opts) && check_todo && !res) {
4074 if (stat(get_todo_path(opts), &st)) {
4075 res = error_errno(_("could not stat '%s'"),
4076 get_todo_path(opts));
4077 } else if (match_stat_data(&todo_list->stat, &st)) {
4078 /* Reread the todo file if it has changed. */
4079 todo_list_release(todo_list);
4080 if (read_populate_todo(r, todo_list, opts))
4081 res = -1; /* message was printed */
4082 /* `current` will be incremented below */
4083 todo_list->current = -1;
4087 todo_list->current++;
4092 if (is_rebase_i(opts)) {
4093 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4096 /* Stopped in the middle, as planned? */
4097 if (todo_list->current < todo_list->nr)
4100 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4101 starts_with(head_ref.buf, "refs/")) {
4103 struct object_id head, orig;
4106 if (get_oid("HEAD", &head)) {
4107 res = error(_("cannot read HEAD"));
4109 strbuf_release(&head_ref);
4110 strbuf_release(&buf);
4113 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4114 get_oid_hex(buf.buf, &orig)) {
4115 res = error(_("could not read orig-head"));
4116 goto cleanup_head_ref;
4119 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4120 res = error(_("could not read 'onto'"));
4121 goto cleanup_head_ref;
4123 msg = reflog_message(opts, "finish", "%s onto %s",
4124 head_ref.buf, buf.buf);
4125 if (update_ref(msg, head_ref.buf, &head, &orig,
4126 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4127 res = error(_("could not update %s"),
4129 goto cleanup_head_ref;
4131 msg = reflog_message(opts, "finish", "returning to %s",
4133 if (create_symref("HEAD", head_ref.buf, msg)) {
4134 res = error(_("could not update HEAD to %s"),
4136 goto cleanup_head_ref;
4141 if (opts->verbose) {
4142 struct rev_info log_tree_opt;
4143 struct object_id orig, head;
4145 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4146 repo_init_revisions(r, &log_tree_opt, NULL);
4147 log_tree_opt.diff = 1;
4148 log_tree_opt.diffopt.output_format =
4149 DIFF_FORMAT_DIFFSTAT;
4150 log_tree_opt.disable_stdin = 1;
4152 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4153 !get_oid(buf.buf, &orig) &&
4154 !get_oid("HEAD", &head)) {
4155 diff_tree_oid(&orig, &head, "",
4156 &log_tree_opt.diffopt);
4157 log_tree_diff_flush(&log_tree_opt);
4160 flush_rewritten_pending();
4161 if (!stat(rebase_path_rewritten_list(), &st) &&
4163 struct child_process child = CHILD_PROCESS_INIT;
4164 const char *post_rewrite_hook =
4165 find_hook("post-rewrite");
4167 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4169 argv_array_push(&child.args, "notes");
4170 argv_array_push(&child.args, "copy");
4171 argv_array_push(&child.args, "--for-rewrite=rebase");
4172 /* we don't care if this copying failed */
4173 run_command(&child);
4175 if (post_rewrite_hook) {
4176 struct child_process hook = CHILD_PROCESS_INIT;
4178 hook.in = open(rebase_path_rewritten_list(),
4180 hook.stdout_to_stderr = 1;
4181 hook.trace2_hook_name = "post-rewrite";
4182 argv_array_push(&hook.args, post_rewrite_hook);
4183 argv_array_push(&hook.args, "rebase");
4184 /* we don't care if this hook failed */
4188 apply_autostash(opts);
4194 "Successfully rebased and updated %s.\n",
4198 strbuf_release(&buf);
4199 strbuf_release(&head_ref);
4203 * Sequence of picks finished successfully; cleanup by
4204 * removing the .git/sequencer directory
4206 return sequencer_remove_state(opts);
4209 static int continue_single_pick(struct repository *r)
4211 const char *argv[] = { "commit", NULL };
4213 if (!file_exists(git_path_cherry_pick_head(r)) &&
4214 !file_exists(git_path_revert_head(r)))
4215 return error(_("no cherry-pick or revert in progress"));
4216 return run_command_v_opt(argv, RUN_GIT_CMD);
4219 static int commit_staged_changes(struct repository *r,
4220 struct replay_opts *opts,
4221 struct todo_list *todo_list)
4223 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4224 unsigned int final_fixup = 0, is_clean;
4226 if (has_unstaged_changes(r, 1))
4227 return error(_("cannot rebase: You have unstaged changes."));
4229 is_clean = !has_uncommitted_changes(r, 0);
4231 if (file_exists(rebase_path_amend())) {
4232 struct strbuf rev = STRBUF_INIT;
4233 struct object_id head, to_amend;
4235 if (get_oid("HEAD", &head))
4236 return error(_("cannot amend non-existing commit"));
4237 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4238 return error(_("invalid file: '%s'"), rebase_path_amend());
4239 if (get_oid_hex(rev.buf, &to_amend))
4240 return error(_("invalid contents: '%s'"),
4241 rebase_path_amend());
4242 if (!is_clean && !oideq(&head, &to_amend))
4243 return error(_("\nYou have uncommitted changes in your "
4244 "working tree. Please, commit them\n"
4245 "first and then run 'git rebase "
4246 "--continue' again."));
4248 * When skipping a failed fixup/squash, we need to edit the
4249 * commit message, the current fixup list and count, and if it
4250 * was the last fixup/squash in the chain, we need to clean up
4251 * the commit message and if there was a squash, let the user
4254 if (!is_clean || !opts->current_fixup_count)
4255 ; /* this is not the final fixup */
4256 else if (!oideq(&head, &to_amend) ||
4257 !file_exists(rebase_path_stopped_sha())) {
4258 /* was a final fixup or squash done manually? */
4259 if (!is_fixup(peek_command(todo_list, 0))) {
4260 unlink(rebase_path_fixup_msg());
4261 unlink(rebase_path_squash_msg());
4262 unlink(rebase_path_current_fixups());
4263 strbuf_reset(&opts->current_fixups);
4264 opts->current_fixup_count = 0;
4267 /* we are in a fixup/squash chain */
4268 const char *p = opts->current_fixups.buf;
4269 int len = opts->current_fixups.len;
4271 opts->current_fixup_count--;
4273 BUG("Incorrect current_fixups:\n%s", p);
4274 while (len && p[len - 1] != '\n')
4276 strbuf_setlen(&opts->current_fixups, len);
4277 if (write_message(p, len, rebase_path_current_fixups(),
4279 return error(_("could not write file: '%s'"),
4280 rebase_path_current_fixups());
4283 * If a fixup/squash in a fixup/squash chain failed, the
4284 * commit message is already correct, no need to commit
4287 * Only if it is the final command in the fixup/squash
4288 * chain, and only if the chain is longer than a single
4289 * fixup/squash command (which was just skipped), do we
4290 * actually need to re-commit with a cleaned up commit
4293 if (opts->current_fixup_count > 0 &&
4294 !is_fixup(peek_command(todo_list, 0))) {
4297 * If there was not a single "squash" in the
4298 * chain, we only need to clean up the commit
4299 * message, no need to bother the user with
4300 * opening the commit message in the editor.
4302 if (!starts_with(p, "squash ") &&
4303 !strstr(p, "\nsquash "))
4304 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4305 } else if (is_fixup(peek_command(todo_list, 0))) {
4307 * We need to update the squash message to skip
4308 * the latest commit message.
4310 struct commit *commit;
4311 const char *path = rebase_path_squash_msg();
4312 const char *encoding = get_commit_output_encoding();
4314 if (parse_head(r, &commit) ||
4315 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4316 write_message(p, strlen(p), path, 0)) {
4317 unuse_commit_buffer(commit, p);
4318 return error(_("could not write file: "
4321 unuse_commit_buffer(commit, p);
4325 strbuf_release(&rev);
4330 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4332 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4333 return error(_("could not remove CHERRY_PICK_HEAD"));
4338 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4340 return error(_("could not commit staged changes."));
4341 unlink(rebase_path_amend());
4342 unlink(git_path_merge_head(r));
4344 unlink(rebase_path_fixup_msg());
4345 unlink(rebase_path_squash_msg());
4347 if (opts->current_fixup_count > 0) {
4349 * Whether final fixup or not, we just cleaned up the commit
4352 unlink(rebase_path_current_fixups());
4353 strbuf_reset(&opts->current_fixups);
4354 opts->current_fixup_count = 0;
4359 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4361 struct todo_list todo_list = TODO_LIST_INIT;
4364 if (read_and_refresh_cache(r, opts))
4367 if (read_populate_opts(opts))
4369 if (is_rebase_i(opts)) {
4370 if ((res = read_populate_todo(r, &todo_list, opts)))
4371 goto release_todo_list;
4373 if (file_exists(rebase_path_dropped())) {
4374 if ((res = todo_list_check_against_backup(r, &todo_list)))
4375 goto release_todo_list;
4377 unlink(rebase_path_dropped());
4380 if (commit_staged_changes(r, opts, &todo_list)) {
4382 goto release_todo_list;
4384 } else if (!file_exists(get_todo_path(opts)))
4385 return continue_single_pick(r);
4386 else if ((res = read_populate_todo(r, &todo_list, opts)))
4387 goto release_todo_list;
4389 if (!is_rebase_i(opts)) {
4390 /* Verify that the conflict has been resolved */
4391 if (file_exists(git_path_cherry_pick_head(r)) ||
4392 file_exists(git_path_revert_head(r))) {
4393 res = continue_single_pick(r);
4395 goto release_todo_list;
4397 if (index_differs_from(r, "HEAD", NULL, 0)) {
4398 res = error_dirty_index(r, opts);
4399 goto release_todo_list;
4401 todo_list.current++;
4402 } else if (file_exists(rebase_path_stopped_sha())) {
4403 struct strbuf buf = STRBUF_INIT;
4404 struct object_id oid;
4406 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4407 !get_oid_committish(buf.buf, &oid))
4408 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4409 strbuf_release(&buf);
4412 res = pick_commits(r, &todo_list, opts);
4414 todo_list_release(&todo_list);
4418 static int single_pick(struct repository *r,
4419 struct commit *cmit,
4420 struct replay_opts *opts)
4424 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4425 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4426 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4430 int sequencer_pick_revisions(struct repository *r,
4431 struct replay_opts *opts)
4433 struct todo_list todo_list = TODO_LIST_INIT;
4434 struct object_id oid;
4438 if (read_and_refresh_cache(r, opts))
4441 for (i = 0; i < opts->revs->pending.nr; i++) {
4442 struct object_id oid;
4443 const char *name = opts->revs->pending.objects[i].name;
4445 /* This happens when using --stdin. */
4449 if (!get_oid(name, &oid)) {
4450 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4451 enum object_type type = oid_object_info(r,
4454 return error(_("%s: can't cherry-pick a %s"),
4455 name, type_name(type));
4458 return error(_("%s: bad revision"), name);
4462 * If we were called as "git cherry-pick <commit>", just
4463 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4464 * REVERT_HEAD, and don't touch the sequencer state.
4465 * This means it is possible to cherry-pick in the middle
4466 * of a cherry-pick sequence.
4468 if (opts->revs->cmdline.nr == 1 &&
4469 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4470 opts->revs->no_walk &&
4471 !opts->revs->cmdline.rev->flags) {
4472 struct commit *cmit;
4473 if (prepare_revision_walk(opts->revs))
4474 return error(_("revision walk setup failed"));
4475 cmit = get_revision(opts->revs);
4477 return error(_("empty commit set passed"));
4478 if (get_revision(opts->revs))
4479 BUG("unexpected extra commit from walk");
4480 return single_pick(r, cmit, opts);
4484 * Start a new cherry-pick/ revert sequence; but
4485 * first, make sure that an existing one isn't in
4489 if (walk_revs_populate_todo(&todo_list, opts) ||
4490 create_seq_dir(r) < 0)
4492 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4493 return error(_("can't revert as initial commit"));
4494 if (save_head(oid_to_hex(&oid)))
4496 if (save_opts(opts))
4498 update_abort_safety_file();
4499 res = pick_commits(r, &todo_list, opts);
4500 todo_list_release(&todo_list);
4504 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4506 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4507 struct strbuf sob = STRBUF_INIT;
4510 strbuf_addstr(&sob, sign_off_header);
4511 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4512 strbuf_addch(&sob, '\n');
4515 strbuf_complete_line(msgbuf);
4518 * If the whole message buffer is equal to the sob, pretend that we
4519 * found a conforming footer with a matching sob
4521 if (msgbuf->len - ignore_footer == sob.len &&
4522 !strncmp(msgbuf->buf, sob.buf, sob.len))
4525 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4528 const char *append_newlines = NULL;
4529 size_t len = msgbuf->len - ignore_footer;
4533 * The buffer is completely empty. Leave foom for
4534 * the title and body to be filled in by the user.
4536 append_newlines = "\n\n";
4537 } else if (len == 1) {
4539 * Buffer contains a single newline. Add another
4540 * so that we leave room for the title and body.
4542 append_newlines = "\n";
4543 } else if (msgbuf->buf[len - 2] != '\n') {
4545 * Buffer ends with a single newline. Add another
4546 * so that there is an empty line between the message
4549 append_newlines = "\n";
4550 } /* else, the buffer already ends with two newlines. */
4552 if (append_newlines)
4553 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4554 append_newlines, strlen(append_newlines));
4557 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4558 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4561 strbuf_release(&sob);
4564 struct labels_entry {
4565 struct hashmap_entry entry;
4566 char label[FLEX_ARRAY];
4569 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4570 const struct hashmap_entry *entry_or_key, const void *key)
4572 const struct labels_entry *a, *b;
4574 a = container_of(eptr, const struct labels_entry, entry);
4575 b = container_of(entry_or_key, const struct labels_entry, entry);
4577 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4580 struct string_entry {
4581 struct oidmap_entry entry;
4582 char string[FLEX_ARRAY];
4585 struct label_state {
4586 struct oidmap commit2label;
4587 struct hashmap labels;
4591 static const char *label_oid(struct object_id *oid, const char *label,
4592 struct label_state *state)
4594 struct labels_entry *labels_entry;
4595 struct string_entry *string_entry;
4596 struct object_id dummy;
4599 string_entry = oidmap_get(&state->commit2label, oid);
4601 return string_entry->string;
4604 * For "uninteresting" commits, i.e. commits that are not to be
4605 * rebased, and which can therefore not be labeled, we use a unique
4606 * abbreviation of the commit name. This is slightly more complicated
4607 * than calling find_unique_abbrev() because we also need to make
4608 * sure that the abbreviation does not conflict with any other
4611 * We disallow "interesting" commits to be labeled by a string that
4612 * is a valid full-length hash, to ensure that we always can find an
4613 * abbreviation for any uninteresting commit's names that does not
4614 * clash with any other label.
4616 strbuf_reset(&state->buf);
4620 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4621 label = p = state->buf.buf;
4623 find_unique_abbrev_r(p, oid, default_abbrev);
4626 * We may need to extend the abbreviated hash so that there is
4627 * no conflicting label.
4629 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4630 size_t i = strlen(p) + 1;
4632 oid_to_hex_r(p, oid);
4633 for (; i < the_hash_algo->hexsz; i++) {
4636 if (!hashmap_get_from_hash(&state->labels,
4643 struct strbuf *buf = &state->buf;
4646 * Sanitize labels by replacing non-alpha-numeric characters
4647 * (including white-space ones) by dashes, as they might be
4648 * illegal in file names (and hence in ref names).
4650 * Note that we retain non-ASCII UTF-8 characters (identified
4651 * via the most significant bit). They should be all acceptable
4652 * in file names. We do not validate the UTF-8 here, that's not
4653 * the job of this function.
4655 for (; *label; label++)
4656 if ((*label & 0x80) || isalnum(*label))
4657 strbuf_addch(buf, *label);
4658 /* avoid leading dash and double-dashes */
4659 else if (buf->len && buf->buf[buf->len - 1] != '-')
4660 strbuf_addch(buf, '-');
4662 strbuf_addstr(buf, "rev-");
4663 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4667 if ((buf->len == the_hash_algo->hexsz &&
4668 !get_oid_hex(label, &dummy)) ||
4669 (buf->len == 1 && *label == '#') ||
4670 hashmap_get_from_hash(&state->labels,
4671 strihash(label), label)) {
4673 * If the label already exists, or if the label is a
4674 * valid full OID, or the label is a '#' (which we use
4675 * as a separator between merge heads and oneline), we
4676 * append a dash and a number to make it unique.
4678 size_t len = buf->len;
4680 for (i = 2; ; i++) {
4681 strbuf_setlen(buf, len);
4682 strbuf_addf(buf, "-%d", i);
4683 if (!hashmap_get_from_hash(&state->labels,
4693 FLEX_ALLOC_STR(labels_entry, label, label);
4694 hashmap_entry_init(&labels_entry->entry, strihash(label));
4695 hashmap_add(&state->labels, &labels_entry->entry);
4697 FLEX_ALLOC_STR(string_entry, string, label);
4698 oidcpy(&string_entry->entry.oid, oid);
4699 oidmap_put(&state->commit2label, string_entry);
4701 return string_entry->string;
4704 static int make_script_with_merges(struct pretty_print_context *pp,
4705 struct rev_info *revs, struct strbuf *out,
4708 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4709 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4710 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4711 struct strbuf label = STRBUF_INIT;
4712 struct commit_list *commits = NULL, **tail = &commits, *iter;
4713 struct commit_list *tips = NULL, **tips_tail = &tips;
4714 struct commit *commit;
4715 struct oidmap commit2todo = OIDMAP_INIT;
4716 struct string_entry *entry;
4717 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4718 shown = OIDSET_INIT;
4719 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4721 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4722 const char *cmd_pick = abbr ? "p" : "pick",
4723 *cmd_label = abbr ? "l" : "label",
4724 *cmd_reset = abbr ? "t" : "reset",
4725 *cmd_merge = abbr ? "m" : "merge";
4727 oidmap_init(&commit2todo, 0);
4728 oidmap_init(&state.commit2label, 0);
4729 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4730 strbuf_init(&state.buf, 32);
4732 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4733 struct labels_entry *onto_label_entry;
4734 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4735 FLEX_ALLOC_STR(entry, string, "onto");
4736 oidcpy(&entry->entry.oid, oid);
4737 oidmap_put(&state.commit2label, entry);
4739 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4740 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4741 hashmap_add(&state.labels, &onto_label_entry->entry);
4746 * - get onelines for all commits
4747 * - gather all branch tips (i.e. 2nd or later parents of merges)
4748 * - label all branch tips
4750 while ((commit = get_revision(revs))) {
4751 struct commit_list *to_merge;
4752 const char *p1, *p2;
4753 struct object_id *oid;
4756 tail = &commit_list_insert(commit, tail)->next;
4757 oidset_insert(&interesting, &commit->object.oid);
4759 is_empty = is_original_commit_empty(commit);
4760 if (!is_empty && (commit->object.flags & PATCHSAME))
4763 strbuf_reset(&oneline);
4764 pretty_print_commit(pp, commit, &oneline);
4766 to_merge = commit->parents ? commit->parents->next : NULL;
4768 /* non-merge commit: easy case */
4770 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4771 oid_to_hex(&commit->object.oid),
4774 FLEX_ALLOC_STR(entry, string, buf.buf);
4775 oidcpy(&entry->entry.oid, &commit->object.oid);
4776 oidmap_put(&commit2todo, entry);
4781 /* Create a label */
4782 strbuf_reset(&label);
4783 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4784 (p1 = strchr(p1, '\'')) &&
4785 (p2 = strchr(++p1, '\'')))
4786 strbuf_add(&label, p1, p2 - p1);
4787 else if (skip_prefix(oneline.buf, "Merge pull request ",
4789 (p1 = strstr(p1, " from ")))
4790 strbuf_addstr(&label, p1 + strlen(" from "));
4792 strbuf_addbuf(&label, &oneline);
4795 strbuf_addf(&buf, "%s -C %s",
4796 cmd_merge, oid_to_hex(&commit->object.oid));
4798 /* label the tips of merged branches */
4799 for (; to_merge; to_merge = to_merge->next) {
4800 oid = &to_merge->item->object.oid;
4801 strbuf_addch(&buf, ' ');
4803 if (!oidset_contains(&interesting, oid)) {
4804 strbuf_addstr(&buf, label_oid(oid, NULL,
4809 tips_tail = &commit_list_insert(to_merge->item,
4812 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4814 strbuf_addf(&buf, " # %s", oneline.buf);
4816 FLEX_ALLOC_STR(entry, string, buf.buf);
4817 oidcpy(&entry->entry.oid, &commit->object.oid);
4818 oidmap_put(&commit2todo, entry);
4823 * - label branch points
4824 * - add HEAD to the branch tips
4826 for (iter = commits; iter; iter = iter->next) {
4827 struct commit_list *parent = iter->item->parents;
4828 for (; parent; parent = parent->next) {
4829 struct object_id *oid = &parent->item->object.oid;
4830 if (!oidset_contains(&interesting, oid))
4832 if (oidset_insert(&child_seen, oid))
4833 label_oid(oid, "branch-point", &state);
4836 /* Add HEAD as implicit "tip of branch" */
4838 tips_tail = &commit_list_insert(iter->item,
4843 * Third phase: output the todo list. This is a bit tricky, as we
4844 * want to avoid jumping back and forth between revisions. To
4845 * accomplish that goal, we walk backwards from the branch tips,
4846 * gathering commits not yet shown, reversing the list on the fly,
4847 * then outputting that list (labeling revisions as needed).
4849 strbuf_addf(out, "%s onto\n", cmd_label);
4850 for (iter = tips; iter; iter = iter->next) {
4851 struct commit_list *list = NULL, *iter2;
4853 commit = iter->item;
4854 if (oidset_contains(&shown, &commit->object.oid))
4856 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4859 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4861 strbuf_addch(out, '\n');
4863 while (oidset_contains(&interesting, &commit->object.oid) &&
4864 !oidset_contains(&shown, &commit->object.oid)) {
4865 commit_list_insert(commit, &list);
4866 if (!commit->parents) {
4870 commit = commit->parents->item;
4874 strbuf_addf(out, "%s %s\n", cmd_reset,
4875 rebase_cousins || root_with_onto ?
4876 "onto" : "[new root]");
4878 const char *to = NULL;
4880 entry = oidmap_get(&state.commit2label,
4881 &commit->object.oid);
4884 else if (!rebase_cousins)
4885 to = label_oid(&commit->object.oid, NULL,
4888 if (!to || !strcmp(to, "onto"))
4889 strbuf_addf(out, "%s onto\n", cmd_reset);
4891 strbuf_reset(&oneline);
4892 pretty_print_commit(pp, commit, &oneline);
4893 strbuf_addf(out, "%s %s # %s\n",
4894 cmd_reset, to, oneline.buf);
4898 for (iter2 = list; iter2; iter2 = iter2->next) {
4899 struct object_id *oid = &iter2->item->object.oid;
4900 entry = oidmap_get(&commit2todo, oid);
4901 /* only show if not already upstream */
4903 strbuf_addf(out, "%s\n", entry->string);
4904 entry = oidmap_get(&state.commit2label, oid);
4906 strbuf_addf(out, "%s %s\n",
4907 cmd_label, entry->string);
4908 oidset_insert(&shown, oid);
4911 free_commit_list(list);
4914 free_commit_list(commits);
4915 free_commit_list(tips);
4917 strbuf_release(&label);
4918 strbuf_release(&oneline);
4919 strbuf_release(&buf);
4921 oidmap_free(&commit2todo, 1);
4922 oidmap_free(&state.commit2label, 1);
4923 hashmap_free_entries(&state.labels, struct labels_entry, entry);
4924 strbuf_release(&state.buf);
4929 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4930 const char **argv, unsigned flags)
4932 char *format = NULL;
4933 struct pretty_print_context pp = {0};
4934 struct rev_info revs;
4935 struct commit *commit;
4936 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4937 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4939 repo_init_revisions(r, &revs, NULL);
4940 revs.verbose_header = 1;
4942 revs.max_parents = 1;
4943 revs.cherry_mark = 1;
4946 revs.right_only = 1;
4947 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4948 revs.topo_order = 1;
4950 revs.pretty_given = 1;
4951 git_config_get_string("rebase.instructionFormat", &format);
4952 if (!format || !*format) {
4954 format = xstrdup("%s");
4956 get_commit_format(format, &revs);
4958 pp.fmt = revs.commit_format;
4959 pp.output_encoding = get_log_output_encoding();
4961 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4962 return error(_("make_script: unhandled options"));
4964 if (prepare_revision_walk(&revs) < 0)
4965 return error(_("make_script: error preparing revisions"));
4968 return make_script_with_merges(&pp, &revs, out, flags);
4970 while ((commit = get_revision(&revs))) {
4971 int is_empty = is_original_commit_empty(commit);
4973 if (!is_empty && (commit->object.flags & PATCHSAME))
4975 strbuf_addf(out, "%s %s ", insn,
4976 oid_to_hex(&commit->object.oid));
4977 pretty_print_commit(&pp, commit, out);
4978 strbuf_addch(out, '\n');
4984 * Add commands after pick and (series of) squash/fixup commands
4987 void todo_list_add_exec_commands(struct todo_list *todo_list,
4988 struct string_list *commands)
4990 struct strbuf *buf = &todo_list->buf;
4991 size_t base_offset = buf->len;
4992 int i, insert, nr = 0, alloc = 0;
4993 struct todo_item *items = NULL, *base_items = NULL;
4995 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4996 for (i = 0; i < commands->nr; i++) {
4997 size_t command_len = strlen(commands->items[i].string);
4999 strbuf_addstr(buf, commands->items[i].string);
5000 strbuf_addch(buf, '\n');
5002 base_items[i].command = TODO_EXEC;
5003 base_items[i].offset_in_buf = base_offset;
5004 base_items[i].arg_offset = base_offset + strlen("exec ");
5005 base_items[i].arg_len = command_len - strlen("exec ");
5007 base_offset += command_len + 1;
5011 * Insert <commands> after every pick. Here, fixup/squash chains
5012 * are considered part of the pick, so we insert the commands *after*
5013 * those chains if there are any.
5015 * As we insert the exec commands immediately after rearranging
5016 * any fixups and before the user edits the list, a fixup chain
5017 * can never contain comments (any comments are empty picks that
5018 * have been commented out because the user did not specify
5019 * --keep-empty). So, it is safe to insert an exec command
5020 * without looking at the command following a comment.
5023 for (i = 0; i < todo_list->nr; i++) {
5024 enum todo_command command = todo_list->items[i].command;
5025 if (insert && !is_fixup(command)) {
5026 ALLOC_GROW(items, nr + commands->nr, alloc);
5027 COPY_ARRAY(items + nr, base_items, commands->nr);
5033 ALLOC_GROW(items, nr + 1, alloc);
5034 items[nr++] = todo_list->items[i];
5036 if (command == TODO_PICK || command == TODO_MERGE)
5040 /* insert or append final <commands> */
5041 if (insert || nr == todo_list->nr) {
5042 ALLOC_GROW(items, nr + commands->nr, alloc);
5043 COPY_ARRAY(items + nr, base_items, commands->nr);
5048 FREE_AND_NULL(todo_list->items);
5049 todo_list->items = items;
5051 todo_list->alloc = alloc;
5054 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5055 struct strbuf *buf, int num, unsigned flags)
5057 struct todo_item *item;
5058 int i, max = todo_list->nr;
5060 if (num > 0 && num < max)
5063 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5064 /* if the item is not a command write it and continue */
5065 if (item->command >= TODO_COMMENT) {
5066 strbuf_addf(buf, "%.*s\n", item->arg_len,
5067 todo_item_get_arg(todo_list, item));
5071 /* add command to the buffer */
5072 if (flags & TODO_LIST_ABBREVIATE_CMDS)
5073 strbuf_addch(buf, command_to_char(item->command));
5075 strbuf_addstr(buf, command_to_string(item->command));
5079 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5080 short_commit_name(item->commit) :
5081 oid_to_hex(&item->commit->object.oid);
5083 if (item->command == TODO_MERGE) {
5084 if (item->flags & TODO_EDIT_MERGE_MSG)
5085 strbuf_addstr(buf, " -c");
5087 strbuf_addstr(buf, " -C");
5090 strbuf_addf(buf, " %s", oid);
5093 /* add all the rest */
5095 strbuf_addch(buf, '\n');
5097 strbuf_addf(buf, " %.*s\n", item->arg_len,
5098 todo_item_get_arg(todo_list, item));
5102 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5103 const char *file, const char *shortrevisions,
5104 const char *shortonto, int num, unsigned flags)
5107 struct strbuf buf = STRBUF_INIT;
5109 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5110 if (flags & TODO_LIST_APPEND_TODO_HELP)
5111 append_todo_help(count_commands(todo_list),
5112 shortrevisions, shortonto, &buf);
5114 res = write_message(buf.buf, buf.len, file, 0);
5115 strbuf_release(&buf);
5120 /* skip picking commits whose parents are unchanged */
5121 static int skip_unnecessary_picks(struct repository *r,
5122 struct todo_list *todo_list,
5123 struct object_id *base_oid)
5125 struct object_id *parent_oid;
5128 for (i = 0; i < todo_list->nr; i++) {
5129 struct todo_item *item = todo_list->items + i;
5131 if (item->command >= TODO_NOOP)
5133 if (item->command != TODO_PICK)
5135 if (parse_commit(item->commit)) {
5136 return error(_("could not parse commit '%s'"),
5137 oid_to_hex(&item->commit->object.oid));
5139 if (!item->commit->parents)
5140 break; /* root commit */
5141 if (item->commit->parents->next)
5142 break; /* merge commit */
5143 parent_oid = &item->commit->parents->item->object.oid;
5144 if (!oideq(parent_oid, base_oid))
5146 oidcpy(base_oid, &item->commit->object.oid);
5149 const char *done_path = rebase_path_done();
5151 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5152 error_errno(_("could not write to '%s'"), done_path);
5156 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5158 todo_list->current = 0;
5159 todo_list->done_nr += i;
5161 if (is_fixup(peek_command(todo_list, 0)))
5162 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5168 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5169 const char *shortrevisions, const char *onto_name,
5170 struct commit *onto, const char *orig_head,
5171 struct string_list *commands, unsigned autosquash,
5172 struct todo_list *todo_list)
5174 const char *shortonto, *todo_file = rebase_path_todo();
5175 struct todo_list new_todo = TODO_LIST_INIT;
5176 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5177 struct object_id oid = onto->object.oid;
5180 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5182 if (buf->len == 0) {
5183 struct todo_item *item = append_new_todo(todo_list);
5184 item->command = TODO_NOOP;
5185 item->commit = NULL;
5186 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5189 if (autosquash && todo_list_rearrange_squash(todo_list))
5193 todo_list_add_exec_commands(todo_list, commands);
5195 if (count_commands(todo_list) == 0) {
5196 apply_autostash(opts);
5197 sequencer_remove_state(opts);
5199 return error(_("nothing to do"));
5202 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5206 else if (res == -2) {
5207 apply_autostash(opts);
5208 sequencer_remove_state(opts);
5211 } else if (res == -3) {
5212 apply_autostash(opts);
5213 sequencer_remove_state(opts);
5214 todo_list_release(&new_todo);
5216 return error(_("nothing to do"));
5217 } else if (res == -4) {
5218 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5219 todo_list_release(&new_todo);
5224 /* Expand the commit IDs */
5225 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5226 strbuf_swap(&new_todo.buf, &buf2);
5227 strbuf_release(&buf2);
5228 new_todo.total_nr -= new_todo.nr;
5229 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5230 BUG("invalid todo list after expanding IDs:\n%s",
5233 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5234 todo_list_release(&new_todo);
5235 return error(_("could not skip unnecessary pick commands"));
5238 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5239 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5240 todo_list_release(&new_todo);
5241 return error_errno(_("could not write '%s'"), todo_file);
5246 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5249 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5252 todo_list_write_total_nr(&new_todo);
5253 res = pick_commits(r, &new_todo, opts);
5256 todo_list_release(&new_todo);
5261 struct subject2item_entry {
5262 struct hashmap_entry entry;
5264 char subject[FLEX_ARRAY];
5267 static int subject2item_cmp(const void *fndata,
5268 const struct hashmap_entry *eptr,
5269 const struct hashmap_entry *entry_or_key,
5272 const struct subject2item_entry *a, *b;
5274 a = container_of(eptr, const struct subject2item_entry, entry);
5275 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5277 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5280 define_commit_slab(commit_todo_item, struct todo_item *);
5283 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5284 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5285 * after the former, and change "pick" to "fixup"/"squash".
5287 * Note that if the config has specified a custom instruction format, each log
5288 * message will have to be retrieved from the commit (as the oneline in the
5289 * script cannot be trusted) in order to normalize the autosquash arrangement.
5291 int todo_list_rearrange_squash(struct todo_list *todo_list)
5293 struct hashmap subject2item;
5294 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5296 struct commit_todo_item commit_todo;
5297 struct todo_item *items = NULL;
5299 init_commit_todo_item(&commit_todo);
5301 * The hashmap maps onelines to the respective todo list index.
5303 * If any items need to be rearranged, the next[i] value will indicate
5304 * which item was moved directly after the i'th.
5306 * In that case, last[i] will indicate the index of the latest item to
5307 * be moved to appear after the i'th.
5309 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5310 ALLOC_ARRAY(next, todo_list->nr);
5311 ALLOC_ARRAY(tail, todo_list->nr);
5312 ALLOC_ARRAY(subjects, todo_list->nr);
5313 for (i = 0; i < todo_list->nr; i++) {
5314 struct strbuf buf = STRBUF_INIT;
5315 struct todo_item *item = todo_list->items + i;
5316 const char *commit_buffer, *subject, *p;
5319 struct subject2item_entry *entry;
5321 next[i] = tail[i] = -1;
5322 if (!item->commit || item->command == TODO_DROP) {
5327 if (is_fixup(item->command)) {
5328 clear_commit_todo_item(&commit_todo);
5329 return error(_("the script was already rearranged."));
5332 *commit_todo_item_at(&commit_todo, item->commit) = item;
5334 parse_commit(item->commit);
5335 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5336 find_commit_subject(commit_buffer, &subject);
5337 format_subject(&buf, subject, " ");
5338 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5339 unuse_commit_buffer(item->commit, commit_buffer);
5340 if ((skip_prefix(subject, "fixup! ", &p) ||
5341 skip_prefix(subject, "squash! ", &p))) {
5342 struct commit *commit2;
5347 if (!skip_prefix(p, "fixup! ", &p) &&
5348 !skip_prefix(p, "squash! ", &p))
5352 entry = hashmap_get_entry_from_hash(&subject2item,
5354 struct subject2item_entry,
5357 /* found by title */
5359 else if (!strchr(p, ' ') &&
5361 lookup_commit_reference_by_name(p)) &&
5362 *commit_todo_item_at(&commit_todo, commit2))
5363 /* found by commit name */
5364 i2 = *commit_todo_item_at(&commit_todo, commit2)
5367 /* copy can be a prefix of the commit subject */
5368 for (i2 = 0; i2 < i; i2++)
5370 starts_with(subjects[i2], p))
5378 todo_list->items[i].command =
5379 starts_with(subject, "fixup!") ?
5380 TODO_FIXUP : TODO_SQUASH;
5386 } else if (!hashmap_get_from_hash(&subject2item,
5387 strhash(subject), subject)) {
5388 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5390 hashmap_entry_init(&entry->entry,
5391 strhash(entry->subject));
5392 hashmap_put(&subject2item, &entry->entry);
5397 for (i = 0; i < todo_list->nr; i++) {
5398 enum todo_command command = todo_list->items[i].command;
5402 * Initially, all commands are 'pick's. If it is a
5403 * fixup or a squash now, we have rearranged it.
5405 if (is_fixup(command))
5409 ALLOC_GROW(items, nr + 1, alloc);
5410 items[nr++] = todo_list->items[cur];
5415 FREE_AND_NULL(todo_list->items);
5416 todo_list->items = items;
5418 todo_list->alloc = alloc;
5423 for (i = 0; i < todo_list->nr; i++)
5426 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5428 clear_commit_todo_item(&commit_todo);
5433 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5435 if (file_exists(git_path_cherry_pick_head(r))) {
5436 struct object_id cherry_pick_head, rebase_head;
5438 if (file_exists(git_path_seq_dir()))
5439 *whence = FROM_CHERRY_PICK_MULTI;
5440 if (file_exists(rebase_path()) &&
5441 !get_oid("REBASE_HEAD", &rebase_head) &&
5442 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5443 oideq(&rebase_head, &cherry_pick_head))
5444 *whence = FROM_REBASE_PICK;
5446 *whence = FROM_CHERRY_PICK_SINGLE;