Merge branch 'jk/remote-wo-url'
[git.git] / sequencer.c
blobb4f055e5a85962a0e6069e451759914e2a61be7d
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 strbuf_release(&err);
1717 strbuf_release(&commit_msg);
1718 free(amend_author);
1720 return res;
1723 static int write_rebase_head(struct object_id *oid)
1725 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1726 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1727 return error(_("could not update %s"), "REBASE_HEAD");
1729 return 0;
1732 static int do_commit(struct repository *r,
1733 const char *msg_file, const char *author,
1734 struct replay_opts *opts, unsigned int flags,
1735 struct object_id *oid)
1737 int res = 1;
1739 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1740 struct object_id oid;
1741 struct strbuf sb = STRBUF_INIT;
1743 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1744 return error_errno(_("unable to read commit message "
1745 "from '%s'"),
1746 msg_file);
1748 res = try_to_commit(r, msg_file ? &sb : NULL,
1749 author, opts, flags, &oid);
1750 strbuf_release(&sb);
1751 if (!res) {
1752 refs_delete_ref(get_main_ref_store(r), "",
1753 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1754 unlink(git_path_merge_msg(r));
1755 if (!is_rebase_i(opts))
1756 print_commit_summary(r, NULL, &oid,
1757 SUMMARY_SHOW_AUTHOR_DATE);
1758 return res;
1761 if (res == 1) {
1762 if (is_rebase_i(opts) && oid)
1763 if (write_rebase_head(oid))
1764 return -1;
1765 return run_git_commit(msg_file, opts, flags);
1768 return res;
1771 static int is_original_commit_empty(struct commit *commit)
1773 const struct object_id *ptree_oid;
1775 if (repo_parse_commit(the_repository, commit))
1776 return error(_("could not parse commit %s"),
1777 oid_to_hex(&commit->object.oid));
1778 if (commit->parents) {
1779 struct commit *parent = commit->parents->item;
1780 if (repo_parse_commit(the_repository, parent))
1781 return error(_("could not parse parent commit %s"),
1782 oid_to_hex(&parent->object.oid));
1783 ptree_oid = get_commit_tree_oid(parent);
1784 } else {
1785 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1788 return oideq(ptree_oid, get_commit_tree_oid(commit));
1792 * Should empty commits be allowed? Return status:
1793 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1794 * 0: Halt on empty commit
1795 * 1: Allow empty commit
1796 * 2: Drop empty commit
1798 static int allow_empty(struct repository *r,
1799 struct replay_opts *opts,
1800 struct commit *commit)
1802 int index_unchanged, originally_empty;
1805 * For a commit that is initially empty, allow_empty determines if it
1806 * should be kept or not
1808 * For a commit that becomes empty, keep_redundant_commits and
1809 * drop_redundant_commits determine whether the commit should be kept or
1810 * dropped. If neither is specified, halt.
1812 index_unchanged = is_index_unchanged(r);
1813 if (index_unchanged < 0)
1814 return index_unchanged;
1815 if (!index_unchanged)
1816 return 0; /* we do not have to say --allow-empty */
1818 originally_empty = is_original_commit_empty(commit);
1819 if (originally_empty < 0)
1820 return originally_empty;
1821 if (originally_empty)
1822 return opts->allow_empty;
1823 else if (opts->keep_redundant_commits)
1824 return 1;
1825 else if (opts->drop_redundant_commits)
1826 return 2;
1827 else
1828 return 0;
1831 static struct {
1832 char c;
1833 const char *str;
1834 } todo_command_info[] = {
1835 [TODO_PICK] = { 'p', "pick" },
1836 [TODO_REVERT] = { 0, "revert" },
1837 [TODO_EDIT] = { 'e', "edit" },
1838 [TODO_REWORD] = { 'r', "reword" },
1839 [TODO_FIXUP] = { 'f', "fixup" },
1840 [TODO_SQUASH] = { 's', "squash" },
1841 [TODO_EXEC] = { 'x', "exec" },
1842 [TODO_BREAK] = { 'b', "break" },
1843 [TODO_LABEL] = { 'l', "label" },
1844 [TODO_RESET] = { 't', "reset" },
1845 [TODO_MERGE] = { 'm', "merge" },
1846 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1847 [TODO_NOOP] = { 0, "noop" },
1848 [TODO_DROP] = { 'd', "drop" },
1849 [TODO_COMMENT] = { 0, NULL },
1852 static const char *command_to_string(const enum todo_command command)
1854 if (command < TODO_COMMENT)
1855 return todo_command_info[command].str;
1856 if (command == TODO_COMMENT)
1857 return comment_line_str;
1858 die(_("unknown command: %d"), command);
1861 static char command_to_char(const enum todo_command command)
1863 if (command < TODO_COMMENT)
1864 return todo_command_info[command].c;
1865 return 0;
1868 static int is_noop(const enum todo_command command)
1870 return TODO_NOOP <= command;
1873 static int is_fixup(enum todo_command command)
1875 return command == TODO_FIXUP || command == TODO_SQUASH;
1878 /* Does this command create a (non-merge) commit? */
1879 static int is_pick_or_similar(enum todo_command command)
1881 switch (command) {
1882 case TODO_PICK:
1883 case TODO_REVERT:
1884 case TODO_EDIT:
1885 case TODO_REWORD:
1886 case TODO_FIXUP:
1887 case TODO_SQUASH:
1888 return 1;
1889 default:
1890 return 0;
1894 enum todo_item_flags {
1895 TODO_EDIT_MERGE_MSG = (1 << 0),
1896 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1897 TODO_EDIT_FIXUP_MSG = (1 << 2),
1900 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1901 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1902 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1903 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1904 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1906 static int is_fixup_flag(enum todo_command command, unsigned flag)
1908 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1909 (flag & TODO_EDIT_FIXUP_MSG));
1913 * Wrapper around strbuf_add_commented_lines() which avoids double
1914 * commenting commit subjects.
1916 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1918 const char *s = str;
1919 while (starts_with_mem(s, len, comment_line_str)) {
1920 size_t count;
1921 const char *n = memchr(s, '\n', len);
1922 if (!n)
1923 count = len;
1924 else
1925 count = n - s + 1;
1926 strbuf_add(buf, s, count);
1927 s += count;
1928 len -= count;
1930 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1933 /* Does the current fixup chain contain a squash command? */
1934 static int seen_squash(struct replay_ctx *ctx)
1936 return starts_with(ctx->current_fixups.buf, "squash") ||
1937 strstr(ctx->current_fixups.buf, "\nsquash");
1940 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1942 strbuf_setlen(buf1, 2);
1943 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1944 strbuf_addch(buf1, '\n');
1945 strbuf_setlen(buf2, 2);
1946 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1947 strbuf_addch(buf2, '\n');
1951 * Comment out any un-commented commit messages, updating the message comments
1952 * to say they will be skipped but do not comment out the empty lines that
1953 * surround commit messages and their comments.
1955 static void update_squash_message_for_fixup(struct strbuf *msg)
1957 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1958 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1959 const char *s, *start;
1960 char *orig_msg;
1961 size_t orig_msg_len;
1962 int i = 1;
1964 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1965 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1966 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1967 while (s) {
1968 const char *next;
1969 size_t off;
1970 if (skip_prefix(s, buf1.buf, &next)) {
1972 * Copy the last message, preserving the blank line
1973 * preceding the current line
1975 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1976 copy_lines(msg, start, s - start - off);
1977 if (off)
1978 strbuf_addch(msg, '\n');
1980 * The next message needs to be commented out but the
1981 * message header is already commented out so just copy
1982 * it and the blank line that follows it.
1984 strbuf_addbuf(msg, &buf2);
1985 if (*next == '\n')
1986 strbuf_addch(msg, *next++);
1987 start = s = next;
1988 copy_lines = add_commented_lines;
1989 update_comment_bufs(&buf1, &buf2, ++i);
1990 } else if (skip_prefix(s, buf2.buf, &next)) {
1991 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1992 copy_lines(msg, start, s - start - off);
1993 start = s - off;
1994 s = next;
1995 copy_lines = strbuf_add;
1996 update_comment_bufs(&buf1, &buf2, ++i);
1997 } else {
1998 s = strchr(s, '\n');
1999 if (s)
2000 s++;
2003 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2004 free(orig_msg);
2005 strbuf_release(&buf1);
2006 strbuf_release(&buf2);
2009 static int append_squash_message(struct strbuf *buf, const char *body,
2010 enum todo_command command, struct replay_opts *opts,
2011 unsigned flag)
2013 struct replay_ctx *ctx = opts->ctx;
2014 const char *fixup_msg;
2015 size_t commented_len = 0, fixup_off;
2017 * amend is non-interactive and not normally used with fixup!
2018 * or squash! commits, so only comment out those subjects when
2019 * squashing commit messages.
2021 if (starts_with(body, "amend!") ||
2022 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2023 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2024 commented_len = commit_subject_length(body);
2026 strbuf_addf(buf, "\n%s ", comment_line_str);
2027 strbuf_addf(buf, _(nth_commit_msg_fmt),
2028 ++ctx->current_fixup_count + 1);
2029 strbuf_addstr(buf, "\n\n");
2030 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2031 /* buf->buf may be reallocated so store an offset into the buffer */
2032 fixup_off = buf->len;
2033 strbuf_addstr(buf, body + commented_len);
2035 /* fixup -C after squash behaves like squash */
2036 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2038 * We're replacing the commit message so we need to
2039 * append the Signed-off-by: trailer if the user
2040 * requested '--signoff'.
2042 if (opts->signoff)
2043 append_signoff(buf, 0, 0);
2045 if ((command == TODO_FIXUP) &&
2046 (flag & TODO_REPLACE_FIXUP_MSG) &&
2047 (file_exists(rebase_path_fixup_msg()) ||
2048 !file_exists(rebase_path_squash_msg()))) {
2049 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2050 if (write_message(fixup_msg, strlen(fixup_msg),
2051 rebase_path_fixup_msg(), 0) < 0)
2052 return error(_("cannot write '%s'"),
2053 rebase_path_fixup_msg());
2054 } else {
2055 unlink(rebase_path_fixup_msg());
2057 } else {
2058 unlink(rebase_path_fixup_msg());
2061 return 0;
2064 static int update_squash_messages(struct repository *r,
2065 enum todo_command command,
2066 struct commit *commit,
2067 struct replay_opts *opts,
2068 unsigned flag)
2070 struct replay_ctx *ctx = opts->ctx;
2071 struct strbuf buf = STRBUF_INIT;
2072 int res = 0;
2073 const char *message, *body;
2074 const char *encoding = get_commit_output_encoding();
2076 if (ctx->current_fixup_count > 0) {
2077 struct strbuf header = STRBUF_INIT;
2078 char *eol;
2080 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2081 return error(_("could not read '%s'"),
2082 rebase_path_squash_msg());
2084 eol = !starts_with(buf.buf, comment_line_str) ?
2085 buf.buf : strchrnul(buf.buf, '\n');
2087 strbuf_addf(&header, "%s ", comment_line_str);
2088 strbuf_addf(&header, _(combined_commit_msg_fmt),
2089 ctx->current_fixup_count + 2);
2090 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2091 strbuf_release(&header);
2092 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2093 update_squash_message_for_fixup(&buf);
2094 } else {
2095 struct object_id head;
2096 struct commit *head_commit;
2097 const char *head_message, *body;
2099 if (repo_get_oid(r, "HEAD", &head))
2100 return error(_("need a HEAD to fixup"));
2101 if (!(head_commit = lookup_commit_reference(r, &head)))
2102 return error(_("could not read HEAD"));
2103 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2104 encoding)))
2105 return error(_("could not read HEAD's commit message"));
2107 find_commit_subject(head_message, &body);
2108 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2109 rebase_path_fixup_msg(), 0) < 0) {
2110 repo_unuse_commit_buffer(r, head_commit, head_message);
2111 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2113 strbuf_addf(&buf, "%s ", comment_line_str);
2114 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2115 strbuf_addf(&buf, "\n%s ", comment_line_str);
2116 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2117 _(skip_first_commit_msg_str) :
2118 _(first_commit_msg_str));
2119 strbuf_addstr(&buf, "\n\n");
2120 if (is_fixup_flag(command, flag))
2121 strbuf_add_commented_lines(&buf, body, strlen(body),
2122 comment_line_str);
2123 else
2124 strbuf_addstr(&buf, body);
2126 repo_unuse_commit_buffer(r, head_commit, head_message);
2129 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2130 return error(_("could not read commit message of %s"),
2131 oid_to_hex(&commit->object.oid));
2132 find_commit_subject(message, &body);
2134 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2135 res = append_squash_message(&buf, body, command, opts, flag);
2136 } else if (command == TODO_FIXUP) {
2137 strbuf_addf(&buf, "\n%s ", comment_line_str);
2138 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2139 ++ctx->current_fixup_count + 1);
2140 strbuf_addstr(&buf, "\n\n");
2141 strbuf_add_commented_lines(&buf, body, strlen(body),
2142 comment_line_str);
2143 } else
2144 return error(_("unknown command: %d"), command);
2145 repo_unuse_commit_buffer(r, commit, message);
2147 if (!res)
2148 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2150 strbuf_release(&buf);
2152 if (!res) {
2153 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2154 ctx->current_fixups.len ? "\n" : "",
2155 command_to_string(command),
2156 oid_to_hex(&commit->object.oid));
2157 res = write_message(ctx->current_fixups.buf,
2158 ctx->current_fixups.len,
2159 rebase_path_current_fixups(), 0);
2162 return res;
2165 static void flush_rewritten_pending(void)
2167 struct strbuf buf = STRBUF_INIT;
2168 struct object_id newoid;
2169 FILE *out;
2171 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2172 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2173 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2174 char *bol = buf.buf, *eol;
2176 while (*bol) {
2177 eol = strchrnul(bol, '\n');
2178 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2179 bol, oid_to_hex(&newoid));
2180 if (!*eol)
2181 break;
2182 bol = eol + 1;
2184 fclose(out);
2185 unlink(rebase_path_rewritten_pending());
2187 strbuf_release(&buf);
2190 static void record_in_rewritten(struct object_id *oid,
2191 enum todo_command next_command)
2193 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2195 if (!out)
2196 return;
2198 fprintf(out, "%s\n", oid_to_hex(oid));
2199 fclose(out);
2201 if (!is_fixup(next_command))
2202 flush_rewritten_pending();
2205 static int should_edit(struct replay_opts *opts) {
2206 if (opts->edit < 0)
2208 * Note that we only handle the case of non-conflicted
2209 * commits; continue_single_pick() handles the conflicted
2210 * commits itself instead of calling this function.
2212 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2213 return opts->edit;
2216 static void refer_to_commit(struct replay_opts *opts,
2217 struct strbuf *msgbuf, struct commit *commit)
2219 if (opts->commit_use_reference) {
2220 struct pretty_print_context ctx = {
2221 .abbrev = DEFAULT_ABBREV,
2222 .date_mode.type = DATE_SHORT,
2224 repo_format_commit_message(the_repository, commit,
2225 "%h (%s, %ad)", msgbuf, &ctx);
2226 } else {
2227 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2231 static int do_pick_commit(struct repository *r,
2232 struct todo_item *item,
2233 struct replay_opts *opts,
2234 int final_fixup, int *check_todo)
2236 struct replay_ctx *ctx = opts->ctx;
2237 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2238 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2239 struct object_id head;
2240 struct commit *base, *next, *parent;
2241 const char *base_label, *next_label;
2242 char *author = NULL;
2243 struct commit_message msg = { NULL, NULL, NULL, NULL };
2244 int res, unborn = 0, reword = 0, allow, drop_commit;
2245 enum todo_command command = item->command;
2246 struct commit *commit = item->commit;
2248 if (opts->no_commit) {
2250 * We do not intend to commit immediately. We just want to
2251 * merge the differences in, so let's compute the tree
2252 * that represents the "current" state for the merge machinery
2253 * to work on.
2255 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2256 return error(_("your index file is unmerged."));
2257 } else {
2258 unborn = repo_get_oid(r, "HEAD", &head);
2259 /* Do we want to generate a root commit? */
2260 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2261 oideq(&head, &opts->squash_onto)) {
2262 if (is_fixup(command))
2263 return error(_("cannot fixup root commit"));
2264 flags |= CREATE_ROOT_COMMIT;
2265 unborn = 1;
2266 } else if (unborn)
2267 oidcpy(&head, the_hash_algo->empty_tree);
2268 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD",
2269 NULL, 0))
2270 return error_dirty_index(r, opts);
2272 discard_index(r->index);
2274 if (!commit->parents)
2275 parent = NULL;
2276 else if (commit->parents->next) {
2277 /* Reverting or cherry-picking a merge commit */
2278 int cnt;
2279 struct commit_list *p;
2281 if (!opts->mainline)
2282 return error(_("commit %s is a merge but no -m option was given."),
2283 oid_to_hex(&commit->object.oid));
2285 for (cnt = 1, p = commit->parents;
2286 cnt != opts->mainline && p;
2287 cnt++)
2288 p = p->next;
2289 if (cnt != opts->mainline || !p)
2290 return error(_("commit %s does not have parent %d"),
2291 oid_to_hex(&commit->object.oid), opts->mainline);
2292 parent = p->item;
2293 } else if (1 < opts->mainline)
2295 * Non-first parent explicitly specified as mainline for
2296 * non-merge commit
2298 return error(_("commit %s does not have parent %d"),
2299 oid_to_hex(&commit->object.oid), opts->mainline);
2300 else
2301 parent = commit->parents->item;
2303 if (get_message(commit, &msg) != 0)
2304 return error(_("cannot get commit message for %s"),
2305 oid_to_hex(&commit->object.oid));
2307 if (opts->allow_ff && !is_fixup(command) &&
2308 ((parent && oideq(&parent->object.oid, &head)) ||
2309 (!parent && unborn))) {
2310 if (is_rebase_i(opts))
2311 write_author_script(msg.message);
2312 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2313 opts);
2314 if (res || command != TODO_REWORD)
2315 goto leave;
2316 reword = 1;
2317 msg_file = NULL;
2318 goto fast_forward_edit;
2320 if (parent && repo_parse_commit(r, parent) < 0)
2321 /* TRANSLATORS: The first %s will be a "todo" command like
2322 "revert" or "pick", the second %s a SHA1. */
2323 return error(_("%s: cannot parse parent commit %s"),
2324 command_to_string(command),
2325 oid_to_hex(&parent->object.oid));
2328 * "commit" is an existing commit. We would want to apply
2329 * the difference it introduces since its first parent "prev"
2330 * on top of the current HEAD if we are cherry-pick. Or the
2331 * reverse of it if we are revert.
2334 if (command == TODO_REVERT) {
2335 const char *orig_subject;
2337 base = commit;
2338 base_label = msg.label;
2339 next = parent;
2340 next_label = msg.parent_label;
2341 if (opts->commit_use_reference) {
2342 strbuf_addstr(&ctx->message,
2343 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2344 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2346 * We don't touch pre-existing repeated reverts, because
2347 * theoretically these can be nested arbitrarily deeply,
2348 * thus requiring excessive complexity to deal with.
2350 !starts_with(orig_subject, "Revert \"")) {
2351 strbuf_addstr(&ctx->message, "Reapply \"");
2352 strbuf_addstr(&ctx->message, orig_subject);
2353 } else {
2354 strbuf_addstr(&ctx->message, "Revert \"");
2355 strbuf_addstr(&ctx->message, msg.subject);
2356 strbuf_addstr(&ctx->message, "\"");
2358 strbuf_addstr(&ctx->message, "\n\nThis reverts commit ");
2359 refer_to_commit(opts, &ctx->message, commit);
2361 if (commit->parents && commit->parents->next) {
2362 strbuf_addstr(&ctx->message, ", reversing\nchanges made to ");
2363 refer_to_commit(opts, &ctx->message, parent);
2365 strbuf_addstr(&ctx->message, ".\n");
2366 } else {
2367 const char *p;
2369 base = parent;
2370 base_label = msg.parent_label;
2371 next = commit;
2372 next_label = msg.label;
2374 /* Append the commit log message to ctx->message. */
2375 if (find_commit_subject(msg.message, &p))
2376 strbuf_addstr(&ctx->message, p);
2378 if (opts->record_origin) {
2379 strbuf_complete_line(&ctx->message);
2380 if (!has_conforming_footer(&ctx->message, NULL, 0))
2381 strbuf_addch(&ctx->message, '\n');
2382 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2383 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid));
2384 strbuf_addstr(&ctx->message, ")\n");
2386 if (!is_fixup(command))
2387 author = get_author(msg.message);
2389 ctx->have_message = 1;
2391 if (command == TODO_REWORD)
2392 reword = 1;
2393 else if (is_fixup(command)) {
2394 if (update_squash_messages(r, command, commit,
2395 opts, item->flags)) {
2396 res = -1;
2397 goto leave;
2399 flags |= AMEND_MSG;
2400 if (!final_fixup)
2401 msg_file = rebase_path_squash_msg();
2402 else if (file_exists(rebase_path_fixup_msg())) {
2403 flags |= VERBATIM_MSG;
2404 msg_file = rebase_path_fixup_msg();
2405 } else {
2406 const char *dest = git_path_squash_msg(r);
2407 unlink(dest);
2408 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2409 res = error(_("could not copy '%s' to '%s'"),
2410 rebase_path_squash_msg(), dest);
2411 goto leave;
2413 unlink(git_path_merge_msg(r));
2414 msg_file = dest;
2415 flags |= EDIT_MSG;
2419 if (opts->signoff && !is_fixup(command))
2420 append_signoff(&ctx->message, 0, 0);
2422 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2423 res = -1;
2424 else if (!opts->strategy ||
2425 !strcmp(opts->strategy, "recursive") ||
2426 !strcmp(opts->strategy, "ort") ||
2427 command == TODO_REVERT) {
2428 res = do_recursive_merge(r, base, next, base_label, next_label,
2429 &head, &ctx->message, opts);
2430 if (res < 0)
2431 goto leave;
2433 res |= write_message(ctx->message.buf, ctx->message.len,
2434 git_path_merge_msg(r), 0);
2435 } else {
2436 struct commit_list *common = NULL;
2437 struct commit_list *remotes = NULL;
2439 res = write_message(ctx->message.buf, ctx->message.len,
2440 git_path_merge_msg(r), 0);
2442 commit_list_insert(base, &common);
2443 commit_list_insert(next, &remotes);
2444 res |= try_merge_command(r, opts->strategy,
2445 opts->xopts.nr, opts->xopts.v,
2446 common, oid_to_hex(&head), remotes);
2447 free_commit_list(common);
2448 free_commit_list(remotes);
2452 * If the merge was clean or if it failed due to conflict, we write
2453 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2454 * However, if the merge did not even start, then we don't want to
2455 * write it at all.
2457 if ((command == TODO_PICK || command == TODO_REWORD ||
2458 command == TODO_EDIT) && !opts->no_commit &&
2459 (res == 0 || res == 1) &&
2460 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2461 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2462 res = -1;
2463 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2464 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2465 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2466 res = -1;
2468 if (res) {
2469 error(command == TODO_REVERT
2470 ? _("could not revert %s... %s")
2471 : _("could not apply %s... %s"),
2472 short_commit_name(r, commit), msg.subject);
2473 print_advice(r, res == 1, opts);
2474 repo_rerere(r, opts->allow_rerere_auto);
2475 goto leave;
2478 drop_commit = 0;
2479 allow = allow_empty(r, opts, commit);
2480 if (allow < 0) {
2481 res = allow;
2482 goto leave;
2483 } else if (allow == 1) {
2484 flags |= ALLOW_EMPTY;
2485 } else if (allow == 2) {
2486 drop_commit = 1;
2487 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2488 NULL, REF_NO_DEREF);
2489 unlink(git_path_merge_msg(r));
2490 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2491 NULL, REF_NO_DEREF);
2492 fprintf(stderr,
2493 _("dropping %s %s -- patch contents already upstream\n"),
2494 oid_to_hex(&commit->object.oid), msg.subject);
2495 } /* else allow == 0 and there's nothing special to do */
2496 if (!opts->no_commit && !drop_commit) {
2497 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2498 res = do_commit(r, msg_file, author, opts, flags,
2499 commit? &commit->object.oid : NULL);
2500 else
2501 res = error(_("unable to parse commit author"));
2502 *check_todo = !!(flags & EDIT_MSG);
2503 if (!res && reword) {
2504 fast_forward_edit:
2505 res = run_git_commit(NULL, opts, EDIT_MSG |
2506 VERIFY_MSG | AMEND_MSG |
2507 (flags & ALLOW_EMPTY));
2508 *check_todo = 1;
2513 if (!res && final_fixup) {
2514 unlink(rebase_path_fixup_msg());
2515 unlink(rebase_path_squash_msg());
2516 unlink(rebase_path_current_fixups());
2517 strbuf_reset(&ctx->current_fixups);
2518 ctx->current_fixup_count = 0;
2521 leave:
2522 free_message(commit, &msg);
2523 free(author);
2524 update_abort_safety_file();
2526 return res;
2529 static int prepare_revs(struct replay_opts *opts)
2532 * picking (but not reverting) ranges (but not individual revisions)
2533 * should be done in reverse
2535 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2536 opts->revs->reverse ^= 1;
2538 if (prepare_revision_walk(opts->revs))
2539 return error(_("revision walk setup failed"));
2541 return 0;
2544 static int read_and_refresh_cache(struct repository *r,
2545 struct replay_opts *opts)
2547 struct lock_file index_lock = LOCK_INIT;
2548 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2549 if (repo_read_index(r) < 0) {
2550 rollback_lock_file(&index_lock);
2551 return error(_("git %s: failed to read the index"),
2552 action_name(opts));
2554 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2556 if (index_fd >= 0) {
2557 if (write_locked_index(r->index, &index_lock,
2558 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2559 return error(_("git %s: failed to refresh the index"),
2560 action_name(opts));
2565 * If we are resolving merges in any way other than "ort", then
2566 * expand the sparse index.
2568 if (opts->strategy && strcmp(opts->strategy, "ort"))
2569 ensure_full_index(r->index);
2570 return 0;
2573 void todo_list_release(struct todo_list *todo_list)
2575 strbuf_release(&todo_list->buf);
2576 FREE_AND_NULL(todo_list->items);
2577 todo_list->nr = todo_list->alloc = 0;
2580 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2582 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2583 return todo_list->items + todo_list->nr++;
2586 const char *todo_item_get_arg(struct todo_list *todo_list,
2587 struct todo_item *item)
2589 return todo_list->buf.buf + item->arg_offset;
2592 static int is_command(enum todo_command command, const char **bol)
2594 const char *str = todo_command_info[command].str;
2595 const char nick = todo_command_info[command].c;
2596 const char *p = *bol;
2598 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2599 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2600 (*bol = p);
2603 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2605 switch (command) {
2606 case TODO_LABEL:
2608 * '#' is not a valid label as the merge command uses it to
2609 * separate merge parents from the commit subject.
2611 if (!strcmp(arg, "#") ||
2612 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2613 return error(_("'%s' is not a valid label"), arg);
2614 break;
2616 case TODO_UPDATE_REF:
2617 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2618 return error(_("'%s' is not a valid refname"), arg);
2619 if (check_refname_format(arg, 0))
2620 return error(_("update-ref requires a fully qualified "
2621 "refname e.g. refs/heads/%s"), arg);
2622 break;
2624 default:
2625 BUG("unexpected todo_command");
2628 return 0;
2631 static int check_merge_commit_insn(enum todo_command command)
2633 switch(command) {
2634 case TODO_PICK:
2635 error(_("'%s' does not accept merge commits"),
2636 todo_command_info[command].str);
2637 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2639 * TRANSLATORS: 'pick' and 'merge -C' should not be
2640 * translated.
2642 "'pick' does not take a merge commit. If you wanted to\n"
2643 "replay the merge, use 'merge -C' on the commit."));
2644 return -1;
2646 case TODO_REWORD:
2647 error(_("'%s' does not accept merge commits"),
2648 todo_command_info[command].str);
2649 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2651 * TRANSLATORS: 'reword' and 'merge -c' should not be
2652 * translated.
2654 "'reword' does not take a merge commit. If you wanted to\n"
2655 "replay the merge and reword the commit message, use\n"
2656 "'merge -c' on the commit"));
2657 return -1;
2659 case TODO_EDIT:
2660 error(_("'%s' does not accept merge commits"),
2661 todo_command_info[command].str);
2662 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2664 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2665 * not be translated.
2667 "'edit' does not take a merge commit. If you wanted to\n"
2668 "replay the merge, use 'merge -C' on the commit, and then\n"
2669 "'break' to give the control back to you so that you can\n"
2670 "do 'git commit --amend && git rebase --continue'."));
2671 return -1;
2673 case TODO_FIXUP:
2674 case TODO_SQUASH:
2675 return error(_("cannot squash merge commit into another commit"));
2677 case TODO_MERGE:
2678 return 0;
2680 default:
2681 BUG("unexpected todo_command");
2685 static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2686 struct todo_item *item, const char *buf,
2687 const char *bol, char *eol)
2689 struct object_id commit_oid;
2690 char *end_of_object_name;
2691 int i, saved, status, padding;
2693 item->flags = 0;
2695 /* left-trim */
2696 bol += strspn(bol, " \t");
2698 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
2699 item->command = TODO_COMMENT;
2700 item->commit = NULL;
2701 item->arg_offset = bol - buf;
2702 item->arg_len = eol - bol;
2703 return 0;
2706 for (i = 0; i < TODO_COMMENT; i++)
2707 if (is_command(i, &bol)) {
2708 item->command = i;
2709 break;
2711 if (i >= TODO_COMMENT)
2712 return error(_("invalid command '%.*s'"),
2713 (int)strcspn(bol, " \t\r\n"), bol);
2715 /* Eat up extra spaces/ tabs before object name */
2716 padding = strspn(bol, " \t");
2717 bol += padding;
2719 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2720 if (bol != eol)
2721 return error(_("%s does not accept arguments: '%s'"),
2722 command_to_string(item->command), bol);
2723 item->commit = NULL;
2724 item->arg_offset = bol - buf;
2725 item->arg_len = eol - bol;
2726 return 0;
2729 if (!padding)
2730 return error(_("missing arguments for %s"),
2731 command_to_string(item->command));
2733 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2734 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2735 int ret = 0;
2737 item->commit = NULL;
2738 item->arg_offset = bol - buf;
2739 item->arg_len = (int)(eol - bol);
2740 if (item->command == TODO_LABEL ||
2741 item->command == TODO_UPDATE_REF) {
2742 saved = *eol;
2743 *eol = '\0';
2744 ret = check_label_or_ref_arg(item->command, bol);
2745 *eol = saved;
2747 return ret;
2750 if (item->command == TODO_FIXUP) {
2751 if (skip_prefix(bol, "-C", &bol)) {
2752 bol += strspn(bol, " \t");
2753 item->flags |= TODO_REPLACE_FIXUP_MSG;
2754 } else if (skip_prefix(bol, "-c", &bol)) {
2755 bol += strspn(bol, " \t");
2756 item->flags |= TODO_EDIT_FIXUP_MSG;
2760 if (item->command == TODO_MERGE) {
2761 if (skip_prefix(bol, "-C", &bol))
2762 bol += strspn(bol, " \t");
2763 else if (skip_prefix(bol, "-c", &bol)) {
2764 bol += strspn(bol, " \t");
2765 item->flags |= TODO_EDIT_MERGE_MSG;
2766 } else {
2767 item->flags |= TODO_EDIT_MERGE_MSG;
2768 item->commit = NULL;
2769 item->arg_offset = bol - buf;
2770 item->arg_len = (int)(eol - bol);
2771 return 0;
2775 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2776 saved = *end_of_object_name;
2777 *end_of_object_name = '\0';
2778 status = repo_get_oid(r, bol, &commit_oid);
2779 if (status < 0)
2780 error(_("could not parse '%s'"), bol); /* return later */
2781 *end_of_object_name = saved;
2783 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2784 item->arg_offset = bol - buf;
2785 item->arg_len = (int)(eol - bol);
2787 if (status < 0)
2788 return status;
2790 item->commit = lookup_commit_reference(r, &commit_oid);
2791 if (!item->commit)
2792 return -1;
2793 if (is_rebase_i(opts) &&
2794 item->commit->parents && item->commit->parents->next)
2795 return check_merge_commit_insn(item->command);
2796 return 0;
2799 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2801 const char *todo_file, *bol;
2802 struct strbuf buf = STRBUF_INIT;
2803 int ret = 0;
2805 todo_file = git_path_todo_file();
2806 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2807 if (errno == ENOENT || errno == ENOTDIR)
2808 return -1;
2809 else
2810 return error_errno("unable to open '%s'", todo_file);
2812 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2813 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2814 *action = REPLAY_PICK;
2815 else if (is_command(TODO_REVERT, &bol) &&
2816 (*bol == ' ' || *bol == '\t'))
2817 *action = REPLAY_REVERT;
2818 else
2819 ret = -1;
2821 strbuf_release(&buf);
2823 return ret;
2826 int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2827 char *buf, struct todo_list *todo_list)
2829 struct todo_item *item;
2830 char *p = buf, *next_p;
2831 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2833 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2835 for (i = 1; *p; i++, p = next_p) {
2836 char *eol = strchrnul(p, '\n');
2838 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2840 if (p != eol && eol[-1] == '\r')
2841 eol--; /* strip Carriage Return */
2843 item = append_new_todo(todo_list);
2844 item->offset_in_buf = p - todo_list->buf.buf;
2845 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2846 res = error(_("invalid line %d: %.*s"),
2847 i, (int)(eol - p), p);
2848 item->command = TODO_COMMENT + 1;
2849 item->arg_offset = p - buf;
2850 item->arg_len = (int)(eol - p);
2851 item->commit = NULL;
2854 if (item->command != TODO_COMMENT)
2855 todo_list->total_nr++;
2857 if (fixup_okay)
2858 ; /* do nothing */
2859 else if (is_fixup(item->command))
2860 res = error(_("cannot '%s' without a previous commit"),
2861 command_to_string(item->command));
2862 else if (!is_noop(item->command))
2863 fixup_okay = 1;
2866 return res;
2869 static int count_commands(struct todo_list *todo_list)
2871 int count = 0, i;
2873 for (i = 0; i < todo_list->nr; i++)
2874 if (todo_list->items[i].command != TODO_COMMENT)
2875 count++;
2877 return count;
2880 static int get_item_line_offset(struct todo_list *todo_list, int index)
2882 return index < todo_list->nr ?
2883 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2886 static const char *get_item_line(struct todo_list *todo_list, int index)
2888 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2891 static int get_item_line_length(struct todo_list *todo_list, int index)
2893 return get_item_line_offset(todo_list, index + 1)
2894 - get_item_line_offset(todo_list, index);
2897 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2899 int fd;
2900 ssize_t len;
2902 fd = open(path, O_RDONLY);
2903 if (fd < 0)
2904 return error_errno(_("could not open '%s'"), path);
2905 len = strbuf_read(sb, fd, 0);
2906 close(fd);
2907 if (len < 0)
2908 return error(_("could not read '%s'."), path);
2909 return len;
2912 static int have_finished_the_last_pick(void)
2914 struct strbuf buf = STRBUF_INIT;
2915 const char *eol;
2916 const char *todo_path = git_path_todo_file();
2917 int ret = 0;
2919 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2920 if (errno == ENOENT) {
2921 return 0;
2922 } else {
2923 error_errno("unable to open '%s'", todo_path);
2924 return 0;
2927 /* If there is only one line then we are done */
2928 eol = strchr(buf.buf, '\n');
2929 if (!eol || !eol[1])
2930 ret = 1;
2932 strbuf_release(&buf);
2934 return ret;
2937 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2939 struct replay_opts opts = REPLAY_OPTS_INIT;
2940 int need_cleanup = 0;
2942 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2943 if (!refs_delete_ref(get_main_ref_store(r), "",
2944 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2945 verbose)
2946 warning(_("cancelling a cherry picking in progress"));
2947 opts.action = REPLAY_PICK;
2948 need_cleanup = 1;
2951 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2952 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2953 NULL, REF_NO_DEREF) &&
2954 verbose)
2955 warning(_("cancelling a revert in progress"));
2956 opts.action = REPLAY_REVERT;
2957 need_cleanup = 1;
2960 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2961 NULL, REF_NO_DEREF);
2963 if (!need_cleanup)
2964 goto out;
2966 if (!have_finished_the_last_pick())
2967 goto out;
2969 sequencer_remove_state(&opts);
2970 out:
2971 replay_opts_release(&opts);
2974 static void todo_list_write_total_nr(struct todo_list *todo_list)
2976 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2978 if (f) {
2979 fprintf(f, "%d\n", todo_list->total_nr);
2980 fclose(f);
2984 static int read_populate_todo(struct repository *r,
2985 struct todo_list *todo_list,
2986 struct replay_opts *opts)
2988 const char *todo_file = get_todo_path(opts);
2989 int res;
2991 strbuf_reset(&todo_list->buf);
2992 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2993 return -1;
2995 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
2996 if (res) {
2997 if (is_rebase_i(opts))
2998 return error(_("please fix this using "
2999 "'git rebase --edit-todo'."));
3000 return error(_("unusable instruction sheet: '%s'"), todo_file);
3003 if (!todo_list->nr &&
3004 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3005 return error(_("no commits parsed."));
3007 if (!is_rebase_i(opts)) {
3008 enum todo_command valid =
3009 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3010 int i;
3012 for (i = 0; i < todo_list->nr; i++)
3013 if (valid == todo_list->items[i].command)
3014 continue;
3015 else if (valid == TODO_PICK)
3016 return error(_("cannot cherry-pick during a revert."));
3017 else
3018 return error(_("cannot revert during a cherry-pick."));
3021 if (is_rebase_i(opts)) {
3022 struct todo_list done = TODO_LIST_INIT;
3024 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3025 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3026 todo_list->done_nr = count_commands(&done);
3027 else
3028 todo_list->done_nr = 0;
3030 todo_list->total_nr = todo_list->done_nr
3031 + count_commands(todo_list);
3032 todo_list_release(&done);
3034 todo_list_write_total_nr(todo_list);
3037 return 0;
3040 static int git_config_string_dup(char **dest,
3041 const char *var, const char *value)
3043 if (!value)
3044 return config_error_nonbool(var);
3045 free(*dest);
3046 *dest = xstrdup(value);
3047 return 0;
3050 static int populate_opts_cb(const char *key, const char *value,
3051 const struct config_context *ctx,
3052 void *data)
3054 struct replay_opts *opts = data;
3055 int error_flag = 1;
3057 if (!value)
3058 error_flag = 0;
3059 else if (!strcmp(key, "options.no-commit"))
3060 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3061 else if (!strcmp(key, "options.edit"))
3062 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3063 else if (!strcmp(key, "options.allow-empty"))
3064 opts->allow_empty =
3065 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3066 else if (!strcmp(key, "options.allow-empty-message"))
3067 opts->allow_empty_message =
3068 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3069 else if (!strcmp(key, "options.drop-redundant-commits"))
3070 opts->drop_redundant_commits =
3071 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3072 else if (!strcmp(key, "options.keep-redundant-commits"))
3073 opts->keep_redundant_commits =
3074 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3075 else if (!strcmp(key, "options.signoff"))
3076 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3077 else if (!strcmp(key, "options.record-origin"))
3078 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3079 else if (!strcmp(key, "options.allow-ff"))
3080 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3081 else if (!strcmp(key, "options.mainline"))
3082 opts->mainline = git_config_int(key, value, ctx->kvi);
3083 else if (!strcmp(key, "options.strategy"))
3084 git_config_string_dup(&opts->strategy, key, value);
3085 else if (!strcmp(key, "options.gpg-sign"))
3086 git_config_string_dup(&opts->gpg_sign, key, value);
3087 else if (!strcmp(key, "options.strategy-option")) {
3088 strvec_push(&opts->xopts, value);
3089 } else if (!strcmp(key, "options.allow-rerere-auto"))
3090 opts->allow_rerere_auto =
3091 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3092 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3093 else if (!strcmp(key, "options.default-msg-cleanup")) {
3094 opts->explicit_cleanup = 1;
3095 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3096 } else
3097 return error(_("invalid key: %s"), key);
3099 if (!error_flag)
3100 return error(_("invalid value for '%s': '%s'"), key, value);
3102 return 0;
3105 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3107 int i;
3108 int count;
3109 const char **argv;
3110 char *strategy_opts_string = raw_opts;
3112 if (*strategy_opts_string == ' ')
3113 strategy_opts_string++;
3115 count = split_cmdline(strategy_opts_string, &argv);
3116 if (count < 0)
3117 BUG("could not split '%s': %s", strategy_opts_string,
3118 split_cmdline_strerror(count));
3119 for (i = 0; i < count; i++) {
3120 const char *arg = argv[i];
3122 skip_prefix(arg, "--", &arg);
3123 strvec_push(&opts->xopts, arg);
3125 free(argv);
3128 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3130 strbuf_reset(buf);
3131 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3132 return;
3133 opts->strategy = strbuf_detach(buf, NULL);
3134 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3135 return;
3137 parse_strategy_opts(opts, buf->buf);
3140 static int read_populate_opts(struct replay_opts *opts)
3142 struct replay_ctx *ctx = opts->ctx;
3144 if (is_rebase_i(opts)) {
3145 struct strbuf buf = STRBUF_INIT;
3146 int ret = 0;
3148 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3149 READ_ONELINER_SKIP_IF_EMPTY)) {
3150 if (!starts_with(buf.buf, "-S"))
3151 strbuf_reset(&buf);
3152 else {
3153 free(opts->gpg_sign);
3154 opts->gpg_sign = xstrdup(buf.buf + 2);
3156 strbuf_reset(&buf);
3159 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3160 READ_ONELINER_SKIP_IF_EMPTY)) {
3161 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3162 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3163 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3164 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3165 strbuf_reset(&buf);
3168 if (file_exists(rebase_path_verbose()))
3169 opts->verbose = 1;
3171 if (file_exists(rebase_path_quiet()))
3172 opts->quiet = 1;
3174 if (file_exists(rebase_path_signoff())) {
3175 opts->allow_ff = 0;
3176 opts->signoff = 1;
3179 if (file_exists(rebase_path_cdate_is_adate())) {
3180 opts->allow_ff = 0;
3181 opts->committer_date_is_author_date = 1;
3184 if (file_exists(rebase_path_ignore_date())) {
3185 opts->allow_ff = 0;
3186 opts->ignore_date = 1;
3189 if (file_exists(rebase_path_reschedule_failed_exec()))
3190 opts->reschedule_failed_exec = 1;
3191 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3192 opts->reschedule_failed_exec = 0;
3194 if (file_exists(rebase_path_drop_redundant_commits()))
3195 opts->drop_redundant_commits = 1;
3197 if (file_exists(rebase_path_keep_redundant_commits()))
3198 opts->keep_redundant_commits = 1;
3200 read_strategy_opts(opts, &buf);
3201 strbuf_reset(&buf);
3203 if (read_oneliner(&ctx->current_fixups,
3204 rebase_path_current_fixups(),
3205 READ_ONELINER_SKIP_IF_EMPTY)) {
3206 const char *p = ctx->current_fixups.buf;
3207 ctx->current_fixup_count = 1;
3208 while ((p = strchr(p, '\n'))) {
3209 ctx->current_fixup_count++;
3210 p++;
3214 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3215 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3216 ret = error(_("unusable squash-onto"));
3217 goto done_rebase_i;
3219 opts->have_squash_onto = 1;
3222 done_rebase_i:
3223 strbuf_release(&buf);
3224 return ret;
3227 if (!file_exists(git_path_opts_file()))
3228 return 0;
3230 * The function git_parse_source(), called from git_config_from_file(),
3231 * may die() in case of a syntactically incorrect file. We do not care
3232 * about this case, though, because we wrote that file ourselves, so we
3233 * are pretty certain that it is syntactically correct.
3235 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3236 return error(_("malformed options sheet: '%s'"),
3237 git_path_opts_file());
3238 return 0;
3241 static void write_strategy_opts(struct replay_opts *opts)
3243 struct strbuf buf = STRBUF_INIT;
3246 * Quote strategy options so that they can be read correctly
3247 * by split_cmdline().
3249 quote_cmdline(&buf, opts->xopts.v);
3250 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3251 strbuf_release(&buf);
3254 int write_basic_state(struct replay_opts *opts, const char *head_name,
3255 struct commit *onto, const struct object_id *orig_head)
3257 if (head_name)
3258 write_file(rebase_path_head_name(), "%s\n", head_name);
3259 if (onto)
3260 write_file(rebase_path_onto(), "%s\n",
3261 oid_to_hex(&onto->object.oid));
3262 if (orig_head)
3263 write_file(rebase_path_orig_head(), "%s\n",
3264 oid_to_hex(orig_head));
3266 if (opts->quiet)
3267 write_file(rebase_path_quiet(), "%s", "");
3268 if (opts->verbose)
3269 write_file(rebase_path_verbose(), "%s", "");
3270 if (opts->strategy)
3271 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3272 if (opts->xopts.nr > 0)
3273 write_strategy_opts(opts);
3275 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3276 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3277 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3278 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3280 if (opts->gpg_sign)
3281 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3282 if (opts->signoff)
3283 write_file(rebase_path_signoff(), "--signoff\n");
3284 if (opts->drop_redundant_commits)
3285 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3286 if (opts->keep_redundant_commits)
3287 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3288 if (opts->committer_date_is_author_date)
3289 write_file(rebase_path_cdate_is_adate(), "%s", "");
3290 if (opts->ignore_date)
3291 write_file(rebase_path_ignore_date(), "%s", "");
3292 if (opts->reschedule_failed_exec)
3293 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3294 else
3295 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3297 return 0;
3300 static int walk_revs_populate_todo(struct todo_list *todo_list,
3301 struct replay_opts *opts)
3303 enum todo_command command = opts->action == REPLAY_PICK ?
3304 TODO_PICK : TODO_REVERT;
3305 const char *command_string = todo_command_info[command].str;
3306 const char *encoding;
3307 struct commit *commit;
3309 if (prepare_revs(opts))
3310 return -1;
3312 encoding = get_log_output_encoding();
3314 while ((commit = get_revision(opts->revs))) {
3315 struct todo_item *item = append_new_todo(todo_list);
3316 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3317 commit, NULL,
3318 encoding);
3319 const char *subject;
3320 int subject_len;
3322 item->command = command;
3323 item->commit = commit;
3324 item->arg_offset = 0;
3325 item->arg_len = 0;
3326 item->offset_in_buf = todo_list->buf.len;
3327 subject_len = find_commit_subject(commit_buffer, &subject);
3328 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3329 short_commit_name(the_repository, commit),
3330 subject_len, subject);
3331 repo_unuse_commit_buffer(the_repository, commit,
3332 commit_buffer);
3335 if (!todo_list->nr)
3336 return error(_("empty commit set passed"));
3338 return 0;
3341 static int create_seq_dir(struct repository *r)
3343 enum replay_action action;
3344 const char *in_progress_error = NULL;
3345 const char *in_progress_advice = NULL;
3346 unsigned int advise_skip =
3347 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3348 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3350 if (!sequencer_get_last_command(r, &action)) {
3351 switch (action) {
3352 case REPLAY_REVERT:
3353 in_progress_error = _("revert is already in progress");
3354 in_progress_advice =
3355 _("try \"git revert (--continue | %s--abort | --quit)\"");
3356 break;
3357 case REPLAY_PICK:
3358 in_progress_error = _("cherry-pick is already in progress");
3359 in_progress_advice =
3360 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3361 break;
3362 default:
3363 BUG("unexpected action in create_seq_dir");
3366 if (in_progress_error) {
3367 error("%s", in_progress_error);
3368 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3369 advise(in_progress_advice,
3370 advise_skip ? "--skip | " : "");
3371 return -1;
3373 if (mkdir(git_path_seq_dir(), 0777) < 0)
3374 return error_errno(_("could not create sequencer directory '%s'"),
3375 git_path_seq_dir());
3377 return 0;
3380 static int save_head(const char *head)
3382 return write_message(head, strlen(head), git_path_head_file(), 1);
3385 static int rollback_is_safe(void)
3387 struct strbuf sb = STRBUF_INIT;
3388 struct object_id expected_head, actual_head;
3390 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3391 strbuf_trim(&sb);
3392 if (get_oid_hex(sb.buf, &expected_head)) {
3393 strbuf_release(&sb);
3394 die(_("could not parse %s"), git_path_abort_safety_file());
3396 strbuf_release(&sb);
3398 else if (errno == ENOENT)
3399 oidclr(&expected_head, the_repository->hash_algo);
3400 else
3401 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3403 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3404 oidclr(&actual_head, the_repository->hash_algo);
3406 return oideq(&actual_head, &expected_head);
3409 static int reset_merge(const struct object_id *oid)
3411 struct child_process cmd = CHILD_PROCESS_INIT;
3413 cmd.git_cmd = 1;
3414 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3416 if (!is_null_oid(oid))
3417 strvec_push(&cmd.args, oid_to_hex(oid));
3419 return run_command(&cmd);
3422 static int rollback_single_pick(struct repository *r)
3424 struct object_id head_oid;
3426 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3427 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3428 return error(_("no cherry-pick or revert in progress"));
3429 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3430 return error(_("cannot resolve HEAD"));
3431 if (is_null_oid(&head_oid))
3432 return error(_("cannot abort from a branch yet to be born"));
3433 return reset_merge(&head_oid);
3436 static int skip_single_pick(void)
3438 struct object_id head;
3440 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3441 return error(_("cannot resolve HEAD"));
3442 return reset_merge(&head);
3445 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3447 FILE *f;
3448 struct object_id oid;
3449 struct strbuf buf = STRBUF_INIT;
3450 const char *p;
3452 f = fopen(git_path_head_file(), "r");
3453 if (!f && errno == ENOENT) {
3455 * There is no multiple-cherry-pick in progress.
3456 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3457 * a single-cherry-pick in progress, abort that.
3459 return rollback_single_pick(r);
3461 if (!f)
3462 return error_errno(_("cannot open '%s'"), git_path_head_file());
3463 if (strbuf_getline_lf(&buf, f)) {
3464 error(_("cannot read '%s': %s"), git_path_head_file(),
3465 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3466 fclose(f);
3467 goto fail;
3469 fclose(f);
3470 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3471 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3472 git_path_head_file());
3473 goto fail;
3475 if (is_null_oid(&oid)) {
3476 error(_("cannot abort from a branch yet to be born"));
3477 goto fail;
3480 if (!rollback_is_safe()) {
3481 /* Do not error, just do not rollback */
3482 warning(_("You seem to have moved HEAD. "
3483 "Not rewinding, check your HEAD!"));
3484 } else
3485 if (reset_merge(&oid))
3486 goto fail;
3487 strbuf_release(&buf);
3488 return sequencer_remove_state(opts);
3489 fail:
3490 strbuf_release(&buf);
3491 return -1;
3494 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3496 enum replay_action action = -1;
3497 sequencer_get_last_command(r, &action);
3500 * Check whether the subcommand requested to skip the commit is actually
3501 * in progress and that it's safe to skip the commit.
3503 * opts->action tells us which subcommand requested to skip the commit.
3504 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3505 * action is in progress and we can skip the commit.
3507 * Otherwise we check that the last instruction was related to the
3508 * particular subcommand we're trying to execute and barf if that's not
3509 * the case.
3511 * Finally we check that the rollback is "safe", i.e., has the HEAD
3512 * moved? In this case, it doesn't make sense to "reset the merge" and
3513 * "skip the commit" as the user already handled this by committing. But
3514 * we'd not want to barf here, instead give advice on how to proceed. We
3515 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3516 * it gets removed when the user commits, so if it still exists we're
3517 * sure the user can't have committed before.
3519 switch (opts->action) {
3520 case REPLAY_REVERT:
3521 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3522 if (action != REPLAY_REVERT)
3523 return error(_("no revert in progress"));
3524 if (!rollback_is_safe())
3525 goto give_advice;
3527 break;
3528 case REPLAY_PICK:
3529 if (!refs_ref_exists(get_main_ref_store(r),
3530 "CHERRY_PICK_HEAD")) {
3531 if (action != REPLAY_PICK)
3532 return error(_("no cherry-pick in progress"));
3533 if (!rollback_is_safe())
3534 goto give_advice;
3536 break;
3537 default:
3538 BUG("unexpected action in sequencer_skip");
3541 if (skip_single_pick())
3542 return error(_("failed to skip the commit"));
3543 if (!is_directory(git_path_seq_dir()))
3544 return 0;
3546 return sequencer_continue(r, opts);
3548 give_advice:
3549 error(_("there is nothing to skip"));
3551 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3552 advise(_("have you committed already?\n"
3553 "try \"git %s --continue\""),
3554 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3556 return -1;
3559 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3560 int reschedule)
3562 struct lock_file todo_lock = LOCK_INIT;
3563 const char *todo_path = get_todo_path(opts);
3564 int next = todo_list->current, offset, fd;
3567 * rebase -i writes "git-rebase-todo" without the currently executing
3568 * command, appending it to "done" instead.
3570 if (is_rebase_i(opts) && !reschedule)
3571 next++;
3573 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3574 if (fd < 0)
3575 return error_errno(_("could not lock '%s'"), todo_path);
3576 offset = get_item_line_offset(todo_list, next);
3577 if (write_in_full(fd, todo_list->buf.buf + offset,
3578 todo_list->buf.len - offset) < 0)
3579 return error_errno(_("could not write to '%s'"), todo_path);
3580 if (commit_lock_file(&todo_lock) < 0)
3581 return error(_("failed to finalize '%s'"), todo_path);
3583 if (is_rebase_i(opts) && !reschedule && next > 0) {
3584 const char *done = rebase_path_done();
3585 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3586 int ret = 0;
3588 if (fd < 0)
3589 return 0;
3590 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3591 get_item_line_length(todo_list, next - 1))
3592 < 0)
3593 ret = error_errno(_("could not write to '%s'"), done);
3594 if (close(fd) < 0)
3595 ret = error_errno(_("failed to finalize '%s'"), done);
3596 return ret;
3598 return 0;
3601 static int save_opts(struct replay_opts *opts)
3603 const char *opts_file = git_path_opts_file();
3604 int res = 0;
3606 if (opts->no_commit)
3607 res |= git_config_set_in_file_gently(opts_file,
3608 "options.no-commit", NULL, "true");
3609 if (opts->edit >= 0)
3610 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
3611 opts->edit ? "true" : "false");
3612 if (opts->allow_empty)
3613 res |= git_config_set_in_file_gently(opts_file,
3614 "options.allow-empty", NULL, "true");
3615 if (opts->allow_empty_message)
3616 res |= git_config_set_in_file_gently(opts_file,
3617 "options.allow-empty-message", NULL, "true");
3618 if (opts->drop_redundant_commits)
3619 res |= git_config_set_in_file_gently(opts_file,
3620 "options.drop-redundant-commits", NULL, "true");
3621 if (opts->keep_redundant_commits)
3622 res |= git_config_set_in_file_gently(opts_file,
3623 "options.keep-redundant-commits", NULL, "true");
3624 if (opts->signoff)
3625 res |= git_config_set_in_file_gently(opts_file,
3626 "options.signoff", NULL, "true");
3627 if (opts->record_origin)
3628 res |= git_config_set_in_file_gently(opts_file,
3629 "options.record-origin", NULL, "true");
3630 if (opts->allow_ff)
3631 res |= git_config_set_in_file_gently(opts_file,
3632 "options.allow-ff", NULL, "true");
3633 if (opts->mainline) {
3634 struct strbuf buf = STRBUF_INIT;
3635 strbuf_addf(&buf, "%d", opts->mainline);
3636 res |= git_config_set_in_file_gently(opts_file,
3637 "options.mainline", NULL, buf.buf);
3638 strbuf_release(&buf);
3640 if (opts->strategy)
3641 res |= git_config_set_in_file_gently(opts_file,
3642 "options.strategy", NULL, opts->strategy);
3643 if (opts->gpg_sign)
3644 res |= git_config_set_in_file_gently(opts_file,
3645 "options.gpg-sign", NULL, opts->gpg_sign);
3646 for (size_t i = 0; i < opts->xopts.nr; i++)
3647 res |= git_config_set_multivar_in_file_gently(opts_file,
3648 "options.strategy-option",
3649 opts->xopts.v[i], "^$", NULL, 0);
3650 if (opts->allow_rerere_auto)
3651 res |= git_config_set_in_file_gently(opts_file,
3652 "options.allow-rerere-auto", NULL,
3653 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3654 "true" : "false");
3656 if (opts->explicit_cleanup)
3657 res |= git_config_set_in_file_gently(opts_file,
3658 "options.default-msg-cleanup", NULL,
3659 describe_cleanup_mode(opts->default_msg_cleanup));
3660 return res;
3663 static int make_patch(struct repository *r,
3664 struct commit *commit,
3665 struct replay_opts *opts)
3667 struct rev_info log_tree_opt;
3668 const char *subject;
3669 char hex[GIT_MAX_HEXSZ + 1];
3670 int res = 0;
3672 if (!is_rebase_i(opts))
3673 BUG("make_patch should only be called when rebasing");
3675 oid_to_hex_r(hex, &commit->object.oid);
3676 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3677 return -1;
3678 res |= write_rebase_head(&commit->object.oid);
3680 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3681 repo_init_revisions(r, &log_tree_opt, NULL);
3682 log_tree_opt.abbrev = 0;
3683 log_tree_opt.diff = 1;
3684 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3685 log_tree_opt.disable_stdin = 1;
3686 log_tree_opt.no_commit_id = 1;
3687 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3688 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3689 if (!log_tree_opt.diffopt.file)
3690 res |= error_errno(_("could not open '%s'"),
3691 rebase_path_patch());
3692 else {
3693 res |= log_tree_commit(&log_tree_opt, commit);
3694 fclose(log_tree_opt.diffopt.file);
3697 if (!file_exists(rebase_path_message())) {
3698 const char *encoding = get_commit_output_encoding();
3699 const char *commit_buffer = repo_logmsg_reencode(r,
3700 commit, NULL,
3701 encoding);
3702 find_commit_subject(commit_buffer, &subject);
3703 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3704 repo_unuse_commit_buffer(r, commit,
3705 commit_buffer);
3707 release_revisions(&log_tree_opt);
3709 return res;
3712 static int intend_to_amend(void)
3714 struct object_id head;
3715 char *p;
3717 if (repo_get_oid(the_repository, "HEAD", &head))
3718 return error(_("cannot read HEAD"));
3720 p = oid_to_hex(&head);
3721 return write_message(p, strlen(p), rebase_path_amend(), 1);
3724 static int error_with_patch(struct repository *r,
3725 struct commit *commit,
3726 const char *subject, int subject_len,
3727 struct replay_opts *opts,
3728 int exit_code, int to_amend)
3730 struct replay_ctx *ctx = opts->ctx;
3733 * Write the commit message to be used by "git rebase
3734 * --continue". If a "fixup" or "squash" command has conflicts
3735 * then we will have already written rebase_path_message() in
3736 * error_failed_squash(). If an "edit" command was
3737 * fast-forwarded then we don't have a message in ctx->message
3738 * and rely on make_patch() to write rebase_path_message()
3739 * instead.
3741 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3742 write_message(ctx->message.buf, ctx->message.len,
3743 rebase_path_message(), 0))
3744 return error(_("could not write commit message file"));
3746 if (commit && make_patch(r, commit, opts))
3747 return -1;
3749 if (to_amend) {
3750 if (intend_to_amend())
3751 return -1;
3753 fprintf(stderr,
3754 _("You can amend the commit now, with\n"
3755 "\n"
3756 " git commit --amend %s\n"
3757 "\n"
3758 "Once you are satisfied with your changes, run\n"
3759 "\n"
3760 " git rebase --continue\n"),
3761 gpg_sign_opt_quoted(opts));
3762 } else if (exit_code) {
3763 if (commit)
3764 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3765 short_commit_name(r, commit), subject_len, subject);
3766 else
3768 * We don't have the hash of the parent so
3769 * just print the line from the todo file.
3771 fprintf_ln(stderr, _("Could not merge %.*s"),
3772 subject_len, subject);
3775 return exit_code;
3778 static int error_failed_squash(struct repository *r,
3779 struct commit *commit,
3780 struct replay_opts *opts,
3781 int subject_len,
3782 const char *subject)
3784 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3785 return error(_("could not copy '%s' to '%s'"),
3786 rebase_path_squash_msg(), rebase_path_message());
3787 unlink(git_path_merge_msg(r));
3788 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3789 return error(_("could not copy '%s' to '%s'"),
3790 rebase_path_message(),
3791 git_path_merge_msg(r));
3792 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3795 static int do_exec(struct repository *r, const char *command_line)
3797 struct child_process cmd = CHILD_PROCESS_INIT;
3798 int dirty, status;
3800 fprintf(stderr, _("Executing: %s\n"), command_line);
3801 cmd.use_shell = 1;
3802 strvec_push(&cmd.args, command_line);
3803 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3804 status = run_command(&cmd);
3806 /* force re-reading of the cache */
3807 discard_index(r->index);
3808 if (repo_read_index(r) < 0)
3809 return error(_("could not read index"));
3811 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3813 if (status) {
3814 warning(_("execution failed: %s\n%s"
3815 "You can fix the problem, and then run\n"
3816 "\n"
3817 " git rebase --continue\n"
3818 "\n"),
3819 command_line,
3820 dirty ? _("and made changes to the index and/or the "
3821 "working tree.\n") : "");
3822 if (status == 127)
3823 /* command not found */
3824 status = 1;
3825 } else if (dirty) {
3826 warning(_("execution succeeded: %s\nbut "
3827 "left changes to the index and/or the working tree.\n"
3828 "Commit or stash your changes, and then run\n"
3829 "\n"
3830 " git rebase --continue\n"
3831 "\n"), command_line);
3832 status = 1;
3835 return status;
3838 __attribute__((format (printf, 2, 3)))
3839 static int safe_append(const char *filename, const char *fmt, ...)
3841 va_list ap;
3842 struct lock_file lock = LOCK_INIT;
3843 int fd = hold_lock_file_for_update(&lock, filename,
3844 LOCK_REPORT_ON_ERROR);
3845 struct strbuf buf = STRBUF_INIT;
3847 if (fd < 0)
3848 return -1;
3850 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3851 error_errno(_("could not read '%s'"), filename);
3852 rollback_lock_file(&lock);
3853 return -1;
3855 strbuf_complete(&buf, '\n');
3856 va_start(ap, fmt);
3857 strbuf_vaddf(&buf, fmt, ap);
3858 va_end(ap);
3860 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3861 error_errno(_("could not write to '%s'"), filename);
3862 strbuf_release(&buf);
3863 rollback_lock_file(&lock);
3864 return -1;
3866 if (commit_lock_file(&lock) < 0) {
3867 strbuf_release(&buf);
3868 return error(_("failed to finalize '%s'"), filename);
3871 strbuf_release(&buf);
3872 return 0;
3875 static int do_label(struct repository *r, const char *name, int len)
3877 struct ref_store *refs = get_main_ref_store(r);
3878 struct ref_transaction *transaction;
3879 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3880 struct strbuf msg = STRBUF_INIT;
3881 int ret = 0;
3882 struct object_id head_oid;
3884 if (len == 1 && *name == '#')
3885 return error(_("illegal label name: '%.*s'"), len, name);
3887 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3888 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3890 transaction = ref_store_transaction_begin(refs, &err);
3891 if (!transaction) {
3892 error("%s", err.buf);
3893 ret = -1;
3894 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3895 error(_("could not read HEAD"));
3896 ret = -1;
3897 } else if (ref_transaction_update(transaction, ref_name.buf,
3898 &head_oid, NULL, NULL, NULL,
3899 0, msg.buf, &err) < 0 ||
3900 ref_transaction_commit(transaction, &err)) {
3901 error("%s", err.buf);
3902 ret = -1;
3904 ref_transaction_free(transaction);
3905 strbuf_release(&err);
3906 strbuf_release(&msg);
3908 if (!ret)
3909 ret = safe_append(rebase_path_refs_to_delete(),
3910 "%s\n", ref_name.buf);
3911 strbuf_release(&ref_name);
3913 return ret;
3916 static const char *sequencer_reflog_action(struct replay_opts *opts)
3918 if (!opts->reflog_action) {
3919 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3920 opts->reflog_action =
3921 xstrdup(opts->reflog_action ? opts->reflog_action
3922 : action_name(opts));
3925 return opts->reflog_action;
3928 __attribute__((format (printf, 3, 4)))
3929 static const char *reflog_message(struct replay_opts *opts,
3930 const char *sub_action, const char *fmt, ...)
3932 va_list ap;
3933 static struct strbuf buf = STRBUF_INIT;
3935 va_start(ap, fmt);
3936 strbuf_reset(&buf);
3937 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3938 if (sub_action)
3939 strbuf_addf(&buf, " (%s)", sub_action);
3940 if (fmt) {
3941 strbuf_addstr(&buf, ": ");
3942 strbuf_vaddf(&buf, fmt, ap);
3944 va_end(ap);
3946 return buf.buf;
3949 static struct commit *lookup_label(struct repository *r, const char *label,
3950 int len, struct strbuf *buf)
3952 struct commit *commit;
3953 struct object_id oid;
3955 strbuf_reset(buf);
3956 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3957 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
3958 commit = lookup_commit_object(r, &oid);
3959 } else {
3960 /* fall back to non-rewritten ref or commit */
3961 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3962 commit = lookup_commit_reference_by_name(buf->buf);
3965 if (!commit)
3966 error(_("could not resolve '%s'"), buf->buf);
3968 return commit;
3971 static int do_reset(struct repository *r,
3972 const char *name, int len,
3973 struct replay_opts *opts)
3975 struct strbuf ref_name = STRBUF_INIT;
3976 struct object_id oid;
3977 struct lock_file lock = LOCK_INIT;
3978 struct tree_desc desc = { 0 };
3979 struct tree *tree;
3980 struct unpack_trees_options unpack_tree_opts = { 0 };
3981 int ret = 0;
3983 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3984 return -1;
3986 if (len == 10 && !strncmp("[new root]", name, len)) {
3987 if (!opts->have_squash_onto) {
3988 const char *hex;
3989 if (commit_tree("", 0, the_hash_algo->empty_tree,
3990 NULL, &opts->squash_onto,
3991 NULL, NULL))
3992 return error(_("writing fake root commit"));
3993 opts->have_squash_onto = 1;
3994 hex = oid_to_hex(&opts->squash_onto);
3995 if (write_message(hex, strlen(hex),
3996 rebase_path_squash_onto(), 0))
3997 return error(_("writing squash-onto"));
3999 oidcpy(&oid, &opts->squash_onto);
4000 } else {
4001 int i;
4002 struct commit *commit;
4004 /* Determine the length of the label */
4005 for (i = 0; i < len; i++)
4006 if (isspace(name[i]))
4007 break;
4008 len = i;
4010 commit = lookup_label(r, name, len, &ref_name);
4011 if (!commit) {
4012 ret = -1;
4013 goto cleanup;
4015 oid = commit->object.oid;
4018 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4019 unpack_tree_opts.head_idx = 1;
4020 unpack_tree_opts.src_index = r->index;
4021 unpack_tree_opts.dst_index = r->index;
4022 unpack_tree_opts.fn = oneway_merge;
4023 unpack_tree_opts.merge = 1;
4024 unpack_tree_opts.update = 1;
4025 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4026 unpack_tree_opts.skip_cache_tree_update = 1;
4027 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4029 if (repo_read_index_unmerged(r)) {
4030 ret = error_resolve_conflict(action_name(opts));
4031 goto cleanup;
4034 if (!fill_tree_descriptor(r, &desc, &oid)) {
4035 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4036 goto cleanup;
4039 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4040 ret = -1;
4041 goto cleanup;
4044 tree = parse_tree_indirect(&oid);
4045 if (!tree)
4046 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4047 prime_cache_tree(r, r->index, tree);
4049 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4050 ret = error(_("could not write index"));
4052 if (!ret)
4053 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4054 len, name),
4055 "HEAD", &oid,
4056 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4057 cleanup:
4058 free((void *)desc.buffer);
4059 if (ret < 0)
4060 rollback_lock_file(&lock);
4061 strbuf_release(&ref_name);
4062 clear_unpack_trees_porcelain(&unpack_tree_opts);
4063 return ret;
4066 static int do_merge(struct repository *r,
4067 struct commit *commit,
4068 const char *arg, int arg_len,
4069 int flags, int *check_todo, struct replay_opts *opts)
4071 struct replay_ctx *ctx = opts->ctx;
4072 int run_commit_flags = 0;
4073 struct strbuf ref_name = STRBUF_INIT;
4074 struct commit *head_commit, *merge_commit, *i;
4075 struct commit_list *bases = NULL, *j;
4076 struct commit_list *to_merge = NULL, **tail = &to_merge;
4077 const char *strategy = !opts->xopts.nr &&
4078 (!opts->strategy ||
4079 !strcmp(opts->strategy, "recursive") ||
4080 !strcmp(opts->strategy, "ort")) ?
4081 NULL : opts->strategy;
4082 struct merge_options o;
4083 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4084 static struct lock_file lock;
4085 const char *p;
4087 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4088 ret = -1;
4089 goto leave_merge;
4092 head_commit = lookup_commit_reference_by_name("HEAD");
4093 if (!head_commit) {
4094 ret = error(_("cannot merge without a current revision"));
4095 goto leave_merge;
4099 * For octopus merges, the arg starts with the list of revisions to be
4100 * merged. The list is optionally followed by '#' and the oneline.
4102 merge_arg_len = oneline_offset = arg_len;
4103 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4104 if (!*p)
4105 break;
4106 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4107 p += 1 + strspn(p + 1, " \t\n");
4108 oneline_offset = p - arg;
4109 break;
4111 k = strcspn(p, " \t\n");
4112 if (!k)
4113 continue;
4114 merge_commit = lookup_label(r, p, k, &ref_name);
4115 if (!merge_commit) {
4116 ret = error(_("unable to parse '%.*s'"), k, p);
4117 goto leave_merge;
4119 tail = &commit_list_insert(merge_commit, tail)->next;
4120 p += k;
4121 merge_arg_len = p - arg;
4124 if (!to_merge) {
4125 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4126 goto leave_merge;
4129 if (opts->have_squash_onto &&
4130 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4132 * When the user tells us to "merge" something into a
4133 * "[new root]", let's simply fast-forward to the merge head.
4135 rollback_lock_file(&lock);
4136 if (to_merge->next)
4137 ret = error(_("octopus merge cannot be executed on "
4138 "top of a [new root]"));
4139 else
4140 ret = fast_forward_to(r, &to_merge->item->object.oid,
4141 &head_commit->object.oid, 0,
4142 opts);
4143 goto leave_merge;
4147 * If HEAD is not identical to the first parent of the original merge
4148 * commit, we cannot fast-forward.
4150 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4151 oideq(&commit->parents->item->object.oid,
4152 &head_commit->object.oid);
4155 * If any merge head is different from the original one, we cannot
4156 * fast-forward.
4158 if (can_fast_forward) {
4159 struct commit_list *p = commit->parents->next;
4161 for (j = to_merge; j && p; j = j->next, p = p->next)
4162 if (!oideq(&j->item->object.oid,
4163 &p->item->object.oid)) {
4164 can_fast_forward = 0;
4165 break;
4168 * If the number of merge heads differs from the original merge
4169 * commit, we cannot fast-forward.
4171 if (j || p)
4172 can_fast_forward = 0;
4175 if (can_fast_forward) {
4176 rollback_lock_file(&lock);
4177 ret = fast_forward_to(r, &commit->object.oid,
4178 &head_commit->object.oid, 0, opts);
4179 if (flags & TODO_EDIT_MERGE_MSG)
4180 goto fast_forward_edit;
4182 goto leave_merge;
4185 if (commit) {
4186 const char *encoding = get_commit_output_encoding();
4187 const char *message = repo_logmsg_reencode(r, commit, NULL,
4188 encoding);
4189 const char *body;
4190 int len;
4192 if (!message) {
4193 ret = error(_("could not get commit message of '%s'"),
4194 oid_to_hex(&commit->object.oid));
4195 goto leave_merge;
4197 write_author_script(message);
4198 find_commit_subject(message, &body);
4199 len = strlen(body);
4200 strbuf_add(&ctx->message, body, len);
4201 repo_unuse_commit_buffer(r, commit, message);
4202 } else {
4203 struct strbuf buf = STRBUF_INIT;
4205 strbuf_addf(&buf, "author %s", git_author_info(0));
4206 write_author_script(buf.buf);
4207 strbuf_release(&buf);
4209 if (oneline_offset < arg_len) {
4210 strbuf_add(&ctx->message, arg + oneline_offset,
4211 arg_len - oneline_offset);
4212 } else {
4213 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4214 to_merge->next ? "branches" : "branch",
4215 merge_arg_len, arg);
4218 ctx->have_message = 1;
4219 if (write_message(ctx->message.buf, ctx->message.len,
4220 git_path_merge_msg(r), 0)) {
4221 ret = error_errno(_("could not write '%s'"),
4222 git_path_merge_msg(r));
4223 goto leave_merge;
4226 if (strategy || to_merge->next) {
4227 /* Octopus merge */
4228 struct child_process cmd = CHILD_PROCESS_INIT;
4230 if (read_env_script(&cmd.env)) {
4231 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4233 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4234 goto leave_merge;
4237 if (opts->committer_date_is_author_date)
4238 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4239 opts->ignore_date ?
4240 "" :
4241 author_date_from_env(&cmd.env));
4242 if (opts->ignore_date)
4243 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4245 cmd.git_cmd = 1;
4246 strvec_push(&cmd.args, "merge");
4247 strvec_push(&cmd.args, "-s");
4248 if (!strategy)
4249 strvec_push(&cmd.args, "octopus");
4250 else {
4251 strvec_push(&cmd.args, strategy);
4252 for (k = 0; k < opts->xopts.nr; k++)
4253 strvec_pushf(&cmd.args,
4254 "-X%s", opts->xopts.v[k]);
4256 if (!(flags & TODO_EDIT_MERGE_MSG))
4257 strvec_push(&cmd.args, "--no-edit");
4258 else
4259 strvec_push(&cmd.args, "--edit");
4260 strvec_push(&cmd.args, "--no-ff");
4261 strvec_push(&cmd.args, "--no-log");
4262 strvec_push(&cmd.args, "--no-stat");
4263 strvec_push(&cmd.args, "-F");
4264 strvec_push(&cmd.args, git_path_merge_msg(r));
4265 if (opts->gpg_sign)
4266 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4267 else
4268 strvec_push(&cmd.args, "--no-gpg-sign");
4270 /* Add the tips to be merged */
4271 for (j = to_merge; j; j = j->next)
4272 strvec_push(&cmd.args,
4273 oid_to_hex(&j->item->object.oid));
4275 strbuf_release(&ref_name);
4276 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4277 NULL, REF_NO_DEREF);
4278 rollback_lock_file(&lock);
4280 ret = run_command(&cmd);
4282 /* force re-reading of the cache */
4283 if (!ret) {
4284 discard_index(r->index);
4285 if (repo_read_index(r) < 0)
4286 ret = error(_("could not read index"));
4288 goto leave_merge;
4291 merge_commit = to_merge->item;
4292 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4293 ret = -1;
4294 goto leave_merge;
4297 if (bases && oideq(&merge_commit->object.oid,
4298 &bases->item->object.oid)) {
4299 ret = 0;
4300 /* skip merging an ancestor of HEAD */
4301 goto leave_merge;
4304 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4305 git_path_merge_head(r), 0);
4306 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4308 bases = reverse_commit_list(bases);
4310 repo_read_index(r);
4311 init_merge_options(&o, r);
4312 o.branch1 = "HEAD";
4313 o.branch2 = ref_name.buf;
4314 o.buffer_output = 2;
4316 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4318 * TODO: Should use merge_incore_recursive() and
4319 * merge_switch_to_result(), skipping the call to
4320 * merge_switch_to_result() when we don't actually need to
4321 * update the index and working copy immediately.
4323 ret = merge_ort_recursive(&o,
4324 head_commit, merge_commit, bases,
4325 &i);
4326 } else {
4327 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4328 &i);
4330 if (ret <= 0)
4331 fputs(o.obuf.buf, stdout);
4332 strbuf_release(&o.obuf);
4333 if (ret < 0) {
4334 error(_("could not even attempt to merge '%.*s'"),
4335 merge_arg_len, arg);
4336 unlink(git_path_merge_msg(r));
4337 goto leave_merge;
4340 * The return value of merge_recursive() is 1 on clean, and 0 on
4341 * unclean merge.
4343 * Let's reverse that, so that do_merge() returns 0 upon success and
4344 * 1 upon failed merge (keeping the return value -1 for the cases where
4345 * we will want to reschedule the `merge` command).
4347 ret = !ret;
4349 if (r->index->cache_changed &&
4350 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4351 ret = error(_("merge: Unable to write new index file"));
4352 goto leave_merge;
4355 rollback_lock_file(&lock);
4356 if (ret)
4357 repo_rerere(r, opts->allow_rerere_auto);
4358 else
4360 * In case of problems, we now want to return a positive
4361 * value (a negative one would indicate that the `merge`
4362 * command needs to be rescheduled).
4364 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4365 run_commit_flags);
4367 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4368 fast_forward_edit:
4369 *check_todo = 1;
4370 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4371 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4375 leave_merge:
4376 strbuf_release(&ref_name);
4377 rollback_lock_file(&lock);
4378 free_commit_list(to_merge);
4379 return ret;
4382 static int write_update_refs_state(struct string_list *refs_to_oids)
4384 int result = 0;
4385 struct lock_file lock = LOCK_INIT;
4386 FILE *fp = NULL;
4387 struct string_list_item *item;
4388 char *path;
4390 path = rebase_path_update_refs(the_repository->gitdir);
4392 if (!refs_to_oids->nr) {
4393 if (unlink(path) && errno != ENOENT)
4394 result = error_errno(_("could not unlink: %s"), path);
4395 goto cleanup;
4398 if (safe_create_leading_directories(path)) {
4399 result = error(_("unable to create leading directories of %s"),
4400 path);
4401 goto cleanup;
4404 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4405 result = error(_("another 'rebase' process appears to be running; "
4406 "'%s.lock' already exists"),
4407 path);
4408 goto cleanup;
4411 fp = fdopen_lock_file(&lock, "w");
4412 if (!fp) {
4413 result = error_errno(_("could not open '%s' for writing"), path);
4414 rollback_lock_file(&lock);
4415 goto cleanup;
4418 for_each_string_list_item(item, refs_to_oids) {
4419 struct update_ref_record *rec = item->util;
4420 fprintf(fp, "%s\n%s\n%s\n", item->string,
4421 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4424 result = commit_lock_file(&lock);
4426 cleanup:
4427 free(path);
4428 return result;
4432 * Parse the update-refs file for the current rebase, then remove the
4433 * refs that do not appear in the todo_list (and have not had updated
4434 * values stored) and add refs that are in the todo_list but not
4435 * represented in the update-refs file.
4437 * If there are changes to the update-refs list, then write the new state
4438 * to disk.
4440 void todo_list_filter_update_refs(struct repository *r,
4441 struct todo_list *todo_list)
4443 int i;
4444 int updated = 0;
4445 struct string_list update_refs = STRING_LIST_INIT_DUP;
4447 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4450 * For each item in the update_refs list, if it has no updated
4451 * value and does not appear in the todo_list, then remove it
4452 * from the update_refs list.
4454 for (i = 0; i < update_refs.nr; i++) {
4455 int j;
4456 int found = 0;
4457 const char *ref = update_refs.items[i].string;
4458 size_t reflen = strlen(ref);
4459 struct update_ref_record *rec = update_refs.items[i].util;
4461 /* OID already stored as updated. */
4462 if (!is_null_oid(&rec->after))
4463 continue;
4465 for (j = 0; !found && j < todo_list->nr; j++) {
4466 struct todo_item *item = &todo_list->items[j];
4467 const char *arg = todo_list->buf.buf + item->arg_offset;
4469 if (item->command != TODO_UPDATE_REF)
4470 continue;
4472 if (item->arg_len != reflen ||
4473 strncmp(arg, ref, reflen))
4474 continue;
4476 found = 1;
4479 if (!found) {
4480 free(update_refs.items[i].string);
4481 free(update_refs.items[i].util);
4483 update_refs.nr--;
4484 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4486 updated = 1;
4487 i--;
4492 * For each todo_item, check if its ref is in the update_refs list.
4493 * If not, then add it as an un-updated ref.
4495 for (i = 0; i < todo_list->nr; i++) {
4496 struct todo_item *item = &todo_list->items[i];
4497 const char *arg = todo_list->buf.buf + item->arg_offset;
4498 int j, found = 0;
4500 if (item->command != TODO_UPDATE_REF)
4501 continue;
4503 for (j = 0; !found && j < update_refs.nr; j++) {
4504 const char *ref = update_refs.items[j].string;
4506 found = strlen(ref) == item->arg_len &&
4507 !strncmp(ref, arg, item->arg_len);
4510 if (!found) {
4511 struct string_list_item *inserted;
4512 struct strbuf argref = STRBUF_INIT;
4514 strbuf_add(&argref, arg, item->arg_len);
4515 inserted = string_list_insert(&update_refs, argref.buf);
4516 inserted->util = init_update_ref_record(argref.buf);
4517 strbuf_release(&argref);
4518 updated = 1;
4522 if (updated)
4523 write_update_refs_state(&update_refs);
4524 string_list_clear(&update_refs, 1);
4527 static int do_update_ref(struct repository *r, const char *refname)
4529 struct string_list_item *item;
4530 struct string_list list = STRING_LIST_INIT_DUP;
4532 if (sequencer_get_update_refs_state(r->gitdir, &list))
4533 return -1;
4535 for_each_string_list_item(item, &list) {
4536 if (!strcmp(item->string, refname)) {
4537 struct update_ref_record *rec = item->util;
4538 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4539 return -1;
4540 break;
4544 write_update_refs_state(&list);
4545 string_list_clear(&list, 1);
4546 return 0;
4549 static int do_update_refs(struct repository *r, int quiet)
4551 int res = 0;
4552 struct string_list_item *item;
4553 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4554 struct ref_store *refs = get_main_ref_store(r);
4555 struct strbuf update_msg = STRBUF_INIT;
4556 struct strbuf error_msg = STRBUF_INIT;
4558 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4559 return res;
4561 for_each_string_list_item(item, &refs_to_oids) {
4562 struct update_ref_record *rec = item->util;
4563 int loop_res;
4565 loop_res = refs_update_ref(refs, "rewritten during rebase",
4566 item->string,
4567 &rec->after, &rec->before,
4568 0, UPDATE_REFS_MSG_ON_ERR);
4569 res |= loop_res;
4571 if (quiet)
4572 continue;
4574 if (loop_res)
4575 strbuf_addf(&error_msg, "\t%s\n", item->string);
4576 else
4577 strbuf_addf(&update_msg, "\t%s\n", item->string);
4580 if (!quiet &&
4581 (update_msg.len || error_msg.len)) {
4582 fprintf(stderr,
4583 _("Updated the following refs with %s:\n%s"),
4584 "--update-refs",
4585 update_msg.buf);
4587 if (res)
4588 fprintf(stderr,
4589 _("Failed to update the following refs with %s:\n%s"),
4590 "--update-refs",
4591 error_msg.buf);
4594 string_list_clear(&refs_to_oids, 1);
4595 strbuf_release(&update_msg);
4596 strbuf_release(&error_msg);
4597 return res;
4600 static int is_final_fixup(struct todo_list *todo_list)
4602 int i = todo_list->current;
4604 if (!is_fixup(todo_list->items[i].command))
4605 return 0;
4607 while (++i < todo_list->nr)
4608 if (is_fixup(todo_list->items[i].command))
4609 return 0;
4610 else if (!is_noop(todo_list->items[i].command))
4611 break;
4612 return 1;
4615 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4617 int i;
4619 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4620 if (!is_noop(todo_list->items[i].command))
4621 return todo_list->items[i].command;
4623 return -1;
4626 static void create_autostash_internal(struct repository *r,
4627 const char *path,
4628 const char *refname)
4630 struct strbuf buf = STRBUF_INIT;
4631 struct lock_file lock_file = LOCK_INIT;
4632 int fd;
4634 if (path && refname)
4635 BUG("can only pass path or refname");
4637 fd = repo_hold_locked_index(r, &lock_file, 0);
4638 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4639 if (0 <= fd)
4640 repo_update_index_if_able(r, &lock_file);
4641 rollback_lock_file(&lock_file);
4643 if (has_unstaged_changes(r, 1) ||
4644 has_uncommitted_changes(r, 1)) {
4645 struct child_process stash = CHILD_PROCESS_INIT;
4646 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4647 struct object_id oid;
4649 strvec_pushl(&stash.args,
4650 "stash", "create", "autostash", NULL);
4651 stash.git_cmd = 1;
4652 stash.no_stdin = 1;
4653 strbuf_reset(&buf);
4654 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4655 die(_("Cannot autostash"));
4656 strbuf_trim_trailing_newline(&buf);
4657 if (repo_get_oid(r, buf.buf, &oid))
4658 die(_("Unexpected stash response: '%s'"),
4659 buf.buf);
4660 strbuf_reset(&buf);
4661 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4663 if (path) {
4664 if (safe_create_leading_directories_const(path))
4665 die(_("Could not create directory for '%s'"),
4666 path);
4667 write_file(path, "%s", oid_to_hex(&oid));
4668 } else {
4669 refs_update_ref(get_main_ref_store(r), "", refname,
4670 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4673 printf(_("Created autostash: %s\n"), buf.buf);
4674 if (reset_head(r, &ropts) < 0)
4675 die(_("could not reset --hard"));
4676 discard_index(r->index);
4677 if (repo_read_index(r) < 0)
4678 die(_("could not read index"));
4680 strbuf_release(&buf);
4683 void create_autostash(struct repository *r, const char *path)
4685 create_autostash_internal(r, path, NULL);
4688 void create_autostash_ref(struct repository *r, const char *refname)
4690 create_autostash_internal(r, NULL, refname);
4693 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4695 struct child_process child = CHILD_PROCESS_INIT;
4696 int ret = 0;
4698 if (attempt_apply) {
4699 child.git_cmd = 1;
4700 child.no_stdout = 1;
4701 child.no_stderr = 1;
4702 strvec_push(&child.args, "stash");
4703 strvec_push(&child.args, "apply");
4704 strvec_push(&child.args, stash_oid);
4705 ret = run_command(&child);
4708 if (attempt_apply && !ret)
4709 fprintf(stderr, _("Applied autostash.\n"));
4710 else {
4711 struct child_process store = CHILD_PROCESS_INIT;
4713 store.git_cmd = 1;
4714 strvec_push(&store.args, "stash");
4715 strvec_push(&store.args, "store");
4716 strvec_push(&store.args, "-m");
4717 strvec_push(&store.args, "autostash");
4718 strvec_push(&store.args, "-q");
4719 strvec_push(&store.args, stash_oid);
4720 if (run_command(&store))
4721 ret = error(_("cannot store %s"), stash_oid);
4722 else
4723 fprintf(stderr,
4724 _("%s\n"
4725 "Your changes are safe in the stash.\n"
4726 "You can run \"git stash pop\" or"
4727 " \"git stash drop\" at any time.\n"),
4728 attempt_apply ?
4729 _("Applying autostash resulted in conflicts.") :
4730 _("Autostash exists; creating a new stash entry."));
4733 return ret;
4736 static int apply_save_autostash(const char *path, int attempt_apply)
4738 struct strbuf stash_oid = STRBUF_INIT;
4739 int ret = 0;
4741 if (!read_oneliner(&stash_oid, path,
4742 READ_ONELINER_SKIP_IF_EMPTY)) {
4743 strbuf_release(&stash_oid);
4744 return 0;
4746 strbuf_trim(&stash_oid);
4748 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4750 unlink(path);
4751 strbuf_release(&stash_oid);
4752 return ret;
4755 int save_autostash(const char *path)
4757 return apply_save_autostash(path, 0);
4760 int apply_autostash(const char *path)
4762 return apply_save_autostash(path, 1);
4765 int apply_autostash_oid(const char *stash_oid)
4767 return apply_save_autostash_oid(stash_oid, 1);
4770 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4771 int attempt_apply)
4773 struct object_id stash_oid;
4774 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4775 int flag, ret;
4777 if (!refs_ref_exists(get_main_ref_store(r), refname))
4778 return 0;
4780 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4781 RESOLVE_REF_READING, &stash_oid, &flag))
4782 return -1;
4783 if (flag & REF_ISSYMREF)
4784 return error(_("autostash reference is a symref"));
4786 oid_to_hex_r(stash_oid_hex, &stash_oid);
4787 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4789 refs_delete_ref(get_main_ref_store(r), "", refname,
4790 &stash_oid, REF_NO_DEREF);
4792 return ret;
4795 int save_autostash_ref(struct repository *r, const char *refname)
4797 return apply_save_autostash_ref(r, refname, 0);
4800 int apply_autostash_ref(struct repository *r, const char *refname)
4802 return apply_save_autostash_ref(r, refname, 1);
4805 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4806 const char *onto_name, const struct object_id *onto,
4807 const struct object_id *orig_head)
4809 struct reset_head_opts ropts = {
4810 .oid = onto,
4811 .orig_head = orig_head,
4812 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4813 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4814 .head_msg = reflog_message(opts, "start", "checkout %s",
4815 onto_name),
4816 .default_reflog_action = sequencer_reflog_action(opts)
4818 if (reset_head(r, &ropts)) {
4819 apply_autostash(rebase_path_autostash());
4820 sequencer_remove_state(opts);
4821 return error(_("could not detach HEAD"));
4824 return 0;
4827 static int stopped_at_head(struct repository *r)
4829 struct object_id head;
4830 struct commit *commit;
4831 struct commit_message message;
4833 if (repo_get_oid(r, "HEAD", &head) ||
4834 !(commit = lookup_commit(r, &head)) ||
4835 repo_parse_commit(r, commit) || get_message(commit, &message))
4836 fprintf(stderr, _("Stopped at HEAD\n"));
4837 else {
4838 fprintf(stderr, _("Stopped at %s\n"), message.label);
4839 free_message(commit, &message);
4841 return 0;
4845 static int reread_todo_if_changed(struct repository *r,
4846 struct todo_list *todo_list,
4847 struct replay_opts *opts)
4849 int offset;
4850 struct strbuf buf = STRBUF_INIT;
4852 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4853 return -1;
4854 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4855 if (buf.len != todo_list->buf.len - offset ||
4856 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4857 /* Reread the todo file if it has changed. */
4858 todo_list_release(todo_list);
4859 if (read_populate_todo(r, todo_list, opts))
4860 return -1; /* message was printed */
4861 /* `current` will be incremented on return */
4862 todo_list->current = -1;
4864 strbuf_release(&buf);
4866 return 0;
4869 static const char rescheduled_advice[] =
4870 N_("Could not execute the todo command\n"
4871 "\n"
4872 " %.*s"
4873 "\n"
4874 "It has been rescheduled; To edit the command before continuing, please\n"
4875 "edit the todo list first:\n"
4876 "\n"
4877 " git rebase --edit-todo\n"
4878 " git rebase --continue\n");
4880 static int pick_one_commit(struct repository *r,
4881 struct todo_list *todo_list,
4882 struct replay_opts *opts,
4883 int *check_todo, int* reschedule)
4885 struct replay_ctx *ctx = opts->ctx;
4886 int res;
4887 struct todo_item *item = todo_list->items + todo_list->current;
4888 const char *arg = todo_item_get_arg(todo_list, item);
4889 if (is_rebase_i(opts))
4890 ctx->reflog_message = reflog_message(
4891 opts, command_to_string(item->command), NULL);
4893 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4894 check_todo);
4895 if (is_rebase_i(opts) && res < 0) {
4896 /* Reschedule */
4897 *reschedule = 1;
4898 return -1;
4900 if (item->command == TODO_EDIT) {
4901 struct commit *commit = item->commit;
4902 if (!res) {
4903 if (!opts->verbose)
4904 term_clear_line();
4905 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4906 short_commit_name(r, commit), item->arg_len, arg);
4908 return error_with_patch(r, commit,
4909 arg, item->arg_len, opts, res, !res);
4911 if (is_rebase_i(opts) && !res)
4912 record_in_rewritten(&item->commit->object.oid,
4913 peek_command(todo_list, 1));
4914 if (res && is_fixup(item->command)) {
4915 if (res == 1)
4916 intend_to_amend();
4917 return error_failed_squash(r, item->commit, opts,
4918 item->arg_len, arg);
4919 } else if (res && is_rebase_i(opts) && item->commit) {
4920 int to_amend = 0;
4921 struct object_id oid;
4924 * If we are rewording and have either
4925 * fast-forwarded already, or are about to
4926 * create a new root commit, we want to amend,
4927 * otherwise we do not.
4929 if (item->command == TODO_REWORD &&
4930 !repo_get_oid(r, "HEAD", &oid) &&
4931 (oideq(&item->commit->object.oid, &oid) ||
4932 (opts->have_squash_onto &&
4933 oideq(&opts->squash_onto, &oid))))
4934 to_amend = 1;
4936 return res | error_with_patch(r, item->commit,
4937 arg, item->arg_len, opts,
4938 res, to_amend);
4940 return res;
4943 static int pick_commits(struct repository *r,
4944 struct todo_list *todo_list,
4945 struct replay_opts *opts)
4947 struct replay_ctx *ctx = opts->ctx;
4948 int res = 0, reschedule = 0;
4950 ctx->reflog_message = sequencer_reflog_action(opts);
4951 if (opts->allow_ff)
4952 assert(!(opts->signoff || opts->no_commit ||
4953 opts->record_origin || should_edit(opts) ||
4954 opts->committer_date_is_author_date ||
4955 opts->ignore_date));
4956 if (read_and_refresh_cache(r, opts))
4957 return -1;
4959 unlink(rebase_path_message());
4960 unlink(rebase_path_stopped_sha());
4961 unlink(rebase_path_amend());
4962 unlink(rebase_path_patch());
4964 while (todo_list->current < todo_list->nr) {
4965 struct todo_item *item = todo_list->items + todo_list->current;
4966 const char *arg = todo_item_get_arg(todo_list, item);
4967 int check_todo = 0;
4969 if (save_todo(todo_list, opts, reschedule))
4970 return -1;
4971 if (is_rebase_i(opts)) {
4972 if (item->command != TODO_COMMENT) {
4973 FILE *f = fopen(rebase_path_msgnum(), "w");
4975 todo_list->done_nr++;
4977 if (f) {
4978 fprintf(f, "%d\n", todo_list->done_nr);
4979 fclose(f);
4981 if (!opts->quiet)
4982 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4983 todo_list->done_nr,
4984 todo_list->total_nr,
4985 opts->verbose ? "\n" : "\r");
4987 unlink(rebase_path_author_script());
4988 unlink(git_path_merge_head(r));
4989 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4990 NULL, REF_NO_DEREF);
4991 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4992 NULL, REF_NO_DEREF);
4994 if (item->command == TODO_BREAK) {
4995 if (!opts->verbose)
4996 term_clear_line();
4997 return stopped_at_head(r);
5000 strbuf_reset(&ctx->message);
5001 ctx->have_message = 0;
5002 if (item->command <= TODO_SQUASH) {
5003 res = pick_one_commit(r, todo_list, opts, &check_todo,
5004 &reschedule);
5005 if (!res && item->command == TODO_EDIT)
5006 return 0;
5007 } else if (item->command == TODO_EXEC) {
5008 char *end_of_arg = (char *)(arg + item->arg_len);
5009 int saved = *end_of_arg;
5011 if (!opts->verbose)
5012 term_clear_line();
5013 *end_of_arg = '\0';
5014 res = do_exec(r, arg);
5015 *end_of_arg = saved;
5017 if (res) {
5018 if (opts->reschedule_failed_exec)
5019 reschedule = 1;
5021 check_todo = 1;
5022 } else if (item->command == TODO_LABEL) {
5023 if ((res = do_label(r, arg, item->arg_len)))
5024 reschedule = 1;
5025 } else if (item->command == TODO_RESET) {
5026 if ((res = do_reset(r, arg, item->arg_len, opts)))
5027 reschedule = 1;
5028 } else if (item->command == TODO_MERGE) {
5029 if ((res = do_merge(r, item->commit, arg, item->arg_len,
5030 item->flags, &check_todo, opts)) < 0)
5031 reschedule = 1;
5032 else if (item->commit)
5033 record_in_rewritten(&item->commit->object.oid,
5034 peek_command(todo_list, 1));
5035 if (res > 0)
5036 /* failed with merge conflicts */
5037 return error_with_patch(r, item->commit,
5038 arg, item->arg_len,
5039 opts, res, 0);
5040 } else if (item->command == TODO_UPDATE_REF) {
5041 struct strbuf ref = STRBUF_INIT;
5042 strbuf_add(&ref, arg, item->arg_len);
5043 if ((res = do_update_ref(r, ref.buf)))
5044 reschedule = 1;
5045 strbuf_release(&ref);
5046 } else if (!is_noop(item->command))
5047 return error(_("unknown command %d"), item->command);
5049 if (reschedule) {
5050 advise(_(rescheduled_advice),
5051 get_item_line_length(todo_list,
5052 todo_list->current),
5053 get_item_line(todo_list, todo_list->current));
5054 if (save_todo(todo_list, opts, reschedule))
5055 return -1;
5056 if (item->commit)
5057 write_rebase_head(&item->commit->object.oid);
5058 } else if (is_rebase_i(opts) && check_todo && !res &&
5059 reread_todo_if_changed(r, todo_list, opts)) {
5060 return -1;
5063 if (res)
5064 return res;
5066 todo_list->current++;
5069 if (is_rebase_i(opts)) {
5070 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
5071 struct stat st;
5073 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5074 starts_with(head_ref.buf, "refs/")) {
5075 const char *msg;
5076 struct object_id head, orig;
5077 int res;
5079 if (repo_get_oid(r, "HEAD", &head)) {
5080 res = error(_("cannot read HEAD"));
5081 cleanup_head_ref:
5082 strbuf_release(&head_ref);
5083 strbuf_release(&buf);
5084 return res;
5086 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
5087 get_oid_hex(buf.buf, &orig)) {
5088 res = error(_("could not read orig-head"));
5089 goto cleanup_head_ref;
5091 strbuf_reset(&buf);
5092 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5093 res = error(_("could not read 'onto'"));
5094 goto cleanup_head_ref;
5096 msg = reflog_message(opts, "finish", "%s onto %s",
5097 head_ref.buf, buf.buf);
5098 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5099 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
5100 res = error(_("could not update %s"),
5101 head_ref.buf);
5102 goto cleanup_head_ref;
5104 msg = reflog_message(opts, "finish", "returning to %s",
5105 head_ref.buf);
5106 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
5107 res = error(_("could not update HEAD to %s"),
5108 head_ref.buf);
5109 goto cleanup_head_ref;
5111 strbuf_reset(&buf);
5114 if (opts->verbose) {
5115 struct rev_info log_tree_opt;
5116 struct object_id orig, head;
5118 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
5119 repo_init_revisions(r, &log_tree_opt, NULL);
5120 log_tree_opt.diff = 1;
5121 log_tree_opt.diffopt.output_format =
5122 DIFF_FORMAT_DIFFSTAT;
5123 log_tree_opt.disable_stdin = 1;
5125 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
5126 !repo_get_oid(r, buf.buf, &orig) &&
5127 !repo_get_oid(r, "HEAD", &head)) {
5128 diff_tree_oid(&orig, &head, "",
5129 &log_tree_opt.diffopt);
5130 log_tree_diff_flush(&log_tree_opt);
5132 release_revisions(&log_tree_opt);
5134 flush_rewritten_pending();
5135 if (!stat(rebase_path_rewritten_list(), &st) &&
5136 st.st_size > 0) {
5137 struct child_process child = CHILD_PROCESS_INIT;
5138 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5140 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5141 child.git_cmd = 1;
5142 strvec_push(&child.args, "notes");
5143 strvec_push(&child.args, "copy");
5144 strvec_push(&child.args, "--for-rewrite=rebase");
5145 /* we don't care if this copying failed */
5146 run_command(&child);
5148 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5149 strvec_push(&hook_opt.args, "rebase");
5150 run_hooks_opt("post-rewrite", &hook_opt);
5152 apply_autostash(rebase_path_autostash());
5154 if (!opts->quiet) {
5155 if (!opts->verbose)
5156 term_clear_line();
5157 fprintf(stderr,
5158 _("Successfully rebased and updated %s.\n"),
5159 head_ref.buf);
5162 strbuf_release(&buf);
5163 strbuf_release(&head_ref);
5165 if (do_update_refs(r, opts->quiet))
5166 return -1;
5170 * Sequence of picks finished successfully; cleanup by
5171 * removing the .git/sequencer directory
5173 return sequencer_remove_state(opts);
5176 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5178 struct child_process cmd = CHILD_PROCESS_INIT;
5180 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5181 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5182 return error(_("no cherry-pick or revert in progress"));
5184 cmd.git_cmd = 1;
5185 strvec_push(&cmd.args, "commit");
5188 * continue_single_pick() handles the case of recovering from a
5189 * conflict. should_edit() doesn't handle that case; for a conflict,
5190 * we want to edit if the user asked for it, or if they didn't specify
5191 * and stdin is a tty.
5193 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5195 * Include --cleanup=strip as well because we don't want the
5196 * "# Conflicts:" messages.
5198 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5200 return run_command(&cmd);
5203 static int commit_staged_changes(struct repository *r,
5204 struct replay_opts *opts,
5205 struct todo_list *todo_list)
5207 struct replay_ctx *ctx = opts->ctx;
5208 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5209 unsigned int final_fixup = 0, is_clean;
5211 if (has_unstaged_changes(r, 1))
5212 return error(_("cannot rebase: You have unstaged changes."));
5214 is_clean = !has_uncommitted_changes(r, 0);
5216 if (!is_clean && !file_exists(rebase_path_message())) {
5217 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5219 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5221 if (file_exists(rebase_path_amend())) {
5222 struct strbuf rev = STRBUF_INIT;
5223 struct object_id head, to_amend;
5225 if (repo_get_oid(r, "HEAD", &head))
5226 return error(_("cannot amend non-existing commit"));
5227 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5228 return error(_("invalid file: '%s'"), rebase_path_amend());
5229 if (get_oid_hex(rev.buf, &to_amend))
5230 return error(_("invalid contents: '%s'"),
5231 rebase_path_amend());
5232 if (!is_clean && !oideq(&head, &to_amend))
5233 return error(_("\nYou have uncommitted changes in your "
5234 "working tree. Please, commit them\n"
5235 "first and then run 'git rebase "
5236 "--continue' again."));
5238 * When skipping a failed fixup/squash, we need to edit the
5239 * commit message, the current fixup list and count, and if it
5240 * was the last fixup/squash in the chain, we need to clean up
5241 * the commit message and if there was a squash, let the user
5242 * edit it.
5244 if (!is_clean || !ctx->current_fixup_count)
5245 ; /* this is not the final fixup */
5246 else if (!oideq(&head, &to_amend) ||
5247 !file_exists(rebase_path_stopped_sha())) {
5248 /* was a final fixup or squash done manually? */
5249 if (!is_fixup(peek_command(todo_list, 0))) {
5250 unlink(rebase_path_fixup_msg());
5251 unlink(rebase_path_squash_msg());
5252 unlink(rebase_path_current_fixups());
5253 strbuf_reset(&ctx->current_fixups);
5254 ctx->current_fixup_count = 0;
5256 } else {
5257 /* we are in a fixup/squash chain */
5258 const char *p = ctx->current_fixups.buf;
5259 int len = ctx->current_fixups.len;
5261 ctx->current_fixup_count--;
5262 if (!len)
5263 BUG("Incorrect current_fixups:\n%s", p);
5264 while (len && p[len - 1] != '\n')
5265 len--;
5266 strbuf_setlen(&ctx->current_fixups, len);
5267 if (write_message(p, len, rebase_path_current_fixups(),
5268 0) < 0)
5269 return error(_("could not write file: '%s'"),
5270 rebase_path_current_fixups());
5273 * If a fixup/squash in a fixup/squash chain failed, the
5274 * commit message is already correct, no need to commit
5275 * it again.
5277 * Only if it is the final command in the fixup/squash
5278 * chain, and only if the chain is longer than a single
5279 * fixup/squash command (which was just skipped), do we
5280 * actually need to re-commit with a cleaned up commit
5281 * message.
5283 if (ctx->current_fixup_count > 0 &&
5284 !is_fixup(peek_command(todo_list, 0))) {
5285 final_fixup = 1;
5287 * If there was not a single "squash" in the
5288 * chain, we only need to clean up the commit
5289 * message, no need to bother the user with
5290 * opening the commit message in the editor.
5292 if (!starts_with(p, "squash ") &&
5293 !strstr(p, "\nsquash "))
5294 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5295 } else if (is_fixup(peek_command(todo_list, 0))) {
5297 * We need to update the squash message to skip
5298 * the latest commit message.
5300 int res = 0;
5301 struct commit *commit;
5302 const char *msg;
5303 const char *path = rebase_path_squash_msg();
5304 const char *encoding = get_commit_output_encoding();
5306 if (parse_head(r, &commit))
5307 return error(_("could not parse HEAD"));
5309 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5310 if (!p) {
5311 res = error(_("could not parse commit %s"),
5312 oid_to_hex(&commit->object.oid));
5313 goto unuse_commit_buffer;
5315 find_commit_subject(p, &msg);
5316 if (write_message(msg, strlen(msg), path, 0)) {
5317 res = error(_("could not write file: "
5318 "'%s'"), path);
5319 goto unuse_commit_buffer;
5321 unuse_commit_buffer:
5322 repo_unuse_commit_buffer(r, commit, p);
5323 if (res)
5324 return res;
5328 strbuf_release(&rev);
5329 flags |= AMEND_MSG;
5332 if (is_clean) {
5333 if (refs_ref_exists(get_main_ref_store(r),
5334 "CHERRY_PICK_HEAD") &&
5335 refs_delete_ref(get_main_ref_store(r), "",
5336 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
5337 return error(_("could not remove CHERRY_PICK_HEAD"));
5338 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5339 return error_errno(_("could not remove '%s'"),
5340 git_path_merge_msg(r));
5341 if (!final_fixup)
5342 return 0;
5345 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5346 opts, flags))
5347 return error(_("could not commit staged changes."));
5348 unlink(rebase_path_amend());
5349 unlink(git_path_merge_head(r));
5350 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5351 NULL, REF_NO_DEREF);
5352 if (final_fixup) {
5353 unlink(rebase_path_fixup_msg());
5354 unlink(rebase_path_squash_msg());
5356 if (ctx->current_fixup_count > 0) {
5358 * Whether final fixup or not, we just cleaned up the commit
5359 * message...
5361 unlink(rebase_path_current_fixups());
5362 strbuf_reset(&ctx->current_fixups);
5363 ctx->current_fixup_count = 0;
5365 return 0;
5368 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5370 struct replay_ctx *ctx = opts->ctx;
5371 struct todo_list todo_list = TODO_LIST_INIT;
5372 int res;
5374 if (read_and_refresh_cache(r, opts))
5375 return -1;
5377 if (read_populate_opts(opts))
5378 return -1;
5379 if (is_rebase_i(opts)) {
5380 if ((res = read_populate_todo(r, &todo_list, opts)))
5381 goto release_todo_list;
5383 if (file_exists(rebase_path_dropped())) {
5384 if ((res = todo_list_check_against_backup(r, opts,
5385 &todo_list)))
5386 goto release_todo_list;
5388 unlink(rebase_path_dropped());
5391 ctx->reflog_message = reflog_message(opts, "continue", NULL);
5392 if (commit_staged_changes(r, opts, &todo_list)) {
5393 res = -1;
5394 goto release_todo_list;
5396 } else if (!file_exists(get_todo_path(opts)))
5397 return continue_single_pick(r, opts);
5398 else if ((res = read_populate_todo(r, &todo_list, opts)))
5399 goto release_todo_list;
5401 if (!is_rebase_i(opts)) {
5402 /* Verify that the conflict has been resolved */
5403 if (refs_ref_exists(get_main_ref_store(r),
5404 "CHERRY_PICK_HEAD") ||
5405 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5406 res = continue_single_pick(r, opts);
5407 if (res)
5408 goto release_todo_list;
5410 if (index_differs_from(r, "HEAD", NULL, 0)) {
5411 res = error_dirty_index(r, opts);
5412 goto release_todo_list;
5414 todo_list.current++;
5415 } else if (file_exists(rebase_path_stopped_sha())) {
5416 struct strbuf buf = STRBUF_INIT;
5417 struct object_id oid;
5419 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5420 READ_ONELINER_SKIP_IF_EMPTY) &&
5421 !get_oid_hex(buf.buf, &oid))
5422 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5423 strbuf_release(&buf);
5426 res = pick_commits(r, &todo_list, opts);
5427 release_todo_list:
5428 todo_list_release(&todo_list);
5429 return res;
5432 static int single_pick(struct repository *r,
5433 struct commit *cmit,
5434 struct replay_opts *opts)
5436 int check_todo;
5437 struct todo_item item;
5439 item.command = opts->action == REPLAY_PICK ?
5440 TODO_PICK : TODO_REVERT;
5441 item.commit = cmit;
5443 opts->ctx->reflog_message = sequencer_reflog_action(opts);
5444 return do_pick_commit(r, &item, opts, 0, &check_todo);
5447 int sequencer_pick_revisions(struct repository *r,
5448 struct replay_opts *opts)
5450 struct todo_list todo_list = TODO_LIST_INIT;
5451 struct object_id oid;
5452 int i, res;
5454 assert(opts->revs);
5455 if (read_and_refresh_cache(r, opts))
5456 return -1;
5458 for (i = 0; i < opts->revs->pending.nr; i++) {
5459 struct object_id oid;
5460 const char *name = opts->revs->pending.objects[i].name;
5462 /* This happens when using --stdin. */
5463 if (!strlen(name))
5464 continue;
5466 if (!repo_get_oid(r, name, &oid)) {
5467 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5468 enum object_type type = oid_object_info(r,
5469 &oid,
5470 NULL);
5471 return error(_("%s: can't cherry-pick a %s"),
5472 name, type_name(type));
5474 } else
5475 return error(_("%s: bad revision"), name);
5479 * If we were called as "git cherry-pick <commit>", just
5480 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5481 * REVERT_HEAD, and don't touch the sequencer state.
5482 * This means it is possible to cherry-pick in the middle
5483 * of a cherry-pick sequence.
5485 if (opts->revs->cmdline.nr == 1 &&
5486 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5487 opts->revs->no_walk &&
5488 !opts->revs->cmdline.rev->flags) {
5489 struct commit *cmit;
5490 if (prepare_revision_walk(opts->revs))
5491 return error(_("revision walk setup failed"));
5492 cmit = get_revision(opts->revs);
5493 if (!cmit)
5494 return error(_("empty commit set passed"));
5495 if (get_revision(opts->revs))
5496 BUG("unexpected extra commit from walk");
5497 return single_pick(r, cmit, opts);
5501 * Start a new cherry-pick/ revert sequence; but
5502 * first, make sure that an existing one isn't in
5503 * progress
5506 if (walk_revs_populate_todo(&todo_list, opts) ||
5507 create_seq_dir(r) < 0)
5508 return -1;
5509 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5510 return error(_("can't revert as initial commit"));
5511 if (save_head(oid_to_hex(&oid)))
5512 return -1;
5513 if (save_opts(opts))
5514 return -1;
5515 update_abort_safety_file();
5516 res = pick_commits(r, &todo_list, opts);
5517 todo_list_release(&todo_list);
5518 return res;
5521 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5523 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5524 struct strbuf sob = STRBUF_INIT;
5525 int has_footer;
5527 strbuf_addstr(&sob, sign_off_header);
5528 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5529 strbuf_addch(&sob, '\n');
5531 if (!ignore_footer)
5532 strbuf_complete_line(msgbuf);
5535 * If the whole message buffer is equal to the sob, pretend that we
5536 * found a conforming footer with a matching sob
5538 if (msgbuf->len - ignore_footer == sob.len &&
5539 !strncmp(msgbuf->buf, sob.buf, sob.len))
5540 has_footer = 3;
5541 else
5542 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5544 if (!has_footer) {
5545 const char *append_newlines = NULL;
5546 size_t len = msgbuf->len - ignore_footer;
5548 if (!len) {
5550 * The buffer is completely empty. Leave foom for
5551 * the title and body to be filled in by the user.
5553 append_newlines = "\n\n";
5554 } else if (len == 1) {
5556 * Buffer contains a single newline. Add another
5557 * so that we leave room for the title and body.
5559 append_newlines = "\n";
5560 } else if (msgbuf->buf[len - 2] != '\n') {
5562 * Buffer ends with a single newline. Add another
5563 * so that there is an empty line between the message
5564 * body and the sob.
5566 append_newlines = "\n";
5567 } /* else, the buffer already ends with two newlines. */
5569 if (append_newlines)
5570 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5571 append_newlines, strlen(append_newlines));
5574 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5575 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5576 sob.buf, sob.len);
5578 strbuf_release(&sob);
5581 struct labels_entry {
5582 struct hashmap_entry entry;
5583 char label[FLEX_ARRAY];
5586 static int labels_cmp(const void *fndata UNUSED,
5587 const struct hashmap_entry *eptr,
5588 const struct hashmap_entry *entry_or_key, const void *key)
5590 const struct labels_entry *a, *b;
5592 a = container_of(eptr, const struct labels_entry, entry);
5593 b = container_of(entry_or_key, const struct labels_entry, entry);
5595 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5598 struct string_entry {
5599 struct oidmap_entry entry;
5600 char string[FLEX_ARRAY];
5603 struct label_state {
5604 struct oidmap commit2label;
5605 struct hashmap labels;
5606 struct strbuf buf;
5607 int max_label_length;
5610 static const char *label_oid(struct object_id *oid, const char *label,
5611 struct label_state *state)
5613 struct labels_entry *labels_entry;
5614 struct string_entry *string_entry;
5615 struct object_id dummy;
5616 int i;
5618 string_entry = oidmap_get(&state->commit2label, oid);
5619 if (string_entry)
5620 return string_entry->string;
5623 * For "uninteresting" commits, i.e. commits that are not to be
5624 * rebased, and which can therefore not be labeled, we use a unique
5625 * abbreviation of the commit name. This is slightly more complicated
5626 * than calling repo_find_unique_abbrev() because we also need to make
5627 * sure that the abbreviation does not conflict with any other
5628 * label.
5630 * We disallow "interesting" commits to be labeled by a string that
5631 * is a valid full-length hash, to ensure that we always can find an
5632 * abbreviation for any uninteresting commit's names that does not
5633 * clash with any other label.
5635 strbuf_reset(&state->buf);
5636 if (!label) {
5637 char *p;
5639 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5640 label = p = state->buf.buf;
5642 repo_find_unique_abbrev_r(the_repository, p, oid,
5643 default_abbrev);
5646 * We may need to extend the abbreviated hash so that there is
5647 * no conflicting label.
5649 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5650 size_t i = strlen(p) + 1;
5652 oid_to_hex_r(p, oid);
5653 for (; i < the_hash_algo->hexsz; i++) {
5654 char save = p[i];
5655 p[i] = '\0';
5656 if (!hashmap_get_from_hash(&state->labels,
5657 strihash(p), p))
5658 break;
5659 p[i] = save;
5662 } else {
5663 struct strbuf *buf = &state->buf;
5664 int label_is_utf8 = 1; /* start with this assumption */
5665 size_t max_len = buf->len + state->max_label_length;
5668 * Sanitize labels by replacing non-alpha-numeric characters
5669 * (including white-space ones) by dashes, as they might be
5670 * illegal in file names (and hence in ref names).
5672 * Note that we retain non-ASCII UTF-8 characters (identified
5673 * via the most significant bit). They should be all acceptable
5674 * in file names.
5676 * As we will use the labels as names of (loose) refs, it is
5677 * vital that the name not be longer than the maximum component
5678 * size of the file system (`NAME_MAX`). We are careful to
5679 * truncate the label accordingly, allowing for the `.lock`
5680 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5681 * truncating in the middle of a character).
5683 for (; *label && buf->len + 1 < max_len; label++)
5684 if (isalnum(*label) ||
5685 (!label_is_utf8 && (*label & 0x80)))
5686 strbuf_addch(buf, *label);
5687 else if (*label & 0x80) {
5688 const char *p = label;
5690 utf8_width(&p, NULL);
5691 if (p) {
5692 if (buf->len + (p - label) > max_len)
5693 break;
5694 strbuf_add(buf, label, p - label);
5695 label = p - 1;
5696 } else {
5697 label_is_utf8 = 0;
5698 strbuf_addch(buf, *label);
5700 /* avoid leading dash and double-dashes */
5701 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5702 strbuf_addch(buf, '-');
5703 if (!buf->len) {
5704 strbuf_addstr(buf, "rev-");
5705 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5707 label = buf->buf;
5709 if ((buf->len == the_hash_algo->hexsz &&
5710 !get_oid_hex(label, &dummy)) ||
5711 (buf->len == 1 && *label == '#') ||
5712 hashmap_get_from_hash(&state->labels,
5713 strihash(label), label)) {
5715 * If the label already exists, or if the label is a
5716 * valid full OID, or the label is a '#' (which we use
5717 * as a separator between merge heads and oneline), we
5718 * append a dash and a number to make it unique.
5720 size_t len = buf->len;
5722 for (i = 2; ; i++) {
5723 strbuf_setlen(buf, len);
5724 strbuf_addf(buf, "-%d", i);
5725 if (!hashmap_get_from_hash(&state->labels,
5726 strihash(buf->buf),
5727 buf->buf))
5728 break;
5731 label = buf->buf;
5735 FLEX_ALLOC_STR(labels_entry, label, label);
5736 hashmap_entry_init(&labels_entry->entry, strihash(label));
5737 hashmap_add(&state->labels, &labels_entry->entry);
5739 FLEX_ALLOC_STR(string_entry, string, label);
5740 oidcpy(&string_entry->entry.oid, oid);
5741 oidmap_put(&state->commit2label, string_entry);
5743 return string_entry->string;
5746 static int make_script_with_merges(struct pretty_print_context *pp,
5747 struct rev_info *revs, struct strbuf *out,
5748 unsigned flags)
5750 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5751 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5752 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5753 int skipped_commit = 0;
5754 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5755 struct strbuf label = STRBUF_INIT;
5756 struct commit_list *commits = NULL, **tail = &commits, *iter;
5757 struct commit_list *tips = NULL, **tips_tail = &tips;
5758 struct commit *commit;
5759 struct oidmap commit2todo = OIDMAP_INIT;
5760 struct string_entry *entry;
5761 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5762 shown = OIDSET_INIT;
5763 struct label_state state =
5764 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5766 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5767 const char *cmd_pick = abbr ? "p" : "pick",
5768 *cmd_label = abbr ? "l" : "label",
5769 *cmd_reset = abbr ? "t" : "reset",
5770 *cmd_merge = abbr ? "m" : "merge";
5772 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5774 oidmap_init(&commit2todo, 0);
5775 oidmap_init(&state.commit2label, 0);
5776 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5777 strbuf_init(&state.buf, 32);
5779 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5780 struct labels_entry *onto_label_entry;
5781 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5782 FLEX_ALLOC_STR(entry, string, "onto");
5783 oidcpy(&entry->entry.oid, oid);
5784 oidmap_put(&state.commit2label, entry);
5786 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5787 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5788 hashmap_add(&state.labels, &onto_label_entry->entry);
5792 * First phase:
5793 * - get onelines for all commits
5794 * - gather all branch tips (i.e. 2nd or later parents of merges)
5795 * - label all branch tips
5797 while ((commit = get_revision(revs))) {
5798 struct commit_list *to_merge;
5799 const char *p1, *p2;
5800 struct object_id *oid;
5801 int is_empty;
5803 tail = &commit_list_insert(commit, tail)->next;
5804 oidset_insert(&interesting, &commit->object.oid);
5806 is_empty = is_original_commit_empty(commit);
5807 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5808 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5809 warning(_("skipped previously applied commit %s"),
5810 short_commit_name(the_repository, commit));
5811 skipped_commit = 1;
5812 continue;
5814 if (is_empty && !keep_empty)
5815 continue;
5817 strbuf_reset(&oneline);
5818 pretty_print_commit(pp, commit, &oneline);
5820 to_merge = commit->parents ? commit->parents->next : NULL;
5821 if (!to_merge) {
5822 /* non-merge commit: easy case */
5823 strbuf_reset(&buf);
5824 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5825 oid_to_hex(&commit->object.oid),
5826 oneline.buf);
5827 if (is_empty)
5828 strbuf_addf(&buf, " %s empty",
5829 comment_line_str);
5831 FLEX_ALLOC_STR(entry, string, buf.buf);
5832 oidcpy(&entry->entry.oid, &commit->object.oid);
5833 oidmap_put(&commit2todo, entry);
5835 continue;
5838 /* Create a label */
5839 strbuf_reset(&label);
5840 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5841 (p1 = strchr(p1, '\'')) &&
5842 (p2 = strchr(++p1, '\'')))
5843 strbuf_add(&label, p1, p2 - p1);
5844 else if (skip_prefix(oneline.buf, "Merge pull request ",
5845 &p1) &&
5846 (p1 = strstr(p1, " from ")))
5847 strbuf_addstr(&label, p1 + strlen(" from "));
5848 else
5849 strbuf_addbuf(&label, &oneline);
5851 strbuf_reset(&buf);
5852 strbuf_addf(&buf, "%s -C %s",
5853 cmd_merge, oid_to_hex(&commit->object.oid));
5855 /* label the tips of merged branches */
5856 for (; to_merge; to_merge = to_merge->next) {
5857 oid = &to_merge->item->object.oid;
5858 strbuf_addch(&buf, ' ');
5860 if (!oidset_contains(&interesting, oid)) {
5861 strbuf_addstr(&buf, label_oid(oid, NULL,
5862 &state));
5863 continue;
5866 tips_tail = &commit_list_insert(to_merge->item,
5867 tips_tail)->next;
5869 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5871 strbuf_addf(&buf, " # %s", oneline.buf);
5873 FLEX_ALLOC_STR(entry, string, buf.buf);
5874 oidcpy(&entry->entry.oid, &commit->object.oid);
5875 oidmap_put(&commit2todo, entry);
5877 if (skipped_commit)
5878 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5879 _("use --reapply-cherry-picks to include skipped commits"));
5882 * Second phase:
5883 * - label branch points
5884 * - add HEAD to the branch tips
5886 for (iter = commits; iter; iter = iter->next) {
5887 struct commit_list *parent = iter->item->parents;
5888 for (; parent; parent = parent->next) {
5889 struct object_id *oid = &parent->item->object.oid;
5890 if (!oidset_contains(&interesting, oid))
5891 continue;
5892 if (oidset_insert(&child_seen, oid))
5893 label_oid(oid, "branch-point", &state);
5896 /* Add HEAD as implicit "tip of branch" */
5897 if (!iter->next)
5898 tips_tail = &commit_list_insert(iter->item,
5899 tips_tail)->next;
5903 * Third phase: output the todo list. This is a bit tricky, as we
5904 * want to avoid jumping back and forth between revisions. To
5905 * accomplish that goal, we walk backwards from the branch tips,
5906 * gathering commits not yet shown, reversing the list on the fly,
5907 * then outputting that list (labeling revisions as needed).
5909 strbuf_addf(out, "%s onto\n", cmd_label);
5910 for (iter = tips; iter; iter = iter->next) {
5911 struct commit_list *list = NULL, *iter2;
5913 commit = iter->item;
5914 if (oidset_contains(&shown, &commit->object.oid))
5915 continue;
5916 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5918 if (entry)
5919 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
5920 else
5921 strbuf_addch(out, '\n');
5923 while (oidset_contains(&interesting, &commit->object.oid) &&
5924 !oidset_contains(&shown, &commit->object.oid)) {
5925 commit_list_insert(commit, &list);
5926 if (!commit->parents) {
5927 commit = NULL;
5928 break;
5930 commit = commit->parents->item;
5933 if (!commit)
5934 strbuf_addf(out, "%s %s\n", cmd_reset,
5935 rebase_cousins || root_with_onto ?
5936 "onto" : "[new root]");
5937 else {
5938 const char *to = NULL;
5940 entry = oidmap_get(&state.commit2label,
5941 &commit->object.oid);
5942 if (entry)
5943 to = entry->string;
5944 else if (!rebase_cousins)
5945 to = label_oid(&commit->object.oid, NULL,
5946 &state);
5948 if (!to || !strcmp(to, "onto"))
5949 strbuf_addf(out, "%s onto\n", cmd_reset);
5950 else {
5951 strbuf_reset(&oneline);
5952 pretty_print_commit(pp, commit, &oneline);
5953 strbuf_addf(out, "%s %s # %s\n",
5954 cmd_reset, to, oneline.buf);
5958 for (iter2 = list; iter2; iter2 = iter2->next) {
5959 struct object_id *oid = &iter2->item->object.oid;
5960 entry = oidmap_get(&commit2todo, oid);
5961 /* only show if not already upstream */
5962 if (entry)
5963 strbuf_addf(out, "%s\n", entry->string);
5964 entry = oidmap_get(&state.commit2label, oid);
5965 if (entry)
5966 strbuf_addf(out, "%s %s\n",
5967 cmd_label, entry->string);
5968 oidset_insert(&shown, oid);
5971 free_commit_list(list);
5974 free_commit_list(commits);
5975 free_commit_list(tips);
5977 strbuf_release(&label);
5978 strbuf_release(&oneline);
5979 strbuf_release(&buf);
5981 oidmap_free(&commit2todo, 1);
5982 oidmap_free(&state.commit2label, 1);
5983 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5984 strbuf_release(&state.buf);
5986 return 0;
5989 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5990 const char **argv, unsigned flags)
5992 char *format = NULL;
5993 struct pretty_print_context pp = {0};
5994 struct rev_info revs;
5995 struct commit *commit;
5996 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5997 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5998 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5999 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
6000 int skipped_commit = 0;
6001 int ret = 0;
6003 repo_init_revisions(r, &revs, NULL);
6004 revs.verbose_header = 1;
6005 if (!rebase_merges)
6006 revs.max_parents = 1;
6007 revs.cherry_mark = !reapply_cherry_picks;
6008 revs.limited = 1;
6009 revs.reverse = 1;
6010 revs.right_only = 1;
6011 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
6012 revs.topo_order = 1;
6014 revs.pretty_given = 1;
6015 git_config_get_string("rebase.instructionFormat", &format);
6016 if (!format || !*format) {
6017 free(format);
6018 format = xstrdup("%s");
6020 get_commit_format(format, &revs);
6021 free(format);
6022 pp.fmt = revs.commit_format;
6023 pp.output_encoding = get_log_output_encoding();
6025 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
6026 ret = error(_("make_script: unhandled options"));
6027 goto cleanup;
6030 if (prepare_revision_walk(&revs) < 0) {
6031 ret = error(_("make_script: error preparing revisions"));
6032 goto cleanup;
6035 if (rebase_merges) {
6036 ret = make_script_with_merges(&pp, &revs, out, flags);
6037 goto cleanup;
6040 while ((commit = get_revision(&revs))) {
6041 int is_empty = is_original_commit_empty(commit);
6043 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6044 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6045 warning(_("skipped previously applied commit %s"),
6046 short_commit_name(r, commit));
6047 skipped_commit = 1;
6048 continue;
6050 if (is_empty && !keep_empty)
6051 continue;
6052 strbuf_addf(out, "%s %s ", insn,
6053 oid_to_hex(&commit->object.oid));
6054 pretty_print_commit(&pp, commit, out);
6055 if (is_empty)
6056 strbuf_addf(out, " %s empty", comment_line_str);
6057 strbuf_addch(out, '\n');
6059 if (skipped_commit)
6060 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6061 _("use --reapply-cherry-picks to include skipped commits"));
6062 cleanup:
6063 release_revisions(&revs);
6064 return ret;
6068 * Add commands after pick and (series of) squash/fixup commands
6069 * in the todo list.
6071 static void todo_list_add_exec_commands(struct todo_list *todo_list,
6072 struct string_list *commands)
6074 struct strbuf *buf = &todo_list->buf;
6075 size_t base_offset = buf->len;
6076 int i, insert, nr = 0, alloc = 0;
6077 struct todo_item *items = NULL, *base_items = NULL;
6079 CALLOC_ARRAY(base_items, commands->nr);
6080 for (i = 0; i < commands->nr; i++) {
6081 size_t command_len = strlen(commands->items[i].string);
6083 strbuf_addstr(buf, commands->items[i].string);
6084 strbuf_addch(buf, '\n');
6086 base_items[i].command = TODO_EXEC;
6087 base_items[i].offset_in_buf = base_offset;
6088 base_items[i].arg_offset = base_offset;
6089 base_items[i].arg_len = command_len;
6091 base_offset += command_len + 1;
6095 * Insert <commands> after every pick. Here, fixup/squash chains
6096 * are considered part of the pick, so we insert the commands *after*
6097 * those chains if there are any.
6099 * As we insert the exec commands immediately after rearranging
6100 * any fixups and before the user edits the list, a fixup chain
6101 * can never contain comments (any comments are empty picks that
6102 * have been commented out because the user did not specify
6103 * --keep-empty). So, it is safe to insert an exec command
6104 * without looking at the command following a comment.
6106 insert = 0;
6107 for (i = 0; i < todo_list->nr; i++) {
6108 enum todo_command command = todo_list->items[i].command;
6109 if (insert && !is_fixup(command)) {
6110 ALLOC_GROW(items, nr + commands->nr, alloc);
6111 COPY_ARRAY(items + nr, base_items, commands->nr);
6112 nr += commands->nr;
6114 insert = 0;
6117 ALLOC_GROW(items, nr + 1, alloc);
6118 items[nr++] = todo_list->items[i];
6120 if (command == TODO_PICK || command == TODO_MERGE)
6121 insert = 1;
6124 /* insert or append final <commands> */
6125 if (insert) {
6126 ALLOC_GROW(items, nr + commands->nr, alloc);
6127 COPY_ARRAY(items + nr, base_items, commands->nr);
6128 nr += commands->nr;
6131 free(base_items);
6132 FREE_AND_NULL(todo_list->items);
6133 todo_list->items = items;
6134 todo_list->nr = nr;
6135 todo_list->alloc = alloc;
6138 static void todo_list_to_strbuf(struct repository *r,
6139 struct todo_list *todo_list,
6140 struct strbuf *buf, int num, unsigned flags)
6142 struct todo_item *item;
6143 int i, max = todo_list->nr;
6145 if (num > 0 && num < max)
6146 max = num;
6148 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6149 char cmd;
6151 /* if the item is not a command write it and continue */
6152 if (item->command >= TODO_COMMENT) {
6153 strbuf_addf(buf, "%.*s\n", item->arg_len,
6154 todo_item_get_arg(todo_list, item));
6155 continue;
6158 /* add command to the buffer */
6159 cmd = command_to_char(item->command);
6160 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6161 strbuf_addch(buf, cmd);
6162 else
6163 strbuf_addstr(buf, command_to_string(item->command));
6165 /* add commit id */
6166 if (item->commit) {
6167 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6168 short_commit_name(r, item->commit) :
6169 oid_to_hex(&item->commit->object.oid);
6171 if (item->command == TODO_FIXUP) {
6172 if (item->flags & TODO_EDIT_FIXUP_MSG)
6173 strbuf_addstr(buf, " -c");
6174 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6175 strbuf_addstr(buf, " -C");
6179 if (item->command == TODO_MERGE) {
6180 if (item->flags & TODO_EDIT_MERGE_MSG)
6181 strbuf_addstr(buf, " -c");
6182 else
6183 strbuf_addstr(buf, " -C");
6186 strbuf_addf(buf, " %s", oid);
6189 /* add all the rest */
6190 if (!item->arg_len)
6191 strbuf_addch(buf, '\n');
6192 else
6193 strbuf_addf(buf, " %.*s\n", item->arg_len,
6194 todo_item_get_arg(todo_list, item));
6198 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6199 const char *file, const char *shortrevisions,
6200 const char *shortonto, int num, unsigned flags)
6202 int res;
6203 struct strbuf buf = STRBUF_INIT;
6205 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6206 if (flags & TODO_LIST_APPEND_TODO_HELP)
6207 append_todo_help(count_commands(todo_list),
6208 shortrevisions, shortonto, &buf);
6210 res = write_message(buf.buf, buf.len, file, 0);
6211 strbuf_release(&buf);
6213 return res;
6216 /* skip picking commits whose parents are unchanged */
6217 static int skip_unnecessary_picks(struct repository *r,
6218 struct todo_list *todo_list,
6219 struct object_id *base_oid)
6221 struct object_id *parent_oid;
6222 int i;
6224 for (i = 0; i < todo_list->nr; i++) {
6225 struct todo_item *item = todo_list->items + i;
6227 if (item->command >= TODO_NOOP)
6228 continue;
6229 if (item->command != TODO_PICK)
6230 break;
6231 if (repo_parse_commit(r, item->commit)) {
6232 return error(_("could not parse commit '%s'"),
6233 oid_to_hex(&item->commit->object.oid));
6235 if (!item->commit->parents)
6236 break; /* root commit */
6237 if (item->commit->parents->next)
6238 break; /* merge commit */
6239 parent_oid = &item->commit->parents->item->object.oid;
6240 if (!oideq(parent_oid, base_oid))
6241 break;
6242 oidcpy(base_oid, &item->commit->object.oid);
6244 if (i > 0) {
6245 const char *done_path = rebase_path_done();
6247 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6248 error_errno(_("could not write to '%s'"), done_path);
6249 return -1;
6252 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6253 todo_list->nr -= i;
6254 todo_list->current = 0;
6255 todo_list->done_nr += i;
6257 if (is_fixup(peek_command(todo_list, 0)))
6258 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6261 return 0;
6264 struct todo_add_branch_context {
6265 struct todo_item *items;
6266 size_t items_nr;
6267 size_t items_alloc;
6268 struct strbuf *buf;
6269 struct commit *commit;
6270 struct string_list refs_to_oids;
6273 static int add_decorations_to_list(const struct commit *commit,
6274 struct todo_add_branch_context *ctx)
6276 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6277 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
6278 "HEAD",
6279 RESOLVE_REF_READING,
6280 NULL,
6281 NULL);
6283 while (decoration) {
6284 struct todo_item *item;
6285 const char *path;
6286 size_t base_offset = ctx->buf->len;
6289 * If the branch is the current HEAD, then it will be
6290 * updated by the default rebase behavior.
6292 if (head_ref && !strcmp(head_ref, decoration->name)) {
6293 decoration = decoration->next;
6294 continue;
6297 ALLOC_GROW(ctx->items,
6298 ctx->items_nr + 1,
6299 ctx->items_alloc);
6300 item = &ctx->items[ctx->items_nr];
6301 memset(item, 0, sizeof(*item));
6303 /* If the branch is checked out, then leave a comment instead. */
6304 if ((path = branch_checked_out(decoration->name))) {
6305 item->command = TODO_COMMENT;
6306 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6307 decoration->name, path);
6308 } else {
6309 struct string_list_item *sti;
6310 item->command = TODO_UPDATE_REF;
6311 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6313 sti = string_list_insert(&ctx->refs_to_oids,
6314 decoration->name);
6315 sti->util = init_update_ref_record(decoration->name);
6318 item->offset_in_buf = base_offset;
6319 item->arg_offset = base_offset;
6320 item->arg_len = ctx->buf->len - base_offset;
6321 ctx->items_nr++;
6323 decoration = decoration->next;
6326 return 0;
6330 * For each 'pick' command, find out if the commit has a decoration in
6331 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6333 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6335 int i, res;
6336 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6337 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6338 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6339 struct decoration_filter decoration_filter = {
6340 .include_ref_pattern = &decorate_refs_include,
6341 .exclude_ref_pattern = &decorate_refs_exclude,
6342 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6344 struct todo_add_branch_context ctx = {
6345 .buf = &todo_list->buf,
6346 .refs_to_oids = STRING_LIST_INIT_DUP,
6349 ctx.items_alloc = 2 * todo_list->nr + 1;
6350 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6352 string_list_append(&decorate_refs_include, "refs/heads/");
6353 load_ref_decorations(&decoration_filter, 0);
6355 for (i = 0; i < todo_list->nr; ) {
6356 struct todo_item *item = &todo_list->items[i];
6358 /* insert ith item into new list */
6359 ALLOC_GROW(ctx.items,
6360 ctx.items_nr + 1,
6361 ctx.items_alloc);
6363 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6365 if (item->commit) {
6366 ctx.commit = item->commit;
6367 add_decorations_to_list(item->commit, &ctx);
6371 res = write_update_refs_state(&ctx.refs_to_oids);
6373 string_list_clear(&ctx.refs_to_oids, 1);
6375 if (res) {
6376 /* we failed, so clean up the new list. */
6377 free(ctx.items);
6378 return res;
6381 free(todo_list->items);
6382 todo_list->items = ctx.items;
6383 todo_list->nr = ctx.items_nr;
6384 todo_list->alloc = ctx.items_alloc;
6386 return 0;
6389 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6390 const char *shortrevisions, const char *onto_name,
6391 struct commit *onto, const struct object_id *orig_head,
6392 struct string_list *commands, unsigned autosquash,
6393 unsigned update_refs,
6394 struct todo_list *todo_list)
6396 char shortonto[GIT_MAX_HEXSZ + 1];
6397 const char *todo_file = rebase_path_todo();
6398 struct todo_list new_todo = TODO_LIST_INIT;
6399 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6400 struct object_id oid = onto->object.oid;
6401 int res;
6403 repo_find_unique_abbrev_r(r, shortonto, &oid,
6404 DEFAULT_ABBREV);
6406 if (buf->len == 0) {
6407 struct todo_item *item = append_new_todo(todo_list);
6408 item->command = TODO_NOOP;
6409 item->commit = NULL;
6410 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6413 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6414 return -1;
6416 if (autosquash && todo_list_rearrange_squash(todo_list))
6417 return -1;
6419 if (commands->nr)
6420 todo_list_add_exec_commands(todo_list, commands);
6422 if (count_commands(todo_list) == 0) {
6423 apply_autostash(rebase_path_autostash());
6424 sequencer_remove_state(opts);
6426 return error(_("nothing to do"));
6429 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions,
6430 shortonto, flags);
6431 if (res == -1)
6432 return -1;
6433 else if (res == -2) {
6434 apply_autostash(rebase_path_autostash());
6435 sequencer_remove_state(opts);
6437 return -1;
6438 } else if (res == -3) {
6439 apply_autostash(rebase_path_autostash());
6440 sequencer_remove_state(opts);
6441 todo_list_release(&new_todo);
6443 return error(_("nothing to do"));
6444 } else if (res == -4) {
6445 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6446 todo_list_release(&new_todo);
6448 return -1;
6451 /* Expand the commit IDs */
6452 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6453 strbuf_swap(&new_todo.buf, &buf2);
6454 strbuf_release(&buf2);
6455 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6456 new_todo.total_nr = 0;
6457 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0)
6458 BUG("invalid todo list after expanding IDs:\n%s",
6459 new_todo.buf.buf);
6461 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6462 todo_list_release(&new_todo);
6463 return error(_("could not skip unnecessary pick commands"));
6466 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6467 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6468 todo_list_release(&new_todo);
6469 return error_errno(_("could not write '%s'"), todo_file);
6472 res = -1;
6474 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6475 goto cleanup;
6477 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6478 goto cleanup;
6480 todo_list_write_total_nr(&new_todo);
6481 res = pick_commits(r, &new_todo, opts);
6483 cleanup:
6484 todo_list_release(&new_todo);
6486 return res;
6489 struct subject2item_entry {
6490 struct hashmap_entry entry;
6491 int i;
6492 char subject[FLEX_ARRAY];
6495 static int subject2item_cmp(const void *fndata UNUSED,
6496 const struct hashmap_entry *eptr,
6497 const struct hashmap_entry *entry_or_key,
6498 const void *key)
6500 const struct subject2item_entry *a, *b;
6502 a = container_of(eptr, const struct subject2item_entry, entry);
6503 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6505 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6508 define_commit_slab(commit_todo_item, struct todo_item *);
6510 static int skip_fixupish(const char *subject, const char **p) {
6511 return skip_prefix(subject, "fixup! ", p) ||
6512 skip_prefix(subject, "amend! ", p) ||
6513 skip_prefix(subject, "squash! ", p);
6517 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6518 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6519 * after the former, and change "pick" to "fixup"/"squash".
6521 * Note that if the config has specified a custom instruction format, each log
6522 * message will have to be retrieved from the commit (as the oneline in the
6523 * script cannot be trusted) in order to normalize the autosquash arrangement.
6525 int todo_list_rearrange_squash(struct todo_list *todo_list)
6527 struct hashmap subject2item;
6528 int rearranged = 0, *next, *tail, i, nr = 0;
6529 char **subjects;
6530 struct commit_todo_item commit_todo;
6531 struct todo_item *items = NULL;
6533 init_commit_todo_item(&commit_todo);
6535 * The hashmap maps onelines to the respective todo list index.
6537 * If any items need to be rearranged, the next[i] value will indicate
6538 * which item was moved directly after the i'th.
6540 * In that case, last[i] will indicate the index of the latest item to
6541 * be moved to appear after the i'th.
6543 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6544 ALLOC_ARRAY(next, todo_list->nr);
6545 ALLOC_ARRAY(tail, todo_list->nr);
6546 ALLOC_ARRAY(subjects, todo_list->nr);
6547 for (i = 0; i < todo_list->nr; i++) {
6548 struct strbuf buf = STRBUF_INIT;
6549 struct todo_item *item = todo_list->items + i;
6550 const char *commit_buffer, *subject, *p;
6551 size_t subject_len;
6552 int i2 = -1;
6553 struct subject2item_entry *entry;
6555 next[i] = tail[i] = -1;
6556 if (!item->commit || item->command == TODO_DROP) {
6557 subjects[i] = NULL;
6558 continue;
6561 if (is_fixup(item->command)) {
6562 clear_commit_todo_item(&commit_todo);
6563 return error(_("the script was already rearranged."));
6566 repo_parse_commit(the_repository, item->commit);
6567 commit_buffer = repo_logmsg_reencode(the_repository,
6568 item->commit, NULL,
6569 "UTF-8");
6570 find_commit_subject(commit_buffer, &subject);
6571 format_subject(&buf, subject, " ");
6572 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6573 repo_unuse_commit_buffer(the_repository, item->commit,
6574 commit_buffer);
6575 if (skip_fixupish(subject, &p)) {
6576 struct commit *commit2;
6578 for (;;) {
6579 while (isspace(*p))
6580 p++;
6581 if (!skip_fixupish(p, &p))
6582 break;
6585 entry = hashmap_get_entry_from_hash(&subject2item,
6586 strhash(p), p,
6587 struct subject2item_entry,
6588 entry);
6589 if (entry)
6590 /* found by title */
6591 i2 = entry->i;
6592 else if (!strchr(p, ' ') &&
6593 (commit2 =
6594 lookup_commit_reference_by_name(p)) &&
6595 *commit_todo_item_at(&commit_todo, commit2))
6596 /* found by commit name */
6597 i2 = *commit_todo_item_at(&commit_todo, commit2)
6598 - todo_list->items;
6599 else {
6600 /* copy can be a prefix of the commit subject */
6601 for (i2 = 0; i2 < i; i2++)
6602 if (subjects[i2] &&
6603 starts_with(subjects[i2], p))
6604 break;
6605 if (i2 == i)
6606 i2 = -1;
6609 if (i2 >= 0) {
6610 rearranged = 1;
6611 if (starts_with(subject, "fixup!")) {
6612 todo_list->items[i].command = TODO_FIXUP;
6613 } else if (starts_with(subject, "amend!")) {
6614 todo_list->items[i].command = TODO_FIXUP;
6615 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6616 } else {
6617 todo_list->items[i].command = TODO_SQUASH;
6619 if (tail[i2] < 0) {
6620 next[i] = next[i2];
6621 next[i2] = i;
6622 } else {
6623 next[i] = next[tail[i2]];
6624 next[tail[i2]] = i;
6626 tail[i2] = i;
6627 } else if (!hashmap_get_from_hash(&subject2item,
6628 strhash(subject), subject)) {
6629 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6630 entry->i = i;
6631 hashmap_entry_init(&entry->entry,
6632 strhash(entry->subject));
6633 hashmap_put(&subject2item, &entry->entry);
6636 *commit_todo_item_at(&commit_todo, item->commit) = item;
6639 if (rearranged) {
6640 ALLOC_ARRAY(items, todo_list->nr);
6642 for (i = 0; i < todo_list->nr; i++) {
6643 enum todo_command command = todo_list->items[i].command;
6644 int cur = i;
6647 * Initially, all commands are 'pick's. If it is a
6648 * fixup or a squash now, we have rearranged it.
6650 if (is_fixup(command))
6651 continue;
6653 while (cur >= 0) {
6654 items[nr++] = todo_list->items[cur];
6655 cur = next[cur];
6659 assert(nr == todo_list->nr);
6660 todo_list->alloc = nr;
6661 FREE_AND_NULL(todo_list->items);
6662 todo_list->items = items;
6665 free(next);
6666 free(tail);
6667 for (i = 0; i < todo_list->nr; i++)
6668 free(subjects[i]);
6669 free(subjects);
6670 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6672 clear_commit_todo_item(&commit_todo);
6674 return 0;
6677 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6679 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6680 struct object_id cherry_pick_head, rebase_head;
6682 if (file_exists(git_path_seq_dir()))
6683 *whence = FROM_CHERRY_PICK_MULTI;
6684 if (file_exists(rebase_path()) &&
6685 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6686 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6687 oideq(&rebase_head, &cherry_pick_head))
6688 *whence = FROM_REBASE_PICK;
6689 else
6690 *whence = FROM_CHERRY_PICK_SINGLE;
6692 return 1;
6695 return 0;
6698 int sequencer_get_update_refs_state(const char *wt_dir,
6699 struct string_list *refs)
6701 int result = 0;
6702 FILE *fp = NULL;
6703 struct strbuf ref = STRBUF_INIT;
6704 struct strbuf hash = STRBUF_INIT;
6705 struct update_ref_record *rec = NULL;
6707 char *path = rebase_path_update_refs(wt_dir);
6709 fp = fopen(path, "r");
6710 if (!fp)
6711 goto cleanup;
6713 while (strbuf_getline(&ref, fp) != EOF) {
6714 struct string_list_item *item;
6716 CALLOC_ARRAY(rec, 1);
6718 if (strbuf_getline(&hash, fp) == EOF ||
6719 get_oid_hex(hash.buf, &rec->before)) {
6720 warning(_("update-refs file at '%s' is invalid"),
6721 path);
6722 result = -1;
6723 goto cleanup;
6726 if (strbuf_getline(&hash, fp) == EOF ||
6727 get_oid_hex(hash.buf, &rec->after)) {
6728 warning(_("update-refs file at '%s' is invalid"),
6729 path);
6730 result = -1;
6731 goto cleanup;
6734 item = string_list_insert(refs, ref.buf);
6735 item->util = rec;
6736 rec = NULL;
6739 cleanup:
6740 if (fp)
6741 fclose(fp);
6742 free(path);
6743 free(rec);
6744 strbuf_release(&ref);
6745 strbuf_release(&hash);
6746 return result;