5 #include "object-store.h"
10 #include "run-command.h"
14 #include "cache-tree.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
25 #include "wt-status.h"
27 #include "notes-utils.h"
29 #include "unpack-trees.h"
33 #include "commit-slab.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
39 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
41 static const char sign_off_header[] = "Signed-off-by: ";
42 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
44 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
46 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
48 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
49 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
50 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
51 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
53 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
55 * The file containing rebase commands, comments, and empty lines.
56 * This file is created by "git rebase -i" then edited by the user. As
57 * the lines are processed, they are removed from the front of this
58 * file and written to the tail of 'done'.
60 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
61 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
63 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
66 * The rebase command lines that have already been processed. A line
67 * is moved here when it is first handled, before any associated user
70 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
72 * The file to keep track of how many commands were already processed (e.g.
75 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
77 * The file to keep track of how many commands are to be processed in total
78 * (e.g. for the prompt).
80 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
82 * The commit message that is planned to be used for any changes that
83 * need to be committed following a user interaction.
85 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
87 * The file into which is accumulated the suggested commit message for
88 * squash/fixup commands. When the first of a series of squash/fixups
89 * is seen, the file is created and the commit message from the
90 * previous commit and from the first squash/fixup commit are written
91 * to it. The commit message for each subsequent squash/fixup commit
92 * is appended to the file as it is processed.
94 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
96 * If the current series of squash/fixups has not yet included a squash
97 * command, then this file exists and holds the commit message of the
98 * original "pick" commit. (If the series ends without a "squash"
99 * command, then this can be used as the commit message of the combined
100 * commit without opening the editor.)
102 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
104 * This file contains the list fixup/squash commands that have been
105 * accumulated into message-fixup or message-squash so far.
107 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
109 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
110 * GIT_AUTHOR_DATE that will be used for the commit that is currently
113 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
115 * When an "edit" rebase command is being processed, the SHA1 of the
116 * commit to be edited is recorded in this file. When "git rebase
117 * --continue" is executed, if there are any staged changes then they
118 * will be amended to the HEAD commit, but only provided the HEAD
119 * commit is still the commit to be edited. When any other rebase
120 * command is processed, this file is deleted.
122 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
124 * When we stop at a given patch via the "edit" command, this file contains
125 * the commit object name of the corresponding patch.
127 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
129 * For the post-rewrite hook, we make a list of rewritten commits and
130 * their new sha1s. The rewritten-pending list keeps the sha1s of
131 * commits that have been processed, but not committed yet,
132 * e.g. because they are waiting for a 'squash' command.
134 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
135 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
136 "rebase-merge/rewritten-pending")
139 * The path of the file containing the OID of the "squash onto" commit, i.e.
140 * the dummy commit used for `reset [new root]`.
142 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
145 * The path of the file listing refs that need to be deleted after the rebase
146 * finishes. This is used by the `label` command to record the need for cleanup.
148 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
151 * The following files are written by git-rebase just after parsing the
154 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
155 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
156 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
157 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
158 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
159 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
160 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
161 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
162 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
163 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
164 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
165 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
166 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
167 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
169 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
170 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
172 static int git_sequencer_config(const char *k, const char *v, void *cb)
174 struct replay_opts *opts = cb;
177 if (!strcmp(k, "commit.cleanup")) {
180 status = git_config_string(&s, k, v);
184 if (!strcmp(s, "verbatim")) {
185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
186 opts->explicit_cleanup = 1;
187 } else if (!strcmp(s, "whitespace")) {
188 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
189 opts->explicit_cleanup = 1;
190 } else if (!strcmp(s, "strip")) {
191 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
192 opts->explicit_cleanup = 1;
193 } else if (!strcmp(s, "scissors")) {
194 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
195 opts->explicit_cleanup = 1;
197 warning(_("invalid commit message cleanup mode '%s'"),
205 if (!strcmp(k, "commit.gpgsign")) {
206 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
210 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
211 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
214 * pull.twohead is allowed to be multi-valued; we only
215 * care about the first value.
217 char *tmp = strchr(opts->default_strategy, ' ');
224 status = git_gpg_config(k, v, NULL);
228 return git_diff_basic_config(k, v, NULL);
231 void sequencer_init_config(struct replay_opts *opts)
233 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
234 git_config(git_sequencer_config, opts);
237 static inline int is_rebase_i(const struct replay_opts *opts)
239 return opts->action == REPLAY_INTERACTIVE_REBASE;
242 static const char *get_dir(const struct replay_opts *opts)
244 if (is_rebase_i(opts))
245 return rebase_path();
246 return git_path_seq_dir();
249 static const char *get_todo_path(const struct replay_opts *opts)
251 if (is_rebase_i(opts))
252 return rebase_path_todo();
253 return git_path_todo_file();
257 * Returns 0 for non-conforming footer
258 * Returns 1 for conforming footer
259 * Returns 2 when sob exists within conforming footer
260 * Returns 3 when sob exists within conforming footer as last entry
262 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
263 size_t ignore_footer)
265 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
266 struct trailer_info info;
268 int found_sob = 0, found_sob_last = 0;
274 saved_char = sb->buf[sb->len - ignore_footer];
275 sb->buf[sb->len - ignore_footer] = '\0';
278 trailer_info_get(&info, sb->buf, &opts);
281 sb->buf[sb->len - ignore_footer] = saved_char;
283 if (info.trailer_start == info.trailer_end)
286 for (i = 0; i < info.trailer_nr; i++)
287 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
289 if (i == info.trailer_nr - 1)
293 trailer_info_release(&info);
302 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
304 static struct strbuf buf = STRBUF_INIT;
308 sq_quotef(&buf, "-S%s", opts->gpg_sign);
312 int sequencer_remove_state(struct replay_opts *opts)
314 struct strbuf buf = STRBUF_INIT;
317 if (is_rebase_i(opts) &&
318 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
321 char *eol = strchr(p, '\n');
324 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
325 warning(_("could not delete '%s'"), p);
334 free(opts->gpg_sign);
335 free(opts->default_strategy);
336 free(opts->strategy);
337 for (i = 0; i < opts->xopts_nr; i++)
338 free(opts->xopts[i]);
340 strbuf_release(&opts->current_fixups);
343 strbuf_addstr(&buf, get_dir(opts));
344 if (remove_dir_recursively(&buf, 0))
345 ret = error(_("could not remove '%s'"), buf.buf);
346 strbuf_release(&buf);
351 static const char *action_name(const struct replay_opts *opts)
353 switch (opts->action) {
357 return N_("cherry-pick");
358 case REPLAY_INTERACTIVE_REBASE:
361 die(_("unknown action: %d"), opts->action);
364 struct commit_message {
371 static const char *short_commit_name(struct commit *commit)
373 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
376 static int get_message(struct commit *commit, struct commit_message *out)
378 const char *abbrev, *subject;
381 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
382 abbrev = short_commit_name(commit);
384 subject_len = find_commit_subject(out->message, &subject);
386 out->subject = xmemdupz(subject, subject_len);
387 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
388 out->parent_label = xstrfmt("parent of %s", out->label);
393 static void free_message(struct commit *commit, struct commit_message *msg)
395 free(msg->parent_label);
398 unuse_commit_buffer(commit, msg->message);
401 static void print_advice(struct repository *r, int show_hint,
402 struct replay_opts *opts)
404 char *msg = getenv("GIT_CHERRY_PICK_HELP");
407 fprintf(stderr, "%s\n", msg);
409 * A conflict has occurred but the porcelain
410 * (typically rebase --interactive) wants to take care
411 * of the commit itself so remove CHERRY_PICK_HEAD
413 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
420 advise(_("after resolving the conflicts, mark the corrected paths\n"
421 "with 'git add <paths>' or 'git rm <paths>'"));
423 advise(_("after resolving the conflicts, mark the corrected paths\n"
424 "with 'git add <paths>' or 'git rm <paths>'\n"
425 "and commit the result with 'git commit'"));
429 static int write_message(const void *buf, size_t len, const char *filename,
432 struct lock_file msg_file = LOCK_INIT;
434 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
436 return error_errno(_("could not lock '%s'"), filename);
437 if (write_in_full(msg_fd, buf, len) < 0) {
438 error_errno(_("could not write to '%s'"), filename);
439 rollback_lock_file(&msg_file);
442 if (append_eol && write(msg_fd, "\n", 1) < 0) {
443 error_errno(_("could not write eol to '%s'"), filename);
444 rollback_lock_file(&msg_file);
447 if (commit_lock_file(&msg_file) < 0)
448 return error(_("failed to finalize '%s'"), filename);
453 int read_oneliner(struct strbuf *buf,
454 const char *path, unsigned flags)
456 int orig_len = buf->len;
458 if (strbuf_read_file(buf, path, 0) < 0) {
459 if ((flags & READ_ONELINER_WARN_MISSING) ||
460 (errno != ENOENT && errno != ENOTDIR))
461 warning_errno(_("could not read '%s'"), path);
465 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
466 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
468 buf->buf[buf->len] = '\0';
471 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
477 static struct tree *empty_tree(struct repository *r)
479 return lookup_tree(r, the_hash_algo->empty_tree);
482 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
484 if (repo_read_index_unmerged(repo))
485 return error_resolve_conflict(_(action_name(opts)));
487 error(_("your local changes would be overwritten by %s."),
488 _(action_name(opts)));
490 if (advice_commit_before_merge)
491 advise(_("commit your changes or stash them to proceed."));
495 static void update_abort_safety_file(void)
497 struct object_id head;
499 /* Do nothing on a single-pick */
500 if (!file_exists(git_path_seq_dir()))
503 if (!get_oid("HEAD", &head))
504 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
506 write_file(git_path_abort_safety_file(), "%s", "");
509 static int fast_forward_to(struct repository *r,
510 const struct object_id *to,
511 const struct object_id *from,
513 struct replay_opts *opts)
515 struct ref_transaction *transaction;
516 struct strbuf sb = STRBUF_INIT;
517 struct strbuf err = STRBUF_INIT;
520 if (checkout_fast_forward(r, from, to, 1))
521 return -1; /* the callee should have complained already */
523 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
525 transaction = ref_transaction_begin(&err);
527 ref_transaction_update(transaction, "HEAD",
528 to, unborn && !is_rebase_i(opts) ?
531 ref_transaction_commit(transaction, &err)) {
532 ref_transaction_free(transaction);
533 error("%s", err.buf);
535 strbuf_release(&err);
540 strbuf_release(&err);
541 ref_transaction_free(transaction);
542 update_abort_safety_file();
546 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
549 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
550 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
551 COMMIT_MSG_CLEANUP_SPACE;
552 else if (!strcmp(cleanup_arg, "verbatim"))
553 return COMMIT_MSG_CLEANUP_NONE;
554 else if (!strcmp(cleanup_arg, "whitespace"))
555 return COMMIT_MSG_CLEANUP_SPACE;
556 else if (!strcmp(cleanup_arg, "strip"))
557 return COMMIT_MSG_CLEANUP_ALL;
558 else if (!strcmp(cleanup_arg, "scissors"))
559 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
560 COMMIT_MSG_CLEANUP_SPACE;
562 die(_("Invalid cleanup mode %s"), cleanup_arg);
566 * NB using int rather than enum cleanup_mode to stop clang's
567 * -Wtautological-constant-out-of-range-compare complaining that the comparison
570 static const char *describe_cleanup_mode(int cleanup_mode)
572 static const char *modes[] = { "whitespace",
577 if (cleanup_mode < ARRAY_SIZE(modes))
578 return modes[cleanup_mode];
580 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
583 void append_conflicts_hint(struct index_state *istate,
584 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
588 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
589 strbuf_addch(msgbuf, '\n');
590 wt_status_append_cut_line(msgbuf);
591 strbuf_addch(msgbuf, comment_line_char);
594 strbuf_addch(msgbuf, '\n');
595 strbuf_commented_addf(msgbuf, "Conflicts:\n");
596 for (i = 0; i < istate->cache_nr;) {
597 const struct cache_entry *ce = istate->cache[i++];
599 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
600 while (i < istate->cache_nr &&
601 !strcmp(ce->name, istate->cache[i]->name))
607 static int do_recursive_merge(struct repository *r,
608 struct commit *base, struct commit *next,
609 const char *base_label, const char *next_label,
610 struct object_id *head, struct strbuf *msgbuf,
611 struct replay_opts *opts)
613 struct merge_options o;
614 struct merge_result result;
615 struct tree *next_tree, *base_tree, *head_tree;
616 int clean, show_output;
618 struct lock_file index_lock = LOCK_INIT;
620 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
625 init_merge_options(&o, r);
626 o.ancestor = base ? base_label : "(empty tree)";
628 o.branch2 = next ? next_label : "(empty tree)";
629 if (is_rebase_i(opts))
631 o.show_rename_progress = 1;
633 head_tree = parse_tree_indirect(head);
634 next_tree = next ? get_commit_tree(next) : empty_tree(r);
635 base_tree = base ? get_commit_tree(base) : empty_tree(r);
637 for (i = 0; i < opts->xopts_nr; i++)
638 parse_merge_opt(&o, opts->xopts[i]);
640 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
641 memset(&result, 0, sizeof(result));
642 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
644 show_output = !is_rebase_i(opts) || !result.clean;
646 * TODO: merge_switch_to_result will update index/working tree;
647 * we only really want to do that if !result.clean || this is
648 * the final patch to be picked. But determining this is the
649 * final patch would take some work, and "head_tree" would need
650 * to be replace with the tree the index matched before we
651 * started doing any picks.
653 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
654 clean = result.clean;
656 clean = merge_trees(&o, head_tree, next_tree, base_tree);
657 if (is_rebase_i(opts) && clean <= 0)
658 fputs(o.obuf.buf, stdout);
659 strbuf_release(&o.obuf);
662 rollback_lock_file(&index_lock);
666 if (write_locked_index(r->index, &index_lock,
667 COMMIT_LOCK | SKIP_IF_UNCHANGED))
669 * TRANSLATORS: %s will be "revert", "cherry-pick" or
672 return error(_("%s: Unable to write new index file"),
673 _(action_name(opts)));
676 append_conflicts_hint(r->index, msgbuf,
677 opts->default_msg_cleanup);
682 static struct object_id *get_cache_tree_oid(struct index_state *istate)
684 if (!cache_tree_fully_valid(istate->cache_tree))
685 if (cache_tree_update(istate, 0)) {
686 error(_("unable to update cache tree"));
690 return &istate->cache_tree->oid;
693 static int is_index_unchanged(struct repository *r)
695 struct object_id head_oid, *cache_tree_oid;
696 struct commit *head_commit;
697 struct index_state *istate = r->index;
699 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
700 return error(_("could not resolve HEAD commit"));
702 head_commit = lookup_commit(r, &head_oid);
705 * If head_commit is NULL, check_commit, called from
706 * lookup_commit, would have indicated that head_commit is not
707 * a commit object already. parse_commit() will return failure
708 * without further complaints in such a case. Otherwise, if
709 * the commit is invalid, parse_commit() will complain. So
710 * there is nothing for us to say here. Just return failure.
712 if (parse_commit(head_commit))
715 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
718 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
721 static int write_author_script(const char *message)
723 struct strbuf buf = STRBUF_INIT;
728 if (!*message || starts_with(message, "\n")) {
730 /* Missing 'author' line? */
731 unlink(rebase_path_author_script());
733 } else if (skip_prefix(message, "author ", &message))
735 else if ((eol = strchr(message, '\n')))
740 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
741 while (*message && *message != '\n' && *message != '\r')
742 if (skip_prefix(message, " <", &message))
744 else if (*message != '\'')
745 strbuf_addch(&buf, *(message++));
747 strbuf_addf(&buf, "'\\%c'", *(message++));
748 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
749 while (*message && *message != '\n' && *message != '\r')
750 if (skip_prefix(message, "> ", &message))
752 else if (*message != '\'')
753 strbuf_addch(&buf, *(message++));
755 strbuf_addf(&buf, "'\\%c'", *(message++));
756 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
757 while (*message && *message != '\n' && *message != '\r')
758 if (*message != '\'')
759 strbuf_addch(&buf, *(message++));
761 strbuf_addf(&buf, "'\\%c'", *(message++));
762 strbuf_addch(&buf, '\'');
763 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
764 strbuf_release(&buf);
769 * Take a series of KEY='VALUE' lines where VALUE part is
770 * sq-quoted, and append <KEY, VALUE> at the end of the string list
772 static int parse_key_value_squoted(char *buf, struct string_list *list)
775 struct string_list_item *item;
777 char *cp = strchr(buf, '=');
779 np = strchrnul(buf, '\n');
780 return error(_("no key present in '%.*s'"),
781 (int) (np - buf), buf);
783 np = strchrnul(cp, '\n');
785 item = string_list_append(list, buf);
787 buf = np + (*np == '\n');
791 return error(_("unable to dequote value of '%s'"),
793 item->util = xstrdup(cp);
799 * Reads and parses the state directory's "author-script" file, and sets name,
800 * email and date accordingly.
801 * Returns 0 on success, -1 if the file could not be parsed.
803 * The author script is of the format:
805 * GIT_AUTHOR_NAME='$author_name'
806 * GIT_AUTHOR_EMAIL='$author_email'
807 * GIT_AUTHOR_DATE='$author_date'
809 * where $author_name, $author_email and $author_date are quoted. We are strict
810 * with our parsing, as the file was meant to be eval'd in the now-removed
811 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
812 * from what this function expects, it is better to bail out than to do
813 * something that the user does not expect.
815 int read_author_script(const char *path, char **name, char **email, char **date,
818 struct strbuf buf = STRBUF_INIT;
819 struct string_list kv = STRING_LIST_INIT_DUP;
820 int retval = -1; /* assume failure */
821 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
823 if (strbuf_read_file(&buf, path, 256) <= 0) {
824 strbuf_release(&buf);
825 if (errno == ENOENT && allow_missing)
828 return error_errno(_("could not open '%s' for reading"),
832 if (parse_key_value_squoted(buf.buf, &kv))
835 for (i = 0; i < kv.nr; i++) {
836 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
838 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
841 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
843 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
846 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
848 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
852 err = error(_("unknown variable '%s'"),
857 error(_("missing 'GIT_AUTHOR_NAME'"));
859 error(_("missing 'GIT_AUTHOR_EMAIL'"));
861 error(_("missing 'GIT_AUTHOR_DATE'"));
862 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
864 *name = kv.items[name_i].util;
865 *email = kv.items[email_i].util;
866 *date = kv.items[date_i].util;
869 string_list_clear(&kv, !!retval);
870 strbuf_release(&buf);
875 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
876 * file with shell quoting into struct strvec. Returns -1 on
877 * error, 0 otherwise.
879 static int read_env_script(struct strvec *env)
881 char *name, *email, *date;
883 if (read_author_script(rebase_path_author_script(),
884 &name, &email, &date, 0))
887 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
888 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
889 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
897 static char *get_author(const char *message)
902 a = find_commit_header(message, "author", &len);
904 return xmemdupz(a, len);
909 static const char *author_date_from_env_array(const struct strvec *env)
914 for (i = 0; i < env->nr; i++)
915 if (skip_prefix(env->v[i],
916 "GIT_AUTHOR_DATE=", &date))
919 * If GIT_AUTHOR_DATE is missing we should have already errored out when
922 BUG("GIT_AUTHOR_DATE missing from author script");
925 static const char staged_changes_advice[] =
926 N_("you have staged changes in your working tree\n"
927 "If these changes are meant to be squashed into the previous commit, run:\n"
929 " git commit --amend %s\n"
931 "If they are meant to go into a new commit, run:\n"
935 "In both cases, once you're done, continue with:\n"
937 " git rebase --continue\n");
939 #define ALLOW_EMPTY (1<<0)
940 #define EDIT_MSG (1<<1)
941 #define AMEND_MSG (1<<2)
942 #define CLEANUP_MSG (1<<3)
943 #define VERIFY_MSG (1<<4)
944 #define CREATE_ROOT_COMMIT (1<<5)
945 #define VERBATIM_MSG (1<<6)
947 static int run_command_silent_on_success(struct child_process *cmd)
949 struct strbuf buf = STRBUF_INIT;
952 cmd->stdout_to_stderr = 1;
953 rc = pipe_command(cmd,
959 fputs(buf.buf, stderr);
960 strbuf_release(&buf);
965 * If we are cherry-pick, and if the merge did not result in
966 * hand-editing, we will hit this commit and inherit the original
967 * author date and name.
969 * If we are revert, or if our cherry-pick results in a hand merge,
970 * we had better say that the current user is responsible for that.
972 * An exception is when run_git_commit() is called during an
973 * interactive rebase: in that case, we will want to retain the
976 static int run_git_commit(const char *defmsg,
977 struct replay_opts *opts,
980 struct child_process cmd = CHILD_PROCESS_INIT;
982 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
983 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
987 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
988 const char *gpg_opt = gpg_sign_opt_quoted(opts);
990 return error(_(staged_changes_advice),
994 if (opts->committer_date_is_author_date)
995 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
998 author_date_from_env_array(&cmd.env_array));
999 if (opts->ignore_date)
1000 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1002 strvec_push(&cmd.args, "commit");
1004 if (!(flags & VERIFY_MSG))
1005 strvec_push(&cmd.args, "-n");
1006 if ((flags & AMEND_MSG))
1007 strvec_push(&cmd.args, "--amend");
1009 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1011 strvec_push(&cmd.args, "--no-gpg-sign");
1013 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1014 else if (!(flags & EDIT_MSG))
1015 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1016 if ((flags & CLEANUP_MSG))
1017 strvec_push(&cmd.args, "--cleanup=strip");
1018 if ((flags & VERBATIM_MSG))
1019 strvec_push(&cmd.args, "--cleanup=verbatim");
1020 if ((flags & EDIT_MSG))
1021 strvec_push(&cmd.args, "-e");
1022 else if (!(flags & CLEANUP_MSG) &&
1023 !opts->signoff && !opts->record_origin &&
1024 !opts->explicit_cleanup)
1025 strvec_push(&cmd.args, "--cleanup=verbatim");
1027 if ((flags & ALLOW_EMPTY))
1028 strvec_push(&cmd.args, "--allow-empty");
1030 if (!(flags & EDIT_MSG))
1031 strvec_push(&cmd.args, "--allow-empty-message");
1033 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1034 return run_command_silent_on_success(&cmd);
1036 return run_command(&cmd);
1039 static int rest_is_empty(const struct strbuf *sb, int start)
1044 /* Check if the rest is just whitespace and Signed-off-by's. */
1045 for (i = start; i < sb->len; i++) {
1046 nl = memchr(sb->buf + i, '\n', sb->len - i);
1052 if (strlen(sign_off_header) <= eol - i &&
1053 starts_with(sb->buf + i, sign_off_header)) {
1058 if (!isspace(sb->buf[i++]))
1065 void cleanup_message(struct strbuf *msgbuf,
1066 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1068 if (verbose || /* Truncate the message just before the diff, if any. */
1069 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1070 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1071 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1072 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1076 * Find out if the message in the strbuf contains only whitespace and
1077 * Signed-off-by lines.
1079 int message_is_empty(const struct strbuf *sb,
1080 enum commit_msg_cleanup_mode cleanup_mode)
1082 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1084 return rest_is_empty(sb, 0);
1088 * See if the user edited the message in the editor or left what
1089 * was in the template intact
1091 int template_untouched(const struct strbuf *sb, const char *template_file,
1092 enum commit_msg_cleanup_mode cleanup_mode)
1094 struct strbuf tmpl = STRBUF_INIT;
1097 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1100 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1103 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1104 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1106 strbuf_release(&tmpl);
1107 return rest_is_empty(sb, start - sb->buf);
1110 int update_head_with_reflog(const struct commit *old_head,
1111 const struct object_id *new_head,
1112 const char *action, const struct strbuf *msg,
1115 struct ref_transaction *transaction;
1116 struct strbuf sb = STRBUF_INIT;
1121 strbuf_addstr(&sb, action);
1122 strbuf_addstr(&sb, ": ");
1125 nl = strchr(msg->buf, '\n');
1127 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1129 strbuf_addbuf(&sb, msg);
1130 strbuf_addch(&sb, '\n');
1133 transaction = ref_transaction_begin(err);
1135 ref_transaction_update(transaction, "HEAD", new_head,
1136 old_head ? &old_head->object.oid : null_oid(),
1138 ref_transaction_commit(transaction, err)) {
1141 ref_transaction_free(transaction);
1142 strbuf_release(&sb);
1147 static int run_rewrite_hook(const struct object_id *oldoid,
1148 const struct object_id *newoid)
1150 struct child_process proc = CHILD_PROCESS_INIT;
1151 const char *argv[3];
1153 struct strbuf sb = STRBUF_INIT;
1155 argv[0] = find_hook("post-rewrite");
1164 proc.stdout_to_stderr = 1;
1165 proc.trace2_hook_name = "post-rewrite";
1167 code = start_command(&proc);
1170 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1171 sigchain_push(SIGPIPE, SIG_IGN);
1172 write_in_full(proc.in, sb.buf, sb.len);
1174 strbuf_release(&sb);
1175 sigchain_pop(SIGPIPE);
1176 return finish_command(&proc);
1179 void commit_post_rewrite(struct repository *r,
1180 const struct commit *old_head,
1181 const struct object_id *new_head)
1183 struct notes_rewrite_cfg *cfg;
1185 cfg = init_copy_notes_for_rewrite("amend");
1187 /* we are amending, so old_head is not NULL */
1188 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1189 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1191 run_rewrite_hook(&old_head->object.oid, new_head);
1194 static int run_prepare_commit_msg_hook(struct repository *r,
1199 const char *name, *arg1 = NULL, *arg2 = NULL;
1201 name = git_path_commit_editmsg();
1202 if (write_message(msg->buf, msg->len, name, 0))
1211 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1213 ret = error(_("'prepare-commit-msg' hook failed"));
1218 static const char implicit_ident_advice_noconfig[] =
1219 N_("Your name and email address were configured automatically based\n"
1220 "on your username and hostname. Please check that they are accurate.\n"
1221 "You can suppress this message by setting them explicitly. Run the\n"
1222 "following command and follow the instructions in your editor to edit\n"
1223 "your configuration file:\n"
1225 " git config --global --edit\n"
1227 "After doing this, you may fix the identity used for this commit with:\n"
1229 " git commit --amend --reset-author\n");
1231 static const char implicit_ident_advice_config[] =
1232 N_("Your name and email address were configured automatically based\n"
1233 "on your username and hostname. Please check that they are accurate.\n"
1234 "You can suppress this message by setting them explicitly:\n"
1236 " git config --global user.name \"Your Name\"\n"
1237 " git config --global user.email you@example.com\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1241 " git commit --amend --reset-author\n");
1243 static const char *implicit_ident_advice(void)
1245 char *user_config = expand_user_path("~/.gitconfig", 0);
1246 char *xdg_config = xdg_config_home("config");
1247 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1253 return _(implicit_ident_advice_config);
1255 return _(implicit_ident_advice_noconfig);
1259 void print_commit_summary(struct repository *r,
1261 const struct object_id *oid,
1264 struct rev_info rev;
1265 struct commit *commit;
1266 struct strbuf format = STRBUF_INIT;
1268 struct pretty_print_context pctx = {0};
1269 struct strbuf author_ident = STRBUF_INIT;
1270 struct strbuf committer_ident = STRBUF_INIT;
1272 commit = lookup_commit(r, oid);
1274 die(_("couldn't look up newly created commit"));
1275 if (parse_commit(commit))
1276 die(_("could not parse newly created commit"));
1278 strbuf_addstr(&format, "format:%h] %s");
1280 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1281 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1282 if (strbuf_cmp(&author_ident, &committer_ident)) {
1283 strbuf_addstr(&format, "\n Author: ");
1284 strbuf_addbuf_percentquote(&format, &author_ident);
1286 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1287 struct strbuf date = STRBUF_INIT;
1289 format_commit_message(commit, "%ad", &date, &pctx);
1290 strbuf_addstr(&format, "\n Date: ");
1291 strbuf_addbuf_percentquote(&format, &date);
1292 strbuf_release(&date);
1294 if (!committer_ident_sufficiently_given()) {
1295 strbuf_addstr(&format, "\n Committer: ");
1296 strbuf_addbuf_percentquote(&format, &committer_ident);
1297 if (advice_implicit_identity) {
1298 strbuf_addch(&format, '\n');
1299 strbuf_addstr(&format, implicit_ident_advice());
1302 strbuf_release(&author_ident);
1303 strbuf_release(&committer_ident);
1305 repo_init_revisions(r, &rev, prefix);
1306 setup_revisions(0, NULL, &rev, NULL);
1309 rev.diffopt.output_format =
1310 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1312 rev.verbose_header = 1;
1313 rev.show_root_diff = 1;
1314 get_commit_format(format.buf, &rev);
1315 rev.always_show_header = 0;
1316 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1317 rev.diffopt.break_opt = 0;
1318 diff_setup_done(&rev.diffopt);
1320 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1322 die_errno(_("unable to resolve HEAD after creating commit"));
1323 if (!strcmp(head, "HEAD"))
1324 head = _("detached HEAD");
1326 skip_prefix(head, "refs/heads/", &head);
1327 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1328 _(" (root-commit)") : "");
1330 if (!log_tree_commit(&rev, commit)) {
1331 rev.always_show_header = 1;
1332 rev.use_terminator = 1;
1333 log_tree_commit(&rev, commit);
1336 strbuf_release(&format);
1339 static int parse_head(struct repository *r, struct commit **head)
1341 struct commit *current_head;
1342 struct object_id oid;
1344 if (get_oid("HEAD", &oid)) {
1345 current_head = NULL;
1347 current_head = lookup_commit_reference(r, &oid);
1349 return error(_("could not parse HEAD"));
1350 if (!oideq(&oid, ¤t_head->object.oid)) {
1351 warning(_("HEAD %s is not a commit!"),
1354 if (parse_commit(current_head))
1355 return error(_("could not parse HEAD commit"));
1357 *head = current_head;
1363 * Try to commit without forking 'git commit'. In some cases we need
1364 * to run 'git commit' to display an error message
1367 * -1 - error unable to commit
1369 * 1 - run 'git commit'
1371 static int try_to_commit(struct repository *r,
1372 struct strbuf *msg, const char *author,
1373 struct replay_opts *opts, unsigned int flags,
1374 struct object_id *oid)
1376 struct object_id tree;
1377 struct commit *current_head = NULL;
1378 struct commit_list *parents = NULL;
1379 struct commit_extra_header *extra = NULL;
1380 struct strbuf err = STRBUF_INIT;
1381 struct strbuf commit_msg = STRBUF_INIT;
1382 char *amend_author = NULL;
1383 const char *committer = NULL;
1384 const char *hook_commit = NULL;
1385 enum commit_msg_cleanup_mode cleanup;
1388 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1389 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1391 if (parse_head(r, ¤t_head))
1394 if (flags & AMEND_MSG) {
1395 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1396 const char *out_enc = get_commit_output_encoding();
1397 const char *message = logmsg_reencode(current_head, NULL,
1401 const char *orig_message = NULL;
1403 find_commit_subject(message, &orig_message);
1405 strbuf_addstr(msg, orig_message);
1406 hook_commit = "HEAD";
1408 author = amend_author = get_author(message);
1409 unuse_commit_buffer(current_head, message);
1411 res = error(_("unable to parse commit author"));
1414 parents = copy_commit_list(current_head->parents);
1415 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1416 } else if (current_head &&
1417 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1418 commit_list_insert(current_head, &parents);
1421 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1422 res = error(_("git write-tree failed to write a tree"));
1426 if (!(flags & ALLOW_EMPTY)) {
1427 struct commit *first_parent = current_head;
1429 if (flags & AMEND_MSG) {
1430 if (current_head->parents) {
1431 first_parent = current_head->parents->item;
1432 if (repo_parse_commit(r, first_parent)) {
1433 res = error(_("could not parse HEAD commit"));
1437 first_parent = NULL;
1440 if (oideq(first_parent
1441 ? get_commit_tree_oid(first_parent)
1442 : the_hash_algo->empty_tree,
1444 res = 1; /* run 'git commit' to display error message */
1449 if (hook_exists("prepare-commit-msg")) {
1450 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1453 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1455 res = error_errno(_("unable to read commit message "
1457 git_path_commit_editmsg());
1463 if (flags & CLEANUP_MSG)
1464 cleanup = COMMIT_MSG_CLEANUP_ALL;
1465 else if (flags & VERBATIM_MSG)
1466 cleanup = COMMIT_MSG_CLEANUP_NONE;
1467 else if ((opts->signoff || opts->record_origin) &&
1468 !opts->explicit_cleanup)
1469 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1471 cleanup = opts->default_msg_cleanup;
1473 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1474 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1475 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1476 res = 1; /* run 'git commit' to display error message */
1480 if (opts->committer_date_is_author_date) {
1481 struct ident_split id;
1482 struct strbuf date = STRBUF_INIT;
1484 if (!opts->ignore_date) {
1485 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1486 res = error(_("invalid author identity '%s'"),
1490 if (!id.date_begin) {
1492 "corrupt author: missing date information"));
1495 strbuf_addf(&date, "@%.*s %.*s",
1496 (int)(id.date_end - id.date_begin),
1498 (int)(id.tz_end - id.tz_begin),
1503 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1504 getenv("GIT_COMMITTER_EMAIL"),
1505 WANT_COMMITTER_IDENT,
1506 opts->ignore_date ? NULL : date.buf,
1508 strbuf_release(&date);
1513 if (opts->ignore_date) {
1514 struct ident_split id;
1517 if (split_ident_line(&id, author, strlen(author)) < 0) {
1518 error(_("invalid author identity '%s'"), author);
1521 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1522 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1523 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1529 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1530 author, committer, opts->gpg_sign, extra)) {
1531 res = error(_("failed to write commit object"));
1535 if (update_head_with_reflog(current_head, oid,
1536 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1537 res = error("%s", err.buf);
1541 run_commit_hook(0, r->index_file, "post-commit", NULL);
1542 if (flags & AMEND_MSG)
1543 commit_post_rewrite(r, current_head, oid);
1546 free_commit_extra_headers(extra);
1547 strbuf_release(&err);
1548 strbuf_release(&commit_msg);
1554 static int write_rebase_head(struct object_id *oid)
1556 if (update_ref("rebase", "REBASE_HEAD", oid,
1557 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1558 return error(_("could not update %s"), "REBASE_HEAD");
1563 static int do_commit(struct repository *r,
1564 const char *msg_file, const char *author,
1565 struct replay_opts *opts, unsigned int flags,
1566 struct object_id *oid)
1570 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1571 struct object_id oid;
1572 struct strbuf sb = STRBUF_INIT;
1574 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1575 return error_errno(_("unable to read commit message "
1579 res = try_to_commit(r, msg_file ? &sb : NULL,
1580 author, opts, flags, &oid);
1581 strbuf_release(&sb);
1583 refs_delete_ref(get_main_ref_store(r), "",
1584 "CHERRY_PICK_HEAD", NULL, 0);
1585 unlink(git_path_merge_msg(r));
1586 if (!is_rebase_i(opts))
1587 print_commit_summary(r, NULL, &oid,
1588 SUMMARY_SHOW_AUTHOR_DATE);
1593 if (is_rebase_i(opts) && oid)
1594 if (write_rebase_head(oid))
1596 return run_git_commit(msg_file, opts, flags);
1602 static int is_original_commit_empty(struct commit *commit)
1604 const struct object_id *ptree_oid;
1606 if (parse_commit(commit))
1607 return error(_("could not parse commit %s"),
1608 oid_to_hex(&commit->object.oid));
1609 if (commit->parents) {
1610 struct commit *parent = commit->parents->item;
1611 if (parse_commit(parent))
1612 return error(_("could not parse parent commit %s"),
1613 oid_to_hex(&parent->object.oid));
1614 ptree_oid = get_commit_tree_oid(parent);
1616 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1619 return oideq(ptree_oid, get_commit_tree_oid(commit));
1623 * Should empty commits be allowed? Return status:
1624 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1625 * 0: Halt on empty commit
1626 * 1: Allow empty commit
1627 * 2: Drop empty commit
1629 static int allow_empty(struct repository *r,
1630 struct replay_opts *opts,
1631 struct commit *commit)
1633 int index_unchanged, originally_empty;
1638 * (1) we do not allow empty at all and error out.
1640 * (2) we allow ones that were initially empty, and
1641 * just drop the ones that become empty
1643 * (3) we allow ones that were initially empty, but
1644 * halt for the ones that become empty;
1646 * (4) we allow both.
1648 if (!opts->allow_empty)
1649 return 0; /* let "git commit" barf as necessary */
1651 index_unchanged = is_index_unchanged(r);
1652 if (index_unchanged < 0)
1653 return index_unchanged;
1654 if (!index_unchanged)
1655 return 0; /* we do not have to say --allow-empty */
1657 if (opts->keep_redundant_commits)
1660 originally_empty = is_original_commit_empty(commit);
1661 if (originally_empty < 0)
1662 return originally_empty;
1663 if (originally_empty)
1665 else if (opts->drop_redundant_commits)
1674 } todo_command_info[] = {
1691 static const char *command_to_string(const enum todo_command command)
1693 if (command < TODO_COMMENT)
1694 return todo_command_info[command].str;
1695 die(_("unknown command: %d"), command);
1698 static char command_to_char(const enum todo_command command)
1700 if (command < TODO_COMMENT)
1701 return todo_command_info[command].c;
1702 return comment_line_char;
1705 static int is_noop(const enum todo_command command)
1707 return TODO_NOOP <= command;
1710 static int is_fixup(enum todo_command command)
1712 return command == TODO_FIXUP || command == TODO_SQUASH;
1715 /* Does this command create a (non-merge) commit? */
1716 static int is_pick_or_similar(enum todo_command command)
1731 enum todo_item_flags {
1732 TODO_EDIT_MERGE_MSG = (1 << 0),
1733 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1734 TODO_EDIT_FIXUP_MSG = (1 << 2),
1737 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1738 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1739 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1740 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1741 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1743 static int is_fixup_flag(enum todo_command command, unsigned flag)
1745 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1746 (flag & TODO_EDIT_FIXUP_MSG));
1750 * Wrapper around strbuf_add_commented_lines() which avoids double
1751 * commenting commit subjects.
1753 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1755 const char *s = str;
1756 while (len > 0 && s[0] == comment_line_char) {
1758 const char *n = memchr(s, '\n', len);
1763 strbuf_add(buf, s, count);
1767 strbuf_add_commented_lines(buf, s, len);
1770 /* Does the current fixup chain contain a squash command? */
1771 static int seen_squash(struct replay_opts *opts)
1773 return starts_with(opts->current_fixups.buf, "squash") ||
1774 strstr(opts->current_fixups.buf, "\nsquash");
1777 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1779 strbuf_setlen(buf1, 2);
1780 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1781 strbuf_addch(buf1, '\n');
1782 strbuf_setlen(buf2, 2);
1783 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1784 strbuf_addch(buf2, '\n');
1788 * Comment out any un-commented commit messages, updating the message comments
1789 * to say they will be skipped but do not comment out the empty lines that
1790 * surround commit messages and their comments.
1792 static void update_squash_message_for_fixup(struct strbuf *msg)
1794 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1795 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1796 const char *s, *start;
1798 size_t orig_msg_len;
1801 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1802 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1803 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1807 if (skip_prefix(s, buf1.buf, &next)) {
1809 * Copy the last message, preserving the blank line
1810 * preceding the current line
1812 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1813 copy_lines(msg, start, s - start - off);
1815 strbuf_addch(msg, '\n');
1817 * The next message needs to be commented out but the
1818 * message header is already commented out so just copy
1819 * it and the blank line that follows it.
1821 strbuf_addbuf(msg, &buf2);
1823 strbuf_addch(msg, *next++);
1825 copy_lines = add_commented_lines;
1826 update_comment_bufs(&buf1, &buf2, ++i);
1827 } else if (skip_prefix(s, buf2.buf, &next)) {
1828 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1829 copy_lines(msg, start, s - start - off);
1832 copy_lines = strbuf_add;
1833 update_comment_bufs(&buf1, &buf2, ++i);
1835 s = strchr(s, '\n');
1840 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1842 strbuf_release(&buf1);
1843 strbuf_release(&buf2);
1846 static int append_squash_message(struct strbuf *buf, const char *body,
1847 enum todo_command command, struct replay_opts *opts,
1850 const char *fixup_msg;
1851 size_t commented_len = 0, fixup_off;
1853 * amend is non-interactive and not normally used with fixup!
1854 * or squash! commits, so only comment out those subjects when
1855 * squashing commit messages.
1857 if (starts_with(body, "amend!") ||
1858 ((command == TODO_SQUASH || seen_squash(opts)) &&
1859 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1860 commented_len = commit_subject_length(body);
1862 strbuf_addf(buf, "\n%c ", comment_line_char);
1863 strbuf_addf(buf, _(nth_commit_msg_fmt),
1864 ++opts->current_fixup_count + 1);
1865 strbuf_addstr(buf, "\n\n");
1866 strbuf_add_commented_lines(buf, body, commented_len);
1867 /* buf->buf may be reallocated so store an offset into the buffer */
1868 fixup_off = buf->len;
1869 strbuf_addstr(buf, body + commented_len);
1871 /* fixup -C after squash behaves like squash */
1872 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1874 * We're replacing the commit message so we need to
1875 * append the Signed-off-by: trailer if the user
1876 * requested '--signoff'.
1879 append_signoff(buf, 0, 0);
1881 if ((command == TODO_FIXUP) &&
1882 (flag & TODO_REPLACE_FIXUP_MSG) &&
1883 (file_exists(rebase_path_fixup_msg()) ||
1884 !file_exists(rebase_path_squash_msg()))) {
1885 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1886 if (write_message(fixup_msg, strlen(fixup_msg),
1887 rebase_path_fixup_msg(), 0) < 0)
1888 return error(_("cannot write '%s'"),
1889 rebase_path_fixup_msg());
1891 unlink(rebase_path_fixup_msg());
1894 unlink(rebase_path_fixup_msg());
1900 static int update_squash_messages(struct repository *r,
1901 enum todo_command command,
1902 struct commit *commit,
1903 struct replay_opts *opts,
1906 struct strbuf buf = STRBUF_INIT;
1908 const char *message, *body;
1909 const char *encoding = get_commit_output_encoding();
1911 if (opts->current_fixup_count > 0) {
1912 struct strbuf header = STRBUF_INIT;
1915 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1916 return error(_("could not read '%s'"),
1917 rebase_path_squash_msg());
1919 eol = buf.buf[0] != comment_line_char ?
1920 buf.buf : strchrnul(buf.buf, '\n');
1922 strbuf_addf(&header, "%c ", comment_line_char);
1923 strbuf_addf(&header, _(combined_commit_msg_fmt),
1924 opts->current_fixup_count + 2);
1925 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1926 strbuf_release(&header);
1927 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1928 update_squash_message_for_fixup(&buf);
1930 struct object_id head;
1931 struct commit *head_commit;
1932 const char *head_message, *body;
1934 if (get_oid("HEAD", &head))
1935 return error(_("need a HEAD to fixup"));
1936 if (!(head_commit = lookup_commit_reference(r, &head)))
1937 return error(_("could not read HEAD"));
1938 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1939 return error(_("could not read HEAD's commit message"));
1941 find_commit_subject(head_message, &body);
1942 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1943 rebase_path_fixup_msg(), 0) < 0) {
1944 unuse_commit_buffer(head_commit, head_message);
1945 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1947 strbuf_addf(&buf, "%c ", comment_line_char);
1948 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1949 strbuf_addf(&buf, "\n%c ", comment_line_char);
1950 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1951 _(skip_first_commit_msg_str) :
1952 _(first_commit_msg_str));
1953 strbuf_addstr(&buf, "\n\n");
1954 if (is_fixup_flag(command, flag))
1955 strbuf_add_commented_lines(&buf, body, strlen(body));
1957 strbuf_addstr(&buf, body);
1959 unuse_commit_buffer(head_commit, head_message);
1962 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1963 return error(_("could not read commit message of %s"),
1964 oid_to_hex(&commit->object.oid));
1965 find_commit_subject(message, &body);
1967 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1968 res = append_squash_message(&buf, body, command, opts, flag);
1969 } else if (command == TODO_FIXUP) {
1970 strbuf_addf(&buf, "\n%c ", comment_line_char);
1971 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1972 ++opts->current_fixup_count + 1);
1973 strbuf_addstr(&buf, "\n\n");
1974 strbuf_add_commented_lines(&buf, body, strlen(body));
1976 return error(_("unknown command: %d"), command);
1977 unuse_commit_buffer(commit, message);
1980 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1982 strbuf_release(&buf);
1985 strbuf_addf(&opts->current_fixups, "%s%s %s",
1986 opts->current_fixups.len ? "\n" : "",
1987 command_to_string(command),
1988 oid_to_hex(&commit->object.oid));
1989 res = write_message(opts->current_fixups.buf,
1990 opts->current_fixups.len,
1991 rebase_path_current_fixups(), 0);
1997 static void flush_rewritten_pending(void)
1999 struct strbuf buf = STRBUF_INIT;
2000 struct object_id newoid;
2003 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2004 !get_oid("HEAD", &newoid) &&
2005 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2006 char *bol = buf.buf, *eol;
2009 eol = strchrnul(bol, '\n');
2010 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2011 bol, oid_to_hex(&newoid));
2017 unlink(rebase_path_rewritten_pending());
2019 strbuf_release(&buf);
2022 static void record_in_rewritten(struct object_id *oid,
2023 enum todo_command next_command)
2025 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2030 fprintf(out, "%s\n", oid_to_hex(oid));
2033 if (!is_fixup(next_command))
2034 flush_rewritten_pending();
2037 static int should_edit(struct replay_opts *opts) {
2040 * Note that we only handle the case of non-conflicted
2041 * commits; continue_single_pick() handles the conflicted
2042 * commits itself instead of calling this function.
2044 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2048 static int do_pick_commit(struct repository *r,
2049 struct todo_item *item,
2050 struct replay_opts *opts,
2051 int final_fixup, int *check_todo)
2053 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2054 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2055 struct object_id head;
2056 struct commit *base, *next, *parent;
2057 const char *base_label, *next_label;
2058 char *author = NULL;
2059 struct commit_message msg = { NULL, NULL, NULL, NULL };
2060 struct strbuf msgbuf = STRBUF_INIT;
2061 int res, unborn = 0, reword = 0, allow, drop_commit;
2062 enum todo_command command = item->command;
2063 struct commit *commit = item->commit;
2065 if (opts->no_commit) {
2067 * We do not intend to commit immediately. We just want to
2068 * merge the differences in, so let's compute the tree
2069 * that represents the "current" state for merge-recursive
2072 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2073 return error(_("your index file is unmerged."));
2075 unborn = get_oid("HEAD", &head);
2076 /* Do we want to generate a root commit? */
2077 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2078 oideq(&head, &opts->squash_onto)) {
2079 if (is_fixup(command))
2080 return error(_("cannot fixup root commit"));
2081 flags |= CREATE_ROOT_COMMIT;
2084 oidcpy(&head, the_hash_algo->empty_tree);
2085 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2087 return error_dirty_index(r, opts);
2089 discard_index(r->index);
2091 if (!commit->parents)
2093 else if (commit->parents->next) {
2094 /* Reverting or cherry-picking a merge commit */
2096 struct commit_list *p;
2098 if (!opts->mainline)
2099 return error(_("commit %s is a merge but no -m option was given."),
2100 oid_to_hex(&commit->object.oid));
2102 for (cnt = 1, p = commit->parents;
2103 cnt != opts->mainline && p;
2106 if (cnt != opts->mainline || !p)
2107 return error(_("commit %s does not have parent %d"),
2108 oid_to_hex(&commit->object.oid), opts->mainline);
2110 } else if (1 < opts->mainline)
2112 * Non-first parent explicitly specified as mainline for
2115 return error(_("commit %s does not have parent %d"),
2116 oid_to_hex(&commit->object.oid), opts->mainline);
2118 parent = commit->parents->item;
2120 if (get_message(commit, &msg) != 0)
2121 return error(_("cannot get commit message for %s"),
2122 oid_to_hex(&commit->object.oid));
2124 if (opts->allow_ff && !is_fixup(command) &&
2125 ((parent && oideq(&parent->object.oid, &head)) ||
2126 (!parent && unborn))) {
2127 if (is_rebase_i(opts))
2128 write_author_script(msg.message);
2129 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2131 if (res || command != TODO_REWORD)
2135 goto fast_forward_edit;
2137 if (parent && parse_commit(parent) < 0)
2138 /* TRANSLATORS: The first %s will be a "todo" command like
2139 "revert" or "pick", the second %s a SHA1. */
2140 return error(_("%s: cannot parse parent commit %s"),
2141 command_to_string(command),
2142 oid_to_hex(&parent->object.oid));
2145 * "commit" is an existing commit. We would want to apply
2146 * the difference it introduces since its first parent "prev"
2147 * on top of the current HEAD if we are cherry-pick. Or the
2148 * reverse of it if we are revert.
2151 if (command == TODO_REVERT) {
2153 base_label = msg.label;
2155 next_label = msg.parent_label;
2156 strbuf_addstr(&msgbuf, "Revert \"");
2157 strbuf_addstr(&msgbuf, msg.subject);
2158 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2159 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2161 if (commit->parents && commit->parents->next) {
2162 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2163 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2165 strbuf_addstr(&msgbuf, ".\n");
2170 base_label = msg.parent_label;
2172 next_label = msg.label;
2174 /* Append the commit log message to msgbuf. */
2175 if (find_commit_subject(msg.message, &p))
2176 strbuf_addstr(&msgbuf, p);
2178 if (opts->record_origin) {
2179 strbuf_complete_line(&msgbuf);
2180 if (!has_conforming_footer(&msgbuf, NULL, 0))
2181 strbuf_addch(&msgbuf, '\n');
2182 strbuf_addstr(&msgbuf, cherry_picked_prefix);
2183 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2184 strbuf_addstr(&msgbuf, ")\n");
2186 if (!is_fixup(command))
2187 author = get_author(msg.message);
2190 if (command == TODO_REWORD)
2192 else if (is_fixup(command)) {
2193 if (update_squash_messages(r, command, commit,
2198 msg_file = rebase_path_squash_msg();
2199 else if (file_exists(rebase_path_fixup_msg())) {
2200 flags |= VERBATIM_MSG;
2201 msg_file = rebase_path_fixup_msg();
2203 const char *dest = git_path_squash_msg(r);
2205 if (copy_file(dest, rebase_path_squash_msg(), 0666))
2206 return error(_("could not rename '%s' to '%s'"),
2207 rebase_path_squash_msg(), dest);
2208 unlink(git_path_merge_msg(r));
2214 if (opts->signoff && !is_fixup(command))
2215 append_signoff(&msgbuf, 0, 0);
2217 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2219 else if (!opts->strategy ||
2220 !strcmp(opts->strategy, "recursive") ||
2221 !strcmp(opts->strategy, "ort") ||
2222 command == TODO_REVERT) {
2223 res = do_recursive_merge(r, base, next, base_label, next_label,
2224 &head, &msgbuf, opts);
2228 res |= write_message(msgbuf.buf, msgbuf.len,
2229 git_path_merge_msg(r), 0);
2231 struct commit_list *common = NULL;
2232 struct commit_list *remotes = NULL;
2234 res = write_message(msgbuf.buf, msgbuf.len,
2235 git_path_merge_msg(r), 0);
2237 commit_list_insert(base, &common);
2238 commit_list_insert(next, &remotes);
2239 res |= try_merge_command(r, opts->strategy,
2240 opts->xopts_nr, (const char **)opts->xopts,
2241 common, oid_to_hex(&head), remotes);
2242 free_commit_list(common);
2243 free_commit_list(remotes);
2245 strbuf_release(&msgbuf);
2248 * If the merge was clean or if it failed due to conflict, we write
2249 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2250 * However, if the merge did not even start, then we don't want to
2253 if ((command == TODO_PICK || command == TODO_REWORD ||
2254 command == TODO_EDIT) && !opts->no_commit &&
2255 (res == 0 || res == 1) &&
2256 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2257 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2259 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2260 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2261 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2265 error(command == TODO_REVERT
2266 ? _("could not revert %s... %s")
2267 : _("could not apply %s... %s"),
2268 short_commit_name(commit), msg.subject);
2269 print_advice(r, res == 1, opts);
2270 repo_rerere(r, opts->allow_rerere_auto);
2275 allow = allow_empty(r, opts, commit);
2279 } else if (allow == 1) {
2280 flags |= ALLOW_EMPTY;
2281 } else if (allow == 2) {
2283 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2285 unlink(git_path_merge_msg(r));
2286 unlink(git_path_auto_merge(r));
2288 _("dropping %s %s -- patch contents already upstream\n"),
2289 oid_to_hex(&commit->object.oid), msg.subject);
2290 } /* else allow == 0 and there's nothing special to do */
2291 if (!opts->no_commit && !drop_commit) {
2292 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2293 res = do_commit(r, msg_file, author, opts, flags,
2294 commit? &commit->object.oid : NULL);
2296 res = error(_("unable to parse commit author"));
2297 *check_todo = !!(flags & EDIT_MSG);
2298 if (!res && reword) {
2300 res = run_git_commit(NULL, opts, EDIT_MSG |
2301 VERIFY_MSG | AMEND_MSG |
2302 (flags & ALLOW_EMPTY));
2308 if (!res && final_fixup) {
2309 unlink(rebase_path_fixup_msg());
2310 unlink(rebase_path_squash_msg());
2311 unlink(rebase_path_current_fixups());
2312 strbuf_reset(&opts->current_fixups);
2313 opts->current_fixup_count = 0;
2317 free_message(commit, &msg);
2319 update_abort_safety_file();
2324 static int prepare_revs(struct replay_opts *opts)
2327 * picking (but not reverting) ranges (but not individual revisions)
2328 * should be done in reverse
2330 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2331 opts->revs->reverse ^= 1;
2333 if (prepare_revision_walk(opts->revs))
2334 return error(_("revision walk setup failed"));
2339 static int read_and_refresh_cache(struct repository *r,
2340 struct replay_opts *opts)
2342 struct lock_file index_lock = LOCK_INIT;
2343 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2344 if (repo_read_index(r) < 0) {
2345 rollback_lock_file(&index_lock);
2346 return error(_("git %s: failed to read the index"),
2347 _(action_name(opts)));
2349 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2350 if (index_fd >= 0) {
2351 if (write_locked_index(r->index, &index_lock,
2352 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2353 return error(_("git %s: failed to refresh the index"),
2354 _(action_name(opts)));
2360 void todo_list_release(struct todo_list *todo_list)
2362 strbuf_release(&todo_list->buf);
2363 FREE_AND_NULL(todo_list->items);
2364 todo_list->nr = todo_list->alloc = 0;
2367 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2369 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2370 todo_list->total_nr++;
2371 return todo_list->items + todo_list->nr++;
2374 const char *todo_item_get_arg(struct todo_list *todo_list,
2375 struct todo_item *item)
2377 return todo_list->buf.buf + item->arg_offset;
2380 static int is_command(enum todo_command command, const char **bol)
2382 const char *str = todo_command_info[command].str;
2383 const char nick = todo_command_info[command].c;
2384 const char *p = *bol + 1;
2386 return skip_prefix(*bol, str, bol) ||
2387 ((nick && **bol == nick) &&
2388 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2392 static int parse_insn_line(struct repository *r, struct todo_item *item,
2393 const char *buf, const char *bol, char *eol)
2395 struct object_id commit_oid;
2396 char *end_of_object_name;
2397 int i, saved, status, padding;
2402 bol += strspn(bol, " \t");
2404 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2405 item->command = TODO_COMMENT;
2406 item->commit = NULL;
2407 item->arg_offset = bol - buf;
2408 item->arg_len = eol - bol;
2412 for (i = 0; i < TODO_COMMENT; i++)
2413 if (is_command(i, &bol)) {
2417 if (i >= TODO_COMMENT)
2420 /* Eat up extra spaces/ tabs before object name */
2421 padding = strspn(bol, " \t");
2424 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2426 return error(_("%s does not accept arguments: '%s'"),
2427 command_to_string(item->command), bol);
2428 item->commit = NULL;
2429 item->arg_offset = bol - buf;
2430 item->arg_len = eol - bol;
2435 return error(_("missing arguments for %s"),
2436 command_to_string(item->command));
2438 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2439 item->command == TODO_RESET) {
2440 item->commit = NULL;
2441 item->arg_offset = bol - buf;
2442 item->arg_len = (int)(eol - bol);
2446 if (item->command == TODO_FIXUP) {
2447 if (skip_prefix(bol, "-C", &bol) &&
2448 (*bol == ' ' || *bol == '\t')) {
2449 bol += strspn(bol, " \t");
2450 item->flags |= TODO_REPLACE_FIXUP_MSG;
2451 } else if (skip_prefix(bol, "-c", &bol) &&
2452 (*bol == ' ' || *bol == '\t')) {
2453 bol += strspn(bol, " \t");
2454 item->flags |= TODO_EDIT_FIXUP_MSG;
2458 if (item->command == TODO_MERGE) {
2459 if (skip_prefix(bol, "-C", &bol))
2460 bol += strspn(bol, " \t");
2461 else if (skip_prefix(bol, "-c", &bol)) {
2462 bol += strspn(bol, " \t");
2463 item->flags |= TODO_EDIT_MERGE_MSG;
2465 item->flags |= TODO_EDIT_MERGE_MSG;
2466 item->commit = NULL;
2467 item->arg_offset = bol - buf;
2468 item->arg_len = (int)(eol - bol);
2473 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2474 saved = *end_of_object_name;
2475 *end_of_object_name = '\0';
2476 status = get_oid(bol, &commit_oid);
2478 error(_("could not parse '%s'"), bol); /* return later */
2479 *end_of_object_name = saved;
2481 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2482 item->arg_offset = bol - buf;
2483 item->arg_len = (int)(eol - bol);
2488 item->commit = lookup_commit_reference(r, &commit_oid);
2489 return item->commit ? 0 : -1;
2492 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2494 const char *todo_file, *bol;
2495 struct strbuf buf = STRBUF_INIT;
2498 todo_file = git_path_todo_file();
2499 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2500 if (errno == ENOENT || errno == ENOTDIR)
2503 return error_errno("unable to open '%s'", todo_file);
2505 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2506 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2507 *action = REPLAY_PICK;
2508 else if (is_command(TODO_REVERT, &bol) &&
2509 (*bol == ' ' || *bol == '\t'))
2510 *action = REPLAY_REVERT;
2514 strbuf_release(&buf);
2519 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2520 struct todo_list *todo_list)
2522 struct todo_item *item;
2523 char *p = buf, *next_p;
2524 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2526 todo_list->current = todo_list->nr = 0;
2528 for (i = 1; *p; i++, p = next_p) {
2529 char *eol = strchrnul(p, '\n');
2531 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2533 if (p != eol && eol[-1] == '\r')
2534 eol--; /* strip Carriage Return */
2536 item = append_new_todo(todo_list);
2537 item->offset_in_buf = p - todo_list->buf.buf;
2538 if (parse_insn_line(r, item, buf, p, eol)) {
2539 res = error(_("invalid line %d: %.*s"),
2540 i, (int)(eol - p), p);
2541 item->command = TODO_COMMENT + 1;
2542 item->arg_offset = p - buf;
2543 item->arg_len = (int)(eol - p);
2544 item->commit = NULL;
2549 else if (is_fixup(item->command))
2550 return error(_("cannot '%s' without a previous commit"),
2551 command_to_string(item->command));
2552 else if (!is_noop(item->command))
2559 static int count_commands(struct todo_list *todo_list)
2563 for (i = 0; i < todo_list->nr; i++)
2564 if (todo_list->items[i].command != TODO_COMMENT)
2570 static int get_item_line_offset(struct todo_list *todo_list, int index)
2572 return index < todo_list->nr ?
2573 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2576 static const char *get_item_line(struct todo_list *todo_list, int index)
2578 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2581 static int get_item_line_length(struct todo_list *todo_list, int index)
2583 return get_item_line_offset(todo_list, index + 1)
2584 - get_item_line_offset(todo_list, index);
2587 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2592 fd = open(path, O_RDONLY);
2594 return error_errno(_("could not open '%s'"), path);
2595 len = strbuf_read(sb, fd, 0);
2598 return error(_("could not read '%s'."), path);
2602 static int have_finished_the_last_pick(void)
2604 struct strbuf buf = STRBUF_INIT;
2606 const char *todo_path = git_path_todo_file();
2609 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2610 if (errno == ENOENT) {
2613 error_errno("unable to open '%s'", todo_path);
2617 /* If there is only one line then we are done */
2618 eol = strchr(buf.buf, '\n');
2619 if (!eol || !eol[1])
2622 strbuf_release(&buf);
2627 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2629 struct replay_opts opts = REPLAY_OPTS_INIT;
2630 int need_cleanup = 0;
2632 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2633 if (!refs_delete_ref(get_main_ref_store(r), "",
2634 "CHERRY_PICK_HEAD", NULL, 0) &&
2636 warning(_("cancelling a cherry picking in progress"));
2637 opts.action = REPLAY_PICK;
2641 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2642 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2645 warning(_("cancelling a revert in progress"));
2646 opts.action = REPLAY_REVERT;
2650 unlink(git_path_auto_merge(r));
2655 if (!have_finished_the_last_pick())
2658 sequencer_remove_state(&opts);
2661 static void todo_list_write_total_nr(struct todo_list *todo_list)
2663 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2666 fprintf(f, "%d\n", todo_list->total_nr);
2671 static int read_populate_todo(struct repository *r,
2672 struct todo_list *todo_list,
2673 struct replay_opts *opts)
2676 const char *todo_file = get_todo_path(opts);
2679 strbuf_reset(&todo_list->buf);
2680 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2683 res = stat(todo_file, &st);
2685 return error(_("could not stat '%s'"), todo_file);
2686 fill_stat_data(&todo_list->stat, &st);
2688 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2690 if (is_rebase_i(opts))
2691 return error(_("please fix this using "
2692 "'git rebase --edit-todo'."));
2693 return error(_("unusable instruction sheet: '%s'"), todo_file);
2696 if (!todo_list->nr &&
2697 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2698 return error(_("no commits parsed."));
2700 if (!is_rebase_i(opts)) {
2701 enum todo_command valid =
2702 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2705 for (i = 0; i < todo_list->nr; i++)
2706 if (valid == todo_list->items[i].command)
2708 else if (valid == TODO_PICK)
2709 return error(_("cannot cherry-pick during a revert."));
2711 return error(_("cannot revert during a cherry-pick."));
2714 if (is_rebase_i(opts)) {
2715 struct todo_list done = TODO_LIST_INIT;
2717 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2718 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2719 todo_list->done_nr = count_commands(&done);
2721 todo_list->done_nr = 0;
2723 todo_list->total_nr = todo_list->done_nr
2724 + count_commands(todo_list);
2725 todo_list_release(&done);
2727 todo_list_write_total_nr(todo_list);
2733 static int git_config_string_dup(char **dest,
2734 const char *var, const char *value)
2737 return config_error_nonbool(var);
2739 *dest = xstrdup(value);
2743 static int populate_opts_cb(const char *key, const char *value, void *data)
2745 struct replay_opts *opts = data;
2750 else if (!strcmp(key, "options.no-commit"))
2751 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2752 else if (!strcmp(key, "options.edit"))
2753 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2754 else if (!strcmp(key, "options.allow-empty"))
2756 git_config_bool_or_int(key, value, &error_flag);
2757 else if (!strcmp(key, "options.allow-empty-message"))
2758 opts->allow_empty_message =
2759 git_config_bool_or_int(key, value, &error_flag);
2760 else if (!strcmp(key, "options.keep-redundant-commits"))
2761 opts->keep_redundant_commits =
2762 git_config_bool_or_int(key, value, &error_flag);
2763 else if (!strcmp(key, "options.signoff"))
2764 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2765 else if (!strcmp(key, "options.record-origin"))
2766 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2767 else if (!strcmp(key, "options.allow-ff"))
2768 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2769 else if (!strcmp(key, "options.mainline"))
2770 opts->mainline = git_config_int(key, value);
2771 else if (!strcmp(key, "options.strategy"))
2772 git_config_string_dup(&opts->strategy, key, value);
2773 else if (!strcmp(key, "options.gpg-sign"))
2774 git_config_string_dup(&opts->gpg_sign, key, value);
2775 else if (!strcmp(key, "options.strategy-option")) {
2776 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2777 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2778 } else if (!strcmp(key, "options.allow-rerere-auto"))
2779 opts->allow_rerere_auto =
2780 git_config_bool_or_int(key, value, &error_flag) ?
2781 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2782 else if (!strcmp(key, "options.default-msg-cleanup")) {
2783 opts->explicit_cleanup = 1;
2784 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2786 return error(_("invalid key: %s"), key);
2789 return error(_("invalid value for %s: %s"), key, value);
2794 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2797 char *strategy_opts_string = raw_opts;
2799 if (*strategy_opts_string == ' ')
2800 strategy_opts_string++;
2802 opts->xopts_nr = split_cmdline(strategy_opts_string,
2803 (const char ***)&opts->xopts);
2804 for (i = 0; i < opts->xopts_nr; i++) {
2805 const char *arg = opts->xopts[i];
2807 skip_prefix(arg, "--", &arg);
2808 opts->xopts[i] = xstrdup(arg);
2812 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2815 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2817 opts->strategy = strbuf_detach(buf, NULL);
2818 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2821 parse_strategy_opts(opts, buf->buf);
2824 static int read_populate_opts(struct replay_opts *opts)
2826 if (is_rebase_i(opts)) {
2827 struct strbuf buf = STRBUF_INIT;
2830 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2831 READ_ONELINER_SKIP_IF_EMPTY)) {
2832 if (!starts_with(buf.buf, "-S"))
2835 free(opts->gpg_sign);
2836 opts->gpg_sign = xstrdup(buf.buf + 2);
2841 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2842 READ_ONELINER_SKIP_IF_EMPTY)) {
2843 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2844 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2845 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2846 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2850 if (file_exists(rebase_path_verbose()))
2853 if (file_exists(rebase_path_quiet()))
2856 if (file_exists(rebase_path_signoff())) {
2861 if (file_exists(rebase_path_cdate_is_adate())) {
2863 opts->committer_date_is_author_date = 1;
2866 if (file_exists(rebase_path_ignore_date())) {
2868 opts->ignore_date = 1;
2871 if (file_exists(rebase_path_reschedule_failed_exec()))
2872 opts->reschedule_failed_exec = 1;
2873 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2874 opts->reschedule_failed_exec = 0;
2876 if (file_exists(rebase_path_drop_redundant_commits()))
2877 opts->drop_redundant_commits = 1;
2879 if (file_exists(rebase_path_keep_redundant_commits()))
2880 opts->keep_redundant_commits = 1;
2882 read_strategy_opts(opts, &buf);
2885 if (read_oneliner(&opts->current_fixups,
2886 rebase_path_current_fixups(),
2887 READ_ONELINER_SKIP_IF_EMPTY)) {
2888 const char *p = opts->current_fixups.buf;
2889 opts->current_fixup_count = 1;
2890 while ((p = strchr(p, '\n'))) {
2891 opts->current_fixup_count++;
2896 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2897 if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2898 ret = error(_("unusable squash-onto"));
2901 opts->have_squash_onto = 1;
2905 strbuf_release(&buf);
2909 if (!file_exists(git_path_opts_file()))
2912 * The function git_parse_source(), called from git_config_from_file(),
2913 * may die() in case of a syntactically incorrect file. We do not care
2914 * about this case, though, because we wrote that file ourselves, so we
2915 * are pretty certain that it is syntactically correct.
2917 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2918 return error(_("malformed options sheet: '%s'"),
2919 git_path_opts_file());
2923 static void write_strategy_opts(struct replay_opts *opts)
2926 struct strbuf buf = STRBUF_INIT;
2928 for (i = 0; i < opts->xopts_nr; ++i)
2929 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2931 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2932 strbuf_release(&buf);
2935 int write_basic_state(struct replay_opts *opts, const char *head_name,
2936 struct commit *onto, const struct object_id *orig_head)
2939 write_file(rebase_path_head_name(), "%s\n", head_name);
2941 write_file(rebase_path_onto(), "%s\n",
2942 oid_to_hex(&onto->object.oid));
2944 write_file(rebase_path_orig_head(), "%s\n",
2945 oid_to_hex(orig_head));
2948 write_file(rebase_path_quiet(), "%s", "");
2950 write_file(rebase_path_verbose(), "%s", "");
2952 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2953 if (opts->xopts_nr > 0)
2954 write_strategy_opts(opts);
2956 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2957 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2958 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2959 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2962 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2964 write_file(rebase_path_signoff(), "--signoff\n");
2965 if (opts->drop_redundant_commits)
2966 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2967 if (opts->keep_redundant_commits)
2968 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2969 if (opts->committer_date_is_author_date)
2970 write_file(rebase_path_cdate_is_adate(), "%s", "");
2971 if (opts->ignore_date)
2972 write_file(rebase_path_ignore_date(), "%s", "");
2973 if (opts->reschedule_failed_exec)
2974 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2976 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2981 static int walk_revs_populate_todo(struct todo_list *todo_list,
2982 struct replay_opts *opts)
2984 enum todo_command command = opts->action == REPLAY_PICK ?
2985 TODO_PICK : TODO_REVERT;
2986 const char *command_string = todo_command_info[command].str;
2987 const char *encoding;
2988 struct commit *commit;
2990 if (prepare_revs(opts))
2993 encoding = get_log_output_encoding();
2995 while ((commit = get_revision(opts->revs))) {
2996 struct todo_item *item = append_new_todo(todo_list);
2997 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2998 const char *subject;
3001 item->command = command;
3002 item->commit = commit;
3003 item->arg_offset = 0;
3005 item->offset_in_buf = todo_list->buf.len;
3006 subject_len = find_commit_subject(commit_buffer, &subject);
3007 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3008 short_commit_name(commit), subject_len, subject);
3009 unuse_commit_buffer(commit, commit_buffer);
3013 return error(_("empty commit set passed"));
3018 static int create_seq_dir(struct repository *r)
3020 enum replay_action action;
3021 const char *in_progress_error = NULL;
3022 const char *in_progress_advice = NULL;
3023 unsigned int advise_skip =
3024 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3025 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3027 if (!sequencer_get_last_command(r, &action)) {
3030 in_progress_error = _("revert is already in progress");
3031 in_progress_advice =
3032 _("try \"git revert (--continue | %s--abort | --quit)\"");
3035 in_progress_error = _("cherry-pick is already in progress");
3036 in_progress_advice =
3037 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3040 BUG("unexpected action in create_seq_dir");
3043 if (in_progress_error) {
3044 error("%s", in_progress_error);
3045 if (advice_sequencer_in_use)
3046 advise(in_progress_advice,
3047 advise_skip ? "--skip | " : "");
3050 if (mkdir(git_path_seq_dir(), 0777) < 0)
3051 return error_errno(_("could not create sequencer directory '%s'"),
3052 git_path_seq_dir());
3057 static int save_head(const char *head)
3059 struct lock_file head_lock = LOCK_INIT;
3060 struct strbuf buf = STRBUF_INIT;
3064 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3066 return error_errno(_("could not lock HEAD"));
3067 strbuf_addf(&buf, "%s\n", head);
3068 written = write_in_full(fd, buf.buf, buf.len);
3069 strbuf_release(&buf);
3071 error_errno(_("could not write to '%s'"), git_path_head_file());
3072 rollback_lock_file(&head_lock);
3075 if (commit_lock_file(&head_lock) < 0)
3076 return error(_("failed to finalize '%s'"), git_path_head_file());
3080 static int rollback_is_safe(void)
3082 struct strbuf sb = STRBUF_INIT;
3083 struct object_id expected_head, actual_head;
3085 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3087 if (get_oid_hex(sb.buf, &expected_head)) {
3088 strbuf_release(&sb);
3089 die(_("could not parse %s"), git_path_abort_safety_file());
3091 strbuf_release(&sb);
3093 else if (errno == ENOENT)
3094 oidclr(&expected_head);
3096 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3098 if (get_oid("HEAD", &actual_head))
3099 oidclr(&actual_head);
3101 return oideq(&actual_head, &expected_head);
3104 static int reset_merge(const struct object_id *oid)
3107 struct strvec argv = STRVEC_INIT;
3109 strvec_pushl(&argv, "reset", "--merge", NULL);
3111 if (!is_null_oid(oid))
3112 strvec_push(&argv, oid_to_hex(oid));
3114 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3115 strvec_clear(&argv);
3120 static int rollback_single_pick(struct repository *r)
3122 struct object_id head_oid;
3124 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3125 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3126 return error(_("no cherry-pick or revert in progress"));
3127 if (read_ref_full("HEAD", 0, &head_oid, NULL))
3128 return error(_("cannot resolve HEAD"));
3129 if (is_null_oid(&head_oid))
3130 return error(_("cannot abort from a branch yet to be born"));
3131 return reset_merge(&head_oid);
3134 static int skip_single_pick(void)
3136 struct object_id head;
3138 if (read_ref_full("HEAD", 0, &head, NULL))
3139 return error(_("cannot resolve HEAD"));
3140 return reset_merge(&head);
3143 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3146 struct object_id oid;
3147 struct strbuf buf = STRBUF_INIT;
3150 f = fopen(git_path_head_file(), "r");
3151 if (!f && errno == ENOENT) {
3153 * There is no multiple-cherry-pick in progress.
3154 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3155 * a single-cherry-pick in progress, abort that.
3157 return rollback_single_pick(r);
3160 return error_errno(_("cannot open '%s'"), git_path_head_file());
3161 if (strbuf_getline_lf(&buf, f)) {
3162 error(_("cannot read '%s': %s"), git_path_head_file(),
3163 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3168 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3169 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3170 git_path_head_file());
3173 if (is_null_oid(&oid)) {
3174 error(_("cannot abort from a branch yet to be born"));
3178 if (!rollback_is_safe()) {
3179 /* Do not error, just do not rollback */
3180 warning(_("You seem to have moved HEAD. "
3181 "Not rewinding, check your HEAD!"));
3183 if (reset_merge(&oid))
3185 strbuf_release(&buf);
3186 return sequencer_remove_state(opts);
3188 strbuf_release(&buf);
3192 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3194 enum replay_action action = -1;
3195 sequencer_get_last_command(r, &action);
3198 * Check whether the subcommand requested to skip the commit is actually
3199 * in progress and that it's safe to skip the commit.
3201 * opts->action tells us which subcommand requested to skip the commit.
3202 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3203 * action is in progress and we can skip the commit.
3205 * Otherwise we check that the last instruction was related to the
3206 * particular subcommand we're trying to execute and barf if that's not
3209 * Finally we check that the rollback is "safe", i.e., has the HEAD
3210 * moved? In this case, it doesn't make sense to "reset the merge" and
3211 * "skip the commit" as the user already handled this by committing. But
3212 * we'd not want to barf here, instead give advice on how to proceed. We
3213 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3214 * it gets removed when the user commits, so if it still exists we're
3215 * sure the user can't have committed before.
3217 switch (opts->action) {
3219 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3220 if (action != REPLAY_REVERT)
3221 return error(_("no revert in progress"));
3222 if (!rollback_is_safe())
3227 if (!refs_ref_exists(get_main_ref_store(r),
3228 "CHERRY_PICK_HEAD")) {
3229 if (action != REPLAY_PICK)
3230 return error(_("no cherry-pick in progress"));
3231 if (!rollback_is_safe())
3236 BUG("unexpected action in sequencer_skip");
3239 if (skip_single_pick())
3240 return error(_("failed to skip the commit"));
3241 if (!is_directory(git_path_seq_dir()))
3244 return sequencer_continue(r, opts);
3247 error(_("there is nothing to skip"));
3249 if (advice_resolve_conflict) {
3250 advise(_("have you committed already?\n"
3251 "try \"git %s --continue\""),
3252 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3257 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3259 struct lock_file todo_lock = LOCK_INIT;
3260 const char *todo_path = get_todo_path(opts);
3261 int next = todo_list->current, offset, fd;
3264 * rebase -i writes "git-rebase-todo" without the currently executing
3265 * command, appending it to "done" instead.
3267 if (is_rebase_i(opts))
3270 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3272 return error_errno(_("could not lock '%s'"), todo_path);
3273 offset = get_item_line_offset(todo_list, next);
3274 if (write_in_full(fd, todo_list->buf.buf + offset,
3275 todo_list->buf.len - offset) < 0)
3276 return error_errno(_("could not write to '%s'"), todo_path);
3277 if (commit_lock_file(&todo_lock) < 0)
3278 return error(_("failed to finalize '%s'"), todo_path);
3280 if (is_rebase_i(opts) && next > 0) {
3281 const char *done = rebase_path_done();
3282 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3287 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3288 get_item_line_length(todo_list, next - 1))
3290 ret = error_errno(_("could not write to '%s'"), done);
3292 ret = error_errno(_("failed to finalize '%s'"), done);
3298 static int save_opts(struct replay_opts *opts)
3300 const char *opts_file = git_path_opts_file();
3303 if (opts->no_commit)
3304 res |= git_config_set_in_file_gently(opts_file,
3305 "options.no-commit", "true");
3306 if (opts->edit >= 0)
3307 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3308 opts->edit ? "true" : "false");
3309 if (opts->allow_empty)
3310 res |= git_config_set_in_file_gently(opts_file,
3311 "options.allow-empty", "true");
3312 if (opts->allow_empty_message)
3313 res |= git_config_set_in_file_gently(opts_file,
3314 "options.allow-empty-message", "true");
3315 if (opts->keep_redundant_commits)
3316 res |= git_config_set_in_file_gently(opts_file,
3317 "options.keep-redundant-commits", "true");
3319 res |= git_config_set_in_file_gently(opts_file,
3320 "options.signoff", "true");
3321 if (opts->record_origin)
3322 res |= git_config_set_in_file_gently(opts_file,
3323 "options.record-origin", "true");
3325 res |= git_config_set_in_file_gently(opts_file,
3326 "options.allow-ff", "true");
3327 if (opts->mainline) {
3328 struct strbuf buf = STRBUF_INIT;
3329 strbuf_addf(&buf, "%d", opts->mainline);
3330 res |= git_config_set_in_file_gently(opts_file,
3331 "options.mainline", buf.buf);
3332 strbuf_release(&buf);
3335 res |= git_config_set_in_file_gently(opts_file,
3336 "options.strategy", opts->strategy);
3338 res |= git_config_set_in_file_gently(opts_file,
3339 "options.gpg-sign", opts->gpg_sign);
3342 for (i = 0; i < opts->xopts_nr; i++)
3343 res |= git_config_set_multivar_in_file_gently(opts_file,
3344 "options.strategy-option",
3345 opts->xopts[i], "^$", 0);
3347 if (opts->allow_rerere_auto)
3348 res |= git_config_set_in_file_gently(opts_file,
3349 "options.allow-rerere-auto",
3350 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3353 if (opts->explicit_cleanup)
3354 res |= git_config_set_in_file_gently(opts_file,
3355 "options.default-msg-cleanup",
3356 describe_cleanup_mode(opts->default_msg_cleanup));
3360 static int make_patch(struct repository *r,
3361 struct commit *commit,
3362 struct replay_opts *opts)
3364 struct strbuf buf = STRBUF_INIT;
3365 struct rev_info log_tree_opt;
3366 const char *subject;
3367 char hex[GIT_MAX_HEXSZ + 1];
3370 oid_to_hex_r(hex, &commit->object.oid);
3371 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3373 res |= write_rebase_head(&commit->object.oid);
3375 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3376 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3377 repo_init_revisions(r, &log_tree_opt, NULL);
3378 log_tree_opt.abbrev = 0;
3379 log_tree_opt.diff = 1;
3380 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3381 log_tree_opt.disable_stdin = 1;
3382 log_tree_opt.no_commit_id = 1;
3383 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3384 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3385 if (!log_tree_opt.diffopt.file)
3386 res |= error_errno(_("could not open '%s'"), buf.buf);
3388 res |= log_tree_commit(&log_tree_opt, commit);
3389 fclose(log_tree_opt.diffopt.file);
3393 strbuf_addf(&buf, "%s/message", get_dir(opts));
3394 if (!file_exists(buf.buf)) {
3395 const char *encoding = get_commit_output_encoding();
3396 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3397 find_commit_subject(commit_buffer, &subject);
3398 res |= write_message(subject, strlen(subject), buf.buf, 1);
3399 unuse_commit_buffer(commit, commit_buffer);
3401 strbuf_release(&buf);
3406 static int intend_to_amend(void)
3408 struct object_id head;
3411 if (get_oid("HEAD", &head))
3412 return error(_("cannot read HEAD"));
3414 p = oid_to_hex(&head);
3415 return write_message(p, strlen(p), rebase_path_amend(), 1);
3418 static int error_with_patch(struct repository *r,
3419 struct commit *commit,
3420 const char *subject, int subject_len,
3421 struct replay_opts *opts,
3422 int exit_code, int to_amend)
3425 if (make_patch(r, commit, opts))
3427 } else if (copy_file(rebase_path_message(),
3428 git_path_merge_msg(r), 0666))
3429 return error(_("unable to copy '%s' to '%s'"),
3430 git_path_merge_msg(r), rebase_path_message());
3433 if (intend_to_amend())
3437 _("You can amend the commit now, with\n"
3439 " git commit --amend %s\n"
3441 "Once you are satisfied with your changes, run\n"
3443 " git rebase --continue\n"),
3444 gpg_sign_opt_quoted(opts));
3445 } else if (exit_code) {
3447 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3448 short_commit_name(commit), subject_len, subject);
3451 * We don't have the hash of the parent so
3452 * just print the line from the todo file.
3454 fprintf_ln(stderr, _("Could not merge %.*s"),
3455 subject_len, subject);
3461 static int error_failed_squash(struct repository *r,
3462 struct commit *commit,
3463 struct replay_opts *opts,
3465 const char *subject)
3467 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3468 return error(_("could not copy '%s' to '%s'"),
3469 rebase_path_squash_msg(), rebase_path_message());
3470 unlink(git_path_merge_msg(r));
3471 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3472 return error(_("could not copy '%s' to '%s'"),
3473 rebase_path_message(),
3474 git_path_merge_msg(r));
3475 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3478 static int do_exec(struct repository *r, const char *command_line)
3480 struct strvec child_env = STRVEC_INIT;
3481 const char *child_argv[] = { NULL, NULL };
3484 fprintf(stderr, _("Executing: %s\n"), command_line);
3485 child_argv[0] = command_line;
3486 strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3487 strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3488 absolute_path(get_git_work_tree()));
3489 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3492 /* force re-reading of the cache */
3493 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3494 return error(_("could not read index"));
3496 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3499 warning(_("execution failed: %s\n%s"
3500 "You can fix the problem, and then run\n"
3502 " git rebase --continue\n"
3505 dirty ? N_("and made changes to the index and/or the "
3506 "working tree\n") : "");
3508 /* command not found */
3511 warning(_("execution succeeded: %s\nbut "
3512 "left changes to the index and/or the working tree\n"
3513 "Commit or stash your changes, and then run\n"
3515 " git rebase --continue\n"
3516 "\n"), command_line);
3520 strvec_clear(&child_env);
3525 static int safe_append(const char *filename, const char *fmt, ...)
3528 struct lock_file lock = LOCK_INIT;
3529 int fd = hold_lock_file_for_update(&lock, filename,
3530 LOCK_REPORT_ON_ERROR);
3531 struct strbuf buf = STRBUF_INIT;
3536 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3537 error_errno(_("could not read '%s'"), filename);
3538 rollback_lock_file(&lock);
3541 strbuf_complete(&buf, '\n');
3543 strbuf_vaddf(&buf, fmt, ap);
3546 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3547 error_errno(_("could not write to '%s'"), filename);
3548 strbuf_release(&buf);
3549 rollback_lock_file(&lock);
3552 if (commit_lock_file(&lock) < 0) {
3553 strbuf_release(&buf);
3554 rollback_lock_file(&lock);
3555 return error(_("failed to finalize '%s'"), filename);
3558 strbuf_release(&buf);
3562 static int do_label(struct repository *r, const char *name, int len)
3564 struct ref_store *refs = get_main_ref_store(r);
3565 struct ref_transaction *transaction;
3566 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3567 struct strbuf msg = STRBUF_INIT;
3569 struct object_id head_oid;
3571 if (len == 1 && *name == '#')
3572 return error(_("illegal label name: '%.*s'"), len, name);
3574 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3575 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3577 transaction = ref_store_transaction_begin(refs, &err);
3579 error("%s", err.buf);
3581 } else if (get_oid("HEAD", &head_oid)) {
3582 error(_("could not read HEAD"));
3584 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3585 NULL, 0, msg.buf, &err) < 0 ||
3586 ref_transaction_commit(transaction, &err)) {
3587 error("%s", err.buf);
3590 ref_transaction_free(transaction);
3591 strbuf_release(&err);
3592 strbuf_release(&msg);
3595 ret = safe_append(rebase_path_refs_to_delete(),
3596 "%s\n", ref_name.buf);
3597 strbuf_release(&ref_name);
3602 static const char *reflog_message(struct replay_opts *opts,
3603 const char *sub_action, const char *fmt, ...);
3605 static int do_reset(struct repository *r,
3606 const char *name, int len,
3607 struct replay_opts *opts)
3609 struct strbuf ref_name = STRBUF_INIT;
3610 struct object_id oid;
3611 struct lock_file lock = LOCK_INIT;
3612 struct tree_desc desc;
3614 struct unpack_trees_options unpack_tree_opts;
3617 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3620 if (len == 10 && !strncmp("[new root]", name, len)) {
3621 if (!opts->have_squash_onto) {
3623 if (commit_tree("", 0, the_hash_algo->empty_tree,
3624 NULL, &opts->squash_onto,
3626 return error(_("writing fake root commit"));
3627 opts->have_squash_onto = 1;
3628 hex = oid_to_hex(&opts->squash_onto);
3629 if (write_message(hex, strlen(hex),
3630 rebase_path_squash_onto(), 0))
3631 return error(_("writing squash-onto"));
3633 oidcpy(&oid, &opts->squash_onto);
3637 /* Determine the length of the label */
3638 for (i = 0; i < len; i++)
3639 if (isspace(name[i]))
3643 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3644 if (get_oid(ref_name.buf, &oid) &&
3645 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3646 error(_("could not read '%s'"), ref_name.buf);
3647 rollback_lock_file(&lock);
3648 strbuf_release(&ref_name);
3653 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3654 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3655 unpack_tree_opts.head_idx = 1;
3656 unpack_tree_opts.src_index = r->index;
3657 unpack_tree_opts.dst_index = r->index;
3658 unpack_tree_opts.fn = oneway_merge;
3659 unpack_tree_opts.merge = 1;
3660 unpack_tree_opts.update = 1;
3661 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3663 if (repo_read_index_unmerged(r)) {
3664 rollback_lock_file(&lock);
3665 strbuf_release(&ref_name);
3666 return error_resolve_conflict(_(action_name(opts)));
3669 if (!fill_tree_descriptor(r, &desc, &oid)) {
3670 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3671 rollback_lock_file(&lock);
3672 free((void *)desc.buffer);
3673 strbuf_release(&ref_name);
3677 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3678 rollback_lock_file(&lock);
3679 free((void *)desc.buffer);
3680 strbuf_release(&ref_name);
3684 tree = parse_tree_indirect(&oid);
3685 prime_cache_tree(r, r->index, tree);
3687 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3688 ret = error(_("could not write index"));
3689 free((void *)desc.buffer);
3692 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3693 len, name), "HEAD", &oid,
3694 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3696 strbuf_release(&ref_name);
3700 static struct commit *lookup_label(const char *label, int len,
3703 struct commit *commit;
3706 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3707 commit = lookup_commit_reference_by_name(buf->buf);
3709 /* fall back to non-rewritten ref or commit */
3710 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3711 commit = lookup_commit_reference_by_name(buf->buf);
3715 error(_("could not resolve '%s'"), buf->buf);
3720 static int do_merge(struct repository *r,
3721 struct commit *commit,
3722 const char *arg, int arg_len,
3723 int flags, struct replay_opts *opts)
3725 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3726 EDIT_MSG | VERIFY_MSG : 0;
3727 struct strbuf ref_name = STRBUF_INIT;
3728 struct commit *head_commit, *merge_commit, *i;
3729 struct commit_list *bases, *j, *reversed = NULL;
3730 struct commit_list *to_merge = NULL, **tail = &to_merge;
3731 const char *strategy = !opts->xopts_nr &&
3733 !strcmp(opts->strategy, "recursive") ||
3734 !strcmp(opts->strategy, "ort")) ?
3735 NULL : opts->strategy;
3736 struct merge_options o;
3737 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3738 static struct lock_file lock;
3741 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3746 head_commit = lookup_commit_reference_by_name("HEAD");
3748 ret = error(_("cannot merge without a current revision"));
3753 * For octopus merges, the arg starts with the list of revisions to be
3754 * merged. The list is optionally followed by '#' and the oneline.
3756 merge_arg_len = oneline_offset = arg_len;
3757 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3760 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3761 p += 1 + strspn(p + 1, " \t\n");
3762 oneline_offset = p - arg;
3765 k = strcspn(p, " \t\n");
3768 merge_commit = lookup_label(p, k, &ref_name);
3769 if (!merge_commit) {
3770 ret = error(_("unable to parse '%.*s'"), k, p);
3773 tail = &commit_list_insert(merge_commit, tail)->next;
3775 merge_arg_len = p - arg;
3779 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3783 if (opts->have_squash_onto &&
3784 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3786 * When the user tells us to "merge" something into a
3787 * "[new root]", let's simply fast-forward to the merge head.
3789 rollback_lock_file(&lock);
3791 ret = error(_("octopus merge cannot be executed on "
3792 "top of a [new root]"));
3794 ret = fast_forward_to(r, &to_merge->item->object.oid,
3795 &head_commit->object.oid, 0,
3801 const char *encoding = get_commit_output_encoding();
3802 const char *message = logmsg_reencode(commit, NULL, encoding);
3807 ret = error(_("could not get commit message of '%s'"),
3808 oid_to_hex(&commit->object.oid));
3811 write_author_script(message);
3812 find_commit_subject(message, &body);
3814 ret = write_message(body, len, git_path_merge_msg(r), 0);
3815 unuse_commit_buffer(commit, message);
3817 error_errno(_("could not write '%s'"),
3818 git_path_merge_msg(r));
3822 struct strbuf buf = STRBUF_INIT;
3825 strbuf_addf(&buf, "author %s", git_author_info(0));
3826 write_author_script(buf.buf);
3829 if (oneline_offset < arg_len) {
3830 p = arg + oneline_offset;
3831 len = arg_len - oneline_offset;
3833 strbuf_addf(&buf, "Merge %s '%.*s'",
3834 to_merge->next ? "branches" : "branch",
3835 merge_arg_len, arg);
3840 ret = write_message(p, len, git_path_merge_msg(r), 0);
3841 strbuf_release(&buf);
3843 error_errno(_("could not write '%s'"),
3844 git_path_merge_msg(r));
3850 * If HEAD is not identical to the first parent of the original merge
3851 * commit, we cannot fast-forward.
3853 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3854 oideq(&commit->parents->item->object.oid,
3855 &head_commit->object.oid);
3858 * If any merge head is different from the original one, we cannot
3861 if (can_fast_forward) {
3862 struct commit_list *p = commit->parents->next;
3864 for (j = to_merge; j && p; j = j->next, p = p->next)
3865 if (!oideq(&j->item->object.oid,
3866 &p->item->object.oid)) {
3867 can_fast_forward = 0;
3871 * If the number of merge heads differs from the original merge
3872 * commit, we cannot fast-forward.
3875 can_fast_forward = 0;
3878 if (can_fast_forward) {
3879 rollback_lock_file(&lock);
3880 ret = fast_forward_to(r, &commit->object.oid,
3881 &head_commit->object.oid, 0, opts);
3882 if (flags & TODO_EDIT_MERGE_MSG) {
3883 run_commit_flags |= AMEND_MSG;
3884 goto fast_forward_edit;
3889 if (strategy || to_merge->next) {
3891 struct child_process cmd = CHILD_PROCESS_INIT;
3893 if (read_env_script(&cmd.env_array)) {
3894 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3896 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3900 if (opts->committer_date_is_author_date)
3901 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3904 author_date_from_env_array(&cmd.env_array));
3905 if (opts->ignore_date)
3906 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3909 strvec_push(&cmd.args, "merge");
3910 strvec_push(&cmd.args, "-s");
3912 strvec_push(&cmd.args, "octopus");
3914 strvec_push(&cmd.args, strategy);
3915 for (k = 0; k < opts->xopts_nr; k++)
3916 strvec_pushf(&cmd.args,
3917 "-X%s", opts->xopts[k]);
3919 strvec_push(&cmd.args, "--no-edit");
3920 strvec_push(&cmd.args, "--no-ff");
3921 strvec_push(&cmd.args, "--no-log");
3922 strvec_push(&cmd.args, "--no-stat");
3923 strvec_push(&cmd.args, "-F");
3924 strvec_push(&cmd.args, git_path_merge_msg(r));
3926 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3928 strvec_push(&cmd.args, "--no-gpg-sign");
3930 /* Add the tips to be merged */
3931 for (j = to_merge; j; j = j->next)
3932 strvec_push(&cmd.args,
3933 oid_to_hex(&j->item->object.oid));
3935 strbuf_release(&ref_name);
3936 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3938 rollback_lock_file(&lock);
3940 ret = run_command(&cmd);
3942 /* force re-reading of the cache */
3943 if (!ret && (discard_index(r->index) < 0 ||
3944 repo_read_index(r) < 0))
3945 ret = error(_("could not read index"));
3949 merge_commit = to_merge->item;
3950 bases = get_merge_bases(head_commit, merge_commit);
3951 if (bases && oideq(&merge_commit->object.oid,
3952 &bases->item->object.oid)) {
3954 /* skip merging an ancestor of HEAD */
3958 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3959 git_path_merge_head(r), 0);
3960 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3962 for (j = bases; j; j = j->next)
3963 commit_list_insert(j->item, &reversed);
3964 free_commit_list(bases);
3967 init_merge_options(&o, r);
3969 o.branch2 = ref_name.buf;
3970 o.buffer_output = 2;
3972 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3974 * TODO: Should use merge_incore_recursive() and
3975 * merge_switch_to_result(), skipping the call to
3976 * merge_switch_to_result() when we don't actually need to
3977 * update the index and working copy immediately.
3979 ret = merge_ort_recursive(&o,
3980 head_commit, merge_commit, reversed,
3983 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3987 fputs(o.obuf.buf, stdout);
3988 strbuf_release(&o.obuf);
3990 error(_("could not even attempt to merge '%.*s'"),
3991 merge_arg_len, arg);
3995 * The return value of merge_recursive() is 1 on clean, and 0 on
3998 * Let's reverse that, so that do_merge() returns 0 upon success and
3999 * 1 upon failed merge (keeping the return value -1 for the cases where
4000 * we will want to reschedule the `merge` command).
4004 if (r->index->cache_changed &&
4005 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4006 ret = error(_("merge: Unable to write new index file"));
4010 rollback_lock_file(&lock);
4012 repo_rerere(r, opts->allow_rerere_auto);
4015 * In case of problems, we now want to return a positive
4016 * value (a negative one would indicate that the `merge`
4017 * command needs to be rescheduled).
4020 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4024 strbuf_release(&ref_name);
4025 rollback_lock_file(&lock);
4026 free_commit_list(to_merge);
4030 static int is_final_fixup(struct todo_list *todo_list)
4032 int i = todo_list->current;
4034 if (!is_fixup(todo_list->items[i].command))
4037 while (++i < todo_list->nr)
4038 if (is_fixup(todo_list->items[i].command))
4040 else if (!is_noop(todo_list->items[i].command))
4045 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4049 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4050 if (!is_noop(todo_list->items[i].command))
4051 return todo_list->items[i].command;
4056 void create_autostash(struct repository *r, const char *path,
4057 const char *default_reflog_action)
4059 struct strbuf buf = STRBUF_INIT;
4060 struct lock_file lock_file = LOCK_INIT;
4063 fd = repo_hold_locked_index(r, &lock_file, 0);
4064 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4066 repo_update_index_if_able(r, &lock_file);
4067 rollback_lock_file(&lock_file);
4069 if (has_unstaged_changes(r, 1) ||
4070 has_uncommitted_changes(r, 1)) {
4071 struct child_process stash = CHILD_PROCESS_INIT;
4072 struct object_id oid;
4074 strvec_pushl(&stash.args,
4075 "stash", "create", "autostash", NULL);
4079 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4080 die(_("Cannot autostash"));
4081 strbuf_trim_trailing_newline(&buf);
4082 if (get_oid(buf.buf, &oid))
4083 die(_("Unexpected stash response: '%s'"),
4086 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4088 if (safe_create_leading_directories_const(path))
4089 die(_("Could not create directory for '%s'"),
4091 write_file(path, "%s", oid_to_hex(&oid));
4092 printf(_("Created autostash: %s\n"), buf.buf);
4093 if (reset_head(r, NULL, "reset --hard",
4094 NULL, RESET_HEAD_HARD, NULL, NULL,
4095 default_reflog_action) < 0)
4096 die(_("could not reset --hard"));
4098 if (discard_index(r->index) < 0 ||
4099 repo_read_index(r) < 0)
4100 die(_("could not read index"));
4102 strbuf_release(&buf);
4105 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4107 struct child_process child = CHILD_PROCESS_INIT;
4110 if (attempt_apply) {
4112 child.no_stdout = 1;
4113 child.no_stderr = 1;
4114 strvec_push(&child.args, "stash");
4115 strvec_push(&child.args, "apply");
4116 strvec_push(&child.args, stash_oid);
4117 ret = run_command(&child);
4120 if (attempt_apply && !ret)
4121 fprintf(stderr, _("Applied autostash.\n"));
4123 struct child_process store = CHILD_PROCESS_INIT;
4126 strvec_push(&store.args, "stash");
4127 strvec_push(&store.args, "store");
4128 strvec_push(&store.args, "-m");
4129 strvec_push(&store.args, "autostash");
4130 strvec_push(&store.args, "-q");
4131 strvec_push(&store.args, stash_oid);
4132 if (run_command(&store))
4133 ret = error(_("cannot store %s"), stash_oid);
4137 "Your changes are safe in the stash.\n"
4138 "You can run \"git stash pop\" or"
4139 " \"git stash drop\" at any time.\n"),
4141 _("Applying autostash resulted in conflicts.") :
4142 _("Autostash exists; creating a new stash entry."));
4148 static int apply_save_autostash(const char *path, int attempt_apply)
4150 struct strbuf stash_oid = STRBUF_INIT;
4153 if (!read_oneliner(&stash_oid, path,
4154 READ_ONELINER_SKIP_IF_EMPTY)) {
4155 strbuf_release(&stash_oid);
4158 strbuf_trim(&stash_oid);
4160 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4163 strbuf_release(&stash_oid);
4167 int save_autostash(const char *path)
4169 return apply_save_autostash(path, 0);
4172 int apply_autostash(const char *path)
4174 return apply_save_autostash(path, 1);
4177 int apply_autostash_oid(const char *stash_oid)
4179 return apply_save_autostash_oid(stash_oid, 1);
4182 static const char *reflog_message(struct replay_opts *opts,
4183 const char *sub_action, const char *fmt, ...)
4186 static struct strbuf buf = STRBUF_INIT;
4187 char *reflog_action = getenv(GIT_REFLOG_ACTION);
4191 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
4193 strbuf_addf(&buf, " (%s)", sub_action);
4195 strbuf_addstr(&buf, ": ");
4196 strbuf_vaddf(&buf, fmt, ap);
4203 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4204 const char *commit, const char *action)
4206 struct child_process cmd = CHILD_PROCESS_INIT;
4211 strvec_push(&cmd.args, "checkout");
4212 strvec_push(&cmd.args, commit);
4213 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4216 ret = run_command(&cmd);
4218 ret = run_command_silent_on_success(&cmd);
4221 discard_index(r->index);
4226 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4227 const char *onto_name, const struct object_id *onto,
4228 const struct object_id *orig_head)
4230 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4232 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4233 apply_autostash(rebase_path_autostash());
4234 sequencer_remove_state(opts);
4235 return error(_("could not detach HEAD"));
4238 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4241 static int stopped_at_head(struct repository *r)
4243 struct object_id head;
4244 struct commit *commit;
4245 struct commit_message message;
4247 if (get_oid("HEAD", &head) ||
4248 !(commit = lookup_commit(r, &head)) ||
4249 parse_commit(commit) || get_message(commit, &message))
4250 fprintf(stderr, _("Stopped at HEAD\n"));
4252 fprintf(stderr, _("Stopped at %s\n"), message.label);
4253 free_message(commit, &message);
4259 static const char rescheduled_advice[] =
4260 N_("Could not execute the todo command\n"
4264 "It has been rescheduled; To edit the command before continuing, please\n"
4265 "edit the todo list first:\n"
4267 " git rebase --edit-todo\n"
4268 " git rebase --continue\n");
4270 static int pick_commits(struct repository *r,
4271 struct todo_list *todo_list,
4272 struct replay_opts *opts)
4274 int res = 0, reschedule = 0;
4275 char *prev_reflog_action;
4277 /* Note that 0 for 3rd parameter of setenv means set only if not set */
4278 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4279 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4281 assert(!(opts->signoff || opts->no_commit ||
4282 opts->record_origin || should_edit(opts) ||
4283 opts->committer_date_is_author_date ||
4284 opts->ignore_date));
4285 if (read_and_refresh_cache(r, opts))
4288 while (todo_list->current < todo_list->nr) {
4289 struct todo_item *item = todo_list->items + todo_list->current;
4290 const char *arg = todo_item_get_arg(todo_list, item);
4293 if (save_todo(todo_list, opts))
4295 if (is_rebase_i(opts)) {
4296 if (item->command != TODO_COMMENT) {
4297 FILE *f = fopen(rebase_path_msgnum(), "w");
4299 todo_list->done_nr++;
4302 fprintf(f, "%d\n", todo_list->done_nr);
4306 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4308 todo_list->total_nr,
4309 opts->verbose ? "\n" : "\r");
4311 unlink(rebase_path_message());
4312 unlink(rebase_path_author_script());
4313 unlink(rebase_path_stopped_sha());
4314 unlink(rebase_path_amend());
4315 unlink(git_path_merge_head(r));
4316 unlink(git_path_auto_merge(r));
4317 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4319 if (item->command == TODO_BREAK) {
4322 return stopped_at_head(r);
4325 if (item->command <= TODO_SQUASH) {
4326 if (is_rebase_i(opts))
4327 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4328 command_to_string(item->command), NULL),
4330 res = do_pick_commit(r, item, opts,
4331 is_final_fixup(todo_list),
4333 if (is_rebase_i(opts))
4334 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4335 if (is_rebase_i(opts) && res < 0) {
4337 advise(_(rescheduled_advice),
4338 get_item_line_length(todo_list,
4339 todo_list->current),
4340 get_item_line(todo_list,
4341 todo_list->current));
4342 todo_list->current--;
4343 if (save_todo(todo_list, opts))
4346 if (item->command == TODO_EDIT) {
4347 struct commit *commit = item->commit;
4352 _("Stopped at %s... %.*s\n"),
4353 short_commit_name(commit),
4354 item->arg_len, arg);
4356 return error_with_patch(r, commit,
4357 arg, item->arg_len, opts, res, !res);
4359 if (is_rebase_i(opts) && !res)
4360 record_in_rewritten(&item->commit->object.oid,
4361 peek_command(todo_list, 1));
4362 if (res && is_fixup(item->command)) {
4365 return error_failed_squash(r, item->commit, opts,
4366 item->arg_len, arg);
4367 } else if (res && is_rebase_i(opts) && item->commit) {
4369 struct object_id oid;
4372 * If we are rewording and have either
4373 * fast-forwarded already, or are about to
4374 * create a new root commit, we want to amend,
4375 * otherwise we do not.
4377 if (item->command == TODO_REWORD &&
4378 !get_oid("HEAD", &oid) &&
4379 (oideq(&item->commit->object.oid, &oid) ||
4380 (opts->have_squash_onto &&
4381 oideq(&opts->squash_onto, &oid))))
4384 return res | error_with_patch(r, item->commit,
4385 arg, item->arg_len, opts,
4388 } else if (item->command == TODO_EXEC) {
4389 char *end_of_arg = (char *)(arg + item->arg_len);
4390 int saved = *end_of_arg;
4395 res = do_exec(r, arg);
4396 *end_of_arg = saved;
4399 if (opts->reschedule_failed_exec)
4403 } else if (item->command == TODO_LABEL) {
4404 if ((res = do_label(r, arg, item->arg_len)))
4406 } else if (item->command == TODO_RESET) {
4407 if ((res = do_reset(r, arg, item->arg_len, opts)))
4409 } else if (item->command == TODO_MERGE) {
4410 if ((res = do_merge(r, item->commit,
4412 item->flags, opts)) < 0)
4414 else if (item->commit)
4415 record_in_rewritten(&item->commit->object.oid,
4416 peek_command(todo_list, 1));
4418 /* failed with merge conflicts */
4419 return error_with_patch(r, item->commit,
4422 } else if (!is_noop(item->command))
4423 return error(_("unknown command %d"), item->command);
4426 advise(_(rescheduled_advice),
4427 get_item_line_length(todo_list,
4428 todo_list->current),
4429 get_item_line(todo_list, todo_list->current));
4430 todo_list->current--;
4431 if (save_todo(todo_list, opts))
4434 return error_with_patch(r,
4438 } else if (is_rebase_i(opts) && check_todo && !res) {
4441 if (stat(get_todo_path(opts), &st)) {
4442 res = error_errno(_("could not stat '%s'"),
4443 get_todo_path(opts));
4444 } else if (match_stat_data(&todo_list->stat, &st)) {
4445 /* Reread the todo file if it has changed. */
4446 todo_list_release(todo_list);
4447 if (read_populate_todo(r, todo_list, opts))
4448 res = -1; /* message was printed */
4449 /* `current` will be incremented below */
4450 todo_list->current = -1;
4454 todo_list->current++;
4459 if (is_rebase_i(opts)) {
4460 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4463 /* Stopped in the middle, as planned? */
4464 if (todo_list->current < todo_list->nr)
4467 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4468 starts_with(head_ref.buf, "refs/")) {
4470 struct object_id head, orig;
4473 if (get_oid("HEAD", &head)) {
4474 res = error(_("cannot read HEAD"));
4476 strbuf_release(&head_ref);
4477 strbuf_release(&buf);
4480 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4481 get_oid_hex(buf.buf, &orig)) {
4482 res = error(_("could not read orig-head"));
4483 goto cleanup_head_ref;
4486 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4487 res = error(_("could not read 'onto'"));
4488 goto cleanup_head_ref;
4490 msg = reflog_message(opts, "finish", "%s onto %s",
4491 head_ref.buf, buf.buf);
4492 if (update_ref(msg, head_ref.buf, &head, &orig,
4493 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4494 res = error(_("could not update %s"),
4496 goto cleanup_head_ref;
4498 msg = reflog_message(opts, "finish", "returning to %s",
4500 if (create_symref("HEAD", head_ref.buf, msg)) {
4501 res = error(_("could not update HEAD to %s"),
4503 goto cleanup_head_ref;
4508 if (opts->verbose) {
4509 struct rev_info log_tree_opt;
4510 struct object_id orig, head;
4512 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4513 repo_init_revisions(r, &log_tree_opt, NULL);
4514 log_tree_opt.diff = 1;
4515 log_tree_opt.diffopt.output_format =
4516 DIFF_FORMAT_DIFFSTAT;
4517 log_tree_opt.disable_stdin = 1;
4519 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4520 !get_oid(buf.buf, &orig) &&
4521 !get_oid("HEAD", &head)) {
4522 diff_tree_oid(&orig, &head, "",
4523 &log_tree_opt.diffopt);
4524 log_tree_diff_flush(&log_tree_opt);
4527 flush_rewritten_pending();
4528 if (!stat(rebase_path_rewritten_list(), &st) &&
4530 struct child_process child = CHILD_PROCESS_INIT;
4531 const char *post_rewrite_hook =
4532 find_hook("post-rewrite");
4534 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4536 strvec_push(&child.args, "notes");
4537 strvec_push(&child.args, "copy");
4538 strvec_push(&child.args, "--for-rewrite=rebase");
4539 /* we don't care if this copying failed */
4540 run_command(&child);
4542 if (post_rewrite_hook) {
4543 struct child_process hook = CHILD_PROCESS_INIT;
4545 hook.in = open(rebase_path_rewritten_list(),
4547 hook.stdout_to_stderr = 1;
4548 hook.trace2_hook_name = "post-rewrite";
4549 strvec_push(&hook.args, post_rewrite_hook);
4550 strvec_push(&hook.args, "rebase");
4551 /* we don't care if this hook failed */
4555 apply_autostash(rebase_path_autostash());
4561 _("Successfully rebased and updated %s.\n"),
4565 strbuf_release(&buf);
4566 strbuf_release(&head_ref);
4570 * Sequence of picks finished successfully; cleanup by
4571 * removing the .git/sequencer directory
4573 return sequencer_remove_state(opts);
4576 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4578 struct strvec argv = STRVEC_INIT;
4581 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4582 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4583 return error(_("no cherry-pick or revert in progress"));
4585 strvec_push(&argv, "commit");
4588 * continue_single_pick() handles the case of recovering from a
4589 * conflict. should_edit() doesn't handle that case; for a conflict,
4590 * we want to edit if the user asked for it, or if they didn't specify
4591 * and stdin is a tty.
4593 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4595 * Include --cleanup=strip as well because we don't want the
4596 * "# Conflicts:" messages.
4598 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4600 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4601 strvec_clear(&argv);
4605 static int commit_staged_changes(struct repository *r,
4606 struct replay_opts *opts,
4607 struct todo_list *todo_list)
4609 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4610 unsigned int final_fixup = 0, is_clean;
4612 if (has_unstaged_changes(r, 1))
4613 return error(_("cannot rebase: You have unstaged changes."));
4615 is_clean = !has_uncommitted_changes(r, 0);
4617 if (file_exists(rebase_path_amend())) {
4618 struct strbuf rev = STRBUF_INIT;
4619 struct object_id head, to_amend;
4621 if (get_oid("HEAD", &head))
4622 return error(_("cannot amend non-existing commit"));
4623 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4624 return error(_("invalid file: '%s'"), rebase_path_amend());
4625 if (get_oid_hex(rev.buf, &to_amend))
4626 return error(_("invalid contents: '%s'"),
4627 rebase_path_amend());
4628 if (!is_clean && !oideq(&head, &to_amend))
4629 return error(_("\nYou have uncommitted changes in your "
4630 "working tree. Please, commit them\n"
4631 "first and then run 'git rebase "
4632 "--continue' again."));
4634 * When skipping a failed fixup/squash, we need to edit the
4635 * commit message, the current fixup list and count, and if it
4636 * was the last fixup/squash in the chain, we need to clean up
4637 * the commit message and if there was a squash, let the user
4640 if (!is_clean || !opts->current_fixup_count)
4641 ; /* this is not the final fixup */
4642 else if (!oideq(&head, &to_amend) ||
4643 !file_exists(rebase_path_stopped_sha())) {
4644 /* was a final fixup or squash done manually? */
4645 if (!is_fixup(peek_command(todo_list, 0))) {
4646 unlink(rebase_path_fixup_msg());
4647 unlink(rebase_path_squash_msg());
4648 unlink(rebase_path_current_fixups());
4649 strbuf_reset(&opts->current_fixups);
4650 opts->current_fixup_count = 0;
4653 /* we are in a fixup/squash chain */
4654 const char *p = opts->current_fixups.buf;
4655 int len = opts->current_fixups.len;
4657 opts->current_fixup_count--;
4659 BUG("Incorrect current_fixups:\n%s", p);
4660 while (len && p[len - 1] != '\n')
4662 strbuf_setlen(&opts->current_fixups, len);
4663 if (write_message(p, len, rebase_path_current_fixups(),
4665 return error(_("could not write file: '%s'"),
4666 rebase_path_current_fixups());
4669 * If a fixup/squash in a fixup/squash chain failed, the
4670 * commit message is already correct, no need to commit
4673 * Only if it is the final command in the fixup/squash
4674 * chain, and only if the chain is longer than a single
4675 * fixup/squash command (which was just skipped), do we
4676 * actually need to re-commit with a cleaned up commit
4679 if (opts->current_fixup_count > 0 &&
4680 !is_fixup(peek_command(todo_list, 0))) {
4683 * If there was not a single "squash" in the
4684 * chain, we only need to clean up the commit
4685 * message, no need to bother the user with
4686 * opening the commit message in the editor.
4688 if (!starts_with(p, "squash ") &&
4689 !strstr(p, "\nsquash "))
4690 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4691 } else if (is_fixup(peek_command(todo_list, 0))) {
4693 * We need to update the squash message to skip
4694 * the latest commit message.
4696 struct commit *commit;
4697 const char *path = rebase_path_squash_msg();
4698 const char *encoding = get_commit_output_encoding();
4700 if (parse_head(r, &commit) ||
4701 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4702 write_message(p, strlen(p), path, 0)) {
4703 unuse_commit_buffer(commit, p);
4704 return error(_("could not write file: "
4707 unuse_commit_buffer(commit, p);
4711 strbuf_release(&rev);
4716 if (refs_ref_exists(get_main_ref_store(r),
4717 "CHERRY_PICK_HEAD") &&
4718 refs_delete_ref(get_main_ref_store(r), "",
4719 "CHERRY_PICK_HEAD", NULL, 0))
4720 return error(_("could not remove CHERRY_PICK_HEAD"));
4725 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4727 return error(_("could not commit staged changes."));
4728 unlink(rebase_path_amend());
4729 unlink(git_path_merge_head(r));
4730 unlink(git_path_auto_merge(r));
4732 unlink(rebase_path_fixup_msg());
4733 unlink(rebase_path_squash_msg());
4735 if (opts->current_fixup_count > 0) {
4737 * Whether final fixup or not, we just cleaned up the commit
4740 unlink(rebase_path_current_fixups());
4741 strbuf_reset(&opts->current_fixups);
4742 opts->current_fixup_count = 0;
4747 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4749 struct todo_list todo_list = TODO_LIST_INIT;
4752 if (read_and_refresh_cache(r, opts))
4755 if (read_populate_opts(opts))
4757 if (is_rebase_i(opts)) {
4758 if ((res = read_populate_todo(r, &todo_list, opts)))
4759 goto release_todo_list;
4761 if (file_exists(rebase_path_dropped())) {
4762 if ((res = todo_list_check_against_backup(r, &todo_list)))
4763 goto release_todo_list;
4765 unlink(rebase_path_dropped());
4768 if (commit_staged_changes(r, opts, &todo_list)) {
4770 goto release_todo_list;
4772 } else if (!file_exists(get_todo_path(opts)))
4773 return continue_single_pick(r, opts);
4774 else if ((res = read_populate_todo(r, &todo_list, opts)))
4775 goto release_todo_list;
4777 if (!is_rebase_i(opts)) {
4778 /* Verify that the conflict has been resolved */
4779 if (refs_ref_exists(get_main_ref_store(r),
4780 "CHERRY_PICK_HEAD") ||
4781 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4782 res = continue_single_pick(r, opts);
4784 goto release_todo_list;
4786 if (index_differs_from(r, "HEAD", NULL, 0)) {
4787 res = error_dirty_index(r, opts);
4788 goto release_todo_list;
4790 todo_list.current++;
4791 } else if (file_exists(rebase_path_stopped_sha())) {
4792 struct strbuf buf = STRBUF_INIT;
4793 struct object_id oid;
4795 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4796 READ_ONELINER_SKIP_IF_EMPTY) &&
4797 !get_oid_hex(buf.buf, &oid))
4798 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4799 strbuf_release(&buf);
4802 res = pick_commits(r, &todo_list, opts);
4804 todo_list_release(&todo_list);
4808 static int single_pick(struct repository *r,
4809 struct commit *cmit,
4810 struct replay_opts *opts)
4813 struct todo_item item;
4815 item.command = opts->action == REPLAY_PICK ?
4816 TODO_PICK : TODO_REVERT;
4819 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4820 return do_pick_commit(r, &item, opts, 0, &check_todo);
4823 int sequencer_pick_revisions(struct repository *r,
4824 struct replay_opts *opts)
4826 struct todo_list todo_list = TODO_LIST_INIT;
4827 struct object_id oid;
4831 if (read_and_refresh_cache(r, opts))
4834 for (i = 0; i < opts->revs->pending.nr; i++) {
4835 struct object_id oid;
4836 const char *name = opts->revs->pending.objects[i].name;
4838 /* This happens when using --stdin. */
4842 if (!get_oid(name, &oid)) {
4843 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4844 enum object_type type = oid_object_info(r,
4847 return error(_("%s: can't cherry-pick a %s"),
4848 name, type_name(type));
4851 return error(_("%s: bad revision"), name);
4855 * If we were called as "git cherry-pick <commit>", just
4856 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4857 * REVERT_HEAD, and don't touch the sequencer state.
4858 * This means it is possible to cherry-pick in the middle
4859 * of a cherry-pick sequence.
4861 if (opts->revs->cmdline.nr == 1 &&
4862 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4863 opts->revs->no_walk &&
4864 !opts->revs->cmdline.rev->flags) {
4865 struct commit *cmit;
4866 if (prepare_revision_walk(opts->revs))
4867 return error(_("revision walk setup failed"));
4868 cmit = get_revision(opts->revs);
4870 return error(_("empty commit set passed"));
4871 if (get_revision(opts->revs))
4872 BUG("unexpected extra commit from walk");
4873 return single_pick(r, cmit, opts);
4877 * Start a new cherry-pick/ revert sequence; but
4878 * first, make sure that an existing one isn't in
4882 if (walk_revs_populate_todo(&todo_list, opts) ||
4883 create_seq_dir(r) < 0)
4885 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4886 return error(_("can't revert as initial commit"));
4887 if (save_head(oid_to_hex(&oid)))
4889 if (save_opts(opts))
4891 update_abort_safety_file();
4892 res = pick_commits(r, &todo_list, opts);
4893 todo_list_release(&todo_list);
4897 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4899 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4900 struct strbuf sob = STRBUF_INIT;
4903 strbuf_addstr(&sob, sign_off_header);
4904 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4905 strbuf_addch(&sob, '\n');
4908 strbuf_complete_line(msgbuf);
4911 * If the whole message buffer is equal to the sob, pretend that we
4912 * found a conforming footer with a matching sob
4914 if (msgbuf->len - ignore_footer == sob.len &&
4915 !strncmp(msgbuf->buf, sob.buf, sob.len))
4918 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4921 const char *append_newlines = NULL;
4922 size_t len = msgbuf->len - ignore_footer;
4926 * The buffer is completely empty. Leave foom for
4927 * the title and body to be filled in by the user.
4929 append_newlines = "\n\n";
4930 } else if (len == 1) {
4932 * Buffer contains a single newline. Add another
4933 * so that we leave room for the title and body.
4935 append_newlines = "\n";
4936 } else if (msgbuf->buf[len - 2] != '\n') {
4938 * Buffer ends with a single newline. Add another
4939 * so that there is an empty line between the message
4942 append_newlines = "\n";
4943 } /* else, the buffer already ends with two newlines. */
4945 if (append_newlines)
4946 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4947 append_newlines, strlen(append_newlines));
4950 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4951 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4954 strbuf_release(&sob);
4957 struct labels_entry {
4958 struct hashmap_entry entry;
4959 char label[FLEX_ARRAY];
4962 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4963 const struct hashmap_entry *entry_or_key, const void *key)
4965 const struct labels_entry *a, *b;
4967 a = container_of(eptr, const struct labels_entry, entry);
4968 b = container_of(entry_or_key, const struct labels_entry, entry);
4970 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4973 struct string_entry {
4974 struct oidmap_entry entry;
4975 char string[FLEX_ARRAY];
4978 struct label_state {
4979 struct oidmap commit2label;
4980 struct hashmap labels;
4984 static const char *label_oid(struct object_id *oid, const char *label,
4985 struct label_state *state)
4987 struct labels_entry *labels_entry;
4988 struct string_entry *string_entry;
4989 struct object_id dummy;
4992 string_entry = oidmap_get(&state->commit2label, oid);
4994 return string_entry->string;
4997 * For "uninteresting" commits, i.e. commits that are not to be
4998 * rebased, and which can therefore not be labeled, we use a unique
4999 * abbreviation of the commit name. This is slightly more complicated
5000 * than calling find_unique_abbrev() because we also need to make
5001 * sure that the abbreviation does not conflict with any other
5004 * We disallow "interesting" commits to be labeled by a string that
5005 * is a valid full-length hash, to ensure that we always can find an
5006 * abbreviation for any uninteresting commit's names that does not
5007 * clash with any other label.
5009 strbuf_reset(&state->buf);
5013 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5014 label = p = state->buf.buf;
5016 find_unique_abbrev_r(p, oid, default_abbrev);
5019 * We may need to extend the abbreviated hash so that there is
5020 * no conflicting label.
5022 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5023 size_t i = strlen(p) + 1;
5025 oid_to_hex_r(p, oid);
5026 for (; i < the_hash_algo->hexsz; i++) {
5029 if (!hashmap_get_from_hash(&state->labels,
5036 struct strbuf *buf = &state->buf;
5039 * Sanitize labels by replacing non-alpha-numeric characters
5040 * (including white-space ones) by dashes, as they might be
5041 * illegal in file names (and hence in ref names).
5043 * Note that we retain non-ASCII UTF-8 characters (identified
5044 * via the most significant bit). They should be all acceptable
5045 * in file names. We do not validate the UTF-8 here, that's not
5046 * the job of this function.
5048 for (; *label; label++)
5049 if ((*label & 0x80) || isalnum(*label))
5050 strbuf_addch(buf, *label);
5051 /* avoid leading dash and double-dashes */
5052 else if (buf->len && buf->buf[buf->len - 1] != '-')
5053 strbuf_addch(buf, '-');
5055 strbuf_addstr(buf, "rev-");
5056 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5060 if ((buf->len == the_hash_algo->hexsz &&
5061 !get_oid_hex(label, &dummy)) ||
5062 (buf->len == 1 && *label == '#') ||
5063 hashmap_get_from_hash(&state->labels,
5064 strihash(label), label)) {
5066 * If the label already exists, or if the label is a
5067 * valid full OID, or the label is a '#' (which we use
5068 * as a separator between merge heads and oneline), we
5069 * append a dash and a number to make it unique.
5071 size_t len = buf->len;
5073 for (i = 2; ; i++) {
5074 strbuf_setlen(buf, len);
5075 strbuf_addf(buf, "-%d", i);
5076 if (!hashmap_get_from_hash(&state->labels,
5086 FLEX_ALLOC_STR(labels_entry, label, label);
5087 hashmap_entry_init(&labels_entry->entry, strihash(label));
5088 hashmap_add(&state->labels, &labels_entry->entry);
5090 FLEX_ALLOC_STR(string_entry, string, label);
5091 oidcpy(&string_entry->entry.oid, oid);
5092 oidmap_put(&state->commit2label, string_entry);
5094 return string_entry->string;
5097 static int make_script_with_merges(struct pretty_print_context *pp,
5098 struct rev_info *revs, struct strbuf *out,
5101 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5102 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5103 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5104 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5105 struct strbuf label = STRBUF_INIT;
5106 struct commit_list *commits = NULL, **tail = &commits, *iter;
5107 struct commit_list *tips = NULL, **tips_tail = &tips;
5108 struct commit *commit;
5109 struct oidmap commit2todo = OIDMAP_INIT;
5110 struct string_entry *entry;
5111 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5112 shown = OIDSET_INIT;
5113 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5115 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5116 const char *cmd_pick = abbr ? "p" : "pick",
5117 *cmd_label = abbr ? "l" : "label",
5118 *cmd_reset = abbr ? "t" : "reset",
5119 *cmd_merge = abbr ? "m" : "merge";
5121 oidmap_init(&commit2todo, 0);
5122 oidmap_init(&state.commit2label, 0);
5123 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5124 strbuf_init(&state.buf, 32);
5126 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5127 struct labels_entry *onto_label_entry;
5128 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5129 FLEX_ALLOC_STR(entry, string, "onto");
5130 oidcpy(&entry->entry.oid, oid);
5131 oidmap_put(&state.commit2label, entry);
5133 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5134 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5135 hashmap_add(&state.labels, &onto_label_entry->entry);
5140 * - get onelines for all commits
5141 * - gather all branch tips (i.e. 2nd or later parents of merges)
5142 * - label all branch tips
5144 while ((commit = get_revision(revs))) {
5145 struct commit_list *to_merge;
5146 const char *p1, *p2;
5147 struct object_id *oid;
5150 tail = &commit_list_insert(commit, tail)->next;
5151 oidset_insert(&interesting, &commit->object.oid);
5153 is_empty = is_original_commit_empty(commit);
5154 if (!is_empty && (commit->object.flags & PATCHSAME))
5156 if (is_empty && !keep_empty)
5159 strbuf_reset(&oneline);
5160 pretty_print_commit(pp, commit, &oneline);
5162 to_merge = commit->parents ? commit->parents->next : NULL;
5164 /* non-merge commit: easy case */
5166 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5167 oid_to_hex(&commit->object.oid),
5170 strbuf_addf(&buf, " %c empty",
5173 FLEX_ALLOC_STR(entry, string, buf.buf);
5174 oidcpy(&entry->entry.oid, &commit->object.oid);
5175 oidmap_put(&commit2todo, entry);
5180 /* Create a label */
5181 strbuf_reset(&label);
5182 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5183 (p1 = strchr(p1, '\'')) &&
5184 (p2 = strchr(++p1, '\'')))
5185 strbuf_add(&label, p1, p2 - p1);
5186 else if (skip_prefix(oneline.buf, "Merge pull request ",
5188 (p1 = strstr(p1, " from ")))
5189 strbuf_addstr(&label, p1 + strlen(" from "));
5191 strbuf_addbuf(&label, &oneline);
5194 strbuf_addf(&buf, "%s -C %s",
5195 cmd_merge, oid_to_hex(&commit->object.oid));
5197 /* label the tips of merged branches */
5198 for (; to_merge; to_merge = to_merge->next) {
5199 oid = &to_merge->item->object.oid;
5200 strbuf_addch(&buf, ' ');
5202 if (!oidset_contains(&interesting, oid)) {
5203 strbuf_addstr(&buf, label_oid(oid, NULL,
5208 tips_tail = &commit_list_insert(to_merge->item,
5211 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5213 strbuf_addf(&buf, " # %s", oneline.buf);
5215 FLEX_ALLOC_STR(entry, string, buf.buf);
5216 oidcpy(&entry->entry.oid, &commit->object.oid);
5217 oidmap_put(&commit2todo, entry);
5222 * - label branch points
5223 * - add HEAD to the branch tips
5225 for (iter = commits; iter; iter = iter->next) {
5226 struct commit_list *parent = iter->item->parents;
5227 for (; parent; parent = parent->next) {
5228 struct object_id *oid = &parent->item->object.oid;
5229 if (!oidset_contains(&interesting, oid))
5231 if (oidset_insert(&child_seen, oid))
5232 label_oid(oid, "branch-point", &state);
5235 /* Add HEAD as implicit "tip of branch" */
5237 tips_tail = &commit_list_insert(iter->item,
5242 * Third phase: output the todo list. This is a bit tricky, as we
5243 * want to avoid jumping back and forth between revisions. To
5244 * accomplish that goal, we walk backwards from the branch tips,
5245 * gathering commits not yet shown, reversing the list on the fly,
5246 * then outputting that list (labeling revisions as needed).
5248 strbuf_addf(out, "%s onto\n", cmd_label);
5249 for (iter = tips; iter; iter = iter->next) {
5250 struct commit_list *list = NULL, *iter2;
5252 commit = iter->item;
5253 if (oidset_contains(&shown, &commit->object.oid))
5255 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5258 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5260 strbuf_addch(out, '\n');
5262 while (oidset_contains(&interesting, &commit->object.oid) &&
5263 !oidset_contains(&shown, &commit->object.oid)) {
5264 commit_list_insert(commit, &list);
5265 if (!commit->parents) {
5269 commit = commit->parents->item;
5273 strbuf_addf(out, "%s %s\n", cmd_reset,
5274 rebase_cousins || root_with_onto ?
5275 "onto" : "[new root]");
5277 const char *to = NULL;
5279 entry = oidmap_get(&state.commit2label,
5280 &commit->object.oid);
5283 else if (!rebase_cousins)
5284 to = label_oid(&commit->object.oid, NULL,
5287 if (!to || !strcmp(to, "onto"))
5288 strbuf_addf(out, "%s onto\n", cmd_reset);
5290 strbuf_reset(&oneline);
5291 pretty_print_commit(pp, commit, &oneline);
5292 strbuf_addf(out, "%s %s # %s\n",
5293 cmd_reset, to, oneline.buf);
5297 for (iter2 = list; iter2; iter2 = iter2->next) {
5298 struct object_id *oid = &iter2->item->object.oid;
5299 entry = oidmap_get(&commit2todo, oid);
5300 /* only show if not already upstream */
5302 strbuf_addf(out, "%s\n", entry->string);
5303 entry = oidmap_get(&state.commit2label, oid);
5305 strbuf_addf(out, "%s %s\n",
5306 cmd_label, entry->string);
5307 oidset_insert(&shown, oid);
5310 free_commit_list(list);
5313 free_commit_list(commits);
5314 free_commit_list(tips);
5316 strbuf_release(&label);
5317 strbuf_release(&oneline);
5318 strbuf_release(&buf);
5320 oidmap_free(&commit2todo, 1);
5321 oidmap_free(&state.commit2label, 1);
5322 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5323 strbuf_release(&state.buf);
5328 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5329 const char **argv, unsigned flags)
5331 char *format = NULL;
5332 struct pretty_print_context pp = {0};
5333 struct rev_info revs;
5334 struct commit *commit;
5335 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5336 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5337 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5338 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5340 repo_init_revisions(r, &revs, NULL);
5341 revs.verbose_header = 1;
5343 revs.max_parents = 1;
5344 revs.cherry_mark = !reapply_cherry_picks;
5347 revs.right_only = 1;
5348 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5349 revs.topo_order = 1;
5351 revs.pretty_given = 1;
5352 git_config_get_string("rebase.instructionFormat", &format);
5353 if (!format || !*format) {
5355 format = xstrdup("%s");
5357 get_commit_format(format, &revs);
5359 pp.fmt = revs.commit_format;
5360 pp.output_encoding = get_log_output_encoding();
5362 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5363 return error(_("make_script: unhandled options"));
5365 if (prepare_revision_walk(&revs) < 0)
5366 return error(_("make_script: error preparing revisions"));
5369 return make_script_with_merges(&pp, &revs, out, flags);
5371 while ((commit = get_revision(&revs))) {
5372 int is_empty = is_original_commit_empty(commit);
5374 if (!is_empty && (commit->object.flags & PATCHSAME))
5376 if (is_empty && !keep_empty)
5378 strbuf_addf(out, "%s %s ", insn,
5379 oid_to_hex(&commit->object.oid));
5380 pretty_print_commit(&pp, commit, out);
5382 strbuf_addf(out, " %c empty", comment_line_char);
5383 strbuf_addch(out, '\n');
5389 * Add commands after pick and (series of) squash/fixup commands
5392 void todo_list_add_exec_commands(struct todo_list *todo_list,
5393 struct string_list *commands)
5395 struct strbuf *buf = &todo_list->buf;
5396 size_t base_offset = buf->len;
5397 int i, insert, nr = 0, alloc = 0;
5398 struct todo_item *items = NULL, *base_items = NULL;
5400 CALLOC_ARRAY(base_items, commands->nr);
5401 for (i = 0; i < commands->nr; i++) {
5402 size_t command_len = strlen(commands->items[i].string);
5404 strbuf_addstr(buf, commands->items[i].string);
5405 strbuf_addch(buf, '\n');
5407 base_items[i].command = TODO_EXEC;
5408 base_items[i].offset_in_buf = base_offset;
5409 base_items[i].arg_offset = base_offset + strlen("exec ");
5410 base_items[i].arg_len = command_len - strlen("exec ");
5412 base_offset += command_len + 1;
5416 * Insert <commands> after every pick. Here, fixup/squash chains
5417 * are considered part of the pick, so we insert the commands *after*
5418 * those chains if there are any.
5420 * As we insert the exec commands immediately after rearranging
5421 * any fixups and before the user edits the list, a fixup chain
5422 * can never contain comments (any comments are empty picks that
5423 * have been commented out because the user did not specify
5424 * --keep-empty). So, it is safe to insert an exec command
5425 * without looking at the command following a comment.
5428 for (i = 0; i < todo_list->nr; i++) {
5429 enum todo_command command = todo_list->items[i].command;
5430 if (insert && !is_fixup(command)) {
5431 ALLOC_GROW(items, nr + commands->nr, alloc);
5432 COPY_ARRAY(items + nr, base_items, commands->nr);
5438 ALLOC_GROW(items, nr + 1, alloc);
5439 items[nr++] = todo_list->items[i];
5441 if (command == TODO_PICK || command == TODO_MERGE)
5445 /* insert or append final <commands> */
5446 if (insert || nr == todo_list->nr) {
5447 ALLOC_GROW(items, nr + commands->nr, alloc);
5448 COPY_ARRAY(items + nr, base_items, commands->nr);
5453 FREE_AND_NULL(todo_list->items);
5454 todo_list->items = items;
5456 todo_list->alloc = alloc;
5459 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5460 struct strbuf *buf, int num, unsigned flags)
5462 struct todo_item *item;
5463 int i, max = todo_list->nr;
5465 if (num > 0 && num < max)
5468 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5471 /* if the item is not a command write it and continue */
5472 if (item->command >= TODO_COMMENT) {
5473 strbuf_addf(buf, "%.*s\n", item->arg_len,
5474 todo_item_get_arg(todo_list, item));
5478 /* add command to the buffer */
5479 cmd = command_to_char(item->command);
5480 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5481 strbuf_addch(buf, cmd);
5483 strbuf_addstr(buf, command_to_string(item->command));
5487 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5488 short_commit_name(item->commit) :
5489 oid_to_hex(&item->commit->object.oid);
5491 if (item->command == TODO_FIXUP) {
5492 if (item->flags & TODO_EDIT_FIXUP_MSG)
5493 strbuf_addstr(buf, " -c");
5494 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5495 strbuf_addstr(buf, " -C");
5499 if (item->command == TODO_MERGE) {
5500 if (item->flags & TODO_EDIT_MERGE_MSG)
5501 strbuf_addstr(buf, " -c");
5503 strbuf_addstr(buf, " -C");
5506 strbuf_addf(buf, " %s", oid);
5509 /* add all the rest */
5511 strbuf_addch(buf, '\n');
5513 strbuf_addf(buf, " %.*s\n", item->arg_len,
5514 todo_item_get_arg(todo_list, item));
5518 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5519 const char *file, const char *shortrevisions,
5520 const char *shortonto, int num, unsigned flags)
5523 struct strbuf buf = STRBUF_INIT;
5525 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5526 if (flags & TODO_LIST_APPEND_TODO_HELP)
5527 append_todo_help(count_commands(todo_list),
5528 shortrevisions, shortonto, &buf);
5530 res = write_message(buf.buf, buf.len, file, 0);
5531 strbuf_release(&buf);
5536 /* skip picking commits whose parents are unchanged */
5537 static int skip_unnecessary_picks(struct repository *r,
5538 struct todo_list *todo_list,
5539 struct object_id *base_oid)
5541 struct object_id *parent_oid;
5544 for (i = 0; i < todo_list->nr; i++) {
5545 struct todo_item *item = todo_list->items + i;
5547 if (item->command >= TODO_NOOP)
5549 if (item->command != TODO_PICK)
5551 if (parse_commit(item->commit)) {
5552 return error(_("could not parse commit '%s'"),
5553 oid_to_hex(&item->commit->object.oid));
5555 if (!item->commit->parents)
5556 break; /* root commit */
5557 if (item->commit->parents->next)
5558 break; /* merge commit */
5559 parent_oid = &item->commit->parents->item->object.oid;
5560 if (!oideq(parent_oid, base_oid))
5562 oidcpy(base_oid, &item->commit->object.oid);
5565 const char *done_path = rebase_path_done();
5567 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5568 error_errno(_("could not write to '%s'"), done_path);
5572 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5574 todo_list->current = 0;
5575 todo_list->done_nr += i;
5577 if (is_fixup(peek_command(todo_list, 0)))
5578 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5584 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5585 const char *shortrevisions, const char *onto_name,
5586 struct commit *onto, const struct object_id *orig_head,
5587 struct string_list *commands, unsigned autosquash,
5588 struct todo_list *todo_list)
5590 char shortonto[GIT_MAX_HEXSZ + 1];
5591 const char *todo_file = rebase_path_todo();
5592 struct todo_list new_todo = TODO_LIST_INIT;
5593 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5594 struct object_id oid = onto->object.oid;
5597 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5599 if (buf->len == 0) {
5600 struct todo_item *item = append_new_todo(todo_list);
5601 item->command = TODO_NOOP;
5602 item->commit = NULL;
5603 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5606 if (autosquash && todo_list_rearrange_squash(todo_list))
5610 todo_list_add_exec_commands(todo_list, commands);
5612 if (count_commands(todo_list) == 0) {
5613 apply_autostash(rebase_path_autostash());
5614 sequencer_remove_state(opts);
5616 return error(_("nothing to do"));
5619 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5623 else if (res == -2) {
5624 apply_autostash(rebase_path_autostash());
5625 sequencer_remove_state(opts);
5628 } else if (res == -3) {
5629 apply_autostash(rebase_path_autostash());
5630 sequencer_remove_state(opts);
5631 todo_list_release(&new_todo);
5633 return error(_("nothing to do"));
5634 } else if (res == -4) {
5635 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5636 todo_list_release(&new_todo);
5641 /* Expand the commit IDs */
5642 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5643 strbuf_swap(&new_todo.buf, &buf2);
5644 strbuf_release(&buf2);
5645 new_todo.total_nr -= new_todo.nr;
5646 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5647 BUG("invalid todo list after expanding IDs:\n%s",
5650 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5651 todo_list_release(&new_todo);
5652 return error(_("could not skip unnecessary pick commands"));
5655 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5656 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5657 todo_list_release(&new_todo);
5658 return error_errno(_("could not write '%s'"), todo_file);
5663 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5666 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5669 todo_list_write_total_nr(&new_todo);
5670 res = pick_commits(r, &new_todo, opts);
5673 todo_list_release(&new_todo);
5678 struct subject2item_entry {
5679 struct hashmap_entry entry;
5681 char subject[FLEX_ARRAY];
5684 static int subject2item_cmp(const void *fndata,
5685 const struct hashmap_entry *eptr,
5686 const struct hashmap_entry *entry_or_key,
5689 const struct subject2item_entry *a, *b;
5691 a = container_of(eptr, const struct subject2item_entry, entry);
5692 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5694 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5697 define_commit_slab(commit_todo_item, struct todo_item *);
5699 static int skip_fixupish(const char *subject, const char **p) {
5700 return skip_prefix(subject, "fixup! ", p) ||
5701 skip_prefix(subject, "amend! ", p) ||
5702 skip_prefix(subject, "squash! ", p);
5706 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5707 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5708 * after the former, and change "pick" to "fixup"/"squash".
5710 * Note that if the config has specified a custom instruction format, each log
5711 * message will have to be retrieved from the commit (as the oneline in the
5712 * script cannot be trusted) in order to normalize the autosquash arrangement.
5714 int todo_list_rearrange_squash(struct todo_list *todo_list)
5716 struct hashmap subject2item;
5717 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5719 struct commit_todo_item commit_todo;
5720 struct todo_item *items = NULL;
5722 init_commit_todo_item(&commit_todo);
5724 * The hashmap maps onelines to the respective todo list index.
5726 * If any items need to be rearranged, the next[i] value will indicate
5727 * which item was moved directly after the i'th.
5729 * In that case, last[i] will indicate the index of the latest item to
5730 * be moved to appear after the i'th.
5732 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5733 ALLOC_ARRAY(next, todo_list->nr);
5734 ALLOC_ARRAY(tail, todo_list->nr);
5735 ALLOC_ARRAY(subjects, todo_list->nr);
5736 for (i = 0; i < todo_list->nr; i++) {
5737 struct strbuf buf = STRBUF_INIT;
5738 struct todo_item *item = todo_list->items + i;
5739 const char *commit_buffer, *subject, *p;
5742 struct subject2item_entry *entry;
5744 next[i] = tail[i] = -1;
5745 if (!item->commit || item->command == TODO_DROP) {
5750 if (is_fixup(item->command)) {
5751 clear_commit_todo_item(&commit_todo);
5752 return error(_("the script was already rearranged."));
5755 *commit_todo_item_at(&commit_todo, item->commit) = item;
5757 parse_commit(item->commit);
5758 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5759 find_commit_subject(commit_buffer, &subject);
5760 format_subject(&buf, subject, " ");
5761 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5762 unuse_commit_buffer(item->commit, commit_buffer);
5763 if (skip_fixupish(subject, &p)) {
5764 struct commit *commit2;
5769 if (!skip_fixupish(p, &p))
5773 entry = hashmap_get_entry_from_hash(&subject2item,
5775 struct subject2item_entry,
5778 /* found by title */
5780 else if (!strchr(p, ' ') &&
5782 lookup_commit_reference_by_name(p)) &&
5783 *commit_todo_item_at(&commit_todo, commit2))
5784 /* found by commit name */
5785 i2 = *commit_todo_item_at(&commit_todo, commit2)
5788 /* copy can be a prefix of the commit subject */
5789 for (i2 = 0; i2 < i; i2++)
5791 starts_with(subjects[i2], p))
5799 if (starts_with(subject, "fixup!")) {
5800 todo_list->items[i].command = TODO_FIXUP;
5801 } else if (starts_with(subject, "amend!")) {
5802 todo_list->items[i].command = TODO_FIXUP;
5803 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5805 todo_list->items[i].command = TODO_SQUASH;
5811 next[i] = next[tail[i2]];
5815 } else if (!hashmap_get_from_hash(&subject2item,
5816 strhash(subject), subject)) {
5817 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5819 hashmap_entry_init(&entry->entry,
5820 strhash(entry->subject));
5821 hashmap_put(&subject2item, &entry->entry);
5826 for (i = 0; i < todo_list->nr; i++) {
5827 enum todo_command command = todo_list->items[i].command;
5831 * Initially, all commands are 'pick's. If it is a
5832 * fixup or a squash now, we have rearranged it.
5834 if (is_fixup(command))
5838 ALLOC_GROW(items, nr + 1, alloc);
5839 items[nr++] = todo_list->items[cur];
5844 FREE_AND_NULL(todo_list->items);
5845 todo_list->items = items;
5847 todo_list->alloc = alloc;
5852 for (i = 0; i < todo_list->nr; i++)
5855 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5857 clear_commit_todo_item(&commit_todo);
5862 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5864 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5865 struct object_id cherry_pick_head, rebase_head;
5867 if (file_exists(git_path_seq_dir()))
5868 *whence = FROM_CHERRY_PICK_MULTI;
5869 if (file_exists(rebase_path()) &&
5870 !get_oid("REBASE_HEAD", &rebase_head) &&
5871 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5872 oideq(&rebase_head, &cherry_pick_head))
5873 *whence = FROM_REBASE_PICK;
5875 *whence = FROM_CHERRY_PICK_SINGLE;