The fifth batch
[git.git] / sequencer.c
blob407ee4e90fea685a53504265ce528cb3b8443330
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "advice.h"
7 #include "config.h"
8 #include "copy.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "lockfile.h"
13 #include "dir.h"
14 #include "object-file.h"
15 #include "object-name.h"
16 #include "object-store-ll.h"
17 #include "object.h"
18 #include "pager.h"
19 #include "commit.h"
20 #include "sequencer.h"
21 #include "run-command.h"
22 #include "hook.h"
23 #include "utf8.h"
24 #include "cache-tree.h"
25 #include "diff.h"
26 #include "path.h"
27 #include "revision.h"
28 #include "rerere.h"
29 #include "merge.h"
30 #include "merge-ort.h"
31 #include "merge-ort-wrappers.h"
32 #include "refs.h"
33 #include "sparse-index.h"
34 #include "strvec.h"
35 #include "quote.h"
36 #include "trailer.h"
37 #include "log-tree.h"
38 #include "wt-status.h"
39 #include "hashmap.h"
40 #include "notes-utils.h"
41 #include "sigchain.h"
42 #include "unpack-trees.h"
43 #include "oidmap.h"
44 #include "oidset.h"
45 #include "commit-slab.h"
46 #include "alias.h"
47 #include "commit-reach.h"
48 #include "rebase-interactive.h"
49 #include "reset.h"
50 #include "branch.h"
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
58 * are too long.
59 * Add some margin to stay clear from reaching `NAME_MAX`.
61 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
63 static const char sign_off_header[] = "Signed-off-by: ";
64 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
66 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
68 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
70 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
71 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
72 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
73 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
75 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
82 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
83 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
85 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
90 * actions.
92 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
94 * The file to keep track of how many commands were already processed (e.g.
95 * for the prompt).
97 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
102 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
107 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
116 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
124 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
129 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
133 * being rebased.
135 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
144 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
146 * When we stop at a given patch via the "edit" command, this file contains
147 * the commit object name of the corresponding patch.
149 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
151 * When we stop for the user to resolve conflicts this file contains
152 * the patch of the commit that is being picked.
154 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
156 * For the post-rewrite hook, we make a list of rewritten commits and
157 * their new sha1s. The rewritten-pending list keeps the sha1s of
158 * commits that have been processed, but not committed yet,
159 * e.g. because they are waiting for a 'squash' command.
161 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
162 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
163 "rebase-merge/rewritten-pending")
166 * The path of the file containing the OID of the "squash onto" commit, i.e.
167 * the dummy commit used for `reset [new root]`.
169 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
172 * The path of the file listing refs that need to be deleted after the rebase
173 * finishes. This is used by the `label` command to record the need for cleanup.
175 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
178 * The update-refs file stores a list of refs that will be updated at the end
179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
180 * update the OIDs for the refs in this file, but the refs are not updated
181 * until the end of the rebase sequence.
183 * rebase_path_update_refs() returns the path to this file for a given
184 * worktree directory. For the current worktree, pass the_repository->gitdir.
186 static char *rebase_path_update_refs(const char *wt_git_dir)
188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
192 * The following files are written by git-rebase just after parsing the
193 * command-line.
195 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
196 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
197 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
198 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
199 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
200 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
201 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
202 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
203 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
204 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
205 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
206 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
207 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
208 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
209 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
210 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
211 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
214 * A 'struct replay_ctx' represents the private state of the sequencer.
216 struct replay_ctx {
218 * The commit message that will be used except at the end of a
219 * chain of fixup and squash commands.
221 struct strbuf message;
223 * The list of completed fixup and squash commands in the
224 * current chain.
226 struct strbuf current_fixups;
228 * Stores the reflog message that will be used when creating a
229 * commit. Points to a static buffer and should not be free()'d.
231 const char *reflog_message;
233 * The number of completed fixup and squash commands in the
234 * current chain.
236 int current_fixup_count;
238 * Whether message contains a commit message.
240 unsigned have_message :1;
243 struct replay_ctx* replay_ctx_new(void)
245 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
247 strbuf_init(&ctx->current_fixups, 0);
248 strbuf_init(&ctx->message, 0);
250 return ctx;
254 * A 'struct update_refs_record' represents a value in the update-refs
255 * list. We use a string_list to map refs to these (before, after) pairs.
257 struct update_ref_record {
258 struct object_id before;
259 struct object_id after;
262 static struct update_ref_record *init_update_ref_record(const char *ref)
264 struct update_ref_record *rec;
266 CALLOC_ARRAY(rec, 1);
268 oidcpy(&rec->before, null_oid());
269 oidcpy(&rec->after, null_oid());
271 /* This may fail, but that's fine, we will keep the null OID. */
272 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
274 return rec;
277 static int git_sequencer_config(const char *k, const char *v,
278 const struct config_context *ctx, void *cb)
280 struct replay_opts *opts = cb;
282 if (!strcmp(k, "commit.cleanup")) {
283 if (!v)
284 return config_error_nonbool(k);
286 if (!strcmp(v, "verbatim")) {
287 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
288 opts->explicit_cleanup = 1;
289 } else if (!strcmp(v, "whitespace")) {
290 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
291 opts->explicit_cleanup = 1;
292 } else if (!strcmp(v, "strip")) {
293 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
294 opts->explicit_cleanup = 1;
295 } else if (!strcmp(v, "scissors")) {
296 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
297 opts->explicit_cleanup = 1;
298 } else {
299 warning(_("invalid commit message cleanup mode '%s'"),
303 return 0;
306 if (!strcmp(k, "commit.gpgsign")) {
307 free(opts->gpg_sign);
308 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
309 return 0;
312 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
313 int ret = git_config_string(&opts->default_strategy, k, v);
314 if (ret == 0) {
316 * pull.twohead is allowed to be multi-valued; we only
317 * care about the first value.
319 char *tmp = strchr(opts->default_strategy, ' ');
320 if (tmp)
321 *tmp = '\0';
323 return ret;
326 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
327 opts->commit_use_reference = git_config_bool(k, v);
329 return git_diff_basic_config(k, v, ctx, NULL);
332 void sequencer_init_config(struct replay_opts *opts)
334 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
335 git_config(git_sequencer_config, opts);
338 static inline int is_rebase_i(const struct replay_opts *opts)
340 return opts->action == REPLAY_INTERACTIVE_REBASE;
343 static const char *get_dir(const struct replay_opts *opts)
345 if (is_rebase_i(opts))
346 return rebase_path();
347 return git_path_seq_dir();
350 static const char *get_todo_path(const struct replay_opts *opts)
352 if (is_rebase_i(opts))
353 return rebase_path_todo();
354 return git_path_todo_file();
358 * Returns 0 for non-conforming footer
359 * Returns 1 for conforming footer
360 * Returns 2 when sob exists within conforming footer
361 * Returns 3 when sob exists within conforming footer as last entry
363 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
364 size_t ignore_footer)
366 struct trailer_iterator iter;
367 size_t i = 0;
368 int found_sob = 0, found_sob_last = 0;
369 char saved_char;
371 if (ignore_footer) {
372 saved_char = sb->buf[sb->len - ignore_footer];
373 sb->buf[sb->len - ignore_footer] = '\0';
376 trailer_iterator_init(&iter, sb->buf);
378 if (ignore_footer)
379 sb->buf[sb->len - ignore_footer] = saved_char;
381 while (trailer_iterator_advance(&iter)) {
382 i++;
383 if (sob && !strncmp(iter.raw, sob->buf, sob->len))
384 found_sob = i;
386 trailer_iterator_release(&iter);
388 if (!i)
389 return 0;
391 found_sob_last = (int)i == found_sob;
393 if (found_sob_last)
394 return 3;
395 if (found_sob)
396 return 2;
397 return 1;
400 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
402 static struct strbuf buf = STRBUF_INIT;
404 strbuf_reset(&buf);
405 if (opts->gpg_sign)
406 sq_quotef(&buf, "-S%s", opts->gpg_sign);
407 return buf.buf;
410 static void replay_ctx_release(struct replay_ctx *ctx)
412 strbuf_release(&ctx->current_fixups);
413 strbuf_release(&ctx->message);
416 void replay_opts_release(struct replay_opts *opts)
418 struct replay_ctx *ctx = opts->ctx;
420 free(opts->gpg_sign);
421 free(opts->reflog_action);
422 free(opts->default_strategy);
423 free(opts->strategy);
424 strvec_clear (&opts->xopts);
425 if (opts->revs)
426 release_revisions(opts->revs);
427 free(opts->revs);
428 replay_ctx_release(ctx);
429 free(opts->ctx);
432 int sequencer_remove_state(struct replay_opts *opts)
434 struct strbuf buf = STRBUF_INIT;
435 int ret = 0;
437 if (is_rebase_i(opts) &&
438 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
439 char *p = buf.buf;
440 while (*p) {
441 char *eol = strchr(p, '\n');
442 if (eol)
443 *eol = '\0';
444 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
445 warning(_("could not delete '%s'"), p);
446 ret = -1;
448 if (!eol)
449 break;
450 p = eol + 1;
454 strbuf_reset(&buf);
455 strbuf_addstr(&buf, get_dir(opts));
456 if (remove_dir_recursively(&buf, 0))
457 ret = error(_("could not remove '%s'"), buf.buf);
458 strbuf_release(&buf);
460 return ret;
463 static const char *action_name(const struct replay_opts *opts)
465 switch (opts->action) {
466 case REPLAY_REVERT:
467 return N_("revert");
468 case REPLAY_PICK:
469 return N_("cherry-pick");
470 case REPLAY_INTERACTIVE_REBASE:
471 return N_("rebase");
473 die(_("unknown action: %d"), opts->action);
476 struct commit_message {
477 char *parent_label;
478 char *label;
479 char *subject;
480 const char *message;
483 static const char *short_commit_name(struct repository *r, struct commit *commit)
485 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
488 static int get_message(struct commit *commit, struct commit_message *out)
490 const char *abbrev, *subject;
491 int subject_len;
493 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
494 get_commit_output_encoding());
495 abbrev = short_commit_name(the_repository, commit);
497 subject_len = find_commit_subject(out->message, &subject);
499 out->subject = xmemdupz(subject, subject_len);
500 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
501 out->parent_label = xstrfmt("parent of %s", out->label);
503 return 0;
506 static void free_message(struct commit *commit, struct commit_message *msg)
508 free(msg->parent_label);
509 free(msg->label);
510 free(msg->subject);
511 repo_unuse_commit_buffer(the_repository, commit, msg->message);
514 const char *rebase_resolvemsg =
515 N_("Resolve all conflicts manually, mark them as resolved with\n"
516 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
517 "You can instead skip this commit: run \"git rebase --skip\".\n"
518 "To abort and get back to the state before \"git rebase\", run "
519 "\"git rebase --abort\".");
521 static void print_advice(struct repository *r, int show_hint,
522 struct replay_opts *opts)
524 const char *msg;
526 if (is_rebase_i(opts))
527 msg = rebase_resolvemsg;
528 else
529 msg = getenv("GIT_CHERRY_PICK_HELP");
531 if (msg) {
532 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
534 * A conflict has occurred but the porcelain
535 * (typically rebase --interactive) wants to take care
536 * of the commit itself so remove CHERRY_PICK_HEAD
538 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
539 NULL, REF_NO_DEREF);
540 return;
543 if (show_hint) {
544 if (opts->no_commit)
545 advise_if_enabled(ADVICE_MERGE_CONFLICT,
546 _("after resolving the conflicts, mark the corrected paths\n"
547 "with 'git add <paths>' or 'git rm <paths>'"));
548 else if (opts->action == REPLAY_PICK)
549 advise_if_enabled(ADVICE_MERGE_CONFLICT,
550 _("After resolving the conflicts, mark them with\n"
551 "\"git add/rm <pathspec>\", then run\n"
552 "\"git cherry-pick --continue\".\n"
553 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
554 "To abort and get back to the state before \"git cherry-pick\",\n"
555 "run \"git cherry-pick --abort\"."));
556 else if (opts->action == REPLAY_REVERT)
557 advise_if_enabled(ADVICE_MERGE_CONFLICT,
558 _("After resolving the conflicts, mark them with\n"
559 "\"git add/rm <pathspec>\", then run\n"
560 "\"git revert --continue\".\n"
561 "You can instead skip this commit with \"git revert --skip\".\n"
562 "To abort and get back to the state before \"git revert\",\n"
563 "run \"git revert --abort\"."));
564 else
565 BUG("unexpected pick action in print_advice()");
569 static int write_message(const void *buf, size_t len, const char *filename,
570 int append_eol)
572 struct lock_file msg_file = LOCK_INIT;
574 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
575 if (msg_fd < 0)
576 return error_errno(_("could not lock '%s'"), filename);
577 if (write_in_full(msg_fd, buf, len) < 0) {
578 error_errno(_("could not write to '%s'"), filename);
579 rollback_lock_file(&msg_file);
580 return -1;
582 if (append_eol && write(msg_fd, "\n", 1) < 0) {
583 error_errno(_("could not write eol to '%s'"), filename);
584 rollback_lock_file(&msg_file);
585 return -1;
587 if (commit_lock_file(&msg_file) < 0)
588 return error(_("failed to finalize '%s'"), filename);
590 return 0;
593 int read_oneliner(struct strbuf *buf,
594 const char *path, unsigned flags)
596 int orig_len = buf->len;
598 if (strbuf_read_file(buf, path, 0) < 0) {
599 if ((flags & READ_ONELINER_WARN_MISSING) ||
600 (errno != ENOENT && errno != ENOTDIR))
601 warning_errno(_("could not read '%s'"), path);
602 return 0;
605 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
606 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
607 --buf->len;
608 buf->buf[buf->len] = '\0';
611 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
612 return 0;
614 return 1;
617 static struct tree *empty_tree(struct repository *r)
619 return lookup_tree(r, the_hash_algo->empty_tree);
622 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
624 if (repo_read_index_unmerged(repo))
625 return error_resolve_conflict(action_name(opts));
627 error(_("your local changes would be overwritten by %s."),
628 _(action_name(opts)));
630 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
631 advise(_("commit your changes or stash them to proceed."));
632 return -1;
635 static void update_abort_safety_file(void)
637 struct object_id head;
639 /* Do nothing on a single-pick */
640 if (!file_exists(git_path_seq_dir()))
641 return;
643 if (!repo_get_oid(the_repository, "HEAD", &head))
644 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
645 else
646 write_file(git_path_abort_safety_file(), "%s", "");
649 static int fast_forward_to(struct repository *r,
650 const struct object_id *to,
651 const struct object_id *from,
652 int unborn,
653 struct replay_opts *opts)
655 struct ref_transaction *transaction;
656 struct strbuf sb = STRBUF_INIT;
657 struct strbuf err = STRBUF_INIT;
659 repo_read_index(r);
660 if (checkout_fast_forward(r, from, to, 1))
661 return -1; /* the callee should have complained already */
663 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
665 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
666 0, &err);
667 if (!transaction ||
668 ref_transaction_update(transaction, "HEAD",
669 to, unborn && !is_rebase_i(opts) ?
670 null_oid() : from, NULL, NULL,
671 0, sb.buf, &err) ||
672 ref_transaction_commit(transaction, &err)) {
673 ref_transaction_free(transaction);
674 error("%s", err.buf);
675 strbuf_release(&sb);
676 strbuf_release(&err);
677 return -1;
680 strbuf_release(&sb);
681 strbuf_release(&err);
682 ref_transaction_free(transaction);
683 update_abort_safety_file();
684 return 0;
687 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
688 int use_editor)
690 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
691 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
692 COMMIT_MSG_CLEANUP_SPACE;
693 else if (!strcmp(cleanup_arg, "verbatim"))
694 return COMMIT_MSG_CLEANUP_NONE;
695 else if (!strcmp(cleanup_arg, "whitespace"))
696 return COMMIT_MSG_CLEANUP_SPACE;
697 else if (!strcmp(cleanup_arg, "strip"))
698 return COMMIT_MSG_CLEANUP_ALL;
699 else if (!strcmp(cleanup_arg, "scissors"))
700 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
701 COMMIT_MSG_CLEANUP_SPACE;
702 else
703 die(_("Invalid cleanup mode %s"), cleanup_arg);
707 * NB using int rather than enum cleanup_mode to stop clang's
708 * -Wtautological-constant-out-of-range-compare complaining that the comparison
709 * is always true.
711 static const char *describe_cleanup_mode(int cleanup_mode)
713 static const char *modes[] = { "whitespace",
714 "verbatim",
715 "scissors",
716 "strip" };
718 if (cleanup_mode < ARRAY_SIZE(modes))
719 return modes[cleanup_mode];
721 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
724 void append_conflicts_hint(struct index_state *istate,
725 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
727 int i;
729 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
730 strbuf_addch(msgbuf, '\n');
731 wt_status_append_cut_line(msgbuf);
732 strbuf_addstr(msgbuf, comment_line_str);
735 strbuf_addch(msgbuf, '\n');
736 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
737 for (i = 0; i < istate->cache_nr;) {
738 const struct cache_entry *ce = istate->cache[i++];
739 if (ce_stage(ce)) {
740 strbuf_commented_addf(msgbuf, comment_line_str,
741 "\t%s\n", ce->name);
742 while (i < istate->cache_nr &&
743 !strcmp(ce->name, istate->cache[i]->name))
744 i++;
749 static int do_recursive_merge(struct repository *r,
750 struct commit *base, struct commit *next,
751 const char *base_label, const char *next_label,
752 struct object_id *head, struct strbuf *msgbuf,
753 struct replay_opts *opts)
755 struct merge_options o;
756 struct merge_result result;
757 struct tree *next_tree, *base_tree, *head_tree;
758 int clean, show_output;
759 int i;
760 struct lock_file index_lock = LOCK_INIT;
762 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
763 return -1;
765 repo_read_index(r);
767 init_ui_merge_options(&o, r);
768 o.ancestor = base ? base_label : "(empty tree)";
769 o.branch1 = "HEAD";
770 o.branch2 = next ? next_label : "(empty tree)";
771 if (is_rebase_i(opts))
772 o.buffer_output = 2;
773 o.show_rename_progress = 1;
775 head_tree = parse_tree_indirect(head);
776 if (!head_tree)
777 return error(_("unable to read tree (%s)"), oid_to_hex(head));
778 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
779 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
781 for (i = 0; i < opts->xopts.nr; i++)
782 parse_merge_opt(&o, opts->xopts.v[i]);
784 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
785 memset(&result, 0, sizeof(result));
786 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
787 &result);
788 show_output = !is_rebase_i(opts) || !result.clean;
790 * TODO: merge_switch_to_result will update index/working tree;
791 * we only really want to do that if !result.clean || this is
792 * the final patch to be picked. But determining this is the
793 * final patch would take some work, and "head_tree" would need
794 * to be replace with the tree the index matched before we
795 * started doing any picks.
797 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
798 clean = result.clean;
799 } else {
800 ensure_full_index(r->index);
801 clean = merge_trees(&o, head_tree, next_tree, base_tree);
802 if (is_rebase_i(opts) && clean <= 0)
803 fputs(o.obuf.buf, stdout);
804 strbuf_release(&o.obuf);
806 if (clean < 0) {
807 rollback_lock_file(&index_lock);
808 return clean;
811 if (write_locked_index(r->index, &index_lock,
812 COMMIT_LOCK | SKIP_IF_UNCHANGED))
814 * TRANSLATORS: %s will be "revert", "cherry-pick" or
815 * "rebase".
817 return error(_("%s: Unable to write new index file"),
818 _(action_name(opts)));
820 if (!clean)
821 append_conflicts_hint(r->index, msgbuf,
822 opts->default_msg_cleanup);
824 return !clean;
827 static struct object_id *get_cache_tree_oid(struct index_state *istate)
829 if (!cache_tree_fully_valid(istate->cache_tree))
830 if (cache_tree_update(istate, 0)) {
831 error(_("unable to update cache tree"));
832 return NULL;
835 return &istate->cache_tree->oid;
838 static int is_index_unchanged(struct repository *r)
840 struct object_id head_oid, *cache_tree_oid;
841 const struct object_id *head_tree_oid;
842 struct commit *head_commit;
843 struct index_state *istate = r->index;
844 const char *head_name;
846 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
847 /* Check to see if this is an unborn branch */
848 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
849 "HEAD",
850 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
851 &head_oid, NULL);
852 if (!head_name ||
853 !starts_with(head_name, "refs/heads/") ||
854 !is_null_oid(&head_oid))
855 return error(_("could not resolve HEAD commit"));
856 head_tree_oid = the_hash_algo->empty_tree;
857 } else {
858 head_commit = lookup_commit(r, &head_oid);
861 * If head_commit is NULL, check_commit, called from
862 * lookup_commit, would have indicated that head_commit is not
863 * a commit object already. repo_parse_commit() will return failure
864 * without further complaints in such a case. Otherwise, if
865 * the commit is invalid, repo_parse_commit() will complain. So
866 * there is nothing for us to say here. Just return failure.
868 if (repo_parse_commit(r, head_commit))
869 return -1;
871 head_tree_oid = get_commit_tree_oid(head_commit);
874 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
875 return -1;
877 return oideq(cache_tree_oid, head_tree_oid);
880 static int write_author_script(const char *message)
882 struct strbuf buf = STRBUF_INIT;
883 const char *eol;
884 int res;
886 for (;;)
887 if (!*message || starts_with(message, "\n")) {
888 missing_author:
889 /* Missing 'author' line? */
890 unlink(rebase_path_author_script());
891 return 0;
892 } else if (skip_prefix(message, "author ", &message))
893 break;
894 else if ((eol = strchr(message, '\n')))
895 message = eol + 1;
896 else
897 goto missing_author;
899 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
900 while (*message && *message != '\n' && *message != '\r')
901 if (skip_prefix(message, " <", &message))
902 break;
903 else if (*message != '\'')
904 strbuf_addch(&buf, *(message++));
905 else
906 strbuf_addf(&buf, "'\\%c'", *(message++));
907 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
908 while (*message && *message != '\n' && *message != '\r')
909 if (skip_prefix(message, "> ", &message))
910 break;
911 else if (*message != '\'')
912 strbuf_addch(&buf, *(message++));
913 else
914 strbuf_addf(&buf, "'\\%c'", *(message++));
915 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
916 while (*message && *message != '\n' && *message != '\r')
917 if (*message != '\'')
918 strbuf_addch(&buf, *(message++));
919 else
920 strbuf_addf(&buf, "'\\%c'", *(message++));
921 strbuf_addch(&buf, '\'');
922 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
923 strbuf_release(&buf);
924 return res;
928 * Take a series of KEY='VALUE' lines where VALUE part is
929 * sq-quoted, and append <KEY, VALUE> at the end of the string list
931 static int parse_key_value_squoted(char *buf, struct string_list *list)
933 while (*buf) {
934 struct string_list_item *item;
935 char *np;
936 char *cp = strchr(buf, '=');
937 if (!cp) {
938 np = strchrnul(buf, '\n');
939 return error(_("no key present in '%.*s'"),
940 (int) (np - buf), buf);
942 np = strchrnul(cp, '\n');
943 *cp++ = '\0';
944 item = string_list_append(list, buf);
946 buf = np + (*np == '\n');
947 *np = '\0';
948 cp = sq_dequote(cp);
949 if (!cp)
950 return error(_("unable to dequote value of '%s'"),
951 item->string);
952 item->util = xstrdup(cp);
954 return 0;
958 * Reads and parses the state directory's "author-script" file, and sets name,
959 * email and date accordingly.
960 * Returns 0 on success, -1 if the file could not be parsed.
962 * The author script is of the format:
964 * GIT_AUTHOR_NAME='$author_name'
965 * GIT_AUTHOR_EMAIL='$author_email'
966 * GIT_AUTHOR_DATE='$author_date'
968 * where $author_name, $author_email and $author_date are quoted. We are strict
969 * with our parsing, as the file was meant to be eval'd in the now-removed
970 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
971 * from what this function expects, it is better to bail out than to do
972 * something that the user does not expect.
974 int read_author_script(const char *path, char **name, char **email, char **date,
975 int allow_missing)
977 struct strbuf buf = STRBUF_INIT;
978 struct string_list kv = STRING_LIST_INIT_DUP;
979 int retval = -1; /* assume failure */
980 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
982 if (strbuf_read_file(&buf, path, 256) <= 0) {
983 strbuf_release(&buf);
984 if (errno == ENOENT && allow_missing)
985 return 0;
986 else
987 return error_errno(_("could not open '%s' for reading"),
988 path);
991 if (parse_key_value_squoted(buf.buf, &kv))
992 goto finish;
994 for (i = 0; i < kv.nr; i++) {
995 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
996 if (name_i != -2)
997 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
998 else
999 name_i = i;
1000 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
1001 if (email_i != -2)
1002 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
1003 else
1004 email_i = i;
1005 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
1006 if (date_i != -2)
1007 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
1008 else
1009 date_i = i;
1010 } else {
1011 err = error(_("unknown variable '%s'"),
1012 kv.items[i].string);
1015 if (name_i == -2)
1016 error(_("missing 'GIT_AUTHOR_NAME'"));
1017 if (email_i == -2)
1018 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1019 if (date_i == -2)
1020 error(_("missing 'GIT_AUTHOR_DATE'"));
1021 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
1022 goto finish;
1023 *name = kv.items[name_i].util;
1024 *email = kv.items[email_i].util;
1025 *date = kv.items[date_i].util;
1026 retval = 0;
1027 finish:
1028 string_list_clear(&kv, !!retval);
1029 strbuf_release(&buf);
1030 return retval;
1034 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
1035 * file with shell quoting into struct strvec. Returns -1 on
1036 * error, 0 otherwise.
1038 static int read_env_script(struct strvec *env)
1040 char *name, *email, *date;
1042 if (read_author_script(rebase_path_author_script(),
1043 &name, &email, &date, 0))
1044 return -1;
1046 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1047 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1048 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
1049 free(name);
1050 free(email);
1051 free(date);
1053 return 0;
1056 static char *get_author(const char *message)
1058 size_t len;
1059 const char *a;
1061 a = find_commit_header(message, "author", &len);
1062 if (a)
1063 return xmemdupz(a, len);
1065 return NULL;
1068 static const char *author_date_from_env(const struct strvec *env)
1070 int i;
1071 const char *date;
1073 for (i = 0; i < env->nr; i++)
1074 if (skip_prefix(env->v[i],
1075 "GIT_AUTHOR_DATE=", &date))
1076 return date;
1078 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1079 * reading the script
1081 BUG("GIT_AUTHOR_DATE missing from author script");
1084 static const char staged_changes_advice[] =
1085 N_("you have staged changes in your working tree\n"
1086 "If these changes are meant to be squashed into the previous commit, run:\n"
1087 "\n"
1088 " git commit --amend %s\n"
1089 "\n"
1090 "If they are meant to go into a new commit, run:\n"
1091 "\n"
1092 " git commit %s\n"
1093 "\n"
1094 "In both cases, once you're done, continue with:\n"
1095 "\n"
1096 " git rebase --continue\n");
1098 #define ALLOW_EMPTY (1<<0)
1099 #define EDIT_MSG (1<<1)
1100 #define AMEND_MSG (1<<2)
1101 #define CLEANUP_MSG (1<<3)
1102 #define VERIFY_MSG (1<<4)
1103 #define CREATE_ROOT_COMMIT (1<<5)
1104 #define VERBATIM_MSG (1<<6)
1106 static int run_command_silent_on_success(struct child_process *cmd)
1108 struct strbuf buf = STRBUF_INIT;
1109 int rc;
1111 cmd->stdout_to_stderr = 1;
1112 rc = pipe_command(cmd,
1113 NULL, 0,
1114 NULL, 0,
1115 &buf, 0);
1117 if (rc)
1118 fputs(buf.buf, stderr);
1119 strbuf_release(&buf);
1120 return rc;
1124 * If we are cherry-pick, and if the merge did not result in
1125 * hand-editing, we will hit this commit and inherit the original
1126 * author date and name.
1128 * If we are revert, or if our cherry-pick results in a hand merge,
1129 * we had better say that the current user is responsible for that.
1131 * An exception is when run_git_commit() is called during an
1132 * interactive rebase: in that case, we will want to retain the
1133 * author metadata.
1135 static int run_git_commit(const char *defmsg,
1136 struct replay_opts *opts,
1137 unsigned int flags)
1139 struct replay_ctx *ctx = opts->ctx;
1140 struct child_process cmd = CHILD_PROCESS_INIT;
1142 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1143 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1145 cmd.git_cmd = 1;
1147 if (is_rebase_i(opts) &&
1148 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1149 !(!defmsg && (flags & AMEND_MSG))) &&
1150 read_env_script(&cmd.env)) {
1151 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1153 return error(_(staged_changes_advice),
1154 gpg_opt, gpg_opt);
1157 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", ctx->reflog_message);
1159 if (opts->committer_date_is_author_date)
1160 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1161 opts->ignore_date ?
1162 "" :
1163 author_date_from_env(&cmd.env));
1164 if (opts->ignore_date)
1165 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1167 strvec_push(&cmd.args, "commit");
1169 if (!(flags & VERIFY_MSG))
1170 strvec_push(&cmd.args, "-n");
1171 if ((flags & AMEND_MSG))
1172 strvec_push(&cmd.args, "--amend");
1173 if (opts->gpg_sign)
1174 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1175 else
1176 strvec_push(&cmd.args, "--no-gpg-sign");
1177 if (defmsg)
1178 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1179 else if (!(flags & EDIT_MSG))
1180 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1181 if ((flags & CLEANUP_MSG))
1182 strvec_push(&cmd.args, "--cleanup=strip");
1183 if ((flags & VERBATIM_MSG))
1184 strvec_push(&cmd.args, "--cleanup=verbatim");
1185 if ((flags & EDIT_MSG))
1186 strvec_push(&cmd.args, "-e");
1187 else if (!(flags & CLEANUP_MSG) &&
1188 !opts->signoff && !opts->record_origin &&
1189 !opts->explicit_cleanup)
1190 strvec_push(&cmd.args, "--cleanup=verbatim");
1192 if ((flags & ALLOW_EMPTY))
1193 strvec_push(&cmd.args, "--allow-empty");
1195 if (!(flags & EDIT_MSG))
1196 strvec_push(&cmd.args, "--allow-empty-message");
1198 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1199 return run_command_silent_on_success(&cmd);
1200 else
1201 return run_command(&cmd);
1204 static int rest_is_empty(const struct strbuf *sb, int start)
1206 int i, eol;
1207 const char *nl;
1209 /* Check if the rest is just whitespace and Signed-off-by's. */
1210 for (i = start; i < sb->len; i++) {
1211 nl = memchr(sb->buf + i, '\n', sb->len - i);
1212 if (nl)
1213 eol = nl - sb->buf;
1214 else
1215 eol = sb->len;
1217 if (strlen(sign_off_header) <= eol - i &&
1218 starts_with(sb->buf + i, sign_off_header)) {
1219 i = eol;
1220 continue;
1222 while (i < eol)
1223 if (!isspace(sb->buf[i++]))
1224 return 0;
1227 return 1;
1230 void cleanup_message(struct strbuf *msgbuf,
1231 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1233 if (verbose || /* Truncate the message just before the diff, if any. */
1234 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1235 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1236 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1237 strbuf_stripspace(msgbuf,
1238 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1242 * Find out if the message in the strbuf contains only whitespace and
1243 * Signed-off-by lines.
1245 int message_is_empty(const struct strbuf *sb,
1246 enum commit_msg_cleanup_mode cleanup_mode)
1248 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1249 return 0;
1250 return rest_is_empty(sb, 0);
1254 * See if the user edited the message in the editor or left what
1255 * was in the template intact
1257 int template_untouched(const struct strbuf *sb, const char *template_file,
1258 enum commit_msg_cleanup_mode cleanup_mode)
1260 struct strbuf tmpl = STRBUF_INIT;
1261 const char *start;
1263 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1264 return 0;
1266 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1267 return 0;
1269 strbuf_stripspace(&tmpl,
1270 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1271 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1272 start = sb->buf;
1273 strbuf_release(&tmpl);
1274 return rest_is_empty(sb, start - sb->buf);
1277 int update_head_with_reflog(const struct commit *old_head,
1278 const struct object_id *new_head,
1279 const char *action, const struct strbuf *msg,
1280 struct strbuf *err)
1282 struct ref_transaction *transaction;
1283 struct strbuf sb = STRBUF_INIT;
1284 const char *nl;
1285 int ret = 0;
1287 if (action) {
1288 strbuf_addstr(&sb, action);
1289 strbuf_addstr(&sb, ": ");
1292 nl = strchr(msg->buf, '\n');
1293 if (nl) {
1294 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1295 } else {
1296 strbuf_addbuf(&sb, msg);
1297 strbuf_addch(&sb, '\n');
1300 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1301 0, err);
1302 if (!transaction ||
1303 ref_transaction_update(transaction, "HEAD", new_head,
1304 old_head ? &old_head->object.oid : null_oid(),
1305 NULL, NULL, 0, sb.buf, err) ||
1306 ref_transaction_commit(transaction, err)) {
1307 ret = -1;
1309 ref_transaction_free(transaction);
1310 strbuf_release(&sb);
1312 return ret;
1315 static int run_rewrite_hook(const struct object_id *oldoid,
1316 const struct object_id *newoid)
1318 struct child_process proc = CHILD_PROCESS_INIT;
1319 int code;
1320 struct strbuf sb = STRBUF_INIT;
1321 const char *hook_path = find_hook(the_repository, "post-rewrite");
1323 if (!hook_path)
1324 return 0;
1326 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1327 proc.in = -1;
1328 proc.stdout_to_stderr = 1;
1329 proc.trace2_hook_name = "post-rewrite";
1331 code = start_command(&proc);
1332 if (code)
1333 return code;
1334 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1335 sigchain_push(SIGPIPE, SIG_IGN);
1336 write_in_full(proc.in, sb.buf, sb.len);
1337 close(proc.in);
1338 strbuf_release(&sb);
1339 sigchain_pop(SIGPIPE);
1340 return finish_command(&proc);
1343 void commit_post_rewrite(struct repository *r,
1344 const struct commit *old_head,
1345 const struct object_id *new_head)
1347 struct notes_rewrite_cfg *cfg;
1349 cfg = init_copy_notes_for_rewrite("amend");
1350 if (cfg) {
1351 /* we are amending, so old_head is not NULL */
1352 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1353 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1355 run_rewrite_hook(&old_head->object.oid, new_head);
1358 static int run_prepare_commit_msg_hook(struct repository *r,
1359 struct strbuf *msg,
1360 const char *commit)
1362 int ret = 0;
1363 const char *name, *arg1 = NULL, *arg2 = NULL;
1365 name = git_path_commit_editmsg();
1366 if (write_message(msg->buf, msg->len, name, 0))
1367 return -1;
1369 if (commit) {
1370 arg1 = "commit";
1371 arg2 = commit;
1372 } else {
1373 arg1 = "message";
1375 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1376 arg1, arg2, NULL))
1377 ret = error(_("'prepare-commit-msg' hook failed"));
1379 return ret;
1382 static const char implicit_ident_advice_noconfig[] =
1383 N_("Your name and email address were configured automatically based\n"
1384 "on your username and hostname. Please check that they are accurate.\n"
1385 "You can suppress this message by setting them explicitly. Run the\n"
1386 "following command and follow the instructions in your editor to edit\n"
1387 "your configuration file:\n"
1388 "\n"
1389 " git config --global --edit\n"
1390 "\n"
1391 "After doing this, you may fix the identity used for this commit with:\n"
1392 "\n"
1393 " git commit --amend --reset-author\n");
1395 static const char implicit_ident_advice_config[] =
1396 N_("Your name and email address were configured automatically based\n"
1397 "on your username and hostname. Please check that they are accurate.\n"
1398 "You can suppress this message by setting them explicitly:\n"
1399 "\n"
1400 " git config --global user.name \"Your Name\"\n"
1401 " git config --global user.email you@example.com\n"
1402 "\n"
1403 "After doing this, you may fix the identity used for this commit with:\n"
1404 "\n"
1405 " git commit --amend --reset-author\n");
1407 static const char *implicit_ident_advice(void)
1409 char *user_config = interpolate_path("~/.gitconfig", 0);
1410 char *xdg_config = xdg_config_home("config");
1411 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1413 free(user_config);
1414 free(xdg_config);
1416 if (config_exists)
1417 return _(implicit_ident_advice_config);
1418 else
1419 return _(implicit_ident_advice_noconfig);
1423 void print_commit_summary(struct repository *r,
1424 const char *prefix,
1425 const struct object_id *oid,
1426 unsigned int flags)
1428 struct rev_info rev;
1429 struct commit *commit;
1430 struct strbuf format = STRBUF_INIT;
1431 const char *head;
1432 struct pretty_print_context pctx = {0};
1433 struct strbuf author_ident = STRBUF_INIT;
1434 struct strbuf committer_ident = STRBUF_INIT;
1435 struct ref_store *refs;
1437 commit = lookup_commit(r, oid);
1438 if (!commit)
1439 die(_("couldn't look up newly created commit"));
1440 if (repo_parse_commit(r, commit))
1441 die(_("could not parse newly created commit"));
1443 strbuf_addstr(&format, "format:%h] %s");
1445 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1446 &pctx);
1447 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1448 &pctx);
1449 if (strbuf_cmp(&author_ident, &committer_ident)) {
1450 strbuf_addstr(&format, "\n Author: ");
1451 strbuf_addbuf_percentquote(&format, &author_ident);
1453 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1454 struct strbuf date = STRBUF_INIT;
1456 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1457 strbuf_addstr(&format, "\n Date: ");
1458 strbuf_addbuf_percentquote(&format, &date);
1459 strbuf_release(&date);
1461 if (!committer_ident_sufficiently_given()) {
1462 strbuf_addstr(&format, "\n Committer: ");
1463 strbuf_addbuf_percentquote(&format, &committer_ident);
1464 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1465 strbuf_addch(&format, '\n');
1466 strbuf_addstr(&format, implicit_ident_advice());
1469 strbuf_release(&author_ident);
1470 strbuf_release(&committer_ident);
1472 repo_init_revisions(r, &rev, prefix);
1473 setup_revisions(0, NULL, &rev, NULL);
1475 rev.diff = 1;
1476 rev.diffopt.output_format =
1477 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1479 rev.verbose_header = 1;
1480 rev.show_root_diff = 1;
1481 get_commit_format(format.buf, &rev);
1482 rev.always_show_header = 0;
1483 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1484 diff_setup_done(&rev.diffopt);
1486 refs = get_main_ref_store(r);
1487 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1488 if (!head)
1489 die(_("unable to resolve HEAD after creating commit"));
1490 if (!strcmp(head, "HEAD"))
1491 head = _("detached HEAD");
1492 else
1493 skip_prefix(head, "refs/heads/", &head);
1494 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1495 _(" (root-commit)") : "");
1497 if (!log_tree_commit(&rev, commit)) {
1498 rev.always_show_header = 1;
1499 rev.use_terminator = 1;
1500 log_tree_commit(&rev, commit);
1503 release_revisions(&rev);
1504 strbuf_release(&format);
1507 static int parse_head(struct repository *r, struct commit **head)
1509 struct commit *current_head;
1510 struct object_id oid;
1512 if (repo_get_oid(r, "HEAD", &oid)) {
1513 current_head = NULL;
1514 } else {
1515 current_head = lookup_commit_reference(r, &oid);
1516 if (!current_head)
1517 return error(_("could not parse HEAD"));
1518 if (!oideq(&oid, &current_head->object.oid)) {
1519 warning(_("HEAD %s is not a commit!"),
1520 oid_to_hex(&oid));
1522 if (repo_parse_commit(r, current_head))
1523 return error(_("could not parse HEAD commit"));
1525 *head = current_head;
1527 return 0;
1531 * Try to commit without forking 'git commit'. In some cases we need
1532 * to run 'git commit' to display an error message
1534 * Returns:
1535 * -1 - error unable to commit
1536 * 0 - success
1537 * 1 - run 'git commit'
1539 static int try_to_commit(struct repository *r,
1540 struct strbuf *msg, const char *author,
1541 struct replay_opts *opts, unsigned int flags,
1542 struct object_id *oid)
1544 struct replay_ctx *ctx = opts->ctx;
1545 struct object_id tree;
1546 struct commit *current_head = NULL;
1547 struct commit_list *parents = NULL;
1548 struct commit_extra_header *extra = NULL;
1549 struct strbuf err = STRBUF_INIT;
1550 struct strbuf commit_msg = STRBUF_INIT;
1551 char *amend_author = NULL;
1552 const char *committer = NULL;
1553 const char *hook_commit = NULL;
1554 enum commit_msg_cleanup_mode cleanup;
1555 int res = 0;
1557 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1558 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1560 if (parse_head(r, &current_head))
1561 return -1;
1563 if (flags & AMEND_MSG) {
1564 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1565 const char *out_enc = get_commit_output_encoding();
1566 const char *message = repo_logmsg_reencode(r, current_head,
1567 NULL, out_enc);
1569 if (!msg) {
1570 const char *orig_message = NULL;
1572 find_commit_subject(message, &orig_message);
1573 msg = &commit_msg;
1574 strbuf_addstr(msg, orig_message);
1575 hook_commit = "HEAD";
1577 author = amend_author = get_author(message);
1578 repo_unuse_commit_buffer(r, current_head,
1579 message);
1580 if (!author) {
1581 res = error(_("unable to parse commit author"));
1582 goto out;
1584 parents = copy_commit_list(current_head->parents);
1585 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1586 } else if (current_head &&
1587 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1588 commit_list_insert(current_head, &parents);
1591 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1592 res = error(_("git write-tree failed to write a tree"));
1593 goto out;
1596 if (!(flags & ALLOW_EMPTY)) {
1597 struct commit *first_parent = current_head;
1599 if (flags & AMEND_MSG) {
1600 if (current_head->parents) {
1601 first_parent = current_head->parents->item;
1602 if (repo_parse_commit(r, first_parent)) {
1603 res = error(_("could not parse HEAD commit"));
1604 goto out;
1606 } else {
1607 first_parent = NULL;
1610 if (oideq(first_parent
1611 ? get_commit_tree_oid(first_parent)
1612 : the_hash_algo->empty_tree,
1613 &tree)) {
1614 res = 1; /* run 'git commit' to display error message */
1615 goto out;
1619 if (hook_exists(r, "prepare-commit-msg")) {
1620 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1621 if (res)
1622 goto out;
1623 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1624 2048) < 0) {
1625 res = error_errno(_("unable to read commit message "
1626 "from '%s'"),
1627 git_path_commit_editmsg());
1628 goto out;
1630 msg = &commit_msg;
1633 if (flags & CLEANUP_MSG)
1634 cleanup = COMMIT_MSG_CLEANUP_ALL;
1635 else if (flags & VERBATIM_MSG)
1636 cleanup = COMMIT_MSG_CLEANUP_NONE;
1637 else if ((opts->signoff || opts->record_origin) &&
1638 !opts->explicit_cleanup)
1639 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1640 else
1641 cleanup = opts->default_msg_cleanup;
1643 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1644 strbuf_stripspace(msg,
1645 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1646 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1647 res = 1; /* run 'git commit' to display error message */
1648 goto out;
1651 if (opts->committer_date_is_author_date) {
1652 struct ident_split id;
1653 struct strbuf date = STRBUF_INIT;
1655 if (!opts->ignore_date) {
1656 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1657 res = error(_("invalid author identity '%s'"),
1658 author);
1659 goto out;
1661 if (!id.date_begin) {
1662 res = error(_(
1663 "corrupt author: missing date information"));
1664 goto out;
1666 strbuf_addf(&date, "@%.*s %.*s",
1667 (int)(id.date_end - id.date_begin),
1668 id.date_begin,
1669 (int)(id.tz_end - id.tz_begin),
1670 id.tz_begin);
1671 } else {
1672 reset_ident_date();
1674 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1675 getenv("GIT_COMMITTER_EMAIL"),
1676 WANT_COMMITTER_IDENT,
1677 opts->ignore_date ? NULL : date.buf,
1678 IDENT_STRICT);
1679 strbuf_release(&date);
1680 } else {
1681 reset_ident_date();
1684 if (opts->ignore_date) {
1685 struct ident_split id;
1686 char *name, *email;
1688 if (split_ident_line(&id, author, strlen(author)) < 0) {
1689 error(_("invalid author identity '%s'"), author);
1690 goto out;
1692 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1693 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1694 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1695 IDENT_STRICT);
1696 free(name);
1697 free(email);
1700 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1701 author, committer, opts->gpg_sign, extra)) {
1702 res = error(_("failed to write commit object"));
1703 goto out;
1706 if (update_head_with_reflog(current_head, oid, ctx->reflog_message,
1707 msg, &err)) {
1708 res = error("%s", err.buf);
1709 goto out;
1712 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1713 if (flags & AMEND_MSG)
1714 commit_post_rewrite(r, current_head, oid);
1716 out:
1717 free_commit_extra_headers(extra);
1718 free_commit_list(parents);
1719 strbuf_release(&err);
1720 strbuf_release(&commit_msg);
1721 free(amend_author);
1723 return res;
1726 static int write_rebase_head(struct object_id *oid)
1728 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1729 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1730 return error(_("could not update %s"), "REBASE_HEAD");
1732 return 0;
1735 static int do_commit(struct repository *r,
1736 const char *msg_file, const char *author,
1737 struct replay_opts *opts, unsigned int flags,
1738 struct object_id *oid)
1740 int res = 1;
1742 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1743 struct object_id oid;
1744 struct strbuf sb = STRBUF_INIT;
1746 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1747 return error_errno(_("unable to read commit message "
1748 "from '%s'"),
1749 msg_file);
1751 res = try_to_commit(r, msg_file ? &sb : NULL,
1752 author, opts, flags, &oid);
1753 strbuf_release(&sb);
1754 if (!res) {
1755 refs_delete_ref(get_main_ref_store(r), "",
1756 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1757 unlink(git_path_merge_msg(r));
1758 if (!is_rebase_i(opts))
1759 print_commit_summary(r, NULL, &oid,
1760 SUMMARY_SHOW_AUTHOR_DATE);
1761 return res;
1764 if (res == 1) {
1765 if (is_rebase_i(opts) && oid)
1766 if (write_rebase_head(oid))
1767 return -1;
1768 return run_git_commit(msg_file, opts, flags);
1771 return res;
1774 static int is_original_commit_empty(struct commit *commit)
1776 const struct object_id *ptree_oid;
1778 if (repo_parse_commit(the_repository, commit))
1779 return error(_("could not parse commit %s"),
1780 oid_to_hex(&commit->object.oid));
1781 if (commit->parents) {
1782 struct commit *parent = commit->parents->item;
1783 if (repo_parse_commit(the_repository, parent))
1784 return error(_("could not parse parent commit %s"),
1785 oid_to_hex(&parent->object.oid));
1786 ptree_oid = get_commit_tree_oid(parent);
1787 } else {
1788 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1791 return oideq(ptree_oid, get_commit_tree_oid(commit));
1795 * Should empty commits be allowed? Return status:
1796 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1797 * 0: Halt on empty commit
1798 * 1: Allow empty commit
1799 * 2: Drop empty commit
1801 static int allow_empty(struct repository *r,
1802 struct replay_opts *opts,
1803 struct commit *commit)
1805 int index_unchanged, originally_empty;
1808 * For a commit that is initially empty, allow_empty determines if it
1809 * should be kept or not
1811 * For a commit that becomes empty, keep_redundant_commits and
1812 * drop_redundant_commits determine whether the commit should be kept or
1813 * dropped. If neither is specified, halt.
1815 index_unchanged = is_index_unchanged(r);
1816 if (index_unchanged < 0)
1817 return index_unchanged;
1818 if (!index_unchanged)
1819 return 0; /* we do not have to say --allow-empty */
1821 originally_empty = is_original_commit_empty(commit);
1822 if (originally_empty < 0)
1823 return originally_empty;
1824 if (originally_empty)
1825 return opts->allow_empty;
1826 else if (opts->keep_redundant_commits)
1827 return 1;
1828 else if (opts->drop_redundant_commits)
1829 return 2;
1830 else
1831 return 0;
1834 static struct {
1835 char c;
1836 const char *str;
1837 } todo_command_info[] = {
1838 [TODO_PICK] = { 'p', "pick" },
1839 [TODO_REVERT] = { 0, "revert" },
1840 [TODO_EDIT] = { 'e', "edit" },
1841 [TODO_REWORD] = { 'r', "reword" },
1842 [TODO_FIXUP] = { 'f', "fixup" },
1843 [TODO_SQUASH] = { 's', "squash" },
1844 [TODO_EXEC] = { 'x', "exec" },
1845 [TODO_BREAK] = { 'b', "break" },
1846 [TODO_LABEL] = { 'l', "label" },
1847 [TODO_RESET] = { 't', "reset" },
1848 [TODO_MERGE] = { 'm', "merge" },
1849 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1850 [TODO_NOOP] = { 0, "noop" },
1851 [TODO_DROP] = { 'd', "drop" },
1852 [TODO_COMMENT] = { 0, NULL },
1855 static const char *command_to_string(const enum todo_command command)
1857 if (command < TODO_COMMENT)
1858 return todo_command_info[command].str;
1859 if (command == TODO_COMMENT)
1860 return comment_line_str;
1861 die(_("unknown command: %d"), command);
1864 static char command_to_char(const enum todo_command command)
1866 if (command < TODO_COMMENT)
1867 return todo_command_info[command].c;
1868 return 0;
1871 static int is_noop(const enum todo_command command)
1873 return TODO_NOOP <= command;
1876 static int is_fixup(enum todo_command command)
1878 return command == TODO_FIXUP || command == TODO_SQUASH;
1881 /* Does this command create a (non-merge) commit? */
1882 static int is_pick_or_similar(enum todo_command command)
1884 switch (command) {
1885 case TODO_PICK:
1886 case TODO_REVERT:
1887 case TODO_EDIT:
1888 case TODO_REWORD:
1889 case TODO_FIXUP:
1890 case TODO_SQUASH:
1891 return 1;
1892 default:
1893 return 0;
1897 enum todo_item_flags {
1898 TODO_EDIT_MERGE_MSG = (1 << 0),
1899 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1900 TODO_EDIT_FIXUP_MSG = (1 << 2),
1903 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1904 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1905 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1906 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1907 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1909 static int is_fixup_flag(enum todo_command command, unsigned flag)
1911 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1912 (flag & TODO_EDIT_FIXUP_MSG));
1916 * Wrapper around strbuf_add_commented_lines() which avoids double
1917 * commenting commit subjects.
1919 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1921 const char *s = str;
1922 while (starts_with_mem(s, len, comment_line_str)) {
1923 size_t count;
1924 const char *n = memchr(s, '\n', len);
1925 if (!n)
1926 count = len;
1927 else
1928 count = n - s + 1;
1929 strbuf_add(buf, s, count);
1930 s += count;
1931 len -= count;
1933 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1936 /* Does the current fixup chain contain a squash command? */
1937 static int seen_squash(struct replay_ctx *ctx)
1939 return starts_with(ctx->current_fixups.buf, "squash") ||
1940 strstr(ctx->current_fixups.buf, "\nsquash");
1943 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1945 strbuf_setlen(buf1, strlen(comment_line_str) + 1);
1946 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1947 strbuf_addch(buf1, '\n');
1948 strbuf_setlen(buf2, strlen(comment_line_str) + 1);
1949 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1950 strbuf_addch(buf2, '\n');
1954 * Comment out any un-commented commit messages, updating the message comments
1955 * to say they will be skipped but do not comment out the empty lines that
1956 * surround commit messages and their comments.
1958 static void update_squash_message_for_fixup(struct strbuf *msg)
1960 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1961 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1962 const char *s, *start;
1963 char *orig_msg;
1964 size_t orig_msg_len;
1965 int i = 1;
1967 strbuf_add_commented_lines(&buf1, _(first_commit_msg_str),
1968 strlen(_(first_commit_msg_str)),
1969 comment_line_str);
1970 strbuf_add_commented_lines(&buf2, _(skip_first_commit_msg_str),
1971 strlen(_(skip_first_commit_msg_str)),
1972 comment_line_str);
1973 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1974 while (s) {
1975 const char *next;
1976 size_t off;
1977 if (skip_prefix(s, buf1.buf, &next)) {
1979 * Copy the last message, preserving the blank line
1980 * preceding the current line
1982 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1983 copy_lines(msg, start, s - start - off);
1984 if (off)
1985 strbuf_addch(msg, '\n');
1987 * The next message needs to be commented out but the
1988 * message header is already commented out so just copy
1989 * it and the blank line that follows it.
1991 strbuf_addbuf(msg, &buf2);
1992 if (*next == '\n')
1993 strbuf_addch(msg, *next++);
1994 start = s = next;
1995 copy_lines = add_commented_lines;
1996 update_comment_bufs(&buf1, &buf2, ++i);
1997 } else if (skip_prefix(s, buf2.buf, &next)) {
1998 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1999 copy_lines(msg, start, s - start - off);
2000 start = s - off;
2001 s = next;
2002 copy_lines = strbuf_add;
2003 update_comment_bufs(&buf1, &buf2, ++i);
2004 } else {
2005 s = strchr(s, '\n');
2006 if (s)
2007 s++;
2010 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2011 free(orig_msg);
2012 strbuf_release(&buf1);
2013 strbuf_release(&buf2);
2016 static int append_squash_message(struct strbuf *buf, const char *body,
2017 enum todo_command command, struct replay_opts *opts,
2018 unsigned flag)
2020 struct replay_ctx *ctx = opts->ctx;
2021 const char *fixup_msg;
2022 size_t commented_len = 0, fixup_off;
2024 * amend is non-interactive and not normally used with fixup!
2025 * or squash! commits, so only comment out those subjects when
2026 * squashing commit messages.
2028 if (starts_with(body, "amend!") ||
2029 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2030 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2031 commented_len = commit_subject_length(body);
2033 strbuf_addf(buf, "\n%s ", comment_line_str);
2034 strbuf_addf(buf, _(nth_commit_msg_fmt),
2035 ++ctx->current_fixup_count + 1);
2036 strbuf_addstr(buf, "\n\n");
2037 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2038 /* buf->buf may be reallocated so store an offset into the buffer */
2039 fixup_off = buf->len;
2040 strbuf_addstr(buf, body + commented_len);
2042 /* fixup -C after squash behaves like squash */
2043 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2045 * We're replacing the commit message so we need to
2046 * append the Signed-off-by: trailer if the user
2047 * requested '--signoff'.
2049 if (opts->signoff)
2050 append_signoff(buf, 0, 0);
2052 if ((command == TODO_FIXUP) &&
2053 (flag & TODO_REPLACE_FIXUP_MSG) &&
2054 (file_exists(rebase_path_fixup_msg()) ||
2055 !file_exists(rebase_path_squash_msg()))) {
2056 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2057 if (write_message(fixup_msg, strlen(fixup_msg),
2058 rebase_path_fixup_msg(), 0) < 0)
2059 return error(_("cannot write '%s'"),
2060 rebase_path_fixup_msg());
2061 } else {
2062 unlink(rebase_path_fixup_msg());
2064 } else {
2065 unlink(rebase_path_fixup_msg());
2068 return 0;
2071 static int update_squash_messages(struct repository *r,
2072 enum todo_command command,
2073 struct commit *commit,
2074 struct replay_opts *opts,
2075 unsigned flag)
2077 struct replay_ctx *ctx = opts->ctx;
2078 struct strbuf buf = STRBUF_INIT;
2079 int res = 0;
2080 const char *message, *body;
2081 const char *encoding = get_commit_output_encoding();
2083 if (ctx->current_fixup_count > 0) {
2084 struct strbuf header = STRBUF_INIT;
2085 char *eol;
2087 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2088 return error(_("could not read '%s'"),
2089 rebase_path_squash_msg());
2091 eol = !starts_with(buf.buf, comment_line_str) ?
2092 buf.buf : strchrnul(buf.buf, '\n');
2094 strbuf_addf(&header, "%s ", comment_line_str);
2095 strbuf_addf(&header, _(combined_commit_msg_fmt),
2096 ctx->current_fixup_count + 2);
2097 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2098 strbuf_release(&header);
2099 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2100 update_squash_message_for_fixup(&buf);
2101 } else {
2102 struct object_id head;
2103 struct commit *head_commit;
2104 const char *head_message, *body;
2106 if (repo_get_oid(r, "HEAD", &head))
2107 return error(_("need a HEAD to fixup"));
2108 if (!(head_commit = lookup_commit_reference(r, &head)))
2109 return error(_("could not read HEAD"));
2110 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2111 encoding)))
2112 return error(_("could not read HEAD's commit message"));
2114 find_commit_subject(head_message, &body);
2115 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2116 rebase_path_fixup_msg(), 0) < 0) {
2117 repo_unuse_commit_buffer(r, head_commit, head_message);
2118 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2120 strbuf_addf(&buf, "%s ", comment_line_str);
2121 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2122 strbuf_addf(&buf, "\n%s ", comment_line_str);
2123 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2124 _(skip_first_commit_msg_str) :
2125 _(first_commit_msg_str));
2126 strbuf_addstr(&buf, "\n\n");
2127 if (is_fixup_flag(command, flag))
2128 strbuf_add_commented_lines(&buf, body, strlen(body),
2129 comment_line_str);
2130 else
2131 strbuf_addstr(&buf, body);
2133 repo_unuse_commit_buffer(r, head_commit, head_message);
2136 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2137 return error(_("could not read commit message of %s"),
2138 oid_to_hex(&commit->object.oid));
2139 find_commit_subject(message, &body);
2141 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2142 res = append_squash_message(&buf, body, command, opts, flag);
2143 } else if (command == TODO_FIXUP) {
2144 strbuf_addf(&buf, "\n%s ", comment_line_str);
2145 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2146 ++ctx->current_fixup_count + 1);
2147 strbuf_addstr(&buf, "\n\n");
2148 strbuf_add_commented_lines(&buf, body, strlen(body),
2149 comment_line_str);
2150 } else
2151 return error(_("unknown command: %d"), command);
2152 repo_unuse_commit_buffer(r, commit, message);
2154 if (!res)
2155 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2157 strbuf_release(&buf);
2159 if (!res) {
2160 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2161 ctx->current_fixups.len ? "\n" : "",
2162 command_to_string(command),
2163 oid_to_hex(&commit->object.oid));
2164 res = write_message(ctx->current_fixups.buf,
2165 ctx->current_fixups.len,
2166 rebase_path_current_fixups(), 0);
2169 return res;
2172 static void flush_rewritten_pending(void)
2174 struct strbuf buf = STRBUF_INIT;
2175 struct object_id newoid;
2176 FILE *out;
2178 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2179 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2180 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2181 char *bol = buf.buf, *eol;
2183 while (*bol) {
2184 eol = strchrnul(bol, '\n');
2185 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2186 bol, oid_to_hex(&newoid));
2187 if (!*eol)
2188 break;
2189 bol = eol + 1;
2191 fclose(out);
2192 unlink(rebase_path_rewritten_pending());
2194 strbuf_release(&buf);
2197 static void record_in_rewritten(struct object_id *oid,
2198 enum todo_command next_command)
2200 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2202 if (!out)
2203 return;
2205 fprintf(out, "%s\n", oid_to_hex(oid));
2206 fclose(out);
2208 if (!is_fixup(next_command))
2209 flush_rewritten_pending();
2212 static int should_edit(struct replay_opts *opts) {
2213 if (opts->edit < 0)
2215 * Note that we only handle the case of non-conflicted
2216 * commits; continue_single_pick() handles the conflicted
2217 * commits itself instead of calling this function.
2219 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2220 return opts->edit;
2223 static void refer_to_commit(struct replay_opts *opts,
2224 struct strbuf *msgbuf, struct commit *commit)
2226 if (opts->commit_use_reference) {
2227 struct pretty_print_context ctx = {
2228 .abbrev = DEFAULT_ABBREV,
2229 .date_mode.type = DATE_SHORT,
2231 repo_format_commit_message(the_repository, commit,
2232 "%h (%s, %ad)", msgbuf, &ctx);
2233 } else {
2234 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2238 static int do_pick_commit(struct repository *r,
2239 struct todo_item *item,
2240 struct replay_opts *opts,
2241 int final_fixup, int *check_todo)
2243 struct replay_ctx *ctx = opts->ctx;
2244 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2245 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2246 struct object_id head;
2247 struct commit *base, *next, *parent;
2248 const char *base_label, *next_label;
2249 char *author = NULL;
2250 struct commit_message msg = { NULL, NULL, NULL, NULL };
2251 int res, unborn = 0, reword = 0, allow, drop_commit;
2252 enum todo_command command = item->command;
2253 struct commit *commit = item->commit;
2255 if (opts->no_commit) {
2257 * We do not intend to commit immediately. We just want to
2258 * merge the differences in, so let's compute the tree
2259 * that represents the "current" state for the merge machinery
2260 * to work on.
2262 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2263 return error(_("your index file is unmerged."));
2264 } else {
2265 unborn = repo_get_oid(r, "HEAD", &head);
2266 /* Do we want to generate a root commit? */
2267 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2268 oideq(&head, &opts->squash_onto)) {
2269 if (is_fixup(command))
2270 return error(_("cannot fixup root commit"));
2271 flags |= CREATE_ROOT_COMMIT;
2272 unborn = 1;
2273 } else if (unborn)
2274 oidcpy(&head, the_hash_algo->empty_tree);
2275 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD",
2276 NULL, 0))
2277 return error_dirty_index(r, opts);
2279 discard_index(r->index);
2281 if (!commit->parents)
2282 parent = NULL;
2283 else if (commit->parents->next) {
2284 /* Reverting or cherry-picking a merge commit */
2285 int cnt;
2286 struct commit_list *p;
2288 if (!opts->mainline)
2289 return error(_("commit %s is a merge but no -m option was given."),
2290 oid_to_hex(&commit->object.oid));
2292 for (cnt = 1, p = commit->parents;
2293 cnt != opts->mainline && p;
2294 cnt++)
2295 p = p->next;
2296 if (cnt != opts->mainline || !p)
2297 return error(_("commit %s does not have parent %d"),
2298 oid_to_hex(&commit->object.oid), opts->mainline);
2299 parent = p->item;
2300 } else if (1 < opts->mainline)
2302 * Non-first parent explicitly specified as mainline for
2303 * non-merge commit
2305 return error(_("commit %s does not have parent %d"),
2306 oid_to_hex(&commit->object.oid), opts->mainline);
2307 else
2308 parent = commit->parents->item;
2310 if (get_message(commit, &msg) != 0)
2311 return error(_("cannot get commit message for %s"),
2312 oid_to_hex(&commit->object.oid));
2314 if (opts->allow_ff && !is_fixup(command) &&
2315 ((parent && oideq(&parent->object.oid, &head)) ||
2316 (!parent && unborn))) {
2317 if (is_rebase_i(opts))
2318 write_author_script(msg.message);
2319 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2320 opts);
2321 if (res || command != TODO_REWORD)
2322 goto leave;
2323 reword = 1;
2324 msg_file = NULL;
2325 goto fast_forward_edit;
2327 if (parent && repo_parse_commit(r, parent) < 0)
2328 /* TRANSLATORS: The first %s will be a "todo" command like
2329 "revert" or "pick", the second %s a SHA1. */
2330 return error(_("%s: cannot parse parent commit %s"),
2331 command_to_string(command),
2332 oid_to_hex(&parent->object.oid));
2335 * "commit" is an existing commit. We would want to apply
2336 * the difference it introduces since its first parent "prev"
2337 * on top of the current HEAD if we are cherry-pick. Or the
2338 * reverse of it if we are revert.
2341 if (command == TODO_REVERT) {
2342 const char *orig_subject;
2344 base = commit;
2345 base_label = msg.label;
2346 next = parent;
2347 next_label = msg.parent_label;
2348 if (opts->commit_use_reference) {
2349 strbuf_commented_addf(&ctx->message, comment_line_str,
2350 "*** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2351 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2353 * We don't touch pre-existing repeated reverts, because
2354 * theoretically these can be nested arbitrarily deeply,
2355 * thus requiring excessive complexity to deal with.
2357 !starts_with(orig_subject, "Revert \"")) {
2358 strbuf_addstr(&ctx->message, "Reapply \"");
2359 strbuf_addstr(&ctx->message, orig_subject);
2360 strbuf_addstr(&ctx->message, "\n");
2361 } else {
2362 strbuf_addstr(&ctx->message, "Revert \"");
2363 strbuf_addstr(&ctx->message, msg.subject);
2364 strbuf_addstr(&ctx->message, "\"\n");
2366 strbuf_addstr(&ctx->message, "\nThis reverts commit ");
2367 refer_to_commit(opts, &ctx->message, commit);
2369 if (commit->parents && commit->parents->next) {
2370 strbuf_addstr(&ctx->message, ", reversing\nchanges made to ");
2371 refer_to_commit(opts, &ctx->message, parent);
2373 strbuf_addstr(&ctx->message, ".\n");
2374 } else {
2375 const char *p;
2377 base = parent;
2378 base_label = msg.parent_label;
2379 next = commit;
2380 next_label = msg.label;
2382 /* Append the commit log message to ctx->message. */
2383 if (find_commit_subject(msg.message, &p))
2384 strbuf_addstr(&ctx->message, p);
2386 if (opts->record_origin) {
2387 strbuf_complete_line(&ctx->message);
2388 if (!has_conforming_footer(&ctx->message, NULL, 0))
2389 strbuf_addch(&ctx->message, '\n');
2390 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2391 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid));
2392 strbuf_addstr(&ctx->message, ")\n");
2394 if (!is_fixup(command))
2395 author = get_author(msg.message);
2397 ctx->have_message = 1;
2399 if (command == TODO_REWORD)
2400 reword = 1;
2401 else if (is_fixup(command)) {
2402 if (update_squash_messages(r, command, commit,
2403 opts, item->flags)) {
2404 res = -1;
2405 goto leave;
2407 flags |= AMEND_MSG;
2408 if (!final_fixup)
2409 msg_file = rebase_path_squash_msg();
2410 else if (file_exists(rebase_path_fixup_msg())) {
2411 flags |= VERBATIM_MSG;
2412 msg_file = rebase_path_fixup_msg();
2413 } else {
2414 const char *dest = git_path_squash_msg(r);
2415 unlink(dest);
2416 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2417 res = error(_("could not copy '%s' to '%s'"),
2418 rebase_path_squash_msg(), dest);
2419 goto leave;
2421 unlink(git_path_merge_msg(r));
2422 msg_file = dest;
2423 flags |= EDIT_MSG;
2427 if (opts->signoff && !is_fixup(command))
2428 append_signoff(&ctx->message, 0, 0);
2430 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2431 res = -1;
2432 else if (!opts->strategy ||
2433 !strcmp(opts->strategy, "recursive") ||
2434 !strcmp(opts->strategy, "ort") ||
2435 command == TODO_REVERT) {
2436 res = do_recursive_merge(r, base, next, base_label, next_label,
2437 &head, &ctx->message, opts);
2438 if (res < 0)
2439 goto leave;
2441 res |= write_message(ctx->message.buf, ctx->message.len,
2442 git_path_merge_msg(r), 0);
2443 } else {
2444 struct commit_list *common = NULL;
2445 struct commit_list *remotes = NULL;
2447 res = write_message(ctx->message.buf, ctx->message.len,
2448 git_path_merge_msg(r), 0);
2450 commit_list_insert(base, &common);
2451 commit_list_insert(next, &remotes);
2452 res |= try_merge_command(r, opts->strategy,
2453 opts->xopts.nr, opts->xopts.v,
2454 common, oid_to_hex(&head), remotes);
2455 free_commit_list(common);
2456 free_commit_list(remotes);
2460 * If the merge was clean or if it failed due to conflict, we write
2461 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2462 * However, if the merge did not even start, then we don't want to
2463 * write it at all.
2465 if ((command == TODO_PICK || command == TODO_REWORD ||
2466 command == TODO_EDIT) && !opts->no_commit &&
2467 (res == 0 || res == 1) &&
2468 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2469 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2470 res = -1;
2471 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2472 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2473 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2474 res = -1;
2476 if (res) {
2477 error(command == TODO_REVERT
2478 ? _("could not revert %s... %s")
2479 : _("could not apply %s... %s"),
2480 short_commit_name(r, commit), msg.subject);
2481 print_advice(r, res == 1, opts);
2482 repo_rerere(r, opts->allow_rerere_auto);
2483 goto leave;
2486 drop_commit = 0;
2487 allow = allow_empty(r, opts, commit);
2488 if (allow < 0) {
2489 res = allow;
2490 goto leave;
2491 } else if (allow == 1) {
2492 flags |= ALLOW_EMPTY;
2493 } else if (allow == 2) {
2494 drop_commit = 1;
2495 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2496 NULL, REF_NO_DEREF);
2497 unlink(git_path_merge_msg(r));
2498 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2499 NULL, REF_NO_DEREF);
2500 fprintf(stderr,
2501 _("dropping %s %s -- patch contents already upstream\n"),
2502 oid_to_hex(&commit->object.oid), msg.subject);
2503 } /* else allow == 0 and there's nothing special to do */
2504 if (!opts->no_commit && !drop_commit) {
2505 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2506 res = do_commit(r, msg_file, author, opts, flags,
2507 commit? &commit->object.oid : NULL);
2508 else
2509 res = error(_("unable to parse commit author"));
2510 *check_todo = !!(flags & EDIT_MSG);
2511 if (!res && reword) {
2512 fast_forward_edit:
2513 res = run_git_commit(NULL, opts, EDIT_MSG |
2514 VERIFY_MSG | AMEND_MSG |
2515 (flags & ALLOW_EMPTY));
2516 *check_todo = 1;
2521 if (!res && final_fixup) {
2522 unlink(rebase_path_fixup_msg());
2523 unlink(rebase_path_squash_msg());
2524 unlink(rebase_path_current_fixups());
2525 strbuf_reset(&ctx->current_fixups);
2526 ctx->current_fixup_count = 0;
2529 leave:
2530 free_message(commit, &msg);
2531 free(author);
2532 update_abort_safety_file();
2534 return res;
2537 static int prepare_revs(struct replay_opts *opts)
2540 * picking (but not reverting) ranges (but not individual revisions)
2541 * should be done in reverse
2543 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2544 opts->revs->reverse ^= 1;
2546 if (prepare_revision_walk(opts->revs))
2547 return error(_("revision walk setup failed"));
2549 return 0;
2552 static int read_and_refresh_cache(struct repository *r,
2553 struct replay_opts *opts)
2555 struct lock_file index_lock = LOCK_INIT;
2556 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2557 if (repo_read_index(r) < 0) {
2558 rollback_lock_file(&index_lock);
2559 return error(_("git %s: failed to read the index"),
2560 action_name(opts));
2562 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2564 if (index_fd >= 0) {
2565 if (write_locked_index(r->index, &index_lock,
2566 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2567 return error(_("git %s: failed to refresh the index"),
2568 action_name(opts));
2573 * If we are resolving merges in any way other than "ort", then
2574 * expand the sparse index.
2576 if (opts->strategy && strcmp(opts->strategy, "ort"))
2577 ensure_full_index(r->index);
2578 return 0;
2581 void todo_list_release(struct todo_list *todo_list)
2583 strbuf_release(&todo_list->buf);
2584 FREE_AND_NULL(todo_list->items);
2585 todo_list->nr = todo_list->alloc = 0;
2588 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2590 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2591 return todo_list->items + todo_list->nr++;
2594 const char *todo_item_get_arg(struct todo_list *todo_list,
2595 struct todo_item *item)
2597 return todo_list->buf.buf + item->arg_offset;
2600 static int is_command(enum todo_command command, const char **bol)
2602 const char *str = todo_command_info[command].str;
2603 const char nick = todo_command_info[command].c;
2604 const char *p = *bol;
2606 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2607 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2608 (*bol = p);
2611 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2613 switch (command) {
2614 case TODO_LABEL:
2616 * '#' is not a valid label as the merge command uses it to
2617 * separate merge parents from the commit subject.
2619 if (!strcmp(arg, "#") ||
2620 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2621 return error(_("'%s' is not a valid label"), arg);
2622 break;
2624 case TODO_UPDATE_REF:
2625 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2626 return error(_("'%s' is not a valid refname"), arg);
2627 if (check_refname_format(arg, 0))
2628 return error(_("update-ref requires a fully qualified "
2629 "refname e.g. refs/heads/%s"), arg);
2630 break;
2632 default:
2633 BUG("unexpected todo_command");
2636 return 0;
2639 static int check_merge_commit_insn(enum todo_command command)
2641 switch(command) {
2642 case TODO_PICK:
2643 error(_("'%s' does not accept merge commits"),
2644 todo_command_info[command].str);
2645 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2647 * TRANSLATORS: 'pick' and 'merge -C' should not be
2648 * translated.
2650 "'pick' does not take a merge commit. If you wanted to\n"
2651 "replay the merge, use 'merge -C' on the commit."));
2652 return -1;
2654 case TODO_REWORD:
2655 error(_("'%s' does not accept merge commits"),
2656 todo_command_info[command].str);
2657 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2659 * TRANSLATORS: 'reword' and 'merge -c' should not be
2660 * translated.
2662 "'reword' does not take a merge commit. If you wanted to\n"
2663 "replay the merge and reword the commit message, use\n"
2664 "'merge -c' on the commit"));
2665 return -1;
2667 case TODO_EDIT:
2668 error(_("'%s' does not accept merge commits"),
2669 todo_command_info[command].str);
2670 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2672 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2673 * not be translated.
2675 "'edit' does not take a merge commit. If you wanted to\n"
2676 "replay the merge, use 'merge -C' on the commit, and then\n"
2677 "'break' to give the control back to you so that you can\n"
2678 "do 'git commit --amend && git rebase --continue'."));
2679 return -1;
2681 case TODO_FIXUP:
2682 case TODO_SQUASH:
2683 return error(_("cannot squash merge commit into another commit"));
2685 case TODO_MERGE:
2686 return 0;
2688 default:
2689 BUG("unexpected todo_command");
2693 static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2694 struct todo_item *item, const char *buf,
2695 const char *bol, char *eol)
2697 struct object_id commit_oid;
2698 char *end_of_object_name;
2699 int i, saved, status, padding;
2701 item->flags = 0;
2703 /* left-trim */
2704 bol += strspn(bol, " \t");
2706 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
2707 item->command = TODO_COMMENT;
2708 item->commit = NULL;
2709 item->arg_offset = bol - buf;
2710 item->arg_len = eol - bol;
2711 return 0;
2714 for (i = 0; i < TODO_COMMENT; i++)
2715 if (is_command(i, &bol)) {
2716 item->command = i;
2717 break;
2719 if (i >= TODO_COMMENT)
2720 return error(_("invalid command '%.*s'"),
2721 (int)strcspn(bol, " \t\r\n"), bol);
2723 /* Eat up extra spaces/ tabs before object name */
2724 padding = strspn(bol, " \t");
2725 bol += padding;
2727 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2728 if (bol != eol)
2729 return error(_("%s does not accept arguments: '%s'"),
2730 command_to_string(item->command), bol);
2731 item->commit = NULL;
2732 item->arg_offset = bol - buf;
2733 item->arg_len = eol - bol;
2734 return 0;
2737 if (!padding)
2738 return error(_("missing arguments for %s"),
2739 command_to_string(item->command));
2741 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2742 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2743 int ret = 0;
2745 item->commit = NULL;
2746 item->arg_offset = bol - buf;
2747 item->arg_len = (int)(eol - bol);
2748 if (item->command == TODO_LABEL ||
2749 item->command == TODO_UPDATE_REF) {
2750 saved = *eol;
2751 *eol = '\0';
2752 ret = check_label_or_ref_arg(item->command, bol);
2753 *eol = saved;
2755 return ret;
2758 if (item->command == TODO_FIXUP) {
2759 if (skip_prefix(bol, "-C", &bol)) {
2760 bol += strspn(bol, " \t");
2761 item->flags |= TODO_REPLACE_FIXUP_MSG;
2762 } else if (skip_prefix(bol, "-c", &bol)) {
2763 bol += strspn(bol, " \t");
2764 item->flags |= TODO_EDIT_FIXUP_MSG;
2768 if (item->command == TODO_MERGE) {
2769 if (skip_prefix(bol, "-C", &bol))
2770 bol += strspn(bol, " \t");
2771 else if (skip_prefix(bol, "-c", &bol)) {
2772 bol += strspn(bol, " \t");
2773 item->flags |= TODO_EDIT_MERGE_MSG;
2774 } else {
2775 item->flags |= TODO_EDIT_MERGE_MSG;
2776 item->commit = NULL;
2777 item->arg_offset = bol - buf;
2778 item->arg_len = (int)(eol - bol);
2779 return 0;
2783 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2784 saved = *end_of_object_name;
2785 *end_of_object_name = '\0';
2786 status = repo_get_oid(r, bol, &commit_oid);
2787 if (status < 0)
2788 error(_("could not parse '%s'"), bol); /* return later */
2789 *end_of_object_name = saved;
2791 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2792 item->arg_offset = bol - buf;
2793 item->arg_len = (int)(eol - bol);
2795 if (status < 0)
2796 return status;
2798 item->commit = lookup_commit_reference(r, &commit_oid);
2799 if (!item->commit)
2800 return -1;
2801 if (is_rebase_i(opts) &&
2802 item->commit->parents && item->commit->parents->next)
2803 return check_merge_commit_insn(item->command);
2804 return 0;
2807 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2809 const char *todo_file, *bol;
2810 struct strbuf buf = STRBUF_INIT;
2811 int ret = 0;
2813 todo_file = git_path_todo_file();
2814 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2815 if (errno == ENOENT || errno == ENOTDIR)
2816 return -1;
2817 else
2818 return error_errno("unable to open '%s'", todo_file);
2820 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2821 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2822 *action = REPLAY_PICK;
2823 else if (is_command(TODO_REVERT, &bol) &&
2824 (*bol == ' ' || *bol == '\t'))
2825 *action = REPLAY_REVERT;
2826 else
2827 ret = -1;
2829 strbuf_release(&buf);
2831 return ret;
2834 int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2835 char *buf, struct todo_list *todo_list)
2837 struct todo_item *item;
2838 char *p = buf, *next_p;
2839 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2841 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2843 for (i = 1; *p; i++, p = next_p) {
2844 char *eol = strchrnul(p, '\n');
2846 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2848 if (p != eol && eol[-1] == '\r')
2849 eol--; /* strip Carriage Return */
2851 item = append_new_todo(todo_list);
2852 item->offset_in_buf = p - todo_list->buf.buf;
2853 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2854 res = error(_("invalid line %d: %.*s"),
2855 i, (int)(eol - p), p);
2856 item->command = TODO_COMMENT + 1;
2857 item->arg_offset = p - buf;
2858 item->arg_len = (int)(eol - p);
2859 item->commit = NULL;
2862 if (item->command != TODO_COMMENT)
2863 todo_list->total_nr++;
2865 if (fixup_okay)
2866 ; /* do nothing */
2867 else if (is_fixup(item->command))
2868 res = error(_("cannot '%s' without a previous commit"),
2869 command_to_string(item->command));
2870 else if (!is_noop(item->command))
2871 fixup_okay = 1;
2874 return res;
2877 static int count_commands(struct todo_list *todo_list)
2879 int count = 0, i;
2881 for (i = 0; i < todo_list->nr; i++)
2882 if (todo_list->items[i].command != TODO_COMMENT)
2883 count++;
2885 return count;
2888 static int get_item_line_offset(struct todo_list *todo_list, int index)
2890 return index < todo_list->nr ?
2891 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2894 static const char *get_item_line(struct todo_list *todo_list, int index)
2896 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2899 static int get_item_line_length(struct todo_list *todo_list, int index)
2901 return get_item_line_offset(todo_list, index + 1)
2902 - get_item_line_offset(todo_list, index);
2905 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2907 int fd;
2908 ssize_t len;
2910 fd = open(path, O_RDONLY);
2911 if (fd < 0)
2912 return error_errno(_("could not open '%s'"), path);
2913 len = strbuf_read(sb, fd, 0);
2914 close(fd);
2915 if (len < 0)
2916 return error(_("could not read '%s'."), path);
2917 return len;
2920 static int have_finished_the_last_pick(void)
2922 struct strbuf buf = STRBUF_INIT;
2923 const char *eol;
2924 const char *todo_path = git_path_todo_file();
2925 int ret = 0;
2927 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2928 if (errno == ENOENT) {
2929 return 0;
2930 } else {
2931 error_errno("unable to open '%s'", todo_path);
2932 return 0;
2935 /* If there is only one line then we are done */
2936 eol = strchr(buf.buf, '\n');
2937 if (!eol || !eol[1])
2938 ret = 1;
2940 strbuf_release(&buf);
2942 return ret;
2945 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2947 struct replay_opts opts = REPLAY_OPTS_INIT;
2948 int need_cleanup = 0;
2950 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2951 if (!refs_delete_ref(get_main_ref_store(r), "",
2952 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2953 verbose)
2954 warning(_("cancelling a cherry picking in progress"));
2955 opts.action = REPLAY_PICK;
2956 need_cleanup = 1;
2959 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2960 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2961 NULL, REF_NO_DEREF) &&
2962 verbose)
2963 warning(_("cancelling a revert in progress"));
2964 opts.action = REPLAY_REVERT;
2965 need_cleanup = 1;
2968 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2969 NULL, REF_NO_DEREF);
2971 if (!need_cleanup)
2972 goto out;
2974 if (!have_finished_the_last_pick())
2975 goto out;
2977 sequencer_remove_state(&opts);
2978 out:
2979 replay_opts_release(&opts);
2982 static void todo_list_write_total_nr(struct todo_list *todo_list)
2984 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2986 if (f) {
2987 fprintf(f, "%d\n", todo_list->total_nr);
2988 fclose(f);
2992 static int read_populate_todo(struct repository *r,
2993 struct todo_list *todo_list,
2994 struct replay_opts *opts)
2996 const char *todo_file = get_todo_path(opts);
2997 int res;
2999 strbuf_reset(&todo_list->buf);
3000 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
3001 return -1;
3003 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
3004 if (res) {
3005 if (is_rebase_i(opts))
3006 return error(_("please fix this using "
3007 "'git rebase --edit-todo'."));
3008 return error(_("unusable instruction sheet: '%s'"), todo_file);
3011 if (!todo_list->nr &&
3012 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3013 return error(_("no commits parsed."));
3015 if (!is_rebase_i(opts)) {
3016 enum todo_command valid =
3017 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3018 int i;
3020 for (i = 0; i < todo_list->nr; i++)
3021 if (valid == todo_list->items[i].command)
3022 continue;
3023 else if (valid == TODO_PICK)
3024 return error(_("cannot cherry-pick during a revert."));
3025 else
3026 return error(_("cannot revert during a cherry-pick."));
3029 if (is_rebase_i(opts)) {
3030 struct todo_list done = TODO_LIST_INIT;
3032 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3033 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3034 todo_list->done_nr = count_commands(&done);
3035 else
3036 todo_list->done_nr = 0;
3038 todo_list->total_nr = todo_list->done_nr
3039 + count_commands(todo_list);
3040 todo_list_release(&done);
3042 todo_list_write_total_nr(todo_list);
3045 return 0;
3048 static int git_config_string_dup(char **dest,
3049 const char *var, const char *value)
3051 if (!value)
3052 return config_error_nonbool(var);
3053 free(*dest);
3054 *dest = xstrdup(value);
3055 return 0;
3058 static int populate_opts_cb(const char *key, const char *value,
3059 const struct config_context *ctx,
3060 void *data)
3062 struct replay_opts *opts = data;
3063 int error_flag = 1;
3065 if (!value)
3066 error_flag = 0;
3067 else if (!strcmp(key, "options.no-commit"))
3068 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3069 else if (!strcmp(key, "options.edit"))
3070 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3071 else if (!strcmp(key, "options.allow-empty"))
3072 opts->allow_empty =
3073 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3074 else if (!strcmp(key, "options.allow-empty-message"))
3075 opts->allow_empty_message =
3076 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3077 else if (!strcmp(key, "options.drop-redundant-commits"))
3078 opts->drop_redundant_commits =
3079 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3080 else if (!strcmp(key, "options.keep-redundant-commits"))
3081 opts->keep_redundant_commits =
3082 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3083 else if (!strcmp(key, "options.signoff"))
3084 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3085 else if (!strcmp(key, "options.record-origin"))
3086 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3087 else if (!strcmp(key, "options.allow-ff"))
3088 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3089 else if (!strcmp(key, "options.mainline"))
3090 opts->mainline = git_config_int(key, value, ctx->kvi);
3091 else if (!strcmp(key, "options.strategy"))
3092 git_config_string_dup(&opts->strategy, key, value);
3093 else if (!strcmp(key, "options.gpg-sign"))
3094 git_config_string_dup(&opts->gpg_sign, key, value);
3095 else if (!strcmp(key, "options.strategy-option")) {
3096 strvec_push(&opts->xopts, value);
3097 } else if (!strcmp(key, "options.allow-rerere-auto"))
3098 opts->allow_rerere_auto =
3099 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3100 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3101 else if (!strcmp(key, "options.default-msg-cleanup")) {
3102 opts->explicit_cleanup = 1;
3103 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3104 } else
3105 return error(_("invalid key: %s"), key);
3107 if (!error_flag)
3108 return error(_("invalid value for '%s': '%s'"), key, value);
3110 return 0;
3113 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3115 int i;
3116 int count;
3117 const char **argv;
3118 char *strategy_opts_string = raw_opts;
3120 if (*strategy_opts_string == ' ')
3121 strategy_opts_string++;
3123 count = split_cmdline(strategy_opts_string, &argv);
3124 if (count < 0)
3125 BUG("could not split '%s': %s", strategy_opts_string,
3126 split_cmdline_strerror(count));
3127 for (i = 0; i < count; i++) {
3128 const char *arg = argv[i];
3130 skip_prefix(arg, "--", &arg);
3131 strvec_push(&opts->xopts, arg);
3133 free(argv);
3136 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3138 strbuf_reset(buf);
3139 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3140 return;
3141 opts->strategy = strbuf_detach(buf, NULL);
3142 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3143 return;
3145 parse_strategy_opts(opts, buf->buf);
3148 static int read_populate_opts(struct replay_opts *opts)
3150 struct replay_ctx *ctx = opts->ctx;
3152 if (is_rebase_i(opts)) {
3153 struct strbuf buf = STRBUF_INIT;
3154 int ret = 0;
3156 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3157 READ_ONELINER_SKIP_IF_EMPTY)) {
3158 if (!starts_with(buf.buf, "-S"))
3159 strbuf_reset(&buf);
3160 else {
3161 free(opts->gpg_sign);
3162 opts->gpg_sign = xstrdup(buf.buf + 2);
3164 strbuf_reset(&buf);
3167 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3168 READ_ONELINER_SKIP_IF_EMPTY)) {
3169 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3170 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3171 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3172 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3173 strbuf_reset(&buf);
3176 if (file_exists(rebase_path_verbose()))
3177 opts->verbose = 1;
3179 if (file_exists(rebase_path_quiet()))
3180 opts->quiet = 1;
3182 if (file_exists(rebase_path_signoff())) {
3183 opts->allow_ff = 0;
3184 opts->signoff = 1;
3187 if (file_exists(rebase_path_cdate_is_adate())) {
3188 opts->allow_ff = 0;
3189 opts->committer_date_is_author_date = 1;
3192 if (file_exists(rebase_path_ignore_date())) {
3193 opts->allow_ff = 0;
3194 opts->ignore_date = 1;
3197 if (file_exists(rebase_path_reschedule_failed_exec()))
3198 opts->reschedule_failed_exec = 1;
3199 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3200 opts->reschedule_failed_exec = 0;
3202 if (file_exists(rebase_path_drop_redundant_commits()))
3203 opts->drop_redundant_commits = 1;
3205 if (file_exists(rebase_path_keep_redundant_commits()))
3206 opts->keep_redundant_commits = 1;
3208 read_strategy_opts(opts, &buf);
3209 strbuf_reset(&buf);
3211 if (read_oneliner(&ctx->current_fixups,
3212 rebase_path_current_fixups(),
3213 READ_ONELINER_SKIP_IF_EMPTY)) {
3214 const char *p = ctx->current_fixups.buf;
3215 ctx->current_fixup_count = 1;
3216 while ((p = strchr(p, '\n'))) {
3217 ctx->current_fixup_count++;
3218 p++;
3222 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3223 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3224 ret = error(_("unusable squash-onto"));
3225 goto done_rebase_i;
3227 opts->have_squash_onto = 1;
3230 done_rebase_i:
3231 strbuf_release(&buf);
3232 return ret;
3235 if (!file_exists(git_path_opts_file()))
3236 return 0;
3238 * The function git_parse_source(), called from git_config_from_file(),
3239 * may die() in case of a syntactically incorrect file. We do not care
3240 * about this case, though, because we wrote that file ourselves, so we
3241 * are pretty certain that it is syntactically correct.
3243 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3244 return error(_("malformed options sheet: '%s'"),
3245 git_path_opts_file());
3246 return 0;
3249 static void write_strategy_opts(struct replay_opts *opts)
3251 struct strbuf buf = STRBUF_INIT;
3254 * Quote strategy options so that they can be read correctly
3255 * by split_cmdline().
3257 quote_cmdline(&buf, opts->xopts.v);
3258 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3259 strbuf_release(&buf);
3262 int write_basic_state(struct replay_opts *opts, const char *head_name,
3263 struct commit *onto, const struct object_id *orig_head)
3265 if (head_name)
3266 write_file(rebase_path_head_name(), "%s\n", head_name);
3267 if (onto)
3268 write_file(rebase_path_onto(), "%s\n",
3269 oid_to_hex(&onto->object.oid));
3270 if (orig_head)
3271 write_file(rebase_path_orig_head(), "%s\n",
3272 oid_to_hex(orig_head));
3274 if (opts->quiet)
3275 write_file(rebase_path_quiet(), "%s", "");
3276 if (opts->verbose)
3277 write_file(rebase_path_verbose(), "%s", "");
3278 if (opts->strategy)
3279 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3280 if (opts->xopts.nr > 0)
3281 write_strategy_opts(opts);
3283 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3284 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3285 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3286 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3288 if (opts->gpg_sign)
3289 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3290 if (opts->signoff)
3291 write_file(rebase_path_signoff(), "--signoff\n");
3292 if (opts->drop_redundant_commits)
3293 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3294 if (opts->keep_redundant_commits)
3295 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3296 if (opts->committer_date_is_author_date)
3297 write_file(rebase_path_cdate_is_adate(), "%s", "");
3298 if (opts->ignore_date)
3299 write_file(rebase_path_ignore_date(), "%s", "");
3300 if (opts->reschedule_failed_exec)
3301 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3302 else
3303 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3305 return 0;
3308 static int walk_revs_populate_todo(struct todo_list *todo_list,
3309 struct replay_opts *opts)
3311 enum todo_command command = opts->action == REPLAY_PICK ?
3312 TODO_PICK : TODO_REVERT;
3313 const char *command_string = todo_command_info[command].str;
3314 const char *encoding;
3315 struct commit *commit;
3317 if (prepare_revs(opts))
3318 return -1;
3320 encoding = get_log_output_encoding();
3322 while ((commit = get_revision(opts->revs))) {
3323 struct todo_item *item = append_new_todo(todo_list);
3324 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3325 commit, NULL,
3326 encoding);
3327 const char *subject;
3328 int subject_len;
3330 item->command = command;
3331 item->commit = commit;
3332 item->arg_offset = 0;
3333 item->arg_len = 0;
3334 item->offset_in_buf = todo_list->buf.len;
3335 subject_len = find_commit_subject(commit_buffer, &subject);
3336 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3337 short_commit_name(the_repository, commit),
3338 subject_len, subject);
3339 repo_unuse_commit_buffer(the_repository, commit,
3340 commit_buffer);
3343 if (!todo_list->nr)
3344 return error(_("empty commit set passed"));
3346 return 0;
3349 static int create_seq_dir(struct repository *r)
3351 enum replay_action action;
3352 const char *in_progress_error = NULL;
3353 const char *in_progress_advice = NULL;
3354 unsigned int advise_skip =
3355 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3356 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3358 if (!sequencer_get_last_command(r, &action)) {
3359 switch (action) {
3360 case REPLAY_REVERT:
3361 in_progress_error = _("revert is already in progress");
3362 in_progress_advice =
3363 _("try \"git revert (--continue | %s--abort | --quit)\"");
3364 break;
3365 case REPLAY_PICK:
3366 in_progress_error = _("cherry-pick is already in progress");
3367 in_progress_advice =
3368 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3369 break;
3370 default:
3371 BUG("unexpected action in create_seq_dir");
3374 if (in_progress_error) {
3375 error("%s", in_progress_error);
3376 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3377 advise(in_progress_advice,
3378 advise_skip ? "--skip | " : "");
3379 return -1;
3381 if (mkdir(git_path_seq_dir(), 0777) < 0)
3382 return error_errno(_("could not create sequencer directory '%s'"),
3383 git_path_seq_dir());
3385 return 0;
3388 static int save_head(const char *head)
3390 return write_message(head, strlen(head), git_path_head_file(), 1);
3393 static int rollback_is_safe(void)
3395 struct strbuf sb = STRBUF_INIT;
3396 struct object_id expected_head, actual_head;
3398 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3399 strbuf_trim(&sb);
3400 if (get_oid_hex(sb.buf, &expected_head)) {
3401 strbuf_release(&sb);
3402 die(_("could not parse %s"), git_path_abort_safety_file());
3404 strbuf_release(&sb);
3406 else if (errno == ENOENT)
3407 oidclr(&expected_head, the_repository->hash_algo);
3408 else
3409 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3411 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3412 oidclr(&actual_head, the_repository->hash_algo);
3414 return oideq(&actual_head, &expected_head);
3417 static int reset_merge(const struct object_id *oid)
3419 struct child_process cmd = CHILD_PROCESS_INIT;
3421 cmd.git_cmd = 1;
3422 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3424 if (!is_null_oid(oid))
3425 strvec_push(&cmd.args, oid_to_hex(oid));
3427 return run_command(&cmd);
3430 static int rollback_single_pick(struct repository *r)
3432 struct object_id head_oid;
3434 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3435 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3436 return error(_("no cherry-pick or revert in progress"));
3437 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3438 return error(_("cannot resolve HEAD"));
3439 if (is_null_oid(&head_oid))
3440 return error(_("cannot abort from a branch yet to be born"));
3441 return reset_merge(&head_oid);
3444 static int skip_single_pick(void)
3446 struct object_id head;
3448 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3449 return error(_("cannot resolve HEAD"));
3450 return reset_merge(&head);
3453 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3455 FILE *f;
3456 struct object_id oid;
3457 struct strbuf buf = STRBUF_INIT;
3458 const char *p;
3460 f = fopen(git_path_head_file(), "r");
3461 if (!f && errno == ENOENT) {
3463 * There is no multiple-cherry-pick in progress.
3464 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3465 * a single-cherry-pick in progress, abort that.
3467 return rollback_single_pick(r);
3469 if (!f)
3470 return error_errno(_("cannot open '%s'"), git_path_head_file());
3471 if (strbuf_getline_lf(&buf, f)) {
3472 error(_("cannot read '%s': %s"), git_path_head_file(),
3473 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3474 fclose(f);
3475 goto fail;
3477 fclose(f);
3478 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3479 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3480 git_path_head_file());
3481 goto fail;
3483 if (is_null_oid(&oid)) {
3484 error(_("cannot abort from a branch yet to be born"));
3485 goto fail;
3488 if (!rollback_is_safe()) {
3489 /* Do not error, just do not rollback */
3490 warning(_("You seem to have moved HEAD. "
3491 "Not rewinding, check your HEAD!"));
3492 } else
3493 if (reset_merge(&oid))
3494 goto fail;
3495 strbuf_release(&buf);
3496 return sequencer_remove_state(opts);
3497 fail:
3498 strbuf_release(&buf);
3499 return -1;
3502 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3504 enum replay_action action = -1;
3505 sequencer_get_last_command(r, &action);
3508 * Check whether the subcommand requested to skip the commit is actually
3509 * in progress and that it's safe to skip the commit.
3511 * opts->action tells us which subcommand requested to skip the commit.
3512 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3513 * action is in progress and we can skip the commit.
3515 * Otherwise we check that the last instruction was related to the
3516 * particular subcommand we're trying to execute and barf if that's not
3517 * the case.
3519 * Finally we check that the rollback is "safe", i.e., has the HEAD
3520 * moved? In this case, it doesn't make sense to "reset the merge" and
3521 * "skip the commit" as the user already handled this by committing. But
3522 * we'd not want to barf here, instead give advice on how to proceed. We
3523 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3524 * it gets removed when the user commits, so if it still exists we're
3525 * sure the user can't have committed before.
3527 switch (opts->action) {
3528 case REPLAY_REVERT:
3529 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3530 if (action != REPLAY_REVERT)
3531 return error(_("no revert in progress"));
3532 if (!rollback_is_safe())
3533 goto give_advice;
3535 break;
3536 case REPLAY_PICK:
3537 if (!refs_ref_exists(get_main_ref_store(r),
3538 "CHERRY_PICK_HEAD")) {
3539 if (action != REPLAY_PICK)
3540 return error(_("no cherry-pick in progress"));
3541 if (!rollback_is_safe())
3542 goto give_advice;
3544 break;
3545 default:
3546 BUG("unexpected action in sequencer_skip");
3549 if (skip_single_pick())
3550 return error(_("failed to skip the commit"));
3551 if (!is_directory(git_path_seq_dir()))
3552 return 0;
3554 return sequencer_continue(r, opts);
3556 give_advice:
3557 error(_("there is nothing to skip"));
3559 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3560 advise(_("have you committed already?\n"
3561 "try \"git %s --continue\""),
3562 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3564 return -1;
3567 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3568 int reschedule)
3570 struct lock_file todo_lock = LOCK_INIT;
3571 const char *todo_path = get_todo_path(opts);
3572 int next = todo_list->current, offset, fd;
3575 * rebase -i writes "git-rebase-todo" without the currently executing
3576 * command, appending it to "done" instead.
3578 if (is_rebase_i(opts) && !reschedule)
3579 next++;
3581 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3582 if (fd < 0)
3583 return error_errno(_("could not lock '%s'"), todo_path);
3584 offset = get_item_line_offset(todo_list, next);
3585 if (write_in_full(fd, todo_list->buf.buf + offset,
3586 todo_list->buf.len - offset) < 0)
3587 return error_errno(_("could not write to '%s'"), todo_path);
3588 if (commit_lock_file(&todo_lock) < 0)
3589 return error(_("failed to finalize '%s'"), todo_path);
3591 if (is_rebase_i(opts) && !reschedule && next > 0) {
3592 const char *done = rebase_path_done();
3593 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3594 int ret = 0;
3596 if (fd < 0)
3597 return 0;
3598 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3599 get_item_line_length(todo_list, next - 1))
3600 < 0)
3601 ret = error_errno(_("could not write to '%s'"), done);
3602 if (close(fd) < 0)
3603 ret = error_errno(_("failed to finalize '%s'"), done);
3604 return ret;
3606 return 0;
3609 static int save_opts(struct replay_opts *opts)
3611 const char *opts_file = git_path_opts_file();
3612 int res = 0;
3614 if (opts->no_commit)
3615 res |= git_config_set_in_file_gently(opts_file,
3616 "options.no-commit", NULL, "true");
3617 if (opts->edit >= 0)
3618 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
3619 opts->edit ? "true" : "false");
3620 if (opts->allow_empty)
3621 res |= git_config_set_in_file_gently(opts_file,
3622 "options.allow-empty", NULL, "true");
3623 if (opts->allow_empty_message)
3624 res |= git_config_set_in_file_gently(opts_file,
3625 "options.allow-empty-message", NULL, "true");
3626 if (opts->drop_redundant_commits)
3627 res |= git_config_set_in_file_gently(opts_file,
3628 "options.drop-redundant-commits", NULL, "true");
3629 if (opts->keep_redundant_commits)
3630 res |= git_config_set_in_file_gently(opts_file,
3631 "options.keep-redundant-commits", NULL, "true");
3632 if (opts->signoff)
3633 res |= git_config_set_in_file_gently(opts_file,
3634 "options.signoff", NULL, "true");
3635 if (opts->record_origin)
3636 res |= git_config_set_in_file_gently(opts_file,
3637 "options.record-origin", NULL, "true");
3638 if (opts->allow_ff)
3639 res |= git_config_set_in_file_gently(opts_file,
3640 "options.allow-ff", NULL, "true");
3641 if (opts->mainline) {
3642 struct strbuf buf = STRBUF_INIT;
3643 strbuf_addf(&buf, "%d", opts->mainline);
3644 res |= git_config_set_in_file_gently(opts_file,
3645 "options.mainline", NULL, buf.buf);
3646 strbuf_release(&buf);
3648 if (opts->strategy)
3649 res |= git_config_set_in_file_gently(opts_file,
3650 "options.strategy", NULL, opts->strategy);
3651 if (opts->gpg_sign)
3652 res |= git_config_set_in_file_gently(opts_file,
3653 "options.gpg-sign", NULL, opts->gpg_sign);
3654 for (size_t i = 0; i < opts->xopts.nr; i++)
3655 res |= git_config_set_multivar_in_file_gently(opts_file,
3656 "options.strategy-option",
3657 opts->xopts.v[i], "^$", NULL, 0);
3658 if (opts->allow_rerere_auto)
3659 res |= git_config_set_in_file_gently(opts_file,
3660 "options.allow-rerere-auto", NULL,
3661 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3662 "true" : "false");
3664 if (opts->explicit_cleanup)
3665 res |= git_config_set_in_file_gently(opts_file,
3666 "options.default-msg-cleanup", NULL,
3667 describe_cleanup_mode(opts->default_msg_cleanup));
3668 return res;
3671 static int make_patch(struct repository *r,
3672 struct commit *commit,
3673 struct replay_opts *opts)
3675 struct rev_info log_tree_opt;
3676 const char *subject;
3677 char hex[GIT_MAX_HEXSZ + 1];
3678 int res = 0;
3680 if (!is_rebase_i(opts))
3681 BUG("make_patch should only be called when rebasing");
3683 oid_to_hex_r(hex, &commit->object.oid);
3684 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3685 return -1;
3686 res |= write_rebase_head(&commit->object.oid);
3688 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3689 repo_init_revisions(r, &log_tree_opt, NULL);
3690 log_tree_opt.abbrev = 0;
3691 log_tree_opt.diff = 1;
3692 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3693 log_tree_opt.disable_stdin = 1;
3694 log_tree_opt.no_commit_id = 1;
3695 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3696 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3697 if (!log_tree_opt.diffopt.file)
3698 res |= error_errno(_("could not open '%s'"),
3699 rebase_path_patch());
3700 else {
3701 res |= log_tree_commit(&log_tree_opt, commit);
3702 fclose(log_tree_opt.diffopt.file);
3705 if (!file_exists(rebase_path_message())) {
3706 const char *encoding = get_commit_output_encoding();
3707 const char *commit_buffer = repo_logmsg_reencode(r,
3708 commit, NULL,
3709 encoding);
3710 find_commit_subject(commit_buffer, &subject);
3711 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3712 repo_unuse_commit_buffer(r, commit,
3713 commit_buffer);
3715 release_revisions(&log_tree_opt);
3717 return res;
3720 static int intend_to_amend(void)
3722 struct object_id head;
3723 char *p;
3725 if (repo_get_oid(the_repository, "HEAD", &head))
3726 return error(_("cannot read HEAD"));
3728 p = oid_to_hex(&head);
3729 return write_message(p, strlen(p), rebase_path_amend(), 1);
3732 static int error_with_patch(struct repository *r,
3733 struct commit *commit,
3734 const char *subject, int subject_len,
3735 struct replay_opts *opts,
3736 int exit_code, int to_amend)
3738 struct replay_ctx *ctx = opts->ctx;
3741 * Write the commit message to be used by "git rebase
3742 * --continue". If a "fixup" or "squash" command has conflicts
3743 * then we will have already written rebase_path_message() in
3744 * error_failed_squash(). If an "edit" command was
3745 * fast-forwarded then we don't have a message in ctx->message
3746 * and rely on make_patch() to write rebase_path_message()
3747 * instead.
3749 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3750 write_message(ctx->message.buf, ctx->message.len,
3751 rebase_path_message(), 0))
3752 return error(_("could not write commit message file"));
3754 if (commit && make_patch(r, commit, opts))
3755 return -1;
3757 if (to_amend) {
3758 if (intend_to_amend())
3759 return -1;
3761 fprintf(stderr,
3762 _("You can amend the commit now, with\n"
3763 "\n"
3764 " git commit --amend %s\n"
3765 "\n"
3766 "Once you are satisfied with your changes, run\n"
3767 "\n"
3768 " git rebase --continue\n"),
3769 gpg_sign_opt_quoted(opts));
3770 } else if (exit_code) {
3771 if (commit)
3772 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3773 short_commit_name(r, commit), subject_len, subject);
3774 else
3776 * We don't have the hash of the parent so
3777 * just print the line from the todo file.
3779 fprintf_ln(stderr, _("Could not merge %.*s"),
3780 subject_len, subject);
3783 return exit_code;
3786 static int error_failed_squash(struct repository *r,
3787 struct commit *commit,
3788 struct replay_opts *opts,
3789 int subject_len,
3790 const char *subject)
3792 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3793 return error(_("could not copy '%s' to '%s'"),
3794 rebase_path_squash_msg(), rebase_path_message());
3795 unlink(git_path_merge_msg(r));
3796 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3797 return error(_("could not copy '%s' to '%s'"),
3798 rebase_path_message(),
3799 git_path_merge_msg(r));
3800 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3803 static int do_exec(struct repository *r, const char *command_line, int quiet)
3805 struct child_process cmd = CHILD_PROCESS_INIT;
3806 int dirty, status;
3808 if (!quiet)
3809 fprintf(stderr, _("Executing: %s\n"), command_line);
3810 cmd.use_shell = 1;
3811 strvec_push(&cmd.args, command_line);
3812 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3813 status = run_command(&cmd);
3815 /* force re-reading of the cache */
3816 discard_index(r->index);
3817 if (repo_read_index(r) < 0)
3818 return error(_("could not read index"));
3820 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3822 if (status) {
3823 warning(_("execution failed: %s\n%s"
3824 "You can fix the problem, and then run\n"
3825 "\n"
3826 " git rebase --continue\n"
3827 "\n"),
3828 command_line,
3829 dirty ? _("and made changes to the index and/or the "
3830 "working tree.\n") : "");
3831 if (status == 127)
3832 /* command not found */
3833 status = 1;
3834 } else if (dirty) {
3835 warning(_("execution succeeded: %s\nbut "
3836 "left changes to the index and/or the working tree.\n"
3837 "Commit or stash your changes, and then run\n"
3838 "\n"
3839 " git rebase --continue\n"
3840 "\n"), command_line);
3841 status = 1;
3844 return status;
3847 __attribute__((format (printf, 2, 3)))
3848 static int safe_append(const char *filename, const char *fmt, ...)
3850 va_list ap;
3851 struct lock_file lock = LOCK_INIT;
3852 int fd = hold_lock_file_for_update(&lock, filename,
3853 LOCK_REPORT_ON_ERROR);
3854 struct strbuf buf = STRBUF_INIT;
3856 if (fd < 0)
3857 return -1;
3859 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3860 error_errno(_("could not read '%s'"), filename);
3861 rollback_lock_file(&lock);
3862 return -1;
3864 strbuf_complete(&buf, '\n');
3865 va_start(ap, fmt);
3866 strbuf_vaddf(&buf, fmt, ap);
3867 va_end(ap);
3869 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3870 error_errno(_("could not write to '%s'"), filename);
3871 strbuf_release(&buf);
3872 rollback_lock_file(&lock);
3873 return -1;
3875 if (commit_lock_file(&lock) < 0) {
3876 strbuf_release(&buf);
3877 return error(_("failed to finalize '%s'"), filename);
3880 strbuf_release(&buf);
3881 return 0;
3884 static int do_label(struct repository *r, const char *name, int len)
3886 struct ref_store *refs = get_main_ref_store(r);
3887 struct ref_transaction *transaction;
3888 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3889 struct strbuf msg = STRBUF_INIT;
3890 int ret = 0;
3891 struct object_id head_oid;
3893 if (len == 1 && *name == '#')
3894 return error(_("illegal label name: '%.*s'"), len, name);
3896 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3897 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3899 transaction = ref_store_transaction_begin(refs, 0, &err);
3900 if (!transaction) {
3901 error("%s", err.buf);
3902 ret = -1;
3903 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3904 error(_("could not read HEAD"));
3905 ret = -1;
3906 } else if (ref_transaction_update(transaction, ref_name.buf,
3907 &head_oid, NULL, NULL, NULL,
3908 0, msg.buf, &err) < 0 ||
3909 ref_transaction_commit(transaction, &err)) {
3910 error("%s", err.buf);
3911 ret = -1;
3913 ref_transaction_free(transaction);
3914 strbuf_release(&err);
3915 strbuf_release(&msg);
3917 if (!ret)
3918 ret = safe_append(rebase_path_refs_to_delete(),
3919 "%s\n", ref_name.buf);
3920 strbuf_release(&ref_name);
3922 return ret;
3925 static const char *sequencer_reflog_action(struct replay_opts *opts)
3927 if (!opts->reflog_action) {
3928 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3929 opts->reflog_action =
3930 xstrdup(opts->reflog_action ? opts->reflog_action
3931 : action_name(opts));
3934 return opts->reflog_action;
3937 __attribute__((format (printf, 3, 4)))
3938 static const char *reflog_message(struct replay_opts *opts,
3939 const char *sub_action, const char *fmt, ...)
3941 va_list ap;
3942 static struct strbuf buf = STRBUF_INIT;
3944 va_start(ap, fmt);
3945 strbuf_reset(&buf);
3946 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3947 if (sub_action)
3948 strbuf_addf(&buf, " (%s)", sub_action);
3949 if (fmt) {
3950 strbuf_addstr(&buf, ": ");
3951 strbuf_vaddf(&buf, fmt, ap);
3953 va_end(ap);
3955 return buf.buf;
3958 static struct commit *lookup_label(struct repository *r, const char *label,
3959 int len, struct strbuf *buf)
3961 struct commit *commit;
3962 struct object_id oid;
3964 strbuf_reset(buf);
3965 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3966 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
3967 commit = lookup_commit_object(r, &oid);
3968 } else {
3969 /* fall back to non-rewritten ref or commit */
3970 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3971 commit = lookup_commit_reference_by_name(buf->buf);
3974 if (!commit)
3975 error(_("could not resolve '%s'"), buf->buf);
3977 return commit;
3980 static int do_reset(struct repository *r,
3981 const char *name, int len,
3982 struct replay_opts *opts)
3984 struct strbuf ref_name = STRBUF_INIT;
3985 struct object_id oid;
3986 struct lock_file lock = LOCK_INIT;
3987 struct tree_desc desc = { 0 };
3988 struct tree *tree;
3989 struct unpack_trees_options unpack_tree_opts = { 0 };
3990 int ret = 0;
3992 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3993 return -1;
3995 if (len == 10 && !strncmp("[new root]", name, len)) {
3996 if (!opts->have_squash_onto) {
3997 const char *hex;
3998 if (commit_tree("", 0, the_hash_algo->empty_tree,
3999 NULL, &opts->squash_onto,
4000 NULL, NULL))
4001 return error(_("writing fake root commit"));
4002 opts->have_squash_onto = 1;
4003 hex = oid_to_hex(&opts->squash_onto);
4004 if (write_message(hex, strlen(hex),
4005 rebase_path_squash_onto(), 0))
4006 return error(_("writing squash-onto"));
4008 oidcpy(&oid, &opts->squash_onto);
4009 } else {
4010 int i;
4011 struct commit *commit;
4013 /* Determine the length of the label */
4014 for (i = 0; i < len; i++)
4015 if (isspace(name[i]))
4016 break;
4017 len = i;
4019 commit = lookup_label(r, name, len, &ref_name);
4020 if (!commit) {
4021 ret = -1;
4022 goto cleanup;
4024 oid = commit->object.oid;
4027 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4028 unpack_tree_opts.head_idx = 1;
4029 unpack_tree_opts.src_index = r->index;
4030 unpack_tree_opts.dst_index = r->index;
4031 unpack_tree_opts.fn = oneway_merge;
4032 unpack_tree_opts.merge = 1;
4033 unpack_tree_opts.update = 1;
4034 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4035 unpack_tree_opts.skip_cache_tree_update = 1;
4036 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4038 if (repo_read_index_unmerged(r)) {
4039 ret = error_resolve_conflict(action_name(opts));
4040 goto cleanup;
4043 if (!fill_tree_descriptor(r, &desc, &oid)) {
4044 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4045 goto cleanup;
4048 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4049 ret = -1;
4050 goto cleanup;
4053 tree = parse_tree_indirect(&oid);
4054 if (!tree)
4055 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4056 prime_cache_tree(r, r->index, tree);
4058 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4059 ret = error(_("could not write index"));
4061 if (!ret)
4062 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4063 len, name),
4064 "HEAD", &oid,
4065 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4066 cleanup:
4067 free((void *)desc.buffer);
4068 if (ret < 0)
4069 rollback_lock_file(&lock);
4070 strbuf_release(&ref_name);
4071 clear_unpack_trees_porcelain(&unpack_tree_opts);
4072 return ret;
4075 static int do_merge(struct repository *r,
4076 struct commit *commit,
4077 const char *arg, int arg_len,
4078 int flags, int *check_todo, struct replay_opts *opts)
4080 struct replay_ctx *ctx = opts->ctx;
4081 int run_commit_flags = 0;
4082 struct strbuf ref_name = STRBUF_INIT;
4083 struct commit *head_commit, *merge_commit, *i;
4084 struct commit_list *bases = NULL, *j;
4085 struct commit_list *to_merge = NULL, **tail = &to_merge;
4086 const char *strategy = !opts->xopts.nr &&
4087 (!opts->strategy ||
4088 !strcmp(opts->strategy, "recursive") ||
4089 !strcmp(opts->strategy, "ort")) ?
4090 NULL : opts->strategy;
4091 struct merge_options o;
4092 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4093 static struct lock_file lock;
4094 const char *p;
4096 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4097 ret = -1;
4098 goto leave_merge;
4101 head_commit = lookup_commit_reference_by_name("HEAD");
4102 if (!head_commit) {
4103 ret = error(_("cannot merge without a current revision"));
4104 goto leave_merge;
4108 * For octopus merges, the arg starts with the list of revisions to be
4109 * merged. The list is optionally followed by '#' and the oneline.
4111 merge_arg_len = oneline_offset = arg_len;
4112 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4113 if (!*p)
4114 break;
4115 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4116 p += 1 + strspn(p + 1, " \t\n");
4117 oneline_offset = p - arg;
4118 break;
4120 k = strcspn(p, " \t\n");
4121 if (!k)
4122 continue;
4123 merge_commit = lookup_label(r, p, k, &ref_name);
4124 if (!merge_commit) {
4125 ret = error(_("unable to parse '%.*s'"), k, p);
4126 goto leave_merge;
4128 tail = &commit_list_insert(merge_commit, tail)->next;
4129 p += k;
4130 merge_arg_len = p - arg;
4133 if (!to_merge) {
4134 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4135 goto leave_merge;
4138 if (opts->have_squash_onto &&
4139 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4141 * When the user tells us to "merge" something into a
4142 * "[new root]", let's simply fast-forward to the merge head.
4144 rollback_lock_file(&lock);
4145 if (to_merge->next)
4146 ret = error(_("octopus merge cannot be executed on "
4147 "top of a [new root]"));
4148 else
4149 ret = fast_forward_to(r, &to_merge->item->object.oid,
4150 &head_commit->object.oid, 0,
4151 opts);
4152 goto leave_merge;
4156 * If HEAD is not identical to the first parent of the original merge
4157 * commit, we cannot fast-forward.
4159 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4160 oideq(&commit->parents->item->object.oid,
4161 &head_commit->object.oid);
4164 * If any merge head is different from the original one, we cannot
4165 * fast-forward.
4167 if (can_fast_forward) {
4168 struct commit_list *p = commit->parents->next;
4170 for (j = to_merge; j && p; j = j->next, p = p->next)
4171 if (!oideq(&j->item->object.oid,
4172 &p->item->object.oid)) {
4173 can_fast_forward = 0;
4174 break;
4177 * If the number of merge heads differs from the original merge
4178 * commit, we cannot fast-forward.
4180 if (j || p)
4181 can_fast_forward = 0;
4184 if (can_fast_forward) {
4185 rollback_lock_file(&lock);
4186 ret = fast_forward_to(r, &commit->object.oid,
4187 &head_commit->object.oid, 0, opts);
4188 if (flags & TODO_EDIT_MERGE_MSG)
4189 goto fast_forward_edit;
4191 goto leave_merge;
4194 if (commit) {
4195 const char *encoding = get_commit_output_encoding();
4196 const char *message = repo_logmsg_reencode(r, commit, NULL,
4197 encoding);
4198 const char *body;
4199 int len;
4201 if (!message) {
4202 ret = error(_("could not get commit message of '%s'"),
4203 oid_to_hex(&commit->object.oid));
4204 goto leave_merge;
4206 write_author_script(message);
4207 find_commit_subject(message, &body);
4208 len = strlen(body);
4209 strbuf_add(&ctx->message, body, len);
4210 repo_unuse_commit_buffer(r, commit, message);
4211 } else {
4212 struct strbuf buf = STRBUF_INIT;
4214 strbuf_addf(&buf, "author %s", git_author_info(0));
4215 write_author_script(buf.buf);
4216 strbuf_release(&buf);
4218 if (oneline_offset < arg_len) {
4219 strbuf_add(&ctx->message, arg + oneline_offset,
4220 arg_len - oneline_offset);
4221 } else {
4222 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4223 to_merge->next ? "branches" : "branch",
4224 merge_arg_len, arg);
4227 ctx->have_message = 1;
4228 if (write_message(ctx->message.buf, ctx->message.len,
4229 git_path_merge_msg(r), 0)) {
4230 ret = error_errno(_("could not write '%s'"),
4231 git_path_merge_msg(r));
4232 goto leave_merge;
4235 if (strategy || to_merge->next) {
4236 /* Octopus merge */
4237 struct child_process cmd = CHILD_PROCESS_INIT;
4239 if (read_env_script(&cmd.env)) {
4240 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4242 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4243 goto leave_merge;
4246 if (opts->committer_date_is_author_date)
4247 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4248 opts->ignore_date ?
4249 "" :
4250 author_date_from_env(&cmd.env));
4251 if (opts->ignore_date)
4252 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4254 cmd.git_cmd = 1;
4255 strvec_push(&cmd.args, "merge");
4256 strvec_push(&cmd.args, "-s");
4257 if (!strategy)
4258 strvec_push(&cmd.args, "octopus");
4259 else {
4260 strvec_push(&cmd.args, strategy);
4261 for (k = 0; k < opts->xopts.nr; k++)
4262 strvec_pushf(&cmd.args,
4263 "-X%s", opts->xopts.v[k]);
4265 if (!(flags & TODO_EDIT_MERGE_MSG))
4266 strvec_push(&cmd.args, "--no-edit");
4267 else
4268 strvec_push(&cmd.args, "--edit");
4269 strvec_push(&cmd.args, "--no-ff");
4270 strvec_push(&cmd.args, "--no-log");
4271 strvec_push(&cmd.args, "--no-stat");
4272 strvec_push(&cmd.args, "-F");
4273 strvec_push(&cmd.args, git_path_merge_msg(r));
4274 if (opts->gpg_sign)
4275 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4276 else
4277 strvec_push(&cmd.args, "--no-gpg-sign");
4279 /* Add the tips to be merged */
4280 for (j = to_merge; j; j = j->next)
4281 strvec_push(&cmd.args,
4282 oid_to_hex(&j->item->object.oid));
4284 strbuf_release(&ref_name);
4285 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4286 NULL, REF_NO_DEREF);
4287 rollback_lock_file(&lock);
4289 ret = run_command(&cmd);
4291 /* force re-reading of the cache */
4292 if (!ret) {
4293 discard_index(r->index);
4294 if (repo_read_index(r) < 0)
4295 ret = error(_("could not read index"));
4297 goto leave_merge;
4300 merge_commit = to_merge->item;
4301 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4302 ret = -1;
4303 goto leave_merge;
4306 if (bases && oideq(&merge_commit->object.oid,
4307 &bases->item->object.oid)) {
4308 ret = 0;
4309 /* skip merging an ancestor of HEAD */
4310 goto leave_merge;
4313 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4314 git_path_merge_head(r), 0);
4315 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4317 bases = reverse_commit_list(bases);
4319 repo_read_index(r);
4320 init_ui_merge_options(&o, r);
4321 o.branch1 = "HEAD";
4322 o.branch2 = ref_name.buf;
4323 o.buffer_output = 2;
4325 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4327 * TODO: Should use merge_incore_recursive() and
4328 * merge_switch_to_result(), skipping the call to
4329 * merge_switch_to_result() when we don't actually need to
4330 * update the index and working copy immediately.
4332 ret = merge_ort_recursive(&o,
4333 head_commit, merge_commit, bases,
4334 &i);
4335 } else {
4336 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4337 &i);
4339 if (ret <= 0)
4340 fputs(o.obuf.buf, stdout);
4341 strbuf_release(&o.obuf);
4342 if (ret < 0) {
4343 error(_("could not even attempt to merge '%.*s'"),
4344 merge_arg_len, arg);
4345 unlink(git_path_merge_msg(r));
4346 goto leave_merge;
4349 * The return value of merge_recursive() is 1 on clean, and 0 on
4350 * unclean merge.
4352 * Let's reverse that, so that do_merge() returns 0 upon success and
4353 * 1 upon failed merge (keeping the return value -1 for the cases where
4354 * we will want to reschedule the `merge` command).
4356 ret = !ret;
4358 if (r->index->cache_changed &&
4359 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4360 ret = error(_("merge: Unable to write new index file"));
4361 goto leave_merge;
4364 rollback_lock_file(&lock);
4365 if (ret)
4366 repo_rerere(r, opts->allow_rerere_auto);
4367 else
4369 * In case of problems, we now want to return a positive
4370 * value (a negative one would indicate that the `merge`
4371 * command needs to be rescheduled).
4373 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4374 run_commit_flags);
4376 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4377 fast_forward_edit:
4378 *check_todo = 1;
4379 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4380 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4384 leave_merge:
4385 strbuf_release(&ref_name);
4386 rollback_lock_file(&lock);
4387 free_commit_list(to_merge);
4388 free_commit_list(bases);
4389 return ret;
4392 static int write_update_refs_state(struct string_list *refs_to_oids)
4394 int result = 0;
4395 struct lock_file lock = LOCK_INIT;
4396 FILE *fp = NULL;
4397 struct string_list_item *item;
4398 char *path;
4400 path = rebase_path_update_refs(the_repository->gitdir);
4402 if (!refs_to_oids->nr) {
4403 if (unlink(path) && errno != ENOENT)
4404 result = error_errno(_("could not unlink: %s"), path);
4405 goto cleanup;
4408 if (safe_create_leading_directories(path)) {
4409 result = error(_("unable to create leading directories of %s"),
4410 path);
4411 goto cleanup;
4414 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4415 result = error(_("another 'rebase' process appears to be running; "
4416 "'%s.lock' already exists"),
4417 path);
4418 goto cleanup;
4421 fp = fdopen_lock_file(&lock, "w");
4422 if (!fp) {
4423 result = error_errno(_("could not open '%s' for writing"), path);
4424 rollback_lock_file(&lock);
4425 goto cleanup;
4428 for_each_string_list_item(item, refs_to_oids) {
4429 struct update_ref_record *rec = item->util;
4430 fprintf(fp, "%s\n%s\n%s\n", item->string,
4431 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4434 result = commit_lock_file(&lock);
4436 cleanup:
4437 free(path);
4438 return result;
4442 * Parse the update-refs file for the current rebase, then remove the
4443 * refs that do not appear in the todo_list (and have not had updated
4444 * values stored) and add refs that are in the todo_list but not
4445 * represented in the update-refs file.
4447 * If there are changes to the update-refs list, then write the new state
4448 * to disk.
4450 void todo_list_filter_update_refs(struct repository *r,
4451 struct todo_list *todo_list)
4453 int i;
4454 int updated = 0;
4455 struct string_list update_refs = STRING_LIST_INIT_DUP;
4457 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4460 * For each item in the update_refs list, if it has no updated
4461 * value and does not appear in the todo_list, then remove it
4462 * from the update_refs list.
4464 for (i = 0; i < update_refs.nr; i++) {
4465 int j;
4466 int found = 0;
4467 const char *ref = update_refs.items[i].string;
4468 size_t reflen = strlen(ref);
4469 struct update_ref_record *rec = update_refs.items[i].util;
4471 /* OID already stored as updated. */
4472 if (!is_null_oid(&rec->after))
4473 continue;
4475 for (j = 0; !found && j < todo_list->nr; j++) {
4476 struct todo_item *item = &todo_list->items[j];
4477 const char *arg = todo_list->buf.buf + item->arg_offset;
4479 if (item->command != TODO_UPDATE_REF)
4480 continue;
4482 if (item->arg_len != reflen ||
4483 strncmp(arg, ref, reflen))
4484 continue;
4486 found = 1;
4489 if (!found) {
4490 free(update_refs.items[i].string);
4491 free(update_refs.items[i].util);
4493 update_refs.nr--;
4494 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4496 updated = 1;
4497 i--;
4502 * For each todo_item, check if its ref is in the update_refs list.
4503 * If not, then add it as an un-updated ref.
4505 for (i = 0; i < todo_list->nr; i++) {
4506 struct todo_item *item = &todo_list->items[i];
4507 const char *arg = todo_list->buf.buf + item->arg_offset;
4508 int j, found = 0;
4510 if (item->command != TODO_UPDATE_REF)
4511 continue;
4513 for (j = 0; !found && j < update_refs.nr; j++) {
4514 const char *ref = update_refs.items[j].string;
4516 found = strlen(ref) == item->arg_len &&
4517 !strncmp(ref, arg, item->arg_len);
4520 if (!found) {
4521 struct string_list_item *inserted;
4522 struct strbuf argref = STRBUF_INIT;
4524 strbuf_add(&argref, arg, item->arg_len);
4525 inserted = string_list_insert(&update_refs, argref.buf);
4526 inserted->util = init_update_ref_record(argref.buf);
4527 strbuf_release(&argref);
4528 updated = 1;
4532 if (updated)
4533 write_update_refs_state(&update_refs);
4534 string_list_clear(&update_refs, 1);
4537 static int do_update_ref(struct repository *r, const char *refname)
4539 struct string_list_item *item;
4540 struct string_list list = STRING_LIST_INIT_DUP;
4542 if (sequencer_get_update_refs_state(r->gitdir, &list))
4543 return -1;
4545 for_each_string_list_item(item, &list) {
4546 if (!strcmp(item->string, refname)) {
4547 struct update_ref_record *rec = item->util;
4548 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4549 return -1;
4550 break;
4554 write_update_refs_state(&list);
4555 string_list_clear(&list, 1);
4556 return 0;
4559 static int do_update_refs(struct repository *r, int quiet)
4561 int res = 0;
4562 struct string_list_item *item;
4563 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4564 struct ref_store *refs = get_main_ref_store(r);
4565 struct strbuf update_msg = STRBUF_INIT;
4566 struct strbuf error_msg = STRBUF_INIT;
4568 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4569 return res;
4571 for_each_string_list_item(item, &refs_to_oids) {
4572 struct update_ref_record *rec = item->util;
4573 int loop_res;
4575 loop_res = refs_update_ref(refs, "rewritten during rebase",
4576 item->string,
4577 &rec->after, &rec->before,
4578 0, UPDATE_REFS_MSG_ON_ERR);
4579 res |= loop_res;
4581 if (quiet)
4582 continue;
4584 if (loop_res)
4585 strbuf_addf(&error_msg, "\t%s\n", item->string);
4586 else
4587 strbuf_addf(&update_msg, "\t%s\n", item->string);
4590 if (!quiet &&
4591 (update_msg.len || error_msg.len)) {
4592 fprintf(stderr,
4593 _("Updated the following refs with %s:\n%s"),
4594 "--update-refs",
4595 update_msg.buf);
4597 if (res)
4598 fprintf(stderr,
4599 _("Failed to update the following refs with %s:\n%s"),
4600 "--update-refs",
4601 error_msg.buf);
4604 string_list_clear(&refs_to_oids, 1);
4605 strbuf_release(&update_msg);
4606 strbuf_release(&error_msg);
4607 return res;
4610 static int is_final_fixup(struct todo_list *todo_list)
4612 int i = todo_list->current;
4614 if (!is_fixup(todo_list->items[i].command))
4615 return 0;
4617 while (++i < todo_list->nr)
4618 if (is_fixup(todo_list->items[i].command))
4619 return 0;
4620 else if (!is_noop(todo_list->items[i].command))
4621 break;
4622 return 1;
4625 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4627 int i;
4629 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4630 if (!is_noop(todo_list->items[i].command))
4631 return todo_list->items[i].command;
4633 return -1;
4636 static void create_autostash_internal(struct repository *r,
4637 const char *path,
4638 const char *refname)
4640 struct strbuf buf = STRBUF_INIT;
4641 struct lock_file lock_file = LOCK_INIT;
4642 int fd;
4644 if (path && refname)
4645 BUG("can only pass path or refname");
4647 fd = repo_hold_locked_index(r, &lock_file, 0);
4648 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4649 if (0 <= fd)
4650 repo_update_index_if_able(r, &lock_file);
4651 rollback_lock_file(&lock_file);
4653 if (has_unstaged_changes(r, 1) ||
4654 has_uncommitted_changes(r, 1)) {
4655 struct child_process stash = CHILD_PROCESS_INIT;
4656 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4657 struct object_id oid;
4659 strvec_pushl(&stash.args,
4660 "stash", "create", "autostash", NULL);
4661 stash.git_cmd = 1;
4662 stash.no_stdin = 1;
4663 strbuf_reset(&buf);
4664 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4665 die(_("Cannot autostash"));
4666 strbuf_trim_trailing_newline(&buf);
4667 if (repo_get_oid(r, buf.buf, &oid))
4668 die(_("Unexpected stash response: '%s'"),
4669 buf.buf);
4670 strbuf_reset(&buf);
4671 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4673 if (path) {
4674 if (safe_create_leading_directories_const(path))
4675 die(_("Could not create directory for '%s'"),
4676 path);
4677 write_file(path, "%s", oid_to_hex(&oid));
4678 } else {
4679 refs_update_ref(get_main_ref_store(r), "", refname,
4680 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4683 printf(_("Created autostash: %s\n"), buf.buf);
4684 if (reset_head(r, &ropts) < 0)
4685 die(_("could not reset --hard"));
4686 discard_index(r->index);
4687 if (repo_read_index(r) < 0)
4688 die(_("could not read index"));
4690 strbuf_release(&buf);
4693 void create_autostash(struct repository *r, const char *path)
4695 create_autostash_internal(r, path, NULL);
4698 void create_autostash_ref(struct repository *r, const char *refname)
4700 create_autostash_internal(r, NULL, refname);
4703 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4705 struct child_process child = CHILD_PROCESS_INIT;
4706 int ret = 0;
4708 if (attempt_apply) {
4709 child.git_cmd = 1;
4710 child.no_stdout = 1;
4711 child.no_stderr = 1;
4712 strvec_push(&child.args, "stash");
4713 strvec_push(&child.args, "apply");
4714 strvec_push(&child.args, stash_oid);
4715 ret = run_command(&child);
4718 if (attempt_apply && !ret)
4719 fprintf(stderr, _("Applied autostash.\n"));
4720 else {
4721 struct child_process store = CHILD_PROCESS_INIT;
4723 store.git_cmd = 1;
4724 strvec_push(&store.args, "stash");
4725 strvec_push(&store.args, "store");
4726 strvec_push(&store.args, "-m");
4727 strvec_push(&store.args, "autostash");
4728 strvec_push(&store.args, "-q");
4729 strvec_push(&store.args, stash_oid);
4730 if (run_command(&store))
4731 ret = error(_("cannot store %s"), stash_oid);
4732 else
4733 fprintf(stderr,
4734 _("%s\n"
4735 "Your changes are safe in the stash.\n"
4736 "You can run \"git stash pop\" or"
4737 " \"git stash drop\" at any time.\n"),
4738 attempt_apply ?
4739 _("Applying autostash resulted in conflicts.") :
4740 _("Autostash exists; creating a new stash entry."));
4743 return ret;
4746 static int apply_save_autostash(const char *path, int attempt_apply)
4748 struct strbuf stash_oid = STRBUF_INIT;
4749 int ret = 0;
4751 if (!read_oneliner(&stash_oid, path,
4752 READ_ONELINER_SKIP_IF_EMPTY)) {
4753 strbuf_release(&stash_oid);
4754 return 0;
4756 strbuf_trim(&stash_oid);
4758 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4760 unlink(path);
4761 strbuf_release(&stash_oid);
4762 return ret;
4765 int save_autostash(const char *path)
4767 return apply_save_autostash(path, 0);
4770 int apply_autostash(const char *path)
4772 return apply_save_autostash(path, 1);
4775 int apply_autostash_oid(const char *stash_oid)
4777 return apply_save_autostash_oid(stash_oid, 1);
4780 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4781 int attempt_apply)
4783 struct object_id stash_oid;
4784 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4785 int flag, ret;
4787 if (!refs_ref_exists(get_main_ref_store(r), refname))
4788 return 0;
4790 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4791 RESOLVE_REF_READING, &stash_oid, &flag))
4792 return -1;
4793 if (flag & REF_ISSYMREF)
4794 return error(_("autostash reference is a symref"));
4796 oid_to_hex_r(stash_oid_hex, &stash_oid);
4797 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4799 refs_delete_ref(get_main_ref_store(r), "", refname,
4800 &stash_oid, REF_NO_DEREF);
4802 return ret;
4805 int save_autostash_ref(struct repository *r, const char *refname)
4807 return apply_save_autostash_ref(r, refname, 0);
4810 int apply_autostash_ref(struct repository *r, const char *refname)
4812 return apply_save_autostash_ref(r, refname, 1);
4815 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4816 const char *onto_name, const struct object_id *onto,
4817 const struct object_id *orig_head)
4819 struct reset_head_opts ropts = {
4820 .oid = onto,
4821 .orig_head = orig_head,
4822 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4823 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4824 .head_msg = reflog_message(opts, "start", "checkout %s",
4825 onto_name),
4826 .default_reflog_action = sequencer_reflog_action(opts)
4828 if (reset_head(r, &ropts)) {
4829 apply_autostash(rebase_path_autostash());
4830 sequencer_remove_state(opts);
4831 return error(_("could not detach HEAD"));
4834 return 0;
4837 static int stopped_at_head(struct repository *r)
4839 struct object_id head;
4840 struct commit *commit;
4841 struct commit_message message;
4843 if (repo_get_oid(r, "HEAD", &head) ||
4844 !(commit = lookup_commit(r, &head)) ||
4845 repo_parse_commit(r, commit) || get_message(commit, &message))
4846 fprintf(stderr, _("Stopped at HEAD\n"));
4847 else {
4848 fprintf(stderr, _("Stopped at %s\n"), message.label);
4849 free_message(commit, &message);
4851 return 0;
4855 static int reread_todo_if_changed(struct repository *r,
4856 struct todo_list *todo_list,
4857 struct replay_opts *opts)
4859 int offset;
4860 struct strbuf buf = STRBUF_INIT;
4862 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4863 return -1;
4864 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4865 if (buf.len != todo_list->buf.len - offset ||
4866 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4867 /* Reread the todo file if it has changed. */
4868 todo_list_release(todo_list);
4869 if (read_populate_todo(r, todo_list, opts))
4870 return -1; /* message was printed */
4871 /* `current` will be incremented on return */
4872 todo_list->current = -1;
4874 strbuf_release(&buf);
4876 return 0;
4879 static const char rescheduled_advice[] =
4880 N_("Could not execute the todo command\n"
4881 "\n"
4882 " %.*s"
4883 "\n"
4884 "It has been rescheduled; To edit the command before continuing, please\n"
4885 "edit the todo list first:\n"
4886 "\n"
4887 " git rebase --edit-todo\n"
4888 " git rebase --continue\n");
4890 static int pick_one_commit(struct repository *r,
4891 struct todo_list *todo_list,
4892 struct replay_opts *opts,
4893 int *check_todo, int* reschedule)
4895 struct replay_ctx *ctx = opts->ctx;
4896 int res;
4897 struct todo_item *item = todo_list->items + todo_list->current;
4898 const char *arg = todo_item_get_arg(todo_list, item);
4899 if (is_rebase_i(opts))
4900 ctx->reflog_message = reflog_message(
4901 opts, command_to_string(item->command), NULL);
4903 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4904 check_todo);
4905 if (is_rebase_i(opts) && res < 0) {
4906 /* Reschedule */
4907 *reschedule = 1;
4908 return -1;
4910 if (item->command == TODO_EDIT) {
4911 struct commit *commit = item->commit;
4912 if (!res) {
4913 if (!opts->verbose)
4914 term_clear_line();
4915 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4916 short_commit_name(r, commit), item->arg_len, arg);
4918 return error_with_patch(r, commit,
4919 arg, item->arg_len, opts, res, !res);
4921 if (is_rebase_i(opts) && !res)
4922 record_in_rewritten(&item->commit->object.oid,
4923 peek_command(todo_list, 1));
4924 if (res && is_fixup(item->command)) {
4925 if (res == 1)
4926 intend_to_amend();
4927 return error_failed_squash(r, item->commit, opts,
4928 item->arg_len, arg);
4929 } else if (res && is_rebase_i(opts) && item->commit) {
4930 int to_amend = 0;
4931 struct object_id oid;
4934 * If we are rewording and have either
4935 * fast-forwarded already, or are about to
4936 * create a new root commit, we want to amend,
4937 * otherwise we do not.
4939 if (item->command == TODO_REWORD &&
4940 !repo_get_oid(r, "HEAD", &oid) &&
4941 (oideq(&item->commit->object.oid, &oid) ||
4942 (opts->have_squash_onto &&
4943 oideq(&opts->squash_onto, &oid))))
4944 to_amend = 1;
4946 return res | error_with_patch(r, item->commit,
4947 arg, item->arg_len, opts,
4948 res, to_amend);
4950 return res;
4953 static int pick_commits(struct repository *r,
4954 struct todo_list *todo_list,
4955 struct replay_opts *opts)
4957 struct replay_ctx *ctx = opts->ctx;
4958 int res = 0, reschedule = 0;
4960 ctx->reflog_message = sequencer_reflog_action(opts);
4961 if (opts->allow_ff)
4962 assert(!(opts->signoff || opts->no_commit ||
4963 opts->record_origin || should_edit(opts) ||
4964 opts->committer_date_is_author_date ||
4965 opts->ignore_date));
4966 if (read_and_refresh_cache(r, opts))
4967 return -1;
4969 unlink(rebase_path_message());
4970 unlink(rebase_path_stopped_sha());
4971 unlink(rebase_path_amend());
4972 unlink(rebase_path_patch());
4974 while (todo_list->current < todo_list->nr) {
4975 struct todo_item *item = todo_list->items + todo_list->current;
4976 const char *arg = todo_item_get_arg(todo_list, item);
4977 int check_todo = 0;
4979 if (save_todo(todo_list, opts, reschedule))
4980 return -1;
4981 if (is_rebase_i(opts)) {
4982 if (item->command != TODO_COMMENT) {
4983 FILE *f = fopen(rebase_path_msgnum(), "w");
4985 todo_list->done_nr++;
4987 if (f) {
4988 fprintf(f, "%d\n", todo_list->done_nr);
4989 fclose(f);
4991 if (!opts->quiet)
4992 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4993 todo_list->done_nr,
4994 todo_list->total_nr,
4995 opts->verbose ? "\n" : "\r");
4997 unlink(rebase_path_author_script());
4998 unlink(git_path_merge_head(r));
4999 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5000 NULL, REF_NO_DEREF);
5001 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
5002 NULL, REF_NO_DEREF);
5004 if (item->command == TODO_BREAK) {
5005 if (!opts->verbose)
5006 term_clear_line();
5007 return stopped_at_head(r);
5010 strbuf_reset(&ctx->message);
5011 ctx->have_message = 0;
5012 if (item->command <= TODO_SQUASH) {
5013 res = pick_one_commit(r, todo_list, opts, &check_todo,
5014 &reschedule);
5015 if (!res && item->command == TODO_EDIT)
5016 return 0;
5017 } else if (item->command == TODO_EXEC) {
5018 char *end_of_arg = (char *)(arg + item->arg_len);
5019 int saved = *end_of_arg;
5021 if (!opts->verbose)
5022 term_clear_line();
5023 *end_of_arg = '\0';
5024 res = do_exec(r, arg, opts->quiet);
5025 *end_of_arg = saved;
5027 if (res) {
5028 if (opts->reschedule_failed_exec)
5029 reschedule = 1;
5031 check_todo = 1;
5032 } else if (item->command == TODO_LABEL) {
5033 if ((res = do_label(r, arg, item->arg_len)))
5034 reschedule = 1;
5035 } else if (item->command == TODO_RESET) {
5036 if ((res = do_reset(r, arg, item->arg_len, opts)))
5037 reschedule = 1;
5038 } else if (item->command == TODO_MERGE) {
5039 if ((res = do_merge(r, item->commit, arg, item->arg_len,
5040 item->flags, &check_todo, opts)) < 0)
5041 reschedule = 1;
5042 else if (item->commit)
5043 record_in_rewritten(&item->commit->object.oid,
5044 peek_command(todo_list, 1));
5045 if (res > 0)
5046 /* failed with merge conflicts */
5047 return error_with_patch(r, item->commit,
5048 arg, item->arg_len,
5049 opts, res, 0);
5050 } else if (item->command == TODO_UPDATE_REF) {
5051 struct strbuf ref = STRBUF_INIT;
5052 strbuf_add(&ref, arg, item->arg_len);
5053 if ((res = do_update_ref(r, ref.buf)))
5054 reschedule = 1;
5055 strbuf_release(&ref);
5056 } else if (!is_noop(item->command))
5057 return error(_("unknown command %d"), item->command);
5059 if (reschedule) {
5060 advise(_(rescheduled_advice),
5061 get_item_line_length(todo_list,
5062 todo_list->current),
5063 get_item_line(todo_list, todo_list->current));
5064 if (save_todo(todo_list, opts, reschedule))
5065 return -1;
5066 if (item->commit)
5067 write_rebase_head(&item->commit->object.oid);
5068 } else if (is_rebase_i(opts) && check_todo && !res &&
5069 reread_todo_if_changed(r, todo_list, opts)) {
5070 return -1;
5073 if (res)
5074 return res;
5076 todo_list->current++;
5079 if (is_rebase_i(opts)) {
5080 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
5081 struct stat st;
5083 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5084 starts_with(head_ref.buf, "refs/")) {
5085 const char *msg;
5086 struct object_id head, orig;
5087 int res;
5089 if (repo_get_oid(r, "HEAD", &head)) {
5090 res = error(_("cannot read HEAD"));
5091 cleanup_head_ref:
5092 strbuf_release(&head_ref);
5093 strbuf_release(&buf);
5094 return res;
5096 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
5097 get_oid_hex(buf.buf, &orig)) {
5098 res = error(_("could not read orig-head"));
5099 goto cleanup_head_ref;
5101 strbuf_reset(&buf);
5102 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5103 res = error(_("could not read 'onto'"));
5104 goto cleanup_head_ref;
5106 msg = reflog_message(opts, "finish", "%s onto %s",
5107 head_ref.buf, buf.buf);
5108 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5109 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
5110 res = error(_("could not update %s"),
5111 head_ref.buf);
5112 goto cleanup_head_ref;
5114 msg = reflog_message(opts, "finish", "returning to %s",
5115 head_ref.buf);
5116 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
5117 res = error(_("could not update HEAD to %s"),
5118 head_ref.buf);
5119 goto cleanup_head_ref;
5121 strbuf_reset(&buf);
5124 if (opts->verbose) {
5125 struct rev_info log_tree_opt;
5126 struct object_id orig, head;
5128 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
5129 repo_init_revisions(r, &log_tree_opt, NULL);
5130 log_tree_opt.diff = 1;
5131 log_tree_opt.diffopt.output_format =
5132 DIFF_FORMAT_DIFFSTAT;
5133 log_tree_opt.disable_stdin = 1;
5135 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
5136 !repo_get_oid(r, buf.buf, &orig) &&
5137 !repo_get_oid(r, "HEAD", &head)) {
5138 diff_tree_oid(&orig, &head, "",
5139 &log_tree_opt.diffopt);
5140 log_tree_diff_flush(&log_tree_opt);
5142 release_revisions(&log_tree_opt);
5144 flush_rewritten_pending();
5145 if (!stat(rebase_path_rewritten_list(), &st) &&
5146 st.st_size > 0) {
5147 struct child_process child = CHILD_PROCESS_INIT;
5148 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5150 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5151 child.git_cmd = 1;
5152 strvec_push(&child.args, "notes");
5153 strvec_push(&child.args, "copy");
5154 strvec_push(&child.args, "--for-rewrite=rebase");
5155 /* we don't care if this copying failed */
5156 run_command(&child);
5158 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5159 strvec_push(&hook_opt.args, "rebase");
5160 run_hooks_opt(r, "post-rewrite", &hook_opt);
5162 apply_autostash(rebase_path_autostash());
5164 if (!opts->quiet) {
5165 if (!opts->verbose)
5166 term_clear_line();
5167 fprintf(stderr,
5168 _("Successfully rebased and updated %s.\n"),
5169 head_ref.buf);
5172 strbuf_release(&buf);
5173 strbuf_release(&head_ref);
5175 if (do_update_refs(r, opts->quiet))
5176 return -1;
5180 * Sequence of picks finished successfully; cleanup by
5181 * removing the .git/sequencer directory
5183 return sequencer_remove_state(opts);
5186 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5188 struct child_process cmd = CHILD_PROCESS_INIT;
5190 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5191 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5192 return error(_("no cherry-pick or revert in progress"));
5194 cmd.git_cmd = 1;
5195 strvec_push(&cmd.args, "commit");
5198 * continue_single_pick() handles the case of recovering from a
5199 * conflict. should_edit() doesn't handle that case; for a conflict,
5200 * we want to edit if the user asked for it, or if they didn't specify
5201 * and stdin is a tty.
5203 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5205 * Include --cleanup=strip as well because we don't want the
5206 * "# Conflicts:" messages.
5208 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5210 return run_command(&cmd);
5213 static int commit_staged_changes(struct repository *r,
5214 struct replay_opts *opts,
5215 struct todo_list *todo_list)
5217 struct replay_ctx *ctx = opts->ctx;
5218 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5219 unsigned int final_fixup = 0, is_clean;
5220 struct strbuf rev = STRBUF_INIT;
5221 int ret;
5223 if (has_unstaged_changes(r, 1)) {
5224 ret = error(_("cannot rebase: You have unstaged changes."));
5225 goto out;
5228 is_clean = !has_uncommitted_changes(r, 0);
5230 if (!is_clean && !file_exists(rebase_path_message())) {
5231 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5232 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
5233 goto out;
5236 if (file_exists(rebase_path_amend())) {
5237 struct object_id head, to_amend;
5239 if (repo_get_oid(r, "HEAD", &head)) {
5240 ret = error(_("cannot amend non-existing commit"));
5241 goto out;
5244 if (!read_oneliner(&rev, rebase_path_amend(), 0)) {
5245 ret = error(_("invalid file: '%s'"), rebase_path_amend());
5246 goto out;
5249 if (get_oid_hex(rev.buf, &to_amend)) {
5250 ret = error(_("invalid contents: '%s'"),
5251 rebase_path_amend());
5252 goto out;
5254 if (!is_clean && !oideq(&head, &to_amend)) {
5255 ret = error(_("\nYou have uncommitted changes in your "
5256 "working tree. Please, commit them\n"
5257 "first and then run 'git rebase "
5258 "--continue' again."));
5259 goto out;
5262 * When skipping a failed fixup/squash, we need to edit the
5263 * commit message, the current fixup list and count, and if it
5264 * was the last fixup/squash in the chain, we need to clean up
5265 * the commit message and if there was a squash, let the user
5266 * edit it.
5268 if (!is_clean || !ctx->current_fixup_count)
5269 ; /* this is not the final fixup */
5270 else if (!oideq(&head, &to_amend) ||
5271 !file_exists(rebase_path_stopped_sha())) {
5272 /* was a final fixup or squash done manually? */
5273 if (!is_fixup(peek_command(todo_list, 0))) {
5274 unlink(rebase_path_fixup_msg());
5275 unlink(rebase_path_squash_msg());
5276 unlink(rebase_path_current_fixups());
5277 strbuf_reset(&ctx->current_fixups);
5278 ctx->current_fixup_count = 0;
5280 } else {
5281 /* we are in a fixup/squash chain */
5282 const char *p = ctx->current_fixups.buf;
5283 int len = ctx->current_fixups.len;
5285 ctx->current_fixup_count--;
5286 if (!len)
5287 BUG("Incorrect current_fixups:\n%s", p);
5288 while (len && p[len - 1] != '\n')
5289 len--;
5290 strbuf_setlen(&ctx->current_fixups, len);
5291 if (write_message(p, len, rebase_path_current_fixups(),
5292 0) < 0) {
5293 ret = error(_("could not write file: '%s'"),
5294 rebase_path_current_fixups());
5295 goto out;
5299 * If a fixup/squash in a fixup/squash chain failed, the
5300 * commit message is already correct, no need to commit
5301 * it again.
5303 * Only if it is the final command in the fixup/squash
5304 * chain, and only if the chain is longer than a single
5305 * fixup/squash command (which was just skipped), do we
5306 * actually need to re-commit with a cleaned up commit
5307 * message.
5309 if (ctx->current_fixup_count > 0 &&
5310 !is_fixup(peek_command(todo_list, 0))) {
5311 final_fixup = 1;
5313 * If there was not a single "squash" in the
5314 * chain, we only need to clean up the commit
5315 * message, no need to bother the user with
5316 * opening the commit message in the editor.
5318 if (!starts_with(p, "squash ") &&
5319 !strstr(p, "\nsquash "))
5320 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5321 } else if (is_fixup(peek_command(todo_list, 0))) {
5323 * We need to update the squash message to skip
5324 * the latest commit message.
5326 struct commit *commit;
5327 const char *msg;
5328 const char *path = rebase_path_squash_msg();
5329 const char *encoding = get_commit_output_encoding();
5331 if (parse_head(r, &commit)) {
5332 ret = error(_("could not parse HEAD"));
5333 goto out;
5336 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5337 if (!p) {
5338 ret = error(_("could not parse commit %s"),
5339 oid_to_hex(&commit->object.oid));
5340 goto unuse_commit_buffer;
5342 find_commit_subject(p, &msg);
5343 if (write_message(msg, strlen(msg), path, 0)) {
5344 ret = error(_("could not write file: "
5345 "'%s'"), path);
5346 goto unuse_commit_buffer;
5349 ret = 0;
5351 unuse_commit_buffer:
5352 repo_unuse_commit_buffer(r, commit, p);
5353 if (ret)
5354 goto out;
5358 flags |= AMEND_MSG;
5361 if (is_clean) {
5362 if (refs_ref_exists(get_main_ref_store(r),
5363 "CHERRY_PICK_HEAD") &&
5364 refs_delete_ref(get_main_ref_store(r), "",
5365 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF)) {
5366 ret = error(_("could not remove CHERRY_PICK_HEAD"));
5367 goto out;
5370 if (unlink(git_path_merge_msg(r)) && errno != ENOENT) {
5371 ret = error_errno(_("could not remove '%s'"),
5372 git_path_merge_msg(r));
5373 goto out;
5376 if (!final_fixup) {
5377 ret = 0;
5378 goto out;
5382 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5383 opts, flags)) {
5384 ret = error(_("could not commit staged changes."));
5385 goto out;
5388 unlink(rebase_path_amend());
5389 unlink(git_path_merge_head(r));
5390 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5391 NULL, REF_NO_DEREF);
5392 if (final_fixup) {
5393 unlink(rebase_path_fixup_msg());
5394 unlink(rebase_path_squash_msg());
5396 if (ctx->current_fixup_count > 0) {
5398 * Whether final fixup or not, we just cleaned up the commit
5399 * message...
5401 unlink(rebase_path_current_fixups());
5402 strbuf_reset(&ctx->current_fixups);
5403 ctx->current_fixup_count = 0;
5406 ret = 0;
5408 out:
5409 strbuf_release(&rev);
5410 return ret;
5413 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5415 struct replay_ctx *ctx = opts->ctx;
5416 struct todo_list todo_list = TODO_LIST_INIT;
5417 int res;
5419 if (read_and_refresh_cache(r, opts))
5420 return -1;
5422 if (read_populate_opts(opts))
5423 return -1;
5424 if (is_rebase_i(opts)) {
5425 if ((res = read_populate_todo(r, &todo_list, opts)))
5426 goto release_todo_list;
5428 if (file_exists(rebase_path_dropped())) {
5429 if ((res = todo_list_check_against_backup(r, opts,
5430 &todo_list)))
5431 goto release_todo_list;
5433 unlink(rebase_path_dropped());
5436 ctx->reflog_message = reflog_message(opts, "continue", NULL);
5437 if (commit_staged_changes(r, opts, &todo_list)) {
5438 res = -1;
5439 goto release_todo_list;
5441 } else if (!file_exists(get_todo_path(opts)))
5442 return continue_single_pick(r, opts);
5443 else if ((res = read_populate_todo(r, &todo_list, opts)))
5444 goto release_todo_list;
5446 if (!is_rebase_i(opts)) {
5447 /* Verify that the conflict has been resolved */
5448 if (refs_ref_exists(get_main_ref_store(r),
5449 "CHERRY_PICK_HEAD") ||
5450 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5451 res = continue_single_pick(r, opts);
5452 if (res)
5453 goto release_todo_list;
5455 if (index_differs_from(r, "HEAD", NULL, 0)) {
5456 res = error_dirty_index(r, opts);
5457 goto release_todo_list;
5459 todo_list.current++;
5460 } else if (file_exists(rebase_path_stopped_sha())) {
5461 struct strbuf buf = STRBUF_INIT;
5462 struct object_id oid;
5464 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5465 READ_ONELINER_SKIP_IF_EMPTY) &&
5466 !get_oid_hex(buf.buf, &oid))
5467 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5468 strbuf_release(&buf);
5471 res = pick_commits(r, &todo_list, opts);
5472 release_todo_list:
5473 todo_list_release(&todo_list);
5474 return res;
5477 static int single_pick(struct repository *r,
5478 struct commit *cmit,
5479 struct replay_opts *opts)
5481 int check_todo;
5482 struct todo_item item;
5484 item.command = opts->action == REPLAY_PICK ?
5485 TODO_PICK : TODO_REVERT;
5486 item.commit = cmit;
5488 opts->ctx->reflog_message = sequencer_reflog_action(opts);
5489 return do_pick_commit(r, &item, opts, 0, &check_todo);
5492 int sequencer_pick_revisions(struct repository *r,
5493 struct replay_opts *opts)
5495 struct todo_list todo_list = TODO_LIST_INIT;
5496 struct object_id oid;
5497 int i, res;
5499 assert(opts->revs);
5500 if (read_and_refresh_cache(r, opts)) {
5501 res = -1;
5502 goto out;
5505 for (i = 0; i < opts->revs->pending.nr; i++) {
5506 struct object_id oid;
5507 const char *name = opts->revs->pending.objects[i].name;
5509 /* This happens when using --stdin. */
5510 if (!strlen(name))
5511 continue;
5513 if (!repo_get_oid(r, name, &oid)) {
5514 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5515 enum object_type type = oid_object_info(r,
5516 &oid,
5517 NULL);
5518 res = error(_("%s: can't cherry-pick a %s"),
5519 name, type_name(type));
5520 goto out;
5522 } else {
5523 res = error(_("%s: bad revision"), name);
5524 goto out;
5529 * If we were called as "git cherry-pick <commit>", just
5530 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5531 * REVERT_HEAD, and don't touch the sequencer state.
5532 * This means it is possible to cherry-pick in the middle
5533 * of a cherry-pick sequence.
5535 if (opts->revs->cmdline.nr == 1 &&
5536 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5537 opts->revs->no_walk &&
5538 !opts->revs->cmdline.rev->flags) {
5539 struct commit *cmit;
5541 if (prepare_revision_walk(opts->revs)) {
5542 res = error(_("revision walk setup failed"));
5543 goto out;
5546 cmit = get_revision(opts->revs);
5547 if (!cmit) {
5548 res = error(_("empty commit set passed"));
5549 goto out;
5552 if (get_revision(opts->revs))
5553 BUG("unexpected extra commit from walk");
5555 res = single_pick(r, cmit, opts);
5556 goto out;
5560 * Start a new cherry-pick/ revert sequence; but
5561 * first, make sure that an existing one isn't in
5562 * progress
5565 if (walk_revs_populate_todo(&todo_list, opts) ||
5566 create_seq_dir(r) < 0) {
5567 res = -1;
5568 goto out;
5571 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT)) {
5572 res = error(_("can't revert as initial commit"));
5573 goto out;
5576 if (save_head(oid_to_hex(&oid))) {
5577 res = -1;
5578 goto out;
5581 if (save_opts(opts)) {
5582 res = -1;
5583 goto out;
5586 update_abort_safety_file();
5587 res = pick_commits(r, &todo_list, opts);
5589 out:
5590 todo_list_release(&todo_list);
5591 return res;
5594 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5596 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5597 struct strbuf sob = STRBUF_INIT;
5598 int has_footer;
5600 strbuf_addstr(&sob, sign_off_header);
5601 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5602 strbuf_addch(&sob, '\n');
5604 if (!ignore_footer)
5605 strbuf_complete_line(msgbuf);
5608 * If the whole message buffer is equal to the sob, pretend that we
5609 * found a conforming footer with a matching sob
5611 if (msgbuf->len - ignore_footer == sob.len &&
5612 !strncmp(msgbuf->buf, sob.buf, sob.len))
5613 has_footer = 3;
5614 else
5615 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5617 if (!has_footer) {
5618 const char *append_newlines = NULL;
5619 size_t len = msgbuf->len - ignore_footer;
5621 if (!len) {
5623 * The buffer is completely empty. Leave foom for
5624 * the title and body to be filled in by the user.
5626 append_newlines = "\n\n";
5627 } else if (len == 1) {
5629 * Buffer contains a single newline. Add another
5630 * so that we leave room for the title and body.
5632 append_newlines = "\n";
5633 } else if (msgbuf->buf[len - 2] != '\n') {
5635 * Buffer ends with a single newline. Add another
5636 * so that there is an empty line between the message
5637 * body and the sob.
5639 append_newlines = "\n";
5640 } /* else, the buffer already ends with two newlines. */
5642 if (append_newlines)
5643 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5644 append_newlines, strlen(append_newlines));
5647 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5648 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5649 sob.buf, sob.len);
5651 strbuf_release(&sob);
5654 struct labels_entry {
5655 struct hashmap_entry entry;
5656 char label[FLEX_ARRAY];
5659 static int labels_cmp(const void *fndata UNUSED,
5660 const struct hashmap_entry *eptr,
5661 const struct hashmap_entry *entry_or_key, const void *key)
5663 const struct labels_entry *a, *b;
5665 a = container_of(eptr, const struct labels_entry, entry);
5666 b = container_of(entry_or_key, const struct labels_entry, entry);
5668 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5671 struct string_entry {
5672 struct oidmap_entry entry;
5673 char string[FLEX_ARRAY];
5676 struct label_state {
5677 struct oidmap commit2label;
5678 struct hashmap labels;
5679 struct strbuf buf;
5680 int max_label_length;
5683 static const char *label_oid(struct object_id *oid, const char *label,
5684 struct label_state *state)
5686 struct labels_entry *labels_entry;
5687 struct string_entry *string_entry;
5688 struct object_id dummy;
5689 int i;
5691 string_entry = oidmap_get(&state->commit2label, oid);
5692 if (string_entry)
5693 return string_entry->string;
5696 * For "uninteresting" commits, i.e. commits that are not to be
5697 * rebased, and which can therefore not be labeled, we use a unique
5698 * abbreviation of the commit name. This is slightly more complicated
5699 * than calling repo_find_unique_abbrev() because we also need to make
5700 * sure that the abbreviation does not conflict with any other
5701 * label.
5703 * We disallow "interesting" commits to be labeled by a string that
5704 * is a valid full-length hash, to ensure that we always can find an
5705 * abbreviation for any uninteresting commit's names that does not
5706 * clash with any other label.
5708 strbuf_reset(&state->buf);
5709 if (!label) {
5710 char *p;
5712 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5713 label = p = state->buf.buf;
5715 repo_find_unique_abbrev_r(the_repository, p, oid,
5716 default_abbrev);
5719 * We may need to extend the abbreviated hash so that there is
5720 * no conflicting label.
5722 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5723 size_t i = strlen(p) + 1;
5725 oid_to_hex_r(p, oid);
5726 for (; i < the_hash_algo->hexsz; i++) {
5727 char save = p[i];
5728 p[i] = '\0';
5729 if (!hashmap_get_from_hash(&state->labels,
5730 strihash(p), p))
5731 break;
5732 p[i] = save;
5735 } else {
5736 struct strbuf *buf = &state->buf;
5737 int label_is_utf8 = 1; /* start with this assumption */
5738 size_t max_len = buf->len + state->max_label_length;
5741 * Sanitize labels by replacing non-alpha-numeric characters
5742 * (including white-space ones) by dashes, as they might be
5743 * illegal in file names (and hence in ref names).
5745 * Note that we retain non-ASCII UTF-8 characters (identified
5746 * via the most significant bit). They should be all acceptable
5747 * in file names.
5749 * As we will use the labels as names of (loose) refs, it is
5750 * vital that the name not be longer than the maximum component
5751 * size of the file system (`NAME_MAX`). We are careful to
5752 * truncate the label accordingly, allowing for the `.lock`
5753 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5754 * truncating in the middle of a character).
5756 for (; *label && buf->len + 1 < max_len; label++)
5757 if (isalnum(*label) ||
5758 (!label_is_utf8 && (*label & 0x80)))
5759 strbuf_addch(buf, *label);
5760 else if (*label & 0x80) {
5761 const char *p = label;
5763 utf8_width(&p, NULL);
5764 if (p) {
5765 if (buf->len + (p - label) > max_len)
5766 break;
5767 strbuf_add(buf, label, p - label);
5768 label = p - 1;
5769 } else {
5770 label_is_utf8 = 0;
5771 strbuf_addch(buf, *label);
5773 /* avoid leading dash and double-dashes */
5774 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5775 strbuf_addch(buf, '-');
5776 if (!buf->len) {
5777 strbuf_addstr(buf, "rev-");
5778 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5780 label = buf->buf;
5782 if ((buf->len == the_hash_algo->hexsz &&
5783 !get_oid_hex(label, &dummy)) ||
5784 (buf->len == 1 && *label == '#') ||
5785 hashmap_get_from_hash(&state->labels,
5786 strihash(label), label)) {
5788 * If the label already exists, or if the label is a
5789 * valid full OID, or the label is a '#' (which we use
5790 * as a separator between merge heads and oneline), we
5791 * append a dash and a number to make it unique.
5793 size_t len = buf->len;
5795 for (i = 2; ; i++) {
5796 strbuf_setlen(buf, len);
5797 strbuf_addf(buf, "-%d", i);
5798 if (!hashmap_get_from_hash(&state->labels,
5799 strihash(buf->buf),
5800 buf->buf))
5801 break;
5804 label = buf->buf;
5808 FLEX_ALLOC_STR(labels_entry, label, label);
5809 hashmap_entry_init(&labels_entry->entry, strihash(label));
5810 hashmap_add(&state->labels, &labels_entry->entry);
5812 FLEX_ALLOC_STR(string_entry, string, label);
5813 oidcpy(&string_entry->entry.oid, oid);
5814 oidmap_put(&state->commit2label, string_entry);
5816 return string_entry->string;
5819 static int make_script_with_merges(struct pretty_print_context *pp,
5820 struct rev_info *revs, struct strbuf *out,
5821 unsigned flags)
5823 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5824 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5825 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5826 int skipped_commit = 0;
5827 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5828 struct strbuf label_from_message = STRBUF_INIT;
5829 struct commit_list *commits = NULL, **tail = &commits, *iter;
5830 struct commit_list *tips = NULL, **tips_tail = &tips;
5831 struct commit *commit;
5832 struct oidmap commit2todo = OIDMAP_INIT;
5833 struct string_entry *entry;
5834 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5835 shown = OIDSET_INIT;
5836 struct label_state state =
5837 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5839 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5840 const char *cmd_pick = abbr ? "p" : "pick",
5841 *cmd_label = abbr ? "l" : "label",
5842 *cmd_reset = abbr ? "t" : "reset",
5843 *cmd_merge = abbr ? "m" : "merge";
5845 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5847 oidmap_init(&commit2todo, 0);
5848 oidmap_init(&state.commit2label, 0);
5849 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5850 strbuf_init(&state.buf, 32);
5851 load_branch_decorations();
5853 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5854 struct labels_entry *onto_label_entry;
5855 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5856 FLEX_ALLOC_STR(entry, string, "onto");
5857 oidcpy(&entry->entry.oid, oid);
5858 oidmap_put(&state.commit2label, entry);
5860 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5861 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5862 hashmap_add(&state.labels, &onto_label_entry->entry);
5866 * First phase:
5867 * - get onelines for all commits
5868 * - gather all branch tips (i.e. 2nd or later parents of merges)
5869 * - label all branch tips
5871 while ((commit = get_revision(revs))) {
5872 struct commit_list *to_merge;
5873 const char *p1, *p2;
5874 struct object_id *oid;
5875 int is_empty;
5877 tail = &commit_list_insert(commit, tail)->next;
5878 oidset_insert(&interesting, &commit->object.oid);
5880 is_empty = is_original_commit_empty(commit);
5881 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5882 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5883 warning(_("skipped previously applied commit %s"),
5884 short_commit_name(the_repository, commit));
5885 skipped_commit = 1;
5886 continue;
5888 if (is_empty && !keep_empty)
5889 continue;
5891 strbuf_reset(&oneline);
5892 pretty_print_commit(pp, commit, &oneline);
5894 to_merge = commit->parents ? commit->parents->next : NULL;
5895 if (!to_merge) {
5896 /* non-merge commit: easy case */
5897 strbuf_reset(&buf);
5898 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5899 oid_to_hex(&commit->object.oid),
5900 oneline.buf);
5901 if (is_empty)
5902 strbuf_addf(&buf, " %s empty",
5903 comment_line_str);
5905 FLEX_ALLOC_STR(entry, string, buf.buf);
5906 oidcpy(&entry->entry.oid, &commit->object.oid);
5907 oidmap_put(&commit2todo, entry);
5909 continue;
5912 /* Create a label from the commit message */
5913 strbuf_reset(&label_from_message);
5914 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5915 (p1 = strchr(p1, '\'')) &&
5916 (p2 = strchr(++p1, '\'')))
5917 strbuf_add(&label_from_message, p1, p2 - p1);
5918 else if (skip_prefix(oneline.buf, "Merge pull request ",
5919 &p1) &&
5920 (p1 = strstr(p1, " from ")))
5921 strbuf_addstr(&label_from_message, p1 + strlen(" from "));
5922 else
5923 strbuf_addbuf(&label_from_message, &oneline);
5925 strbuf_reset(&buf);
5926 strbuf_addf(&buf, "%s -C %s",
5927 cmd_merge, oid_to_hex(&commit->object.oid));
5929 /* label the tips of merged branches */
5930 for (; to_merge; to_merge = to_merge->next) {
5931 const char *label = label_from_message.buf;
5932 const struct name_decoration *decoration =
5933 get_name_decoration(&to_merge->item->object);
5935 if (decoration)
5936 skip_prefix(decoration->name, "refs/heads/",
5937 &label);
5939 oid = &to_merge->item->object.oid;
5940 strbuf_addch(&buf, ' ');
5942 if (!oidset_contains(&interesting, oid)) {
5943 strbuf_addstr(&buf, label_oid(oid, NULL,
5944 &state));
5945 continue;
5948 tips_tail = &commit_list_insert(to_merge->item,
5949 tips_tail)->next;
5951 strbuf_addstr(&buf, label_oid(oid, label, &state));
5953 strbuf_addf(&buf, " # %s", oneline.buf);
5955 FLEX_ALLOC_STR(entry, string, buf.buf);
5956 oidcpy(&entry->entry.oid, &commit->object.oid);
5957 oidmap_put(&commit2todo, entry);
5959 if (skipped_commit)
5960 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5961 _("use --reapply-cherry-picks to include skipped commits"));
5964 * Second phase:
5965 * - label branch points
5966 * - add HEAD to the branch tips
5968 for (iter = commits; iter; iter = iter->next) {
5969 struct commit_list *parent = iter->item->parents;
5970 for (; parent; parent = parent->next) {
5971 struct object_id *oid = &parent->item->object.oid;
5972 if (!oidset_contains(&interesting, oid))
5973 continue;
5974 if (oidset_insert(&child_seen, oid))
5975 label_oid(oid, "branch-point", &state);
5978 /* Add HEAD as implicit "tip of branch" */
5979 if (!iter->next)
5980 tips_tail = &commit_list_insert(iter->item,
5981 tips_tail)->next;
5985 * Third phase: output the todo list. This is a bit tricky, as we
5986 * want to avoid jumping back and forth between revisions. To
5987 * accomplish that goal, we walk backwards from the branch tips,
5988 * gathering commits not yet shown, reversing the list on the fly,
5989 * then outputting that list (labeling revisions as needed).
5991 strbuf_addf(out, "%s onto\n", cmd_label);
5992 for (iter = tips; iter; iter = iter->next) {
5993 struct commit_list *list = NULL, *iter2;
5995 commit = iter->item;
5996 if (oidset_contains(&shown, &commit->object.oid))
5997 continue;
5998 entry = oidmap_get(&state.commit2label, &commit->object.oid);
6000 if (entry)
6001 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
6002 else
6003 strbuf_addch(out, '\n');
6005 while (oidset_contains(&interesting, &commit->object.oid) &&
6006 !oidset_contains(&shown, &commit->object.oid)) {
6007 commit_list_insert(commit, &list);
6008 if (!commit->parents) {
6009 commit = NULL;
6010 break;
6012 commit = commit->parents->item;
6015 if (!commit)
6016 strbuf_addf(out, "%s %s\n", cmd_reset,
6017 rebase_cousins || root_with_onto ?
6018 "onto" : "[new root]");
6019 else {
6020 const char *to = NULL;
6022 entry = oidmap_get(&state.commit2label,
6023 &commit->object.oid);
6024 if (entry)
6025 to = entry->string;
6026 else if (!rebase_cousins)
6027 to = label_oid(&commit->object.oid, NULL,
6028 &state);
6030 if (!to || !strcmp(to, "onto"))
6031 strbuf_addf(out, "%s onto\n", cmd_reset);
6032 else {
6033 strbuf_reset(&oneline);
6034 pretty_print_commit(pp, commit, &oneline);
6035 strbuf_addf(out, "%s %s # %s\n",
6036 cmd_reset, to, oneline.buf);
6040 for (iter2 = list; iter2; iter2 = iter2->next) {
6041 struct object_id *oid = &iter2->item->object.oid;
6042 entry = oidmap_get(&commit2todo, oid);
6043 /* only show if not already upstream */
6044 if (entry)
6045 strbuf_addf(out, "%s\n", entry->string);
6046 entry = oidmap_get(&state.commit2label, oid);
6047 if (entry)
6048 strbuf_addf(out, "%s %s\n",
6049 cmd_label, entry->string);
6050 oidset_insert(&shown, oid);
6053 free_commit_list(list);
6056 free_commit_list(commits);
6057 free_commit_list(tips);
6059 strbuf_release(&label_from_message);
6060 strbuf_release(&oneline);
6061 strbuf_release(&buf);
6063 oidset_clear(&interesting);
6064 oidset_clear(&child_seen);
6065 oidset_clear(&shown);
6066 oidmap_free(&commit2todo, 1);
6067 oidmap_free(&state.commit2label, 1);
6068 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
6069 strbuf_release(&state.buf);
6071 return 0;
6074 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
6075 const char **argv, unsigned flags)
6077 char *format = NULL;
6078 struct pretty_print_context pp = {0};
6079 struct rev_info revs;
6080 struct commit *commit;
6081 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
6082 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
6083 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
6084 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
6085 int skipped_commit = 0;
6086 int ret = 0;
6088 repo_init_revisions(r, &revs, NULL);
6089 revs.verbose_header = 1;
6090 if (!rebase_merges)
6091 revs.max_parents = 1;
6092 revs.cherry_mark = !reapply_cherry_picks;
6093 revs.limited = 1;
6094 revs.reverse = 1;
6095 revs.right_only = 1;
6096 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
6097 revs.topo_order = 1;
6099 revs.pretty_given = 1;
6100 git_config_get_string("rebase.instructionFormat", &format);
6101 if (!format || !*format) {
6102 free(format);
6103 format = xstrdup("%s");
6105 get_commit_format(format, &revs);
6106 free(format);
6107 pp.fmt = revs.commit_format;
6108 pp.output_encoding = get_log_output_encoding();
6110 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
6111 ret = error(_("make_script: unhandled options"));
6112 goto cleanup;
6115 if (prepare_revision_walk(&revs) < 0) {
6116 ret = error(_("make_script: error preparing revisions"));
6117 goto cleanup;
6120 if (rebase_merges) {
6121 ret = make_script_with_merges(&pp, &revs, out, flags);
6122 goto cleanup;
6125 while ((commit = get_revision(&revs))) {
6126 int is_empty = is_original_commit_empty(commit);
6128 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6129 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6130 warning(_("skipped previously applied commit %s"),
6131 short_commit_name(r, commit));
6132 skipped_commit = 1;
6133 continue;
6135 if (is_empty && !keep_empty)
6136 continue;
6137 strbuf_addf(out, "%s %s ", insn,
6138 oid_to_hex(&commit->object.oid));
6139 pretty_print_commit(&pp, commit, out);
6140 if (is_empty)
6141 strbuf_addf(out, " %s empty", comment_line_str);
6142 strbuf_addch(out, '\n');
6144 if (skipped_commit)
6145 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6146 _("use --reapply-cherry-picks to include skipped commits"));
6147 cleanup:
6148 release_revisions(&revs);
6149 return ret;
6153 * Add commands after pick and (series of) squash/fixup commands
6154 * in the todo list.
6156 static void todo_list_add_exec_commands(struct todo_list *todo_list,
6157 struct string_list *commands)
6159 struct strbuf *buf = &todo_list->buf;
6160 size_t base_offset = buf->len;
6161 int i, insert, nr = 0, alloc = 0;
6162 struct todo_item *items = NULL, *base_items = NULL;
6164 CALLOC_ARRAY(base_items, commands->nr);
6165 for (i = 0; i < commands->nr; i++) {
6166 size_t command_len = strlen(commands->items[i].string);
6168 strbuf_addstr(buf, commands->items[i].string);
6169 strbuf_addch(buf, '\n');
6171 base_items[i].command = TODO_EXEC;
6172 base_items[i].offset_in_buf = base_offset;
6173 base_items[i].arg_offset = base_offset;
6174 base_items[i].arg_len = command_len;
6176 base_offset += command_len + 1;
6180 * Insert <commands> after every pick. Here, fixup/squash chains
6181 * are considered part of the pick, so we insert the commands *after*
6182 * those chains if there are any.
6184 * As we insert the exec commands immediately after rearranging
6185 * any fixups and before the user edits the list, a fixup chain
6186 * can never contain comments (any comments are empty picks that
6187 * have been commented out because the user did not specify
6188 * --keep-empty). So, it is safe to insert an exec command
6189 * without looking at the command following a comment.
6191 insert = 0;
6192 for (i = 0; i < todo_list->nr; i++) {
6193 enum todo_command command = todo_list->items[i].command;
6194 if (insert && !is_fixup(command)) {
6195 ALLOC_GROW(items, nr + commands->nr, alloc);
6196 COPY_ARRAY(items + nr, base_items, commands->nr);
6197 nr += commands->nr;
6199 insert = 0;
6202 ALLOC_GROW(items, nr + 1, alloc);
6203 items[nr++] = todo_list->items[i];
6205 if (command == TODO_PICK || command == TODO_MERGE)
6206 insert = 1;
6209 /* insert or append final <commands> */
6210 if (insert) {
6211 ALLOC_GROW(items, nr + commands->nr, alloc);
6212 COPY_ARRAY(items + nr, base_items, commands->nr);
6213 nr += commands->nr;
6216 free(base_items);
6217 FREE_AND_NULL(todo_list->items);
6218 todo_list->items = items;
6219 todo_list->nr = nr;
6220 todo_list->alloc = alloc;
6223 static void todo_list_to_strbuf(struct repository *r,
6224 struct todo_list *todo_list,
6225 struct strbuf *buf, int num, unsigned flags)
6227 struct todo_item *item;
6228 int i, max = todo_list->nr;
6230 if (num > 0 && num < max)
6231 max = num;
6233 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6234 char cmd;
6236 /* if the item is not a command write it and continue */
6237 if (item->command >= TODO_COMMENT) {
6238 strbuf_addf(buf, "%.*s\n", item->arg_len,
6239 todo_item_get_arg(todo_list, item));
6240 continue;
6243 /* add command to the buffer */
6244 cmd = command_to_char(item->command);
6245 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6246 strbuf_addch(buf, cmd);
6247 else
6248 strbuf_addstr(buf, command_to_string(item->command));
6250 /* add commit id */
6251 if (item->commit) {
6252 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6253 short_commit_name(r, item->commit) :
6254 oid_to_hex(&item->commit->object.oid);
6256 if (item->command == TODO_FIXUP) {
6257 if (item->flags & TODO_EDIT_FIXUP_MSG)
6258 strbuf_addstr(buf, " -c");
6259 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6260 strbuf_addstr(buf, " -C");
6264 if (item->command == TODO_MERGE) {
6265 if (item->flags & TODO_EDIT_MERGE_MSG)
6266 strbuf_addstr(buf, " -c");
6267 else
6268 strbuf_addstr(buf, " -C");
6271 strbuf_addf(buf, " %s", oid);
6274 /* add all the rest */
6275 if (!item->arg_len)
6276 strbuf_addch(buf, '\n');
6277 else
6278 strbuf_addf(buf, " %.*s\n", item->arg_len,
6279 todo_item_get_arg(todo_list, item));
6283 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6284 const char *file, const char *shortrevisions,
6285 const char *shortonto, int num, unsigned flags)
6287 int res;
6288 struct strbuf buf = STRBUF_INIT;
6290 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6291 if (flags & TODO_LIST_APPEND_TODO_HELP)
6292 append_todo_help(count_commands(todo_list),
6293 shortrevisions, shortonto, &buf);
6295 res = write_message(buf.buf, buf.len, file, 0);
6296 strbuf_release(&buf);
6298 return res;
6301 /* skip picking commits whose parents are unchanged */
6302 static int skip_unnecessary_picks(struct repository *r,
6303 struct todo_list *todo_list,
6304 struct object_id *base_oid)
6306 struct object_id *parent_oid;
6307 int i;
6309 for (i = 0; i < todo_list->nr; i++) {
6310 struct todo_item *item = todo_list->items + i;
6312 if (item->command >= TODO_NOOP)
6313 continue;
6314 if (item->command != TODO_PICK)
6315 break;
6316 if (repo_parse_commit(r, item->commit)) {
6317 return error(_("could not parse commit '%s'"),
6318 oid_to_hex(&item->commit->object.oid));
6320 if (!item->commit->parents)
6321 break; /* root commit */
6322 if (item->commit->parents->next)
6323 break; /* merge commit */
6324 parent_oid = &item->commit->parents->item->object.oid;
6325 if (!oideq(parent_oid, base_oid))
6326 break;
6327 oidcpy(base_oid, &item->commit->object.oid);
6329 if (i > 0) {
6330 const char *done_path = rebase_path_done();
6332 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6333 error_errno(_("could not write to '%s'"), done_path);
6334 return -1;
6337 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6338 todo_list->nr -= i;
6339 todo_list->current = 0;
6340 todo_list->done_nr += i;
6342 if (is_fixup(peek_command(todo_list, 0)))
6343 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6346 return 0;
6349 struct todo_add_branch_context {
6350 struct todo_item *items;
6351 size_t items_nr;
6352 size_t items_alloc;
6353 struct strbuf *buf;
6354 struct commit *commit;
6355 struct string_list refs_to_oids;
6358 static int add_decorations_to_list(const struct commit *commit,
6359 struct todo_add_branch_context *ctx)
6361 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6362 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
6363 "HEAD",
6364 RESOLVE_REF_READING,
6365 NULL,
6366 NULL);
6368 while (decoration) {
6369 struct todo_item *item;
6370 const char *path;
6371 size_t base_offset = ctx->buf->len;
6374 * If the branch is the current HEAD, then it will be
6375 * updated by the default rebase behavior.
6377 if (head_ref && !strcmp(head_ref, decoration->name)) {
6378 decoration = decoration->next;
6379 continue;
6382 ALLOC_GROW(ctx->items,
6383 ctx->items_nr + 1,
6384 ctx->items_alloc);
6385 item = &ctx->items[ctx->items_nr];
6386 memset(item, 0, sizeof(*item));
6388 /* If the branch is checked out, then leave a comment instead. */
6389 if ((path = branch_checked_out(decoration->name))) {
6390 item->command = TODO_COMMENT;
6391 strbuf_commented_addf(ctx->buf, comment_line_str,
6392 "Ref %s checked out at '%s'\n",
6393 decoration->name, path);
6394 } else {
6395 struct string_list_item *sti;
6396 item->command = TODO_UPDATE_REF;
6397 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6399 sti = string_list_insert(&ctx->refs_to_oids,
6400 decoration->name);
6401 sti->util = init_update_ref_record(decoration->name);
6404 item->offset_in_buf = base_offset;
6405 item->arg_offset = base_offset;
6406 item->arg_len = ctx->buf->len - base_offset;
6407 ctx->items_nr++;
6409 decoration = decoration->next;
6412 return 0;
6416 * For each 'pick' command, find out if the commit has a decoration in
6417 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6419 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6421 int i, res;
6422 struct todo_add_branch_context ctx = {
6423 .buf = &todo_list->buf,
6424 .refs_to_oids = STRING_LIST_INIT_DUP,
6427 ctx.items_alloc = 2 * todo_list->nr + 1;
6428 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6430 load_branch_decorations();
6432 for (i = 0; i < todo_list->nr; ) {
6433 struct todo_item *item = &todo_list->items[i];
6435 /* insert ith item into new list */
6436 ALLOC_GROW(ctx.items,
6437 ctx.items_nr + 1,
6438 ctx.items_alloc);
6440 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6442 if (item->commit) {
6443 ctx.commit = item->commit;
6444 add_decorations_to_list(item->commit, &ctx);
6448 res = write_update_refs_state(&ctx.refs_to_oids);
6450 string_list_clear(&ctx.refs_to_oids, 1);
6452 if (res) {
6453 /* we failed, so clean up the new list. */
6454 free(ctx.items);
6455 return res;
6458 free(todo_list->items);
6459 todo_list->items = ctx.items;
6460 todo_list->nr = ctx.items_nr;
6461 todo_list->alloc = ctx.items_alloc;
6463 return 0;
6466 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6467 const char *shortrevisions, const char *onto_name,
6468 struct commit *onto, const struct object_id *orig_head,
6469 struct string_list *commands, unsigned autosquash,
6470 unsigned update_refs,
6471 struct todo_list *todo_list)
6473 char shortonto[GIT_MAX_HEXSZ + 1];
6474 const char *todo_file = rebase_path_todo();
6475 struct todo_list new_todo = TODO_LIST_INIT;
6476 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6477 struct object_id oid = onto->object.oid;
6478 int res;
6480 repo_find_unique_abbrev_r(r, shortonto, &oid,
6481 DEFAULT_ABBREV);
6483 if (buf->len == 0) {
6484 struct todo_item *item = append_new_todo(todo_list);
6485 item->command = TODO_NOOP;
6486 item->commit = NULL;
6487 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6490 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6491 return -1;
6493 if (autosquash && todo_list_rearrange_squash(todo_list))
6494 return -1;
6496 if (commands->nr)
6497 todo_list_add_exec_commands(todo_list, commands);
6499 if (count_commands(todo_list) == 0) {
6500 apply_autostash(rebase_path_autostash());
6501 sequencer_remove_state(opts);
6503 return error(_("nothing to do"));
6506 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions,
6507 shortonto, flags);
6508 if (res == -1)
6509 return -1;
6510 else if (res == -2) {
6511 apply_autostash(rebase_path_autostash());
6512 sequencer_remove_state(opts);
6514 return -1;
6515 } else if (res == -3) {
6516 apply_autostash(rebase_path_autostash());
6517 sequencer_remove_state(opts);
6518 todo_list_release(&new_todo);
6520 return error(_("nothing to do"));
6521 } else if (res == -4) {
6522 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6523 todo_list_release(&new_todo);
6525 return -1;
6528 /* Expand the commit IDs */
6529 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6530 strbuf_swap(&new_todo.buf, &buf2);
6531 strbuf_release(&buf2);
6532 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6533 new_todo.total_nr = 0;
6534 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0)
6535 BUG("invalid todo list after expanding IDs:\n%s",
6536 new_todo.buf.buf);
6538 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6539 todo_list_release(&new_todo);
6540 return error(_("could not skip unnecessary pick commands"));
6543 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6544 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6545 todo_list_release(&new_todo);
6546 return error_errno(_("could not write '%s'"), todo_file);
6549 res = -1;
6551 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6552 goto cleanup;
6554 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6555 goto cleanup;
6557 todo_list_write_total_nr(&new_todo);
6558 res = pick_commits(r, &new_todo, opts);
6560 cleanup:
6561 todo_list_release(&new_todo);
6563 return res;
6566 struct subject2item_entry {
6567 struct hashmap_entry entry;
6568 int i;
6569 char subject[FLEX_ARRAY];
6572 static int subject2item_cmp(const void *fndata UNUSED,
6573 const struct hashmap_entry *eptr,
6574 const struct hashmap_entry *entry_or_key,
6575 const void *key)
6577 const struct subject2item_entry *a, *b;
6579 a = container_of(eptr, const struct subject2item_entry, entry);
6580 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6582 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6585 define_commit_slab(commit_todo_item, struct todo_item *);
6587 static int skip_fixupish(const char *subject, const char **p) {
6588 return skip_prefix(subject, "fixup! ", p) ||
6589 skip_prefix(subject, "amend! ", p) ||
6590 skip_prefix(subject, "squash! ", p);
6594 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6595 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6596 * after the former, and change "pick" to "fixup"/"squash".
6598 * Note that if the config has specified a custom instruction format, each log
6599 * message will have to be retrieved from the commit (as the oneline in the
6600 * script cannot be trusted) in order to normalize the autosquash arrangement.
6602 int todo_list_rearrange_squash(struct todo_list *todo_list)
6604 struct hashmap subject2item;
6605 int rearranged = 0, *next, *tail, i, nr = 0;
6606 char **subjects;
6607 struct commit_todo_item commit_todo;
6608 struct todo_item *items = NULL;
6610 init_commit_todo_item(&commit_todo);
6612 * The hashmap maps onelines to the respective todo list index.
6614 * If any items need to be rearranged, the next[i] value will indicate
6615 * which item was moved directly after the i'th.
6617 * In that case, last[i] will indicate the index of the latest item to
6618 * be moved to appear after the i'th.
6620 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6621 ALLOC_ARRAY(next, todo_list->nr);
6622 ALLOC_ARRAY(tail, todo_list->nr);
6623 ALLOC_ARRAY(subjects, todo_list->nr);
6624 for (i = 0; i < todo_list->nr; i++) {
6625 struct strbuf buf = STRBUF_INIT;
6626 struct todo_item *item = todo_list->items + i;
6627 const char *commit_buffer, *subject, *p;
6628 size_t subject_len;
6629 int i2 = -1;
6630 struct subject2item_entry *entry;
6632 next[i] = tail[i] = -1;
6633 if (!item->commit || item->command == TODO_DROP) {
6634 subjects[i] = NULL;
6635 continue;
6638 if (is_fixup(item->command)) {
6639 clear_commit_todo_item(&commit_todo);
6640 return error(_("the script was already rearranged."));
6643 repo_parse_commit(the_repository, item->commit);
6644 commit_buffer = repo_logmsg_reencode(the_repository,
6645 item->commit, NULL,
6646 "UTF-8");
6647 find_commit_subject(commit_buffer, &subject);
6648 format_subject(&buf, subject, " ");
6649 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6650 repo_unuse_commit_buffer(the_repository, item->commit,
6651 commit_buffer);
6652 if (skip_fixupish(subject, &p)) {
6653 struct commit *commit2;
6655 for (;;) {
6656 while (isspace(*p))
6657 p++;
6658 if (!skip_fixupish(p, &p))
6659 break;
6662 entry = hashmap_get_entry_from_hash(&subject2item,
6663 strhash(p), p,
6664 struct subject2item_entry,
6665 entry);
6666 if (entry)
6667 /* found by title */
6668 i2 = entry->i;
6669 else if (!strchr(p, ' ') &&
6670 (commit2 =
6671 lookup_commit_reference_by_name(p)) &&
6672 *commit_todo_item_at(&commit_todo, commit2))
6673 /* found by commit name */
6674 i2 = *commit_todo_item_at(&commit_todo, commit2)
6675 - todo_list->items;
6676 else {
6677 /* copy can be a prefix of the commit subject */
6678 for (i2 = 0; i2 < i; i2++)
6679 if (subjects[i2] &&
6680 starts_with(subjects[i2], p))
6681 break;
6682 if (i2 == i)
6683 i2 = -1;
6686 if (i2 >= 0) {
6687 rearranged = 1;
6688 if (starts_with(subject, "fixup!")) {
6689 todo_list->items[i].command = TODO_FIXUP;
6690 } else if (starts_with(subject, "amend!")) {
6691 todo_list->items[i].command = TODO_FIXUP;
6692 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6693 } else {
6694 todo_list->items[i].command = TODO_SQUASH;
6696 if (tail[i2] < 0) {
6697 next[i] = next[i2];
6698 next[i2] = i;
6699 } else {
6700 next[i] = next[tail[i2]];
6701 next[tail[i2]] = i;
6703 tail[i2] = i;
6704 } else if (!hashmap_get_from_hash(&subject2item,
6705 strhash(subject), subject)) {
6706 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6707 entry->i = i;
6708 hashmap_entry_init(&entry->entry,
6709 strhash(entry->subject));
6710 hashmap_put(&subject2item, &entry->entry);
6713 *commit_todo_item_at(&commit_todo, item->commit) = item;
6716 if (rearranged) {
6717 ALLOC_ARRAY(items, todo_list->nr);
6719 for (i = 0; i < todo_list->nr; i++) {
6720 enum todo_command command = todo_list->items[i].command;
6721 int cur = i;
6724 * Initially, all commands are 'pick's. If it is a
6725 * fixup or a squash now, we have rearranged it.
6727 if (is_fixup(command))
6728 continue;
6730 while (cur >= 0) {
6731 items[nr++] = todo_list->items[cur];
6732 cur = next[cur];
6736 assert(nr == todo_list->nr);
6737 todo_list->alloc = nr;
6738 FREE_AND_NULL(todo_list->items);
6739 todo_list->items = items;
6742 free(next);
6743 free(tail);
6744 for (i = 0; i < todo_list->nr; i++)
6745 free(subjects[i]);
6746 free(subjects);
6747 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6749 clear_commit_todo_item(&commit_todo);
6751 return 0;
6754 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6756 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6757 struct object_id cherry_pick_head, rebase_head;
6759 if (file_exists(git_path_seq_dir()))
6760 *whence = FROM_CHERRY_PICK_MULTI;
6761 if (file_exists(rebase_path()) &&
6762 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6763 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6764 oideq(&rebase_head, &cherry_pick_head))
6765 *whence = FROM_REBASE_PICK;
6766 else
6767 *whence = FROM_CHERRY_PICK_SINGLE;
6769 return 1;
6772 return 0;
6775 int sequencer_get_update_refs_state(const char *wt_dir,
6776 struct string_list *refs)
6778 int result = 0;
6779 FILE *fp = NULL;
6780 struct strbuf ref = STRBUF_INIT;
6781 struct strbuf hash = STRBUF_INIT;
6782 struct update_ref_record *rec = NULL;
6784 char *path = rebase_path_update_refs(wt_dir);
6786 fp = fopen(path, "r");
6787 if (!fp)
6788 goto cleanup;
6790 while (strbuf_getline(&ref, fp) != EOF) {
6791 struct string_list_item *item;
6793 CALLOC_ARRAY(rec, 1);
6795 if (strbuf_getline(&hash, fp) == EOF ||
6796 get_oid_hex(hash.buf, &rec->before)) {
6797 warning(_("update-refs file at '%s' is invalid"),
6798 path);
6799 result = -1;
6800 goto cleanup;
6803 if (strbuf_getline(&hash, fp) == EOF ||
6804 get_oid_hex(hash.buf, &rec->after)) {
6805 warning(_("update-refs file at '%s' is invalid"),
6806 path);
6807 result = -1;
6808 goto cleanup;
6811 item = string_list_insert(refs, ref.buf);
6812 item->util = rec;
6813 rec = NULL;
6816 cleanup:
6817 if (fp)
6818 fclose(fp);
6819 free(path);
6820 free(rec);
6821 strbuf_release(&ref);
6822 strbuf_release(&hash);
6823 return result;