builtin/bundle: have unbundle check for repo before opening its bundle
[git/gitster.git] / sequencer.c
bloba2284ac9e953fca5bffb7addf6c9d7fbbedc3492
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "advice.h"
6 #include "config.h"
7 #include "copy.h"
8 #include "environment.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "lockfile.h"
12 #include "dir.h"
13 #include "object-file.h"
14 #include "object-name.h"
15 #include "object-store-ll.h"
16 #include "object.h"
17 #include "pager.h"
18 #include "commit.h"
19 #include "sequencer.h"
20 #include "run-command.h"
21 #include "hook.h"
22 #include "utf8.h"
23 #include "cache-tree.h"
24 #include "diff.h"
25 #include "path.h"
26 #include "revision.h"
27 #include "rerere.h"
28 #include "merge.h"
29 #include "merge-ort.h"
30 #include "merge-ort-wrappers.h"
31 #include "refs.h"
32 #include "sparse-index.h"
33 #include "strvec.h"
34 #include "quote.h"
35 #include "trailer.h"
36 #include "log-tree.h"
37 #include "wt-status.h"
38 #include "hashmap.h"
39 #include "notes-utils.h"
40 #include "sigchain.h"
41 #include "unpack-trees.h"
42 #include "oidmap.h"
43 #include "oidset.h"
44 #include "commit-slab.h"
45 #include "alias.h"
46 #include "commit-reach.h"
47 #include "rebase-interactive.h"
48 #include "reset.h"
49 #include "branch.h"
51 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
54 * To accommodate common filesystem limitations, where the loose refs' file
55 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
56 * --rebase-merges` need to be truncated if the corresponding commit subjects
57 * are too long.
58 * Add some margin to stay clear from reaching `NAME_MAX`.
60 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
62 static const char sign_off_header[] = "Signed-off-by: ";
63 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
65 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
67 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
69 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
70 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
71 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
72 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
74 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
76 * The file containing rebase commands, comments, and empty lines.
77 * This file is created by "git rebase -i" then edited by the user. As
78 * the lines are processed, they are removed from the front of this
79 * file and written to the tail of 'done'.
81 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
82 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
84 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
87 * The rebase command lines that have already been processed. A line
88 * is moved here when it is first handled, before any associated user
89 * actions.
91 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
93 * The file to keep track of how many commands were already processed (e.g.
94 * for the prompt).
96 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
98 * The file to keep track of how many commands are to be processed in total
99 * (e.g. for the prompt).
101 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
103 * The commit message that is planned to be used for any changes that
104 * need to be committed following a user interaction.
106 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
108 * The file into which is accumulated the suggested commit message for
109 * squash/fixup commands. When the first of a series of squash/fixups
110 * is seen, the file is created and the commit message from the
111 * previous commit and from the first squash/fixup commit are written
112 * to it. The commit message for each subsequent squash/fixup commit
113 * is appended to the file as it is processed.
115 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
117 * If the current series of squash/fixups has not yet included a squash
118 * command, then this file exists and holds the commit message of the
119 * original "pick" commit. (If the series ends without a "squash"
120 * command, then this can be used as the commit message of the combined
121 * commit without opening the editor.)
123 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
125 * This file contains the list fixup/squash commands that have been
126 * accumulated into message-fixup or message-squash so far.
128 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
130 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
131 * GIT_AUTHOR_DATE that will be used for the commit that is currently
132 * being rebased.
134 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
136 * When an "edit" rebase command is being processed, the SHA1 of the
137 * commit to be edited is recorded in this file. When "git rebase
138 * --continue" is executed, if there are any staged changes then they
139 * will be amended to the HEAD commit, but only provided the HEAD
140 * commit is still the commit to be edited. When any other rebase
141 * command is processed, this file is deleted.
143 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
145 * When we stop at a given patch via the "edit" command, this file contains
146 * the commit object name of the corresponding patch.
148 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
150 * When we stop for the user to resolve conflicts this file contains
151 * the patch of the commit that is being picked.
153 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
155 * For the post-rewrite hook, we make a list of rewritten commits and
156 * their new sha1s. The rewritten-pending list keeps the sha1s of
157 * commits that have been processed, but not committed yet,
158 * e.g. because they are waiting for a 'squash' command.
160 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
161 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
162 "rebase-merge/rewritten-pending")
165 * The path of the file containing the OID of the "squash onto" commit, i.e.
166 * the dummy commit used for `reset [new root]`.
168 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
171 * The path of the file listing refs that need to be deleted after the rebase
172 * finishes. This is used by the `label` command to record the need for cleanup.
174 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
177 * The update-refs file stores a list of refs that will be updated at the end
178 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
179 * update the OIDs for the refs in this file, but the refs are not updated
180 * until the end of the rebase sequence.
182 * rebase_path_update_refs() returns the path to this file for a given
183 * worktree directory. For the current worktree, pass the_repository->gitdir.
185 static char *rebase_path_update_refs(const char *wt_git_dir)
187 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
191 * The following files are written by git-rebase just after parsing the
192 * command-line.
194 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
195 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
196 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
197 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
198 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
199 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
200 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
201 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
202 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
203 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
204 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
205 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
206 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
207 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
208 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
209 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
210 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
213 * A 'struct replay_ctx' represents the private state of the sequencer.
215 struct replay_ctx {
217 * The commit message that will be used except at the end of a
218 * chain of fixup and squash commands.
220 struct strbuf message;
222 * The list of completed fixup and squash commands in the
223 * current chain.
225 struct strbuf current_fixups;
227 * Stores the reflog message that will be used when creating a
228 * commit. Points to a static buffer and should not be free()'d.
230 const char *reflog_message;
232 * The number of completed fixup and squash commands in the
233 * current chain.
235 int current_fixup_count;
237 * Whether message contains a commit message.
239 unsigned have_message :1;
242 struct replay_ctx* replay_ctx_new(void)
244 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
246 strbuf_init(&ctx->current_fixups, 0);
247 strbuf_init(&ctx->message, 0);
249 return ctx;
253 * A 'struct update_refs_record' represents a value in the update-refs
254 * list. We use a string_list to map refs to these (before, after) pairs.
256 struct update_ref_record {
257 struct object_id before;
258 struct object_id after;
261 static struct update_ref_record *init_update_ref_record(const char *ref)
263 struct update_ref_record *rec;
265 CALLOC_ARRAY(rec, 1);
267 oidcpy(&rec->before, null_oid());
268 oidcpy(&rec->after, null_oid());
270 /* This may fail, but that's fine, we will keep the null OID. */
271 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
273 return rec;
276 static int git_sequencer_config(const char *k, const char *v,
277 const struct config_context *ctx, void *cb)
279 struct replay_opts *opts = cb;
281 if (!strcmp(k, "commit.cleanup")) {
282 if (!v)
283 return config_error_nonbool(k);
285 if (!strcmp(v, "verbatim")) {
286 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
287 opts->explicit_cleanup = 1;
288 } else if (!strcmp(v, "whitespace")) {
289 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
290 opts->explicit_cleanup = 1;
291 } else if (!strcmp(v, "strip")) {
292 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
293 opts->explicit_cleanup = 1;
294 } else if (!strcmp(v, "scissors")) {
295 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
296 opts->explicit_cleanup = 1;
297 } else {
298 warning(_("invalid commit message cleanup mode '%s'"),
302 return 0;
305 if (!strcmp(k, "commit.gpgsign")) {
306 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
307 return 0;
310 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
311 int ret = git_config_string(&opts->default_strategy, k, v);
312 if (ret == 0) {
314 * pull.twohead is allowed to be multi-valued; we only
315 * care about the first value.
317 char *tmp = strchr(opts->default_strategy, ' ');
318 if (tmp)
319 *tmp = '\0';
321 return ret;
324 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
325 opts->commit_use_reference = git_config_bool(k, v);
327 return git_diff_basic_config(k, v, ctx, NULL);
330 void sequencer_init_config(struct replay_opts *opts)
332 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
333 git_config(git_sequencer_config, opts);
336 static inline int is_rebase_i(const struct replay_opts *opts)
338 return opts->action == REPLAY_INTERACTIVE_REBASE;
341 static const char *get_dir(const struct replay_opts *opts)
343 if (is_rebase_i(opts))
344 return rebase_path();
345 return git_path_seq_dir();
348 static const char *get_todo_path(const struct replay_opts *opts)
350 if (is_rebase_i(opts))
351 return rebase_path_todo();
352 return git_path_todo_file();
356 * Returns 0 for non-conforming footer
357 * Returns 1 for conforming footer
358 * Returns 2 when sob exists within conforming footer
359 * Returns 3 when sob exists within conforming footer as last entry
361 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
362 size_t ignore_footer)
364 struct trailer_iterator iter;
365 size_t i = 0;
366 int found_sob = 0, found_sob_last = 0;
367 char saved_char;
369 if (ignore_footer) {
370 saved_char = sb->buf[sb->len - ignore_footer];
371 sb->buf[sb->len - ignore_footer] = '\0';
374 trailer_iterator_init(&iter, sb->buf);
376 if (ignore_footer)
377 sb->buf[sb->len - ignore_footer] = saved_char;
379 while (trailer_iterator_advance(&iter)) {
380 i++;
381 if (sob && !strncmp(iter.raw, sob->buf, sob->len))
382 found_sob = i;
384 trailer_iterator_release(&iter);
386 if (!i)
387 return 0;
389 found_sob_last = (int)i == found_sob;
391 if (found_sob_last)
392 return 3;
393 if (found_sob)
394 return 2;
395 return 1;
398 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
400 static struct strbuf buf = STRBUF_INIT;
402 strbuf_reset(&buf);
403 if (opts->gpg_sign)
404 sq_quotef(&buf, "-S%s", opts->gpg_sign);
405 return buf.buf;
408 static void replay_ctx_release(struct replay_ctx *ctx)
410 strbuf_release(&ctx->current_fixups);
411 strbuf_release(&ctx->message);
414 void replay_opts_release(struct replay_opts *opts)
416 struct replay_ctx *ctx = opts->ctx;
418 free(opts->gpg_sign);
419 free(opts->reflog_action);
420 free(opts->default_strategy);
421 free(opts->strategy);
422 strvec_clear (&opts->xopts);
423 if (opts->revs)
424 release_revisions(opts->revs);
425 free(opts->revs);
426 replay_ctx_release(ctx);
427 free(opts->ctx);
430 int sequencer_remove_state(struct replay_opts *opts)
432 struct strbuf buf = STRBUF_INIT;
433 int ret = 0;
435 if (is_rebase_i(opts) &&
436 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
437 char *p = buf.buf;
438 while (*p) {
439 char *eol = strchr(p, '\n');
440 if (eol)
441 *eol = '\0';
442 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
443 warning(_("could not delete '%s'"), p);
444 ret = -1;
446 if (!eol)
447 break;
448 p = eol + 1;
452 strbuf_reset(&buf);
453 strbuf_addstr(&buf, get_dir(opts));
454 if (remove_dir_recursively(&buf, 0))
455 ret = error(_("could not remove '%s'"), buf.buf);
456 strbuf_release(&buf);
458 return ret;
461 static const char *action_name(const struct replay_opts *opts)
463 switch (opts->action) {
464 case REPLAY_REVERT:
465 return N_("revert");
466 case REPLAY_PICK:
467 return N_("cherry-pick");
468 case REPLAY_INTERACTIVE_REBASE:
469 return N_("rebase");
471 die(_("unknown action: %d"), opts->action);
474 struct commit_message {
475 char *parent_label;
476 char *label;
477 char *subject;
478 const char *message;
481 static const char *short_commit_name(struct repository *r, struct commit *commit)
483 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
486 static int get_message(struct commit *commit, struct commit_message *out)
488 const char *abbrev, *subject;
489 int subject_len;
491 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
492 get_commit_output_encoding());
493 abbrev = short_commit_name(the_repository, commit);
495 subject_len = find_commit_subject(out->message, &subject);
497 out->subject = xmemdupz(subject, subject_len);
498 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
499 out->parent_label = xstrfmt("parent of %s", out->label);
501 return 0;
504 static void free_message(struct commit *commit, struct commit_message *msg)
506 free(msg->parent_label);
507 free(msg->label);
508 free(msg->subject);
509 repo_unuse_commit_buffer(the_repository, commit, msg->message);
512 const char *rebase_resolvemsg =
513 N_("Resolve all conflicts manually, mark them as resolved with\n"
514 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
515 "You can instead skip this commit: run \"git rebase --skip\".\n"
516 "To abort and get back to the state before \"git rebase\", run "
517 "\"git rebase --abort\".");
519 static void print_advice(struct repository *r, int show_hint,
520 struct replay_opts *opts)
522 const char *msg;
524 if (is_rebase_i(opts))
525 msg = rebase_resolvemsg;
526 else
527 msg = getenv("GIT_CHERRY_PICK_HELP");
529 if (msg) {
530 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
532 * A conflict has occurred but the porcelain
533 * (typically rebase --interactive) wants to take care
534 * of the commit itself so remove CHERRY_PICK_HEAD
536 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
537 NULL, REF_NO_DEREF);
538 return;
541 if (show_hint) {
542 if (opts->no_commit)
543 advise_if_enabled(ADVICE_MERGE_CONFLICT,
544 _("after resolving the conflicts, mark the corrected paths\n"
545 "with 'git add <paths>' or 'git rm <paths>'"));
546 else if (opts->action == REPLAY_PICK)
547 advise_if_enabled(ADVICE_MERGE_CONFLICT,
548 _("After resolving the conflicts, mark them with\n"
549 "\"git add/rm <pathspec>\", then run\n"
550 "\"git cherry-pick --continue\".\n"
551 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
552 "To abort and get back to the state before \"git cherry-pick\",\n"
553 "run \"git cherry-pick --abort\"."));
554 else if (opts->action == REPLAY_REVERT)
555 advise_if_enabled(ADVICE_MERGE_CONFLICT,
556 _("After resolving the conflicts, mark them with\n"
557 "\"git add/rm <pathspec>\", then run\n"
558 "\"git revert --continue\".\n"
559 "You can instead skip this commit with \"git revert --skip\".\n"
560 "To abort and get back to the state before \"git revert\",\n"
561 "run \"git revert --abort\"."));
562 else
563 BUG("unexpected pick action in print_advice()");
567 static int write_message(const void *buf, size_t len, const char *filename,
568 int append_eol)
570 struct lock_file msg_file = LOCK_INIT;
572 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
573 if (msg_fd < 0)
574 return error_errno(_("could not lock '%s'"), filename);
575 if (write_in_full(msg_fd, buf, len) < 0) {
576 error_errno(_("could not write to '%s'"), filename);
577 rollback_lock_file(&msg_file);
578 return -1;
580 if (append_eol && write(msg_fd, "\n", 1) < 0) {
581 error_errno(_("could not write eol to '%s'"), filename);
582 rollback_lock_file(&msg_file);
583 return -1;
585 if (commit_lock_file(&msg_file) < 0)
586 return error(_("failed to finalize '%s'"), filename);
588 return 0;
591 int read_oneliner(struct strbuf *buf,
592 const char *path, unsigned flags)
594 int orig_len = buf->len;
596 if (strbuf_read_file(buf, path, 0) < 0) {
597 if ((flags & READ_ONELINER_WARN_MISSING) ||
598 (errno != ENOENT && errno != ENOTDIR))
599 warning_errno(_("could not read '%s'"), path);
600 return 0;
603 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
604 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
605 --buf->len;
606 buf->buf[buf->len] = '\0';
609 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
610 return 0;
612 return 1;
615 static struct tree *empty_tree(struct repository *r)
617 return lookup_tree(r, the_hash_algo->empty_tree);
620 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
622 if (repo_read_index_unmerged(repo))
623 return error_resolve_conflict(action_name(opts));
625 error(_("your local changes would be overwritten by %s."),
626 _(action_name(opts)));
628 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
629 advise(_("commit your changes or stash them to proceed."));
630 return -1;
633 static void update_abort_safety_file(void)
635 struct object_id head;
637 /* Do nothing on a single-pick */
638 if (!file_exists(git_path_seq_dir()))
639 return;
641 if (!repo_get_oid(the_repository, "HEAD", &head))
642 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
643 else
644 write_file(git_path_abort_safety_file(), "%s", "");
647 static int fast_forward_to(struct repository *r,
648 const struct object_id *to,
649 const struct object_id *from,
650 int unborn,
651 struct replay_opts *opts)
653 struct ref_transaction *transaction;
654 struct strbuf sb = STRBUF_INIT;
655 struct strbuf err = STRBUF_INIT;
657 repo_read_index(r);
658 if (checkout_fast_forward(r, from, to, 1))
659 return -1; /* the callee should have complained already */
661 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
663 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
664 &err);
665 if (!transaction ||
666 ref_transaction_update(transaction, "HEAD",
667 to, unborn && !is_rebase_i(opts) ?
668 null_oid() : from, NULL, NULL,
669 0, sb.buf, &err) ||
670 ref_transaction_commit(transaction, &err)) {
671 ref_transaction_free(transaction);
672 error("%s", err.buf);
673 strbuf_release(&sb);
674 strbuf_release(&err);
675 return -1;
678 strbuf_release(&sb);
679 strbuf_release(&err);
680 ref_transaction_free(transaction);
681 update_abort_safety_file();
682 return 0;
685 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
686 int use_editor)
688 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
689 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
690 COMMIT_MSG_CLEANUP_SPACE;
691 else if (!strcmp(cleanup_arg, "verbatim"))
692 return COMMIT_MSG_CLEANUP_NONE;
693 else if (!strcmp(cleanup_arg, "whitespace"))
694 return COMMIT_MSG_CLEANUP_SPACE;
695 else if (!strcmp(cleanup_arg, "strip"))
696 return COMMIT_MSG_CLEANUP_ALL;
697 else if (!strcmp(cleanup_arg, "scissors"))
698 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
699 COMMIT_MSG_CLEANUP_SPACE;
700 else
701 die(_("Invalid cleanup mode %s"), cleanup_arg);
705 * NB using int rather than enum cleanup_mode to stop clang's
706 * -Wtautological-constant-out-of-range-compare complaining that the comparison
707 * is always true.
709 static const char *describe_cleanup_mode(int cleanup_mode)
711 static const char *modes[] = { "whitespace",
712 "verbatim",
713 "scissors",
714 "strip" };
716 if (cleanup_mode < ARRAY_SIZE(modes))
717 return modes[cleanup_mode];
719 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
722 void append_conflicts_hint(struct index_state *istate,
723 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
725 int i;
727 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
728 strbuf_addch(msgbuf, '\n');
729 wt_status_append_cut_line(msgbuf);
730 strbuf_addstr(msgbuf, comment_line_str);
733 strbuf_addch(msgbuf, '\n');
734 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
735 for (i = 0; i < istate->cache_nr;) {
736 const struct cache_entry *ce = istate->cache[i++];
737 if (ce_stage(ce)) {
738 strbuf_commented_addf(msgbuf, comment_line_str,
739 "\t%s\n", ce->name);
740 while (i < istate->cache_nr &&
741 !strcmp(ce->name, istate->cache[i]->name))
742 i++;
747 static int do_recursive_merge(struct repository *r,
748 struct commit *base, struct commit *next,
749 const char *base_label, const char *next_label,
750 struct object_id *head, struct strbuf *msgbuf,
751 struct replay_opts *opts)
753 struct merge_options o;
754 struct merge_result result;
755 struct tree *next_tree, *base_tree, *head_tree;
756 int clean, show_output;
757 int i;
758 struct lock_file index_lock = LOCK_INIT;
760 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
761 return -1;
763 repo_read_index(r);
765 init_merge_options(&o, r);
766 o.ancestor = base ? base_label : "(empty tree)";
767 o.branch1 = "HEAD";
768 o.branch2 = next ? next_label : "(empty tree)";
769 if (is_rebase_i(opts))
770 o.buffer_output = 2;
771 o.show_rename_progress = 1;
773 head_tree = parse_tree_indirect(head);
774 if (!head_tree)
775 return error(_("unable to read tree (%s)"), oid_to_hex(head));
776 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
777 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
779 for (i = 0; i < opts->xopts.nr; i++)
780 parse_merge_opt(&o, opts->xopts.v[i]);
782 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
783 memset(&result, 0, sizeof(result));
784 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
785 &result);
786 show_output = !is_rebase_i(opts) || !result.clean;
788 * TODO: merge_switch_to_result will update index/working tree;
789 * we only really want to do that if !result.clean || this is
790 * the final patch to be picked. But determining this is the
791 * final patch would take some work, and "head_tree" would need
792 * to be replace with the tree the index matched before we
793 * started doing any picks.
795 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
796 clean = result.clean;
797 } else {
798 ensure_full_index(r->index);
799 clean = merge_trees(&o, head_tree, next_tree, base_tree);
800 if (is_rebase_i(opts) && clean <= 0)
801 fputs(o.obuf.buf, stdout);
802 strbuf_release(&o.obuf);
804 if (clean < 0) {
805 rollback_lock_file(&index_lock);
806 return clean;
809 if (write_locked_index(r->index, &index_lock,
810 COMMIT_LOCK | SKIP_IF_UNCHANGED))
812 * TRANSLATORS: %s will be "revert", "cherry-pick" or
813 * "rebase".
815 return error(_("%s: Unable to write new index file"),
816 _(action_name(opts)));
818 if (!clean)
819 append_conflicts_hint(r->index, msgbuf,
820 opts->default_msg_cleanup);
822 return !clean;
825 static struct object_id *get_cache_tree_oid(struct index_state *istate)
827 if (!cache_tree_fully_valid(istate->cache_tree))
828 if (cache_tree_update(istate, 0)) {
829 error(_("unable to update cache tree"));
830 return NULL;
833 return &istate->cache_tree->oid;
836 static int is_index_unchanged(struct repository *r)
838 struct object_id head_oid, *cache_tree_oid;
839 const struct object_id *head_tree_oid;
840 struct commit *head_commit;
841 struct index_state *istate = r->index;
842 const char *head_name;
844 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
845 /* Check to see if this is an unborn branch */
846 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
847 "HEAD",
848 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
849 &head_oid, NULL);
850 if (!head_name ||
851 !starts_with(head_name, "refs/heads/") ||
852 !is_null_oid(&head_oid))
853 return error(_("could not resolve HEAD commit"));
854 head_tree_oid = the_hash_algo->empty_tree;
855 } else {
856 head_commit = lookup_commit(r, &head_oid);
859 * If head_commit is NULL, check_commit, called from
860 * lookup_commit, would have indicated that head_commit is not
861 * a commit object already. repo_parse_commit() will return failure
862 * without further complaints in such a case. Otherwise, if
863 * the commit is invalid, repo_parse_commit() will complain. So
864 * there is nothing for us to say here. Just return failure.
866 if (repo_parse_commit(r, head_commit))
867 return -1;
869 head_tree_oid = get_commit_tree_oid(head_commit);
872 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
873 return -1;
875 return oideq(cache_tree_oid, head_tree_oid);
878 static int write_author_script(const char *message)
880 struct strbuf buf = STRBUF_INIT;
881 const char *eol;
882 int res;
884 for (;;)
885 if (!*message || starts_with(message, "\n")) {
886 missing_author:
887 /* Missing 'author' line? */
888 unlink(rebase_path_author_script());
889 return 0;
890 } else if (skip_prefix(message, "author ", &message))
891 break;
892 else if ((eol = strchr(message, '\n')))
893 message = eol + 1;
894 else
895 goto missing_author;
897 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
898 while (*message && *message != '\n' && *message != '\r')
899 if (skip_prefix(message, " <", &message))
900 break;
901 else if (*message != '\'')
902 strbuf_addch(&buf, *(message++));
903 else
904 strbuf_addf(&buf, "'\\%c'", *(message++));
905 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
906 while (*message && *message != '\n' && *message != '\r')
907 if (skip_prefix(message, "> ", &message))
908 break;
909 else if (*message != '\'')
910 strbuf_addch(&buf, *(message++));
911 else
912 strbuf_addf(&buf, "'\\%c'", *(message++));
913 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
914 while (*message && *message != '\n' && *message != '\r')
915 if (*message != '\'')
916 strbuf_addch(&buf, *(message++));
917 else
918 strbuf_addf(&buf, "'\\%c'", *(message++));
919 strbuf_addch(&buf, '\'');
920 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
921 strbuf_release(&buf);
922 return res;
926 * Take a series of KEY='VALUE' lines where VALUE part is
927 * sq-quoted, and append <KEY, VALUE> at the end of the string list
929 static int parse_key_value_squoted(char *buf, struct string_list *list)
931 while (*buf) {
932 struct string_list_item *item;
933 char *np;
934 char *cp = strchr(buf, '=');
935 if (!cp) {
936 np = strchrnul(buf, '\n');
937 return error(_("no key present in '%.*s'"),
938 (int) (np - buf), buf);
940 np = strchrnul(cp, '\n');
941 *cp++ = '\0';
942 item = string_list_append(list, buf);
944 buf = np + (*np == '\n');
945 *np = '\0';
946 cp = sq_dequote(cp);
947 if (!cp)
948 return error(_("unable to dequote value of '%s'"),
949 item->string);
950 item->util = xstrdup(cp);
952 return 0;
956 * Reads and parses the state directory's "author-script" file, and sets name,
957 * email and date accordingly.
958 * Returns 0 on success, -1 if the file could not be parsed.
960 * The author script is of the format:
962 * GIT_AUTHOR_NAME='$author_name'
963 * GIT_AUTHOR_EMAIL='$author_email'
964 * GIT_AUTHOR_DATE='$author_date'
966 * where $author_name, $author_email and $author_date are quoted. We are strict
967 * with our parsing, as the file was meant to be eval'd in the now-removed
968 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
969 * from what this function expects, it is better to bail out than to do
970 * something that the user does not expect.
972 int read_author_script(const char *path, char **name, char **email, char **date,
973 int allow_missing)
975 struct strbuf buf = STRBUF_INIT;
976 struct string_list kv = STRING_LIST_INIT_DUP;
977 int retval = -1; /* assume failure */
978 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
980 if (strbuf_read_file(&buf, path, 256) <= 0) {
981 strbuf_release(&buf);
982 if (errno == ENOENT && allow_missing)
983 return 0;
984 else
985 return error_errno(_("could not open '%s' for reading"),
986 path);
989 if (parse_key_value_squoted(buf.buf, &kv))
990 goto finish;
992 for (i = 0; i < kv.nr; i++) {
993 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
994 if (name_i != -2)
995 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
996 else
997 name_i = i;
998 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
999 if (email_i != -2)
1000 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
1001 else
1002 email_i = i;
1003 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
1004 if (date_i != -2)
1005 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
1006 else
1007 date_i = i;
1008 } else {
1009 err = error(_("unknown variable '%s'"),
1010 kv.items[i].string);
1013 if (name_i == -2)
1014 error(_("missing 'GIT_AUTHOR_NAME'"));
1015 if (email_i == -2)
1016 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1017 if (date_i == -2)
1018 error(_("missing 'GIT_AUTHOR_DATE'"));
1019 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
1020 goto finish;
1021 *name = kv.items[name_i].util;
1022 *email = kv.items[email_i].util;
1023 *date = kv.items[date_i].util;
1024 retval = 0;
1025 finish:
1026 string_list_clear(&kv, !!retval);
1027 strbuf_release(&buf);
1028 return retval;
1032 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
1033 * file with shell quoting into struct strvec. Returns -1 on
1034 * error, 0 otherwise.
1036 static int read_env_script(struct strvec *env)
1038 char *name, *email, *date;
1040 if (read_author_script(rebase_path_author_script(),
1041 &name, &email, &date, 0))
1042 return -1;
1044 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1045 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1046 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
1047 free(name);
1048 free(email);
1049 free(date);
1051 return 0;
1054 static char *get_author(const char *message)
1056 size_t len;
1057 const char *a;
1059 a = find_commit_header(message, "author", &len);
1060 if (a)
1061 return xmemdupz(a, len);
1063 return NULL;
1066 static const char *author_date_from_env(const struct strvec *env)
1068 int i;
1069 const char *date;
1071 for (i = 0; i < env->nr; i++)
1072 if (skip_prefix(env->v[i],
1073 "GIT_AUTHOR_DATE=", &date))
1074 return date;
1076 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1077 * reading the script
1079 BUG("GIT_AUTHOR_DATE missing from author script");
1082 static const char staged_changes_advice[] =
1083 N_("you have staged changes in your working tree\n"
1084 "If these changes are meant to be squashed into the previous commit, run:\n"
1085 "\n"
1086 " git commit --amend %s\n"
1087 "\n"
1088 "If they are meant to go into a new commit, run:\n"
1089 "\n"
1090 " git commit %s\n"
1091 "\n"
1092 "In both cases, once you're done, continue with:\n"
1093 "\n"
1094 " git rebase --continue\n");
1096 #define ALLOW_EMPTY (1<<0)
1097 #define EDIT_MSG (1<<1)
1098 #define AMEND_MSG (1<<2)
1099 #define CLEANUP_MSG (1<<3)
1100 #define VERIFY_MSG (1<<4)
1101 #define CREATE_ROOT_COMMIT (1<<5)
1102 #define VERBATIM_MSG (1<<6)
1104 static int run_command_silent_on_success(struct child_process *cmd)
1106 struct strbuf buf = STRBUF_INIT;
1107 int rc;
1109 cmd->stdout_to_stderr = 1;
1110 rc = pipe_command(cmd,
1111 NULL, 0,
1112 NULL, 0,
1113 &buf, 0);
1115 if (rc)
1116 fputs(buf.buf, stderr);
1117 strbuf_release(&buf);
1118 return rc;
1122 * If we are cherry-pick, and if the merge did not result in
1123 * hand-editing, we will hit this commit and inherit the original
1124 * author date and name.
1126 * If we are revert, or if our cherry-pick results in a hand merge,
1127 * we had better say that the current user is responsible for that.
1129 * An exception is when run_git_commit() is called during an
1130 * interactive rebase: in that case, we will want to retain the
1131 * author metadata.
1133 static int run_git_commit(const char *defmsg,
1134 struct replay_opts *opts,
1135 unsigned int flags)
1137 struct replay_ctx *ctx = opts->ctx;
1138 struct child_process cmd = CHILD_PROCESS_INIT;
1140 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1141 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1143 cmd.git_cmd = 1;
1145 if (is_rebase_i(opts) &&
1146 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1147 !(!defmsg && (flags & AMEND_MSG))) &&
1148 read_env_script(&cmd.env)) {
1149 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1151 return error(_(staged_changes_advice),
1152 gpg_opt, gpg_opt);
1155 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", ctx->reflog_message);
1157 if (opts->committer_date_is_author_date)
1158 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1159 opts->ignore_date ?
1160 "" :
1161 author_date_from_env(&cmd.env));
1162 if (opts->ignore_date)
1163 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1165 strvec_push(&cmd.args, "commit");
1167 if (!(flags & VERIFY_MSG))
1168 strvec_push(&cmd.args, "-n");
1169 if ((flags & AMEND_MSG))
1170 strvec_push(&cmd.args, "--amend");
1171 if (opts->gpg_sign)
1172 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1173 else
1174 strvec_push(&cmd.args, "--no-gpg-sign");
1175 if (defmsg)
1176 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1177 else if (!(flags & EDIT_MSG))
1178 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1179 if ((flags & CLEANUP_MSG))
1180 strvec_push(&cmd.args, "--cleanup=strip");
1181 if ((flags & VERBATIM_MSG))
1182 strvec_push(&cmd.args, "--cleanup=verbatim");
1183 if ((flags & EDIT_MSG))
1184 strvec_push(&cmd.args, "-e");
1185 else if (!(flags & CLEANUP_MSG) &&
1186 !opts->signoff && !opts->record_origin &&
1187 !opts->explicit_cleanup)
1188 strvec_push(&cmd.args, "--cleanup=verbatim");
1190 if ((flags & ALLOW_EMPTY))
1191 strvec_push(&cmd.args, "--allow-empty");
1193 if (!(flags & EDIT_MSG))
1194 strvec_push(&cmd.args, "--allow-empty-message");
1196 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1197 return run_command_silent_on_success(&cmd);
1198 else
1199 return run_command(&cmd);
1202 static int rest_is_empty(const struct strbuf *sb, int start)
1204 int i, eol;
1205 const char *nl;
1207 /* Check if the rest is just whitespace and Signed-off-by's. */
1208 for (i = start; i < sb->len; i++) {
1209 nl = memchr(sb->buf + i, '\n', sb->len - i);
1210 if (nl)
1211 eol = nl - sb->buf;
1212 else
1213 eol = sb->len;
1215 if (strlen(sign_off_header) <= eol - i &&
1216 starts_with(sb->buf + i, sign_off_header)) {
1217 i = eol;
1218 continue;
1220 while (i < eol)
1221 if (!isspace(sb->buf[i++]))
1222 return 0;
1225 return 1;
1228 void cleanup_message(struct strbuf *msgbuf,
1229 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1231 if (verbose || /* Truncate the message just before the diff, if any. */
1232 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1233 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1234 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1235 strbuf_stripspace(msgbuf,
1236 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1240 * Find out if the message in the strbuf contains only whitespace and
1241 * Signed-off-by lines.
1243 int message_is_empty(const struct strbuf *sb,
1244 enum commit_msg_cleanup_mode cleanup_mode)
1246 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1247 return 0;
1248 return rest_is_empty(sb, 0);
1252 * See if the user edited the message in the editor or left what
1253 * was in the template intact
1255 int template_untouched(const struct strbuf *sb, const char *template_file,
1256 enum commit_msg_cleanup_mode cleanup_mode)
1258 struct strbuf tmpl = STRBUF_INIT;
1259 const char *start;
1261 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1262 return 0;
1264 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1265 return 0;
1267 strbuf_stripspace(&tmpl,
1268 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1269 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1270 start = sb->buf;
1271 strbuf_release(&tmpl);
1272 return rest_is_empty(sb, start - sb->buf);
1275 int update_head_with_reflog(const struct commit *old_head,
1276 const struct object_id *new_head,
1277 const char *action, const struct strbuf *msg,
1278 struct strbuf *err)
1280 struct ref_transaction *transaction;
1281 struct strbuf sb = STRBUF_INIT;
1282 const char *nl;
1283 int ret = 0;
1285 if (action) {
1286 strbuf_addstr(&sb, action);
1287 strbuf_addstr(&sb, ": ");
1290 nl = strchr(msg->buf, '\n');
1291 if (nl) {
1292 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1293 } else {
1294 strbuf_addbuf(&sb, msg);
1295 strbuf_addch(&sb, '\n');
1298 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1299 err);
1300 if (!transaction ||
1301 ref_transaction_update(transaction, "HEAD", new_head,
1302 old_head ? &old_head->object.oid : null_oid(),
1303 NULL, NULL, 0, sb.buf, err) ||
1304 ref_transaction_commit(transaction, err)) {
1305 ret = -1;
1307 ref_transaction_free(transaction);
1308 strbuf_release(&sb);
1310 return ret;
1313 static int run_rewrite_hook(const struct object_id *oldoid,
1314 const struct object_id *newoid)
1316 struct child_process proc = CHILD_PROCESS_INIT;
1317 int code;
1318 struct strbuf sb = STRBUF_INIT;
1319 const char *hook_path = find_hook("post-rewrite");
1321 if (!hook_path)
1322 return 0;
1324 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1325 proc.in = -1;
1326 proc.stdout_to_stderr = 1;
1327 proc.trace2_hook_name = "post-rewrite";
1329 code = start_command(&proc);
1330 if (code)
1331 return code;
1332 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1333 sigchain_push(SIGPIPE, SIG_IGN);
1334 write_in_full(proc.in, sb.buf, sb.len);
1335 close(proc.in);
1336 strbuf_release(&sb);
1337 sigchain_pop(SIGPIPE);
1338 return finish_command(&proc);
1341 void commit_post_rewrite(struct repository *r,
1342 const struct commit *old_head,
1343 const struct object_id *new_head)
1345 struct notes_rewrite_cfg *cfg;
1347 cfg = init_copy_notes_for_rewrite("amend");
1348 if (cfg) {
1349 /* we are amending, so old_head is not NULL */
1350 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1351 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1353 run_rewrite_hook(&old_head->object.oid, new_head);
1356 static int run_prepare_commit_msg_hook(struct repository *r,
1357 struct strbuf *msg,
1358 const char *commit)
1360 int ret = 0;
1361 const char *name, *arg1 = NULL, *arg2 = NULL;
1363 name = git_path_commit_editmsg();
1364 if (write_message(msg->buf, msg->len, name, 0))
1365 return -1;
1367 if (commit) {
1368 arg1 = "commit";
1369 arg2 = commit;
1370 } else {
1371 arg1 = "message";
1373 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1374 arg1, arg2, NULL))
1375 ret = error(_("'prepare-commit-msg' hook failed"));
1377 return ret;
1380 static const char implicit_ident_advice_noconfig[] =
1381 N_("Your name and email address were configured automatically based\n"
1382 "on your username and hostname. Please check that they are accurate.\n"
1383 "You can suppress this message by setting them explicitly. Run the\n"
1384 "following command and follow the instructions in your editor to edit\n"
1385 "your configuration file:\n"
1386 "\n"
1387 " git config --global --edit\n"
1388 "\n"
1389 "After doing this, you may fix the identity used for this commit with:\n"
1390 "\n"
1391 " git commit --amend --reset-author\n");
1393 static const char implicit_ident_advice_config[] =
1394 N_("Your name and email address were configured automatically based\n"
1395 "on your username and hostname. Please check that they are accurate.\n"
1396 "You can suppress this message by setting them explicitly:\n"
1397 "\n"
1398 " git config --global user.name \"Your Name\"\n"
1399 " git config --global user.email you@example.com\n"
1400 "\n"
1401 "After doing this, you may fix the identity used for this commit with:\n"
1402 "\n"
1403 " git commit --amend --reset-author\n");
1405 static const char *implicit_ident_advice(void)
1407 char *user_config = interpolate_path("~/.gitconfig", 0);
1408 char *xdg_config = xdg_config_home("config");
1409 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1411 free(user_config);
1412 free(xdg_config);
1414 if (config_exists)
1415 return _(implicit_ident_advice_config);
1416 else
1417 return _(implicit_ident_advice_noconfig);
1421 void print_commit_summary(struct repository *r,
1422 const char *prefix,
1423 const struct object_id *oid,
1424 unsigned int flags)
1426 struct rev_info rev;
1427 struct commit *commit;
1428 struct strbuf format = STRBUF_INIT;
1429 const char *head;
1430 struct pretty_print_context pctx = {0};
1431 struct strbuf author_ident = STRBUF_INIT;
1432 struct strbuf committer_ident = STRBUF_INIT;
1433 struct ref_store *refs;
1435 commit = lookup_commit(r, oid);
1436 if (!commit)
1437 die(_("couldn't look up newly created commit"));
1438 if (repo_parse_commit(r, commit))
1439 die(_("could not parse newly created commit"));
1441 strbuf_addstr(&format, "format:%h] %s");
1443 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1444 &pctx);
1445 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1446 &pctx);
1447 if (strbuf_cmp(&author_ident, &committer_ident)) {
1448 strbuf_addstr(&format, "\n Author: ");
1449 strbuf_addbuf_percentquote(&format, &author_ident);
1451 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1452 struct strbuf date = STRBUF_INIT;
1454 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1455 strbuf_addstr(&format, "\n Date: ");
1456 strbuf_addbuf_percentquote(&format, &date);
1457 strbuf_release(&date);
1459 if (!committer_ident_sufficiently_given()) {
1460 strbuf_addstr(&format, "\n Committer: ");
1461 strbuf_addbuf_percentquote(&format, &committer_ident);
1462 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1463 strbuf_addch(&format, '\n');
1464 strbuf_addstr(&format, implicit_ident_advice());
1467 strbuf_release(&author_ident);
1468 strbuf_release(&committer_ident);
1470 repo_init_revisions(r, &rev, prefix);
1471 setup_revisions(0, NULL, &rev, NULL);
1473 rev.diff = 1;
1474 rev.diffopt.output_format =
1475 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1477 rev.verbose_header = 1;
1478 rev.show_root_diff = 1;
1479 get_commit_format(format.buf, &rev);
1480 rev.always_show_header = 0;
1481 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1482 diff_setup_done(&rev.diffopt);
1484 refs = get_main_ref_store(r);
1485 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1486 if (!head)
1487 die(_("unable to resolve HEAD after creating commit"));
1488 if (!strcmp(head, "HEAD"))
1489 head = _("detached HEAD");
1490 else
1491 skip_prefix(head, "refs/heads/", &head);
1492 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1493 _(" (root-commit)") : "");
1495 if (!log_tree_commit(&rev, commit)) {
1496 rev.always_show_header = 1;
1497 rev.use_terminator = 1;
1498 log_tree_commit(&rev, commit);
1501 release_revisions(&rev);
1502 strbuf_release(&format);
1505 static int parse_head(struct repository *r, struct commit **head)
1507 struct commit *current_head;
1508 struct object_id oid;
1510 if (repo_get_oid(r, "HEAD", &oid)) {
1511 current_head = NULL;
1512 } else {
1513 current_head = lookup_commit_reference(r, &oid);
1514 if (!current_head)
1515 return error(_("could not parse HEAD"));
1516 if (!oideq(&oid, &current_head->object.oid)) {
1517 warning(_("HEAD %s is not a commit!"),
1518 oid_to_hex(&oid));
1520 if (repo_parse_commit(r, current_head))
1521 return error(_("could not parse HEAD commit"));
1523 *head = current_head;
1525 return 0;
1529 * Try to commit without forking 'git commit'. In some cases we need
1530 * to run 'git commit' to display an error message
1532 * Returns:
1533 * -1 - error unable to commit
1534 * 0 - success
1535 * 1 - run 'git commit'
1537 static int try_to_commit(struct repository *r,
1538 struct strbuf *msg, const char *author,
1539 struct replay_opts *opts, unsigned int flags,
1540 struct object_id *oid)
1542 struct replay_ctx *ctx = opts->ctx;
1543 struct object_id tree;
1544 struct commit *current_head = NULL;
1545 struct commit_list *parents = NULL;
1546 struct commit_extra_header *extra = NULL;
1547 struct strbuf err = STRBUF_INIT;
1548 struct strbuf commit_msg = STRBUF_INIT;
1549 char *amend_author = NULL;
1550 const char *committer = NULL;
1551 const char *hook_commit = NULL;
1552 enum commit_msg_cleanup_mode cleanup;
1553 int res = 0;
1555 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1556 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1558 if (parse_head(r, &current_head))
1559 return -1;
1561 if (flags & AMEND_MSG) {
1562 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1563 const char *out_enc = get_commit_output_encoding();
1564 const char *message = repo_logmsg_reencode(r, current_head,
1565 NULL, out_enc);
1567 if (!msg) {
1568 const char *orig_message = NULL;
1570 find_commit_subject(message, &orig_message);
1571 msg = &commit_msg;
1572 strbuf_addstr(msg, orig_message);
1573 hook_commit = "HEAD";
1575 author = amend_author = get_author(message);
1576 repo_unuse_commit_buffer(r, current_head,
1577 message);
1578 if (!author) {
1579 res = error(_("unable to parse commit author"));
1580 goto out;
1582 parents = copy_commit_list(current_head->parents);
1583 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1584 } else if (current_head &&
1585 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1586 commit_list_insert(current_head, &parents);
1589 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1590 res = error(_("git write-tree failed to write a tree"));
1591 goto out;
1594 if (!(flags & ALLOW_EMPTY)) {
1595 struct commit *first_parent = current_head;
1597 if (flags & AMEND_MSG) {
1598 if (current_head->parents) {
1599 first_parent = current_head->parents->item;
1600 if (repo_parse_commit(r, first_parent)) {
1601 res = error(_("could not parse HEAD commit"));
1602 goto out;
1604 } else {
1605 first_parent = NULL;
1608 if (oideq(first_parent
1609 ? get_commit_tree_oid(first_parent)
1610 : the_hash_algo->empty_tree,
1611 &tree)) {
1612 res = 1; /* run 'git commit' to display error message */
1613 goto out;
1617 if (hook_exists("prepare-commit-msg")) {
1618 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1619 if (res)
1620 goto out;
1621 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1622 2048) < 0) {
1623 res = error_errno(_("unable to read commit message "
1624 "from '%s'"),
1625 git_path_commit_editmsg());
1626 goto out;
1628 msg = &commit_msg;
1631 if (flags & CLEANUP_MSG)
1632 cleanup = COMMIT_MSG_CLEANUP_ALL;
1633 else if (flags & VERBATIM_MSG)
1634 cleanup = COMMIT_MSG_CLEANUP_NONE;
1635 else if ((opts->signoff || opts->record_origin) &&
1636 !opts->explicit_cleanup)
1637 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1638 else
1639 cleanup = opts->default_msg_cleanup;
1641 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1642 strbuf_stripspace(msg,
1643 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1644 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1645 res = 1; /* run 'git commit' to display error message */
1646 goto out;
1649 if (opts->committer_date_is_author_date) {
1650 struct ident_split id;
1651 struct strbuf date = STRBUF_INIT;
1653 if (!opts->ignore_date) {
1654 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1655 res = error(_("invalid author identity '%s'"),
1656 author);
1657 goto out;
1659 if (!id.date_begin) {
1660 res = error(_(
1661 "corrupt author: missing date information"));
1662 goto out;
1664 strbuf_addf(&date, "@%.*s %.*s",
1665 (int)(id.date_end - id.date_begin),
1666 id.date_begin,
1667 (int)(id.tz_end - id.tz_begin),
1668 id.tz_begin);
1669 } else {
1670 reset_ident_date();
1672 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1673 getenv("GIT_COMMITTER_EMAIL"),
1674 WANT_COMMITTER_IDENT,
1675 opts->ignore_date ? NULL : date.buf,
1676 IDENT_STRICT);
1677 strbuf_release(&date);
1678 } else {
1679 reset_ident_date();
1682 if (opts->ignore_date) {
1683 struct ident_split id;
1684 char *name, *email;
1686 if (split_ident_line(&id, author, strlen(author)) < 0) {
1687 error(_("invalid author identity '%s'"), author);
1688 goto out;
1690 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1691 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1692 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1693 IDENT_STRICT);
1694 free(name);
1695 free(email);
1698 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1699 author, committer, opts->gpg_sign, extra)) {
1700 res = error(_("failed to write commit object"));
1701 goto out;
1704 if (update_head_with_reflog(current_head, oid, ctx->reflog_message,
1705 msg, &err)) {
1706 res = error("%s", err.buf);
1707 goto out;
1710 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1711 if (flags & AMEND_MSG)
1712 commit_post_rewrite(r, current_head, oid);
1714 out:
1715 free_commit_extra_headers(extra);
1716 free_commit_list(parents);
1717 strbuf_release(&err);
1718 strbuf_release(&commit_msg);
1719 free(amend_author);
1721 return res;
1724 static int write_rebase_head(struct object_id *oid)
1726 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1727 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1728 return error(_("could not update %s"), "REBASE_HEAD");
1730 return 0;
1733 static int do_commit(struct repository *r,
1734 const char *msg_file, const char *author,
1735 struct replay_opts *opts, unsigned int flags,
1736 struct object_id *oid)
1738 int res = 1;
1740 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1741 struct object_id oid;
1742 struct strbuf sb = STRBUF_INIT;
1744 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1745 return error_errno(_("unable to read commit message "
1746 "from '%s'"),
1747 msg_file);
1749 res = try_to_commit(r, msg_file ? &sb : NULL,
1750 author, opts, flags, &oid);
1751 strbuf_release(&sb);
1752 if (!res) {
1753 refs_delete_ref(get_main_ref_store(r), "",
1754 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1755 unlink(git_path_merge_msg(r));
1756 if (!is_rebase_i(opts))
1757 print_commit_summary(r, NULL, &oid,
1758 SUMMARY_SHOW_AUTHOR_DATE);
1759 return res;
1762 if (res == 1) {
1763 if (is_rebase_i(opts) && oid)
1764 if (write_rebase_head(oid))
1765 return -1;
1766 return run_git_commit(msg_file, opts, flags);
1769 return res;
1772 static int is_original_commit_empty(struct commit *commit)
1774 const struct object_id *ptree_oid;
1776 if (repo_parse_commit(the_repository, commit))
1777 return error(_("could not parse commit %s"),
1778 oid_to_hex(&commit->object.oid));
1779 if (commit->parents) {
1780 struct commit *parent = commit->parents->item;
1781 if (repo_parse_commit(the_repository, parent))
1782 return error(_("could not parse parent commit %s"),
1783 oid_to_hex(&parent->object.oid));
1784 ptree_oid = get_commit_tree_oid(parent);
1785 } else {
1786 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1789 return oideq(ptree_oid, get_commit_tree_oid(commit));
1793 * Should empty commits be allowed? Return status:
1794 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1795 * 0: Halt on empty commit
1796 * 1: Allow empty commit
1797 * 2: Drop empty commit
1799 static int allow_empty(struct repository *r,
1800 struct replay_opts *opts,
1801 struct commit *commit)
1803 int index_unchanged, originally_empty;
1806 * For a commit that is initially empty, allow_empty determines if it
1807 * should be kept or not
1809 * For a commit that becomes empty, keep_redundant_commits and
1810 * drop_redundant_commits determine whether the commit should be kept or
1811 * dropped. If neither is specified, halt.
1813 index_unchanged = is_index_unchanged(r);
1814 if (index_unchanged < 0)
1815 return index_unchanged;
1816 if (!index_unchanged)
1817 return 0; /* we do not have to say --allow-empty */
1819 originally_empty = is_original_commit_empty(commit);
1820 if (originally_empty < 0)
1821 return originally_empty;
1822 if (originally_empty)
1823 return opts->allow_empty;
1824 else if (opts->keep_redundant_commits)
1825 return 1;
1826 else if (opts->drop_redundant_commits)
1827 return 2;
1828 else
1829 return 0;
1832 static struct {
1833 char c;
1834 const char *str;
1835 } todo_command_info[] = {
1836 [TODO_PICK] = { 'p', "pick" },
1837 [TODO_REVERT] = { 0, "revert" },
1838 [TODO_EDIT] = { 'e', "edit" },
1839 [TODO_REWORD] = { 'r', "reword" },
1840 [TODO_FIXUP] = { 'f', "fixup" },
1841 [TODO_SQUASH] = { 's', "squash" },
1842 [TODO_EXEC] = { 'x', "exec" },
1843 [TODO_BREAK] = { 'b', "break" },
1844 [TODO_LABEL] = { 'l', "label" },
1845 [TODO_RESET] = { 't', "reset" },
1846 [TODO_MERGE] = { 'm', "merge" },
1847 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1848 [TODO_NOOP] = { 0, "noop" },
1849 [TODO_DROP] = { 'd', "drop" },
1850 [TODO_COMMENT] = { 0, NULL },
1853 static const char *command_to_string(const enum todo_command command)
1855 if (command < TODO_COMMENT)
1856 return todo_command_info[command].str;
1857 if (command == TODO_COMMENT)
1858 return comment_line_str;
1859 die(_("unknown command: %d"), command);
1862 static char command_to_char(const enum todo_command command)
1864 if (command < TODO_COMMENT)
1865 return todo_command_info[command].c;
1866 return 0;
1869 static int is_noop(const enum todo_command command)
1871 return TODO_NOOP <= command;
1874 static int is_fixup(enum todo_command command)
1876 return command == TODO_FIXUP || command == TODO_SQUASH;
1879 /* Does this command create a (non-merge) commit? */
1880 static int is_pick_or_similar(enum todo_command command)
1882 switch (command) {
1883 case TODO_PICK:
1884 case TODO_REVERT:
1885 case TODO_EDIT:
1886 case TODO_REWORD:
1887 case TODO_FIXUP:
1888 case TODO_SQUASH:
1889 return 1;
1890 default:
1891 return 0;
1895 enum todo_item_flags {
1896 TODO_EDIT_MERGE_MSG = (1 << 0),
1897 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1898 TODO_EDIT_FIXUP_MSG = (1 << 2),
1901 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1902 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1903 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1904 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1905 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1907 static int is_fixup_flag(enum todo_command command, unsigned flag)
1909 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1910 (flag & TODO_EDIT_FIXUP_MSG));
1914 * Wrapper around strbuf_add_commented_lines() which avoids double
1915 * commenting commit subjects.
1917 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1919 const char *s = str;
1920 while (starts_with_mem(s, len, comment_line_str)) {
1921 size_t count;
1922 const char *n = memchr(s, '\n', len);
1923 if (!n)
1924 count = len;
1925 else
1926 count = n - s + 1;
1927 strbuf_add(buf, s, count);
1928 s += count;
1929 len -= count;
1931 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1934 /* Does the current fixup chain contain a squash command? */
1935 static int seen_squash(struct replay_ctx *ctx)
1937 return starts_with(ctx->current_fixups.buf, "squash") ||
1938 strstr(ctx->current_fixups.buf, "\nsquash");
1941 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1943 strbuf_setlen(buf1, 2);
1944 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1945 strbuf_addch(buf1, '\n');
1946 strbuf_setlen(buf2, 2);
1947 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1948 strbuf_addch(buf2, '\n');
1952 * Comment out any un-commented commit messages, updating the message comments
1953 * to say they will be skipped but do not comment out the empty lines that
1954 * surround commit messages and their comments.
1956 static void update_squash_message_for_fixup(struct strbuf *msg)
1958 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1959 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1960 const char *s, *start;
1961 char *orig_msg;
1962 size_t orig_msg_len;
1963 int i = 1;
1965 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1966 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1967 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1968 while (s) {
1969 const char *next;
1970 size_t off;
1971 if (skip_prefix(s, buf1.buf, &next)) {
1973 * Copy the last message, preserving the blank line
1974 * preceding the current line
1976 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1977 copy_lines(msg, start, s - start - off);
1978 if (off)
1979 strbuf_addch(msg, '\n');
1981 * The next message needs to be commented out but the
1982 * message header is already commented out so just copy
1983 * it and the blank line that follows it.
1985 strbuf_addbuf(msg, &buf2);
1986 if (*next == '\n')
1987 strbuf_addch(msg, *next++);
1988 start = s = next;
1989 copy_lines = add_commented_lines;
1990 update_comment_bufs(&buf1, &buf2, ++i);
1991 } else if (skip_prefix(s, buf2.buf, &next)) {
1992 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1993 copy_lines(msg, start, s - start - off);
1994 start = s - off;
1995 s = next;
1996 copy_lines = strbuf_add;
1997 update_comment_bufs(&buf1, &buf2, ++i);
1998 } else {
1999 s = strchr(s, '\n');
2000 if (s)
2001 s++;
2004 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2005 free(orig_msg);
2006 strbuf_release(&buf1);
2007 strbuf_release(&buf2);
2010 static int append_squash_message(struct strbuf *buf, const char *body,
2011 enum todo_command command, struct replay_opts *opts,
2012 unsigned flag)
2014 struct replay_ctx *ctx = opts->ctx;
2015 const char *fixup_msg;
2016 size_t commented_len = 0, fixup_off;
2018 * amend is non-interactive and not normally used with fixup!
2019 * or squash! commits, so only comment out those subjects when
2020 * squashing commit messages.
2022 if (starts_with(body, "amend!") ||
2023 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2024 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2025 commented_len = commit_subject_length(body);
2027 strbuf_addf(buf, "\n%s ", comment_line_str);
2028 strbuf_addf(buf, _(nth_commit_msg_fmt),
2029 ++ctx->current_fixup_count + 1);
2030 strbuf_addstr(buf, "\n\n");
2031 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2032 /* buf->buf may be reallocated so store an offset into the buffer */
2033 fixup_off = buf->len;
2034 strbuf_addstr(buf, body + commented_len);
2036 /* fixup -C after squash behaves like squash */
2037 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2039 * We're replacing the commit message so we need to
2040 * append the Signed-off-by: trailer if the user
2041 * requested '--signoff'.
2043 if (opts->signoff)
2044 append_signoff(buf, 0, 0);
2046 if ((command == TODO_FIXUP) &&
2047 (flag & TODO_REPLACE_FIXUP_MSG) &&
2048 (file_exists(rebase_path_fixup_msg()) ||
2049 !file_exists(rebase_path_squash_msg()))) {
2050 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2051 if (write_message(fixup_msg, strlen(fixup_msg),
2052 rebase_path_fixup_msg(), 0) < 0)
2053 return error(_("cannot write '%s'"),
2054 rebase_path_fixup_msg());
2055 } else {
2056 unlink(rebase_path_fixup_msg());
2058 } else {
2059 unlink(rebase_path_fixup_msg());
2062 return 0;
2065 static int update_squash_messages(struct repository *r,
2066 enum todo_command command,
2067 struct commit *commit,
2068 struct replay_opts *opts,
2069 unsigned flag)
2071 struct replay_ctx *ctx = opts->ctx;
2072 struct strbuf buf = STRBUF_INIT;
2073 int res = 0;
2074 const char *message, *body;
2075 const char *encoding = get_commit_output_encoding();
2077 if (ctx->current_fixup_count > 0) {
2078 struct strbuf header = STRBUF_INIT;
2079 char *eol;
2081 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2082 return error(_("could not read '%s'"),
2083 rebase_path_squash_msg());
2085 eol = !starts_with(buf.buf, comment_line_str) ?
2086 buf.buf : strchrnul(buf.buf, '\n');
2088 strbuf_addf(&header, "%s ", comment_line_str);
2089 strbuf_addf(&header, _(combined_commit_msg_fmt),
2090 ctx->current_fixup_count + 2);
2091 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2092 strbuf_release(&header);
2093 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2094 update_squash_message_for_fixup(&buf);
2095 } else {
2096 struct object_id head;
2097 struct commit *head_commit;
2098 const char *head_message, *body;
2100 if (repo_get_oid(r, "HEAD", &head))
2101 return error(_("need a HEAD to fixup"));
2102 if (!(head_commit = lookup_commit_reference(r, &head)))
2103 return error(_("could not read HEAD"));
2104 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2105 encoding)))
2106 return error(_("could not read HEAD's commit message"));
2108 find_commit_subject(head_message, &body);
2109 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2110 rebase_path_fixup_msg(), 0) < 0) {
2111 repo_unuse_commit_buffer(r, head_commit, head_message);
2112 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2114 strbuf_addf(&buf, "%s ", comment_line_str);
2115 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2116 strbuf_addf(&buf, "\n%s ", comment_line_str);
2117 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2118 _(skip_first_commit_msg_str) :
2119 _(first_commit_msg_str));
2120 strbuf_addstr(&buf, "\n\n");
2121 if (is_fixup_flag(command, flag))
2122 strbuf_add_commented_lines(&buf, body, strlen(body),
2123 comment_line_str);
2124 else
2125 strbuf_addstr(&buf, body);
2127 repo_unuse_commit_buffer(r, head_commit, head_message);
2130 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2131 return error(_("could not read commit message of %s"),
2132 oid_to_hex(&commit->object.oid));
2133 find_commit_subject(message, &body);
2135 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2136 res = append_squash_message(&buf, body, command, opts, flag);
2137 } else if (command == TODO_FIXUP) {
2138 strbuf_addf(&buf, "\n%s ", comment_line_str);
2139 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2140 ++ctx->current_fixup_count + 1);
2141 strbuf_addstr(&buf, "\n\n");
2142 strbuf_add_commented_lines(&buf, body, strlen(body),
2143 comment_line_str);
2144 } else
2145 return error(_("unknown command: %d"), command);
2146 repo_unuse_commit_buffer(r, commit, message);
2148 if (!res)
2149 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2151 strbuf_release(&buf);
2153 if (!res) {
2154 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2155 ctx->current_fixups.len ? "\n" : "",
2156 command_to_string(command),
2157 oid_to_hex(&commit->object.oid));
2158 res = write_message(ctx->current_fixups.buf,
2159 ctx->current_fixups.len,
2160 rebase_path_current_fixups(), 0);
2163 return res;
2166 static void flush_rewritten_pending(void)
2168 struct strbuf buf = STRBUF_INIT;
2169 struct object_id newoid;
2170 FILE *out;
2172 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2173 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2174 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2175 char *bol = buf.buf, *eol;
2177 while (*bol) {
2178 eol = strchrnul(bol, '\n');
2179 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2180 bol, oid_to_hex(&newoid));
2181 if (!*eol)
2182 break;
2183 bol = eol + 1;
2185 fclose(out);
2186 unlink(rebase_path_rewritten_pending());
2188 strbuf_release(&buf);
2191 static void record_in_rewritten(struct object_id *oid,
2192 enum todo_command next_command)
2194 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2196 if (!out)
2197 return;
2199 fprintf(out, "%s\n", oid_to_hex(oid));
2200 fclose(out);
2202 if (!is_fixup(next_command))
2203 flush_rewritten_pending();
2206 static int should_edit(struct replay_opts *opts) {
2207 if (opts->edit < 0)
2209 * Note that we only handle the case of non-conflicted
2210 * commits; continue_single_pick() handles the conflicted
2211 * commits itself instead of calling this function.
2213 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2214 return opts->edit;
2217 static void refer_to_commit(struct replay_opts *opts,
2218 struct strbuf *msgbuf, struct commit *commit)
2220 if (opts->commit_use_reference) {
2221 struct pretty_print_context ctx = {
2222 .abbrev = DEFAULT_ABBREV,
2223 .date_mode.type = DATE_SHORT,
2225 repo_format_commit_message(the_repository, commit,
2226 "%h (%s, %ad)", msgbuf, &ctx);
2227 } else {
2228 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2232 static int do_pick_commit(struct repository *r,
2233 struct todo_item *item,
2234 struct replay_opts *opts,
2235 int final_fixup, int *check_todo)
2237 struct replay_ctx *ctx = opts->ctx;
2238 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2239 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2240 struct object_id head;
2241 struct commit *base, *next, *parent;
2242 const char *base_label, *next_label;
2243 char *author = NULL;
2244 struct commit_message msg = { NULL, NULL, NULL, NULL };
2245 int res, unborn = 0, reword = 0, allow, drop_commit;
2246 enum todo_command command = item->command;
2247 struct commit *commit = item->commit;
2249 if (opts->no_commit) {
2251 * We do not intend to commit immediately. We just want to
2252 * merge the differences in, so let's compute the tree
2253 * that represents the "current" state for the merge machinery
2254 * to work on.
2256 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2257 return error(_("your index file is unmerged."));
2258 } else {
2259 unborn = repo_get_oid(r, "HEAD", &head);
2260 /* Do we want to generate a root commit? */
2261 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2262 oideq(&head, &opts->squash_onto)) {
2263 if (is_fixup(command))
2264 return error(_("cannot fixup root commit"));
2265 flags |= CREATE_ROOT_COMMIT;
2266 unborn = 1;
2267 } else if (unborn)
2268 oidcpy(&head, the_hash_algo->empty_tree);
2269 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD",
2270 NULL, 0))
2271 return error_dirty_index(r, opts);
2273 discard_index(r->index);
2275 if (!commit->parents)
2276 parent = NULL;
2277 else if (commit->parents->next) {
2278 /* Reverting or cherry-picking a merge commit */
2279 int cnt;
2280 struct commit_list *p;
2282 if (!opts->mainline)
2283 return error(_("commit %s is a merge but no -m option was given."),
2284 oid_to_hex(&commit->object.oid));
2286 for (cnt = 1, p = commit->parents;
2287 cnt != opts->mainline && p;
2288 cnt++)
2289 p = p->next;
2290 if (cnt != opts->mainline || !p)
2291 return error(_("commit %s does not have parent %d"),
2292 oid_to_hex(&commit->object.oid), opts->mainline);
2293 parent = p->item;
2294 } else if (1 < opts->mainline)
2296 * Non-first parent explicitly specified as mainline for
2297 * non-merge commit
2299 return error(_("commit %s does not have parent %d"),
2300 oid_to_hex(&commit->object.oid), opts->mainline);
2301 else
2302 parent = commit->parents->item;
2304 if (get_message(commit, &msg) != 0)
2305 return error(_("cannot get commit message for %s"),
2306 oid_to_hex(&commit->object.oid));
2308 if (opts->allow_ff && !is_fixup(command) &&
2309 ((parent && oideq(&parent->object.oid, &head)) ||
2310 (!parent && unborn))) {
2311 if (is_rebase_i(opts))
2312 write_author_script(msg.message);
2313 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2314 opts);
2315 if (res || command != TODO_REWORD)
2316 goto leave;
2317 reword = 1;
2318 msg_file = NULL;
2319 goto fast_forward_edit;
2321 if (parent && repo_parse_commit(r, parent) < 0)
2322 /* TRANSLATORS: The first %s will be a "todo" command like
2323 "revert" or "pick", the second %s a SHA1. */
2324 return error(_("%s: cannot parse parent commit %s"),
2325 command_to_string(command),
2326 oid_to_hex(&parent->object.oid));
2329 * "commit" is an existing commit. We would want to apply
2330 * the difference it introduces since its first parent "prev"
2331 * on top of the current HEAD if we are cherry-pick. Or the
2332 * reverse of it if we are revert.
2335 if (command == TODO_REVERT) {
2336 const char *orig_subject;
2338 base = commit;
2339 base_label = msg.label;
2340 next = parent;
2341 next_label = msg.parent_label;
2342 if (opts->commit_use_reference) {
2343 strbuf_addstr(&ctx->message,
2344 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2345 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2347 * We don't touch pre-existing repeated reverts, because
2348 * theoretically these can be nested arbitrarily deeply,
2349 * thus requiring excessive complexity to deal with.
2351 !starts_with(orig_subject, "Revert \"")) {
2352 strbuf_addstr(&ctx->message, "Reapply \"");
2353 strbuf_addstr(&ctx->message, orig_subject);
2354 } else {
2355 strbuf_addstr(&ctx->message, "Revert \"");
2356 strbuf_addstr(&ctx->message, msg.subject);
2357 strbuf_addstr(&ctx->message, "\"");
2359 strbuf_addstr(&ctx->message, "\n\nThis reverts commit ");
2360 refer_to_commit(opts, &ctx->message, commit);
2362 if (commit->parents && commit->parents->next) {
2363 strbuf_addstr(&ctx->message, ", reversing\nchanges made to ");
2364 refer_to_commit(opts, &ctx->message, parent);
2366 strbuf_addstr(&ctx->message, ".\n");
2367 } else {
2368 const char *p;
2370 base = parent;
2371 base_label = msg.parent_label;
2372 next = commit;
2373 next_label = msg.label;
2375 /* Append the commit log message to ctx->message. */
2376 if (find_commit_subject(msg.message, &p))
2377 strbuf_addstr(&ctx->message, p);
2379 if (opts->record_origin) {
2380 strbuf_complete_line(&ctx->message);
2381 if (!has_conforming_footer(&ctx->message, NULL, 0))
2382 strbuf_addch(&ctx->message, '\n');
2383 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2384 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid));
2385 strbuf_addstr(&ctx->message, ")\n");
2387 if (!is_fixup(command))
2388 author = get_author(msg.message);
2390 ctx->have_message = 1;
2392 if (command == TODO_REWORD)
2393 reword = 1;
2394 else if (is_fixup(command)) {
2395 if (update_squash_messages(r, command, commit,
2396 opts, item->flags)) {
2397 res = -1;
2398 goto leave;
2400 flags |= AMEND_MSG;
2401 if (!final_fixup)
2402 msg_file = rebase_path_squash_msg();
2403 else if (file_exists(rebase_path_fixup_msg())) {
2404 flags |= VERBATIM_MSG;
2405 msg_file = rebase_path_fixup_msg();
2406 } else {
2407 const char *dest = git_path_squash_msg(r);
2408 unlink(dest);
2409 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2410 res = error(_("could not copy '%s' to '%s'"),
2411 rebase_path_squash_msg(), dest);
2412 goto leave;
2414 unlink(git_path_merge_msg(r));
2415 msg_file = dest;
2416 flags |= EDIT_MSG;
2420 if (opts->signoff && !is_fixup(command))
2421 append_signoff(&ctx->message, 0, 0);
2423 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2424 res = -1;
2425 else if (!opts->strategy ||
2426 !strcmp(opts->strategy, "recursive") ||
2427 !strcmp(opts->strategy, "ort") ||
2428 command == TODO_REVERT) {
2429 res = do_recursive_merge(r, base, next, base_label, next_label,
2430 &head, &ctx->message, opts);
2431 if (res < 0)
2432 goto leave;
2434 res |= write_message(ctx->message.buf, ctx->message.len,
2435 git_path_merge_msg(r), 0);
2436 } else {
2437 struct commit_list *common = NULL;
2438 struct commit_list *remotes = NULL;
2440 res = write_message(ctx->message.buf, ctx->message.len,
2441 git_path_merge_msg(r), 0);
2443 commit_list_insert(base, &common);
2444 commit_list_insert(next, &remotes);
2445 res |= try_merge_command(r, opts->strategy,
2446 opts->xopts.nr, opts->xopts.v,
2447 common, oid_to_hex(&head), remotes);
2448 free_commit_list(common);
2449 free_commit_list(remotes);
2453 * If the merge was clean or if it failed due to conflict, we write
2454 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2455 * However, if the merge did not even start, then we don't want to
2456 * write it at all.
2458 if ((command == TODO_PICK || command == TODO_REWORD ||
2459 command == TODO_EDIT) && !opts->no_commit &&
2460 (res == 0 || res == 1) &&
2461 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2462 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2463 res = -1;
2464 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2465 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2466 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2467 res = -1;
2469 if (res) {
2470 error(command == TODO_REVERT
2471 ? _("could not revert %s... %s")
2472 : _("could not apply %s... %s"),
2473 short_commit_name(r, commit), msg.subject);
2474 print_advice(r, res == 1, opts);
2475 repo_rerere(r, opts->allow_rerere_auto);
2476 goto leave;
2479 drop_commit = 0;
2480 allow = allow_empty(r, opts, commit);
2481 if (allow < 0) {
2482 res = allow;
2483 goto leave;
2484 } else if (allow == 1) {
2485 flags |= ALLOW_EMPTY;
2486 } else if (allow == 2) {
2487 drop_commit = 1;
2488 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2489 NULL, REF_NO_DEREF);
2490 unlink(git_path_merge_msg(r));
2491 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2492 NULL, REF_NO_DEREF);
2493 fprintf(stderr,
2494 _("dropping %s %s -- patch contents already upstream\n"),
2495 oid_to_hex(&commit->object.oid), msg.subject);
2496 } /* else allow == 0 and there's nothing special to do */
2497 if (!opts->no_commit && !drop_commit) {
2498 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2499 res = do_commit(r, msg_file, author, opts, flags,
2500 commit? &commit->object.oid : NULL);
2501 else
2502 res = error(_("unable to parse commit author"));
2503 *check_todo = !!(flags & EDIT_MSG);
2504 if (!res && reword) {
2505 fast_forward_edit:
2506 res = run_git_commit(NULL, opts, EDIT_MSG |
2507 VERIFY_MSG | AMEND_MSG |
2508 (flags & ALLOW_EMPTY));
2509 *check_todo = 1;
2514 if (!res && final_fixup) {
2515 unlink(rebase_path_fixup_msg());
2516 unlink(rebase_path_squash_msg());
2517 unlink(rebase_path_current_fixups());
2518 strbuf_reset(&ctx->current_fixups);
2519 ctx->current_fixup_count = 0;
2522 leave:
2523 free_message(commit, &msg);
2524 free(author);
2525 update_abort_safety_file();
2527 return res;
2530 static int prepare_revs(struct replay_opts *opts)
2533 * picking (but not reverting) ranges (but not individual revisions)
2534 * should be done in reverse
2536 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2537 opts->revs->reverse ^= 1;
2539 if (prepare_revision_walk(opts->revs))
2540 return error(_("revision walk setup failed"));
2542 return 0;
2545 static int read_and_refresh_cache(struct repository *r,
2546 struct replay_opts *opts)
2548 struct lock_file index_lock = LOCK_INIT;
2549 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2550 if (repo_read_index(r) < 0) {
2551 rollback_lock_file(&index_lock);
2552 return error(_("git %s: failed to read the index"),
2553 action_name(opts));
2555 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2557 if (index_fd >= 0) {
2558 if (write_locked_index(r->index, &index_lock,
2559 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2560 return error(_("git %s: failed to refresh the index"),
2561 action_name(opts));
2566 * If we are resolving merges in any way other than "ort", then
2567 * expand the sparse index.
2569 if (opts->strategy && strcmp(opts->strategy, "ort"))
2570 ensure_full_index(r->index);
2571 return 0;
2574 void todo_list_release(struct todo_list *todo_list)
2576 strbuf_release(&todo_list->buf);
2577 FREE_AND_NULL(todo_list->items);
2578 todo_list->nr = todo_list->alloc = 0;
2581 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2583 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2584 return todo_list->items + todo_list->nr++;
2587 const char *todo_item_get_arg(struct todo_list *todo_list,
2588 struct todo_item *item)
2590 return todo_list->buf.buf + item->arg_offset;
2593 static int is_command(enum todo_command command, const char **bol)
2595 const char *str = todo_command_info[command].str;
2596 const char nick = todo_command_info[command].c;
2597 const char *p = *bol;
2599 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2600 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2601 (*bol = p);
2604 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2606 switch (command) {
2607 case TODO_LABEL:
2609 * '#' is not a valid label as the merge command uses it to
2610 * separate merge parents from the commit subject.
2612 if (!strcmp(arg, "#") ||
2613 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2614 return error(_("'%s' is not a valid label"), arg);
2615 break;
2617 case TODO_UPDATE_REF:
2618 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2619 return error(_("'%s' is not a valid refname"), arg);
2620 if (check_refname_format(arg, 0))
2621 return error(_("update-ref requires a fully qualified "
2622 "refname e.g. refs/heads/%s"), arg);
2623 break;
2625 default:
2626 BUG("unexpected todo_command");
2629 return 0;
2632 static int check_merge_commit_insn(enum todo_command command)
2634 switch(command) {
2635 case TODO_PICK:
2636 error(_("'%s' does not accept merge commits"),
2637 todo_command_info[command].str);
2638 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2640 * TRANSLATORS: 'pick' and 'merge -C' should not be
2641 * translated.
2643 "'pick' does not take a merge commit. If you wanted to\n"
2644 "replay the merge, use 'merge -C' on the commit."));
2645 return -1;
2647 case TODO_REWORD:
2648 error(_("'%s' does not accept merge commits"),
2649 todo_command_info[command].str);
2650 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2652 * TRANSLATORS: 'reword' and 'merge -c' should not be
2653 * translated.
2655 "'reword' does not take a merge commit. If you wanted to\n"
2656 "replay the merge and reword the commit message, use\n"
2657 "'merge -c' on the commit"));
2658 return -1;
2660 case TODO_EDIT:
2661 error(_("'%s' does not accept merge commits"),
2662 todo_command_info[command].str);
2663 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2665 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2666 * not be translated.
2668 "'edit' does not take a merge commit. If you wanted to\n"
2669 "replay the merge, use 'merge -C' on the commit, and then\n"
2670 "'break' to give the control back to you so that you can\n"
2671 "do 'git commit --amend && git rebase --continue'."));
2672 return -1;
2674 case TODO_FIXUP:
2675 case TODO_SQUASH:
2676 return error(_("cannot squash merge commit into another commit"));
2678 case TODO_MERGE:
2679 return 0;
2681 default:
2682 BUG("unexpected todo_command");
2686 static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2687 struct todo_item *item, const char *buf,
2688 const char *bol, char *eol)
2690 struct object_id commit_oid;
2691 char *end_of_object_name;
2692 int i, saved, status, padding;
2694 item->flags = 0;
2696 /* left-trim */
2697 bol += strspn(bol, " \t");
2699 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
2700 item->command = TODO_COMMENT;
2701 item->commit = NULL;
2702 item->arg_offset = bol - buf;
2703 item->arg_len = eol - bol;
2704 return 0;
2707 for (i = 0; i < TODO_COMMENT; i++)
2708 if (is_command(i, &bol)) {
2709 item->command = i;
2710 break;
2712 if (i >= TODO_COMMENT)
2713 return error(_("invalid command '%.*s'"),
2714 (int)strcspn(bol, " \t\r\n"), bol);
2716 /* Eat up extra spaces/ tabs before object name */
2717 padding = strspn(bol, " \t");
2718 bol += padding;
2720 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2721 if (bol != eol)
2722 return error(_("%s does not accept arguments: '%s'"),
2723 command_to_string(item->command), bol);
2724 item->commit = NULL;
2725 item->arg_offset = bol - buf;
2726 item->arg_len = eol - bol;
2727 return 0;
2730 if (!padding)
2731 return error(_("missing arguments for %s"),
2732 command_to_string(item->command));
2734 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2735 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2736 int ret = 0;
2738 item->commit = NULL;
2739 item->arg_offset = bol - buf;
2740 item->arg_len = (int)(eol - bol);
2741 if (item->command == TODO_LABEL ||
2742 item->command == TODO_UPDATE_REF) {
2743 saved = *eol;
2744 *eol = '\0';
2745 ret = check_label_or_ref_arg(item->command, bol);
2746 *eol = saved;
2748 return ret;
2751 if (item->command == TODO_FIXUP) {
2752 if (skip_prefix(bol, "-C", &bol)) {
2753 bol += strspn(bol, " \t");
2754 item->flags |= TODO_REPLACE_FIXUP_MSG;
2755 } else if (skip_prefix(bol, "-c", &bol)) {
2756 bol += strspn(bol, " \t");
2757 item->flags |= TODO_EDIT_FIXUP_MSG;
2761 if (item->command == TODO_MERGE) {
2762 if (skip_prefix(bol, "-C", &bol))
2763 bol += strspn(bol, " \t");
2764 else if (skip_prefix(bol, "-c", &bol)) {
2765 bol += strspn(bol, " \t");
2766 item->flags |= TODO_EDIT_MERGE_MSG;
2767 } else {
2768 item->flags |= TODO_EDIT_MERGE_MSG;
2769 item->commit = NULL;
2770 item->arg_offset = bol - buf;
2771 item->arg_len = (int)(eol - bol);
2772 return 0;
2776 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2777 saved = *end_of_object_name;
2778 *end_of_object_name = '\0';
2779 status = repo_get_oid(r, bol, &commit_oid);
2780 if (status < 0)
2781 error(_("could not parse '%s'"), bol); /* return later */
2782 *end_of_object_name = saved;
2784 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2785 item->arg_offset = bol - buf;
2786 item->arg_len = (int)(eol - bol);
2788 if (status < 0)
2789 return status;
2791 item->commit = lookup_commit_reference(r, &commit_oid);
2792 if (!item->commit)
2793 return -1;
2794 if (is_rebase_i(opts) &&
2795 item->commit->parents && item->commit->parents->next)
2796 return check_merge_commit_insn(item->command);
2797 return 0;
2800 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2802 const char *todo_file, *bol;
2803 struct strbuf buf = STRBUF_INIT;
2804 int ret = 0;
2806 todo_file = git_path_todo_file();
2807 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2808 if (errno == ENOENT || errno == ENOTDIR)
2809 return -1;
2810 else
2811 return error_errno("unable to open '%s'", todo_file);
2813 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2814 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2815 *action = REPLAY_PICK;
2816 else if (is_command(TODO_REVERT, &bol) &&
2817 (*bol == ' ' || *bol == '\t'))
2818 *action = REPLAY_REVERT;
2819 else
2820 ret = -1;
2822 strbuf_release(&buf);
2824 return ret;
2827 int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2828 char *buf, struct todo_list *todo_list)
2830 struct todo_item *item;
2831 char *p = buf, *next_p;
2832 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2834 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2836 for (i = 1; *p; i++, p = next_p) {
2837 char *eol = strchrnul(p, '\n');
2839 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2841 if (p != eol && eol[-1] == '\r')
2842 eol--; /* strip Carriage Return */
2844 item = append_new_todo(todo_list);
2845 item->offset_in_buf = p - todo_list->buf.buf;
2846 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2847 res = error(_("invalid line %d: %.*s"),
2848 i, (int)(eol - p), p);
2849 item->command = TODO_COMMENT + 1;
2850 item->arg_offset = p - buf;
2851 item->arg_len = (int)(eol - p);
2852 item->commit = NULL;
2855 if (item->command != TODO_COMMENT)
2856 todo_list->total_nr++;
2858 if (fixup_okay)
2859 ; /* do nothing */
2860 else if (is_fixup(item->command))
2861 res = error(_("cannot '%s' without a previous commit"),
2862 command_to_string(item->command));
2863 else if (!is_noop(item->command))
2864 fixup_okay = 1;
2867 return res;
2870 static int count_commands(struct todo_list *todo_list)
2872 int count = 0, i;
2874 for (i = 0; i < todo_list->nr; i++)
2875 if (todo_list->items[i].command != TODO_COMMENT)
2876 count++;
2878 return count;
2881 static int get_item_line_offset(struct todo_list *todo_list, int index)
2883 return index < todo_list->nr ?
2884 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2887 static const char *get_item_line(struct todo_list *todo_list, int index)
2889 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2892 static int get_item_line_length(struct todo_list *todo_list, int index)
2894 return get_item_line_offset(todo_list, index + 1)
2895 - get_item_line_offset(todo_list, index);
2898 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2900 int fd;
2901 ssize_t len;
2903 fd = open(path, O_RDONLY);
2904 if (fd < 0)
2905 return error_errno(_("could not open '%s'"), path);
2906 len = strbuf_read(sb, fd, 0);
2907 close(fd);
2908 if (len < 0)
2909 return error(_("could not read '%s'."), path);
2910 return len;
2913 static int have_finished_the_last_pick(void)
2915 struct strbuf buf = STRBUF_INIT;
2916 const char *eol;
2917 const char *todo_path = git_path_todo_file();
2918 int ret = 0;
2920 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2921 if (errno == ENOENT) {
2922 return 0;
2923 } else {
2924 error_errno("unable to open '%s'", todo_path);
2925 return 0;
2928 /* If there is only one line then we are done */
2929 eol = strchr(buf.buf, '\n');
2930 if (!eol || !eol[1])
2931 ret = 1;
2933 strbuf_release(&buf);
2935 return ret;
2938 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2940 struct replay_opts opts = REPLAY_OPTS_INIT;
2941 int need_cleanup = 0;
2943 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2944 if (!refs_delete_ref(get_main_ref_store(r), "",
2945 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2946 verbose)
2947 warning(_("cancelling a cherry picking in progress"));
2948 opts.action = REPLAY_PICK;
2949 need_cleanup = 1;
2952 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2953 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2954 NULL, REF_NO_DEREF) &&
2955 verbose)
2956 warning(_("cancelling a revert in progress"));
2957 opts.action = REPLAY_REVERT;
2958 need_cleanup = 1;
2961 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2962 NULL, REF_NO_DEREF);
2964 if (!need_cleanup)
2965 goto out;
2967 if (!have_finished_the_last_pick())
2968 goto out;
2970 sequencer_remove_state(&opts);
2971 out:
2972 replay_opts_release(&opts);
2975 static void todo_list_write_total_nr(struct todo_list *todo_list)
2977 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2979 if (f) {
2980 fprintf(f, "%d\n", todo_list->total_nr);
2981 fclose(f);
2985 static int read_populate_todo(struct repository *r,
2986 struct todo_list *todo_list,
2987 struct replay_opts *opts)
2989 const char *todo_file = get_todo_path(opts);
2990 int res;
2992 strbuf_reset(&todo_list->buf);
2993 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2994 return -1;
2996 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
2997 if (res) {
2998 if (is_rebase_i(opts))
2999 return error(_("please fix this using "
3000 "'git rebase --edit-todo'."));
3001 return error(_("unusable instruction sheet: '%s'"), todo_file);
3004 if (!todo_list->nr &&
3005 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3006 return error(_("no commits parsed."));
3008 if (!is_rebase_i(opts)) {
3009 enum todo_command valid =
3010 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3011 int i;
3013 for (i = 0; i < todo_list->nr; i++)
3014 if (valid == todo_list->items[i].command)
3015 continue;
3016 else if (valid == TODO_PICK)
3017 return error(_("cannot cherry-pick during a revert."));
3018 else
3019 return error(_("cannot revert during a cherry-pick."));
3022 if (is_rebase_i(opts)) {
3023 struct todo_list done = TODO_LIST_INIT;
3025 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3026 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3027 todo_list->done_nr = count_commands(&done);
3028 else
3029 todo_list->done_nr = 0;
3031 todo_list->total_nr = todo_list->done_nr
3032 + count_commands(todo_list);
3033 todo_list_release(&done);
3035 todo_list_write_total_nr(todo_list);
3038 return 0;
3041 static int git_config_string_dup(char **dest,
3042 const char *var, const char *value)
3044 if (!value)
3045 return config_error_nonbool(var);
3046 free(*dest);
3047 *dest = xstrdup(value);
3048 return 0;
3051 static int populate_opts_cb(const char *key, const char *value,
3052 const struct config_context *ctx,
3053 void *data)
3055 struct replay_opts *opts = data;
3056 int error_flag = 1;
3058 if (!value)
3059 error_flag = 0;
3060 else if (!strcmp(key, "options.no-commit"))
3061 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3062 else if (!strcmp(key, "options.edit"))
3063 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3064 else if (!strcmp(key, "options.allow-empty"))
3065 opts->allow_empty =
3066 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3067 else if (!strcmp(key, "options.allow-empty-message"))
3068 opts->allow_empty_message =
3069 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3070 else if (!strcmp(key, "options.drop-redundant-commits"))
3071 opts->drop_redundant_commits =
3072 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3073 else if (!strcmp(key, "options.keep-redundant-commits"))
3074 opts->keep_redundant_commits =
3075 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3076 else if (!strcmp(key, "options.signoff"))
3077 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3078 else if (!strcmp(key, "options.record-origin"))
3079 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3080 else if (!strcmp(key, "options.allow-ff"))
3081 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3082 else if (!strcmp(key, "options.mainline"))
3083 opts->mainline = git_config_int(key, value, ctx->kvi);
3084 else if (!strcmp(key, "options.strategy"))
3085 git_config_string_dup(&opts->strategy, key, value);
3086 else if (!strcmp(key, "options.gpg-sign"))
3087 git_config_string_dup(&opts->gpg_sign, key, value);
3088 else if (!strcmp(key, "options.strategy-option")) {
3089 strvec_push(&opts->xopts, value);
3090 } else if (!strcmp(key, "options.allow-rerere-auto"))
3091 opts->allow_rerere_auto =
3092 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3093 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3094 else if (!strcmp(key, "options.default-msg-cleanup")) {
3095 opts->explicit_cleanup = 1;
3096 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3097 } else
3098 return error(_("invalid key: %s"), key);
3100 if (!error_flag)
3101 return error(_("invalid value for '%s': '%s'"), key, value);
3103 return 0;
3106 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3108 int i;
3109 int count;
3110 const char **argv;
3111 char *strategy_opts_string = raw_opts;
3113 if (*strategy_opts_string == ' ')
3114 strategy_opts_string++;
3116 count = split_cmdline(strategy_opts_string, &argv);
3117 if (count < 0)
3118 BUG("could not split '%s': %s", strategy_opts_string,
3119 split_cmdline_strerror(count));
3120 for (i = 0; i < count; i++) {
3121 const char *arg = argv[i];
3123 skip_prefix(arg, "--", &arg);
3124 strvec_push(&opts->xopts, arg);
3126 free(argv);
3129 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3131 strbuf_reset(buf);
3132 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3133 return;
3134 opts->strategy = strbuf_detach(buf, NULL);
3135 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3136 return;
3138 parse_strategy_opts(opts, buf->buf);
3141 static int read_populate_opts(struct replay_opts *opts)
3143 struct replay_ctx *ctx = opts->ctx;
3145 if (is_rebase_i(opts)) {
3146 struct strbuf buf = STRBUF_INIT;
3147 int ret = 0;
3149 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3150 READ_ONELINER_SKIP_IF_EMPTY)) {
3151 if (!starts_with(buf.buf, "-S"))
3152 strbuf_reset(&buf);
3153 else {
3154 free(opts->gpg_sign);
3155 opts->gpg_sign = xstrdup(buf.buf + 2);
3157 strbuf_reset(&buf);
3160 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3161 READ_ONELINER_SKIP_IF_EMPTY)) {
3162 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3163 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3164 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3165 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3166 strbuf_reset(&buf);
3169 if (file_exists(rebase_path_verbose()))
3170 opts->verbose = 1;
3172 if (file_exists(rebase_path_quiet()))
3173 opts->quiet = 1;
3175 if (file_exists(rebase_path_signoff())) {
3176 opts->allow_ff = 0;
3177 opts->signoff = 1;
3180 if (file_exists(rebase_path_cdate_is_adate())) {
3181 opts->allow_ff = 0;
3182 opts->committer_date_is_author_date = 1;
3185 if (file_exists(rebase_path_ignore_date())) {
3186 opts->allow_ff = 0;
3187 opts->ignore_date = 1;
3190 if (file_exists(rebase_path_reschedule_failed_exec()))
3191 opts->reschedule_failed_exec = 1;
3192 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3193 opts->reschedule_failed_exec = 0;
3195 if (file_exists(rebase_path_drop_redundant_commits()))
3196 opts->drop_redundant_commits = 1;
3198 if (file_exists(rebase_path_keep_redundant_commits()))
3199 opts->keep_redundant_commits = 1;
3201 read_strategy_opts(opts, &buf);
3202 strbuf_reset(&buf);
3204 if (read_oneliner(&ctx->current_fixups,
3205 rebase_path_current_fixups(),
3206 READ_ONELINER_SKIP_IF_EMPTY)) {
3207 const char *p = ctx->current_fixups.buf;
3208 ctx->current_fixup_count = 1;
3209 while ((p = strchr(p, '\n'))) {
3210 ctx->current_fixup_count++;
3211 p++;
3215 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3216 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3217 ret = error(_("unusable squash-onto"));
3218 goto done_rebase_i;
3220 opts->have_squash_onto = 1;
3223 done_rebase_i:
3224 strbuf_release(&buf);
3225 return ret;
3228 if (!file_exists(git_path_opts_file()))
3229 return 0;
3231 * The function git_parse_source(), called from git_config_from_file(),
3232 * may die() in case of a syntactically incorrect file. We do not care
3233 * about this case, though, because we wrote that file ourselves, so we
3234 * are pretty certain that it is syntactically correct.
3236 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3237 return error(_("malformed options sheet: '%s'"),
3238 git_path_opts_file());
3239 return 0;
3242 static void write_strategy_opts(struct replay_opts *opts)
3244 struct strbuf buf = STRBUF_INIT;
3247 * Quote strategy options so that they can be read correctly
3248 * by split_cmdline().
3250 quote_cmdline(&buf, opts->xopts.v);
3251 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3252 strbuf_release(&buf);
3255 int write_basic_state(struct replay_opts *opts, const char *head_name,
3256 struct commit *onto, const struct object_id *orig_head)
3258 if (head_name)
3259 write_file(rebase_path_head_name(), "%s\n", head_name);
3260 if (onto)
3261 write_file(rebase_path_onto(), "%s\n",
3262 oid_to_hex(&onto->object.oid));
3263 if (orig_head)
3264 write_file(rebase_path_orig_head(), "%s\n",
3265 oid_to_hex(orig_head));
3267 if (opts->quiet)
3268 write_file(rebase_path_quiet(), "%s", "");
3269 if (opts->verbose)
3270 write_file(rebase_path_verbose(), "%s", "");
3271 if (opts->strategy)
3272 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3273 if (opts->xopts.nr > 0)
3274 write_strategy_opts(opts);
3276 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3277 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3278 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3279 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3281 if (opts->gpg_sign)
3282 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3283 if (opts->signoff)
3284 write_file(rebase_path_signoff(), "--signoff\n");
3285 if (opts->drop_redundant_commits)
3286 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3287 if (opts->keep_redundant_commits)
3288 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3289 if (opts->committer_date_is_author_date)
3290 write_file(rebase_path_cdate_is_adate(), "%s", "");
3291 if (opts->ignore_date)
3292 write_file(rebase_path_ignore_date(), "%s", "");
3293 if (opts->reschedule_failed_exec)
3294 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3295 else
3296 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3298 return 0;
3301 static int walk_revs_populate_todo(struct todo_list *todo_list,
3302 struct replay_opts *opts)
3304 enum todo_command command = opts->action == REPLAY_PICK ?
3305 TODO_PICK : TODO_REVERT;
3306 const char *command_string = todo_command_info[command].str;
3307 const char *encoding;
3308 struct commit *commit;
3310 if (prepare_revs(opts))
3311 return -1;
3313 encoding = get_log_output_encoding();
3315 while ((commit = get_revision(opts->revs))) {
3316 struct todo_item *item = append_new_todo(todo_list);
3317 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3318 commit, NULL,
3319 encoding);
3320 const char *subject;
3321 int subject_len;
3323 item->command = command;
3324 item->commit = commit;
3325 item->arg_offset = 0;
3326 item->arg_len = 0;
3327 item->offset_in_buf = todo_list->buf.len;
3328 subject_len = find_commit_subject(commit_buffer, &subject);
3329 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3330 short_commit_name(the_repository, commit),
3331 subject_len, subject);
3332 repo_unuse_commit_buffer(the_repository, commit,
3333 commit_buffer);
3336 if (!todo_list->nr)
3337 return error(_("empty commit set passed"));
3339 return 0;
3342 static int create_seq_dir(struct repository *r)
3344 enum replay_action action;
3345 const char *in_progress_error = NULL;
3346 const char *in_progress_advice = NULL;
3347 unsigned int advise_skip =
3348 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3349 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3351 if (!sequencer_get_last_command(r, &action)) {
3352 switch (action) {
3353 case REPLAY_REVERT:
3354 in_progress_error = _("revert is already in progress");
3355 in_progress_advice =
3356 _("try \"git revert (--continue | %s--abort | --quit)\"");
3357 break;
3358 case REPLAY_PICK:
3359 in_progress_error = _("cherry-pick is already in progress");
3360 in_progress_advice =
3361 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3362 break;
3363 default:
3364 BUG("unexpected action in create_seq_dir");
3367 if (in_progress_error) {
3368 error("%s", in_progress_error);
3369 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3370 advise(in_progress_advice,
3371 advise_skip ? "--skip | " : "");
3372 return -1;
3374 if (mkdir(git_path_seq_dir(), 0777) < 0)
3375 return error_errno(_("could not create sequencer directory '%s'"),
3376 git_path_seq_dir());
3378 return 0;
3381 static int save_head(const char *head)
3383 return write_message(head, strlen(head), git_path_head_file(), 1);
3386 static int rollback_is_safe(void)
3388 struct strbuf sb = STRBUF_INIT;
3389 struct object_id expected_head, actual_head;
3391 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3392 strbuf_trim(&sb);
3393 if (get_oid_hex(sb.buf, &expected_head)) {
3394 strbuf_release(&sb);
3395 die(_("could not parse %s"), git_path_abort_safety_file());
3397 strbuf_release(&sb);
3399 else if (errno == ENOENT)
3400 oidclr(&expected_head, the_repository->hash_algo);
3401 else
3402 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3404 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3405 oidclr(&actual_head, the_repository->hash_algo);
3407 return oideq(&actual_head, &expected_head);
3410 static int reset_merge(const struct object_id *oid)
3412 struct child_process cmd = CHILD_PROCESS_INIT;
3414 cmd.git_cmd = 1;
3415 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3417 if (!is_null_oid(oid))
3418 strvec_push(&cmd.args, oid_to_hex(oid));
3420 return run_command(&cmd);
3423 static int rollback_single_pick(struct repository *r)
3425 struct object_id head_oid;
3427 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3428 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3429 return error(_("no cherry-pick or revert in progress"));
3430 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3431 return error(_("cannot resolve HEAD"));
3432 if (is_null_oid(&head_oid))
3433 return error(_("cannot abort from a branch yet to be born"));
3434 return reset_merge(&head_oid);
3437 static int skip_single_pick(void)
3439 struct object_id head;
3441 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3442 return error(_("cannot resolve HEAD"));
3443 return reset_merge(&head);
3446 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3448 FILE *f;
3449 struct object_id oid;
3450 struct strbuf buf = STRBUF_INIT;
3451 const char *p;
3453 f = fopen(git_path_head_file(), "r");
3454 if (!f && errno == ENOENT) {
3456 * There is no multiple-cherry-pick in progress.
3457 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3458 * a single-cherry-pick in progress, abort that.
3460 return rollback_single_pick(r);
3462 if (!f)
3463 return error_errno(_("cannot open '%s'"), git_path_head_file());
3464 if (strbuf_getline_lf(&buf, f)) {
3465 error(_("cannot read '%s': %s"), git_path_head_file(),
3466 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3467 fclose(f);
3468 goto fail;
3470 fclose(f);
3471 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3472 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3473 git_path_head_file());
3474 goto fail;
3476 if (is_null_oid(&oid)) {
3477 error(_("cannot abort from a branch yet to be born"));
3478 goto fail;
3481 if (!rollback_is_safe()) {
3482 /* Do not error, just do not rollback */
3483 warning(_("You seem to have moved HEAD. "
3484 "Not rewinding, check your HEAD!"));
3485 } else
3486 if (reset_merge(&oid))
3487 goto fail;
3488 strbuf_release(&buf);
3489 return sequencer_remove_state(opts);
3490 fail:
3491 strbuf_release(&buf);
3492 return -1;
3495 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3497 enum replay_action action = -1;
3498 sequencer_get_last_command(r, &action);
3501 * Check whether the subcommand requested to skip the commit is actually
3502 * in progress and that it's safe to skip the commit.
3504 * opts->action tells us which subcommand requested to skip the commit.
3505 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3506 * action is in progress and we can skip the commit.
3508 * Otherwise we check that the last instruction was related to the
3509 * particular subcommand we're trying to execute and barf if that's not
3510 * the case.
3512 * Finally we check that the rollback is "safe", i.e., has the HEAD
3513 * moved? In this case, it doesn't make sense to "reset the merge" and
3514 * "skip the commit" as the user already handled this by committing. But
3515 * we'd not want to barf here, instead give advice on how to proceed. We
3516 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3517 * it gets removed when the user commits, so if it still exists we're
3518 * sure the user can't have committed before.
3520 switch (opts->action) {
3521 case REPLAY_REVERT:
3522 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3523 if (action != REPLAY_REVERT)
3524 return error(_("no revert in progress"));
3525 if (!rollback_is_safe())
3526 goto give_advice;
3528 break;
3529 case REPLAY_PICK:
3530 if (!refs_ref_exists(get_main_ref_store(r),
3531 "CHERRY_PICK_HEAD")) {
3532 if (action != REPLAY_PICK)
3533 return error(_("no cherry-pick in progress"));
3534 if (!rollback_is_safe())
3535 goto give_advice;
3537 break;
3538 default:
3539 BUG("unexpected action in sequencer_skip");
3542 if (skip_single_pick())
3543 return error(_("failed to skip the commit"));
3544 if (!is_directory(git_path_seq_dir()))
3545 return 0;
3547 return sequencer_continue(r, opts);
3549 give_advice:
3550 error(_("there is nothing to skip"));
3552 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3553 advise(_("have you committed already?\n"
3554 "try \"git %s --continue\""),
3555 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3557 return -1;
3560 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3561 int reschedule)
3563 struct lock_file todo_lock = LOCK_INIT;
3564 const char *todo_path = get_todo_path(opts);
3565 int next = todo_list->current, offset, fd;
3568 * rebase -i writes "git-rebase-todo" without the currently executing
3569 * command, appending it to "done" instead.
3571 if (is_rebase_i(opts) && !reschedule)
3572 next++;
3574 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3575 if (fd < 0)
3576 return error_errno(_("could not lock '%s'"), todo_path);
3577 offset = get_item_line_offset(todo_list, next);
3578 if (write_in_full(fd, todo_list->buf.buf + offset,
3579 todo_list->buf.len - offset) < 0)
3580 return error_errno(_("could not write to '%s'"), todo_path);
3581 if (commit_lock_file(&todo_lock) < 0)
3582 return error(_("failed to finalize '%s'"), todo_path);
3584 if (is_rebase_i(opts) && !reschedule && next > 0) {
3585 const char *done = rebase_path_done();
3586 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3587 int ret = 0;
3589 if (fd < 0)
3590 return 0;
3591 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3592 get_item_line_length(todo_list, next - 1))
3593 < 0)
3594 ret = error_errno(_("could not write to '%s'"), done);
3595 if (close(fd) < 0)
3596 ret = error_errno(_("failed to finalize '%s'"), done);
3597 return ret;
3599 return 0;
3602 static int save_opts(struct replay_opts *opts)
3604 const char *opts_file = git_path_opts_file();
3605 int res = 0;
3607 if (opts->no_commit)
3608 res |= git_config_set_in_file_gently(opts_file,
3609 "options.no-commit", NULL, "true");
3610 if (opts->edit >= 0)
3611 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
3612 opts->edit ? "true" : "false");
3613 if (opts->allow_empty)
3614 res |= git_config_set_in_file_gently(opts_file,
3615 "options.allow-empty", NULL, "true");
3616 if (opts->allow_empty_message)
3617 res |= git_config_set_in_file_gently(opts_file,
3618 "options.allow-empty-message", NULL, "true");
3619 if (opts->drop_redundant_commits)
3620 res |= git_config_set_in_file_gently(opts_file,
3621 "options.drop-redundant-commits", NULL, "true");
3622 if (opts->keep_redundant_commits)
3623 res |= git_config_set_in_file_gently(opts_file,
3624 "options.keep-redundant-commits", NULL, "true");
3625 if (opts->signoff)
3626 res |= git_config_set_in_file_gently(opts_file,
3627 "options.signoff", NULL, "true");
3628 if (opts->record_origin)
3629 res |= git_config_set_in_file_gently(opts_file,
3630 "options.record-origin", NULL, "true");
3631 if (opts->allow_ff)
3632 res |= git_config_set_in_file_gently(opts_file,
3633 "options.allow-ff", NULL, "true");
3634 if (opts->mainline) {
3635 struct strbuf buf = STRBUF_INIT;
3636 strbuf_addf(&buf, "%d", opts->mainline);
3637 res |= git_config_set_in_file_gently(opts_file,
3638 "options.mainline", NULL, buf.buf);
3639 strbuf_release(&buf);
3641 if (opts->strategy)
3642 res |= git_config_set_in_file_gently(opts_file,
3643 "options.strategy", NULL, opts->strategy);
3644 if (opts->gpg_sign)
3645 res |= git_config_set_in_file_gently(opts_file,
3646 "options.gpg-sign", NULL, opts->gpg_sign);
3647 for (size_t i = 0; i < opts->xopts.nr; i++)
3648 res |= git_config_set_multivar_in_file_gently(opts_file,
3649 "options.strategy-option",
3650 opts->xopts.v[i], "^$", NULL, 0);
3651 if (opts->allow_rerere_auto)
3652 res |= git_config_set_in_file_gently(opts_file,
3653 "options.allow-rerere-auto", NULL,
3654 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3655 "true" : "false");
3657 if (opts->explicit_cleanup)
3658 res |= git_config_set_in_file_gently(opts_file,
3659 "options.default-msg-cleanup", NULL,
3660 describe_cleanup_mode(opts->default_msg_cleanup));
3661 return res;
3664 static int make_patch(struct repository *r,
3665 struct commit *commit,
3666 struct replay_opts *opts)
3668 struct rev_info log_tree_opt;
3669 const char *subject;
3670 char hex[GIT_MAX_HEXSZ + 1];
3671 int res = 0;
3673 if (!is_rebase_i(opts))
3674 BUG("make_patch should only be called when rebasing");
3676 oid_to_hex_r(hex, &commit->object.oid);
3677 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3678 return -1;
3679 res |= write_rebase_head(&commit->object.oid);
3681 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3682 repo_init_revisions(r, &log_tree_opt, NULL);
3683 log_tree_opt.abbrev = 0;
3684 log_tree_opt.diff = 1;
3685 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3686 log_tree_opt.disable_stdin = 1;
3687 log_tree_opt.no_commit_id = 1;
3688 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3689 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3690 if (!log_tree_opt.diffopt.file)
3691 res |= error_errno(_("could not open '%s'"),
3692 rebase_path_patch());
3693 else {
3694 res |= log_tree_commit(&log_tree_opt, commit);
3695 fclose(log_tree_opt.diffopt.file);
3698 if (!file_exists(rebase_path_message())) {
3699 const char *encoding = get_commit_output_encoding();
3700 const char *commit_buffer = repo_logmsg_reencode(r,
3701 commit, NULL,
3702 encoding);
3703 find_commit_subject(commit_buffer, &subject);
3704 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3705 repo_unuse_commit_buffer(r, commit,
3706 commit_buffer);
3708 release_revisions(&log_tree_opt);
3710 return res;
3713 static int intend_to_amend(void)
3715 struct object_id head;
3716 char *p;
3718 if (repo_get_oid(the_repository, "HEAD", &head))
3719 return error(_("cannot read HEAD"));
3721 p = oid_to_hex(&head);
3722 return write_message(p, strlen(p), rebase_path_amend(), 1);
3725 static int error_with_patch(struct repository *r,
3726 struct commit *commit,
3727 const char *subject, int subject_len,
3728 struct replay_opts *opts,
3729 int exit_code, int to_amend)
3731 struct replay_ctx *ctx = opts->ctx;
3734 * Write the commit message to be used by "git rebase
3735 * --continue". If a "fixup" or "squash" command has conflicts
3736 * then we will have already written rebase_path_message() in
3737 * error_failed_squash(). If an "edit" command was
3738 * fast-forwarded then we don't have a message in ctx->message
3739 * and rely on make_patch() to write rebase_path_message()
3740 * instead.
3742 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3743 write_message(ctx->message.buf, ctx->message.len,
3744 rebase_path_message(), 0))
3745 return error(_("could not write commit message file"));
3747 if (commit && make_patch(r, commit, opts))
3748 return -1;
3750 if (to_amend) {
3751 if (intend_to_amend())
3752 return -1;
3754 fprintf(stderr,
3755 _("You can amend the commit now, with\n"
3756 "\n"
3757 " git commit --amend %s\n"
3758 "\n"
3759 "Once you are satisfied with your changes, run\n"
3760 "\n"
3761 " git rebase --continue\n"),
3762 gpg_sign_opt_quoted(opts));
3763 } else if (exit_code) {
3764 if (commit)
3765 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3766 short_commit_name(r, commit), subject_len, subject);
3767 else
3769 * We don't have the hash of the parent so
3770 * just print the line from the todo file.
3772 fprintf_ln(stderr, _("Could not merge %.*s"),
3773 subject_len, subject);
3776 return exit_code;
3779 static int error_failed_squash(struct repository *r,
3780 struct commit *commit,
3781 struct replay_opts *opts,
3782 int subject_len,
3783 const char *subject)
3785 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3786 return error(_("could not copy '%s' to '%s'"),
3787 rebase_path_squash_msg(), rebase_path_message());
3788 unlink(git_path_merge_msg(r));
3789 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3790 return error(_("could not copy '%s' to '%s'"),
3791 rebase_path_message(),
3792 git_path_merge_msg(r));
3793 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3796 static int do_exec(struct repository *r, const char *command_line)
3798 struct child_process cmd = CHILD_PROCESS_INIT;
3799 int dirty, status;
3801 fprintf(stderr, _("Executing: %s\n"), command_line);
3802 cmd.use_shell = 1;
3803 strvec_push(&cmd.args, command_line);
3804 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3805 status = run_command(&cmd);
3807 /* force re-reading of the cache */
3808 discard_index(r->index);
3809 if (repo_read_index(r) < 0)
3810 return error(_("could not read index"));
3812 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3814 if (status) {
3815 warning(_("execution failed: %s\n%s"
3816 "You can fix the problem, and then run\n"
3817 "\n"
3818 " git rebase --continue\n"
3819 "\n"),
3820 command_line,
3821 dirty ? _("and made changes to the index and/or the "
3822 "working tree.\n") : "");
3823 if (status == 127)
3824 /* command not found */
3825 status = 1;
3826 } else if (dirty) {
3827 warning(_("execution succeeded: %s\nbut "
3828 "left changes to the index and/or the working tree.\n"
3829 "Commit or stash your changes, and then run\n"
3830 "\n"
3831 " git rebase --continue\n"
3832 "\n"), command_line);
3833 status = 1;
3836 return status;
3839 __attribute__((format (printf, 2, 3)))
3840 static int safe_append(const char *filename, const char *fmt, ...)
3842 va_list ap;
3843 struct lock_file lock = LOCK_INIT;
3844 int fd = hold_lock_file_for_update(&lock, filename,
3845 LOCK_REPORT_ON_ERROR);
3846 struct strbuf buf = STRBUF_INIT;
3848 if (fd < 0)
3849 return -1;
3851 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3852 error_errno(_("could not read '%s'"), filename);
3853 rollback_lock_file(&lock);
3854 return -1;
3856 strbuf_complete(&buf, '\n');
3857 va_start(ap, fmt);
3858 strbuf_vaddf(&buf, fmt, ap);
3859 va_end(ap);
3861 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3862 error_errno(_("could not write to '%s'"), filename);
3863 strbuf_release(&buf);
3864 rollback_lock_file(&lock);
3865 return -1;
3867 if (commit_lock_file(&lock) < 0) {
3868 strbuf_release(&buf);
3869 return error(_("failed to finalize '%s'"), filename);
3872 strbuf_release(&buf);
3873 return 0;
3876 static int do_label(struct repository *r, const char *name, int len)
3878 struct ref_store *refs = get_main_ref_store(r);
3879 struct ref_transaction *transaction;
3880 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3881 struct strbuf msg = STRBUF_INIT;
3882 int ret = 0;
3883 struct object_id head_oid;
3885 if (len == 1 && *name == '#')
3886 return error(_("illegal label name: '%.*s'"), len, name);
3888 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3889 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3891 transaction = ref_store_transaction_begin(refs, &err);
3892 if (!transaction) {
3893 error("%s", err.buf);
3894 ret = -1;
3895 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3896 error(_("could not read HEAD"));
3897 ret = -1;
3898 } else if (ref_transaction_update(transaction, ref_name.buf,
3899 &head_oid, NULL, NULL, NULL,
3900 0, msg.buf, &err) < 0 ||
3901 ref_transaction_commit(transaction, &err)) {
3902 error("%s", err.buf);
3903 ret = -1;
3905 ref_transaction_free(transaction);
3906 strbuf_release(&err);
3907 strbuf_release(&msg);
3909 if (!ret)
3910 ret = safe_append(rebase_path_refs_to_delete(),
3911 "%s\n", ref_name.buf);
3912 strbuf_release(&ref_name);
3914 return ret;
3917 static const char *sequencer_reflog_action(struct replay_opts *opts)
3919 if (!opts->reflog_action) {
3920 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3921 opts->reflog_action =
3922 xstrdup(opts->reflog_action ? opts->reflog_action
3923 : action_name(opts));
3926 return opts->reflog_action;
3929 __attribute__((format (printf, 3, 4)))
3930 static const char *reflog_message(struct replay_opts *opts,
3931 const char *sub_action, const char *fmt, ...)
3933 va_list ap;
3934 static struct strbuf buf = STRBUF_INIT;
3936 va_start(ap, fmt);
3937 strbuf_reset(&buf);
3938 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3939 if (sub_action)
3940 strbuf_addf(&buf, " (%s)", sub_action);
3941 if (fmt) {
3942 strbuf_addstr(&buf, ": ");
3943 strbuf_vaddf(&buf, fmt, ap);
3945 va_end(ap);
3947 return buf.buf;
3950 static struct commit *lookup_label(struct repository *r, const char *label,
3951 int len, struct strbuf *buf)
3953 struct commit *commit;
3954 struct object_id oid;
3956 strbuf_reset(buf);
3957 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3958 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
3959 commit = lookup_commit_object(r, &oid);
3960 } else {
3961 /* fall back to non-rewritten ref or commit */
3962 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3963 commit = lookup_commit_reference_by_name(buf->buf);
3966 if (!commit)
3967 error(_("could not resolve '%s'"), buf->buf);
3969 return commit;
3972 static int do_reset(struct repository *r,
3973 const char *name, int len,
3974 struct replay_opts *opts)
3976 struct strbuf ref_name = STRBUF_INIT;
3977 struct object_id oid;
3978 struct lock_file lock = LOCK_INIT;
3979 struct tree_desc desc = { 0 };
3980 struct tree *tree;
3981 struct unpack_trees_options unpack_tree_opts = { 0 };
3982 int ret = 0;
3984 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3985 return -1;
3987 if (len == 10 && !strncmp("[new root]", name, len)) {
3988 if (!opts->have_squash_onto) {
3989 const char *hex;
3990 if (commit_tree("", 0, the_hash_algo->empty_tree,
3991 NULL, &opts->squash_onto,
3992 NULL, NULL))
3993 return error(_("writing fake root commit"));
3994 opts->have_squash_onto = 1;
3995 hex = oid_to_hex(&opts->squash_onto);
3996 if (write_message(hex, strlen(hex),
3997 rebase_path_squash_onto(), 0))
3998 return error(_("writing squash-onto"));
4000 oidcpy(&oid, &opts->squash_onto);
4001 } else {
4002 int i;
4003 struct commit *commit;
4005 /* Determine the length of the label */
4006 for (i = 0; i < len; i++)
4007 if (isspace(name[i]))
4008 break;
4009 len = i;
4011 commit = lookup_label(r, name, len, &ref_name);
4012 if (!commit) {
4013 ret = -1;
4014 goto cleanup;
4016 oid = commit->object.oid;
4019 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4020 unpack_tree_opts.head_idx = 1;
4021 unpack_tree_opts.src_index = r->index;
4022 unpack_tree_opts.dst_index = r->index;
4023 unpack_tree_opts.fn = oneway_merge;
4024 unpack_tree_opts.merge = 1;
4025 unpack_tree_opts.update = 1;
4026 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4027 unpack_tree_opts.skip_cache_tree_update = 1;
4028 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4030 if (repo_read_index_unmerged(r)) {
4031 ret = error_resolve_conflict(action_name(opts));
4032 goto cleanup;
4035 if (!fill_tree_descriptor(r, &desc, &oid)) {
4036 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4037 goto cleanup;
4040 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4041 ret = -1;
4042 goto cleanup;
4045 tree = parse_tree_indirect(&oid);
4046 if (!tree)
4047 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4048 prime_cache_tree(r, r->index, tree);
4050 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4051 ret = error(_("could not write index"));
4053 if (!ret)
4054 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4055 len, name),
4056 "HEAD", &oid,
4057 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4058 cleanup:
4059 free((void *)desc.buffer);
4060 if (ret < 0)
4061 rollback_lock_file(&lock);
4062 strbuf_release(&ref_name);
4063 clear_unpack_trees_porcelain(&unpack_tree_opts);
4064 return ret;
4067 static int do_merge(struct repository *r,
4068 struct commit *commit,
4069 const char *arg, int arg_len,
4070 int flags, int *check_todo, struct replay_opts *opts)
4072 struct replay_ctx *ctx = opts->ctx;
4073 int run_commit_flags = 0;
4074 struct strbuf ref_name = STRBUF_INIT;
4075 struct commit *head_commit, *merge_commit, *i;
4076 struct commit_list *bases = NULL, *j;
4077 struct commit_list *to_merge = NULL, **tail = &to_merge;
4078 const char *strategy = !opts->xopts.nr &&
4079 (!opts->strategy ||
4080 !strcmp(opts->strategy, "recursive") ||
4081 !strcmp(opts->strategy, "ort")) ?
4082 NULL : opts->strategy;
4083 struct merge_options o;
4084 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4085 static struct lock_file lock;
4086 const char *p;
4088 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4089 ret = -1;
4090 goto leave_merge;
4093 head_commit = lookup_commit_reference_by_name("HEAD");
4094 if (!head_commit) {
4095 ret = error(_("cannot merge without a current revision"));
4096 goto leave_merge;
4100 * For octopus merges, the arg starts with the list of revisions to be
4101 * merged. The list is optionally followed by '#' and the oneline.
4103 merge_arg_len = oneline_offset = arg_len;
4104 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4105 if (!*p)
4106 break;
4107 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4108 p += 1 + strspn(p + 1, " \t\n");
4109 oneline_offset = p - arg;
4110 break;
4112 k = strcspn(p, " \t\n");
4113 if (!k)
4114 continue;
4115 merge_commit = lookup_label(r, p, k, &ref_name);
4116 if (!merge_commit) {
4117 ret = error(_("unable to parse '%.*s'"), k, p);
4118 goto leave_merge;
4120 tail = &commit_list_insert(merge_commit, tail)->next;
4121 p += k;
4122 merge_arg_len = p - arg;
4125 if (!to_merge) {
4126 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4127 goto leave_merge;
4130 if (opts->have_squash_onto &&
4131 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4133 * When the user tells us to "merge" something into a
4134 * "[new root]", let's simply fast-forward to the merge head.
4136 rollback_lock_file(&lock);
4137 if (to_merge->next)
4138 ret = error(_("octopus merge cannot be executed on "
4139 "top of a [new root]"));
4140 else
4141 ret = fast_forward_to(r, &to_merge->item->object.oid,
4142 &head_commit->object.oid, 0,
4143 opts);
4144 goto leave_merge;
4148 * If HEAD is not identical to the first parent of the original merge
4149 * commit, we cannot fast-forward.
4151 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4152 oideq(&commit->parents->item->object.oid,
4153 &head_commit->object.oid);
4156 * If any merge head is different from the original one, we cannot
4157 * fast-forward.
4159 if (can_fast_forward) {
4160 struct commit_list *p = commit->parents->next;
4162 for (j = to_merge; j && p; j = j->next, p = p->next)
4163 if (!oideq(&j->item->object.oid,
4164 &p->item->object.oid)) {
4165 can_fast_forward = 0;
4166 break;
4169 * If the number of merge heads differs from the original merge
4170 * commit, we cannot fast-forward.
4172 if (j || p)
4173 can_fast_forward = 0;
4176 if (can_fast_forward) {
4177 rollback_lock_file(&lock);
4178 ret = fast_forward_to(r, &commit->object.oid,
4179 &head_commit->object.oid, 0, opts);
4180 if (flags & TODO_EDIT_MERGE_MSG)
4181 goto fast_forward_edit;
4183 goto leave_merge;
4186 if (commit) {
4187 const char *encoding = get_commit_output_encoding();
4188 const char *message = repo_logmsg_reencode(r, commit, NULL,
4189 encoding);
4190 const char *body;
4191 int len;
4193 if (!message) {
4194 ret = error(_("could not get commit message of '%s'"),
4195 oid_to_hex(&commit->object.oid));
4196 goto leave_merge;
4198 write_author_script(message);
4199 find_commit_subject(message, &body);
4200 len = strlen(body);
4201 strbuf_add(&ctx->message, body, len);
4202 repo_unuse_commit_buffer(r, commit, message);
4203 } else {
4204 struct strbuf buf = STRBUF_INIT;
4206 strbuf_addf(&buf, "author %s", git_author_info(0));
4207 write_author_script(buf.buf);
4208 strbuf_release(&buf);
4210 if (oneline_offset < arg_len) {
4211 strbuf_add(&ctx->message, arg + oneline_offset,
4212 arg_len - oneline_offset);
4213 } else {
4214 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4215 to_merge->next ? "branches" : "branch",
4216 merge_arg_len, arg);
4219 ctx->have_message = 1;
4220 if (write_message(ctx->message.buf, ctx->message.len,
4221 git_path_merge_msg(r), 0)) {
4222 ret = error_errno(_("could not write '%s'"),
4223 git_path_merge_msg(r));
4224 goto leave_merge;
4227 if (strategy || to_merge->next) {
4228 /* Octopus merge */
4229 struct child_process cmd = CHILD_PROCESS_INIT;
4231 if (read_env_script(&cmd.env)) {
4232 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4234 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4235 goto leave_merge;
4238 if (opts->committer_date_is_author_date)
4239 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4240 opts->ignore_date ?
4241 "" :
4242 author_date_from_env(&cmd.env));
4243 if (opts->ignore_date)
4244 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4246 cmd.git_cmd = 1;
4247 strvec_push(&cmd.args, "merge");
4248 strvec_push(&cmd.args, "-s");
4249 if (!strategy)
4250 strvec_push(&cmd.args, "octopus");
4251 else {
4252 strvec_push(&cmd.args, strategy);
4253 for (k = 0; k < opts->xopts.nr; k++)
4254 strvec_pushf(&cmd.args,
4255 "-X%s", opts->xopts.v[k]);
4257 if (!(flags & TODO_EDIT_MERGE_MSG))
4258 strvec_push(&cmd.args, "--no-edit");
4259 else
4260 strvec_push(&cmd.args, "--edit");
4261 strvec_push(&cmd.args, "--no-ff");
4262 strvec_push(&cmd.args, "--no-log");
4263 strvec_push(&cmd.args, "--no-stat");
4264 strvec_push(&cmd.args, "-F");
4265 strvec_push(&cmd.args, git_path_merge_msg(r));
4266 if (opts->gpg_sign)
4267 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4268 else
4269 strvec_push(&cmd.args, "--no-gpg-sign");
4271 /* Add the tips to be merged */
4272 for (j = to_merge; j; j = j->next)
4273 strvec_push(&cmd.args,
4274 oid_to_hex(&j->item->object.oid));
4276 strbuf_release(&ref_name);
4277 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4278 NULL, REF_NO_DEREF);
4279 rollback_lock_file(&lock);
4281 ret = run_command(&cmd);
4283 /* force re-reading of the cache */
4284 if (!ret) {
4285 discard_index(r->index);
4286 if (repo_read_index(r) < 0)
4287 ret = error(_("could not read index"));
4289 goto leave_merge;
4292 merge_commit = to_merge->item;
4293 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4294 ret = -1;
4295 goto leave_merge;
4298 if (bases && oideq(&merge_commit->object.oid,
4299 &bases->item->object.oid)) {
4300 ret = 0;
4301 /* skip merging an ancestor of HEAD */
4302 goto leave_merge;
4305 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4306 git_path_merge_head(r), 0);
4307 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4309 bases = reverse_commit_list(bases);
4311 repo_read_index(r);
4312 init_merge_options(&o, r);
4313 o.branch1 = "HEAD";
4314 o.branch2 = ref_name.buf;
4315 o.buffer_output = 2;
4317 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4319 * TODO: Should use merge_incore_recursive() and
4320 * merge_switch_to_result(), skipping the call to
4321 * merge_switch_to_result() when we don't actually need to
4322 * update the index and working copy immediately.
4324 ret = merge_ort_recursive(&o,
4325 head_commit, merge_commit, bases,
4326 &i);
4327 } else {
4328 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4329 &i);
4331 if (ret <= 0)
4332 fputs(o.obuf.buf, stdout);
4333 strbuf_release(&o.obuf);
4334 if (ret < 0) {
4335 error(_("could not even attempt to merge '%.*s'"),
4336 merge_arg_len, arg);
4337 unlink(git_path_merge_msg(r));
4338 goto leave_merge;
4341 * The return value of merge_recursive() is 1 on clean, and 0 on
4342 * unclean merge.
4344 * Let's reverse that, so that do_merge() returns 0 upon success and
4345 * 1 upon failed merge (keeping the return value -1 for the cases where
4346 * we will want to reschedule the `merge` command).
4348 ret = !ret;
4350 if (r->index->cache_changed &&
4351 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4352 ret = error(_("merge: Unable to write new index file"));
4353 goto leave_merge;
4356 rollback_lock_file(&lock);
4357 if (ret)
4358 repo_rerere(r, opts->allow_rerere_auto);
4359 else
4361 * In case of problems, we now want to return a positive
4362 * value (a negative one would indicate that the `merge`
4363 * command needs to be rescheduled).
4365 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4366 run_commit_flags);
4368 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4369 fast_forward_edit:
4370 *check_todo = 1;
4371 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4372 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4376 leave_merge:
4377 strbuf_release(&ref_name);
4378 rollback_lock_file(&lock);
4379 free_commit_list(to_merge);
4380 free_commit_list(bases);
4381 return ret;
4384 static int write_update_refs_state(struct string_list *refs_to_oids)
4386 int result = 0;
4387 struct lock_file lock = LOCK_INIT;
4388 FILE *fp = NULL;
4389 struct string_list_item *item;
4390 char *path;
4392 path = rebase_path_update_refs(the_repository->gitdir);
4394 if (!refs_to_oids->nr) {
4395 if (unlink(path) && errno != ENOENT)
4396 result = error_errno(_("could not unlink: %s"), path);
4397 goto cleanup;
4400 if (safe_create_leading_directories(path)) {
4401 result = error(_("unable to create leading directories of %s"),
4402 path);
4403 goto cleanup;
4406 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4407 result = error(_("another 'rebase' process appears to be running; "
4408 "'%s.lock' already exists"),
4409 path);
4410 goto cleanup;
4413 fp = fdopen_lock_file(&lock, "w");
4414 if (!fp) {
4415 result = error_errno(_("could not open '%s' for writing"), path);
4416 rollback_lock_file(&lock);
4417 goto cleanup;
4420 for_each_string_list_item(item, refs_to_oids) {
4421 struct update_ref_record *rec = item->util;
4422 fprintf(fp, "%s\n%s\n%s\n", item->string,
4423 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4426 result = commit_lock_file(&lock);
4428 cleanup:
4429 free(path);
4430 return result;
4434 * Parse the update-refs file for the current rebase, then remove the
4435 * refs that do not appear in the todo_list (and have not had updated
4436 * values stored) and add refs that are in the todo_list but not
4437 * represented in the update-refs file.
4439 * If there are changes to the update-refs list, then write the new state
4440 * to disk.
4442 void todo_list_filter_update_refs(struct repository *r,
4443 struct todo_list *todo_list)
4445 int i;
4446 int updated = 0;
4447 struct string_list update_refs = STRING_LIST_INIT_DUP;
4449 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4452 * For each item in the update_refs list, if it has no updated
4453 * value and does not appear in the todo_list, then remove it
4454 * from the update_refs list.
4456 for (i = 0; i < update_refs.nr; i++) {
4457 int j;
4458 int found = 0;
4459 const char *ref = update_refs.items[i].string;
4460 size_t reflen = strlen(ref);
4461 struct update_ref_record *rec = update_refs.items[i].util;
4463 /* OID already stored as updated. */
4464 if (!is_null_oid(&rec->after))
4465 continue;
4467 for (j = 0; !found && j < todo_list->nr; j++) {
4468 struct todo_item *item = &todo_list->items[j];
4469 const char *arg = todo_list->buf.buf + item->arg_offset;
4471 if (item->command != TODO_UPDATE_REF)
4472 continue;
4474 if (item->arg_len != reflen ||
4475 strncmp(arg, ref, reflen))
4476 continue;
4478 found = 1;
4481 if (!found) {
4482 free(update_refs.items[i].string);
4483 free(update_refs.items[i].util);
4485 update_refs.nr--;
4486 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4488 updated = 1;
4489 i--;
4494 * For each todo_item, check if its ref is in the update_refs list.
4495 * If not, then add it as an un-updated ref.
4497 for (i = 0; i < todo_list->nr; i++) {
4498 struct todo_item *item = &todo_list->items[i];
4499 const char *arg = todo_list->buf.buf + item->arg_offset;
4500 int j, found = 0;
4502 if (item->command != TODO_UPDATE_REF)
4503 continue;
4505 for (j = 0; !found && j < update_refs.nr; j++) {
4506 const char *ref = update_refs.items[j].string;
4508 found = strlen(ref) == item->arg_len &&
4509 !strncmp(ref, arg, item->arg_len);
4512 if (!found) {
4513 struct string_list_item *inserted;
4514 struct strbuf argref = STRBUF_INIT;
4516 strbuf_add(&argref, arg, item->arg_len);
4517 inserted = string_list_insert(&update_refs, argref.buf);
4518 inserted->util = init_update_ref_record(argref.buf);
4519 strbuf_release(&argref);
4520 updated = 1;
4524 if (updated)
4525 write_update_refs_state(&update_refs);
4526 string_list_clear(&update_refs, 1);
4529 static int do_update_ref(struct repository *r, const char *refname)
4531 struct string_list_item *item;
4532 struct string_list list = STRING_LIST_INIT_DUP;
4534 if (sequencer_get_update_refs_state(r->gitdir, &list))
4535 return -1;
4537 for_each_string_list_item(item, &list) {
4538 if (!strcmp(item->string, refname)) {
4539 struct update_ref_record *rec = item->util;
4540 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4541 return -1;
4542 break;
4546 write_update_refs_state(&list);
4547 string_list_clear(&list, 1);
4548 return 0;
4551 static int do_update_refs(struct repository *r, int quiet)
4553 int res = 0;
4554 struct string_list_item *item;
4555 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4556 struct ref_store *refs = get_main_ref_store(r);
4557 struct strbuf update_msg = STRBUF_INIT;
4558 struct strbuf error_msg = STRBUF_INIT;
4560 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4561 return res;
4563 for_each_string_list_item(item, &refs_to_oids) {
4564 struct update_ref_record *rec = item->util;
4565 int loop_res;
4567 loop_res = refs_update_ref(refs, "rewritten during rebase",
4568 item->string,
4569 &rec->after, &rec->before,
4570 0, UPDATE_REFS_MSG_ON_ERR);
4571 res |= loop_res;
4573 if (quiet)
4574 continue;
4576 if (loop_res)
4577 strbuf_addf(&error_msg, "\t%s\n", item->string);
4578 else
4579 strbuf_addf(&update_msg, "\t%s\n", item->string);
4582 if (!quiet &&
4583 (update_msg.len || error_msg.len)) {
4584 fprintf(stderr,
4585 _("Updated the following refs with %s:\n%s"),
4586 "--update-refs",
4587 update_msg.buf);
4589 if (res)
4590 fprintf(stderr,
4591 _("Failed to update the following refs with %s:\n%s"),
4592 "--update-refs",
4593 error_msg.buf);
4596 string_list_clear(&refs_to_oids, 1);
4597 strbuf_release(&update_msg);
4598 strbuf_release(&error_msg);
4599 return res;
4602 static int is_final_fixup(struct todo_list *todo_list)
4604 int i = todo_list->current;
4606 if (!is_fixup(todo_list->items[i].command))
4607 return 0;
4609 while (++i < todo_list->nr)
4610 if (is_fixup(todo_list->items[i].command))
4611 return 0;
4612 else if (!is_noop(todo_list->items[i].command))
4613 break;
4614 return 1;
4617 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4619 int i;
4621 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4622 if (!is_noop(todo_list->items[i].command))
4623 return todo_list->items[i].command;
4625 return -1;
4628 static void create_autostash_internal(struct repository *r,
4629 const char *path,
4630 const char *refname)
4632 struct strbuf buf = STRBUF_INIT;
4633 struct lock_file lock_file = LOCK_INIT;
4634 int fd;
4636 if (path && refname)
4637 BUG("can only pass path or refname");
4639 fd = repo_hold_locked_index(r, &lock_file, 0);
4640 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4641 if (0 <= fd)
4642 repo_update_index_if_able(r, &lock_file);
4643 rollback_lock_file(&lock_file);
4645 if (has_unstaged_changes(r, 1) ||
4646 has_uncommitted_changes(r, 1)) {
4647 struct child_process stash = CHILD_PROCESS_INIT;
4648 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4649 struct object_id oid;
4651 strvec_pushl(&stash.args,
4652 "stash", "create", "autostash", NULL);
4653 stash.git_cmd = 1;
4654 stash.no_stdin = 1;
4655 strbuf_reset(&buf);
4656 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4657 die(_("Cannot autostash"));
4658 strbuf_trim_trailing_newline(&buf);
4659 if (repo_get_oid(r, buf.buf, &oid))
4660 die(_("Unexpected stash response: '%s'"),
4661 buf.buf);
4662 strbuf_reset(&buf);
4663 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4665 if (path) {
4666 if (safe_create_leading_directories_const(path))
4667 die(_("Could not create directory for '%s'"),
4668 path);
4669 write_file(path, "%s", oid_to_hex(&oid));
4670 } else {
4671 refs_update_ref(get_main_ref_store(r), "", refname,
4672 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4675 printf(_("Created autostash: %s\n"), buf.buf);
4676 if (reset_head(r, &ropts) < 0)
4677 die(_("could not reset --hard"));
4678 discard_index(r->index);
4679 if (repo_read_index(r) < 0)
4680 die(_("could not read index"));
4682 strbuf_release(&buf);
4685 void create_autostash(struct repository *r, const char *path)
4687 create_autostash_internal(r, path, NULL);
4690 void create_autostash_ref(struct repository *r, const char *refname)
4692 create_autostash_internal(r, NULL, refname);
4695 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4697 struct child_process child = CHILD_PROCESS_INIT;
4698 int ret = 0;
4700 if (attempt_apply) {
4701 child.git_cmd = 1;
4702 child.no_stdout = 1;
4703 child.no_stderr = 1;
4704 strvec_push(&child.args, "stash");
4705 strvec_push(&child.args, "apply");
4706 strvec_push(&child.args, stash_oid);
4707 ret = run_command(&child);
4710 if (attempt_apply && !ret)
4711 fprintf(stderr, _("Applied autostash.\n"));
4712 else {
4713 struct child_process store = CHILD_PROCESS_INIT;
4715 store.git_cmd = 1;
4716 strvec_push(&store.args, "stash");
4717 strvec_push(&store.args, "store");
4718 strvec_push(&store.args, "-m");
4719 strvec_push(&store.args, "autostash");
4720 strvec_push(&store.args, "-q");
4721 strvec_push(&store.args, stash_oid);
4722 if (run_command(&store))
4723 ret = error(_("cannot store %s"), stash_oid);
4724 else
4725 fprintf(stderr,
4726 _("%s\n"
4727 "Your changes are safe in the stash.\n"
4728 "You can run \"git stash pop\" or"
4729 " \"git stash drop\" at any time.\n"),
4730 attempt_apply ?
4731 _("Applying autostash resulted in conflicts.") :
4732 _("Autostash exists; creating a new stash entry."));
4735 return ret;
4738 static int apply_save_autostash(const char *path, int attempt_apply)
4740 struct strbuf stash_oid = STRBUF_INIT;
4741 int ret = 0;
4743 if (!read_oneliner(&stash_oid, path,
4744 READ_ONELINER_SKIP_IF_EMPTY)) {
4745 strbuf_release(&stash_oid);
4746 return 0;
4748 strbuf_trim(&stash_oid);
4750 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4752 unlink(path);
4753 strbuf_release(&stash_oid);
4754 return ret;
4757 int save_autostash(const char *path)
4759 return apply_save_autostash(path, 0);
4762 int apply_autostash(const char *path)
4764 return apply_save_autostash(path, 1);
4767 int apply_autostash_oid(const char *stash_oid)
4769 return apply_save_autostash_oid(stash_oid, 1);
4772 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4773 int attempt_apply)
4775 struct object_id stash_oid;
4776 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4777 int flag, ret;
4779 if (!refs_ref_exists(get_main_ref_store(r), refname))
4780 return 0;
4782 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4783 RESOLVE_REF_READING, &stash_oid, &flag))
4784 return -1;
4785 if (flag & REF_ISSYMREF)
4786 return error(_("autostash reference is a symref"));
4788 oid_to_hex_r(stash_oid_hex, &stash_oid);
4789 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4791 refs_delete_ref(get_main_ref_store(r), "", refname,
4792 &stash_oid, REF_NO_DEREF);
4794 return ret;
4797 int save_autostash_ref(struct repository *r, const char *refname)
4799 return apply_save_autostash_ref(r, refname, 0);
4802 int apply_autostash_ref(struct repository *r, const char *refname)
4804 return apply_save_autostash_ref(r, refname, 1);
4807 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4808 const char *onto_name, const struct object_id *onto,
4809 const struct object_id *orig_head)
4811 struct reset_head_opts ropts = {
4812 .oid = onto,
4813 .orig_head = orig_head,
4814 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4815 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4816 .head_msg = reflog_message(opts, "start", "checkout %s",
4817 onto_name),
4818 .default_reflog_action = sequencer_reflog_action(opts)
4820 if (reset_head(r, &ropts)) {
4821 apply_autostash(rebase_path_autostash());
4822 sequencer_remove_state(opts);
4823 return error(_("could not detach HEAD"));
4826 return 0;
4829 static int stopped_at_head(struct repository *r)
4831 struct object_id head;
4832 struct commit *commit;
4833 struct commit_message message;
4835 if (repo_get_oid(r, "HEAD", &head) ||
4836 !(commit = lookup_commit(r, &head)) ||
4837 repo_parse_commit(r, commit) || get_message(commit, &message))
4838 fprintf(stderr, _("Stopped at HEAD\n"));
4839 else {
4840 fprintf(stderr, _("Stopped at %s\n"), message.label);
4841 free_message(commit, &message);
4843 return 0;
4847 static int reread_todo_if_changed(struct repository *r,
4848 struct todo_list *todo_list,
4849 struct replay_opts *opts)
4851 int offset;
4852 struct strbuf buf = STRBUF_INIT;
4854 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4855 return -1;
4856 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4857 if (buf.len != todo_list->buf.len - offset ||
4858 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4859 /* Reread the todo file if it has changed. */
4860 todo_list_release(todo_list);
4861 if (read_populate_todo(r, todo_list, opts))
4862 return -1; /* message was printed */
4863 /* `current` will be incremented on return */
4864 todo_list->current = -1;
4866 strbuf_release(&buf);
4868 return 0;
4871 static const char rescheduled_advice[] =
4872 N_("Could not execute the todo command\n"
4873 "\n"
4874 " %.*s"
4875 "\n"
4876 "It has been rescheduled; To edit the command before continuing, please\n"
4877 "edit the todo list first:\n"
4878 "\n"
4879 " git rebase --edit-todo\n"
4880 " git rebase --continue\n");
4882 static int pick_one_commit(struct repository *r,
4883 struct todo_list *todo_list,
4884 struct replay_opts *opts,
4885 int *check_todo, int* reschedule)
4887 struct replay_ctx *ctx = opts->ctx;
4888 int res;
4889 struct todo_item *item = todo_list->items + todo_list->current;
4890 const char *arg = todo_item_get_arg(todo_list, item);
4891 if (is_rebase_i(opts))
4892 ctx->reflog_message = reflog_message(
4893 opts, command_to_string(item->command), NULL);
4895 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4896 check_todo);
4897 if (is_rebase_i(opts) && res < 0) {
4898 /* Reschedule */
4899 *reschedule = 1;
4900 return -1;
4902 if (item->command == TODO_EDIT) {
4903 struct commit *commit = item->commit;
4904 if (!res) {
4905 if (!opts->verbose)
4906 term_clear_line();
4907 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4908 short_commit_name(r, commit), item->arg_len, arg);
4910 return error_with_patch(r, commit,
4911 arg, item->arg_len, opts, res, !res);
4913 if (is_rebase_i(opts) && !res)
4914 record_in_rewritten(&item->commit->object.oid,
4915 peek_command(todo_list, 1));
4916 if (res && is_fixup(item->command)) {
4917 if (res == 1)
4918 intend_to_amend();
4919 return error_failed_squash(r, item->commit, opts,
4920 item->arg_len, arg);
4921 } else if (res && is_rebase_i(opts) && item->commit) {
4922 int to_amend = 0;
4923 struct object_id oid;
4926 * If we are rewording and have either
4927 * fast-forwarded already, or are about to
4928 * create a new root commit, we want to amend,
4929 * otherwise we do not.
4931 if (item->command == TODO_REWORD &&
4932 !repo_get_oid(r, "HEAD", &oid) &&
4933 (oideq(&item->commit->object.oid, &oid) ||
4934 (opts->have_squash_onto &&
4935 oideq(&opts->squash_onto, &oid))))
4936 to_amend = 1;
4938 return res | error_with_patch(r, item->commit,
4939 arg, item->arg_len, opts,
4940 res, to_amend);
4942 return res;
4945 static int pick_commits(struct repository *r,
4946 struct todo_list *todo_list,
4947 struct replay_opts *opts)
4949 struct replay_ctx *ctx = opts->ctx;
4950 int res = 0, reschedule = 0;
4952 ctx->reflog_message = sequencer_reflog_action(opts);
4953 if (opts->allow_ff)
4954 assert(!(opts->signoff || opts->no_commit ||
4955 opts->record_origin || should_edit(opts) ||
4956 opts->committer_date_is_author_date ||
4957 opts->ignore_date));
4958 if (read_and_refresh_cache(r, opts))
4959 return -1;
4961 unlink(rebase_path_message());
4962 unlink(rebase_path_stopped_sha());
4963 unlink(rebase_path_amend());
4964 unlink(rebase_path_patch());
4966 while (todo_list->current < todo_list->nr) {
4967 struct todo_item *item = todo_list->items + todo_list->current;
4968 const char *arg = todo_item_get_arg(todo_list, item);
4969 int check_todo = 0;
4971 if (save_todo(todo_list, opts, reschedule))
4972 return -1;
4973 if (is_rebase_i(opts)) {
4974 if (item->command != TODO_COMMENT) {
4975 FILE *f = fopen(rebase_path_msgnum(), "w");
4977 todo_list->done_nr++;
4979 if (f) {
4980 fprintf(f, "%d\n", todo_list->done_nr);
4981 fclose(f);
4983 if (!opts->quiet)
4984 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4985 todo_list->done_nr,
4986 todo_list->total_nr,
4987 opts->verbose ? "\n" : "\r");
4989 unlink(rebase_path_author_script());
4990 unlink(git_path_merge_head(r));
4991 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4992 NULL, REF_NO_DEREF);
4993 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4994 NULL, REF_NO_DEREF);
4996 if (item->command == TODO_BREAK) {
4997 if (!opts->verbose)
4998 term_clear_line();
4999 return stopped_at_head(r);
5002 strbuf_reset(&ctx->message);
5003 ctx->have_message = 0;
5004 if (item->command <= TODO_SQUASH) {
5005 res = pick_one_commit(r, todo_list, opts, &check_todo,
5006 &reschedule);
5007 if (!res && item->command == TODO_EDIT)
5008 return 0;
5009 } else if (item->command == TODO_EXEC) {
5010 char *end_of_arg = (char *)(arg + item->arg_len);
5011 int saved = *end_of_arg;
5013 if (!opts->verbose)
5014 term_clear_line();
5015 *end_of_arg = '\0';
5016 res = do_exec(r, arg);
5017 *end_of_arg = saved;
5019 if (res) {
5020 if (opts->reschedule_failed_exec)
5021 reschedule = 1;
5023 check_todo = 1;
5024 } else if (item->command == TODO_LABEL) {
5025 if ((res = do_label(r, arg, item->arg_len)))
5026 reschedule = 1;
5027 } else if (item->command == TODO_RESET) {
5028 if ((res = do_reset(r, arg, item->arg_len, opts)))
5029 reschedule = 1;
5030 } else if (item->command == TODO_MERGE) {
5031 if ((res = do_merge(r, item->commit, arg, item->arg_len,
5032 item->flags, &check_todo, opts)) < 0)
5033 reschedule = 1;
5034 else if (item->commit)
5035 record_in_rewritten(&item->commit->object.oid,
5036 peek_command(todo_list, 1));
5037 if (res > 0)
5038 /* failed with merge conflicts */
5039 return error_with_patch(r, item->commit,
5040 arg, item->arg_len,
5041 opts, res, 0);
5042 } else if (item->command == TODO_UPDATE_REF) {
5043 struct strbuf ref = STRBUF_INIT;
5044 strbuf_add(&ref, arg, item->arg_len);
5045 if ((res = do_update_ref(r, ref.buf)))
5046 reschedule = 1;
5047 strbuf_release(&ref);
5048 } else if (!is_noop(item->command))
5049 return error(_("unknown command %d"), item->command);
5051 if (reschedule) {
5052 advise(_(rescheduled_advice),
5053 get_item_line_length(todo_list,
5054 todo_list->current),
5055 get_item_line(todo_list, todo_list->current));
5056 if (save_todo(todo_list, opts, reschedule))
5057 return -1;
5058 if (item->commit)
5059 write_rebase_head(&item->commit->object.oid);
5060 } else if (is_rebase_i(opts) && check_todo && !res &&
5061 reread_todo_if_changed(r, todo_list, opts)) {
5062 return -1;
5065 if (res)
5066 return res;
5068 todo_list->current++;
5071 if (is_rebase_i(opts)) {
5072 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
5073 struct stat st;
5075 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5076 starts_with(head_ref.buf, "refs/")) {
5077 const char *msg;
5078 struct object_id head, orig;
5079 int res;
5081 if (repo_get_oid(r, "HEAD", &head)) {
5082 res = error(_("cannot read HEAD"));
5083 cleanup_head_ref:
5084 strbuf_release(&head_ref);
5085 strbuf_release(&buf);
5086 return res;
5088 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
5089 get_oid_hex(buf.buf, &orig)) {
5090 res = error(_("could not read orig-head"));
5091 goto cleanup_head_ref;
5093 strbuf_reset(&buf);
5094 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5095 res = error(_("could not read 'onto'"));
5096 goto cleanup_head_ref;
5098 msg = reflog_message(opts, "finish", "%s onto %s",
5099 head_ref.buf, buf.buf);
5100 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5101 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
5102 res = error(_("could not update %s"),
5103 head_ref.buf);
5104 goto cleanup_head_ref;
5106 msg = reflog_message(opts, "finish", "returning to %s",
5107 head_ref.buf);
5108 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
5109 res = error(_("could not update HEAD to %s"),
5110 head_ref.buf);
5111 goto cleanup_head_ref;
5113 strbuf_reset(&buf);
5116 if (opts->verbose) {
5117 struct rev_info log_tree_opt;
5118 struct object_id orig, head;
5120 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
5121 repo_init_revisions(r, &log_tree_opt, NULL);
5122 log_tree_opt.diff = 1;
5123 log_tree_opt.diffopt.output_format =
5124 DIFF_FORMAT_DIFFSTAT;
5125 log_tree_opt.disable_stdin = 1;
5127 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
5128 !repo_get_oid(r, buf.buf, &orig) &&
5129 !repo_get_oid(r, "HEAD", &head)) {
5130 diff_tree_oid(&orig, &head, "",
5131 &log_tree_opt.diffopt);
5132 log_tree_diff_flush(&log_tree_opt);
5134 release_revisions(&log_tree_opt);
5136 flush_rewritten_pending();
5137 if (!stat(rebase_path_rewritten_list(), &st) &&
5138 st.st_size > 0) {
5139 struct child_process child = CHILD_PROCESS_INIT;
5140 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5142 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5143 child.git_cmd = 1;
5144 strvec_push(&child.args, "notes");
5145 strvec_push(&child.args, "copy");
5146 strvec_push(&child.args, "--for-rewrite=rebase");
5147 /* we don't care if this copying failed */
5148 run_command(&child);
5150 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5151 strvec_push(&hook_opt.args, "rebase");
5152 run_hooks_opt("post-rewrite", &hook_opt);
5154 apply_autostash(rebase_path_autostash());
5156 if (!opts->quiet) {
5157 if (!opts->verbose)
5158 term_clear_line();
5159 fprintf(stderr,
5160 _("Successfully rebased and updated %s.\n"),
5161 head_ref.buf);
5164 strbuf_release(&buf);
5165 strbuf_release(&head_ref);
5167 if (do_update_refs(r, opts->quiet))
5168 return -1;
5172 * Sequence of picks finished successfully; cleanup by
5173 * removing the .git/sequencer directory
5175 return sequencer_remove_state(opts);
5178 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5180 struct child_process cmd = CHILD_PROCESS_INIT;
5182 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5183 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5184 return error(_("no cherry-pick or revert in progress"));
5186 cmd.git_cmd = 1;
5187 strvec_push(&cmd.args, "commit");
5190 * continue_single_pick() handles the case of recovering from a
5191 * conflict. should_edit() doesn't handle that case; for a conflict,
5192 * we want to edit if the user asked for it, or if they didn't specify
5193 * and stdin is a tty.
5195 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5197 * Include --cleanup=strip as well because we don't want the
5198 * "# Conflicts:" messages.
5200 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5202 return run_command(&cmd);
5205 static int commit_staged_changes(struct repository *r,
5206 struct replay_opts *opts,
5207 struct todo_list *todo_list)
5209 struct replay_ctx *ctx = opts->ctx;
5210 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5211 unsigned int final_fixup = 0, is_clean;
5212 struct strbuf rev = STRBUF_INIT;
5213 int ret;
5215 if (has_unstaged_changes(r, 1)) {
5216 ret = error(_("cannot rebase: You have unstaged changes."));
5217 goto out;
5220 is_clean = !has_uncommitted_changes(r, 0);
5222 if (!is_clean && !file_exists(rebase_path_message())) {
5223 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5224 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
5225 goto out;
5228 if (file_exists(rebase_path_amend())) {
5229 struct object_id head, to_amend;
5231 if (repo_get_oid(r, "HEAD", &head)) {
5232 ret = error(_("cannot amend non-existing commit"));
5233 goto out;
5236 if (!read_oneliner(&rev, rebase_path_amend(), 0)) {
5237 ret = error(_("invalid file: '%s'"), rebase_path_amend());
5238 goto out;
5241 if (get_oid_hex(rev.buf, &to_amend)) {
5242 ret = error(_("invalid contents: '%s'"),
5243 rebase_path_amend());
5244 goto out;
5246 if (!is_clean && !oideq(&head, &to_amend)) {
5247 ret = error(_("\nYou have uncommitted changes in your "
5248 "working tree. Please, commit them\n"
5249 "first and then run 'git rebase "
5250 "--continue' again."));
5251 goto out;
5254 * When skipping a failed fixup/squash, we need to edit the
5255 * commit message, the current fixup list and count, and if it
5256 * was the last fixup/squash in the chain, we need to clean up
5257 * the commit message and if there was a squash, let the user
5258 * edit it.
5260 if (!is_clean || !ctx->current_fixup_count)
5261 ; /* this is not the final fixup */
5262 else if (!oideq(&head, &to_amend) ||
5263 !file_exists(rebase_path_stopped_sha())) {
5264 /* was a final fixup or squash done manually? */
5265 if (!is_fixup(peek_command(todo_list, 0))) {
5266 unlink(rebase_path_fixup_msg());
5267 unlink(rebase_path_squash_msg());
5268 unlink(rebase_path_current_fixups());
5269 strbuf_reset(&ctx->current_fixups);
5270 ctx->current_fixup_count = 0;
5272 } else {
5273 /* we are in a fixup/squash chain */
5274 const char *p = ctx->current_fixups.buf;
5275 int len = ctx->current_fixups.len;
5277 ctx->current_fixup_count--;
5278 if (!len)
5279 BUG("Incorrect current_fixups:\n%s", p);
5280 while (len && p[len - 1] != '\n')
5281 len--;
5282 strbuf_setlen(&ctx->current_fixups, len);
5283 if (write_message(p, len, rebase_path_current_fixups(),
5284 0) < 0) {
5285 ret = error(_("could not write file: '%s'"),
5286 rebase_path_current_fixups());
5287 goto out;
5291 * If a fixup/squash in a fixup/squash chain failed, the
5292 * commit message is already correct, no need to commit
5293 * it again.
5295 * Only if it is the final command in the fixup/squash
5296 * chain, and only if the chain is longer than a single
5297 * fixup/squash command (which was just skipped), do we
5298 * actually need to re-commit with a cleaned up commit
5299 * message.
5301 if (ctx->current_fixup_count > 0 &&
5302 !is_fixup(peek_command(todo_list, 0))) {
5303 final_fixup = 1;
5305 * If there was not a single "squash" in the
5306 * chain, we only need to clean up the commit
5307 * message, no need to bother the user with
5308 * opening the commit message in the editor.
5310 if (!starts_with(p, "squash ") &&
5311 !strstr(p, "\nsquash "))
5312 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5313 } else if (is_fixup(peek_command(todo_list, 0))) {
5315 * We need to update the squash message to skip
5316 * the latest commit message.
5318 struct commit *commit;
5319 const char *msg;
5320 const char *path = rebase_path_squash_msg();
5321 const char *encoding = get_commit_output_encoding();
5323 if (parse_head(r, &commit)) {
5324 ret = error(_("could not parse HEAD"));
5325 goto out;
5328 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5329 if (!p) {
5330 ret = error(_("could not parse commit %s"),
5331 oid_to_hex(&commit->object.oid));
5332 goto unuse_commit_buffer;
5334 find_commit_subject(p, &msg);
5335 if (write_message(msg, strlen(msg), path, 0)) {
5336 ret = error(_("could not write file: "
5337 "'%s'"), path);
5338 goto unuse_commit_buffer;
5341 ret = 0;
5343 unuse_commit_buffer:
5344 repo_unuse_commit_buffer(r, commit, p);
5345 if (ret)
5346 goto out;
5350 flags |= AMEND_MSG;
5353 if (is_clean) {
5354 if (refs_ref_exists(get_main_ref_store(r),
5355 "CHERRY_PICK_HEAD") &&
5356 refs_delete_ref(get_main_ref_store(r), "",
5357 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF)) {
5358 ret = error(_("could not remove CHERRY_PICK_HEAD"));
5359 goto out;
5362 if (unlink(git_path_merge_msg(r)) && errno != ENOENT) {
5363 ret = error_errno(_("could not remove '%s'"),
5364 git_path_merge_msg(r));
5365 goto out;
5368 if (!final_fixup) {
5369 ret = 0;
5370 goto out;
5374 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5375 opts, flags)) {
5376 ret = error(_("could not commit staged changes."));
5377 goto out;
5380 unlink(rebase_path_amend());
5381 unlink(git_path_merge_head(r));
5382 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5383 NULL, REF_NO_DEREF);
5384 if (final_fixup) {
5385 unlink(rebase_path_fixup_msg());
5386 unlink(rebase_path_squash_msg());
5388 if (ctx->current_fixup_count > 0) {
5390 * Whether final fixup or not, we just cleaned up the commit
5391 * message...
5393 unlink(rebase_path_current_fixups());
5394 strbuf_reset(&ctx->current_fixups);
5395 ctx->current_fixup_count = 0;
5398 ret = 0;
5400 out:
5401 strbuf_release(&rev);
5402 return ret;
5405 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5407 struct replay_ctx *ctx = opts->ctx;
5408 struct todo_list todo_list = TODO_LIST_INIT;
5409 int res;
5411 if (read_and_refresh_cache(r, opts))
5412 return -1;
5414 if (read_populate_opts(opts))
5415 return -1;
5416 if (is_rebase_i(opts)) {
5417 if ((res = read_populate_todo(r, &todo_list, opts)))
5418 goto release_todo_list;
5420 if (file_exists(rebase_path_dropped())) {
5421 if ((res = todo_list_check_against_backup(r, opts,
5422 &todo_list)))
5423 goto release_todo_list;
5425 unlink(rebase_path_dropped());
5428 ctx->reflog_message = reflog_message(opts, "continue", NULL);
5429 if (commit_staged_changes(r, opts, &todo_list)) {
5430 res = -1;
5431 goto release_todo_list;
5433 } else if (!file_exists(get_todo_path(opts)))
5434 return continue_single_pick(r, opts);
5435 else if ((res = read_populate_todo(r, &todo_list, opts)))
5436 goto release_todo_list;
5438 if (!is_rebase_i(opts)) {
5439 /* Verify that the conflict has been resolved */
5440 if (refs_ref_exists(get_main_ref_store(r),
5441 "CHERRY_PICK_HEAD") ||
5442 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5443 res = continue_single_pick(r, opts);
5444 if (res)
5445 goto release_todo_list;
5447 if (index_differs_from(r, "HEAD", NULL, 0)) {
5448 res = error_dirty_index(r, opts);
5449 goto release_todo_list;
5451 todo_list.current++;
5452 } else if (file_exists(rebase_path_stopped_sha())) {
5453 struct strbuf buf = STRBUF_INIT;
5454 struct object_id oid;
5456 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5457 READ_ONELINER_SKIP_IF_EMPTY) &&
5458 !get_oid_hex(buf.buf, &oid))
5459 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5460 strbuf_release(&buf);
5463 res = pick_commits(r, &todo_list, opts);
5464 release_todo_list:
5465 todo_list_release(&todo_list);
5466 return res;
5469 static int single_pick(struct repository *r,
5470 struct commit *cmit,
5471 struct replay_opts *opts)
5473 int check_todo;
5474 struct todo_item item;
5476 item.command = opts->action == REPLAY_PICK ?
5477 TODO_PICK : TODO_REVERT;
5478 item.commit = cmit;
5480 opts->ctx->reflog_message = sequencer_reflog_action(opts);
5481 return do_pick_commit(r, &item, opts, 0, &check_todo);
5484 int sequencer_pick_revisions(struct repository *r,
5485 struct replay_opts *opts)
5487 struct todo_list todo_list = TODO_LIST_INIT;
5488 struct object_id oid;
5489 int i, res;
5491 assert(opts->revs);
5492 if (read_and_refresh_cache(r, opts))
5493 return -1;
5495 for (i = 0; i < opts->revs->pending.nr; i++) {
5496 struct object_id oid;
5497 const char *name = opts->revs->pending.objects[i].name;
5499 /* This happens when using --stdin. */
5500 if (!strlen(name))
5501 continue;
5503 if (!repo_get_oid(r, name, &oid)) {
5504 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5505 enum object_type type = oid_object_info(r,
5506 &oid,
5507 NULL);
5508 return error(_("%s: can't cherry-pick a %s"),
5509 name, type_name(type));
5511 } else
5512 return error(_("%s: bad revision"), name);
5516 * If we were called as "git cherry-pick <commit>", just
5517 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5518 * REVERT_HEAD, and don't touch the sequencer state.
5519 * This means it is possible to cherry-pick in the middle
5520 * of a cherry-pick sequence.
5522 if (opts->revs->cmdline.nr == 1 &&
5523 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5524 opts->revs->no_walk &&
5525 !opts->revs->cmdline.rev->flags) {
5526 struct commit *cmit;
5527 if (prepare_revision_walk(opts->revs))
5528 return error(_("revision walk setup failed"));
5529 cmit = get_revision(opts->revs);
5530 if (!cmit)
5531 return error(_("empty commit set passed"));
5532 if (get_revision(opts->revs))
5533 BUG("unexpected extra commit from walk");
5534 return single_pick(r, cmit, opts);
5538 * Start a new cherry-pick/ revert sequence; but
5539 * first, make sure that an existing one isn't in
5540 * progress
5543 if (walk_revs_populate_todo(&todo_list, opts) ||
5544 create_seq_dir(r) < 0)
5545 return -1;
5546 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5547 return error(_("can't revert as initial commit"));
5548 if (save_head(oid_to_hex(&oid)))
5549 return -1;
5550 if (save_opts(opts))
5551 return -1;
5552 update_abort_safety_file();
5553 res = pick_commits(r, &todo_list, opts);
5554 todo_list_release(&todo_list);
5555 return res;
5558 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5560 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5561 struct strbuf sob = STRBUF_INIT;
5562 int has_footer;
5564 strbuf_addstr(&sob, sign_off_header);
5565 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5566 strbuf_addch(&sob, '\n');
5568 if (!ignore_footer)
5569 strbuf_complete_line(msgbuf);
5572 * If the whole message buffer is equal to the sob, pretend that we
5573 * found a conforming footer with a matching sob
5575 if (msgbuf->len - ignore_footer == sob.len &&
5576 !strncmp(msgbuf->buf, sob.buf, sob.len))
5577 has_footer = 3;
5578 else
5579 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5581 if (!has_footer) {
5582 const char *append_newlines = NULL;
5583 size_t len = msgbuf->len - ignore_footer;
5585 if (!len) {
5587 * The buffer is completely empty. Leave foom for
5588 * the title and body to be filled in by the user.
5590 append_newlines = "\n\n";
5591 } else if (len == 1) {
5593 * Buffer contains a single newline. Add another
5594 * so that we leave room for the title and body.
5596 append_newlines = "\n";
5597 } else if (msgbuf->buf[len - 2] != '\n') {
5599 * Buffer ends with a single newline. Add another
5600 * so that there is an empty line between the message
5601 * body and the sob.
5603 append_newlines = "\n";
5604 } /* else, the buffer already ends with two newlines. */
5606 if (append_newlines)
5607 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5608 append_newlines, strlen(append_newlines));
5611 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5612 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5613 sob.buf, sob.len);
5615 strbuf_release(&sob);
5618 struct labels_entry {
5619 struct hashmap_entry entry;
5620 char label[FLEX_ARRAY];
5623 static int labels_cmp(const void *fndata UNUSED,
5624 const struct hashmap_entry *eptr,
5625 const struct hashmap_entry *entry_or_key, const void *key)
5627 const struct labels_entry *a, *b;
5629 a = container_of(eptr, const struct labels_entry, entry);
5630 b = container_of(entry_or_key, const struct labels_entry, entry);
5632 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5635 struct string_entry {
5636 struct oidmap_entry entry;
5637 char string[FLEX_ARRAY];
5640 struct label_state {
5641 struct oidmap commit2label;
5642 struct hashmap labels;
5643 struct strbuf buf;
5644 int max_label_length;
5647 static const char *label_oid(struct object_id *oid, const char *label,
5648 struct label_state *state)
5650 struct labels_entry *labels_entry;
5651 struct string_entry *string_entry;
5652 struct object_id dummy;
5653 int i;
5655 string_entry = oidmap_get(&state->commit2label, oid);
5656 if (string_entry)
5657 return string_entry->string;
5660 * For "uninteresting" commits, i.e. commits that are not to be
5661 * rebased, and which can therefore not be labeled, we use a unique
5662 * abbreviation of the commit name. This is slightly more complicated
5663 * than calling repo_find_unique_abbrev() because we also need to make
5664 * sure that the abbreviation does not conflict with any other
5665 * label.
5667 * We disallow "interesting" commits to be labeled by a string that
5668 * is a valid full-length hash, to ensure that we always can find an
5669 * abbreviation for any uninteresting commit's names that does not
5670 * clash with any other label.
5672 strbuf_reset(&state->buf);
5673 if (!label) {
5674 char *p;
5676 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5677 label = p = state->buf.buf;
5679 repo_find_unique_abbrev_r(the_repository, p, oid,
5680 default_abbrev);
5683 * We may need to extend the abbreviated hash so that there is
5684 * no conflicting label.
5686 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5687 size_t i = strlen(p) + 1;
5689 oid_to_hex_r(p, oid);
5690 for (; i < the_hash_algo->hexsz; i++) {
5691 char save = p[i];
5692 p[i] = '\0';
5693 if (!hashmap_get_from_hash(&state->labels,
5694 strihash(p), p))
5695 break;
5696 p[i] = save;
5699 } else {
5700 struct strbuf *buf = &state->buf;
5701 int label_is_utf8 = 1; /* start with this assumption */
5702 size_t max_len = buf->len + state->max_label_length;
5705 * Sanitize labels by replacing non-alpha-numeric characters
5706 * (including white-space ones) by dashes, as they might be
5707 * illegal in file names (and hence in ref names).
5709 * Note that we retain non-ASCII UTF-8 characters (identified
5710 * via the most significant bit). They should be all acceptable
5711 * in file names.
5713 * As we will use the labels as names of (loose) refs, it is
5714 * vital that the name not be longer than the maximum component
5715 * size of the file system (`NAME_MAX`). We are careful to
5716 * truncate the label accordingly, allowing for the `.lock`
5717 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5718 * truncating in the middle of a character).
5720 for (; *label && buf->len + 1 < max_len; label++)
5721 if (isalnum(*label) ||
5722 (!label_is_utf8 && (*label & 0x80)))
5723 strbuf_addch(buf, *label);
5724 else if (*label & 0x80) {
5725 const char *p = label;
5727 utf8_width(&p, NULL);
5728 if (p) {
5729 if (buf->len + (p - label) > max_len)
5730 break;
5731 strbuf_add(buf, label, p - label);
5732 label = p - 1;
5733 } else {
5734 label_is_utf8 = 0;
5735 strbuf_addch(buf, *label);
5737 /* avoid leading dash and double-dashes */
5738 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5739 strbuf_addch(buf, '-');
5740 if (!buf->len) {
5741 strbuf_addstr(buf, "rev-");
5742 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5744 label = buf->buf;
5746 if ((buf->len == the_hash_algo->hexsz &&
5747 !get_oid_hex(label, &dummy)) ||
5748 (buf->len == 1 && *label == '#') ||
5749 hashmap_get_from_hash(&state->labels,
5750 strihash(label), label)) {
5752 * If the label already exists, or if the label is a
5753 * valid full OID, or the label is a '#' (which we use
5754 * as a separator between merge heads and oneline), we
5755 * append a dash and a number to make it unique.
5757 size_t len = buf->len;
5759 for (i = 2; ; i++) {
5760 strbuf_setlen(buf, len);
5761 strbuf_addf(buf, "-%d", i);
5762 if (!hashmap_get_from_hash(&state->labels,
5763 strihash(buf->buf),
5764 buf->buf))
5765 break;
5768 label = buf->buf;
5772 FLEX_ALLOC_STR(labels_entry, label, label);
5773 hashmap_entry_init(&labels_entry->entry, strihash(label));
5774 hashmap_add(&state->labels, &labels_entry->entry);
5776 FLEX_ALLOC_STR(string_entry, string, label);
5777 oidcpy(&string_entry->entry.oid, oid);
5778 oidmap_put(&state->commit2label, string_entry);
5780 return string_entry->string;
5783 static int make_script_with_merges(struct pretty_print_context *pp,
5784 struct rev_info *revs, struct strbuf *out,
5785 unsigned flags)
5787 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5788 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5789 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5790 int skipped_commit = 0;
5791 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5792 struct strbuf label = STRBUF_INIT;
5793 struct commit_list *commits = NULL, **tail = &commits, *iter;
5794 struct commit_list *tips = NULL, **tips_tail = &tips;
5795 struct commit *commit;
5796 struct oidmap commit2todo = OIDMAP_INIT;
5797 struct string_entry *entry;
5798 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5799 shown = OIDSET_INIT;
5800 struct label_state state =
5801 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5803 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5804 const char *cmd_pick = abbr ? "p" : "pick",
5805 *cmd_label = abbr ? "l" : "label",
5806 *cmd_reset = abbr ? "t" : "reset",
5807 *cmd_merge = abbr ? "m" : "merge";
5809 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5811 oidmap_init(&commit2todo, 0);
5812 oidmap_init(&state.commit2label, 0);
5813 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5814 strbuf_init(&state.buf, 32);
5816 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5817 struct labels_entry *onto_label_entry;
5818 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5819 FLEX_ALLOC_STR(entry, string, "onto");
5820 oidcpy(&entry->entry.oid, oid);
5821 oidmap_put(&state.commit2label, entry);
5823 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5824 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5825 hashmap_add(&state.labels, &onto_label_entry->entry);
5829 * First phase:
5830 * - get onelines for all commits
5831 * - gather all branch tips (i.e. 2nd or later parents of merges)
5832 * - label all branch tips
5834 while ((commit = get_revision(revs))) {
5835 struct commit_list *to_merge;
5836 const char *p1, *p2;
5837 struct object_id *oid;
5838 int is_empty;
5840 tail = &commit_list_insert(commit, tail)->next;
5841 oidset_insert(&interesting, &commit->object.oid);
5843 is_empty = is_original_commit_empty(commit);
5844 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5845 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5846 warning(_("skipped previously applied commit %s"),
5847 short_commit_name(the_repository, commit));
5848 skipped_commit = 1;
5849 continue;
5851 if (is_empty && !keep_empty)
5852 continue;
5854 strbuf_reset(&oneline);
5855 pretty_print_commit(pp, commit, &oneline);
5857 to_merge = commit->parents ? commit->parents->next : NULL;
5858 if (!to_merge) {
5859 /* non-merge commit: easy case */
5860 strbuf_reset(&buf);
5861 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5862 oid_to_hex(&commit->object.oid),
5863 oneline.buf);
5864 if (is_empty)
5865 strbuf_addf(&buf, " %s empty",
5866 comment_line_str);
5868 FLEX_ALLOC_STR(entry, string, buf.buf);
5869 oidcpy(&entry->entry.oid, &commit->object.oid);
5870 oidmap_put(&commit2todo, entry);
5872 continue;
5875 /* Create a label */
5876 strbuf_reset(&label);
5877 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5878 (p1 = strchr(p1, '\'')) &&
5879 (p2 = strchr(++p1, '\'')))
5880 strbuf_add(&label, p1, p2 - p1);
5881 else if (skip_prefix(oneline.buf, "Merge pull request ",
5882 &p1) &&
5883 (p1 = strstr(p1, " from ")))
5884 strbuf_addstr(&label, p1 + strlen(" from "));
5885 else
5886 strbuf_addbuf(&label, &oneline);
5888 strbuf_reset(&buf);
5889 strbuf_addf(&buf, "%s -C %s",
5890 cmd_merge, oid_to_hex(&commit->object.oid));
5892 /* label the tips of merged branches */
5893 for (; to_merge; to_merge = to_merge->next) {
5894 oid = &to_merge->item->object.oid;
5895 strbuf_addch(&buf, ' ');
5897 if (!oidset_contains(&interesting, oid)) {
5898 strbuf_addstr(&buf, label_oid(oid, NULL,
5899 &state));
5900 continue;
5903 tips_tail = &commit_list_insert(to_merge->item,
5904 tips_tail)->next;
5906 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5908 strbuf_addf(&buf, " # %s", oneline.buf);
5910 FLEX_ALLOC_STR(entry, string, buf.buf);
5911 oidcpy(&entry->entry.oid, &commit->object.oid);
5912 oidmap_put(&commit2todo, entry);
5914 if (skipped_commit)
5915 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5916 _("use --reapply-cherry-picks to include skipped commits"));
5919 * Second phase:
5920 * - label branch points
5921 * - add HEAD to the branch tips
5923 for (iter = commits; iter; iter = iter->next) {
5924 struct commit_list *parent = iter->item->parents;
5925 for (; parent; parent = parent->next) {
5926 struct object_id *oid = &parent->item->object.oid;
5927 if (!oidset_contains(&interesting, oid))
5928 continue;
5929 if (oidset_insert(&child_seen, oid))
5930 label_oid(oid, "branch-point", &state);
5933 /* Add HEAD as implicit "tip of branch" */
5934 if (!iter->next)
5935 tips_tail = &commit_list_insert(iter->item,
5936 tips_tail)->next;
5940 * Third phase: output the todo list. This is a bit tricky, as we
5941 * want to avoid jumping back and forth between revisions. To
5942 * accomplish that goal, we walk backwards from the branch tips,
5943 * gathering commits not yet shown, reversing the list on the fly,
5944 * then outputting that list (labeling revisions as needed).
5946 strbuf_addf(out, "%s onto\n", cmd_label);
5947 for (iter = tips; iter; iter = iter->next) {
5948 struct commit_list *list = NULL, *iter2;
5950 commit = iter->item;
5951 if (oidset_contains(&shown, &commit->object.oid))
5952 continue;
5953 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5955 if (entry)
5956 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
5957 else
5958 strbuf_addch(out, '\n');
5960 while (oidset_contains(&interesting, &commit->object.oid) &&
5961 !oidset_contains(&shown, &commit->object.oid)) {
5962 commit_list_insert(commit, &list);
5963 if (!commit->parents) {
5964 commit = NULL;
5965 break;
5967 commit = commit->parents->item;
5970 if (!commit)
5971 strbuf_addf(out, "%s %s\n", cmd_reset,
5972 rebase_cousins || root_with_onto ?
5973 "onto" : "[new root]");
5974 else {
5975 const char *to = NULL;
5977 entry = oidmap_get(&state.commit2label,
5978 &commit->object.oid);
5979 if (entry)
5980 to = entry->string;
5981 else if (!rebase_cousins)
5982 to = label_oid(&commit->object.oid, NULL,
5983 &state);
5985 if (!to || !strcmp(to, "onto"))
5986 strbuf_addf(out, "%s onto\n", cmd_reset);
5987 else {
5988 strbuf_reset(&oneline);
5989 pretty_print_commit(pp, commit, &oneline);
5990 strbuf_addf(out, "%s %s # %s\n",
5991 cmd_reset, to, oneline.buf);
5995 for (iter2 = list; iter2; iter2 = iter2->next) {
5996 struct object_id *oid = &iter2->item->object.oid;
5997 entry = oidmap_get(&commit2todo, oid);
5998 /* only show if not already upstream */
5999 if (entry)
6000 strbuf_addf(out, "%s\n", entry->string);
6001 entry = oidmap_get(&state.commit2label, oid);
6002 if (entry)
6003 strbuf_addf(out, "%s %s\n",
6004 cmd_label, entry->string);
6005 oidset_insert(&shown, oid);
6008 free_commit_list(list);
6011 free_commit_list(commits);
6012 free_commit_list(tips);
6014 strbuf_release(&label);
6015 strbuf_release(&oneline);
6016 strbuf_release(&buf);
6018 oidset_clear(&interesting);
6019 oidset_clear(&child_seen);
6020 oidset_clear(&shown);
6021 oidmap_free(&commit2todo, 1);
6022 oidmap_free(&state.commit2label, 1);
6023 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
6024 strbuf_release(&state.buf);
6026 return 0;
6029 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
6030 const char **argv, unsigned flags)
6032 char *format = NULL;
6033 struct pretty_print_context pp = {0};
6034 struct rev_info revs;
6035 struct commit *commit;
6036 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
6037 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
6038 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
6039 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
6040 int skipped_commit = 0;
6041 int ret = 0;
6043 repo_init_revisions(r, &revs, NULL);
6044 revs.verbose_header = 1;
6045 if (!rebase_merges)
6046 revs.max_parents = 1;
6047 revs.cherry_mark = !reapply_cherry_picks;
6048 revs.limited = 1;
6049 revs.reverse = 1;
6050 revs.right_only = 1;
6051 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
6052 revs.topo_order = 1;
6054 revs.pretty_given = 1;
6055 git_config_get_string("rebase.instructionFormat", &format);
6056 if (!format || !*format) {
6057 free(format);
6058 format = xstrdup("%s");
6060 get_commit_format(format, &revs);
6061 free(format);
6062 pp.fmt = revs.commit_format;
6063 pp.output_encoding = get_log_output_encoding();
6065 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
6066 ret = error(_("make_script: unhandled options"));
6067 goto cleanup;
6070 if (prepare_revision_walk(&revs) < 0) {
6071 ret = error(_("make_script: error preparing revisions"));
6072 goto cleanup;
6075 if (rebase_merges) {
6076 ret = make_script_with_merges(&pp, &revs, out, flags);
6077 goto cleanup;
6080 while ((commit = get_revision(&revs))) {
6081 int is_empty = is_original_commit_empty(commit);
6083 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6084 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6085 warning(_("skipped previously applied commit %s"),
6086 short_commit_name(r, commit));
6087 skipped_commit = 1;
6088 continue;
6090 if (is_empty && !keep_empty)
6091 continue;
6092 strbuf_addf(out, "%s %s ", insn,
6093 oid_to_hex(&commit->object.oid));
6094 pretty_print_commit(&pp, commit, out);
6095 if (is_empty)
6096 strbuf_addf(out, " %s empty", comment_line_str);
6097 strbuf_addch(out, '\n');
6099 if (skipped_commit)
6100 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6101 _("use --reapply-cherry-picks to include skipped commits"));
6102 cleanup:
6103 release_revisions(&revs);
6104 return ret;
6108 * Add commands after pick and (series of) squash/fixup commands
6109 * in the todo list.
6111 static void todo_list_add_exec_commands(struct todo_list *todo_list,
6112 struct string_list *commands)
6114 struct strbuf *buf = &todo_list->buf;
6115 size_t base_offset = buf->len;
6116 int i, insert, nr = 0, alloc = 0;
6117 struct todo_item *items = NULL, *base_items = NULL;
6119 CALLOC_ARRAY(base_items, commands->nr);
6120 for (i = 0; i < commands->nr; i++) {
6121 size_t command_len = strlen(commands->items[i].string);
6123 strbuf_addstr(buf, commands->items[i].string);
6124 strbuf_addch(buf, '\n');
6126 base_items[i].command = TODO_EXEC;
6127 base_items[i].offset_in_buf = base_offset;
6128 base_items[i].arg_offset = base_offset;
6129 base_items[i].arg_len = command_len;
6131 base_offset += command_len + 1;
6135 * Insert <commands> after every pick. Here, fixup/squash chains
6136 * are considered part of the pick, so we insert the commands *after*
6137 * those chains if there are any.
6139 * As we insert the exec commands immediately after rearranging
6140 * any fixups and before the user edits the list, a fixup chain
6141 * can never contain comments (any comments are empty picks that
6142 * have been commented out because the user did not specify
6143 * --keep-empty). So, it is safe to insert an exec command
6144 * without looking at the command following a comment.
6146 insert = 0;
6147 for (i = 0; i < todo_list->nr; i++) {
6148 enum todo_command command = todo_list->items[i].command;
6149 if (insert && !is_fixup(command)) {
6150 ALLOC_GROW(items, nr + commands->nr, alloc);
6151 COPY_ARRAY(items + nr, base_items, commands->nr);
6152 nr += commands->nr;
6154 insert = 0;
6157 ALLOC_GROW(items, nr + 1, alloc);
6158 items[nr++] = todo_list->items[i];
6160 if (command == TODO_PICK || command == TODO_MERGE)
6161 insert = 1;
6164 /* insert or append final <commands> */
6165 if (insert) {
6166 ALLOC_GROW(items, nr + commands->nr, alloc);
6167 COPY_ARRAY(items + nr, base_items, commands->nr);
6168 nr += commands->nr;
6171 free(base_items);
6172 FREE_AND_NULL(todo_list->items);
6173 todo_list->items = items;
6174 todo_list->nr = nr;
6175 todo_list->alloc = alloc;
6178 static void todo_list_to_strbuf(struct repository *r,
6179 struct todo_list *todo_list,
6180 struct strbuf *buf, int num, unsigned flags)
6182 struct todo_item *item;
6183 int i, max = todo_list->nr;
6185 if (num > 0 && num < max)
6186 max = num;
6188 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6189 char cmd;
6191 /* if the item is not a command write it and continue */
6192 if (item->command >= TODO_COMMENT) {
6193 strbuf_addf(buf, "%.*s\n", item->arg_len,
6194 todo_item_get_arg(todo_list, item));
6195 continue;
6198 /* add command to the buffer */
6199 cmd = command_to_char(item->command);
6200 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6201 strbuf_addch(buf, cmd);
6202 else
6203 strbuf_addstr(buf, command_to_string(item->command));
6205 /* add commit id */
6206 if (item->commit) {
6207 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6208 short_commit_name(r, item->commit) :
6209 oid_to_hex(&item->commit->object.oid);
6211 if (item->command == TODO_FIXUP) {
6212 if (item->flags & TODO_EDIT_FIXUP_MSG)
6213 strbuf_addstr(buf, " -c");
6214 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6215 strbuf_addstr(buf, " -C");
6219 if (item->command == TODO_MERGE) {
6220 if (item->flags & TODO_EDIT_MERGE_MSG)
6221 strbuf_addstr(buf, " -c");
6222 else
6223 strbuf_addstr(buf, " -C");
6226 strbuf_addf(buf, " %s", oid);
6229 /* add all the rest */
6230 if (!item->arg_len)
6231 strbuf_addch(buf, '\n');
6232 else
6233 strbuf_addf(buf, " %.*s\n", item->arg_len,
6234 todo_item_get_arg(todo_list, item));
6238 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6239 const char *file, const char *shortrevisions,
6240 const char *shortonto, int num, unsigned flags)
6242 int res;
6243 struct strbuf buf = STRBUF_INIT;
6245 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6246 if (flags & TODO_LIST_APPEND_TODO_HELP)
6247 append_todo_help(count_commands(todo_list),
6248 shortrevisions, shortonto, &buf);
6250 res = write_message(buf.buf, buf.len, file, 0);
6251 strbuf_release(&buf);
6253 return res;
6256 /* skip picking commits whose parents are unchanged */
6257 static int skip_unnecessary_picks(struct repository *r,
6258 struct todo_list *todo_list,
6259 struct object_id *base_oid)
6261 struct object_id *parent_oid;
6262 int i;
6264 for (i = 0; i < todo_list->nr; i++) {
6265 struct todo_item *item = todo_list->items + i;
6267 if (item->command >= TODO_NOOP)
6268 continue;
6269 if (item->command != TODO_PICK)
6270 break;
6271 if (repo_parse_commit(r, item->commit)) {
6272 return error(_("could not parse commit '%s'"),
6273 oid_to_hex(&item->commit->object.oid));
6275 if (!item->commit->parents)
6276 break; /* root commit */
6277 if (item->commit->parents->next)
6278 break; /* merge commit */
6279 parent_oid = &item->commit->parents->item->object.oid;
6280 if (!oideq(parent_oid, base_oid))
6281 break;
6282 oidcpy(base_oid, &item->commit->object.oid);
6284 if (i > 0) {
6285 const char *done_path = rebase_path_done();
6287 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6288 error_errno(_("could not write to '%s'"), done_path);
6289 return -1;
6292 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6293 todo_list->nr -= i;
6294 todo_list->current = 0;
6295 todo_list->done_nr += i;
6297 if (is_fixup(peek_command(todo_list, 0)))
6298 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6301 return 0;
6304 struct todo_add_branch_context {
6305 struct todo_item *items;
6306 size_t items_nr;
6307 size_t items_alloc;
6308 struct strbuf *buf;
6309 struct commit *commit;
6310 struct string_list refs_to_oids;
6313 static int add_decorations_to_list(const struct commit *commit,
6314 struct todo_add_branch_context *ctx)
6316 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6317 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
6318 "HEAD",
6319 RESOLVE_REF_READING,
6320 NULL,
6321 NULL);
6323 while (decoration) {
6324 struct todo_item *item;
6325 const char *path;
6326 size_t base_offset = ctx->buf->len;
6329 * If the branch is the current HEAD, then it will be
6330 * updated by the default rebase behavior.
6332 if (head_ref && !strcmp(head_ref, decoration->name)) {
6333 decoration = decoration->next;
6334 continue;
6337 ALLOC_GROW(ctx->items,
6338 ctx->items_nr + 1,
6339 ctx->items_alloc);
6340 item = &ctx->items[ctx->items_nr];
6341 memset(item, 0, sizeof(*item));
6343 /* If the branch is checked out, then leave a comment instead. */
6344 if ((path = branch_checked_out(decoration->name))) {
6345 item->command = TODO_COMMENT;
6346 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6347 decoration->name, path);
6348 } else {
6349 struct string_list_item *sti;
6350 item->command = TODO_UPDATE_REF;
6351 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6353 sti = string_list_insert(&ctx->refs_to_oids,
6354 decoration->name);
6355 sti->util = init_update_ref_record(decoration->name);
6358 item->offset_in_buf = base_offset;
6359 item->arg_offset = base_offset;
6360 item->arg_len = ctx->buf->len - base_offset;
6361 ctx->items_nr++;
6363 decoration = decoration->next;
6366 return 0;
6370 * For each 'pick' command, find out if the commit has a decoration in
6371 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6373 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6375 int i, res;
6376 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6377 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6378 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6379 struct decoration_filter decoration_filter = {
6380 .include_ref_pattern = &decorate_refs_include,
6381 .exclude_ref_pattern = &decorate_refs_exclude,
6382 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6384 struct todo_add_branch_context ctx = {
6385 .buf = &todo_list->buf,
6386 .refs_to_oids = STRING_LIST_INIT_DUP,
6389 ctx.items_alloc = 2 * todo_list->nr + 1;
6390 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6392 string_list_append(&decorate_refs_include, "refs/heads/");
6393 load_ref_decorations(&decoration_filter, 0);
6395 for (i = 0; i < todo_list->nr; ) {
6396 struct todo_item *item = &todo_list->items[i];
6398 /* insert ith item into new list */
6399 ALLOC_GROW(ctx.items,
6400 ctx.items_nr + 1,
6401 ctx.items_alloc);
6403 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6405 if (item->commit) {
6406 ctx.commit = item->commit;
6407 add_decorations_to_list(item->commit, &ctx);
6411 res = write_update_refs_state(&ctx.refs_to_oids);
6413 string_list_clear(&ctx.refs_to_oids, 1);
6415 if (res) {
6416 /* we failed, so clean up the new list. */
6417 free(ctx.items);
6418 return res;
6421 free(todo_list->items);
6422 todo_list->items = ctx.items;
6423 todo_list->nr = ctx.items_nr;
6424 todo_list->alloc = ctx.items_alloc;
6426 return 0;
6429 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6430 const char *shortrevisions, const char *onto_name,
6431 struct commit *onto, const struct object_id *orig_head,
6432 struct string_list *commands, unsigned autosquash,
6433 unsigned update_refs,
6434 struct todo_list *todo_list)
6436 char shortonto[GIT_MAX_HEXSZ + 1];
6437 const char *todo_file = rebase_path_todo();
6438 struct todo_list new_todo = TODO_LIST_INIT;
6439 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6440 struct object_id oid = onto->object.oid;
6441 int res;
6443 repo_find_unique_abbrev_r(r, shortonto, &oid,
6444 DEFAULT_ABBREV);
6446 if (buf->len == 0) {
6447 struct todo_item *item = append_new_todo(todo_list);
6448 item->command = TODO_NOOP;
6449 item->commit = NULL;
6450 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6453 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6454 return -1;
6456 if (autosquash && todo_list_rearrange_squash(todo_list))
6457 return -1;
6459 if (commands->nr)
6460 todo_list_add_exec_commands(todo_list, commands);
6462 if (count_commands(todo_list) == 0) {
6463 apply_autostash(rebase_path_autostash());
6464 sequencer_remove_state(opts);
6466 return error(_("nothing to do"));
6469 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions,
6470 shortonto, flags);
6471 if (res == -1)
6472 return -1;
6473 else if (res == -2) {
6474 apply_autostash(rebase_path_autostash());
6475 sequencer_remove_state(opts);
6477 return -1;
6478 } else if (res == -3) {
6479 apply_autostash(rebase_path_autostash());
6480 sequencer_remove_state(opts);
6481 todo_list_release(&new_todo);
6483 return error(_("nothing to do"));
6484 } else if (res == -4) {
6485 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6486 todo_list_release(&new_todo);
6488 return -1;
6491 /* Expand the commit IDs */
6492 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6493 strbuf_swap(&new_todo.buf, &buf2);
6494 strbuf_release(&buf2);
6495 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6496 new_todo.total_nr = 0;
6497 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0)
6498 BUG("invalid todo list after expanding IDs:\n%s",
6499 new_todo.buf.buf);
6501 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6502 todo_list_release(&new_todo);
6503 return error(_("could not skip unnecessary pick commands"));
6506 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6507 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6508 todo_list_release(&new_todo);
6509 return error_errno(_("could not write '%s'"), todo_file);
6512 res = -1;
6514 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6515 goto cleanup;
6517 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6518 goto cleanup;
6520 todo_list_write_total_nr(&new_todo);
6521 res = pick_commits(r, &new_todo, opts);
6523 cleanup:
6524 todo_list_release(&new_todo);
6526 return res;
6529 struct subject2item_entry {
6530 struct hashmap_entry entry;
6531 int i;
6532 char subject[FLEX_ARRAY];
6535 static int subject2item_cmp(const void *fndata UNUSED,
6536 const struct hashmap_entry *eptr,
6537 const struct hashmap_entry *entry_or_key,
6538 const void *key)
6540 const struct subject2item_entry *a, *b;
6542 a = container_of(eptr, const struct subject2item_entry, entry);
6543 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6545 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6548 define_commit_slab(commit_todo_item, struct todo_item *);
6550 static int skip_fixupish(const char *subject, const char **p) {
6551 return skip_prefix(subject, "fixup! ", p) ||
6552 skip_prefix(subject, "amend! ", p) ||
6553 skip_prefix(subject, "squash! ", p);
6557 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6558 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6559 * after the former, and change "pick" to "fixup"/"squash".
6561 * Note that if the config has specified a custom instruction format, each log
6562 * message will have to be retrieved from the commit (as the oneline in the
6563 * script cannot be trusted) in order to normalize the autosquash arrangement.
6565 int todo_list_rearrange_squash(struct todo_list *todo_list)
6567 struct hashmap subject2item;
6568 int rearranged = 0, *next, *tail, i, nr = 0;
6569 char **subjects;
6570 struct commit_todo_item commit_todo;
6571 struct todo_item *items = NULL;
6573 init_commit_todo_item(&commit_todo);
6575 * The hashmap maps onelines to the respective todo list index.
6577 * If any items need to be rearranged, the next[i] value will indicate
6578 * which item was moved directly after the i'th.
6580 * In that case, last[i] will indicate the index of the latest item to
6581 * be moved to appear after the i'th.
6583 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6584 ALLOC_ARRAY(next, todo_list->nr);
6585 ALLOC_ARRAY(tail, todo_list->nr);
6586 ALLOC_ARRAY(subjects, todo_list->nr);
6587 for (i = 0; i < todo_list->nr; i++) {
6588 struct strbuf buf = STRBUF_INIT;
6589 struct todo_item *item = todo_list->items + i;
6590 const char *commit_buffer, *subject, *p;
6591 size_t subject_len;
6592 int i2 = -1;
6593 struct subject2item_entry *entry;
6595 next[i] = tail[i] = -1;
6596 if (!item->commit || item->command == TODO_DROP) {
6597 subjects[i] = NULL;
6598 continue;
6601 if (is_fixup(item->command)) {
6602 clear_commit_todo_item(&commit_todo);
6603 return error(_("the script was already rearranged."));
6606 repo_parse_commit(the_repository, item->commit);
6607 commit_buffer = repo_logmsg_reencode(the_repository,
6608 item->commit, NULL,
6609 "UTF-8");
6610 find_commit_subject(commit_buffer, &subject);
6611 format_subject(&buf, subject, " ");
6612 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6613 repo_unuse_commit_buffer(the_repository, item->commit,
6614 commit_buffer);
6615 if (skip_fixupish(subject, &p)) {
6616 struct commit *commit2;
6618 for (;;) {
6619 while (isspace(*p))
6620 p++;
6621 if (!skip_fixupish(p, &p))
6622 break;
6625 entry = hashmap_get_entry_from_hash(&subject2item,
6626 strhash(p), p,
6627 struct subject2item_entry,
6628 entry);
6629 if (entry)
6630 /* found by title */
6631 i2 = entry->i;
6632 else if (!strchr(p, ' ') &&
6633 (commit2 =
6634 lookup_commit_reference_by_name(p)) &&
6635 *commit_todo_item_at(&commit_todo, commit2))
6636 /* found by commit name */
6637 i2 = *commit_todo_item_at(&commit_todo, commit2)
6638 - todo_list->items;
6639 else {
6640 /* copy can be a prefix of the commit subject */
6641 for (i2 = 0; i2 < i; i2++)
6642 if (subjects[i2] &&
6643 starts_with(subjects[i2], p))
6644 break;
6645 if (i2 == i)
6646 i2 = -1;
6649 if (i2 >= 0) {
6650 rearranged = 1;
6651 if (starts_with(subject, "fixup!")) {
6652 todo_list->items[i].command = TODO_FIXUP;
6653 } else if (starts_with(subject, "amend!")) {
6654 todo_list->items[i].command = TODO_FIXUP;
6655 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6656 } else {
6657 todo_list->items[i].command = TODO_SQUASH;
6659 if (tail[i2] < 0) {
6660 next[i] = next[i2];
6661 next[i2] = i;
6662 } else {
6663 next[i] = next[tail[i2]];
6664 next[tail[i2]] = i;
6666 tail[i2] = i;
6667 } else if (!hashmap_get_from_hash(&subject2item,
6668 strhash(subject), subject)) {
6669 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6670 entry->i = i;
6671 hashmap_entry_init(&entry->entry,
6672 strhash(entry->subject));
6673 hashmap_put(&subject2item, &entry->entry);
6676 *commit_todo_item_at(&commit_todo, item->commit) = item;
6679 if (rearranged) {
6680 ALLOC_ARRAY(items, todo_list->nr);
6682 for (i = 0; i < todo_list->nr; i++) {
6683 enum todo_command command = todo_list->items[i].command;
6684 int cur = i;
6687 * Initially, all commands are 'pick's. If it is a
6688 * fixup or a squash now, we have rearranged it.
6690 if (is_fixup(command))
6691 continue;
6693 while (cur >= 0) {
6694 items[nr++] = todo_list->items[cur];
6695 cur = next[cur];
6699 assert(nr == todo_list->nr);
6700 todo_list->alloc = nr;
6701 FREE_AND_NULL(todo_list->items);
6702 todo_list->items = items;
6705 free(next);
6706 free(tail);
6707 for (i = 0; i < todo_list->nr; i++)
6708 free(subjects[i]);
6709 free(subjects);
6710 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6712 clear_commit_todo_item(&commit_todo);
6714 return 0;
6717 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6719 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6720 struct object_id cherry_pick_head, rebase_head;
6722 if (file_exists(git_path_seq_dir()))
6723 *whence = FROM_CHERRY_PICK_MULTI;
6724 if (file_exists(rebase_path()) &&
6725 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6726 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6727 oideq(&rebase_head, &cherry_pick_head))
6728 *whence = FROM_REBASE_PICK;
6729 else
6730 *whence = FROM_CHERRY_PICK_SINGLE;
6732 return 1;
6735 return 0;
6738 int sequencer_get_update_refs_state(const char *wt_dir,
6739 struct string_list *refs)
6741 int result = 0;
6742 FILE *fp = NULL;
6743 struct strbuf ref = STRBUF_INIT;
6744 struct strbuf hash = STRBUF_INIT;
6745 struct update_ref_record *rec = NULL;
6747 char *path = rebase_path_update_refs(wt_dir);
6749 fp = fopen(path, "r");
6750 if (!fp)
6751 goto cleanup;
6753 while (strbuf_getline(&ref, fp) != EOF) {
6754 struct string_list_item *item;
6756 CALLOC_ARRAY(rec, 1);
6758 if (strbuf_getline(&hash, fp) == EOF ||
6759 get_oid_hex(hash.buf, &rec->before)) {
6760 warning(_("update-refs file at '%s' is invalid"),
6761 path);
6762 result = -1;
6763 goto cleanup;
6766 if (strbuf_getline(&hash, fp) == EOF ||
6767 get_oid_hex(hash.buf, &rec->after)) {
6768 warning(_("update-refs file at '%s' is invalid"),
6769 path);
6770 result = -1;
6771 goto cleanup;
6774 item = string_list_insert(refs, ref.buf);
6775 item->util = rec;
6776 rec = NULL;
6779 cleanup:
6780 if (fp)
6781 fclose(fp);
6782 free(path);
6783 free(rec);
6784 strbuf_release(&ref);
6785 strbuf_release(&hash);
6786 return result;