Merge branch 'jc/git-gui-maintainer-update' into next
[alt-git.git] / sequencer.c
blobdbd60d79b9c73619d38e0504eec9e74dace7dc3d
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "config.h"
5 #include "copy.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
14 #include "object.h"
15 #include "pager.h"
16 #include "commit.h"
17 #include "sequencer.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "utf8.h"
21 #include "cache-tree.h"
22 #include "diff.h"
23 #include "path.h"
24 #include "revision.h"
25 #include "rerere.h"
26 #include "merge.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
29 #include "refs.h"
30 #include "sparse-index.h"
31 #include "strvec.h"
32 #include "quote.h"
33 #include "trailer.h"
34 #include "log-tree.h"
35 #include "wt-status.h"
36 #include "hashmap.h"
37 #include "notes-utils.h"
38 #include "sigchain.h"
39 #include "unpack-trees.h"
40 #include "oidmap.h"
41 #include "oidset.h"
42 #include "commit-slab.h"
43 #include "alias.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
46 #include "reset.h"
47 #include "branch.h"
49 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 * To accommodate common filesystem limitations, where the loose refs' file
53 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
54 * --rebase-merges` need to be truncated if the corresponding commit subjects
55 * are too long.
56 * Add some margin to stay clear from reaching `NAME_MAX`.
58 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
60 static const char sign_off_header[] = "Signed-off-by: ";
61 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
63 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
65 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
67 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
68 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
69 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
70 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
72 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
74 * The file containing rebase commands, comments, and empty lines.
75 * This file is created by "git rebase -i" then edited by the user. As
76 * the lines are processed, they are removed from the front of this
77 * file and written to the tail of 'done'.
79 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
80 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
82 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
85 * The rebase command lines that have already been processed. A line
86 * is moved here when it is first handled, before any associated user
87 * actions.
89 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
91 * The file to keep track of how many commands were already processed (e.g.
92 * for the prompt).
94 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
96 * The file to keep track of how many commands are to be processed in total
97 * (e.g. for the prompt).
99 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
101 * The commit message that is planned to be used for any changes that
102 * need to be committed following a user interaction.
104 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
106 * The file into which is accumulated the suggested commit message for
107 * squash/fixup commands. When the first of a series of squash/fixups
108 * is seen, the file is created and the commit message from the
109 * previous commit and from the first squash/fixup commit are written
110 * to it. The commit message for each subsequent squash/fixup commit
111 * is appended to the file as it is processed.
113 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
115 * If the current series of squash/fixups has not yet included a squash
116 * command, then this file exists and holds the commit message of the
117 * original "pick" commit. (If the series ends without a "squash"
118 * command, then this can be used as the commit message of the combined
119 * commit without opening the editor.)
121 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
123 * This file contains the list fixup/squash commands that have been
124 * accumulated into message-fixup or message-squash so far.
126 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
128 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
129 * GIT_AUTHOR_DATE that will be used for the commit that is currently
130 * being rebased.
132 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
134 * When an "edit" rebase command is being processed, the SHA1 of the
135 * commit to be edited is recorded in this file. When "git rebase
136 * --continue" is executed, if there are any staged changes then they
137 * will be amended to the HEAD commit, but only provided the HEAD
138 * commit is still the commit to be edited. When any other rebase
139 * command is processed, this file is deleted.
141 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
143 * When we stop at a given patch via the "edit" command, this file contains
144 * the commit object name of the corresponding patch.
146 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
148 * When we stop for the user to resolve conflicts this file contains
149 * the patch of the commit that is being picked.
151 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
153 * For the post-rewrite hook, we make a list of rewritten commits and
154 * their new sha1s. The rewritten-pending list keeps the sha1s of
155 * commits that have been processed, but not committed yet,
156 * e.g. because they are waiting for a 'squash' command.
158 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
159 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
160 "rebase-merge/rewritten-pending")
163 * The path of the file containing the OID of the "squash onto" commit, i.e.
164 * the dummy commit used for `reset [new root]`.
166 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
169 * The path of the file listing refs that need to be deleted after the rebase
170 * finishes. This is used by the `label` command to record the need for cleanup.
172 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
175 * The update-refs file stores a list of refs that will be updated at the end
176 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
177 * update the OIDs for the refs in this file, but the refs are not updated
178 * until the end of the rebase sequence.
180 * rebase_path_update_refs() returns the path to this file for a given
181 * worktree directory. For the current worktree, pass the_repository->gitdir.
183 static char *rebase_path_update_refs(const char *wt_git_dir)
185 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
189 * The following files are written by git-rebase just after parsing the
190 * command-line.
192 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
193 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
194 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
195 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
196 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
197 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
198 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
199 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
200 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
201 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
202 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
203 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
204 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
205 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
206 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
207 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
208 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
211 * A 'struct replay_ctx' represents the private state of the sequencer.
213 struct replay_ctx {
215 * The commit message that will be used except at the end of a
216 * chain of fixup and squash commands.
218 struct strbuf message;
220 * The list of completed fixup and squash commands in the
221 * current chain.
223 struct strbuf current_fixups;
225 * Stores the reflog message that will be used when creating a
226 * commit. Points to a static buffer and should not be free()'d.
228 const char *reflog_message;
230 * The number of completed fixup and squash commands in the
231 * current chain.
233 int current_fixup_count;
235 * Whether message contains a commit message.
237 unsigned have_message :1;
240 struct replay_ctx* replay_ctx_new(void)
242 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
244 strbuf_init(&ctx->current_fixups, 0);
245 strbuf_init(&ctx->message, 0);
247 return ctx;
251 * A 'struct update_refs_record' represents a value in the update-refs
252 * list. We use a string_list to map refs to these (before, after) pairs.
254 struct update_ref_record {
255 struct object_id before;
256 struct object_id after;
259 static struct update_ref_record *init_update_ref_record(const char *ref)
261 struct update_ref_record *rec;
263 CALLOC_ARRAY(rec, 1);
265 oidcpy(&rec->before, null_oid());
266 oidcpy(&rec->after, null_oid());
268 /* This may fail, but that's fine, we will keep the null OID. */
269 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
271 return rec;
274 static int git_sequencer_config(const char *k, const char *v,
275 const struct config_context *ctx, void *cb)
277 struct replay_opts *opts = cb;
279 if (!strcmp(k, "commit.cleanup")) {
280 if (!v)
281 return config_error_nonbool(k);
283 if (!strcmp(v, "verbatim")) {
284 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
285 opts->explicit_cleanup = 1;
286 } else if (!strcmp(v, "whitespace")) {
287 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
288 opts->explicit_cleanup = 1;
289 } else if (!strcmp(v, "strip")) {
290 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
291 opts->explicit_cleanup = 1;
292 } else if (!strcmp(v, "scissors")) {
293 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
294 opts->explicit_cleanup = 1;
295 } else {
296 warning(_("invalid commit message cleanup mode '%s'"),
300 return 0;
303 if (!strcmp(k, "commit.gpgsign")) {
304 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
305 return 0;
308 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
309 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
310 if (ret == 0) {
312 * pull.twohead is allowed to be multi-valued; we only
313 * care about the first value.
315 char *tmp = strchr(opts->default_strategy, ' ');
316 if (tmp)
317 *tmp = '\0';
319 return ret;
322 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
323 opts->commit_use_reference = git_config_bool(k, v);
325 return git_diff_basic_config(k, v, ctx, NULL);
328 void sequencer_init_config(struct replay_opts *opts)
330 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
331 git_config(git_sequencer_config, opts);
334 static inline int is_rebase_i(const struct replay_opts *opts)
336 return opts->action == REPLAY_INTERACTIVE_REBASE;
339 static const char *get_dir(const struct replay_opts *opts)
341 if (is_rebase_i(opts))
342 return rebase_path();
343 return git_path_seq_dir();
346 static const char *get_todo_path(const struct replay_opts *opts)
348 if (is_rebase_i(opts))
349 return rebase_path_todo();
350 return git_path_todo_file();
354 * Returns 0 for non-conforming footer
355 * Returns 1 for conforming footer
356 * Returns 2 when sob exists within conforming footer
357 * Returns 3 when sob exists within conforming footer as last entry
359 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
360 size_t ignore_footer)
362 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
363 struct trailer_info info;
364 size_t i;
365 int found_sob = 0, found_sob_last = 0;
366 char saved_char;
368 opts.no_divider = 1;
370 if (ignore_footer) {
371 saved_char = sb->buf[sb->len - ignore_footer];
372 sb->buf[sb->len - ignore_footer] = '\0';
375 trailer_info_get(&opts, sb->buf, &info);
377 if (ignore_footer)
378 sb->buf[sb->len - ignore_footer] = saved_char;
380 if (info.trailer_block_start == info.trailer_block_end)
381 return 0;
383 for (i = 0; i < info.trailer_nr; i++)
384 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
385 found_sob = 1;
386 if (i == info.trailer_nr - 1)
387 found_sob_last = 1;
390 trailer_info_release(&info);
392 if (found_sob_last)
393 return 3;
394 if (found_sob)
395 return 2;
396 return 1;
399 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
401 static struct strbuf buf = STRBUF_INIT;
403 strbuf_reset(&buf);
404 if (opts->gpg_sign)
405 sq_quotef(&buf, "-S%s", opts->gpg_sign);
406 return buf.buf;
409 static void replay_ctx_release(struct replay_ctx *ctx)
411 strbuf_release(&ctx->current_fixups);
412 strbuf_release(&ctx->message);
415 void replay_opts_release(struct replay_opts *opts)
417 struct replay_ctx *ctx = opts->ctx;
419 free(opts->gpg_sign);
420 free(opts->reflog_action);
421 free(opts->default_strategy);
422 free(opts->strategy);
423 strvec_clear (&opts->xopts);
424 if (opts->revs)
425 release_revisions(opts->revs);
426 free(opts->revs);
427 replay_ctx_release(ctx);
428 free(opts->ctx);
431 int sequencer_remove_state(struct replay_opts *opts)
433 struct strbuf buf = STRBUF_INIT;
434 int ret = 0;
436 if (is_rebase_i(opts) &&
437 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
438 char *p = buf.buf;
439 while (*p) {
440 char *eol = strchr(p, '\n');
441 if (eol)
442 *eol = '\0';
443 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
444 warning(_("could not delete '%s'"), p);
445 ret = -1;
447 if (!eol)
448 break;
449 p = eol + 1;
453 strbuf_reset(&buf);
454 strbuf_addstr(&buf, get_dir(opts));
455 if (remove_dir_recursively(&buf, 0))
456 ret = error(_("could not remove '%s'"), buf.buf);
457 strbuf_release(&buf);
459 return ret;
462 static const char *action_name(const struct replay_opts *opts)
464 switch (opts->action) {
465 case REPLAY_REVERT:
466 return N_("revert");
467 case REPLAY_PICK:
468 return N_("cherry-pick");
469 case REPLAY_INTERACTIVE_REBASE:
470 return N_("rebase");
472 die(_("unknown action: %d"), opts->action);
475 struct commit_message {
476 char *parent_label;
477 char *label;
478 char *subject;
479 const char *message;
482 static const char *short_commit_name(struct repository *r, struct commit *commit)
484 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
487 static int get_message(struct commit *commit, struct commit_message *out)
489 const char *abbrev, *subject;
490 int subject_len;
492 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
493 get_commit_output_encoding());
494 abbrev = short_commit_name(the_repository, commit);
496 subject_len = find_commit_subject(out->message, &subject);
498 out->subject = xmemdupz(subject, subject_len);
499 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
500 out->parent_label = xstrfmt("parent of %s", out->label);
502 return 0;
505 static void free_message(struct commit *commit, struct commit_message *msg)
507 free(msg->parent_label);
508 free(msg->label);
509 free(msg->subject);
510 repo_unuse_commit_buffer(the_repository, commit, msg->message);
513 const char *rebase_resolvemsg =
514 N_("Resolve all conflicts manually, mark them as resolved with\n"
515 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
516 "You can instead skip this commit: run \"git rebase --skip\".\n"
517 "To abort and get back to the state before \"git rebase\", run "
518 "\"git rebase --abort\".");
520 static void print_advice(struct repository *r, int show_hint,
521 struct replay_opts *opts)
523 const char *msg;
525 if (is_rebase_i(opts))
526 msg = rebase_resolvemsg;
527 else
528 msg = getenv("GIT_CHERRY_PICK_HELP");
530 if (msg) {
531 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
533 * A conflict has occurred but the porcelain
534 * (typically rebase --interactive) wants to take care
535 * of the commit itself so remove CHERRY_PICK_HEAD
537 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
538 NULL, REF_NO_DEREF);
539 return;
542 if (show_hint) {
543 if (opts->no_commit)
544 advise_if_enabled(ADVICE_MERGE_CONFLICT,
545 _("after resolving the conflicts, mark the corrected paths\n"
546 "with 'git add <paths>' or 'git rm <paths>'"));
547 else if (opts->action == REPLAY_PICK)
548 advise_if_enabled(ADVICE_MERGE_CONFLICT,
549 _("After resolving the conflicts, mark them with\n"
550 "\"git add/rm <pathspec>\", then run\n"
551 "\"git cherry-pick --continue\".\n"
552 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
553 "To abort and get back to the state before \"git cherry-pick\",\n"
554 "run \"git cherry-pick --abort\"."));
555 else if (opts->action == REPLAY_REVERT)
556 advise_if_enabled(ADVICE_MERGE_CONFLICT,
557 _("After resolving the conflicts, mark them with\n"
558 "\"git add/rm <pathspec>\", then run\n"
559 "\"git revert --continue\".\n"
560 "You can instead skip this commit with \"git revert --skip\".\n"
561 "To abort and get back to the state before \"git revert\",\n"
562 "run \"git revert --abort\"."));
563 else
564 BUG("unexpected pick action in print_advice()");
568 static int write_message(const void *buf, size_t len, const char *filename,
569 int append_eol)
571 struct lock_file msg_file = LOCK_INIT;
573 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
574 if (msg_fd < 0)
575 return error_errno(_("could not lock '%s'"), filename);
576 if (write_in_full(msg_fd, buf, len) < 0) {
577 error_errno(_("could not write to '%s'"), filename);
578 rollback_lock_file(&msg_file);
579 return -1;
581 if (append_eol && write(msg_fd, "\n", 1) < 0) {
582 error_errno(_("could not write eol to '%s'"), filename);
583 rollback_lock_file(&msg_file);
584 return -1;
586 if (commit_lock_file(&msg_file) < 0)
587 return error(_("failed to finalize '%s'"), filename);
589 return 0;
592 int read_oneliner(struct strbuf *buf,
593 const char *path, unsigned flags)
595 int orig_len = buf->len;
597 if (strbuf_read_file(buf, path, 0) < 0) {
598 if ((flags & READ_ONELINER_WARN_MISSING) ||
599 (errno != ENOENT && errno != ENOTDIR))
600 warning_errno(_("could not read '%s'"), path);
601 return 0;
604 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
605 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
606 --buf->len;
607 buf->buf[buf->len] = '\0';
610 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
611 return 0;
613 return 1;
616 static struct tree *empty_tree(struct repository *r)
618 return lookup_tree(r, the_hash_algo->empty_tree);
621 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
623 if (repo_read_index_unmerged(repo))
624 return error_resolve_conflict(action_name(opts));
626 error(_("your local changes would be overwritten by %s."),
627 _(action_name(opts)));
629 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
630 advise(_("commit your changes or stash them to proceed."));
631 return -1;
634 static void update_abort_safety_file(void)
636 struct object_id head;
638 /* Do nothing on a single-pick */
639 if (!file_exists(git_path_seq_dir()))
640 return;
642 if (!repo_get_oid(the_repository, "HEAD", &head))
643 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
644 else
645 write_file(git_path_abort_safety_file(), "%s", "");
648 static int fast_forward_to(struct repository *r,
649 const struct object_id *to,
650 const struct object_id *from,
651 int unborn,
652 struct replay_opts *opts)
654 struct ref_transaction *transaction;
655 struct strbuf sb = STRBUF_INIT;
656 struct strbuf err = STRBUF_INIT;
658 repo_read_index(r);
659 if (checkout_fast_forward(r, from, to, 1))
660 return -1; /* the callee should have complained already */
662 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
664 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
665 &err);
666 if (!transaction ||
667 ref_transaction_update(transaction, "HEAD",
668 to, unborn && !is_rebase_i(opts) ?
669 null_oid() : from, NULL, NULL,
670 0, sb.buf, &err) ||
671 ref_transaction_commit(transaction, &err)) {
672 ref_transaction_free(transaction);
673 error("%s", err.buf);
674 strbuf_release(&sb);
675 strbuf_release(&err);
676 return -1;
679 strbuf_release(&sb);
680 strbuf_release(&err);
681 ref_transaction_free(transaction);
682 update_abort_safety_file();
683 return 0;
686 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
687 int use_editor)
689 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
690 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
691 COMMIT_MSG_CLEANUP_SPACE;
692 else if (!strcmp(cleanup_arg, "verbatim"))
693 return COMMIT_MSG_CLEANUP_NONE;
694 else if (!strcmp(cleanup_arg, "whitespace"))
695 return COMMIT_MSG_CLEANUP_SPACE;
696 else if (!strcmp(cleanup_arg, "strip"))
697 return COMMIT_MSG_CLEANUP_ALL;
698 else if (!strcmp(cleanup_arg, "scissors"))
699 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
700 COMMIT_MSG_CLEANUP_SPACE;
701 else
702 die(_("Invalid cleanup mode %s"), cleanup_arg);
706 * NB using int rather than enum cleanup_mode to stop clang's
707 * -Wtautological-constant-out-of-range-compare complaining that the comparison
708 * is always true.
710 static const char *describe_cleanup_mode(int cleanup_mode)
712 static const char *modes[] = { "whitespace",
713 "verbatim",
714 "scissors",
715 "strip" };
717 if (cleanup_mode < ARRAY_SIZE(modes))
718 return modes[cleanup_mode];
720 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
723 void append_conflicts_hint(struct index_state *istate,
724 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
726 int i;
728 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
729 strbuf_addch(msgbuf, '\n');
730 wt_status_append_cut_line(msgbuf);
731 strbuf_addstr(msgbuf, comment_line_str);
734 strbuf_addch(msgbuf, '\n');
735 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
736 for (i = 0; i < istate->cache_nr;) {
737 const struct cache_entry *ce = istate->cache[i++];
738 if (ce_stage(ce)) {
739 strbuf_commented_addf(msgbuf, comment_line_str,
740 "\t%s\n", ce->name);
741 while (i < istate->cache_nr &&
742 !strcmp(ce->name, istate->cache[i]->name))
743 i++;
748 static int do_recursive_merge(struct repository *r,
749 struct commit *base, struct commit *next,
750 const char *base_label, const char *next_label,
751 struct object_id *head, struct strbuf *msgbuf,
752 struct replay_opts *opts)
754 struct merge_options o;
755 struct merge_result result;
756 struct tree *next_tree, *base_tree, *head_tree;
757 int clean, show_output;
758 int i;
759 struct lock_file index_lock = LOCK_INIT;
761 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
762 return -1;
764 repo_read_index(r);
766 init_merge_options(&o, r);
767 o.ancestor = base ? base_label : "(empty tree)";
768 o.branch1 = "HEAD";
769 o.branch2 = next ? next_label : "(empty tree)";
770 if (is_rebase_i(opts))
771 o.buffer_output = 2;
772 o.show_rename_progress = 1;
774 head_tree = parse_tree_indirect(head);
775 if (!head_tree)
776 return error(_("unable to read tree (%s)"), oid_to_hex(head));
777 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
778 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
780 for (i = 0; i < opts->xopts.nr; i++)
781 parse_merge_opt(&o, opts->xopts.v[i]);
783 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
784 memset(&result, 0, sizeof(result));
785 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
786 &result);
787 show_output = !is_rebase_i(opts) || !result.clean;
789 * TODO: merge_switch_to_result will update index/working tree;
790 * we only really want to do that if !result.clean || this is
791 * the final patch to be picked. But determining this is the
792 * final patch would take some work, and "head_tree" would need
793 * to be replace with the tree the index matched before we
794 * started doing any picks.
796 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
797 clean = result.clean;
798 } else {
799 ensure_full_index(r->index);
800 clean = merge_trees(&o, head_tree, next_tree, base_tree);
801 if (is_rebase_i(opts) && clean <= 0)
802 fputs(o.obuf.buf, stdout);
803 strbuf_release(&o.obuf);
805 if (clean < 0) {
806 rollback_lock_file(&index_lock);
807 return clean;
810 if (write_locked_index(r->index, &index_lock,
811 COMMIT_LOCK | SKIP_IF_UNCHANGED))
813 * TRANSLATORS: %s will be "revert", "cherry-pick" or
814 * "rebase".
816 return error(_("%s: Unable to write new index file"),
817 _(action_name(opts)));
819 if (!clean)
820 append_conflicts_hint(r->index, msgbuf,
821 opts->default_msg_cleanup);
823 return !clean;
826 static struct object_id *get_cache_tree_oid(struct index_state *istate)
828 if (!cache_tree_fully_valid(istate->cache_tree))
829 if (cache_tree_update(istate, 0)) {
830 error(_("unable to update cache tree"));
831 return NULL;
834 return &istate->cache_tree->oid;
837 static int is_index_unchanged(struct repository *r)
839 struct object_id head_oid, *cache_tree_oid;
840 const struct object_id *head_tree_oid;
841 struct commit *head_commit;
842 struct index_state *istate = r->index;
843 const char *head_name;
845 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
846 /* Check to see if this is an unborn branch */
847 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
848 "HEAD",
849 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
850 &head_oid, NULL);
851 if (!head_name ||
852 !starts_with(head_name, "refs/heads/") ||
853 !is_null_oid(&head_oid))
854 return error(_("could not resolve HEAD commit"));
855 head_tree_oid = the_hash_algo->empty_tree;
856 } else {
857 head_commit = lookup_commit(r, &head_oid);
860 * If head_commit is NULL, check_commit, called from
861 * lookup_commit, would have indicated that head_commit is not
862 * a commit object already. repo_parse_commit() will return failure
863 * without further complaints in such a case. Otherwise, if
864 * the commit is invalid, repo_parse_commit() will complain. So
865 * there is nothing for us to say here. Just return failure.
867 if (repo_parse_commit(r, head_commit))
868 return -1;
870 head_tree_oid = get_commit_tree_oid(head_commit);
873 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
874 return -1;
876 return oideq(cache_tree_oid, head_tree_oid);
879 static int write_author_script(const char *message)
881 struct strbuf buf = STRBUF_INIT;
882 const char *eol;
883 int res;
885 for (;;)
886 if (!*message || starts_with(message, "\n")) {
887 missing_author:
888 /* Missing 'author' line? */
889 unlink(rebase_path_author_script());
890 return 0;
891 } else if (skip_prefix(message, "author ", &message))
892 break;
893 else if ((eol = strchr(message, '\n')))
894 message = eol + 1;
895 else
896 goto missing_author;
898 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
899 while (*message && *message != '\n' && *message != '\r')
900 if (skip_prefix(message, " <", &message))
901 break;
902 else if (*message != '\'')
903 strbuf_addch(&buf, *(message++));
904 else
905 strbuf_addf(&buf, "'\\%c'", *(message++));
906 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
907 while (*message && *message != '\n' && *message != '\r')
908 if (skip_prefix(message, "> ", &message))
909 break;
910 else if (*message != '\'')
911 strbuf_addch(&buf, *(message++));
912 else
913 strbuf_addf(&buf, "'\\%c'", *(message++));
914 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
915 while (*message && *message != '\n' && *message != '\r')
916 if (*message != '\'')
917 strbuf_addch(&buf, *(message++));
918 else
919 strbuf_addf(&buf, "'\\%c'", *(message++));
920 strbuf_addch(&buf, '\'');
921 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
922 strbuf_release(&buf);
923 return res;
927 * Take a series of KEY='VALUE' lines where VALUE part is
928 * sq-quoted, and append <KEY, VALUE> at the end of the string list
930 static int parse_key_value_squoted(char *buf, struct string_list *list)
932 while (*buf) {
933 struct string_list_item *item;
934 char *np;
935 char *cp = strchr(buf, '=');
936 if (!cp) {
937 np = strchrnul(buf, '\n');
938 return error(_("no key present in '%.*s'"),
939 (int) (np - buf), buf);
941 np = strchrnul(cp, '\n');
942 *cp++ = '\0';
943 item = string_list_append(list, buf);
945 buf = np + (*np == '\n');
946 *np = '\0';
947 cp = sq_dequote(cp);
948 if (!cp)
949 return error(_("unable to dequote value of '%s'"),
950 item->string);
951 item->util = xstrdup(cp);
953 return 0;
957 * Reads and parses the state directory's "author-script" file, and sets name,
958 * email and date accordingly.
959 * Returns 0 on success, -1 if the file could not be parsed.
961 * The author script is of the format:
963 * GIT_AUTHOR_NAME='$author_name'
964 * GIT_AUTHOR_EMAIL='$author_email'
965 * GIT_AUTHOR_DATE='$author_date'
967 * where $author_name, $author_email and $author_date are quoted. We are strict
968 * with our parsing, as the file was meant to be eval'd in the now-removed
969 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
970 * from what this function expects, it is better to bail out than to do
971 * something that the user does not expect.
973 int read_author_script(const char *path, char **name, char **email, char **date,
974 int allow_missing)
976 struct strbuf buf = STRBUF_INIT;
977 struct string_list kv = STRING_LIST_INIT_DUP;
978 int retval = -1; /* assume failure */
979 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
981 if (strbuf_read_file(&buf, path, 256) <= 0) {
982 strbuf_release(&buf);
983 if (errno == ENOENT && allow_missing)
984 return 0;
985 else
986 return error_errno(_("could not open '%s' for reading"),
987 path);
990 if (parse_key_value_squoted(buf.buf, &kv))
991 goto finish;
993 for (i = 0; i < kv.nr; i++) {
994 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
995 if (name_i != -2)
996 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
997 else
998 name_i = i;
999 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
1000 if (email_i != -2)
1001 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
1002 else
1003 email_i = i;
1004 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
1005 if (date_i != -2)
1006 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
1007 else
1008 date_i = i;
1009 } else {
1010 err = error(_("unknown variable '%s'"),
1011 kv.items[i].string);
1014 if (name_i == -2)
1015 error(_("missing 'GIT_AUTHOR_NAME'"));
1016 if (email_i == -2)
1017 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1018 if (date_i == -2)
1019 error(_("missing 'GIT_AUTHOR_DATE'"));
1020 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
1021 goto finish;
1022 *name = kv.items[name_i].util;
1023 *email = kv.items[email_i].util;
1024 *date = kv.items[date_i].util;
1025 retval = 0;
1026 finish:
1027 string_list_clear(&kv, !!retval);
1028 strbuf_release(&buf);
1029 return retval;
1033 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
1034 * file with shell quoting into struct strvec. Returns -1 on
1035 * error, 0 otherwise.
1037 static int read_env_script(struct strvec *env)
1039 char *name, *email, *date;
1041 if (read_author_script(rebase_path_author_script(),
1042 &name, &email, &date, 0))
1043 return -1;
1045 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1046 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1047 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
1048 free(name);
1049 free(email);
1050 free(date);
1052 return 0;
1055 static char *get_author(const char *message)
1057 size_t len;
1058 const char *a;
1060 a = find_commit_header(message, "author", &len);
1061 if (a)
1062 return xmemdupz(a, len);
1064 return NULL;
1067 static const char *author_date_from_env(const struct strvec *env)
1069 int i;
1070 const char *date;
1072 for (i = 0; i < env->nr; i++)
1073 if (skip_prefix(env->v[i],
1074 "GIT_AUTHOR_DATE=", &date))
1075 return date;
1077 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1078 * reading the script
1080 BUG("GIT_AUTHOR_DATE missing from author script");
1083 static const char staged_changes_advice[] =
1084 N_("you have staged changes in your working tree\n"
1085 "If these changes are meant to be squashed into the previous commit, run:\n"
1086 "\n"
1087 " git commit --amend %s\n"
1088 "\n"
1089 "If they are meant to go into a new commit, run:\n"
1090 "\n"
1091 " git commit %s\n"
1092 "\n"
1093 "In both cases, once you're done, continue with:\n"
1094 "\n"
1095 " git rebase --continue\n");
1097 #define ALLOW_EMPTY (1<<0)
1098 #define EDIT_MSG (1<<1)
1099 #define AMEND_MSG (1<<2)
1100 #define CLEANUP_MSG (1<<3)
1101 #define VERIFY_MSG (1<<4)
1102 #define CREATE_ROOT_COMMIT (1<<5)
1103 #define VERBATIM_MSG (1<<6)
1105 static int run_command_silent_on_success(struct child_process *cmd)
1107 struct strbuf buf = STRBUF_INIT;
1108 int rc;
1110 cmd->stdout_to_stderr = 1;
1111 rc = pipe_command(cmd,
1112 NULL, 0,
1113 NULL, 0,
1114 &buf, 0);
1116 if (rc)
1117 fputs(buf.buf, stderr);
1118 strbuf_release(&buf);
1119 return rc;
1123 * If we are cherry-pick, and if the merge did not result in
1124 * hand-editing, we will hit this commit and inherit the original
1125 * author date and name.
1127 * If we are revert, or if our cherry-pick results in a hand merge,
1128 * we had better say that the current user is responsible for that.
1130 * An exception is when run_git_commit() is called during an
1131 * interactive rebase: in that case, we will want to retain the
1132 * author metadata.
1134 static int run_git_commit(const char *defmsg,
1135 struct replay_opts *opts,
1136 unsigned int flags)
1138 struct replay_ctx *ctx = opts->ctx;
1139 struct child_process cmd = CHILD_PROCESS_INIT;
1141 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1142 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1144 cmd.git_cmd = 1;
1146 if (is_rebase_i(opts) &&
1147 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1148 !(!defmsg && (flags & AMEND_MSG))) &&
1149 read_env_script(&cmd.env)) {
1150 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1152 return error(_(staged_changes_advice),
1153 gpg_opt, gpg_opt);
1156 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", ctx->reflog_message);
1158 if (opts->committer_date_is_author_date)
1159 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1160 opts->ignore_date ?
1161 "" :
1162 author_date_from_env(&cmd.env));
1163 if (opts->ignore_date)
1164 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1166 strvec_push(&cmd.args, "commit");
1168 if (!(flags & VERIFY_MSG))
1169 strvec_push(&cmd.args, "-n");
1170 if ((flags & AMEND_MSG))
1171 strvec_push(&cmd.args, "--amend");
1172 if (opts->gpg_sign)
1173 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1174 else
1175 strvec_push(&cmd.args, "--no-gpg-sign");
1176 if (defmsg)
1177 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1178 else if (!(flags & EDIT_MSG))
1179 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1180 if ((flags & CLEANUP_MSG))
1181 strvec_push(&cmd.args, "--cleanup=strip");
1182 if ((flags & VERBATIM_MSG))
1183 strvec_push(&cmd.args, "--cleanup=verbatim");
1184 if ((flags & EDIT_MSG))
1185 strvec_push(&cmd.args, "-e");
1186 else if (!(flags & CLEANUP_MSG) &&
1187 !opts->signoff && !opts->record_origin &&
1188 !opts->explicit_cleanup)
1189 strvec_push(&cmd.args, "--cleanup=verbatim");
1191 if ((flags & ALLOW_EMPTY))
1192 strvec_push(&cmd.args, "--allow-empty");
1194 if (!(flags & EDIT_MSG))
1195 strvec_push(&cmd.args, "--allow-empty-message");
1197 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1198 return run_command_silent_on_success(&cmd);
1199 else
1200 return run_command(&cmd);
1203 static int rest_is_empty(const struct strbuf *sb, int start)
1205 int i, eol;
1206 const char *nl;
1208 /* Check if the rest is just whitespace and Signed-off-by's. */
1209 for (i = start; i < sb->len; i++) {
1210 nl = memchr(sb->buf + i, '\n', sb->len - i);
1211 if (nl)
1212 eol = nl - sb->buf;
1213 else
1214 eol = sb->len;
1216 if (strlen(sign_off_header) <= eol - i &&
1217 starts_with(sb->buf + i, sign_off_header)) {
1218 i = eol;
1219 continue;
1221 while (i < eol)
1222 if (!isspace(sb->buf[i++]))
1223 return 0;
1226 return 1;
1229 void cleanup_message(struct strbuf *msgbuf,
1230 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1232 if (verbose || /* Truncate the message just before the diff, if any. */
1233 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1234 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1235 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1236 strbuf_stripspace(msgbuf,
1237 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1241 * Find out if the message in the strbuf contains only whitespace and
1242 * Signed-off-by lines.
1244 int message_is_empty(const struct strbuf *sb,
1245 enum commit_msg_cleanup_mode cleanup_mode)
1247 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1248 return 0;
1249 return rest_is_empty(sb, 0);
1253 * See if the user edited the message in the editor or left what
1254 * was in the template intact
1256 int template_untouched(const struct strbuf *sb, const char *template_file,
1257 enum commit_msg_cleanup_mode cleanup_mode)
1259 struct strbuf tmpl = STRBUF_INIT;
1260 const char *start;
1262 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1263 return 0;
1265 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1266 return 0;
1268 strbuf_stripspace(&tmpl,
1269 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1270 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1271 start = sb->buf;
1272 strbuf_release(&tmpl);
1273 return rest_is_empty(sb, start - sb->buf);
1276 int update_head_with_reflog(const struct commit *old_head,
1277 const struct object_id *new_head,
1278 const char *action, const struct strbuf *msg,
1279 struct strbuf *err)
1281 struct ref_transaction *transaction;
1282 struct strbuf sb = STRBUF_INIT;
1283 const char *nl;
1284 int ret = 0;
1286 if (action) {
1287 strbuf_addstr(&sb, action);
1288 strbuf_addstr(&sb, ": ");
1291 nl = strchr(msg->buf, '\n');
1292 if (nl) {
1293 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1294 } else {
1295 strbuf_addbuf(&sb, msg);
1296 strbuf_addch(&sb, '\n');
1299 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1300 err);
1301 if (!transaction ||
1302 ref_transaction_update(transaction, "HEAD", new_head,
1303 old_head ? &old_head->object.oid : null_oid(),
1304 NULL, NULL, 0, sb.buf, err) ||
1305 ref_transaction_commit(transaction, err)) {
1306 ret = -1;
1308 ref_transaction_free(transaction);
1309 strbuf_release(&sb);
1311 return ret;
1314 static int run_rewrite_hook(const struct object_id *oldoid,
1315 const struct object_id *newoid)
1317 struct child_process proc = CHILD_PROCESS_INIT;
1318 int code;
1319 struct strbuf sb = STRBUF_INIT;
1320 const char *hook_path = find_hook("post-rewrite");
1322 if (!hook_path)
1323 return 0;
1325 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1326 proc.in = -1;
1327 proc.stdout_to_stderr = 1;
1328 proc.trace2_hook_name = "post-rewrite";
1330 code = start_command(&proc);
1331 if (code)
1332 return code;
1333 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1334 sigchain_push(SIGPIPE, SIG_IGN);
1335 write_in_full(proc.in, sb.buf, sb.len);
1336 close(proc.in);
1337 strbuf_release(&sb);
1338 sigchain_pop(SIGPIPE);
1339 return finish_command(&proc);
1342 void commit_post_rewrite(struct repository *r,
1343 const struct commit *old_head,
1344 const struct object_id *new_head)
1346 struct notes_rewrite_cfg *cfg;
1348 cfg = init_copy_notes_for_rewrite("amend");
1349 if (cfg) {
1350 /* we are amending, so old_head is not NULL */
1351 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1352 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1354 run_rewrite_hook(&old_head->object.oid, new_head);
1357 static int run_prepare_commit_msg_hook(struct repository *r,
1358 struct strbuf *msg,
1359 const char *commit)
1361 int ret = 0;
1362 const char *name, *arg1 = NULL, *arg2 = NULL;
1364 name = git_path_commit_editmsg();
1365 if (write_message(msg->buf, msg->len, name, 0))
1366 return -1;
1368 if (commit) {
1369 arg1 = "commit";
1370 arg2 = commit;
1371 } else {
1372 arg1 = "message";
1374 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1375 arg1, arg2, NULL))
1376 ret = error(_("'prepare-commit-msg' hook failed"));
1378 return ret;
1381 static const char implicit_ident_advice_noconfig[] =
1382 N_("Your name and email address were configured automatically based\n"
1383 "on your username and hostname. Please check that they are accurate.\n"
1384 "You can suppress this message by setting them explicitly. Run the\n"
1385 "following command and follow the instructions in your editor to edit\n"
1386 "your configuration file:\n"
1387 "\n"
1388 " git config --global --edit\n"
1389 "\n"
1390 "After doing this, you may fix the identity used for this commit with:\n"
1391 "\n"
1392 " git commit --amend --reset-author\n");
1394 static const char implicit_ident_advice_config[] =
1395 N_("Your name and email address were configured automatically based\n"
1396 "on your username and hostname. Please check that they are accurate.\n"
1397 "You can suppress this message by setting them explicitly:\n"
1398 "\n"
1399 " git config --global user.name \"Your Name\"\n"
1400 " git config --global user.email you@example.com\n"
1401 "\n"
1402 "After doing this, you may fix the identity used for this commit with:\n"
1403 "\n"
1404 " git commit --amend --reset-author\n");
1406 static const char *implicit_ident_advice(void)
1408 char *user_config = interpolate_path("~/.gitconfig", 0);
1409 char *xdg_config = xdg_config_home("config");
1410 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1412 free(user_config);
1413 free(xdg_config);
1415 if (config_exists)
1416 return _(implicit_ident_advice_config);
1417 else
1418 return _(implicit_ident_advice_noconfig);
1422 void print_commit_summary(struct repository *r,
1423 const char *prefix,
1424 const struct object_id *oid,
1425 unsigned int flags)
1427 struct rev_info rev;
1428 struct commit *commit;
1429 struct strbuf format = STRBUF_INIT;
1430 const char *head;
1431 struct pretty_print_context pctx = {0};
1432 struct strbuf author_ident = STRBUF_INIT;
1433 struct strbuf committer_ident = STRBUF_INIT;
1434 struct ref_store *refs;
1436 commit = lookup_commit(r, oid);
1437 if (!commit)
1438 die(_("couldn't look up newly created commit"));
1439 if (repo_parse_commit(r, commit))
1440 die(_("could not parse newly created commit"));
1442 strbuf_addstr(&format, "format:%h] %s");
1444 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1445 &pctx);
1446 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1447 &pctx);
1448 if (strbuf_cmp(&author_ident, &committer_ident)) {
1449 strbuf_addstr(&format, "\n Author: ");
1450 strbuf_addbuf_percentquote(&format, &author_ident);
1452 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1453 struct strbuf date = STRBUF_INIT;
1455 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1456 strbuf_addstr(&format, "\n Date: ");
1457 strbuf_addbuf_percentquote(&format, &date);
1458 strbuf_release(&date);
1460 if (!committer_ident_sufficiently_given()) {
1461 strbuf_addstr(&format, "\n Committer: ");
1462 strbuf_addbuf_percentquote(&format, &committer_ident);
1463 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1464 strbuf_addch(&format, '\n');
1465 strbuf_addstr(&format, implicit_ident_advice());
1468 strbuf_release(&author_ident);
1469 strbuf_release(&committer_ident);
1471 repo_init_revisions(r, &rev, prefix);
1472 setup_revisions(0, NULL, &rev, NULL);
1474 rev.diff = 1;
1475 rev.diffopt.output_format =
1476 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1478 rev.verbose_header = 1;
1479 rev.show_root_diff = 1;
1480 get_commit_format(format.buf, &rev);
1481 rev.always_show_header = 0;
1482 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1483 diff_setup_done(&rev.diffopt);
1485 refs = get_main_ref_store(r);
1486 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1487 if (!head)
1488 die(_("unable to resolve HEAD after creating commit"));
1489 if (!strcmp(head, "HEAD"))
1490 head = _("detached HEAD");
1491 else
1492 skip_prefix(head, "refs/heads/", &head);
1493 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1494 _(" (root-commit)") : "");
1496 if (!log_tree_commit(&rev, commit)) {
1497 rev.always_show_header = 1;
1498 rev.use_terminator = 1;
1499 log_tree_commit(&rev, commit);
1502 release_revisions(&rev);
1503 strbuf_release(&format);
1506 static int parse_head(struct repository *r, struct commit **head)
1508 struct commit *current_head;
1509 struct object_id oid;
1511 if (repo_get_oid(r, "HEAD", &oid)) {
1512 current_head = NULL;
1513 } else {
1514 current_head = lookup_commit_reference(r, &oid);
1515 if (!current_head)
1516 return error(_("could not parse HEAD"));
1517 if (!oideq(&oid, &current_head->object.oid)) {
1518 warning(_("HEAD %s is not a commit!"),
1519 oid_to_hex(&oid));
1521 if (repo_parse_commit(r, current_head))
1522 return error(_("could not parse HEAD commit"));
1524 *head = current_head;
1526 return 0;
1530 * Try to commit without forking 'git commit'. In some cases we need
1531 * to run 'git commit' to display an error message
1533 * Returns:
1534 * -1 - error unable to commit
1535 * 0 - success
1536 * 1 - run 'git commit'
1538 static int try_to_commit(struct repository *r,
1539 struct strbuf *msg, const char *author,
1540 struct replay_opts *opts, unsigned int flags,
1541 struct object_id *oid)
1543 struct replay_ctx *ctx = opts->ctx;
1544 struct object_id tree;
1545 struct commit *current_head = NULL;
1546 struct commit_list *parents = NULL;
1547 struct commit_extra_header *extra = NULL;
1548 struct strbuf err = STRBUF_INIT;
1549 struct strbuf commit_msg = STRBUF_INIT;
1550 char *amend_author = NULL;
1551 const char *committer = NULL;
1552 const char *hook_commit = NULL;
1553 enum commit_msg_cleanup_mode cleanup;
1554 int res = 0;
1556 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1557 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1559 if (parse_head(r, &current_head))
1560 return -1;
1562 if (flags & AMEND_MSG) {
1563 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1564 const char *out_enc = get_commit_output_encoding();
1565 const char *message = repo_logmsg_reencode(r, current_head,
1566 NULL, out_enc);
1568 if (!msg) {
1569 const char *orig_message = NULL;
1571 find_commit_subject(message, &orig_message);
1572 msg = &commit_msg;
1573 strbuf_addstr(msg, orig_message);
1574 hook_commit = "HEAD";
1576 author = amend_author = get_author(message);
1577 repo_unuse_commit_buffer(r, current_head,
1578 message);
1579 if (!author) {
1580 res = error(_("unable to parse commit author"));
1581 goto out;
1583 parents = copy_commit_list(current_head->parents);
1584 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1585 } else if (current_head &&
1586 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1587 commit_list_insert(current_head, &parents);
1590 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1591 res = error(_("git write-tree failed to write a tree"));
1592 goto out;
1595 if (!(flags & ALLOW_EMPTY)) {
1596 struct commit *first_parent = current_head;
1598 if (flags & AMEND_MSG) {
1599 if (current_head->parents) {
1600 first_parent = current_head->parents->item;
1601 if (repo_parse_commit(r, first_parent)) {
1602 res = error(_("could not parse HEAD commit"));
1603 goto out;
1605 } else {
1606 first_parent = NULL;
1609 if (oideq(first_parent
1610 ? get_commit_tree_oid(first_parent)
1611 : the_hash_algo->empty_tree,
1612 &tree)) {
1613 res = 1; /* run 'git commit' to display error message */
1614 goto out;
1618 if (hook_exists("prepare-commit-msg")) {
1619 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1620 if (res)
1621 goto out;
1622 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1623 2048) < 0) {
1624 res = error_errno(_("unable to read commit message "
1625 "from '%s'"),
1626 git_path_commit_editmsg());
1627 goto out;
1629 msg = &commit_msg;
1632 if (flags & CLEANUP_MSG)
1633 cleanup = COMMIT_MSG_CLEANUP_ALL;
1634 else if (flags & VERBATIM_MSG)
1635 cleanup = COMMIT_MSG_CLEANUP_NONE;
1636 else if ((opts->signoff || opts->record_origin) &&
1637 !opts->explicit_cleanup)
1638 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1639 else
1640 cleanup = opts->default_msg_cleanup;
1642 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1643 strbuf_stripspace(msg,
1644 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1645 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1646 res = 1; /* run 'git commit' to display error message */
1647 goto out;
1650 if (opts->committer_date_is_author_date) {
1651 struct ident_split id;
1652 struct strbuf date = STRBUF_INIT;
1654 if (!opts->ignore_date) {
1655 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1656 res = error(_("invalid author identity '%s'"),
1657 author);
1658 goto out;
1660 if (!id.date_begin) {
1661 res = error(_(
1662 "corrupt author: missing date information"));
1663 goto out;
1665 strbuf_addf(&date, "@%.*s %.*s",
1666 (int)(id.date_end - id.date_begin),
1667 id.date_begin,
1668 (int)(id.tz_end - id.tz_begin),
1669 id.tz_begin);
1670 } else {
1671 reset_ident_date();
1673 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1674 getenv("GIT_COMMITTER_EMAIL"),
1675 WANT_COMMITTER_IDENT,
1676 opts->ignore_date ? NULL : date.buf,
1677 IDENT_STRICT);
1678 strbuf_release(&date);
1679 } else {
1680 reset_ident_date();
1683 if (opts->ignore_date) {
1684 struct ident_split id;
1685 char *name, *email;
1687 if (split_ident_line(&id, author, strlen(author)) < 0) {
1688 error(_("invalid author identity '%s'"), author);
1689 goto out;
1691 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1692 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1693 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1694 IDENT_STRICT);
1695 free(name);
1696 free(email);
1699 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1700 author, committer, opts->gpg_sign, extra)) {
1701 res = error(_("failed to write commit object"));
1702 goto out;
1705 if (update_head_with_reflog(current_head, oid, ctx->reflog_message,
1706 msg, &err)) {
1707 res = error("%s", err.buf);
1708 goto out;
1711 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1712 if (flags & AMEND_MSG)
1713 commit_post_rewrite(r, current_head, oid);
1715 out:
1716 free_commit_extra_headers(extra);
1717 strbuf_release(&err);
1718 strbuf_release(&commit_msg);
1719 free(amend_author);
1721 return res;
1724 static int write_rebase_head(struct object_id *oid)
1726 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1727 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1728 return error(_("could not update %s"), "REBASE_HEAD");
1730 return 0;
1733 static int do_commit(struct repository *r,
1734 const char *msg_file, const char *author,
1735 struct replay_opts *opts, unsigned int flags,
1736 struct object_id *oid)
1738 int res = 1;
1740 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1741 struct object_id oid;
1742 struct strbuf sb = STRBUF_INIT;
1744 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1745 return error_errno(_("unable to read commit message "
1746 "from '%s'"),
1747 msg_file);
1749 res = try_to_commit(r, msg_file ? &sb : NULL,
1750 author, opts, flags, &oid);
1751 strbuf_release(&sb);
1752 if (!res) {
1753 refs_delete_ref(get_main_ref_store(r), "",
1754 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1755 unlink(git_path_merge_msg(r));
1756 if (!is_rebase_i(opts))
1757 print_commit_summary(r, NULL, &oid,
1758 SUMMARY_SHOW_AUTHOR_DATE);
1759 return res;
1762 if (res == 1) {
1763 if (is_rebase_i(opts) && oid)
1764 if (write_rebase_head(oid))
1765 return -1;
1766 return run_git_commit(msg_file, opts, flags);
1769 return res;
1772 static int is_original_commit_empty(struct commit *commit)
1774 const struct object_id *ptree_oid;
1776 if (repo_parse_commit(the_repository, commit))
1777 return error(_("could not parse commit %s"),
1778 oid_to_hex(&commit->object.oid));
1779 if (commit->parents) {
1780 struct commit *parent = commit->parents->item;
1781 if (repo_parse_commit(the_repository, parent))
1782 return error(_("could not parse parent commit %s"),
1783 oid_to_hex(&parent->object.oid));
1784 ptree_oid = get_commit_tree_oid(parent);
1785 } else {
1786 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1789 return oideq(ptree_oid, get_commit_tree_oid(commit));
1793 * Should empty commits be allowed? Return status:
1794 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1795 * 0: Halt on empty commit
1796 * 1: Allow empty commit
1797 * 2: Drop empty commit
1799 static int allow_empty(struct repository *r,
1800 struct replay_opts *opts,
1801 struct commit *commit)
1803 int index_unchanged, originally_empty;
1806 * For a commit that is initially empty, allow_empty determines if it
1807 * should be kept or not
1809 * For a commit that becomes empty, keep_redundant_commits and
1810 * drop_redundant_commits determine whether the commit should be kept or
1811 * dropped. If neither is specified, halt.
1813 index_unchanged = is_index_unchanged(r);
1814 if (index_unchanged < 0)
1815 return index_unchanged;
1816 if (!index_unchanged)
1817 return 0; /* we do not have to say --allow-empty */
1819 originally_empty = is_original_commit_empty(commit);
1820 if (originally_empty < 0)
1821 return originally_empty;
1822 if (originally_empty)
1823 return opts->allow_empty;
1824 else if (opts->keep_redundant_commits)
1825 return 1;
1826 else if (opts->drop_redundant_commits)
1827 return 2;
1828 else
1829 return 0;
1832 static struct {
1833 char c;
1834 const char *str;
1835 } todo_command_info[] = {
1836 [TODO_PICK] = { 'p', "pick" },
1837 [TODO_REVERT] = { 0, "revert" },
1838 [TODO_EDIT] = { 'e', "edit" },
1839 [TODO_REWORD] = { 'r', "reword" },
1840 [TODO_FIXUP] = { 'f', "fixup" },
1841 [TODO_SQUASH] = { 's', "squash" },
1842 [TODO_EXEC] = { 'x', "exec" },
1843 [TODO_BREAK] = { 'b', "break" },
1844 [TODO_LABEL] = { 'l', "label" },
1845 [TODO_RESET] = { 't', "reset" },
1846 [TODO_MERGE] = { 'm', "merge" },
1847 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1848 [TODO_NOOP] = { 0, "noop" },
1849 [TODO_DROP] = { 'd', "drop" },
1850 [TODO_COMMENT] = { 0, NULL },
1853 static const char *command_to_string(const enum todo_command command)
1855 if (command < TODO_COMMENT)
1856 return todo_command_info[command].str;
1857 if (command == TODO_COMMENT)
1858 return comment_line_str;
1859 die(_("unknown command: %d"), command);
1862 static char command_to_char(const enum todo_command command)
1864 if (command < TODO_COMMENT)
1865 return todo_command_info[command].c;
1866 return 0;
1869 static int is_noop(const enum todo_command command)
1871 return TODO_NOOP <= command;
1874 static int is_fixup(enum todo_command command)
1876 return command == TODO_FIXUP || command == TODO_SQUASH;
1879 /* Does this command create a (non-merge) commit? */
1880 static int is_pick_or_similar(enum todo_command command)
1882 switch (command) {
1883 case TODO_PICK:
1884 case TODO_REVERT:
1885 case TODO_EDIT:
1886 case TODO_REWORD:
1887 case TODO_FIXUP:
1888 case TODO_SQUASH:
1889 return 1;
1890 default:
1891 return 0;
1895 enum todo_item_flags {
1896 TODO_EDIT_MERGE_MSG = (1 << 0),
1897 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1898 TODO_EDIT_FIXUP_MSG = (1 << 2),
1901 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1902 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1903 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1904 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1905 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1907 static int is_fixup_flag(enum todo_command command, unsigned flag)
1909 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1910 (flag & TODO_EDIT_FIXUP_MSG));
1914 * Wrapper around strbuf_add_commented_lines() which avoids double
1915 * commenting commit subjects.
1917 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1919 const char *s = str;
1920 while (starts_with_mem(s, len, comment_line_str)) {
1921 size_t count;
1922 const char *n = memchr(s, '\n', len);
1923 if (!n)
1924 count = len;
1925 else
1926 count = n - s + 1;
1927 strbuf_add(buf, s, count);
1928 s += count;
1929 len -= count;
1931 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1934 /* Does the current fixup chain contain a squash command? */
1935 static int seen_squash(struct replay_ctx *ctx)
1937 return starts_with(ctx->current_fixups.buf, "squash") ||
1938 strstr(ctx->current_fixups.buf, "\nsquash");
1941 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1943 strbuf_setlen(buf1, 2);
1944 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1945 strbuf_addch(buf1, '\n');
1946 strbuf_setlen(buf2, 2);
1947 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1948 strbuf_addch(buf2, '\n');
1952 * Comment out any un-commented commit messages, updating the message comments
1953 * to say they will be skipped but do not comment out the empty lines that
1954 * surround commit messages and their comments.
1956 static void update_squash_message_for_fixup(struct strbuf *msg)
1958 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1959 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1960 const char *s, *start;
1961 char *orig_msg;
1962 size_t orig_msg_len;
1963 int i = 1;
1965 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1966 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1967 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1968 while (s) {
1969 const char *next;
1970 size_t off;
1971 if (skip_prefix(s, buf1.buf, &next)) {
1973 * Copy the last message, preserving the blank line
1974 * preceding the current line
1976 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1977 copy_lines(msg, start, s - start - off);
1978 if (off)
1979 strbuf_addch(msg, '\n');
1981 * The next message needs to be commented out but the
1982 * message header is already commented out so just copy
1983 * it and the blank line that follows it.
1985 strbuf_addbuf(msg, &buf2);
1986 if (*next == '\n')
1987 strbuf_addch(msg, *next++);
1988 start = s = next;
1989 copy_lines = add_commented_lines;
1990 update_comment_bufs(&buf1, &buf2, ++i);
1991 } else if (skip_prefix(s, buf2.buf, &next)) {
1992 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1993 copy_lines(msg, start, s - start - off);
1994 start = s - off;
1995 s = next;
1996 copy_lines = strbuf_add;
1997 update_comment_bufs(&buf1, &buf2, ++i);
1998 } else {
1999 s = strchr(s, '\n');
2000 if (s)
2001 s++;
2004 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2005 free(orig_msg);
2006 strbuf_release(&buf1);
2007 strbuf_release(&buf2);
2010 static int append_squash_message(struct strbuf *buf, const char *body,
2011 enum todo_command command, struct replay_opts *opts,
2012 unsigned flag)
2014 struct replay_ctx *ctx = opts->ctx;
2015 const char *fixup_msg;
2016 size_t commented_len = 0, fixup_off;
2018 * amend is non-interactive and not normally used with fixup!
2019 * or squash! commits, so only comment out those subjects when
2020 * squashing commit messages.
2022 if (starts_with(body, "amend!") ||
2023 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2024 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2025 commented_len = commit_subject_length(body);
2027 strbuf_addf(buf, "\n%s ", comment_line_str);
2028 strbuf_addf(buf, _(nth_commit_msg_fmt),
2029 ++ctx->current_fixup_count + 1);
2030 strbuf_addstr(buf, "\n\n");
2031 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2032 /* buf->buf may be reallocated so store an offset into the buffer */
2033 fixup_off = buf->len;
2034 strbuf_addstr(buf, body + commented_len);
2036 /* fixup -C after squash behaves like squash */
2037 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2039 * We're replacing the commit message so we need to
2040 * append the Signed-off-by: trailer if the user
2041 * requested '--signoff'.
2043 if (opts->signoff)
2044 append_signoff(buf, 0, 0);
2046 if ((command == TODO_FIXUP) &&
2047 (flag & TODO_REPLACE_FIXUP_MSG) &&
2048 (file_exists(rebase_path_fixup_msg()) ||
2049 !file_exists(rebase_path_squash_msg()))) {
2050 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2051 if (write_message(fixup_msg, strlen(fixup_msg),
2052 rebase_path_fixup_msg(), 0) < 0)
2053 return error(_("cannot write '%s'"),
2054 rebase_path_fixup_msg());
2055 } else {
2056 unlink(rebase_path_fixup_msg());
2058 } else {
2059 unlink(rebase_path_fixup_msg());
2062 return 0;
2065 static int update_squash_messages(struct repository *r,
2066 enum todo_command command,
2067 struct commit *commit,
2068 struct replay_opts *opts,
2069 unsigned flag)
2071 struct replay_ctx *ctx = opts->ctx;
2072 struct strbuf buf = STRBUF_INIT;
2073 int res = 0;
2074 const char *message, *body;
2075 const char *encoding = get_commit_output_encoding();
2077 if (ctx->current_fixup_count > 0) {
2078 struct strbuf header = STRBUF_INIT;
2079 char *eol;
2081 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2082 return error(_("could not read '%s'"),
2083 rebase_path_squash_msg());
2085 eol = !starts_with(buf.buf, comment_line_str) ?
2086 buf.buf : strchrnul(buf.buf, '\n');
2088 strbuf_addf(&header, "%s ", comment_line_str);
2089 strbuf_addf(&header, _(combined_commit_msg_fmt),
2090 ctx->current_fixup_count + 2);
2091 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2092 strbuf_release(&header);
2093 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2094 update_squash_message_for_fixup(&buf);
2095 } else {
2096 struct object_id head;
2097 struct commit *head_commit;
2098 const char *head_message, *body;
2100 if (repo_get_oid(r, "HEAD", &head))
2101 return error(_("need a HEAD to fixup"));
2102 if (!(head_commit = lookup_commit_reference(r, &head)))
2103 return error(_("could not read HEAD"));
2104 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2105 encoding)))
2106 return error(_("could not read HEAD's commit message"));
2108 find_commit_subject(head_message, &body);
2109 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2110 rebase_path_fixup_msg(), 0) < 0) {
2111 repo_unuse_commit_buffer(r, head_commit, head_message);
2112 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2114 strbuf_addf(&buf, "%s ", comment_line_str);
2115 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2116 strbuf_addf(&buf, "\n%s ", comment_line_str);
2117 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2118 _(skip_first_commit_msg_str) :
2119 _(first_commit_msg_str));
2120 strbuf_addstr(&buf, "\n\n");
2121 if (is_fixup_flag(command, flag))
2122 strbuf_add_commented_lines(&buf, body, strlen(body),
2123 comment_line_str);
2124 else
2125 strbuf_addstr(&buf, body);
2127 repo_unuse_commit_buffer(r, head_commit, head_message);
2130 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2131 return error(_("could not read commit message of %s"),
2132 oid_to_hex(&commit->object.oid));
2133 find_commit_subject(message, &body);
2135 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2136 res = append_squash_message(&buf, body, command, opts, flag);
2137 } else if (command == TODO_FIXUP) {
2138 strbuf_addf(&buf, "\n%s ", comment_line_str);
2139 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2140 ++ctx->current_fixup_count + 1);
2141 strbuf_addstr(&buf, "\n\n");
2142 strbuf_add_commented_lines(&buf, body, strlen(body),
2143 comment_line_str);
2144 } else
2145 return error(_("unknown command: %d"), command);
2146 repo_unuse_commit_buffer(r, commit, message);
2148 if (!res)
2149 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2151 strbuf_release(&buf);
2153 if (!res) {
2154 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2155 ctx->current_fixups.len ? "\n" : "",
2156 command_to_string(command),
2157 oid_to_hex(&commit->object.oid));
2158 res = write_message(ctx->current_fixups.buf,
2159 ctx->current_fixups.len,
2160 rebase_path_current_fixups(), 0);
2163 return res;
2166 static void flush_rewritten_pending(void)
2168 struct strbuf buf = STRBUF_INIT;
2169 struct object_id newoid;
2170 FILE *out;
2172 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2173 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2174 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2175 char *bol = buf.buf, *eol;
2177 while (*bol) {
2178 eol = strchrnul(bol, '\n');
2179 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2180 bol, oid_to_hex(&newoid));
2181 if (!*eol)
2182 break;
2183 bol = eol + 1;
2185 fclose(out);
2186 unlink(rebase_path_rewritten_pending());
2188 strbuf_release(&buf);
2191 static void record_in_rewritten(struct object_id *oid,
2192 enum todo_command next_command)
2194 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2196 if (!out)
2197 return;
2199 fprintf(out, "%s\n", oid_to_hex(oid));
2200 fclose(out);
2202 if (!is_fixup(next_command))
2203 flush_rewritten_pending();
2206 static int should_edit(struct replay_opts *opts) {
2207 if (opts->edit < 0)
2209 * Note that we only handle the case of non-conflicted
2210 * commits; continue_single_pick() handles the conflicted
2211 * commits itself instead of calling this function.
2213 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2214 return opts->edit;
2217 static void refer_to_commit(struct replay_opts *opts,
2218 struct strbuf *msgbuf, struct commit *commit)
2220 if (opts->commit_use_reference) {
2221 struct pretty_print_context ctx = {
2222 .abbrev = DEFAULT_ABBREV,
2223 .date_mode.type = DATE_SHORT,
2225 repo_format_commit_message(the_repository, commit,
2226 "%h (%s, %ad)", msgbuf, &ctx);
2227 } else {
2228 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2232 static int do_pick_commit(struct repository *r,
2233 struct todo_item *item,
2234 struct replay_opts *opts,
2235 int final_fixup, int *check_todo)
2237 struct replay_ctx *ctx = opts->ctx;
2238 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2239 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2240 struct object_id head;
2241 struct commit *base, *next, *parent;
2242 const char *base_label, *next_label;
2243 char *author = NULL;
2244 struct commit_message msg = { NULL, NULL, NULL, NULL };
2245 int res, unborn = 0, reword = 0, allow, drop_commit;
2246 enum todo_command command = item->command;
2247 struct commit *commit = item->commit;
2249 if (opts->no_commit) {
2251 * We do not intend to commit immediately. We just want to
2252 * merge the differences in, so let's compute the tree
2253 * that represents the "current" state for the merge machinery
2254 * to work on.
2256 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2257 return error(_("your index file is unmerged."));
2258 } else {
2259 unborn = repo_get_oid(r, "HEAD", &head);
2260 /* Do we want to generate a root commit? */
2261 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2262 oideq(&head, &opts->squash_onto)) {
2263 if (is_fixup(command))
2264 return error(_("cannot fixup root commit"));
2265 flags |= CREATE_ROOT_COMMIT;
2266 unborn = 1;
2267 } else if (unborn)
2268 oidcpy(&head, the_hash_algo->empty_tree);
2269 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2270 NULL, 0))
2271 return error_dirty_index(r, opts);
2273 discard_index(r->index);
2275 if (!commit->parents)
2276 parent = NULL;
2277 else if (commit->parents->next) {
2278 /* Reverting or cherry-picking a merge commit */
2279 int cnt;
2280 struct commit_list *p;
2282 if (!opts->mainline)
2283 return error(_("commit %s is a merge but no -m option was given."),
2284 oid_to_hex(&commit->object.oid));
2286 for (cnt = 1, p = commit->parents;
2287 cnt != opts->mainline && p;
2288 cnt++)
2289 p = p->next;
2290 if (cnt != opts->mainline || !p)
2291 return error(_("commit %s does not have parent %d"),
2292 oid_to_hex(&commit->object.oid), opts->mainline);
2293 parent = p->item;
2294 } else if (1 < opts->mainline)
2296 * Non-first parent explicitly specified as mainline for
2297 * non-merge commit
2299 return error(_("commit %s does not have parent %d"),
2300 oid_to_hex(&commit->object.oid), opts->mainline);
2301 else
2302 parent = commit->parents->item;
2304 if (get_message(commit, &msg) != 0)
2305 return error(_("cannot get commit message for %s"),
2306 oid_to_hex(&commit->object.oid));
2308 if (opts->allow_ff && !is_fixup(command) &&
2309 ((parent && oideq(&parent->object.oid, &head)) ||
2310 (!parent && unborn))) {
2311 if (is_rebase_i(opts))
2312 write_author_script(msg.message);
2313 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2314 opts);
2315 if (res || command != TODO_REWORD)
2316 goto leave;
2317 reword = 1;
2318 msg_file = NULL;
2319 goto fast_forward_edit;
2321 if (parent && repo_parse_commit(r, parent) < 0)
2322 /* TRANSLATORS: The first %s will be a "todo" command like
2323 "revert" or "pick", the second %s a SHA1. */
2324 return error(_("%s: cannot parse parent commit %s"),
2325 command_to_string(command),
2326 oid_to_hex(&parent->object.oid));
2329 * "commit" is an existing commit. We would want to apply
2330 * the difference it introduces since its first parent "prev"
2331 * on top of the current HEAD if we are cherry-pick. Or the
2332 * reverse of it if we are revert.
2335 if (command == TODO_REVERT) {
2336 const char *orig_subject;
2338 base = commit;
2339 base_label = msg.label;
2340 next = parent;
2341 next_label = msg.parent_label;
2342 if (opts->commit_use_reference) {
2343 strbuf_addstr(&ctx->message,
2344 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2345 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2347 * We don't touch pre-existing repeated reverts, because
2348 * theoretically these can be nested arbitrarily deeply,
2349 * thus requiring excessive complexity to deal with.
2351 !starts_with(orig_subject, "Revert \"")) {
2352 strbuf_addstr(&ctx->message, "Reapply \"");
2353 strbuf_addstr(&ctx->message, orig_subject);
2354 } else {
2355 strbuf_addstr(&ctx->message, "Revert \"");
2356 strbuf_addstr(&ctx->message, msg.subject);
2357 strbuf_addstr(&ctx->message, "\"");
2359 strbuf_addstr(&ctx->message, "\n\nThis reverts commit ");
2360 refer_to_commit(opts, &ctx->message, commit);
2362 if (commit->parents && commit->parents->next) {
2363 strbuf_addstr(&ctx->message, ", reversing\nchanges made to ");
2364 refer_to_commit(opts, &ctx->message, parent);
2366 strbuf_addstr(&ctx->message, ".\n");
2367 } else {
2368 const char *p;
2370 base = parent;
2371 base_label = msg.parent_label;
2372 next = commit;
2373 next_label = msg.label;
2375 /* Append the commit log message to ctx->message. */
2376 if (find_commit_subject(msg.message, &p))
2377 strbuf_addstr(&ctx->message, p);
2379 if (opts->record_origin) {
2380 strbuf_complete_line(&ctx->message);
2381 if (!has_conforming_footer(&ctx->message, NULL, 0))
2382 strbuf_addch(&ctx->message, '\n');
2383 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2384 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid));
2385 strbuf_addstr(&ctx->message, ")\n");
2387 if (!is_fixup(command))
2388 author = get_author(msg.message);
2390 ctx->have_message = 1;
2392 if (command == TODO_REWORD)
2393 reword = 1;
2394 else if (is_fixup(command)) {
2395 if (update_squash_messages(r, command, commit,
2396 opts, item->flags)) {
2397 res = -1;
2398 goto leave;
2400 flags |= AMEND_MSG;
2401 if (!final_fixup)
2402 msg_file = rebase_path_squash_msg();
2403 else if (file_exists(rebase_path_fixup_msg())) {
2404 flags |= VERBATIM_MSG;
2405 msg_file = rebase_path_fixup_msg();
2406 } else {
2407 const char *dest = git_path_squash_msg(r);
2408 unlink(dest);
2409 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2410 res = error(_("could not copy '%s' to '%s'"),
2411 rebase_path_squash_msg(), dest);
2412 goto leave;
2414 unlink(git_path_merge_msg(r));
2415 msg_file = dest;
2416 flags |= EDIT_MSG;
2420 if (opts->signoff && !is_fixup(command))
2421 append_signoff(&ctx->message, 0, 0);
2423 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2424 res = -1;
2425 else if (!opts->strategy ||
2426 !strcmp(opts->strategy, "recursive") ||
2427 !strcmp(opts->strategy, "ort") ||
2428 command == TODO_REVERT) {
2429 res = do_recursive_merge(r, base, next, base_label, next_label,
2430 &head, &ctx->message, opts);
2431 if (res < 0)
2432 goto leave;
2434 res |= write_message(ctx->message.buf, ctx->message.len,
2435 git_path_merge_msg(r), 0);
2436 } else {
2437 struct commit_list *common = NULL;
2438 struct commit_list *remotes = NULL;
2440 res = write_message(ctx->message.buf, ctx->message.len,
2441 git_path_merge_msg(r), 0);
2443 commit_list_insert(base, &common);
2444 commit_list_insert(next, &remotes);
2445 res |= try_merge_command(r, opts->strategy,
2446 opts->xopts.nr, opts->xopts.v,
2447 common, oid_to_hex(&head), remotes);
2448 free_commit_list(common);
2449 free_commit_list(remotes);
2453 * If the merge was clean or if it failed due to conflict, we write
2454 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2455 * However, if the merge did not even start, then we don't want to
2456 * write it at all.
2458 if ((command == TODO_PICK || command == TODO_REWORD ||
2459 command == TODO_EDIT) && !opts->no_commit &&
2460 (res == 0 || res == 1) &&
2461 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2462 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2463 res = -1;
2464 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2465 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2466 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2467 res = -1;
2469 if (res) {
2470 error(command == TODO_REVERT
2471 ? _("could not revert %s... %s")
2472 : _("could not apply %s... %s"),
2473 short_commit_name(r, commit), msg.subject);
2474 print_advice(r, res == 1, opts);
2475 repo_rerere(r, opts->allow_rerere_auto);
2476 goto leave;
2479 drop_commit = 0;
2480 allow = allow_empty(r, opts, commit);
2481 if (allow < 0) {
2482 res = allow;
2483 goto leave;
2484 } else if (allow == 1) {
2485 flags |= ALLOW_EMPTY;
2486 } else if (allow == 2) {
2487 drop_commit = 1;
2488 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2489 NULL, REF_NO_DEREF);
2490 unlink(git_path_merge_msg(r));
2491 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2492 NULL, REF_NO_DEREF);
2493 fprintf(stderr,
2494 _("dropping %s %s -- patch contents already upstream\n"),
2495 oid_to_hex(&commit->object.oid), msg.subject);
2496 } /* else allow == 0 and there's nothing special to do */
2497 if (!opts->no_commit && !drop_commit) {
2498 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2499 res = do_commit(r, msg_file, author, opts, flags,
2500 commit? &commit->object.oid : NULL);
2501 else
2502 res = error(_("unable to parse commit author"));
2503 *check_todo = !!(flags & EDIT_MSG);
2504 if (!res && reword) {
2505 fast_forward_edit:
2506 res = run_git_commit(NULL, opts, EDIT_MSG |
2507 VERIFY_MSG | AMEND_MSG |
2508 (flags & ALLOW_EMPTY));
2509 *check_todo = 1;
2514 if (!res && final_fixup) {
2515 unlink(rebase_path_fixup_msg());
2516 unlink(rebase_path_squash_msg());
2517 unlink(rebase_path_current_fixups());
2518 strbuf_reset(&ctx->current_fixups);
2519 ctx->current_fixup_count = 0;
2522 leave:
2523 free_message(commit, &msg);
2524 free(author);
2525 update_abort_safety_file();
2527 return res;
2530 static int prepare_revs(struct replay_opts *opts)
2533 * picking (but not reverting) ranges (but not individual revisions)
2534 * should be done in reverse
2536 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2537 opts->revs->reverse ^= 1;
2539 if (prepare_revision_walk(opts->revs))
2540 return error(_("revision walk setup failed"));
2542 return 0;
2545 static int read_and_refresh_cache(struct repository *r,
2546 struct replay_opts *opts)
2548 struct lock_file index_lock = LOCK_INIT;
2549 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2550 if (repo_read_index(r) < 0) {
2551 rollback_lock_file(&index_lock);
2552 return error(_("git %s: failed to read the index"),
2553 action_name(opts));
2555 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2557 if (index_fd >= 0) {
2558 if (write_locked_index(r->index, &index_lock,
2559 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2560 return error(_("git %s: failed to refresh the index"),
2561 action_name(opts));
2566 * If we are resolving merges in any way other than "ort", then
2567 * expand the sparse index.
2569 if (opts->strategy && strcmp(opts->strategy, "ort"))
2570 ensure_full_index(r->index);
2571 return 0;
2574 void todo_list_release(struct todo_list *todo_list)
2576 strbuf_release(&todo_list->buf);
2577 FREE_AND_NULL(todo_list->items);
2578 todo_list->nr = todo_list->alloc = 0;
2581 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2583 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2584 return todo_list->items + todo_list->nr++;
2587 const char *todo_item_get_arg(struct todo_list *todo_list,
2588 struct todo_item *item)
2590 return todo_list->buf.buf + item->arg_offset;
2593 static int is_command(enum todo_command command, const char **bol)
2595 const char *str = todo_command_info[command].str;
2596 const char nick = todo_command_info[command].c;
2597 const char *p = *bol;
2599 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2600 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2601 (*bol = p);
2604 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2606 switch (command) {
2607 case TODO_LABEL:
2609 * '#' is not a valid label as the merge command uses it to
2610 * separate merge parents from the commit subject.
2612 if (!strcmp(arg, "#") ||
2613 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2614 return error(_("'%s' is not a valid label"), arg);
2615 break;
2617 case TODO_UPDATE_REF:
2618 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2619 return error(_("'%s' is not a valid refname"), arg);
2620 if (check_refname_format(arg, 0))
2621 return error(_("update-ref requires a fully qualified "
2622 "refname e.g. refs/heads/%s"), arg);
2623 break;
2625 default:
2626 BUG("unexpected todo_command");
2629 return 0;
2632 static int parse_insn_line(struct repository *r, struct todo_item *item,
2633 const char *buf, const char *bol, char *eol)
2635 struct object_id commit_oid;
2636 char *end_of_object_name;
2637 int i, saved, status, padding;
2639 item->flags = 0;
2641 /* left-trim */
2642 bol += strspn(bol, " \t");
2644 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
2645 item->command = TODO_COMMENT;
2646 item->commit = NULL;
2647 item->arg_offset = bol - buf;
2648 item->arg_len = eol - bol;
2649 return 0;
2652 for (i = 0; i < TODO_COMMENT; i++)
2653 if (is_command(i, &bol)) {
2654 item->command = i;
2655 break;
2657 if (i >= TODO_COMMENT)
2658 return error(_("invalid command '%.*s'"),
2659 (int)strcspn(bol, " \t\r\n"), bol);
2661 /* Eat up extra spaces/ tabs before object name */
2662 padding = strspn(bol, " \t");
2663 bol += padding;
2665 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2666 if (bol != eol)
2667 return error(_("%s does not accept arguments: '%s'"),
2668 command_to_string(item->command), bol);
2669 item->commit = NULL;
2670 item->arg_offset = bol - buf;
2671 item->arg_len = eol - bol;
2672 return 0;
2675 if (!padding)
2676 return error(_("missing arguments for %s"),
2677 command_to_string(item->command));
2679 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2680 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2681 int ret = 0;
2683 item->commit = NULL;
2684 item->arg_offset = bol - buf;
2685 item->arg_len = (int)(eol - bol);
2686 if (item->command == TODO_LABEL ||
2687 item->command == TODO_UPDATE_REF) {
2688 saved = *eol;
2689 *eol = '\0';
2690 ret = check_label_or_ref_arg(item->command, bol);
2691 *eol = saved;
2693 return ret;
2696 if (item->command == TODO_FIXUP) {
2697 if (skip_prefix(bol, "-C", &bol)) {
2698 bol += strspn(bol, " \t");
2699 item->flags |= TODO_REPLACE_FIXUP_MSG;
2700 } else if (skip_prefix(bol, "-c", &bol)) {
2701 bol += strspn(bol, " \t");
2702 item->flags |= TODO_EDIT_FIXUP_MSG;
2706 if (item->command == TODO_MERGE) {
2707 if (skip_prefix(bol, "-C", &bol))
2708 bol += strspn(bol, " \t");
2709 else if (skip_prefix(bol, "-c", &bol)) {
2710 bol += strspn(bol, " \t");
2711 item->flags |= TODO_EDIT_MERGE_MSG;
2712 } else {
2713 item->flags |= TODO_EDIT_MERGE_MSG;
2714 item->commit = NULL;
2715 item->arg_offset = bol - buf;
2716 item->arg_len = (int)(eol - bol);
2717 return 0;
2721 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2722 saved = *end_of_object_name;
2723 *end_of_object_name = '\0';
2724 status = repo_get_oid(r, bol, &commit_oid);
2725 if (status < 0)
2726 error(_("could not parse '%s'"), bol); /* return later */
2727 *end_of_object_name = saved;
2729 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2730 item->arg_offset = bol - buf;
2731 item->arg_len = (int)(eol - bol);
2733 if (status < 0)
2734 return status;
2736 item->commit = lookup_commit_reference(r, &commit_oid);
2737 return item->commit ? 0 : -1;
2740 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2742 const char *todo_file, *bol;
2743 struct strbuf buf = STRBUF_INIT;
2744 int ret = 0;
2746 todo_file = git_path_todo_file();
2747 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2748 if (errno == ENOENT || errno == ENOTDIR)
2749 return -1;
2750 else
2751 return error_errno("unable to open '%s'", todo_file);
2753 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2754 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2755 *action = REPLAY_PICK;
2756 else if (is_command(TODO_REVERT, &bol) &&
2757 (*bol == ' ' || *bol == '\t'))
2758 *action = REPLAY_REVERT;
2759 else
2760 ret = -1;
2762 strbuf_release(&buf);
2764 return ret;
2767 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2768 struct todo_list *todo_list)
2770 struct todo_item *item;
2771 char *p = buf, *next_p;
2772 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2774 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2776 for (i = 1; *p; i++, p = next_p) {
2777 char *eol = strchrnul(p, '\n');
2779 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2781 if (p != eol && eol[-1] == '\r')
2782 eol--; /* strip Carriage Return */
2784 item = append_new_todo(todo_list);
2785 item->offset_in_buf = p - todo_list->buf.buf;
2786 if (parse_insn_line(r, item, buf, p, eol)) {
2787 res = error(_("invalid line %d: %.*s"),
2788 i, (int)(eol - p), p);
2789 item->command = TODO_COMMENT + 1;
2790 item->arg_offset = p - buf;
2791 item->arg_len = (int)(eol - p);
2792 item->commit = NULL;
2795 if (item->command != TODO_COMMENT)
2796 todo_list->total_nr++;
2798 if (fixup_okay)
2799 ; /* do nothing */
2800 else if (is_fixup(item->command))
2801 res = error(_("cannot '%s' without a previous commit"),
2802 command_to_string(item->command));
2803 else if (!is_noop(item->command))
2804 fixup_okay = 1;
2807 return res;
2810 static int count_commands(struct todo_list *todo_list)
2812 int count = 0, i;
2814 for (i = 0; i < todo_list->nr; i++)
2815 if (todo_list->items[i].command != TODO_COMMENT)
2816 count++;
2818 return count;
2821 static int get_item_line_offset(struct todo_list *todo_list, int index)
2823 return index < todo_list->nr ?
2824 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2827 static const char *get_item_line(struct todo_list *todo_list, int index)
2829 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2832 static int get_item_line_length(struct todo_list *todo_list, int index)
2834 return get_item_line_offset(todo_list, index + 1)
2835 - get_item_line_offset(todo_list, index);
2838 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2840 int fd;
2841 ssize_t len;
2843 fd = open(path, O_RDONLY);
2844 if (fd < 0)
2845 return error_errno(_("could not open '%s'"), path);
2846 len = strbuf_read(sb, fd, 0);
2847 close(fd);
2848 if (len < 0)
2849 return error(_("could not read '%s'."), path);
2850 return len;
2853 static int have_finished_the_last_pick(void)
2855 struct strbuf buf = STRBUF_INIT;
2856 const char *eol;
2857 const char *todo_path = git_path_todo_file();
2858 int ret = 0;
2860 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2861 if (errno == ENOENT) {
2862 return 0;
2863 } else {
2864 error_errno("unable to open '%s'", todo_path);
2865 return 0;
2868 /* If there is only one line then we are done */
2869 eol = strchr(buf.buf, '\n');
2870 if (!eol || !eol[1])
2871 ret = 1;
2873 strbuf_release(&buf);
2875 return ret;
2878 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2880 struct replay_opts opts = REPLAY_OPTS_INIT;
2881 int need_cleanup = 0;
2883 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2884 if (!refs_delete_ref(get_main_ref_store(r), "",
2885 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
2886 verbose)
2887 warning(_("cancelling a cherry picking in progress"));
2888 opts.action = REPLAY_PICK;
2889 need_cleanup = 1;
2892 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2893 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2894 NULL, REF_NO_DEREF) &&
2895 verbose)
2896 warning(_("cancelling a revert in progress"));
2897 opts.action = REPLAY_REVERT;
2898 need_cleanup = 1;
2901 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2902 NULL, REF_NO_DEREF);
2904 if (!need_cleanup)
2905 goto out;
2907 if (!have_finished_the_last_pick())
2908 goto out;
2910 sequencer_remove_state(&opts);
2911 out:
2912 replay_opts_release(&opts);
2915 static void todo_list_write_total_nr(struct todo_list *todo_list)
2917 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2919 if (f) {
2920 fprintf(f, "%d\n", todo_list->total_nr);
2921 fclose(f);
2925 static int read_populate_todo(struct repository *r,
2926 struct todo_list *todo_list,
2927 struct replay_opts *opts)
2929 const char *todo_file = get_todo_path(opts);
2930 int res;
2932 strbuf_reset(&todo_list->buf);
2933 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2934 return -1;
2936 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2937 if (res) {
2938 if (is_rebase_i(opts))
2939 return error(_("please fix this using "
2940 "'git rebase --edit-todo'."));
2941 return error(_("unusable instruction sheet: '%s'"), todo_file);
2944 if (!todo_list->nr &&
2945 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2946 return error(_("no commits parsed."));
2948 if (!is_rebase_i(opts)) {
2949 enum todo_command valid =
2950 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2951 int i;
2953 for (i = 0; i < todo_list->nr; i++)
2954 if (valid == todo_list->items[i].command)
2955 continue;
2956 else if (valid == TODO_PICK)
2957 return error(_("cannot cherry-pick during a revert."));
2958 else
2959 return error(_("cannot revert during a cherry-pick."));
2962 if (is_rebase_i(opts)) {
2963 struct todo_list done = TODO_LIST_INIT;
2965 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2966 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2967 todo_list->done_nr = count_commands(&done);
2968 else
2969 todo_list->done_nr = 0;
2971 todo_list->total_nr = todo_list->done_nr
2972 + count_commands(todo_list);
2973 todo_list_release(&done);
2975 todo_list_write_total_nr(todo_list);
2978 return 0;
2981 static int git_config_string_dup(char **dest,
2982 const char *var, const char *value)
2984 if (!value)
2985 return config_error_nonbool(var);
2986 free(*dest);
2987 *dest = xstrdup(value);
2988 return 0;
2991 static int populate_opts_cb(const char *key, const char *value,
2992 const struct config_context *ctx,
2993 void *data)
2995 struct replay_opts *opts = data;
2996 int error_flag = 1;
2998 if (!value)
2999 error_flag = 0;
3000 else if (!strcmp(key, "options.no-commit"))
3001 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3002 else if (!strcmp(key, "options.edit"))
3003 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3004 else if (!strcmp(key, "options.allow-empty"))
3005 opts->allow_empty =
3006 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3007 else if (!strcmp(key, "options.allow-empty-message"))
3008 opts->allow_empty_message =
3009 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3010 else if (!strcmp(key, "options.drop-redundant-commits"))
3011 opts->drop_redundant_commits =
3012 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3013 else if (!strcmp(key, "options.keep-redundant-commits"))
3014 opts->keep_redundant_commits =
3015 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3016 else if (!strcmp(key, "options.signoff"))
3017 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3018 else if (!strcmp(key, "options.record-origin"))
3019 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3020 else if (!strcmp(key, "options.allow-ff"))
3021 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3022 else if (!strcmp(key, "options.mainline"))
3023 opts->mainline = git_config_int(key, value, ctx->kvi);
3024 else if (!strcmp(key, "options.strategy"))
3025 git_config_string_dup(&opts->strategy, key, value);
3026 else if (!strcmp(key, "options.gpg-sign"))
3027 git_config_string_dup(&opts->gpg_sign, key, value);
3028 else if (!strcmp(key, "options.strategy-option")) {
3029 strvec_push(&opts->xopts, value);
3030 } else if (!strcmp(key, "options.allow-rerere-auto"))
3031 opts->allow_rerere_auto =
3032 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3033 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3034 else if (!strcmp(key, "options.default-msg-cleanup")) {
3035 opts->explicit_cleanup = 1;
3036 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3037 } else
3038 return error(_("invalid key: %s"), key);
3040 if (!error_flag)
3041 return error(_("invalid value for '%s': '%s'"), key, value);
3043 return 0;
3046 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3048 int i;
3049 int count;
3050 const char **argv;
3051 char *strategy_opts_string = raw_opts;
3053 if (*strategy_opts_string == ' ')
3054 strategy_opts_string++;
3056 count = split_cmdline(strategy_opts_string, &argv);
3057 if (count < 0)
3058 BUG("could not split '%s': %s", strategy_opts_string,
3059 split_cmdline_strerror(count));
3060 for (i = 0; i < count; i++) {
3061 const char *arg = argv[i];
3063 skip_prefix(arg, "--", &arg);
3064 strvec_push(&opts->xopts, arg);
3066 free(argv);
3069 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3071 strbuf_reset(buf);
3072 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3073 return;
3074 opts->strategy = strbuf_detach(buf, NULL);
3075 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3076 return;
3078 parse_strategy_opts(opts, buf->buf);
3081 static int read_populate_opts(struct replay_opts *opts)
3083 struct replay_ctx *ctx = opts->ctx;
3085 if (is_rebase_i(opts)) {
3086 struct strbuf buf = STRBUF_INIT;
3087 int ret = 0;
3089 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3090 READ_ONELINER_SKIP_IF_EMPTY)) {
3091 if (!starts_with(buf.buf, "-S"))
3092 strbuf_reset(&buf);
3093 else {
3094 free(opts->gpg_sign);
3095 opts->gpg_sign = xstrdup(buf.buf + 2);
3097 strbuf_reset(&buf);
3100 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3101 READ_ONELINER_SKIP_IF_EMPTY)) {
3102 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3103 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3104 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3105 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3106 strbuf_reset(&buf);
3109 if (file_exists(rebase_path_verbose()))
3110 opts->verbose = 1;
3112 if (file_exists(rebase_path_quiet()))
3113 opts->quiet = 1;
3115 if (file_exists(rebase_path_signoff())) {
3116 opts->allow_ff = 0;
3117 opts->signoff = 1;
3120 if (file_exists(rebase_path_cdate_is_adate())) {
3121 opts->allow_ff = 0;
3122 opts->committer_date_is_author_date = 1;
3125 if (file_exists(rebase_path_ignore_date())) {
3126 opts->allow_ff = 0;
3127 opts->ignore_date = 1;
3130 if (file_exists(rebase_path_reschedule_failed_exec()))
3131 opts->reschedule_failed_exec = 1;
3132 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3133 opts->reschedule_failed_exec = 0;
3135 if (file_exists(rebase_path_drop_redundant_commits()))
3136 opts->drop_redundant_commits = 1;
3138 if (file_exists(rebase_path_keep_redundant_commits()))
3139 opts->keep_redundant_commits = 1;
3141 read_strategy_opts(opts, &buf);
3142 strbuf_reset(&buf);
3144 if (read_oneliner(&ctx->current_fixups,
3145 rebase_path_current_fixups(),
3146 READ_ONELINER_SKIP_IF_EMPTY)) {
3147 const char *p = ctx->current_fixups.buf;
3148 ctx->current_fixup_count = 1;
3149 while ((p = strchr(p, '\n'))) {
3150 ctx->current_fixup_count++;
3151 p++;
3155 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3156 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3157 ret = error(_("unusable squash-onto"));
3158 goto done_rebase_i;
3160 opts->have_squash_onto = 1;
3163 done_rebase_i:
3164 strbuf_release(&buf);
3165 return ret;
3168 if (!file_exists(git_path_opts_file()))
3169 return 0;
3171 * The function git_parse_source(), called from git_config_from_file(),
3172 * may die() in case of a syntactically incorrect file. We do not care
3173 * about this case, though, because we wrote that file ourselves, so we
3174 * are pretty certain that it is syntactically correct.
3176 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3177 return error(_("malformed options sheet: '%s'"),
3178 git_path_opts_file());
3179 return 0;
3182 static void write_strategy_opts(struct replay_opts *opts)
3184 struct strbuf buf = STRBUF_INIT;
3187 * Quote strategy options so that they can be read correctly
3188 * by split_cmdline().
3190 quote_cmdline(&buf, opts->xopts.v);
3191 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3192 strbuf_release(&buf);
3195 int write_basic_state(struct replay_opts *opts, const char *head_name,
3196 struct commit *onto, const struct object_id *orig_head)
3198 if (head_name)
3199 write_file(rebase_path_head_name(), "%s\n", head_name);
3200 if (onto)
3201 write_file(rebase_path_onto(), "%s\n",
3202 oid_to_hex(&onto->object.oid));
3203 if (orig_head)
3204 write_file(rebase_path_orig_head(), "%s\n",
3205 oid_to_hex(orig_head));
3207 if (opts->quiet)
3208 write_file(rebase_path_quiet(), "%s", "");
3209 if (opts->verbose)
3210 write_file(rebase_path_verbose(), "%s", "");
3211 if (opts->strategy)
3212 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3213 if (opts->xopts.nr > 0)
3214 write_strategy_opts(opts);
3216 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3217 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3218 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3219 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3221 if (opts->gpg_sign)
3222 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3223 if (opts->signoff)
3224 write_file(rebase_path_signoff(), "--signoff\n");
3225 if (opts->drop_redundant_commits)
3226 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3227 if (opts->keep_redundant_commits)
3228 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3229 if (opts->committer_date_is_author_date)
3230 write_file(rebase_path_cdate_is_adate(), "%s", "");
3231 if (opts->ignore_date)
3232 write_file(rebase_path_ignore_date(), "%s", "");
3233 if (opts->reschedule_failed_exec)
3234 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3235 else
3236 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3238 return 0;
3241 static int walk_revs_populate_todo(struct todo_list *todo_list,
3242 struct replay_opts *opts)
3244 enum todo_command command = opts->action == REPLAY_PICK ?
3245 TODO_PICK : TODO_REVERT;
3246 const char *command_string = todo_command_info[command].str;
3247 const char *encoding;
3248 struct commit *commit;
3250 if (prepare_revs(opts))
3251 return -1;
3253 encoding = get_log_output_encoding();
3255 while ((commit = get_revision(opts->revs))) {
3256 struct todo_item *item = append_new_todo(todo_list);
3257 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3258 commit, NULL,
3259 encoding);
3260 const char *subject;
3261 int subject_len;
3263 item->command = command;
3264 item->commit = commit;
3265 item->arg_offset = 0;
3266 item->arg_len = 0;
3267 item->offset_in_buf = todo_list->buf.len;
3268 subject_len = find_commit_subject(commit_buffer, &subject);
3269 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3270 short_commit_name(the_repository, commit),
3271 subject_len, subject);
3272 repo_unuse_commit_buffer(the_repository, commit,
3273 commit_buffer);
3276 if (!todo_list->nr)
3277 return error(_("empty commit set passed"));
3279 return 0;
3282 static int create_seq_dir(struct repository *r)
3284 enum replay_action action;
3285 const char *in_progress_error = NULL;
3286 const char *in_progress_advice = NULL;
3287 unsigned int advise_skip =
3288 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3289 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3291 if (!sequencer_get_last_command(r, &action)) {
3292 switch (action) {
3293 case REPLAY_REVERT:
3294 in_progress_error = _("revert is already in progress");
3295 in_progress_advice =
3296 _("try \"git revert (--continue | %s--abort | --quit)\"");
3297 break;
3298 case REPLAY_PICK:
3299 in_progress_error = _("cherry-pick is already in progress");
3300 in_progress_advice =
3301 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3302 break;
3303 default:
3304 BUG("unexpected action in create_seq_dir");
3307 if (in_progress_error) {
3308 error("%s", in_progress_error);
3309 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3310 advise(in_progress_advice,
3311 advise_skip ? "--skip | " : "");
3312 return -1;
3314 if (mkdir(git_path_seq_dir(), 0777) < 0)
3315 return error_errno(_("could not create sequencer directory '%s'"),
3316 git_path_seq_dir());
3318 return 0;
3321 static int save_head(const char *head)
3323 return write_message(head, strlen(head), git_path_head_file(), 1);
3326 static int rollback_is_safe(void)
3328 struct strbuf sb = STRBUF_INIT;
3329 struct object_id expected_head, actual_head;
3331 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3332 strbuf_trim(&sb);
3333 if (get_oid_hex(sb.buf, &expected_head)) {
3334 strbuf_release(&sb);
3335 die(_("could not parse %s"), git_path_abort_safety_file());
3337 strbuf_release(&sb);
3339 else if (errno == ENOENT)
3340 oidclr(&expected_head);
3341 else
3342 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3344 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3345 oidclr(&actual_head);
3347 return oideq(&actual_head, &expected_head);
3350 static int reset_merge(const struct object_id *oid)
3352 struct child_process cmd = CHILD_PROCESS_INIT;
3354 cmd.git_cmd = 1;
3355 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3357 if (!is_null_oid(oid))
3358 strvec_push(&cmd.args, oid_to_hex(oid));
3360 return run_command(&cmd);
3363 static int rollback_single_pick(struct repository *r)
3365 struct object_id head_oid;
3367 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3368 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3369 return error(_("no cherry-pick or revert in progress"));
3370 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3371 return error(_("cannot resolve HEAD"));
3372 if (is_null_oid(&head_oid))
3373 return error(_("cannot abort from a branch yet to be born"));
3374 return reset_merge(&head_oid);
3377 static int skip_single_pick(void)
3379 struct object_id head;
3381 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3382 return error(_("cannot resolve HEAD"));
3383 return reset_merge(&head);
3386 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3388 FILE *f;
3389 struct object_id oid;
3390 struct strbuf buf = STRBUF_INIT;
3391 const char *p;
3393 f = fopen(git_path_head_file(), "r");
3394 if (!f && errno == ENOENT) {
3396 * There is no multiple-cherry-pick in progress.
3397 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3398 * a single-cherry-pick in progress, abort that.
3400 return rollback_single_pick(r);
3402 if (!f)
3403 return error_errno(_("cannot open '%s'"), git_path_head_file());
3404 if (strbuf_getline_lf(&buf, f)) {
3405 error(_("cannot read '%s': %s"), git_path_head_file(),
3406 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3407 fclose(f);
3408 goto fail;
3410 fclose(f);
3411 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3412 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3413 git_path_head_file());
3414 goto fail;
3416 if (is_null_oid(&oid)) {
3417 error(_("cannot abort from a branch yet to be born"));
3418 goto fail;
3421 if (!rollback_is_safe()) {
3422 /* Do not error, just do not rollback */
3423 warning(_("You seem to have moved HEAD. "
3424 "Not rewinding, check your HEAD!"));
3425 } else
3426 if (reset_merge(&oid))
3427 goto fail;
3428 strbuf_release(&buf);
3429 return sequencer_remove_state(opts);
3430 fail:
3431 strbuf_release(&buf);
3432 return -1;
3435 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3437 enum replay_action action = -1;
3438 sequencer_get_last_command(r, &action);
3441 * Check whether the subcommand requested to skip the commit is actually
3442 * in progress and that it's safe to skip the commit.
3444 * opts->action tells us which subcommand requested to skip the commit.
3445 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3446 * action is in progress and we can skip the commit.
3448 * Otherwise we check that the last instruction was related to the
3449 * particular subcommand we're trying to execute and barf if that's not
3450 * the case.
3452 * Finally we check that the rollback is "safe", i.e., has the HEAD
3453 * moved? In this case, it doesn't make sense to "reset the merge" and
3454 * "skip the commit" as the user already handled this by committing. But
3455 * we'd not want to barf here, instead give advice on how to proceed. We
3456 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3457 * it gets removed when the user commits, so if it still exists we're
3458 * sure the user can't have committed before.
3460 switch (opts->action) {
3461 case REPLAY_REVERT:
3462 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3463 if (action != REPLAY_REVERT)
3464 return error(_("no revert in progress"));
3465 if (!rollback_is_safe())
3466 goto give_advice;
3468 break;
3469 case REPLAY_PICK:
3470 if (!refs_ref_exists(get_main_ref_store(r),
3471 "CHERRY_PICK_HEAD")) {
3472 if (action != REPLAY_PICK)
3473 return error(_("no cherry-pick in progress"));
3474 if (!rollback_is_safe())
3475 goto give_advice;
3477 break;
3478 default:
3479 BUG("unexpected action in sequencer_skip");
3482 if (skip_single_pick())
3483 return error(_("failed to skip the commit"));
3484 if (!is_directory(git_path_seq_dir()))
3485 return 0;
3487 return sequencer_continue(r, opts);
3489 give_advice:
3490 error(_("there is nothing to skip"));
3492 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3493 advise(_("have you committed already?\n"
3494 "try \"git %s --continue\""),
3495 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3497 return -1;
3500 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3501 int reschedule)
3503 struct lock_file todo_lock = LOCK_INIT;
3504 const char *todo_path = get_todo_path(opts);
3505 int next = todo_list->current, offset, fd;
3508 * rebase -i writes "git-rebase-todo" without the currently executing
3509 * command, appending it to "done" instead.
3511 if (is_rebase_i(opts) && !reschedule)
3512 next++;
3514 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3515 if (fd < 0)
3516 return error_errno(_("could not lock '%s'"), todo_path);
3517 offset = get_item_line_offset(todo_list, next);
3518 if (write_in_full(fd, todo_list->buf.buf + offset,
3519 todo_list->buf.len - offset) < 0)
3520 return error_errno(_("could not write to '%s'"), todo_path);
3521 if (commit_lock_file(&todo_lock) < 0)
3522 return error(_("failed to finalize '%s'"), todo_path);
3524 if (is_rebase_i(opts) && !reschedule && next > 0) {
3525 const char *done = rebase_path_done();
3526 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3527 int ret = 0;
3529 if (fd < 0)
3530 return 0;
3531 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3532 get_item_line_length(todo_list, next - 1))
3533 < 0)
3534 ret = error_errno(_("could not write to '%s'"), done);
3535 if (close(fd) < 0)
3536 ret = error_errno(_("failed to finalize '%s'"), done);
3537 return ret;
3539 return 0;
3542 static int save_opts(struct replay_opts *opts)
3544 const char *opts_file = git_path_opts_file();
3545 int res = 0;
3547 if (opts->no_commit)
3548 res |= git_config_set_in_file_gently(opts_file,
3549 "options.no-commit", NULL, "true");
3550 if (opts->edit >= 0)
3551 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
3552 opts->edit ? "true" : "false");
3553 if (opts->allow_empty)
3554 res |= git_config_set_in_file_gently(opts_file,
3555 "options.allow-empty", NULL, "true");
3556 if (opts->allow_empty_message)
3557 res |= git_config_set_in_file_gently(opts_file,
3558 "options.allow-empty-message", NULL, "true");
3559 if (opts->drop_redundant_commits)
3560 res |= git_config_set_in_file_gently(opts_file,
3561 "options.drop-redundant-commits", NULL, "true");
3562 if (opts->keep_redundant_commits)
3563 res |= git_config_set_in_file_gently(opts_file,
3564 "options.keep-redundant-commits", NULL, "true");
3565 if (opts->signoff)
3566 res |= git_config_set_in_file_gently(opts_file,
3567 "options.signoff", NULL, "true");
3568 if (opts->record_origin)
3569 res |= git_config_set_in_file_gently(opts_file,
3570 "options.record-origin", NULL, "true");
3571 if (opts->allow_ff)
3572 res |= git_config_set_in_file_gently(opts_file,
3573 "options.allow-ff", NULL, "true");
3574 if (opts->mainline) {
3575 struct strbuf buf = STRBUF_INIT;
3576 strbuf_addf(&buf, "%d", opts->mainline);
3577 res |= git_config_set_in_file_gently(opts_file,
3578 "options.mainline", NULL, buf.buf);
3579 strbuf_release(&buf);
3581 if (opts->strategy)
3582 res |= git_config_set_in_file_gently(opts_file,
3583 "options.strategy", NULL, opts->strategy);
3584 if (opts->gpg_sign)
3585 res |= git_config_set_in_file_gently(opts_file,
3586 "options.gpg-sign", NULL, opts->gpg_sign);
3587 for (size_t i = 0; i < opts->xopts.nr; i++)
3588 res |= git_config_set_multivar_in_file_gently(opts_file,
3589 "options.strategy-option",
3590 opts->xopts.v[i], "^$", NULL, 0);
3591 if (opts->allow_rerere_auto)
3592 res |= git_config_set_in_file_gently(opts_file,
3593 "options.allow-rerere-auto", NULL,
3594 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3595 "true" : "false");
3597 if (opts->explicit_cleanup)
3598 res |= git_config_set_in_file_gently(opts_file,
3599 "options.default-msg-cleanup", NULL,
3600 describe_cleanup_mode(opts->default_msg_cleanup));
3601 return res;
3604 static int make_patch(struct repository *r,
3605 struct commit *commit,
3606 struct replay_opts *opts)
3608 struct rev_info log_tree_opt;
3609 const char *subject;
3610 char hex[GIT_MAX_HEXSZ + 1];
3611 int res = 0;
3613 if (!is_rebase_i(opts))
3614 BUG("make_patch should only be called when rebasing");
3616 oid_to_hex_r(hex, &commit->object.oid);
3617 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3618 return -1;
3619 res |= write_rebase_head(&commit->object.oid);
3621 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3622 repo_init_revisions(r, &log_tree_opt, NULL);
3623 log_tree_opt.abbrev = 0;
3624 log_tree_opt.diff = 1;
3625 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3626 log_tree_opt.disable_stdin = 1;
3627 log_tree_opt.no_commit_id = 1;
3628 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3629 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3630 if (!log_tree_opt.diffopt.file)
3631 res |= error_errno(_("could not open '%s'"),
3632 rebase_path_patch());
3633 else {
3634 res |= log_tree_commit(&log_tree_opt, commit);
3635 fclose(log_tree_opt.diffopt.file);
3638 if (!file_exists(rebase_path_message())) {
3639 const char *encoding = get_commit_output_encoding();
3640 const char *commit_buffer = repo_logmsg_reencode(r,
3641 commit, NULL,
3642 encoding);
3643 find_commit_subject(commit_buffer, &subject);
3644 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3645 repo_unuse_commit_buffer(r, commit,
3646 commit_buffer);
3648 release_revisions(&log_tree_opt);
3650 return res;
3653 static int intend_to_amend(void)
3655 struct object_id head;
3656 char *p;
3658 if (repo_get_oid(the_repository, "HEAD", &head))
3659 return error(_("cannot read HEAD"));
3661 p = oid_to_hex(&head);
3662 return write_message(p, strlen(p), rebase_path_amend(), 1);
3665 static int error_with_patch(struct repository *r,
3666 struct commit *commit,
3667 const char *subject, int subject_len,
3668 struct replay_opts *opts,
3669 int exit_code, int to_amend)
3671 struct replay_ctx *ctx = opts->ctx;
3674 * Write the commit message to be used by "git rebase
3675 * --continue". If a "fixup" or "squash" command has conflicts
3676 * then we will have already written rebase_path_message() in
3677 * error_failed_squash(). If an "edit" command was
3678 * fast-forwarded then we don't have a message in ctx->message
3679 * and rely on make_patch() to write rebase_path_message()
3680 * instead.
3682 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3683 write_message(ctx->message.buf, ctx->message.len,
3684 rebase_path_message(), 0))
3685 return error(_("could not write commit message file"));
3687 if (commit && make_patch(r, commit, opts))
3688 return -1;
3690 if (to_amend) {
3691 if (intend_to_amend())
3692 return -1;
3694 fprintf(stderr,
3695 _("You can amend the commit now, with\n"
3696 "\n"
3697 " git commit --amend %s\n"
3698 "\n"
3699 "Once you are satisfied with your changes, run\n"
3700 "\n"
3701 " git rebase --continue\n"),
3702 gpg_sign_opt_quoted(opts));
3703 } else if (exit_code) {
3704 if (commit)
3705 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3706 short_commit_name(r, commit), subject_len, subject);
3707 else
3709 * We don't have the hash of the parent so
3710 * just print the line from the todo file.
3712 fprintf_ln(stderr, _("Could not merge %.*s"),
3713 subject_len, subject);
3716 return exit_code;
3719 static int error_failed_squash(struct repository *r,
3720 struct commit *commit,
3721 struct replay_opts *opts,
3722 int subject_len,
3723 const char *subject)
3725 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3726 return error(_("could not copy '%s' to '%s'"),
3727 rebase_path_squash_msg(), rebase_path_message());
3728 unlink(git_path_merge_msg(r));
3729 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3730 return error(_("could not copy '%s' to '%s'"),
3731 rebase_path_message(),
3732 git_path_merge_msg(r));
3733 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3736 static int do_exec(struct repository *r, const char *command_line)
3738 struct child_process cmd = CHILD_PROCESS_INIT;
3739 int dirty, status;
3741 fprintf(stderr, _("Executing: %s\n"), command_line);
3742 cmd.use_shell = 1;
3743 strvec_push(&cmd.args, command_line);
3744 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3745 status = run_command(&cmd);
3747 /* force re-reading of the cache */
3748 discard_index(r->index);
3749 if (repo_read_index(r) < 0)
3750 return error(_("could not read index"));
3752 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3754 if (status) {
3755 warning(_("execution failed: %s\n%s"
3756 "You can fix the problem, and then run\n"
3757 "\n"
3758 " git rebase --continue\n"
3759 "\n"),
3760 command_line,
3761 dirty ? _("and made changes to the index and/or the "
3762 "working tree.\n") : "");
3763 if (status == 127)
3764 /* command not found */
3765 status = 1;
3766 } else if (dirty) {
3767 warning(_("execution succeeded: %s\nbut "
3768 "left changes to the index and/or the working tree.\n"
3769 "Commit or stash your changes, and then run\n"
3770 "\n"
3771 " git rebase --continue\n"
3772 "\n"), command_line);
3773 status = 1;
3776 return status;
3779 __attribute__((format (printf, 2, 3)))
3780 static int safe_append(const char *filename, const char *fmt, ...)
3782 va_list ap;
3783 struct lock_file lock = LOCK_INIT;
3784 int fd = hold_lock_file_for_update(&lock, filename,
3785 LOCK_REPORT_ON_ERROR);
3786 struct strbuf buf = STRBUF_INIT;
3788 if (fd < 0)
3789 return -1;
3791 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3792 error_errno(_("could not read '%s'"), filename);
3793 rollback_lock_file(&lock);
3794 return -1;
3796 strbuf_complete(&buf, '\n');
3797 va_start(ap, fmt);
3798 strbuf_vaddf(&buf, fmt, ap);
3799 va_end(ap);
3801 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3802 error_errno(_("could not write to '%s'"), filename);
3803 strbuf_release(&buf);
3804 rollback_lock_file(&lock);
3805 return -1;
3807 if (commit_lock_file(&lock) < 0) {
3808 strbuf_release(&buf);
3809 return error(_("failed to finalize '%s'"), filename);
3812 strbuf_release(&buf);
3813 return 0;
3816 static int do_label(struct repository *r, const char *name, int len)
3818 struct ref_store *refs = get_main_ref_store(r);
3819 struct ref_transaction *transaction;
3820 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3821 struct strbuf msg = STRBUF_INIT;
3822 int ret = 0;
3823 struct object_id head_oid;
3825 if (len == 1 && *name == '#')
3826 return error(_("illegal label name: '%.*s'"), len, name);
3828 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3829 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3831 transaction = ref_store_transaction_begin(refs, &err);
3832 if (!transaction) {
3833 error("%s", err.buf);
3834 ret = -1;
3835 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
3836 error(_("could not read HEAD"));
3837 ret = -1;
3838 } else if (ref_transaction_update(transaction, ref_name.buf,
3839 &head_oid, NULL, NULL, NULL,
3840 0, msg.buf, &err) < 0 ||
3841 ref_transaction_commit(transaction, &err)) {
3842 error("%s", err.buf);
3843 ret = -1;
3845 ref_transaction_free(transaction);
3846 strbuf_release(&err);
3847 strbuf_release(&msg);
3849 if (!ret)
3850 ret = safe_append(rebase_path_refs_to_delete(),
3851 "%s\n", ref_name.buf);
3852 strbuf_release(&ref_name);
3854 return ret;
3857 static const char *sequencer_reflog_action(struct replay_opts *opts)
3859 if (!opts->reflog_action) {
3860 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3861 opts->reflog_action =
3862 xstrdup(opts->reflog_action ? opts->reflog_action
3863 : action_name(opts));
3866 return opts->reflog_action;
3869 __attribute__((format (printf, 3, 4)))
3870 static const char *reflog_message(struct replay_opts *opts,
3871 const char *sub_action, const char *fmt, ...)
3873 va_list ap;
3874 static struct strbuf buf = STRBUF_INIT;
3876 va_start(ap, fmt);
3877 strbuf_reset(&buf);
3878 strbuf_addstr(&buf, sequencer_reflog_action(opts));
3879 if (sub_action)
3880 strbuf_addf(&buf, " (%s)", sub_action);
3881 if (fmt) {
3882 strbuf_addstr(&buf, ": ");
3883 strbuf_vaddf(&buf, fmt, ap);
3885 va_end(ap);
3887 return buf.buf;
3890 static struct commit *lookup_label(struct repository *r, const char *label,
3891 int len, struct strbuf *buf)
3893 struct commit *commit;
3894 struct object_id oid;
3896 strbuf_reset(buf);
3897 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3898 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
3899 commit = lookup_commit_object(r, &oid);
3900 } else {
3901 /* fall back to non-rewritten ref or commit */
3902 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3903 commit = lookup_commit_reference_by_name(buf->buf);
3906 if (!commit)
3907 error(_("could not resolve '%s'"), buf->buf);
3909 return commit;
3912 static int do_reset(struct repository *r,
3913 const char *name, int len,
3914 struct replay_opts *opts)
3916 struct strbuf ref_name = STRBUF_INIT;
3917 struct object_id oid;
3918 struct lock_file lock = LOCK_INIT;
3919 struct tree_desc desc = { 0 };
3920 struct tree *tree;
3921 struct unpack_trees_options unpack_tree_opts = { 0 };
3922 int ret = 0;
3924 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3925 return -1;
3927 if (len == 10 && !strncmp("[new root]", name, len)) {
3928 if (!opts->have_squash_onto) {
3929 const char *hex;
3930 if (commit_tree("", 0, the_hash_algo->empty_tree,
3931 NULL, &opts->squash_onto,
3932 NULL, NULL))
3933 return error(_("writing fake root commit"));
3934 opts->have_squash_onto = 1;
3935 hex = oid_to_hex(&opts->squash_onto);
3936 if (write_message(hex, strlen(hex),
3937 rebase_path_squash_onto(), 0))
3938 return error(_("writing squash-onto"));
3940 oidcpy(&oid, &opts->squash_onto);
3941 } else {
3942 int i;
3943 struct commit *commit;
3945 /* Determine the length of the label */
3946 for (i = 0; i < len; i++)
3947 if (isspace(name[i]))
3948 break;
3949 len = i;
3951 commit = lookup_label(r, name, len, &ref_name);
3952 if (!commit) {
3953 ret = -1;
3954 goto cleanup;
3956 oid = commit->object.oid;
3959 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3960 unpack_tree_opts.head_idx = 1;
3961 unpack_tree_opts.src_index = r->index;
3962 unpack_tree_opts.dst_index = r->index;
3963 unpack_tree_opts.fn = oneway_merge;
3964 unpack_tree_opts.merge = 1;
3965 unpack_tree_opts.update = 1;
3966 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
3967 unpack_tree_opts.skip_cache_tree_update = 1;
3968 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3970 if (repo_read_index_unmerged(r)) {
3971 ret = error_resolve_conflict(action_name(opts));
3972 goto cleanup;
3975 if (!fill_tree_descriptor(r, &desc, &oid)) {
3976 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3977 goto cleanup;
3980 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3981 ret = -1;
3982 goto cleanup;
3985 tree = parse_tree_indirect(&oid);
3986 if (!tree)
3987 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
3988 prime_cache_tree(r, r->index, tree);
3990 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3991 ret = error(_("could not write index"));
3993 if (!ret)
3994 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
3995 len, name),
3996 "HEAD", &oid,
3997 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3998 cleanup:
3999 free((void *)desc.buffer);
4000 if (ret < 0)
4001 rollback_lock_file(&lock);
4002 strbuf_release(&ref_name);
4003 clear_unpack_trees_porcelain(&unpack_tree_opts);
4004 return ret;
4007 static int do_merge(struct repository *r,
4008 struct commit *commit,
4009 const char *arg, int arg_len,
4010 int flags, int *check_todo, struct replay_opts *opts)
4012 struct replay_ctx *ctx = opts->ctx;
4013 int run_commit_flags = 0;
4014 struct strbuf ref_name = STRBUF_INIT;
4015 struct commit *head_commit, *merge_commit, *i;
4016 struct commit_list *bases = NULL, *j;
4017 struct commit_list *to_merge = NULL, **tail = &to_merge;
4018 const char *strategy = !opts->xopts.nr &&
4019 (!opts->strategy ||
4020 !strcmp(opts->strategy, "recursive") ||
4021 !strcmp(opts->strategy, "ort")) ?
4022 NULL : opts->strategy;
4023 struct merge_options o;
4024 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4025 static struct lock_file lock;
4026 const char *p;
4028 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4029 ret = -1;
4030 goto leave_merge;
4033 head_commit = lookup_commit_reference_by_name("HEAD");
4034 if (!head_commit) {
4035 ret = error(_("cannot merge without a current revision"));
4036 goto leave_merge;
4040 * For octopus merges, the arg starts with the list of revisions to be
4041 * merged. The list is optionally followed by '#' and the oneline.
4043 merge_arg_len = oneline_offset = arg_len;
4044 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4045 if (!*p)
4046 break;
4047 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4048 p += 1 + strspn(p + 1, " \t\n");
4049 oneline_offset = p - arg;
4050 break;
4052 k = strcspn(p, " \t\n");
4053 if (!k)
4054 continue;
4055 merge_commit = lookup_label(r, p, k, &ref_name);
4056 if (!merge_commit) {
4057 ret = error(_("unable to parse '%.*s'"), k, p);
4058 goto leave_merge;
4060 tail = &commit_list_insert(merge_commit, tail)->next;
4061 p += k;
4062 merge_arg_len = p - arg;
4065 if (!to_merge) {
4066 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4067 goto leave_merge;
4070 if (opts->have_squash_onto &&
4071 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4073 * When the user tells us to "merge" something into a
4074 * "[new root]", let's simply fast-forward to the merge head.
4076 rollback_lock_file(&lock);
4077 if (to_merge->next)
4078 ret = error(_("octopus merge cannot be executed on "
4079 "top of a [new root]"));
4080 else
4081 ret = fast_forward_to(r, &to_merge->item->object.oid,
4082 &head_commit->object.oid, 0,
4083 opts);
4084 goto leave_merge;
4088 * If HEAD is not identical to the first parent of the original merge
4089 * commit, we cannot fast-forward.
4091 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4092 oideq(&commit->parents->item->object.oid,
4093 &head_commit->object.oid);
4096 * If any merge head is different from the original one, we cannot
4097 * fast-forward.
4099 if (can_fast_forward) {
4100 struct commit_list *p = commit->parents->next;
4102 for (j = to_merge; j && p; j = j->next, p = p->next)
4103 if (!oideq(&j->item->object.oid,
4104 &p->item->object.oid)) {
4105 can_fast_forward = 0;
4106 break;
4109 * If the number of merge heads differs from the original merge
4110 * commit, we cannot fast-forward.
4112 if (j || p)
4113 can_fast_forward = 0;
4116 if (can_fast_forward) {
4117 rollback_lock_file(&lock);
4118 ret = fast_forward_to(r, &commit->object.oid,
4119 &head_commit->object.oid, 0, opts);
4120 if (flags & TODO_EDIT_MERGE_MSG)
4121 goto fast_forward_edit;
4123 goto leave_merge;
4126 if (commit) {
4127 const char *encoding = get_commit_output_encoding();
4128 const char *message = repo_logmsg_reencode(r, commit, NULL,
4129 encoding);
4130 const char *body;
4131 int len;
4133 if (!message) {
4134 ret = error(_("could not get commit message of '%s'"),
4135 oid_to_hex(&commit->object.oid));
4136 goto leave_merge;
4138 write_author_script(message);
4139 find_commit_subject(message, &body);
4140 len = strlen(body);
4141 strbuf_add(&ctx->message, body, len);
4142 repo_unuse_commit_buffer(r, commit, message);
4143 } else {
4144 struct strbuf buf = STRBUF_INIT;
4146 strbuf_addf(&buf, "author %s", git_author_info(0));
4147 write_author_script(buf.buf);
4148 strbuf_release(&buf);
4150 if (oneline_offset < arg_len) {
4151 strbuf_add(&ctx->message, arg + oneline_offset,
4152 arg_len - oneline_offset);
4153 } else {
4154 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4155 to_merge->next ? "branches" : "branch",
4156 merge_arg_len, arg);
4159 ctx->have_message = 1;
4160 if (write_message(ctx->message.buf, ctx->message.len,
4161 git_path_merge_msg(r), 0)) {
4162 ret = error_errno(_("could not write '%s'"),
4163 git_path_merge_msg(r));
4164 goto leave_merge;
4167 if (strategy || to_merge->next) {
4168 /* Octopus merge */
4169 struct child_process cmd = CHILD_PROCESS_INIT;
4171 if (read_env_script(&cmd.env)) {
4172 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4174 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4175 goto leave_merge;
4178 if (opts->committer_date_is_author_date)
4179 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4180 opts->ignore_date ?
4181 "" :
4182 author_date_from_env(&cmd.env));
4183 if (opts->ignore_date)
4184 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4186 cmd.git_cmd = 1;
4187 strvec_push(&cmd.args, "merge");
4188 strvec_push(&cmd.args, "-s");
4189 if (!strategy)
4190 strvec_push(&cmd.args, "octopus");
4191 else {
4192 strvec_push(&cmd.args, strategy);
4193 for (k = 0; k < opts->xopts.nr; k++)
4194 strvec_pushf(&cmd.args,
4195 "-X%s", opts->xopts.v[k]);
4197 if (!(flags & TODO_EDIT_MERGE_MSG))
4198 strvec_push(&cmd.args, "--no-edit");
4199 else
4200 strvec_push(&cmd.args, "--edit");
4201 strvec_push(&cmd.args, "--no-ff");
4202 strvec_push(&cmd.args, "--no-log");
4203 strvec_push(&cmd.args, "--no-stat");
4204 strvec_push(&cmd.args, "-F");
4205 strvec_push(&cmd.args, git_path_merge_msg(r));
4206 if (opts->gpg_sign)
4207 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4208 else
4209 strvec_push(&cmd.args, "--no-gpg-sign");
4211 /* Add the tips to be merged */
4212 for (j = to_merge; j; j = j->next)
4213 strvec_push(&cmd.args,
4214 oid_to_hex(&j->item->object.oid));
4216 strbuf_release(&ref_name);
4217 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4218 NULL, REF_NO_DEREF);
4219 rollback_lock_file(&lock);
4221 ret = run_command(&cmd);
4223 /* force re-reading of the cache */
4224 if (!ret) {
4225 discard_index(r->index);
4226 if (repo_read_index(r) < 0)
4227 ret = error(_("could not read index"));
4229 goto leave_merge;
4232 merge_commit = to_merge->item;
4233 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4234 ret = -1;
4235 goto leave_merge;
4238 if (bases && oideq(&merge_commit->object.oid,
4239 &bases->item->object.oid)) {
4240 ret = 0;
4241 /* skip merging an ancestor of HEAD */
4242 goto leave_merge;
4245 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4246 git_path_merge_head(r), 0);
4247 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4249 bases = reverse_commit_list(bases);
4251 repo_read_index(r);
4252 init_merge_options(&o, r);
4253 o.branch1 = "HEAD";
4254 o.branch2 = ref_name.buf;
4255 o.buffer_output = 2;
4257 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
4259 * TODO: Should use merge_incore_recursive() and
4260 * merge_switch_to_result(), skipping the call to
4261 * merge_switch_to_result() when we don't actually need to
4262 * update the index and working copy immediately.
4264 ret = merge_ort_recursive(&o,
4265 head_commit, merge_commit, bases,
4266 &i);
4267 } else {
4268 ret = merge_recursive(&o, head_commit, merge_commit, bases,
4269 &i);
4271 if (ret <= 0)
4272 fputs(o.obuf.buf, stdout);
4273 strbuf_release(&o.obuf);
4274 if (ret < 0) {
4275 error(_("could not even attempt to merge '%.*s'"),
4276 merge_arg_len, arg);
4277 unlink(git_path_merge_msg(r));
4278 goto leave_merge;
4281 * The return value of merge_recursive() is 1 on clean, and 0 on
4282 * unclean merge.
4284 * Let's reverse that, so that do_merge() returns 0 upon success and
4285 * 1 upon failed merge (keeping the return value -1 for the cases where
4286 * we will want to reschedule the `merge` command).
4288 ret = !ret;
4290 if (r->index->cache_changed &&
4291 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4292 ret = error(_("merge: Unable to write new index file"));
4293 goto leave_merge;
4296 rollback_lock_file(&lock);
4297 if (ret)
4298 repo_rerere(r, opts->allow_rerere_auto);
4299 else
4301 * In case of problems, we now want to return a positive
4302 * value (a negative one would indicate that the `merge`
4303 * command needs to be rescheduled).
4305 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4306 run_commit_flags);
4308 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4309 fast_forward_edit:
4310 *check_todo = 1;
4311 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4312 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4316 leave_merge:
4317 strbuf_release(&ref_name);
4318 rollback_lock_file(&lock);
4319 free_commit_list(to_merge);
4320 return ret;
4323 static int write_update_refs_state(struct string_list *refs_to_oids)
4325 int result = 0;
4326 struct lock_file lock = LOCK_INIT;
4327 FILE *fp = NULL;
4328 struct string_list_item *item;
4329 char *path;
4331 path = rebase_path_update_refs(the_repository->gitdir);
4333 if (!refs_to_oids->nr) {
4334 if (unlink(path) && errno != ENOENT)
4335 result = error_errno(_("could not unlink: %s"), path);
4336 goto cleanup;
4339 if (safe_create_leading_directories(path)) {
4340 result = error(_("unable to create leading directories of %s"),
4341 path);
4342 goto cleanup;
4345 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4346 result = error(_("another 'rebase' process appears to be running; "
4347 "'%s.lock' already exists"),
4348 path);
4349 goto cleanup;
4352 fp = fdopen_lock_file(&lock, "w");
4353 if (!fp) {
4354 result = error_errno(_("could not open '%s' for writing"), path);
4355 rollback_lock_file(&lock);
4356 goto cleanup;
4359 for_each_string_list_item(item, refs_to_oids) {
4360 struct update_ref_record *rec = item->util;
4361 fprintf(fp, "%s\n%s\n%s\n", item->string,
4362 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4365 result = commit_lock_file(&lock);
4367 cleanup:
4368 free(path);
4369 return result;
4373 * Parse the update-refs file for the current rebase, then remove the
4374 * refs that do not appear in the todo_list (and have not had updated
4375 * values stored) and add refs that are in the todo_list but not
4376 * represented in the update-refs file.
4378 * If there are changes to the update-refs list, then write the new state
4379 * to disk.
4381 void todo_list_filter_update_refs(struct repository *r,
4382 struct todo_list *todo_list)
4384 int i;
4385 int updated = 0;
4386 struct string_list update_refs = STRING_LIST_INIT_DUP;
4388 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4391 * For each item in the update_refs list, if it has no updated
4392 * value and does not appear in the todo_list, then remove it
4393 * from the update_refs list.
4395 for (i = 0; i < update_refs.nr; i++) {
4396 int j;
4397 int found = 0;
4398 const char *ref = update_refs.items[i].string;
4399 size_t reflen = strlen(ref);
4400 struct update_ref_record *rec = update_refs.items[i].util;
4402 /* OID already stored as updated. */
4403 if (!is_null_oid(&rec->after))
4404 continue;
4406 for (j = 0; !found && j < todo_list->nr; j++) {
4407 struct todo_item *item = &todo_list->items[j];
4408 const char *arg = todo_list->buf.buf + item->arg_offset;
4410 if (item->command != TODO_UPDATE_REF)
4411 continue;
4413 if (item->arg_len != reflen ||
4414 strncmp(arg, ref, reflen))
4415 continue;
4417 found = 1;
4420 if (!found) {
4421 free(update_refs.items[i].string);
4422 free(update_refs.items[i].util);
4424 update_refs.nr--;
4425 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4427 updated = 1;
4428 i--;
4433 * For each todo_item, check if its ref is in the update_refs list.
4434 * If not, then add it as an un-updated ref.
4436 for (i = 0; i < todo_list->nr; i++) {
4437 struct todo_item *item = &todo_list->items[i];
4438 const char *arg = todo_list->buf.buf + item->arg_offset;
4439 int j, found = 0;
4441 if (item->command != TODO_UPDATE_REF)
4442 continue;
4444 for (j = 0; !found && j < update_refs.nr; j++) {
4445 const char *ref = update_refs.items[j].string;
4447 found = strlen(ref) == item->arg_len &&
4448 !strncmp(ref, arg, item->arg_len);
4451 if (!found) {
4452 struct string_list_item *inserted;
4453 struct strbuf argref = STRBUF_INIT;
4455 strbuf_add(&argref, arg, item->arg_len);
4456 inserted = string_list_insert(&update_refs, argref.buf);
4457 inserted->util = init_update_ref_record(argref.buf);
4458 strbuf_release(&argref);
4459 updated = 1;
4463 if (updated)
4464 write_update_refs_state(&update_refs);
4465 string_list_clear(&update_refs, 1);
4468 static int do_update_ref(struct repository *r, const char *refname)
4470 struct string_list_item *item;
4471 struct string_list list = STRING_LIST_INIT_DUP;
4473 if (sequencer_get_update_refs_state(r->gitdir, &list))
4474 return -1;
4476 for_each_string_list_item(item, &list) {
4477 if (!strcmp(item->string, refname)) {
4478 struct update_ref_record *rec = item->util;
4479 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4480 return -1;
4481 break;
4485 write_update_refs_state(&list);
4486 string_list_clear(&list, 1);
4487 return 0;
4490 static int do_update_refs(struct repository *r, int quiet)
4492 int res = 0;
4493 struct string_list_item *item;
4494 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4495 struct ref_store *refs = get_main_ref_store(r);
4496 struct strbuf update_msg = STRBUF_INIT;
4497 struct strbuf error_msg = STRBUF_INIT;
4499 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4500 return res;
4502 for_each_string_list_item(item, &refs_to_oids) {
4503 struct update_ref_record *rec = item->util;
4504 int loop_res;
4506 loop_res = refs_update_ref(refs, "rewritten during rebase",
4507 item->string,
4508 &rec->after, &rec->before,
4509 0, UPDATE_REFS_MSG_ON_ERR);
4510 res |= loop_res;
4512 if (quiet)
4513 continue;
4515 if (loop_res)
4516 strbuf_addf(&error_msg, "\t%s\n", item->string);
4517 else
4518 strbuf_addf(&update_msg, "\t%s\n", item->string);
4521 if (!quiet &&
4522 (update_msg.len || error_msg.len)) {
4523 fprintf(stderr,
4524 _("Updated the following refs with %s:\n%s"),
4525 "--update-refs",
4526 update_msg.buf);
4528 if (res)
4529 fprintf(stderr,
4530 _("Failed to update the following refs with %s:\n%s"),
4531 "--update-refs",
4532 error_msg.buf);
4535 string_list_clear(&refs_to_oids, 1);
4536 strbuf_release(&update_msg);
4537 strbuf_release(&error_msg);
4538 return res;
4541 static int is_final_fixup(struct todo_list *todo_list)
4543 int i = todo_list->current;
4545 if (!is_fixup(todo_list->items[i].command))
4546 return 0;
4548 while (++i < todo_list->nr)
4549 if (is_fixup(todo_list->items[i].command))
4550 return 0;
4551 else if (!is_noop(todo_list->items[i].command))
4552 break;
4553 return 1;
4556 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4558 int i;
4560 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4561 if (!is_noop(todo_list->items[i].command))
4562 return todo_list->items[i].command;
4564 return -1;
4567 static void create_autostash_internal(struct repository *r,
4568 const char *path,
4569 const char *refname)
4571 struct strbuf buf = STRBUF_INIT;
4572 struct lock_file lock_file = LOCK_INIT;
4573 int fd;
4575 if (path && refname)
4576 BUG("can only pass path or refname");
4578 fd = repo_hold_locked_index(r, &lock_file, 0);
4579 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4580 if (0 <= fd)
4581 repo_update_index_if_able(r, &lock_file);
4582 rollback_lock_file(&lock_file);
4584 if (has_unstaged_changes(r, 1) ||
4585 has_uncommitted_changes(r, 1)) {
4586 struct child_process stash = CHILD_PROCESS_INIT;
4587 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
4588 struct object_id oid;
4590 strvec_pushl(&stash.args,
4591 "stash", "create", "autostash", NULL);
4592 stash.git_cmd = 1;
4593 stash.no_stdin = 1;
4594 strbuf_reset(&buf);
4595 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4596 die(_("Cannot autostash"));
4597 strbuf_trim_trailing_newline(&buf);
4598 if (repo_get_oid(r, buf.buf, &oid))
4599 die(_("Unexpected stash response: '%s'"),
4600 buf.buf);
4601 strbuf_reset(&buf);
4602 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4604 if (path) {
4605 if (safe_create_leading_directories_const(path))
4606 die(_("Could not create directory for '%s'"),
4607 path);
4608 write_file(path, "%s", oid_to_hex(&oid));
4609 } else {
4610 refs_update_ref(get_main_ref_store(r), "", refname,
4611 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4614 printf(_("Created autostash: %s\n"), buf.buf);
4615 if (reset_head(r, &ropts) < 0)
4616 die(_("could not reset --hard"));
4617 discard_index(r->index);
4618 if (repo_read_index(r) < 0)
4619 die(_("could not read index"));
4621 strbuf_release(&buf);
4624 void create_autostash(struct repository *r, const char *path)
4626 create_autostash_internal(r, path, NULL);
4629 void create_autostash_ref(struct repository *r, const char *refname)
4631 create_autostash_internal(r, NULL, refname);
4634 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4636 struct child_process child = CHILD_PROCESS_INIT;
4637 int ret = 0;
4639 if (attempt_apply) {
4640 child.git_cmd = 1;
4641 child.no_stdout = 1;
4642 child.no_stderr = 1;
4643 strvec_push(&child.args, "stash");
4644 strvec_push(&child.args, "apply");
4645 strvec_push(&child.args, stash_oid);
4646 ret = run_command(&child);
4649 if (attempt_apply && !ret)
4650 fprintf(stderr, _("Applied autostash.\n"));
4651 else {
4652 struct child_process store = CHILD_PROCESS_INIT;
4654 store.git_cmd = 1;
4655 strvec_push(&store.args, "stash");
4656 strvec_push(&store.args, "store");
4657 strvec_push(&store.args, "-m");
4658 strvec_push(&store.args, "autostash");
4659 strvec_push(&store.args, "-q");
4660 strvec_push(&store.args, stash_oid);
4661 if (run_command(&store))
4662 ret = error(_("cannot store %s"), stash_oid);
4663 else
4664 fprintf(stderr,
4665 _("%s\n"
4666 "Your changes are safe in the stash.\n"
4667 "You can run \"git stash pop\" or"
4668 " \"git stash drop\" at any time.\n"),
4669 attempt_apply ?
4670 _("Applying autostash resulted in conflicts.") :
4671 _("Autostash exists; creating a new stash entry."));
4674 return ret;
4677 static int apply_save_autostash(const char *path, int attempt_apply)
4679 struct strbuf stash_oid = STRBUF_INIT;
4680 int ret = 0;
4682 if (!read_oneliner(&stash_oid, path,
4683 READ_ONELINER_SKIP_IF_EMPTY)) {
4684 strbuf_release(&stash_oid);
4685 return 0;
4687 strbuf_trim(&stash_oid);
4689 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4691 unlink(path);
4692 strbuf_release(&stash_oid);
4693 return ret;
4696 int save_autostash(const char *path)
4698 return apply_save_autostash(path, 0);
4701 int apply_autostash(const char *path)
4703 return apply_save_autostash(path, 1);
4706 int apply_autostash_oid(const char *stash_oid)
4708 return apply_save_autostash_oid(stash_oid, 1);
4711 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4712 int attempt_apply)
4714 struct object_id stash_oid;
4715 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4716 int flag, ret;
4718 if (!refs_ref_exists(get_main_ref_store(r), refname))
4719 return 0;
4721 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4722 RESOLVE_REF_READING, &stash_oid, &flag))
4723 return -1;
4724 if (flag & REF_ISSYMREF)
4725 return error(_("autostash reference is a symref"));
4727 oid_to_hex_r(stash_oid_hex, &stash_oid);
4728 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4730 refs_delete_ref(get_main_ref_store(r), "", refname,
4731 &stash_oid, REF_NO_DEREF);
4733 return ret;
4736 int save_autostash_ref(struct repository *r, const char *refname)
4738 return apply_save_autostash_ref(r, refname, 0);
4741 int apply_autostash_ref(struct repository *r, const char *refname)
4743 return apply_save_autostash_ref(r, refname, 1);
4746 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4747 const char *onto_name, const struct object_id *onto,
4748 const struct object_id *orig_head)
4750 struct reset_head_opts ropts = {
4751 .oid = onto,
4752 .orig_head = orig_head,
4753 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4754 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4755 .head_msg = reflog_message(opts, "start", "checkout %s",
4756 onto_name),
4757 .default_reflog_action = sequencer_reflog_action(opts)
4759 if (reset_head(r, &ropts)) {
4760 apply_autostash(rebase_path_autostash());
4761 sequencer_remove_state(opts);
4762 return error(_("could not detach HEAD"));
4765 return 0;
4768 static int stopped_at_head(struct repository *r)
4770 struct object_id head;
4771 struct commit *commit;
4772 struct commit_message message;
4774 if (repo_get_oid(r, "HEAD", &head) ||
4775 !(commit = lookup_commit(r, &head)) ||
4776 repo_parse_commit(r, commit) || get_message(commit, &message))
4777 fprintf(stderr, _("Stopped at HEAD\n"));
4778 else {
4779 fprintf(stderr, _("Stopped at %s\n"), message.label);
4780 free_message(commit, &message);
4782 return 0;
4786 static int reread_todo_if_changed(struct repository *r,
4787 struct todo_list *todo_list,
4788 struct replay_opts *opts)
4790 int offset;
4791 struct strbuf buf = STRBUF_INIT;
4793 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4794 return -1;
4795 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4796 if (buf.len != todo_list->buf.len - offset ||
4797 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4798 /* Reread the todo file if it has changed. */
4799 todo_list_release(todo_list);
4800 if (read_populate_todo(r, todo_list, opts))
4801 return -1; /* message was printed */
4802 /* `current` will be incremented on return */
4803 todo_list->current = -1;
4805 strbuf_release(&buf);
4807 return 0;
4810 static const char rescheduled_advice[] =
4811 N_("Could not execute the todo command\n"
4812 "\n"
4813 " %.*s"
4814 "\n"
4815 "It has been rescheduled; To edit the command before continuing, please\n"
4816 "edit the todo list first:\n"
4817 "\n"
4818 " git rebase --edit-todo\n"
4819 " git rebase --continue\n");
4821 static int pick_one_commit(struct repository *r,
4822 struct todo_list *todo_list,
4823 struct replay_opts *opts,
4824 int *check_todo, int* reschedule)
4826 struct replay_ctx *ctx = opts->ctx;
4827 int res;
4828 struct todo_item *item = todo_list->items + todo_list->current;
4829 const char *arg = todo_item_get_arg(todo_list, item);
4830 if (is_rebase_i(opts))
4831 ctx->reflog_message = reflog_message(
4832 opts, command_to_string(item->command), NULL);
4834 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4835 check_todo);
4836 if (is_rebase_i(opts) && res < 0) {
4837 /* Reschedule */
4838 *reschedule = 1;
4839 return -1;
4841 if (item->command == TODO_EDIT) {
4842 struct commit *commit = item->commit;
4843 if (!res) {
4844 if (!opts->verbose)
4845 term_clear_line();
4846 fprintf(stderr, _("Stopped at %s... %.*s\n"),
4847 short_commit_name(r, commit), item->arg_len, arg);
4849 return error_with_patch(r, commit,
4850 arg, item->arg_len, opts, res, !res);
4852 if (is_rebase_i(opts) && !res)
4853 record_in_rewritten(&item->commit->object.oid,
4854 peek_command(todo_list, 1));
4855 if (res && is_fixup(item->command)) {
4856 if (res == 1)
4857 intend_to_amend();
4858 return error_failed_squash(r, item->commit, opts,
4859 item->arg_len, arg);
4860 } else if (res && is_rebase_i(opts) && item->commit) {
4861 int to_amend = 0;
4862 struct object_id oid;
4865 * If we are rewording and have either
4866 * fast-forwarded already, or are about to
4867 * create a new root commit, we want to amend,
4868 * otherwise we do not.
4870 if (item->command == TODO_REWORD &&
4871 !repo_get_oid(r, "HEAD", &oid) &&
4872 (oideq(&item->commit->object.oid, &oid) ||
4873 (opts->have_squash_onto &&
4874 oideq(&opts->squash_onto, &oid))))
4875 to_amend = 1;
4877 return res | error_with_patch(r, item->commit,
4878 arg, item->arg_len, opts,
4879 res, to_amend);
4881 return res;
4884 static int pick_commits(struct repository *r,
4885 struct todo_list *todo_list,
4886 struct replay_opts *opts)
4888 struct replay_ctx *ctx = opts->ctx;
4889 int res = 0, reschedule = 0;
4891 ctx->reflog_message = sequencer_reflog_action(opts);
4892 if (opts->allow_ff)
4893 assert(!(opts->signoff || opts->no_commit ||
4894 opts->record_origin || should_edit(opts) ||
4895 opts->committer_date_is_author_date ||
4896 opts->ignore_date));
4897 if (read_and_refresh_cache(r, opts))
4898 return -1;
4900 unlink(rebase_path_message());
4901 unlink(rebase_path_stopped_sha());
4902 unlink(rebase_path_amend());
4903 unlink(rebase_path_patch());
4905 while (todo_list->current < todo_list->nr) {
4906 struct todo_item *item = todo_list->items + todo_list->current;
4907 const char *arg = todo_item_get_arg(todo_list, item);
4908 int check_todo = 0;
4910 if (save_todo(todo_list, opts, reschedule))
4911 return -1;
4912 if (is_rebase_i(opts)) {
4913 if (item->command != TODO_COMMENT) {
4914 FILE *f = fopen(rebase_path_msgnum(), "w");
4916 todo_list->done_nr++;
4918 if (f) {
4919 fprintf(f, "%d\n", todo_list->done_nr);
4920 fclose(f);
4922 if (!opts->quiet)
4923 fprintf(stderr, _("Rebasing (%d/%d)%s"),
4924 todo_list->done_nr,
4925 todo_list->total_nr,
4926 opts->verbose ? "\n" : "\r");
4928 unlink(rebase_path_author_script());
4929 unlink(git_path_merge_head(r));
4930 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4931 NULL, REF_NO_DEREF);
4932 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4933 NULL, REF_NO_DEREF);
4935 if (item->command == TODO_BREAK) {
4936 if (!opts->verbose)
4937 term_clear_line();
4938 return stopped_at_head(r);
4941 strbuf_reset(&ctx->message);
4942 ctx->have_message = 0;
4943 if (item->command <= TODO_SQUASH) {
4944 res = pick_one_commit(r, todo_list, opts, &check_todo,
4945 &reschedule);
4946 if (!res && item->command == TODO_EDIT)
4947 return 0;
4948 } else if (item->command == TODO_EXEC) {
4949 char *end_of_arg = (char *)(arg + item->arg_len);
4950 int saved = *end_of_arg;
4952 if (!opts->verbose)
4953 term_clear_line();
4954 *end_of_arg = '\0';
4955 res = do_exec(r, arg);
4956 *end_of_arg = saved;
4958 if (res) {
4959 if (opts->reschedule_failed_exec)
4960 reschedule = 1;
4962 check_todo = 1;
4963 } else if (item->command == TODO_LABEL) {
4964 if ((res = do_label(r, arg, item->arg_len)))
4965 reschedule = 1;
4966 } else if (item->command == TODO_RESET) {
4967 if ((res = do_reset(r, arg, item->arg_len, opts)))
4968 reschedule = 1;
4969 } else if (item->command == TODO_MERGE) {
4970 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4971 item->flags, &check_todo, opts)) < 0)
4972 reschedule = 1;
4973 else if (item->commit)
4974 record_in_rewritten(&item->commit->object.oid,
4975 peek_command(todo_list, 1));
4976 if (res > 0)
4977 /* failed with merge conflicts */
4978 return error_with_patch(r, item->commit,
4979 arg, item->arg_len,
4980 opts, res, 0);
4981 } else if (item->command == TODO_UPDATE_REF) {
4982 struct strbuf ref = STRBUF_INIT;
4983 strbuf_add(&ref, arg, item->arg_len);
4984 if ((res = do_update_ref(r, ref.buf)))
4985 reschedule = 1;
4986 strbuf_release(&ref);
4987 } else if (!is_noop(item->command))
4988 return error(_("unknown command %d"), item->command);
4990 if (reschedule) {
4991 advise(_(rescheduled_advice),
4992 get_item_line_length(todo_list,
4993 todo_list->current),
4994 get_item_line(todo_list, todo_list->current));
4995 if (save_todo(todo_list, opts, reschedule))
4996 return -1;
4997 if (item->commit)
4998 write_rebase_head(&item->commit->object.oid);
4999 } else if (is_rebase_i(opts) && check_todo && !res &&
5000 reread_todo_if_changed(r, todo_list, opts)) {
5001 return -1;
5004 if (res)
5005 return res;
5007 todo_list->current++;
5010 if (is_rebase_i(opts)) {
5011 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
5012 struct stat st;
5014 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5015 starts_with(head_ref.buf, "refs/")) {
5016 const char *msg;
5017 struct object_id head, orig;
5018 int res;
5020 if (repo_get_oid(r, "HEAD", &head)) {
5021 res = error(_("cannot read HEAD"));
5022 cleanup_head_ref:
5023 strbuf_release(&head_ref);
5024 strbuf_release(&buf);
5025 return res;
5027 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
5028 get_oid_hex(buf.buf, &orig)) {
5029 res = error(_("could not read orig-head"));
5030 goto cleanup_head_ref;
5032 strbuf_reset(&buf);
5033 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5034 res = error(_("could not read 'onto'"));
5035 goto cleanup_head_ref;
5037 msg = reflog_message(opts, "finish", "%s onto %s",
5038 head_ref.buf, buf.buf);
5039 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5040 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
5041 res = error(_("could not update %s"),
5042 head_ref.buf);
5043 goto cleanup_head_ref;
5045 msg = reflog_message(opts, "finish", "returning to %s",
5046 head_ref.buf);
5047 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
5048 res = error(_("could not update HEAD to %s"),
5049 head_ref.buf);
5050 goto cleanup_head_ref;
5052 strbuf_reset(&buf);
5055 if (opts->verbose) {
5056 struct rev_info log_tree_opt;
5057 struct object_id orig, head;
5059 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
5060 repo_init_revisions(r, &log_tree_opt, NULL);
5061 log_tree_opt.diff = 1;
5062 log_tree_opt.diffopt.output_format =
5063 DIFF_FORMAT_DIFFSTAT;
5064 log_tree_opt.disable_stdin = 1;
5066 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
5067 !repo_get_oid(r, buf.buf, &orig) &&
5068 !repo_get_oid(r, "HEAD", &head)) {
5069 diff_tree_oid(&orig, &head, "",
5070 &log_tree_opt.diffopt);
5071 log_tree_diff_flush(&log_tree_opt);
5073 release_revisions(&log_tree_opt);
5075 flush_rewritten_pending();
5076 if (!stat(rebase_path_rewritten_list(), &st) &&
5077 st.st_size > 0) {
5078 struct child_process child = CHILD_PROCESS_INIT;
5079 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5081 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5082 child.git_cmd = 1;
5083 strvec_push(&child.args, "notes");
5084 strvec_push(&child.args, "copy");
5085 strvec_push(&child.args, "--for-rewrite=rebase");
5086 /* we don't care if this copying failed */
5087 run_command(&child);
5089 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5090 strvec_push(&hook_opt.args, "rebase");
5091 run_hooks_opt("post-rewrite", &hook_opt);
5093 apply_autostash(rebase_path_autostash());
5095 if (!opts->quiet) {
5096 if (!opts->verbose)
5097 term_clear_line();
5098 fprintf(stderr,
5099 _("Successfully rebased and updated %s.\n"),
5100 head_ref.buf);
5103 strbuf_release(&buf);
5104 strbuf_release(&head_ref);
5106 if (do_update_refs(r, opts->quiet))
5107 return -1;
5111 * Sequence of picks finished successfully; cleanup by
5112 * removing the .git/sequencer directory
5114 return sequencer_remove_state(opts);
5117 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5119 struct child_process cmd = CHILD_PROCESS_INIT;
5121 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5122 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5123 return error(_("no cherry-pick or revert in progress"));
5125 cmd.git_cmd = 1;
5126 strvec_push(&cmd.args, "commit");
5129 * continue_single_pick() handles the case of recovering from a
5130 * conflict. should_edit() doesn't handle that case; for a conflict,
5131 * we want to edit if the user asked for it, or if they didn't specify
5132 * and stdin is a tty.
5134 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5136 * Include --cleanup=strip as well because we don't want the
5137 * "# Conflicts:" messages.
5139 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5141 return run_command(&cmd);
5144 static int commit_staged_changes(struct repository *r,
5145 struct replay_opts *opts,
5146 struct todo_list *todo_list)
5148 struct replay_ctx *ctx = opts->ctx;
5149 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5150 unsigned int final_fixup = 0, is_clean;
5152 if (has_unstaged_changes(r, 1))
5153 return error(_("cannot rebase: You have unstaged changes."));
5155 is_clean = !has_uncommitted_changes(r, 0);
5157 if (!is_clean && !file_exists(rebase_path_message())) {
5158 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5160 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5162 if (file_exists(rebase_path_amend())) {
5163 struct strbuf rev = STRBUF_INIT;
5164 struct object_id head, to_amend;
5166 if (repo_get_oid(r, "HEAD", &head))
5167 return error(_("cannot amend non-existing commit"));
5168 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5169 return error(_("invalid file: '%s'"), rebase_path_amend());
5170 if (get_oid_hex(rev.buf, &to_amend))
5171 return error(_("invalid contents: '%s'"),
5172 rebase_path_amend());
5173 if (!is_clean && !oideq(&head, &to_amend))
5174 return error(_("\nYou have uncommitted changes in your "
5175 "working tree. Please, commit them\n"
5176 "first and then run 'git rebase "
5177 "--continue' again."));
5179 * When skipping a failed fixup/squash, we need to edit the
5180 * commit message, the current fixup list and count, and if it
5181 * was the last fixup/squash in the chain, we need to clean up
5182 * the commit message and if there was a squash, let the user
5183 * edit it.
5185 if (!is_clean || !ctx->current_fixup_count)
5186 ; /* this is not the final fixup */
5187 else if (!oideq(&head, &to_amend) ||
5188 !file_exists(rebase_path_stopped_sha())) {
5189 /* was a final fixup or squash done manually? */
5190 if (!is_fixup(peek_command(todo_list, 0))) {
5191 unlink(rebase_path_fixup_msg());
5192 unlink(rebase_path_squash_msg());
5193 unlink(rebase_path_current_fixups());
5194 strbuf_reset(&ctx->current_fixups);
5195 ctx->current_fixup_count = 0;
5197 } else {
5198 /* we are in a fixup/squash chain */
5199 const char *p = ctx->current_fixups.buf;
5200 int len = ctx->current_fixups.len;
5202 ctx->current_fixup_count--;
5203 if (!len)
5204 BUG("Incorrect current_fixups:\n%s", p);
5205 while (len && p[len - 1] != '\n')
5206 len--;
5207 strbuf_setlen(&ctx->current_fixups, len);
5208 if (write_message(p, len, rebase_path_current_fixups(),
5209 0) < 0)
5210 return error(_("could not write file: '%s'"),
5211 rebase_path_current_fixups());
5214 * If a fixup/squash in a fixup/squash chain failed, the
5215 * commit message is already correct, no need to commit
5216 * it again.
5218 * Only if it is the final command in the fixup/squash
5219 * chain, and only if the chain is longer than a single
5220 * fixup/squash command (which was just skipped), do we
5221 * actually need to re-commit with a cleaned up commit
5222 * message.
5224 if (ctx->current_fixup_count > 0 &&
5225 !is_fixup(peek_command(todo_list, 0))) {
5226 final_fixup = 1;
5228 * If there was not a single "squash" in the
5229 * chain, we only need to clean up the commit
5230 * message, no need to bother the user with
5231 * opening the commit message in the editor.
5233 if (!starts_with(p, "squash ") &&
5234 !strstr(p, "\nsquash "))
5235 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5236 } else if (is_fixup(peek_command(todo_list, 0))) {
5238 * We need to update the squash message to skip
5239 * the latest commit message.
5241 int res = 0;
5242 struct commit *commit;
5243 const char *msg;
5244 const char *path = rebase_path_squash_msg();
5245 const char *encoding = get_commit_output_encoding();
5247 if (parse_head(r, &commit))
5248 return error(_("could not parse HEAD"));
5250 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5251 if (!p) {
5252 res = error(_("could not parse commit %s"),
5253 oid_to_hex(&commit->object.oid));
5254 goto unuse_commit_buffer;
5256 find_commit_subject(p, &msg);
5257 if (write_message(msg, strlen(msg), path, 0)) {
5258 res = error(_("could not write file: "
5259 "'%s'"), path);
5260 goto unuse_commit_buffer;
5262 unuse_commit_buffer:
5263 repo_unuse_commit_buffer(r, commit, p);
5264 if (res)
5265 return res;
5269 strbuf_release(&rev);
5270 flags |= AMEND_MSG;
5273 if (is_clean) {
5274 if (refs_ref_exists(get_main_ref_store(r),
5275 "CHERRY_PICK_HEAD") &&
5276 refs_delete_ref(get_main_ref_store(r), "",
5277 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
5278 return error(_("could not remove CHERRY_PICK_HEAD"));
5279 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5280 return error_errno(_("could not remove '%s'"),
5281 git_path_merge_msg(r));
5282 if (!final_fixup)
5283 return 0;
5286 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5287 opts, flags))
5288 return error(_("could not commit staged changes."));
5289 unlink(rebase_path_amend());
5290 unlink(git_path_merge_head(r));
5291 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5292 NULL, REF_NO_DEREF);
5293 if (final_fixup) {
5294 unlink(rebase_path_fixup_msg());
5295 unlink(rebase_path_squash_msg());
5297 if (ctx->current_fixup_count > 0) {
5299 * Whether final fixup or not, we just cleaned up the commit
5300 * message...
5302 unlink(rebase_path_current_fixups());
5303 strbuf_reset(&ctx->current_fixups);
5304 ctx->current_fixup_count = 0;
5306 return 0;
5309 int sequencer_continue(struct repository *r, struct replay_opts *opts)
5311 struct replay_ctx *ctx = opts->ctx;
5312 struct todo_list todo_list = TODO_LIST_INIT;
5313 int res;
5315 if (read_and_refresh_cache(r, opts))
5316 return -1;
5318 if (read_populate_opts(opts))
5319 return -1;
5320 if (is_rebase_i(opts)) {
5321 if ((res = read_populate_todo(r, &todo_list, opts)))
5322 goto release_todo_list;
5324 if (file_exists(rebase_path_dropped())) {
5325 if ((res = todo_list_check_against_backup(r, &todo_list)))
5326 goto release_todo_list;
5328 unlink(rebase_path_dropped());
5331 ctx->reflog_message = reflog_message(opts, "continue", NULL);
5332 if (commit_staged_changes(r, opts, &todo_list)) {
5333 res = -1;
5334 goto release_todo_list;
5336 } else if (!file_exists(get_todo_path(opts)))
5337 return continue_single_pick(r, opts);
5338 else if ((res = read_populate_todo(r, &todo_list, opts)))
5339 goto release_todo_list;
5341 if (!is_rebase_i(opts)) {
5342 /* Verify that the conflict has been resolved */
5343 if (refs_ref_exists(get_main_ref_store(r),
5344 "CHERRY_PICK_HEAD") ||
5345 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5346 res = continue_single_pick(r, opts);
5347 if (res)
5348 goto release_todo_list;
5350 if (index_differs_from(r, "HEAD", NULL, 0)) {
5351 res = error_dirty_index(r, opts);
5352 goto release_todo_list;
5354 todo_list.current++;
5355 } else if (file_exists(rebase_path_stopped_sha())) {
5356 struct strbuf buf = STRBUF_INIT;
5357 struct object_id oid;
5359 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5360 READ_ONELINER_SKIP_IF_EMPTY) &&
5361 !get_oid_hex(buf.buf, &oid))
5362 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5363 strbuf_release(&buf);
5366 res = pick_commits(r, &todo_list, opts);
5367 release_todo_list:
5368 todo_list_release(&todo_list);
5369 return res;
5372 static int single_pick(struct repository *r,
5373 struct commit *cmit,
5374 struct replay_opts *opts)
5376 int check_todo;
5377 struct todo_item item;
5379 item.command = opts->action == REPLAY_PICK ?
5380 TODO_PICK : TODO_REVERT;
5381 item.commit = cmit;
5383 opts->ctx->reflog_message = sequencer_reflog_action(opts);
5384 return do_pick_commit(r, &item, opts, 0, &check_todo);
5387 int sequencer_pick_revisions(struct repository *r,
5388 struct replay_opts *opts)
5390 struct todo_list todo_list = TODO_LIST_INIT;
5391 struct object_id oid;
5392 int i, res;
5394 assert(opts->revs);
5395 if (read_and_refresh_cache(r, opts))
5396 return -1;
5398 for (i = 0; i < opts->revs->pending.nr; i++) {
5399 struct object_id oid;
5400 const char *name = opts->revs->pending.objects[i].name;
5402 /* This happens when using --stdin. */
5403 if (!strlen(name))
5404 continue;
5406 if (!repo_get_oid(r, name, &oid)) {
5407 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5408 enum object_type type = oid_object_info(r,
5409 &oid,
5410 NULL);
5411 return error(_("%s: can't cherry-pick a %s"),
5412 name, type_name(type));
5414 } else
5415 return error(_("%s: bad revision"), name);
5419 * If we were called as "git cherry-pick <commit>", just
5420 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5421 * REVERT_HEAD, and don't touch the sequencer state.
5422 * This means it is possible to cherry-pick in the middle
5423 * of a cherry-pick sequence.
5425 if (opts->revs->cmdline.nr == 1 &&
5426 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5427 opts->revs->no_walk &&
5428 !opts->revs->cmdline.rev->flags) {
5429 struct commit *cmit;
5430 if (prepare_revision_walk(opts->revs))
5431 return error(_("revision walk setup failed"));
5432 cmit = get_revision(opts->revs);
5433 if (!cmit)
5434 return error(_("empty commit set passed"));
5435 if (get_revision(opts->revs))
5436 BUG("unexpected extra commit from walk");
5437 return single_pick(r, cmit, opts);
5441 * Start a new cherry-pick/ revert sequence; but
5442 * first, make sure that an existing one isn't in
5443 * progress
5446 if (walk_revs_populate_todo(&todo_list, opts) ||
5447 create_seq_dir(r) < 0)
5448 return -1;
5449 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
5450 return error(_("can't revert as initial commit"));
5451 if (save_head(oid_to_hex(&oid)))
5452 return -1;
5453 if (save_opts(opts))
5454 return -1;
5455 update_abort_safety_file();
5456 res = pick_commits(r, &todo_list, opts);
5457 todo_list_release(&todo_list);
5458 return res;
5461 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5463 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5464 struct strbuf sob = STRBUF_INIT;
5465 int has_footer;
5467 strbuf_addstr(&sob, sign_off_header);
5468 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5469 strbuf_addch(&sob, '\n');
5471 if (!ignore_footer)
5472 strbuf_complete_line(msgbuf);
5475 * If the whole message buffer is equal to the sob, pretend that we
5476 * found a conforming footer with a matching sob
5478 if (msgbuf->len - ignore_footer == sob.len &&
5479 !strncmp(msgbuf->buf, sob.buf, sob.len))
5480 has_footer = 3;
5481 else
5482 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5484 if (!has_footer) {
5485 const char *append_newlines = NULL;
5486 size_t len = msgbuf->len - ignore_footer;
5488 if (!len) {
5490 * The buffer is completely empty. Leave foom for
5491 * the title and body to be filled in by the user.
5493 append_newlines = "\n\n";
5494 } else if (len == 1) {
5496 * Buffer contains a single newline. Add another
5497 * so that we leave room for the title and body.
5499 append_newlines = "\n";
5500 } else if (msgbuf->buf[len - 2] != '\n') {
5502 * Buffer ends with a single newline. Add another
5503 * so that there is an empty line between the message
5504 * body and the sob.
5506 append_newlines = "\n";
5507 } /* else, the buffer already ends with two newlines. */
5509 if (append_newlines)
5510 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5511 append_newlines, strlen(append_newlines));
5514 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5515 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5516 sob.buf, sob.len);
5518 strbuf_release(&sob);
5521 struct labels_entry {
5522 struct hashmap_entry entry;
5523 char label[FLEX_ARRAY];
5526 static int labels_cmp(const void *fndata UNUSED,
5527 const struct hashmap_entry *eptr,
5528 const struct hashmap_entry *entry_or_key, const void *key)
5530 const struct labels_entry *a, *b;
5532 a = container_of(eptr, const struct labels_entry, entry);
5533 b = container_of(entry_or_key, const struct labels_entry, entry);
5535 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5538 struct string_entry {
5539 struct oidmap_entry entry;
5540 char string[FLEX_ARRAY];
5543 struct label_state {
5544 struct oidmap commit2label;
5545 struct hashmap labels;
5546 struct strbuf buf;
5547 int max_label_length;
5550 static const char *label_oid(struct object_id *oid, const char *label,
5551 struct label_state *state)
5553 struct labels_entry *labels_entry;
5554 struct string_entry *string_entry;
5555 struct object_id dummy;
5556 int i;
5558 string_entry = oidmap_get(&state->commit2label, oid);
5559 if (string_entry)
5560 return string_entry->string;
5563 * For "uninteresting" commits, i.e. commits that are not to be
5564 * rebased, and which can therefore not be labeled, we use a unique
5565 * abbreviation of the commit name. This is slightly more complicated
5566 * than calling repo_find_unique_abbrev() because we also need to make
5567 * sure that the abbreviation does not conflict with any other
5568 * label.
5570 * We disallow "interesting" commits to be labeled by a string that
5571 * is a valid full-length hash, to ensure that we always can find an
5572 * abbreviation for any uninteresting commit's names that does not
5573 * clash with any other label.
5575 strbuf_reset(&state->buf);
5576 if (!label) {
5577 char *p;
5579 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5580 label = p = state->buf.buf;
5582 repo_find_unique_abbrev_r(the_repository, p, oid,
5583 default_abbrev);
5586 * We may need to extend the abbreviated hash so that there is
5587 * no conflicting label.
5589 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5590 size_t i = strlen(p) + 1;
5592 oid_to_hex_r(p, oid);
5593 for (; i < the_hash_algo->hexsz; i++) {
5594 char save = p[i];
5595 p[i] = '\0';
5596 if (!hashmap_get_from_hash(&state->labels,
5597 strihash(p), p))
5598 break;
5599 p[i] = save;
5602 } else {
5603 struct strbuf *buf = &state->buf;
5604 int label_is_utf8 = 1; /* start with this assumption */
5605 size_t max_len = buf->len + state->max_label_length;
5608 * Sanitize labels by replacing non-alpha-numeric characters
5609 * (including white-space ones) by dashes, as they might be
5610 * illegal in file names (and hence in ref names).
5612 * Note that we retain non-ASCII UTF-8 characters (identified
5613 * via the most significant bit). They should be all acceptable
5614 * in file names.
5616 * As we will use the labels as names of (loose) refs, it is
5617 * vital that the name not be longer than the maximum component
5618 * size of the file system (`NAME_MAX`). We are careful to
5619 * truncate the label accordingly, allowing for the `.lock`
5620 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5621 * truncating in the middle of a character).
5623 for (; *label && buf->len + 1 < max_len; label++)
5624 if (isalnum(*label) ||
5625 (!label_is_utf8 && (*label & 0x80)))
5626 strbuf_addch(buf, *label);
5627 else if (*label & 0x80) {
5628 const char *p = label;
5630 utf8_width(&p, NULL);
5631 if (p) {
5632 if (buf->len + (p - label) > max_len)
5633 break;
5634 strbuf_add(buf, label, p - label);
5635 label = p - 1;
5636 } else {
5637 label_is_utf8 = 0;
5638 strbuf_addch(buf, *label);
5640 /* avoid leading dash and double-dashes */
5641 } else if (buf->len && buf->buf[buf->len - 1] != '-')
5642 strbuf_addch(buf, '-');
5643 if (!buf->len) {
5644 strbuf_addstr(buf, "rev-");
5645 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5647 label = buf->buf;
5649 if ((buf->len == the_hash_algo->hexsz &&
5650 !get_oid_hex(label, &dummy)) ||
5651 (buf->len == 1 && *label == '#') ||
5652 hashmap_get_from_hash(&state->labels,
5653 strihash(label), label)) {
5655 * If the label already exists, or if the label is a
5656 * valid full OID, or the label is a '#' (which we use
5657 * as a separator between merge heads and oneline), we
5658 * append a dash and a number to make it unique.
5660 size_t len = buf->len;
5662 for (i = 2; ; i++) {
5663 strbuf_setlen(buf, len);
5664 strbuf_addf(buf, "-%d", i);
5665 if (!hashmap_get_from_hash(&state->labels,
5666 strihash(buf->buf),
5667 buf->buf))
5668 break;
5671 label = buf->buf;
5675 FLEX_ALLOC_STR(labels_entry, label, label);
5676 hashmap_entry_init(&labels_entry->entry, strihash(label));
5677 hashmap_add(&state->labels, &labels_entry->entry);
5679 FLEX_ALLOC_STR(string_entry, string, label);
5680 oidcpy(&string_entry->entry.oid, oid);
5681 oidmap_put(&state->commit2label, string_entry);
5683 return string_entry->string;
5686 static int make_script_with_merges(struct pretty_print_context *pp,
5687 struct rev_info *revs, struct strbuf *out,
5688 unsigned flags)
5690 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5691 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5692 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5693 int skipped_commit = 0;
5694 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5695 struct strbuf label = STRBUF_INIT;
5696 struct commit_list *commits = NULL, **tail = &commits, *iter;
5697 struct commit_list *tips = NULL, **tips_tail = &tips;
5698 struct commit *commit;
5699 struct oidmap commit2todo = OIDMAP_INIT;
5700 struct string_entry *entry;
5701 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5702 shown = OIDSET_INIT;
5703 struct label_state state =
5704 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
5706 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5707 const char *cmd_pick = abbr ? "p" : "pick",
5708 *cmd_label = abbr ? "l" : "label",
5709 *cmd_reset = abbr ? "t" : "reset",
5710 *cmd_merge = abbr ? "m" : "merge";
5712 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5714 oidmap_init(&commit2todo, 0);
5715 oidmap_init(&state.commit2label, 0);
5716 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5717 strbuf_init(&state.buf, 32);
5719 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5720 struct labels_entry *onto_label_entry;
5721 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5722 FLEX_ALLOC_STR(entry, string, "onto");
5723 oidcpy(&entry->entry.oid, oid);
5724 oidmap_put(&state.commit2label, entry);
5726 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5727 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5728 hashmap_add(&state.labels, &onto_label_entry->entry);
5732 * First phase:
5733 * - get onelines for all commits
5734 * - gather all branch tips (i.e. 2nd or later parents of merges)
5735 * - label all branch tips
5737 while ((commit = get_revision(revs))) {
5738 struct commit_list *to_merge;
5739 const char *p1, *p2;
5740 struct object_id *oid;
5741 int is_empty;
5743 tail = &commit_list_insert(commit, tail)->next;
5744 oidset_insert(&interesting, &commit->object.oid);
5746 is_empty = is_original_commit_empty(commit);
5747 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5748 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5749 warning(_("skipped previously applied commit %s"),
5750 short_commit_name(the_repository, commit));
5751 skipped_commit = 1;
5752 continue;
5754 if (is_empty && !keep_empty)
5755 continue;
5757 strbuf_reset(&oneline);
5758 pretty_print_commit(pp, commit, &oneline);
5760 to_merge = commit->parents ? commit->parents->next : NULL;
5761 if (!to_merge) {
5762 /* non-merge commit: easy case */
5763 strbuf_reset(&buf);
5764 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5765 oid_to_hex(&commit->object.oid),
5766 oneline.buf);
5767 if (is_empty)
5768 strbuf_addf(&buf, " %s empty",
5769 comment_line_str);
5771 FLEX_ALLOC_STR(entry, string, buf.buf);
5772 oidcpy(&entry->entry.oid, &commit->object.oid);
5773 oidmap_put(&commit2todo, entry);
5775 continue;
5778 /* Create a label */
5779 strbuf_reset(&label);
5780 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5781 (p1 = strchr(p1, '\'')) &&
5782 (p2 = strchr(++p1, '\'')))
5783 strbuf_add(&label, p1, p2 - p1);
5784 else if (skip_prefix(oneline.buf, "Merge pull request ",
5785 &p1) &&
5786 (p1 = strstr(p1, " from ")))
5787 strbuf_addstr(&label, p1 + strlen(" from "));
5788 else
5789 strbuf_addbuf(&label, &oneline);
5791 strbuf_reset(&buf);
5792 strbuf_addf(&buf, "%s -C %s",
5793 cmd_merge, oid_to_hex(&commit->object.oid));
5795 /* label the tips of merged branches */
5796 for (; to_merge; to_merge = to_merge->next) {
5797 oid = &to_merge->item->object.oid;
5798 strbuf_addch(&buf, ' ');
5800 if (!oidset_contains(&interesting, oid)) {
5801 strbuf_addstr(&buf, label_oid(oid, NULL,
5802 &state));
5803 continue;
5806 tips_tail = &commit_list_insert(to_merge->item,
5807 tips_tail)->next;
5809 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5811 strbuf_addf(&buf, " # %s", oneline.buf);
5813 FLEX_ALLOC_STR(entry, string, buf.buf);
5814 oidcpy(&entry->entry.oid, &commit->object.oid);
5815 oidmap_put(&commit2todo, entry);
5817 if (skipped_commit)
5818 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5819 _("use --reapply-cherry-picks to include skipped commits"));
5822 * Second phase:
5823 * - label branch points
5824 * - add HEAD to the branch tips
5826 for (iter = commits; iter; iter = iter->next) {
5827 struct commit_list *parent = iter->item->parents;
5828 for (; parent; parent = parent->next) {
5829 struct object_id *oid = &parent->item->object.oid;
5830 if (!oidset_contains(&interesting, oid))
5831 continue;
5832 if (oidset_insert(&child_seen, oid))
5833 label_oid(oid, "branch-point", &state);
5836 /* Add HEAD as implicit "tip of branch" */
5837 if (!iter->next)
5838 tips_tail = &commit_list_insert(iter->item,
5839 tips_tail)->next;
5843 * Third phase: output the todo list. This is a bit tricky, as we
5844 * want to avoid jumping back and forth between revisions. To
5845 * accomplish that goal, we walk backwards from the branch tips,
5846 * gathering commits not yet shown, reversing the list on the fly,
5847 * then outputting that list (labeling revisions as needed).
5849 strbuf_addf(out, "%s onto\n", cmd_label);
5850 for (iter = tips; iter; iter = iter->next) {
5851 struct commit_list *list = NULL, *iter2;
5853 commit = iter->item;
5854 if (oidset_contains(&shown, &commit->object.oid))
5855 continue;
5856 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5858 if (entry)
5859 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
5860 else
5861 strbuf_addch(out, '\n');
5863 while (oidset_contains(&interesting, &commit->object.oid) &&
5864 !oidset_contains(&shown, &commit->object.oid)) {
5865 commit_list_insert(commit, &list);
5866 if (!commit->parents) {
5867 commit = NULL;
5868 break;
5870 commit = commit->parents->item;
5873 if (!commit)
5874 strbuf_addf(out, "%s %s\n", cmd_reset,
5875 rebase_cousins || root_with_onto ?
5876 "onto" : "[new root]");
5877 else {
5878 const char *to = NULL;
5880 entry = oidmap_get(&state.commit2label,
5881 &commit->object.oid);
5882 if (entry)
5883 to = entry->string;
5884 else if (!rebase_cousins)
5885 to = label_oid(&commit->object.oid, NULL,
5886 &state);
5888 if (!to || !strcmp(to, "onto"))
5889 strbuf_addf(out, "%s onto\n", cmd_reset);
5890 else {
5891 strbuf_reset(&oneline);
5892 pretty_print_commit(pp, commit, &oneline);
5893 strbuf_addf(out, "%s %s # %s\n",
5894 cmd_reset, to, oneline.buf);
5898 for (iter2 = list; iter2; iter2 = iter2->next) {
5899 struct object_id *oid = &iter2->item->object.oid;
5900 entry = oidmap_get(&commit2todo, oid);
5901 /* only show if not already upstream */
5902 if (entry)
5903 strbuf_addf(out, "%s\n", entry->string);
5904 entry = oidmap_get(&state.commit2label, oid);
5905 if (entry)
5906 strbuf_addf(out, "%s %s\n",
5907 cmd_label, entry->string);
5908 oidset_insert(&shown, oid);
5911 free_commit_list(list);
5914 free_commit_list(commits);
5915 free_commit_list(tips);
5917 strbuf_release(&label);
5918 strbuf_release(&oneline);
5919 strbuf_release(&buf);
5921 oidmap_free(&commit2todo, 1);
5922 oidmap_free(&state.commit2label, 1);
5923 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5924 strbuf_release(&state.buf);
5926 return 0;
5929 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5930 const char **argv, unsigned flags)
5932 char *format = NULL;
5933 struct pretty_print_context pp = {0};
5934 struct rev_info revs;
5935 struct commit *commit;
5936 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5937 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5938 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5939 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5940 int skipped_commit = 0;
5941 int ret = 0;
5943 repo_init_revisions(r, &revs, NULL);
5944 revs.verbose_header = 1;
5945 if (!rebase_merges)
5946 revs.max_parents = 1;
5947 revs.cherry_mark = !reapply_cherry_picks;
5948 revs.limited = 1;
5949 revs.reverse = 1;
5950 revs.right_only = 1;
5951 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5952 revs.topo_order = 1;
5954 revs.pretty_given = 1;
5955 git_config_get_string("rebase.instructionFormat", &format);
5956 if (!format || !*format) {
5957 free(format);
5958 format = xstrdup("%s");
5960 get_commit_format(format, &revs);
5961 free(format);
5962 pp.fmt = revs.commit_format;
5963 pp.output_encoding = get_log_output_encoding();
5965 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5966 ret = error(_("make_script: unhandled options"));
5967 goto cleanup;
5970 if (prepare_revision_walk(&revs) < 0) {
5971 ret = error(_("make_script: error preparing revisions"));
5972 goto cleanup;
5975 if (rebase_merges) {
5976 ret = make_script_with_merges(&pp, &revs, out, flags);
5977 goto cleanup;
5980 while ((commit = get_revision(&revs))) {
5981 int is_empty = is_original_commit_empty(commit);
5983 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5984 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5985 warning(_("skipped previously applied commit %s"),
5986 short_commit_name(r, commit));
5987 skipped_commit = 1;
5988 continue;
5990 if (is_empty && !keep_empty)
5991 continue;
5992 strbuf_addf(out, "%s %s ", insn,
5993 oid_to_hex(&commit->object.oid));
5994 pretty_print_commit(&pp, commit, out);
5995 if (is_empty)
5996 strbuf_addf(out, " %s empty", comment_line_str);
5997 strbuf_addch(out, '\n');
5999 if (skipped_commit)
6000 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6001 _("use --reapply-cherry-picks to include skipped commits"));
6002 cleanup:
6003 release_revisions(&revs);
6004 return ret;
6008 * Add commands after pick and (series of) squash/fixup commands
6009 * in the todo list.
6011 static void todo_list_add_exec_commands(struct todo_list *todo_list,
6012 struct string_list *commands)
6014 struct strbuf *buf = &todo_list->buf;
6015 size_t base_offset = buf->len;
6016 int i, insert, nr = 0, alloc = 0;
6017 struct todo_item *items = NULL, *base_items = NULL;
6019 CALLOC_ARRAY(base_items, commands->nr);
6020 for (i = 0; i < commands->nr; i++) {
6021 size_t command_len = strlen(commands->items[i].string);
6023 strbuf_addstr(buf, commands->items[i].string);
6024 strbuf_addch(buf, '\n');
6026 base_items[i].command = TODO_EXEC;
6027 base_items[i].offset_in_buf = base_offset;
6028 base_items[i].arg_offset = base_offset;
6029 base_items[i].arg_len = command_len;
6031 base_offset += command_len + 1;
6035 * Insert <commands> after every pick. Here, fixup/squash chains
6036 * are considered part of the pick, so we insert the commands *after*
6037 * those chains if there are any.
6039 * As we insert the exec commands immediately after rearranging
6040 * any fixups and before the user edits the list, a fixup chain
6041 * can never contain comments (any comments are empty picks that
6042 * have been commented out because the user did not specify
6043 * --keep-empty). So, it is safe to insert an exec command
6044 * without looking at the command following a comment.
6046 insert = 0;
6047 for (i = 0; i < todo_list->nr; i++) {
6048 enum todo_command command = todo_list->items[i].command;
6049 if (insert && !is_fixup(command)) {
6050 ALLOC_GROW(items, nr + commands->nr, alloc);
6051 COPY_ARRAY(items + nr, base_items, commands->nr);
6052 nr += commands->nr;
6054 insert = 0;
6057 ALLOC_GROW(items, nr + 1, alloc);
6058 items[nr++] = todo_list->items[i];
6060 if (command == TODO_PICK || command == TODO_MERGE)
6061 insert = 1;
6064 /* insert or append final <commands> */
6065 if (insert) {
6066 ALLOC_GROW(items, nr + commands->nr, alloc);
6067 COPY_ARRAY(items + nr, base_items, commands->nr);
6068 nr += commands->nr;
6071 free(base_items);
6072 FREE_AND_NULL(todo_list->items);
6073 todo_list->items = items;
6074 todo_list->nr = nr;
6075 todo_list->alloc = alloc;
6078 static void todo_list_to_strbuf(struct repository *r,
6079 struct todo_list *todo_list,
6080 struct strbuf *buf, int num, unsigned flags)
6082 struct todo_item *item;
6083 int i, max = todo_list->nr;
6085 if (num > 0 && num < max)
6086 max = num;
6088 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6089 char cmd;
6091 /* if the item is not a command write it and continue */
6092 if (item->command >= TODO_COMMENT) {
6093 strbuf_addf(buf, "%.*s\n", item->arg_len,
6094 todo_item_get_arg(todo_list, item));
6095 continue;
6098 /* add command to the buffer */
6099 cmd = command_to_char(item->command);
6100 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6101 strbuf_addch(buf, cmd);
6102 else
6103 strbuf_addstr(buf, command_to_string(item->command));
6105 /* add commit id */
6106 if (item->commit) {
6107 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6108 short_commit_name(r, item->commit) :
6109 oid_to_hex(&item->commit->object.oid);
6111 if (item->command == TODO_FIXUP) {
6112 if (item->flags & TODO_EDIT_FIXUP_MSG)
6113 strbuf_addstr(buf, " -c");
6114 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6115 strbuf_addstr(buf, " -C");
6119 if (item->command == TODO_MERGE) {
6120 if (item->flags & TODO_EDIT_MERGE_MSG)
6121 strbuf_addstr(buf, " -c");
6122 else
6123 strbuf_addstr(buf, " -C");
6126 strbuf_addf(buf, " %s", oid);
6129 /* add all the rest */
6130 if (!item->arg_len)
6131 strbuf_addch(buf, '\n');
6132 else
6133 strbuf_addf(buf, " %.*s\n", item->arg_len,
6134 todo_item_get_arg(todo_list, item));
6138 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6139 const char *file, const char *shortrevisions,
6140 const char *shortonto, int num, unsigned flags)
6142 int res;
6143 struct strbuf buf = STRBUF_INIT;
6145 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6146 if (flags & TODO_LIST_APPEND_TODO_HELP)
6147 append_todo_help(count_commands(todo_list),
6148 shortrevisions, shortonto, &buf);
6150 res = write_message(buf.buf, buf.len, file, 0);
6151 strbuf_release(&buf);
6153 return res;
6156 /* skip picking commits whose parents are unchanged */
6157 static int skip_unnecessary_picks(struct repository *r,
6158 struct todo_list *todo_list,
6159 struct object_id *base_oid)
6161 struct object_id *parent_oid;
6162 int i;
6164 for (i = 0; i < todo_list->nr; i++) {
6165 struct todo_item *item = todo_list->items + i;
6167 if (item->command >= TODO_NOOP)
6168 continue;
6169 if (item->command != TODO_PICK)
6170 break;
6171 if (repo_parse_commit(r, item->commit)) {
6172 return error(_("could not parse commit '%s'"),
6173 oid_to_hex(&item->commit->object.oid));
6175 if (!item->commit->parents)
6176 break; /* root commit */
6177 if (item->commit->parents->next)
6178 break; /* merge commit */
6179 parent_oid = &item->commit->parents->item->object.oid;
6180 if (!oideq(parent_oid, base_oid))
6181 break;
6182 oidcpy(base_oid, &item->commit->object.oid);
6184 if (i > 0) {
6185 const char *done_path = rebase_path_done();
6187 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6188 error_errno(_("could not write to '%s'"), done_path);
6189 return -1;
6192 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6193 todo_list->nr -= i;
6194 todo_list->current = 0;
6195 todo_list->done_nr += i;
6197 if (is_fixup(peek_command(todo_list, 0)))
6198 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6201 return 0;
6204 struct todo_add_branch_context {
6205 struct todo_item *items;
6206 size_t items_nr;
6207 size_t items_alloc;
6208 struct strbuf *buf;
6209 struct commit *commit;
6210 struct string_list refs_to_oids;
6213 static int add_decorations_to_list(const struct commit *commit,
6214 struct todo_add_branch_context *ctx)
6216 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6217 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
6218 "HEAD",
6219 RESOLVE_REF_READING,
6220 NULL,
6221 NULL);
6223 while (decoration) {
6224 struct todo_item *item;
6225 const char *path;
6226 size_t base_offset = ctx->buf->len;
6229 * If the branch is the current HEAD, then it will be
6230 * updated by the default rebase behavior.
6232 if (head_ref && !strcmp(head_ref, decoration->name)) {
6233 decoration = decoration->next;
6234 continue;
6237 ALLOC_GROW(ctx->items,
6238 ctx->items_nr + 1,
6239 ctx->items_alloc);
6240 item = &ctx->items[ctx->items_nr];
6241 memset(item, 0, sizeof(*item));
6243 /* If the branch is checked out, then leave a comment instead. */
6244 if ((path = branch_checked_out(decoration->name))) {
6245 item->command = TODO_COMMENT;
6246 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6247 decoration->name, path);
6248 } else {
6249 struct string_list_item *sti;
6250 item->command = TODO_UPDATE_REF;
6251 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6253 sti = string_list_insert(&ctx->refs_to_oids,
6254 decoration->name);
6255 sti->util = init_update_ref_record(decoration->name);
6258 item->offset_in_buf = base_offset;
6259 item->arg_offset = base_offset;
6260 item->arg_len = ctx->buf->len - base_offset;
6261 ctx->items_nr++;
6263 decoration = decoration->next;
6266 return 0;
6270 * For each 'pick' command, find out if the commit has a decoration in
6271 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6273 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6275 int i, res;
6276 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6277 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6278 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6279 struct decoration_filter decoration_filter = {
6280 .include_ref_pattern = &decorate_refs_include,
6281 .exclude_ref_pattern = &decorate_refs_exclude,
6282 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6284 struct todo_add_branch_context ctx = {
6285 .buf = &todo_list->buf,
6286 .refs_to_oids = STRING_LIST_INIT_DUP,
6289 ctx.items_alloc = 2 * todo_list->nr + 1;
6290 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6292 string_list_append(&decorate_refs_include, "refs/heads/");
6293 load_ref_decorations(&decoration_filter, 0);
6295 for (i = 0; i < todo_list->nr; ) {
6296 struct todo_item *item = &todo_list->items[i];
6298 /* insert ith item into new list */
6299 ALLOC_GROW(ctx.items,
6300 ctx.items_nr + 1,
6301 ctx.items_alloc);
6303 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6305 if (item->commit) {
6306 ctx.commit = item->commit;
6307 add_decorations_to_list(item->commit, &ctx);
6311 res = write_update_refs_state(&ctx.refs_to_oids);
6313 string_list_clear(&ctx.refs_to_oids, 1);
6315 if (res) {
6316 /* we failed, so clean up the new list. */
6317 free(ctx.items);
6318 return res;
6321 free(todo_list->items);
6322 todo_list->items = ctx.items;
6323 todo_list->nr = ctx.items_nr;
6324 todo_list->alloc = ctx.items_alloc;
6326 return 0;
6329 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6330 const char *shortrevisions, const char *onto_name,
6331 struct commit *onto, const struct object_id *orig_head,
6332 struct string_list *commands, unsigned autosquash,
6333 unsigned update_refs,
6334 struct todo_list *todo_list)
6336 char shortonto[GIT_MAX_HEXSZ + 1];
6337 const char *todo_file = rebase_path_todo();
6338 struct todo_list new_todo = TODO_LIST_INIT;
6339 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6340 struct object_id oid = onto->object.oid;
6341 int res;
6343 repo_find_unique_abbrev_r(r, shortonto, &oid,
6344 DEFAULT_ABBREV);
6346 if (buf->len == 0) {
6347 struct todo_item *item = append_new_todo(todo_list);
6348 item->command = TODO_NOOP;
6349 item->commit = NULL;
6350 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6353 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6354 return -1;
6356 if (autosquash && todo_list_rearrange_squash(todo_list))
6357 return -1;
6359 if (commands->nr)
6360 todo_list_add_exec_commands(todo_list, commands);
6362 if (count_commands(todo_list) == 0) {
6363 apply_autostash(rebase_path_autostash());
6364 sequencer_remove_state(opts);
6366 return error(_("nothing to do"));
6369 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6370 shortonto, flags);
6371 if (res == -1)
6372 return -1;
6373 else if (res == -2) {
6374 apply_autostash(rebase_path_autostash());
6375 sequencer_remove_state(opts);
6377 return -1;
6378 } else if (res == -3) {
6379 apply_autostash(rebase_path_autostash());
6380 sequencer_remove_state(opts);
6381 todo_list_release(&new_todo);
6383 return error(_("nothing to do"));
6384 } else if (res == -4) {
6385 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6386 todo_list_release(&new_todo);
6388 return -1;
6391 /* Expand the commit IDs */
6392 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6393 strbuf_swap(&new_todo.buf, &buf2);
6394 strbuf_release(&buf2);
6395 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6396 new_todo.total_nr = 0;
6397 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6398 BUG("invalid todo list after expanding IDs:\n%s",
6399 new_todo.buf.buf);
6401 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6402 todo_list_release(&new_todo);
6403 return error(_("could not skip unnecessary pick commands"));
6406 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6407 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6408 todo_list_release(&new_todo);
6409 return error_errno(_("could not write '%s'"), todo_file);
6412 res = -1;
6414 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6415 goto cleanup;
6417 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6418 goto cleanup;
6420 todo_list_write_total_nr(&new_todo);
6421 res = pick_commits(r, &new_todo, opts);
6423 cleanup:
6424 todo_list_release(&new_todo);
6426 return res;
6429 struct subject2item_entry {
6430 struct hashmap_entry entry;
6431 int i;
6432 char subject[FLEX_ARRAY];
6435 static int subject2item_cmp(const void *fndata UNUSED,
6436 const struct hashmap_entry *eptr,
6437 const struct hashmap_entry *entry_or_key,
6438 const void *key)
6440 const struct subject2item_entry *a, *b;
6442 a = container_of(eptr, const struct subject2item_entry, entry);
6443 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6445 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6448 define_commit_slab(commit_todo_item, struct todo_item *);
6450 static int skip_fixupish(const char *subject, const char **p) {
6451 return skip_prefix(subject, "fixup! ", p) ||
6452 skip_prefix(subject, "amend! ", p) ||
6453 skip_prefix(subject, "squash! ", p);
6457 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6458 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6459 * after the former, and change "pick" to "fixup"/"squash".
6461 * Note that if the config has specified a custom instruction format, each log
6462 * message will have to be retrieved from the commit (as the oneline in the
6463 * script cannot be trusted) in order to normalize the autosquash arrangement.
6465 int todo_list_rearrange_squash(struct todo_list *todo_list)
6467 struct hashmap subject2item;
6468 int rearranged = 0, *next, *tail, i, nr = 0;
6469 char **subjects;
6470 struct commit_todo_item commit_todo;
6471 struct todo_item *items = NULL;
6473 init_commit_todo_item(&commit_todo);
6475 * The hashmap maps onelines to the respective todo list index.
6477 * If any items need to be rearranged, the next[i] value will indicate
6478 * which item was moved directly after the i'th.
6480 * In that case, last[i] will indicate the index of the latest item to
6481 * be moved to appear after the i'th.
6483 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6484 ALLOC_ARRAY(next, todo_list->nr);
6485 ALLOC_ARRAY(tail, todo_list->nr);
6486 ALLOC_ARRAY(subjects, todo_list->nr);
6487 for (i = 0; i < todo_list->nr; i++) {
6488 struct strbuf buf = STRBUF_INIT;
6489 struct todo_item *item = todo_list->items + i;
6490 const char *commit_buffer, *subject, *p;
6491 size_t subject_len;
6492 int i2 = -1;
6493 struct subject2item_entry *entry;
6495 next[i] = tail[i] = -1;
6496 if (!item->commit || item->command == TODO_DROP) {
6497 subjects[i] = NULL;
6498 continue;
6501 if (is_fixup(item->command)) {
6502 clear_commit_todo_item(&commit_todo);
6503 return error(_("the script was already rearranged."));
6506 repo_parse_commit(the_repository, item->commit);
6507 commit_buffer = repo_logmsg_reencode(the_repository,
6508 item->commit, NULL,
6509 "UTF-8");
6510 find_commit_subject(commit_buffer, &subject);
6511 format_subject(&buf, subject, " ");
6512 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6513 repo_unuse_commit_buffer(the_repository, item->commit,
6514 commit_buffer);
6515 if (skip_fixupish(subject, &p)) {
6516 struct commit *commit2;
6518 for (;;) {
6519 while (isspace(*p))
6520 p++;
6521 if (!skip_fixupish(p, &p))
6522 break;
6525 entry = hashmap_get_entry_from_hash(&subject2item,
6526 strhash(p), p,
6527 struct subject2item_entry,
6528 entry);
6529 if (entry)
6530 /* found by title */
6531 i2 = entry->i;
6532 else if (!strchr(p, ' ') &&
6533 (commit2 =
6534 lookup_commit_reference_by_name(p)) &&
6535 *commit_todo_item_at(&commit_todo, commit2))
6536 /* found by commit name */
6537 i2 = *commit_todo_item_at(&commit_todo, commit2)
6538 - todo_list->items;
6539 else {
6540 /* copy can be a prefix of the commit subject */
6541 for (i2 = 0; i2 < i; i2++)
6542 if (subjects[i2] &&
6543 starts_with(subjects[i2], p))
6544 break;
6545 if (i2 == i)
6546 i2 = -1;
6549 if (i2 >= 0) {
6550 rearranged = 1;
6551 if (starts_with(subject, "fixup!")) {
6552 todo_list->items[i].command = TODO_FIXUP;
6553 } else if (starts_with(subject, "amend!")) {
6554 todo_list->items[i].command = TODO_FIXUP;
6555 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6556 } else {
6557 todo_list->items[i].command = TODO_SQUASH;
6559 if (tail[i2] < 0) {
6560 next[i] = next[i2];
6561 next[i2] = i;
6562 } else {
6563 next[i] = next[tail[i2]];
6564 next[tail[i2]] = i;
6566 tail[i2] = i;
6567 } else if (!hashmap_get_from_hash(&subject2item,
6568 strhash(subject), subject)) {
6569 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6570 entry->i = i;
6571 hashmap_entry_init(&entry->entry,
6572 strhash(entry->subject));
6573 hashmap_put(&subject2item, &entry->entry);
6576 *commit_todo_item_at(&commit_todo, item->commit) = item;
6579 if (rearranged) {
6580 ALLOC_ARRAY(items, todo_list->nr);
6582 for (i = 0; i < todo_list->nr; i++) {
6583 enum todo_command command = todo_list->items[i].command;
6584 int cur = i;
6587 * Initially, all commands are 'pick's. If it is a
6588 * fixup or a squash now, we have rearranged it.
6590 if (is_fixup(command))
6591 continue;
6593 while (cur >= 0) {
6594 items[nr++] = todo_list->items[cur];
6595 cur = next[cur];
6599 assert(nr == todo_list->nr);
6600 todo_list->alloc = nr;
6601 FREE_AND_NULL(todo_list->items);
6602 todo_list->items = items;
6605 free(next);
6606 free(tail);
6607 for (i = 0; i < todo_list->nr; i++)
6608 free(subjects[i]);
6609 free(subjects);
6610 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6612 clear_commit_todo_item(&commit_todo);
6614 return 0;
6617 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6619 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6620 struct object_id cherry_pick_head, rebase_head;
6622 if (file_exists(git_path_seq_dir()))
6623 *whence = FROM_CHERRY_PICK_MULTI;
6624 if (file_exists(rebase_path()) &&
6625 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6626 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6627 oideq(&rebase_head, &cherry_pick_head))
6628 *whence = FROM_REBASE_PICK;
6629 else
6630 *whence = FROM_CHERRY_PICK_SINGLE;
6632 return 1;
6635 return 0;
6638 int sequencer_get_update_refs_state(const char *wt_dir,
6639 struct string_list *refs)
6641 int result = 0;
6642 FILE *fp = NULL;
6643 struct strbuf ref = STRBUF_INIT;
6644 struct strbuf hash = STRBUF_INIT;
6645 struct update_ref_record *rec = NULL;
6647 char *path = rebase_path_update_refs(wt_dir);
6649 fp = fopen(path, "r");
6650 if (!fp)
6651 goto cleanup;
6653 while (strbuf_getline(&ref, fp) != EOF) {
6654 struct string_list_item *item;
6656 CALLOC_ARRAY(rec, 1);
6658 if (strbuf_getline(&hash, fp) == EOF ||
6659 get_oid_hex(hash.buf, &rec->before)) {
6660 warning(_("update-refs file at '%s' is invalid"),
6661 path);
6662 result = -1;
6663 goto cleanup;
6666 if (strbuf_getline(&hash, fp) == EOF ||
6667 get_oid_hex(hash.buf, &rec->after)) {
6668 warning(_("update-refs file at '%s' is invalid"),
6669 path);
6670 result = -1;
6671 goto cleanup;
6674 item = string_list_insert(refs, ref.buf);
6675 item->util = rec;
6676 rec = NULL;
6679 cleanup:
6680 if (fp)
6681 fclose(fp);
6682 free(path);
6683 free(rec);
6684 strbuf_release(&ref);
6685 strbuf_release(&hash);
6686 return result;