5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-recursive.h"
19 #include "argv-array.h"
23 #include "wt-status.h"
25 #include "notes-utils.h"
27 #include "unpack-trees.h"
31 #include "commit-slab.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
36 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
38 static const char sign_off_header[] = "Signed-off-by: ";
39 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
41 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
43 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
45 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
50 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
57 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
60 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
63 * The rebase command lines that have already been processed. A line
64 * is moved here when it is first handled, before any associated user
67 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
69 * The file to keep track of how many commands were already processed (e.g.
72 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
74 * The file to keep track of how many commands are to be processed in total
75 * (e.g. for the prompt).
77 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
79 * The commit message that is planned to be used for any changes that
80 * need to be committed following a user interaction.
82 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
84 * The file into which is accumulated the suggested commit message for
85 * squash/fixup commands. When the first of a series of squash/fixups
86 * is seen, the file is created and the commit message from the
87 * previous commit and from the first squash/fixup commit are written
88 * to it. The commit message for each subsequent squash/fixup commit
89 * is appended to the file as it is processed.
91 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
93 * If the current series of squash/fixups has not yet included a squash
94 * command, then this file exists and holds the commit message of the
95 * original "pick" commit. (If the series ends without a "squash"
96 * command, then this can be used as the commit message of the combined
97 * commit without opening the editor.)
99 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
101 * This file contains the list fixup/squash commands that have been
102 * accumulated into message-fixup or message-squash so far.
104 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
106 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
107 * GIT_AUTHOR_DATE that will be used for the commit that is currently
110 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
112 * When an "edit" rebase command is being processed, the SHA1 of the
113 * commit to be edited is recorded in this file. When "git rebase
114 * --continue" is executed, if there are any staged changes then they
115 * will be amended to the HEAD commit, but only provided the HEAD
116 * commit is still the commit to be edited. When any other rebase
117 * command is processed, this file is deleted.
119 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
121 * When we stop at a given patch via the "edit" command, this file contains
122 * the abbreviated commit name of the corresponding patch.
124 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
126 * For the post-rewrite hook, we make a list of rewritten commits and
127 * their new sha1s. The rewritten-pending list keeps the sha1s of
128 * commits that have been processed, but not committed yet,
129 * e.g. because they are waiting for a 'squash' command.
131 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
132 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
133 "rebase-merge/rewritten-pending")
136 * The path of the file containing the OID of the "squash onto" commit, i.e.
137 * the dummy commit used for `reset [new root]`.
139 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
142 * The path of the file listing refs that need to be deleted after the rebase
143 * finishes. This is used by the `label` command to record the need for cleanup.
145 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
148 * The following files are written by git-rebase just after parsing the
151 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
152 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
153 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
154 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
155 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
156 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
157 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
158 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
159 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
160 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
161 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
162 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
163 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
164 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
165 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
167 static int git_sequencer_config(const char *k, const char *v, void *cb)
169 struct replay_opts *opts = cb;
172 if (!strcmp(k, "commit.cleanup")) {
175 status = git_config_string(&s, k, v);
179 if (!strcmp(s, "verbatim")) {
180 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
181 opts->explicit_cleanup = 1;
182 } else if (!strcmp(s, "whitespace")) {
183 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
184 opts->explicit_cleanup = 1;
185 } else if (!strcmp(s, "strip")) {
186 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
187 opts->explicit_cleanup = 1;
188 } else if (!strcmp(s, "scissors")) {
189 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
190 opts->explicit_cleanup = 1;
192 warning(_("invalid commit message cleanup mode '%s'"),
200 if (!strcmp(k, "commit.gpgsign")) {
201 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
205 status = git_gpg_config(k, v, NULL);
209 return git_diff_basic_config(k, v, NULL);
212 void sequencer_init_config(struct replay_opts *opts)
214 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
215 git_config(git_sequencer_config, opts);
218 static inline int is_rebase_i(const struct replay_opts *opts)
220 return opts->action == REPLAY_INTERACTIVE_REBASE;
223 static const char *get_dir(const struct replay_opts *opts)
225 if (is_rebase_i(opts))
226 return rebase_path();
227 return git_path_seq_dir();
230 static const char *get_todo_path(const struct replay_opts *opts)
232 if (is_rebase_i(opts))
233 return rebase_path_todo();
234 return git_path_todo_file();
238 * Returns 0 for non-conforming footer
239 * Returns 1 for conforming footer
240 * Returns 2 when sob exists within conforming footer
241 * Returns 3 when sob exists within conforming footer as last entry
243 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
244 size_t ignore_footer)
246 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
247 struct trailer_info info;
249 int found_sob = 0, found_sob_last = 0;
253 trailer_info_get(&info, sb->buf, &opts);
255 if (info.trailer_start == info.trailer_end)
258 for (i = 0; i < info.trailer_nr; i++)
259 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
261 if (i == info.trailer_nr - 1)
265 trailer_info_release(&info);
274 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
276 static struct strbuf buf = STRBUF_INIT;
280 sq_quotef(&buf, "-S%s", opts->gpg_sign);
284 int sequencer_remove_state(struct replay_opts *opts)
286 struct strbuf buf = STRBUF_INIT;
289 if (is_rebase_i(opts) &&
290 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
293 char *eol = strchr(p, '\n');
296 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
297 warning(_("could not delete '%s'"), p);
306 free(opts->committer_name);
307 free(opts->committer_email);
308 free(opts->gpg_sign);
309 free(opts->strategy);
310 for (i = 0; i < opts->xopts_nr; i++)
311 free(opts->xopts[i]);
313 strbuf_release(&opts->current_fixups);
316 strbuf_addstr(&buf, get_dir(opts));
317 if (remove_dir_recursively(&buf, 0))
318 ret = error(_("could not remove '%s'"), buf.buf);
319 strbuf_release(&buf);
324 static const char *action_name(const struct replay_opts *opts)
326 switch (opts->action) {
330 return N_("cherry-pick");
331 case REPLAY_INTERACTIVE_REBASE:
334 die(_("unknown action: %d"), opts->action);
337 struct commit_message {
344 static const char *short_commit_name(struct commit *commit)
346 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
349 static int get_message(struct commit *commit, struct commit_message *out)
351 const char *abbrev, *subject;
354 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
355 abbrev = short_commit_name(commit);
357 subject_len = find_commit_subject(out->message, &subject);
359 out->subject = xmemdupz(subject, subject_len);
360 out->label = xstrfmt("%s... %s", abbrev, out->subject);
361 out->parent_label = xstrfmt("parent of %s", out->label);
366 static void free_message(struct commit *commit, struct commit_message *msg)
368 free(msg->parent_label);
371 unuse_commit_buffer(commit, msg->message);
374 static void print_advice(struct repository *r, int show_hint,
375 struct replay_opts *opts)
377 char *msg = getenv("GIT_CHERRY_PICK_HELP");
380 fprintf(stderr, "%s\n", msg);
382 * A conflict has occurred but the porcelain
383 * (typically rebase --interactive) wants to take care
384 * of the commit itself so remove CHERRY_PICK_HEAD
386 unlink(git_path_cherry_pick_head(r));
392 advise(_("after resolving the conflicts, mark the corrected paths\n"
393 "with 'git add <paths>' or 'git rm <paths>'"));
395 advise(_("after resolving the conflicts, mark the corrected paths\n"
396 "with 'git add <paths>' or 'git rm <paths>'\n"
397 "and commit the result with 'git commit'"));
401 static int write_message(const void *buf, size_t len, const char *filename,
404 struct lock_file msg_file = LOCK_INIT;
406 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
408 return error_errno(_("could not lock '%s'"), filename);
409 if (write_in_full(msg_fd, buf, len) < 0) {
410 error_errno(_("could not write to '%s'"), filename);
411 rollback_lock_file(&msg_file);
414 if (append_eol && write(msg_fd, "\n", 1) < 0) {
415 error_errno(_("could not write eol to '%s'"), filename);
416 rollback_lock_file(&msg_file);
419 if (commit_lock_file(&msg_file) < 0)
420 return error(_("failed to finalize '%s'"), filename);
426 * Reads a file that was presumably written by a shell script, i.e. with an
427 * end-of-line marker that needs to be stripped.
429 * Note that only the last end-of-line marker is stripped, consistent with the
430 * behavior of "$(cat path)" in a shell script.
432 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
434 static int read_oneliner(struct strbuf *buf,
435 const char *path, int skip_if_empty)
437 int orig_len = buf->len;
439 if (!file_exists(path))
442 if (strbuf_read_file(buf, path, 0) < 0) {
443 warning_errno(_("could not read '%s'"), path);
447 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
448 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
450 buf->buf[buf->len] = '\0';
453 if (skip_if_empty && buf->len == orig_len)
459 static struct tree *empty_tree(struct repository *r)
461 return lookup_tree(r, the_hash_algo->empty_tree);
464 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
466 if (repo_read_index_unmerged(repo))
467 return error_resolve_conflict(_(action_name(opts)));
469 error(_("your local changes would be overwritten by %s."),
470 _(action_name(opts)));
472 if (advice_commit_before_merge)
473 advise(_("commit your changes or stash them to proceed."));
477 static void update_abort_safety_file(void)
479 struct object_id head;
481 /* Do nothing on a single-pick */
482 if (!file_exists(git_path_seq_dir()))
485 if (!get_oid("HEAD", &head))
486 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
488 write_file(git_path_abort_safety_file(), "%s", "");
491 static int fast_forward_to(struct repository *r,
492 const struct object_id *to,
493 const struct object_id *from,
495 struct replay_opts *opts)
497 struct ref_transaction *transaction;
498 struct strbuf sb = STRBUF_INIT;
499 struct strbuf err = STRBUF_INIT;
502 if (checkout_fast_forward(r, from, to, 1))
503 return -1; /* the callee should have complained already */
505 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
507 transaction = ref_transaction_begin(&err);
509 ref_transaction_update(transaction, "HEAD",
510 to, unborn && !is_rebase_i(opts) ?
513 ref_transaction_commit(transaction, &err)) {
514 ref_transaction_free(transaction);
515 error("%s", err.buf);
517 strbuf_release(&err);
522 strbuf_release(&err);
523 ref_transaction_free(transaction);
524 update_abort_safety_file();
528 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
531 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
532 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
533 COMMIT_MSG_CLEANUP_SPACE;
534 else if (!strcmp(cleanup_arg, "verbatim"))
535 return COMMIT_MSG_CLEANUP_NONE;
536 else if (!strcmp(cleanup_arg, "whitespace"))
537 return COMMIT_MSG_CLEANUP_SPACE;
538 else if (!strcmp(cleanup_arg, "strip"))
539 return COMMIT_MSG_CLEANUP_ALL;
540 else if (!strcmp(cleanup_arg, "scissors"))
541 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
542 COMMIT_MSG_CLEANUP_SPACE;
544 die(_("Invalid cleanup mode %s"), cleanup_arg);
548 * NB using int rather than enum cleanup_mode to stop clang's
549 * -Wtautological-constant-out-of-range-compare complaining that the comparison
552 static const char *describe_cleanup_mode(int cleanup_mode)
554 static const char *modes[] = { "whitespace",
559 if (cleanup_mode < ARRAY_SIZE(modes))
560 return modes[cleanup_mode];
562 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
565 void append_conflicts_hint(struct index_state *istate,
566 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
570 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
571 strbuf_addch(msgbuf, '\n');
572 wt_status_append_cut_line(msgbuf);
573 strbuf_addch(msgbuf, comment_line_char);
576 strbuf_addch(msgbuf, '\n');
577 strbuf_commented_addf(msgbuf, "Conflicts:\n");
578 for (i = 0; i < istate->cache_nr;) {
579 const struct cache_entry *ce = istate->cache[i++];
581 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
582 while (i < istate->cache_nr &&
583 !strcmp(ce->name, istate->cache[i]->name))
589 static int do_recursive_merge(struct repository *r,
590 struct commit *base, struct commit *next,
591 const char *base_label, const char *next_label,
592 struct object_id *head, struct strbuf *msgbuf,
593 struct replay_opts *opts)
595 struct merge_options o;
596 struct tree *next_tree, *base_tree, *head_tree;
599 struct lock_file index_lock = LOCK_INIT;
601 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
606 init_merge_options(&o, r);
607 o.ancestor = base ? base_label : "(empty tree)";
609 o.branch2 = next ? next_label : "(empty tree)";
610 if (is_rebase_i(opts))
612 o.show_rename_progress = 1;
614 head_tree = parse_tree_indirect(head);
615 next_tree = next ? get_commit_tree(next) : empty_tree(r);
616 base_tree = base ? get_commit_tree(base) : empty_tree(r);
618 for (i = 0; i < opts->xopts_nr; i++)
619 parse_merge_opt(&o, opts->xopts[i]);
621 clean = merge_trees(&o,
623 next_tree, base_tree);
624 if (is_rebase_i(opts) && clean <= 0)
625 fputs(o.obuf.buf, stdout);
626 strbuf_release(&o.obuf);
628 rollback_lock_file(&index_lock);
632 if (write_locked_index(r->index, &index_lock,
633 COMMIT_LOCK | SKIP_IF_UNCHANGED))
635 * TRANSLATORS: %s will be "revert", "cherry-pick" or
638 return error(_("%s: Unable to write new index file"),
639 _(action_name(opts)));
642 append_conflicts_hint(r->index, msgbuf,
643 opts->default_msg_cleanup);
648 static struct object_id *get_cache_tree_oid(struct index_state *istate)
650 if (!istate->cache_tree)
651 istate->cache_tree = cache_tree();
653 if (!cache_tree_fully_valid(istate->cache_tree))
654 if (cache_tree_update(istate, 0)) {
655 error(_("unable to update cache tree"));
659 return &istate->cache_tree->oid;
662 static int is_index_unchanged(struct repository *r)
664 struct object_id head_oid, *cache_tree_oid;
665 struct commit *head_commit;
666 struct index_state *istate = r->index;
668 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
669 return error(_("could not resolve HEAD commit"));
671 head_commit = lookup_commit(r, &head_oid);
674 * If head_commit is NULL, check_commit, called from
675 * lookup_commit, would have indicated that head_commit is not
676 * a commit object already. parse_commit() will return failure
677 * without further complaints in such a case. Otherwise, if
678 * the commit is invalid, parse_commit() will complain. So
679 * there is nothing for us to say here. Just return failure.
681 if (parse_commit(head_commit))
684 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
687 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
690 static int write_author_script(const char *message)
692 struct strbuf buf = STRBUF_INIT;
697 if (!*message || starts_with(message, "\n")) {
699 /* Missing 'author' line? */
700 unlink(rebase_path_author_script());
702 } else if (skip_prefix(message, "author ", &message))
704 else if ((eol = strchr(message, '\n')))
709 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
710 while (*message && *message != '\n' && *message != '\r')
711 if (skip_prefix(message, " <", &message))
713 else if (*message != '\'')
714 strbuf_addch(&buf, *(message++));
716 strbuf_addf(&buf, "'\\%c'", *(message++));
717 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
718 while (*message && *message != '\n' && *message != '\r')
719 if (skip_prefix(message, "> ", &message))
721 else if (*message != '\'')
722 strbuf_addch(&buf, *(message++));
724 strbuf_addf(&buf, "'\\%c'", *(message++));
725 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
726 while (*message && *message != '\n' && *message != '\r')
727 if (*message != '\'')
728 strbuf_addch(&buf, *(message++));
730 strbuf_addf(&buf, "'\\%c'", *(message++));
731 strbuf_addch(&buf, '\'');
732 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
733 strbuf_release(&buf);
738 * Take a series of KEY='VALUE' lines where VALUE part is
739 * sq-quoted, and append <KEY, VALUE> at the end of the string list
741 static int parse_key_value_squoted(char *buf, struct string_list *list)
744 struct string_list_item *item;
746 char *cp = strchr(buf, '=');
748 np = strchrnul(buf, '\n');
749 return error(_("no key present in '%.*s'"),
750 (int) (np - buf), buf);
752 np = strchrnul(cp, '\n');
754 item = string_list_append(list, buf);
756 buf = np + (*np == '\n');
760 return error(_("unable to dequote value of '%s'"),
762 item->util = xstrdup(cp);
768 * Reads and parses the state directory's "author-script" file, and sets name,
769 * email and date accordingly.
770 * Returns 0 on success, -1 if the file could not be parsed.
772 * The author script is of the format:
774 * GIT_AUTHOR_NAME='$author_name'
775 * GIT_AUTHOR_EMAIL='$author_email'
776 * GIT_AUTHOR_DATE='$author_date'
778 * where $author_name, $author_email and $author_date are quoted. We are strict
779 * with our parsing, as the file was meant to be eval'd in the now-removed
780 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
781 * from what this function expects, it is better to bail out than to do
782 * something that the user does not expect.
784 int read_author_script(const char *path, char **name, char **email, char **date,
787 struct strbuf buf = STRBUF_INIT;
788 struct string_list kv = STRING_LIST_INIT_DUP;
789 int retval = -1; /* assume failure */
790 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
792 if (strbuf_read_file(&buf, path, 256) <= 0) {
793 strbuf_release(&buf);
794 if (errno == ENOENT && allow_missing)
797 return error_errno(_("could not open '%s' for reading"),
801 if (parse_key_value_squoted(buf.buf, &kv))
804 for (i = 0; i < kv.nr; i++) {
805 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
807 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
810 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
812 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
815 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
817 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
821 err = error(_("unknown variable '%s'"),
826 error(_("missing 'GIT_AUTHOR_NAME'"));
828 error(_("missing 'GIT_AUTHOR_EMAIL'"));
830 error(_("missing 'GIT_AUTHOR_DATE'"));
831 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
833 *name = kv.items[name_i].util;
834 *email = kv.items[email_i].util;
835 *date = kv.items[date_i].util;
838 string_list_clear(&kv, !!retval);
839 strbuf_release(&buf);
844 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
845 * file with shell quoting into struct argv_array. Returns -1 on
846 * error, 0 otherwise.
848 static int read_env_script(struct argv_array *env)
850 char *name, *email, *date;
852 if (read_author_script(rebase_path_author_script(),
853 &name, &email, &date, 0))
856 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
857 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
858 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
866 static char *get_author(const char *message)
871 a = find_commit_header(message, "author", &len);
873 return xmemdupz(a, len);
878 static const char *author_date_from_env_array(const struct argv_array *env)
883 for (i = 0; i < env->argc; i++)
884 if (skip_prefix(env->argv[i],
885 "GIT_AUTHOR_DATE=", &date))
888 * If GIT_AUTHOR_DATE is missing we should have already errored out when
891 BUG("GIT_AUTHOR_DATE missing from author script");
894 static const char staged_changes_advice[] =
895 N_("you have staged changes in your working tree\n"
896 "If these changes are meant to be squashed into the previous commit, run:\n"
898 " git commit --amend %s\n"
900 "If they are meant to go into a new commit, run:\n"
904 "In both cases, once you're done, continue with:\n"
906 " git rebase --continue\n");
908 #define ALLOW_EMPTY (1<<0)
909 #define EDIT_MSG (1<<1)
910 #define AMEND_MSG (1<<2)
911 #define CLEANUP_MSG (1<<3)
912 #define VERIFY_MSG (1<<4)
913 #define CREATE_ROOT_COMMIT (1<<5)
915 static int run_command_silent_on_success(struct child_process *cmd)
917 struct strbuf buf = STRBUF_INIT;
920 cmd->stdout_to_stderr = 1;
921 rc = pipe_command(cmd,
927 fputs(buf.buf, stderr);
928 strbuf_release(&buf);
933 * If we are cherry-pick, and if the merge did not result in
934 * hand-editing, we will hit this commit and inherit the original
935 * author date and name.
937 * If we are revert, or if our cherry-pick results in a hand merge,
938 * we had better say that the current user is responsible for that.
940 * An exception is when run_git_commit() is called during an
941 * interactive rebase: in that case, we will want to retain the
944 static int run_git_commit(struct repository *r,
946 struct replay_opts *opts,
949 struct child_process cmd = CHILD_PROCESS_INIT;
953 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
954 const char *gpg_opt = gpg_sign_opt_quoted(opts);
956 return error(_(staged_changes_advice),
960 if (opts->committer_date_is_author_date)
961 argv_array_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
962 author_date_from_env_array(&cmd.env_array));
964 argv_array_push(&cmd.args, "commit");
966 if (!(flags & VERIFY_MSG))
967 argv_array_push(&cmd.args, "-n");
968 if ((flags & AMEND_MSG))
969 argv_array_push(&cmd.args, "--amend");
971 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
973 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
974 else if (!(flags & EDIT_MSG))
975 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
976 if ((flags & CLEANUP_MSG))
977 argv_array_push(&cmd.args, "--cleanup=strip");
978 if ((flags & EDIT_MSG))
979 argv_array_push(&cmd.args, "-e");
980 else if (!(flags & CLEANUP_MSG) &&
981 !opts->signoff && !opts->record_origin &&
982 !opts->explicit_cleanup)
983 argv_array_push(&cmd.args, "--cleanup=verbatim");
985 if ((flags & ALLOW_EMPTY))
986 argv_array_push(&cmd.args, "--allow-empty");
988 if (!(flags & EDIT_MSG))
989 argv_array_push(&cmd.args, "--allow-empty-message");
991 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
992 return run_command_silent_on_success(&cmd);
994 return run_command(&cmd);
997 static int rest_is_empty(const struct strbuf *sb, int start)
1002 /* Check if the rest is just whitespace and Signed-off-by's. */
1003 for (i = start; i < sb->len; i++) {
1004 nl = memchr(sb->buf + i, '\n', sb->len - i);
1010 if (strlen(sign_off_header) <= eol - i &&
1011 starts_with(sb->buf + i, sign_off_header)) {
1016 if (!isspace(sb->buf[i++]))
1023 void cleanup_message(struct strbuf *msgbuf,
1024 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1026 if (verbose || /* Truncate the message just before the diff, if any. */
1027 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1028 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1029 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1030 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1034 * Find out if the message in the strbuf contains only whitespace and
1035 * Signed-off-by lines.
1037 int message_is_empty(const struct strbuf *sb,
1038 enum commit_msg_cleanup_mode cleanup_mode)
1040 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1042 return rest_is_empty(sb, 0);
1046 * See if the user edited the message in the editor or left what
1047 * was in the template intact
1049 int template_untouched(const struct strbuf *sb, const char *template_file,
1050 enum commit_msg_cleanup_mode cleanup_mode)
1052 struct strbuf tmpl = STRBUF_INIT;
1055 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1058 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1061 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1062 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1064 strbuf_release(&tmpl);
1065 return rest_is_empty(sb, start - sb->buf);
1068 int update_head_with_reflog(const struct commit *old_head,
1069 const struct object_id *new_head,
1070 const char *action, const struct strbuf *msg,
1073 struct ref_transaction *transaction;
1074 struct strbuf sb = STRBUF_INIT;
1079 strbuf_addstr(&sb, action);
1080 strbuf_addstr(&sb, ": ");
1083 nl = strchr(msg->buf, '\n');
1085 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1087 strbuf_addbuf(&sb, msg);
1088 strbuf_addch(&sb, '\n');
1091 transaction = ref_transaction_begin(err);
1093 ref_transaction_update(transaction, "HEAD", new_head,
1094 old_head ? &old_head->object.oid : &null_oid,
1096 ref_transaction_commit(transaction, err)) {
1099 ref_transaction_free(transaction);
1100 strbuf_release(&sb);
1105 static int run_rewrite_hook(const struct object_id *oldoid,
1106 const struct object_id *newoid)
1108 struct child_process proc = CHILD_PROCESS_INIT;
1109 const char *argv[3];
1111 struct strbuf sb = STRBUF_INIT;
1113 argv[0] = find_hook("post-rewrite");
1122 proc.stdout_to_stderr = 1;
1123 proc.trace2_hook_name = "post-rewrite";
1125 code = start_command(&proc);
1128 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1129 sigchain_push(SIGPIPE, SIG_IGN);
1130 write_in_full(proc.in, sb.buf, sb.len);
1132 strbuf_release(&sb);
1133 sigchain_pop(SIGPIPE);
1134 return finish_command(&proc);
1137 void commit_post_rewrite(struct repository *r,
1138 const struct commit *old_head,
1139 const struct object_id *new_head)
1141 struct notes_rewrite_cfg *cfg;
1143 cfg = init_copy_notes_for_rewrite("amend");
1145 /* we are amending, so old_head is not NULL */
1146 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1147 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1149 run_rewrite_hook(&old_head->object.oid, new_head);
1152 static int run_prepare_commit_msg_hook(struct repository *r,
1157 const char *name, *arg1 = NULL, *arg2 = NULL;
1159 name = git_path_commit_editmsg();
1160 if (write_message(msg->buf, msg->len, name, 0))
1169 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1171 ret = error(_("'prepare-commit-msg' hook failed"));
1176 static const char implicit_ident_advice_noconfig[] =
1177 N_("Your name and email address were configured automatically based\n"
1178 "on your username and hostname. Please check that they are accurate.\n"
1179 "You can suppress this message by setting them explicitly. Run the\n"
1180 "following command and follow the instructions in your editor to edit\n"
1181 "your configuration file:\n"
1183 " git config --global --edit\n"
1185 "After doing this, you may fix the identity used for this commit with:\n"
1187 " git commit --amend --reset-author\n");
1189 static const char implicit_ident_advice_config[] =
1190 N_("Your name and email address were configured automatically based\n"
1191 "on your username and hostname. Please check that they are accurate.\n"
1192 "You can suppress this message by setting them explicitly:\n"
1194 " git config --global user.name \"Your Name\"\n"
1195 " git config --global user.email you@example.com\n"
1197 "After doing this, you may fix the identity used for this commit with:\n"
1199 " git commit --amend --reset-author\n");
1201 static const char *implicit_ident_advice(void)
1203 char *user_config = expand_user_path("~/.gitconfig", 0);
1204 char *xdg_config = xdg_config_home("config");
1205 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1211 return _(implicit_ident_advice_config);
1213 return _(implicit_ident_advice_noconfig);
1217 void print_commit_summary(struct repository *r,
1219 const struct object_id *oid,
1222 struct rev_info rev;
1223 struct commit *commit;
1224 struct strbuf format = STRBUF_INIT;
1226 struct pretty_print_context pctx = {0};
1227 struct strbuf author_ident = STRBUF_INIT;
1228 struct strbuf committer_ident = STRBUF_INIT;
1230 commit = lookup_commit(r, oid);
1232 die(_("couldn't look up newly created commit"));
1233 if (parse_commit(commit))
1234 die(_("could not parse newly created commit"));
1236 strbuf_addstr(&format, "format:%h] %s");
1238 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1239 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1240 if (strbuf_cmp(&author_ident, &committer_ident)) {
1241 strbuf_addstr(&format, "\n Author: ");
1242 strbuf_addbuf_percentquote(&format, &author_ident);
1244 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1245 struct strbuf date = STRBUF_INIT;
1247 format_commit_message(commit, "%ad", &date, &pctx);
1248 strbuf_addstr(&format, "\n Date: ");
1249 strbuf_addbuf_percentquote(&format, &date);
1250 strbuf_release(&date);
1252 if (!committer_ident_sufficiently_given()) {
1253 strbuf_addstr(&format, "\n Committer: ");
1254 strbuf_addbuf_percentquote(&format, &committer_ident);
1255 if (advice_implicit_identity) {
1256 strbuf_addch(&format, '\n');
1257 strbuf_addstr(&format, implicit_ident_advice());
1260 strbuf_release(&author_ident);
1261 strbuf_release(&committer_ident);
1263 repo_init_revisions(r, &rev, prefix);
1264 setup_revisions(0, NULL, &rev, NULL);
1267 rev.diffopt.output_format =
1268 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1270 rev.verbose_header = 1;
1271 rev.show_root_diff = 1;
1272 get_commit_format(format.buf, &rev);
1273 rev.always_show_header = 0;
1274 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1275 rev.diffopt.break_opt = 0;
1276 diff_setup_done(&rev.diffopt);
1278 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1280 die_errno(_("unable to resolve HEAD after creating commit"));
1281 if (!strcmp(head, "HEAD"))
1282 head = _("detached HEAD");
1284 skip_prefix(head, "refs/heads/", &head);
1285 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1286 _(" (root-commit)") : "");
1288 if (!log_tree_commit(&rev, commit)) {
1289 rev.always_show_header = 1;
1290 rev.use_terminator = 1;
1291 log_tree_commit(&rev, commit);
1294 strbuf_release(&format);
1297 static int parse_head(struct repository *r, struct commit **head)
1299 struct commit *current_head;
1300 struct object_id oid;
1302 if (get_oid("HEAD", &oid)) {
1303 current_head = NULL;
1305 current_head = lookup_commit_reference(r, &oid);
1307 return error(_("could not parse HEAD"));
1308 if (!oideq(&oid, ¤t_head->object.oid)) {
1309 warning(_("HEAD %s is not a commit!"),
1312 if (parse_commit(current_head))
1313 return error(_("could not parse HEAD commit"));
1315 *head = current_head;
1321 * Try to commit without forking 'git commit'. In some cases we need
1322 * to run 'git commit' to display an error message
1325 * -1 - error unable to commit
1327 * 1 - run 'git commit'
1329 static int try_to_commit(struct repository *r,
1330 struct strbuf *msg, const char *author,
1331 struct replay_opts *opts, unsigned int flags,
1332 struct object_id *oid)
1334 struct object_id tree;
1335 struct commit *current_head = NULL;
1336 struct commit_list *parents = NULL;
1337 struct commit_extra_header *extra = NULL;
1338 struct strbuf err = STRBUF_INIT;
1339 struct strbuf commit_msg = STRBUF_INIT;
1340 char *amend_author = NULL;
1341 const char *committer = NULL;
1342 const char *hook_commit = NULL;
1343 enum commit_msg_cleanup_mode cleanup;
1346 if (parse_head(r, ¤t_head))
1349 if (flags & AMEND_MSG) {
1350 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1351 const char *out_enc = get_commit_output_encoding();
1352 const char *message = logmsg_reencode(current_head, NULL,
1356 const char *orig_message = NULL;
1358 find_commit_subject(message, &orig_message);
1360 strbuf_addstr(msg, orig_message);
1361 hook_commit = "HEAD";
1363 author = amend_author = get_author(message);
1364 unuse_commit_buffer(current_head, message);
1366 res = error(_("unable to parse commit author"));
1369 parents = copy_commit_list(current_head->parents);
1370 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1371 } else if (current_head &&
1372 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1373 commit_list_insert(current_head, &parents);
1376 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1377 res = error(_("git write-tree failed to write a tree"));
1381 if (!(flags & ALLOW_EMPTY)) {
1382 struct commit *first_parent = current_head;
1384 if (flags & AMEND_MSG) {
1385 if (current_head->parents) {
1386 first_parent = current_head->parents->item;
1387 if (repo_parse_commit(r, first_parent)) {
1388 res = error(_("could not parse HEAD commit"));
1392 first_parent = NULL;
1395 if (oideq(first_parent
1396 ? get_commit_tree_oid(first_parent)
1397 : the_hash_algo->empty_tree,
1399 res = 1; /* run 'git commit' to display error message */
1404 if (find_hook("prepare-commit-msg")) {
1405 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1408 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1410 res = error_errno(_("unable to read commit message "
1412 git_path_commit_editmsg());
1418 if (flags & CLEANUP_MSG)
1419 cleanup = COMMIT_MSG_CLEANUP_ALL;
1420 else if ((opts->signoff || opts->record_origin) &&
1421 !opts->explicit_cleanup)
1422 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1424 cleanup = opts->default_msg_cleanup;
1426 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1427 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1428 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1429 res = 1; /* run 'git commit' to display error message */
1433 if (opts->committer_date_is_author_date) {
1434 struct ident_split id;
1435 struct strbuf date = STRBUF_INIT;
1437 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1438 res = error(_("invalid author identity '%s'"), author);
1441 if (!id.date_begin) {
1442 res = error(_("corrupt author: missing date information"));
1445 strbuf_addf(&date, "@%.*s %.*s",
1446 (int)(id.date_end - id.date_begin), id.date_begin,
1447 (int)(id.tz_end - id.tz_begin), id.tz_begin);
1448 committer = fmt_ident(opts->committer_name,
1449 opts->committer_email,
1450 WANT_COMMITTER_IDENT, date.buf,
1452 strbuf_release(&date);
1457 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1458 author, committer, opts->gpg_sign, extra)) {
1459 res = error(_("failed to write commit object"));
1463 if (update_head_with_reflog(current_head, oid,
1464 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1465 res = error("%s", err.buf);
1469 run_commit_hook(0, r->index_file, "post-commit", NULL);
1470 if (flags & AMEND_MSG)
1471 commit_post_rewrite(r, current_head, oid);
1474 free_commit_extra_headers(extra);
1475 strbuf_release(&err);
1476 strbuf_release(&commit_msg);
1482 static int write_rebase_head(struct object_id *oid)
1484 if (update_ref("rebase", "REBASE_HEAD", oid,
1485 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1486 return error(_("could not update %s"), "REBASE_HEAD");
1491 static int do_commit(struct repository *r,
1492 const char *msg_file, const char *author,
1493 struct replay_opts *opts, unsigned int flags,
1494 struct object_id *oid)
1498 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1499 struct object_id oid;
1500 struct strbuf sb = STRBUF_INIT;
1502 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1503 return error_errno(_("unable to read commit message "
1507 res = try_to_commit(r, msg_file ? &sb : NULL,
1508 author, opts, flags, &oid);
1509 strbuf_release(&sb);
1511 unlink(git_path_cherry_pick_head(r));
1512 unlink(git_path_merge_msg(r));
1513 if (!is_rebase_i(opts))
1514 print_commit_summary(r, NULL, &oid,
1515 SUMMARY_SHOW_AUTHOR_DATE);
1520 if (is_rebase_i(opts) && oid)
1521 if (write_rebase_head(oid))
1523 return run_git_commit(r, msg_file, opts, flags);
1529 static int is_original_commit_empty(struct commit *commit)
1531 const struct object_id *ptree_oid;
1533 if (parse_commit(commit))
1534 return error(_("could not parse commit %s"),
1535 oid_to_hex(&commit->object.oid));
1536 if (commit->parents) {
1537 struct commit *parent = commit->parents->item;
1538 if (parse_commit(parent))
1539 return error(_("could not parse parent commit %s"),
1540 oid_to_hex(&parent->object.oid));
1541 ptree_oid = get_commit_tree_oid(parent);
1543 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1546 return oideq(ptree_oid, get_commit_tree_oid(commit));
1550 * Should empty commits be allowed? Return status:
1551 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1552 * 0: Halt on empty commit
1553 * 1: Allow empty commit
1554 * 2: Drop empty commit
1556 static int allow_empty(struct repository *r,
1557 struct replay_opts *opts,
1558 struct commit *commit)
1560 int index_unchanged, originally_empty;
1565 * (1) we do not allow empty at all and error out.
1567 * (2) we allow ones that were initially empty, and
1568 * just drop the ones that become empty
1570 * (3) we allow ones that were initially empty, but
1571 * halt for the ones that become empty;
1573 * (4) we allow both.
1575 if (!opts->allow_empty)
1576 return 0; /* let "git commit" barf as necessary */
1578 index_unchanged = is_index_unchanged(r);
1579 if (index_unchanged < 0)
1580 return index_unchanged;
1581 if (!index_unchanged)
1582 return 0; /* we do not have to say --allow-empty */
1584 if (opts->keep_redundant_commits)
1587 originally_empty = is_original_commit_empty(commit);
1588 if (originally_empty < 0)
1589 return originally_empty;
1590 if (originally_empty)
1592 else if (opts->drop_redundant_commits)
1601 } todo_command_info[] = {
1618 static const char *command_to_string(const enum todo_command command)
1620 if (command < TODO_COMMENT)
1621 return todo_command_info[command].str;
1622 die(_("unknown command: %d"), command);
1625 static char command_to_char(const enum todo_command command)
1627 if (command < TODO_COMMENT && todo_command_info[command].c)
1628 return todo_command_info[command].c;
1629 return comment_line_char;
1632 static int is_noop(const enum todo_command command)
1634 return TODO_NOOP <= command;
1637 static int is_fixup(enum todo_command command)
1639 return command == TODO_FIXUP || command == TODO_SQUASH;
1642 /* Does this command create a (non-merge) commit? */
1643 static int is_pick_or_similar(enum todo_command command)
1658 static int update_squash_messages(struct repository *r,
1659 enum todo_command command,
1660 struct commit *commit,
1661 struct replay_opts *opts)
1663 struct strbuf buf = STRBUF_INIT;
1665 const char *message, *body;
1666 const char *encoding = get_commit_output_encoding();
1668 if (opts->current_fixup_count > 0) {
1669 struct strbuf header = STRBUF_INIT;
1672 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1673 return error(_("could not read '%s'"),
1674 rebase_path_squash_msg());
1676 eol = buf.buf[0] != comment_line_char ?
1677 buf.buf : strchrnul(buf.buf, '\n');
1679 strbuf_addf(&header, "%c ", comment_line_char);
1680 strbuf_addf(&header, _("This is a combination of %d commits."),
1681 opts->current_fixup_count + 2);
1682 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1683 strbuf_release(&header);
1685 struct object_id head;
1686 struct commit *head_commit;
1687 const char *head_message, *body;
1689 if (get_oid("HEAD", &head))
1690 return error(_("need a HEAD to fixup"));
1691 if (!(head_commit = lookup_commit_reference(r, &head)))
1692 return error(_("could not read HEAD"));
1693 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1694 return error(_("could not read HEAD's commit message"));
1696 find_commit_subject(head_message, &body);
1697 if (write_message(body, strlen(body),
1698 rebase_path_fixup_msg(), 0)) {
1699 unuse_commit_buffer(head_commit, head_message);
1700 return error(_("cannot write '%s'"),
1701 rebase_path_fixup_msg());
1704 strbuf_addf(&buf, "%c ", comment_line_char);
1705 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1706 strbuf_addf(&buf, "\n%c ", comment_line_char);
1707 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1708 strbuf_addstr(&buf, "\n\n");
1709 strbuf_addstr(&buf, body);
1711 unuse_commit_buffer(head_commit, head_message);
1714 if (!(message = logmsg_reencode(commit, NULL, encoding)))
1715 return error(_("could not read commit message of %s"),
1716 oid_to_hex(&commit->object.oid));
1717 find_commit_subject(message, &body);
1719 if (command == TODO_SQUASH) {
1720 unlink(rebase_path_fixup_msg());
1721 strbuf_addf(&buf, "\n%c ", comment_line_char);
1722 strbuf_addf(&buf, _("This is the commit message #%d:"),
1723 ++opts->current_fixup_count + 1);
1724 strbuf_addstr(&buf, "\n\n");
1725 strbuf_addstr(&buf, body);
1726 } else if (command == TODO_FIXUP) {
1727 strbuf_addf(&buf, "\n%c ", comment_line_char);
1728 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1729 ++opts->current_fixup_count + 1);
1730 strbuf_addstr(&buf, "\n\n");
1731 strbuf_add_commented_lines(&buf, body, strlen(body));
1733 return error(_("unknown command: %d"), command);
1734 unuse_commit_buffer(commit, message);
1736 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1737 strbuf_release(&buf);
1740 strbuf_addf(&opts->current_fixups, "%s%s %s",
1741 opts->current_fixups.len ? "\n" : "",
1742 command_to_string(command),
1743 oid_to_hex(&commit->object.oid));
1744 res = write_message(opts->current_fixups.buf,
1745 opts->current_fixups.len,
1746 rebase_path_current_fixups(), 0);
1752 static void flush_rewritten_pending(void)
1754 struct strbuf buf = STRBUF_INIT;
1755 struct object_id newoid;
1758 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1759 !get_oid("HEAD", &newoid) &&
1760 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1761 char *bol = buf.buf, *eol;
1764 eol = strchrnul(bol, '\n');
1765 fprintf(out, "%.*s %s\n", (int)(eol - bol),
1766 bol, oid_to_hex(&newoid));
1772 unlink(rebase_path_rewritten_pending());
1774 strbuf_release(&buf);
1777 static void record_in_rewritten(struct object_id *oid,
1778 enum todo_command next_command)
1780 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1785 fprintf(out, "%s\n", oid_to_hex(oid));
1788 if (!is_fixup(next_command))
1789 flush_rewritten_pending();
1792 static int do_pick_commit(struct repository *r,
1793 enum todo_command command,
1794 struct commit *commit,
1795 struct replay_opts *opts,
1796 int final_fixup, int *check_todo)
1798 unsigned int flags = opts->edit ? EDIT_MSG : 0;
1799 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1800 struct object_id head;
1801 struct commit *base, *next, *parent;
1802 const char *base_label, *next_label;
1803 char *author = NULL;
1804 struct commit_message msg = { NULL, NULL, NULL, NULL };
1805 struct strbuf msgbuf = STRBUF_INIT;
1806 int res, unborn = 0, reword = 0, allow, drop_commit;
1808 if (opts->no_commit) {
1810 * We do not intend to commit immediately. We just want to
1811 * merge the differences in, so let's compute the tree
1812 * that represents the "current" state for merge-recursive
1815 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1816 return error(_("your index file is unmerged."));
1818 unborn = get_oid("HEAD", &head);
1819 /* Do we want to generate a root commit? */
1820 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1821 oideq(&head, &opts->squash_onto)) {
1822 if (is_fixup(command))
1823 return error(_("cannot fixup root commit"));
1824 flags |= CREATE_ROOT_COMMIT;
1827 oidcpy(&head, the_hash_algo->empty_tree);
1828 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1830 return error_dirty_index(r, opts);
1832 discard_index(r->index);
1834 if (!commit->parents)
1836 else if (commit->parents->next) {
1837 /* Reverting or cherry-picking a merge commit */
1839 struct commit_list *p;
1841 if (!opts->mainline)
1842 return error(_("commit %s is a merge but no -m option was given."),
1843 oid_to_hex(&commit->object.oid));
1845 for (cnt = 1, p = commit->parents;
1846 cnt != opts->mainline && p;
1849 if (cnt != opts->mainline || !p)
1850 return error(_("commit %s does not have parent %d"),
1851 oid_to_hex(&commit->object.oid), opts->mainline);
1853 } else if (1 < opts->mainline)
1855 * Non-first parent explicitly specified as mainline for
1858 return error(_("commit %s does not have parent %d"),
1859 oid_to_hex(&commit->object.oid), opts->mainline);
1861 parent = commit->parents->item;
1863 if (get_message(commit, &msg) != 0)
1864 return error(_("cannot get commit message for %s"),
1865 oid_to_hex(&commit->object.oid));
1867 if (opts->allow_ff && !is_fixup(command) &&
1868 ((parent && oideq(&parent->object.oid, &head)) ||
1869 (!parent && unborn))) {
1870 if (is_rebase_i(opts))
1871 write_author_script(msg.message);
1872 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1874 if (res || command != TODO_REWORD)
1878 goto fast_forward_edit;
1880 if (parent && parse_commit(parent) < 0)
1881 /* TRANSLATORS: The first %s will be a "todo" command like
1882 "revert" or "pick", the second %s a SHA1. */
1883 return error(_("%s: cannot parse parent commit %s"),
1884 command_to_string(command),
1885 oid_to_hex(&parent->object.oid));
1888 * "commit" is an existing commit. We would want to apply
1889 * the difference it introduces since its first parent "prev"
1890 * on top of the current HEAD if we are cherry-pick. Or the
1891 * reverse of it if we are revert.
1894 if (command == TODO_REVERT) {
1896 base_label = msg.label;
1898 next_label = msg.parent_label;
1899 strbuf_addstr(&msgbuf, "Revert \"");
1900 strbuf_addstr(&msgbuf, msg.subject);
1901 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1902 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1904 if (commit->parents && commit->parents->next) {
1905 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1906 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1908 strbuf_addstr(&msgbuf, ".\n");
1913 base_label = msg.parent_label;
1915 next_label = msg.label;
1917 /* Append the commit log message to msgbuf. */
1918 if (find_commit_subject(msg.message, &p))
1919 strbuf_addstr(&msgbuf, p);
1921 if (opts->record_origin) {
1922 strbuf_complete_line(&msgbuf);
1923 if (!has_conforming_footer(&msgbuf, NULL, 0))
1924 strbuf_addch(&msgbuf, '\n');
1925 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1926 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1927 strbuf_addstr(&msgbuf, ")\n");
1929 if (!is_fixup(command))
1930 author = get_author(msg.message);
1933 if (command == TODO_REWORD)
1935 else if (is_fixup(command)) {
1936 if (update_squash_messages(r, command, commit, opts))
1940 msg_file = rebase_path_squash_msg();
1941 else if (file_exists(rebase_path_fixup_msg())) {
1942 flags |= CLEANUP_MSG;
1943 msg_file = rebase_path_fixup_msg();
1945 const char *dest = git_path_squash_msg(r);
1947 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1948 return error(_("could not rename '%s' to '%s'"),
1949 rebase_path_squash_msg(), dest);
1950 unlink(git_path_merge_msg(r));
1956 if (opts->signoff && !is_fixup(command))
1957 append_signoff(&msgbuf, 0, 0);
1959 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1961 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1962 res = do_recursive_merge(r, base, next, base_label, next_label,
1963 &head, &msgbuf, opts);
1967 res |= write_message(msgbuf.buf, msgbuf.len,
1968 git_path_merge_msg(r), 0);
1970 struct commit_list *common = NULL;
1971 struct commit_list *remotes = NULL;
1973 res = write_message(msgbuf.buf, msgbuf.len,
1974 git_path_merge_msg(r), 0);
1976 commit_list_insert(base, &common);
1977 commit_list_insert(next, &remotes);
1978 res |= try_merge_command(r, opts->strategy,
1979 opts->xopts_nr, (const char **)opts->xopts,
1980 common, oid_to_hex(&head), remotes);
1981 free_commit_list(common);
1982 free_commit_list(remotes);
1984 strbuf_release(&msgbuf);
1987 * If the merge was clean or if it failed due to conflict, we write
1988 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1989 * However, if the merge did not even start, then we don't want to
1992 if ((command == TODO_PICK || command == TODO_REWORD ||
1993 command == TODO_EDIT) && !opts->no_commit &&
1994 (res == 0 || res == 1) &&
1995 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1996 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1998 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1999 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2000 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2004 error(command == TODO_REVERT
2005 ? _("could not revert %s... %s")
2006 : _("could not apply %s... %s"),
2007 short_commit_name(commit), msg.subject);
2008 print_advice(r, res == 1, opts);
2009 repo_rerere(r, opts->allow_rerere_auto);
2014 allow = allow_empty(r, opts, commit);
2018 } else if (allow == 1) {
2019 flags |= ALLOW_EMPTY;
2020 } else if (allow == 2) {
2022 unlink(git_path_cherry_pick_head(r));
2023 unlink(git_path_merge_msg(r));
2025 _("dropping %s %s -- patch contents already upstream\n"),
2026 oid_to_hex(&commit->object.oid), msg.subject);
2027 } /* else allow == 0 and there's nothing special to do */
2028 if (!opts->no_commit && !drop_commit) {
2029 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2030 res = do_commit(r, msg_file, author, opts, flags,
2031 commit? &commit->object.oid : NULL);
2033 res = error(_("unable to parse commit author"));
2034 *check_todo = !!(flags & EDIT_MSG);
2035 if (!res && reword) {
2037 res = run_git_commit(r, NULL, opts, EDIT_MSG |
2038 VERIFY_MSG | AMEND_MSG |
2039 (flags & ALLOW_EMPTY));
2045 if (!res && final_fixup) {
2046 unlink(rebase_path_fixup_msg());
2047 unlink(rebase_path_squash_msg());
2048 unlink(rebase_path_current_fixups());
2049 strbuf_reset(&opts->current_fixups);
2050 opts->current_fixup_count = 0;
2054 free_message(commit, &msg);
2056 update_abort_safety_file();
2061 static int prepare_revs(struct replay_opts *opts)
2064 * picking (but not reverting) ranges (but not individual revisions)
2065 * should be done in reverse
2067 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2068 opts->revs->reverse ^= 1;
2070 if (prepare_revision_walk(opts->revs))
2071 return error(_("revision walk setup failed"));
2076 static int read_and_refresh_cache(struct repository *r,
2077 struct replay_opts *opts)
2079 struct lock_file index_lock = LOCK_INIT;
2080 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2081 if (repo_read_index(r) < 0) {
2082 rollback_lock_file(&index_lock);
2083 return error(_("git %s: failed to read the index"),
2084 _(action_name(opts)));
2086 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2087 if (index_fd >= 0) {
2088 if (write_locked_index(r->index, &index_lock,
2089 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2090 return error(_("git %s: failed to refresh the index"),
2091 _(action_name(opts)));
2097 enum todo_item_flags {
2098 TODO_EDIT_MERGE_MSG = 1
2101 void todo_list_release(struct todo_list *todo_list)
2103 strbuf_release(&todo_list->buf);
2104 FREE_AND_NULL(todo_list->items);
2105 todo_list->nr = todo_list->alloc = 0;
2108 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2110 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2111 todo_list->total_nr++;
2112 return todo_list->items + todo_list->nr++;
2115 const char *todo_item_get_arg(struct todo_list *todo_list,
2116 struct todo_item *item)
2118 return todo_list->buf.buf + item->arg_offset;
2121 static int is_command(enum todo_command command, const char **bol)
2123 const char *str = todo_command_info[command].str;
2124 const char nick = todo_command_info[command].c;
2125 const char *p = *bol + 1;
2127 return skip_prefix(*bol, str, bol) ||
2128 ((nick && **bol == nick) &&
2129 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2133 static int parse_insn_line(struct repository *r, struct todo_item *item,
2134 const char *buf, const char *bol, char *eol)
2136 struct object_id commit_oid;
2137 char *end_of_object_name;
2138 int i, saved, status, padding;
2143 bol += strspn(bol, " \t");
2145 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2146 item->command = TODO_COMMENT;
2147 item->commit = NULL;
2148 item->arg_offset = bol - buf;
2149 item->arg_len = eol - bol;
2153 for (i = 0; i < TODO_COMMENT; i++)
2154 if (is_command(i, &bol)) {
2158 if (i >= TODO_COMMENT)
2161 /* Eat up extra spaces/ tabs before object name */
2162 padding = strspn(bol, " \t");
2165 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2167 return error(_("%s does not accept arguments: '%s'"),
2168 command_to_string(item->command), bol);
2169 item->commit = NULL;
2170 item->arg_offset = bol - buf;
2171 item->arg_len = eol - bol;
2176 return error(_("missing arguments for %s"),
2177 command_to_string(item->command));
2179 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2180 item->command == TODO_RESET) {
2181 item->commit = NULL;
2182 item->arg_offset = bol - buf;
2183 item->arg_len = (int)(eol - bol);
2187 if (item->command == TODO_MERGE) {
2188 if (skip_prefix(bol, "-C", &bol))
2189 bol += strspn(bol, " \t");
2190 else if (skip_prefix(bol, "-c", &bol)) {
2191 bol += strspn(bol, " \t");
2192 item->flags |= TODO_EDIT_MERGE_MSG;
2194 item->flags |= TODO_EDIT_MERGE_MSG;
2195 item->commit = NULL;
2196 item->arg_offset = bol - buf;
2197 item->arg_len = (int)(eol - bol);
2202 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2203 saved = *end_of_object_name;
2204 *end_of_object_name = '\0';
2205 status = get_oid(bol, &commit_oid);
2207 error(_("could not parse '%s'"), bol); /* return later */
2208 *end_of_object_name = saved;
2210 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2211 item->arg_offset = bol - buf;
2212 item->arg_len = (int)(eol - bol);
2217 item->commit = lookup_commit_reference(r, &commit_oid);
2218 return item->commit ? 0 : -1;
2221 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2223 const char *todo_file, *bol;
2224 struct strbuf buf = STRBUF_INIT;
2227 todo_file = git_path_todo_file();
2228 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2229 if (errno == ENOENT || errno == ENOTDIR)
2232 return error_errno("unable to open '%s'", todo_file);
2234 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2235 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2236 *action = REPLAY_PICK;
2237 else if (is_command(TODO_REVERT, &bol) &&
2238 (*bol == ' ' || *bol == '\t'))
2239 *action = REPLAY_REVERT;
2243 strbuf_release(&buf);
2248 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2249 struct todo_list *todo_list)
2251 struct todo_item *item;
2252 char *p = buf, *next_p;
2253 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2255 todo_list->current = todo_list->nr = 0;
2257 for (i = 1; *p; i++, p = next_p) {
2258 char *eol = strchrnul(p, '\n');
2260 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2262 if (p != eol && eol[-1] == '\r')
2263 eol--; /* strip Carriage Return */
2265 item = append_new_todo(todo_list);
2266 item->offset_in_buf = p - todo_list->buf.buf;
2267 if (parse_insn_line(r, item, buf, p, eol)) {
2268 res = error(_("invalid line %d: %.*s"),
2269 i, (int)(eol - p), p);
2270 item->command = TODO_COMMENT + 1;
2271 item->arg_offset = p - buf;
2272 item->arg_len = (int)(eol - p);
2273 item->commit = NULL;
2278 else if (is_fixup(item->command))
2279 return error(_("cannot '%s' without a previous commit"),
2280 command_to_string(item->command));
2281 else if (!is_noop(item->command))
2288 static int count_commands(struct todo_list *todo_list)
2292 for (i = 0; i < todo_list->nr; i++)
2293 if (todo_list->items[i].command != TODO_COMMENT)
2299 static int get_item_line_offset(struct todo_list *todo_list, int index)
2301 return index < todo_list->nr ?
2302 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2305 static const char *get_item_line(struct todo_list *todo_list, int index)
2307 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2310 static int get_item_line_length(struct todo_list *todo_list, int index)
2312 return get_item_line_offset(todo_list, index + 1)
2313 - get_item_line_offset(todo_list, index);
2316 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2321 fd = open(path, O_RDONLY);
2323 return error_errno(_("could not open '%s'"), path);
2324 len = strbuf_read(sb, fd, 0);
2327 return error(_("could not read '%s'."), path);
2331 static int have_finished_the_last_pick(void)
2333 struct strbuf buf = STRBUF_INIT;
2335 const char *todo_path = git_path_todo_file();
2338 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2339 if (errno == ENOENT) {
2342 error_errno("unable to open '%s'", todo_path);
2346 /* If there is only one line then we are done */
2347 eol = strchr(buf.buf, '\n');
2348 if (!eol || !eol[1])
2351 strbuf_release(&buf);
2356 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2358 struct replay_opts opts = REPLAY_OPTS_INIT;
2359 int need_cleanup = 0;
2361 if (file_exists(git_path_cherry_pick_head(r))) {
2362 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2363 warning(_("cancelling a cherry picking in progress"));
2364 opts.action = REPLAY_PICK;
2368 if (file_exists(git_path_revert_head(r))) {
2369 if (!unlink(git_path_revert_head(r)) && verbose)
2370 warning(_("cancelling a revert in progress"));
2371 opts.action = REPLAY_REVERT;
2378 if (!have_finished_the_last_pick())
2381 sequencer_remove_state(&opts);
2384 static void todo_list_write_total_nr(struct todo_list *todo_list)
2386 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2389 fprintf(f, "%d\n", todo_list->total_nr);
2394 static int read_populate_todo(struct repository *r,
2395 struct todo_list *todo_list,
2396 struct replay_opts *opts)
2399 const char *todo_file = get_todo_path(opts);
2402 strbuf_reset(&todo_list->buf);
2403 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2406 res = stat(todo_file, &st);
2408 return error(_("could not stat '%s'"), todo_file);
2409 fill_stat_data(&todo_list->stat, &st);
2411 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2413 if (is_rebase_i(opts))
2414 return error(_("please fix this using "
2415 "'git rebase --edit-todo'."));
2416 return error(_("unusable instruction sheet: '%s'"), todo_file);
2419 if (!todo_list->nr &&
2420 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2421 return error(_("no commits parsed."));
2423 if (!is_rebase_i(opts)) {
2424 enum todo_command valid =
2425 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2428 for (i = 0; i < todo_list->nr; i++)
2429 if (valid == todo_list->items[i].command)
2431 else if (valid == TODO_PICK)
2432 return error(_("cannot cherry-pick during a revert."));
2434 return error(_("cannot revert during a cherry-pick."));
2437 if (is_rebase_i(opts)) {
2438 struct todo_list done = TODO_LIST_INIT;
2440 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2441 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2442 todo_list->done_nr = count_commands(&done);
2444 todo_list->done_nr = 0;
2446 todo_list->total_nr = todo_list->done_nr
2447 + count_commands(todo_list);
2448 todo_list_release(&done);
2450 todo_list_write_total_nr(todo_list);
2456 static int git_config_string_dup(char **dest,
2457 const char *var, const char *value)
2460 return config_error_nonbool(var);
2462 *dest = xstrdup(value);
2466 static int populate_opts_cb(const char *key, const char *value, void *data)
2468 struct replay_opts *opts = data;
2473 else if (!strcmp(key, "options.no-commit"))
2474 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2475 else if (!strcmp(key, "options.edit"))
2476 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2477 else if (!strcmp(key, "options.allow-empty"))
2479 git_config_bool_or_int(key, value, &error_flag);
2480 else if (!strcmp(key, "options.allow-empty-message"))
2481 opts->allow_empty_message =
2482 git_config_bool_or_int(key, value, &error_flag);
2483 else if (!strcmp(key, "options.keep-redundant-commits"))
2484 opts->keep_redundant_commits =
2485 git_config_bool_or_int(key, value, &error_flag);
2486 else if (!strcmp(key, "options.signoff"))
2487 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2488 else if (!strcmp(key, "options.record-origin"))
2489 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2490 else if (!strcmp(key, "options.allow-ff"))
2491 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2492 else if (!strcmp(key, "options.mainline"))
2493 opts->mainline = git_config_int(key, value);
2494 else if (!strcmp(key, "options.strategy"))
2495 git_config_string_dup(&opts->strategy, key, value);
2496 else if (!strcmp(key, "options.gpg-sign"))
2497 git_config_string_dup(&opts->gpg_sign, key, value);
2498 else if (!strcmp(key, "options.strategy-option")) {
2499 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2500 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2501 } else if (!strcmp(key, "options.allow-rerere-auto"))
2502 opts->allow_rerere_auto =
2503 git_config_bool_or_int(key, value, &error_flag) ?
2504 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2505 else if (!strcmp(key, "options.default-msg-cleanup")) {
2506 opts->explicit_cleanup = 1;
2507 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2509 return error(_("invalid key: %s"), key);
2512 return error(_("invalid value for %s: %s"), key, value);
2517 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2520 char *strategy_opts_string = raw_opts;
2522 if (*strategy_opts_string == ' ')
2523 strategy_opts_string++;
2525 opts->xopts_nr = split_cmdline(strategy_opts_string,
2526 (const char ***)&opts->xopts);
2527 for (i = 0; i < opts->xopts_nr; i++) {
2528 const char *arg = opts->xopts[i];
2530 skip_prefix(arg, "--", &arg);
2531 opts->xopts[i] = xstrdup(arg);
2535 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2538 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2540 opts->strategy = strbuf_detach(buf, NULL);
2541 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2544 parse_strategy_opts(opts, buf->buf);
2547 static int read_populate_opts(struct replay_opts *opts)
2549 if (is_rebase_i(opts)) {
2550 struct strbuf buf = STRBUF_INIT;
2552 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2553 if (!starts_with(buf.buf, "-S"))
2556 free(opts->gpg_sign);
2557 opts->gpg_sign = xstrdup(buf.buf + 2);
2562 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2563 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2564 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2565 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2566 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2570 if (file_exists(rebase_path_verbose()))
2573 if (file_exists(rebase_path_quiet()))
2576 if (file_exists(rebase_path_signoff())) {
2581 if (file_exists(rebase_path_cdate_is_adate())) {
2583 opts->committer_date_is_author_date = 1;
2586 if (file_exists(rebase_path_reschedule_failed_exec()))
2587 opts->reschedule_failed_exec = 1;
2589 if (file_exists(rebase_path_drop_redundant_commits()))
2590 opts->drop_redundant_commits = 1;
2592 if (file_exists(rebase_path_keep_redundant_commits()))
2593 opts->keep_redundant_commits = 1;
2595 read_strategy_opts(opts, &buf);
2596 strbuf_release(&buf);
2598 if (read_oneliner(&opts->current_fixups,
2599 rebase_path_current_fixups(), 1)) {
2600 const char *p = opts->current_fixups.buf;
2601 opts->current_fixup_count = 1;
2602 while ((p = strchr(p, '\n'))) {
2603 opts->current_fixup_count++;
2608 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2609 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2610 return error(_("unusable squash-onto"));
2611 opts->have_squash_onto = 1;
2617 if (!file_exists(git_path_opts_file()))
2620 * The function git_parse_source(), called from git_config_from_file(),
2621 * may die() in case of a syntactically incorrect file. We do not care
2622 * about this case, though, because we wrote that file ourselves, so we
2623 * are pretty certain that it is syntactically correct.
2625 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2626 return error(_("malformed options sheet: '%s'"),
2627 git_path_opts_file());
2631 static void write_strategy_opts(struct replay_opts *opts)
2634 struct strbuf buf = STRBUF_INIT;
2636 for (i = 0; i < opts->xopts_nr; ++i)
2637 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2639 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2640 strbuf_release(&buf);
2643 int write_basic_state(struct replay_opts *opts, const char *head_name,
2644 struct commit *onto, const char *orig_head)
2647 write_file(rebase_path_head_name(), "%s\n", head_name);
2649 write_file(rebase_path_onto(), "%s\n",
2650 oid_to_hex(&onto->object.oid));
2652 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2655 write_file(rebase_path_quiet(), "%s", "");
2657 write_file(rebase_path_verbose(), "%s", "");
2659 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2660 if (opts->xopts_nr > 0)
2661 write_strategy_opts(opts);
2663 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2664 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2665 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2666 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2669 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2671 write_file(rebase_path_signoff(), "--signoff\n");
2672 if (opts->drop_redundant_commits)
2673 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2674 if (opts->keep_redundant_commits)
2675 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2676 if (opts->committer_date_is_author_date)
2677 write_file(rebase_path_cdate_is_adate(), "%s", "");
2678 if (opts->reschedule_failed_exec)
2679 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2684 static int walk_revs_populate_todo(struct todo_list *todo_list,
2685 struct replay_opts *opts)
2687 enum todo_command command = opts->action == REPLAY_PICK ?
2688 TODO_PICK : TODO_REVERT;
2689 const char *command_string = todo_command_info[command].str;
2690 const char *encoding;
2691 struct commit *commit;
2693 if (prepare_revs(opts))
2696 encoding = get_log_output_encoding();
2698 while ((commit = get_revision(opts->revs))) {
2699 struct todo_item *item = append_new_todo(todo_list);
2700 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2701 const char *subject;
2704 item->command = command;
2705 item->commit = commit;
2706 item->arg_offset = 0;
2708 item->offset_in_buf = todo_list->buf.len;
2709 subject_len = find_commit_subject(commit_buffer, &subject);
2710 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2711 short_commit_name(commit), subject_len, subject);
2712 unuse_commit_buffer(commit, commit_buffer);
2716 return error(_("empty commit set passed"));
2721 static int create_seq_dir(struct repository *r)
2723 enum replay_action action;
2724 const char *in_progress_error = NULL;
2725 const char *in_progress_advice = NULL;
2726 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2727 file_exists(git_path_cherry_pick_head(r));
2729 if (!sequencer_get_last_command(r, &action)) {
2732 in_progress_error = _("revert is already in progress");
2733 in_progress_advice =
2734 _("try \"git revert (--continue | %s--abort | --quit)\"");
2737 in_progress_error = _("cherry-pick is already in progress");
2738 in_progress_advice =
2739 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2742 BUG("unexpected action in create_seq_dir");
2745 if (in_progress_error) {
2746 error("%s", in_progress_error);
2747 if (advice_sequencer_in_use)
2748 advise(in_progress_advice,
2749 advise_skip ? "--skip | " : "");
2752 if (mkdir(git_path_seq_dir(), 0777) < 0)
2753 return error_errno(_("could not create sequencer directory '%s'"),
2754 git_path_seq_dir());
2759 static int save_head(const char *head)
2761 struct lock_file head_lock = LOCK_INIT;
2762 struct strbuf buf = STRBUF_INIT;
2766 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2768 return error_errno(_("could not lock HEAD"));
2769 strbuf_addf(&buf, "%s\n", head);
2770 written = write_in_full(fd, buf.buf, buf.len);
2771 strbuf_release(&buf);
2773 error_errno(_("could not write to '%s'"), git_path_head_file());
2774 rollback_lock_file(&head_lock);
2777 if (commit_lock_file(&head_lock) < 0)
2778 return error(_("failed to finalize '%s'"), git_path_head_file());
2782 static int rollback_is_safe(void)
2784 struct strbuf sb = STRBUF_INIT;
2785 struct object_id expected_head, actual_head;
2787 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2789 if (get_oid_hex(sb.buf, &expected_head)) {
2790 strbuf_release(&sb);
2791 die(_("could not parse %s"), git_path_abort_safety_file());
2793 strbuf_release(&sb);
2795 else if (errno == ENOENT)
2796 oidclr(&expected_head);
2798 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2800 if (get_oid("HEAD", &actual_head))
2801 oidclr(&actual_head);
2803 return oideq(&actual_head, &expected_head);
2806 static int reset_merge(const struct object_id *oid)
2809 struct argv_array argv = ARGV_ARRAY_INIT;
2811 argv_array_pushl(&argv, "reset", "--merge", NULL);
2813 if (!is_null_oid(oid))
2814 argv_array_push(&argv, oid_to_hex(oid));
2816 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2817 argv_array_clear(&argv);
2822 static int rollback_single_pick(struct repository *r)
2824 struct object_id head_oid;
2826 if (!file_exists(git_path_cherry_pick_head(r)) &&
2827 !file_exists(git_path_revert_head(r)))
2828 return error(_("no cherry-pick or revert in progress"));
2829 if (read_ref_full("HEAD", 0, &head_oid, NULL))
2830 return error(_("cannot resolve HEAD"));
2831 if (is_null_oid(&head_oid))
2832 return error(_("cannot abort from a branch yet to be born"));
2833 return reset_merge(&head_oid);
2836 static int skip_single_pick(void)
2838 struct object_id head;
2840 if (read_ref_full("HEAD", 0, &head, NULL))
2841 return error(_("cannot resolve HEAD"));
2842 return reset_merge(&head);
2845 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2848 struct object_id oid;
2849 struct strbuf buf = STRBUF_INIT;
2852 f = fopen(git_path_head_file(), "r");
2853 if (!f && errno == ENOENT) {
2855 * There is no multiple-cherry-pick in progress.
2856 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2857 * a single-cherry-pick in progress, abort that.
2859 return rollback_single_pick(r);
2862 return error_errno(_("cannot open '%s'"), git_path_head_file());
2863 if (strbuf_getline_lf(&buf, f)) {
2864 error(_("cannot read '%s': %s"), git_path_head_file(),
2865 ferror(f) ? strerror(errno) : _("unexpected end of file"));
2870 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2871 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2872 git_path_head_file());
2875 if (is_null_oid(&oid)) {
2876 error(_("cannot abort from a branch yet to be born"));
2880 if (!rollback_is_safe()) {
2881 /* Do not error, just do not rollback */
2882 warning(_("You seem to have moved HEAD. "
2883 "Not rewinding, check your HEAD!"));
2885 if (reset_merge(&oid))
2887 strbuf_release(&buf);
2888 return sequencer_remove_state(opts);
2890 strbuf_release(&buf);
2894 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2896 enum replay_action action = -1;
2897 sequencer_get_last_command(r, &action);
2900 * Check whether the subcommand requested to skip the commit is actually
2901 * in progress and that it's safe to skip the commit.
2903 * opts->action tells us which subcommand requested to skip the commit.
2904 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2905 * action is in progress and we can skip the commit.
2907 * Otherwise we check that the last instruction was related to the
2908 * particular subcommand we're trying to execute and barf if that's not
2911 * Finally we check that the rollback is "safe", i.e., has the HEAD
2912 * moved? In this case, it doesn't make sense to "reset the merge" and
2913 * "skip the commit" as the user already handled this by committing. But
2914 * we'd not want to barf here, instead give advice on how to proceed. We
2915 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2916 * it gets removed when the user commits, so if it still exists we're
2917 * sure the user can't have committed before.
2919 switch (opts->action) {
2921 if (!file_exists(git_path_revert_head(r))) {
2922 if (action != REPLAY_REVERT)
2923 return error(_("no revert in progress"));
2924 if (!rollback_is_safe())
2929 if (!file_exists(git_path_cherry_pick_head(r))) {
2930 if (action != REPLAY_PICK)
2931 return error(_("no cherry-pick in progress"));
2932 if (!rollback_is_safe())
2937 BUG("unexpected action in sequencer_skip");
2940 if (skip_single_pick())
2941 return error(_("failed to skip the commit"));
2942 if (!is_directory(git_path_seq_dir()))
2945 return sequencer_continue(r, opts);
2948 error(_("there is nothing to skip"));
2950 if (advice_resolve_conflict) {
2951 advise(_("have you committed already?\n"
2952 "try \"git %s --continue\""),
2953 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2958 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2960 struct lock_file todo_lock = LOCK_INIT;
2961 const char *todo_path = get_todo_path(opts);
2962 int next = todo_list->current, offset, fd;
2965 * rebase -i writes "git-rebase-todo" without the currently executing
2966 * command, appending it to "done" instead.
2968 if (is_rebase_i(opts))
2971 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2973 return error_errno(_("could not lock '%s'"), todo_path);
2974 offset = get_item_line_offset(todo_list, next);
2975 if (write_in_full(fd, todo_list->buf.buf + offset,
2976 todo_list->buf.len - offset) < 0)
2977 return error_errno(_("could not write to '%s'"), todo_path);
2978 if (commit_lock_file(&todo_lock) < 0)
2979 return error(_("failed to finalize '%s'"), todo_path);
2981 if (is_rebase_i(opts) && next > 0) {
2982 const char *done = rebase_path_done();
2983 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2988 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2989 get_item_line_length(todo_list, next - 1))
2991 ret = error_errno(_("could not write to '%s'"), done);
2993 ret = error_errno(_("failed to finalize '%s'"), done);
2999 static int save_opts(struct replay_opts *opts)
3001 const char *opts_file = git_path_opts_file();
3004 if (opts->no_commit)
3005 res |= git_config_set_in_file_gently(opts_file,
3006 "options.no-commit", "true");
3008 res |= git_config_set_in_file_gently(opts_file,
3009 "options.edit", "true");
3010 if (opts->allow_empty)
3011 res |= git_config_set_in_file_gently(opts_file,
3012 "options.allow-empty", "true");
3013 if (opts->allow_empty_message)
3014 res |= git_config_set_in_file_gently(opts_file,
3015 "options.allow-empty-message", "true");
3016 if (opts->keep_redundant_commits)
3017 res |= git_config_set_in_file_gently(opts_file,
3018 "options.keep-redundant-commits", "true");
3020 res |= git_config_set_in_file_gently(opts_file,
3021 "options.signoff", "true");
3022 if (opts->record_origin)
3023 res |= git_config_set_in_file_gently(opts_file,
3024 "options.record-origin", "true");
3026 res |= git_config_set_in_file_gently(opts_file,
3027 "options.allow-ff", "true");
3028 if (opts->mainline) {
3029 struct strbuf buf = STRBUF_INIT;
3030 strbuf_addf(&buf, "%d", opts->mainline);
3031 res |= git_config_set_in_file_gently(opts_file,
3032 "options.mainline", buf.buf);
3033 strbuf_release(&buf);
3036 res |= git_config_set_in_file_gently(opts_file,
3037 "options.strategy", opts->strategy);
3039 res |= git_config_set_in_file_gently(opts_file,
3040 "options.gpg-sign", opts->gpg_sign);
3043 for (i = 0; i < opts->xopts_nr; i++)
3044 res |= git_config_set_multivar_in_file_gently(opts_file,
3045 "options.strategy-option",
3046 opts->xopts[i], "^$", 0);
3048 if (opts->allow_rerere_auto)
3049 res |= git_config_set_in_file_gently(opts_file,
3050 "options.allow-rerere-auto",
3051 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3054 if (opts->explicit_cleanup)
3055 res |= git_config_set_in_file_gently(opts_file,
3056 "options.default-msg-cleanup",
3057 describe_cleanup_mode(opts->default_msg_cleanup));
3061 static int make_patch(struct repository *r,
3062 struct commit *commit,
3063 struct replay_opts *opts)
3065 struct strbuf buf = STRBUF_INIT;
3066 struct rev_info log_tree_opt;
3067 const char *subject, *p;
3070 p = short_commit_name(commit);
3071 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3073 res |= write_rebase_head(&commit->object.oid);
3075 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3076 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3077 repo_init_revisions(r, &log_tree_opt, NULL);
3078 log_tree_opt.abbrev = 0;
3079 log_tree_opt.diff = 1;
3080 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3081 log_tree_opt.disable_stdin = 1;
3082 log_tree_opt.no_commit_id = 1;
3083 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3084 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3085 if (!log_tree_opt.diffopt.file)
3086 res |= error_errno(_("could not open '%s'"), buf.buf);
3088 res |= log_tree_commit(&log_tree_opt, commit);
3089 fclose(log_tree_opt.diffopt.file);
3093 strbuf_addf(&buf, "%s/message", get_dir(opts));
3094 if (!file_exists(buf.buf)) {
3095 const char *encoding = get_commit_output_encoding();
3096 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3097 find_commit_subject(commit_buffer, &subject);
3098 res |= write_message(subject, strlen(subject), buf.buf, 1);
3099 unuse_commit_buffer(commit, commit_buffer);
3101 strbuf_release(&buf);
3106 static int intend_to_amend(void)
3108 struct object_id head;
3111 if (get_oid("HEAD", &head))
3112 return error(_("cannot read HEAD"));
3114 p = oid_to_hex(&head);
3115 return write_message(p, strlen(p), rebase_path_amend(), 1);
3118 static int error_with_patch(struct repository *r,
3119 struct commit *commit,
3120 const char *subject, int subject_len,
3121 struct replay_opts *opts,
3122 int exit_code, int to_amend)
3125 if (make_patch(r, commit, opts))
3127 } else if (copy_file(rebase_path_message(),
3128 git_path_merge_msg(r), 0666))
3129 return error(_("unable to copy '%s' to '%s'"),
3130 git_path_merge_msg(r), rebase_path_message());
3133 if (intend_to_amend())
3137 _("You can amend the commit now, with\n"
3139 " git commit --amend %s\n"
3141 "Once you are satisfied with your changes, run\n"
3143 " git rebase --continue\n"),
3144 gpg_sign_opt_quoted(opts));
3145 } else if (exit_code) {
3147 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3148 short_commit_name(commit), subject_len, subject);
3151 * We don't have the hash of the parent so
3152 * just print the line from the todo file.
3154 fprintf_ln(stderr, _("Could not merge %.*s"),
3155 subject_len, subject);
3161 static int error_failed_squash(struct repository *r,
3162 struct commit *commit,
3163 struct replay_opts *opts,
3165 const char *subject)
3167 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3168 return error(_("could not copy '%s' to '%s'"),
3169 rebase_path_squash_msg(), rebase_path_message());
3170 unlink(git_path_merge_msg(r));
3171 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3172 return error(_("could not copy '%s' to '%s'"),
3173 rebase_path_message(),
3174 git_path_merge_msg(r));
3175 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3178 static int do_exec(struct repository *r, const char *command_line)
3180 struct argv_array child_env = ARGV_ARRAY_INIT;
3181 const char *child_argv[] = { NULL, NULL };
3184 fprintf(stderr, "Executing: %s\n", command_line);
3185 child_argv[0] = command_line;
3186 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3187 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3188 absolute_path(get_git_work_tree()));
3189 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3192 /* force re-reading of the cache */
3193 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3194 return error(_("could not read index"));
3196 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3199 warning(_("execution failed: %s\n%s"
3200 "You can fix the problem, and then run\n"
3202 " git rebase --continue\n"
3205 dirty ? N_("and made changes to the index and/or the "
3206 "working tree\n") : "");
3208 /* command not found */
3211 warning(_("execution succeeded: %s\nbut "
3212 "left changes to the index and/or the working tree\n"
3213 "Commit or stash your changes, and then run\n"
3215 " git rebase --continue\n"
3216 "\n"), command_line);
3220 argv_array_clear(&child_env);
3225 static int safe_append(const char *filename, const char *fmt, ...)
3228 struct lock_file lock = LOCK_INIT;
3229 int fd = hold_lock_file_for_update(&lock, filename,
3230 LOCK_REPORT_ON_ERROR);
3231 struct strbuf buf = STRBUF_INIT;
3236 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3237 error_errno(_("could not read '%s'"), filename);
3238 rollback_lock_file(&lock);
3241 strbuf_complete(&buf, '\n');
3243 strbuf_vaddf(&buf, fmt, ap);
3246 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3247 error_errno(_("could not write to '%s'"), filename);
3248 strbuf_release(&buf);
3249 rollback_lock_file(&lock);
3252 if (commit_lock_file(&lock) < 0) {
3253 strbuf_release(&buf);
3254 rollback_lock_file(&lock);
3255 return error(_("failed to finalize '%s'"), filename);
3258 strbuf_release(&buf);
3262 static int do_label(struct repository *r, const char *name, int len)
3264 struct ref_store *refs = get_main_ref_store(r);
3265 struct ref_transaction *transaction;
3266 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3267 struct strbuf msg = STRBUF_INIT;
3269 struct object_id head_oid;
3271 if (len == 1 && *name == '#')
3272 return error(_("illegal label name: '%.*s'"), len, name);
3274 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3275 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3277 transaction = ref_store_transaction_begin(refs, &err);
3279 error("%s", err.buf);
3281 } else if (get_oid("HEAD", &head_oid)) {
3282 error(_("could not read HEAD"));
3284 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3285 NULL, 0, msg.buf, &err) < 0 ||
3286 ref_transaction_commit(transaction, &err)) {
3287 error("%s", err.buf);
3290 ref_transaction_free(transaction);
3291 strbuf_release(&err);
3292 strbuf_release(&msg);
3295 ret = safe_append(rebase_path_refs_to_delete(),
3296 "%s\n", ref_name.buf);
3297 strbuf_release(&ref_name);
3302 static const char *reflog_message(struct replay_opts *opts,
3303 const char *sub_action, const char *fmt, ...);
3305 static int do_reset(struct repository *r,
3306 const char *name, int len,
3307 struct replay_opts *opts)
3309 struct strbuf ref_name = STRBUF_INIT;
3310 struct object_id oid;
3311 struct lock_file lock = LOCK_INIT;
3312 struct tree_desc desc;
3314 struct unpack_trees_options unpack_tree_opts;
3317 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3320 if (len == 10 && !strncmp("[new root]", name, len)) {
3321 if (!opts->have_squash_onto) {
3323 if (commit_tree("", 0, the_hash_algo->empty_tree,
3324 NULL, &opts->squash_onto,
3326 return error(_("writing fake root commit"));
3327 opts->have_squash_onto = 1;
3328 hex = oid_to_hex(&opts->squash_onto);
3329 if (write_message(hex, strlen(hex),
3330 rebase_path_squash_onto(), 0))
3331 return error(_("writing squash-onto"));
3333 oidcpy(&oid, &opts->squash_onto);
3337 /* Determine the length of the label */
3338 for (i = 0; i < len; i++)
3339 if (isspace(name[i]))
3343 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3344 if (get_oid(ref_name.buf, &oid) &&
3345 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3346 error(_("could not read '%s'"), ref_name.buf);
3347 rollback_lock_file(&lock);
3348 strbuf_release(&ref_name);
3353 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3354 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3355 unpack_tree_opts.head_idx = 1;
3356 unpack_tree_opts.src_index = r->index;
3357 unpack_tree_opts.dst_index = r->index;
3358 unpack_tree_opts.fn = oneway_merge;
3359 unpack_tree_opts.merge = 1;
3360 unpack_tree_opts.update = 1;
3361 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3363 if (repo_read_index_unmerged(r)) {
3364 rollback_lock_file(&lock);
3365 strbuf_release(&ref_name);
3366 return error_resolve_conflict(_(action_name(opts)));
3369 if (!fill_tree_descriptor(r, &desc, &oid)) {
3370 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3371 rollback_lock_file(&lock);
3372 free((void *)desc.buffer);
3373 strbuf_release(&ref_name);
3377 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3378 rollback_lock_file(&lock);
3379 free((void *)desc.buffer);
3380 strbuf_release(&ref_name);
3384 tree = parse_tree_indirect(&oid);
3385 prime_cache_tree(r, r->index, tree);
3387 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3388 ret = error(_("could not write index"));
3389 free((void *)desc.buffer);
3392 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3393 len, name), "HEAD", &oid,
3394 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3396 strbuf_release(&ref_name);
3400 static struct commit *lookup_label(const char *label, int len,
3403 struct commit *commit;
3406 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3407 commit = lookup_commit_reference_by_name(buf->buf);
3409 /* fall back to non-rewritten ref or commit */
3410 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3411 commit = lookup_commit_reference_by_name(buf->buf);
3415 error(_("could not resolve '%s'"), buf->buf);
3420 static int do_merge(struct repository *r,
3421 struct commit *commit,
3422 const char *arg, int arg_len,
3423 int flags, struct replay_opts *opts)
3425 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3426 EDIT_MSG | VERIFY_MSG : 0;
3427 struct strbuf ref_name = STRBUF_INIT;
3428 struct commit *head_commit, *merge_commit, *i;
3429 struct commit_list *bases, *j, *reversed = NULL;
3430 struct commit_list *to_merge = NULL, **tail = &to_merge;
3431 const char *strategy = !opts->xopts_nr &&
3432 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3433 NULL : opts->strategy;
3434 struct merge_options o;
3435 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3436 static struct lock_file lock;
3439 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3444 head_commit = lookup_commit_reference_by_name("HEAD");
3446 ret = error(_("cannot merge without a current revision"));
3451 * For octopus merges, the arg starts with the list of revisions to be
3452 * merged. The list is optionally followed by '#' and the oneline.
3454 merge_arg_len = oneline_offset = arg_len;
3455 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3458 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3459 p += 1 + strspn(p + 1, " \t\n");
3460 oneline_offset = p - arg;
3463 k = strcspn(p, " \t\n");
3466 merge_commit = lookup_label(p, k, &ref_name);
3467 if (!merge_commit) {
3468 ret = error(_("unable to parse '%.*s'"), k, p);
3471 tail = &commit_list_insert(merge_commit, tail)->next;
3473 merge_arg_len = p - arg;
3477 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3481 if (opts->have_squash_onto &&
3482 oideq(&head_commit->object.oid, &opts->squash_onto)) {
3484 * When the user tells us to "merge" something into a
3485 * "[new root]", let's simply fast-forward to the merge head.
3487 rollback_lock_file(&lock);
3489 ret = error(_("octopus merge cannot be executed on "
3490 "top of a [new root]"));
3492 ret = fast_forward_to(r, &to_merge->item->object.oid,
3493 &head_commit->object.oid, 0,
3499 const char *encoding = get_commit_output_encoding();
3500 const char *message = logmsg_reencode(commit, NULL, encoding);
3505 ret = error(_("could not get commit message of '%s'"),
3506 oid_to_hex(&commit->object.oid));
3509 write_author_script(message);
3510 find_commit_subject(message, &body);
3512 ret = write_message(body, len, git_path_merge_msg(r), 0);
3513 unuse_commit_buffer(commit, message);
3515 error_errno(_("could not write '%s'"),
3516 git_path_merge_msg(r));
3520 struct strbuf buf = STRBUF_INIT;
3523 strbuf_addf(&buf, "author %s", git_author_info(0));
3524 write_author_script(buf.buf);
3527 if (oneline_offset < arg_len) {
3528 p = arg + oneline_offset;
3529 len = arg_len - oneline_offset;
3531 strbuf_addf(&buf, "Merge %s '%.*s'",
3532 to_merge->next ? "branches" : "branch",
3533 merge_arg_len, arg);
3538 ret = write_message(p, len, git_path_merge_msg(r), 0);
3539 strbuf_release(&buf);
3541 error_errno(_("could not write '%s'"),
3542 git_path_merge_msg(r));
3548 * If HEAD is not identical to the first parent of the original merge
3549 * commit, we cannot fast-forward.
3551 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3552 oideq(&commit->parents->item->object.oid,
3553 &head_commit->object.oid);
3556 * If any merge head is different from the original one, we cannot
3559 if (can_fast_forward) {
3560 struct commit_list *p = commit->parents->next;
3562 for (j = to_merge; j && p; j = j->next, p = p->next)
3563 if (!oideq(&j->item->object.oid,
3564 &p->item->object.oid)) {
3565 can_fast_forward = 0;
3569 * If the number of merge heads differs from the original merge
3570 * commit, we cannot fast-forward.
3573 can_fast_forward = 0;
3576 if (can_fast_forward) {
3577 rollback_lock_file(&lock);
3578 ret = fast_forward_to(r, &commit->object.oid,
3579 &head_commit->object.oid, 0, opts);
3580 if (flags & TODO_EDIT_MERGE_MSG) {
3581 run_commit_flags |= AMEND_MSG;
3582 goto fast_forward_edit;
3587 if (strategy || to_merge->next) {
3589 struct child_process cmd = CHILD_PROCESS_INIT;
3591 if (read_env_script(&cmd.env_array)) {
3592 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3594 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3598 if (opts->committer_date_is_author_date)
3599 argv_array_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3600 author_date_from_env_array(&cmd.env_array));
3603 argv_array_push(&cmd.args, "merge");
3604 argv_array_push(&cmd.args, "-s");
3606 argv_array_push(&cmd.args, "octopus");
3608 argv_array_push(&cmd.args, strategy);
3609 for (k = 0; k < opts->xopts_nr; k++)
3610 argv_array_pushf(&cmd.args,
3611 "-X%s", opts->xopts[k]);
3613 argv_array_push(&cmd.args, "--no-edit");
3614 argv_array_push(&cmd.args, "--no-ff");
3615 argv_array_push(&cmd.args, "--no-log");
3616 argv_array_push(&cmd.args, "--no-stat");
3617 argv_array_push(&cmd.args, "-F");
3618 argv_array_push(&cmd.args, git_path_merge_msg(r));
3620 argv_array_push(&cmd.args, opts->gpg_sign);
3622 /* Add the tips to be merged */
3623 for (j = to_merge; j; j = j->next)
3624 argv_array_push(&cmd.args,
3625 oid_to_hex(&j->item->object.oid));
3627 strbuf_release(&ref_name);
3628 unlink(git_path_cherry_pick_head(r));
3629 rollback_lock_file(&lock);
3631 rollback_lock_file(&lock);
3632 ret = run_command(&cmd);
3634 /* force re-reading of the cache */
3635 if (!ret && (discard_index(r->index) < 0 ||
3636 repo_read_index(r) < 0))
3637 ret = error(_("could not read index"));
3641 merge_commit = to_merge->item;
3642 bases = get_merge_bases(head_commit, merge_commit);
3643 if (bases && oideq(&merge_commit->object.oid,
3644 &bases->item->object.oid)) {
3646 /* skip merging an ancestor of HEAD */
3650 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3651 git_path_merge_head(r), 0);
3652 write_message("no-ff", 5, git_path_merge_mode(r), 0);
3654 for (j = bases; j; j = j->next)
3655 commit_list_insert(j->item, &reversed);
3656 free_commit_list(bases);
3659 init_merge_options(&o, r);
3661 o.branch2 = ref_name.buf;
3662 o.buffer_output = 2;
3664 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3666 fputs(o.obuf.buf, stdout);
3667 strbuf_release(&o.obuf);
3669 error(_("could not even attempt to merge '%.*s'"),
3670 merge_arg_len, arg);
3674 * The return value of merge_recursive() is 1 on clean, and 0 on
3677 * Let's reverse that, so that do_merge() returns 0 upon success and
3678 * 1 upon failed merge (keeping the return value -1 for the cases where
3679 * we will want to reschedule the `merge` command).
3683 if (r->index->cache_changed &&
3684 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3685 ret = error(_("merge: Unable to write new index file"));
3689 rollback_lock_file(&lock);
3691 repo_rerere(r, opts->allow_rerere_auto);
3694 * In case of problems, we now want to return a positive
3695 * value (a negative one would indicate that the `merge`
3696 * command needs to be rescheduled).
3699 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3703 strbuf_release(&ref_name);
3704 rollback_lock_file(&lock);
3705 free_commit_list(to_merge);
3709 static int is_final_fixup(struct todo_list *todo_list)
3711 int i = todo_list->current;
3713 if (!is_fixup(todo_list->items[i].command))
3716 while (++i < todo_list->nr)
3717 if (is_fixup(todo_list->items[i].command))
3719 else if (!is_noop(todo_list->items[i].command))
3724 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3728 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3729 if (!is_noop(todo_list->items[i].command))
3730 return todo_list->items[i].command;
3735 static int apply_autostash(struct replay_opts *opts)
3737 struct strbuf stash_sha1 = STRBUF_INIT;
3738 struct child_process child = CHILD_PROCESS_INIT;
3741 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3742 strbuf_release(&stash_sha1);
3745 strbuf_trim(&stash_sha1);
3748 child.no_stdout = 1;
3749 child.no_stderr = 1;
3750 argv_array_push(&child.args, "stash");
3751 argv_array_push(&child.args, "apply");
3752 argv_array_push(&child.args, stash_sha1.buf);
3753 if (!run_command(&child))
3754 fprintf(stderr, _("Applied autostash.\n"));
3756 struct child_process store = CHILD_PROCESS_INIT;
3759 argv_array_push(&store.args, "stash");
3760 argv_array_push(&store.args, "store");
3761 argv_array_push(&store.args, "-m");
3762 argv_array_push(&store.args, "autostash");
3763 argv_array_push(&store.args, "-q");
3764 argv_array_push(&store.args, stash_sha1.buf);
3765 if (run_command(&store))
3766 ret = error(_("cannot store %s"), stash_sha1.buf);
3769 _("Applying autostash resulted in conflicts.\n"
3770 "Your changes are safe in the stash.\n"
3771 "You can run \"git stash pop\" or"
3772 " \"git stash drop\" at any time.\n"));
3775 strbuf_release(&stash_sha1);
3779 static const char *reflog_message(struct replay_opts *opts,
3780 const char *sub_action, const char *fmt, ...)
3783 static struct strbuf buf = STRBUF_INIT;
3787 strbuf_addstr(&buf, action_name(opts));
3789 strbuf_addf(&buf, " (%s)", sub_action);
3791 strbuf_addstr(&buf, ": ");
3792 strbuf_vaddf(&buf, fmt, ap);
3799 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3800 const char *commit, const char *action)
3802 struct child_process cmd = CHILD_PROCESS_INIT;
3807 argv_array_push(&cmd.args, "checkout");
3808 argv_array_push(&cmd.args, commit);
3809 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3812 ret = run_command(&cmd);
3814 ret = run_command_silent_on_success(&cmd);
3817 discard_index(r->index);
3822 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3823 const char *onto_name, const struct object_id *onto,
3824 const char *orig_head)
3826 struct object_id oid;
3827 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3829 if (get_oid(orig_head, &oid))
3830 return error(_("%s: not a valid OID"), orig_head);
3832 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3833 apply_autostash(opts);
3834 sequencer_remove_state(opts);
3835 return error(_("could not detach HEAD"));
3838 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3841 static int stopped_at_head(struct repository *r)
3843 struct object_id head;
3844 struct commit *commit;
3845 struct commit_message message;
3847 if (get_oid("HEAD", &head) ||
3848 !(commit = lookup_commit(r, &head)) ||
3849 parse_commit(commit) || get_message(commit, &message))
3850 fprintf(stderr, _("Stopped at HEAD\n"));
3852 fprintf(stderr, _("Stopped at %s\n"), message.label);
3853 free_message(commit, &message);
3859 static const char rescheduled_advice[] =
3860 N_("Could not execute the todo command\n"
3864 "It has been rescheduled; To edit the command before continuing, please\n"
3865 "edit the todo list first:\n"
3867 " git rebase --edit-todo\n"
3868 " git rebase --continue\n");
3870 static int pick_commits(struct repository *r,
3871 struct todo_list *todo_list,
3872 struct replay_opts *opts)
3874 int res = 0, reschedule = 0;
3876 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3878 assert(!(opts->signoff || opts->no_commit ||
3879 opts->record_origin || opts->edit ||
3880 opts->committer_date_is_author_date));
3881 if (read_and_refresh_cache(r, opts))
3884 while (todo_list->current < todo_list->nr) {
3885 struct todo_item *item = todo_list->items + todo_list->current;
3886 const char *arg = todo_item_get_arg(todo_list, item);
3889 if (save_todo(todo_list, opts))
3891 if (is_rebase_i(opts)) {
3892 if (item->command != TODO_COMMENT) {
3893 FILE *f = fopen(rebase_path_msgnum(), "w");
3895 todo_list->done_nr++;
3898 fprintf(f, "%d\n", todo_list->done_nr);
3902 fprintf(stderr, "Rebasing (%d/%d)%s",
3904 todo_list->total_nr,
3905 opts->verbose ? "\n" : "\r");
3907 unlink(rebase_path_message());
3908 unlink(rebase_path_author_script());
3909 unlink(rebase_path_stopped_sha());
3910 unlink(rebase_path_amend());
3911 unlink(git_path_merge_head(r));
3912 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3914 if (item->command == TODO_BREAK) {
3917 return stopped_at_head(r);
3920 if (item->command <= TODO_SQUASH) {
3921 if (is_rebase_i(opts))
3922 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3923 command_to_string(item->command), NULL),
3925 res = do_pick_commit(r, item->command, item->commit,
3926 opts, is_final_fixup(todo_list),
3928 if (is_rebase_i(opts) && res < 0) {
3930 advise(_(rescheduled_advice),
3931 get_item_line_length(todo_list,
3932 todo_list->current),
3933 get_item_line(todo_list,
3934 todo_list->current));
3935 todo_list->current--;
3936 if (save_todo(todo_list, opts))
3939 if (item->command == TODO_EDIT) {
3940 struct commit *commit = item->commit;
3945 _("Stopped at %s... %.*s\n"),
3946 short_commit_name(commit),
3947 item->arg_len, arg);
3949 return error_with_patch(r, commit,
3950 arg, item->arg_len, opts, res, !res);
3952 if (is_rebase_i(opts) && !res)
3953 record_in_rewritten(&item->commit->object.oid,
3954 peek_command(todo_list, 1));
3955 if (res && is_fixup(item->command)) {
3958 return error_failed_squash(r, item->commit, opts,
3959 item->arg_len, arg);
3960 } else if (res && is_rebase_i(opts) && item->commit) {
3962 struct object_id oid;
3965 * If we are rewording and have either
3966 * fast-forwarded already, or are about to
3967 * create a new root commit, we want to amend,
3968 * otherwise we do not.
3970 if (item->command == TODO_REWORD &&
3971 !get_oid("HEAD", &oid) &&
3972 (oideq(&item->commit->object.oid, &oid) ||
3973 (opts->have_squash_onto &&
3974 oideq(&opts->squash_onto, &oid))))
3977 return res | error_with_patch(r, item->commit,
3978 arg, item->arg_len, opts,
3981 } else if (item->command == TODO_EXEC) {
3982 char *end_of_arg = (char *)(arg + item->arg_len);
3983 int saved = *end_of_arg;
3988 res = do_exec(r, arg);
3989 *end_of_arg = saved;
3992 if (opts->reschedule_failed_exec)
3996 } else if (item->command == TODO_LABEL) {
3997 if ((res = do_label(r, arg, item->arg_len)))
3999 } else if (item->command == TODO_RESET) {
4000 if ((res = do_reset(r, arg, item->arg_len, opts)))
4002 } else if (item->command == TODO_MERGE) {
4003 if ((res = do_merge(r, item->commit,
4005 item->flags, opts)) < 0)
4007 else if (item->commit)
4008 record_in_rewritten(&item->commit->object.oid,
4009 peek_command(todo_list, 1));
4011 /* failed with merge conflicts */
4012 return error_with_patch(r, item->commit,
4015 } else if (!is_noop(item->command))
4016 return error(_("unknown command %d"), item->command);
4019 advise(_(rescheduled_advice),
4020 get_item_line_length(todo_list,
4021 todo_list->current),
4022 get_item_line(todo_list, todo_list->current));
4023 todo_list->current--;
4024 if (save_todo(todo_list, opts))
4027 return error_with_patch(r,
4031 } else if (is_rebase_i(opts) && check_todo && !res) {
4034 if (stat(get_todo_path(opts), &st)) {
4035 res = error_errno(_("could not stat '%s'"),
4036 get_todo_path(opts));
4037 } else if (match_stat_data(&todo_list->stat, &st)) {
4038 /* Reread the todo file if it has changed. */
4039 todo_list_release(todo_list);
4040 if (read_populate_todo(r, todo_list, opts))
4041 res = -1; /* message was printed */
4042 /* `current` will be incremented below */
4043 todo_list->current = -1;
4047 todo_list->current++;
4052 if (is_rebase_i(opts)) {
4053 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4056 /* Stopped in the middle, as planned? */
4057 if (todo_list->current < todo_list->nr)
4060 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4061 starts_with(head_ref.buf, "refs/")) {
4063 struct object_id head, orig;
4066 if (get_oid("HEAD", &head)) {
4067 res = error(_("cannot read HEAD"));
4069 strbuf_release(&head_ref);
4070 strbuf_release(&buf);
4073 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4074 get_oid_hex(buf.buf, &orig)) {
4075 res = error(_("could not read orig-head"));
4076 goto cleanup_head_ref;
4079 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4080 res = error(_("could not read 'onto'"));
4081 goto cleanup_head_ref;
4083 msg = reflog_message(opts, "finish", "%s onto %s",
4084 head_ref.buf, buf.buf);
4085 if (update_ref(msg, head_ref.buf, &head, &orig,
4086 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4087 res = error(_("could not update %s"),
4089 goto cleanup_head_ref;
4091 msg = reflog_message(opts, "finish", "returning to %s",
4093 if (create_symref("HEAD", head_ref.buf, msg)) {
4094 res = error(_("could not update HEAD to %s"),
4096 goto cleanup_head_ref;
4101 if (opts->verbose) {
4102 struct rev_info log_tree_opt;
4103 struct object_id orig, head;
4105 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4106 repo_init_revisions(r, &log_tree_opt, NULL);
4107 log_tree_opt.diff = 1;
4108 log_tree_opt.diffopt.output_format =
4109 DIFF_FORMAT_DIFFSTAT;
4110 log_tree_opt.disable_stdin = 1;
4112 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4113 !get_oid(buf.buf, &orig) &&
4114 !get_oid("HEAD", &head)) {
4115 diff_tree_oid(&orig, &head, "",
4116 &log_tree_opt.diffopt);
4117 log_tree_diff_flush(&log_tree_opt);
4120 flush_rewritten_pending();
4121 if (!stat(rebase_path_rewritten_list(), &st) &&
4123 struct child_process child = CHILD_PROCESS_INIT;
4124 const char *post_rewrite_hook =
4125 find_hook("post-rewrite");
4127 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4129 argv_array_push(&child.args, "notes");
4130 argv_array_push(&child.args, "copy");
4131 argv_array_push(&child.args, "--for-rewrite=rebase");
4132 /* we don't care if this copying failed */
4133 run_command(&child);
4135 if (post_rewrite_hook) {
4136 struct child_process hook = CHILD_PROCESS_INIT;
4138 hook.in = open(rebase_path_rewritten_list(),
4140 hook.stdout_to_stderr = 1;
4141 hook.trace2_hook_name = "post-rewrite";
4142 argv_array_push(&hook.args, post_rewrite_hook);
4143 argv_array_push(&hook.args, "rebase");
4144 /* we don't care if this hook failed */
4148 apply_autostash(opts);
4154 "Successfully rebased and updated %s.\n",
4158 strbuf_release(&buf);
4159 strbuf_release(&head_ref);
4163 * Sequence of picks finished successfully; cleanup by
4164 * removing the .git/sequencer directory
4166 return sequencer_remove_state(opts);
4169 static int continue_single_pick(struct repository *r)
4171 const char *argv[] = { "commit", NULL };
4173 if (!file_exists(git_path_cherry_pick_head(r)) &&
4174 !file_exists(git_path_revert_head(r)))
4175 return error(_("no cherry-pick or revert in progress"));
4176 return run_command_v_opt(argv, RUN_GIT_CMD);
4179 static int commit_staged_changes(struct repository *r,
4180 struct replay_opts *opts,
4181 struct todo_list *todo_list)
4183 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4184 unsigned int final_fixup = 0, is_clean;
4186 if (has_unstaged_changes(r, 1))
4187 return error(_("cannot rebase: You have unstaged changes."));
4189 is_clean = !has_uncommitted_changes(r, 0);
4191 if (file_exists(rebase_path_amend())) {
4192 struct strbuf rev = STRBUF_INIT;
4193 struct object_id head, to_amend;
4195 if (get_oid("HEAD", &head))
4196 return error(_("cannot amend non-existing commit"));
4197 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4198 return error(_("invalid file: '%s'"), rebase_path_amend());
4199 if (get_oid_hex(rev.buf, &to_amend))
4200 return error(_("invalid contents: '%s'"),
4201 rebase_path_amend());
4202 if (!is_clean && !oideq(&head, &to_amend))
4203 return error(_("\nYou have uncommitted changes in your "
4204 "working tree. Please, commit them\n"
4205 "first and then run 'git rebase "
4206 "--continue' again."));
4208 * When skipping a failed fixup/squash, we need to edit the
4209 * commit message, the current fixup list and count, and if it
4210 * was the last fixup/squash in the chain, we need to clean up
4211 * the commit message and if there was a squash, let the user
4214 if (!is_clean || !opts->current_fixup_count)
4215 ; /* this is not the final fixup */
4216 else if (!oideq(&head, &to_amend) ||
4217 !file_exists(rebase_path_stopped_sha())) {
4218 /* was a final fixup or squash done manually? */
4219 if (!is_fixup(peek_command(todo_list, 0))) {
4220 unlink(rebase_path_fixup_msg());
4221 unlink(rebase_path_squash_msg());
4222 unlink(rebase_path_current_fixups());
4223 strbuf_reset(&opts->current_fixups);
4224 opts->current_fixup_count = 0;
4227 /* we are in a fixup/squash chain */
4228 const char *p = opts->current_fixups.buf;
4229 int len = opts->current_fixups.len;
4231 opts->current_fixup_count--;
4233 BUG("Incorrect current_fixups:\n%s", p);
4234 while (len && p[len - 1] != '\n')
4236 strbuf_setlen(&opts->current_fixups, len);
4237 if (write_message(p, len, rebase_path_current_fixups(),
4239 return error(_("could not write file: '%s'"),
4240 rebase_path_current_fixups());
4243 * If a fixup/squash in a fixup/squash chain failed, the
4244 * commit message is already correct, no need to commit
4247 * Only if it is the final command in the fixup/squash
4248 * chain, and only if the chain is longer than a single
4249 * fixup/squash command (which was just skipped), do we
4250 * actually need to re-commit with a cleaned up commit
4253 if (opts->current_fixup_count > 0 &&
4254 !is_fixup(peek_command(todo_list, 0))) {
4257 * If there was not a single "squash" in the
4258 * chain, we only need to clean up the commit
4259 * message, no need to bother the user with
4260 * opening the commit message in the editor.
4262 if (!starts_with(p, "squash ") &&
4263 !strstr(p, "\nsquash "))
4264 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4265 } else if (is_fixup(peek_command(todo_list, 0))) {
4267 * We need to update the squash message to skip
4268 * the latest commit message.
4270 struct commit *commit;
4271 const char *path = rebase_path_squash_msg();
4272 const char *encoding = get_commit_output_encoding();
4274 if (parse_head(r, &commit) ||
4275 !(p = logmsg_reencode(commit, NULL, encoding)) ||
4276 write_message(p, strlen(p), path, 0)) {
4277 unuse_commit_buffer(commit, p);
4278 return error(_("could not write file: "
4281 unuse_commit_buffer(commit, p);
4285 strbuf_release(&rev);
4290 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4292 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4293 return error(_("could not remove CHERRY_PICK_HEAD"));
4298 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4300 return error(_("could not commit staged changes."));
4301 unlink(rebase_path_amend());
4302 unlink(git_path_merge_head(r));
4304 unlink(rebase_path_fixup_msg());
4305 unlink(rebase_path_squash_msg());
4307 if (opts->current_fixup_count > 0) {
4309 * Whether final fixup or not, we just cleaned up the commit
4312 unlink(rebase_path_current_fixups());
4313 strbuf_reset(&opts->current_fixups);
4314 opts->current_fixup_count = 0;
4319 static int init_committer(struct replay_opts *opts)
4321 struct ident_split id;
4322 const char *committer;
4324 committer = git_committer_info(IDENT_STRICT);
4325 if (split_ident_line(&id, committer, strlen(committer)) < 0)
4326 return error(_("invalid committer '%s'"), committer);
4327 opts->committer_name =
4328 xmemdupz(id.name_begin, id.name_end - id.name_begin);
4329 opts->committer_email =
4330 xmemdupz(id.mail_begin, id.mail_end - id.mail_end);
4335 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4337 struct todo_list todo_list = TODO_LIST_INIT;
4340 if (read_and_refresh_cache(r, opts))
4343 if (read_populate_opts(opts))
4345 if (is_rebase_i(opts)) {
4346 if (opts->committer_date_is_author_date && init_committer(opts))
4349 if ((res = read_populate_todo(r, &todo_list, opts)))
4350 goto release_todo_list;
4352 if (file_exists(rebase_path_dropped())) {
4353 if ((res = todo_list_check_against_backup(r, &todo_list)))
4354 goto release_todo_list;
4356 unlink(rebase_path_dropped());
4359 if (commit_staged_changes(r, opts, &todo_list)) {
4361 goto release_todo_list;
4363 } else if (!file_exists(get_todo_path(opts)))
4364 return continue_single_pick(r);
4365 else if ((res = read_populate_todo(r, &todo_list, opts)))
4366 goto release_todo_list;
4368 if (!is_rebase_i(opts)) {
4369 /* Verify that the conflict has been resolved */
4370 if (file_exists(git_path_cherry_pick_head(r)) ||
4371 file_exists(git_path_revert_head(r))) {
4372 res = continue_single_pick(r);
4374 goto release_todo_list;
4376 if (index_differs_from(r, "HEAD", NULL, 0)) {
4377 res = error_dirty_index(r, opts);
4378 goto release_todo_list;
4380 todo_list.current++;
4381 } else if (file_exists(rebase_path_stopped_sha())) {
4382 struct strbuf buf = STRBUF_INIT;
4383 struct object_id oid;
4385 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4386 !get_oid_committish(buf.buf, &oid))
4387 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4388 strbuf_release(&buf);
4391 res = pick_commits(r, &todo_list, opts);
4393 todo_list_release(&todo_list);
4397 static int single_pick(struct repository *r,
4398 struct commit *cmit,
4399 struct replay_opts *opts)
4403 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4404 return do_pick_commit(r, opts->action == REPLAY_PICK ?
4405 TODO_PICK : TODO_REVERT, cmit, opts, 0,
4409 int sequencer_pick_revisions(struct repository *r,
4410 struct replay_opts *opts)
4412 struct todo_list todo_list = TODO_LIST_INIT;
4413 struct object_id oid;
4417 if (read_and_refresh_cache(r, opts))
4420 for (i = 0; i < opts->revs->pending.nr; i++) {
4421 struct object_id oid;
4422 const char *name = opts->revs->pending.objects[i].name;
4424 /* This happens when using --stdin. */
4428 if (!get_oid(name, &oid)) {
4429 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4430 enum object_type type = oid_object_info(r,
4433 return error(_("%s: can't cherry-pick a %s"),
4434 name, type_name(type));
4437 return error(_("%s: bad revision"), name);
4441 * If we were called as "git cherry-pick <commit>", just
4442 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4443 * REVERT_HEAD, and don't touch the sequencer state.
4444 * This means it is possible to cherry-pick in the middle
4445 * of a cherry-pick sequence.
4447 if (opts->revs->cmdline.nr == 1 &&
4448 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4449 opts->revs->no_walk &&
4450 !opts->revs->cmdline.rev->flags) {
4451 struct commit *cmit;
4452 if (prepare_revision_walk(opts->revs))
4453 return error(_("revision walk setup failed"));
4454 cmit = get_revision(opts->revs);
4456 return error(_("empty commit set passed"));
4457 if (get_revision(opts->revs))
4458 BUG("unexpected extra commit from walk");
4459 return single_pick(r, cmit, opts);
4463 * Start a new cherry-pick/ revert sequence; but
4464 * first, make sure that an existing one isn't in
4468 if (walk_revs_populate_todo(&todo_list, opts) ||
4469 create_seq_dir(r) < 0)
4471 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4472 return error(_("can't revert as initial commit"));
4473 if (save_head(oid_to_hex(&oid)))
4475 if (save_opts(opts))
4477 update_abort_safety_file();
4478 res = pick_commits(r, &todo_list, opts);
4479 todo_list_release(&todo_list);
4483 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4485 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4486 struct strbuf sob = STRBUF_INIT;
4489 strbuf_addstr(&sob, sign_off_header);
4490 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4491 strbuf_addch(&sob, '\n');
4494 strbuf_complete_line(msgbuf);
4497 * If the whole message buffer is equal to the sob, pretend that we
4498 * found a conforming footer with a matching sob
4500 if (msgbuf->len - ignore_footer == sob.len &&
4501 !strncmp(msgbuf->buf, sob.buf, sob.len))
4504 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4507 const char *append_newlines = NULL;
4508 size_t len = msgbuf->len - ignore_footer;
4512 * The buffer is completely empty. Leave foom for
4513 * the title and body to be filled in by the user.
4515 append_newlines = "\n\n";
4516 } else if (len == 1) {
4518 * Buffer contains a single newline. Add another
4519 * so that we leave room for the title and body.
4521 append_newlines = "\n";
4522 } else if (msgbuf->buf[len - 2] != '\n') {
4524 * Buffer ends with a single newline. Add another
4525 * so that there is an empty line between the message
4528 append_newlines = "\n";
4529 } /* else, the buffer already ends with two newlines. */
4531 if (append_newlines)
4532 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4533 append_newlines, strlen(append_newlines));
4536 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4537 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4540 strbuf_release(&sob);
4543 struct labels_entry {
4544 struct hashmap_entry entry;
4545 char label[FLEX_ARRAY];
4548 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4549 const struct hashmap_entry *entry_or_key, const void *key)
4551 const struct labels_entry *a, *b;
4553 a = container_of(eptr, const struct labels_entry, entry);
4554 b = container_of(entry_or_key, const struct labels_entry, entry);
4556 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4559 struct string_entry {
4560 struct oidmap_entry entry;
4561 char string[FLEX_ARRAY];
4564 struct label_state {
4565 struct oidmap commit2label;
4566 struct hashmap labels;
4570 static const char *label_oid(struct object_id *oid, const char *label,
4571 struct label_state *state)
4573 struct labels_entry *labels_entry;
4574 struct string_entry *string_entry;
4575 struct object_id dummy;
4578 string_entry = oidmap_get(&state->commit2label, oid);
4580 return string_entry->string;
4583 * For "uninteresting" commits, i.e. commits that are not to be
4584 * rebased, and which can therefore not be labeled, we use a unique
4585 * abbreviation of the commit name. This is slightly more complicated
4586 * than calling find_unique_abbrev() because we also need to make
4587 * sure that the abbreviation does not conflict with any other
4590 * We disallow "interesting" commits to be labeled by a string that
4591 * is a valid full-length hash, to ensure that we always can find an
4592 * abbreviation for any uninteresting commit's names that does not
4593 * clash with any other label.
4595 strbuf_reset(&state->buf);
4599 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4600 label = p = state->buf.buf;
4602 find_unique_abbrev_r(p, oid, default_abbrev);
4605 * We may need to extend the abbreviated hash so that there is
4606 * no conflicting label.
4608 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4609 size_t i = strlen(p) + 1;
4611 oid_to_hex_r(p, oid);
4612 for (; i < the_hash_algo->hexsz; i++) {
4615 if (!hashmap_get_from_hash(&state->labels,
4622 struct strbuf *buf = &state->buf;
4625 * Sanitize labels by replacing non-alpha-numeric characters
4626 * (including white-space ones) by dashes, as they might be
4627 * illegal in file names (and hence in ref names).
4629 * Note that we retain non-ASCII UTF-8 characters (identified
4630 * via the most significant bit). They should be all acceptable
4631 * in file names. We do not validate the UTF-8 here, that's not
4632 * the job of this function.
4634 for (; *label; label++)
4635 if ((*label & 0x80) || isalnum(*label))
4636 strbuf_addch(buf, *label);
4637 /* avoid leading dash and double-dashes */
4638 else if (buf->len && buf->buf[buf->len - 1] != '-')
4639 strbuf_addch(buf, '-');
4641 strbuf_addstr(buf, "rev-");
4642 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4646 if ((buf->len == the_hash_algo->hexsz &&
4647 !get_oid_hex(label, &dummy)) ||
4648 (buf->len == 1 && *label == '#') ||
4649 hashmap_get_from_hash(&state->labels,
4650 strihash(label), label)) {
4652 * If the label already exists, or if the label is a
4653 * valid full OID, or the label is a '#' (which we use
4654 * as a separator between merge heads and oneline), we
4655 * append a dash and a number to make it unique.
4657 size_t len = buf->len;
4659 for (i = 2; ; i++) {
4660 strbuf_setlen(buf, len);
4661 strbuf_addf(buf, "-%d", i);
4662 if (!hashmap_get_from_hash(&state->labels,
4672 FLEX_ALLOC_STR(labels_entry, label, label);
4673 hashmap_entry_init(&labels_entry->entry, strihash(label));
4674 hashmap_add(&state->labels, &labels_entry->entry);
4676 FLEX_ALLOC_STR(string_entry, string, label);
4677 oidcpy(&string_entry->entry.oid, oid);
4678 oidmap_put(&state->commit2label, string_entry);
4680 return string_entry->string;
4683 static int make_script_with_merges(struct pretty_print_context *pp,
4684 struct rev_info *revs, struct strbuf *out,
4687 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4688 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4689 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4690 struct strbuf label = STRBUF_INIT;
4691 struct commit_list *commits = NULL, **tail = &commits, *iter;
4692 struct commit_list *tips = NULL, **tips_tail = &tips;
4693 struct commit *commit;
4694 struct oidmap commit2todo = OIDMAP_INIT;
4695 struct string_entry *entry;
4696 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4697 shown = OIDSET_INIT;
4698 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4700 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4701 const char *cmd_pick = abbr ? "p" : "pick",
4702 *cmd_label = abbr ? "l" : "label",
4703 *cmd_reset = abbr ? "t" : "reset",
4704 *cmd_merge = abbr ? "m" : "merge";
4706 oidmap_init(&commit2todo, 0);
4707 oidmap_init(&state.commit2label, 0);
4708 hashmap_init(&state.labels, labels_cmp, NULL, 0);
4709 strbuf_init(&state.buf, 32);
4711 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4712 struct labels_entry *onto_label_entry;
4713 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4714 FLEX_ALLOC_STR(entry, string, "onto");
4715 oidcpy(&entry->entry.oid, oid);
4716 oidmap_put(&state.commit2label, entry);
4718 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4719 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4720 hashmap_add(&state.labels, &onto_label_entry->entry);
4725 * - get onelines for all commits
4726 * - gather all branch tips (i.e. 2nd or later parents of merges)
4727 * - label all branch tips
4729 while ((commit = get_revision(revs))) {
4730 struct commit_list *to_merge;
4731 const char *p1, *p2;
4732 struct object_id *oid;
4735 tail = &commit_list_insert(commit, tail)->next;
4736 oidset_insert(&interesting, &commit->object.oid);
4738 is_empty = is_original_commit_empty(commit);
4739 if (!is_empty && (commit->object.flags & PATCHSAME))
4742 strbuf_reset(&oneline);
4743 pretty_print_commit(pp, commit, &oneline);
4745 to_merge = commit->parents ? commit->parents->next : NULL;
4747 /* non-merge commit: easy case */
4749 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4750 oid_to_hex(&commit->object.oid),
4753 FLEX_ALLOC_STR(entry, string, buf.buf);
4754 oidcpy(&entry->entry.oid, &commit->object.oid);
4755 oidmap_put(&commit2todo, entry);
4760 /* Create a label */
4761 strbuf_reset(&label);
4762 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4763 (p1 = strchr(p1, '\'')) &&
4764 (p2 = strchr(++p1, '\'')))
4765 strbuf_add(&label, p1, p2 - p1);
4766 else if (skip_prefix(oneline.buf, "Merge pull request ",
4768 (p1 = strstr(p1, " from ")))
4769 strbuf_addstr(&label, p1 + strlen(" from "));
4771 strbuf_addbuf(&label, &oneline);
4774 strbuf_addf(&buf, "%s -C %s",
4775 cmd_merge, oid_to_hex(&commit->object.oid));
4777 /* label the tips of merged branches */
4778 for (; to_merge; to_merge = to_merge->next) {
4779 oid = &to_merge->item->object.oid;
4780 strbuf_addch(&buf, ' ');
4782 if (!oidset_contains(&interesting, oid)) {
4783 strbuf_addstr(&buf, label_oid(oid, NULL,
4788 tips_tail = &commit_list_insert(to_merge->item,
4791 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4793 strbuf_addf(&buf, " # %s", oneline.buf);
4795 FLEX_ALLOC_STR(entry, string, buf.buf);
4796 oidcpy(&entry->entry.oid, &commit->object.oid);
4797 oidmap_put(&commit2todo, entry);
4802 * - label branch points
4803 * - add HEAD to the branch tips
4805 for (iter = commits; iter; iter = iter->next) {
4806 struct commit_list *parent = iter->item->parents;
4807 for (; parent; parent = parent->next) {
4808 struct object_id *oid = &parent->item->object.oid;
4809 if (!oidset_contains(&interesting, oid))
4811 if (oidset_insert(&child_seen, oid))
4812 label_oid(oid, "branch-point", &state);
4815 /* Add HEAD as implicit "tip of branch" */
4817 tips_tail = &commit_list_insert(iter->item,
4822 * Third phase: output the todo list. This is a bit tricky, as we
4823 * want to avoid jumping back and forth between revisions. To
4824 * accomplish that goal, we walk backwards from the branch tips,
4825 * gathering commits not yet shown, reversing the list on the fly,
4826 * then outputting that list (labeling revisions as needed).
4828 strbuf_addf(out, "%s onto\n", cmd_label);
4829 for (iter = tips; iter; iter = iter->next) {
4830 struct commit_list *list = NULL, *iter2;
4832 commit = iter->item;
4833 if (oidset_contains(&shown, &commit->object.oid))
4835 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4838 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4840 strbuf_addch(out, '\n');
4842 while (oidset_contains(&interesting, &commit->object.oid) &&
4843 !oidset_contains(&shown, &commit->object.oid)) {
4844 commit_list_insert(commit, &list);
4845 if (!commit->parents) {
4849 commit = commit->parents->item;
4853 strbuf_addf(out, "%s %s\n", cmd_reset,
4854 rebase_cousins || root_with_onto ?
4855 "onto" : "[new root]");
4857 const char *to = NULL;
4859 entry = oidmap_get(&state.commit2label,
4860 &commit->object.oid);
4863 else if (!rebase_cousins)
4864 to = label_oid(&commit->object.oid, NULL,
4867 if (!to || !strcmp(to, "onto"))
4868 strbuf_addf(out, "%s onto\n", cmd_reset);
4870 strbuf_reset(&oneline);
4871 pretty_print_commit(pp, commit, &oneline);
4872 strbuf_addf(out, "%s %s # %s\n",
4873 cmd_reset, to, oneline.buf);
4877 for (iter2 = list; iter2; iter2 = iter2->next) {
4878 struct object_id *oid = &iter2->item->object.oid;
4879 entry = oidmap_get(&commit2todo, oid);
4880 /* only show if not already upstream */
4882 strbuf_addf(out, "%s\n", entry->string);
4883 entry = oidmap_get(&state.commit2label, oid);
4885 strbuf_addf(out, "%s %s\n",
4886 cmd_label, entry->string);
4887 oidset_insert(&shown, oid);
4890 free_commit_list(list);
4893 free_commit_list(commits);
4894 free_commit_list(tips);
4896 strbuf_release(&label);
4897 strbuf_release(&oneline);
4898 strbuf_release(&buf);
4900 oidmap_free(&commit2todo, 1);
4901 oidmap_free(&state.commit2label, 1);
4902 hashmap_free_entries(&state.labels, struct labels_entry, entry);
4903 strbuf_release(&state.buf);
4908 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4909 const char **argv, unsigned flags)
4911 char *format = NULL;
4912 struct pretty_print_context pp = {0};
4913 struct rev_info revs;
4914 struct commit *commit;
4915 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4916 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4918 repo_init_revisions(r, &revs, NULL);
4919 revs.verbose_header = 1;
4921 revs.max_parents = 1;
4922 revs.cherry_mark = 1;
4925 revs.right_only = 1;
4926 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4927 revs.topo_order = 1;
4929 revs.pretty_given = 1;
4930 git_config_get_string("rebase.instructionFormat", &format);
4931 if (!format || !*format) {
4933 format = xstrdup("%s");
4935 get_commit_format(format, &revs);
4937 pp.fmt = revs.commit_format;
4938 pp.output_encoding = get_log_output_encoding();
4940 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4941 return error(_("make_script: unhandled options"));
4943 if (prepare_revision_walk(&revs) < 0)
4944 return error(_("make_script: error preparing revisions"));
4947 return make_script_with_merges(&pp, &revs, out, flags);
4949 while ((commit = get_revision(&revs))) {
4950 int is_empty = is_original_commit_empty(commit);
4952 if (!is_empty && (commit->object.flags & PATCHSAME))
4954 strbuf_addf(out, "%s %s ", insn,
4955 oid_to_hex(&commit->object.oid));
4956 pretty_print_commit(&pp, commit, out);
4957 strbuf_addch(out, '\n');
4963 * Add commands after pick and (series of) squash/fixup commands
4966 void todo_list_add_exec_commands(struct todo_list *todo_list,
4967 struct string_list *commands)
4969 struct strbuf *buf = &todo_list->buf;
4970 size_t base_offset = buf->len;
4971 int i, insert, nr = 0, alloc = 0;
4972 struct todo_item *items = NULL, *base_items = NULL;
4974 base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4975 for (i = 0; i < commands->nr; i++) {
4976 size_t command_len = strlen(commands->items[i].string);
4978 strbuf_addstr(buf, commands->items[i].string);
4979 strbuf_addch(buf, '\n');
4981 base_items[i].command = TODO_EXEC;
4982 base_items[i].offset_in_buf = base_offset;
4983 base_items[i].arg_offset = base_offset + strlen("exec ");
4984 base_items[i].arg_len = command_len - strlen("exec ");
4986 base_offset += command_len + 1;
4990 * Insert <commands> after every pick. Here, fixup/squash chains
4991 * are considered part of the pick, so we insert the commands *after*
4992 * those chains if there are any.
4994 * As we insert the exec commands immediately after rearranging
4995 * any fixups and before the user edits the list, a fixup chain
4996 * can never contain comments (any comments are empty picks that
4997 * have been commented out because the user did not specify
4998 * --keep-empty). So, it is safe to insert an exec command
4999 * without looking at the command following a comment.
5002 for (i = 0; i < todo_list->nr; i++) {
5003 enum todo_command command = todo_list->items[i].command;
5004 if (insert && !is_fixup(command)) {
5005 ALLOC_GROW(items, nr + commands->nr, alloc);
5006 COPY_ARRAY(items + nr, base_items, commands->nr);
5012 ALLOC_GROW(items, nr + 1, alloc);
5013 items[nr++] = todo_list->items[i];
5015 if (command == TODO_PICK || command == TODO_MERGE)
5019 /* insert or append final <commands> */
5020 if (insert || nr == todo_list->nr) {
5021 ALLOC_GROW(items, nr + commands->nr, alloc);
5022 COPY_ARRAY(items + nr, base_items, commands->nr);
5027 FREE_AND_NULL(todo_list->items);
5028 todo_list->items = items;
5030 todo_list->alloc = alloc;
5033 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5034 struct strbuf *buf, int num, unsigned flags)
5036 struct todo_item *item;
5037 int i, max = todo_list->nr;
5039 if (num > 0 && num < max)
5042 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5043 /* if the item is not a command write it and continue */
5044 if (item->command >= TODO_COMMENT) {
5045 strbuf_addf(buf, "%.*s\n", item->arg_len,
5046 todo_item_get_arg(todo_list, item));
5050 /* add command to the buffer */
5051 if (flags & TODO_LIST_ABBREVIATE_CMDS)
5052 strbuf_addch(buf, command_to_char(item->command));
5054 strbuf_addstr(buf, command_to_string(item->command));
5058 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5059 short_commit_name(item->commit) :
5060 oid_to_hex(&item->commit->object.oid);
5062 if (item->command == TODO_MERGE) {
5063 if (item->flags & TODO_EDIT_MERGE_MSG)
5064 strbuf_addstr(buf, " -c");
5066 strbuf_addstr(buf, " -C");
5069 strbuf_addf(buf, " %s", oid);
5072 /* add all the rest */
5074 strbuf_addch(buf, '\n');
5076 strbuf_addf(buf, " %.*s\n", item->arg_len,
5077 todo_item_get_arg(todo_list, item));
5081 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5082 const char *file, const char *shortrevisions,
5083 const char *shortonto, int num, unsigned flags)
5086 struct strbuf buf = STRBUF_INIT;
5088 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5089 if (flags & TODO_LIST_APPEND_TODO_HELP)
5090 append_todo_help(count_commands(todo_list),
5091 shortrevisions, shortonto, &buf);
5093 res = write_message(buf.buf, buf.len, file, 0);
5094 strbuf_release(&buf);
5099 /* skip picking commits whose parents are unchanged */
5100 static int skip_unnecessary_picks(struct repository *r,
5101 struct todo_list *todo_list,
5102 struct object_id *base_oid)
5104 struct object_id *parent_oid;
5107 for (i = 0; i < todo_list->nr; i++) {
5108 struct todo_item *item = todo_list->items + i;
5110 if (item->command >= TODO_NOOP)
5112 if (item->command != TODO_PICK)
5114 if (parse_commit(item->commit)) {
5115 return error(_("could not parse commit '%s'"),
5116 oid_to_hex(&item->commit->object.oid));
5118 if (!item->commit->parents)
5119 break; /* root commit */
5120 if (item->commit->parents->next)
5121 break; /* merge commit */
5122 parent_oid = &item->commit->parents->item->object.oid;
5123 if (!oideq(parent_oid, base_oid))
5125 oidcpy(base_oid, &item->commit->object.oid);
5128 const char *done_path = rebase_path_done();
5130 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5131 error_errno(_("could not write to '%s'"), done_path);
5135 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5137 todo_list->current = 0;
5138 todo_list->done_nr += i;
5140 if (is_fixup(peek_command(todo_list, 0)))
5141 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5147 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5148 const char *shortrevisions, const char *onto_name,
5149 struct commit *onto, const char *orig_head,
5150 struct string_list *commands, unsigned autosquash,
5151 struct todo_list *todo_list)
5153 const char *shortonto, *todo_file = rebase_path_todo();
5154 struct todo_list new_todo = TODO_LIST_INIT;
5155 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5156 struct object_id oid = onto->object.oid;
5159 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5161 if (buf->len == 0) {
5162 struct todo_item *item = append_new_todo(todo_list);
5163 item->command = TODO_NOOP;
5164 item->commit = NULL;
5165 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5168 if (autosquash && todo_list_rearrange_squash(todo_list))
5172 todo_list_add_exec_commands(todo_list, commands);
5174 if (count_commands(todo_list) == 0) {
5175 apply_autostash(opts);
5176 sequencer_remove_state(opts);
5178 return error(_("nothing to do"));
5181 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5185 else if (res == -2) {
5186 apply_autostash(opts);
5187 sequencer_remove_state(opts);
5190 } else if (res == -3) {
5191 apply_autostash(opts);
5192 sequencer_remove_state(opts);
5193 todo_list_release(&new_todo);
5195 return error(_("nothing to do"));
5196 } else if (res == -4) {
5197 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5198 todo_list_release(&new_todo);
5203 /* Expand the commit IDs */
5204 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5205 strbuf_swap(&new_todo.buf, &buf2);
5206 strbuf_release(&buf2);
5207 new_todo.total_nr -= new_todo.nr;
5208 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5209 BUG("invalid todo list after expanding IDs:\n%s",
5212 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5213 todo_list_release(&new_todo);
5214 return error(_("could not skip unnecessary pick commands"));
5217 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5218 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5219 todo_list_release(&new_todo);
5220 return error_errno(_("could not write '%s'"), todo_file);
5225 if (opts->committer_date_is_author_date && init_committer(opts))
5228 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5231 if (require_clean_work_tree(r, "rebase", "", 1, 1))
5234 todo_list_write_total_nr(&new_todo);
5235 res = pick_commits(r, &new_todo, opts);
5238 todo_list_release(&new_todo);
5243 struct subject2item_entry {
5244 struct hashmap_entry entry;
5246 char subject[FLEX_ARRAY];
5249 static int subject2item_cmp(const void *fndata,
5250 const struct hashmap_entry *eptr,
5251 const struct hashmap_entry *entry_or_key,
5254 const struct subject2item_entry *a, *b;
5256 a = container_of(eptr, const struct subject2item_entry, entry);
5257 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5259 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5262 define_commit_slab(commit_todo_item, struct todo_item *);
5265 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5266 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5267 * after the former, and change "pick" to "fixup"/"squash".
5269 * Note that if the config has specified a custom instruction format, each log
5270 * message will have to be retrieved from the commit (as the oneline in the
5271 * script cannot be trusted) in order to normalize the autosquash arrangement.
5273 int todo_list_rearrange_squash(struct todo_list *todo_list)
5275 struct hashmap subject2item;
5276 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5278 struct commit_todo_item commit_todo;
5279 struct todo_item *items = NULL;
5281 init_commit_todo_item(&commit_todo);
5283 * The hashmap maps onelines to the respective todo list index.
5285 * If any items need to be rearranged, the next[i] value will indicate
5286 * which item was moved directly after the i'th.
5288 * In that case, last[i] will indicate the index of the latest item to
5289 * be moved to appear after the i'th.
5291 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5292 ALLOC_ARRAY(next, todo_list->nr);
5293 ALLOC_ARRAY(tail, todo_list->nr);
5294 ALLOC_ARRAY(subjects, todo_list->nr);
5295 for (i = 0; i < todo_list->nr; i++) {
5296 struct strbuf buf = STRBUF_INIT;
5297 struct todo_item *item = todo_list->items + i;
5298 const char *commit_buffer, *subject, *p;
5301 struct subject2item_entry *entry;
5303 next[i] = tail[i] = -1;
5304 if (!item->commit || item->command == TODO_DROP) {
5309 if (is_fixup(item->command)) {
5310 clear_commit_todo_item(&commit_todo);
5311 return error(_("the script was already rearranged."));
5314 *commit_todo_item_at(&commit_todo, item->commit) = item;
5316 parse_commit(item->commit);
5317 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5318 find_commit_subject(commit_buffer, &subject);
5319 format_subject(&buf, subject, " ");
5320 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5321 unuse_commit_buffer(item->commit, commit_buffer);
5322 if ((skip_prefix(subject, "fixup! ", &p) ||
5323 skip_prefix(subject, "squash! ", &p))) {
5324 struct commit *commit2;
5329 if (!skip_prefix(p, "fixup! ", &p) &&
5330 !skip_prefix(p, "squash! ", &p))
5334 entry = hashmap_get_entry_from_hash(&subject2item,
5336 struct subject2item_entry,
5339 /* found by title */
5341 else if (!strchr(p, ' ') &&
5343 lookup_commit_reference_by_name(p)) &&
5344 *commit_todo_item_at(&commit_todo, commit2))
5345 /* found by commit name */
5346 i2 = *commit_todo_item_at(&commit_todo, commit2)
5349 /* copy can be a prefix of the commit subject */
5350 for (i2 = 0; i2 < i; i2++)
5352 starts_with(subjects[i2], p))
5360 todo_list->items[i].command =
5361 starts_with(subject, "fixup!") ?
5362 TODO_FIXUP : TODO_SQUASH;
5368 } else if (!hashmap_get_from_hash(&subject2item,
5369 strhash(subject), subject)) {
5370 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5372 hashmap_entry_init(&entry->entry,
5373 strhash(entry->subject));
5374 hashmap_put(&subject2item, &entry->entry);
5379 for (i = 0; i < todo_list->nr; i++) {
5380 enum todo_command command = todo_list->items[i].command;
5384 * Initially, all commands are 'pick's. If it is a
5385 * fixup or a squash now, we have rearranged it.
5387 if (is_fixup(command))
5391 ALLOC_GROW(items, nr + 1, alloc);
5392 items[nr++] = todo_list->items[cur];
5397 FREE_AND_NULL(todo_list->items);
5398 todo_list->items = items;
5400 todo_list->alloc = alloc;
5405 for (i = 0; i < todo_list->nr; i++)
5408 hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5410 clear_commit_todo_item(&commit_todo);
5415 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5417 if (file_exists(git_path_cherry_pick_head(r))) {
5418 struct object_id cherry_pick_head, rebase_head;
5420 if (file_exists(git_path_seq_dir()))
5421 *whence = FROM_CHERRY_PICK_MULTI;
5422 if (file_exists(rebase_path()) &&
5423 !get_oid("REBASE_HEAD", &rebase_head) &&
5424 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5425 oideq(&rebase_head, &cherry_pick_head))
5426 *whence = FROM_REBASE_PICK;
5428 *whence = FROM_CHERRY_PICK_SINGLE;