chainlint.pl: add test_expect_success call to test snippets
[alt-git.git] / sequencer.c
blobc6a5ccf6ddbe51c7cffda8263d8b7072068b4d40
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "config.h"
5 #include "copy.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
14 #include "object.h"
15 #include "pager.h"
16 #include "commit.h"
17 #include "sequencer.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "utf8.h"
21 #include "cache-tree.h"
22 #include "diff.h"
23 #include "path.h"
24 #include "revision.h"
25 #include "rerere.h"
26 #include "merge.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
29 #include "refs.h"
30 #include "sparse-index.h"
31 #include "strvec.h"
32 #include "quote.h"
33 #include "trailer.h"
34 #include "log-tree.h"
35 #include "wt-status.h"
36 #include "hashmap.h"
37 #include "notes-utils.h"
38 #include "sigchain.h"
39 #include "unpack-trees.h"
40 #include "oidmap.h"
41 #include "oidset.h"
42 #include "commit-slab.h"
43 #include "alias.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
46 #include "reset.h"
47 #include "branch.h"
49 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 * To accommodate common filesystem limitations, where the loose refs' file
53 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
54 * --rebase-merges` need to be truncated if the corresponding commit subjects
55 * are too long.
56 * Add some margin to stay clear from reaching `NAME_MAX`.
58 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
60 static const char sign_off_header[] = "Signed-off-by: ";
61 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
63 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
65 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
67 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
68 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
69 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
70 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
72 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
74 * The file containing rebase commands, comments, and empty lines.
75 * This file is created by "git rebase -i" then edited by the user. As
76 * the lines are processed, they are removed from the front of this
77 * file and written to the tail of 'done'.
79 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
80 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
82 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
85 * The rebase command lines that have already been processed. A line
86 * is moved here when it is first handled, before any associated user
87 * actions.
89 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
91 * The file to keep track of how many commands were already processed (e.g.
92 * for the prompt).
94 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
96 * The file to keep track of how many commands are to be processed in total
97 * (e.g. for the prompt).
99 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
101 * The commit message that is planned to be used for any changes that
102 * need to be committed following a user interaction.
104 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
106 * The file into which is accumulated the suggested commit message for
107 * squash/fixup commands. When the first of a series of squash/fixups
108 * is seen, the file is created and the commit message from the
109 * previous commit and from the first squash/fixup commit are written
110 * to it. The commit message for each subsequent squash/fixup commit
111 * is appended to the file as it is processed.
113 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
115 * If the current series of squash/fixups has not yet included a squash
116 * command, then this file exists and holds the commit message of the
117 * original "pick" commit. (If the series ends without a "squash"
118 * command, then this can be used as the commit message of the combined
119 * commit without opening the editor.)
121 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
123 * This file contains the list fixup/squash commands that have been
124 * accumulated into message-fixup or message-squash so far.
126 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
128 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
129 * GIT_AUTHOR_DATE that will be used for the commit that is currently
130 * being rebased.
132 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
134 * When an "edit" rebase command is being processed, the SHA1 of the
135 * commit to be edited is recorded in this file. When "git rebase
136 * --continue" is executed, if there are any staged changes then they
137 * will be amended to the HEAD commit, but only provided the HEAD
138 * commit is still the commit to be edited. When any other rebase
139 * command is processed, this file is deleted.
141 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
143 * When we stop at a given patch via the "edit" command, this file contains
144 * the commit object name of the corresponding patch.
146 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
148 * When we stop for the user to resolve conflicts this file contains
149 * the patch of the commit that is being picked.
151 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
153 * For the post-rewrite hook, we make a list of rewritten commits and
154 * their new sha1s. The rewritten-pending list keeps the sha1s of
155 * commits that have been processed, but not committed yet,
156 * e.g. because they are waiting for a 'squash' command.
158 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
159 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
160 "rebase-merge/rewritten-pending")
163 * The path of the file containing the OID of the "squash onto" commit, i.e.
164 * the dummy commit used for `reset [new root]`.
166 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
169 * The path of the file listing refs that need to be deleted after the rebase
170 * finishes. This is used by the `label` command to record the need for cleanup.
172 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
175 * The update-refs file stores a list of refs that will be updated at the end
176 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
177 * update the OIDs for the refs in this file, but the refs are not updated
178 * until the end of the rebase sequence.
180 * rebase_path_update_refs() returns the path to this file for a given
181 * worktree directory. For the current worktree, pass the_repository->gitdir.
183 static char *rebase_path_update_refs(const char *wt_git_dir)
185 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
189 * The following files are written by git-rebase just after parsing the
190 * command-line.
192 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
193 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
194 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
195 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
196 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
197 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
198 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
199 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
200 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
201 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
202 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
203 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
204 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
205 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
206 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
207 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
208 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
211 * A 'struct replay_ctx' represents the private state of the sequencer.
213 struct replay_ctx {
215 * The commit message that will be used except at the end of a
216 * chain of fixup and squash commands.
218 struct strbuf message;
220 * The list of completed fixup and squash commands in the
221 * current chain.
223 struct strbuf current_fixups;
225 * Stores the reflog message that will be used when creating a
226 * commit. Points to a static buffer and should not be free()'d.
228 const char *reflog_message;
230 * The number of completed fixup and squash commands in the
231 * current chain.
233 int current_fixup_count;
235 * Whether message contains a commit message.
237 unsigned have_message :1;
240 struct replay_ctx* replay_ctx_new(void)
242 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
244 strbuf_init(&ctx->current_fixups, 0);
245 strbuf_init(&ctx->message, 0);
247 return ctx;
251 * A 'struct update_refs_record' represents a value in the update-refs
252 * list. We use a string_list to map refs to these (before, after) pairs.
254 struct update_ref_record {
255 struct object_id before;
256 struct object_id after;
259 static struct update_ref_record *init_update_ref_record(const char *ref)
261 struct update_ref_record *rec;
263 CALLOC_ARRAY(rec, 1);
265 oidcpy(&rec->before, null_oid());
266 oidcpy(&rec->after, null_oid());
268 /* This may fail, but that's fine, we will keep the null OID. */
269 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
271 return rec;
274 static int git_sequencer_config(const char *k, const char *v,
275 const struct config_context *ctx, void *cb)
277 struct replay_opts *opts = cb;
279 if (!strcmp(k, "commit.cleanup")) {
280 if (!v)
281 return config_error_nonbool(k);
283 if (!strcmp(v, "verbatim")) {
284 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
285 opts->explicit_cleanup = 1;
286 } else if (!strcmp(v, "whitespace")) {
287 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
288 opts->explicit_cleanup = 1;
289 } else if (!strcmp(v, "strip")) {
290 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
291 opts->explicit_cleanup = 1;
292 } else if (!strcmp(v, "scissors")) {
293 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
294 opts->explicit_cleanup = 1;
295 } else {
296 warning(_("invalid commit message cleanup mode '%s'"),
300 return 0;
303 if (!strcmp(k, "commit.gpgsign")) {
304 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
305 return 0;
308 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
309 int ret = git_config_string(&opts->default_strategy, k, v);
310 if (ret == 0) {
312 * pull.twohead is allowed to be multi-valued; we only
313 * care about the first value.
315 char *tmp = strchr(opts->default_strategy, ' ');
316 if (tmp)
317 *tmp = '\0';
319 return ret;
322 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
323 opts->commit_use_reference = git_config_bool(k, v);
325 return git_diff_basic_config(k, v, ctx, NULL);
328 void sequencer_init_config(struct replay_opts *opts)
330 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
331 git_config(git_sequencer_config, opts);
334 static inline int is_rebase_i(const struct replay_opts *opts)
336 return opts->action == REPLAY_INTERACTIVE_REBASE;
339 static const char *get_dir(const struct replay_opts *opts)
341 if (is_rebase_i(opts))
342 return rebase_path();
343 return git_path_seq_dir();
346 static const char *get_todo_path(const struct replay_opts *opts)
348 if (is_rebase_i(opts))
349 return rebase_path_todo();
350 return git_path_todo_file();
354 * Returns 0 for non-conforming footer
355 * Returns 1 for conforming footer
356 * Returns 2 when sob exists within conforming footer
357 * Returns 3 when sob exists within conforming footer as last entry
359 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
360 size_t ignore_footer)
362 struct trailer_iterator iter;
363 size_t i = 0;
364 int found_sob = 0, found_sob_last = 0;
365 char saved_char;
367 if (ignore_footer) {
368 saved_char = sb->buf[sb->len - ignore_footer];
369 sb->buf[sb->len - ignore_footer] = '\0';
372 trailer_iterator_init(&iter, sb->buf);
374 if (ignore_footer)
375 sb->buf[sb->len - ignore_footer] = saved_char;
377 while (trailer_iterator_advance(&iter)) {
378 i++;
379 if (sob && !strncmp(iter.raw, sob->buf, sob->len))
380 found_sob = i;
382 trailer_iterator_release(&iter);
384 if (!i)
385 return 0;
387 found_sob_last = (int)i == found_sob;
389 if (found_sob_last)
390 return 3;
391 if (found_sob)
392 return 2;
393 return 1;
396 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
398 static struct strbuf buf = STRBUF_INIT;
400 strbuf_reset(&buf);
401 if (opts->gpg_sign)
402 sq_quotef(&buf, "-S%s", opts->gpg_sign);
403 return buf.buf;
406 static void replay_ctx_release(struct replay_ctx *ctx)
408 strbuf_release(&ctx->current_fixups);
409 strbuf_release(&ctx->message);
412 void replay_opts_release(struct replay_opts *opts)
414 struct replay_ctx *ctx = opts->ctx;
416 free(opts->gpg_sign);
417 free(opts->reflog_action);
418 free(opts->default_strategy);
419 free(opts->strategy);
420 strvec_clear (&opts->xopts);
421 if (opts->revs)
422 release_revisions(opts->revs);
423 free(opts->revs);
424 replay_ctx_release(ctx);
425 free(opts->ctx);
428 int sequencer_remove_state(struct replay_opts *opts)
430 struct strbuf buf = STRBUF_INIT;
431 int ret = 0;
433 if (is_rebase_i(opts) &&
434 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
435 char *p = buf.buf;
436 while (*p) {
437 char *eol = strchr(p, '\n');
438 if (eol)
439 *eol = '\0';
440 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
441 warning(_("could not delete '%s'"), p);
442 ret = -1;
444 if (!eol)
445 break;
446 p = eol + 1;
450 strbuf_reset(&buf);
451 strbuf_addstr(&buf, get_dir(opts));
452 if (remove_dir_recursively(&buf, 0))
453 ret = error(_("could not remove '%s'"), buf.buf);
454 strbuf_release(&buf);
456 return ret;
459 static const char *action_name(const struct replay_opts *opts)
461 switch (opts->action) {
462 case REPLAY_REVERT:
463 return N_("revert");
464 case REPLAY_PICK:
465 return N_("cherry-pick");
466 case REPLAY_INTERACTIVE_REBASE:
467 return N_("rebase");
469 die(_("unknown action: %d"), opts->action);
472 struct commit_message {
473 char *parent_label;
474 char *label;
475 char *subject;
476 const char *message;
479 static const char *short_commit_name(struct repository *r, struct commit *commit)
481 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
484 static int get_message(struct commit *commit, struct commit_message *out)
486 const char *abbrev, *subject;
487 int subject_len;
489 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
490 get_commit_output_encoding());
491 abbrev = short_commit_name(the_repository, commit);
493 subject_len = find_commit_subject(out->message, &subject);
495 out->subject = xmemdupz(subject, subject_len);
496 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
497 out->parent_label = xstrfmt("parent of %s", out->label);
499 return 0;
502 static void free_message(struct commit *commit, struct commit_message *msg)
504 free(msg->parent_label);
505 free(msg->label);
506 free(msg->subject);
507 repo_unuse_commit_buffer(the_repository, commit, msg->message);
510 const char *rebase_resolvemsg =
511 N_("Resolve all conflicts manually, mark them as resolved with\n"
512 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
513 "You can instead skip this commit: run \"git rebase --skip\".\n"
514 "To abort and get back to the state before \"git rebase\", run "
515 "\"git rebase --abort\".");
517 static void print_advice(struct repository *r, int show_hint,
518 struct replay_opts *opts)
520 const char *msg;
522 if (is_rebase_i(opts))
523 msg = rebase_resolvemsg;
524 else
525 msg = getenv("GIT_CHERRY_PICK_HELP");
527 if (msg) {
528 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
530 * A conflict has occurred but the porcelain
531 * (typically rebase --interactive) wants to take care
532 * of the commit itself so remove CHERRY_PICK_HEAD
534 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
535 NULL, REF_NO_DEREF);
536 return;
539 if (show_hint) {
540 if (opts->no_commit)
541 advise_if_enabled(ADVICE_MERGE_CONFLICT,
542 _("after resolving the conflicts, mark the corrected paths\n"
543 "with 'git add <paths>' or 'git rm <paths>'"));
544 else if (opts->action == REPLAY_PICK)
545 advise_if_enabled(ADVICE_MERGE_CONFLICT,
546 _("After resolving the conflicts, mark them with\n"
547 "\"git add/rm <pathspec>\", then run\n"
548 "\"git cherry-pick --continue\".\n"
549 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
550 "To abort and get back to the state before \"git cherry-pick\",\n"
551 "run \"git cherry-pick --abort\"."));
552 else if (opts->action == REPLAY_REVERT)
553 advise_if_enabled(ADVICE_MERGE_CONFLICT,
554 _("After resolving the conflicts, mark them with\n"
555 "\"git add/rm <pathspec>\", then run\n"
556 "\"git revert --continue\".\n"
557 "You can instead skip this commit with \"git revert --skip\".\n"
558 "To abort and get back to the state before \"git revert\",\n"
559 "run \"git revert --abort\"."));
560 else
561 BUG("unexpected pick action in print_advice()");
565 static int write_message(const void *buf, size_t len, const char *filename,
566 int append_eol)
568 struct lock_file msg_file = LOCK_INIT;
570 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
571 if (msg_fd < 0)
572 return error_errno(_("could not lock '%s'"), filename);
573 if (write_in_full(msg_fd, buf, len) < 0) {
574 error_errno(_("could not write to '%s'"), filename);
575 rollback_lock_file(&msg_file);
576 return -1;
578 if (append_eol && write(msg_fd, "\n", 1) < 0) {
579 error_errno(_("could not write eol to '%s'"), filename);
580 rollback_lock_file(&msg_file);
581 return -1;
583 if (commit_lock_file(&msg_file) < 0)
584 return error(_("failed to finalize '%s'"), filename);
586 return 0;
589 int read_oneliner(struct strbuf *buf,
590 const char *path, unsigned flags)
592 int orig_len = buf->len;
594 if (strbuf_read_file(buf, path, 0) < 0) {
595 if ((flags & READ_ONELINER_WARN_MISSING) ||
596 (errno != ENOENT && errno != ENOTDIR))
597 warning_errno(_("could not read '%s'"), path);
598 return 0;
601 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
602 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
603 --buf->len;
604 buf->buf[buf->len] = '\0';
607 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
608 return 0;
610 return 1;
613 static struct tree *empty_tree(struct repository *r)
615 return lookup_tree(r, the_hash_algo->empty_tree);
618 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
620 if (repo_read_index_unmerged(repo))
621 return error_resolve_conflict(action_name(opts));
623 error(_("your local changes would be overwritten by %s."),
624 _(action_name(opts)));
626 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
627 advise(_("commit your changes or stash them to proceed."));
628 return -1;
631 static void update_abort_safety_file(void)
633 struct object_id head;
635 /* Do nothing on a single-pick */
636 if (!file_exists(git_path_seq_dir()))
637 return;
639 if (!repo_get_oid(the_repository, "HEAD", &head))
640 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
641 else
642 write_file(git_path_abort_safety_file(), "%s", "");
645 static int fast_forward_to(struct repository *r,
646 const struct object_id *to,
647 const struct object_id *from,
648 int unborn,
649 struct replay_opts *opts)
651 struct ref_transaction *transaction;
652 struct strbuf sb = STRBUF_INIT;
653 struct strbuf err = STRBUF_INIT;
655 repo_read_index(r);
656 if (checkout_fast_forward(r, from, to, 1))
657 return -1; /* the callee should have complained already */
659 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
661 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
662 &err);
663 if (!transaction ||
664 ref_transaction_update(transaction, "HEAD",
665 to, unborn && !is_rebase_i(opts) ?
666 null_oid() : from, NULL, NULL,
667 0, sb.buf, &err) ||
668 ref_transaction_commit(transaction, &err)) {
669 ref_transaction_free(transaction);
670 error("%s", err.buf);
671 strbuf_release(&sb);
672 strbuf_release(&err);
673 return -1;
676 strbuf_release(&sb);
677 strbuf_release(&err);
678 ref_transaction_free(transaction);
679 update_abort_safety_file();
680 return 0;
683 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
684 int use_editor)
686 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
687 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
688 COMMIT_MSG_CLEANUP_SPACE;
689 else if (!strcmp(cleanup_arg, "verbatim"))
690 return COMMIT_MSG_CLEANUP_NONE;
691 else if (!strcmp(cleanup_arg, "whitespace"))
692 return COMMIT_MSG_CLEANUP_SPACE;
693 else if (!strcmp(cleanup_arg, "strip"))
694 return COMMIT_MSG_CLEANUP_ALL;
695 else if (!strcmp(cleanup_arg, "scissors"))
696 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
697 COMMIT_MSG_CLEANUP_SPACE;
698 else
699 die(_("Invalid cleanup mode %s"), cleanup_arg);
703 * NB using int rather than enum cleanup_mode to stop clang's
704 * -Wtautological-constant-out-of-range-compare complaining that the comparison
705 * is always true.
707 static const char *describe_cleanup_mode(int cleanup_mode)
709 static const char *modes[] = { "whitespace",
710 "verbatim",
711 "scissors",
712 "strip" };
714 if (cleanup_mode < ARRAY_SIZE(modes))
715 return modes[cleanup_mode];
717 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
720 void append_conflicts_hint(struct index_state *istate,
721 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
723 int i;
725 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
726 strbuf_addch(msgbuf, '\n');
727 wt_status_append_cut_line(msgbuf);
728 strbuf_addstr(msgbuf, comment_line_str);
731 strbuf_addch(msgbuf, '\n');
732 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
733 for (i = 0; i < istate->cache_nr;) {
734 const struct cache_entry *ce = istate->cache[i++];
735 if (ce_stage(ce)) {
736 strbuf_commented_addf(msgbuf, comment_line_str,
737 "\t%s\n", ce->name);
738 while (i < istate->cache_nr &&
739 !strcmp(ce->name, istate->cache[i]->name))
740 i++;
745 static int do_recursive_merge(struct repository *r,
746 struct commit *base, struct commit *next,
747 const char *base_label, const char *next_label,
748 struct object_id *head, struct strbuf *msgbuf,
749 struct replay_opts *opts)
751 struct merge_options o;
752 struct merge_result result;
753 struct tree *next_tree, *base_tree, *head_tree;
754 int clean, show_output;
755 int i;
756 struct lock_file index_lock = LOCK_INIT;
758 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
759 return -1;
761 repo_read_index(r);
763 init_merge_options(&o, r);
764 o.ancestor = base ? base_label : "(empty tree)";
765 o.branch1 = "HEAD";
766 o.branch2 = next ? next_label : "(empty tree)";
767 if (is_rebase_i(opts))
768 o.buffer_output = 2;
769 o.show_rename_progress = 1;
771 head_tree = parse_tree_indirect(head);
772 if (!head_tree)
773 return error(_("unable to read tree (%s)"), oid_to_hex(head));
774 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
775 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
777 for (i = 0; i < opts->xopts.nr; i++)
778 parse_merge_opt(&o, opts->xopts.v[i]);
780 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
781 memset(&result, 0, sizeof(result));
782 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
783 &result);
784 show_output = !is_rebase_i(opts) || !result.clean;
786 * TODO: merge_switch_to_result will update index/working tree;
787 * we only really want to do that if !result.clean || this is
788 * the final patch to be picked. But determining this is the
789 * final patch would take some work, and "head_tree" would need
790 * to be replace with the tree the index matched before we
791 * started doing any picks.
793 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
794 clean = result.clean;
795 } else {
796 ensure_full_index(r->index);
797 clean = merge_trees(&o, head_tree, next_tree, base_tree);
798 if (is_rebase_i(opts) && clean <= 0)
799 fputs(o.obuf.buf, stdout);
800 strbuf_release(&o.obuf);
802 if (clean < 0) {
803 rollback_lock_file(&index_lock);
804 return clean;
807 if (write_locked_index(r->index, &index_lock,
808 COMMIT_LOCK | SKIP_IF_UNCHANGED))
810 * TRANSLATORS: %s will be "revert", "cherry-pick" or
811 * "rebase".
813 return error(_("%s: Unable to write new index file"),
814 _(action_name(opts)));
816 if (!clean)
817 append_conflicts_hint(r->index, msgbuf,
818 opts->default_msg_cleanup);
820 return !clean;
823 static struct object_id *get_cache_tree_oid(struct index_state *istate)
825 if (!cache_tree_fully_valid(istate->cache_tree))
826 if (cache_tree_update(istate, 0)) {
827 error(_("unable to update cache tree"));
828 return NULL;
831 return &istate->cache_tree->oid;
834 static int is_index_unchanged(struct repository *r)
836 struct object_id head_oid, *cache_tree_oid;
837 const struct object_id *head_tree_oid;
838 struct commit *head_commit;
839 struct index_state *istate = r->index;
840 const char *head_name;
842 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
843 /* Check to see if this is an unborn branch */
844 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
845 "HEAD",
846 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
847 &head_oid, NULL);
848 if (!head_name ||
849 !starts_with(head_name, "refs/heads/") ||
850 !is_null_oid(&head_oid))
851 return error(_("could not resolve HEAD commit"));
852 head_tree_oid = the_hash_algo->empty_tree;
853 } else {
854 head_commit = lookup_commit(r, &head_oid);
857 * If head_commit is NULL, check_commit, called from
858 * lookup_commit, would have indicated that head_commit is not
859 * a commit object already. repo_parse_commit() will return failure
860 * without further complaints in such a case. Otherwise, if
861 * the commit is invalid, repo_parse_commit() will complain. So
862 * there is nothing for us to say here. Just return failure.
864 if (repo_parse_commit(r, head_commit))
865 return -1;
867 head_tree_oid = get_commit_tree_oid(head_commit);
870 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
871 return -1;
873 return oideq(cache_tree_oid, head_tree_oid);
876 static int write_author_script(const char *message)
878 struct strbuf buf = STRBUF_INIT;
879 const char *eol;
880 int res;
882 for (;;)
883 if (!*message || starts_with(message, "\n")) {
884 missing_author:
885 /* Missing 'author' line? */
886 unlink(rebase_path_author_script());
887 return 0;
888 } else if (skip_prefix(message, "author ", &message))
889 break;
890 else if ((eol = strchr(message, '\n')))
891 message = eol + 1;
892 else
893 goto missing_author;
895 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
896 while (*message && *message != '\n' && *message != '\r')
897 if (skip_prefix(message, " <", &message))
898 break;
899 else if (*message != '\'')
900 strbuf_addch(&buf, *(message++));
901 else
902 strbuf_addf(&buf, "'\\%c'", *(message++));
903 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
904 while (*message && *message != '\n' && *message != '\r')
905 if (skip_prefix(message, "> ", &message))
906 break;
907 else if (*message != '\'')
908 strbuf_addch(&buf, *(message++));
909 else
910 strbuf_addf(&buf, "'\\%c'", *(message++));
911 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
912 while (*message && *message != '\n' && *message != '\r')
913 if (*message != '\'')
914 strbuf_addch(&buf, *(message++));
915 else
916 strbuf_addf(&buf, "'\\%c'", *(message++));
917 strbuf_addch(&buf, '\'');
918 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
919 strbuf_release(&buf);
920 return res;
924 * Take a series of KEY='VALUE' lines where VALUE part is
925 * sq-quoted, and append <KEY, VALUE> at the end of the string list
927 static int parse_key_value_squoted(char *buf, struct string_list *list)
929 while (*buf) {
930 struct string_list_item *item;
931 char *np;
932 char *cp = strchr(buf, '=');
933 if (!cp) {
934 np = strchrnul(buf, '\n');
935 return error(_("no key present in '%.*s'"),
936 (int) (np - buf), buf);
938 np = strchrnul(cp, '\n');
939 *cp++ = '\0';
940 item = string_list_append(list, buf);
942 buf = np + (*np == '\n');
943 *np = '\0';
944 cp = sq_dequote(cp);
945 if (!cp)
946 return error(_("unable to dequote value of '%s'"),
947 item->string);
948 item->util = xstrdup(cp);
950 return 0;
954 * Reads and parses the state directory's "author-script" file, and sets name,
955 * email and date accordingly.
956 * Returns 0 on success, -1 if the file could not be parsed.
958 * The author script is of the format:
960 * GIT_AUTHOR_NAME='$author_name'
961 * GIT_AUTHOR_EMAIL='$author_email'
962 * GIT_AUTHOR_DATE='$author_date'
964 * where $author_name, $author_email and $author_date are quoted. We are strict
965 * with our parsing, as the file was meant to be eval'd in the now-removed
966 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
967 * from what this function expects, it is better to bail out than to do
968 * something that the user does not expect.
970 int read_author_script(const char *path, char **name, char **email, char **date,
971 int allow_missing)
973 struct strbuf buf = STRBUF_INIT;
974 struct string_list kv = STRING_LIST_INIT_DUP;
975 int retval = -1; /* assume failure */
976 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
978 if (strbuf_read_file(&buf, path, 256) <= 0) {
979 strbuf_release(&buf);
980 if (errno == ENOENT && allow_missing)
981 return 0;
982 else
983 return error_errno(_("could not open '%s' for reading"),
984 path);
987 if (parse_key_value_squoted(buf.buf, &kv))
988 goto finish;
990 for (i = 0; i < kv.nr; i++) {
991 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
992 if (name_i != -2)
993 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
994 else
995 name_i = i;
996 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
997 if (email_i != -2)
998 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
999 else
1000 email_i = i;
1001 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
1002 if (date_i != -2)
1003 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
1004 else
1005 date_i = i;
1006 } else {
1007 err = error(_("unknown variable '%s'"),
1008 kv.items[i].string);
1011 if (name_i == -2)
1012 error(_("missing 'GIT_AUTHOR_NAME'"));
1013 if (email_i == -2)
1014 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1015 if (date_i == -2)
1016 error(_("missing 'GIT_AUTHOR_DATE'"));
1017 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
1018 goto finish;
1019 *name = kv.items[name_i].util;
1020 *email = kv.items[email_i].util;
1021 *date = kv.items[date_i].util;
1022 retval = 0;
1023 finish:
1024 string_list_clear(&kv, !!retval);
1025 strbuf_release(&buf);
1026 return retval;
1030 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
1031 * file with shell quoting into struct strvec. Returns -1 on
1032 * error, 0 otherwise.
1034 static int read_env_script(struct strvec *env)
1036 char *name, *email, *date;
1038 if (read_author_script(rebase_path_author_script(),
1039 &name, &email, &date, 0))
1040 return -1;
1042 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1043 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1044 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
1045 free(name);
1046 free(email);
1047 free(date);
1049 return 0;
1052 static char *get_author(const char *message)
1054 size_t len;
1055 const char *a;
1057 a = find_commit_header(message, "author", &len);
1058 if (a)
1059 return xmemdupz(a, len);
1061 return NULL;
1064 static const char *author_date_from_env(const struct strvec *env)
1066 int i;
1067 const char *date;
1069 for (i = 0; i < env->nr; i++)
1070 if (skip_prefix(env->v[i],
1071 "GIT_AUTHOR_DATE=", &date))
1072 return date;
1074 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1075 * reading the script
1077 BUG("GIT_AUTHOR_DATE missing from author script");
1080 static const char staged_changes_advice[] =
1081 N_("you have staged changes in your working tree\n"
1082 "If these changes are meant to be squashed into the previous commit, run:\n"
1083 "\n"
1084 " git commit --amend %s\n"
1085 "\n"
1086 "If they are meant to go into a new commit, run:\n"
1087 "\n"
1088 " git commit %s\n"
1089 "\n"
1090 "In both cases, once you're done, continue with:\n"
1091 "\n"
1092 " git rebase --continue\n");
1094 #define ALLOW_EMPTY (1<<0)
1095 #define EDIT_MSG (1<<1)
1096 #define AMEND_MSG (1<<2)
1097 #define CLEANUP_MSG (1<<3)
1098 #define VERIFY_MSG (1<<4)
1099 #define CREATE_ROOT_COMMIT (1<<5)
1100 #define VERBATIM_MSG (1<<6)
1102 static int run_command_silent_on_success(struct child_process *cmd)
1104 struct strbuf buf = STRBUF_INIT;
1105 int rc;
1107 cmd->stdout_to_stderr = 1;
1108 rc = pipe_command(cmd,
1109 NULL, 0,
1110 NULL, 0,
1111 &buf, 0);
1113 if (rc)
1114 fputs(buf.buf, stderr);
1115 strbuf_release(&buf);
1116 return rc;
1120 * If we are cherry-pick, and if the merge did not result in
1121 * hand-editing, we will hit this commit and inherit the original
1122 * author date and name.
1124 * If we are revert, or if our cherry-pick results in a hand merge,
1125 * we had better say that the current user is responsible for that.
1127 * An exception is when run_git_commit() is called during an
1128 * interactive rebase: in that case, we will want to retain the
1129 * author metadata.
1131 static int run_git_commit(const char *defmsg,
1132 struct replay_opts *opts,
1133 unsigned int flags)
1135 struct replay_ctx *ctx = opts->ctx;
1136 struct child_process cmd = CHILD_PROCESS_INIT;
1138 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1139 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1141 cmd.git_cmd = 1;
1143 if (is_rebase_i(opts) &&
1144 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1145 !(!defmsg && (flags & AMEND_MSG))) &&
1146 read_env_script(&cmd.env)) {
1147 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1149 return error(_(staged_changes_advice),
1150 gpg_opt, gpg_opt);
1153 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", ctx->reflog_message);
1155 if (opts->committer_date_is_author_date)
1156 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1157 opts->ignore_date ?
1158 "" :
1159 author_date_from_env(&cmd.env));
1160 if (opts->ignore_date)
1161 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1163 strvec_push(&cmd.args, "commit");
1165 if (!(flags & VERIFY_MSG))
1166 strvec_push(&cmd.args, "-n");
1167 if ((flags & AMEND_MSG))
1168 strvec_push(&cmd.args, "--amend");
1169 if (opts->gpg_sign)
1170 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1171 else
1172 strvec_push(&cmd.args, "--no-gpg-sign");
1173 if (defmsg)
1174 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1175 else if (!(flags & EDIT_MSG))
1176 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1177 if ((flags & CLEANUP_MSG))
1178 strvec_push(&cmd.args, "--cleanup=strip");
1179 if ((flags & VERBATIM_MSG))
1180 strvec_push(&cmd.args, "--cleanup=verbatim");
1181 if ((flags & EDIT_MSG))
1182 strvec_push(&cmd.args, "-e");
1183 else if (!(flags & CLEANUP_MSG) &&
1184 !opts->signoff && !opts->record_origin &&
1185 !opts->explicit_cleanup)
1186 strvec_push(&cmd.args, "--cleanup=verbatim");
1188 if ((flags & ALLOW_EMPTY))
1189 strvec_push(&cmd.args, "--allow-empty");
1191 if (!(flags & EDIT_MSG))
1192 strvec_push(&cmd.args, "--allow-empty-message");
1194 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1195 return run_command_silent_on_success(&cmd);
1196 else
1197 return run_command(&cmd);
1200 static int rest_is_empty(const struct strbuf *sb, int start)
1202 int i, eol;
1203 const char *nl;
1205 /* Check if the rest is just whitespace and Signed-off-by's. */
1206 for (i = start; i < sb->len; i++) {
1207 nl = memchr(sb->buf + i, '\n', sb->len - i);
1208 if (nl)
1209 eol = nl - sb->buf;
1210 else
1211 eol = sb->len;
1213 if (strlen(sign_off_header) <= eol - i &&
1214 starts_with(sb->buf + i, sign_off_header)) {
1215 i = eol;
1216 continue;
1218 while (i < eol)
1219 if (!isspace(sb->buf[i++]))
1220 return 0;
1223 return 1;
1226 void cleanup_message(struct strbuf *msgbuf,
1227 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1229 if (verbose || /* Truncate the message just before the diff, if any. */
1230 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1231 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1232 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1233 strbuf_stripspace(msgbuf,
1234 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1238 * Find out if the message in the strbuf contains only whitespace and
1239 * Signed-off-by lines.
1241 int message_is_empty(const struct strbuf *sb,
1242 enum commit_msg_cleanup_mode cleanup_mode)
1244 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1245 return 0;
1246 return rest_is_empty(sb, 0);
1250 * See if the user edited the message in the editor or left what
1251 * was in the template intact
1253 int template_untouched(const struct strbuf *sb, const char *template_file,
1254 enum commit_msg_cleanup_mode cleanup_mode)
1256 struct strbuf tmpl = STRBUF_INIT;
1257 const char *start;
1259 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1260 return 0;
1262 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1263 return 0;
1265 strbuf_stripspace(&tmpl,
1266 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1267 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1268 start = sb->buf;
1269 strbuf_release(&tmpl);
1270 return rest_is_empty(sb, start - sb->buf);
1273 int update_head_with_reflog(const struct commit *old_head,
1274 const struct object_id *new_head,
1275 const char *action, const struct strbuf *msg,
1276 struct strbuf *err)
1278 struct ref_transaction *transaction;
1279 struct strbuf sb = STRBUF_INIT;
1280 const char *nl;
1281 int ret = 0;
1283 if (action) {
1284 strbuf_addstr(&sb, action);
1285 strbuf_addstr(&sb, ": ");
1288 nl = strchr(msg->buf, '\n');
1289 if (nl) {
1290 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1291 } else {
1292 strbuf_addbuf(&sb, msg);
1293 strbuf_addch(&sb, '\n');
1296 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1297 err);
1298 if (!transaction ||
1299 ref_transaction_update(transaction, "HEAD", new_head,
1300 old_head ? &old_head->object.oid : null_oid(),
1301 NULL, NULL, 0, sb.buf, err) ||
1302 ref_transaction_commit(transaction, err)) {
1303 ret = -1;
1305 ref_transaction_free(transaction);
1306 strbuf_release(&sb);
1308 return ret;
1311 static int run_rewrite_hook(const struct object_id *oldoid,
1312 const struct object_id *newoid)
1314 struct child_process proc = CHILD_PROCESS_INIT;
1315 int code;
1316 struct strbuf sb = STRBUF_INIT;
1317 const char *hook_path = find_hook("post-rewrite");
1319 if (!hook_path)
1320 return 0;
1322 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1323 proc.in = -1;
1324 proc.stdout_to_stderr = 1;
1325 proc.trace2_hook_name = "post-rewrite";
1327 code = start_command(&proc);
1328 if (code)
1329 return code;
1330 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1331 sigchain_push(SIGPIPE, SIG_IGN);
1332 write_in_full(proc.in, sb.buf, sb.len);
1333 close(proc.in);
1334 strbuf_release(&sb);
1335 sigchain_pop(SIGPIPE);
1336 return finish_command(&proc);
1339 void commit_post_rewrite(struct repository *r,
1340 const struct commit *old_head,
1341 const struct object_id *new_head)
1343 struct notes_rewrite_cfg *cfg;
1345 cfg = init_copy_notes_for_rewrite("amend");
1346 if (cfg) {
1347 /* we are amending, so old_head is not NULL */
1348 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1349 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1351 run_rewrite_hook(&old_head->object.oid, new_head);
1354 static int run_prepare_commit_msg_hook(struct repository *r,
1355 struct strbuf *msg,
1356 const char *commit)
1358 int ret = 0;
1359 const char *name, *arg1 = NULL, *arg2 = NULL;
1361 name = git_path_commit_editmsg();
1362 if (write_message(msg->buf, msg->len, name, 0))
1363 return -1;
1365 if (commit) {
1366 arg1 = "commit";
1367 arg2 = commit;
1368 } else {
1369 arg1 = "message";
1371 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1372 arg1, arg2, NULL))
1373 ret = error(_("'prepare-commit-msg' hook failed"));
1375 return ret;
1378 static const char implicit_ident_advice_noconfig[] =
1379 N_("Your name and email address were configured automatically based\n"
1380 "on your username and hostname. Please check that they are accurate.\n"
1381 "You can suppress this message by setting them explicitly. Run the\n"
1382 "following command and follow the instructions in your editor to edit\n"
1383 "your configuration file:\n"
1384 "\n"
1385 " git config --global --edit\n"
1386 "\n"
1387 "After doing this, you may fix the identity used for this commit with:\n"
1388 "\n"
1389 " git commit --amend --reset-author\n");
1391 static const char implicit_ident_advice_config[] =
1392 N_("Your name and email address were configured automatically based\n"
1393 "on your username and hostname. Please check that they are accurate.\n"
1394 "You can suppress this message by setting them explicitly:\n"
1395 "\n"
1396 " git config --global user.name \"Your Name\"\n"
1397 " git config --global user.email you@example.com\n"
1398 "\n"
1399 "After doing this, you may fix the identity used for this commit with:\n"
1400 "\n"
1401 " git commit --amend --reset-author\n");
1403 static const char *implicit_ident_advice(void)
1405 char *user_config = interpolate_path("~/.gitconfig", 0);
1406 char *xdg_config = xdg_config_home("config");
1407 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1409 free(user_config);
1410 free(xdg_config);
1412 if (config_exists)
1413 return _(implicit_ident_advice_config);
1414 else
1415 return _(implicit_ident_advice_noconfig);
1419 void print_commit_summary(struct repository *r,
1420 const char *prefix,
1421 const struct object_id *oid,
1422 unsigned int flags)
1424 struct rev_info rev;
1425 struct commit *commit;
1426 struct strbuf format = STRBUF_INIT;
1427 const char *head;
1428 struct pretty_print_context pctx = {0};
1429 struct strbuf author_ident = STRBUF_INIT;
1430 struct strbuf committer_ident = STRBUF_INIT;
1431 struct ref_store *refs;
1433 commit = lookup_commit(r, oid);
1434 if (!commit)
1435 die(_("couldn't look up newly created commit"));
1436 if (repo_parse_commit(r, commit))
1437 die(_("could not parse newly created commit"));
1439 strbuf_addstr(&format, "format:%h] %s");
1441 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1442 &pctx);
1443 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1444 &pctx);
1445 if (strbuf_cmp(&author_ident, &committer_ident)) {
1446 strbuf_addstr(&format, "\n Author: ");
1447 strbuf_addbuf_percentquote(&format, &author_ident);
1449 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1450 struct strbuf date = STRBUF_INIT;
1452 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1453 strbuf_addstr(&format, "\n Date: ");
1454 strbuf_addbuf_percentquote(&format, &date);
1455 strbuf_release(&date);
1457 if (!committer_ident_sufficiently_given()) {
1458 strbuf_addstr(&format, "\n Committer: ");
1459 strbuf_addbuf_percentquote(&format, &committer_ident);
1460 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1461 strbuf_addch(&format, '\n');
1462 strbuf_addstr(&format, implicit_ident_advice());
1465 strbuf_release(&author_ident);
1466 strbuf_release(&committer_ident);
1468 repo_init_revisions(r, &rev, prefix);
1469 setup_revisions(0, NULL, &rev, NULL);
1471 rev.diff = 1;
1472 rev.diffopt.output_format =
1473 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1475 rev.verbose_header = 1;
1476 rev.show_root_diff = 1;
1477 get_commit_format(format.buf, &rev);
1478 rev.always_show_header = 0;
1479 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1480 diff_setup_done(&rev.diffopt);
1482 refs = get_main_ref_store(r);
1483 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1484 if (!head)
1485 die(_("unable to resolve HEAD after creating commit"));
1486 if (!strcmp(head, "HEAD"))
1487 head = _("detached HEAD");
1488 else
1489 skip_prefix(head, "refs/heads/", &head);
1490 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1491 _(" (root-commit)") : "");
1493 if (!log_tree_commit(&rev, commit)) {
1494 rev.always_show_header = 1;
1495 rev.use_terminator = 1;
1496 log_tree_commit(&rev, commit);
1499 release_revisions(&rev);
1500 strbuf_release(&format);
1503 static int parse_head(struct repository *r, struct commit **head)
1505 struct commit *current_head;
1506 struct object_id oid;
1508 if (repo_get_oid(r, "HEAD", &oid)) {
1509 current_head = NULL;
1510 } else {
1511 current_head = lookup_commit_reference(r, &oid);
1512 if (!current_head)
1513 return error(_("could not parse HEAD"));
1514 if (!oideq(&oid, &current_head->object.oid)) {
1515 warning(_("HEAD %s is not a commit!"),
1516 oid_to_hex(&oid));
1518 if (repo_parse_commit(r, current_head))
1519 return error(_("could not parse HEAD commit"));
1521 *head = current_head;
1523 return 0;
1527 * Try to commit without forking 'git commit'. In some cases we need
1528 * to run 'git commit' to display an error message
1530 * Returns:
1531 * -1 - error unable to commit
1532 * 0 - success
1533 * 1 - run 'git commit'
1535 static int try_to_commit(struct repository *r,
1536 struct strbuf *msg, const char *author,
1537 struct replay_opts *opts, unsigned int flags,
1538 struct object_id *oid)
1540 struct replay_ctx *ctx = opts->ctx;
1541 struct object_id tree;
1542 struct commit *current_head = NULL;
1543 struct commit_list *parents = NULL;
1544 struct commit_extra_header *extra = NULL;
1545 struct strbuf err = STRBUF_INIT;
1546 struct strbuf commit_msg = STRBUF_INIT;
1547 char *amend_author = NULL;
1548 const char *committer = NULL;
1549 const char *hook_commit = NULL;
1550 enum commit_msg_cleanup_mode cleanup;
1551 int res = 0;
1553 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1554 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1556 if (parse_head(r, &current_head))
1557 return -1;
1559 if (flags & AMEND_MSG) {
1560 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1561 const char *out_enc = get_commit_output_encoding();
1562 const char *message = repo_logmsg_reencode(r, current_head,
1563 NULL, out_enc);
1565 if (!msg) {
1566 const char *orig_message = NULL;
1568 find_commit_subject(message, &orig_message);
1569 msg = &commit_msg;
1570 strbuf_addstr(msg, orig_message);
1571 hook_commit = "HEAD";
1573 author = amend_author = get_author(message);
1574 repo_unuse_commit_buffer(r, current_head,
1575 message);
1576 if (!author) {
1577 res = error(_("unable to parse commit author"));
1578 goto out;
1580 parents = copy_commit_list(current_head->parents);
1581 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1582 } else if (current_head &&
1583 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1584 commit_list_insert(current_head, &parents);
1587 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1588 res = error(_("git write-tree failed to write a tree"));
1589 goto out;
1592 if (!(flags & ALLOW_EMPTY)) {
1593 struct commit *first_parent = current_head;
1595 if (flags & AMEND_MSG) {
1596 if (current_head->parents) {
1597 first_parent = current_head->parents->item;
1598 if (repo_parse_commit(r, first_parent)) {
1599 res = error(_("could not parse HEAD commit"));
1600 goto out;
1602 } else {
1603 first_parent = NULL;
1606 if (oideq(first_parent
1607 ? get_commit_tree_oid(first_parent)
1608 : the_hash_algo->empty_tree,
1609 &tree)) {
1610 res = 1; /* run 'git commit' to display error message */
1611 goto out;
1615 if (hook_exists("prepare-commit-msg")) {
1616 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1617 if (res)
1618 goto out;
1619 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1620 2048) < 0) {
1621 res = error_errno(_("unable to read commit message "
1622 "from '%s'"),
1623 git_path_commit_editmsg());
1624 goto out;
1626 msg = &commit_msg;
1629 if (flags & CLEANUP_MSG)
1630 cleanup = COMMIT_MSG_CLEANUP_ALL;
1631 else if (flags & VERBATIM_MSG)
1632 cleanup = COMMIT_MSG_CLEANUP_NONE;
1633 else if ((opts->signoff || opts->record_origin) &&
1634 !opts->explicit_cleanup)
1635 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1636 else
1637 cleanup = opts->default_msg_cleanup;
1639 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1640 strbuf_stripspace(msg,
1641 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1642 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1643 res = 1; /* run 'git commit' to display error message */
1644 goto out;
1647 if (opts->committer_date_is_author_date) {
1648 struct ident_split id;
1649 struct strbuf date = STRBUF_INIT;
1651 if (!opts->ignore_date) {
1652 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1653 res = error(_("invalid author identity '%s'"),
1654 author);
1655 goto out;
1657 if (!id.date_begin) {
1658 res = error(_(
1659 "corrupt author: missing date information"));
1660 goto out;
1662 strbuf_addf(&date, "@%.*s %.*s",
1663 (int)(id.date_end - id.date_begin),
1664 id.date_begin,
1665 (int)(id.tz_end - id.tz_begin),
1666 id.tz_begin);
1667 } else {
1668 reset_ident_date();
1670 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1671 getenv("GIT_COMMITTER_EMAIL"),
1672 WANT_COMMITTER_IDENT,
1673 opts->ignore_date ? NULL : date.buf,
1674 IDENT_STRICT);
1675 strbuf_release(&date);
1676 } else {
1677 reset_ident_date();
1680 if (opts->ignore_date) {
1681 struct ident_split id;
1682 char *name, *email;
1684 if (split_ident_line(&id, author, strlen(author)) < 0) {
1685 error(_("invalid author identity '%s'"), author);
1686 goto out;
1688 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1689 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1690 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1691 IDENT_STRICT);
1692 free(name);
1693 free(email);
1696 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1697 author, committer, opts->gpg_sign, extra)) {
1698 res = error(_("failed to write commit object"));
1699 goto out;
1702 if (update_head_with_reflog(current_head, oid, ctx->reflog_message,
1703 msg, &err)) {
1704 res = error("%s", err.buf);
1705 goto out;
1708 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1709 if (flags & AMEND_MSG)
1710 commit_post_rewrite(r, current_head, oid);
1712 out:
1713 free_commit_extra_headers(extra);
1714 strbuf_release(&err);
1715 strbuf_release(&commit_msg);
1716 free(amend_author);
1718 return res;
1721 static int write_rebase_head(struct object_id *oid)
1723 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1724 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1725 return error(_("could not update %s"), "REBASE_HEAD");
1727 return 0;
1730 static int do_commit(struct repository *r,
1731 const char *msg_file, const char *author,
1732 struct replay_opts *opts, unsigned int flags,
1733 struct object_id *oid)
1735 int res = 1;
1737 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1738 struct object_id oid;
1739 struct strbuf sb = STRBUF_INIT;
1741 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1742 return error_errno(_("unable to read commit message "
1743 "from '%s'"),
1744 msg_file);
1746 res = try_to_commit(r, msg_file ? &sb : NULL,
1747 author, opts, flags, &oid);
1748 strbuf_release(&sb);
1749 if (!res) {
1750 refs_delete_ref(get_main_ref_store(r), "",
1751 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1752 unlink(git_path_merge_msg(r));
1753 if (!is_rebase_i(opts))
1754 print_commit_summary(r, NULL, &oid,
1755 SUMMARY_SHOW_AUTHOR_DATE);
1756 return res;
1759 if (res == 1) {
1760 if (is_rebase_i(opts) && oid)
1761 if (write_rebase_head(oid))
1762 return -1;
1763 return run_git_commit(msg_file, opts, flags);
1766 return res;
1769 static int is_original_commit_empty(struct commit *commit)
1771 const struct object_id *ptree_oid;
1773 if (repo_parse_commit(the_repository, commit))
1774 return error(_("could not parse commit %s"),
1775 oid_to_hex(&commit->object.oid));
1776 if (commit->parents) {
1777 struct commit *parent = commit->parents->item;
1778 if (repo_parse_commit(the_repository, parent))
1779 return error(_("could not parse parent commit %s"),
1780 oid_to_hex(&parent->object.oid));
1781 ptree_oid = get_commit_tree_oid(parent);
1782 } else {
1783 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1786 return oideq(ptree_oid, get_commit_tree_oid(commit));
1790 * Should empty commits be allowed? Return status:
1791 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1792 * 0: Halt on empty commit
1793 * 1: Allow empty commit
1794 * 2: Drop empty commit
1796 static int allow_empty(struct repository *r,
1797 struct replay_opts *opts,
1798 struct commit *commit)
1800 int index_unchanged, originally_empty;
1803 * For a commit that is initially empty, allow_empty determines if it
1804 * should be kept or not
1806 * For a commit that becomes empty, keep_redundant_commits and
1807 * drop_redundant_commits determine whether the commit should be kept or
1808 * dropped. If neither is specified, halt.
1810 index_unchanged = is_index_unchanged(r);
1811 if (index_unchanged < 0)
1812 return index_unchanged;
1813 if (!index_unchanged)
1814 return 0; /* we do not have to say --allow-empty */
1816 originally_empty = is_original_commit_empty(commit);
1817 if (originally_empty < 0)
1818 return originally_empty;
1819 if (originally_empty)
1820 return opts->allow_empty;
1821 else if (opts->keep_redundant_commits)
1822 return 1;
1823 else if (opts->drop_redundant_commits)
1824 return 2;
1825 else
1826 return 0;
1829 static struct {
1830 char c;
1831 const char *str;
1832 } todo_command_info[] = {
1833 [TODO_PICK] = { 'p', "pick" },
1834 [TODO_REVERT] = { 0, "revert" },
1835 [TODO_EDIT] = { 'e', "edit" },
1836 [TODO_REWORD] = { 'r', "reword" },
1837 [TODO_FIXUP] = { 'f', "fixup" },
1838 [TODO_SQUASH] = { 's', "squash" },
1839 [TODO_EXEC] = { 'x', "exec" },
1840 [TODO_BREAK] = { 'b', "break" },
1841 [TODO_LABEL] = { 'l', "label" },
1842 [TODO_RESET] = { 't', "reset" },
1843 [TODO_MERGE] = { 'm', "merge" },
1844 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1845 [TODO_NOOP] = { 0, "noop" },
1846 [TODO_DROP] = { 'd', "drop" },
1847 [TODO_COMMENT] = { 0, NULL },
1850 static const char *command_to_string(const enum todo_command command)
1852 if (command < TODO_COMMENT)
1853 return todo_command_info[command].str;
1854 if (command == TODO_COMMENT)
1855 return comment_line_str;
1856 die(_("unknown command: %d"), command);
1859 static char command_to_char(const enum todo_command command)
1861 if (command < TODO_COMMENT)
1862 return todo_command_info[command].c;
1863 return 0;
1866 static int is_noop(const enum todo_command command)
1868 return TODO_NOOP <= command;
1871 static int is_fixup(enum todo_command command)
1873 return command == TODO_FIXUP || command == TODO_SQUASH;
1876 /* Does this command create a (non-merge) commit? */
1877 static int is_pick_or_similar(enum todo_command command)
1879 switch (command) {
1880 case TODO_PICK:
1881 case TODO_REVERT:
1882 case TODO_EDIT:
1883 case TODO_REWORD:
1884 case TODO_FIXUP:
1885 case TODO_SQUASH:
1886 return 1;
1887 default:
1888 return 0;
1892 enum todo_item_flags {
1893 TODO_EDIT_MERGE_MSG = (1 << 0),
1894 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1895 TODO_EDIT_FIXUP_MSG = (1 << 2),
1898 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1899 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1900 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1901 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1902 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1904 static int is_fixup_flag(enum todo_command command, unsigned flag)
1906 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1907 (flag & TODO_EDIT_FIXUP_MSG));
1911 * Wrapper around strbuf_add_commented_lines() which avoids double
1912 * commenting commit subjects.
1914 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1916 const char *s = str;
1917 while (starts_with_mem(s, len, comment_line_str)) {
1918 size_t count;
1919 const char *n = memchr(s, '\n', len);
1920 if (!n)
1921 count = len;
1922 else
1923 count = n - s + 1;
1924 strbuf_add(buf, s, count);
1925 s += count;
1926 len -= count;
1928 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1931 /* Does the current fixup chain contain a squash command? */
1932 static int seen_squash(struct replay_ctx *ctx)
1934 return starts_with(ctx->current_fixups.buf, "squash") ||
1935 strstr(ctx->current_fixups.buf, "\nsquash");
1938 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1940 strbuf_setlen(buf1, 2);
1941 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1942 strbuf_addch(buf1, '\n');
1943 strbuf_setlen(buf2, 2);
1944 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1945 strbuf_addch(buf2, '\n');
1949 * Comment out any un-commented commit messages, updating the message comments
1950 * to say they will be skipped but do not comment out the empty lines that
1951 * surround commit messages and their comments.
1953 static void update_squash_message_for_fixup(struct strbuf *msg)
1955 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1956 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1957 const char *s, *start;
1958 char *orig_msg;
1959 size_t orig_msg_len;
1960 int i = 1;
1962 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1963 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1964 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1965 while (s) {
1966 const char *next;
1967 size_t off;
1968 if (skip_prefix(s, buf1.buf, &next)) {
1970 * Copy the last message, preserving the blank line
1971 * preceding the current line
1973 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1974 copy_lines(msg, start, s - start - off);
1975 if (off)
1976 strbuf_addch(msg, '\n');
1978 * The next message needs to be commented out but the
1979 * message header is already commented out so just copy
1980 * it and the blank line that follows it.
1982 strbuf_addbuf(msg, &buf2);
1983 if (*next == '\n')
1984 strbuf_addch(msg, *next++);
1985 start = s = next;
1986 copy_lines = add_commented_lines;
1987 update_comment_bufs(&buf1, &buf2, ++i);
1988 } else if (skip_prefix(s, buf2.buf, &next)) {
1989 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1990 copy_lines(msg, start, s - start - off);
1991 start = s - off;
1992 s = next;
1993 copy_lines = strbuf_add;
1994 update_comment_bufs(&buf1, &buf2, ++i);
1995 } else {
1996 s = strchr(s, '\n');
1997 if (s)
1998 s++;
2001 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2002 free(orig_msg);
2003 strbuf_release(&buf1);
2004 strbuf_release(&buf2);
2007 static int append_squash_message(struct strbuf *buf, const char *body,
2008 enum todo_command command, struct replay_opts *opts,
2009 unsigned flag)
2011 struct replay_ctx *ctx = opts->ctx;
2012 const char *fixup_msg;
2013 size_t commented_len = 0, fixup_off;
2015 * amend is non-interactive and not normally used with fixup!
2016 * or squash! commits, so only comment out those subjects when
2017 * squashing commit messages.
2019 if (starts_with(body, "amend!") ||
2020 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2021 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2022 commented_len = commit_subject_length(body);
2024 strbuf_addf(buf, "\n%s ", comment_line_str);
2025 strbuf_addf(buf, _(nth_commit_msg_fmt),
2026 ++ctx->current_fixup_count + 1);
2027 strbuf_addstr(buf, "\n\n");
2028 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2029 /* buf->buf may be reallocated so store an offset into the buffer */
2030 fixup_off = buf->len;
2031 strbuf_addstr(buf, body + commented_len);
2033 /* fixup -C after squash behaves like squash */
2034 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2036 * We're replacing the commit message so we need to
2037 * append the Signed-off-by: trailer if the user
2038 * requested '--signoff'.
2040 if (opts->signoff)
2041 append_signoff(buf, 0, 0);
2043 if ((command == TODO_FIXUP) &&
2044 (flag & TODO_REPLACE_FIXUP_MSG) &&
2045 (file_exists(rebase_path_fixup_msg()) ||
2046 !file_exists(rebase_path_squash_msg()))) {
2047 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2048 if (write_message(fixup_msg, strlen(fixup_msg),
2049 rebase_path_fixup_msg(), 0) < 0)
2050 return error(_("cannot write '%s'"),
2051 rebase_path_fixup_msg());
2052 } else {
2053 unlink(rebase_path_fixup_msg());
2055 } else {
2056 unlink(rebase_path_fixup_msg());
2059 return 0;
2062 static int update_squash_messages(struct repository *r,
2063 enum todo_command command,
2064 struct commit *commit,
2065 struct replay_opts *opts,
2066 unsigned flag)
2068 struct replay_ctx *ctx = opts->ctx;
2069 struct strbuf buf = STRBUF_INIT;
2070 int res = 0;
2071 const char *message, *body;
2072 const char *encoding = get_commit_output_encoding();
2074 if (ctx->current_fixup_count > 0) {
2075 struct strbuf header = STRBUF_INIT;
2076 char *eol;
2078 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2079 return error(_("could not read '%s'"),
2080 rebase_path_squash_msg());
2082 eol = !starts_with(buf.buf, comment_line_str) ?
2083 buf.buf : strchrnul(buf.buf, '\n');
2085 strbuf_addf(&header, "%s ", comment_line_str);
2086 strbuf_addf(&header, _(combined_commit_msg_fmt),
2087 ctx->current_fixup_count + 2);
2088 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2089 strbuf_release(&header);
2090 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2091 update_squash_message_for_fixup(&buf);
2092 } else {
2093 struct object_id head;
2094 struct commit *head_commit;
2095 const char *head_message, *body;
2097 if (repo_get_oid(r, "HEAD", &head))
2098 return error(_("need a HEAD to fixup"));
2099 if (!(head_commit = lookup_commit_reference(r, &head)))
2100 return error(_("could not read HEAD"));
2101 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2102 encoding)))
2103 return error(_("could not read HEAD's commit message"));
2105 find_commit_subject(head_message, &body);
2106 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2107 rebase_path_fixup_msg(), 0) < 0) {
2108 repo_unuse_commit_buffer(r, head_commit, head_message);
2109 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2111 strbuf_addf(&buf, "%s ", comment_line_str);
2112 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2113 strbuf_addf(&buf, "\n%s ", comment_line_str);
2114 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2115 _(skip_first_commit_msg_str) :
2116 _(first_commit_msg_str));
2117 strbuf_addstr(&buf, "\n\n");
2118 if (is_fixup_flag(command, flag))
2119 strbuf_add_commented_lines(&buf, body, strlen(body),
2120 comment_line_str);
2121 else
2122 strbuf_addstr(&buf, body);
2124 repo_unuse_commit_buffer(r, head_commit, head_message);
2127 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2128 return error(_("could not read commit message of %s"),
2129 oid_to_hex(&commit->object.oid));
2130 find_commit_subject(message, &body);
2132 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2133 res = append_squash_message(&buf, body, command, opts, flag);
2134 } else if (command == TODO_FIXUP) {
2135 strbuf_addf(&buf, "\n%s ", comment_line_str);
2136 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2137 ++ctx->current_fixup_count + 1);
2138 strbuf_addstr(&buf, "\n\n");
2139 strbuf_add_commented_lines(&buf, body, strlen(body),
2140 comment_line_str);
2141 } else
2142 return error(_("unknown command: %d"), command);
2143 repo_unuse_commit_buffer(r, commit, message);
2145 if (!res)
2146 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2148 strbuf_release(&buf);
2150 if (!res) {
2151 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2152 ctx->current_fixups.len ? "\n" : "",
2153 command_to_string(command),
2154 oid_to_hex(&commit->object.oid));
2155 res = write_message(ctx->current_fixups.buf,
2156 ctx->current_fixups.len,
2157 rebase_path_current_fixups(), 0);
2160 return res;
2163 static void flush_rewritten_pending(void)
2165 struct strbuf buf = STRBUF_INIT;
2166 struct object_id newoid;
2167 FILE *out;
2169 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2170 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2171 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2172 char *bol = buf.buf, *eol;
2174 while (*bol) {
2175 eol = strchrnul(bol, '\n');
2176 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2177 bol, oid_to_hex(&newoid));
2178 if (!*eol)
2179 break;
2180 bol = eol + 1;
2182 fclose(out);
2183 unlink(rebase_path_rewritten_pending());
2185 strbuf_release(&buf);
2188 static void record_in_rewritten(struct object_id *oid,
2189 enum todo_command next_command)
2191 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2193 if (!out)
2194 return;
2196 fprintf(out, "%s\n", oid_to_hex(oid));
2197 fclose(out);
2199 if (!is_fixup(next_command))
2200 flush_rewritten_pending();
2203 static int should_edit(struct replay_opts *opts) {
2204 if (opts->edit < 0)
2206 * Note that we only handle the case of non-conflicted
2207 * commits; continue_single_pick() handles the conflicted
2208 * commits itself instead of calling this function.
2210 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2211 return opts->edit;
2214 static void refer_to_commit(struct replay_opts *opts,
2215 struct strbuf *msgbuf, struct commit *commit)
2217 if (opts->commit_use_reference) {
2218 struct pretty_print_context ctx = {
2219 .abbrev = DEFAULT_ABBREV,
2220 .date_mode.type = DATE_SHORT,
2222 repo_format_commit_message(the_repository, commit,
2223 "%h (%s, %ad)", msgbuf, &ctx);
2224 } else {
2225 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2229 static int do_pick_commit(struct repository *r,
2230 struct todo_item *item,
2231 struct replay_opts *opts,
2232 int final_fixup, int *check_todo)
2234 struct replay_ctx *ctx = opts->ctx;
2235 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2236 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2237 struct object_id head;
2238 struct commit *base, *next, *parent;
2239 const char *base_label, *next_label;
2240 char *author = NULL;
2241 struct commit_message msg = { NULL, NULL, NULL, NULL };
2242 int res, unborn = 0, reword = 0, allow, drop_commit;
2243 enum todo_command command = item->command;
2244 struct commit *commit = item->commit;
2246 if (opts->no_commit) {
2248 * We do not intend to commit immediately. We just want to
2249 * merge the differences in, so let's compute the tree
2250 * that represents the "current" state for the merge machinery
2251 * to work on.
2253 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2254 return error(_("your index file is unmerged."));
2255 } else {
2256 unborn = repo_get_oid(r, "HEAD", &head);
2257 /* Do we want to generate a root commit? */
2258 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2259 oideq(&head, &opts->squash_onto)) {
2260 if (is_fixup(command))
2261 return error(_("cannot fixup root commit"));
2262 flags |= CREATE_ROOT_COMMIT;
2263 unborn = 1;
2264 } else if (unborn)
2265 oidcpy(&head, the_hash_algo->empty_tree);
2266 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2267 NULL, 0))
2268 return error_dirty_index(r, opts);
2270 discard_index(r->index);
2272 if (!commit->parents)
2273 parent = NULL;
2274 else if (commit->parents->next) {
2275 /* Reverting or cherry-picking a merge commit */
2276 int cnt;
2277 struct commit_list *p;
2279 if (!opts->mainline)
2280 return error(_("commit %s is a merge but no -m option was given."),
2281 oid_to_hex(&commit->object.oid));
2283 for (cnt = 1, p = commit->parents;
2284 cnt != opts->mainline && p;
2285 cnt++)
2286 p = p->next;
2287 if (cnt != opts->mainline || !p)
2288 return error(_("commit %s does not have parent %d"),
2289 oid_to_hex(&commit->object.oid), opts->mainline);
2290 parent = p->item;
2291 } else if (1 < opts->mainline)
2293 * Non-first parent explicitly specified as mainline for
2294 * non-merge commit
2296 return error(_("commit %s does not have parent %d"),
2297 oid_to_hex(&commit->object.oid), opts->mainline);
2298 else
2299 parent = commit->parents->item;
2301 if (get_message(commit, &msg) != 0)
2302 return error(_("cannot get commit message for %s"),
2303 oid_to_hex(&commit->object.oid));
2305 if (opts->allow_ff && !is_fixup(command) &&
2306 ((parent && oideq(&parent->object.oid, &head)) ||
2307 (!parent && unborn))) {
2308 if (is_rebase_i(opts))
2309 write_author_script(msg.message);
2310 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2311 opts);
2312 if (res || command != TODO_REWORD)
2313 goto leave;
2314 reword = 1;
2315 msg_file = NULL;
2316 goto fast_forward_edit;
2318 if (parent && repo_parse_commit(r, parent) < 0)
2319 /* TRANSLATORS: The first %s will be a "todo" command like
2320 "revert" or "pick", the second %s a SHA1. */
2321 return error(_("%s: cannot parse parent commit %s"),
2322 command_to_string(command),
2323 oid_to_hex(&parent->object.oid));
2326 * "commit" is an existing commit. We would want to apply
2327 * the difference it introduces since its first parent "prev"
2328 * on top of the current HEAD if we are cherry-pick. Or the
2329 * reverse of it if we are revert.
2332 if (command == TODO_REVERT) {
2333 const char *orig_subject;
2335 base = commit;
2336 base_label = msg.label;
2337 next = parent;
2338 next_label = msg.parent_label;
2339 if (opts->commit_use_reference) {
2340 strbuf_addstr(&ctx->message,
2341 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2342 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2344 * We don't touch pre-existing repeated reverts, because
2345 * theoretically these can be nested arbitrarily deeply,
2346 * thus requiring excessive complexity to deal with.
2348 !starts_with(orig_subject, "Revert \"")) {
2349 strbuf_addstr(&ctx->message, "Reapply \"");
2350 strbuf_addstr(&ctx->message, orig_subject);
2351 } else {
2352 strbuf_addstr(&ctx->message, "Revert \"");
2353 strbuf_addstr(&ctx->message, msg.subject);
2354 strbuf_addstr(&ctx->message, "\"");
2356 strbuf_addstr(&ctx->message, "\n\nThis reverts commit ");
2357 refer_to_commit(opts, &ctx->message, commit);
2359 if (commit->parents && commit->parents->next) {
2360 strbuf_addstr(&ctx->message, ", reversing\nchanges made to ");
2361 refer_to_commit(opts, &ctx->message, parent);
2363 strbuf_addstr(&ctx->message, ".\n");
2364 } else {
2365 const char *p;
2367 base = parent;
2368 base_label = msg.parent_label;
2369 next = commit;
2370 next_label = msg.label;
2372 /* Append the commit log message to ctx->message. */
2373 if (find_commit_subject(msg.message, &p))
2374 strbuf_addstr(&ctx->message, p);
2376 if (opts->record_origin) {
2377 strbuf_complete_line(&ctx->message);
2378 if (!has_conforming_footer(&ctx->message, NULL, 0))
2379 strbuf_addch(&ctx->message, '\n');
2380 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2381 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid));
2382 strbuf_addstr(&ctx->message, ")\n");
2384 if (!is_fixup(command))
2385 author = get_author(msg.message);
2387 ctx->have_message = 1;
2389 if (command == TODO_REWORD)
2390 reword = 1;
2391 else if (is_fixup(command)) {
2392 if (update_squash_messages(r, command, commit,
2393 opts, item->flags)) {
2394 res = -1;
2395 goto leave;
2397 flags |= AMEND_MSG;
2398 if (!final_fixup)
2399 msg_file = rebase_path_squash_msg();
2400 else if (file_exists(rebase_path_fixup_msg())) {
2401 flags |= VERBATIM_MSG;
2402 msg_file = rebase_path_fixup_msg();
2403 } else {
2404 const char *dest = git_path_squash_msg(r);
2405 unlink(dest);
2406 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2407 res = error(_("could not copy '%s' to '%s'"),
2408 rebase_path_squash_msg(), dest);
2409 goto leave;
2411 unlink(git_path_merge_msg(r));
2412 msg_file = dest;
2413 flags |= EDIT_MSG;
2417 if (opts->signoff && !is_fixup(command))
2418 append_signoff(&ctx->message, 0, 0);
2420 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2421 res = -1;
2422 else if (!opts->strategy ||
2423 !strcmp(opts->strategy, "recursive") ||
2424 !strcmp(opts->strategy, "ort") ||
2425 command == TODO_REVERT) {
2426 res = do_recursive_merge(r, base, next, base_label, next_label,
2427 &head, &ctx->message, opts);
2428 if (res < 0)
2429 goto leave;
2431 res |= write_message(ctx->message.buf, ctx->message.len,
2432 git_path_merge_msg(r), 0);
2433 } else {
2434 struct commit_list *common = NULL;
2435 struct commit_list *remotes = NULL;
2437 res = write_message(ctx->message.buf, ctx->message.len,
2438 git_path_merge_msg(r), 0);
2440 commit_list_insert(base, &common);
2441 commit_list_insert(next, &remotes);
2442 res |= try_merge_command(r, opts->strategy,
2443 opts->xopts.nr, opts->xopts.v,
2444 common, oid_to_hex(&head), remotes);
2445 free_commit_list(common);
2446 free_commit_list(remotes);
2450 * If the merge was clean or if it failed due to conflict, we write
2451 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2452 * However, if the merge did not even start, then we don't want to
2453 * write it at all.
2455 if ((command == TODO_PICK || command == TODO_REWORD ||
2456 command == TODO_EDIT) && !opts->no_commit &&
2457 (res == 0 || res == 1) &&
2458 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2459 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2460 res = -1;
2461 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2462 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2463 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2464 res = -1;
2466 if (res) {
2467 error(command == TODO_REVERT
2468 ? _("could not revert %s... %s")
2469 : _("could not apply %s... %s"),
2470 short_commit_name(r, commit), msg.subject);
2471 print_advice(r, res == 1, opts);
2472 repo_rerere(r, opts->allow_rerere_auto);
2473 goto leave;
2476 drop_commit = 0;
2477 allow = allow_empty(r, opts, commit);
2478 if (allow < 0) {
2479 res = allow;
2480 goto leave;
2481 } else if (allow == 1) {
2482 flags |= ALLOW_EMPTY;
2483 } else if (allow == 2) {
2484 drop_commit = 1;
2485 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2486 NULL, REF_NO_DEREF);
2487 unlink(git_path_merge_msg(r));
2488 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2489 NULL, REF_NO_DEREF);
2490 fprintf(stderr,
2491 _("dropping %s %s -- patch contents already upstream\n"),
2492 oid_to_hex(&commit->object.oid), msg.subject);
2493 } /* else allow == 0 and there's nothing special to do */
2494 if (!opts->no_commit && !drop_commit) {
2495 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2496 res = do_commit(r, msg_file, author, opts, flags,
2497 commit? &commit->object.oid : NULL);
2498 else
2499 res = error(_("unable to parse commit author"));
2500 *check_todo = !!(flags & EDIT_MSG);
2501 if (!res && reword) {
2502 fast_forward_edit:
2503 res = run_git_commit(NULL, opts, EDIT_MSG |
2504 VERIFY_MSG | AMEND_MSG |
2505 (flags & ALLOW_EMPTY));
2506 *check_todo = 1;
2511 if (!res && final_fixup) {
2512 unlink(rebase_path_fixup_msg());
2513 unlink(rebase_path_squash_msg());
2514 unlink(rebase_path_current_fixups());
2515 strbuf_reset(&ctx->current_fixups);
2516 ctx->current_fixup_count = 0;
2519 leave:
2520 free_message(commit, &msg);
2521 free(author);
2522 update_abort_safety_file();
2524 return res;
2527 static int prepare_revs(struct replay_opts *opts)
2530 * picking (but not reverting) ranges (but not individual revisions)
2531 * should be done in reverse
2533 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2534 opts->revs->reverse ^= 1;
2536 if (prepare_revision_walk(opts->revs))
2537 return error(_("revision walk setup failed"));
2539 return 0;
2542 static int read_and_refresh_cache(struct repository *r,
2543 struct replay_opts *opts)
2545 struct lock_file index_lock = LOCK_INIT;
2546 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2547 if (repo_read_index(r) < 0) {
2548 rollback_lock_file(&index_lock);
2549 return error(_("git %s: failed to read the index"),
2550 action_name(opts));
2552 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2554 if (index_fd >= 0) {
2555 if (write_locked_index(r->index, &index_lock,
2556 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2557 return error(_("git %s: failed to refresh the index"),
2558 action_name(opts));
2563 * If we are resolving merges in any way other than "ort", then
2564 * expand the sparse index.
2566 if (opts->strategy && strcmp(opts->strategy, "ort"))
2567 ensure_full_index(r->index);
2568 return 0;
2571 void todo_list_release(struct todo_list *todo_list)
2573 strbuf_release(&todo_list->buf);
2574 FREE_AND_NULL(todo_list->items);
2575 todo_list->nr = todo_list->alloc = 0;
2578 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2580 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2581 return todo_list->items + todo_list->nr++;
2584 const char *todo_item_get_arg(struct todo_list *todo_list,
2585 struct todo_item *item)
2587 return todo_list->buf.buf + item->arg_offset;
2590 static int is_command(enum todo_command command, const char **bol)
2592 const char *str = todo_command_info[command].str;
2593 const char nick = todo_command_info[command].c;
2594 const char *p = *bol;
2596 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2597 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2598 (*bol = p);
2601 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2603 switch (command) {
2604 case TODO_LABEL:
2606 * '#' is not a valid label as the merge command uses it to
2607 * separate merge parents from the commit subject.
2609 if (!strcmp(arg, "#") ||
2610 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2611 return error(_("'%s' is not a valid label"), arg);
2612 break;
2614 case TODO_UPDATE_REF:
2615 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2616 return error(_("'%s' is not a valid refname"), arg);
2617 if (check_refname_format(arg, 0))
2618 return error(_("update-ref requires a fully qualified "
2619 "refname e.g. refs/heads/%s"), arg);
2620 break;
2622 default:
2623 BUG("unexpected todo_command");
2626 return 0;
2629 static int check_merge_commit_insn(enum todo_command command)
2631 switch(command) {
2632 case TODO_PICK:
2633 error(_("'%s' does not accept merge commits"),
2634 todo_command_info[command].str);
2635 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2637 * TRANSLATORS: 'pick' and 'merge -C' should not be
2638 * translated.
2640 "'pick' does not take a merge commit. If you wanted to\n"
2641 "replay the merge, use 'merge -C' on the commit."));
2642 return -1;
2644 case TODO_REWORD:
2645 error(_("'%s' does not accept merge commits"),
2646 todo_command_info[command].str);
2647 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2649 * TRANSLATORS: 'reword' and 'merge -c' should not be
2650 * translated.
2652 "'reword' does not take a merge commit. If you wanted to\n"
2653 "replay the merge and reword the commit message, use\n"
2654 "'merge -c' on the commit"));
2655 return -1;
2657 case TODO_EDIT:
2658 error(_("'%s' does not accept merge commits"),
2659 todo_command_info[command].str);
2660 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2662 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2663 * not be translated.
2665 "'edit' does not take a merge commit. If you wanted to\n"
2666 "replay the merge, use 'merge -C' on the commit, and then\n"
2667 "'break' to give the control back to you so that you can\n"
2668 "do 'git commit --amend && git rebase --continue'."));
2669 return -1;
2671 case TODO_FIXUP:
2672 case TODO_SQUASH:
2673 return error(_("cannot squash merge commit into another commit"));
2675 case TODO_MERGE:
2676 return 0;
2678 default:
2679 BUG("unexpected todo_command");
2683 static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2684 struct todo_item *item, const char *buf,
2685 const char *bol, char *eol)
2687 struct object_id commit_oid;
2688 char *end_of_object_name;
2689 int i, saved, status, padding;
2691 item->flags = 0;
2693 /* left-trim */
2694 bol += strspn(bol, " \t");
2696 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
2697 item->command = TODO_COMMENT;
2698 item->commit = NULL;
2699 item->arg_offset = bol - buf;
2700 item->arg_len = eol - bol;
2701 return 0;
2704 for (i = 0; i < TODO_COMMENT; i++)
2705 if (is_command(i, &bol)) {
2706 item->command = i;
2707 break;
2709 if (i >= TODO_COMMENT)
2710 return error(_("invalid command '%.*s'"),
2711 (int)strcspn(bol, " \t\r\n"), bol);
2713 /* Eat up extra spaces/ tabs before object name */
2714 padding = strspn(bol, " \t");
2715 bol += padding;
2717 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2718 if (bol != eol)
2719 return error(_("%s does not accept arguments: '%s'"),
2720 command_to_string(item->command), bol);
2721 item->commit = NULL;
2722 item->arg_offset = bol - buf;
2723 item->arg_len = eol - bol;
2724 return 0;
2727 if (!padding)
2728 return error(_("missing arguments for %s"),
2729 command_to_string(item->command));
2731 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2732 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2733 int ret = 0;
2735 item->commit = NULL;
2736 item->arg_offset = bol - buf;
2737 item->arg_len = (int)(eol - bol);
2738 if (item->command == TODO_LABEL ||
2739 item->command == TODO_UPDATE_REF) {
2740 saved = *eol;
2741 *eol = '\0';
2742 ret = check_label_or_ref_arg(item->command, bol);
2743 *eol = saved;
2745 return ret;
2748 if (item->command == TODO_FIXUP) {
2749 if (skip_prefix(bol, "-C", &bol)) {
2750 bol += strspn(bol, " \t");
2751 item->flags |= TODO_REPLACE_FIXUP_MSG;
2752 } else if (skip_prefix(bol, "-c", &bol)) {
2753 bol += strspn(bol, " \t");
2754 item->flags |= TODO_EDIT_FIXUP_MSG;
2758 if (item->command == TODO_MERGE) {
2759 if (skip_prefix(bol, "-C", &bol))
2760 bol += strspn(bol, " \t");
2761 else if (skip_prefix(bol, "-c", &bol)) {
2762 bol += strspn(bol, " \t");
2763 item->flags |= TODO_EDIT_MERGE_MSG;
2764 } else {
2765 item->flags |= TODO_EDIT_MERGE_MSG;
2766 item->commit = NULL;
2767 item->arg_offset = bol - buf;
2768 item->arg_len = (int)(eol - bol);
2769 return 0;
2773 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2774 saved = *end_of_object_name;
2775 *end_of_object_name = '\0';
2776 status = repo_get_oid(r, bol, &commit_oid);
2777 if (status < 0)
2778 error(_("could not parse '%s'"), bol); /* return later */
2779 *end_of_object_name = saved;
2781 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2782 item->arg_offset = bol - buf;
2783 item->arg_len = (int)(eol - bol);
2785 if (status < 0)
2786 return status;
2788 item->commit = lookup_commit_reference(r, &commit_oid);
2789 if (!item->commit)
2790 return -1;
2791 if (is_rebase_i(opts) &&
2792 item->commit->parents && item->commit->parents->next)
2793 return check_merge_commit_insn(item->command);
2794 return 0;
2797 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2799 const char *todo_file, *bol;
2800 struct strbuf buf = STRBUF_INIT;
2801 int ret = 0;
2803 todo_file = git_path_todo_file();
2804 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2805 if (errno == ENOENT || errno == ENOTDIR)
2806 return -1;
2807 else
2808 return error_errno("unable to open '%s'", todo_file);
2810 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2811 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2812 *action = REPLAY_PICK;
2813 else if (is_command(TODO_REVERT, &bol) &&
2814 (*bol == ' ' || *bol == '\t'))
2815 *action = REPLAY_REVERT;
2816 else
2817 ret = -1;
2819 strbuf_release(&buf);
2821 return ret;
2824 int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2825 char *buf, struct todo_list *todo_list)
2827 struct todo_item *item;
2828 char *p = buf, *next_p;
2829 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2831 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2833 for (i = 1; *p; i++, p = next_p) {
2834 char *eol = strchrnul(p, '\n');
2836 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2838 if (p != eol && eol[-1] == '\r')
2839 eol--; /* strip Carriage Return */
2841 item = append_new_todo(todo_list);
2842 item->offset_in_buf = p - todo_list->buf.buf;
2843 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2844 res = error(_("invalid line %d: %.*s"),
2845 i, (int)(eol - p), p);
2846 item->command = TODO_COMMENT + 1;
2847 item->arg_offset = p - buf;
2848 item->arg_len = (int)(eol - p);
2849 item->commit = NULL;
2852 if (item->command != TODO_COMMENT)
2853 todo_list->total_nr++;
2855 if (fixup_okay)
2856 ; /* do nothing */
2857 else if (is_fixup(item->command))
2858 res = error(_("cannot '%s' without a previous commit"),
2859 command_to_string(item->command));
2860 else if (!is_noop(item->command))
2861 fixup_okay = 1;
2864 return res;
2867 static int count_commands(struct todo_list *todo_list)
2869 int count = 0, i;
2871 for (i = 0; i < todo_list->nr; i++)
2872 if (todo_list->items[i].command != TODO_COMMENT)
2873 count++;
2875 return count;
2878 static int get_item_line_offset(struct todo_list *todo_list, int index)
2880 return index < todo_list->nr ?
2881 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2884 static const char *get_item_line(struct todo_list *todo_list, int index)
2886 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2889 static int get_item_line_length(struct todo_list *todo_list, int index)
2891 return get_item_line_offset(todo_list, index + 1)
2892 - get_item_line_offset(todo_list, index);
2895 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2897 int fd;
2898 ssize_t len;
2900 fd = open(path, O_RDONLY);
2901 if (fd < 0)
2902 return error_errno(_("could not open '%s'"), path);
2903 len = strbuf_read(sb, fd, 0);
2904 close(fd);
2905 if (len < 0)
2906 return error(_("could not read '%s'."), path);
2907 return len;
2910 static int have_finished_the_last_pick(void)
2912 struct strbuf buf = STRBUF_INIT;
2913 const char *eol;
2914 const char *todo_path = git_path_todo_file();
2915 int ret = 0;
2917 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2918 if (errno == ENOENT) {
2919 return 0;
2920 } else {
2921 error_errno("unable to open '%s'", todo_path);
2922 return 0;
2925 /* If there is only one line then we are done */
2926 eol = strchr(buf.buf, '\n');
2927 if (!eol || !eol[1])
2928 ret = 1;
2930 strbuf_release(&buf);
2932 return ret;
2935 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2937 struct replay_opts opts = REPLAY_OPTS_INIT;
2938 int need_cleanup = 0;
2940 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2941 if (!refs_delete_ref(get_main_ref_store(r), "",
2942 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2943 verbose)
2944 warning(_("cancelling a cherry picking in progress"));
2945 opts.action = REPLAY_PICK;
2946 need_cleanup = 1;
2949 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2950 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2951 NULL, REF_NO_DEREF) &&
2952 verbose)
2953 warning(_("cancelling a revert in progress"));
2954 opts.action = REPLAY_REVERT;
2955 need_cleanup = 1;
2958 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2959 NULL, REF_NO_DEREF);
2961 if (!need_cleanup)
2962 goto out;
2964 if (!have_finished_the_last_pick())
2965 goto out;
2967 sequencer_remove_state(&opts);
2968 out:
2969 replay_opts_release(&opts);
2972 static void todo_list_write_total_nr(struct todo_list *todo_list)
2974 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2976 if (f) {
2977 fprintf(f, "%d\n", todo_list->total_nr);
2978 fclose(f);
2982 static int read_populate_todo(struct repository *r,
2983 struct todo_list *todo_list,
2984 struct replay_opts *opts)
2986 const char *todo_file = get_todo_path(opts);
2987 int res;
2989 strbuf_reset(&todo_list->buf);
2990 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2991 return -1;
2993 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
2994 if (res) {
2995 if (is_rebase_i(opts))
2996 return error(_("please fix this using "
2997 "'git rebase --edit-todo'."));
2998 return error(_("unusable instruction sheet: '%s'"), todo_file);
3001 if (!todo_list->nr &&
3002 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3003 return error(_("no commits parsed."));
3005 if (!is_rebase_i(opts)) {
3006 enum todo_command valid =
3007 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3008 int i;
3010 for (i = 0; i < todo_list->nr; i++)
3011 if (valid == todo_list->items[i].command)
3012 continue;
3013 else if (valid == TODO_PICK)
3014 return error(_("cannot cherry-pick during a revert."));
3015 else
3016 return error(_("cannot revert during a cherry-pick."));
3019 if (is_rebase_i(opts)) {
3020 struct todo_list done = TODO_LIST_INIT;
3022 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3023 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3024 todo_list->done_nr = count_commands(&done);
3025 else
3026 todo_list->done_nr = 0;
3028 todo_list->total_nr = todo_list->done_nr
3029 + count_commands(todo_list);
3030 todo_list_release(&done);
3032 todo_list_write_total_nr(todo_list);
3035 return 0;
3038 static int git_config_string_dup(char **dest,
3039 const char *var, const char *value)
3041 if (!value)
3042 return config_error_nonbool(var);
3043 free(*dest);
3044 *dest = xstrdup(value);
3045 return 0;
3048 static int populate_opts_cb(const char *key, const char *value,
3049 const struct config_context *ctx,
3050 void *data)
3052 struct replay_opts *opts = data;
3053 int error_flag = 1;
3055 if (!value)
3056 error_flag = 0;
3057 else if (!strcmp(key, "options.no-commit"))
3058 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3059 else if (!strcmp(key, "options.edit"))
3060 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3061 else if (!strcmp(key, "options.allow-empty"))
3062 opts->allow_empty =
3063 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3064 else if (!strcmp(key, "options.allow-empty-message"))
3065 opts->allow_empty_message =
3066 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3067 else if (!strcmp(key, "options.drop-redundant-commits"))
3068 opts->drop_redundant_commits =
3069 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3070 else if (!strcmp(key, "options.keep-redundant-commits"))
3071 opts->keep_redundant_commits =
3072 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3073 else if (!strcmp(key, "options.signoff"))
3074 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3075 else if (!strcmp(key, "options.record-origin"))
3076 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3077 else if (!strcmp(key, "options.allow-ff"))
3078 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3079 else if (!strcmp(key, "options.mainline"))
3080 opts->mainline = git_config_int(key, value, ctx->kvi);
3081 else if (!strcmp(key, "options.strategy"))
3082 git_config_string_dup(&opts->strategy, key, value);
3083 else if (!strcmp(key, "options.gpg-sign"))
3084 git_config_string_dup(&opts->gpg_sign, key, value);
3085 else if (!strcmp(key, "options.strategy-option")) {
3086 strvec_push(&opts->xopts, value);
3087 } else if (!strcmp(key, "options.allow-rerere-auto"))
3088 opts->allow_rerere_auto =
3089 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3090 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3091 else if (!strcmp(key, "options.default-msg-cleanup")) {
3092 opts->explicit_cleanup = 1;
3093 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3094 } else
3095 return error(_("invalid key: %s"), key);
3097 if (!error_flag)
3098 return error(_("invalid value for '%s': '%s'"), key, value);
3100 return 0;
3103 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3105 int i;
3106 int count;
3107 const char **argv;
3108 char *strategy_opts_string = raw_opts;
3110 if (*strategy_opts_string == ' ')
3111 strategy_opts_string++;
3113 count = split_cmdline(strategy_opts_string, &argv);
3114 if (count < 0)
3115 BUG("could not split '%s': %s", strategy_opts_string,
3116 split_cmdline_strerror(count));
3117 for (i = 0; i < count; i++) {
3118 const char *arg = argv[i];
3120 skip_prefix(arg, "--", &arg);
3121 strvec_push(&opts->xopts, arg);
3123 free(argv);
3126 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3128 strbuf_reset(buf);
3129 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3130 return;
3131 opts->strategy = strbuf_detach(buf, NULL);
3132 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3133 return;
3135 parse_strategy_opts(opts, buf->buf);
3138 static int read_populate_opts(struct replay_opts *opts)
3140 struct replay_ctx *ctx = opts->ctx;
3142 if (is_rebase_i(opts)) {
3143 struct strbuf buf = STRBUF_INIT;
3144 int ret = 0;
3146 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3147 READ_ONELINER_SKIP_IF_EMPTY)) {
3148 if (!starts_with(buf.buf, "-S"))
3149 strbuf_reset(&buf);
3150 else {
3151 free(opts->gpg_sign);
3152 opts->gpg_sign = xstrdup(buf.buf + 2);
3154 strbuf_reset(&buf);
3157 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3158 READ_ONELINER_SKIP_IF_EMPTY)) {
3159 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3160 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3161 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3162 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3163 strbuf_reset(&buf);
3166 if (file_exists(rebase_path_verbose()))
3167 opts->verbose = 1;
3169 if (file_exists(rebase_path_quiet()))
3170 opts->quiet = 1;
3172 if (file_exists(rebase_path_signoff())) {
3173 opts->allow_ff = 0;
3174 opts->signoff = 1;
3177 if (file_exists(rebase_path_cdate_is_adate())) {
3178 opts->allow_ff = 0;
3179 opts->committer_date_is_author_date = 1;
3182 if (file_exists(rebase_path_ignore_date())) {
3183 opts->allow_ff = 0;
3184 opts->ignore_date = 1;
3187 if (file_exists(rebase_path_reschedule_failed_exec()))
3188 opts->reschedule_failed_exec = 1;
3189 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3190 opts->reschedule_failed_exec = 0;
3192 if (file_exists(rebase_path_drop_redundant_commits()))
3193 opts->drop_redundant_commits = 1;
3195 if (file_exists(rebase_path_keep_redundant_commits()))
3196 opts->keep_redundant_commits = 1;
3198 read_strategy_opts(opts, &buf);
3199 strbuf_reset(&buf);
3201 if (read_oneliner(&ctx->current_fixups,
3202 rebase_path_current_fixups(),
3203 READ_ONELINER_SKIP_IF_EMPTY)) {
3204 const char *p = ctx->current_fixups.buf;
3205 ctx->current_fixup_count = 1;
3206 while ((p = strchr(p, '\n'))) {
3207 ctx->current_fixup_count++;
3208 p++;
3212 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3213 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3214 ret = error(_("unusable squash-onto"));
3215 goto done_rebase_i;
3217 opts->have_squash_onto = 1;
3220 done_rebase_i:
3221 strbuf_release(&buf);
3222 return ret;
3225 if (!file_exists(git_path_opts_file()))
3226 return 0;
3228 * The function git_parse_source(), called from git_config_from_file(),
3229 * may die() in case of a syntactically incorrect file. We do not care
3230 * about this case, though, because we wrote that file ourselves, so we
3231 * are pretty certain that it is syntactically correct.
3233 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3234 return error(_("malformed options sheet: '%s'"),
3235 git_path_opts_file());
3236 return 0;
3239 static void write_strategy_opts(struct replay_opts *opts)
3241 struct strbuf buf = STRBUF_INIT;
3244 * Quote strategy options so that they can be read correctly
3245 * by split_cmdline().
3247 quote_cmdline(&buf, opts->xopts.v);
3248 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3249 strbuf_release(&buf);
3252 int write_basic_state(struct replay_opts *opts, const char *head_name,
3253 struct commit *onto, const struct object_id *orig_head)
3255 if (head_name)
3256 write_file(rebase_path_head_name(), "%s\n", head_name);
3257 if (onto)
3258 write_file(rebase_path_onto(), "%s\n",
3259 oid_to_hex(&onto->object.oid));
3260 if (orig_head)
3261 write_file(rebase_path_orig_head(), "%s\n",
3262 oid_to_hex(orig_head));
3264 if (opts->quiet)
3265 write_file(rebase_path_quiet(), "%s", "");
3266 if (opts->verbose)
3267 write_file(rebase_path_verbose(), "%s", "");
3268 if (opts->strategy)
3269 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3270 if (opts->xopts.nr > 0)
3271 write_strategy_opts(opts);
3273 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3274 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3275 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3276 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3278 if (opts->gpg_sign)
3279 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3280 if (opts->signoff)
3281 write_file(rebase_path_signoff(), "--signoff\n");
3282 if (opts->drop_redundant_commits)
3283 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3284 if (opts->keep_redundant_commits)
3285 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3286 if (opts->committer_date_is_author_date)
3287 write_file(rebase_path_cdate_is_adate(), "%s", "");
3288 if (opts->ignore_date)
3289 write_file(rebase_path_ignore_date(), "%s", "");
3290 if (opts->reschedule_failed_exec)
3291 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3292 else
3293 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3295 return 0;
3298 static int walk_revs_populate_todo(struct todo_list *todo_list,
3299 struct replay_opts *opts)
3301 enum todo_command command = opts->action == REPLAY_PICK ?
3302 TODO_PICK : TODO_REVERT;
3303 const char *command_string = todo_command_info[command].str;
3304 const char *encoding;
3305 struct commit *commit;
3307 if (prepare_revs(opts))
3308 return -1;
3310 encoding = get_log_output_encoding();
3312 while ((commit = get_revision(opts->revs))) {
3313 struct todo_item *item = append_new_todo(todo_list);
3314 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3315 commit, NULL,
3316 encoding);
3317 const char *subject;
3318 int subject_len;
3320 item->command = command;
3321 item->commit = commit;
3322 item->arg_offset = 0;
3323 item->arg_len = 0;
3324 item->offset_in_buf = todo_list->buf.len;
3325 subject_len = find_commit_subject(commit_buffer, &subject);
3326 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3327 short_commit_name(the_repository, commit),
3328 subject_len, subject);
3329 repo_unuse_commit_buffer(the_repository, commit,
3330 commit_buffer);
3333 if (!todo_list->nr)
3334 return error(_("empty commit set passed"));
3336 return 0;
3339 static int create_seq_dir(struct repository *r)
3341 enum replay_action action;
3342 const char *in_progress_error = NULL;
3343 const char *in_progress_advice = NULL;
3344 unsigned int advise_skip =
3345 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3346 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3348 if (!sequencer_get_last_command(r, &action)) {
3349 switch (action) {
3350 case REPLAY_REVERT:
3351 in_progress_error = _("revert is already in progress");
3352 in_progress_advice =
3353 _("try \"git revert (--continue | %s--abort | --quit)\"");
3354 break;
3355 case REPLAY_PICK:
3356 in_progress_error = _("cherry-pick is already in progress");
3357 in_progress_advice =
3358 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3359 break;
3360 default:
3361 BUG("unexpected action in create_seq_dir");
3364 if (in_progress_error) {
3365 error("%s", in_progress_error);
3366 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3367 advise(in_progress_advice,
3368 advise_skip ? "--skip | " : "");
3369 return -1;
3371 if (mkdir(git_path_seq_dir(), 0777) < 0)
3372 return error_errno(_("could not create sequencer directory '%s'"),
3373 git_path_seq_dir());
3375 return 0;
3378 static int save_head(const char *head)
3380 return write_message(head, strlen(head), git_path_head_file(), 1);
3383 static int rollback_is_safe(void)
3385 struct strbuf sb = STRBUF_INIT;
3386 struct object_id expected_head, actual_head;
3388 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3389 strbuf_trim(&sb);
3390 if (get_oid_hex(sb.buf, &expected_head)) {
3391 strbuf_release(&sb);
3392 die(_("could not parse %s"), git_path_abort_safety_file());
3394 strbuf_release(&sb);
3396 else if (errno == ENOENT)
3397 oidclr(&expected_head);
3398 else
3399 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3401 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3402 oidclr(&actual_head);
3404 return oideq(&actual_head, &expected_head);
3407 static int reset_merge(const struct object_id *oid)
3409 struct child_process cmd = CHILD_PROCESS_INIT;
3411 cmd.git_cmd = 1;
3412 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3414 if (!is_null_oid(oid))
3415 strvec_push(&cmd.args, oid_to_hex(oid));
3417 return run_command(&cmd);
3420 static int rollback_single_pick(struct repository *r)
3422 struct object_id head_oid;
3424 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3425 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3426 return error(_("no cherry-pick or revert in progress"));
3427 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3428 return error(_("cannot resolve HEAD"));
3429 if (is_null_oid(&head_oid))
3430 return error(_("cannot abort from a branch yet to be born"));
3431 return reset_merge(&head_oid);
3434 static int skip_single_pick(void)
3436 struct object_id head;
3438 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3439 return error(_("cannot resolve HEAD"));
3440 return reset_merge(&head);
3443 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3445 FILE *f;
3446 struct object_id oid;
3447 struct strbuf buf = STRBUF_INIT;
3448 const char *p;
3450 f = fopen(git_path_head_file(), "r");
3451 if (!f && errno == ENOENT) {
3453 * There is no multiple-cherry-pick in progress.
3454 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3455 * a single-cherry-pick in progress, abort that.
3457 return rollback_single_pick(r);
3459 if (!f)
3460 return error_errno(_("cannot open '%s'"), git_path_head_file());
3461 if (strbuf_getline_lf(&buf, f)) {
3462 error(_("cannot read '%s': %s"), git_path_head_file(),
3463 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3464 fclose(f);
3465 goto fail;
3467 fclose(f);
3468 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3469 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3470 git_path_head_file());
3471 goto fail;
3473 if (is_null_oid(&oid)) {
3474 error(_("cannot abort from a branch yet to be born"));
3475 goto fail;
3478 if (!rollback_is_safe()) {
3479 /* Do not error, just do not rollback */
3480 warning(_("You seem to have moved HEAD. "
3481 "Not rewinding, check your HEAD!"));
3482 } else
3483 if (reset_merge(&oid))
3484 goto fail;
3485 strbuf_release(&buf);
3486 return sequencer_remove_state(opts);
3487 fail:
3488 strbuf_release(&buf);
3489 return -1;
3492 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3494 enum replay_action action = -1;
3495 sequencer_get_last_command(r, &action);
3498 * Check whether the subcommand requested to skip the commit is actually
3499 * in progress and that it's safe to skip the commit.
3501 * opts->action tells us which subcommand requested to skip the commit.
3502 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3503 * action is in progress and we can skip the commit.
3505 * Otherwise we check that the last instruction was related to the
3506 * particular subcommand we're trying to execute and barf if that's not
3507 * the case.
3509 * Finally we check that the rollback is "safe", i.e., has the HEAD
3510 * moved? In this case, it doesn't make sense to "reset the merge" and
3511 * "skip the commit" as the user already handled this by committing. But
3512 * we'd not want to barf here, instead give advice on how to proceed. We
3513 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3514 * it gets removed when the user commits, so if it still exists we're
3515 * sure the user can't have committed before.
3517 switch (opts->action) {
3518 case REPLAY_REVERT:
3519 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3520 if (action != REPLAY_REVERT)
3521 return error(_("no revert in progress"));
3522 if (!rollback_is_safe())
3523 goto give_advice;
3525 break;
3526 case REPLAY_PICK:
3527 if (!refs_ref_exists(get_main_ref_store(r),
3528 "CHERRY_PICK_HEAD")) {
3529 if (action != REPLAY_PICK)
3530 return error(_("no cherry-pick in progress"));
3531 if (!rollback_is_safe())
3532 goto give_advice;
3534 break;
3535 default:
3536 BUG("unexpected action in sequencer_skip");
3539 if (skip_single_pick())
3540 return error(_("failed to skip the commit"));
3541 if (!is_directory(git_path_seq_dir()))
3542 return 0;
3544 return sequencer_continue(r, opts);
3546 give_advice:
3547 error(_("there is nothing to skip"));
3549 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3550 advise(_("have you committed already?\n"
3551 "try \"git %s --continue\""),
3552 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3554 return -1;
3557 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3558 int reschedule)
3560 struct lock_file todo_lock = LOCK_INIT;
3561 const char *todo_path = get_todo_path(opts);
3562 int next = todo_list->current, offset, fd;
3565 * rebase -i writes "git-rebase-todo" without the currently executing
3566 * command, appending it to "done" instead.
3568 if (is_rebase_i(opts) && !reschedule)
3569 next++;
3571 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3572 if (fd < 0)
3573 return error_errno(_("could not lock '%s'"), todo_path);
3574 offset = get_item_line_offset(todo_list, next);
3575 if (write_in_full(fd, todo_list->buf.buf + offset,
3576 todo_list->buf.len - offset) < 0)
3577 return error_errno(_("could not write to '%s'"), todo_path);
3578 if (commit_lock_file(&todo_lock) < 0)
3579 return error(_("failed to finalize '%s'"), todo_path);
3581 if (is_rebase_i(opts) && !reschedule && next > 0) {
3582 const char *done = rebase_path_done();
3583 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3584 int ret = 0;
3586 if (fd < 0)
3587 return 0;
3588 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3589 get_item_line_length(todo_list, next - 1))
3590 < 0)
3591 ret = error_errno(_("could not write to '%s'"), done);
3592 if (close(fd) < 0)
3593 ret = error_errno(_("failed to finalize '%s'"), done);
3594 return ret;
3596 return 0;
3599 static int save_opts(struct replay_opts *opts)
3601 const char *opts_file = git_path_opts_file();
3602 int res = 0;
3604 if (opts->no_commit)
3605 res |= git_config_set_in_file_gently(opts_file,
3606 "options.no-commit", NULL, "true");
3607 if (opts->edit >= 0)
3608 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
3609 opts->edit ? "true" : "false");
3610 if (opts->allow_empty)
3611 res |= git_config_set_in_file_gently(opts_file,
3612 "options.allow-empty", NULL, "true");
3613 if (opts->allow_empty_message)
3614 res |= git_config_set_in_file_gently(opts_file,
3615 "options.allow-empty-message", NULL, "true");
3616 if (opts->drop_redundant_commits)
3617 res |= git_config_set_in_file_gently(opts_file,
3618 "options.drop-redundant-commits", NULL, "true");
3619 if (opts->keep_redundant_commits)
3620 res |= git_config_set_in_file_gently(opts_file,
3621 "options.keep-redundant-commits", NULL, "true");
3622 if (opts->signoff)
3623 res |= git_config_set_in_file_gently(opts_file,
3624 "options.signoff", NULL, "true");
3625 if (opts->record_origin)
3626 res |= git_config_set_in_file_gently(opts_file,
3627 "options.record-origin", NULL, "true");
3628 if (opts->allow_ff)
3629 res |= git_config_set_in_file_gently(opts_file,
3630 "options.allow-ff", NULL, "true");
3631 if (opts->mainline) {
3632 struct strbuf buf = STRBUF_INIT;
3633 strbuf_addf(&buf, "%d", opts->mainline);
3634 res |= git_config_set_in_file_gently(opts_file,
3635 "options.mainline", NULL, buf.buf);
3636 strbuf_release(&buf);
3638 if (opts->strategy)
3639 res |= git_config_set_in_file_gently(opts_file,
3640 "options.strategy", NULL, opts->strategy);
3641 if (opts->gpg_sign)
3642 res |= git_config_set_in_file_gently(opts_file,
3643 "options.gpg-sign", NULL, opts->gpg_sign);
3644 for (size_t i = 0; i < opts->xopts.nr; i++)
3645 res |= git_config_set_multivar_in_file_gently(opts_file,
3646 "options.strategy-option",
3647 opts->xopts.v[i], "^$", NULL, 0);
3648 if (opts->allow_rerere_auto)
3649 res |= git_config_set_in_file_gently(opts_file,
3650 "options.allow-rerere-auto", NULL,
3651 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3652 "true" : "false");
3654 if (opts->explicit_cleanup)
3655 res |= git_config_set_in_file_gently(opts_file,
3656 "options.default-msg-cleanup", NULL,
3657 describe_cleanup_mode(opts->default_msg_cleanup));
3658 return res;
3661 static int make_patch(struct repository *r,
3662 struct commit *commit,
3663 struct replay_opts *opts)
3665 struct rev_info log_tree_opt;
3666 const char *subject;
3667 char hex[GIT_MAX_HEXSZ + 1];
3668 int res = 0;
3670 if (!is_rebase_i(opts))
3671 BUG("make_patch should only be called when rebasing");
3673 oid_to_hex_r(hex, &commit->object.oid);
3674 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3675 return -1;
3676 res |= write_rebase_head(&commit->object.oid);
3678 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3679 repo_init_revisions(r, &log_tree_opt, NULL);
3680 log_tree_opt.abbrev = 0;
3681 log_tree_opt.diff = 1;
3682 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3683 log_tree_opt.disable_stdin = 1;
3684 log_tree_opt.no_commit_id = 1;
3685 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3686 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3687 if (!log_tree_opt.diffopt.file)
3688 res |= error_errno(_("could not open '%s'"),
3689 rebase_path_patch());
3690 else {
3691 res |= log_tree_commit(&log_tree_opt, commit);
3692 fclose(log_tree_opt.diffopt.file);
3695 if (!file_exists(rebase_path_message())) {
3696 const char *encoding = get_commit_output_encoding();
3697 const char *commit_buffer = repo_logmsg_reencode(r,
3698 commit, NULL,
3699 encoding);
3700 find_commit_subject(commit_buffer, &subject);
3701 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3702 repo_unuse_commit_buffer(r, commit,
3703 commit_buffer);
3705 release_revisions(&log_tree_opt);
3707 return res;
3710 static int intend_to_amend(void)
3712 struct object_id head;
3713 char *p;
3715 if (repo_get_oid(the_repository, "HEAD", &head))
3716 return error(_("cannot read HEAD"));
3718 p = oid_to_hex(&head);
3719 return write_message(p, strlen(p), rebase_path_amend(), 1);
3722 static int error_with_patch(struct repository *r,
3723 struct commit *commit,
3724 const char *subject, int subject_len,
3725 struct replay_opts *opts,
3726 int exit_code, int to_amend)
3728 struct replay_ctx *ctx = opts->ctx;
3731 * Write the commit message to be used by "git rebase
3732 * --continue". If a "fixup" or "squash" command has conflicts
3733 * then we will have already written rebase_path_message() in
3734 * error_failed_squash(). If an "edit" command was
3735 * fast-forwarded then we don't have a message in ctx->message
3736 * and rely on make_patch() to write rebase_path_message()
3737 * instead.
3739 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3740 write_message(ctx->message.buf, ctx->message.len,
3741 rebase_path_message(), 0))
3742 return error(_("could not write commit message file"));
3744 if (commit && make_patch(r, commit, opts))
3745 return -1;
3747 if (to_amend) {
3748 if (intend_to_amend())
3749 return -1;
3751 fprintf(stderr,
3752 _("You can amend the commit now, with\n"
3753 "\n"
3754 " git commit --amend %s\n"
3755 "\n"
3756 "Once you are satisfied with your changes, run\n"
3757 "\n"
3758 " git rebase --continue\n"),
3759 gpg_sign_opt_quoted(opts));
3760 } else if (exit_code) {
3761 if (commit)
3762 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3763 short_commit_name(r, commit), subject_len, subject);
3764 else
3766 * We don't have the hash of the parent so
3767 * just print the line from the todo file.
3769 fprintf_ln(stderr, _("Could not merge %.*s"),
3770 subject_len, subject);
3773 return exit_code;
3776 static int error_failed_squash(struct repository *r,
3777 struct commit *commit,
3778 struct replay_opts *opts,
3779 int subject_len,
3780 const char *subject)
3782 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3783 return error(_("could not copy '%s' to '%s'"),
3784 rebase_path_squash_msg(), rebase_path_message());
3785 unlink(git_path_merge_msg(r));
3786 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3787 return error(_("could not copy '%s' to '%s'"),
3788 rebase_path_message(),
3789 git_path_merge_msg(r));
3790 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3793 static int do_exec(struct repository *r, const char *command_line)
3795 struct child_process cmd = CHILD_PROCESS_INIT;
3796 int dirty, status;
3798 fprintf(stderr, _("Executing: %s\n"), command_line);
3799 cmd.use_shell = 1;
3800 strvec_push(&cmd.args, command_line);
3801 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3802 status = run_command(&cmd);
3804 /* force re-reading of the cache */
3805 discard_index(r->index);
3806 if (repo_read_index(r) < 0)
3807 return error(_("could not read index"));
3809 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3811 if (status) {
3812 warning(_("execution failed: %s\n%s"
3813 "You can fix the problem, and then run\n"
3814 "\n"
3815 " git rebase --continue\n"
3816 "\n"),
3817 command_line,
3818 dirty ? _("and made changes to the index and/or the "
3819 "working tree.\n") : "");
3820 if (status == 127)
3821 /* command not found */
3822 status = 1;
3823 } else if (dirty) {
3824 warning(_("execution succeeded: %s\nbut "
3825 "left changes to the index and/or the working tree.\n"
3826 "Commit or stash your changes, and then run\n"
3827 "\n"
3828 " git rebase --continue\n"
3829 "\n"), command_line);
3830 status = 1;
3833 return status;
3836 __attribute__((format (printf, 2, 3)))
3837 static int safe_append(const char *filename, const char *fmt, ...)
3839 va_list ap;
3840 struct lock_file lock = LOCK_INIT;
3841 int fd = hold_lock_file_for_update(&lock, filename,
3842 LOCK_REPORT_ON_ERROR);
3843 struct strbuf buf = STRBUF_INIT;
3845 if (fd < 0)
3846 return -1;
3848 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3849 error_errno(_("could not read '%s'"), filename);
3850 rollback_lock_file(&lock);
3851 return -1;
3853 strbuf_complete(&buf, '\n');
3854 va_start(ap, fmt);
3855 strbuf_vaddf(&buf, fmt, ap);
3856 va_end(ap);
3858 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3859 error_errno(_("could not write to '%s'"), filename);
3860 strbuf_release(&buf);
3861 rollback_lock_file(&lock);
3862 return -1;
3864 if (commit_lock_file(&lock) < 0) {
3865 strbuf_release(&buf);
3866 return error(_("failed to finalize '%s'"), filename);
3869 strbuf_release(&buf);
3870 return 0;
3873 static int do_label(struct repository *r, const char *name, int len)
3875 struct ref_store *refs = get_main_ref_store(r);
3876 struct ref_transaction *transaction;
3877 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3878 struct strbuf msg = STRBUF_INIT;
3879 int ret = 0;
3880 struct object_id head_oid;
3882 if (len == 1 && *name == '#')
3883 return error(_("illegal label name: '%.*s'"), len, name);
3885 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3886 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3888 transaction = ref_store_transaction_begin(refs, &err);
3889 if (!transaction) {
3890 error("%s", err.buf);
3891 ret = -1;
3892 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3893 error(_("could not read HEAD"));
3894 ret = -1;
3895 } else if (ref_transaction_update(transaction, ref_name.buf,
3896 &head_oid, NULL, NULL, NULL,
3897 0, msg.buf, &err) < 0 ||
3898 ref_transaction_commit(transaction, &err)) {
3899 error("%s", err.buf);
3900 ret = -1;
3902 ref_transaction_free(transaction);
3903 strbuf_release(&err);
3904 strbuf_release(&msg);
3906 if (!ret)
3907 ret = safe_append(rebase_path_refs_to_delete(),
3908 "%s\n", ref_name.buf);
3909 strbuf_release(&ref_name);
3911 return ret;
3914 static const char *sequencer_reflog_action(struct replay_opts *opts)
3916 if (!opts->reflog_action) {
3917 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3918 opts->reflog_action =
3919 xstrdup(opts->reflog_action ? opts->reflog_action
3920 : action_name(opts));
3923 return opts->reflog_action;
3926 __attribute__((format (printf, 3, 4)))
3927 static const char *reflog_message(struct replay_opts *opts,
3928 const char *sub_action, const char *fmt, ...)
3930 va_list ap;
3931 static struct strbuf buf = STRBUF_INIT;
3933 va_start(ap, fmt);
3934 strbuf_reset(&buf);
3935 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3936 if (sub_action)
3937 strbuf_addf(&buf, " (%s)", sub_action);
3938 if (fmt) {
3939 strbuf_addstr(&buf, ": ");
3940 strbuf_vaddf(&buf, fmt, ap);
3942 va_end(ap);
3944 return buf.buf;
3947 static struct commit *lookup_label(struct repository *r, const char *label,
3948 int len, struct strbuf *buf)
3950 struct commit *commit;
3951 struct object_id oid;
3953 strbuf_reset(buf);
3954 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3955 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
3956 commit = lookup_commit_object(r, &oid);
3957 } else {
3958 /* fall back to non-rewritten ref or commit */
3959 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3960 commit = lookup_commit_reference_by_name(buf->buf);
3963 if (!commit)
3964 error(_("could not resolve '%s'"), buf->buf);
3966 return commit;
3969 static int do_reset(struct repository *r,
3970 const char *name, int len,
3971 struct replay_opts *opts)
3973 struct strbuf ref_name = STRBUF_INIT;
3974 struct object_id oid;
3975 struct lock_file lock = LOCK_INIT;
3976 struct tree_desc desc = { 0 };
3977 struct tree *tree;
3978 struct unpack_trees_options unpack_tree_opts = { 0 };
3979 int ret = 0;
3981 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3982 return -1;
3984 if (len == 10 && !strncmp("[new root]", name, len)) {
3985 if (!opts->have_squash_onto) {
3986 const char *hex;
3987 if (commit_tree("", 0, the_hash_algo->empty_tree,
3988 NULL, &opts->squash_onto,
3989 NULL, NULL))
3990 return error(_("writing fake root commit"));
3991 opts->have_squash_onto = 1;
3992 hex = oid_to_hex(&opts->squash_onto);
3993 if (write_message(hex, strlen(hex),
3994 rebase_path_squash_onto(), 0))
3995 return error(_("writing squash-onto"));
3997 oidcpy(&oid, &opts->squash_onto);
3998 } else {
3999 int i;
4000 struct commit *commit;
4002 /* Determine the length of the label */
4003 for (i = 0; i < len; i++)
4004 if (isspace(name[i]))
4005 break;
4006 len = i;
4008 commit = lookup_label(r, name, len, &ref_name);
4009 if (!commit) {
4010 ret = -1;
4011 goto cleanup;
4013 oid = commit->object.oid;
4016 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4017 unpack_tree_opts.head_idx = 1;
4018 unpack_tree_opts.src_index = r->index;
4019 unpack_tree_opts.dst_index = r->index;
4020 unpack_tree_opts.fn = oneway_merge;
4021 unpack_tree_opts.merge = 1;
4022 unpack_tree_opts.update = 1;
4023 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4024 unpack_tree_opts.skip_cache_tree_update = 1;
4025 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4027 if (repo_read_index_unmerged(r)) {
4028 ret = error_resolve_conflict(action_name(opts));
4029 goto cleanup;
4032 if (!fill_tree_descriptor(r, &desc, &oid)) {
4033 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4034 goto cleanup;
4037 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4038 ret = -1;
4039 goto cleanup;
4042 tree = parse_tree_indirect(&oid);
4043 if (!tree)
4044 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4045 prime_cache_tree(r, r->index, tree);
4047 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4048 ret = error(_("could not write index"));
4050 if (!ret)
4051 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4052 len, name),
4053 "HEAD", &oid,
4054 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4055 cleanup:
4056 free((void *)desc.buffer);
4057 if (ret < 0)
4058 rollback_lock_file(&lock);
4059 strbuf_release(&ref_name);
4060 clear_unpack_trees_porcelain(&unpack_tree_opts);
4061 return ret;
4064 static int do_merge(struct repository *r,
4065 struct commit *commit,
4066 const char *arg, int arg_len,
4067 int flags, int *check_todo, struct replay_opts *opts)
4069 struct replay_ctx *ctx = opts->ctx;
4070 int run_commit_flags = 0;
4071 struct strbuf ref_name = STRBUF_INIT;
4072 struct commit *head_commit, *merge_commit, *i;
4073 struct commit_list *bases = NULL, *j;
4074 struct commit_list *to_merge = NULL, **tail = &to_merge;
4075 const char *strategy = !opts->xopts.nr &&
4076 (!opts->strategy ||
4077 !strcmp(opts->strategy, "recursive") ||
4078 !strcmp(opts->strategy, "ort")) ?
4079 NULL : opts->strategy;
4080 struct merge_options o;
4081 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4082 static struct lock_file lock;
4083 const char *p;
4085 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4086 ret = -1;
4087 goto leave_merge;
4090 head_commit = lookup_commit_reference_by_name("HEAD");
4091 if (!head_commit) {
4092 ret = error(_("cannot merge without a current revision"));
4093 goto leave_merge;
4097 * For octopus merges, the arg starts with the list of revisions to be
4098 * merged. The list is optionally followed by '#' and the oneline.
4100 merge_arg_len = oneline_offset = arg_len;
4101 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4102 if (!*p)
4103 break;
4104 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4105 p += 1 + strspn(p + 1, " \t\n");
4106 oneline_offset = p - arg;
4107 break;
4109 k = strcspn(p, " \t\n");
4110 if (!k)
4111 continue;
4112 merge_commit = lookup_label(r, p, k, &ref_name);
4113 if (!merge_commit) {
4114 ret = error(_("unable to parse '%.*s'"), k, p);
4115 goto leave_merge;
4117 tail = &commit_list_insert(merge_commit, tail)->next;
4118 p += k;
4119 merge_arg_len = p - arg;
4122 if (!to_merge) {
4123 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4124 goto leave_merge;
4127 if (opts->have_squash_onto &&
4128 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4130 * When the user tells us to "merge" something into a
4131 * "[new root]", let's simply fast-forward to the merge head.
4133 rollback_lock_file(&lock);
4134 if (to_merge->next)
4135 ret = error(_("octopus merge cannot be executed on "
4136 "top of a [new root]"));
4137 else
4138 ret = fast_forward_to(r, &to_merge->item->object.oid,
4139 &head_commit->object.oid, 0,
4140 opts);
4141 goto leave_merge;
4145 * If HEAD is not identical to the first parent of the original merge
4146 * commit, we cannot fast-forward.
4148 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4149 oideq(&commit->parents->item->object.oid,
4150 &head_commit->object.oid);
4153 * If any merge head is different from the original one, we cannot
4154 * fast-forward.
4156 if (can_fast_forward) {
4157 struct commit_list *p = commit->parents->next;
4159 for (j = to_merge; j && p; j = j->next, p = p->next)
4160 if (!oideq(&j->item->object.oid,
4161 &p->item->object.oid)) {
4162 can_fast_forward = 0;
4163 break;
4166 * If the number of merge heads differs from the original merge
4167 * commit, we cannot fast-forward.
4169 if (j || p)
4170 can_fast_forward = 0;
4173 if (can_fast_forward) {
4174 rollback_lock_file(&lock);
4175 ret = fast_forward_to(r, &commit->object.oid,
4176 &head_commit->object.oid, 0, opts);
4177 if (flags & TODO_EDIT_MERGE_MSG)
4178 goto fast_forward_edit;
4180 goto leave_merge;
4183 if (commit) {
4184 const char *encoding = get_commit_output_encoding();
4185 const char *message = repo_logmsg_reencode(r, commit, NULL,
4186 encoding);
4187 const char *body;
4188 int len;
4190 if (!message) {
4191 ret = error(_("could not get commit message of '%s'"),
4192 oid_to_hex(&commit->object.oid));
4193 goto leave_merge;
4195 write_author_script(message);
4196 find_commit_subject(message, &body);
4197 len = strlen(body);
4198 strbuf_add(&ctx->message, body, len);
4199 repo_unuse_commit_buffer(r, commit, message);
4200 } else {
4201 struct strbuf buf = STRBUF_INIT;
4203 strbuf_addf(&buf, "author %s", git_author_info(0));
4204 write_author_script(buf.buf);
4205 strbuf_release(&buf);
4207 if (oneline_offset < arg_len) {
4208 strbuf_add(&ctx->message, arg + oneline_offset,
4209 arg_len - oneline_offset);
4210 } else {
4211 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4212 to_merge->next ? "branches" : "branch",
4213 merge_arg_len, arg);
4216 ctx->have_message = 1;
4217 if (write_message(ctx->message.buf, ctx->message.len,
4218 git_path_merge_msg(r), 0)) {
4219 ret = error_errno(_("could not write '%s'"),
4220 git_path_merge_msg(r));
4221 goto leave_merge;
4224 if (strategy || to_merge->next) {
4225 /* Octopus merge */
4226 struct child_process cmd = CHILD_PROCESS_INIT;
4228 if (read_env_script(&cmd.env)) {
4229 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4231 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4232 goto leave_merge;
4235 if (opts->committer_date_is_author_date)
4236 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4237 opts->ignore_date ?
4238 "" :
4239 author_date_from_env(&cmd.env));
4240 if (opts->ignore_date)
4241 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4243 cmd.git_cmd = 1;
4244 strvec_push(&cmd.args, "merge");
4245 strvec_push(&cmd.args, "-s");
4246 if (!strategy)
4247 strvec_push(&cmd.args, "octopus");
4248 else {
4249 strvec_push(&cmd.args, strategy);
4250 for (k = 0; k < opts->xopts.nr; k++)
4251 strvec_pushf(&cmd.args,
4252 "-X%s", opts->xopts.v[k]);
4254 if (!(flags & TODO_EDIT_MERGE_MSG))
4255 strvec_push(&cmd.args, "--no-edit");
4256 else
4257 strvec_push(&cmd.args, "--edit");
4258 strvec_push(&cmd.args, "--no-ff");
4259 strvec_push(&cmd.args, "--no-log");
4260 strvec_push(&cmd.args, "--no-stat");
4261 strvec_push(&cmd.args, "-F");
4262 strvec_push(&cmd.args, git_path_merge_msg(r));
4263 if (opts->gpg_sign)
4264 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4265 else
4266 strvec_push(&cmd.args, "--no-gpg-sign");
4268 /* Add the tips to be merged */
4269 for (j = to_merge; j; j = j->next)
4270 strvec_push(&cmd.args,
4271 oid_to_hex(&j->item->object.oid));
4273 strbuf_release(&ref_name);
4274 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4275 NULL, REF_NO_DEREF);
4276 rollback_lock_file(&lock);
4278 ret = run_command(&cmd);
4280 /* force re-reading of the cache */
4281 if (!ret) {
4282 discard_index(r->index);
4283 if (repo_read_index(r) < 0)
4284 ret = error(_("could not read index"));
4286 goto leave_merge;
4289 merge_commit = to_merge->item;
4290 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4291 ret = -1;
4292 goto leave_merge;
4295 if (bases && oideq(&merge_commit->object.oid,
4296 &bases->item->object.oid)) {
4297 ret = 0;
4298 /* skip merging an ancestor of HEAD */
4299 goto leave_merge;
4302 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4303 git_path_merge_head(r), 0);
4304 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4306 bases = reverse_commit_list(bases);
4308 repo_read_index(r);
4309 init_merge_options(&o, r);
4310 o.branch1 = "HEAD";
4311 o.branch2 = ref_name.buf;
4312 o.buffer_output = 2;
4314 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4316 * TODO: Should use merge_incore_recursive() and
4317 * merge_switch_to_result(), skipping the call to
4318 * merge_switch_to_result() when we don't actually need to
4319 * update the index and working copy immediately.
4321 ret = merge_ort_recursive(&o,
4322 head_commit, merge_commit, bases,
4323 &i);
4324 } else {
4325 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4326 &i);
4328 if (ret <= 0)
4329 fputs(o.obuf.buf, stdout);
4330 strbuf_release(&o.obuf);
4331 if (ret < 0) {
4332 error(_("could not even attempt to merge '%.*s'"),
4333 merge_arg_len, arg);
4334 unlink(git_path_merge_msg(r));
4335 goto leave_merge;
4338 * The return value of merge_recursive() is 1 on clean, and 0 on
4339 * unclean merge.
4341 * Let's reverse that, so that do_merge() returns 0 upon success and
4342 * 1 upon failed merge (keeping the return value -1 for the cases where
4343 * we will want to reschedule the `merge` command).
4345 ret = !ret;
4347 if (r->index->cache_changed &&
4348 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4349 ret = error(_("merge: Unable to write new index file"));
4350 goto leave_merge;
4353 rollback_lock_file(&lock);
4354 if (ret)
4355 repo_rerere(r, opts->allow_rerere_auto);
4356 else
4358 * In case of problems, we now want to return a positive
4359 * value (a negative one would indicate that the `merge`
4360 * command needs to be rescheduled).
4362 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4363 run_commit_flags);
4365 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4366 fast_forward_edit:
4367 *check_todo = 1;
4368 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4369 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4373 leave_merge:
4374 strbuf_release(&ref_name);
4375 rollback_lock_file(&lock);
4376 free_commit_list(to_merge);
4377 return ret;
4380 static int write_update_refs_state(struct string_list *refs_to_oids)
4382 int result = 0;
4383 struct lock_file lock = LOCK_INIT;
4384 FILE *fp = NULL;
4385 struct string_list_item *item;
4386 char *path;
4388 path = rebase_path_update_refs(the_repository->gitdir);
4390 if (!refs_to_oids->nr) {
4391 if (unlink(path) && errno != ENOENT)
4392 result = error_errno(_("could not unlink: %s"), path);
4393 goto cleanup;
4396 if (safe_create_leading_directories(path)) {
4397 result = error(_("unable to create leading directories of %s"),
4398 path);
4399 goto cleanup;
4402 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4403 result = error(_("another 'rebase' process appears to be running; "
4404 "'%s.lock' already exists"),
4405 path);
4406 goto cleanup;
4409 fp = fdopen_lock_file(&lock, "w");
4410 if (!fp) {
4411 result = error_errno(_("could not open '%s' for writing"), path);
4412 rollback_lock_file(&lock);
4413 goto cleanup;
4416 for_each_string_list_item(item, refs_to_oids) {
4417 struct update_ref_record *rec = item->util;
4418 fprintf(fp, "%s\n%s\n%s\n", item->string,
4419 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4422 result = commit_lock_file(&lock);
4424 cleanup:
4425 free(path);
4426 return result;
4430 * Parse the update-refs file for the current rebase, then remove the
4431 * refs that do not appear in the todo_list (and have not had updated
4432 * values stored) and add refs that are in the todo_list but not
4433 * represented in the update-refs file.
4435 * If there are changes to the update-refs list, then write the new state
4436 * to disk.
4438 void todo_list_filter_update_refs(struct repository *r,
4439 struct todo_list *todo_list)
4441 int i;
4442 int updated = 0;
4443 struct string_list update_refs = STRING_LIST_INIT_DUP;
4445 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4448 * For each item in the update_refs list, if it has no updated
4449 * value and does not appear in the todo_list, then remove it
4450 * from the update_refs list.
4452 for (i = 0; i < update_refs.nr; i++) {
4453 int j;
4454 int found = 0;
4455 const char *ref = update_refs.items[i].string;
4456 size_t reflen = strlen(ref);
4457 struct update_ref_record *rec = update_refs.items[i].util;
4459 /* OID already stored as updated. */
4460 if (!is_null_oid(&rec->after))
4461 continue;
4463 for (j = 0; !found && j < todo_list->nr; j++) {
4464 struct todo_item *item = &todo_list->items[j];
4465 const char *arg = todo_list->buf.buf + item->arg_offset;
4467 if (item->command != TODO_UPDATE_REF)
4468 continue;
4470 if (item->arg_len != reflen ||
4471 strncmp(arg, ref, reflen))
4472 continue;
4474 found = 1;
4477 if (!found) {
4478 free(update_refs.items[i].string);
4479 free(update_refs.items[i].util);
4481 update_refs.nr--;
4482 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4484 updated = 1;
4485 i--;
4490 * For each todo_item, check if its ref is in the update_refs list.
4491 * If not, then add it as an un-updated ref.
4493 for (i = 0; i < todo_list->nr; i++) {
4494 struct todo_item *item = &todo_list->items[i];
4495 const char *arg = todo_list->buf.buf + item->arg_offset;
4496 int j, found = 0;
4498 if (item->command != TODO_UPDATE_REF)
4499 continue;
4501 for (j = 0; !found && j < update_refs.nr; j++) {
4502 const char *ref = update_refs.items[j].string;
4504 found = strlen(ref) == item->arg_len &&
4505 !strncmp(ref, arg, item->arg_len);
4508 if (!found) {
4509 struct string_list_item *inserted;
4510 struct strbuf argref = STRBUF_INIT;
4512 strbuf_add(&argref, arg, item->arg_len);
4513 inserted = string_list_insert(&update_refs, argref.buf);
4514 inserted->util = init_update_ref_record(argref.buf);
4515 strbuf_release(&argref);
4516 updated = 1;
4520 if (updated)
4521 write_update_refs_state(&update_refs);
4522 string_list_clear(&update_refs, 1);
4525 static int do_update_ref(struct repository *r, const char *refname)
4527 struct string_list_item *item;
4528 struct string_list list = STRING_LIST_INIT_DUP;
4530 if (sequencer_get_update_refs_state(r->gitdir, &list))
4531 return -1;
4533 for_each_string_list_item(item, &list) {
4534 if (!strcmp(item->string, refname)) {
4535 struct update_ref_record *rec = item->util;
4536 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4537 return -1;
4538 break;
4542 write_update_refs_state(&list);
4543 string_list_clear(&list, 1);
4544 return 0;
4547 static int do_update_refs(struct repository *r, int quiet)
4549 int res = 0;
4550 struct string_list_item *item;
4551 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4552 struct ref_store *refs = get_main_ref_store(r);
4553 struct strbuf update_msg = STRBUF_INIT;
4554 struct strbuf error_msg = STRBUF_INIT;
4556 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4557 return res;
4559 for_each_string_list_item(item, &refs_to_oids) {
4560 struct update_ref_record *rec = item->util;
4561 int loop_res;
4563 loop_res = refs_update_ref(refs, "rewritten during rebase",
4564 item->string,
4565 &rec->after, &rec->before,
4566 0, UPDATE_REFS_MSG_ON_ERR);
4567 res |= loop_res;
4569 if (quiet)
4570 continue;
4572 if (loop_res)
4573 strbuf_addf(&error_msg, "\t%s\n", item->string);
4574 else
4575 strbuf_addf(&update_msg, "\t%s\n", item->string);
4578 if (!quiet &&
4579 (update_msg.len || error_msg.len)) {
4580 fprintf(stderr,
4581 _("Updated the following refs with %s:\n%s"),
4582 "--update-refs",
4583 update_msg.buf);
4585 if (res)
4586 fprintf(stderr,
4587 _("Failed to update the following refs with %s:\n%s"),
4588 "--update-refs",
4589 error_msg.buf);
4592 string_list_clear(&refs_to_oids, 1);
4593 strbuf_release(&update_msg);
4594 strbuf_release(&error_msg);
4595 return res;
4598 static int is_final_fixup(struct todo_list *todo_list)
4600 int i = todo_list->current;
4602 if (!is_fixup(todo_list->items[i].command))
4603 return 0;
4605 while (++i < todo_list->nr)
4606 if (is_fixup(todo_list->items[i].command))
4607 return 0;
4608 else if (!is_noop(todo_list->items[i].command))
4609 break;
4610 return 1;
4613 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4615 int i;
4617 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4618 if (!is_noop(todo_list->items[i].command))
4619 return todo_list->items[i].command;
4621 return -1;
4624 static void create_autostash_internal(struct repository *r,
4625 const char *path,
4626 const char *refname)
4628 struct strbuf buf = STRBUF_INIT;
4629 struct lock_file lock_file = LOCK_INIT;
4630 int fd;
4632 if (path && refname)
4633 BUG("can only pass path or refname");
4635 fd = repo_hold_locked_index(r, &lock_file, 0);
4636 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4637 if (0 <= fd)
4638 repo_update_index_if_able(r, &lock_file);
4639 rollback_lock_file(&lock_file);
4641 if (has_unstaged_changes(r, 1) ||
4642 has_uncommitted_changes(r, 1)) {
4643 struct child_process stash = CHILD_PROCESS_INIT;
4644 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4645 struct object_id oid;
4647 strvec_pushl(&stash.args,
4648 "stash", "create", "autostash", NULL);
4649 stash.git_cmd = 1;
4650 stash.no_stdin = 1;
4651 strbuf_reset(&buf);
4652 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4653 die(_("Cannot autostash"));
4654 strbuf_trim_trailing_newline(&buf);
4655 if (repo_get_oid(r, buf.buf, &oid))
4656 die(_("Unexpected stash response: '%s'"),
4657 buf.buf);
4658 strbuf_reset(&buf);
4659 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4661 if (path) {
4662 if (safe_create_leading_directories_const(path))
4663 die(_("Could not create directory for '%s'"),
4664 path);
4665 write_file(path, "%s", oid_to_hex(&oid));
4666 } else {
4667 refs_update_ref(get_main_ref_store(r), "", refname,
4668 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4671 printf(_("Created autostash: %s\n"), buf.buf);
4672 if (reset_head(r, &ropts) < 0)
4673 die(_("could not reset --hard"));
4674 discard_index(r->index);
4675 if (repo_read_index(r) < 0)
4676 die(_("could not read index"));
4678 strbuf_release(&buf);
4681 void create_autostash(struct repository *r, const char *path)
4683 create_autostash_internal(r, path, NULL);
4686 void create_autostash_ref(struct repository *r, const char *refname)
4688 create_autostash_internal(r, NULL, refname);
4691 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4693 struct child_process child = CHILD_PROCESS_INIT;
4694 int ret = 0;
4696 if (attempt_apply) {
4697 child.git_cmd = 1;
4698 child.no_stdout = 1;
4699 child.no_stderr = 1;
4700 strvec_push(&child.args, "stash");
4701 strvec_push(&child.args, "apply");
4702 strvec_push(&child.args, stash_oid);
4703 ret = run_command(&child);
4706 if (attempt_apply && !ret)
4707 fprintf(stderr, _("Applied autostash.\n"));
4708 else {
4709 struct child_process store = CHILD_PROCESS_INIT;
4711 store.git_cmd = 1;
4712 strvec_push(&store.args, "stash");
4713 strvec_push(&store.args, "store");
4714 strvec_push(&store.args, "-m");
4715 strvec_push(&store.args, "autostash");
4716 strvec_push(&store.args, "-q");
4717 strvec_push(&store.args, stash_oid);
4718 if (run_command(&store))
4719 ret = error(_("cannot store %s"), stash_oid);
4720 else
4721 fprintf(stderr,
4722 _("%s\n"
4723 "Your changes are safe in the stash.\n"
4724 "You can run \"git stash pop\" or"
4725 " \"git stash drop\" at any time.\n"),
4726 attempt_apply ?
4727 _("Applying autostash resulted in conflicts.") :
4728 _("Autostash exists; creating a new stash entry."));
4731 return ret;
4734 static int apply_save_autostash(const char *path, int attempt_apply)
4736 struct strbuf stash_oid = STRBUF_INIT;
4737 int ret = 0;
4739 if (!read_oneliner(&stash_oid, path,
4740 READ_ONELINER_SKIP_IF_EMPTY)) {
4741 strbuf_release(&stash_oid);
4742 return 0;
4744 strbuf_trim(&stash_oid);
4746 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4748 unlink(path);
4749 strbuf_release(&stash_oid);
4750 return ret;
4753 int save_autostash(const char *path)
4755 return apply_save_autostash(path, 0);
4758 int apply_autostash(const char *path)
4760 return apply_save_autostash(path, 1);
4763 int apply_autostash_oid(const char *stash_oid)
4765 return apply_save_autostash_oid(stash_oid, 1);
4768 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4769 int attempt_apply)
4771 struct object_id stash_oid;
4772 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4773 int flag, ret;
4775 if (!refs_ref_exists(get_main_ref_store(r), refname))
4776 return 0;
4778 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4779 RESOLVE_REF_READING, &stash_oid, &flag))
4780 return -1;
4781 if (flag & REF_ISSYMREF)
4782 return error(_("autostash reference is a symref"));
4784 oid_to_hex_r(stash_oid_hex, &stash_oid);
4785 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4787 refs_delete_ref(get_main_ref_store(r), "", refname,
4788 &stash_oid, REF_NO_DEREF);
4790 return ret;
4793 int save_autostash_ref(struct repository *r, const char *refname)
4795 return apply_save_autostash_ref(r, refname, 0);
4798 int apply_autostash_ref(struct repository *r, const char *refname)
4800 return apply_save_autostash_ref(r, refname, 1);
4803 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4804 const char *onto_name, const struct object_id *onto,
4805 const struct object_id *orig_head)
4807 struct reset_head_opts ropts = {
4808 .oid = onto,
4809 .orig_head = orig_head,
4810 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4811 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4812 .head_msg = reflog_message(opts, "start", "checkout %s",
4813 onto_name),
4814 .default_reflog_action = sequencer_reflog_action(opts)
4816 if (reset_head(r, &ropts)) {
4817 apply_autostash(rebase_path_autostash());
4818 sequencer_remove_state(opts);
4819 return error(_("could not detach HEAD"));
4822 return 0;
4825 static int stopped_at_head(struct repository *r)
4827 struct object_id head;
4828 struct commit *commit;
4829 struct commit_message message;
4831 if (repo_get_oid(r, "HEAD", &head) ||
4832 !(commit = lookup_commit(r, &head)) ||
4833 repo_parse_commit(r, commit) || get_message(commit, &message))
4834 fprintf(stderr, _("Stopped at HEAD\n"));
4835 else {
4836 fprintf(stderr, _("Stopped at %s\n"), message.label);
4837 free_message(commit, &message);
4839 return 0;
4843 static int reread_todo_if_changed(struct repository *r,
4844 struct todo_list *todo_list,
4845 struct replay_opts *opts)
4847 int offset;
4848 struct strbuf buf = STRBUF_INIT;
4850 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4851 return -1;
4852 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4853 if (buf.len != todo_list->buf.len - offset ||
4854 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4855 /* Reread the todo file if it has changed. */
4856 todo_list_release(todo_list);
4857 if (read_populate_todo(r, todo_list, opts))
4858 return -1; /* message was printed */
4859 /* `current` will be incremented on return */
4860 todo_list->current = -1;
4862 strbuf_release(&buf);
4864 return 0;
4867 static const char rescheduled_advice[] =
4868 N_("Could not execute the todo command\n"
4869 "\n"
4870 " %.*s"
4871 "\n"
4872 "It has been rescheduled; To edit the command before continuing, please\n"
4873 "edit the todo list first:\n"
4874 "\n"
4875 " git rebase --edit-todo\n"
4876 " git rebase --continue\n");
4878 static int pick_one_commit(struct repository *r,
4879 struct todo_list *todo_list,
4880 struct replay_opts *opts,
4881 int *check_todo, int* reschedule)
4883 struct replay_ctx *ctx = opts->ctx;
4884 int res;
4885 struct todo_item *item = todo_list->items + todo_list->current;
4886 const char *arg = todo_item_get_arg(todo_list, item);
4887 if (is_rebase_i(opts))
4888 ctx->reflog_message = reflog_message(
4889 opts, command_to_string(item->command), NULL);
4891 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4892 check_todo);
4893 if (is_rebase_i(opts) && res < 0) {
4894 /* Reschedule */
4895 *reschedule = 1;
4896 return -1;
4898 if (item->command == TODO_EDIT) {
4899 struct commit *commit = item->commit;
4900 if (!res) {
4901 if (!opts->verbose)
4902 term_clear_line();
4903 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4904 short_commit_name(r, commit), item->arg_len, arg);
4906 return error_with_patch(r, commit,
4907 arg, item->arg_len, opts, res, !res);
4909 if (is_rebase_i(opts) && !res)
4910 record_in_rewritten(&item->commit->object.oid,
4911 peek_command(todo_list, 1));
4912 if (res && is_fixup(item->command)) {
4913 if (res == 1)
4914 intend_to_amend();
4915 return error_failed_squash(r, item->commit, opts,
4916 item->arg_len, arg);
4917 } else if (res && is_rebase_i(opts) && item->commit) {
4918 int to_amend = 0;
4919 struct object_id oid;
4922 * If we are rewording and have either
4923 * fast-forwarded already, or are about to
4924 * create a new root commit, we want to amend,
4925 * otherwise we do not.
4927 if (item->command == TODO_REWORD &&
4928 !repo_get_oid(r, "HEAD", &oid) &&
4929 (oideq(&item->commit->object.oid, &oid) ||
4930 (opts->have_squash_onto &&
4931 oideq(&opts->squash_onto, &oid))))
4932 to_amend = 1;
4934 return res | error_with_patch(r, item->commit,
4935 arg, item->arg_len, opts,
4936 res, to_amend);
4938 return res;
4941 static int pick_commits(struct repository *r,
4942 struct todo_list *todo_list,
4943 struct replay_opts *opts)
4945 struct replay_ctx *ctx = opts->ctx;
4946 int res = 0, reschedule = 0;
4948 ctx->reflog_message = sequencer_reflog_action(opts);
4949 if (opts->allow_ff)
4950 assert(!(opts->signoff || opts->no_commit ||
4951 opts->record_origin || should_edit(opts) ||
4952 opts->committer_date_is_author_date ||
4953 opts->ignore_date));
4954 if (read_and_refresh_cache(r, opts))
4955 return -1;
4957 unlink(rebase_path_message());
4958 unlink(rebase_path_stopped_sha());
4959 unlink(rebase_path_amend());
4960 unlink(rebase_path_patch());
4962 while (todo_list->current < todo_list->nr) {
4963 struct todo_item *item = todo_list->items + todo_list->current;
4964 const char *arg = todo_item_get_arg(todo_list, item);
4965 int check_todo = 0;
4967 if (save_todo(todo_list, opts, reschedule))
4968 return -1;
4969 if (is_rebase_i(opts)) {
4970 if (item->command != TODO_COMMENT) {
4971 FILE *f = fopen(rebase_path_msgnum(), "w");
4973 todo_list->done_nr++;
4975 if (f) {
4976 fprintf(f, "%d\n", todo_list->done_nr);
4977 fclose(f);
4979 if (!opts->quiet)
4980 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4981 todo_list->done_nr,
4982 todo_list->total_nr,
4983 opts->verbose ? "\n" : "\r");
4985 unlink(rebase_path_author_script());
4986 unlink(git_path_merge_head(r));
4987 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4988 NULL, REF_NO_DEREF);
4989 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4990 NULL, REF_NO_DEREF);
4992 if (item->command == TODO_BREAK) {
4993 if (!opts->verbose)
4994 term_clear_line();
4995 return stopped_at_head(r);
4998 strbuf_reset(&ctx->message);
4999 ctx->have_message = 0;
5000 if (item->command <= TODO_SQUASH) {
5001 res = pick_one_commit(r, todo_list, opts, &check_todo,
5002 &reschedule);
5003 if (!res && item->command == TODO_EDIT)
5004 return 0;
5005 } else if (item->command == TODO_EXEC) {
5006 char *end_of_arg = (char *)(arg + item->arg_len);
5007 int saved = *end_of_arg;
5009 if (!opts->verbose)
5010 term_clear_line();
5011 *end_of_arg = '\0';
5012 res = do_exec(r, arg);
5013 *end_of_arg = saved;
5015 if (res) {
5016 if (opts->reschedule_failed_exec)
5017 reschedule = 1;
5019 check_todo = 1;
5020 } else if (item->command == TODO_LABEL) {
5021 if ((res = do_label(r, arg, item->arg_len)))
5022 reschedule = 1;
5023 } else if (item->command == TODO_RESET) {
5024 if ((res = do_reset(r, arg, item->arg_len, opts)))
5025 reschedule = 1;
5026 } else if (item->command == TODO_MERGE) {
5027 if ((res = do_merge(r, item->commit, arg, item->arg_len,
5028 item->flags, &check_todo, opts)) < 0)
5029 reschedule = 1;
5030 else if (item->commit)
5031 record_in_rewritten(&item->commit->object.oid,
5032 peek_command(todo_list, 1));
5033 if (res > 0)
5034 /* failed with merge conflicts */
5035 return error_with_patch(r, item->commit,
5036 arg, item->arg_len,
5037 opts, res, 0);
5038 } else if (item->command == TODO_UPDATE_REF) {
5039 struct strbuf ref = STRBUF_INIT;
5040 strbuf_add(&ref, arg, item->arg_len);
5041 if ((res = do_update_ref(r, ref.buf)))
5042 reschedule = 1;
5043 strbuf_release(&ref);
5044 } else if (!is_noop(item->command))
5045 return error(_("unknown command %d"), item->command);
5047 if (reschedule) {
5048 advise(_(rescheduled_advice),
5049 get_item_line_length(todo_list,
5050 todo_list->current),
5051 get_item_line(todo_list, todo_list->current));
5052 if (save_todo(todo_list, opts, reschedule))
5053 return -1;
5054 if (item->commit)
5055 write_rebase_head(&item->commit->object.oid);
5056 } else if (is_rebase_i(opts) && check_todo && !res &&
5057 reread_todo_if_changed(r, todo_list, opts)) {
5058 return -1;
5061 if (res)
5062 return res;
5064 todo_list->current++;
5067 if (is_rebase_i(opts)) {
5068 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
5069 struct stat st;
5071 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5072 starts_with(head_ref.buf, "refs/")) {
5073 const char *msg;
5074 struct object_id head, orig;
5075 int res;
5077 if (repo_get_oid(r, "HEAD", &head)) {
5078 res = error(_("cannot read HEAD"));
5079 cleanup_head_ref:
5080 strbuf_release(&head_ref);
5081 strbuf_release(&buf);
5082 return res;
5084 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
5085 get_oid_hex(buf.buf, &orig)) {
5086 res = error(_("could not read orig-head"));
5087 goto cleanup_head_ref;
5089 strbuf_reset(&buf);
5090 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5091 res = error(_("could not read 'onto'"));
5092 goto cleanup_head_ref;
5094 msg = reflog_message(opts, "finish", "%s onto %s",
5095 head_ref.buf, buf.buf);
5096 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5097 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
5098 res = error(_("could not update %s"),
5099 head_ref.buf);
5100 goto cleanup_head_ref;
5102 msg = reflog_message(opts, "finish", "returning to %s",
5103 head_ref.buf);
5104 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
5105 res = error(_("could not update HEAD to %s"),
5106 head_ref.buf);
5107 goto cleanup_head_ref;
5109 strbuf_reset(&buf);
5112 if (opts->verbose) {
5113 struct rev_info log_tree_opt;
5114 struct object_id orig, head;
5116 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
5117 repo_init_revisions(r, &log_tree_opt, NULL);
5118 log_tree_opt.diff = 1;
5119 log_tree_opt.diffopt.output_format =
5120 DIFF_FORMAT_DIFFSTAT;
5121 log_tree_opt.disable_stdin = 1;
5123 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
5124 !repo_get_oid(r, buf.buf, &orig) &&
5125 !repo_get_oid(r, "HEAD", &head)) {
5126 diff_tree_oid(&orig, &head, "",
5127 &log_tree_opt.diffopt);
5128 log_tree_diff_flush(&log_tree_opt);
5130 release_revisions(&log_tree_opt);
5132 flush_rewritten_pending();
5133 if (!stat(rebase_path_rewritten_list(), &st) &&
5134 st.st_size > 0) {
5135 struct child_process child = CHILD_PROCESS_INIT;
5136 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5138 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5139 child.git_cmd = 1;
5140 strvec_push(&child.args, "notes");
5141 strvec_push(&child.args, "copy");
5142 strvec_push(&child.args, "--for-rewrite=rebase");
5143 /* we don't care if this copying failed */
5144 run_command(&child);
5146 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5147 strvec_push(&hook_opt.args, "rebase");
5148 run_hooks_opt("post-rewrite", &hook_opt);
5150 apply_autostash(rebase_path_autostash());
5152 if (!opts->quiet) {
5153 if (!opts->verbose)
5154 term_clear_line();
5155 fprintf(stderr,
5156 _("Successfully rebased and updated %s.\n"),
5157 head_ref.buf);
5160 strbuf_release(&buf);
5161 strbuf_release(&head_ref);
5163 if (do_update_refs(r, opts->quiet))
5164 return -1;
5168 * Sequence of picks finished successfully; cleanup by
5169 * removing the .git/sequencer directory
5171 return sequencer_remove_state(opts);
5174 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5176 struct child_process cmd = CHILD_PROCESS_INIT;
5178 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5179 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5180 return error(_("no cherry-pick or revert in progress"));
5182 cmd.git_cmd = 1;
5183 strvec_push(&cmd.args, "commit");
5186 * continue_single_pick() handles the case of recovering from a
5187 * conflict. should_edit() doesn't handle that case; for a conflict,
5188 * we want to edit if the user asked for it, or if they didn't specify
5189 * and stdin is a tty.
5191 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5193 * Include --cleanup=strip as well because we don't want the
5194 * "# Conflicts:" messages.
5196 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5198 return run_command(&cmd);
5201 static int commit_staged_changes(struct repository *r,
5202 struct replay_opts *opts,
5203 struct todo_list *todo_list)
5205 struct replay_ctx *ctx = opts->ctx;
5206 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5207 unsigned int final_fixup = 0, is_clean;
5209 if (has_unstaged_changes(r, 1))
5210 return error(_("cannot rebase: You have unstaged changes."));
5212 is_clean = !has_uncommitted_changes(r, 0);
5214 if (!is_clean && !file_exists(rebase_path_message())) {
5215 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5217 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5219 if (file_exists(rebase_path_amend())) {
5220 struct strbuf rev = STRBUF_INIT;
5221 struct object_id head, to_amend;
5223 if (repo_get_oid(r, "HEAD", &head))
5224 return error(_("cannot amend non-existing commit"));
5225 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5226 return error(_("invalid file: '%s'"), rebase_path_amend());
5227 if (get_oid_hex(rev.buf, &to_amend))
5228 return error(_("invalid contents: '%s'"),
5229 rebase_path_amend());
5230 if (!is_clean && !oideq(&head, &to_amend))
5231 return error(_("\nYou have uncommitted changes in your "
5232 "working tree. Please, commit them\n"
5233 "first and then run 'git rebase "
5234 "--continue' again."));
5236 * When skipping a failed fixup/squash, we need to edit the
5237 * commit message, the current fixup list and count, and if it
5238 * was the last fixup/squash in the chain, we need to clean up
5239 * the commit message and if there was a squash, let the user
5240 * edit it.
5242 if (!is_clean || !ctx->current_fixup_count)
5243 ; /* this is not the final fixup */
5244 else if (!oideq(&head, &to_amend) ||
5245 !file_exists(rebase_path_stopped_sha())) {
5246 /* was a final fixup or squash done manually? */
5247 if (!is_fixup(peek_command(todo_list, 0))) {
5248 unlink(rebase_path_fixup_msg());
5249 unlink(rebase_path_squash_msg());
5250 unlink(rebase_path_current_fixups());
5251 strbuf_reset(&ctx->current_fixups);
5252 ctx->current_fixup_count = 0;
5254 } else {
5255 /* we are in a fixup/squash chain */
5256 const char *p = ctx->current_fixups.buf;
5257 int len = ctx->current_fixups.len;
5259 ctx->current_fixup_count--;
5260 if (!len)
5261 BUG("Incorrect current_fixups:\n%s", p);
5262 while (len && p[len - 1] != '\n')
5263 len--;
5264 strbuf_setlen(&ctx->current_fixups, len);
5265 if (write_message(p, len, rebase_path_current_fixups(),
5266 0) < 0)
5267 return error(_("could not write file: '%s'"),
5268 rebase_path_current_fixups());
5271 * If a fixup/squash in a fixup/squash chain failed, the
5272 * commit message is already correct, no need to commit
5273 * it again.
5275 * Only if it is the final command in the fixup/squash
5276 * chain, and only if the chain is longer than a single
5277 * fixup/squash command (which was just skipped), do we
5278 * actually need to re-commit with a cleaned up commit
5279 * message.
5281 if (ctx->current_fixup_count > 0 &&
5282 !is_fixup(peek_command(todo_list, 0))) {
5283 final_fixup = 1;
5285 * If there was not a single "squash" in the
5286 * chain, we only need to clean up the commit
5287 * message, no need to bother the user with
5288 * opening the commit message in the editor.
5290 if (!starts_with(p, "squash ") &&
5291 !strstr(p, "\nsquash "))
5292 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5293 } else if (is_fixup(peek_command(todo_list, 0))) {
5295 * We need to update the squash message to skip
5296 * the latest commit message.
5298 int res = 0;
5299 struct commit *commit;
5300 const char *msg;
5301 const char *path = rebase_path_squash_msg();
5302 const char *encoding = get_commit_output_encoding();
5304 if (parse_head(r, &commit))
5305 return error(_("could not parse HEAD"));
5307 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5308 if (!p) {
5309 res = error(_("could not parse commit %s"),
5310 oid_to_hex(&commit->object.oid));
5311 goto unuse_commit_buffer;
5313 find_commit_subject(p, &msg);
5314 if (write_message(msg, strlen(msg), path, 0)) {
5315 res = error(_("could not write file: "
5316 "'%s'"), path);
5317 goto unuse_commit_buffer;
5319 unuse_commit_buffer:
5320 repo_unuse_commit_buffer(r, commit, p);
5321 if (res)
5322 return res;
5326 strbuf_release(&rev);
5327 flags |= AMEND_MSG;
5330 if (is_clean) {
5331 if (refs_ref_exists(get_main_ref_store(r),
5332 "CHERRY_PICK_HEAD") &&
5333 refs_delete_ref(get_main_ref_store(r), "",
5334 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
5335 return error(_("could not remove CHERRY_PICK_HEAD"));
5336 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5337 return error_errno(_("could not remove '%s'"),
5338 git_path_merge_msg(r));
5339 if (!final_fixup)
5340 return 0;
5343 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5344 opts, flags))
5345 return error(_("could not commit staged changes."));
5346 unlink(rebase_path_amend());
5347 unlink(git_path_merge_head(r));
5348 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5349 NULL, REF_NO_DEREF);
5350 if (final_fixup) {
5351 unlink(rebase_path_fixup_msg());
5352 unlink(rebase_path_squash_msg());
5354 if (ctx->current_fixup_count > 0) {
5356 * Whether final fixup or not, we just cleaned up the commit
5357 * message...
5359 unlink(rebase_path_current_fixups());
5360 strbuf_reset(&ctx->current_fixups);
5361 ctx->current_fixup_count = 0;
5363 return 0;
5366 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5368 struct replay_ctx *ctx = opts->ctx;
5369 struct todo_list todo_list = TODO_LIST_INIT;
5370 int res;
5372 if (read_and_refresh_cache(r, opts))
5373 return -1;
5375 if (read_populate_opts(opts))
5376 return -1;
5377 if (is_rebase_i(opts)) {
5378 if ((res = read_populate_todo(r, &todo_list, opts)))
5379 goto release_todo_list;
5381 if (file_exists(rebase_path_dropped())) {
5382 if ((res = todo_list_check_against_backup(r, opts,
5383 &todo_list)))
5384 goto release_todo_list;
5386 unlink(rebase_path_dropped());
5389 ctx->reflog_message = reflog_message(opts, "continue", NULL);
5390 if (commit_staged_changes(r, opts, &todo_list)) {
5391 res = -1;
5392 goto release_todo_list;
5394 } else if (!file_exists(get_todo_path(opts)))
5395 return continue_single_pick(r, opts);
5396 else if ((res = read_populate_todo(r, &todo_list, opts)))
5397 goto release_todo_list;
5399 if (!is_rebase_i(opts)) {
5400 /* Verify that the conflict has been resolved */
5401 if (refs_ref_exists(get_main_ref_store(r),
5402 "CHERRY_PICK_HEAD") ||
5403 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5404 res = continue_single_pick(r, opts);
5405 if (res)
5406 goto release_todo_list;
5408 if (index_differs_from(r, "HEAD", NULL, 0)) {
5409 res = error_dirty_index(r, opts);
5410 goto release_todo_list;
5412 todo_list.current++;
5413 } else if (file_exists(rebase_path_stopped_sha())) {
5414 struct strbuf buf = STRBUF_INIT;
5415 struct object_id oid;
5417 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5418 READ_ONELINER_SKIP_IF_EMPTY) &&
5419 !get_oid_hex(buf.buf, &oid))
5420 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5421 strbuf_release(&buf);
5424 res = pick_commits(r, &todo_list, opts);
5425 release_todo_list:
5426 todo_list_release(&todo_list);
5427 return res;
5430 static int single_pick(struct repository *r,
5431 struct commit *cmit,
5432 struct replay_opts *opts)
5434 int check_todo;
5435 struct todo_item item;
5437 item.command = opts->action == REPLAY_PICK ?
5438 TODO_PICK : TODO_REVERT;
5439 item.commit = cmit;
5441 opts->ctx->reflog_message = sequencer_reflog_action(opts);
5442 return do_pick_commit(r, &item, opts, 0, &check_todo);
5445 int sequencer_pick_revisions(struct repository *r,
5446 struct replay_opts *opts)
5448 struct todo_list todo_list = TODO_LIST_INIT;
5449 struct object_id oid;
5450 int i, res;
5452 assert(opts->revs);
5453 if (read_and_refresh_cache(r, opts))
5454 return -1;
5456 for (i = 0; i < opts->revs->pending.nr; i++) {
5457 struct object_id oid;
5458 const char *name = opts->revs->pending.objects[i].name;
5460 /* This happens when using --stdin. */
5461 if (!strlen(name))
5462 continue;
5464 if (!repo_get_oid(r, name, &oid)) {
5465 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5466 enum object_type type = oid_object_info(r,
5467 &oid,
5468 NULL);
5469 return error(_("%s: can't cherry-pick a %s"),
5470 name, type_name(type));
5472 } else
5473 return error(_("%s: bad revision"), name);
5477 * If we were called as "git cherry-pick <commit>", just
5478 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5479 * REVERT_HEAD, and don't touch the sequencer state.
5480 * This means it is possible to cherry-pick in the middle
5481 * of a cherry-pick sequence.
5483 if (opts->revs->cmdline.nr == 1 &&
5484 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5485 opts->revs->no_walk &&
5486 !opts->revs->cmdline.rev->flags) {
5487 struct commit *cmit;
5488 if (prepare_revision_walk(opts->revs))
5489 return error(_("revision walk setup failed"));
5490 cmit = get_revision(opts->revs);
5491 if (!cmit)
5492 return error(_("empty commit set passed"));
5493 if (get_revision(opts->revs))
5494 BUG("unexpected extra commit from walk");
5495 return single_pick(r, cmit, opts);
5499 * Start a new cherry-pick/ revert sequence; but
5500 * first, make sure that an existing one isn't in
5501 * progress
5504 if (walk_revs_populate_todo(&todo_list, opts) ||
5505 create_seq_dir(r) < 0)
5506 return -1;
5507 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5508 return error(_("can't revert as initial commit"));
5509 if (save_head(oid_to_hex(&oid)))
5510 return -1;
5511 if (save_opts(opts))
5512 return -1;
5513 update_abort_safety_file();
5514 res = pick_commits(r, &todo_list, opts);
5515 todo_list_release(&todo_list);
5516 return res;
5519 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5521 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5522 struct strbuf sob = STRBUF_INIT;
5523 int has_footer;
5525 strbuf_addstr(&sob, sign_off_header);
5526 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5527 strbuf_addch(&sob, '\n');
5529 if (!ignore_footer)
5530 strbuf_complete_line(msgbuf);
5533 * If the whole message buffer is equal to the sob, pretend that we
5534 * found a conforming footer with a matching sob
5536 if (msgbuf->len - ignore_footer == sob.len &&
5537 !strncmp(msgbuf->buf, sob.buf, sob.len))
5538 has_footer = 3;
5539 else
5540 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5542 if (!has_footer) {
5543 const char *append_newlines = NULL;
5544 size_t len = msgbuf->len - ignore_footer;
5546 if (!len) {
5548 * The buffer is completely empty. Leave foom for
5549 * the title and body to be filled in by the user.
5551 append_newlines = "\n\n";
5552 } else if (len == 1) {
5554 * Buffer contains a single newline. Add another
5555 * so that we leave room for the title and body.
5557 append_newlines = "\n";
5558 } else if (msgbuf->buf[len - 2] != '\n') {
5560 * Buffer ends with a single newline. Add another
5561 * so that there is an empty line between the message
5562 * body and the sob.
5564 append_newlines = "\n";
5565 } /* else, the buffer already ends with two newlines. */
5567 if (append_newlines)
5568 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5569 append_newlines, strlen(append_newlines));
5572 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5573 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5574 sob.buf, sob.len);
5576 strbuf_release(&sob);
5579 struct labels_entry {
5580 struct hashmap_entry entry;
5581 char label[FLEX_ARRAY];
5584 static int labels_cmp(const void *fndata UNUSED,
5585 const struct hashmap_entry *eptr,
5586 const struct hashmap_entry *entry_or_key, const void *key)
5588 const struct labels_entry *a, *b;
5590 a = container_of(eptr, const struct labels_entry, entry);
5591 b = container_of(entry_or_key, const struct labels_entry, entry);
5593 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5596 struct string_entry {
5597 struct oidmap_entry entry;
5598 char string[FLEX_ARRAY];
5601 struct label_state {
5602 struct oidmap commit2label;
5603 struct hashmap labels;
5604 struct strbuf buf;
5605 int max_label_length;
5608 static const char *label_oid(struct object_id *oid, const char *label,
5609 struct label_state *state)
5611 struct labels_entry *labels_entry;
5612 struct string_entry *string_entry;
5613 struct object_id dummy;
5614 int i;
5616 string_entry = oidmap_get(&state->commit2label, oid);
5617 if (string_entry)
5618 return string_entry->string;
5621 * For "uninteresting" commits, i.e. commits that are not to be
5622 * rebased, and which can therefore not be labeled, we use a unique
5623 * abbreviation of the commit name. This is slightly more complicated
5624 * than calling repo_find_unique_abbrev() because we also need to make
5625 * sure that the abbreviation does not conflict with any other
5626 * label.
5628 * We disallow "interesting" commits to be labeled by a string that
5629 * is a valid full-length hash, to ensure that we always can find an
5630 * abbreviation for any uninteresting commit's names that does not
5631 * clash with any other label.
5633 strbuf_reset(&state->buf);
5634 if (!label) {
5635 char *p;
5637 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5638 label = p = state->buf.buf;
5640 repo_find_unique_abbrev_r(the_repository, p, oid,
5641 default_abbrev);
5644 * We may need to extend the abbreviated hash so that there is
5645 * no conflicting label.
5647 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5648 size_t i = strlen(p) + 1;
5650 oid_to_hex_r(p, oid);
5651 for (; i < the_hash_algo->hexsz; i++) {
5652 char save = p[i];
5653 p[i] = '\0';
5654 if (!hashmap_get_from_hash(&state->labels,
5655 strihash(p), p))
5656 break;
5657 p[i] = save;
5660 } else {
5661 struct strbuf *buf = &state->buf;
5662 int label_is_utf8 = 1; /* start with this assumption */
5663 size_t max_len = buf->len + state->max_label_length;
5666 * Sanitize labels by replacing non-alpha-numeric characters
5667 * (including white-space ones) by dashes, as they might be
5668 * illegal in file names (and hence in ref names).
5670 * Note that we retain non-ASCII UTF-8 characters (identified
5671 * via the most significant bit). They should be all acceptable
5672 * in file names.
5674 * As we will use the labels as names of (loose) refs, it is
5675 * vital that the name not be longer than the maximum component
5676 * size of the file system (`NAME_MAX`). We are careful to
5677 * truncate the label accordingly, allowing for the `.lock`
5678 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5679 * truncating in the middle of a character).
5681 for (; *label && buf->len + 1 < max_len; label++)
5682 if (isalnum(*label) ||
5683 (!label_is_utf8 && (*label & 0x80)))
5684 strbuf_addch(buf, *label);
5685 else if (*label & 0x80) {
5686 const char *p = label;
5688 utf8_width(&p, NULL);
5689 if (p) {
5690 if (buf->len + (p - label) > max_len)
5691 break;
5692 strbuf_add(buf, label, p - label);
5693 label = p - 1;
5694 } else {
5695 label_is_utf8 = 0;
5696 strbuf_addch(buf, *label);
5698 /* avoid leading dash and double-dashes */
5699 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5700 strbuf_addch(buf, '-');
5701 if (!buf->len) {
5702 strbuf_addstr(buf, "rev-");
5703 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5705 label = buf->buf;
5707 if ((buf->len == the_hash_algo->hexsz &&
5708 !get_oid_hex(label, &dummy)) ||
5709 (buf->len == 1 && *label == '#') ||
5710 hashmap_get_from_hash(&state->labels,
5711 strihash(label), label)) {
5713 * If the label already exists, or if the label is a
5714 * valid full OID, or the label is a '#' (which we use
5715 * as a separator between merge heads and oneline), we
5716 * append a dash and a number to make it unique.
5718 size_t len = buf->len;
5720 for (i = 2; ; i++) {
5721 strbuf_setlen(buf, len);
5722 strbuf_addf(buf, "-%d", i);
5723 if (!hashmap_get_from_hash(&state->labels,
5724 strihash(buf->buf),
5725 buf->buf))
5726 break;
5729 label = buf->buf;
5733 FLEX_ALLOC_STR(labels_entry, label, label);
5734 hashmap_entry_init(&labels_entry->entry, strihash(label));
5735 hashmap_add(&state->labels, &labels_entry->entry);
5737 FLEX_ALLOC_STR(string_entry, string, label);
5738 oidcpy(&string_entry->entry.oid, oid);
5739 oidmap_put(&state->commit2label, string_entry);
5741 return string_entry->string;
5744 static int make_script_with_merges(struct pretty_print_context *pp,
5745 struct rev_info *revs, struct strbuf *out,
5746 unsigned flags)
5748 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5749 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5750 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5751 int skipped_commit = 0;
5752 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5753 struct strbuf label = STRBUF_INIT;
5754 struct commit_list *commits = NULL, **tail = &commits, *iter;
5755 struct commit_list *tips = NULL, **tips_tail = &tips;
5756 struct commit *commit;
5757 struct oidmap commit2todo = OIDMAP_INIT;
5758 struct string_entry *entry;
5759 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5760 shown = OIDSET_INIT;
5761 struct label_state state =
5762 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5764 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5765 const char *cmd_pick = abbr ? "p" : "pick",
5766 *cmd_label = abbr ? "l" : "label",
5767 *cmd_reset = abbr ? "t" : "reset",
5768 *cmd_merge = abbr ? "m" : "merge";
5770 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5772 oidmap_init(&commit2todo, 0);
5773 oidmap_init(&state.commit2label, 0);
5774 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5775 strbuf_init(&state.buf, 32);
5777 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5778 struct labels_entry *onto_label_entry;
5779 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5780 FLEX_ALLOC_STR(entry, string, "onto");
5781 oidcpy(&entry->entry.oid, oid);
5782 oidmap_put(&state.commit2label, entry);
5784 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5785 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5786 hashmap_add(&state.labels, &onto_label_entry->entry);
5790 * First phase:
5791 * - get onelines for all commits
5792 * - gather all branch tips (i.e. 2nd or later parents of merges)
5793 * - label all branch tips
5795 while ((commit = get_revision(revs))) {
5796 struct commit_list *to_merge;
5797 const char *p1, *p2;
5798 struct object_id *oid;
5799 int is_empty;
5801 tail = &commit_list_insert(commit, tail)->next;
5802 oidset_insert(&interesting, &commit->object.oid);
5804 is_empty = is_original_commit_empty(commit);
5805 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5806 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5807 warning(_("skipped previously applied commit %s"),
5808 short_commit_name(the_repository, commit));
5809 skipped_commit = 1;
5810 continue;
5812 if (is_empty && !keep_empty)
5813 continue;
5815 strbuf_reset(&oneline);
5816 pretty_print_commit(pp, commit, &oneline);
5818 to_merge = commit->parents ? commit->parents->next : NULL;
5819 if (!to_merge) {
5820 /* non-merge commit: easy case */
5821 strbuf_reset(&buf);
5822 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5823 oid_to_hex(&commit->object.oid),
5824 oneline.buf);
5825 if (is_empty)
5826 strbuf_addf(&buf, " %s empty",
5827 comment_line_str);
5829 FLEX_ALLOC_STR(entry, string, buf.buf);
5830 oidcpy(&entry->entry.oid, &commit->object.oid);
5831 oidmap_put(&commit2todo, entry);
5833 continue;
5836 /* Create a label */
5837 strbuf_reset(&label);
5838 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5839 (p1 = strchr(p1, '\'')) &&
5840 (p2 = strchr(++p1, '\'')))
5841 strbuf_add(&label, p1, p2 - p1);
5842 else if (skip_prefix(oneline.buf, "Merge pull request ",
5843 &p1) &&
5844 (p1 = strstr(p1, " from ")))
5845 strbuf_addstr(&label, p1 + strlen(" from "));
5846 else
5847 strbuf_addbuf(&label, &oneline);
5849 strbuf_reset(&buf);
5850 strbuf_addf(&buf, "%s -C %s",
5851 cmd_merge, oid_to_hex(&commit->object.oid));
5853 /* label the tips of merged branches */
5854 for (; to_merge; to_merge = to_merge->next) {
5855 oid = &to_merge->item->object.oid;
5856 strbuf_addch(&buf, ' ');
5858 if (!oidset_contains(&interesting, oid)) {
5859 strbuf_addstr(&buf, label_oid(oid, NULL,
5860 &state));
5861 continue;
5864 tips_tail = &commit_list_insert(to_merge->item,
5865 tips_tail)->next;
5867 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5869 strbuf_addf(&buf, " # %s", oneline.buf);
5871 FLEX_ALLOC_STR(entry, string, buf.buf);
5872 oidcpy(&entry->entry.oid, &commit->object.oid);
5873 oidmap_put(&commit2todo, entry);
5875 if (skipped_commit)
5876 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5877 _("use --reapply-cherry-picks to include skipped commits"));
5880 * Second phase:
5881 * - label branch points
5882 * - add HEAD to the branch tips
5884 for (iter = commits; iter; iter = iter->next) {
5885 struct commit_list *parent = iter->item->parents;
5886 for (; parent; parent = parent->next) {
5887 struct object_id *oid = &parent->item->object.oid;
5888 if (!oidset_contains(&interesting, oid))
5889 continue;
5890 if (oidset_insert(&child_seen, oid))
5891 label_oid(oid, "branch-point", &state);
5894 /* Add HEAD as implicit "tip of branch" */
5895 if (!iter->next)
5896 tips_tail = &commit_list_insert(iter->item,
5897 tips_tail)->next;
5901 * Third phase: output the todo list. This is a bit tricky, as we
5902 * want to avoid jumping back and forth between revisions. To
5903 * accomplish that goal, we walk backwards from the branch tips,
5904 * gathering commits not yet shown, reversing the list on the fly,
5905 * then outputting that list (labeling revisions as needed).
5907 strbuf_addf(out, "%s onto\n", cmd_label);
5908 for (iter = tips; iter; iter = iter->next) {
5909 struct commit_list *list = NULL, *iter2;
5911 commit = iter->item;
5912 if (oidset_contains(&shown, &commit->object.oid))
5913 continue;
5914 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5916 if (entry)
5917 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
5918 else
5919 strbuf_addch(out, '\n');
5921 while (oidset_contains(&interesting, &commit->object.oid) &&
5922 !oidset_contains(&shown, &commit->object.oid)) {
5923 commit_list_insert(commit, &list);
5924 if (!commit->parents) {
5925 commit = NULL;
5926 break;
5928 commit = commit->parents->item;
5931 if (!commit)
5932 strbuf_addf(out, "%s %s\n", cmd_reset,
5933 rebase_cousins || root_with_onto ?
5934 "onto" : "[new root]");
5935 else {
5936 const char *to = NULL;
5938 entry = oidmap_get(&state.commit2label,
5939 &commit->object.oid);
5940 if (entry)
5941 to = entry->string;
5942 else if (!rebase_cousins)
5943 to = label_oid(&commit->object.oid, NULL,
5944 &state);
5946 if (!to || !strcmp(to, "onto"))
5947 strbuf_addf(out, "%s onto\n", cmd_reset);
5948 else {
5949 strbuf_reset(&oneline);
5950 pretty_print_commit(pp, commit, &oneline);
5951 strbuf_addf(out, "%s %s # %s\n",
5952 cmd_reset, to, oneline.buf);
5956 for (iter2 = list; iter2; iter2 = iter2->next) {
5957 struct object_id *oid = &iter2->item->object.oid;
5958 entry = oidmap_get(&commit2todo, oid);
5959 /* only show if not already upstream */
5960 if (entry)
5961 strbuf_addf(out, "%s\n", entry->string);
5962 entry = oidmap_get(&state.commit2label, oid);
5963 if (entry)
5964 strbuf_addf(out, "%s %s\n",
5965 cmd_label, entry->string);
5966 oidset_insert(&shown, oid);
5969 free_commit_list(list);
5972 free_commit_list(commits);
5973 free_commit_list(tips);
5975 strbuf_release(&label);
5976 strbuf_release(&oneline);
5977 strbuf_release(&buf);
5979 oidmap_free(&commit2todo, 1);
5980 oidmap_free(&state.commit2label, 1);
5981 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5982 strbuf_release(&state.buf);
5984 return 0;
5987 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5988 const char **argv, unsigned flags)
5990 char *format = NULL;
5991 struct pretty_print_context pp = {0};
5992 struct rev_info revs;
5993 struct commit *commit;
5994 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5995 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5996 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5997 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5998 int skipped_commit = 0;
5999 int ret = 0;
6001 repo_init_revisions(r, &revs, NULL);
6002 revs.verbose_header = 1;
6003 if (!rebase_merges)
6004 revs.max_parents = 1;
6005 revs.cherry_mark = !reapply_cherry_picks;
6006 revs.limited = 1;
6007 revs.reverse = 1;
6008 revs.right_only = 1;
6009 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
6010 revs.topo_order = 1;
6012 revs.pretty_given = 1;
6013 git_config_get_string("rebase.instructionFormat", &format);
6014 if (!format || !*format) {
6015 free(format);
6016 format = xstrdup("%s");
6018 get_commit_format(format, &revs);
6019 free(format);
6020 pp.fmt = revs.commit_format;
6021 pp.output_encoding = get_log_output_encoding();
6023 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
6024 ret = error(_("make_script: unhandled options"));
6025 goto cleanup;
6028 if (prepare_revision_walk(&revs) < 0) {
6029 ret = error(_("make_script: error preparing revisions"));
6030 goto cleanup;
6033 if (rebase_merges) {
6034 ret = make_script_with_merges(&pp, &revs, out, flags);
6035 goto cleanup;
6038 while ((commit = get_revision(&revs))) {
6039 int is_empty = is_original_commit_empty(commit);
6041 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6042 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6043 warning(_("skipped previously applied commit %s"),
6044 short_commit_name(r, commit));
6045 skipped_commit = 1;
6046 continue;
6048 if (is_empty && !keep_empty)
6049 continue;
6050 strbuf_addf(out, "%s %s ", insn,
6051 oid_to_hex(&commit->object.oid));
6052 pretty_print_commit(&pp, commit, out);
6053 if (is_empty)
6054 strbuf_addf(out, " %s empty", comment_line_str);
6055 strbuf_addch(out, '\n');
6057 if (skipped_commit)
6058 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6059 _("use --reapply-cherry-picks to include skipped commits"));
6060 cleanup:
6061 release_revisions(&revs);
6062 return ret;
6066 * Add commands after pick and (series of) squash/fixup commands
6067 * in the todo list.
6069 static void todo_list_add_exec_commands(struct todo_list *todo_list,
6070 struct string_list *commands)
6072 struct strbuf *buf = &todo_list->buf;
6073 size_t base_offset = buf->len;
6074 int i, insert, nr = 0, alloc = 0;
6075 struct todo_item *items = NULL, *base_items = NULL;
6077 CALLOC_ARRAY(base_items, commands->nr);
6078 for (i = 0; i < commands->nr; i++) {
6079 size_t command_len = strlen(commands->items[i].string);
6081 strbuf_addstr(buf, commands->items[i].string);
6082 strbuf_addch(buf, '\n');
6084 base_items[i].command = TODO_EXEC;
6085 base_items[i].offset_in_buf = base_offset;
6086 base_items[i].arg_offset = base_offset;
6087 base_items[i].arg_len = command_len;
6089 base_offset += command_len + 1;
6093 * Insert <commands> after every pick. Here, fixup/squash chains
6094 * are considered part of the pick, so we insert the commands *after*
6095 * those chains if there are any.
6097 * As we insert the exec commands immediately after rearranging
6098 * any fixups and before the user edits the list, a fixup chain
6099 * can never contain comments (any comments are empty picks that
6100 * have been commented out because the user did not specify
6101 * --keep-empty). So, it is safe to insert an exec command
6102 * without looking at the command following a comment.
6104 insert = 0;
6105 for (i = 0; i < todo_list->nr; i++) {
6106 enum todo_command command = todo_list->items[i].command;
6107 if (insert && !is_fixup(command)) {
6108 ALLOC_GROW(items, nr + commands->nr, alloc);
6109 COPY_ARRAY(items + nr, base_items, commands->nr);
6110 nr += commands->nr;
6112 insert = 0;
6115 ALLOC_GROW(items, nr + 1, alloc);
6116 items[nr++] = todo_list->items[i];
6118 if (command == TODO_PICK || command == TODO_MERGE)
6119 insert = 1;
6122 /* insert or append final <commands> */
6123 if (insert) {
6124 ALLOC_GROW(items, nr + commands->nr, alloc);
6125 COPY_ARRAY(items + nr, base_items, commands->nr);
6126 nr += commands->nr;
6129 free(base_items);
6130 FREE_AND_NULL(todo_list->items);
6131 todo_list->items = items;
6132 todo_list->nr = nr;
6133 todo_list->alloc = alloc;
6136 static void todo_list_to_strbuf(struct repository *r,
6137 struct todo_list *todo_list,
6138 struct strbuf *buf, int num, unsigned flags)
6140 struct todo_item *item;
6141 int i, max = todo_list->nr;
6143 if (num > 0 && num < max)
6144 max = num;
6146 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6147 char cmd;
6149 /* if the item is not a command write it and continue */
6150 if (item->command >= TODO_COMMENT) {
6151 strbuf_addf(buf, "%.*s\n", item->arg_len,
6152 todo_item_get_arg(todo_list, item));
6153 continue;
6156 /* add command to the buffer */
6157 cmd = command_to_char(item->command);
6158 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6159 strbuf_addch(buf, cmd);
6160 else
6161 strbuf_addstr(buf, command_to_string(item->command));
6163 /* add commit id */
6164 if (item->commit) {
6165 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6166 short_commit_name(r, item->commit) :
6167 oid_to_hex(&item->commit->object.oid);
6169 if (item->command == TODO_FIXUP) {
6170 if (item->flags & TODO_EDIT_FIXUP_MSG)
6171 strbuf_addstr(buf, " -c");
6172 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6173 strbuf_addstr(buf, " -C");
6177 if (item->command == TODO_MERGE) {
6178 if (item->flags & TODO_EDIT_MERGE_MSG)
6179 strbuf_addstr(buf, " -c");
6180 else
6181 strbuf_addstr(buf, " -C");
6184 strbuf_addf(buf, " %s", oid);
6187 /* add all the rest */
6188 if (!item->arg_len)
6189 strbuf_addch(buf, '\n');
6190 else
6191 strbuf_addf(buf, " %.*s\n", item->arg_len,
6192 todo_item_get_arg(todo_list, item));
6196 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6197 const char *file, const char *shortrevisions,
6198 const char *shortonto, int num, unsigned flags)
6200 int res;
6201 struct strbuf buf = STRBUF_INIT;
6203 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6204 if (flags & TODO_LIST_APPEND_TODO_HELP)
6205 append_todo_help(count_commands(todo_list),
6206 shortrevisions, shortonto, &buf);
6208 res = write_message(buf.buf, buf.len, file, 0);
6209 strbuf_release(&buf);
6211 return res;
6214 /* skip picking commits whose parents are unchanged */
6215 static int skip_unnecessary_picks(struct repository *r,
6216 struct todo_list *todo_list,
6217 struct object_id *base_oid)
6219 struct object_id *parent_oid;
6220 int i;
6222 for (i = 0; i < todo_list->nr; i++) {
6223 struct todo_item *item = todo_list->items + i;
6225 if (item->command >= TODO_NOOP)
6226 continue;
6227 if (item->command != TODO_PICK)
6228 break;
6229 if (repo_parse_commit(r, item->commit)) {
6230 return error(_("could not parse commit '%s'"),
6231 oid_to_hex(&item->commit->object.oid));
6233 if (!item->commit->parents)
6234 break; /* root commit */
6235 if (item->commit->parents->next)
6236 break; /* merge commit */
6237 parent_oid = &item->commit->parents->item->object.oid;
6238 if (!oideq(parent_oid, base_oid))
6239 break;
6240 oidcpy(base_oid, &item->commit->object.oid);
6242 if (i > 0) {
6243 const char *done_path = rebase_path_done();
6245 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6246 error_errno(_("could not write to '%s'"), done_path);
6247 return -1;
6250 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6251 todo_list->nr -= i;
6252 todo_list->current = 0;
6253 todo_list->done_nr += i;
6255 if (is_fixup(peek_command(todo_list, 0)))
6256 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6259 return 0;
6262 struct todo_add_branch_context {
6263 struct todo_item *items;
6264 size_t items_nr;
6265 size_t items_alloc;
6266 struct strbuf *buf;
6267 struct commit *commit;
6268 struct string_list refs_to_oids;
6271 static int add_decorations_to_list(const struct commit *commit,
6272 struct todo_add_branch_context *ctx)
6274 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6275 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
6276 "HEAD",
6277 RESOLVE_REF_READING,
6278 NULL,
6279 NULL);
6281 while (decoration) {
6282 struct todo_item *item;
6283 const char *path;
6284 size_t base_offset = ctx->buf->len;
6287 * If the branch is the current HEAD, then it will be
6288 * updated by the default rebase behavior.
6290 if (head_ref && !strcmp(head_ref, decoration->name)) {
6291 decoration = decoration->next;
6292 continue;
6295 ALLOC_GROW(ctx->items,
6296 ctx->items_nr + 1,
6297 ctx->items_alloc);
6298 item = &ctx->items[ctx->items_nr];
6299 memset(item, 0, sizeof(*item));
6301 /* If the branch is checked out, then leave a comment instead. */
6302 if ((path = branch_checked_out(decoration->name))) {
6303 item->command = TODO_COMMENT;
6304 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6305 decoration->name, path);
6306 } else {
6307 struct string_list_item *sti;
6308 item->command = TODO_UPDATE_REF;
6309 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6311 sti = string_list_insert(&ctx->refs_to_oids,
6312 decoration->name);
6313 sti->util = init_update_ref_record(decoration->name);
6316 item->offset_in_buf = base_offset;
6317 item->arg_offset = base_offset;
6318 item->arg_len = ctx->buf->len - base_offset;
6319 ctx->items_nr++;
6321 decoration = decoration->next;
6324 return 0;
6328 * For each 'pick' command, find out if the commit has a decoration in
6329 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6331 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6333 int i, res;
6334 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6335 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6336 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6337 struct decoration_filter decoration_filter = {
6338 .include_ref_pattern = &decorate_refs_include,
6339 .exclude_ref_pattern = &decorate_refs_exclude,
6340 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6342 struct todo_add_branch_context ctx = {
6343 .buf = &todo_list->buf,
6344 .refs_to_oids = STRING_LIST_INIT_DUP,
6347 ctx.items_alloc = 2 * todo_list->nr + 1;
6348 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6350 string_list_append(&decorate_refs_include, "refs/heads/");
6351 load_ref_decorations(&decoration_filter, 0);
6353 for (i = 0; i < todo_list->nr; ) {
6354 struct todo_item *item = &todo_list->items[i];
6356 /* insert ith item into new list */
6357 ALLOC_GROW(ctx.items,
6358 ctx.items_nr + 1,
6359 ctx.items_alloc);
6361 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6363 if (item->commit) {
6364 ctx.commit = item->commit;
6365 add_decorations_to_list(item->commit, &ctx);
6369 res = write_update_refs_state(&ctx.refs_to_oids);
6371 string_list_clear(&ctx.refs_to_oids, 1);
6373 if (res) {
6374 /* we failed, so clean up the new list. */
6375 free(ctx.items);
6376 return res;
6379 free(todo_list->items);
6380 todo_list->items = ctx.items;
6381 todo_list->nr = ctx.items_nr;
6382 todo_list->alloc = ctx.items_alloc;
6384 return 0;
6387 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6388 const char *shortrevisions, const char *onto_name,
6389 struct commit *onto, const struct object_id *orig_head,
6390 struct string_list *commands, unsigned autosquash,
6391 unsigned update_refs,
6392 struct todo_list *todo_list)
6394 char shortonto[GIT_MAX_HEXSZ + 1];
6395 const char *todo_file = rebase_path_todo();
6396 struct todo_list new_todo = TODO_LIST_INIT;
6397 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6398 struct object_id oid = onto->object.oid;
6399 int res;
6401 repo_find_unique_abbrev_r(r, shortonto, &oid,
6402 DEFAULT_ABBREV);
6404 if (buf->len == 0) {
6405 struct todo_item *item = append_new_todo(todo_list);
6406 item->command = TODO_NOOP;
6407 item->commit = NULL;
6408 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6411 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6412 return -1;
6414 if (autosquash && todo_list_rearrange_squash(todo_list))
6415 return -1;
6417 if (commands->nr)
6418 todo_list_add_exec_commands(todo_list, commands);
6420 if (count_commands(todo_list) == 0) {
6421 apply_autostash(rebase_path_autostash());
6422 sequencer_remove_state(opts);
6424 return error(_("nothing to do"));
6427 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions,
6428 shortonto, flags);
6429 if (res == -1)
6430 return -1;
6431 else if (res == -2) {
6432 apply_autostash(rebase_path_autostash());
6433 sequencer_remove_state(opts);
6435 return -1;
6436 } else if (res == -3) {
6437 apply_autostash(rebase_path_autostash());
6438 sequencer_remove_state(opts);
6439 todo_list_release(&new_todo);
6441 return error(_("nothing to do"));
6442 } else if (res == -4) {
6443 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6444 todo_list_release(&new_todo);
6446 return -1;
6449 /* Expand the commit IDs */
6450 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6451 strbuf_swap(&new_todo.buf, &buf2);
6452 strbuf_release(&buf2);
6453 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6454 new_todo.total_nr = 0;
6455 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0)
6456 BUG("invalid todo list after expanding IDs:\n%s",
6457 new_todo.buf.buf);
6459 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6460 todo_list_release(&new_todo);
6461 return error(_("could not skip unnecessary pick commands"));
6464 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6465 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6466 todo_list_release(&new_todo);
6467 return error_errno(_("could not write '%s'"), todo_file);
6470 res = -1;
6472 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6473 goto cleanup;
6475 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6476 goto cleanup;
6478 todo_list_write_total_nr(&new_todo);
6479 res = pick_commits(r, &new_todo, opts);
6481 cleanup:
6482 todo_list_release(&new_todo);
6484 return res;
6487 struct subject2item_entry {
6488 struct hashmap_entry entry;
6489 int i;
6490 char subject[FLEX_ARRAY];
6493 static int subject2item_cmp(const void *fndata UNUSED,
6494 const struct hashmap_entry *eptr,
6495 const struct hashmap_entry *entry_or_key,
6496 const void *key)
6498 const struct subject2item_entry *a, *b;
6500 a = container_of(eptr, const struct subject2item_entry, entry);
6501 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6503 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6506 define_commit_slab(commit_todo_item, struct todo_item *);
6508 static int skip_fixupish(const char *subject, const char **p) {
6509 return skip_prefix(subject, "fixup! ", p) ||
6510 skip_prefix(subject, "amend! ", p) ||
6511 skip_prefix(subject, "squash! ", p);
6515 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6516 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6517 * after the former, and change "pick" to "fixup"/"squash".
6519 * Note that if the config has specified a custom instruction format, each log
6520 * message will have to be retrieved from the commit (as the oneline in the
6521 * script cannot be trusted) in order to normalize the autosquash arrangement.
6523 int todo_list_rearrange_squash(struct todo_list *todo_list)
6525 struct hashmap subject2item;
6526 int rearranged = 0, *next, *tail, i, nr = 0;
6527 char **subjects;
6528 struct commit_todo_item commit_todo;
6529 struct todo_item *items = NULL;
6531 init_commit_todo_item(&commit_todo);
6533 * The hashmap maps onelines to the respective todo list index.
6535 * If any items need to be rearranged, the next[i] value will indicate
6536 * which item was moved directly after the i'th.
6538 * In that case, last[i] will indicate the index of the latest item to
6539 * be moved to appear after the i'th.
6541 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6542 ALLOC_ARRAY(next, todo_list->nr);
6543 ALLOC_ARRAY(tail, todo_list->nr);
6544 ALLOC_ARRAY(subjects, todo_list->nr);
6545 for (i = 0; i < todo_list->nr; i++) {
6546 struct strbuf buf = STRBUF_INIT;
6547 struct todo_item *item = todo_list->items + i;
6548 const char *commit_buffer, *subject, *p;
6549 size_t subject_len;
6550 int i2 = -1;
6551 struct subject2item_entry *entry;
6553 next[i] = tail[i] = -1;
6554 if (!item->commit || item->command == TODO_DROP) {
6555 subjects[i] = NULL;
6556 continue;
6559 if (is_fixup(item->command)) {
6560 clear_commit_todo_item(&commit_todo);
6561 return error(_("the script was already rearranged."));
6564 repo_parse_commit(the_repository, item->commit);
6565 commit_buffer = repo_logmsg_reencode(the_repository,
6566 item->commit, NULL,
6567 "UTF-8");
6568 find_commit_subject(commit_buffer, &subject);
6569 format_subject(&buf, subject, " ");
6570 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6571 repo_unuse_commit_buffer(the_repository, item->commit,
6572 commit_buffer);
6573 if (skip_fixupish(subject, &p)) {
6574 struct commit *commit2;
6576 for (;;) {
6577 while (isspace(*p))
6578 p++;
6579 if (!skip_fixupish(p, &p))
6580 break;
6583 entry = hashmap_get_entry_from_hash(&subject2item,
6584 strhash(p), p,
6585 struct subject2item_entry,
6586 entry);
6587 if (entry)
6588 /* found by title */
6589 i2 = entry->i;
6590 else if (!strchr(p, ' ') &&
6591 (commit2 =
6592 lookup_commit_reference_by_name(p)) &&
6593 *commit_todo_item_at(&commit_todo, commit2))
6594 /* found by commit name */
6595 i2 = *commit_todo_item_at(&commit_todo, commit2)
6596 - todo_list->items;
6597 else {
6598 /* copy can be a prefix of the commit subject */
6599 for (i2 = 0; i2 < i; i2++)
6600 if (subjects[i2] &&
6601 starts_with(subjects[i2], p))
6602 break;
6603 if (i2 == i)
6604 i2 = -1;
6607 if (i2 >= 0) {
6608 rearranged = 1;
6609 if (starts_with(subject, "fixup!")) {
6610 todo_list->items[i].command = TODO_FIXUP;
6611 } else if (starts_with(subject, "amend!")) {
6612 todo_list->items[i].command = TODO_FIXUP;
6613 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6614 } else {
6615 todo_list->items[i].command = TODO_SQUASH;
6617 if (tail[i2] < 0) {
6618 next[i] = next[i2];
6619 next[i2] = i;
6620 } else {
6621 next[i] = next[tail[i2]];
6622 next[tail[i2]] = i;
6624 tail[i2] = i;
6625 } else if (!hashmap_get_from_hash(&subject2item,
6626 strhash(subject), subject)) {
6627 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6628 entry->i = i;
6629 hashmap_entry_init(&entry->entry,
6630 strhash(entry->subject));
6631 hashmap_put(&subject2item, &entry->entry);
6634 *commit_todo_item_at(&commit_todo, item->commit) = item;
6637 if (rearranged) {
6638 ALLOC_ARRAY(items, todo_list->nr);
6640 for (i = 0; i < todo_list->nr; i++) {
6641 enum todo_command command = todo_list->items[i].command;
6642 int cur = i;
6645 * Initially, all commands are 'pick's. If it is a
6646 * fixup or a squash now, we have rearranged it.
6648 if (is_fixup(command))
6649 continue;
6651 while (cur >= 0) {
6652 items[nr++] = todo_list->items[cur];
6653 cur = next[cur];
6657 assert(nr == todo_list->nr);
6658 todo_list->alloc = nr;
6659 FREE_AND_NULL(todo_list->items);
6660 todo_list->items = items;
6663 free(next);
6664 free(tail);
6665 for (i = 0; i < todo_list->nr; i++)
6666 free(subjects[i]);
6667 free(subjects);
6668 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6670 clear_commit_todo_item(&commit_todo);
6672 return 0;
6675 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6677 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6678 struct object_id cherry_pick_head, rebase_head;
6680 if (file_exists(git_path_seq_dir()))
6681 *whence = FROM_CHERRY_PICK_MULTI;
6682 if (file_exists(rebase_path()) &&
6683 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6684 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6685 oideq(&rebase_head, &cherry_pick_head))
6686 *whence = FROM_REBASE_PICK;
6687 else
6688 *whence = FROM_CHERRY_PICK_SINGLE;
6690 return 1;
6693 return 0;
6696 int sequencer_get_update_refs_state(const char *wt_dir,
6697 struct string_list *refs)
6699 int result = 0;
6700 FILE *fp = NULL;
6701 struct strbuf ref = STRBUF_INIT;
6702 struct strbuf hash = STRBUF_INIT;
6703 struct update_ref_record *rec = NULL;
6705 char *path = rebase_path_update_refs(wt_dir);
6707 fp = fopen(path, "r");
6708 if (!fp)
6709 goto cleanup;
6711 while (strbuf_getline(&ref, fp) != EOF) {
6712 struct string_list_item *item;
6714 CALLOC_ARRAY(rec, 1);
6716 if (strbuf_getline(&hash, fp) == EOF ||
6717 get_oid_hex(hash.buf, &rec->before)) {
6718 warning(_("update-refs file at '%s' is invalid"),
6719 path);
6720 result = -1;
6721 goto cleanup;
6724 if (strbuf_getline(&hash, fp) == EOF ||
6725 get_oid_hex(hash.buf, &rec->after)) {
6726 warning(_("update-refs file at '%s' is invalid"),
6727 path);
6728 result = -1;
6729 goto cleanup;
6732 item = string_list_insert(refs, ref.buf);
6733 item->util = rec;
6734 rec = NULL;
6737 cleanup:
6738 if (fp)
6739 fclose(fp);
6740 free(path);
6741 free(rec);
6742 strbuf_release(&ref);
6743 strbuf_release(&hash);
6744 return result;