5 #include "object-store.h"
10 #include "run-command.h"
14 #include "cache-tree.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
25 #include "wt-status.h"
27 #include "notes-utils.h"
29 #include "unpack-trees.h"
33 #include "commit-slab.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
40 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
42 static const char sign_off_header
[] = "Signed-off-by: ";
43 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
45 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
47 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
49 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
50 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
51 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
52 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
54 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
56 * The file containing rebase commands, comments, and empty lines.
57 * This file is created by "git rebase -i" then edited by the user. As
58 * the lines are processed, they are removed from the front of this
59 * file and written to the tail of 'done'.
61 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
62 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
64 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
67 * The rebase command lines that have already been processed. A line
68 * is moved here when it is first handled, before any associated user
71 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
73 * The file to keep track of how many commands were already processed (e.g.
76 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
78 * The file to keep track of how many commands are to be processed in total
79 * (e.g. for the prompt).
81 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
83 * The commit message that is planned to be used for any changes that
84 * need to be committed following a user interaction.
86 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
88 * The file into which is accumulated the suggested commit message for
89 * squash/fixup commands. When the first of a series of squash/fixups
90 * is seen, the file is created and the commit message from the
91 * previous commit and from the first squash/fixup commit are written
92 * to it. The commit message for each subsequent squash/fixup commit
93 * is appended to the file as it is processed.
95 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
97 * If the current series of squash/fixups has not yet included a squash
98 * command, then this file exists and holds the commit message of the
99 * original "pick" commit. (If the series ends without a "squash"
100 * command, then this can be used as the commit message of the combined
101 * commit without opening the editor.)
103 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
105 * This file contains the list fixup/squash commands that have been
106 * accumulated into message-fixup or message-squash so far.
108 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
110 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
111 * GIT_AUTHOR_DATE that will be used for the commit that is currently
114 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
116 * When an "edit" rebase command is being processed, the SHA1 of the
117 * commit to be edited is recorded in this file. When "git rebase
118 * --continue" is executed, if there are any staged changes then they
119 * will be amended to the HEAD commit, but only provided the HEAD
120 * commit is still the commit to be edited. When any other rebase
121 * command is processed, this file is deleted.
123 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
125 * When we stop at a given patch via the "edit" command, this file contains
126 * the commit object name of the corresponding patch.
128 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
130 * For the post-rewrite hook, we make a list of rewritten commits and
131 * their new sha1s. The rewritten-pending list keeps the sha1s of
132 * commits that have been processed, but not committed yet,
133 * e.g. because they are waiting for a 'squash' command.
135 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
136 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
137 "rebase-merge/rewritten-pending")
140 * The path of the file containing the OID of the "squash onto" commit, i.e.
141 * the dummy commit used for `reset [new root]`.
143 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
146 * The path of the file listing refs that need to be deleted after the rebase
147 * finishes. This is used by the `label` command to record the need for cleanup.
149 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
152 * The update-refs file stores a list of refs that will be updated at the end
153 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
154 * update the OIDs for the refs in this file, but the refs are not updated
155 * until the end of the rebase sequence.
157 * rebase_path_update_refs() returns the path to this file for a given
158 * worktree directory. For the current worktree, pass the_repository->gitdir.
160 static char *rebase_path_update_refs(const char *wt_git_dir
)
162 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
166 * The following files are written by git-rebase just after parsing the
169 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
170 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
171 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
172 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
173 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
174 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
175 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
176 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
177 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
178 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
179 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
180 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
181 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
182 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
183 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
184 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
185 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
188 * A 'struct update_refs_record' represents a value in the update-refs
189 * list. We use a string_list to map refs to these (before, after) pairs.
191 struct update_ref_record
{
192 struct object_id before
;
193 struct object_id after
;
196 static struct update_ref_record
*init_update_ref_record(const char *ref
)
198 struct update_ref_record
*rec
;
200 CALLOC_ARRAY(rec
, 1);
202 oidcpy(&rec
->before
, null_oid());
203 oidcpy(&rec
->after
, null_oid());
205 /* This may fail, but that's fine, we will keep the null OID. */
206 read_ref(ref
, &rec
->before
);
211 static int git_sequencer_config(const char *k
, const char *v
, void *cb
)
213 struct replay_opts
*opts
= cb
;
216 if (!strcmp(k
, "commit.cleanup")) {
219 status
= git_config_string(&s
, k
, v
);
223 if (!strcmp(s
, "verbatim")) {
224 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
225 opts
->explicit_cleanup
= 1;
226 } else if (!strcmp(s
, "whitespace")) {
227 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
228 opts
->explicit_cleanup
= 1;
229 } else if (!strcmp(s
, "strip")) {
230 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
231 opts
->explicit_cleanup
= 1;
232 } else if (!strcmp(s
, "scissors")) {
233 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
234 opts
->explicit_cleanup
= 1;
236 warning(_("invalid commit message cleanup mode '%s'"),
244 if (!strcmp(k
, "commit.gpgsign")) {
245 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
249 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
250 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
253 * pull.twohead is allowed to be multi-valued; we only
254 * care about the first value.
256 char *tmp
= strchr(opts
->default_strategy
, ' ');
263 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
264 opts
->commit_use_reference
= git_config_bool(k
, v
);
266 status
= git_gpg_config(k
, v
, NULL
);
270 return git_diff_basic_config(k
, v
, NULL
);
273 void sequencer_init_config(struct replay_opts
*opts
)
275 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
276 git_config(git_sequencer_config
, opts
);
279 static inline int is_rebase_i(const struct replay_opts
*opts
)
281 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
284 static const char *get_dir(const struct replay_opts
*opts
)
286 if (is_rebase_i(opts
))
287 return rebase_path();
288 return git_path_seq_dir();
291 static const char *get_todo_path(const struct replay_opts
*opts
)
293 if (is_rebase_i(opts
))
294 return rebase_path_todo();
295 return git_path_todo_file();
299 * Returns 0 for non-conforming footer
300 * Returns 1 for conforming footer
301 * Returns 2 when sob exists within conforming footer
302 * Returns 3 when sob exists within conforming footer as last entry
304 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
305 size_t ignore_footer
)
307 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
308 struct trailer_info info
;
310 int found_sob
= 0, found_sob_last
= 0;
316 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
317 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
320 trailer_info_get(&info
, sb
->buf
, &opts
);
323 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
325 if (info
.trailer_start
== info
.trailer_end
)
328 for (i
= 0; i
< info
.trailer_nr
; i
++)
329 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
331 if (i
== info
.trailer_nr
- 1)
335 trailer_info_release(&info
);
344 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
346 static struct strbuf buf
= STRBUF_INIT
;
350 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
354 void replay_opts_release(struct replay_opts
*opts
)
356 free(opts
->gpg_sign
);
357 free(opts
->reflog_action
);
358 free(opts
->default_strategy
);
359 free(opts
->strategy
);
360 for (size_t i
= 0; i
< opts
->xopts_nr
; i
++)
361 free(opts
->xopts
[i
]);
363 strbuf_release(&opts
->current_fixups
);
365 release_revisions(opts
->revs
);
369 int sequencer_remove_state(struct replay_opts
*opts
)
371 struct strbuf buf
= STRBUF_INIT
;
374 if (is_rebase_i(opts
) &&
375 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
378 char *eol
= strchr(p
, '\n');
381 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
382 warning(_("could not delete '%s'"), p
);
392 strbuf_addstr(&buf
, get_dir(opts
));
393 if (remove_dir_recursively(&buf
, 0))
394 ret
= error(_("could not remove '%s'"), buf
.buf
);
395 strbuf_release(&buf
);
400 static const char *action_name(const struct replay_opts
*opts
)
402 switch (opts
->action
) {
406 return N_("cherry-pick");
407 case REPLAY_INTERACTIVE_REBASE
:
410 die(_("unknown action: %d"), opts
->action
);
413 struct commit_message
{
420 static const char *short_commit_name(struct commit
*commit
)
422 return repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
,
426 static int get_message(struct commit
*commit
, struct commit_message
*out
)
428 const char *abbrev
, *subject
;
431 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
432 get_commit_output_encoding());
433 abbrev
= short_commit_name(commit
);
435 subject_len
= find_commit_subject(out
->message
, &subject
);
437 out
->subject
= xmemdupz(subject
, subject_len
);
438 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
439 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
444 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
446 free(msg
->parent_label
);
449 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
452 static void print_advice(struct repository
*r
, int show_hint
,
453 struct replay_opts
*opts
)
455 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
460 * A conflict has occurred but the porcelain
461 * (typically rebase --interactive) wants to take care
462 * of the commit itself so remove CHERRY_PICK_HEAD
464 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
471 advise(_("after resolving the conflicts, mark the corrected paths\n"
472 "with 'git add <paths>' or 'git rm <paths>'"));
473 else if (opts
->action
== REPLAY_PICK
)
474 advise(_("After resolving the conflicts, mark them with\n"
475 "\"git add/rm <pathspec>\", then run\n"
476 "\"git cherry-pick --continue\".\n"
477 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
478 "To abort and get back to the state before \"git cherry-pick\",\n"
479 "run \"git cherry-pick --abort\"."));
480 else if (opts
->action
== REPLAY_REVERT
)
481 advise(_("After resolving the conflicts, mark them with\n"
482 "\"git add/rm <pathspec>\", then run\n"
483 "\"git revert --continue\".\n"
484 "You can instead skip this commit with \"git revert --skip\".\n"
485 "To abort and get back to the state before \"git revert\",\n"
486 "run \"git revert --abort\"."));
488 BUG("unexpected pick action in print_advice()");
492 static int write_message(const void *buf
, size_t len
, const char *filename
,
495 struct lock_file msg_file
= LOCK_INIT
;
497 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
499 return error_errno(_("could not lock '%s'"), filename
);
500 if (write_in_full(msg_fd
, buf
, len
) < 0) {
501 error_errno(_("could not write to '%s'"), filename
);
502 rollback_lock_file(&msg_file
);
505 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
506 error_errno(_("could not write eol to '%s'"), filename
);
507 rollback_lock_file(&msg_file
);
510 if (commit_lock_file(&msg_file
) < 0)
511 return error(_("failed to finalize '%s'"), filename
);
516 int read_oneliner(struct strbuf
*buf
,
517 const char *path
, unsigned flags
)
519 int orig_len
= buf
->len
;
521 if (strbuf_read_file(buf
, path
, 0) < 0) {
522 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
523 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
524 warning_errno(_("could not read '%s'"), path
);
528 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
529 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
531 buf
->buf
[buf
->len
] = '\0';
534 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
540 static struct tree
*empty_tree(struct repository
*r
)
542 return lookup_tree(r
, the_hash_algo
->empty_tree
);
545 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
547 if (repo_read_index_unmerged(repo
))
548 return error_resolve_conflict(action_name(opts
));
550 error(_("your local changes would be overwritten by %s."),
551 _(action_name(opts
)));
553 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
554 advise(_("commit your changes or stash them to proceed."));
558 static void update_abort_safety_file(void)
560 struct object_id head
;
562 /* Do nothing on a single-pick */
563 if (!file_exists(git_path_seq_dir()))
566 if (!repo_get_oid(the_repository
, "HEAD", &head
))
567 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
569 write_file(git_path_abort_safety_file(), "%s", "");
572 static int fast_forward_to(struct repository
*r
,
573 const struct object_id
*to
,
574 const struct object_id
*from
,
576 struct replay_opts
*opts
)
578 struct ref_transaction
*transaction
;
579 struct strbuf sb
= STRBUF_INIT
;
580 struct strbuf err
= STRBUF_INIT
;
583 if (checkout_fast_forward(r
, from
, to
, 1))
584 return -1; /* the callee should have complained already */
586 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
588 transaction
= ref_transaction_begin(&err
);
590 ref_transaction_update(transaction
, "HEAD",
591 to
, unborn
&& !is_rebase_i(opts
) ?
594 ref_transaction_commit(transaction
, &err
)) {
595 ref_transaction_free(transaction
);
596 error("%s", err
.buf
);
598 strbuf_release(&err
);
603 strbuf_release(&err
);
604 ref_transaction_free(transaction
);
605 update_abort_safety_file();
609 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
612 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
613 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
614 COMMIT_MSG_CLEANUP_SPACE
;
615 else if (!strcmp(cleanup_arg
, "verbatim"))
616 return COMMIT_MSG_CLEANUP_NONE
;
617 else if (!strcmp(cleanup_arg
, "whitespace"))
618 return COMMIT_MSG_CLEANUP_SPACE
;
619 else if (!strcmp(cleanup_arg
, "strip"))
620 return COMMIT_MSG_CLEANUP_ALL
;
621 else if (!strcmp(cleanup_arg
, "scissors"))
622 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
623 COMMIT_MSG_CLEANUP_SPACE
;
625 die(_("Invalid cleanup mode %s"), cleanup_arg
);
629 * NB using int rather than enum cleanup_mode to stop clang's
630 * -Wtautological-constant-out-of-range-compare complaining that the comparison
633 static const char *describe_cleanup_mode(int cleanup_mode
)
635 static const char *modes
[] = { "whitespace",
640 if (cleanup_mode
< ARRAY_SIZE(modes
))
641 return modes
[cleanup_mode
];
643 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
646 void append_conflicts_hint(struct index_state
*istate
,
647 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
651 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
652 strbuf_addch(msgbuf
, '\n');
653 wt_status_append_cut_line(msgbuf
);
654 strbuf_addch(msgbuf
, comment_line_char
);
657 strbuf_addch(msgbuf
, '\n');
658 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
659 for (i
= 0; i
< istate
->cache_nr
;) {
660 const struct cache_entry
*ce
= istate
->cache
[i
++];
662 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
663 while (i
< istate
->cache_nr
&&
664 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
670 static int do_recursive_merge(struct repository
*r
,
671 struct commit
*base
, struct commit
*next
,
672 const char *base_label
, const char *next_label
,
673 struct object_id
*head
, struct strbuf
*msgbuf
,
674 struct replay_opts
*opts
)
676 struct merge_options o
;
677 struct merge_result result
;
678 struct tree
*next_tree
, *base_tree
, *head_tree
;
679 int clean
, show_output
;
681 struct lock_file index_lock
= LOCK_INIT
;
683 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
688 init_merge_options(&o
, r
);
689 o
.ancestor
= base
? base_label
: "(empty tree)";
691 o
.branch2
= next
? next_label
: "(empty tree)";
692 if (is_rebase_i(opts
))
694 o
.show_rename_progress
= 1;
696 head_tree
= parse_tree_indirect(head
);
697 next_tree
= next
? repo_get_commit_tree(the_repository
, next
) : empty_tree(r
);
698 base_tree
= base
? repo_get_commit_tree(the_repository
, base
) : empty_tree(r
);
700 for (i
= 0; i
< opts
->xopts_nr
; i
++)
701 parse_merge_opt(&o
, opts
->xopts
[i
]);
703 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
704 memset(&result
, 0, sizeof(result
));
705 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
707 show_output
= !is_rebase_i(opts
) || !result
.clean
;
709 * TODO: merge_switch_to_result will update index/working tree;
710 * we only really want to do that if !result.clean || this is
711 * the final patch to be picked. But determining this is the
712 * final patch would take some work, and "head_tree" would need
713 * to be replace with the tree the index matched before we
714 * started doing any picks.
716 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
717 clean
= result
.clean
;
719 ensure_full_index(r
->index
);
720 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
721 if (is_rebase_i(opts
) && clean
<= 0)
722 fputs(o
.obuf
.buf
, stdout
);
723 strbuf_release(&o
.obuf
);
726 rollback_lock_file(&index_lock
);
730 if (write_locked_index(r
->index
, &index_lock
,
731 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
733 * TRANSLATORS: %s will be "revert", "cherry-pick" or
736 return error(_("%s: Unable to write new index file"),
737 _(action_name(opts
)));
740 append_conflicts_hint(r
->index
, msgbuf
,
741 opts
->default_msg_cleanup
);
746 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
748 if (!cache_tree_fully_valid(istate
->cache_tree
))
749 if (cache_tree_update(istate
, 0)) {
750 error(_("unable to update cache tree"));
754 return &istate
->cache_tree
->oid
;
757 static int is_index_unchanged(struct repository
*r
)
759 struct object_id head_oid
, *cache_tree_oid
;
760 struct commit
*head_commit
;
761 struct index_state
*istate
= r
->index
;
763 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
764 return error(_("could not resolve HEAD commit"));
766 head_commit
= lookup_commit(r
, &head_oid
);
769 * If head_commit is NULL, check_commit, called from
770 * lookup_commit, would have indicated that head_commit is not
771 * a commit object already. repo_parse_commit() will return failure
772 * without further complaints in such a case. Otherwise, if
773 * the commit is invalid, repo_parse_commit() will complain. So
774 * there is nothing for us to say here. Just return failure.
776 if (repo_parse_commit(the_repository
, head_commit
))
779 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
782 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
785 static int write_author_script(const char *message
)
787 struct strbuf buf
= STRBUF_INIT
;
792 if (!*message
|| starts_with(message
, "\n")) {
794 /* Missing 'author' line? */
795 unlink(rebase_path_author_script());
797 } else if (skip_prefix(message
, "author ", &message
))
799 else if ((eol
= strchr(message
, '\n')))
804 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
805 while (*message
&& *message
!= '\n' && *message
!= '\r')
806 if (skip_prefix(message
, " <", &message
))
808 else if (*message
!= '\'')
809 strbuf_addch(&buf
, *(message
++));
811 strbuf_addf(&buf
, "'\\%c'", *(message
++));
812 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
813 while (*message
&& *message
!= '\n' && *message
!= '\r')
814 if (skip_prefix(message
, "> ", &message
))
816 else if (*message
!= '\'')
817 strbuf_addch(&buf
, *(message
++));
819 strbuf_addf(&buf
, "'\\%c'", *(message
++));
820 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
821 while (*message
&& *message
!= '\n' && *message
!= '\r')
822 if (*message
!= '\'')
823 strbuf_addch(&buf
, *(message
++));
825 strbuf_addf(&buf
, "'\\%c'", *(message
++));
826 strbuf_addch(&buf
, '\'');
827 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
828 strbuf_release(&buf
);
833 * Take a series of KEY='VALUE' lines where VALUE part is
834 * sq-quoted, and append <KEY, VALUE> at the end of the string list
836 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
839 struct string_list_item
*item
;
841 char *cp
= strchr(buf
, '=');
843 np
= strchrnul(buf
, '\n');
844 return error(_("no key present in '%.*s'"),
845 (int) (np
- buf
), buf
);
847 np
= strchrnul(cp
, '\n');
849 item
= string_list_append(list
, buf
);
851 buf
= np
+ (*np
== '\n');
855 return error(_("unable to dequote value of '%s'"),
857 item
->util
= xstrdup(cp
);
863 * Reads and parses the state directory's "author-script" file, and sets name,
864 * email and date accordingly.
865 * Returns 0 on success, -1 if the file could not be parsed.
867 * The author script is of the format:
869 * GIT_AUTHOR_NAME='$author_name'
870 * GIT_AUTHOR_EMAIL='$author_email'
871 * GIT_AUTHOR_DATE='$author_date'
873 * where $author_name, $author_email and $author_date are quoted. We are strict
874 * with our parsing, as the file was meant to be eval'd in the now-removed
875 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
876 * from what this function expects, it is better to bail out than to do
877 * something that the user does not expect.
879 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
882 struct strbuf buf
= STRBUF_INIT
;
883 struct string_list kv
= STRING_LIST_INIT_DUP
;
884 int retval
= -1; /* assume failure */
885 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
887 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
888 strbuf_release(&buf
);
889 if (errno
== ENOENT
&& allow_missing
)
892 return error_errno(_("could not open '%s' for reading"),
896 if (parse_key_value_squoted(buf
.buf
, &kv
))
899 for (i
= 0; i
< kv
.nr
; i
++) {
900 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
902 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
905 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
907 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
910 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
912 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
916 err
= error(_("unknown variable '%s'"),
921 error(_("missing 'GIT_AUTHOR_NAME'"));
923 error(_("missing 'GIT_AUTHOR_EMAIL'"));
925 error(_("missing 'GIT_AUTHOR_DATE'"));
926 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
928 *name
= kv
.items
[name_i
].util
;
929 *email
= kv
.items
[email_i
].util
;
930 *date
= kv
.items
[date_i
].util
;
933 string_list_clear(&kv
, !!retval
);
934 strbuf_release(&buf
);
939 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
940 * file with shell quoting into struct strvec. Returns -1 on
941 * error, 0 otherwise.
943 static int read_env_script(struct strvec
*env
)
945 char *name
, *email
, *date
;
947 if (read_author_script(rebase_path_author_script(),
948 &name
, &email
, &date
, 0))
951 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
952 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
953 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
961 static char *get_author(const char *message
)
966 a
= find_commit_header(message
, "author", &len
);
968 return xmemdupz(a
, len
);
973 static const char *author_date_from_env(const struct strvec
*env
)
978 for (i
= 0; i
< env
->nr
; i
++)
979 if (skip_prefix(env
->v
[i
],
980 "GIT_AUTHOR_DATE=", &date
))
983 * If GIT_AUTHOR_DATE is missing we should have already errored out when
986 BUG("GIT_AUTHOR_DATE missing from author script");
989 static const char staged_changes_advice
[] =
990 N_("you have staged changes in your working tree\n"
991 "If these changes are meant to be squashed into the previous commit, run:\n"
993 " git commit --amend %s\n"
995 "If they are meant to go into a new commit, run:\n"
999 "In both cases, once you're done, continue with:\n"
1001 " git rebase --continue\n");
1003 #define ALLOW_EMPTY (1<<0)
1004 #define EDIT_MSG (1<<1)
1005 #define AMEND_MSG (1<<2)
1006 #define CLEANUP_MSG (1<<3)
1007 #define VERIFY_MSG (1<<4)
1008 #define CREATE_ROOT_COMMIT (1<<5)
1009 #define VERBATIM_MSG (1<<6)
1011 static int run_command_silent_on_success(struct child_process
*cmd
)
1013 struct strbuf buf
= STRBUF_INIT
;
1016 cmd
->stdout_to_stderr
= 1;
1017 rc
= pipe_command(cmd
,
1023 fputs(buf
.buf
, stderr
);
1024 strbuf_release(&buf
);
1029 * If we are cherry-pick, and if the merge did not result in
1030 * hand-editing, we will hit this commit and inherit the original
1031 * author date and name.
1033 * If we are revert, or if our cherry-pick results in a hand merge,
1034 * we had better say that the current user is responsible for that.
1036 * An exception is when run_git_commit() is called during an
1037 * interactive rebase: in that case, we will want to retain the
1040 static int run_git_commit(const char *defmsg
,
1041 struct replay_opts
*opts
,
1044 struct child_process cmd
= CHILD_PROCESS_INIT
;
1046 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1047 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1051 if (is_rebase_i(opts
) &&
1052 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1053 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1054 read_env_script(&cmd
.env
)) {
1055 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1057 return error(_(staged_changes_advice
),
1061 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1063 if (opts
->committer_date_is_author_date
)
1064 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1067 author_date_from_env(&cmd
.env
));
1068 if (opts
->ignore_date
)
1069 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1071 strvec_push(&cmd
.args
, "commit");
1073 if (!(flags
& VERIFY_MSG
))
1074 strvec_push(&cmd
.args
, "-n");
1075 if ((flags
& AMEND_MSG
))
1076 strvec_push(&cmd
.args
, "--amend");
1078 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1080 strvec_push(&cmd
.args
, "--no-gpg-sign");
1082 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1083 else if (!(flags
& EDIT_MSG
))
1084 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1085 if ((flags
& CLEANUP_MSG
))
1086 strvec_push(&cmd
.args
, "--cleanup=strip");
1087 if ((flags
& VERBATIM_MSG
))
1088 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1089 if ((flags
& EDIT_MSG
))
1090 strvec_push(&cmd
.args
, "-e");
1091 else if (!(flags
& CLEANUP_MSG
) &&
1092 !opts
->signoff
&& !opts
->record_origin
&&
1093 !opts
->explicit_cleanup
)
1094 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1096 if ((flags
& ALLOW_EMPTY
))
1097 strvec_push(&cmd
.args
, "--allow-empty");
1099 if (!(flags
& EDIT_MSG
))
1100 strvec_push(&cmd
.args
, "--allow-empty-message");
1102 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1103 return run_command_silent_on_success(&cmd
);
1105 return run_command(&cmd
);
1108 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1113 /* Check if the rest is just whitespace and Signed-off-by's. */
1114 for (i
= start
; i
< sb
->len
; i
++) {
1115 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1121 if (strlen(sign_off_header
) <= eol
- i
&&
1122 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1127 if (!isspace(sb
->buf
[i
++]))
1134 void cleanup_message(struct strbuf
*msgbuf
,
1135 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1137 if (verbose
|| /* Truncate the message just before the diff, if any. */
1138 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1139 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1140 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1141 strbuf_stripspace(msgbuf
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
1145 * Find out if the message in the strbuf contains only whitespace and
1146 * Signed-off-by lines.
1148 int message_is_empty(const struct strbuf
*sb
,
1149 enum commit_msg_cleanup_mode cleanup_mode
)
1151 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1153 return rest_is_empty(sb
, 0);
1157 * See if the user edited the message in the editor or left what
1158 * was in the template intact
1160 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1161 enum commit_msg_cleanup_mode cleanup_mode
)
1163 struct strbuf tmpl
= STRBUF_INIT
;
1166 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1169 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1172 strbuf_stripspace(&tmpl
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
1173 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1175 strbuf_release(&tmpl
);
1176 return rest_is_empty(sb
, start
- sb
->buf
);
1179 int update_head_with_reflog(const struct commit
*old_head
,
1180 const struct object_id
*new_head
,
1181 const char *action
, const struct strbuf
*msg
,
1184 struct ref_transaction
*transaction
;
1185 struct strbuf sb
= STRBUF_INIT
;
1190 strbuf_addstr(&sb
, action
);
1191 strbuf_addstr(&sb
, ": ");
1194 nl
= strchr(msg
->buf
, '\n');
1196 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1198 strbuf_addbuf(&sb
, msg
);
1199 strbuf_addch(&sb
, '\n');
1202 transaction
= ref_transaction_begin(err
);
1204 ref_transaction_update(transaction
, "HEAD", new_head
,
1205 old_head
? &old_head
->object
.oid
: null_oid(),
1207 ref_transaction_commit(transaction
, err
)) {
1210 ref_transaction_free(transaction
);
1211 strbuf_release(&sb
);
1216 static int run_rewrite_hook(const struct object_id
*oldoid
,
1217 const struct object_id
*newoid
)
1219 struct child_process proc
= CHILD_PROCESS_INIT
;
1221 struct strbuf sb
= STRBUF_INIT
;
1222 const char *hook_path
= find_hook("post-rewrite");
1227 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1229 proc
.stdout_to_stderr
= 1;
1230 proc
.trace2_hook_name
= "post-rewrite";
1232 code
= start_command(&proc
);
1235 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1236 sigchain_push(SIGPIPE
, SIG_IGN
);
1237 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1239 strbuf_release(&sb
);
1240 sigchain_pop(SIGPIPE
);
1241 return finish_command(&proc
);
1244 void commit_post_rewrite(struct repository
*r
,
1245 const struct commit
*old_head
,
1246 const struct object_id
*new_head
)
1248 struct notes_rewrite_cfg
*cfg
;
1250 cfg
= init_copy_notes_for_rewrite("amend");
1252 /* we are amending, so old_head is not NULL */
1253 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1254 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1256 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1259 static int run_prepare_commit_msg_hook(struct repository
*r
,
1264 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1266 name
= git_path_commit_editmsg();
1267 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1276 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1278 ret
= error(_("'prepare-commit-msg' hook failed"));
1283 static const char implicit_ident_advice_noconfig
[] =
1284 N_("Your name and email address were configured automatically based\n"
1285 "on your username and hostname. Please check that they are accurate.\n"
1286 "You can suppress this message by setting them explicitly. Run the\n"
1287 "following command and follow the instructions in your editor to edit\n"
1288 "your configuration file:\n"
1290 " git config --global --edit\n"
1292 "After doing this, you may fix the identity used for this commit with:\n"
1294 " git commit --amend --reset-author\n");
1296 static const char implicit_ident_advice_config
[] =
1297 N_("Your name and email address were configured automatically based\n"
1298 "on your username and hostname. Please check that they are accurate.\n"
1299 "You can suppress this message by setting them explicitly:\n"
1301 " git config --global user.name \"Your Name\"\n"
1302 " git config --global user.email you@example.com\n"
1304 "After doing this, you may fix the identity used for this commit with:\n"
1306 " git commit --amend --reset-author\n");
1308 static const char *implicit_ident_advice(void)
1310 char *user_config
= interpolate_path("~/.gitconfig", 0);
1311 char *xdg_config
= xdg_config_home("config");
1312 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1318 return _(implicit_ident_advice_config
);
1320 return _(implicit_ident_advice_noconfig
);
1324 void print_commit_summary(struct repository
*r
,
1326 const struct object_id
*oid
,
1329 struct rev_info rev
;
1330 struct commit
*commit
;
1331 struct strbuf format
= STRBUF_INIT
;
1333 struct pretty_print_context pctx
= {0};
1334 struct strbuf author_ident
= STRBUF_INIT
;
1335 struct strbuf committer_ident
= STRBUF_INIT
;
1336 struct ref_store
*refs
;
1338 commit
= lookup_commit(r
, oid
);
1340 die(_("couldn't look up newly created commit"));
1341 if (repo_parse_commit(the_repository
, commit
))
1342 die(_("could not parse newly created commit"));
1344 strbuf_addstr(&format
, "format:%h] %s");
1346 repo_format_commit_message(the_repository
, commit
, "%an <%ae>",
1347 &author_ident
, &pctx
);
1348 repo_format_commit_message(the_repository
, commit
, "%cn <%ce>",
1349 &committer_ident
, &pctx
);
1350 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1351 strbuf_addstr(&format
, "\n Author: ");
1352 strbuf_addbuf_percentquote(&format
, &author_ident
);
1354 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1355 struct strbuf date
= STRBUF_INIT
;
1357 repo_format_commit_message(the_repository
, commit
, "%ad",
1359 strbuf_addstr(&format
, "\n Date: ");
1360 strbuf_addbuf_percentquote(&format
, &date
);
1361 strbuf_release(&date
);
1363 if (!committer_ident_sufficiently_given()) {
1364 strbuf_addstr(&format
, "\n Committer: ");
1365 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1366 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1367 strbuf_addch(&format
, '\n');
1368 strbuf_addstr(&format
, implicit_ident_advice());
1371 strbuf_release(&author_ident
);
1372 strbuf_release(&committer_ident
);
1374 repo_init_revisions(r
, &rev
, prefix
);
1375 setup_revisions(0, NULL
, &rev
, NULL
);
1378 rev
.diffopt
.output_format
=
1379 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1381 rev
.verbose_header
= 1;
1382 rev
.show_root_diff
= 1;
1383 get_commit_format(format
.buf
, &rev
);
1384 rev
.always_show_header
= 0;
1385 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1386 diff_setup_done(&rev
.diffopt
);
1388 refs
= get_main_ref_store(the_repository
);
1389 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1391 die(_("unable to resolve HEAD after creating commit"));
1392 if (!strcmp(head
, "HEAD"))
1393 head
= _("detached HEAD");
1395 skip_prefix(head
, "refs/heads/", &head
);
1396 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1397 _(" (root-commit)") : "");
1399 if (!log_tree_commit(&rev
, commit
)) {
1400 rev
.always_show_header
= 1;
1401 rev
.use_terminator
= 1;
1402 log_tree_commit(&rev
, commit
);
1405 release_revisions(&rev
);
1406 strbuf_release(&format
);
1409 static int parse_head(struct repository
*r
, struct commit
**head
)
1411 struct commit
*current_head
;
1412 struct object_id oid
;
1414 if (repo_get_oid(the_repository
, "HEAD", &oid
)) {
1415 current_head
= NULL
;
1417 current_head
= lookup_commit_reference(r
, &oid
);
1419 return error(_("could not parse HEAD"));
1420 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1421 warning(_("HEAD %s is not a commit!"),
1424 if (repo_parse_commit(the_repository
, current_head
))
1425 return error(_("could not parse HEAD commit"));
1427 *head
= current_head
;
1433 * Try to commit without forking 'git commit'. In some cases we need
1434 * to run 'git commit' to display an error message
1437 * -1 - error unable to commit
1439 * 1 - run 'git commit'
1441 static int try_to_commit(struct repository
*r
,
1442 struct strbuf
*msg
, const char *author
,
1443 struct replay_opts
*opts
, unsigned int flags
,
1444 struct object_id
*oid
)
1446 struct object_id tree
;
1447 struct commit
*current_head
= NULL
;
1448 struct commit_list
*parents
= NULL
;
1449 struct commit_extra_header
*extra
= NULL
;
1450 struct strbuf err
= STRBUF_INIT
;
1451 struct strbuf commit_msg
= STRBUF_INIT
;
1452 char *amend_author
= NULL
;
1453 const char *committer
= NULL
;
1454 const char *hook_commit
= NULL
;
1455 enum commit_msg_cleanup_mode cleanup
;
1458 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1459 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1461 if (parse_head(r
, ¤t_head
))
1464 if (flags
& AMEND_MSG
) {
1465 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1466 const char *out_enc
= get_commit_output_encoding();
1467 const char *message
= repo_logmsg_reencode(the_repository
,
1472 const char *orig_message
= NULL
;
1474 find_commit_subject(message
, &orig_message
);
1476 strbuf_addstr(msg
, orig_message
);
1477 hook_commit
= "HEAD";
1479 author
= amend_author
= get_author(message
);
1480 repo_unuse_commit_buffer(the_repository
, current_head
,
1483 res
= error(_("unable to parse commit author"));
1486 parents
= copy_commit_list(current_head
->parents
);
1487 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1488 } else if (current_head
&&
1489 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1490 commit_list_insert(current_head
, &parents
);
1493 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1494 res
= error(_("git write-tree failed to write a tree"));
1498 if (!(flags
& ALLOW_EMPTY
)) {
1499 struct commit
*first_parent
= current_head
;
1501 if (flags
& AMEND_MSG
) {
1502 if (current_head
->parents
) {
1503 first_parent
= current_head
->parents
->item
;
1504 if (repo_parse_commit(r
, first_parent
)) {
1505 res
= error(_("could not parse HEAD commit"));
1509 first_parent
= NULL
;
1512 if (oideq(first_parent
1513 ? get_commit_tree_oid(first_parent
)
1514 : the_hash_algo
->empty_tree
,
1516 res
= 1; /* run 'git commit' to display error message */
1521 if (hook_exists("prepare-commit-msg")) {
1522 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1525 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1527 res
= error_errno(_("unable to read commit message "
1529 git_path_commit_editmsg());
1535 if (flags
& CLEANUP_MSG
)
1536 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1537 else if (flags
& VERBATIM_MSG
)
1538 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1539 else if ((opts
->signoff
|| opts
->record_origin
) &&
1540 !opts
->explicit_cleanup
)
1541 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1543 cleanup
= opts
->default_msg_cleanup
;
1545 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1546 strbuf_stripspace(msg
, cleanup
== COMMIT_MSG_CLEANUP_ALL
);
1547 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1548 res
= 1; /* run 'git commit' to display error message */
1552 if (opts
->committer_date_is_author_date
) {
1553 struct ident_split id
;
1554 struct strbuf date
= STRBUF_INIT
;
1556 if (!opts
->ignore_date
) {
1557 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1558 res
= error(_("invalid author identity '%s'"),
1562 if (!id
.date_begin
) {
1564 "corrupt author: missing date information"));
1567 strbuf_addf(&date
, "@%.*s %.*s",
1568 (int)(id
.date_end
- id
.date_begin
),
1570 (int)(id
.tz_end
- id
.tz_begin
),
1575 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1576 getenv("GIT_COMMITTER_EMAIL"),
1577 WANT_COMMITTER_IDENT
,
1578 opts
->ignore_date
? NULL
: date
.buf
,
1580 strbuf_release(&date
);
1585 if (opts
->ignore_date
) {
1586 struct ident_split id
;
1589 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1590 error(_("invalid author identity '%s'"), author
);
1593 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1594 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1595 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1601 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1602 author
, committer
, opts
->gpg_sign
, extra
)) {
1603 res
= error(_("failed to write commit object"));
1607 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1609 res
= error("%s", err
.buf
);
1613 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1614 if (flags
& AMEND_MSG
)
1615 commit_post_rewrite(r
, current_head
, oid
);
1618 free_commit_extra_headers(extra
);
1619 strbuf_release(&err
);
1620 strbuf_release(&commit_msg
);
1626 static int write_rebase_head(struct object_id
*oid
)
1628 if (update_ref("rebase", "REBASE_HEAD", oid
,
1629 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1630 return error(_("could not update %s"), "REBASE_HEAD");
1635 static int do_commit(struct repository
*r
,
1636 const char *msg_file
, const char *author
,
1637 struct replay_opts
*opts
, unsigned int flags
,
1638 struct object_id
*oid
)
1642 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1643 struct object_id oid
;
1644 struct strbuf sb
= STRBUF_INIT
;
1646 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1647 return error_errno(_("unable to read commit message "
1651 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1652 author
, opts
, flags
, &oid
);
1653 strbuf_release(&sb
);
1655 refs_delete_ref(get_main_ref_store(r
), "",
1656 "CHERRY_PICK_HEAD", NULL
, 0);
1657 unlink(git_path_merge_msg(r
));
1658 if (!is_rebase_i(opts
))
1659 print_commit_summary(r
, NULL
, &oid
,
1660 SUMMARY_SHOW_AUTHOR_DATE
);
1665 if (is_rebase_i(opts
) && oid
)
1666 if (write_rebase_head(oid
))
1668 return run_git_commit(msg_file
, opts
, flags
);
1674 static int is_original_commit_empty(struct commit
*commit
)
1676 const struct object_id
*ptree_oid
;
1678 if (repo_parse_commit(the_repository
, commit
))
1679 return error(_("could not parse commit %s"),
1680 oid_to_hex(&commit
->object
.oid
));
1681 if (commit
->parents
) {
1682 struct commit
*parent
= commit
->parents
->item
;
1683 if (repo_parse_commit(the_repository
, parent
))
1684 return error(_("could not parse parent commit %s"),
1685 oid_to_hex(&parent
->object
.oid
));
1686 ptree_oid
= get_commit_tree_oid(parent
);
1688 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1691 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1695 * Should empty commits be allowed? Return status:
1696 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1697 * 0: Halt on empty commit
1698 * 1: Allow empty commit
1699 * 2: Drop empty commit
1701 static int allow_empty(struct repository
*r
,
1702 struct replay_opts
*opts
,
1703 struct commit
*commit
)
1705 int index_unchanged
, originally_empty
;
1710 * (1) we do not allow empty at all and error out.
1712 * (2) we allow ones that were initially empty, and
1713 * just drop the ones that become empty
1715 * (3) we allow ones that were initially empty, but
1716 * halt for the ones that become empty;
1718 * (4) we allow both.
1720 if (!opts
->allow_empty
)
1721 return 0; /* let "git commit" barf as necessary */
1723 index_unchanged
= is_index_unchanged(r
);
1724 if (index_unchanged
< 0)
1725 return index_unchanged
;
1726 if (!index_unchanged
)
1727 return 0; /* we do not have to say --allow-empty */
1729 if (opts
->keep_redundant_commits
)
1732 originally_empty
= is_original_commit_empty(commit
);
1733 if (originally_empty
< 0)
1734 return originally_empty
;
1735 if (originally_empty
)
1737 else if (opts
->drop_redundant_commits
)
1746 } todo_command_info
[] = {
1747 [TODO_PICK
] = { 'p', "pick" },
1748 [TODO_REVERT
] = { 0, "revert" },
1749 [TODO_EDIT
] = { 'e', "edit" },
1750 [TODO_REWORD
] = { 'r', "reword" },
1751 [TODO_FIXUP
] = { 'f', "fixup" },
1752 [TODO_SQUASH
] = { 's', "squash" },
1753 [TODO_EXEC
] = { 'x', "exec" },
1754 [TODO_BREAK
] = { 'b', "break" },
1755 [TODO_LABEL
] = { 'l', "label" },
1756 [TODO_RESET
] = { 't', "reset" },
1757 [TODO_MERGE
] = { 'm', "merge" },
1758 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1759 [TODO_NOOP
] = { 0, "noop" },
1760 [TODO_DROP
] = { 'd', "drop" },
1761 [TODO_COMMENT
] = { 0, NULL
},
1764 static const char *command_to_string(const enum todo_command command
)
1766 if (command
< TODO_COMMENT
)
1767 return todo_command_info
[command
].str
;
1768 die(_("unknown command: %d"), command
);
1771 static char command_to_char(const enum todo_command command
)
1773 if (command
< TODO_COMMENT
)
1774 return todo_command_info
[command
].c
;
1775 return comment_line_char
;
1778 static int is_noop(const enum todo_command command
)
1780 return TODO_NOOP
<= command
;
1783 static int is_fixup(enum todo_command command
)
1785 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1788 /* Does this command create a (non-merge) commit? */
1789 static int is_pick_or_similar(enum todo_command command
)
1804 enum todo_item_flags
{
1805 TODO_EDIT_MERGE_MSG
= (1 << 0),
1806 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1807 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1810 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1811 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1812 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1813 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1814 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1816 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1818 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1819 (flag
& TODO_EDIT_FIXUP_MSG
));
1823 * Wrapper around strbuf_add_commented_lines() which avoids double
1824 * commenting commit subjects.
1826 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1828 const char *s
= str
;
1829 while (len
> 0 && s
[0] == comment_line_char
) {
1831 const char *n
= memchr(s
, '\n', len
);
1836 strbuf_add(buf
, s
, count
);
1840 strbuf_add_commented_lines(buf
, s
, len
);
1843 /* Does the current fixup chain contain a squash command? */
1844 static int seen_squash(struct replay_opts
*opts
)
1846 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1847 strstr(opts
->current_fixups
.buf
, "\nsquash");
1850 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1852 strbuf_setlen(buf1
, 2);
1853 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1854 strbuf_addch(buf1
, '\n');
1855 strbuf_setlen(buf2
, 2);
1856 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1857 strbuf_addch(buf2
, '\n');
1861 * Comment out any un-commented commit messages, updating the message comments
1862 * to say they will be skipped but do not comment out the empty lines that
1863 * surround commit messages and their comments.
1865 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1867 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1868 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1869 const char *s
, *start
;
1871 size_t orig_msg_len
;
1874 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1875 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1876 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1880 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1882 * Copy the last message, preserving the blank line
1883 * preceding the current line
1885 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1886 copy_lines(msg
, start
, s
- start
- off
);
1888 strbuf_addch(msg
, '\n');
1890 * The next message needs to be commented out but the
1891 * message header is already commented out so just copy
1892 * it and the blank line that follows it.
1894 strbuf_addbuf(msg
, &buf2
);
1896 strbuf_addch(msg
, *next
++);
1898 copy_lines
= add_commented_lines
;
1899 update_comment_bufs(&buf1
, &buf2
, ++i
);
1900 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1901 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1902 copy_lines(msg
, start
, s
- start
- off
);
1905 copy_lines
= strbuf_add
;
1906 update_comment_bufs(&buf1
, &buf2
, ++i
);
1908 s
= strchr(s
, '\n');
1913 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1915 strbuf_release(&buf1
);
1916 strbuf_release(&buf2
);
1919 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1920 enum todo_command command
, struct replay_opts
*opts
,
1923 const char *fixup_msg
;
1924 size_t commented_len
= 0, fixup_off
;
1926 * amend is non-interactive and not normally used with fixup!
1927 * or squash! commits, so only comment out those subjects when
1928 * squashing commit messages.
1930 if (starts_with(body
, "amend!") ||
1931 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1932 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1933 commented_len
= commit_subject_length(body
);
1935 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1936 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1937 ++opts
->current_fixup_count
+ 1);
1938 strbuf_addstr(buf
, "\n\n");
1939 strbuf_add_commented_lines(buf
, body
, commented_len
);
1940 /* buf->buf may be reallocated so store an offset into the buffer */
1941 fixup_off
= buf
->len
;
1942 strbuf_addstr(buf
, body
+ commented_len
);
1944 /* fixup -C after squash behaves like squash */
1945 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1947 * We're replacing the commit message so we need to
1948 * append the Signed-off-by: trailer if the user
1949 * requested '--signoff'.
1952 append_signoff(buf
, 0, 0);
1954 if ((command
== TODO_FIXUP
) &&
1955 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1956 (file_exists(rebase_path_fixup_msg()) ||
1957 !file_exists(rebase_path_squash_msg()))) {
1958 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1959 if (write_message(fixup_msg
, strlen(fixup_msg
),
1960 rebase_path_fixup_msg(), 0) < 0)
1961 return error(_("cannot write '%s'"),
1962 rebase_path_fixup_msg());
1964 unlink(rebase_path_fixup_msg());
1967 unlink(rebase_path_fixup_msg());
1973 static int update_squash_messages(struct repository
*r
,
1974 enum todo_command command
,
1975 struct commit
*commit
,
1976 struct replay_opts
*opts
,
1979 struct strbuf buf
= STRBUF_INIT
;
1981 const char *message
, *body
;
1982 const char *encoding
= get_commit_output_encoding();
1984 if (opts
->current_fixup_count
> 0) {
1985 struct strbuf header
= STRBUF_INIT
;
1988 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
1989 return error(_("could not read '%s'"),
1990 rebase_path_squash_msg());
1992 eol
= buf
.buf
[0] != comment_line_char
?
1993 buf
.buf
: strchrnul(buf
.buf
, '\n');
1995 strbuf_addf(&header
, "%c ", comment_line_char
);
1996 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
1997 opts
->current_fixup_count
+ 2);
1998 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
1999 strbuf_release(&header
);
2000 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2001 update_squash_message_for_fixup(&buf
);
2003 struct object_id head
;
2004 struct commit
*head_commit
;
2005 const char *head_message
, *body
;
2007 if (repo_get_oid(the_repository
, "HEAD", &head
))
2008 return error(_("need a HEAD to fixup"));
2009 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2010 return error(_("could not read HEAD"));
2011 if (!(head_message
= repo_logmsg_reencode(the_repository
, head_commit
, NULL
, encoding
)))
2012 return error(_("could not read HEAD's commit message"));
2014 find_commit_subject(head_message
, &body
);
2015 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2016 rebase_path_fixup_msg(), 0) < 0) {
2017 repo_unuse_commit_buffer(the_repository
, head_commit
,
2019 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2021 strbuf_addf(&buf
, "%c ", comment_line_char
);
2022 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2023 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2024 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2025 _(skip_first_commit_msg_str
) :
2026 _(first_commit_msg_str
));
2027 strbuf_addstr(&buf
, "\n\n");
2028 if (is_fixup_flag(command
, flag
))
2029 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
2031 strbuf_addstr(&buf
, body
);
2033 repo_unuse_commit_buffer(the_repository
, head_commit
,
2037 if (!(message
= repo_logmsg_reencode(the_repository
, commit
, NULL
, encoding
)))
2038 return error(_("could not read commit message of %s"),
2039 oid_to_hex(&commit
->object
.oid
));
2040 find_commit_subject(message
, &body
);
2042 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2043 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2044 } else if (command
== TODO_FIXUP
) {
2045 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2046 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2047 ++opts
->current_fixup_count
+ 1);
2048 strbuf_addstr(&buf
, "\n\n");
2049 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
2051 return error(_("unknown command: %d"), command
);
2052 repo_unuse_commit_buffer(the_repository
, commit
, message
);
2055 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2057 strbuf_release(&buf
);
2060 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2061 opts
->current_fixups
.len
? "\n" : "",
2062 command_to_string(command
),
2063 oid_to_hex(&commit
->object
.oid
));
2064 res
= write_message(opts
->current_fixups
.buf
,
2065 opts
->current_fixups
.len
,
2066 rebase_path_current_fixups(), 0);
2072 static void flush_rewritten_pending(void)
2074 struct strbuf buf
= STRBUF_INIT
;
2075 struct object_id newoid
;
2078 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2079 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2080 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2081 char *bol
= buf
.buf
, *eol
;
2084 eol
= strchrnul(bol
, '\n');
2085 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2086 bol
, oid_to_hex(&newoid
));
2092 unlink(rebase_path_rewritten_pending());
2094 strbuf_release(&buf
);
2097 static void record_in_rewritten(struct object_id
*oid
,
2098 enum todo_command next_command
)
2100 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2105 fprintf(out
, "%s\n", oid_to_hex(oid
));
2108 if (!is_fixup(next_command
))
2109 flush_rewritten_pending();
2112 static int should_edit(struct replay_opts
*opts
) {
2115 * Note that we only handle the case of non-conflicted
2116 * commits; continue_single_pick() handles the conflicted
2117 * commits itself instead of calling this function.
2119 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2123 static void refer_to_commit(struct replay_opts
*opts
,
2124 struct strbuf
*msgbuf
, struct commit
*commit
)
2126 if (opts
->commit_use_reference
) {
2127 struct pretty_print_context ctx
= {
2128 .abbrev
= DEFAULT_ABBREV
,
2129 .date_mode
.type
= DATE_SHORT
,
2131 repo_format_commit_message(the_repository
, commit
,
2132 "%h (%s, %ad)", msgbuf
, &ctx
);
2134 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2138 static int do_pick_commit(struct repository
*r
,
2139 struct todo_item
*item
,
2140 struct replay_opts
*opts
,
2141 int final_fixup
, int *check_todo
)
2143 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2144 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2145 struct object_id head
;
2146 struct commit
*base
, *next
, *parent
;
2147 const char *base_label
, *next_label
;
2148 char *author
= NULL
;
2149 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2150 struct strbuf msgbuf
= STRBUF_INIT
;
2151 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2152 enum todo_command command
= item
->command
;
2153 struct commit
*commit
= item
->commit
;
2155 if (opts
->no_commit
) {
2157 * We do not intend to commit immediately. We just want to
2158 * merge the differences in, so let's compute the tree
2159 * that represents the "current" state for the merge machinery
2162 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2163 return error(_("your index file is unmerged."));
2165 unborn
= repo_get_oid(the_repository
, "HEAD", &head
);
2166 /* Do we want to generate a root commit? */
2167 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2168 oideq(&head
, &opts
->squash_onto
)) {
2169 if (is_fixup(command
))
2170 return error(_("cannot fixup root commit"));
2171 flags
|= CREATE_ROOT_COMMIT
;
2174 oidcpy(&head
, the_hash_algo
->empty_tree
);
2175 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2177 return error_dirty_index(r
, opts
);
2179 discard_index(r
->index
);
2181 if (!commit
->parents
)
2183 else if (commit
->parents
->next
) {
2184 /* Reverting or cherry-picking a merge commit */
2186 struct commit_list
*p
;
2188 if (!opts
->mainline
)
2189 return error(_("commit %s is a merge but no -m option was given."),
2190 oid_to_hex(&commit
->object
.oid
));
2192 for (cnt
= 1, p
= commit
->parents
;
2193 cnt
!= opts
->mainline
&& p
;
2196 if (cnt
!= opts
->mainline
|| !p
)
2197 return error(_("commit %s does not have parent %d"),
2198 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2200 } else if (1 < opts
->mainline
)
2202 * Non-first parent explicitly specified as mainline for
2205 return error(_("commit %s does not have parent %d"),
2206 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2208 parent
= commit
->parents
->item
;
2210 if (get_message(commit
, &msg
) != 0)
2211 return error(_("cannot get commit message for %s"),
2212 oid_to_hex(&commit
->object
.oid
));
2214 if (opts
->allow_ff
&& !is_fixup(command
) &&
2215 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2216 (!parent
&& unborn
))) {
2217 if (is_rebase_i(opts
))
2218 write_author_script(msg
.message
);
2219 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2221 if (res
|| command
!= TODO_REWORD
)
2225 goto fast_forward_edit
;
2227 if (parent
&& repo_parse_commit(the_repository
, parent
) < 0)
2228 /* TRANSLATORS: The first %s will be a "todo" command like
2229 "revert" or "pick", the second %s a SHA1. */
2230 return error(_("%s: cannot parse parent commit %s"),
2231 command_to_string(command
),
2232 oid_to_hex(&parent
->object
.oid
));
2235 * "commit" is an existing commit. We would want to apply
2236 * the difference it introduces since its first parent "prev"
2237 * on top of the current HEAD if we are cherry-pick. Or the
2238 * reverse of it if we are revert.
2241 if (command
== TODO_REVERT
) {
2243 base_label
= msg
.label
;
2245 next_label
= msg
.parent_label
;
2246 if (opts
->commit_use_reference
) {
2247 strbuf_addstr(&msgbuf
,
2248 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2250 strbuf_addstr(&msgbuf
, "Revert \"");
2251 strbuf_addstr(&msgbuf
, msg
.subject
);
2252 strbuf_addstr(&msgbuf
, "\"");
2254 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2255 refer_to_commit(opts
, &msgbuf
, commit
);
2257 if (commit
->parents
&& commit
->parents
->next
) {
2258 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2259 refer_to_commit(opts
, &msgbuf
, parent
);
2261 strbuf_addstr(&msgbuf
, ".\n");
2266 base_label
= msg
.parent_label
;
2268 next_label
= msg
.label
;
2270 /* Append the commit log message to msgbuf. */
2271 if (find_commit_subject(msg
.message
, &p
))
2272 strbuf_addstr(&msgbuf
, p
);
2274 if (opts
->record_origin
) {
2275 strbuf_complete_line(&msgbuf
);
2276 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2277 strbuf_addch(&msgbuf
, '\n');
2278 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2279 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2280 strbuf_addstr(&msgbuf
, ")\n");
2282 if (!is_fixup(command
))
2283 author
= get_author(msg
.message
);
2286 if (command
== TODO_REWORD
)
2288 else if (is_fixup(command
)) {
2289 if (update_squash_messages(r
, command
, commit
,
2290 opts
, item
->flags
)) {
2296 msg_file
= rebase_path_squash_msg();
2297 else if (file_exists(rebase_path_fixup_msg())) {
2298 flags
|= VERBATIM_MSG
;
2299 msg_file
= rebase_path_fixup_msg();
2301 const char *dest
= git_path_squash_msg(r
);
2303 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2304 res
= error(_("could not rename '%s' to '%s'"),
2305 rebase_path_squash_msg(), dest
);
2308 unlink(git_path_merge_msg(r
));
2314 if (opts
->signoff
&& !is_fixup(command
))
2315 append_signoff(&msgbuf
, 0, 0);
2317 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2319 else if (!opts
->strategy
||
2320 !strcmp(opts
->strategy
, "recursive") ||
2321 !strcmp(opts
->strategy
, "ort") ||
2322 command
== TODO_REVERT
) {
2323 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2324 &head
, &msgbuf
, opts
);
2328 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2329 git_path_merge_msg(r
), 0);
2331 struct commit_list
*common
= NULL
;
2332 struct commit_list
*remotes
= NULL
;
2334 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2335 git_path_merge_msg(r
), 0);
2337 commit_list_insert(base
, &common
);
2338 commit_list_insert(next
, &remotes
);
2339 res
|= try_merge_command(r
, opts
->strategy
,
2340 opts
->xopts_nr
, (const char **)opts
->xopts
,
2341 common
, oid_to_hex(&head
), remotes
);
2342 free_commit_list(common
);
2343 free_commit_list(remotes
);
2347 * If the merge was clean or if it failed due to conflict, we write
2348 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2349 * However, if the merge did not even start, then we don't want to
2352 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2353 command
== TODO_EDIT
) && !opts
->no_commit
&&
2354 (res
== 0 || res
== 1) &&
2355 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2356 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2358 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2359 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2360 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2364 error(command
== TODO_REVERT
2365 ? _("could not revert %s... %s")
2366 : _("could not apply %s... %s"),
2367 short_commit_name(commit
), msg
.subject
);
2368 print_advice(r
, res
== 1, opts
);
2369 repo_rerere(r
, opts
->allow_rerere_auto
);
2374 allow
= allow_empty(r
, opts
, commit
);
2378 } else if (allow
== 1) {
2379 flags
|= ALLOW_EMPTY
;
2380 } else if (allow
== 2) {
2382 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2384 unlink(git_path_merge_msg(r
));
2385 unlink(git_path_auto_merge(r
));
2387 _("dropping %s %s -- patch contents already upstream\n"),
2388 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2389 } /* else allow == 0 and there's nothing special to do */
2390 if (!opts
->no_commit
&& !drop_commit
) {
2391 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2392 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2393 commit
? &commit
->object
.oid
: NULL
);
2395 res
= error(_("unable to parse commit author"));
2396 *check_todo
= !!(flags
& EDIT_MSG
);
2397 if (!res
&& reword
) {
2399 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2400 VERIFY_MSG
| AMEND_MSG
|
2401 (flags
& ALLOW_EMPTY
));
2407 if (!res
&& final_fixup
) {
2408 unlink(rebase_path_fixup_msg());
2409 unlink(rebase_path_squash_msg());
2410 unlink(rebase_path_current_fixups());
2411 strbuf_reset(&opts
->current_fixups
);
2412 opts
->current_fixup_count
= 0;
2416 free_message(commit
, &msg
);
2418 strbuf_release(&msgbuf
);
2419 update_abort_safety_file();
2424 static int prepare_revs(struct replay_opts
*opts
)
2427 * picking (but not reverting) ranges (but not individual revisions)
2428 * should be done in reverse
2430 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2431 opts
->revs
->reverse
^= 1;
2433 if (prepare_revision_walk(opts
->revs
))
2434 return error(_("revision walk setup failed"));
2439 static int read_and_refresh_cache(struct repository
*r
,
2440 struct replay_opts
*opts
)
2442 struct lock_file index_lock
= LOCK_INIT
;
2443 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2444 if (repo_read_index(r
) < 0) {
2445 rollback_lock_file(&index_lock
);
2446 return error(_("git %s: failed to read the index"),
2449 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2451 if (index_fd
>= 0) {
2452 if (write_locked_index(r
->index
, &index_lock
,
2453 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2454 return error(_("git %s: failed to refresh the index"),
2460 * If we are resolving merges in any way other than "ort", then
2461 * expand the sparse index.
2463 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2464 ensure_full_index(r
->index
);
2468 void todo_list_release(struct todo_list
*todo_list
)
2470 strbuf_release(&todo_list
->buf
);
2471 FREE_AND_NULL(todo_list
->items
);
2472 todo_list
->nr
= todo_list
->alloc
= 0;
2475 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2477 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2478 todo_list
->total_nr
++;
2479 return todo_list
->items
+ todo_list
->nr
++;
2482 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2483 struct todo_item
*item
)
2485 return todo_list
->buf
.buf
+ item
->arg_offset
;
2488 static int is_command(enum todo_command command
, const char **bol
)
2490 const char *str
= todo_command_info
[command
].str
;
2491 const char nick
= todo_command_info
[command
].c
;
2492 const char *p
= *bol
;
2494 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2495 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2499 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2504 * '#' is not a valid label as the merge command uses it to
2505 * separate merge parents from the commit subject.
2507 if (!strcmp(arg
, "#") ||
2508 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2509 return error(_("'%s' is not a valid label"), arg
);
2512 case TODO_UPDATE_REF
:
2513 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2514 return error(_("'%s' is not a valid refname"), arg
);
2515 if (check_refname_format(arg
, 0))
2516 return error(_("update-ref requires a fully qualified "
2517 "refname e.g. refs/heads/%s"), arg
);
2521 BUG("unexpected todo_command");
2527 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2528 const char *buf
, const char *bol
, char *eol
)
2530 struct object_id commit_oid
;
2531 char *end_of_object_name
;
2532 int i
, saved
, status
, padding
;
2537 bol
+= strspn(bol
, " \t");
2539 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2540 item
->command
= TODO_COMMENT
;
2541 item
->commit
= NULL
;
2542 item
->arg_offset
= bol
- buf
;
2543 item
->arg_len
= eol
- bol
;
2547 for (i
= 0; i
< TODO_COMMENT
; i
++)
2548 if (is_command(i
, &bol
)) {
2552 if (i
>= TODO_COMMENT
)
2553 return error(_("invalid command '%.*s'"),
2554 (int)strcspn(bol
, " \t\r\n"), bol
);
2556 /* Eat up extra spaces/ tabs before object name */
2557 padding
= strspn(bol
, " \t");
2560 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2562 return error(_("%s does not accept arguments: '%s'"),
2563 command_to_string(item
->command
), bol
);
2564 item
->commit
= NULL
;
2565 item
->arg_offset
= bol
- buf
;
2566 item
->arg_len
= eol
- bol
;
2571 return error(_("missing arguments for %s"),
2572 command_to_string(item
->command
));
2574 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2575 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2578 item
->commit
= NULL
;
2579 item
->arg_offset
= bol
- buf
;
2580 item
->arg_len
= (int)(eol
- bol
);
2581 if (item
->command
== TODO_LABEL
||
2582 item
->command
== TODO_UPDATE_REF
) {
2585 ret
= check_label_or_ref_arg(item
->command
, bol
);
2591 if (item
->command
== TODO_FIXUP
) {
2592 if (skip_prefix(bol
, "-C", &bol
)) {
2593 bol
+= strspn(bol
, " \t");
2594 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2595 } else if (skip_prefix(bol
, "-c", &bol
)) {
2596 bol
+= strspn(bol
, " \t");
2597 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2601 if (item
->command
== TODO_MERGE
) {
2602 if (skip_prefix(bol
, "-C", &bol
))
2603 bol
+= strspn(bol
, " \t");
2604 else if (skip_prefix(bol
, "-c", &bol
)) {
2605 bol
+= strspn(bol
, " \t");
2606 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2608 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2609 item
->commit
= NULL
;
2610 item
->arg_offset
= bol
- buf
;
2611 item
->arg_len
= (int)(eol
- bol
);
2616 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2617 saved
= *end_of_object_name
;
2618 *end_of_object_name
= '\0';
2619 status
= repo_get_oid(the_repository
, bol
, &commit_oid
);
2621 error(_("could not parse '%s'"), bol
); /* return later */
2622 *end_of_object_name
= saved
;
2624 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2625 item
->arg_offset
= bol
- buf
;
2626 item
->arg_len
= (int)(eol
- bol
);
2631 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2632 return item
->commit
? 0 : -1;
2635 int sequencer_get_last_command(struct repository
*r
, enum replay_action
*action
)
2637 const char *todo_file
, *bol
;
2638 struct strbuf buf
= STRBUF_INIT
;
2641 todo_file
= git_path_todo_file();
2642 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2643 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2646 return error_errno("unable to open '%s'", todo_file
);
2648 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2649 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2650 *action
= REPLAY_PICK
;
2651 else if (is_command(TODO_REVERT
, &bol
) &&
2652 (*bol
== ' ' || *bol
== '\t'))
2653 *action
= REPLAY_REVERT
;
2657 strbuf_release(&buf
);
2662 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2663 struct todo_list
*todo_list
)
2665 struct todo_item
*item
;
2666 char *p
= buf
, *next_p
;
2667 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2669 todo_list
->current
= todo_list
->nr
= 0;
2671 for (i
= 1; *p
; i
++, p
= next_p
) {
2672 char *eol
= strchrnul(p
, '\n');
2674 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2676 if (p
!= eol
&& eol
[-1] == '\r')
2677 eol
--; /* strip Carriage Return */
2679 item
= append_new_todo(todo_list
);
2680 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2681 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2682 res
= error(_("invalid line %d: %.*s"),
2683 i
, (int)(eol
- p
), p
);
2684 item
->command
= TODO_COMMENT
+ 1;
2685 item
->arg_offset
= p
- buf
;
2686 item
->arg_len
= (int)(eol
- p
);
2687 item
->commit
= NULL
;
2692 else if (is_fixup(item
->command
))
2693 return error(_("cannot '%s' without a previous commit"),
2694 command_to_string(item
->command
));
2695 else if (!is_noop(item
->command
))
2702 static int count_commands(struct todo_list
*todo_list
)
2706 for (i
= 0; i
< todo_list
->nr
; i
++)
2707 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2713 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2715 return index
< todo_list
->nr
?
2716 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2719 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2721 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2724 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2726 return get_item_line_offset(todo_list
, index
+ 1)
2727 - get_item_line_offset(todo_list
, index
);
2730 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2735 fd
= open(path
, O_RDONLY
);
2737 return error_errno(_("could not open '%s'"), path
);
2738 len
= strbuf_read(sb
, fd
, 0);
2741 return error(_("could not read '%s'."), path
);
2745 static int have_finished_the_last_pick(void)
2747 struct strbuf buf
= STRBUF_INIT
;
2749 const char *todo_path
= git_path_todo_file();
2752 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2753 if (errno
== ENOENT
) {
2756 error_errno("unable to open '%s'", todo_path
);
2760 /* If there is only one line then we are done */
2761 eol
= strchr(buf
.buf
, '\n');
2762 if (!eol
|| !eol
[1])
2765 strbuf_release(&buf
);
2770 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2772 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2773 int need_cleanup
= 0;
2775 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2776 if (!refs_delete_ref(get_main_ref_store(r
), "",
2777 "CHERRY_PICK_HEAD", NULL
, 0) &&
2779 warning(_("cancelling a cherry picking in progress"));
2780 opts
.action
= REPLAY_PICK
;
2784 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2785 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2788 warning(_("cancelling a revert in progress"));
2789 opts
.action
= REPLAY_REVERT
;
2793 unlink(git_path_auto_merge(r
));
2798 if (!have_finished_the_last_pick())
2801 sequencer_remove_state(&opts
);
2804 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2806 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2809 fprintf(f
, "%d\n", todo_list
->total_nr
);
2814 static int read_populate_todo(struct repository
*r
,
2815 struct todo_list
*todo_list
,
2816 struct replay_opts
*opts
)
2818 const char *todo_file
= get_todo_path(opts
);
2821 strbuf_reset(&todo_list
->buf
);
2822 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2825 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2827 if (is_rebase_i(opts
))
2828 return error(_("please fix this using "
2829 "'git rebase --edit-todo'."));
2830 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2833 if (!todo_list
->nr
&&
2834 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2835 return error(_("no commits parsed."));
2837 if (!is_rebase_i(opts
)) {
2838 enum todo_command valid
=
2839 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2842 for (i
= 0; i
< todo_list
->nr
; i
++)
2843 if (valid
== todo_list
->items
[i
].command
)
2845 else if (valid
== TODO_PICK
)
2846 return error(_("cannot cherry-pick during a revert."));
2848 return error(_("cannot revert during a cherry-pick."));
2851 if (is_rebase_i(opts
)) {
2852 struct todo_list done
= TODO_LIST_INIT
;
2854 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2855 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2856 todo_list
->done_nr
= count_commands(&done
);
2858 todo_list
->done_nr
= 0;
2860 todo_list
->total_nr
= todo_list
->done_nr
2861 + count_commands(todo_list
);
2862 todo_list_release(&done
);
2864 todo_list_write_total_nr(todo_list
);
2870 static int git_config_string_dup(char **dest
,
2871 const char *var
, const char *value
)
2874 return config_error_nonbool(var
);
2876 *dest
= xstrdup(value
);
2880 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
2882 struct replay_opts
*opts
= data
;
2887 else if (!strcmp(key
, "options.no-commit"))
2888 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
2889 else if (!strcmp(key
, "options.edit"))
2890 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
2891 else if (!strcmp(key
, "options.allow-empty"))
2893 git_config_bool_or_int(key
, value
, &error_flag
);
2894 else if (!strcmp(key
, "options.allow-empty-message"))
2895 opts
->allow_empty_message
=
2896 git_config_bool_or_int(key
, value
, &error_flag
);
2897 else if (!strcmp(key
, "options.keep-redundant-commits"))
2898 opts
->keep_redundant_commits
=
2899 git_config_bool_or_int(key
, value
, &error_flag
);
2900 else if (!strcmp(key
, "options.signoff"))
2901 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
2902 else if (!strcmp(key
, "options.record-origin"))
2903 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
2904 else if (!strcmp(key
, "options.allow-ff"))
2905 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
2906 else if (!strcmp(key
, "options.mainline"))
2907 opts
->mainline
= git_config_int(key
, value
);
2908 else if (!strcmp(key
, "options.strategy"))
2909 git_config_string_dup(&opts
->strategy
, key
, value
);
2910 else if (!strcmp(key
, "options.gpg-sign"))
2911 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2912 else if (!strcmp(key
, "options.strategy-option")) {
2913 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
2914 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(value
);
2915 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2916 opts
->allow_rerere_auto
=
2917 git_config_bool_or_int(key
, value
, &error_flag
) ?
2918 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2919 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2920 opts
->explicit_cleanup
= 1;
2921 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2923 return error(_("invalid key: %s"), key
);
2926 return error(_("invalid value for '%s': '%s'"), key
, value
);
2931 void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2934 char *strategy_opts_string
= raw_opts
;
2936 if (*strategy_opts_string
== ' ')
2937 strategy_opts_string
++;
2939 opts
->xopts_nr
= split_cmdline(strategy_opts_string
,
2940 (const char ***)&opts
->xopts
);
2941 for (i
= 0; i
< opts
->xopts_nr
; i
++) {
2942 const char *arg
= opts
->xopts
[i
];
2944 skip_prefix(arg
, "--", &arg
);
2945 opts
->xopts
[i
] = xstrdup(arg
);
2949 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2952 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2954 free(opts
->strategy
);
2955 opts
->strategy
= strbuf_detach(buf
, NULL
);
2956 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2959 parse_strategy_opts(opts
, buf
->buf
);
2962 static int read_populate_opts(struct replay_opts
*opts
)
2964 if (is_rebase_i(opts
)) {
2965 struct strbuf buf
= STRBUF_INIT
;
2968 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
2969 READ_ONELINER_SKIP_IF_EMPTY
)) {
2970 if (!starts_with(buf
.buf
, "-S"))
2973 free(opts
->gpg_sign
);
2974 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
2979 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
2980 READ_ONELINER_SKIP_IF_EMPTY
)) {
2981 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
2982 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
2983 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
2984 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
2988 if (file_exists(rebase_path_verbose()))
2991 if (file_exists(rebase_path_quiet()))
2994 if (file_exists(rebase_path_signoff())) {
2999 if (file_exists(rebase_path_cdate_is_adate())) {
3001 opts
->committer_date_is_author_date
= 1;
3004 if (file_exists(rebase_path_ignore_date())) {
3006 opts
->ignore_date
= 1;
3009 if (file_exists(rebase_path_reschedule_failed_exec()))
3010 opts
->reschedule_failed_exec
= 1;
3011 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3012 opts
->reschedule_failed_exec
= 0;
3014 if (file_exists(rebase_path_drop_redundant_commits()))
3015 opts
->drop_redundant_commits
= 1;
3017 if (file_exists(rebase_path_keep_redundant_commits()))
3018 opts
->keep_redundant_commits
= 1;
3020 read_strategy_opts(opts
, &buf
);
3023 if (read_oneliner(&opts
->current_fixups
,
3024 rebase_path_current_fixups(),
3025 READ_ONELINER_SKIP_IF_EMPTY
)) {
3026 const char *p
= opts
->current_fixups
.buf
;
3027 opts
->current_fixup_count
= 1;
3028 while ((p
= strchr(p
, '\n'))) {
3029 opts
->current_fixup_count
++;
3034 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3035 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3036 ret
= error(_("unusable squash-onto"));
3039 opts
->have_squash_onto
= 1;
3043 strbuf_release(&buf
);
3047 if (!file_exists(git_path_opts_file()))
3050 * The function git_parse_source(), called from git_config_from_file(),
3051 * may die() in case of a syntactically incorrect file. We do not care
3052 * about this case, though, because we wrote that file ourselves, so we
3053 * are pretty certain that it is syntactically correct.
3055 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3056 return error(_("malformed options sheet: '%s'"),
3057 git_path_opts_file());
3061 static void write_strategy_opts(struct replay_opts
*opts
)
3064 struct strbuf buf
= STRBUF_INIT
;
3066 for (i
= 0; i
< opts
->xopts_nr
; ++i
)
3067 strbuf_addf(&buf
, " --%s", opts
->xopts
[i
]);
3069 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3070 strbuf_release(&buf
);
3073 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3074 struct commit
*onto
, const struct object_id
*orig_head
)
3077 write_file(rebase_path_head_name(), "%s\n", head_name
);
3079 write_file(rebase_path_onto(), "%s\n",
3080 oid_to_hex(&onto
->object
.oid
));
3082 write_file(rebase_path_orig_head(), "%s\n",
3083 oid_to_hex(orig_head
));
3086 write_file(rebase_path_quiet(), "%s", "");
3088 write_file(rebase_path_verbose(), "%s", "");
3090 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3091 if (opts
->xopts_nr
> 0)
3092 write_strategy_opts(opts
);
3094 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3095 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3096 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3097 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3100 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3102 write_file(rebase_path_signoff(), "--signoff\n");
3103 if (opts
->drop_redundant_commits
)
3104 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3105 if (opts
->keep_redundant_commits
)
3106 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3107 if (opts
->committer_date_is_author_date
)
3108 write_file(rebase_path_cdate_is_adate(), "%s", "");
3109 if (opts
->ignore_date
)
3110 write_file(rebase_path_ignore_date(), "%s", "");
3111 if (opts
->reschedule_failed_exec
)
3112 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3114 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3119 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3120 struct replay_opts
*opts
)
3122 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3123 TODO_PICK
: TODO_REVERT
;
3124 const char *command_string
= todo_command_info
[command
].str
;
3125 const char *encoding
;
3126 struct commit
*commit
;
3128 if (prepare_revs(opts
))
3131 encoding
= get_log_output_encoding();
3133 while ((commit
= get_revision(opts
->revs
))) {
3134 struct todo_item
*item
= append_new_todo(todo_list
);
3135 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3138 const char *subject
;
3141 item
->command
= command
;
3142 item
->commit
= commit
;
3143 item
->arg_offset
= 0;
3145 item
->offset_in_buf
= todo_list
->buf
.len
;
3146 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3147 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3148 short_commit_name(commit
), subject_len
, subject
);
3149 repo_unuse_commit_buffer(the_repository
, commit
,
3154 return error(_("empty commit set passed"));
3159 static int create_seq_dir(struct repository
*r
)
3161 enum replay_action action
;
3162 const char *in_progress_error
= NULL
;
3163 const char *in_progress_advice
= NULL
;
3164 unsigned int advise_skip
=
3165 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3166 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3168 if (!sequencer_get_last_command(r
, &action
)) {
3171 in_progress_error
= _("revert is already in progress");
3172 in_progress_advice
=
3173 _("try \"git revert (--continue | %s--abort | --quit)\"");
3176 in_progress_error
= _("cherry-pick is already in progress");
3177 in_progress_advice
=
3178 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3181 BUG("unexpected action in create_seq_dir");
3184 if (in_progress_error
) {
3185 error("%s", in_progress_error
);
3186 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3187 advise(in_progress_advice
,
3188 advise_skip
? "--skip | " : "");
3191 if (mkdir(git_path_seq_dir(), 0777) < 0)
3192 return error_errno(_("could not create sequencer directory '%s'"),
3193 git_path_seq_dir());
3198 static int save_head(const char *head
)
3200 struct lock_file head_lock
= LOCK_INIT
;
3201 struct strbuf buf
= STRBUF_INIT
;
3205 fd
= hold_lock_file_for_update(&head_lock
, git_path_head_file(), 0);
3207 return error_errno(_("could not lock HEAD"));
3208 strbuf_addf(&buf
, "%s\n", head
);
3209 written
= write_in_full(fd
, buf
.buf
, buf
.len
);
3210 strbuf_release(&buf
);
3212 error_errno(_("could not write to '%s'"), git_path_head_file());
3213 rollback_lock_file(&head_lock
);
3216 if (commit_lock_file(&head_lock
) < 0)
3217 return error(_("failed to finalize '%s'"), git_path_head_file());
3221 static int rollback_is_safe(void)
3223 struct strbuf sb
= STRBUF_INIT
;
3224 struct object_id expected_head
, actual_head
;
3226 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3228 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3229 strbuf_release(&sb
);
3230 die(_("could not parse %s"), git_path_abort_safety_file());
3232 strbuf_release(&sb
);
3234 else if (errno
== ENOENT
)
3235 oidclr(&expected_head
);
3237 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3239 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3240 oidclr(&actual_head
);
3242 return oideq(&actual_head
, &expected_head
);
3245 static int reset_merge(const struct object_id
*oid
)
3247 struct child_process cmd
= CHILD_PROCESS_INIT
;
3250 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3252 if (!is_null_oid(oid
))
3253 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3255 return run_command(&cmd
);
3258 static int rollback_single_pick(struct repository
*r
)
3260 struct object_id head_oid
;
3262 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3263 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3264 return error(_("no cherry-pick or revert in progress"));
3265 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3266 return error(_("cannot resolve HEAD"));
3267 if (is_null_oid(&head_oid
))
3268 return error(_("cannot abort from a branch yet to be born"));
3269 return reset_merge(&head_oid
);
3272 static int skip_single_pick(void)
3274 struct object_id head
;
3276 if (read_ref_full("HEAD", 0, &head
, NULL
))
3277 return error(_("cannot resolve HEAD"));
3278 return reset_merge(&head
);
3281 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3284 struct object_id oid
;
3285 struct strbuf buf
= STRBUF_INIT
;
3288 f
= fopen(git_path_head_file(), "r");
3289 if (!f
&& errno
== ENOENT
) {
3291 * There is no multiple-cherry-pick in progress.
3292 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3293 * a single-cherry-pick in progress, abort that.
3295 return rollback_single_pick(r
);
3298 return error_errno(_("cannot open '%s'"), git_path_head_file());
3299 if (strbuf_getline_lf(&buf
, f
)) {
3300 error(_("cannot read '%s': %s"), git_path_head_file(),
3301 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3306 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3307 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3308 git_path_head_file());
3311 if (is_null_oid(&oid
)) {
3312 error(_("cannot abort from a branch yet to be born"));
3316 if (!rollback_is_safe()) {
3317 /* Do not error, just do not rollback */
3318 warning(_("You seem to have moved HEAD. "
3319 "Not rewinding, check your HEAD!"));
3321 if (reset_merge(&oid
))
3323 strbuf_release(&buf
);
3324 return sequencer_remove_state(opts
);
3326 strbuf_release(&buf
);
3330 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3332 enum replay_action action
= -1;
3333 sequencer_get_last_command(r
, &action
);
3336 * Check whether the subcommand requested to skip the commit is actually
3337 * in progress and that it's safe to skip the commit.
3339 * opts->action tells us which subcommand requested to skip the commit.
3340 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3341 * action is in progress and we can skip the commit.
3343 * Otherwise we check that the last instruction was related to the
3344 * particular subcommand we're trying to execute and barf if that's not
3347 * Finally we check that the rollback is "safe", i.e., has the HEAD
3348 * moved? In this case, it doesn't make sense to "reset the merge" and
3349 * "skip the commit" as the user already handled this by committing. But
3350 * we'd not want to barf here, instead give advice on how to proceed. We
3351 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3352 * it gets removed when the user commits, so if it still exists we're
3353 * sure the user can't have committed before.
3355 switch (opts
->action
) {
3357 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3358 if (action
!= REPLAY_REVERT
)
3359 return error(_("no revert in progress"));
3360 if (!rollback_is_safe())
3365 if (!refs_ref_exists(get_main_ref_store(r
),
3366 "CHERRY_PICK_HEAD")) {
3367 if (action
!= REPLAY_PICK
)
3368 return error(_("no cherry-pick in progress"));
3369 if (!rollback_is_safe())
3374 BUG("unexpected action in sequencer_skip");
3377 if (skip_single_pick())
3378 return error(_("failed to skip the commit"));
3379 if (!is_directory(git_path_seq_dir()))
3382 return sequencer_continue(r
, opts
);
3385 error(_("there is nothing to skip"));
3387 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3388 advise(_("have you committed already?\n"
3389 "try \"git %s --continue\""),
3390 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3395 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
3397 struct lock_file todo_lock
= LOCK_INIT
;
3398 const char *todo_path
= get_todo_path(opts
);
3399 int next
= todo_list
->current
, offset
, fd
;
3402 * rebase -i writes "git-rebase-todo" without the currently executing
3403 * command, appending it to "done" instead.
3405 if (is_rebase_i(opts
))
3408 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3410 return error_errno(_("could not lock '%s'"), todo_path
);
3411 offset
= get_item_line_offset(todo_list
, next
);
3412 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3413 todo_list
->buf
.len
- offset
) < 0)
3414 return error_errno(_("could not write to '%s'"), todo_path
);
3415 if (commit_lock_file(&todo_lock
) < 0)
3416 return error(_("failed to finalize '%s'"), todo_path
);
3418 if (is_rebase_i(opts
) && next
> 0) {
3419 const char *done
= rebase_path_done();
3420 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3425 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3426 get_item_line_length(todo_list
, next
- 1))
3428 ret
= error_errno(_("could not write to '%s'"), done
);
3430 ret
= error_errno(_("failed to finalize '%s'"), done
);
3436 static int save_opts(struct replay_opts
*opts
)
3438 const char *opts_file
= git_path_opts_file();
3441 if (opts
->no_commit
)
3442 res
|= git_config_set_in_file_gently(opts_file
,
3443 "options.no-commit", "true");
3444 if (opts
->edit
>= 0)
3445 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3446 opts
->edit
? "true" : "false");
3447 if (opts
->allow_empty
)
3448 res
|= git_config_set_in_file_gently(opts_file
,
3449 "options.allow-empty", "true");
3450 if (opts
->allow_empty_message
)
3451 res
|= git_config_set_in_file_gently(opts_file
,
3452 "options.allow-empty-message", "true");
3453 if (opts
->keep_redundant_commits
)
3454 res
|= git_config_set_in_file_gently(opts_file
,
3455 "options.keep-redundant-commits", "true");
3457 res
|= git_config_set_in_file_gently(opts_file
,
3458 "options.signoff", "true");
3459 if (opts
->record_origin
)
3460 res
|= git_config_set_in_file_gently(opts_file
,
3461 "options.record-origin", "true");
3463 res
|= git_config_set_in_file_gently(opts_file
,
3464 "options.allow-ff", "true");
3465 if (opts
->mainline
) {
3466 struct strbuf buf
= STRBUF_INIT
;
3467 strbuf_addf(&buf
, "%d", opts
->mainline
);
3468 res
|= git_config_set_in_file_gently(opts_file
,
3469 "options.mainline", buf
.buf
);
3470 strbuf_release(&buf
);
3473 res
|= git_config_set_in_file_gently(opts_file
,
3474 "options.strategy", opts
->strategy
);
3476 res
|= git_config_set_in_file_gently(opts_file
,
3477 "options.gpg-sign", opts
->gpg_sign
);
3480 for (i
= 0; i
< opts
->xopts_nr
; i
++)
3481 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3482 "options.strategy-option",
3483 opts
->xopts
[i
], "^$", 0);
3485 if (opts
->allow_rerere_auto
)
3486 res
|= git_config_set_in_file_gently(opts_file
,
3487 "options.allow-rerere-auto",
3488 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3491 if (opts
->explicit_cleanup
)
3492 res
|= git_config_set_in_file_gently(opts_file
,
3493 "options.default-msg-cleanup",
3494 describe_cleanup_mode(opts
->default_msg_cleanup
));
3498 static int make_patch(struct repository
*r
,
3499 struct commit
*commit
,
3500 struct replay_opts
*opts
)
3502 struct strbuf buf
= STRBUF_INIT
;
3503 struct rev_info log_tree_opt
;
3504 const char *subject
;
3505 char hex
[GIT_MAX_HEXSZ
+ 1];
3508 oid_to_hex_r(hex
, &commit
->object
.oid
);
3509 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3511 res
|= write_rebase_head(&commit
->object
.oid
);
3513 strbuf_addf(&buf
, "%s/patch", get_dir(opts
));
3514 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3515 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3516 log_tree_opt
.abbrev
= 0;
3517 log_tree_opt
.diff
= 1;
3518 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3519 log_tree_opt
.disable_stdin
= 1;
3520 log_tree_opt
.no_commit_id
= 1;
3521 log_tree_opt
.diffopt
.file
= fopen(buf
.buf
, "w");
3522 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3523 if (!log_tree_opt
.diffopt
.file
)
3524 res
|= error_errno(_("could not open '%s'"), buf
.buf
);
3526 res
|= log_tree_commit(&log_tree_opt
, commit
);
3527 fclose(log_tree_opt
.diffopt
.file
);
3531 strbuf_addf(&buf
, "%s/message", get_dir(opts
));
3532 if (!file_exists(buf
.buf
)) {
3533 const char *encoding
= get_commit_output_encoding();
3534 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3537 find_commit_subject(commit_buffer
, &subject
);
3538 res
|= write_message(subject
, strlen(subject
), buf
.buf
, 1);
3539 repo_unuse_commit_buffer(the_repository
, commit
,
3542 strbuf_release(&buf
);
3543 release_revisions(&log_tree_opt
);
3548 static int intend_to_amend(void)
3550 struct object_id head
;
3553 if (repo_get_oid(the_repository
, "HEAD", &head
))
3554 return error(_("cannot read HEAD"));
3556 p
= oid_to_hex(&head
);
3557 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3560 static int error_with_patch(struct repository
*r
,
3561 struct commit
*commit
,
3562 const char *subject
, int subject_len
,
3563 struct replay_opts
*opts
,
3564 int exit_code
, int to_amend
)
3567 if (make_patch(r
, commit
, opts
))
3569 } else if (copy_file(rebase_path_message(),
3570 git_path_merge_msg(r
), 0666))
3571 return error(_("unable to copy '%s' to '%s'"),
3572 git_path_merge_msg(r
), rebase_path_message());
3575 if (intend_to_amend())
3579 _("You can amend the commit now, with\n"
3581 " git commit --amend %s\n"
3583 "Once you are satisfied with your changes, run\n"
3585 " git rebase --continue\n"),
3586 gpg_sign_opt_quoted(opts
));
3587 } else if (exit_code
) {
3589 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3590 short_commit_name(commit
), subject_len
, subject
);
3593 * We don't have the hash of the parent so
3594 * just print the line from the todo file.
3596 fprintf_ln(stderr
, _("Could not merge %.*s"),
3597 subject_len
, subject
);
3603 static int error_failed_squash(struct repository
*r
,
3604 struct commit
*commit
,
3605 struct replay_opts
*opts
,
3607 const char *subject
)
3609 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3610 return error(_("could not copy '%s' to '%s'"),
3611 rebase_path_squash_msg(), rebase_path_message());
3612 unlink(git_path_merge_msg(r
));
3613 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3614 return error(_("could not copy '%s' to '%s'"),
3615 rebase_path_message(),
3616 git_path_merge_msg(r
));
3617 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3620 static int do_exec(struct repository
*r
, const char *command_line
)
3622 struct child_process cmd
= CHILD_PROCESS_INIT
;
3625 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3627 strvec_push(&cmd
.args
, command_line
);
3628 status
= run_command(&cmd
);
3630 /* force re-reading of the cache */
3631 discard_index(r
->index
);
3632 if (repo_read_index(r
) < 0)
3633 return error(_("could not read index"));
3635 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3638 warning(_("execution failed: %s\n%s"
3639 "You can fix the problem, and then run\n"
3641 " git rebase --continue\n"
3644 dirty
? N_("and made changes to the index and/or the "
3645 "working tree\n") : "");
3647 /* command not found */
3650 warning(_("execution succeeded: %s\nbut "
3651 "left changes to the index and/or the working tree\n"
3652 "Commit or stash your changes, and then run\n"
3654 " git rebase --continue\n"
3655 "\n"), command_line
);
3662 __attribute__((format (printf
, 2, 3)))
3663 static int safe_append(const char *filename
, const char *fmt
, ...)
3666 struct lock_file lock
= LOCK_INIT
;
3667 int fd
= hold_lock_file_for_update(&lock
, filename
,
3668 LOCK_REPORT_ON_ERROR
);
3669 struct strbuf buf
= STRBUF_INIT
;
3674 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3675 error_errno(_("could not read '%s'"), filename
);
3676 rollback_lock_file(&lock
);
3679 strbuf_complete(&buf
, '\n');
3681 strbuf_vaddf(&buf
, fmt
, ap
);
3684 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3685 error_errno(_("could not write to '%s'"), filename
);
3686 strbuf_release(&buf
);
3687 rollback_lock_file(&lock
);
3690 if (commit_lock_file(&lock
) < 0) {
3691 strbuf_release(&buf
);
3692 rollback_lock_file(&lock
);
3693 return error(_("failed to finalize '%s'"), filename
);
3696 strbuf_release(&buf
);
3700 static int do_label(struct repository
*r
, const char *name
, int len
)
3702 struct ref_store
*refs
= get_main_ref_store(r
);
3703 struct ref_transaction
*transaction
;
3704 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3705 struct strbuf msg
= STRBUF_INIT
;
3707 struct object_id head_oid
;
3709 if (len
== 1 && *name
== '#')
3710 return error(_("illegal label name: '%.*s'"), len
, name
);
3712 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3713 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3715 transaction
= ref_store_transaction_begin(refs
, &err
);
3717 error("%s", err
.buf
);
3719 } else if (repo_get_oid(the_repository
, "HEAD", &head_oid
)) {
3720 error(_("could not read HEAD"));
3722 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3723 NULL
, 0, msg
.buf
, &err
) < 0 ||
3724 ref_transaction_commit(transaction
, &err
)) {
3725 error("%s", err
.buf
);
3728 ref_transaction_free(transaction
);
3729 strbuf_release(&err
);
3730 strbuf_release(&msg
);
3733 ret
= safe_append(rebase_path_refs_to_delete(),
3734 "%s\n", ref_name
.buf
);
3735 strbuf_release(&ref_name
);
3740 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3742 if (!opts
->reflog_action
) {
3743 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3744 opts
->reflog_action
=
3745 xstrdup(opts
->reflog_action
? opts
->reflog_action
3746 : action_name(opts
));
3749 return opts
->reflog_action
;
3752 __attribute__((format (printf
, 3, 4)))
3753 static const char *reflog_message(struct replay_opts
*opts
,
3754 const char *sub_action
, const char *fmt
, ...)
3757 static struct strbuf buf
= STRBUF_INIT
;
3761 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3763 strbuf_addf(&buf
, " (%s)", sub_action
);
3765 strbuf_addstr(&buf
, ": ");
3766 strbuf_vaddf(&buf
, fmt
, ap
);
3773 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3774 int len
, struct strbuf
*buf
)
3776 struct commit
*commit
;
3777 struct object_id oid
;
3780 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3781 if (!read_ref(buf
->buf
, &oid
)) {
3782 commit
= lookup_commit_object(r
, &oid
);
3784 /* fall back to non-rewritten ref or commit */
3785 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3786 commit
= lookup_commit_reference_by_name(buf
->buf
);
3790 error(_("could not resolve '%s'"), buf
->buf
);
3795 static int do_reset(struct repository
*r
,
3796 const char *name
, int len
,
3797 struct replay_opts
*opts
)
3799 struct strbuf ref_name
= STRBUF_INIT
;
3800 struct object_id oid
;
3801 struct lock_file lock
= LOCK_INIT
;
3802 struct tree_desc desc
= { 0 };
3804 struct unpack_trees_options unpack_tree_opts
= { 0 };
3807 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3810 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3811 if (!opts
->have_squash_onto
) {
3813 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3814 NULL
, &opts
->squash_onto
,
3816 return error(_("writing fake root commit"));
3817 opts
->have_squash_onto
= 1;
3818 hex
= oid_to_hex(&opts
->squash_onto
);
3819 if (write_message(hex
, strlen(hex
),
3820 rebase_path_squash_onto(), 0))
3821 return error(_("writing squash-onto"));
3823 oidcpy(&oid
, &opts
->squash_onto
);
3826 struct commit
*commit
;
3828 /* Determine the length of the label */
3829 for (i
= 0; i
< len
; i
++)
3830 if (isspace(name
[i
]))
3834 commit
= lookup_label(r
, name
, len
, &ref_name
);
3839 oid
= commit
->object
.oid
;
3842 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3843 unpack_tree_opts
.head_idx
= 1;
3844 unpack_tree_opts
.src_index
= r
->index
;
3845 unpack_tree_opts
.dst_index
= r
->index
;
3846 unpack_tree_opts
.fn
= oneway_merge
;
3847 unpack_tree_opts
.merge
= 1;
3848 unpack_tree_opts
.update
= 1;
3849 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3850 unpack_tree_opts
.skip_cache_tree_update
= 1;
3851 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3853 if (repo_read_index_unmerged(r
)) {
3854 ret
= error_resolve_conflict(action_name(opts
));
3858 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3859 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3863 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3868 tree
= parse_tree_indirect(&oid
);
3869 prime_cache_tree(r
, r
->index
, tree
);
3871 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3872 ret
= error(_("could not write index"));
3875 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3876 len
, name
), "HEAD", &oid
,
3877 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3879 free((void *)desc
.buffer
);
3881 rollback_lock_file(&lock
);
3882 strbuf_release(&ref_name
);
3883 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3887 static int do_merge(struct repository
*r
,
3888 struct commit
*commit
,
3889 const char *arg
, int arg_len
,
3890 int flags
, int *check_todo
, struct replay_opts
*opts
)
3892 int run_commit_flags
= 0;
3893 struct strbuf ref_name
= STRBUF_INIT
;
3894 struct commit
*head_commit
, *merge_commit
, *i
;
3895 struct commit_list
*bases
, *j
;
3896 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3897 const char *strategy
= !opts
->xopts_nr
&&
3899 !strcmp(opts
->strategy
, "recursive") ||
3900 !strcmp(opts
->strategy
, "ort")) ?
3901 NULL
: opts
->strategy
;
3902 struct merge_options o
;
3903 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3904 static struct lock_file lock
;
3907 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3912 head_commit
= lookup_commit_reference_by_name("HEAD");
3914 ret
= error(_("cannot merge without a current revision"));
3919 * For octopus merges, the arg starts with the list of revisions to be
3920 * merged. The list is optionally followed by '#' and the oneline.
3922 merge_arg_len
= oneline_offset
= arg_len
;
3923 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3926 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3927 p
+= 1 + strspn(p
+ 1, " \t\n");
3928 oneline_offset
= p
- arg
;
3931 k
= strcspn(p
, " \t\n");
3934 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3935 if (!merge_commit
) {
3936 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3939 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3941 merge_arg_len
= p
- arg
;
3945 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3949 if (opts
->have_squash_onto
&&
3950 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3952 * When the user tells us to "merge" something into a
3953 * "[new root]", let's simply fast-forward to the merge head.
3955 rollback_lock_file(&lock
);
3957 ret
= error(_("octopus merge cannot be executed on "
3958 "top of a [new root]"));
3960 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3961 &head_commit
->object
.oid
, 0,
3967 * If HEAD is not identical to the first parent of the original merge
3968 * commit, we cannot fast-forward.
3970 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3971 oideq(&commit
->parents
->item
->object
.oid
,
3972 &head_commit
->object
.oid
);
3975 * If any merge head is different from the original one, we cannot
3978 if (can_fast_forward
) {
3979 struct commit_list
*p
= commit
->parents
->next
;
3981 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
3982 if (!oideq(&j
->item
->object
.oid
,
3983 &p
->item
->object
.oid
)) {
3984 can_fast_forward
= 0;
3988 * If the number of merge heads differs from the original merge
3989 * commit, we cannot fast-forward.
3992 can_fast_forward
= 0;
3995 if (can_fast_forward
) {
3996 rollback_lock_file(&lock
);
3997 ret
= fast_forward_to(r
, &commit
->object
.oid
,
3998 &head_commit
->object
.oid
, 0, opts
);
3999 if (flags
& TODO_EDIT_MERGE_MSG
)
4000 goto fast_forward_edit
;
4006 const char *encoding
= get_commit_output_encoding();
4007 const char *message
= repo_logmsg_reencode(the_repository
,
4014 ret
= error(_("could not get commit message of '%s'"),
4015 oid_to_hex(&commit
->object
.oid
));
4018 write_author_script(message
);
4019 find_commit_subject(message
, &body
);
4021 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4022 repo_unuse_commit_buffer(the_repository
, commit
, message
);
4024 error_errno(_("could not write '%s'"),
4025 git_path_merge_msg(r
));
4029 struct strbuf buf
= STRBUF_INIT
;
4032 strbuf_addf(&buf
, "author %s", git_author_info(0));
4033 write_author_script(buf
.buf
);
4036 if (oneline_offset
< arg_len
) {
4037 p
= arg
+ oneline_offset
;
4038 len
= arg_len
- oneline_offset
;
4040 strbuf_addf(&buf
, "Merge %s '%.*s'",
4041 to_merge
->next
? "branches" : "branch",
4042 merge_arg_len
, arg
);
4047 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4048 strbuf_release(&buf
);
4050 error_errno(_("could not write '%s'"),
4051 git_path_merge_msg(r
));
4056 if (strategy
|| to_merge
->next
) {
4058 struct child_process cmd
= CHILD_PROCESS_INIT
;
4060 if (read_env_script(&cmd
.env
)) {
4061 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4063 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4067 if (opts
->committer_date_is_author_date
)
4068 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4071 author_date_from_env(&cmd
.env
));
4072 if (opts
->ignore_date
)
4073 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4076 strvec_push(&cmd
.args
, "merge");
4077 strvec_push(&cmd
.args
, "-s");
4079 strvec_push(&cmd
.args
, "octopus");
4081 strvec_push(&cmd
.args
, strategy
);
4082 for (k
= 0; k
< opts
->xopts_nr
; k
++)
4083 strvec_pushf(&cmd
.args
,
4084 "-X%s", opts
->xopts
[k
]);
4086 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4087 strvec_push(&cmd
.args
, "--no-edit");
4089 strvec_push(&cmd
.args
, "--edit");
4090 strvec_push(&cmd
.args
, "--no-ff");
4091 strvec_push(&cmd
.args
, "--no-log");
4092 strvec_push(&cmd
.args
, "--no-stat");
4093 strvec_push(&cmd
.args
, "-F");
4094 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4096 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4098 strvec_push(&cmd
.args
, "--no-gpg-sign");
4100 /* Add the tips to be merged */
4101 for (j
= to_merge
; j
; j
= j
->next
)
4102 strvec_push(&cmd
.args
,
4103 oid_to_hex(&j
->item
->object
.oid
));
4105 strbuf_release(&ref_name
);
4106 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4108 rollback_lock_file(&lock
);
4110 ret
= run_command(&cmd
);
4112 /* force re-reading of the cache */
4114 discard_index(r
->index
);
4115 if (repo_read_index(r
) < 0)
4116 ret
= error(_("could not read index"));
4121 merge_commit
= to_merge
->item
;
4122 bases
= repo_get_merge_bases(the_repository
, head_commit
,
4124 if (bases
&& oideq(&merge_commit
->object
.oid
,
4125 &bases
->item
->object
.oid
)) {
4127 /* skip merging an ancestor of HEAD */
4131 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4132 git_path_merge_head(r
), 0);
4133 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4135 bases
= reverse_commit_list(bases
);
4138 init_merge_options(&o
, r
);
4140 o
.branch2
= ref_name
.buf
;
4141 o
.buffer_output
= 2;
4143 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4145 * TODO: Should use merge_incore_recursive() and
4146 * merge_switch_to_result(), skipping the call to
4147 * merge_switch_to_result() when we don't actually need to
4148 * update the index and working copy immediately.
4150 ret
= merge_ort_recursive(&o
,
4151 head_commit
, merge_commit
, bases
,
4154 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4158 fputs(o
.obuf
.buf
, stdout
);
4159 strbuf_release(&o
.obuf
);
4161 error(_("could not even attempt to merge '%.*s'"),
4162 merge_arg_len
, arg
);
4166 * The return value of merge_recursive() is 1 on clean, and 0 on
4169 * Let's reverse that, so that do_merge() returns 0 upon success and
4170 * 1 upon failed merge (keeping the return value -1 for the cases where
4171 * we will want to reschedule the `merge` command).
4175 if (r
->index
->cache_changed
&&
4176 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4177 ret
= error(_("merge: Unable to write new index file"));
4181 rollback_lock_file(&lock
);
4183 repo_rerere(r
, opts
->allow_rerere_auto
);
4186 * In case of problems, we now want to return a positive
4187 * value (a negative one would indicate that the `merge`
4188 * command needs to be rescheduled).
4190 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4193 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4196 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4197 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4202 strbuf_release(&ref_name
);
4203 rollback_lock_file(&lock
);
4204 free_commit_list(to_merge
);
4208 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4211 struct lock_file lock
= LOCK_INIT
;
4213 struct string_list_item
*item
;
4216 path
= rebase_path_update_refs(the_repository
->gitdir
);
4218 if (!refs_to_oids
->nr
) {
4219 if (unlink(path
) && errno
!= ENOENT
)
4220 result
= error_errno(_("could not unlink: %s"), path
);
4224 if (safe_create_leading_directories(path
)) {
4225 result
= error(_("unable to create leading directories of %s"),
4230 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4231 result
= error(_("another 'rebase' process appears to be running; "
4232 "'%s.lock' already exists"),
4237 fp
= fdopen_lock_file(&lock
, "w");
4239 result
= error_errno(_("could not open '%s' for writing"), path
);
4240 rollback_lock_file(&lock
);
4244 for_each_string_list_item(item
, refs_to_oids
) {
4245 struct update_ref_record
*rec
= item
->util
;
4246 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4247 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4250 result
= commit_lock_file(&lock
);
4258 * Parse the update-refs file for the current rebase, then remove the
4259 * refs that do not appear in the todo_list (and have not had updated
4260 * values stored) and add refs that are in the todo_list but not
4261 * represented in the update-refs file.
4263 * If there are changes to the update-refs list, then write the new state
4266 void todo_list_filter_update_refs(struct repository
*r
,
4267 struct todo_list
*todo_list
)
4271 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4273 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4276 * For each item in the update_refs list, if it has no updated
4277 * value and does not appear in the todo_list, then remove it
4278 * from the update_refs list.
4280 for (i
= 0; i
< update_refs
.nr
; i
++) {
4283 const char *ref
= update_refs
.items
[i
].string
;
4284 size_t reflen
= strlen(ref
);
4285 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4287 /* OID already stored as updated. */
4288 if (!is_null_oid(&rec
->after
))
4291 for (j
= 0; !found
&& j
< todo_list
->total_nr
; j
++) {
4292 struct todo_item
*item
= &todo_list
->items
[j
];
4293 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4295 if (item
->command
!= TODO_UPDATE_REF
)
4298 if (item
->arg_len
!= reflen
||
4299 strncmp(arg
, ref
, reflen
))
4306 free(update_refs
.items
[i
].string
);
4307 free(update_refs
.items
[i
].util
);
4310 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4318 * For each todo_item, check if its ref is in the update_refs list.
4319 * If not, then add it as an un-updated ref.
4321 for (i
= 0; i
< todo_list
->total_nr
; i
++) {
4322 struct todo_item
*item
= &todo_list
->items
[i
];
4323 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4326 if (item
->command
!= TODO_UPDATE_REF
)
4329 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4330 const char *ref
= update_refs
.items
[j
].string
;
4332 found
= strlen(ref
) == item
->arg_len
&&
4333 !strncmp(ref
, arg
, item
->arg_len
);
4337 struct string_list_item
*inserted
;
4338 struct strbuf argref
= STRBUF_INIT
;
4340 strbuf_add(&argref
, arg
, item
->arg_len
);
4341 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4342 inserted
->util
= init_update_ref_record(argref
.buf
);
4343 strbuf_release(&argref
);
4349 write_update_refs_state(&update_refs
);
4350 string_list_clear(&update_refs
, 1);
4353 static int do_update_ref(struct repository
*r
, const char *refname
)
4355 struct string_list_item
*item
;
4356 struct string_list list
= STRING_LIST_INIT_DUP
;
4358 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4361 for_each_string_list_item(item
, &list
) {
4362 if (!strcmp(item
->string
, refname
)) {
4363 struct update_ref_record
*rec
= item
->util
;
4364 if (read_ref("HEAD", &rec
->after
))
4370 write_update_refs_state(&list
);
4371 string_list_clear(&list
, 1);
4375 static int do_update_refs(struct repository
*r
, int quiet
)
4378 struct string_list_item
*item
;
4379 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4380 struct ref_store
*refs
= get_main_ref_store(r
);
4381 struct strbuf update_msg
= STRBUF_INIT
;
4382 struct strbuf error_msg
= STRBUF_INIT
;
4384 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4387 for_each_string_list_item(item
, &refs_to_oids
) {
4388 struct update_ref_record
*rec
= item
->util
;
4391 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4393 &rec
->after
, &rec
->before
,
4394 0, UPDATE_REFS_MSG_ON_ERR
);
4401 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4403 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4407 (update_msg
.len
|| error_msg
.len
)) {
4409 _("Updated the following refs with %s:\n%s"),
4415 _("Failed to update the following refs with %s:\n%s"),
4420 string_list_clear(&refs_to_oids
, 1);
4421 strbuf_release(&update_msg
);
4422 strbuf_release(&error_msg
);
4426 static int is_final_fixup(struct todo_list
*todo_list
)
4428 int i
= todo_list
->current
;
4430 if (!is_fixup(todo_list
->items
[i
].command
))
4433 while (++i
< todo_list
->nr
)
4434 if (is_fixup(todo_list
->items
[i
].command
))
4436 else if (!is_noop(todo_list
->items
[i
].command
))
4441 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4445 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4446 if (!is_noop(todo_list
->items
[i
].command
))
4447 return todo_list
->items
[i
].command
;
4452 void create_autostash(struct repository
*r
, const char *path
)
4454 struct strbuf buf
= STRBUF_INIT
;
4455 struct lock_file lock_file
= LOCK_INIT
;
4458 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4459 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4461 repo_update_index_if_able(r
, &lock_file
);
4462 rollback_lock_file(&lock_file
);
4464 if (has_unstaged_changes(r
, 1) ||
4465 has_uncommitted_changes(r
, 1)) {
4466 struct child_process stash
= CHILD_PROCESS_INIT
;
4467 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4468 struct object_id oid
;
4470 strvec_pushl(&stash
.args
,
4471 "stash", "create", "autostash", NULL
);
4475 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4476 die(_("Cannot autostash"));
4477 strbuf_trim_trailing_newline(&buf
);
4478 if (repo_get_oid(the_repository
, buf
.buf
, &oid
))
4479 die(_("Unexpected stash response: '%s'"),
4482 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4484 if (safe_create_leading_directories_const(path
))
4485 die(_("Could not create directory for '%s'"),
4487 write_file(path
, "%s", oid_to_hex(&oid
));
4488 printf(_("Created autostash: %s\n"), buf
.buf
);
4489 if (reset_head(r
, &ropts
) < 0)
4490 die(_("could not reset --hard"));
4491 discard_index(r
->index
);
4492 if (repo_read_index(r
) < 0)
4493 die(_("could not read index"));
4495 strbuf_release(&buf
);
4498 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4500 struct child_process child
= CHILD_PROCESS_INIT
;
4503 if (attempt_apply
) {
4505 child
.no_stdout
= 1;
4506 child
.no_stderr
= 1;
4507 strvec_push(&child
.args
, "stash");
4508 strvec_push(&child
.args
, "apply");
4509 strvec_push(&child
.args
, stash_oid
);
4510 ret
= run_command(&child
);
4513 if (attempt_apply
&& !ret
)
4514 fprintf(stderr
, _("Applied autostash.\n"));
4516 struct child_process store
= CHILD_PROCESS_INIT
;
4519 strvec_push(&store
.args
, "stash");
4520 strvec_push(&store
.args
, "store");
4521 strvec_push(&store
.args
, "-m");
4522 strvec_push(&store
.args
, "autostash");
4523 strvec_push(&store
.args
, "-q");
4524 strvec_push(&store
.args
, stash_oid
);
4525 if (run_command(&store
))
4526 ret
= error(_("cannot store %s"), stash_oid
);
4530 "Your changes are safe in the stash.\n"
4531 "You can run \"git stash pop\" or"
4532 " \"git stash drop\" at any time.\n"),
4534 _("Applying autostash resulted in conflicts.") :
4535 _("Autostash exists; creating a new stash entry."));
4541 static int apply_save_autostash(const char *path
, int attempt_apply
)
4543 struct strbuf stash_oid
= STRBUF_INIT
;
4546 if (!read_oneliner(&stash_oid
, path
,
4547 READ_ONELINER_SKIP_IF_EMPTY
)) {
4548 strbuf_release(&stash_oid
);
4551 strbuf_trim(&stash_oid
);
4553 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4556 strbuf_release(&stash_oid
);
4560 int save_autostash(const char *path
)
4562 return apply_save_autostash(path
, 0);
4565 int apply_autostash(const char *path
)
4567 return apply_save_autostash(path
, 1);
4570 int apply_autostash_oid(const char *stash_oid
)
4572 return apply_save_autostash_oid(stash_oid
, 1);
4575 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4576 const char *onto_name
, const struct object_id
*onto
,
4577 const struct object_id
*orig_head
)
4579 struct reset_head_opts ropts
= {
4581 .orig_head
= orig_head
,
4582 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4583 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4584 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4586 .default_reflog_action
= sequencer_reflog_action(opts
)
4588 if (reset_head(r
, &ropts
)) {
4589 apply_autostash(rebase_path_autostash());
4590 sequencer_remove_state(opts
);
4591 return error(_("could not detach HEAD"));
4597 static int stopped_at_head(struct repository
*r
)
4599 struct object_id head
;
4600 struct commit
*commit
;
4601 struct commit_message message
;
4603 if (repo_get_oid(the_repository
, "HEAD", &head
) ||
4604 !(commit
= lookup_commit(r
, &head
)) ||
4605 repo_parse_commit(the_repository
, commit
) || get_message(commit
, &message
))
4606 fprintf(stderr
, _("Stopped at HEAD\n"));
4608 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4609 free_message(commit
, &message
);
4615 static int reread_todo_if_changed(struct repository
*r
,
4616 struct todo_list
*todo_list
,
4617 struct replay_opts
*opts
)
4620 struct strbuf buf
= STRBUF_INIT
;
4622 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4624 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4625 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4626 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4627 /* Reread the todo file if it has changed. */
4628 todo_list_release(todo_list
);
4629 if (read_populate_todo(r
, todo_list
, opts
))
4630 return -1; /* message was printed */
4631 /* `current` will be incremented on return */
4632 todo_list
->current
= -1;
4634 strbuf_release(&buf
);
4639 static const char rescheduled_advice
[] =
4640 N_("Could not execute the todo command\n"
4644 "It has been rescheduled; To edit the command before continuing, please\n"
4645 "edit the todo list first:\n"
4647 " git rebase --edit-todo\n"
4648 " git rebase --continue\n");
4650 static int pick_commits(struct repository
*r
,
4651 struct todo_list
*todo_list
,
4652 struct replay_opts
*opts
)
4654 int res
= 0, reschedule
= 0;
4656 opts
->reflog_message
= sequencer_reflog_action(opts
);
4658 assert(!(opts
->signoff
|| opts
->no_commit
||
4659 opts
->record_origin
|| should_edit(opts
) ||
4660 opts
->committer_date_is_author_date
||
4661 opts
->ignore_date
));
4662 if (read_and_refresh_cache(r
, opts
))
4665 while (todo_list
->current
< todo_list
->nr
) {
4666 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4667 const char *arg
= todo_item_get_arg(todo_list
, item
);
4670 if (save_todo(todo_list
, opts
))
4672 if (is_rebase_i(opts
)) {
4673 if (item
->command
!= TODO_COMMENT
) {
4674 FILE *f
= fopen(rebase_path_msgnum(), "w");
4676 todo_list
->done_nr
++;
4679 fprintf(f
, "%d\n", todo_list
->done_nr
);
4683 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4685 todo_list
->total_nr
,
4686 opts
->verbose
? "\n" : "\r");
4688 unlink(rebase_path_message());
4689 unlink(rebase_path_author_script());
4690 unlink(rebase_path_stopped_sha());
4691 unlink(rebase_path_amend());
4692 unlink(git_path_merge_head(r
));
4693 unlink(git_path_auto_merge(r
));
4694 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
4696 if (item
->command
== TODO_BREAK
) {
4699 return stopped_at_head(r
);
4702 if (item
->command
<= TODO_SQUASH
) {
4703 if (is_rebase_i(opts
))
4704 opts
->reflog_message
= reflog_message(opts
,
4705 command_to_string(item
->command
), NULL
);
4707 res
= do_pick_commit(r
, item
, opts
,
4708 is_final_fixup(todo_list
),
4710 if (is_rebase_i(opts
) && res
< 0) {
4712 advise(_(rescheduled_advice
),
4713 get_item_line_length(todo_list
,
4714 todo_list
->current
),
4715 get_item_line(todo_list
,
4716 todo_list
->current
));
4717 todo_list
->current
--;
4718 if (save_todo(todo_list
, opts
))
4721 if (item
->command
== TODO_EDIT
) {
4722 struct commit
*commit
= item
->commit
;
4727 _("Stopped at %s... %.*s\n"),
4728 short_commit_name(commit
),
4729 item
->arg_len
, arg
);
4731 return error_with_patch(r
, commit
,
4732 arg
, item
->arg_len
, opts
, res
, !res
);
4734 if (is_rebase_i(opts
) && !res
)
4735 record_in_rewritten(&item
->commit
->object
.oid
,
4736 peek_command(todo_list
, 1));
4737 if (res
&& is_fixup(item
->command
)) {
4740 return error_failed_squash(r
, item
->commit
, opts
,
4741 item
->arg_len
, arg
);
4742 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4744 struct object_id oid
;
4747 * If we are rewording and have either
4748 * fast-forwarded already, or are about to
4749 * create a new root commit, we want to amend,
4750 * otherwise we do not.
4752 if (item
->command
== TODO_REWORD
&&
4753 !repo_get_oid(the_repository
, "HEAD", &oid
) &&
4754 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4755 (opts
->have_squash_onto
&&
4756 oideq(&opts
->squash_onto
, &oid
))))
4759 return res
| error_with_patch(r
, item
->commit
,
4760 arg
, item
->arg_len
, opts
,
4763 } else if (item
->command
== TODO_EXEC
) {
4764 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4765 int saved
= *end_of_arg
;
4770 res
= do_exec(r
, arg
);
4771 *end_of_arg
= saved
;
4774 if (opts
->reschedule_failed_exec
)
4778 } else if (item
->command
== TODO_LABEL
) {
4779 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4781 } else if (item
->command
== TODO_RESET
) {
4782 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4784 } else if (item
->command
== TODO_MERGE
) {
4785 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4786 item
->flags
, &check_todo
, opts
)) < 0)
4788 else if (item
->commit
)
4789 record_in_rewritten(&item
->commit
->object
.oid
,
4790 peek_command(todo_list
, 1));
4792 /* failed with merge conflicts */
4793 return error_with_patch(r
, item
->commit
,
4796 } else if (item
->command
== TODO_UPDATE_REF
) {
4797 struct strbuf ref
= STRBUF_INIT
;
4798 strbuf_add(&ref
, arg
, item
->arg_len
);
4799 if ((res
= do_update_ref(r
, ref
.buf
)))
4801 strbuf_release(&ref
);
4802 } else if (!is_noop(item
->command
))
4803 return error(_("unknown command %d"), item
->command
);
4806 advise(_(rescheduled_advice
),
4807 get_item_line_length(todo_list
,
4808 todo_list
->current
),
4809 get_item_line(todo_list
, todo_list
->current
));
4810 todo_list
->current
--;
4811 if (save_todo(todo_list
, opts
))
4814 return error_with_patch(r
,
4818 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4819 reread_todo_if_changed(r
, todo_list
, opts
)) {
4823 todo_list
->current
++;
4828 if (is_rebase_i(opts
)) {
4829 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4832 /* Stopped in the middle, as planned? */
4833 if (todo_list
->current
< todo_list
->nr
)
4836 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4837 starts_with(head_ref
.buf
, "refs/")) {
4839 struct object_id head
, orig
;
4842 if (repo_get_oid(the_repository
, "HEAD", &head
)) {
4843 res
= error(_("cannot read HEAD"));
4845 strbuf_release(&head_ref
);
4846 strbuf_release(&buf
);
4849 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4850 get_oid_hex(buf
.buf
, &orig
)) {
4851 res
= error(_("could not read orig-head"));
4852 goto cleanup_head_ref
;
4855 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4856 res
= error(_("could not read 'onto'"));
4857 goto cleanup_head_ref
;
4859 msg
= reflog_message(opts
, "finish", "%s onto %s",
4860 head_ref
.buf
, buf
.buf
);
4861 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4862 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4863 res
= error(_("could not update %s"),
4865 goto cleanup_head_ref
;
4867 msg
= reflog_message(opts
, "finish", "returning to %s",
4869 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4870 res
= error(_("could not update HEAD to %s"),
4872 goto cleanup_head_ref
;
4877 if (opts
->verbose
) {
4878 struct rev_info log_tree_opt
;
4879 struct object_id orig
, head
;
4881 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4882 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4883 log_tree_opt
.diff
= 1;
4884 log_tree_opt
.diffopt
.output_format
=
4885 DIFF_FORMAT_DIFFSTAT
;
4886 log_tree_opt
.disable_stdin
= 1;
4888 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4889 !repo_get_oid(the_repository
, buf
.buf
, &orig
) &&
4890 !repo_get_oid(the_repository
, "HEAD", &head
)) {
4891 diff_tree_oid(&orig
, &head
, "",
4892 &log_tree_opt
.diffopt
);
4893 log_tree_diff_flush(&log_tree_opt
);
4895 release_revisions(&log_tree_opt
);
4897 flush_rewritten_pending();
4898 if (!stat(rebase_path_rewritten_list(), &st
) &&
4900 struct child_process child
= CHILD_PROCESS_INIT
;
4901 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4903 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4905 strvec_push(&child
.args
, "notes");
4906 strvec_push(&child
.args
, "copy");
4907 strvec_push(&child
.args
, "--for-rewrite=rebase");
4908 /* we don't care if this copying failed */
4909 run_command(&child
);
4911 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4912 strvec_push(&hook_opt
.args
, "rebase");
4913 run_hooks_opt("post-rewrite", &hook_opt
);
4915 apply_autostash(rebase_path_autostash());
4921 _("Successfully rebased and updated %s.\n"),
4925 strbuf_release(&buf
);
4926 strbuf_release(&head_ref
);
4928 if (do_update_refs(r
, opts
->quiet
))
4933 * Sequence of picks finished successfully; cleanup by
4934 * removing the .git/sequencer directory
4936 return sequencer_remove_state(opts
);
4939 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
4941 struct child_process cmd
= CHILD_PROCESS_INIT
;
4943 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
4944 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
4945 return error(_("no cherry-pick or revert in progress"));
4948 strvec_push(&cmd
.args
, "commit");
4951 * continue_single_pick() handles the case of recovering from a
4952 * conflict. should_edit() doesn't handle that case; for a conflict,
4953 * we want to edit if the user asked for it, or if they didn't specify
4954 * and stdin is a tty.
4956 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
4958 * Include --cleanup=strip as well because we don't want the
4959 * "# Conflicts:" messages.
4961 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
4963 return run_command(&cmd
);
4966 static int commit_staged_changes(struct repository
*r
,
4967 struct replay_opts
*opts
,
4968 struct todo_list
*todo_list
)
4970 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
4971 unsigned int final_fixup
= 0, is_clean
;
4973 if (has_unstaged_changes(r
, 1))
4974 return error(_("cannot rebase: You have unstaged changes."));
4976 is_clean
= !has_uncommitted_changes(r
, 0);
4978 if (file_exists(rebase_path_amend())) {
4979 struct strbuf rev
= STRBUF_INIT
;
4980 struct object_id head
, to_amend
;
4982 if (repo_get_oid(the_repository
, "HEAD", &head
))
4983 return error(_("cannot amend non-existing commit"));
4984 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
4985 return error(_("invalid file: '%s'"), rebase_path_amend());
4986 if (get_oid_hex(rev
.buf
, &to_amend
))
4987 return error(_("invalid contents: '%s'"),
4988 rebase_path_amend());
4989 if (!is_clean
&& !oideq(&head
, &to_amend
))
4990 return error(_("\nYou have uncommitted changes in your "
4991 "working tree. Please, commit them\n"
4992 "first and then run 'git rebase "
4993 "--continue' again."));
4995 * When skipping a failed fixup/squash, we need to edit the
4996 * commit message, the current fixup list and count, and if it
4997 * was the last fixup/squash in the chain, we need to clean up
4998 * the commit message and if there was a squash, let the user
5001 if (!is_clean
|| !opts
->current_fixup_count
)
5002 ; /* this is not the final fixup */
5003 else if (!oideq(&head
, &to_amend
) ||
5004 !file_exists(rebase_path_stopped_sha())) {
5005 /* was a final fixup or squash done manually? */
5006 if (!is_fixup(peek_command(todo_list
, 0))) {
5007 unlink(rebase_path_fixup_msg());
5008 unlink(rebase_path_squash_msg());
5009 unlink(rebase_path_current_fixups());
5010 strbuf_reset(&opts
->current_fixups
);
5011 opts
->current_fixup_count
= 0;
5014 /* we are in a fixup/squash chain */
5015 const char *p
= opts
->current_fixups
.buf
;
5016 int len
= opts
->current_fixups
.len
;
5018 opts
->current_fixup_count
--;
5020 BUG("Incorrect current_fixups:\n%s", p
);
5021 while (len
&& p
[len
- 1] != '\n')
5023 strbuf_setlen(&opts
->current_fixups
, len
);
5024 if (write_message(p
, len
, rebase_path_current_fixups(),
5026 return error(_("could not write file: '%s'"),
5027 rebase_path_current_fixups());
5030 * If a fixup/squash in a fixup/squash chain failed, the
5031 * commit message is already correct, no need to commit
5034 * Only if it is the final command in the fixup/squash
5035 * chain, and only if the chain is longer than a single
5036 * fixup/squash command (which was just skipped), do we
5037 * actually need to re-commit with a cleaned up commit
5040 if (opts
->current_fixup_count
> 0 &&
5041 !is_fixup(peek_command(todo_list
, 0))) {
5044 * If there was not a single "squash" in the
5045 * chain, we only need to clean up the commit
5046 * message, no need to bother the user with
5047 * opening the commit message in the editor.
5049 if (!starts_with(p
, "squash ") &&
5050 !strstr(p
, "\nsquash "))
5051 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5052 } else if (is_fixup(peek_command(todo_list
, 0))) {
5054 * We need to update the squash message to skip
5055 * the latest commit message.
5057 struct commit
*commit
;
5058 const char *path
= rebase_path_squash_msg();
5059 const char *encoding
= get_commit_output_encoding();
5061 if (parse_head(r
, &commit
) ||
5062 !(p
= repo_logmsg_reencode(the_repository
, commit
, NULL
, encoding
)) ||
5063 write_message(p
, strlen(p
), path
, 0)) {
5064 repo_unuse_commit_buffer(the_repository
,
5066 return error(_("could not write file: "
5069 repo_unuse_commit_buffer(the_repository
,
5074 strbuf_release(&rev
);
5079 if (refs_ref_exists(get_main_ref_store(r
),
5080 "CHERRY_PICK_HEAD") &&
5081 refs_delete_ref(get_main_ref_store(r
), "",
5082 "CHERRY_PICK_HEAD", NULL
, 0))
5083 return error(_("could not remove CHERRY_PICK_HEAD"));
5084 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5085 return error_errno(_("could not remove '%s'"),
5086 git_path_merge_msg(r
));
5091 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5093 return error(_("could not commit staged changes."));
5094 unlink(rebase_path_amend());
5095 unlink(git_path_merge_head(r
));
5096 unlink(git_path_auto_merge(r
));
5098 unlink(rebase_path_fixup_msg());
5099 unlink(rebase_path_squash_msg());
5101 if (opts
->current_fixup_count
> 0) {
5103 * Whether final fixup or not, we just cleaned up the commit
5106 unlink(rebase_path_current_fixups());
5107 strbuf_reset(&opts
->current_fixups
);
5108 opts
->current_fixup_count
= 0;
5113 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5115 struct todo_list todo_list
= TODO_LIST_INIT
;
5118 if (read_and_refresh_cache(r
, opts
))
5121 if (read_populate_opts(opts
))
5123 if (is_rebase_i(opts
)) {
5124 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5125 goto release_todo_list
;
5127 if (file_exists(rebase_path_dropped())) {
5128 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5129 goto release_todo_list
;
5131 unlink(rebase_path_dropped());
5134 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5135 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5137 goto release_todo_list
;
5139 } else if (!file_exists(get_todo_path(opts
)))
5140 return continue_single_pick(r
, opts
);
5141 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5142 goto release_todo_list
;
5144 if (!is_rebase_i(opts
)) {
5145 /* Verify that the conflict has been resolved */
5146 if (refs_ref_exists(get_main_ref_store(r
),
5147 "CHERRY_PICK_HEAD") ||
5148 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5149 res
= continue_single_pick(r
, opts
);
5151 goto release_todo_list
;
5153 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5154 res
= error_dirty_index(r
, opts
);
5155 goto release_todo_list
;
5157 todo_list
.current
++;
5158 } else if (file_exists(rebase_path_stopped_sha())) {
5159 struct strbuf buf
= STRBUF_INIT
;
5160 struct object_id oid
;
5162 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5163 READ_ONELINER_SKIP_IF_EMPTY
) &&
5164 !get_oid_hex(buf
.buf
, &oid
))
5165 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5166 strbuf_release(&buf
);
5169 res
= pick_commits(r
, &todo_list
, opts
);
5171 todo_list_release(&todo_list
);
5175 static int single_pick(struct repository
*r
,
5176 struct commit
*cmit
,
5177 struct replay_opts
*opts
)
5180 struct todo_item item
;
5182 item
.command
= opts
->action
== REPLAY_PICK
?
5183 TODO_PICK
: TODO_REVERT
;
5186 opts
->reflog_message
= sequencer_reflog_action(opts
);
5187 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5190 int sequencer_pick_revisions(struct repository
*r
,
5191 struct replay_opts
*opts
)
5193 struct todo_list todo_list
= TODO_LIST_INIT
;
5194 struct object_id oid
;
5198 if (read_and_refresh_cache(r
, opts
))
5201 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5202 struct object_id oid
;
5203 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5205 /* This happens when using --stdin. */
5209 if (!repo_get_oid(the_repository
, name
, &oid
)) {
5210 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5211 enum object_type type
= oid_object_info(r
,
5214 return error(_("%s: can't cherry-pick a %s"),
5215 name
, type_name(type
));
5218 return error(_("%s: bad revision"), name
);
5222 * If we were called as "git cherry-pick <commit>", just
5223 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5224 * REVERT_HEAD, and don't touch the sequencer state.
5225 * This means it is possible to cherry-pick in the middle
5226 * of a cherry-pick sequence.
5228 if (opts
->revs
->cmdline
.nr
== 1 &&
5229 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5230 opts
->revs
->no_walk
&&
5231 !opts
->revs
->cmdline
.rev
->flags
) {
5232 struct commit
*cmit
;
5233 if (prepare_revision_walk(opts
->revs
))
5234 return error(_("revision walk setup failed"));
5235 cmit
= get_revision(opts
->revs
);
5237 return error(_("empty commit set passed"));
5238 if (get_revision(opts
->revs
))
5239 BUG("unexpected extra commit from walk");
5240 return single_pick(r
, cmit
, opts
);
5244 * Start a new cherry-pick/ revert sequence; but
5245 * first, make sure that an existing one isn't in
5249 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5250 create_seq_dir(r
) < 0)
5252 if (repo_get_oid(the_repository
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5253 return error(_("can't revert as initial commit"));
5254 if (save_head(oid_to_hex(&oid
)))
5256 if (save_opts(opts
))
5258 update_abort_safety_file();
5259 res
= pick_commits(r
, &todo_list
, opts
);
5260 todo_list_release(&todo_list
);
5264 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5266 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5267 struct strbuf sob
= STRBUF_INIT
;
5270 strbuf_addstr(&sob
, sign_off_header
);
5271 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5272 strbuf_addch(&sob
, '\n');
5275 strbuf_complete_line(msgbuf
);
5278 * If the whole message buffer is equal to the sob, pretend that we
5279 * found a conforming footer with a matching sob
5281 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5282 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5285 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5288 const char *append_newlines
= NULL
;
5289 size_t len
= msgbuf
->len
- ignore_footer
;
5293 * The buffer is completely empty. Leave foom for
5294 * the title and body to be filled in by the user.
5296 append_newlines
= "\n\n";
5297 } else if (len
== 1) {
5299 * Buffer contains a single newline. Add another
5300 * so that we leave room for the title and body.
5302 append_newlines
= "\n";
5303 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5305 * Buffer ends with a single newline. Add another
5306 * so that there is an empty line between the message
5309 append_newlines
= "\n";
5310 } /* else, the buffer already ends with two newlines. */
5312 if (append_newlines
)
5313 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5314 append_newlines
, strlen(append_newlines
));
5317 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5318 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5321 strbuf_release(&sob
);
5324 struct labels_entry
{
5325 struct hashmap_entry entry
;
5326 char label
[FLEX_ARRAY
];
5329 static int labels_cmp(const void *fndata UNUSED
,
5330 const struct hashmap_entry
*eptr
,
5331 const struct hashmap_entry
*entry_or_key
, const void *key
)
5333 const struct labels_entry
*a
, *b
;
5335 a
= container_of(eptr
, const struct labels_entry
, entry
);
5336 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5338 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5341 struct string_entry
{
5342 struct oidmap_entry entry
;
5343 char string
[FLEX_ARRAY
];
5346 struct label_state
{
5347 struct oidmap commit2label
;
5348 struct hashmap labels
;
5352 static const char *label_oid(struct object_id
*oid
, const char *label
,
5353 struct label_state
*state
)
5355 struct labels_entry
*labels_entry
;
5356 struct string_entry
*string_entry
;
5357 struct object_id dummy
;
5360 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5362 return string_entry
->string
;
5365 * For "uninteresting" commits, i.e. commits that are not to be
5366 * rebased, and which can therefore not be labeled, we use a unique
5367 * abbreviation of the commit name. This is slightly more complicated
5368 * than calling repo_find_unique_abbrev() because we also need to make
5369 * sure that the abbreviation does not conflict with any other
5372 * We disallow "interesting" commits to be labeled by a string that
5373 * is a valid full-length hash, to ensure that we always can find an
5374 * abbreviation for any uninteresting commit's names that does not
5375 * clash with any other label.
5377 strbuf_reset(&state
->buf
);
5381 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5382 label
= p
= state
->buf
.buf
;
5384 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5388 * We may need to extend the abbreviated hash so that there is
5389 * no conflicting label.
5391 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5392 size_t i
= strlen(p
) + 1;
5394 oid_to_hex_r(p
, oid
);
5395 for (; i
< the_hash_algo
->hexsz
; i
++) {
5398 if (!hashmap_get_from_hash(&state
->labels
,
5405 struct strbuf
*buf
= &state
->buf
;
5408 * Sanitize labels by replacing non-alpha-numeric characters
5409 * (including white-space ones) by dashes, as they might be
5410 * illegal in file names (and hence in ref names).
5412 * Note that we retain non-ASCII UTF-8 characters (identified
5413 * via the most significant bit). They should be all acceptable
5414 * in file names. We do not validate the UTF-8 here, that's not
5415 * the job of this function.
5417 for (; *label
; label
++)
5418 if ((*label
& 0x80) || isalnum(*label
))
5419 strbuf_addch(buf
, *label
);
5420 /* avoid leading dash and double-dashes */
5421 else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5422 strbuf_addch(buf
, '-');
5424 strbuf_addstr(buf
, "rev-");
5425 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5429 if ((buf
->len
== the_hash_algo
->hexsz
&&
5430 !get_oid_hex(label
, &dummy
)) ||
5431 (buf
->len
== 1 && *label
== '#') ||
5432 hashmap_get_from_hash(&state
->labels
,
5433 strihash(label
), label
)) {
5435 * If the label already exists, or if the label is a
5436 * valid full OID, or the label is a '#' (which we use
5437 * as a separator between merge heads and oneline), we
5438 * append a dash and a number to make it unique.
5440 size_t len
= buf
->len
;
5442 for (i
= 2; ; i
++) {
5443 strbuf_setlen(buf
, len
);
5444 strbuf_addf(buf
, "-%d", i
);
5445 if (!hashmap_get_from_hash(&state
->labels
,
5455 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5456 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5457 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5459 FLEX_ALLOC_STR(string_entry
, string
, label
);
5460 oidcpy(&string_entry
->entry
.oid
, oid
);
5461 oidmap_put(&state
->commit2label
, string_entry
);
5463 return string_entry
->string
;
5466 static int make_script_with_merges(struct pretty_print_context
*pp
,
5467 struct rev_info
*revs
, struct strbuf
*out
,
5470 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5471 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5472 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5473 int skipped_commit
= 0;
5474 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5475 struct strbuf label
= STRBUF_INIT
;
5476 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5477 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5478 struct commit
*commit
;
5479 struct oidmap commit2todo
= OIDMAP_INIT
;
5480 struct string_entry
*entry
;
5481 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5482 shown
= OIDSET_INIT
;
5483 struct label_state state
= { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
};
5485 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5486 const char *cmd_pick
= abbr
? "p" : "pick",
5487 *cmd_label
= abbr
? "l" : "label",
5488 *cmd_reset
= abbr
? "t" : "reset",
5489 *cmd_merge
= abbr
? "m" : "merge";
5491 oidmap_init(&commit2todo
, 0);
5492 oidmap_init(&state
.commit2label
, 0);
5493 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5494 strbuf_init(&state
.buf
, 32);
5496 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5497 struct labels_entry
*onto_label_entry
;
5498 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5499 FLEX_ALLOC_STR(entry
, string
, "onto");
5500 oidcpy(&entry
->entry
.oid
, oid
);
5501 oidmap_put(&state
.commit2label
, entry
);
5503 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5504 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5505 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5510 * - get onelines for all commits
5511 * - gather all branch tips (i.e. 2nd or later parents of merges)
5512 * - label all branch tips
5514 while ((commit
= get_revision(revs
))) {
5515 struct commit_list
*to_merge
;
5516 const char *p1
, *p2
;
5517 struct object_id
*oid
;
5520 tail
= &commit_list_insert(commit
, tail
)->next
;
5521 oidset_insert(&interesting
, &commit
->object
.oid
);
5523 is_empty
= is_original_commit_empty(commit
);
5524 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5525 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5526 warning(_("skipped previously applied commit %s"),
5527 short_commit_name(commit
));
5531 if (is_empty
&& !keep_empty
)
5534 strbuf_reset(&oneline
);
5535 pretty_print_commit(pp
, commit
, &oneline
);
5537 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5539 /* non-merge commit: easy case */
5541 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5542 oid_to_hex(&commit
->object
.oid
),
5545 strbuf_addf(&buf
, " %c empty",
5548 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5549 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5550 oidmap_put(&commit2todo
, entry
);
5555 /* Create a label */
5556 strbuf_reset(&label
);
5557 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5558 (p1
= strchr(p1
, '\'')) &&
5559 (p2
= strchr(++p1
, '\'')))
5560 strbuf_add(&label
, p1
, p2
- p1
);
5561 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5563 (p1
= strstr(p1
, " from ")))
5564 strbuf_addstr(&label
, p1
+ strlen(" from "));
5566 strbuf_addbuf(&label
, &oneline
);
5569 strbuf_addf(&buf
, "%s -C %s",
5570 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5572 /* label the tips of merged branches */
5573 for (; to_merge
; to_merge
= to_merge
->next
) {
5574 oid
= &to_merge
->item
->object
.oid
;
5575 strbuf_addch(&buf
, ' ');
5577 if (!oidset_contains(&interesting
, oid
)) {
5578 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5583 tips_tail
= &commit_list_insert(to_merge
->item
,
5586 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5588 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5590 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5591 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5592 oidmap_put(&commit2todo
, entry
);
5595 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5596 _("use --reapply-cherry-picks to include skipped commits"));
5600 * - label branch points
5601 * - add HEAD to the branch tips
5603 for (iter
= commits
; iter
; iter
= iter
->next
) {
5604 struct commit_list
*parent
= iter
->item
->parents
;
5605 for (; parent
; parent
= parent
->next
) {
5606 struct object_id
*oid
= &parent
->item
->object
.oid
;
5607 if (!oidset_contains(&interesting
, oid
))
5609 if (oidset_insert(&child_seen
, oid
))
5610 label_oid(oid
, "branch-point", &state
);
5613 /* Add HEAD as implicit "tip of branch" */
5615 tips_tail
= &commit_list_insert(iter
->item
,
5620 * Third phase: output the todo list. This is a bit tricky, as we
5621 * want to avoid jumping back and forth between revisions. To
5622 * accomplish that goal, we walk backwards from the branch tips,
5623 * gathering commits not yet shown, reversing the list on the fly,
5624 * then outputting that list (labeling revisions as needed).
5626 strbuf_addf(out
, "%s onto\n", cmd_label
);
5627 for (iter
= tips
; iter
; iter
= iter
->next
) {
5628 struct commit_list
*list
= NULL
, *iter2
;
5630 commit
= iter
->item
;
5631 if (oidset_contains(&shown
, &commit
->object
.oid
))
5633 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5636 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5638 strbuf_addch(out
, '\n');
5640 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5641 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5642 commit_list_insert(commit
, &list
);
5643 if (!commit
->parents
) {
5647 commit
= commit
->parents
->item
;
5651 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5652 rebase_cousins
|| root_with_onto
?
5653 "onto" : "[new root]");
5655 const char *to
= NULL
;
5657 entry
= oidmap_get(&state
.commit2label
,
5658 &commit
->object
.oid
);
5661 else if (!rebase_cousins
)
5662 to
= label_oid(&commit
->object
.oid
, NULL
,
5665 if (!to
|| !strcmp(to
, "onto"))
5666 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5668 strbuf_reset(&oneline
);
5669 pretty_print_commit(pp
, commit
, &oneline
);
5670 strbuf_addf(out
, "%s %s # %s\n",
5671 cmd_reset
, to
, oneline
.buf
);
5675 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5676 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5677 entry
= oidmap_get(&commit2todo
, oid
);
5678 /* only show if not already upstream */
5680 strbuf_addf(out
, "%s\n", entry
->string
);
5681 entry
= oidmap_get(&state
.commit2label
, oid
);
5683 strbuf_addf(out
, "%s %s\n",
5684 cmd_label
, entry
->string
);
5685 oidset_insert(&shown
, oid
);
5688 free_commit_list(list
);
5691 free_commit_list(commits
);
5692 free_commit_list(tips
);
5694 strbuf_release(&label
);
5695 strbuf_release(&oneline
);
5696 strbuf_release(&buf
);
5698 oidmap_free(&commit2todo
, 1);
5699 oidmap_free(&state
.commit2label
, 1);
5700 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5701 strbuf_release(&state
.buf
);
5706 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5707 const char **argv
, unsigned flags
)
5709 char *format
= NULL
;
5710 struct pretty_print_context pp
= {0};
5711 struct rev_info revs
;
5712 struct commit
*commit
;
5713 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5714 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5715 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5716 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5717 int skipped_commit
= 0;
5720 repo_init_revisions(r
, &revs
, NULL
);
5721 revs
.verbose_header
= 1;
5723 revs
.max_parents
= 1;
5724 revs
.cherry_mark
= !reapply_cherry_picks
;
5727 revs
.right_only
= 1;
5728 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5729 revs
.topo_order
= 1;
5731 revs
.pretty_given
= 1;
5732 git_config_get_string("rebase.instructionFormat", &format
);
5733 if (!format
|| !*format
) {
5735 format
= xstrdup("%s");
5737 get_commit_format(format
, &revs
);
5739 pp
.fmt
= revs
.commit_format
;
5740 pp
.output_encoding
= get_log_output_encoding();
5742 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5743 ret
= error(_("make_script: unhandled options"));
5747 if (prepare_revision_walk(&revs
) < 0) {
5748 ret
= error(_("make_script: error preparing revisions"));
5752 if (rebase_merges
) {
5753 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5757 while ((commit
= get_revision(&revs
))) {
5758 int is_empty
= is_original_commit_empty(commit
);
5760 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5761 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5762 warning(_("skipped previously applied commit %s"),
5763 short_commit_name(commit
));
5767 if (is_empty
&& !keep_empty
)
5769 strbuf_addf(out
, "%s %s ", insn
,
5770 oid_to_hex(&commit
->object
.oid
));
5771 pretty_print_commit(&pp
, commit
, out
);
5773 strbuf_addf(out
, " %c empty", comment_line_char
);
5774 strbuf_addch(out
, '\n');
5777 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5778 _("use --reapply-cherry-picks to include skipped commits"));
5780 release_revisions(&revs
);
5785 * Add commands after pick and (series of) squash/fixup commands
5788 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5789 struct string_list
*commands
)
5791 struct strbuf
*buf
= &todo_list
->buf
;
5792 size_t base_offset
= buf
->len
;
5793 int i
, insert
, nr
= 0, alloc
= 0;
5794 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5796 CALLOC_ARRAY(base_items
, commands
->nr
);
5797 for (i
= 0; i
< commands
->nr
; i
++) {
5798 size_t command_len
= strlen(commands
->items
[i
].string
);
5800 strbuf_addstr(buf
, commands
->items
[i
].string
);
5801 strbuf_addch(buf
, '\n');
5803 base_items
[i
].command
= TODO_EXEC
;
5804 base_items
[i
].offset_in_buf
= base_offset
;
5805 base_items
[i
].arg_offset
= base_offset
;
5806 base_items
[i
].arg_len
= command_len
;
5808 base_offset
+= command_len
+ 1;
5812 * Insert <commands> after every pick. Here, fixup/squash chains
5813 * are considered part of the pick, so we insert the commands *after*
5814 * those chains if there are any.
5816 * As we insert the exec commands immediately after rearranging
5817 * any fixups and before the user edits the list, a fixup chain
5818 * can never contain comments (any comments are empty picks that
5819 * have been commented out because the user did not specify
5820 * --keep-empty). So, it is safe to insert an exec command
5821 * without looking at the command following a comment.
5824 for (i
= 0; i
< todo_list
->nr
; i
++) {
5825 enum todo_command command
= todo_list
->items
[i
].command
;
5826 if (insert
&& !is_fixup(command
)) {
5827 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5828 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5834 ALLOC_GROW(items
, nr
+ 1, alloc
);
5835 items
[nr
++] = todo_list
->items
[i
];
5837 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5841 /* insert or append final <commands> */
5843 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5844 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5849 FREE_AND_NULL(todo_list
->items
);
5850 todo_list
->items
= items
;
5852 todo_list
->alloc
= alloc
;
5855 static void todo_list_to_strbuf(struct repository
*r
, struct todo_list
*todo_list
,
5856 struct strbuf
*buf
, int num
, unsigned flags
)
5858 struct todo_item
*item
;
5859 int i
, max
= todo_list
->nr
;
5861 if (num
> 0 && num
< max
)
5864 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5867 /* if the item is not a command write it and continue */
5868 if (item
->command
>= TODO_COMMENT
) {
5869 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5870 todo_item_get_arg(todo_list
, item
));
5874 /* add command to the buffer */
5875 cmd
= command_to_char(item
->command
);
5876 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5877 strbuf_addch(buf
, cmd
);
5879 strbuf_addstr(buf
, command_to_string(item
->command
));
5883 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5884 short_commit_name(item
->commit
) :
5885 oid_to_hex(&item
->commit
->object
.oid
);
5887 if (item
->command
== TODO_FIXUP
) {
5888 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
5889 strbuf_addstr(buf
, " -c");
5890 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
5891 strbuf_addstr(buf
, " -C");
5895 if (item
->command
== TODO_MERGE
) {
5896 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5897 strbuf_addstr(buf
, " -c");
5899 strbuf_addstr(buf
, " -C");
5902 strbuf_addf(buf
, " %s", oid
);
5905 /* add all the rest */
5907 strbuf_addch(buf
, '\n');
5909 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5910 todo_item_get_arg(todo_list
, item
));
5914 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5915 const char *file
, const char *shortrevisions
,
5916 const char *shortonto
, int num
, unsigned flags
)
5919 struct strbuf buf
= STRBUF_INIT
;
5921 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5922 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5923 append_todo_help(count_commands(todo_list
),
5924 shortrevisions
, shortonto
, &buf
);
5926 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5927 strbuf_release(&buf
);
5932 /* skip picking commits whose parents are unchanged */
5933 static int skip_unnecessary_picks(struct repository
*r
,
5934 struct todo_list
*todo_list
,
5935 struct object_id
*base_oid
)
5937 struct object_id
*parent_oid
;
5940 for (i
= 0; i
< todo_list
->nr
; i
++) {
5941 struct todo_item
*item
= todo_list
->items
+ i
;
5943 if (item
->command
>= TODO_NOOP
)
5945 if (item
->command
!= TODO_PICK
)
5947 if (repo_parse_commit(the_repository
, item
->commit
)) {
5948 return error(_("could not parse commit '%s'"),
5949 oid_to_hex(&item
->commit
->object
.oid
));
5951 if (!item
->commit
->parents
)
5952 break; /* root commit */
5953 if (item
->commit
->parents
->next
)
5954 break; /* merge commit */
5955 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
5956 if (!oideq(parent_oid
, base_oid
))
5958 oidcpy(base_oid
, &item
->commit
->object
.oid
);
5961 const char *done_path
= rebase_path_done();
5963 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
5964 error_errno(_("could not write to '%s'"), done_path
);
5968 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
5970 todo_list
->current
= 0;
5971 todo_list
->done_nr
+= i
;
5973 if (is_fixup(peek_command(todo_list
, 0)))
5974 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
5980 struct todo_add_branch_context
{
5981 struct todo_item
*items
;
5985 struct commit
*commit
;
5986 struct string_list refs_to_oids
;
5989 static int add_decorations_to_list(const struct commit
*commit
,
5990 struct todo_add_branch_context
*ctx
)
5992 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
5993 const char *head_ref
= resolve_ref_unsafe("HEAD",
5994 RESOLVE_REF_READING
,
5998 while (decoration
) {
5999 struct todo_item
*item
;
6001 size_t base_offset
= ctx
->buf
->len
;
6004 * If the branch is the current HEAD, then it will be
6005 * updated by the default rebase behavior.
6007 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6008 decoration
= decoration
->next
;
6012 ALLOC_GROW(ctx
->items
,
6015 item
= &ctx
->items
[ctx
->items_nr
];
6016 memset(item
, 0, sizeof(*item
));
6018 /* If the branch is checked out, then leave a comment instead. */
6019 if ((path
= branch_checked_out(decoration
->name
))) {
6020 item
->command
= TODO_COMMENT
;
6021 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6022 decoration
->name
, path
);
6024 struct string_list_item
*sti
;
6025 item
->command
= TODO_UPDATE_REF
;
6026 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6028 sti
= string_list_insert(&ctx
->refs_to_oids
,
6030 sti
->util
= init_update_ref_record(decoration
->name
);
6033 item
->offset_in_buf
= base_offset
;
6034 item
->arg_offset
= base_offset
;
6035 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6038 decoration
= decoration
->next
;
6045 * For each 'pick' command, find out if the commit has a decoration in
6046 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6048 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6051 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6052 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6053 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6054 struct decoration_filter decoration_filter
= {
6055 .include_ref_pattern
= &decorate_refs_include
,
6056 .exclude_ref_pattern
= &decorate_refs_exclude
,
6057 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6059 struct todo_add_branch_context ctx
= {
6060 .buf
= &todo_list
->buf
,
6061 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6064 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6065 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6067 string_list_append(&decorate_refs_include
, "refs/heads/");
6068 load_ref_decorations(&decoration_filter
, 0);
6070 for (i
= 0; i
< todo_list
->nr
; ) {
6071 struct todo_item
*item
= &todo_list
->items
[i
];
6073 /* insert ith item into new list */
6074 ALLOC_GROW(ctx
.items
,
6078 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6081 ctx
.commit
= item
->commit
;
6082 add_decorations_to_list(item
->commit
, &ctx
);
6086 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6088 string_list_clear(&ctx
.refs_to_oids
, 1);
6091 /* we failed, so clean up the new list. */
6096 free(todo_list
->items
);
6097 todo_list
->items
= ctx
.items
;
6098 todo_list
->nr
= ctx
.items_nr
;
6099 todo_list
->alloc
= ctx
.items_alloc
;
6104 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6105 const char *shortrevisions
, const char *onto_name
,
6106 struct commit
*onto
, const struct object_id
*orig_head
,
6107 struct string_list
*commands
, unsigned autosquash
,
6108 unsigned update_refs
,
6109 struct todo_list
*todo_list
)
6111 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6112 const char *todo_file
= rebase_path_todo();
6113 struct todo_list new_todo
= TODO_LIST_INIT
;
6114 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6115 struct object_id oid
= onto
->object
.oid
;
6118 repo_find_unique_abbrev_r(the_repository
, shortonto
, &oid
,
6121 if (buf
->len
== 0) {
6122 struct todo_item
*item
= append_new_todo(todo_list
);
6123 item
->command
= TODO_NOOP
;
6124 item
->commit
= NULL
;
6125 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6128 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6131 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6135 todo_list_add_exec_commands(todo_list
, commands
);
6137 if (count_commands(todo_list
) == 0) {
6138 apply_autostash(rebase_path_autostash());
6139 sequencer_remove_state(opts
);
6141 return error(_("nothing to do"));
6144 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6148 else if (res
== -2) {
6149 apply_autostash(rebase_path_autostash());
6150 sequencer_remove_state(opts
);
6153 } else if (res
== -3) {
6154 apply_autostash(rebase_path_autostash());
6155 sequencer_remove_state(opts
);
6156 todo_list_release(&new_todo
);
6158 return error(_("nothing to do"));
6159 } else if (res
== -4) {
6160 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6161 todo_list_release(&new_todo
);
6166 /* Expand the commit IDs */
6167 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6168 strbuf_swap(&new_todo
.buf
, &buf2
);
6169 strbuf_release(&buf2
);
6170 new_todo
.total_nr
-= new_todo
.nr
;
6171 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6172 BUG("invalid todo list after expanding IDs:\n%s",
6175 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6176 todo_list_release(&new_todo
);
6177 return error(_("could not skip unnecessary pick commands"));
6180 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6181 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6182 todo_list_release(&new_todo
);
6183 return error_errno(_("could not write '%s'"), todo_file
);
6188 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6191 if (require_clean_work_tree(r
, "rebase", "", 1, 1))
6194 todo_list_write_total_nr(&new_todo
);
6195 res
= pick_commits(r
, &new_todo
, opts
);
6198 todo_list_release(&new_todo
);
6203 struct subject2item_entry
{
6204 struct hashmap_entry entry
;
6206 char subject
[FLEX_ARRAY
];
6209 static int subject2item_cmp(const void *fndata UNUSED
,
6210 const struct hashmap_entry
*eptr
,
6211 const struct hashmap_entry
*entry_or_key
,
6214 const struct subject2item_entry
*a
, *b
;
6216 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6217 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6219 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6222 define_commit_slab(commit_todo_item
, struct todo_item
*);
6224 static int skip_fixupish(const char *subject
, const char **p
) {
6225 return skip_prefix(subject
, "fixup! ", p
) ||
6226 skip_prefix(subject
, "amend! ", p
) ||
6227 skip_prefix(subject
, "squash! ", p
);
6231 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6232 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6233 * after the former, and change "pick" to "fixup"/"squash".
6235 * Note that if the config has specified a custom instruction format, each log
6236 * message will have to be retrieved from the commit (as the oneline in the
6237 * script cannot be trusted) in order to normalize the autosquash arrangement.
6239 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6241 struct hashmap subject2item
;
6242 int rearranged
= 0, *next
, *tail
, i
, nr
= 0, alloc
= 0;
6244 struct commit_todo_item commit_todo
;
6245 struct todo_item
*items
= NULL
;
6247 init_commit_todo_item(&commit_todo
);
6249 * The hashmap maps onelines to the respective todo list index.
6251 * If any items need to be rearranged, the next[i] value will indicate
6252 * which item was moved directly after the i'th.
6254 * In that case, last[i] will indicate the index of the latest item to
6255 * be moved to appear after the i'th.
6257 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6258 ALLOC_ARRAY(next
, todo_list
->nr
);
6259 ALLOC_ARRAY(tail
, todo_list
->nr
);
6260 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6261 for (i
= 0; i
< todo_list
->nr
; i
++) {
6262 struct strbuf buf
= STRBUF_INIT
;
6263 struct todo_item
*item
= todo_list
->items
+ i
;
6264 const char *commit_buffer
, *subject
, *p
;
6267 struct subject2item_entry
*entry
;
6269 next
[i
] = tail
[i
] = -1;
6270 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6275 if (is_fixup(item
->command
)) {
6276 clear_commit_todo_item(&commit_todo
);
6277 return error(_("the script was already rearranged."));
6280 repo_parse_commit(the_repository
, item
->commit
);
6281 commit_buffer
= repo_logmsg_reencode(the_repository
,
6284 find_commit_subject(commit_buffer
, &subject
);
6285 format_subject(&buf
, subject
, " ");
6286 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6287 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6289 if (skip_fixupish(subject
, &p
)) {
6290 struct commit
*commit2
;
6295 if (!skip_fixupish(p
, &p
))
6299 entry
= hashmap_get_entry_from_hash(&subject2item
,
6301 struct subject2item_entry
,
6304 /* found by title */
6306 else if (!strchr(p
, ' ') &&
6308 lookup_commit_reference_by_name(p
)) &&
6309 *commit_todo_item_at(&commit_todo
, commit2
))
6310 /* found by commit name */
6311 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6314 /* copy can be a prefix of the commit subject */
6315 for (i2
= 0; i2
< i
; i2
++)
6317 starts_with(subjects
[i2
], p
))
6325 if (starts_with(subject
, "fixup!")) {
6326 todo_list
->items
[i
].command
= TODO_FIXUP
;
6327 } else if (starts_with(subject
, "amend!")) {
6328 todo_list
->items
[i
].command
= TODO_FIXUP
;
6329 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6331 todo_list
->items
[i
].command
= TODO_SQUASH
;
6337 next
[i
] = next
[tail
[i2
]];
6341 } else if (!hashmap_get_from_hash(&subject2item
,
6342 strhash(subject
), subject
)) {
6343 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6345 hashmap_entry_init(&entry
->entry
,
6346 strhash(entry
->subject
));
6347 hashmap_put(&subject2item
, &entry
->entry
);
6350 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6354 for (i
= 0; i
< todo_list
->nr
; i
++) {
6355 enum todo_command command
= todo_list
->items
[i
].command
;
6359 * Initially, all commands are 'pick's. If it is a
6360 * fixup or a squash now, we have rearranged it.
6362 if (is_fixup(command
))
6366 ALLOC_GROW(items
, nr
+ 1, alloc
);
6367 items
[nr
++] = todo_list
->items
[cur
];
6372 FREE_AND_NULL(todo_list
->items
);
6373 todo_list
->items
= items
;
6375 todo_list
->alloc
= alloc
;
6380 for (i
= 0; i
< todo_list
->nr
; i
++)
6383 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6385 clear_commit_todo_item(&commit_todo
);
6390 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6392 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6393 struct object_id cherry_pick_head
, rebase_head
;
6395 if (file_exists(git_path_seq_dir()))
6396 *whence
= FROM_CHERRY_PICK_MULTI
;
6397 if (file_exists(rebase_path()) &&
6398 !repo_get_oid(the_repository
, "REBASE_HEAD", &rebase_head
) &&
6399 !repo_get_oid(the_repository
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6400 oideq(&rebase_head
, &cherry_pick_head
))
6401 *whence
= FROM_REBASE_PICK
;
6403 *whence
= FROM_CHERRY_PICK_SINGLE
;
6411 int sequencer_get_update_refs_state(const char *wt_dir
,
6412 struct string_list
*refs
)
6416 struct strbuf ref
= STRBUF_INIT
;
6417 struct strbuf hash
= STRBUF_INIT
;
6418 struct update_ref_record
*rec
= NULL
;
6420 char *path
= rebase_path_update_refs(wt_dir
);
6422 fp
= fopen(path
, "r");
6426 while (strbuf_getline(&ref
, fp
) != EOF
) {
6427 struct string_list_item
*item
;
6429 CALLOC_ARRAY(rec
, 1);
6431 if (strbuf_getline(&hash
, fp
) == EOF
||
6432 get_oid_hex(hash
.buf
, &rec
->before
)) {
6433 warning(_("update-refs file at '%s' is invalid"),
6439 if (strbuf_getline(&hash
, fp
) == EOF
||
6440 get_oid_hex(hash
.buf
, &rec
->after
)) {
6441 warning(_("update-refs file at '%s' is invalid"),
6447 item
= string_list_insert(refs
, ref
.buf
);
6457 strbuf_release(&ref
);
6458 strbuf_release(&hash
);