5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-ort.h"
18 #include "merge-ort-wrappers.h"
24 #include "wt-status.h"
26 #include "notes-utils.h"
28 #include "unpack-trees.h"
32 #include "commit-slab.h"
34 #include "commit-reach.h"
35 #include "rebase-interactive.h"
38 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40 static const char sign_off_header[] = "Signed-off-by: ";
41 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
48 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
49 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
50 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 * The file containing rebase commands, comments, and empty lines.
55 * This file is created by "git rebase -i" then edited by the user. As
56 * the lines are processed, they are removed from the front of this
57 * file and written to the tail of 'done'.
59 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
60 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65 * The rebase command lines that have already been processed. A line
66 * is moved here when it is first handled, before any associated user
69 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 * The file to keep track of how many commands were already processed (e.g.
74 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 * The file to keep track of how many commands are to be processed in total
77 * (e.g. for the prompt).
79 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 * The commit message that is planned to be used for any changes that
82 * need to be committed following a user interaction.
84 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 * The file into which is accumulated the suggested commit message for
87 * squash/fixup commands. When the first of a series of squash/fixups
88 * is seen, the file is created and the commit message from the
89 * previous commit and from the first squash/fixup commit are written
90 * to it. The commit message for each subsequent squash/fixup commit
91 * is appended to the file as it is processed.
93 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 * If the current series of squash/fixups has not yet included a squash
96 * command, then this file exists and holds the commit message of the
97 * original "pick" commit. (If the series ends without a "squash"
98 * command, then this can be used as the commit message of the combined
99 * commit without opening the editor.)
101 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 * This file contains the list fixup/squash commands that have been
104 * accumulated into message-fixup or message-squash so far.
106 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
109 * GIT_AUTHOR_DATE that will be used for the commit that is currently
112 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 * When an "edit" rebase command is being processed, the SHA1 of the
115 * commit to be edited is recorded in this file. When "git rebase
116 * --continue" is executed, if there are any staged changes then they
117 * will be amended to the HEAD commit, but only provided the HEAD
118 * commit is still the commit to be edited. When any other rebase
119 * command is processed, this file is deleted.
121 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 * When we stop at a given patch via the "edit" command, this file contains
124 * the commit object name of the corresponding patch.
126 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 * For the post-rewrite hook, we make a list of rewritten commits and
129 * their new sha1s. The rewritten-pending list keeps the sha1s of
130 * commits that have been processed, but not committed yet,
131 * e.g. because they are waiting for a 'squash' command.
133 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
134 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
135 "rebase-merge/rewritten-pending")
138 * The path of the file containing the OID of the "squash onto" commit, i.e.
139 * the dummy commit used for `reset [new root]`.
141 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144 * The path of the file listing refs that need to be deleted after the rebase
145 * finishes. This is used by the `label` command to record the need for cleanup.
147 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150 * The following files are written by git-rebase just after parsing the
153 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
154 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
155 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
156 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
157 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
158 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
159 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
160 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
161 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
162 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
163 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
164 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
165 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
166 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
167 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
168 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
170 static int git_sequencer_config(const char *k, const char *v, void *cb)
172 struct replay_opts *opts = cb;
175 if (!strcmp(k, "commit.cleanup")) {
178 status = git_config_string(&s, k, v);
182 if (!strcmp(s, "verbatim")) {
183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "whitespace")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
187 opts->explicit_cleanup = 1;
188 } else if (!strcmp(s, "strip")) {
189 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
190 opts->explicit_cleanup = 1;
191 } else if (!strcmp(s, "scissors")) {
192 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
193 opts->explicit_cleanup = 1;
195 warning(_("invalid commit message cleanup mode '%s'"),
203 if (!strcmp(k, "commit.gpgsign")) {
204 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
208 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
209 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
212 * pull.twohead is allowed to be multi-valued; we only
213 * care about the first value.
215 char *tmp = strchr(opts->default_strategy, ' ');
222 status = git_gpg_config(k, v, NULL);
226 return git_diff_basic_config(k, v, NULL);
229 void sequencer_init_config(struct replay_opts *opts)
231 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
232 git_config(git_sequencer_config, opts);
235 static inline int is_rebase_i(const struct replay_opts *opts)
237 return opts->action == REPLAY_INTERACTIVE_REBASE;
240 static const char *get_dir(const struct replay_opts *opts)
242 if (is_rebase_i(opts))
243 return rebase_path();
244 return git_path_seq_dir();
247 static const char *get_todo_path(const struct replay_opts *opts)
249 if (is_rebase_i(opts))
250 return rebase_path_todo();
251 return git_path_todo_file();
255 * Returns 0 for non-conforming footer
256 * Returns 1 for conforming footer
257 * Returns 2 when sob exists within conforming footer
258 * Returns 3 when sob exists within conforming footer as last entry
260 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
261 size_t ignore_footer)
263 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
264 struct trailer_info info;
266 int found_sob = 0, found_sob_last = 0;
272 saved_char = sb->buf[sb->len - ignore_footer];
273 sb->buf[sb->len - ignore_footer] = '\0';
276 trailer_info_get(&info, sb->buf, &opts);
279 sb->buf[sb->len - ignore_footer] = saved_char;
281 if (info.trailer_start == info.trailer_end)
284 for (i = 0; i < info.trailer_nr; i++)
285 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
287 if (i == info.trailer_nr - 1)
291 trailer_info_release(&info);
300 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
302 static struct strbuf buf = STRBUF_INIT;
306 sq_quotef(&buf, "-S%s", opts->gpg_sign);
310 int sequencer_remove_state(struct replay_opts *opts)
312 struct strbuf buf = STRBUF_INIT;
315 if (is_rebase_i(opts) &&
316 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
319 char *eol = strchr(p, '\n');
322 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
323 warning(_("could not delete '%s'"), p);
332 free(opts->gpg_sign);
333 free(opts->default_strategy);
334 free(opts->strategy);
335 for (i = 0; i < opts->xopts_nr; i++)
336 free(opts->xopts[i]);
338 strbuf_release(&opts->current_fixups);
341 strbuf_addstr(&buf, get_dir(opts));
342 if (remove_dir_recursively(&buf, 0))
343 ret = error(_("could not remove '%s'"), buf.buf);
344 strbuf_release(&buf);
349 static const char *action_name(const struct replay_opts *opts)
351 switch (opts->action) {
355 return N_("cherry-pick");
356 case REPLAY_INTERACTIVE_REBASE:
359 die(_("unknown action: %d"), opts->action);
362 struct commit_message {
369 static const char *short_commit_name(struct commit *commit)
371 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
374 static int get_message(struct commit *commit, struct commit_message *out)
376 const char *abbrev, *subject;
379 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
380 abbrev = short_commit_name(commit);
382 subject_len = find_commit_subject(out->message, &subject);
384 out->subject = xmemdupz(subject, subject_len);
385 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
386 out->parent_label = xstrfmt("parent of %s", out->label);
391 static void free_message(struct commit *commit, struct commit_message *msg)
393 free(msg->parent_label);
396 unuse_commit_buffer(commit, msg->message);
399 static void print_advice(struct repository *r, int show_hint,
400 struct replay_opts *opts)
402 char *msg = getenv("GIT_CHERRY_PICK_HELP");
405 fprintf(stderr, "%s\n", msg);
407 * A conflict has occurred but the porcelain
408 * (typically rebase --interactive) wants to take care
409 * of the commit itself so remove CHERRY_PICK_HEAD
411 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
418 advise(_("after resolving the conflicts, mark the corrected paths\n"
419 "with 'git add <paths>' or 'git rm <paths>'"));
421 advise(_("after resolving the conflicts, mark the corrected paths\n"
422 "with 'git add <paths>' or 'git rm <paths>'\n"
423 "and commit the result with 'git commit'"));
427 static int write_message(const void *buf, size_t len, const char *filename,
430 struct lock_file msg_file = LOCK_INIT;
432 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
434 return error_errno(_("could not lock '%s'"), filename);
435 if (write_in_full(msg_fd, buf, len) < 0) {
436 error_errno(_("could not write to '%s'"), filename);
437 rollback_lock_file(&msg_file);
440 if (append_eol && write(msg_fd, "\n", 1) < 0) {
441 error_errno(_("could not write eol to '%s'"), filename);
442 rollback_lock_file(&msg_file);
445 if (commit_lock_file(&msg_file) < 0)
446 return error(_("failed to finalize '%s'"), filename);
451 int read_oneliner(struct strbuf *buf,
452 const char *path, unsigned flags)
454 int orig_len = buf->len;
456 if (strbuf_read_file(buf, path, 0) < 0) {
457 if ((flags & READ_ONELINER_WARN_MISSING) ||
458 (errno != ENOENT && errno != ENOTDIR))
459 warning_errno(_("could not read '%s'"), path);
463 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
464 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
466 buf->buf[buf->len] = '\0';
469 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
475 static struct tree *empty_tree(struct repository *r)
477 return lookup_tree(r, the_hash_algo->empty_tree);
480 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
482 if (repo_read_index_unmerged(repo))
483 return error_resolve_conflict(_(action_name(opts)));
485 error(_("your local changes would be overwritten by %s."),
486 _(action_name(opts)));
488 if (advice_commit_before_merge)
489 advise(_("commit your changes or stash them to proceed."));
493 static void update_abort_safety_file(void)
495 struct object_id head;
497 /* Do nothing on a single-pick */
498 if (!file_exists(git_path_seq_dir()))
501 if (!get_oid("HEAD", &head))
502 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
504 write_file(git_path_abort_safety_file(), "%s", "");
507 static int fast_forward_to(struct repository *r,
508 const struct object_id *to,
509 const struct object_id *from,
511 struct replay_opts *opts)
513 struct ref_transaction *transaction;
514 struct strbuf sb = STRBUF_INIT;
515 struct strbuf err = STRBUF_INIT;
518 if (checkout_fast_forward(r, from, to, 1))
519 return -1; /* the callee should have complained already */
521 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
523 transaction = ref_transaction_begin(&err);
525 ref_transaction_update(transaction, "HEAD",
526 to, unborn && !is_rebase_i(opts) ?
529 ref_transaction_commit(transaction, &err)) {
530 ref_transaction_free(transaction);
531 error("%s", err.buf);
533 strbuf_release(&err);
538 strbuf_release(&err);
539 ref_transaction_free(transaction);
540 update_abort_safety_file();
544 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
547 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
548 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
549 COMMIT_MSG_CLEANUP_SPACE;
550 else if (!strcmp(cleanup_arg, "verbatim"))
551 return COMMIT_MSG_CLEANUP_NONE;
552 else if (!strcmp(cleanup_arg, "whitespace"))
553 return COMMIT_MSG_CLEANUP_SPACE;
554 else if (!strcmp(cleanup_arg, "strip"))
555 return COMMIT_MSG_CLEANUP_ALL;
556 else if (!strcmp(cleanup_arg, "scissors"))
557 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
558 COMMIT_MSG_CLEANUP_SPACE;
560 die(_("Invalid cleanup mode %s"), cleanup_arg);
564 * NB using int rather than enum cleanup_mode to stop clang's
565 * -Wtautological-constant-out-of-range-compare complaining that the comparison
568 static const char *describe_cleanup_mode(int cleanup_mode)
570 static const char *modes[] = { "whitespace",
575 if (cleanup_mode < ARRAY_SIZE(modes))
576 return modes[cleanup_mode];
578 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
581 void append_conflicts_hint(struct index_state *istate,
582 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
586 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
587 strbuf_addch(msgbuf, '\n');
588 wt_status_append_cut_line(msgbuf);
589 strbuf_addch(msgbuf, comment_line_char);
592 strbuf_addch(msgbuf, '\n');
593 strbuf_commented_addf(msgbuf, "Conflicts:\n");
594 for (i = 0; i < istate->cache_nr;) {
595 const struct cache_entry *ce = istate->cache[i++];
597 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
598 while (i < istate->cache_nr &&
599 !strcmp(ce->name, istate->cache[i]->name))
605 static int do_recursive_merge(struct repository *r,
606 struct commit *base, struct commit *next,
607 const char *base_label, const char *next_label,
608 struct object_id *head, struct strbuf *msgbuf,
609 struct replay_opts *opts)
611 struct merge_options o;
612 struct merge_result result;
613 struct tree *next_tree, *base_tree, *head_tree;
614 int clean, show_output;
616 struct lock_file index_lock = LOCK_INIT;
618 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
623 init_merge_options(&o, r);
624 o.ancestor = base ? base_label : "(empty tree)";
626 o.branch2 = next ? next_label : "(empty tree)";
627 if (is_rebase_i(opts))
629 o.show_rename_progress = 1;
631 head_tree = parse_tree_indirect(head);
632 next_tree = next ? get_commit_tree(next) : empty_tree(r);
633 base_tree = base ? get_commit_tree(base) : empty_tree(r);
635 for (i = 0; i < opts->xopts_nr; i++)
636 parse_merge_opt(&o, opts->xopts[i]);
638 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
639 memset(&result, 0, sizeof(result));
640 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
642 show_output = !is_rebase_i(opts) || !result.clean;
644 * TODO: merge_switch_to_result will update index/working tree;
645 * we only really want to do that if !result.clean || this is
646 * the final patch to be picked. But determining this is the
647 * final patch would take some work, and "head_tree" would need
648 * to be replace with the tree the index matched before we
649 * started doing any picks.
651 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
652 clean = result.clean;
654 clean = merge_trees(&o, head_tree, next_tree, base_tree);
655 if (is_rebase_i(opts) && clean <= 0)
656 fputs(o.obuf.buf, stdout);
657 strbuf_release(&o.obuf);
660 rollback_lock_file(&index_lock);
664 if (write_locked_index(r->index, &index_lock,
665 COMMIT_LOCK | SKIP_IF_UNCHANGED))
667 * TRANSLATORS: %s will be "revert", "cherry-pick" or
670 return error(_("%s: Unable to write new index file"),
671 _(action_name(opts)));
674 append_conflicts_hint(r->index, msgbuf,
675 opts->default_msg_cleanup);
680 static struct object_id *get_cache_tree_oid(struct index_state *istate)
682 if (!istate->cache_tree)
683 istate->cache_tree = cache_tree();
685 if (!cache_tree_fully_valid(istate->cache_tree))
686 if (cache_tree_update(istate, 0)) {
687 error(_("unable to update cache tree"));
691 return &istate->cache_tree->oid;
694 static int is_index_unchanged(struct repository *r)
696 struct object_id head_oid, *cache_tree_oid;
697 struct commit *head_commit;
698 struct index_state *istate = r->index;
700 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
701 return error(_("could not resolve HEAD commit"));
703 head_commit = lookup_commit(r, &head_oid);
706 * If head_commit is NULL, check_commit, called from
707 * lookup_commit, would have indicated that head_commit is not
708 * a commit object already. parse_commit() will return failure
709 * without further complaints in such a case. Otherwise, if
710 * the commit is invalid, parse_commit() will complain. So
711 * there is nothing for us to say here. Just return failure.
713 if (parse_commit(head_commit))
716 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
719 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
722 static int write_author_script(const char *message)
724 struct strbuf buf = STRBUF_INIT;
729 if (!*message || starts_with(message, "\n")) {
731 /* Missing 'author' line? */
732 unlink(rebase_path_author_script());
734 } else if (skip_prefix(message, "author ", &message))
736 else if ((eol = strchr(message, '\n')))
741 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
742 while (*message && *message != '\n' && *message != '\r')
743 if (skip_prefix(message, " <", &message))
745 else if (*message != '\'')
746 strbuf_addch(&buf, *(message++));
748 strbuf_addf(&buf, "'\\%c'", *(message++));
749 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
750 while (*message && *message != '\n' && *message != '\r')
751 if (skip_prefix(message, "> ", &message))
753 else if (*message != '\'')
754 strbuf_addch(&buf, *(message++));
756 strbuf_addf(&buf, "'\\%c'", *(message++));
757 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
758 while (*message && *message != '\n' && *message != '\r')
759 if (*message != '\'')
760 strbuf_addch(&buf, *(message++));
762 strbuf_addf(&buf, "'\\%c'", *(message++));
763 strbuf_addch(&buf, '\'');
764 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
765 strbuf_release(&buf);
770 * Take a series of KEY='VALUE' lines where VALUE part is
771 * sq-quoted, and append <KEY, VALUE> at the end of the string list
773 static int parse_key_value_squoted(char *buf, struct string_list *list)
776 struct string_list_item *item;
778 char *cp = strchr(buf, '=');
780 np = strchrnul(buf, '\n');
781 return error(_("no key present in '%.*s'"),
782 (int) (np - buf), buf);
784 np = strchrnul(cp, '\n');
786 item = string_list_append(list, buf);
788 buf = np + (*np == '\n');
792 return error(_("unable to dequote value of '%s'"),
794 item->util = xstrdup(cp);
800 * Reads and parses the state directory's "author-script" file, and sets name,
801 * email and date accordingly.
802 * Returns 0 on success, -1 if the file could not be parsed.
804 * The author script is of the format:
806 * GIT_AUTHOR_NAME='$author_name'
807 * GIT_AUTHOR_EMAIL='$author_email'
808 * GIT_AUTHOR_DATE='$author_date'
810 * where $author_name, $author_email and $author_date are quoted. We are strict
811 * with our parsing, as the file was meant to be eval'd in the now-removed
812 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
813 * from what this function expects, it is better to bail out than to do
814 * something that the user does not expect.
816 int read_author_script(const char *path, char **name, char **email, char **date,
819 struct strbuf buf = STRBUF_INIT;
820 struct string_list kv = STRING_LIST_INIT_DUP;
821 int retval = -1; /* assume failure */
822 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
824 if (strbuf_read_file(&buf, path, 256) <= 0) {
825 strbuf_release(&buf);
826 if (errno == ENOENT && allow_missing)
829 return error_errno(_("could not open '%s' for reading"),
833 if (parse_key_value_squoted(buf.buf, &kv))
836 for (i = 0; i < kv.nr; i++) {
837 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
839 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
842 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
844 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
847 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
849 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
853 err = error(_("unknown variable '%s'"),
858 error(_("missing 'GIT_AUTHOR_NAME'"));
860 error(_("missing 'GIT_AUTHOR_EMAIL'"));
862 error(_("missing 'GIT_AUTHOR_DATE'"));
863 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
865 *name = kv.items[name_i].util;
866 *email = kv.items[email_i].util;
867 *date = kv.items[date_i].util;
870 string_list_clear(&kv, !!retval);
871 strbuf_release(&buf);
876 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
877 * file with shell quoting into struct strvec. Returns -1 on
878 * error, 0 otherwise.
880 static int read_env_script(struct strvec *env)
882 char *name, *email, *date;
884 if (read_author_script(rebase_path_author_script(),
885 &name, &email, &date, 0))
888 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
889 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
890 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
898 static char *get_author(const char *message)
903 a = find_commit_header(message, "author", &len);
905 return xmemdupz(a, len);
910 static const char *author_date_from_env_array(const struct strvec *env)
915 for (i = 0; i < env->nr; i++)
916 if (skip_prefix(env->v[i],
917 "GIT_AUTHOR_DATE=", &date))
920 * If GIT_AUTHOR_DATE is missing we should have already errored out when
923 BUG("GIT_AUTHOR_DATE missing from author script");
926 static const char staged_changes_advice[] =
927 N_("you have staged changes in your working tree\n"
928 "If these changes are meant to be squashed into the previous commit, run:\n"
930 " git commit --amend %s\n"
932 "If they are meant to go into a new commit, run:\n"
936 "In both cases, once you're done, continue with:\n"
938 " git rebase --continue\n");
940 #define ALLOW_EMPTY (1<<0)
941 #define EDIT_MSG (1<<1)
942 #define AMEND_MSG (1<<2)
943 #define CLEANUP_MSG (1<<3)
944 #define VERIFY_MSG (1<<4)
945 #define CREATE_ROOT_COMMIT (1<<5)
946 #define VERBATIM_MSG (1<<6)
948 static int run_command_silent_on_success(struct child_process *cmd)
950 struct strbuf buf = STRBUF_INIT;
953 cmd->stdout_to_stderr = 1;
954 rc = pipe_command(cmd,
960 fputs(buf.buf, stderr);
961 strbuf_release(&buf);
966 * If we are cherry-pick, and if the merge did not result in
967 * hand-editing, we will hit this commit and inherit the original
968 * author date and name.
970 * If we are revert, or if our cherry-pick results in a hand merge,
971 * we had better say that the current user is responsible for that.
973 * An exception is when run_git_commit() is called during an
974 * interactive rebase: in that case, we will want to retain the
977 static int run_git_commit(const char *defmsg,
978 struct replay_opts *opts,
981 struct child_process cmd = CHILD_PROCESS_INIT;
983 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
984 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
988 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
989 const char *gpg_opt = gpg_sign_opt_quoted(opts);
991 return error(_(staged_changes_advice),
995 if (opts->committer_date_is_author_date)
996 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
999 author_date_from_env_array(&cmd.env_array));
1000 if (opts->ignore_date)
1001 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1003 strvec_push(&cmd.args, "commit");
1005 if (!(flags & VERIFY_MSG))
1006 strvec_push(&cmd.args, "-n");
1007 if ((flags & AMEND_MSG))
1008 strvec_push(&cmd.args, "--amend");
1010 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1012 strvec_push(&cmd.args, "--no-gpg-sign");
1014 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1015 else if (!(flags & EDIT_MSG))
1016 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1017 if ((flags & CLEANUP_MSG))
1018 strvec_push(&cmd.args, "--cleanup=strip");
1019 if ((flags & VERBATIM_MSG))
1020 strvec_push(&cmd.args, "--cleanup=verbatim");
1021 if ((flags & EDIT_MSG))
1022 strvec_push(&cmd.args, "-e");
1023 else if (!(flags & CLEANUP_MSG) &&
1024 !opts->signoff && !opts->record_origin &&
1025 !opts->explicit_cleanup)
1026 strvec_push(&cmd.args, "--cleanup=verbatim");
1028 if ((flags & ALLOW_EMPTY))
1029 strvec_push(&cmd.args, "--allow-empty");
1031 if (!(flags & EDIT_MSG))
1032 strvec_push(&cmd.args, "--allow-empty-message");
1034 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1035 return run_command_silent_on_success(&cmd);
1037 return run_command(&cmd);
1040 static int rest_is_empty(const struct strbuf *sb, int start)
1045 /* Check if the rest is just whitespace and Signed-off-by's. */
1046 for (i = start; i < sb->len; i++) {
1047 nl = memchr(sb->buf + i, '\n', sb->len - i);
1053 if (strlen(sign_off_header) <= eol - i &&
1054 starts_with(sb->buf + i, sign_off_header)) {
1059 if (!isspace(sb->buf[i++]))
1066 void cleanup_message(struct strbuf *msgbuf,
1067 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1069 if (verbose || /* Truncate the message just before the diff, if any. */
1070 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1071 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1072 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1073 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1077 * Find out if the message in the strbuf contains only whitespace and
1078 * Signed-off-by lines.
1080 int message_is_empty(const struct strbuf *sb,
1081 enum commit_msg_cleanup_mode cleanup_mode)
1083 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1085 return rest_is_empty(sb, 0);
1089 * See if the user edited the message in the editor or left what
1090 * was in the template intact
1092 int template_untouched(const struct strbuf *sb, const char *template_file,
1093 enum commit_msg_cleanup_mode cleanup_mode)
1095 struct strbuf tmpl = STRBUF_INIT;
1098 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1101 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1104 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1105 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1107 strbuf_release(&tmpl);
1108 return rest_is_empty(sb, start - sb->buf);
1111 int update_head_with_reflog(const struct commit *old_head,
1112 const struct object_id *new_head,
1113 const char *action, const struct strbuf *msg,
1116 struct ref_transaction *transaction;
1117 struct strbuf sb = STRBUF_INIT;
1122 strbuf_addstr(&sb, action);
1123 strbuf_addstr(&sb, ": ");
1126 nl = strchr(msg->buf, '\n');
1128 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1130 strbuf_addbuf(&sb, msg);
1131 strbuf_addch(&sb, '\n');
1134 transaction = ref_transaction_begin(err);
1136 ref_transaction_update(transaction, "HEAD", new_head,
1137 old_head ? &old_head->object.oid : &null_oid,
1139 ref_transaction_commit(transaction, err)) {
1142 ref_transaction_free(transaction);
1143 strbuf_release(&sb);
1148 static int run_rewrite_hook(const struct object_id *oldoid,
1149 const struct object_id *newoid)
1151 struct child_process proc = CHILD_PROCESS_INIT;
1152 const char *argv[3];
1154 struct strbuf sb = STRBUF_INIT;
1156 argv[0] = find_hook("post-rewrite");
1165 proc.stdout_to_stderr = 1;
1166 proc.trace2_hook_name = "post-rewrite";
1168 code = start_command(&proc);
1171 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1172 sigchain_push(SIGPIPE, SIG_IGN);
1173 write_in_full(proc.in, sb.buf, sb.len);
1175 strbuf_release(&sb);
1176 sigchain_pop(SIGPIPE);
1177 return finish_command(&proc);
1180 void commit_post_rewrite(struct repository *r,
1181 const struct commit *old_head,
1182 const struct object_id *new_head)
1184 struct notes_rewrite_cfg *cfg;
1186 cfg = init_copy_notes_for_rewrite("amend");
1188 /* we are amending, so old_head is not NULL */
1189 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1190 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1192 run_rewrite_hook(&old_head->object.oid, new_head);
1195 static int run_prepare_commit_msg_hook(struct repository *r,
1200 const char *name, *arg1 = NULL, *arg2 = NULL;
1202 name = git_path_commit_editmsg();
1203 if (write_message(msg->buf, msg->len, name, 0))
1212 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1214 ret = error(_("'prepare-commit-msg' hook failed"));
1219 static const char implicit_ident_advice_noconfig[] =
1220 N_("Your name and email address were configured automatically based\n"
1221 "on your username and hostname. Please check that they are accurate.\n"
1222 "You can suppress this message by setting them explicitly. Run the\n"
1223 "following command and follow the instructions in your editor to edit\n"
1224 "your configuration file:\n"
1226 " git config --global --edit\n"
1228 "After doing this, you may fix the identity used for this commit with:\n"
1230 " git commit --amend --reset-author\n");
1232 static const char implicit_ident_advice_config[] =
1233 N_("Your name and email address were configured automatically based\n"
1234 "on your username and hostname. Please check that they are accurate.\n"
1235 "You can suppress this message by setting them explicitly:\n"
1237 " git config --global user.name \"Your Name\"\n"
1238 " git config --global user.email you@example.com\n"
1240 "After doing this, you may fix the identity used for this commit with:\n"
1242 " git commit --amend --reset-author\n");
1244 static const char *implicit_ident_advice(void)
1246 char *user_config = expand_user_path("~/.gitconfig", 0);
1247 char *xdg_config = xdg_config_home("config");
1248 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1254 return _(implicit_ident_advice_config);
1256 return _(implicit_ident_advice_noconfig);
1260 void print_commit_summary(struct repository *r,
1262 const struct object_id *oid,
1265 struct rev_info rev;
1266 struct commit *commit;
1267 struct strbuf format = STRBUF_INIT;
1269 struct pretty_print_context pctx = {0};
1270 struct strbuf author_ident = STRBUF_INIT;
1271 struct strbuf committer_ident = STRBUF_INIT;
1273 commit = lookup_commit(r, oid);
1275 die(_("couldn't look up newly created commit"));
1276 if (parse_commit(commit))
1277 die(_("could not parse newly created commit"));
1279 strbuf_addstr(&format, "format:%h] %s");
1281 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1282 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1283 if (strbuf_cmp(&author_ident, &committer_ident)) {
1284 strbuf_addstr(&format, "\n Author: ");
1285 strbuf_addbuf_percentquote(&format, &author_ident);
1287 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1288 struct strbuf date = STRBUF_INIT;
1290 format_commit_message(commit, "%ad", &date, &pctx);
1291 strbuf_addstr(&format, "\n Date: ");
1292 strbuf_addbuf_percentquote(&format, &date);
1293 strbuf_release(&date);
1295 if (!committer_ident_sufficiently_given()) {
1296 strbuf_addstr(&format, "\n Committer: ");
1297 strbuf_addbuf_percentquote(&format, &committer_ident);
1298 if (advice_implicit_identity) {
1299 strbuf_addch(&format, '\n');
1300 strbuf_addstr(&format, implicit_ident_advice());
1303 strbuf_release(&author_ident);
1304 strbuf_release(&committer_ident);
1306 repo_init_revisions(r, &rev, prefix);
1307 setup_revisions(0, NULL, &rev, NULL);
1310 rev.diffopt.output_format =
1311 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1313 rev.verbose_header = 1;
1314 rev.show_root_diff = 1;
1315 get_commit_format(format.buf, &rev);
1316 rev.always_show_header = 0;
1317 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1318 rev.diffopt.break_opt = 0;
1319 diff_setup_done(&rev.diffopt);
1321 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1323 die_errno(_("unable to resolve HEAD after creating commit"));
1324 if (!strcmp(head, "HEAD"))
1325 head = _("detached HEAD");
1327 skip_prefix(head, "refs/heads/", &head);
1328 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1329 _(" (root-commit)") : "");
1331 if (!log_tree_commit(&rev, commit)) {
1332 rev.always_show_header = 1;
1333 rev.use_terminator = 1;
1334 log_tree_commit(&rev, commit);
1337 strbuf_release(&format);
1340 static int parse_head(struct repository *r, struct commit **head)
1342 struct commit *current_head;
1343 struct object_id oid;
1345 if (get_oid("HEAD", &oid)) {
1346 current_head = NULL;
1348 current_head = lookup_commit_reference(r, &oid);
1350 return error(_("could not parse HEAD"));
1351 if (!oideq(&oid, ¤t_head->object.oid)) {
1352 warning(_("HEAD %s is not a commit!"),
1355 if (parse_commit(current_head))
1356 return error(_("could not parse HEAD commit"));
1358 *head = current_head;
1364 * Try to commit without forking 'git commit'. In some cases we need
1365 * to run 'git commit' to display an error message
1368 * -1 - error unable to commit
1370 * 1 - run 'git commit'
1372 static int try_to_commit(struct repository *r,
1373 struct strbuf *msg, const char *author,
1374 struct replay_opts *opts, unsigned int flags,
1375 struct object_id *oid)
1377 struct object_id tree;
1378 struct commit *current_head = NULL;
1379 struct commit_list *parents = NULL;
1380 struct commit_extra_header *extra = NULL;
1381 struct strbuf err = STRBUF_INIT;
1382 struct strbuf commit_msg = STRBUF_INIT;
1383 char *amend_author = NULL;
1384 const char *committer = NULL;
1385 const char *hook_commit = NULL;
1386 enum commit_msg_cleanup_mode cleanup;
1389 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1390 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1392 if (parse_head(r, ¤t_head))
1395 if (flags & AMEND_MSG) {
1396 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1397 const char *out_enc = get_commit_output_encoding();
1398 const char *message = logmsg_reencode(current_head, NULL,
1402 const char *orig_message = NULL;
1404 find_commit_subject(message, &orig_message);
1406 strbuf_addstr(msg, orig_message);
1407 hook_commit = "HEAD";
1409 author = amend_author = get_author(message);
1410 unuse_commit_buffer(current_head, message);
1412 res = error(_("unable to parse commit author"));
1415 parents = copy_commit_list(current_head->parents);
1416 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1417 } else if (current_head &&
1418 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1419 commit_list_insert(current_head, &parents);
1422 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1423 res = error(_("git write-tree failed to write a tree"));
1427 if (!(flags & ALLOW_EMPTY)) {
1428 struct commit *first_parent = current_head;
1430 if (flags & AMEND_MSG) {
1431 if (current_head->parents) {
1432 first_parent = current_head->parents->item;
1433 if (repo_parse_commit(r, first_parent)) {
1434 res = error(_("could not parse HEAD commit"));
1438 first_parent = NULL;
1441 if (oideq(first_parent
1442 ? get_commit_tree_oid(first_parent)
1443 : the_hash_algo->empty_tree,
1445 res = 1; /* run 'git commit' to display error message */
1450 if (find_hook("prepare-commit-msg")) {
1451 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1454 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1456 res = error_errno(_("unable to read commit message "
1458 git_path_commit_editmsg());
1464 if (flags & CLEANUP_MSG)
1465 cleanup = COMMIT_MSG_CLEANUP_ALL;
1466 else if (flags & VERBATIM_MSG)
1467 cleanup = COMMIT_MSG_CLEANUP_NONE;
1468 else if ((opts->signoff || opts->record_origin) &&
1469 !opts->explicit_cleanup)
1470 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1472 cleanup = opts->default_msg_cleanup;
1474 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1475 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1476 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1477 res = 1; /* run 'git commit' to display error message */
1481 if (opts->committer_date_is_author_date) {
1482 struct ident_split id;
1483 struct strbuf date = STRBUF_INIT;
1485 if (!opts->ignore_date) {
1486 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1487 res = error(_("invalid author identity '%s'"),
1491 if (!id.date_begin) {
1493 "corrupt author: missing date information"));
1496 strbuf_addf(&date, "@%.*s %.*s",
1497 (int)(id.date_end - id.date_begin),
1499 (int)(id.tz_end - id.tz_begin),
1504 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1505 getenv("GIT_COMMITTER_EMAIL"),
1506 WANT_COMMITTER_IDENT,
1507 opts->ignore_date ? NULL : date.buf,
1509 strbuf_release(&date);
1514 if (opts->ignore_date) {
1515 struct ident_split id;
1518 if (split_ident_line(&id, author, strlen(author)) < 0) {
1519 error(_("invalid author identity '%s'"), author);
1522 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1523 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1524 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1530 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1531 author, committer, opts->gpg_sign, extra)) {
1532 res = error(_("failed to write commit object"));
1536 if (update_head_with_reflog(current_head, oid,
1537 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1538 res = error("%s", err.buf);
1542 run_commit_hook(0, r->index_file, "post-commit", NULL);
1543 if (flags & AMEND_MSG)
1544 commit_post_rewrite(r, current_head, oid);
1547 free_commit_extra_headers(extra);
1548 strbuf_release(&err);
1549 strbuf_release(&commit_msg);
1555 static int write_rebase_head(struct object_id *oid)
1557 if (update_ref("rebase", "REBASE_HEAD", oid,
1558 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1559 return error(_("could not update %s"), "REBASE_HEAD");
1564 static int do_commit(struct repository *r,
1565 const char *msg_file, const char *author,
1566 struct replay_opts *opts, unsigned int flags,
1567 struct object_id *oid)
1571 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1572 struct object_id oid;
1573 struct strbuf sb = STRBUF_INIT;
1575 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1576 return error_errno(_("unable to read commit message "
1580 res = try_to_commit(r, msg_file ? &sb : NULL,
1581 author, opts, flags, &oid);
1582 strbuf_release(&sb);
1584 refs_delete_ref(get_main_ref_store(r), "",
1585 "CHERRY_PICK_HEAD", NULL, 0);
1586 unlink(git_path_merge_msg(r));
1587 if (!is_rebase_i(opts))
1588 print_commit_summary(r, NULL, &oid,
1589 SUMMARY_SHOW_AUTHOR_DATE);
1594 if (is_rebase_i(opts) && oid)
1595 if (write_rebase_head(oid))
1597 return run_git_commit(msg_file, opts, flags);
1603 static int is_original_commit_empty(struct commit *commit)
1605 const struct object_id *ptree_oid;
1607 if (parse_commit(commit))
1608 return error(_("could not parse commit %s"),
1609 oid_to_hex(&commit->object.oid));
1610 if (commit->parents) {
1611 struct commit *parent = commit->parents->item;
1612 if (parse_commit(parent))
1613 return error(_("could not parse parent commit %s"),
1614 oid_to_hex(&parent->object.oid));
1615 ptree_oid = get_commit_tree_oid(parent);
1617 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1620 return oideq(ptree_oid, get_commit_tree_oid(commit));
1624 * Should empty commits be allowed? Return status:
1625 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1626 * 0: Halt on empty commit
1627 * 1: Allow empty commit
1628 * 2: Drop empty commit
1630 static int allow_empty(struct repository *r,
1631 struct replay_opts *opts,
1632 struct commit *commit)
1634 int index_unchanged, originally_empty;
1639 * (1) we do not allow empty at all and error out.
1641 * (2) we allow ones that were initially empty, and
1642 * just drop the ones that become empty
1644 * (3) we allow ones that were initially empty, but
1645 * halt for the ones that become empty;
1647 * (4) we allow both.
1649 if (!opts->allow_empty)
1650 return 0; /* let "git commit" barf as necessary */
1652 index_unchanged = is_index_unchanged(r);
1653 if (index_unchanged < 0)
1654 return index_unchanged;
1655 if (!index_unchanged)
1656 return 0; /* we do not have to say --allow-empty */
1658 if (opts->keep_redundant_commits)
1661 originally_empty = is_original_commit_empty(commit);
1662 if (originally_empty < 0)
1663 return originally_empty;
1664 if (originally_empty)
1666 else if (opts->drop_redundant_commits)
1675 } todo_command_info[] = {
1692 static const char *command_to_string(const enum todo_command command)
1694 if (command < TODO_COMMENT)
1695 return todo_command_info[command].str;
1696 die(_("unknown command: %d"), command);
1699 static char command_to_char(const enum todo_command command)
1701 if (command < TODO_COMMENT)
1702 return todo_command_info[command].c;
1703 return comment_line_char;
1706 static int is_noop(const enum todo_command command)
1708 return TODO_NOOP <= command;
1711 static int is_fixup(enum todo_command command)
1713 return command == TODO_FIXUP || command == TODO_SQUASH;
1716 /* Does this command create a (non-merge) commit? */
1717 static int is_pick_or_similar(enum todo_command command)
1732 static int update_squash_messages(struct repository *r,
1733 enum todo_command command,
1734 struct commit *commit,
1735 struct replay_opts *opts)
1737 struct strbuf buf = STRBUF_INIT;
1739 const char *message, *body;
1740 const char *encoding = get_commit_output_encoding();
1742 if (opts->current_fixup_count > 0) {
1743 struct strbuf header = STRBUF_INIT;
1746 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1747 return error(_("could not read '%s'"),
1748 rebase_path_squash_msg());
1750 eol = buf.buf[0] != comment_line_char ?
1751 buf.buf : strchrnul(buf.buf, '\n');
1753 strbuf_addf(&header, "%c ", comment_line_char);
1754 strbuf_addf(&header, _("This is a combination of %d commits."),
1755 opts->current_fixup_count + 2);
1756 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1757 strbuf_release(&header);
1759 struct object_id head;
1760 struct commit *head_commit;
1761 const char *head_message, *body;
1763 if (get_oid("HEAD", &head))
1764 return error(_("need a HEAD to fixup"));
1765 if (!(head_commit = lookup_commit_reference(r, &head)))
1766 return error(_("could not read HEAD"));
1767 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1768 return error(_("could not read HEAD's commit message"));
1770 find_commit_subject(head_message, &body);
1771 if (write_message(body, strlen(body),
1772 rebase_path_fixup_msg(), 0)) {
1773 unuse_commit_buffer(head_commit, head_message);
1774 return error(_("cannot write '%s'"),
1775 rebase_path_fixup_msg());
1778 strbuf_addf(&buf, "%c ", comment_line_char);
1779 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1780 strbuf_addf(&buf, "\n%c ", comment_line_char);
1781 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1782 strbuf_addstr(&buf, "\n\n");
1783 strbuf_addstr(&buf, body);
1785 unuse_commit_buffer(head_commit, head_message);
1788 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1789 return error(_("could not read commit message of %s"),
1790 oid_to_hex(&commit->object.oid));
1791 find_commit_subject(message, &body);
1793 if (command == TODO_SQUASH) {
1794 unlink(rebase_path_fixup_msg());
1795 strbuf_addf(&buf, "\n%c ", comment_line_char);
1796 strbuf_addf(&buf, _("This is the commit message #%d:"),
1797 ++opts->current_fixup_count + 1);
1798 strbuf_addstr(&buf, "\n\n");
1799 strbuf_addstr(&buf, body);
1800 } else if (command == TODO_FIXUP) {
1801 strbuf_addf(&buf, "\n%c ", comment_line_char);
1802 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1803 ++opts->current_fixup_count + 1);
1804 strbuf_addstr(&buf, "\n\n");
1805 strbuf_add_commented_lines(&buf, body, strlen(body));
1807 return error(_("unknown command: %d"), command);
1808 unuse_commit_buffer(commit, message);
1810 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1811 strbuf_release(&buf);
1814 strbuf_addf(&opts->current_fixups, "%s%s %s",
1815 opts->current_fixups.len ? "\n" : "",
1816 command_to_string(command),
1817 oid_to_hex(&commit->object.oid));
1818 res = write_message(opts->current_fixups.buf,
1819 opts->current_fixups.len,
1820 rebase_path_current_fixups(), 0);
1826 static void flush_rewritten_pending(void)
1828 struct strbuf buf = STRBUF_INIT;
1829 struct object_id newoid;
1832 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1833 !get_oid("HEAD", &newoid) &&
1834 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1835 char *bol = buf.buf, *eol;
1838 eol = strchrnul(bol, '\n');
1839 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1840 bol, oid_to_hex(&newoid));
1846 unlink(rebase_path_rewritten_pending());
1848 strbuf_release(&buf);
1851 static void record_in_rewritten(struct object_id *oid,
1852 enum todo_command next_command)
1854 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1859 fprintf(out, "%s\n", oid_to_hex(oid));
1862 if (!is_fixup(next_command))
1863 flush_rewritten_pending();
1866 static int do_pick_commit(struct repository *r,
1867 enum todo_command command,
1868 struct commit *commit,
1869 struct replay_opts *opts,
1870 int final_fixup, int *check_todo)
1872 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1873 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1874 struct object_id head;
1875 struct commit *base, *next, *parent;
1876 const char *base_label, *next_label;
1877 char *author = NULL;
1878 struct commit_message msg = { NULL, NULL, NULL, NULL };
1879 struct strbuf msgbuf = STRBUF_INIT;
1880 int res, unborn = 0, reword = 0, allow, drop_commit;
1882 if (opts->no_commit) {
1884 * We do not intend to commit immediately. We just want to
1885 * merge the differences in, so let's compute the tree
1886 * that represents the "current" state for merge-recursive
1889 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1890 return error(_("your index file is unmerged."));
1892 unborn = get_oid("HEAD", &head);
1893 /* Do we want to generate a root commit? */
1894 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1895 oideq(&head, &opts->squash_onto)) {
1896 if (is_fixup(command))
1897 return error(_("cannot fixup root commit"));
1898 flags |= CREATE_ROOT_COMMIT;
1901 oidcpy(&head, the_hash_algo->empty_tree);
1902 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1904 return error_dirty_index(r, opts);
1906 discard_index(r->index);
1908 if (!commit->parents)
1910 else if (commit->parents->next) {
1911 /* Reverting or cherry-picking a merge commit */
1913 struct commit_list *p;
1915 if (!opts->mainline)
1916 return error(_("commit %s is a merge but no -m option was given."),
1917 oid_to_hex(&commit->object.oid));
1919 for (cnt = 1, p = commit->parents;
1920 cnt != opts->mainline && p;
1923 if (cnt != opts->mainline || !p)
1924 return error(_("commit %s does not have parent %d"),
1925 oid_to_hex(&commit->object.oid), opts->mainline);
1927 } else if (1 < opts->mainline)
1929 * Non-first parent explicitly specified as mainline for
1932 return error(_("commit %s does not have parent %d"),
1933 oid_to_hex(&commit->object.oid), opts->mainline);
1935 parent = commit->parents->item;
1937 if (get_message(commit, &msg) != 0)
1938 return error(_("cannot get commit message for %s"),
1939 oid_to_hex(&commit->object.oid));
1941 if (opts->allow_ff && !is_fixup(command) &&
1942 ((parent && oideq(&parent->object.oid, &head)) ||
1943 (!parent && unborn))) {
1944 if (is_rebase_i(opts))
1945 write_author_script(msg.message);
1946 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1948 if (res || command != TODO_REWORD)
1952 goto fast_forward_edit;
1954 if (parent && parse_commit(parent) < 0)
1955 /* TRANSLATORS: The first %s will be a "todo" command like
1956 "revert" or "pick", the second %s a SHA1. */
1957 return error(_("%s: cannot parse parent commit %s"),
1958 command_to_string(command),
1959 oid_to_hex(&parent->object.oid));
1962 * "commit" is an existing commit. We would want to apply
1963 * the difference it introduces since its first parent "prev"
1964 * on top of the current HEAD if we are cherry-pick. Or the
1965 * reverse of it if we are revert.
1968 if (command == TODO_REVERT) {
1970 base_label = msg.label;
1972 next_label = msg.parent_label;
1973 strbuf_addstr(&msgbuf, "Revert \"");
1974 strbuf_addstr(&msgbuf, msg.subject);
1975 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1976 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1978 if (commit->parents && commit->parents->next) {
1979 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1980 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1982 strbuf_addstr(&msgbuf, ".\n");
1987 base_label = msg.parent_label;
1989 next_label = msg.label;
1991 /* Append the commit log message to msgbuf. */
1992 if (find_commit_subject(msg.message, &p))
1993 strbuf_addstr(&msgbuf, p);
1995 if (opts->record_origin) {
1996 strbuf_complete_line(&msgbuf);
1997 if (!has_conforming_footer(&msgbuf, NULL, 0))
1998 strbuf_addch(&msgbuf, '\n');
1999 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2000 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2001 strbuf_addstr(&msgbuf, ")\n");
2003 if (!is_fixup(command))
2004 author = get_author(msg.message);
2007 if (command == TODO_REWORD)
2009 else if (is_fixup(command)) {
2010 if (update_squash_messages(r, command, commit, opts))
2014 msg_file = rebase_path_squash_msg();
2015 else if (file_exists(rebase_path_fixup_msg())) {
2016 flags |= VERBATIM_MSG;
2017 msg_file = rebase_path_fixup_msg();
2019 const char *dest = git_path_squash_msg(r);
2021 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2022 return error(_("could not rename '%s' to '%s'"),
2023 rebase_path_squash_msg(), dest);
2024 unlink(git_path_merge_msg(r));
2030 if (opts->signoff && !is_fixup(command))
2031 append_signoff(&msgbuf, 0, 0);
2033 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2035 else if (!opts->strategy ||
2036 !strcmp(opts->strategy, "recursive") ||
2037 !strcmp(opts->strategy, "ort") ||
2038 command == TODO_REVERT) {
2039 res = do_recursive_merge(r, base, next, base_label, next_label,
2040 &head, &msgbuf, opts);
2044 res |= write_message(msgbuf.buf, msgbuf.len,
2045 git_path_merge_msg(r), 0);
2047 struct commit_list *common = NULL;
2048 struct commit_list *remotes = NULL;
2050 res = write_message(msgbuf.buf, msgbuf.len,
2051 git_path_merge_msg(r), 0);
2053 commit_list_insert(base, &common);
2054 commit_list_insert(next, &remotes);
2055 res |= try_merge_command(r, opts->strategy,
2056 opts->xopts_nr, (const char **)opts->xopts,
2057 common, oid_to_hex(&head), remotes);
2058 free_commit_list(common);
2059 free_commit_list(remotes);
2061 strbuf_release(&msgbuf);
2064 * If the merge was clean or if it failed due to conflict, we write
2065 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2066 * However, if the merge did not even start, then we don't want to
2069 if ((command == TODO_PICK || command == TODO_REWORD ||
2070 command == TODO_EDIT) && !opts->no_commit &&
2071 (res == 0 || res == 1) &&
2072 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2073 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2075 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2076 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2077 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2081 error(command == TODO_REVERT
2082 ? _("could not revert %s... %s")
2083 : _("could not apply %s... %s"),
2084 short_commit_name(commit), msg.subject);
2085 print_advice(r, res == 1, opts);
2086 repo_rerere(r, opts->allow_rerere_auto);
2091 allow = allow_empty(r, opts, commit);
2095 } else if (allow == 1) {
2096 flags |= ALLOW_EMPTY;
2097 } else if (allow == 2) {
2099 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2101 unlink(git_path_merge_msg(r));
2103 _("dropping %s %s -- patch contents already upstream\n"),
2104 oid_to_hex(&commit->object.oid), msg.subject);
2105 } /* else allow == 0 and there's nothing special to do */
2106 if (!opts->no_commit && !drop_commit) {
2107 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2108 res = do_commit(r, msg_file, author, opts, flags,
2109 commit? &commit->object.oid : NULL);
2111 res = error(_("unable to parse commit author"));
2112 *check_todo = !!(flags & EDIT_MSG);
2113 if (!res && reword) {
2115 res = run_git_commit(NULL, opts, EDIT_MSG |
2116 VERIFY_MSG | AMEND_MSG |
2117 (flags & ALLOW_EMPTY));
2123 if (!res && final_fixup) {
2124 unlink(rebase_path_fixup_msg());
2125 unlink(rebase_path_squash_msg());
2126 unlink(rebase_path_current_fixups());
2127 strbuf_reset(&opts->current_fixups);
2128 opts->current_fixup_count = 0;
2132 free_message(commit, &msg);
2134 update_abort_safety_file();
2139 static int prepare_revs(struct replay_opts *opts)
2142 * picking (but not reverting) ranges (but not individual revisions)
2143 * should be done in reverse
2145 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2146 opts->revs->reverse ^= 1;
2148 if (prepare_revision_walk(opts->revs))
2149 return error(_("revision walk setup failed"));
2154 static int read_and_refresh_cache(struct repository *r,
2155 struct replay_opts *opts)
2157 struct lock_file index_lock = LOCK_INIT;
2158 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2159 if (repo_read_index(r) < 0) {
2160 rollback_lock_file(&index_lock);
2161 return error(_("git %s: failed to read the index"),
2162 _(action_name(opts)));
2164 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2165 if (index_fd >= 0) {
2166 if (write_locked_index(r->index, &index_lock,
2167 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2168 return error(_("git %s: failed to refresh the index"),
2169 _(action_name(opts)));
2175 enum todo_item_flags {
2176 TODO_EDIT_MERGE_MSG = 1
2179 void todo_list_release(struct todo_list *todo_list)
2181 strbuf_release(&todo_list->buf);
2182 FREE_AND_NULL(todo_list->items);
2183 todo_list->nr = todo_list->alloc = 0;
2186 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2188 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2189 todo_list->total_nr++;
2190 return todo_list->items + todo_list->nr++;
2193 const char *todo_item_get_arg(struct todo_list *todo_list,
2194 struct todo_item *item)
2196 return todo_list->buf.buf + item->arg_offset;
2199 static int is_command(enum todo_command command, const char **bol)
2201 const char *str = todo_command_info[command].str;
2202 const char nick = todo_command_info[command].c;
2203 const char *p = *bol + 1;
2205 return skip_prefix(*bol, str, bol) ||
2206 ((nick && **bol == nick) &&
2207 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2211 static int parse_insn_line(struct repository *r, struct todo_item *item,
2212 const char *buf, const char *bol, char *eol)
2214 struct object_id commit_oid;
2215 char *end_of_object_name;
2216 int i, saved, status, padding;
2221 bol += strspn(bol, " \t");
2223 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2224 item->command = TODO_COMMENT;
2225 item->commit = NULL;
2226 item->arg_offset = bol - buf;
2227 item->arg_len = eol - bol;
2231 for (i = 0; i < TODO_COMMENT; i++)
2232 if (is_command(i, &bol)) {
2236 if (i >= TODO_COMMENT)
2239 /* Eat up extra spaces/ tabs before object name */
2240 padding = strspn(bol, " \t");
2243 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2245 return error(_("%s does not accept arguments: '%s'"),
2246 command_to_string(item->command), bol);
2247 item->commit = NULL;
2248 item->arg_offset = bol - buf;
2249 item->arg_len = eol - bol;
2254 return error(_("missing arguments for %s"),
2255 command_to_string(item->command));
2257 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2258 item->command == TODO_RESET) {
2259 item->commit = NULL;
2260 item->arg_offset = bol - buf;
2261 item->arg_len = (int)(eol - bol);
2265 if (item->command == TODO_MERGE) {
2266 if (skip_prefix(bol, "-C", &bol))
2267 bol += strspn(bol, " \t");
2268 else if (skip_prefix(bol, "-c", &bol)) {
2269 bol += strspn(bol, " \t");
2270 item->flags |= TODO_EDIT_MERGE_MSG;
2272 item->flags |= TODO_EDIT_MERGE_MSG;
2273 item->commit = NULL;
2274 item->arg_offset = bol - buf;
2275 item->arg_len = (int)(eol - bol);
2280 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2281 saved = *end_of_object_name;
2282 *end_of_object_name = '\0';
2283 status = get_oid(bol, &commit_oid);
2285 error(_("could not parse '%s'"), bol); /* return later */
2286 *end_of_object_name = saved;
2288 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2289 item->arg_offset = bol - buf;
2290 item->arg_len = (int)(eol - bol);
2295 item->commit = lookup_commit_reference(r, &commit_oid);
2296 return item->commit ? 0 : -1;
2299 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2301 const char *todo_file, *bol;
2302 struct strbuf buf = STRBUF_INIT;
2305 todo_file = git_path_todo_file();
2306 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2307 if (errno == ENOENT || errno == ENOTDIR)
2310 return error_errno("unable to open '%s'", todo_file);
2312 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2313 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2314 *action = REPLAY_PICK;
2315 else if (is_command(TODO_REVERT, &bol) &&
2316 (*bol == ' ' || *bol == '\t'))
2317 *action = REPLAY_REVERT;
2321 strbuf_release(&buf);
2326 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2327 struct todo_list *todo_list)
2329 struct todo_item *item;
2330 char *p = buf, *next_p;
2331 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2333 todo_list->current = todo_list->nr = 0;
2335 for (i = 1; *p; i++, p = next_p) {
2336 char *eol = strchrnul(p, '\n');
2338 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2340 if (p != eol && eol[-1] == '\r')
2341 eol--; /* strip Carriage Return */
2343 item = append_new_todo(todo_list);
2344 item->offset_in_buf = p - todo_list->buf.buf;
2345 if (parse_insn_line(r, item, buf, p, eol)) {
2346 res = error(_("invalid line %d: %.*s"),
2347 i, (int)(eol - p), p);
2348 item->command = TODO_COMMENT + 1;
2349 item->arg_offset = p - buf;
2350 item->arg_len = (int)(eol - p);
2351 item->commit = NULL;
2356 else if (is_fixup(item->command))
2357 return error(_("cannot '%s' without a previous commit"),
2358 command_to_string(item->command));
2359 else if (!is_noop(item->command))
2366 static int count_commands(struct todo_list *todo_list)
2370 for (i = 0; i < todo_list->nr; i++)
2371 if (todo_list->items[i].command != TODO_COMMENT)
2377 static int get_item_line_offset(struct todo_list *todo_list, int index)
2379 return index < todo_list->nr ?
2380 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2383 static const char *get_item_line(struct todo_list *todo_list, int index)
2385 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2388 static int get_item_line_length(struct todo_list *todo_list, int index)
2390 return get_item_line_offset(todo_list, index + 1)
2391 - get_item_line_offset(todo_list, index);
2394 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2399 fd = open(path, O_RDONLY);
2401 return error_errno(_("could not open '%s'"), path);
2402 len = strbuf_read(sb, fd, 0);
2405 return error(_("could not read '%s'."), path);
2409 static int have_finished_the_last_pick(void)
2411 struct strbuf buf = STRBUF_INIT;
2413 const char *todo_path = git_path_todo_file();
2416 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2417 if (errno == ENOENT) {
2420 error_errno("unable to open '%s'", todo_path);
2424 /* If there is only one line then we are done */
2425 eol = strchr(buf.buf, '\n');
2426 if (!eol || !eol[1])
2429 strbuf_release(&buf);
2434 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2436 struct replay_opts opts = REPLAY_OPTS_INIT;
2437 int need_cleanup = 0;
2439 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2440 if (!refs_delete_ref(get_main_ref_store(r), "",
2441 "CHERRY_PICK_HEAD", NULL, 0) &&
2443 warning(_("cancelling a cherry picking in progress"));
2444 opts.action = REPLAY_PICK;
2448 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2449 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2452 warning(_("cancelling a revert in progress"));
2453 opts.action = REPLAY_REVERT;
2460 if (!have_finished_the_last_pick())
2463 sequencer_remove_state(&opts);
2466 static void todo_list_write_total_nr(struct todo_list *todo_list)
2468 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2471 fprintf(f, "%d\n", todo_list->total_nr);
2476 static int read_populate_todo(struct repository *r,
2477 struct todo_list *todo_list,
2478 struct replay_opts *opts)
2481 const char *todo_file = get_todo_path(opts);
2484 strbuf_reset(&todo_list->buf);
2485 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2488 res = stat(todo_file, &st);
2490 return error(_("could not stat '%s'"), todo_file);
2491 fill_stat_data(&todo_list->stat, &st);
2493 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2495 if (is_rebase_i(opts))
2496 return error(_("please fix this using "
2497 "'git rebase --edit-todo'."));
2498 return error(_("unusable instruction sheet: '%s'"), todo_file);
2501 if (!todo_list->nr &&
2502 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2503 return error(_("no commits parsed."));
2505 if (!is_rebase_i(opts)) {
2506 enum todo_command valid =
2507 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2510 for (i = 0; i < todo_list->nr; i++)
2511 if (valid == todo_list->items[i].command)
2513 else if (valid == TODO_PICK)
2514 return error(_("cannot cherry-pick during a revert."));
2516 return error(_("cannot revert during a cherry-pick."));
2519 if (is_rebase_i(opts)) {
2520 struct todo_list done = TODO_LIST_INIT;
2522 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2523 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2524 todo_list->done_nr = count_commands(&done);
2526 todo_list->done_nr = 0;
2528 todo_list->total_nr = todo_list->done_nr
2529 + count_commands(todo_list);
2530 todo_list_release(&done);
2532 todo_list_write_total_nr(todo_list);
2538 static int git_config_string_dup(char **dest,
2539 const char *var, const char *value)
2542 return config_error_nonbool(var);
2544 *dest = xstrdup(value);
2548 static int populate_opts_cb(const char *key, const char *value, void *data)
2550 struct replay_opts *opts = data;
2555 else if (!strcmp(key, "options.no-commit"))
2556 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2557 else if (!strcmp(key, "options.edit"))
2558 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2559 else if (!strcmp(key, "options.allow-empty"))
2561 git_config_bool_or_int(key, value, &error_flag);
2562 else if (!strcmp(key, "options.allow-empty-message"))
2563 opts->allow_empty_message =
2564 git_config_bool_or_int(key, value, &error_flag);
2565 else if (!strcmp(key, "options.keep-redundant-commits"))
2566 opts->keep_redundant_commits =
2567 git_config_bool_or_int(key, value, &error_flag);
2568 else if (!strcmp(key, "options.signoff"))
2569 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2570 else if (!strcmp(key, "options.record-origin"))
2571 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2572 else if (!strcmp(key, "options.allow-ff"))
2573 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2574 else if (!strcmp(key, "options.mainline"))
2575 opts->mainline = git_config_int(key, value);
2576 else if (!strcmp(key, "options.strategy"))
2577 git_config_string_dup(&opts->strategy, key, value);
2578 else if (!strcmp(key, "options.gpg-sign"))
2579 git_config_string_dup(&opts->gpg_sign, key, value);
2580 else if (!strcmp(key, "options.strategy-option")) {
2581 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2582 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2583 } else if (!strcmp(key, "options.allow-rerere-auto"))
2584 opts->allow_rerere_auto =
2585 git_config_bool_or_int(key, value, &error_flag) ?
2586 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2587 else if (!strcmp(key, "options.default-msg-cleanup")) {
2588 opts->explicit_cleanup = 1;
2589 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2591 return error(_("invalid key: %s"), key);
2594 return error(_("invalid value for %s: %s"), key, value);
2599 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2602 char *strategy_opts_string = raw_opts;
2604 if (*strategy_opts_string == ' ')
2605 strategy_opts_string++;
2607 opts->xopts_nr = split_cmdline(strategy_opts_string,
2608 (const char ***)&opts->xopts);
2609 for (i = 0; i < opts->xopts_nr; i++) {
2610 const char *arg = opts->xopts[i];
2612 skip_prefix(arg, "--", &arg);
2613 opts->xopts[i] = xstrdup(arg);
2617 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2620 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2622 opts->strategy = strbuf_detach(buf, NULL);
2623 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2626 parse_strategy_opts(opts, buf->buf);
2629 static int read_populate_opts(struct replay_opts *opts)
2631 if (is_rebase_i(opts)) {
2632 struct strbuf buf = STRBUF_INIT;
2635 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2636 READ_ONELINER_SKIP_IF_EMPTY)) {
2637 if (!starts_with(buf.buf, "-S"))
2640 free(opts->gpg_sign);
2641 opts->gpg_sign = xstrdup(buf.buf + 2);
2646 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2647 READ_ONELINER_SKIP_IF_EMPTY)) {
2648 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2649 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2650 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2651 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2655 if (file_exists(rebase_path_verbose()))
2658 if (file_exists(rebase_path_quiet()))
2661 if (file_exists(rebase_path_signoff())) {
2666 if (file_exists(rebase_path_cdate_is_adate())) {
2668 opts->committer_date_is_author_date = 1;
2671 if (file_exists(rebase_path_ignore_date())) {
2673 opts->ignore_date = 1;
2676 if (file_exists(rebase_path_reschedule_failed_exec()))
2677 opts->reschedule_failed_exec = 1;
2679 if (file_exists(rebase_path_drop_redundant_commits()))
2680 opts->drop_redundant_commits = 1;
2682 if (file_exists(rebase_path_keep_redundant_commits()))
2683 opts->keep_redundant_commits = 1;
2685 read_strategy_opts(opts, &buf);
2688 if (read_oneliner(&opts->current_fixups,
2689 rebase_path_current_fixups(),
2690 READ_ONELINER_SKIP_IF_EMPTY)) {
2691 const char *p = opts->current_fixups.buf;
2692 opts->current_fixup_count = 1;
2693 while ((p = strchr(p, '\n'))) {
2694 opts->current_fixup_count++;
2699 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2700 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2701 ret = error(_("unusable squash-onto"));
2704 opts->have_squash_onto = 1;
2708 strbuf_release(&buf);
2712 if (!file_exists(git_path_opts_file()))
2715 * The function git_parse_source(), called from git_config_from_file(),
2716 * may die() in case of a syntactically incorrect file. We do not care
2717 * about this case, though, because we wrote that file ourselves, so we
2718 * are pretty certain that it is syntactically correct.
2720 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2721 return error(_("malformed options sheet: '%s'"),
2722 git_path_opts_file());
2726 static void write_strategy_opts(struct replay_opts *opts)
2729 struct strbuf buf = STRBUF_INIT;
2731 for (i = 0; i < opts->xopts_nr; ++i)
2732 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2734 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2735 strbuf_release(&buf);
2738 int write_basic_state(struct replay_opts *opts, const char *head_name,
2739 struct commit *onto, const struct object_id *orig_head)
2742 write_file(rebase_path_head_name(), "%s\n", head_name);
2744 write_file(rebase_path_onto(), "%s\n",
2745 oid_to_hex(&onto->object.oid));
2747 write_file(rebase_path_orig_head(), "%s\n",
2748 oid_to_hex(orig_head));
2751 write_file(rebase_path_quiet(), "%s", "");
2753 write_file(rebase_path_verbose(), "%s", "");
2755 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2756 if (opts->xopts_nr > 0)
2757 write_strategy_opts(opts);
2759 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2760 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2761 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2762 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2765 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2767 write_file(rebase_path_signoff(), "--signoff\n");
2768 if (opts->drop_redundant_commits)
2769 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2770 if (opts->keep_redundant_commits)
2771 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2772 if (opts->committer_date_is_author_date)
2773 write_file(rebase_path_cdate_is_adate(), "%s", "");
2774 if (opts->ignore_date)
2775 write_file(rebase_path_ignore_date(), "%s", "");
2776 if (opts->reschedule_failed_exec)
2777 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2782 static int walk_revs_populate_todo(struct todo_list *todo_list,
2783 struct replay_opts *opts)
2785 enum todo_command command = opts->action == REPLAY_PICK ?
2786 TODO_PICK : TODO_REVERT;
2787 const char *command_string = todo_command_info[command].str;
2788 const char *encoding;
2789 struct commit *commit;
2791 if (prepare_revs(opts))
2794 encoding = get_log_output_encoding();
2796 while ((commit = get_revision(opts->revs))) {
2797 struct todo_item *item = append_new_todo(todo_list);
2798 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2799 const char *subject;
2802 item->command = command;
2803 item->commit = commit;
2804 item->arg_offset = 0;
2806 item->offset_in_buf = todo_list->buf.len;
2807 subject_len = find_commit_subject(commit_buffer, &subject);
2808 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2809 short_commit_name(commit), subject_len, subject);
2810 unuse_commit_buffer(commit, commit_buffer);
2814 return error(_("empty commit set passed"));
2819 static int create_seq_dir(struct repository *r)
2821 enum replay_action action;
2822 const char *in_progress_error = NULL;
2823 const char *in_progress_advice = NULL;
2824 unsigned int advise_skip =
2825 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
2826 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
2828 if (!sequencer_get_last_command(r, &action)) {
2831 in_progress_error = _("revert is already in progress");
2832 in_progress_advice =
2833 _("try \"git revert (--continue | %s--abort | --quit)\"");
2836 in_progress_error = _("cherry-pick is already in progress");
2837 in_progress_advice =
2838 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2841 BUG("unexpected action in create_seq_dir");
2844 if (in_progress_error) {
2845 error("%s", in_progress_error);
2846 if (advice_sequencer_in_use)
2847 advise(in_progress_advice,
2848 advise_skip ? "--skip | " : "");
2851 if (mkdir(git_path_seq_dir(), 0777) < 0)
2852 return error_errno(_("could not create sequencer directory '%s'"),
2853 git_path_seq_dir());
2858 static int save_head(const char *head)
2860 struct lock_file head_lock = LOCK_INIT;
2861 struct strbuf buf = STRBUF_INIT;
2865 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2867 return error_errno(_("could not lock HEAD"));
2868 strbuf_addf(&buf, "%s\n", head);
2869 written = write_in_full(fd, buf.buf, buf.len);
2870 strbuf_release(&buf);
2872 error_errno(_("could not write to '%s'"), git_path_head_file());
2873 rollback_lock_file(&head_lock);
2876 if (commit_lock_file(&head_lock) < 0)
2877 return error(_("failed to finalize '%s'"), git_path_head_file());
2881 static int rollback_is_safe(void)
2883 struct strbuf sb = STRBUF_INIT;
2884 struct object_id expected_head, actual_head;
2886 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2888 if (get_oid_hex(sb.buf, &expected_head)) {
2889 strbuf_release(&sb);
2890 die(_("could not parse %s"), git_path_abort_safety_file());
2892 strbuf_release(&sb);
2894 else if (errno == ENOENT)
2895 oidclr(&expected_head);
2897 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2899 if (get_oid("HEAD", &actual_head))
2900 oidclr(&actual_head);
2902 return oideq(&actual_head, &expected_head);
2905 static int reset_merge(const struct object_id *oid)
2908 struct strvec argv = STRVEC_INIT;
2910 strvec_pushl(&argv, "reset", "--merge", NULL);
2912 if (!is_null_oid(oid))
2913 strvec_push(&argv, oid_to_hex(oid));
2915 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
2916 strvec_clear(&argv);
2921 static int rollback_single_pick(struct repository *r)
2923 struct object_id head_oid;
2925 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
2926 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
2927 return error(_("no cherry-pick or revert in progress"));
2928 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2929 return error(_("cannot resolve HEAD"));
2930 if (is_null_oid(&head_oid))
2931 return error(_("cannot abort from a branch yet to be born"));
2932 return reset_merge(&head_oid);
2935 static int skip_single_pick(void)
2937 struct object_id head;
2939 if (read_ref_full("HEAD", 0, &head, NULL))
2940 return error(_("cannot resolve HEAD"));
2941 return reset_merge(&head);
2944 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2947 struct object_id oid;
2948 struct strbuf buf = STRBUF_INIT;
2951 f = fopen(git_path_head_file(), "r");
2952 if (!f && errno == ENOENT) {
2954 * There is no multiple-cherry-pick in progress.
2955 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2956 * a single-cherry-pick in progress, abort that.
2958 return rollback_single_pick(r);
2961 return error_errno(_("cannot open '%s'"), git_path_head_file());
2962 if (strbuf_getline_lf(&buf, f)) {
2963 error(_("cannot read '%s': %s"), git_path_head_file(),
2964 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2969 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2970 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2971 git_path_head_file());
2974 if (is_null_oid(&oid)) {
2975 error(_("cannot abort from a branch yet to be born"));
2979 if (!rollback_is_safe()) {
2980 /* Do not error, just do not rollback */
2981 warning(_("You seem to have moved HEAD. "
2982 "Not rewinding, check your HEAD!"));
2984 if (reset_merge(&oid))
2986 strbuf_release(&buf);
2987 return sequencer_remove_state(opts);
2989 strbuf_release(&buf);
2993 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2995 enum replay_action action = -1;
2996 sequencer_get_last_command(r, &action);
2999 * Check whether the subcommand requested to skip the commit is actually
3000 * in progress and that it's safe to skip the commit.
3002 * opts->action tells us which subcommand requested to skip the commit.
3003 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3004 * action is in progress and we can skip the commit.
3006 * Otherwise we check that the last instruction was related to the
3007 * particular subcommand we're trying to execute and barf if that's not
3010 * Finally we check that the rollback is "safe", i.e., has the HEAD
3011 * moved? In this case, it doesn't make sense to "reset the merge" and
3012 * "skip the commit" as the user already handled this by committing. But
3013 * we'd not want to barf here, instead give advice on how to proceed. We
3014 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3015 * it gets removed when the user commits, so if it still exists we're
3016 * sure the user can't have committed before.
3018 switch (opts->action) {
3020 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3021 if (action != REPLAY_REVERT)
3022 return error(_("no revert in progress"));
3023 if (!rollback_is_safe())
3028 if (!refs_ref_exists(get_main_ref_store(r),
3029 "CHERRY_PICK_HEAD")) {
3030 if (action != REPLAY_PICK)
3031 return error(_("no cherry-pick in progress"));
3032 if (!rollback_is_safe())
3037 BUG("unexpected action in sequencer_skip");
3040 if (skip_single_pick())
3041 return error(_("failed to skip the commit"));
3042 if (!is_directory(git_path_seq_dir()))
3045 return sequencer_continue(r, opts);
3048 error(_("there is nothing to skip"));
3050 if (advice_resolve_conflict) {
3051 advise(_("have you committed already?\n"
3052 "try \"git %s --continue\""),
3053 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3058 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3060 struct lock_file todo_lock = LOCK_INIT;
3061 const char *todo_path = get_todo_path(opts);
3062 int next = todo_list->current, offset, fd;
3065 * rebase -i writes "git-rebase-todo" without the currently executing
3066 * command, appending it to "done" instead.
3068 if (is_rebase_i(opts))
3071 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3073 return error_errno(_("could not lock '%s'"), todo_path);
3074 offset = get_item_line_offset(todo_list, next);
3075 if (write_in_full(fd, todo_list->buf.buf + offset,
3076 todo_list->buf.len - offset) < 0)
3077 return error_errno(_("could not write to '%s'"), todo_path);
3078 if (commit_lock_file(&todo_lock) < 0)
3079 return error(_("failed to finalize '%s'"), todo_path);
3081 if (is_rebase_i(opts) && next > 0) {
3082 const char *done = rebase_path_done();
3083 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3088 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3089 get_item_line_length(todo_list, next - 1))
3091 ret = error_errno(_("could not write to '%s'"), done);
3093 ret = error_errno(_("failed to finalize '%s'"), done);
3099 static int save_opts(struct replay_opts *opts)
3101 const char *opts_file = git_path_opts_file();
3104 if (opts->no_commit)
3105 res |= git_config_set_in_file_gently(opts_file,
3106 "options.no-commit", "true");
3108 res |= git_config_set_in_file_gently(opts_file,
3109 "options.edit", "true");
3110 if (opts->allow_empty)
3111 res |= git_config_set_in_file_gently(opts_file,
3112 "options.allow-empty", "true");
3113 if (opts->allow_empty_message)
3114 res |= git_config_set_in_file_gently(opts_file,
3115 "options.allow-empty-message", "true");
3116 if (opts->keep_redundant_commits)
3117 res |= git_config_set_in_file_gently(opts_file,
3118 "options.keep-redundant-commits", "true");
3120 res |= git_config_set_in_file_gently(opts_file,
3121 "options.signoff", "true");
3122 if (opts->record_origin)
3123 res |= git_config_set_in_file_gently(opts_file,
3124 "options.record-origin", "true");
3126 res |= git_config_set_in_file_gently(opts_file,
3127 "options.allow-ff", "true");
3128 if (opts->mainline) {
3129 struct strbuf buf = STRBUF_INIT;
3130 strbuf_addf(&buf, "%d", opts->mainline);
3131 res |= git_config_set_in_file_gently(opts_file,
3132 "options.mainline", buf.buf);
3133 strbuf_release(&buf);
3136 res |= git_config_set_in_file_gently(opts_file,
3137 "options.strategy", opts->strategy);
3139 res |= git_config_set_in_file_gently(opts_file,
3140 "options.gpg-sign", opts->gpg_sign);
3143 for (i = 0; i < opts->xopts_nr; i++)
3144 res |= git_config_set_multivar_in_file_gently(opts_file,
3145 "options.strategy-option",
3146 opts->xopts[i], "^$", 0);
3148 if (opts->allow_rerere_auto)
3149 res |= git_config_set_in_file_gently(opts_file,
3150 "options.allow-rerere-auto",
3151 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3154 if (opts->explicit_cleanup)
3155 res |= git_config_set_in_file_gently(opts_file,
3156 "options.default-msg-cleanup",
3157 describe_cleanup_mode(opts->default_msg_cleanup));
3161 static int make_patch(struct repository *r,
3162 struct commit *commit,
3163 struct replay_opts *opts)
3165 struct strbuf buf = STRBUF_INIT;
3166 struct rev_info log_tree_opt;
3167 const char *subject;
3168 char hex[GIT_MAX_HEXSZ + 1];
3171 oid_to_hex_r(hex, &commit->object.oid);
3172 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3174 res |= write_rebase_head(&commit->object.oid);
3176 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3177 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3178 repo_init_revisions(r, &log_tree_opt, NULL);
3179 log_tree_opt.abbrev = 0;
3180 log_tree_opt.diff = 1;
3181 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3182 log_tree_opt.disable_stdin = 1;
3183 log_tree_opt.no_commit_id = 1;
3184 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3185 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3186 if (!log_tree_opt.diffopt.file)
3187 res |= error_errno(_("could not open '%s'"), buf.buf);
3189 res |= log_tree_commit(&log_tree_opt, commit);
3190 fclose(log_tree_opt.diffopt.file);
3194 strbuf_addf(&buf, "%s/message", get_dir(opts));
3195 if (!file_exists(buf.buf)) {
3196 const char *encoding = get_commit_output_encoding();
3197 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3198 find_commit_subject(commit_buffer, &subject);
3199 res |= write_message(subject, strlen(subject), buf.buf, 1);
3200 unuse_commit_buffer(commit, commit_buffer);
3202 strbuf_release(&buf);
3207 static int intend_to_amend(void)
3209 struct object_id head;
3212 if (get_oid("HEAD", &head))
3213 return error(_("cannot read HEAD"));
3215 p = oid_to_hex(&head);
3216 return write_message(p, strlen(p), rebase_path_amend(), 1);
3219 static int error_with_patch(struct repository *r,
3220 struct commit *commit,
3221 const char *subject, int subject_len,
3222 struct replay_opts *opts,
3223 int exit_code, int to_amend)
3226 if (make_patch(r, commit, opts))
3228 } else if (copy_file(rebase_path_message(),
3229 git_path_merge_msg(r), 0666))
3230 return error(_("unable to copy '%s' to '%s'"),
3231 git_path_merge_msg(r), rebase_path_message());
3234 if (intend_to_amend())
3238 _("You can amend the commit now, with\n"
3240 " git commit --amend %s\n"
3242 "Once you are satisfied with your changes, run\n"
3244 " git rebase --continue\n"),
3245 gpg_sign_opt_quoted(opts));
3246 } else if (exit_code) {
3248 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3249 short_commit_name(commit), subject_len, subject);
3252 * We don't have the hash of the parent so
3253 * just print the line from the todo file.
3255 fprintf_ln(stderr, _("Could not merge %.*s"),
3256 subject_len, subject);
3262 static int error_failed_squash(struct repository *r,
3263 struct commit *commit,
3264 struct replay_opts *opts,
3266 const char *subject)
3268 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3269 return error(_("could not copy '%s' to '%s'"),
3270 rebase_path_squash_msg(), rebase_path_message());
3271 unlink(git_path_merge_msg(r));
3272 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3273 return error(_("could not copy '%s' to '%s'"),
3274 rebase_path_message(),
3275 git_path_merge_msg(r));
3276 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3279 static int do_exec(struct repository *r, const char *command_line)
3281 struct strvec child_env = STRVEC_INIT;
3282 const char *child_argv[] = { NULL, NULL };
3285 fprintf(stderr, _("Executing: %s\n"), command_line);
3286 child_argv[0] = command_line;
3287 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3288 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3289 absolute_path(get_git_work_tree()));
3290 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3293 /* force re-reading of the cache */
3294 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3295 return error(_("could not read index"));
3297 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3300 warning(_("execution failed: %s\n%s"
3301 "You can fix the problem, and then run\n"
3303 " git rebase --continue\n"
3306 dirty ? N_("and made changes to the index and/or the "
3307 "working tree\n") : "");
3309 /* command not found */
3312 warning(_("execution succeeded: %s\nbut "
3313 "left changes to the index and/or the working tree\n"
3314 "Commit or stash your changes, and then run\n"
3316 " git rebase --continue\n"
3317 "\n"), command_line);
3321 strvec_clear(&child_env);
3326 static int safe_append(const char *filename, const char *fmt, ...)
3329 struct lock_file lock = LOCK_INIT;
3330 int fd = hold_lock_file_for_update(&lock, filename,
3331 LOCK_REPORT_ON_ERROR);
3332 struct strbuf buf = STRBUF_INIT;
3337 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3338 error_errno(_("could not read '%s'"), filename);
3339 rollback_lock_file(&lock);
3342 strbuf_complete(&buf, '\n');
3344 strbuf_vaddf(&buf, fmt, ap);
3347 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3348 error_errno(_("could not write to '%s'"), filename);
3349 strbuf_release(&buf);
3350 rollback_lock_file(&lock);
3353 if (commit_lock_file(&lock) < 0) {
3354 strbuf_release(&buf);
3355 rollback_lock_file(&lock);
3356 return error(_("failed to finalize '%s'"), filename);
3359 strbuf_release(&buf);
3363 static int do_label(struct repository *r, const char *name, int len)
3365 struct ref_store *refs = get_main_ref_store(r);
3366 struct ref_transaction *transaction;
3367 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3368 struct strbuf msg = STRBUF_INIT;
3370 struct object_id head_oid;
3372 if (len == 1 && *name == '#')
3373 return error(_("illegal label name: '%.*s'"), len, name);
3375 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3376 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3378 transaction = ref_store_transaction_begin(refs, &err);
3380 error("%s", err.buf);
3382 } else if (get_oid("HEAD", &head_oid)) {
3383 error(_("could not read HEAD"));
3385 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3386 NULL, 0, msg.buf, &err) < 0 ||
3387 ref_transaction_commit(transaction, &err)) {
3388 error("%s", err.buf);
3391 ref_transaction_free(transaction);
3392 strbuf_release(&err);
3393 strbuf_release(&msg);
3396 ret = safe_append(rebase_path_refs_to_delete(),
3397 "%s\n", ref_name.buf);
3398 strbuf_release(&ref_name);
3403 static const char *reflog_message(struct replay_opts *opts,
3404 const char *sub_action, const char *fmt, ...);
3406 static int do_reset(struct repository *r,
3407 const char *name, int len,
3408 struct replay_opts *opts)
3410 struct strbuf ref_name = STRBUF_INIT;
3411 struct object_id oid;
3412 struct lock_file lock = LOCK_INIT;
3413 struct tree_desc desc;
3415 struct unpack_trees_options unpack_tree_opts;
3418 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3421 if (len == 10 && !strncmp("[new root]", name, len)) {
3422 if (!opts->have_squash_onto) {
3424 if (commit_tree("", 0, the_hash_algo->empty_tree,
3425 NULL, &opts->squash_onto,
3427 return error(_("writing fake root commit"));
3428 opts->have_squash_onto = 1;
3429 hex = oid_to_hex(&opts->squash_onto);
3430 if (write_message(hex, strlen(hex),
3431 rebase_path_squash_onto(), 0))
3432 return error(_("writing squash-onto"));
3434 oidcpy(&oid, &opts->squash_onto);
3438 /* Determine the length of the label */
3439 for (i = 0; i < len; i++)
3440 if (isspace(name[i]))
3444 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3445 if (get_oid(ref_name.buf, &oid) &&
3446 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3447 error(_("could not read '%s'"), ref_name.buf);
3448 rollback_lock_file(&lock);
3449 strbuf_release(&ref_name);
3454 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3455 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3456 unpack_tree_opts.head_idx = 1;
3457 unpack_tree_opts.src_index = r->index;
3458 unpack_tree_opts.dst_index = r->index;
3459 unpack_tree_opts.fn = oneway_merge;
3460 unpack_tree_opts.merge = 1;
3461 unpack_tree_opts.update = 1;
3462 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3464 if (repo_read_index_unmerged(r)) {
3465 rollback_lock_file(&lock);
3466 strbuf_release(&ref_name);
3467 return error_resolve_conflict(_(action_name(opts)));
3470 if (!fill_tree_descriptor(r, &desc, &oid)) {
3471 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3472 rollback_lock_file(&lock);
3473 free((void *)desc.buffer);
3474 strbuf_release(&ref_name);
3478 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3479 rollback_lock_file(&lock);
3480 free((void *)desc.buffer);
3481 strbuf_release(&ref_name);
3485 tree = parse_tree_indirect(&oid);
3486 prime_cache_tree(r, r->index, tree);
3488 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3489 ret = error(_("could not write index"));
3490 free((void *)desc.buffer);
3493 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3494 len, name), "HEAD", &oid,
3495 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3497 strbuf_release(&ref_name);
3501 static struct commit *lookup_label(const char *label, int len,
3504 struct commit *commit;
3507 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3508 commit = lookup_commit_reference_by_name(buf->buf);
3510 /* fall back to non-rewritten ref or commit */
3511 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3512 commit = lookup_commit_reference_by_name(buf->buf);
3516 error(_("could not resolve '%s'"), buf->buf);
3521 static int do_merge(struct repository *r,
3522 struct commit *commit,
3523 const char *arg, int arg_len,
3524 int flags, struct replay_opts *opts)
3526 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3527 EDIT_MSG | VERIFY_MSG : 0;
3528 struct strbuf ref_name = STRBUF_INIT;
3529 struct commit *head_commit, *merge_commit, *i;
3530 struct commit_list *bases, *j, *reversed = NULL;
3531 struct commit_list *to_merge = NULL, **tail = &to_merge;
3532 const char *strategy = !opts->xopts_nr &&
3534 !strcmp(opts->strategy, "recursive") ||
3535 !strcmp(opts->strategy, "ort")) ?
3536 NULL : opts->strategy;
3537 struct merge_options o;
3538 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3539 static struct lock_file lock;
3542 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3547 head_commit = lookup_commit_reference_by_name("HEAD");
3549 ret = error(_("cannot merge without a current revision"));
3554 * For octopus merges, the arg starts with the list of revisions to be
3555 * merged. The list is optionally followed by '#' and the oneline.
3557 merge_arg_len = oneline_offset = arg_len;
3558 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3561 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3562 p += 1 + strspn(p + 1, " \t\n");
3563 oneline_offset = p - arg;
3566 k = strcspn(p, " \t\n");
3569 merge_commit = lookup_label(p, k, &ref_name);
3570 if (!merge_commit) {
3571 ret = error(_("unable to parse '%.*s'"), k, p);
3574 tail = &commit_list_insert(merge_commit, tail)->next;
3576 merge_arg_len = p - arg;
3580 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3584 if (opts->have_squash_onto &&
3585 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3587 * When the user tells us to "merge" something into a
3588 * "[new root]", let's simply fast-forward to the merge head.
3590 rollback_lock_file(&lock);
3592 ret = error(_("octopus merge cannot be executed on "
3593 "top of a [new root]"));
3595 ret = fast_forward_to(r, &to_merge->item->object.oid,
3596 &head_commit->object.oid, 0,
3602 const char *encoding = get_commit_output_encoding();
3603 const char *message = logmsg_reencode(commit, NULL, encoding);
3608 ret = error(_("could not get commit message of '%s'"),
3609 oid_to_hex(&commit->object.oid));
3612 write_author_script(message);
3613 find_commit_subject(message, &body);
3615 ret = write_message(body, len, git_path_merge_msg(r), 0);
3616 unuse_commit_buffer(commit, message);
3618 error_errno(_("could not write '%s'"),
3619 git_path_merge_msg(r));
3623 struct strbuf buf = STRBUF_INIT;
3626 strbuf_addf(&buf, "author %s", git_author_info(0));
3627 write_author_script(buf.buf);
3630 if (oneline_offset < arg_len) {
3631 p = arg + oneline_offset;
3632 len = arg_len - oneline_offset;
3634 strbuf_addf(&buf, "Merge %s '%.*s'",
3635 to_merge->next ? "branches" : "branch",
3636 merge_arg_len, arg);
3641 ret = write_message(p, len, git_path_merge_msg(r), 0);
3642 strbuf_release(&buf);
3644 error_errno(_("could not write '%s'"),
3645 git_path_merge_msg(r));
3651 * If HEAD is not identical to the first parent of the original merge
3652 * commit, we cannot fast-forward.
3654 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3655 oideq(&commit->parents->item->object.oid,
3656 &head_commit->object.oid);
3659 * If any merge head is different from the original one, we cannot
3662 if (can_fast_forward) {
3663 struct commit_list *p = commit->parents->next;
3665 for (j = to_merge; j && p; j = j->next, p = p->next)
3666 if (!oideq(&j->item->object.oid,
3667 &p->item->object.oid)) {
3668 can_fast_forward = 0;
3672 * If the number of merge heads differs from the original merge
3673 * commit, we cannot fast-forward.
3676 can_fast_forward = 0;
3679 if (can_fast_forward) {
3680 rollback_lock_file(&lock);
3681 ret = fast_forward_to(r, &commit->object.oid,
3682 &head_commit->object.oid, 0, opts);
3683 if (flags & TODO_EDIT_MERGE_MSG) {
3684 run_commit_flags |= AMEND_MSG;
3685 goto fast_forward_edit;
3690 if (strategy || to_merge->next) {
3692 struct child_process cmd = CHILD_PROCESS_INIT;
3694 if (read_env_script(&cmd.env_array)) {
3695 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3697 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3701 if (opts->committer_date_is_author_date)
3702 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3705 author_date_from_env_array(&cmd.env_array));
3706 if (opts->ignore_date)
3707 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3710 strvec_push(&cmd.args, "merge");
3711 strvec_push(&cmd.args, "-s");
3713 strvec_push(&cmd.args, "octopus");
3715 strvec_push(&cmd.args, strategy);
3716 for (k = 0; k < opts->xopts_nr; k++)
3717 strvec_pushf(&cmd.args,
3718 "-X%s", opts->xopts[k]);
3720 strvec_push(&cmd.args, "--no-edit");
3721 strvec_push(&cmd.args, "--no-ff");
3722 strvec_push(&cmd.args, "--no-log");
3723 strvec_push(&cmd.args, "--no-stat");
3724 strvec_push(&cmd.args, "-F");
3725 strvec_push(&cmd.args, git_path_merge_msg(r));
3727 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3729 strvec_push(&cmd.args, "--no-gpg-sign");
3731 /* Add the tips to be merged */
3732 for (j = to_merge; j; j = j->next)
3733 strvec_push(&cmd.args,
3734 oid_to_hex(&j->item->object.oid));
3736 strbuf_release(&ref_name);
3737 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3739 rollback_lock_file(&lock);
3741 ret = run_command(&cmd);
3743 /* force re-reading of the cache */
3744 if (!ret && (discard_index(r->index) < 0 ||
3745 repo_read_index(r) < 0))
3746 ret = error(_("could not read index"));
3750 merge_commit = to_merge->item;
3751 bases = get_merge_bases(head_commit, merge_commit);
3752 if (bases && oideq(&merge_commit->object.oid,
3753 &bases->item->object.oid)) {
3755 /* skip merging an ancestor of HEAD */
3759 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3760 git_path_merge_head(r), 0);
3761 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3763 for (j = bases; j; j = j->next)
3764 commit_list_insert(j->item, &reversed);
3765 free_commit_list(bases);
3768 init_merge_options(&o, r);
3770 o.branch2 = ref_name.buf;
3771 o.buffer_output = 2;
3773 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3775 * TODO: Should use merge_incore_recursive() and
3776 * merge_switch_to_result(), skipping the call to
3777 * merge_switch_to_result() when we don't actually need to
3778 * update the index and working copy immediately.
3780 ret = merge_ort_recursive(&o,
3781 head_commit, merge_commit, reversed,
3784 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3788 fputs(o.obuf.buf, stdout);
3789 strbuf_release(&o.obuf);
3791 error(_("could not even attempt to merge '%.*s'"),
3792 merge_arg_len, arg);
3796 * The return value of merge_recursive() is 1 on clean, and 0 on
3799 * Let's reverse that, so that do_merge() returns 0 upon success and
3800 * 1 upon failed merge (keeping the return value -1 for the cases where
3801 * we will want to reschedule the `merge` command).
3805 if (r->index->cache_changed &&
3806 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3807 ret = error(_("merge: Unable to write new index file"));
3811 rollback_lock_file(&lock);
3813 repo_rerere(r, opts->allow_rerere_auto);
3816 * In case of problems, we now want to return a positive
3817 * value (a negative one would indicate that the `merge`
3818 * command needs to be rescheduled).
3821 ret = !!run_git_commit(git_path_merge_msg(r), opts,
3825 strbuf_release(&ref_name);
3826 rollback_lock_file(&lock);
3827 free_commit_list(to_merge);
3831 static int is_final_fixup(struct todo_list *todo_list)
3833 int i = todo_list->current;
3835 if (!is_fixup(todo_list->items[i].command))
3838 while (++i < todo_list->nr)
3839 if (is_fixup(todo_list->items[i].command))
3841 else if (!is_noop(todo_list->items[i].command))
3846 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3850 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3851 if (!is_noop(todo_list->items[i].command))
3852 return todo_list->items[i].command;
3857 void create_autostash(struct repository *r, const char *path,
3858 const char *default_reflog_action)
3860 struct strbuf buf = STRBUF_INIT;
3861 struct lock_file lock_file = LOCK_INIT;
3864 fd = repo_hold_locked_index(r, &lock_file, 0);
3865 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
3867 repo_update_index_if_able(r, &lock_file);
3868 rollback_lock_file(&lock_file);
3870 if (has_unstaged_changes(r, 1) ||
3871 has_uncommitted_changes(r, 1)) {
3872 struct child_process stash = CHILD_PROCESS_INIT;
3873 struct object_id oid;
3875 strvec_pushl(&stash.args,
3876 "stash", "create", "autostash", NULL);
3880 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
3881 die(_("Cannot autostash"));
3882 strbuf_trim_trailing_newline(&buf);
3883 if (get_oid(buf.buf, &oid))
3884 die(_("Unexpected stash response: '%s'"),
3887 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
3889 if (safe_create_leading_directories_const(path))
3890 die(_("Could not create directory for '%s'"),
3892 write_file(path, "%s", oid_to_hex(&oid));
3893 printf(_("Created autostash: %s\n"), buf.buf);
3894 if (reset_head(r, NULL, "reset --hard",
3895 NULL, RESET_HEAD_HARD, NULL, NULL,
3896 default_reflog_action) < 0)
3897 die(_("could not reset --hard"));
3899 if (discard_index(r->index) < 0 ||
3900 repo_read_index(r) < 0)
3901 die(_("could not read index"));
3903 strbuf_release(&buf);
3906 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
3908 struct child_process child = CHILD_PROCESS_INIT;
3911 if (attempt_apply) {
3913 child.no_stdout = 1;
3914 child.no_stderr = 1;
3915 strvec_push(&child.args, "stash");
3916 strvec_push(&child.args, "apply");
3917 strvec_push(&child.args, stash_oid);
3918 ret = run_command(&child);
3921 if (attempt_apply && !ret)
3922 fprintf(stderr, _("Applied autostash.\n"));
3924 struct child_process store = CHILD_PROCESS_INIT;
3927 strvec_push(&store.args, "stash");
3928 strvec_push(&store.args, "store");
3929 strvec_push(&store.args, "-m");
3930 strvec_push(&store.args, "autostash");
3931 strvec_push(&store.args, "-q");
3932 strvec_push(&store.args, stash_oid);
3933 if (run_command(&store))
3934 ret = error(_("cannot store %s"), stash_oid);
3938 "Your changes are safe in the stash.\n"
3939 "You can run \"git stash pop\" or"
3940 " \"git stash drop\" at any time.\n"),
3942 _("Applying autostash resulted in conflicts.") :
3943 _("Autostash exists; creating a new stash entry."));
3949 static int apply_save_autostash(const char *path, int attempt_apply)
3951 struct strbuf stash_oid = STRBUF_INIT;
3954 if (!read_oneliner(&stash_oid, path,
3955 READ_ONELINER_SKIP_IF_EMPTY)) {
3956 strbuf_release(&stash_oid);
3959 strbuf_trim(&stash_oid);
3961 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
3964 strbuf_release(&stash_oid);
3968 int save_autostash(const char *path)
3970 return apply_save_autostash(path, 0);
3973 int apply_autostash(const char *path)
3975 return apply_save_autostash(path, 1);
3978 int apply_autostash_oid(const char *stash_oid)
3980 return apply_save_autostash_oid(stash_oid, 1);
3983 static const char *reflog_message(struct replay_opts *opts,
3984 const char *sub_action, const char *fmt, ...)
3987 static struct strbuf buf = STRBUF_INIT;
3988 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3992 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3994 strbuf_addf(&buf, " (%s)", sub_action);
3996 strbuf_addstr(&buf, ": ");
3997 strbuf_vaddf(&buf, fmt, ap);
4004 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4005 const char *commit, const char *action)
4007 struct child_process cmd = CHILD_PROCESS_INIT;
4012 strvec_push(&cmd.args, "checkout");
4013 strvec_push(&cmd.args, commit);
4014 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4017 ret = run_command(&cmd);
4019 ret = run_command_silent_on_success(&cmd);
4022 discard_index(r->index);
4027 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4028 const char *onto_name, const struct object_id *onto,
4029 const struct object_id *orig_head)
4031 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4033 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4034 apply_autostash(rebase_path_autostash());
4035 sequencer_remove_state(opts);
4036 return error(_("could not detach HEAD"));
4039 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4042 static int stopped_at_head(struct repository *r)
4044 struct object_id head;
4045 struct commit *commit;
4046 struct commit_message message;
4048 if (get_oid("HEAD", &head) ||
4049 !(commit = lookup_commit(r, &head)) ||
4050 parse_commit(commit) || get_message(commit, &message))
4051 fprintf(stderr, _("Stopped at HEAD\n"));
4053 fprintf(stderr, _("Stopped at %s\n"), message.label);
4054 free_message(commit, &message);
4060 static const char rescheduled_advice[] =
4061 N_("Could not execute the todo command\n"
4065 "It has been rescheduled; To edit the command before continuing, please\n"
4066 "edit the todo list first:\n"
4068 " git rebase --edit-todo\n"
4069 " git rebase --continue\n");
4071 static int pick_commits(struct repository *r,
4072 struct todo_list *todo_list,
4073 struct replay_opts *opts)
4075 int res = 0, reschedule = 0;
4076 char *prev_reflog_action;
4078 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4079 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4080 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4082 assert(!(opts->signoff || opts->no_commit ||
4083 opts->record_origin || opts->edit ||
4084 opts->committer_date_is_author_date ||
4085 opts->ignore_date));
4086 if (read_and_refresh_cache(r, opts))
4089 while (todo_list->current < todo_list->nr) {
4090 struct todo_item *item = todo_list->items + todo_list->current;
4091 const char *arg = todo_item_get_arg(todo_list, item);
4094 if (save_todo(todo_list, opts))
4096 if (is_rebase_i(opts)) {
4097 if (item->command != TODO_COMMENT) {
4098 FILE *f = fopen(rebase_path_msgnum(), "w");
4100 todo_list->done_nr++;
4103 fprintf(f, "%d\n", todo_list->done_nr);
4107 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4109 todo_list->total_nr,
4110 opts->verbose ? "\n" : "\r");
4112 unlink(rebase_path_message());
4113 unlink(rebase_path_author_script());
4114 unlink(rebase_path_stopped_sha());
4115 unlink(rebase_path_amend());
4116 unlink(git_path_merge_head(r));
4117 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4119 if (item->command == TODO_BREAK) {
4122 return stopped_at_head(r);
4125 if (item->command <= TODO_SQUASH) {
4126 if (is_rebase_i(opts))
4127 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4128 command_to_string(item->command), NULL),
4130 res = do_pick_commit(r, item->command, item->commit,
4131 opts, is_final_fixup(todo_list),
4133 if (is_rebase_i(opts))
4134 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4135 if (is_rebase_i(opts) && res < 0) {
4137 advise(_(rescheduled_advice),
4138 get_item_line_length(todo_list,
4139 todo_list->current),
4140 get_item_line(todo_list,
4141 todo_list->current));
4142 todo_list->current--;
4143 if (save_todo(todo_list, opts))
4146 if (item->command == TODO_EDIT) {
4147 struct commit *commit = item->commit;
4152 _("Stopped at %s... %.*s\n"),
4153 short_commit_name(commit),
4154 item->arg_len, arg);
4156 return error_with_patch(r, commit,
4157 arg, item->arg_len, opts, res, !res);
4159 if (is_rebase_i(opts) && !res)
4160 record_in_rewritten(&item->commit->object.oid,
4161 peek_command(todo_list, 1));
4162 if (res && is_fixup(item->command)) {
4165 return error_failed_squash(r, item->commit, opts,
4166 item->arg_len, arg);
4167 } else if (res && is_rebase_i(opts) && item->commit) {
4169 struct object_id oid;
4172 * If we are rewording and have either
4173 * fast-forwarded already, or are about to
4174 * create a new root commit, we want to amend,
4175 * otherwise we do not.
4177 if (item->command == TODO_REWORD &&
4178 !get_oid("HEAD", &oid) &&
4179 (oideq(&item->commit->object.oid, &oid) ||
4180 (opts->have_squash_onto &&
4181 oideq(&opts->squash_onto, &oid))))
4184 return res | error_with_patch(r, item->commit,
4185 arg, item->arg_len, opts,
4188 } else if (item->command == TODO_EXEC) {
4189 char *end_of_arg = (char *)(arg + item->arg_len);
4190 int saved = *end_of_arg;
4195 res = do_exec(r, arg);
4196 *end_of_arg = saved;
4199 if (opts->reschedule_failed_exec)
4203 } else if (item->command == TODO_LABEL) {
4204 if ((res = do_label(r, arg, item->arg_len)))
4206 } else if (item->command == TODO_RESET) {
4207 if ((res = do_reset(r, arg, item->arg_len, opts)))
4209 } else if (item->command == TODO_MERGE) {
4210 if ((res = do_merge(r, item->commit,
4212 item->flags, opts)) < 0)
4214 else if (item->commit)
4215 record_in_rewritten(&item->commit->object.oid,
4216 peek_command(todo_list, 1));
4218 /* failed with merge conflicts */
4219 return error_with_patch(r, item->commit,
4222 } else if (!is_noop(item->command))
4223 return error(_("unknown command %d"), item->command);
4226 advise(_(rescheduled_advice),
4227 get_item_line_length(todo_list,
4228 todo_list->current),
4229 get_item_line(todo_list, todo_list->current));
4230 todo_list->current--;
4231 if (save_todo(todo_list, opts))
4234 return error_with_patch(r,
4238 } else if (is_rebase_i(opts) && check_todo && !res) {
4241 if (stat(get_todo_path(opts), &st)) {
4242 res = error_errno(_("could not stat '%s'"),
4243 get_todo_path(opts));
4244 } else if (match_stat_data(&todo_list->stat, &st)) {
4245 /* Reread the todo file if it has changed. */
4246 todo_list_release(todo_list);
4247 if (read_populate_todo(r, todo_list, opts))
4248 res = -1; /* message was printed */
4249 /* `current` will be incremented below */
4250 todo_list->current = -1;
4254 todo_list->current++;
4259 if (is_rebase_i(opts)) {
4260 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4263 /* Stopped in the middle, as planned? */
4264 if (todo_list->current < todo_list->nr)
4267 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4268 starts_with(head_ref.buf, "refs/")) {
4270 struct object_id head, orig;
4273 if (get_oid("HEAD", &head)) {
4274 res = error(_("cannot read HEAD"));
4276 strbuf_release(&head_ref);
4277 strbuf_release(&buf);
4280 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4281 get_oid_hex(buf.buf, &orig)) {
4282 res = error(_("could not read orig-head"));
4283 goto cleanup_head_ref;
4286 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4287 res = error(_("could not read 'onto'"));
4288 goto cleanup_head_ref;
4290 msg = reflog_message(opts, "finish", "%s onto %s",
4291 head_ref.buf, buf.buf);
4292 if (update_ref(msg, head_ref.buf, &head, &orig,
4293 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4294 res = error(_("could not update %s"),
4296 goto cleanup_head_ref;
4298 msg = reflog_message(opts, "finish", "returning to %s",
4300 if (create_symref("HEAD", head_ref.buf, msg)) {
4301 res = error(_("could not update HEAD to %s"),
4303 goto cleanup_head_ref;
4308 if (opts->verbose) {
4309 struct rev_info log_tree_opt;
4310 struct object_id orig, head;
4312 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4313 repo_init_revisions(r, &log_tree_opt, NULL);
4314 log_tree_opt.diff = 1;
4315 log_tree_opt.diffopt.output_format =
4316 DIFF_FORMAT_DIFFSTAT;
4317 log_tree_opt.disable_stdin = 1;
4319 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4320 !get_oid(buf.buf, &orig) &&
4321 !get_oid("HEAD", &head)) {
4322 diff_tree_oid(&orig, &head, "",
4323 &log_tree_opt.diffopt);
4324 log_tree_diff_flush(&log_tree_opt);
4327 flush_rewritten_pending();
4328 if (!stat(rebase_path_rewritten_list(), &st) &&
4330 struct child_process child = CHILD_PROCESS_INIT;
4331 const char *post_rewrite_hook =
4332 find_hook("post-rewrite");
4334 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4336 strvec_push(&child.args, "notes");
4337 strvec_push(&child.args, "copy");
4338 strvec_push(&child.args, "--for-rewrite=rebase");
4339 /* we don't care if this copying failed */
4340 run_command(&child);
4342 if (post_rewrite_hook) {
4343 struct child_process hook = CHILD_PROCESS_INIT;
4345 hook.in = open(rebase_path_rewritten_list(),
4347 hook.stdout_to_stderr = 1;
4348 hook.trace2_hook_name = "post-rewrite";
4349 strvec_push(&hook.args, post_rewrite_hook);
4350 strvec_push(&hook.args, "rebase");
4351 /* we don't care if this hook failed */
4355 apply_autostash(rebase_path_autostash());
4361 _("Successfully rebased and updated %s.\n"),
4365 strbuf_release(&buf);
4366 strbuf_release(&head_ref);
4370 * Sequence of picks finished successfully; cleanup by
4371 * removing the .git/sequencer directory
4373 return sequencer_remove_state(opts);
4376 static int continue_single_pick(struct repository *r)
4378 const char *argv[] = { "commit", NULL };
4380 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4381 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4382 return error(_("no cherry-pick or revert in progress"));
4383 return run_command_v_opt(argv, RUN_GIT_CMD);
4386 static int commit_staged_changes(struct repository *r,
4387 struct replay_opts *opts,
4388 struct todo_list *todo_list)
4390 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4391 unsigned int final_fixup = 0, is_clean;
4393 if (has_unstaged_changes(r, 1))
4394 return error(_("cannot rebase: You have unstaged changes."));
4396 is_clean = !has_uncommitted_changes(r, 0);
4398 if (file_exists(rebase_path_amend())) {
4399 struct strbuf rev = STRBUF_INIT;
4400 struct object_id head, to_amend;
4402 if (get_oid("HEAD", &head))
4403 return error(_("cannot amend non-existing commit"));
4404 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4405 return error(_("invalid file: '%s'"), rebase_path_amend());
4406 if (get_oid_hex(rev.buf, &to_amend))
4407 return error(_("invalid contents: '%s'"),
4408 rebase_path_amend());
4409 if (!is_clean && !oideq(&head, &to_amend))
4410 return error(_("\nYou have uncommitted changes in your "
4411 "working tree. Please, commit them\n"
4412 "first and then run 'git rebase "
4413 "--continue' again."));
4415 * When skipping a failed fixup/squash, we need to edit the
4416 * commit message, the current fixup list and count, and if it
4417 * was the last fixup/squash in the chain, we need to clean up
4418 * the commit message and if there was a squash, let the user
4421 if (!is_clean || !opts->current_fixup_count)
4422 ; /* this is not the final fixup */
4423 else if (!oideq(&head, &to_amend) ||
4424 !file_exists(rebase_path_stopped_sha())) {
4425 /* was a final fixup or squash done manually? */
4426 if (!is_fixup(peek_command(todo_list, 0))) {
4427 unlink(rebase_path_fixup_msg());
4428 unlink(rebase_path_squash_msg());
4429 unlink(rebase_path_current_fixups());
4430 strbuf_reset(&opts->current_fixups);
4431 opts->current_fixup_count = 0;
4434 /* we are in a fixup/squash chain */
4435 const char *p = opts->current_fixups.buf;
4436 int len = opts->current_fixups.len;
4438 opts->current_fixup_count--;
4440 BUG("Incorrect current_fixups:\n%s", p);
4441 while (len && p[len - 1] != '\n')
4443 strbuf_setlen(&opts->current_fixups, len);
4444 if (write_message(p, len, rebase_path_current_fixups(),
4446 return error(_("could not write file: '%s'"),
4447 rebase_path_current_fixups());
4450 * If a fixup/squash in a fixup/squash chain failed, the
4451 * commit message is already correct, no need to commit
4454 * Only if it is the final command in the fixup/squash
4455 * chain, and only if the chain is longer than a single
4456 * fixup/squash command (which was just skipped), do we
4457 * actually need to re-commit with a cleaned up commit
4460 if (opts->current_fixup_count > 0 &&
4461 !is_fixup(peek_command(todo_list, 0))) {
4464 * If there was not a single "squash" in the
4465 * chain, we only need to clean up the commit
4466 * message, no need to bother the user with
4467 * opening the commit message in the editor.
4469 if (!starts_with(p, "squash ") &&
4470 !strstr(p, "\nsquash "))
4471 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4472 } else if (is_fixup(peek_command(todo_list, 0))) {
4474 * We need to update the squash message to skip
4475 * the latest commit message.
4477 struct commit *commit;
4478 const char *path = rebase_path_squash_msg();
4479 const char *encoding = get_commit_output_encoding();
4481 if (parse_head(r, &commit) ||
4482 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4483 write_message(p, strlen(p), path, 0)) {
4484 unuse_commit_buffer(commit, p);
4485 return error(_("could not write file: "
4488 unuse_commit_buffer(commit, p);
4492 strbuf_release(&rev);
4497 if (refs_ref_exists(get_main_ref_store(r),
4498 "CHERRY_PICK_HEAD") &&
4499 refs_delete_ref(get_main_ref_store(r), "",
4500 "CHERRY_PICK_HEAD", NULL, 0))
4501 return error(_("could not remove CHERRY_PICK_HEAD"));
4506 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4508 return error(_("could not commit staged changes."));
4509 unlink(rebase_path_amend());
4510 unlink(git_path_merge_head(r));
4512 unlink(rebase_path_fixup_msg());
4513 unlink(rebase_path_squash_msg());
4515 if (opts->current_fixup_count > 0) {
4517 * Whether final fixup or not, we just cleaned up the commit
4520 unlink(rebase_path_current_fixups());
4521 strbuf_reset(&opts->current_fixups);
4522 opts->current_fixup_count = 0;
4527 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4529 struct todo_list todo_list = TODO_LIST_INIT;
4532 if (read_and_refresh_cache(r, opts))
4535 if (read_populate_opts(opts))
4537 if (is_rebase_i(opts)) {
4538 if ((res = read_populate_todo(r, &todo_list, opts)))
4539 goto release_todo_list;
4541 if (file_exists(rebase_path_dropped())) {
4542 if ((res = todo_list_check_against_backup(r, &todo_list)))
4543 goto release_todo_list;
4545 unlink(rebase_path_dropped());
4548 if (commit_staged_changes(r, opts, &todo_list)) {
4550 goto release_todo_list;
4552 } else if (!file_exists(get_todo_path(opts)))
4553 return continue_single_pick(r);
4554 else if ((res = read_populate_todo(r, &todo_list, opts)))
4555 goto release_todo_list;
4557 if (!is_rebase_i(opts)) {
4558 /* Verify that the conflict has been resolved */
4559 if (refs_ref_exists(get_main_ref_store(r),
4560 "CHERRY_PICK_HEAD") ||
4561 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4562 res = continue_single_pick(r);
4564 goto release_todo_list;
4566 if (index_differs_from(r, "HEAD", NULL, 0)) {
4567 res = error_dirty_index(r, opts);
4568 goto release_todo_list;
4570 todo_list.current++;
4571 } else if (file_exists(rebase_path_stopped_sha())) {
4572 struct strbuf buf = STRBUF_INIT;
4573 struct object_id oid;
4575 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4576 READ_ONELINER_SKIP_IF_EMPTY) &&
4577 !get_oid_hex(buf.buf, &oid))
4578 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4579 strbuf_release(&buf);
4582 res = pick_commits(r, &todo_list, opts);
4584 todo_list_release(&todo_list);
4588 static int single_pick(struct repository *r,
4589 struct commit *cmit,
4590 struct replay_opts *opts)
4594 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4595 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4596 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4600 int sequencer_pick_revisions(struct repository *r,
4601 struct replay_opts *opts)
4603 struct todo_list todo_list = TODO_LIST_INIT;
4604 struct object_id oid;
4608 if (read_and_refresh_cache(r, opts))
4611 for (i = 0; i < opts->revs->pending.nr; i++) {
4612 struct object_id oid;
4613 const char *name = opts->revs->pending.objects[i].name;
4615 /* This happens when using --stdin. */
4619 if (!get_oid(name, &oid)) {
4620 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4621 enum object_type type = oid_object_info(r,
4624 return error(_("%s: can't cherry-pick a %s"),
4625 name, type_name(type));
4628 return error(_("%s: bad revision"), name);
4632 * If we were called as "git cherry-pick <commit>", just
4633 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4634 * REVERT_HEAD, and don't touch the sequencer state.
4635 * This means it is possible to cherry-pick in the middle
4636 * of a cherry-pick sequence.
4638 if (opts->revs->cmdline.nr == 1 &&
4639 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4640 opts->revs->no_walk &&
4641 !opts->revs->cmdline.rev->flags) {
4642 struct commit *cmit;
4643 if (prepare_revision_walk(opts->revs))
4644 return error(_("revision walk setup failed"));
4645 cmit = get_revision(opts->revs);
4647 return error(_("empty commit set passed"));
4648 if (get_revision(opts->revs))
4649 BUG("unexpected extra commit from walk");
4650 return single_pick(r, cmit, opts);
4654 * Start a new cherry-pick/ revert sequence; but
4655 * first, make sure that an existing one isn't in
4659 if (walk_revs_populate_todo(&todo_list, opts) ||
4660 create_seq_dir(r) < 0)
4662 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4663 return error(_("can't revert as initial commit"));
4664 if (save_head(oid_to_hex(&oid)))
4666 if (save_opts(opts))
4668 update_abort_safety_file();
4669 res = pick_commits(r, &todo_list, opts);
4670 todo_list_release(&todo_list);
4674 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4676 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4677 struct strbuf sob = STRBUF_INIT;
4680 strbuf_addstr(&sob, sign_off_header);
4681 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4682 strbuf_addch(&sob, '\n');
4685 strbuf_complete_line(msgbuf);
4688 * If the whole message buffer is equal to the sob, pretend that we
4689 * found a conforming footer with a matching sob
4691 if (msgbuf->len - ignore_footer == sob.len &&
4692 !strncmp(msgbuf->buf, sob.buf, sob.len))
4695 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4698 const char *append_newlines = NULL;
4699 size_t len = msgbuf->len - ignore_footer;
4703 * The buffer is completely empty. Leave foom for
4704 * the title and body to be filled in by the user.
4706 append_newlines = "\n\n";
4707 } else if (len == 1) {
4709 * Buffer contains a single newline. Add another
4710 * so that we leave room for the title and body.
4712 append_newlines = "\n";
4713 } else if (msgbuf->buf[len - 2] != '\n') {
4715 * Buffer ends with a single newline. Add another
4716 * so that there is an empty line between the message
4719 append_newlines = "\n";
4720 } /* else, the buffer already ends with two newlines. */
4722 if (append_newlines)
4723 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4724 append_newlines, strlen(append_newlines));
4727 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4728 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4731 strbuf_release(&sob);
4734 struct labels_entry {
4735 struct hashmap_entry entry;
4736 char label[FLEX_ARRAY];
4739 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4740 const struct hashmap_entry *entry_or_key, const void *key)
4742 const struct labels_entry *a, *b;
4744 a = container_of(eptr, const struct labels_entry, entry);
4745 b = container_of(entry_or_key, const struct labels_entry, entry);
4747 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4750 struct string_entry {
4751 struct oidmap_entry entry;
4752 char string[FLEX_ARRAY];
4755 struct label_state {
4756 struct oidmap commit2label;
4757 struct hashmap labels;
4761 static const char *label_oid(struct object_id *oid, const char *label,
4762 struct label_state *state)
4764 struct labels_entry *labels_entry;
4765 struct string_entry *string_entry;
4766 struct object_id dummy;
4769 string_entry = oidmap_get(&state->commit2label, oid);
4771 return string_entry->string;
4774 * For "uninteresting" commits, i.e. commits that are not to be
4775 * rebased, and which can therefore not be labeled, we use a unique
4776 * abbreviation of the commit name. This is slightly more complicated
4777 * than calling find_unique_abbrev() because we also need to make
4778 * sure that the abbreviation does not conflict with any other
4781 * We disallow "interesting" commits to be labeled by a string that
4782 * is a valid full-length hash, to ensure that we always can find an
4783 * abbreviation for any uninteresting commit's names that does not
4784 * clash with any other label.
4786 strbuf_reset(&state->buf);
4790 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4791 label = p = state->buf.buf;
4793 find_unique_abbrev_r(p, oid, default_abbrev);
4796 * We may need to extend the abbreviated hash so that there is
4797 * no conflicting label.
4799 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4800 size_t i = strlen(p) + 1;
4802 oid_to_hex_r(p, oid);
4803 for (; i < the_hash_algo->hexsz; i++) {
4806 if (!hashmap_get_from_hash(&state->labels,
4813 struct strbuf *buf = &state->buf;
4816 * Sanitize labels by replacing non-alpha-numeric characters
4817 * (including white-space ones) by dashes, as they might be
4818 * illegal in file names (and hence in ref names).
4820 * Note that we retain non-ASCII UTF-8 characters (identified
4821 * via the most significant bit). They should be all acceptable
4822 * in file names. We do not validate the UTF-8 here, that's not
4823 * the job of this function.
4825 for (; *label; label++)
4826 if ((*label & 0x80) || isalnum(*label))
4827 strbuf_addch(buf, *label);
4828 /* avoid leading dash and double-dashes */
4829 else if (buf->len && buf->buf[buf->len - 1] != '-')
4830 strbuf_addch(buf, '-');
4832 strbuf_addstr(buf, "rev-");
4833 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4837 if ((buf->len == the_hash_algo->hexsz &&
4838 !get_oid_hex(label, &dummy)) ||
4839 (buf->len == 1 && *label == '#') ||
4840 hashmap_get_from_hash(&state->labels,
4841 strihash(label), label)) {
4843 * If the label already exists, or if the label is a
4844 * valid full OID, or the label is a '#' (which we use
4845 * as a separator between merge heads and oneline), we
4846 * append a dash and a number to make it unique.
4848 size_t len = buf->len;
4850 for (i = 2; ; i++) {
4851 strbuf_setlen(buf, len);
4852 strbuf_addf(buf, "-%d", i);
4853 if (!hashmap_get_from_hash(&state->labels,
4863 FLEX_ALLOC_STR(labels_entry, label, label);
4864 hashmap_entry_init(&labels_entry->entry, strihash(label));
4865 hashmap_add(&state->labels, &labels_entry->entry);
4867 FLEX_ALLOC_STR(string_entry, string, label);
4868 oidcpy(&string_entry->entry.oid, oid);
4869 oidmap_put(&state->commit2label, string_entry);
4871 return string_entry->string;
4874 static int make_script_with_merges(struct pretty_print_context *pp,
4875 struct rev_info *revs, struct strbuf *out,
4878 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4879 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4880 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4881 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4882 struct strbuf label = STRBUF_INIT;
4883 struct commit_list *commits = NULL, **tail = &commits, *iter;
4884 struct commit_list *tips = NULL, **tips_tail = &tips;
4885 struct commit *commit;
4886 struct oidmap commit2todo = OIDMAP_INIT;
4887 struct string_entry *entry;
4888 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4889 shown = OIDSET_INIT;
4890 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4892 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4893 const char *cmd_pick = abbr ? "p" : "pick",
4894 *cmd_label = abbr ? "l" : "label",
4895 *cmd_reset = abbr ? "t" : "reset",
4896 *cmd_merge = abbr ? "m" : "merge";
4898 oidmap_init(&commit2todo, 0);
4899 oidmap_init(&state.commit2label, 0);
4900 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4901 strbuf_init(&state.buf, 32);
4903 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4904 struct labels_entry *onto_label_entry;
4905 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4906 FLEX_ALLOC_STR(entry, string, "onto");
4907 oidcpy(&entry->entry.oid, oid);
4908 oidmap_put(&state.commit2label, entry);
4910 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4911 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4912 hashmap_add(&state.labels, &onto_label_entry->entry);
4917 * - get onelines for all commits
4918 * - gather all branch tips (i.e. 2nd or later parents of merges)
4919 * - label all branch tips
4921 while ((commit = get_revision(revs))) {
4922 struct commit_list *to_merge;
4923 const char *p1, *p2;
4924 struct object_id *oid;
4927 tail = &commit_list_insert(commit, tail)->next;
4928 oidset_insert(&interesting, &commit->object.oid);
4930 is_empty = is_original_commit_empty(commit);
4931 if (!is_empty && (commit->object.flags & PATCHSAME))
4933 if (is_empty && !keep_empty)
4936 strbuf_reset(&oneline);
4937 pretty_print_commit(pp, commit, &oneline);
4939 to_merge = commit->parents ? commit->parents->next : NULL;
4941 /* non-merge commit: easy case */
4943 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4944 oid_to_hex(&commit->object.oid),
4947 strbuf_addf(&buf, " %c empty",
4950 FLEX_ALLOC_STR(entry, string, buf.buf);
4951 oidcpy(&entry->entry.oid, &commit->object.oid);
4952 oidmap_put(&commit2todo, entry);
4957 /* Create a label */
4958 strbuf_reset(&label);
4959 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4960 (p1 = strchr(p1, '\'')) &&
4961 (p2 = strchr(++p1, '\'')))
4962 strbuf_add(&label, p1, p2 - p1);
4963 else if (skip_prefix(oneline.buf, "Merge pull request ",
4965 (p1 = strstr(p1, " from ")))
4966 strbuf_addstr(&label, p1 + strlen(" from "));
4968 strbuf_addbuf(&label, &oneline);
4971 strbuf_addf(&buf, "%s -C %s",
4972 cmd_merge, oid_to_hex(&commit->object.oid));
4974 /* label the tips of merged branches */
4975 for (; to_merge; to_merge = to_merge->next) {
4976 oid = &to_merge->item->object.oid;
4977 strbuf_addch(&buf, ' ');
4979 if (!oidset_contains(&interesting, oid)) {
4980 strbuf_addstr(&buf, label_oid(oid, NULL,
4985 tips_tail = &commit_list_insert(to_merge->item,
4988 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4990 strbuf_addf(&buf, " # %s", oneline.buf);
4992 FLEX_ALLOC_STR(entry, string, buf.buf);
4993 oidcpy(&entry->entry.oid, &commit->object.oid);
4994 oidmap_put(&commit2todo, entry);
4999 * - label branch points
5000 * - add HEAD to the branch tips
5002 for (iter = commits; iter; iter = iter->next) {
5003 struct commit_list *parent = iter->item->parents;
5004 for (; parent; parent = parent->next) {
5005 struct object_id *oid = &parent->item->object.oid;
5006 if (!oidset_contains(&interesting, oid))
5008 if (oidset_insert(&child_seen, oid))
5009 label_oid(oid, "branch-point", &state);
5012 /* Add HEAD as implicit "tip of branch" */
5014 tips_tail = &commit_list_insert(iter->item,
5019 * Third phase: output the todo list. This is a bit tricky, as we
5020 * want to avoid jumping back and forth between revisions. To
5021 * accomplish that goal, we walk backwards from the branch tips,
5022 * gathering commits not yet shown, reversing the list on the fly,
5023 * then outputting that list (labeling revisions as needed).
5025 strbuf_addf(out, "%s onto\n", cmd_label);
5026 for (iter = tips; iter; iter = iter->next) {
5027 struct commit_list *list = NULL, *iter2;
5029 commit = iter->item;
5030 if (oidset_contains(&shown, &commit->object.oid))
5032 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5035 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5037 strbuf_addch(out, '\n');
5039 while (oidset_contains(&interesting, &commit->object.oid) &&
5040 !oidset_contains(&shown, &commit->object.oid)) {
5041 commit_list_insert(commit, &list);
5042 if (!commit->parents) {
5046 commit = commit->parents->item;
5050 strbuf_addf(out, "%s %s\n", cmd_reset,
5051 rebase_cousins || root_with_onto ?
5052 "onto" : "[new root]");
5054 const char *to = NULL;
5056 entry = oidmap_get(&state.commit2label,
5057 &commit->object.oid);
5060 else if (!rebase_cousins)
5061 to = label_oid(&commit->object.oid, NULL,
5064 if (!to || !strcmp(to, "onto"))
5065 strbuf_addf(out, "%s onto\n", cmd_reset);
5067 strbuf_reset(&oneline);
5068 pretty_print_commit(pp, commit, &oneline);
5069 strbuf_addf(out, "%s %s # %s\n",
5070 cmd_reset, to, oneline.buf);
5074 for (iter2 = list; iter2; iter2 = iter2->next) {
5075 struct object_id *oid = &iter2->item->object.oid;
5076 entry = oidmap_get(&commit2todo, oid);
5077 /* only show if not already upstream */
5079 strbuf_addf(out, "%s\n", entry->string);
5080 entry = oidmap_get(&state.commit2label, oid);
5082 strbuf_addf(out, "%s %s\n",
5083 cmd_label, entry->string);
5084 oidset_insert(&shown, oid);
5087 free_commit_list(list);
5090 free_commit_list(commits);
5091 free_commit_list(tips);
5093 strbuf_release(&label);
5094 strbuf_release(&oneline);
5095 strbuf_release(&buf);
5097 oidmap_free(&commit2todo, 1);
5098 oidmap_free(&state.commit2label, 1);
5099 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5100 strbuf_release(&state.buf);
5105 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5106 const char **argv, unsigned flags)
5108 char *format = NULL;
5109 struct pretty_print_context pp = {0};
5110 struct rev_info revs;
5111 struct commit *commit;
5112 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5113 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5114 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5115 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5117 repo_init_revisions(r, &revs, NULL);
5118 revs.verbose_header = 1;
5120 revs.max_parents = 1;
5121 revs.cherry_mark = !reapply_cherry_picks;
5124 revs.right_only = 1;
5125 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5126 revs.topo_order = 1;
5128 revs.pretty_given = 1;
5129 git_config_get_string("rebase.instructionFormat", &format);
5130 if (!format || !*format) {
5132 format = xstrdup("%s");
5134 get_commit_format(format, &revs);
5136 pp.fmt = revs.commit_format;
5137 pp.output_encoding = get_log_output_encoding();
5139 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5140 return error(_("make_script: unhandled options"));
5142 if (prepare_revision_walk(&revs) < 0)
5143 return error(_("make_script: error preparing revisions"));
5146 return make_script_with_merges(&pp, &revs, out, flags);
5148 while ((commit = get_revision(&revs))) {
5149 int is_empty = is_original_commit_empty(commit);
5151 if (!is_empty && (commit->object.flags & PATCHSAME))
5153 if (is_empty && !keep_empty)
5155 strbuf_addf(out, "%s %s ", insn,
5156 oid_to_hex(&commit->object.oid));
5157 pretty_print_commit(&pp, commit, out);
5159 strbuf_addf(out, " %c empty", comment_line_char);
5160 strbuf_addch(out, '\n');
5166 * Add commands after pick and (series of) squash/fixup commands
5169 void todo_list_add_exec_commands(struct todo_list *todo_list,
5170 struct string_list *commands)
5172 struct strbuf *buf = &todo_list->buf;
5173 size_t base_offset = buf->len;
5174 int i, insert, nr = 0, alloc = 0;
5175 struct todo_item *items = NULL, *base_items = NULL;
5177 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
5178 for (i = 0; i < commands->nr; i++) {
5179 size_t command_len = strlen(commands->items[i].string);
5181 strbuf_addstr(buf, commands->items[i].string);
5182 strbuf_addch(buf, '\n');
5184 base_items[i].command = TODO_EXEC;
5185 base_items[i].offset_in_buf = base_offset;
5186 base_items[i].arg_offset = base_offset + strlen("exec ");
5187 base_items[i].arg_len = command_len - strlen("exec ");
5189 base_offset += command_len + 1;
5193 * Insert <commands> after every pick. Here, fixup/squash chains
5194 * are considered part of the pick, so we insert the commands *after*
5195 * those chains if there are any.
5197 * As we insert the exec commands immediately after rearranging
5198 * any fixups and before the user edits the list, a fixup chain
5199 * can never contain comments (any comments are empty picks that
5200 * have been commented out because the user did not specify
5201 * --keep-empty). So, it is safe to insert an exec command
5202 * without looking at the command following a comment.
5205 for (i = 0; i < todo_list->nr; i++) {
5206 enum todo_command command = todo_list->items[i].command;
5207 if (insert && !is_fixup(command)) {
5208 ALLOC_GROW(items, nr + commands->nr, alloc);
5209 COPY_ARRAY(items + nr, base_items, commands->nr);
5215 ALLOC_GROW(items, nr + 1, alloc);
5216 items[nr++] = todo_list->items[i];
5218 if (command == TODO_PICK || command == TODO_MERGE)
5222 /* insert or append final <commands> */
5223 if (insert || nr == todo_list->nr) {
5224 ALLOC_GROW(items, nr + commands->nr, alloc);
5225 COPY_ARRAY(items + nr, base_items, commands->nr);
5230 FREE_AND_NULL(todo_list->items);
5231 todo_list->items = items;
5233 todo_list->alloc = alloc;
5236 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5237 struct strbuf *buf, int num, unsigned flags)
5239 struct todo_item *item;
5240 int i, max = todo_list->nr;
5242 if (num > 0 && num < max)
5245 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5248 /* if the item is not a command write it and continue */
5249 if (item->command >= TODO_COMMENT) {
5250 strbuf_addf(buf, "%.*s\n", item->arg_len,
5251 todo_item_get_arg(todo_list, item));
5255 /* add command to the buffer */
5256 cmd = command_to_char(item->command);
5257 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5258 strbuf_addch(buf, cmd);
5260 strbuf_addstr(buf, command_to_string(item->command));
5264 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5265 short_commit_name(item->commit) :
5266 oid_to_hex(&item->commit->object.oid);
5268 if (item->command == TODO_MERGE) {
5269 if (item->flags & TODO_EDIT_MERGE_MSG)
5270 strbuf_addstr(buf, " -c");
5272 strbuf_addstr(buf, " -C");
5275 strbuf_addf(buf, " %s", oid);
5278 /* add all the rest */
5280 strbuf_addch(buf, '\n');
5282 strbuf_addf(buf, " %.*s\n", item->arg_len,
5283 todo_item_get_arg(todo_list, item));
5287 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5288 const char *file, const char *shortrevisions,
5289 const char *shortonto, int num, unsigned flags)
5292 struct strbuf buf = STRBUF_INIT;
5294 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5295 if (flags & TODO_LIST_APPEND_TODO_HELP)
5296 append_todo_help(count_commands(todo_list),
5297 shortrevisions, shortonto, &buf);
5299 res = write_message(buf.buf, buf.len, file, 0);
5300 strbuf_release(&buf);
5305 /* skip picking commits whose parents are unchanged */
5306 static int skip_unnecessary_picks(struct repository *r,
5307 struct todo_list *todo_list,
5308 struct object_id *base_oid)
5310 struct object_id *parent_oid;
5313 for (i = 0; i < todo_list->nr; i++) {
5314 struct todo_item *item = todo_list->items + i;
5316 if (item->command >= TODO_NOOP)
5318 if (item->command != TODO_PICK)
5320 if (parse_commit(item->commit)) {
5321 return error(_("could not parse commit '%s'"),
5322 oid_to_hex(&item->commit->object.oid));
5324 if (!item->commit->parents)
5325 break; /* root commit */
5326 if (item->commit->parents->next)
5327 break; /* merge commit */
5328 parent_oid = &item->commit->parents->item->object.oid;
5329 if (!oideq(parent_oid, base_oid))
5331 oidcpy(base_oid, &item->commit->object.oid);
5334 const char *done_path = rebase_path_done();
5336 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5337 error_errno(_("could not write to '%s'"), done_path);
5341 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5343 todo_list->current = 0;
5344 todo_list->done_nr += i;
5346 if (is_fixup(peek_command(todo_list, 0)))
5347 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5353 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5354 const char *shortrevisions, const char *onto_name,
5355 struct commit *onto, const struct object_id *orig_head,
5356 struct string_list *commands, unsigned autosquash,
5357 struct todo_list *todo_list)
5359 char shortonto[GIT_MAX_HEXSZ + 1];
5360 const char *todo_file = rebase_path_todo();
5361 struct todo_list new_todo = TODO_LIST_INIT;
5362 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5363 struct object_id oid = onto->object.oid;
5366 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5368 if (buf->len == 0) {
5369 struct todo_item *item = append_new_todo(todo_list);
5370 item->command = TODO_NOOP;
5371 item->commit = NULL;
5372 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5375 if (autosquash && todo_list_rearrange_squash(todo_list))
5379 todo_list_add_exec_commands(todo_list, commands);
5381 if (count_commands(todo_list) == 0) {
5382 apply_autostash(rebase_path_autostash());
5383 sequencer_remove_state(opts);
5385 return error(_("nothing to do"));
5388 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5392 else if (res == -2) {
5393 apply_autostash(rebase_path_autostash());
5394 sequencer_remove_state(opts);
5397 } else if (res == -3) {
5398 apply_autostash(rebase_path_autostash());
5399 sequencer_remove_state(opts);
5400 todo_list_release(&new_todo);
5402 return error(_("nothing to do"));
5403 } else if (res == -4) {
5404 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5405 todo_list_release(&new_todo);
5410 /* Expand the commit IDs */
5411 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5412 strbuf_swap(&new_todo.buf, &buf2);
5413 strbuf_release(&buf2);
5414 new_todo.total_nr -= new_todo.nr;
5415 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5416 BUG("invalid todo list after expanding IDs:\n%s",
5419 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5420 todo_list_release(&new_todo);
5421 return error(_("could not skip unnecessary pick commands"));
5424 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5425 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5426 todo_list_release(&new_todo);
5427 return error_errno(_("could not write '%s'"), todo_file);
5432 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5435 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5438 todo_list_write_total_nr(&new_todo);
5439 res = pick_commits(r, &new_todo, opts);
5442 todo_list_release(&new_todo);
5447 struct subject2item_entry {
5448 struct hashmap_entry entry;
5450 char subject[FLEX_ARRAY];
5453 static int subject2item_cmp(const void *fndata,
5454 const struct hashmap_entry *eptr,
5455 const struct hashmap_entry *entry_or_key,
5458 const struct subject2item_entry *a, *b;
5460 a = container_of(eptr, const struct subject2item_entry, entry);
5461 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5463 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5466 define_commit_slab(commit_todo_item, struct todo_item *);
5469 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5470 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5471 * after the former, and change "pick" to "fixup"/"squash".
5473 * Note that if the config has specified a custom instruction format, each log
5474 * message will have to be retrieved from the commit (as the oneline in the
5475 * script cannot be trusted) in order to normalize the autosquash arrangement.
5477 int todo_list_rearrange_squash(struct todo_list *todo_list)
5479 struct hashmap subject2item;
5480 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5482 struct commit_todo_item commit_todo;
5483 struct todo_item *items = NULL;
5485 init_commit_todo_item(&commit_todo);
5487 * The hashmap maps onelines to the respective todo list index.
5489 * If any items need to be rearranged, the next[i] value will indicate
5490 * which item was moved directly after the i'th.
5492 * In that case, last[i] will indicate the index of the latest item to
5493 * be moved to appear after the i'th.
5495 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5496 ALLOC_ARRAY(next, todo_list->nr);
5497 ALLOC_ARRAY(tail, todo_list->nr);
5498 ALLOC_ARRAY(subjects, todo_list->nr);
5499 for (i = 0; i < todo_list->nr; i++) {
5500 struct strbuf buf = STRBUF_INIT;
5501 struct todo_item *item = todo_list->items + i;
5502 const char *commit_buffer, *subject, *p;
5505 struct subject2item_entry *entry;
5507 next[i] = tail[i] = -1;
5508 if (!item->commit || item->command == TODO_DROP) {
5513 if (is_fixup(item->command)) {
5514 clear_commit_todo_item(&commit_todo);
5515 return error(_("the script was already rearranged."));
5518 *commit_todo_item_at(&commit_todo, item->commit) = item;
5520 parse_commit(item->commit);
5521 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5522 find_commit_subject(commit_buffer, &subject);
5523 format_subject(&buf, subject, " ");
5524 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5525 unuse_commit_buffer(item->commit, commit_buffer);
5526 if ((skip_prefix(subject, "fixup! ", &p) ||
5527 skip_prefix(subject, "squash! ", &p))) {
5528 struct commit *commit2;
5533 if (!skip_prefix(p, "fixup! ", &p) &&
5534 !skip_prefix(p, "squash! ", &p))
5538 entry = hashmap_get_entry_from_hash(&subject2item,
5540 struct subject2item_entry,
5543 /* found by title */
5545 else if (!strchr(p, ' ') &&
5547 lookup_commit_reference_by_name(p)) &&
5548 *commit_todo_item_at(&commit_todo, commit2))
5549 /* found by commit name */
5550 i2 = *commit_todo_item_at(&commit_todo, commit2)
5553 /* copy can be a prefix of the commit subject */
5554 for (i2 = 0; i2 < i; i2++)
5556 starts_with(subjects[i2], p))
5564 todo_list->items[i].command =
5565 starts_with(subject, "fixup!") ?
5566 TODO_FIXUP : TODO_SQUASH;
5571 next[i] = next[tail[i2]];
5575 } else if (!hashmap_get_from_hash(&subject2item,
5576 strhash(subject), subject)) {
5577 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5579 hashmap_entry_init(&entry->entry,
5580 strhash(entry->subject));
5581 hashmap_put(&subject2item, &entry->entry);
5586 for (i = 0; i < todo_list->nr; i++) {
5587 enum todo_command command = todo_list->items[i].command;
5591 * Initially, all commands are 'pick's. If it is a
5592 * fixup or a squash now, we have rearranged it.
5594 if (is_fixup(command))
5598 ALLOC_GROW(items, nr + 1, alloc);
5599 items[nr++] = todo_list->items[cur];
5604 FREE_AND_NULL(todo_list->items);
5605 todo_list->items = items;
5607 todo_list->alloc = alloc;
5612 for (i = 0; i < todo_list->nr; i++)
5615 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5617 clear_commit_todo_item(&commit_todo);
5622 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5624 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5625 struct object_id cherry_pick_head, rebase_head;
5627 if (file_exists(git_path_seq_dir()))
5628 *whence = FROM_CHERRY_PICK_MULTI;
5629 if (file_exists(rebase_path()) &&
5630 !get_oid("REBASE_HEAD", &rebase_head) &&
5631 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5632 oideq(&rebase_head, &cherry_pick_head))
5633 *whence = FROM_REBASE_PICK;
5635 *whence = FROM_CHERRY_PICK_SINGLE;