1 #include "git-compat-util.h"
6 #include "environment.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
17 #include "sequencer.h"
18 #include "run-command.h"
21 #include "cache-tree.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
30 #include "sparse-index.h"
35 #include "wt-status.h"
37 #include "notes-utils.h"
39 #include "unpack-trees.h"
42 #include "commit-slab.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
49 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 * To accommodate common filesystem limitations, where the loose refs' file
53 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
54 * --rebase-merges` need to be truncated if the corresponding commit subjects
56 * Add some margin to stay clear from reaching `NAME_MAX`.
58 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
60 static const char sign_off_header
[] = "Signed-off-by: ";
61 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
63 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
65 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
67 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
68 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
69 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
70 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
72 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
74 * The file containing rebase commands, comments, and empty lines.
75 * This file is created by "git rebase -i" then edited by the user. As
76 * the lines are processed, they are removed from the front of this
77 * file and written to the tail of 'done'.
79 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
80 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
82 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
85 * The rebase command lines that have already been processed. A line
86 * is moved here when it is first handled, before any associated user
89 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
91 * The file to keep track of how many commands were already processed (e.g.
94 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
96 * The file to keep track of how many commands are to be processed in total
97 * (e.g. for the prompt).
99 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
101 * The commit message that is planned to be used for any changes that
102 * need to be committed following a user interaction.
104 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
106 * The file into which is accumulated the suggested commit message for
107 * squash/fixup commands. When the first of a series of squash/fixups
108 * is seen, the file is created and the commit message from the
109 * previous commit and from the first squash/fixup commit are written
110 * to it. The commit message for each subsequent squash/fixup commit
111 * is appended to the file as it is processed.
113 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
115 * If the current series of squash/fixups has not yet included a squash
116 * command, then this file exists and holds the commit message of the
117 * original "pick" commit. (If the series ends without a "squash"
118 * command, then this can be used as the commit message of the combined
119 * commit without opening the editor.)
121 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
123 * This file contains the list fixup/squash commands that have been
124 * accumulated into message-fixup or message-squash so far.
126 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
128 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
129 * GIT_AUTHOR_DATE that will be used for the commit that is currently
132 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
134 * When an "edit" rebase command is being processed, the SHA1 of the
135 * commit to be edited is recorded in this file. When "git rebase
136 * --continue" is executed, if there are any staged changes then they
137 * will be amended to the HEAD commit, but only provided the HEAD
138 * commit is still the commit to be edited. When any other rebase
139 * command is processed, this file is deleted.
141 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
143 * When we stop at a given patch via the "edit" command, this file contains
144 * the commit object name of the corresponding patch.
146 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
148 * When we stop for the user to resolve conflicts this file contains
149 * the patch of the commit that is being picked.
151 static GIT_PATH_FUNC(rebase_path_patch
, "rebase-merge/patch")
153 * For the post-rewrite hook, we make a list of rewritten commits and
154 * their new sha1s. The rewritten-pending list keeps the sha1s of
155 * commits that have been processed, but not committed yet,
156 * e.g. because they are waiting for a 'squash' command.
158 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
159 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
160 "rebase-merge/rewritten-pending")
163 * The path of the file containing the OID of the "squash onto" commit, i.e.
164 * the dummy commit used for `reset [new root]`.
166 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
169 * The path of the file listing refs that need to be deleted after the rebase
170 * finishes. This is used by the `label` command to record the need for cleanup.
172 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
175 * The update-refs file stores a list of refs that will be updated at the end
176 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
177 * update the OIDs for the refs in this file, but the refs are not updated
178 * until the end of the rebase sequence.
180 * rebase_path_update_refs() returns the path to this file for a given
181 * worktree directory. For the current worktree, pass the_repository->gitdir.
183 static char *rebase_path_update_refs(const char *wt_git_dir
)
185 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
189 * The following files are written by git-rebase just after parsing the
192 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
193 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
194 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
195 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
196 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
197 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
198 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
199 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
200 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
201 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
202 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
203 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
204 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
205 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
206 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
207 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
208 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
211 * A 'struct update_refs_record' represents a value in the update-refs
212 * list. We use a string_list to map refs to these (before, after) pairs.
214 struct update_ref_record
{
215 struct object_id before
;
216 struct object_id after
;
219 static struct update_ref_record
*init_update_ref_record(const char *ref
)
221 struct update_ref_record
*rec
;
223 CALLOC_ARRAY(rec
, 1);
225 oidcpy(&rec
->before
, null_oid());
226 oidcpy(&rec
->after
, null_oid());
228 /* This may fail, but that's fine, we will keep the null OID. */
229 read_ref(ref
, &rec
->before
);
234 static int git_sequencer_config(const char *k
, const char *v
,
235 const struct config_context
*ctx
, void *cb
)
237 struct replay_opts
*opts
= cb
;
239 if (!strcmp(k
, "commit.cleanup")) {
241 return config_error_nonbool(k
);
243 if (!strcmp(v
, "verbatim")) {
244 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
245 opts
->explicit_cleanup
= 1;
246 } else if (!strcmp(v
, "whitespace")) {
247 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
248 opts
->explicit_cleanup
= 1;
249 } else if (!strcmp(v
, "strip")) {
250 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
251 opts
->explicit_cleanup
= 1;
252 } else if (!strcmp(v
, "scissors")) {
253 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
254 opts
->explicit_cleanup
= 1;
256 warning(_("invalid commit message cleanup mode '%s'"),
263 if (!strcmp(k
, "commit.gpgsign")) {
264 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
268 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
269 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
272 * pull.twohead is allowed to be multi-valued; we only
273 * care about the first value.
275 char *tmp
= strchr(opts
->default_strategy
, ' ');
282 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
283 opts
->commit_use_reference
= git_config_bool(k
, v
);
285 return git_diff_basic_config(k
, v
, ctx
, NULL
);
288 void sequencer_init_config(struct replay_opts
*opts
)
290 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
291 git_config(git_sequencer_config
, opts
);
294 static inline int is_rebase_i(const struct replay_opts
*opts
)
296 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
299 static const char *get_dir(const struct replay_opts
*opts
)
301 if (is_rebase_i(opts
))
302 return rebase_path();
303 return git_path_seq_dir();
306 static const char *get_todo_path(const struct replay_opts
*opts
)
308 if (is_rebase_i(opts
))
309 return rebase_path_todo();
310 return git_path_todo_file();
314 * Returns 0 for non-conforming footer
315 * Returns 1 for conforming footer
316 * Returns 2 when sob exists within conforming footer
317 * Returns 3 when sob exists within conforming footer as last entry
319 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
320 size_t ignore_footer
)
322 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
323 struct trailer_info info
;
325 int found_sob
= 0, found_sob_last
= 0;
331 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
332 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
335 trailer_info_get(&info
, sb
->buf
, &opts
);
338 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
340 if (info
.trailer_block_start
== info
.trailer_block_end
)
343 for (i
= 0; i
< info
.trailer_nr
; i
++)
344 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
346 if (i
== info
.trailer_nr
- 1)
350 trailer_info_release(&info
);
359 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
361 static struct strbuf buf
= STRBUF_INIT
;
365 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
369 void replay_opts_release(struct replay_opts
*opts
)
371 free(opts
->gpg_sign
);
372 free(opts
->reflog_action
);
373 free(opts
->default_strategy
);
374 free(opts
->strategy
);
375 strvec_clear (&opts
->xopts
);
376 strbuf_release(&opts
->current_fixups
);
378 release_revisions(opts
->revs
);
382 int sequencer_remove_state(struct replay_opts
*opts
)
384 struct strbuf buf
= STRBUF_INIT
;
387 if (is_rebase_i(opts
) &&
388 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
391 char *eol
= strchr(p
, '\n');
394 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
395 warning(_("could not delete '%s'"), p
);
405 strbuf_addstr(&buf
, get_dir(opts
));
406 if (remove_dir_recursively(&buf
, 0))
407 ret
= error(_("could not remove '%s'"), buf
.buf
);
408 strbuf_release(&buf
);
413 static const char *action_name(const struct replay_opts
*opts
)
415 switch (opts
->action
) {
419 return N_("cherry-pick");
420 case REPLAY_INTERACTIVE_REBASE
:
423 die(_("unknown action: %d"), opts
->action
);
426 struct commit_message
{
433 static const char *short_commit_name(struct repository
*r
, struct commit
*commit
)
435 return repo_find_unique_abbrev(r
, &commit
->object
.oid
, DEFAULT_ABBREV
);
438 static int get_message(struct commit
*commit
, struct commit_message
*out
)
440 const char *abbrev
, *subject
;
443 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
444 get_commit_output_encoding());
445 abbrev
= short_commit_name(the_repository
, commit
);
447 subject_len
= find_commit_subject(out
->message
, &subject
);
449 out
->subject
= xmemdupz(subject
, subject_len
);
450 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
451 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
456 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
458 free(msg
->parent_label
);
461 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
464 static void print_advice(struct repository
*r
, int show_hint
,
465 struct replay_opts
*opts
)
467 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
472 * A conflict has occurred but the porcelain
473 * (typically rebase --interactive) wants to take care
474 * of the commit itself so remove CHERRY_PICK_HEAD
476 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
483 advise(_("after resolving the conflicts, mark the corrected paths\n"
484 "with 'git add <paths>' or 'git rm <paths>'"));
485 else if (opts
->action
== REPLAY_PICK
)
486 advise(_("After resolving the conflicts, mark them with\n"
487 "\"git add/rm <pathspec>\", then run\n"
488 "\"git cherry-pick --continue\".\n"
489 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
490 "To abort and get back to the state before \"git cherry-pick\",\n"
491 "run \"git cherry-pick --abort\"."));
492 else if (opts
->action
== REPLAY_REVERT
)
493 advise(_("After resolving the conflicts, mark them with\n"
494 "\"git add/rm <pathspec>\", then run\n"
495 "\"git revert --continue\".\n"
496 "You can instead skip this commit with \"git revert --skip\".\n"
497 "To abort and get back to the state before \"git revert\",\n"
498 "run \"git revert --abort\"."));
500 BUG("unexpected pick action in print_advice()");
504 static int write_message(const void *buf
, size_t len
, const char *filename
,
507 struct lock_file msg_file
= LOCK_INIT
;
509 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
511 return error_errno(_("could not lock '%s'"), filename
);
512 if (write_in_full(msg_fd
, buf
, len
) < 0) {
513 error_errno(_("could not write to '%s'"), filename
);
514 rollback_lock_file(&msg_file
);
517 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
518 error_errno(_("could not write eol to '%s'"), filename
);
519 rollback_lock_file(&msg_file
);
522 if (commit_lock_file(&msg_file
) < 0)
523 return error(_("failed to finalize '%s'"), filename
);
528 int read_oneliner(struct strbuf
*buf
,
529 const char *path
, unsigned flags
)
531 int orig_len
= buf
->len
;
533 if (strbuf_read_file(buf
, path
, 0) < 0) {
534 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
535 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
536 warning_errno(_("could not read '%s'"), path
);
540 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
541 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
543 buf
->buf
[buf
->len
] = '\0';
546 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
552 static struct tree
*empty_tree(struct repository
*r
)
554 return lookup_tree(r
, the_hash_algo
->empty_tree
);
557 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
559 if (repo_read_index_unmerged(repo
))
560 return error_resolve_conflict(action_name(opts
));
562 error(_("your local changes would be overwritten by %s."),
563 _(action_name(opts
)));
565 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
566 advise(_("commit your changes or stash them to proceed."));
570 static void update_abort_safety_file(void)
572 struct object_id head
;
574 /* Do nothing on a single-pick */
575 if (!file_exists(git_path_seq_dir()))
578 if (!repo_get_oid(the_repository
, "HEAD", &head
))
579 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
581 write_file(git_path_abort_safety_file(), "%s", "");
584 static int fast_forward_to(struct repository
*r
,
585 const struct object_id
*to
,
586 const struct object_id
*from
,
588 struct replay_opts
*opts
)
590 struct ref_transaction
*transaction
;
591 struct strbuf sb
= STRBUF_INIT
;
592 struct strbuf err
= STRBUF_INIT
;
595 if (checkout_fast_forward(r
, from
, to
, 1))
596 return -1; /* the callee should have complained already */
598 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
600 transaction
= ref_transaction_begin(&err
);
602 ref_transaction_update(transaction
, "HEAD",
603 to
, unborn
&& !is_rebase_i(opts
) ?
606 ref_transaction_commit(transaction
, &err
)) {
607 ref_transaction_free(transaction
);
608 error("%s", err
.buf
);
610 strbuf_release(&err
);
615 strbuf_release(&err
);
616 ref_transaction_free(transaction
);
617 update_abort_safety_file();
621 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
624 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
625 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
626 COMMIT_MSG_CLEANUP_SPACE
;
627 else if (!strcmp(cleanup_arg
, "verbatim"))
628 return COMMIT_MSG_CLEANUP_NONE
;
629 else if (!strcmp(cleanup_arg
, "whitespace"))
630 return COMMIT_MSG_CLEANUP_SPACE
;
631 else if (!strcmp(cleanup_arg
, "strip"))
632 return COMMIT_MSG_CLEANUP_ALL
;
633 else if (!strcmp(cleanup_arg
, "scissors"))
634 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
635 COMMIT_MSG_CLEANUP_SPACE
;
637 die(_("Invalid cleanup mode %s"), cleanup_arg
);
641 * NB using int rather than enum cleanup_mode to stop clang's
642 * -Wtautological-constant-out-of-range-compare complaining that the comparison
645 static const char *describe_cleanup_mode(int cleanup_mode
)
647 static const char *modes
[] = { "whitespace",
652 if (cleanup_mode
< ARRAY_SIZE(modes
))
653 return modes
[cleanup_mode
];
655 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
658 void append_conflicts_hint(struct index_state
*istate
,
659 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
663 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
664 strbuf_addch(msgbuf
, '\n');
665 wt_status_append_cut_line(msgbuf
);
666 strbuf_addch(msgbuf
, comment_line_char
);
669 strbuf_addch(msgbuf
, '\n');
670 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
671 for (i
= 0; i
< istate
->cache_nr
;) {
672 const struct cache_entry
*ce
= istate
->cache
[i
++];
674 strbuf_commented_addf(msgbuf
, comment_line_char
,
676 while (i
< istate
->cache_nr
&&
677 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
683 static int do_recursive_merge(struct repository
*r
,
684 struct commit
*base
, struct commit
*next
,
685 const char *base_label
, const char *next_label
,
686 struct object_id
*head
, struct strbuf
*msgbuf
,
687 struct replay_opts
*opts
)
689 struct merge_options o
;
690 struct merge_result result
;
691 struct tree
*next_tree
, *base_tree
, *head_tree
;
692 int clean
, show_output
;
694 struct lock_file index_lock
= LOCK_INIT
;
696 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
701 init_merge_options(&o
, r
);
702 o
.ancestor
= base
? base_label
: "(empty tree)";
704 o
.branch2
= next
? next_label
: "(empty tree)";
705 if (is_rebase_i(opts
))
707 o
.show_rename_progress
= 1;
709 head_tree
= parse_tree_indirect(head
);
711 return error(_("unable to read tree (%s)"), oid_to_hex(head
));
712 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
713 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
715 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
716 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
718 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
719 memset(&result
, 0, sizeof(result
));
720 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
722 show_output
= !is_rebase_i(opts
) || !result
.clean
;
724 * TODO: merge_switch_to_result will update index/working tree;
725 * we only really want to do that if !result.clean || this is
726 * the final patch to be picked. But determining this is the
727 * final patch would take some work, and "head_tree" would need
728 * to be replace with the tree the index matched before we
729 * started doing any picks.
731 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
732 clean
= result
.clean
;
734 ensure_full_index(r
->index
);
735 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
736 if (is_rebase_i(opts
) && clean
<= 0)
737 fputs(o
.obuf
.buf
, stdout
);
738 strbuf_release(&o
.obuf
);
741 rollback_lock_file(&index_lock
);
745 if (write_locked_index(r
->index
, &index_lock
,
746 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
748 * TRANSLATORS: %s will be "revert", "cherry-pick" or
751 return error(_("%s: Unable to write new index file"),
752 _(action_name(opts
)));
755 append_conflicts_hint(r
->index
, msgbuf
,
756 opts
->default_msg_cleanup
);
761 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
763 if (!cache_tree_fully_valid(istate
->cache_tree
))
764 if (cache_tree_update(istate
, 0)) {
765 error(_("unable to update cache tree"));
769 return &istate
->cache_tree
->oid
;
772 static int is_index_unchanged(struct repository
*r
)
774 struct object_id head_oid
, *cache_tree_oid
;
775 const struct object_id
*head_tree_oid
;
776 struct commit
*head_commit
;
777 struct index_state
*istate
= r
->index
;
778 const char *head_name
;
780 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
)) {
781 /* Check to see if this is an unborn branch */
782 head_name
= resolve_ref_unsafe("HEAD",
783 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
786 !starts_with(head_name
, "refs/heads/") ||
787 !is_null_oid(&head_oid
))
788 return error(_("could not resolve HEAD commit"));
789 head_tree_oid
= the_hash_algo
->empty_tree
;
791 head_commit
= lookup_commit(r
, &head_oid
);
794 * If head_commit is NULL, check_commit, called from
795 * lookup_commit, would have indicated that head_commit is not
796 * a commit object already. repo_parse_commit() will return failure
797 * without further complaints in such a case. Otherwise, if
798 * the commit is invalid, repo_parse_commit() will complain. So
799 * there is nothing for us to say here. Just return failure.
801 if (repo_parse_commit(r
, head_commit
))
804 head_tree_oid
= get_commit_tree_oid(head_commit
);
807 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
810 return oideq(cache_tree_oid
, head_tree_oid
);
813 static int write_author_script(const char *message
)
815 struct strbuf buf
= STRBUF_INIT
;
820 if (!*message
|| starts_with(message
, "\n")) {
822 /* Missing 'author' line? */
823 unlink(rebase_path_author_script());
825 } else if (skip_prefix(message
, "author ", &message
))
827 else if ((eol
= strchr(message
, '\n')))
832 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
833 while (*message
&& *message
!= '\n' && *message
!= '\r')
834 if (skip_prefix(message
, " <", &message
))
836 else if (*message
!= '\'')
837 strbuf_addch(&buf
, *(message
++));
839 strbuf_addf(&buf
, "'\\%c'", *(message
++));
840 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
841 while (*message
&& *message
!= '\n' && *message
!= '\r')
842 if (skip_prefix(message
, "> ", &message
))
844 else if (*message
!= '\'')
845 strbuf_addch(&buf
, *(message
++));
847 strbuf_addf(&buf
, "'\\%c'", *(message
++));
848 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
849 while (*message
&& *message
!= '\n' && *message
!= '\r')
850 if (*message
!= '\'')
851 strbuf_addch(&buf
, *(message
++));
853 strbuf_addf(&buf
, "'\\%c'", *(message
++));
854 strbuf_addch(&buf
, '\'');
855 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
856 strbuf_release(&buf
);
861 * Take a series of KEY='VALUE' lines where VALUE part is
862 * sq-quoted, and append <KEY, VALUE> at the end of the string list
864 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
867 struct string_list_item
*item
;
869 char *cp
= strchr(buf
, '=');
871 np
= strchrnul(buf
, '\n');
872 return error(_("no key present in '%.*s'"),
873 (int) (np
- buf
), buf
);
875 np
= strchrnul(cp
, '\n');
877 item
= string_list_append(list
, buf
);
879 buf
= np
+ (*np
== '\n');
883 return error(_("unable to dequote value of '%s'"),
885 item
->util
= xstrdup(cp
);
891 * Reads and parses the state directory's "author-script" file, and sets name,
892 * email and date accordingly.
893 * Returns 0 on success, -1 if the file could not be parsed.
895 * The author script is of the format:
897 * GIT_AUTHOR_NAME='$author_name'
898 * GIT_AUTHOR_EMAIL='$author_email'
899 * GIT_AUTHOR_DATE='$author_date'
901 * where $author_name, $author_email and $author_date are quoted. We are strict
902 * with our parsing, as the file was meant to be eval'd in the now-removed
903 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
904 * from what this function expects, it is better to bail out than to do
905 * something that the user does not expect.
907 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
910 struct strbuf buf
= STRBUF_INIT
;
911 struct string_list kv
= STRING_LIST_INIT_DUP
;
912 int retval
= -1; /* assume failure */
913 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
915 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
916 strbuf_release(&buf
);
917 if (errno
== ENOENT
&& allow_missing
)
920 return error_errno(_("could not open '%s' for reading"),
924 if (parse_key_value_squoted(buf
.buf
, &kv
))
927 for (i
= 0; i
< kv
.nr
; i
++) {
928 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
930 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
933 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
935 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
938 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
940 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
944 err
= error(_("unknown variable '%s'"),
949 error(_("missing 'GIT_AUTHOR_NAME'"));
951 error(_("missing 'GIT_AUTHOR_EMAIL'"));
953 error(_("missing 'GIT_AUTHOR_DATE'"));
954 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
956 *name
= kv
.items
[name_i
].util
;
957 *email
= kv
.items
[email_i
].util
;
958 *date
= kv
.items
[date_i
].util
;
961 string_list_clear(&kv
, !!retval
);
962 strbuf_release(&buf
);
967 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
968 * file with shell quoting into struct strvec. Returns -1 on
969 * error, 0 otherwise.
971 static int read_env_script(struct strvec
*env
)
973 char *name
, *email
, *date
;
975 if (read_author_script(rebase_path_author_script(),
976 &name
, &email
, &date
, 0))
979 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
980 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
981 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
989 static char *get_author(const char *message
)
994 a
= find_commit_header(message
, "author", &len
);
996 return xmemdupz(a
, len
);
1001 static const char *author_date_from_env(const struct strvec
*env
)
1006 for (i
= 0; i
< env
->nr
; i
++)
1007 if (skip_prefix(env
->v
[i
],
1008 "GIT_AUTHOR_DATE=", &date
))
1011 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1012 * reading the script
1014 BUG("GIT_AUTHOR_DATE missing from author script");
1017 static const char staged_changes_advice
[] =
1018 N_("you have staged changes in your working tree\n"
1019 "If these changes are meant to be squashed into the previous commit, run:\n"
1021 " git commit --amend %s\n"
1023 "If they are meant to go into a new commit, run:\n"
1027 "In both cases, once you're done, continue with:\n"
1029 " git rebase --continue\n");
1031 #define ALLOW_EMPTY (1<<0)
1032 #define EDIT_MSG (1<<1)
1033 #define AMEND_MSG (1<<2)
1034 #define CLEANUP_MSG (1<<3)
1035 #define VERIFY_MSG (1<<4)
1036 #define CREATE_ROOT_COMMIT (1<<5)
1037 #define VERBATIM_MSG (1<<6)
1039 static int run_command_silent_on_success(struct child_process
*cmd
)
1041 struct strbuf buf
= STRBUF_INIT
;
1044 cmd
->stdout_to_stderr
= 1;
1045 rc
= pipe_command(cmd
,
1051 fputs(buf
.buf
, stderr
);
1052 strbuf_release(&buf
);
1057 * If we are cherry-pick, and if the merge did not result in
1058 * hand-editing, we will hit this commit and inherit the original
1059 * author date and name.
1061 * If we are revert, or if our cherry-pick results in a hand merge,
1062 * we had better say that the current user is responsible for that.
1064 * An exception is when run_git_commit() is called during an
1065 * interactive rebase: in that case, we will want to retain the
1068 static int run_git_commit(const char *defmsg
,
1069 struct replay_opts
*opts
,
1072 struct child_process cmd
= CHILD_PROCESS_INIT
;
1074 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1075 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1079 if (is_rebase_i(opts
) &&
1080 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1081 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1082 read_env_script(&cmd
.env
)) {
1083 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1085 return error(_(staged_changes_advice
),
1089 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1091 if (opts
->committer_date_is_author_date
)
1092 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1095 author_date_from_env(&cmd
.env
));
1096 if (opts
->ignore_date
)
1097 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1099 strvec_push(&cmd
.args
, "commit");
1101 if (!(flags
& VERIFY_MSG
))
1102 strvec_push(&cmd
.args
, "-n");
1103 if ((flags
& AMEND_MSG
))
1104 strvec_push(&cmd
.args
, "--amend");
1106 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1108 strvec_push(&cmd
.args
, "--no-gpg-sign");
1110 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1111 else if (!(flags
& EDIT_MSG
))
1112 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1113 if ((flags
& CLEANUP_MSG
))
1114 strvec_push(&cmd
.args
, "--cleanup=strip");
1115 if ((flags
& VERBATIM_MSG
))
1116 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1117 if ((flags
& EDIT_MSG
))
1118 strvec_push(&cmd
.args
, "-e");
1119 else if (!(flags
& CLEANUP_MSG
) &&
1120 !opts
->signoff
&& !opts
->record_origin
&&
1121 !opts
->explicit_cleanup
)
1122 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1124 if ((flags
& ALLOW_EMPTY
))
1125 strvec_push(&cmd
.args
, "--allow-empty");
1127 if (!(flags
& EDIT_MSG
))
1128 strvec_push(&cmd
.args
, "--allow-empty-message");
1130 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1131 return run_command_silent_on_success(&cmd
);
1133 return run_command(&cmd
);
1136 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1141 /* Check if the rest is just whitespace and Signed-off-by's. */
1142 for (i
= start
; i
< sb
->len
; i
++) {
1143 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1149 if (strlen(sign_off_header
) <= eol
- i
&&
1150 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1155 if (!isspace(sb
->buf
[i
++]))
1162 void cleanup_message(struct strbuf
*msgbuf
,
1163 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1165 if (verbose
|| /* Truncate the message just before the diff, if any. */
1166 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1167 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1168 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1169 strbuf_stripspace(msgbuf
,
1170 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1174 * Find out if the message in the strbuf contains only whitespace and
1175 * Signed-off-by lines.
1177 int message_is_empty(const struct strbuf
*sb
,
1178 enum commit_msg_cleanup_mode cleanup_mode
)
1180 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1182 return rest_is_empty(sb
, 0);
1186 * See if the user edited the message in the editor or left what
1187 * was in the template intact
1189 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1190 enum commit_msg_cleanup_mode cleanup_mode
)
1192 struct strbuf tmpl
= STRBUF_INIT
;
1195 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1198 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1201 strbuf_stripspace(&tmpl
,
1202 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1203 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1205 strbuf_release(&tmpl
);
1206 return rest_is_empty(sb
, start
- sb
->buf
);
1209 int update_head_with_reflog(const struct commit
*old_head
,
1210 const struct object_id
*new_head
,
1211 const char *action
, const struct strbuf
*msg
,
1214 struct ref_transaction
*transaction
;
1215 struct strbuf sb
= STRBUF_INIT
;
1220 strbuf_addstr(&sb
, action
);
1221 strbuf_addstr(&sb
, ": ");
1224 nl
= strchr(msg
->buf
, '\n');
1226 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1228 strbuf_addbuf(&sb
, msg
);
1229 strbuf_addch(&sb
, '\n');
1232 transaction
= ref_transaction_begin(err
);
1234 ref_transaction_update(transaction
, "HEAD", new_head
,
1235 old_head
? &old_head
->object
.oid
: null_oid(),
1237 ref_transaction_commit(transaction
, err
)) {
1240 ref_transaction_free(transaction
);
1241 strbuf_release(&sb
);
1246 static int run_rewrite_hook(const struct object_id
*oldoid
,
1247 const struct object_id
*newoid
)
1249 struct child_process proc
= CHILD_PROCESS_INIT
;
1251 struct strbuf sb
= STRBUF_INIT
;
1252 const char *hook_path
= find_hook("post-rewrite");
1257 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1259 proc
.stdout_to_stderr
= 1;
1260 proc
.trace2_hook_name
= "post-rewrite";
1262 code
= start_command(&proc
);
1265 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1266 sigchain_push(SIGPIPE
, SIG_IGN
);
1267 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1269 strbuf_release(&sb
);
1270 sigchain_pop(SIGPIPE
);
1271 return finish_command(&proc
);
1274 void commit_post_rewrite(struct repository
*r
,
1275 const struct commit
*old_head
,
1276 const struct object_id
*new_head
)
1278 struct notes_rewrite_cfg
*cfg
;
1280 cfg
= init_copy_notes_for_rewrite("amend");
1282 /* we are amending, so old_head is not NULL */
1283 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1284 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1286 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1289 static int run_prepare_commit_msg_hook(struct repository
*r
,
1294 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1296 name
= git_path_commit_editmsg();
1297 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1306 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1308 ret
= error(_("'prepare-commit-msg' hook failed"));
1313 static const char implicit_ident_advice_noconfig
[] =
1314 N_("Your name and email address were configured automatically based\n"
1315 "on your username and hostname. Please check that they are accurate.\n"
1316 "You can suppress this message by setting them explicitly. Run the\n"
1317 "following command and follow the instructions in your editor to edit\n"
1318 "your configuration file:\n"
1320 " git config --global --edit\n"
1322 "After doing this, you may fix the identity used for this commit with:\n"
1324 " git commit --amend --reset-author\n");
1326 static const char implicit_ident_advice_config
[] =
1327 N_("Your name and email address were configured automatically based\n"
1328 "on your username and hostname. Please check that they are accurate.\n"
1329 "You can suppress this message by setting them explicitly:\n"
1331 " git config --global user.name \"Your Name\"\n"
1332 " git config --global user.email you@example.com\n"
1334 "After doing this, you may fix the identity used for this commit with:\n"
1336 " git commit --amend --reset-author\n");
1338 static const char *implicit_ident_advice(void)
1340 char *user_config
= interpolate_path("~/.gitconfig", 0);
1341 char *xdg_config
= xdg_config_home("config");
1342 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1348 return _(implicit_ident_advice_config
);
1350 return _(implicit_ident_advice_noconfig
);
1354 void print_commit_summary(struct repository
*r
,
1356 const struct object_id
*oid
,
1359 struct rev_info rev
;
1360 struct commit
*commit
;
1361 struct strbuf format
= STRBUF_INIT
;
1363 struct pretty_print_context pctx
= {0};
1364 struct strbuf author_ident
= STRBUF_INIT
;
1365 struct strbuf committer_ident
= STRBUF_INIT
;
1366 struct ref_store
*refs
;
1368 commit
= lookup_commit(r
, oid
);
1370 die(_("couldn't look up newly created commit"));
1371 if (repo_parse_commit(r
, commit
))
1372 die(_("could not parse newly created commit"));
1374 strbuf_addstr(&format
, "format:%h] %s");
1376 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1378 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1380 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1381 strbuf_addstr(&format
, "\n Author: ");
1382 strbuf_addbuf_percentquote(&format
, &author_ident
);
1384 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1385 struct strbuf date
= STRBUF_INIT
;
1387 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1388 strbuf_addstr(&format
, "\n Date: ");
1389 strbuf_addbuf_percentquote(&format
, &date
);
1390 strbuf_release(&date
);
1392 if (!committer_ident_sufficiently_given()) {
1393 strbuf_addstr(&format
, "\n Committer: ");
1394 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1395 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1396 strbuf_addch(&format
, '\n');
1397 strbuf_addstr(&format
, implicit_ident_advice());
1400 strbuf_release(&author_ident
);
1401 strbuf_release(&committer_ident
);
1403 repo_init_revisions(r
, &rev
, prefix
);
1404 setup_revisions(0, NULL
, &rev
, NULL
);
1407 rev
.diffopt
.output_format
=
1408 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1410 rev
.verbose_header
= 1;
1411 rev
.show_root_diff
= 1;
1412 get_commit_format(format
.buf
, &rev
);
1413 rev
.always_show_header
= 0;
1414 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1415 diff_setup_done(&rev
.diffopt
);
1417 refs
= get_main_ref_store(r
);
1418 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1420 die(_("unable to resolve HEAD after creating commit"));
1421 if (!strcmp(head
, "HEAD"))
1422 head
= _("detached HEAD");
1424 skip_prefix(head
, "refs/heads/", &head
);
1425 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1426 _(" (root-commit)") : "");
1428 if (!log_tree_commit(&rev
, commit
)) {
1429 rev
.always_show_header
= 1;
1430 rev
.use_terminator
= 1;
1431 log_tree_commit(&rev
, commit
);
1434 release_revisions(&rev
);
1435 strbuf_release(&format
);
1438 static int parse_head(struct repository
*r
, struct commit
**head
)
1440 struct commit
*current_head
;
1441 struct object_id oid
;
1443 if (repo_get_oid(r
, "HEAD", &oid
)) {
1444 current_head
= NULL
;
1446 current_head
= lookup_commit_reference(r
, &oid
);
1448 return error(_("could not parse HEAD"));
1449 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1450 warning(_("HEAD %s is not a commit!"),
1453 if (repo_parse_commit(r
, current_head
))
1454 return error(_("could not parse HEAD commit"));
1456 *head
= current_head
;
1462 * Try to commit without forking 'git commit'. In some cases we need
1463 * to run 'git commit' to display an error message
1466 * -1 - error unable to commit
1468 * 1 - run 'git commit'
1470 static int try_to_commit(struct repository
*r
,
1471 struct strbuf
*msg
, const char *author
,
1472 struct replay_opts
*opts
, unsigned int flags
,
1473 struct object_id
*oid
)
1475 struct object_id tree
;
1476 struct commit
*current_head
= NULL
;
1477 struct commit_list
*parents
= NULL
;
1478 struct commit_extra_header
*extra
= NULL
;
1479 struct strbuf err
= STRBUF_INIT
;
1480 struct strbuf commit_msg
= STRBUF_INIT
;
1481 char *amend_author
= NULL
;
1482 const char *committer
= NULL
;
1483 const char *hook_commit
= NULL
;
1484 enum commit_msg_cleanup_mode cleanup
;
1487 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1488 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1490 if (parse_head(r
, ¤t_head
))
1493 if (flags
& AMEND_MSG
) {
1494 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1495 const char *out_enc
= get_commit_output_encoding();
1496 const char *message
= repo_logmsg_reencode(r
, current_head
,
1500 const char *orig_message
= NULL
;
1502 find_commit_subject(message
, &orig_message
);
1504 strbuf_addstr(msg
, orig_message
);
1505 hook_commit
= "HEAD";
1507 author
= amend_author
= get_author(message
);
1508 repo_unuse_commit_buffer(r
, current_head
,
1511 res
= error(_("unable to parse commit author"));
1514 parents
= copy_commit_list(current_head
->parents
);
1515 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1516 } else if (current_head
&&
1517 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1518 commit_list_insert(current_head
, &parents
);
1521 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1522 res
= error(_("git write-tree failed to write a tree"));
1526 if (!(flags
& ALLOW_EMPTY
)) {
1527 struct commit
*first_parent
= current_head
;
1529 if (flags
& AMEND_MSG
) {
1530 if (current_head
->parents
) {
1531 first_parent
= current_head
->parents
->item
;
1532 if (repo_parse_commit(r
, first_parent
)) {
1533 res
= error(_("could not parse HEAD commit"));
1537 first_parent
= NULL
;
1540 if (oideq(first_parent
1541 ? get_commit_tree_oid(first_parent
)
1542 : the_hash_algo
->empty_tree
,
1544 res
= 1; /* run 'git commit' to display error message */
1549 if (hook_exists("prepare-commit-msg")) {
1550 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1553 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1555 res
= error_errno(_("unable to read commit message "
1557 git_path_commit_editmsg());
1563 if (flags
& CLEANUP_MSG
)
1564 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1565 else if (flags
& VERBATIM_MSG
)
1566 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1567 else if ((opts
->signoff
|| opts
->record_origin
) &&
1568 !opts
->explicit_cleanup
)
1569 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1571 cleanup
= opts
->default_msg_cleanup
;
1573 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1574 strbuf_stripspace(msg
,
1575 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1576 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1577 res
= 1; /* run 'git commit' to display error message */
1581 if (opts
->committer_date_is_author_date
) {
1582 struct ident_split id
;
1583 struct strbuf date
= STRBUF_INIT
;
1585 if (!opts
->ignore_date
) {
1586 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1587 res
= error(_("invalid author identity '%s'"),
1591 if (!id
.date_begin
) {
1593 "corrupt author: missing date information"));
1596 strbuf_addf(&date
, "@%.*s %.*s",
1597 (int)(id
.date_end
- id
.date_begin
),
1599 (int)(id
.tz_end
- id
.tz_begin
),
1604 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1605 getenv("GIT_COMMITTER_EMAIL"),
1606 WANT_COMMITTER_IDENT
,
1607 opts
->ignore_date
? NULL
: date
.buf
,
1609 strbuf_release(&date
);
1614 if (opts
->ignore_date
) {
1615 struct ident_split id
;
1618 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1619 error(_("invalid author identity '%s'"), author
);
1622 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1623 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1624 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1630 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1631 author
, committer
, opts
->gpg_sign
, extra
)) {
1632 res
= error(_("failed to write commit object"));
1636 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1638 res
= error("%s", err
.buf
);
1642 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1643 if (flags
& AMEND_MSG
)
1644 commit_post_rewrite(r
, current_head
, oid
);
1647 free_commit_extra_headers(extra
);
1648 strbuf_release(&err
);
1649 strbuf_release(&commit_msg
);
1655 static int write_rebase_head(struct object_id
*oid
)
1657 if (update_ref("rebase", "REBASE_HEAD", oid
,
1658 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1659 return error(_("could not update %s"), "REBASE_HEAD");
1664 static int do_commit(struct repository
*r
,
1665 const char *msg_file
, const char *author
,
1666 struct replay_opts
*opts
, unsigned int flags
,
1667 struct object_id
*oid
)
1671 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1672 struct object_id oid
;
1673 struct strbuf sb
= STRBUF_INIT
;
1675 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1676 return error_errno(_("unable to read commit message "
1680 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1681 author
, opts
, flags
, &oid
);
1682 strbuf_release(&sb
);
1684 refs_delete_ref(get_main_ref_store(r
), "",
1685 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
);
1686 unlink(git_path_merge_msg(r
));
1687 if (!is_rebase_i(opts
))
1688 print_commit_summary(r
, NULL
, &oid
,
1689 SUMMARY_SHOW_AUTHOR_DATE
);
1694 if (is_rebase_i(opts
) && oid
)
1695 if (write_rebase_head(oid
))
1697 return run_git_commit(msg_file
, opts
, flags
);
1703 static int is_original_commit_empty(struct commit
*commit
)
1705 const struct object_id
*ptree_oid
;
1707 if (repo_parse_commit(the_repository
, commit
))
1708 return error(_("could not parse commit %s"),
1709 oid_to_hex(&commit
->object
.oid
));
1710 if (commit
->parents
) {
1711 struct commit
*parent
= commit
->parents
->item
;
1712 if (repo_parse_commit(the_repository
, parent
))
1713 return error(_("could not parse parent commit %s"),
1714 oid_to_hex(&parent
->object
.oid
));
1715 ptree_oid
= get_commit_tree_oid(parent
);
1717 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1720 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1724 * Should empty commits be allowed? Return status:
1725 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1726 * 0: Halt on empty commit
1727 * 1: Allow empty commit
1728 * 2: Drop empty commit
1730 static int allow_empty(struct repository
*r
,
1731 struct replay_opts
*opts
,
1732 struct commit
*commit
)
1734 int index_unchanged
, originally_empty
;
1737 * For a commit that is initially empty, allow_empty determines if it
1738 * should be kept or not
1740 * For a commit that becomes empty, keep_redundant_commits and
1741 * drop_redundant_commits determine whether the commit should be kept or
1742 * dropped. If neither is specified, halt.
1744 index_unchanged
= is_index_unchanged(r
);
1745 if (index_unchanged
< 0)
1746 return index_unchanged
;
1747 if (!index_unchanged
)
1748 return 0; /* we do not have to say --allow-empty */
1750 originally_empty
= is_original_commit_empty(commit
);
1751 if (originally_empty
< 0)
1752 return originally_empty
;
1753 if (originally_empty
)
1754 return opts
->allow_empty
;
1755 else if (opts
->keep_redundant_commits
)
1757 else if (opts
->drop_redundant_commits
)
1766 } todo_command_info
[] = {
1767 [TODO_PICK
] = { 'p', "pick" },
1768 [TODO_REVERT
] = { 0, "revert" },
1769 [TODO_EDIT
] = { 'e', "edit" },
1770 [TODO_REWORD
] = { 'r', "reword" },
1771 [TODO_FIXUP
] = { 'f', "fixup" },
1772 [TODO_SQUASH
] = { 's', "squash" },
1773 [TODO_EXEC
] = { 'x', "exec" },
1774 [TODO_BREAK
] = { 'b', "break" },
1775 [TODO_LABEL
] = { 'l', "label" },
1776 [TODO_RESET
] = { 't', "reset" },
1777 [TODO_MERGE
] = { 'm', "merge" },
1778 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1779 [TODO_NOOP
] = { 0, "noop" },
1780 [TODO_DROP
] = { 'd', "drop" },
1781 [TODO_COMMENT
] = { 0, NULL
},
1784 static const char *command_to_string(const enum todo_command command
)
1786 if (command
< TODO_COMMENT
)
1787 return todo_command_info
[command
].str
;
1788 die(_("unknown command: %d"), command
);
1791 static char command_to_char(const enum todo_command command
)
1793 if (command
< TODO_COMMENT
)
1794 return todo_command_info
[command
].c
;
1795 return comment_line_char
;
1798 static int is_noop(const enum todo_command command
)
1800 return TODO_NOOP
<= command
;
1803 static int is_fixup(enum todo_command command
)
1805 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1808 /* Does this command create a (non-merge) commit? */
1809 static int is_pick_or_similar(enum todo_command command
)
1824 enum todo_item_flags
{
1825 TODO_EDIT_MERGE_MSG
= (1 << 0),
1826 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1827 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1830 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1831 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1832 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1833 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1834 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1836 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1838 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1839 (flag
& TODO_EDIT_FIXUP_MSG
));
1843 * Wrapper around strbuf_add_commented_lines() which avoids double
1844 * commenting commit subjects.
1846 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1848 const char *s
= str
;
1849 while (len
> 0 && s
[0] == comment_line_char
) {
1851 const char *n
= memchr(s
, '\n', len
);
1856 strbuf_add(buf
, s
, count
);
1860 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1863 /* Does the current fixup chain contain a squash command? */
1864 static int seen_squash(struct replay_opts
*opts
)
1866 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1867 strstr(opts
->current_fixups
.buf
, "\nsquash");
1870 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1872 strbuf_setlen(buf1
, 2);
1873 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1874 strbuf_addch(buf1
, '\n');
1875 strbuf_setlen(buf2
, 2);
1876 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1877 strbuf_addch(buf2
, '\n');
1881 * Comment out any un-commented commit messages, updating the message comments
1882 * to say they will be skipped but do not comment out the empty lines that
1883 * surround commit messages and their comments.
1885 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1887 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1888 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1889 const char *s
, *start
;
1891 size_t orig_msg_len
;
1894 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1895 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1896 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1900 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1902 * Copy the last message, preserving the blank line
1903 * preceding the current line
1905 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1906 copy_lines(msg
, start
, s
- start
- off
);
1908 strbuf_addch(msg
, '\n');
1910 * The next message needs to be commented out but the
1911 * message header is already commented out so just copy
1912 * it and the blank line that follows it.
1914 strbuf_addbuf(msg
, &buf2
);
1916 strbuf_addch(msg
, *next
++);
1918 copy_lines
= add_commented_lines
;
1919 update_comment_bufs(&buf1
, &buf2
, ++i
);
1920 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1921 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1922 copy_lines(msg
, start
, s
- start
- off
);
1925 copy_lines
= strbuf_add
;
1926 update_comment_bufs(&buf1
, &buf2
, ++i
);
1928 s
= strchr(s
, '\n');
1933 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1935 strbuf_release(&buf1
);
1936 strbuf_release(&buf2
);
1939 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1940 enum todo_command command
, struct replay_opts
*opts
,
1943 const char *fixup_msg
;
1944 size_t commented_len
= 0, fixup_off
;
1946 * amend is non-interactive and not normally used with fixup!
1947 * or squash! commits, so only comment out those subjects when
1948 * squashing commit messages.
1950 if (starts_with(body
, "amend!") ||
1951 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1952 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1953 commented_len
= commit_subject_length(body
);
1955 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1956 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1957 ++opts
->current_fixup_count
+ 1);
1958 strbuf_addstr(buf
, "\n\n");
1959 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1960 /* buf->buf may be reallocated so store an offset into the buffer */
1961 fixup_off
= buf
->len
;
1962 strbuf_addstr(buf
, body
+ commented_len
);
1964 /* fixup -C after squash behaves like squash */
1965 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1967 * We're replacing the commit message so we need to
1968 * append the Signed-off-by: trailer if the user
1969 * requested '--signoff'.
1972 append_signoff(buf
, 0, 0);
1974 if ((command
== TODO_FIXUP
) &&
1975 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1976 (file_exists(rebase_path_fixup_msg()) ||
1977 !file_exists(rebase_path_squash_msg()))) {
1978 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1979 if (write_message(fixup_msg
, strlen(fixup_msg
),
1980 rebase_path_fixup_msg(), 0) < 0)
1981 return error(_("cannot write '%s'"),
1982 rebase_path_fixup_msg());
1984 unlink(rebase_path_fixup_msg());
1987 unlink(rebase_path_fixup_msg());
1993 static int update_squash_messages(struct repository
*r
,
1994 enum todo_command command
,
1995 struct commit
*commit
,
1996 struct replay_opts
*opts
,
1999 struct strbuf buf
= STRBUF_INIT
;
2001 const char *message
, *body
;
2002 const char *encoding
= get_commit_output_encoding();
2004 if (opts
->current_fixup_count
> 0) {
2005 struct strbuf header
= STRBUF_INIT
;
2008 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2009 return error(_("could not read '%s'"),
2010 rebase_path_squash_msg());
2012 eol
= buf
.buf
[0] != comment_line_char
?
2013 buf
.buf
: strchrnul(buf
.buf
, '\n');
2015 strbuf_addf(&header
, "%c ", comment_line_char
);
2016 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2017 opts
->current_fixup_count
+ 2);
2018 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2019 strbuf_release(&header
);
2020 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2021 update_squash_message_for_fixup(&buf
);
2023 struct object_id head
;
2024 struct commit
*head_commit
;
2025 const char *head_message
, *body
;
2027 if (repo_get_oid(r
, "HEAD", &head
))
2028 return error(_("need a HEAD to fixup"));
2029 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2030 return error(_("could not read HEAD"));
2031 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2033 return error(_("could not read HEAD's commit message"));
2035 find_commit_subject(head_message
, &body
);
2036 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2037 rebase_path_fixup_msg(), 0) < 0) {
2038 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2039 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2041 strbuf_addf(&buf
, "%c ", comment_line_char
);
2042 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2043 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2044 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2045 _(skip_first_commit_msg_str
) :
2046 _(first_commit_msg_str
));
2047 strbuf_addstr(&buf
, "\n\n");
2048 if (is_fixup_flag(command
, flag
))
2049 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2052 strbuf_addstr(&buf
, body
);
2054 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2057 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2058 return error(_("could not read commit message of %s"),
2059 oid_to_hex(&commit
->object
.oid
));
2060 find_commit_subject(message
, &body
);
2062 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2063 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2064 } else if (command
== TODO_FIXUP
) {
2065 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2066 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2067 ++opts
->current_fixup_count
+ 1);
2068 strbuf_addstr(&buf
, "\n\n");
2069 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2072 return error(_("unknown command: %d"), command
);
2073 repo_unuse_commit_buffer(r
, commit
, message
);
2076 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2078 strbuf_release(&buf
);
2081 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2082 opts
->current_fixups
.len
? "\n" : "",
2083 command_to_string(command
),
2084 oid_to_hex(&commit
->object
.oid
));
2085 res
= write_message(opts
->current_fixups
.buf
,
2086 opts
->current_fixups
.len
,
2087 rebase_path_current_fixups(), 0);
2093 static void flush_rewritten_pending(void)
2095 struct strbuf buf
= STRBUF_INIT
;
2096 struct object_id newoid
;
2099 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2100 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2101 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2102 char *bol
= buf
.buf
, *eol
;
2105 eol
= strchrnul(bol
, '\n');
2106 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2107 bol
, oid_to_hex(&newoid
));
2113 unlink(rebase_path_rewritten_pending());
2115 strbuf_release(&buf
);
2118 static void record_in_rewritten(struct object_id
*oid
,
2119 enum todo_command next_command
)
2121 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2126 fprintf(out
, "%s\n", oid_to_hex(oid
));
2129 if (!is_fixup(next_command
))
2130 flush_rewritten_pending();
2133 static int should_edit(struct replay_opts
*opts
) {
2136 * Note that we only handle the case of non-conflicted
2137 * commits; continue_single_pick() handles the conflicted
2138 * commits itself instead of calling this function.
2140 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2144 static void refer_to_commit(struct replay_opts
*opts
,
2145 struct strbuf
*msgbuf
, struct commit
*commit
)
2147 if (opts
->commit_use_reference
) {
2148 struct pretty_print_context ctx
= {
2149 .abbrev
= DEFAULT_ABBREV
,
2150 .date_mode
.type
= DATE_SHORT
,
2152 repo_format_commit_message(the_repository
, commit
,
2153 "%h (%s, %ad)", msgbuf
, &ctx
);
2155 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2159 static int do_pick_commit(struct repository
*r
,
2160 struct todo_item
*item
,
2161 struct replay_opts
*opts
,
2162 int final_fixup
, int *check_todo
)
2164 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2165 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2166 struct object_id head
;
2167 struct commit
*base
, *next
, *parent
;
2168 const char *base_label
, *next_label
;
2169 char *author
= NULL
;
2170 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2171 struct strbuf msgbuf
= STRBUF_INIT
;
2172 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2173 enum todo_command command
= item
->command
;
2174 struct commit
*commit
= item
->commit
;
2176 if (opts
->no_commit
) {
2178 * We do not intend to commit immediately. We just want to
2179 * merge the differences in, so let's compute the tree
2180 * that represents the "current" state for the merge machinery
2183 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2184 return error(_("your index file is unmerged."));
2186 unborn
= repo_get_oid(r
, "HEAD", &head
);
2187 /* Do we want to generate a root commit? */
2188 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2189 oideq(&head
, &opts
->squash_onto
)) {
2190 if (is_fixup(command
))
2191 return error(_("cannot fixup root commit"));
2192 flags
|= CREATE_ROOT_COMMIT
;
2195 oidcpy(&head
, the_hash_algo
->empty_tree
);
2196 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2198 return error_dirty_index(r
, opts
);
2200 discard_index(r
->index
);
2202 if (!commit
->parents
)
2204 else if (commit
->parents
->next
) {
2205 /* Reverting or cherry-picking a merge commit */
2207 struct commit_list
*p
;
2209 if (!opts
->mainline
)
2210 return error(_("commit %s is a merge but no -m option was given."),
2211 oid_to_hex(&commit
->object
.oid
));
2213 for (cnt
= 1, p
= commit
->parents
;
2214 cnt
!= opts
->mainline
&& p
;
2217 if (cnt
!= opts
->mainline
|| !p
)
2218 return error(_("commit %s does not have parent %d"),
2219 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2221 } else if (1 < opts
->mainline
)
2223 * Non-first parent explicitly specified as mainline for
2226 return error(_("commit %s does not have parent %d"),
2227 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2229 parent
= commit
->parents
->item
;
2231 if (get_message(commit
, &msg
) != 0)
2232 return error(_("cannot get commit message for %s"),
2233 oid_to_hex(&commit
->object
.oid
));
2235 if (opts
->allow_ff
&& !is_fixup(command
) &&
2236 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2237 (!parent
&& unborn
))) {
2238 if (is_rebase_i(opts
))
2239 write_author_script(msg
.message
);
2240 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2242 if (res
|| command
!= TODO_REWORD
)
2246 goto fast_forward_edit
;
2248 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2249 /* TRANSLATORS: The first %s will be a "todo" command like
2250 "revert" or "pick", the second %s a SHA1. */
2251 return error(_("%s: cannot parse parent commit %s"),
2252 command_to_string(command
),
2253 oid_to_hex(&parent
->object
.oid
));
2256 * "commit" is an existing commit. We would want to apply
2257 * the difference it introduces since its first parent "prev"
2258 * on top of the current HEAD if we are cherry-pick. Or the
2259 * reverse of it if we are revert.
2262 if (command
== TODO_REVERT
) {
2263 const char *orig_subject
;
2266 base_label
= msg
.label
;
2268 next_label
= msg
.parent_label
;
2269 if (opts
->commit_use_reference
) {
2270 strbuf_addstr(&msgbuf
,
2271 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2272 } else if (skip_prefix(msg
.subject
, "Revert \"", &orig_subject
) &&
2274 * We don't touch pre-existing repeated reverts, because
2275 * theoretically these can be nested arbitrarily deeply,
2276 * thus requiring excessive complexity to deal with.
2278 !starts_with(orig_subject
, "Revert \"")) {
2279 strbuf_addstr(&msgbuf
, "Reapply \"");
2280 strbuf_addstr(&msgbuf
, orig_subject
);
2282 strbuf_addstr(&msgbuf
, "Revert \"");
2283 strbuf_addstr(&msgbuf
, msg
.subject
);
2284 strbuf_addstr(&msgbuf
, "\"");
2286 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2287 refer_to_commit(opts
, &msgbuf
, commit
);
2289 if (commit
->parents
&& commit
->parents
->next
) {
2290 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2291 refer_to_commit(opts
, &msgbuf
, parent
);
2293 strbuf_addstr(&msgbuf
, ".\n");
2298 base_label
= msg
.parent_label
;
2300 next_label
= msg
.label
;
2302 /* Append the commit log message to msgbuf. */
2303 if (find_commit_subject(msg
.message
, &p
))
2304 strbuf_addstr(&msgbuf
, p
);
2306 if (opts
->record_origin
) {
2307 strbuf_complete_line(&msgbuf
);
2308 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2309 strbuf_addch(&msgbuf
, '\n');
2310 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2311 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2312 strbuf_addstr(&msgbuf
, ")\n");
2314 if (!is_fixup(command
))
2315 author
= get_author(msg
.message
);
2318 if (command
== TODO_REWORD
)
2320 else if (is_fixup(command
)) {
2321 if (update_squash_messages(r
, command
, commit
,
2322 opts
, item
->flags
)) {
2328 msg_file
= rebase_path_squash_msg();
2329 else if (file_exists(rebase_path_fixup_msg())) {
2330 flags
|= VERBATIM_MSG
;
2331 msg_file
= rebase_path_fixup_msg();
2333 const char *dest
= git_path_squash_msg(r
);
2335 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2336 res
= error(_("could not copy '%s' to '%s'"),
2337 rebase_path_squash_msg(), dest
);
2340 unlink(git_path_merge_msg(r
));
2346 if (opts
->signoff
&& !is_fixup(command
))
2347 append_signoff(&msgbuf
, 0, 0);
2349 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2351 else if (!opts
->strategy
||
2352 !strcmp(opts
->strategy
, "recursive") ||
2353 !strcmp(opts
->strategy
, "ort") ||
2354 command
== TODO_REVERT
) {
2355 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2356 &head
, &msgbuf
, opts
);
2360 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2361 git_path_merge_msg(r
), 0);
2363 struct commit_list
*common
= NULL
;
2364 struct commit_list
*remotes
= NULL
;
2366 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2367 git_path_merge_msg(r
), 0);
2369 commit_list_insert(base
, &common
);
2370 commit_list_insert(next
, &remotes
);
2371 res
|= try_merge_command(r
, opts
->strategy
,
2372 opts
->xopts
.nr
, opts
->xopts
.v
,
2373 common
, oid_to_hex(&head
), remotes
);
2374 free_commit_list(common
);
2375 free_commit_list(remotes
);
2379 * If the merge was clean or if it failed due to conflict, we write
2380 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2381 * However, if the merge did not even start, then we don't want to
2384 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2385 command
== TODO_EDIT
) && !opts
->no_commit
&&
2386 (res
== 0 || res
== 1) &&
2387 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2388 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2390 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2391 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2392 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2396 error(command
== TODO_REVERT
2397 ? _("could not revert %s... %s")
2398 : _("could not apply %s... %s"),
2399 short_commit_name(r
, commit
), msg
.subject
);
2400 print_advice(r
, res
== 1, opts
);
2401 repo_rerere(r
, opts
->allow_rerere_auto
);
2406 allow
= allow_empty(r
, opts
, commit
);
2410 } else if (allow
== 1) {
2411 flags
|= ALLOW_EMPTY
;
2412 } else if (allow
== 2) {
2414 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2415 NULL
, REF_NO_DEREF
);
2416 unlink(git_path_merge_msg(r
));
2417 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2418 NULL
, REF_NO_DEREF
);
2420 _("dropping %s %s -- patch contents already upstream\n"),
2421 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2422 } /* else allow == 0 and there's nothing special to do */
2423 if (!opts
->no_commit
&& !drop_commit
) {
2424 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2425 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2426 commit
? &commit
->object
.oid
: NULL
);
2428 res
= error(_("unable to parse commit author"));
2429 *check_todo
= !!(flags
& EDIT_MSG
);
2430 if (!res
&& reword
) {
2432 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2433 VERIFY_MSG
| AMEND_MSG
|
2434 (flags
& ALLOW_EMPTY
));
2440 if (!res
&& final_fixup
) {
2441 unlink(rebase_path_fixup_msg());
2442 unlink(rebase_path_squash_msg());
2443 unlink(rebase_path_current_fixups());
2444 strbuf_reset(&opts
->current_fixups
);
2445 opts
->current_fixup_count
= 0;
2449 free_message(commit
, &msg
);
2451 strbuf_release(&msgbuf
);
2452 update_abort_safety_file();
2457 static int prepare_revs(struct replay_opts
*opts
)
2460 * picking (but not reverting) ranges (but not individual revisions)
2461 * should be done in reverse
2463 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2464 opts
->revs
->reverse
^= 1;
2466 if (prepare_revision_walk(opts
->revs
))
2467 return error(_("revision walk setup failed"));
2472 static int read_and_refresh_cache(struct repository
*r
,
2473 struct replay_opts
*opts
)
2475 struct lock_file index_lock
= LOCK_INIT
;
2476 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2477 if (repo_read_index(r
) < 0) {
2478 rollback_lock_file(&index_lock
);
2479 return error(_("git %s: failed to read the index"),
2482 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2484 if (index_fd
>= 0) {
2485 if (write_locked_index(r
->index
, &index_lock
,
2486 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2487 return error(_("git %s: failed to refresh the index"),
2493 * If we are resolving merges in any way other than "ort", then
2494 * expand the sparse index.
2496 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2497 ensure_full_index(r
->index
);
2501 void todo_list_release(struct todo_list
*todo_list
)
2503 strbuf_release(&todo_list
->buf
);
2504 FREE_AND_NULL(todo_list
->items
);
2505 todo_list
->nr
= todo_list
->alloc
= 0;
2508 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2510 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2511 return todo_list
->items
+ todo_list
->nr
++;
2514 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2515 struct todo_item
*item
)
2517 return todo_list
->buf
.buf
+ item
->arg_offset
;
2520 static int is_command(enum todo_command command
, const char **bol
)
2522 const char *str
= todo_command_info
[command
].str
;
2523 const char nick
= todo_command_info
[command
].c
;
2524 const char *p
= *bol
;
2526 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2527 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2531 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2536 * '#' is not a valid label as the merge command uses it to
2537 * separate merge parents from the commit subject.
2539 if (!strcmp(arg
, "#") ||
2540 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2541 return error(_("'%s' is not a valid label"), arg
);
2544 case TODO_UPDATE_REF
:
2545 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2546 return error(_("'%s' is not a valid refname"), arg
);
2547 if (check_refname_format(arg
, 0))
2548 return error(_("update-ref requires a fully qualified "
2549 "refname e.g. refs/heads/%s"), arg
);
2553 BUG("unexpected todo_command");
2559 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2560 const char *buf
, const char *bol
, char *eol
)
2562 struct object_id commit_oid
;
2563 char *end_of_object_name
;
2564 int i
, saved
, status
, padding
;
2569 bol
+= strspn(bol
, " \t");
2571 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2572 item
->command
= TODO_COMMENT
;
2573 item
->commit
= NULL
;
2574 item
->arg_offset
= bol
- buf
;
2575 item
->arg_len
= eol
- bol
;
2579 for (i
= 0; i
< TODO_COMMENT
; i
++)
2580 if (is_command(i
, &bol
)) {
2584 if (i
>= TODO_COMMENT
)
2585 return error(_("invalid command '%.*s'"),
2586 (int)strcspn(bol
, " \t\r\n"), bol
);
2588 /* Eat up extra spaces/ tabs before object name */
2589 padding
= strspn(bol
, " \t");
2592 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2594 return error(_("%s does not accept arguments: '%s'"),
2595 command_to_string(item
->command
), bol
);
2596 item
->commit
= NULL
;
2597 item
->arg_offset
= bol
- buf
;
2598 item
->arg_len
= eol
- bol
;
2603 return error(_("missing arguments for %s"),
2604 command_to_string(item
->command
));
2606 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2607 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2610 item
->commit
= NULL
;
2611 item
->arg_offset
= bol
- buf
;
2612 item
->arg_len
= (int)(eol
- bol
);
2613 if (item
->command
== TODO_LABEL
||
2614 item
->command
== TODO_UPDATE_REF
) {
2617 ret
= check_label_or_ref_arg(item
->command
, bol
);
2623 if (item
->command
== TODO_FIXUP
) {
2624 if (skip_prefix(bol
, "-C", &bol
)) {
2625 bol
+= strspn(bol
, " \t");
2626 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2627 } else if (skip_prefix(bol
, "-c", &bol
)) {
2628 bol
+= strspn(bol
, " \t");
2629 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2633 if (item
->command
== TODO_MERGE
) {
2634 if (skip_prefix(bol
, "-C", &bol
))
2635 bol
+= strspn(bol
, " \t");
2636 else if (skip_prefix(bol
, "-c", &bol
)) {
2637 bol
+= strspn(bol
, " \t");
2638 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2640 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2641 item
->commit
= NULL
;
2642 item
->arg_offset
= bol
- buf
;
2643 item
->arg_len
= (int)(eol
- bol
);
2648 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2649 saved
= *end_of_object_name
;
2650 *end_of_object_name
= '\0';
2651 status
= repo_get_oid(r
, bol
, &commit_oid
);
2653 error(_("could not parse '%s'"), bol
); /* return later */
2654 *end_of_object_name
= saved
;
2656 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2657 item
->arg_offset
= bol
- buf
;
2658 item
->arg_len
= (int)(eol
- bol
);
2663 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2664 return item
->commit
? 0 : -1;
2667 int sequencer_get_last_command(struct repository
*r UNUSED
, enum replay_action
*action
)
2669 const char *todo_file
, *bol
;
2670 struct strbuf buf
= STRBUF_INIT
;
2673 todo_file
= git_path_todo_file();
2674 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2675 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2678 return error_errno("unable to open '%s'", todo_file
);
2680 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2681 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2682 *action
= REPLAY_PICK
;
2683 else if (is_command(TODO_REVERT
, &bol
) &&
2684 (*bol
== ' ' || *bol
== '\t'))
2685 *action
= REPLAY_REVERT
;
2689 strbuf_release(&buf
);
2694 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2695 struct todo_list
*todo_list
)
2697 struct todo_item
*item
;
2698 char *p
= buf
, *next_p
;
2699 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2701 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2703 for (i
= 1; *p
; i
++, p
= next_p
) {
2704 char *eol
= strchrnul(p
, '\n');
2706 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2708 if (p
!= eol
&& eol
[-1] == '\r')
2709 eol
--; /* strip Carriage Return */
2711 item
= append_new_todo(todo_list
);
2712 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2713 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2714 res
= error(_("invalid line %d: %.*s"),
2715 i
, (int)(eol
- p
), p
);
2716 item
->command
= TODO_COMMENT
+ 1;
2717 item
->arg_offset
= p
- buf
;
2718 item
->arg_len
= (int)(eol
- p
);
2719 item
->commit
= NULL
;
2722 if (item
->command
!= TODO_COMMENT
)
2723 todo_list
->total_nr
++;
2727 else if (is_fixup(item
->command
))
2728 res
= error(_("cannot '%s' without a previous commit"),
2729 command_to_string(item
->command
));
2730 else if (!is_noop(item
->command
))
2737 static int count_commands(struct todo_list
*todo_list
)
2741 for (i
= 0; i
< todo_list
->nr
; i
++)
2742 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2748 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2750 return index
< todo_list
->nr
?
2751 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2754 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2756 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2759 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2761 return get_item_line_offset(todo_list
, index
+ 1)
2762 - get_item_line_offset(todo_list
, index
);
2765 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2770 fd
= open(path
, O_RDONLY
);
2772 return error_errno(_("could not open '%s'"), path
);
2773 len
= strbuf_read(sb
, fd
, 0);
2776 return error(_("could not read '%s'."), path
);
2780 static int have_finished_the_last_pick(void)
2782 struct strbuf buf
= STRBUF_INIT
;
2784 const char *todo_path
= git_path_todo_file();
2787 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2788 if (errno
== ENOENT
) {
2791 error_errno("unable to open '%s'", todo_path
);
2795 /* If there is only one line then we are done */
2796 eol
= strchr(buf
.buf
, '\n');
2797 if (!eol
|| !eol
[1])
2800 strbuf_release(&buf
);
2805 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2807 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2808 int need_cleanup
= 0;
2810 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2811 if (!refs_delete_ref(get_main_ref_store(r
), "",
2812 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
) &&
2814 warning(_("cancelling a cherry picking in progress"));
2815 opts
.action
= REPLAY_PICK
;
2819 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2820 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2821 NULL
, REF_NO_DEREF
) &&
2823 warning(_("cancelling a revert in progress"));
2824 opts
.action
= REPLAY_REVERT
;
2828 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2829 NULL
, REF_NO_DEREF
);
2834 if (!have_finished_the_last_pick())
2837 sequencer_remove_state(&opts
);
2840 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2842 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2845 fprintf(f
, "%d\n", todo_list
->total_nr
);
2850 static int read_populate_todo(struct repository
*r
,
2851 struct todo_list
*todo_list
,
2852 struct replay_opts
*opts
)
2854 const char *todo_file
= get_todo_path(opts
);
2857 strbuf_reset(&todo_list
->buf
);
2858 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2861 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2863 if (is_rebase_i(opts
))
2864 return error(_("please fix this using "
2865 "'git rebase --edit-todo'."));
2866 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2869 if (!todo_list
->nr
&&
2870 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2871 return error(_("no commits parsed."));
2873 if (!is_rebase_i(opts
)) {
2874 enum todo_command valid
=
2875 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2878 for (i
= 0; i
< todo_list
->nr
; i
++)
2879 if (valid
== todo_list
->items
[i
].command
)
2881 else if (valid
== TODO_PICK
)
2882 return error(_("cannot cherry-pick during a revert."));
2884 return error(_("cannot revert during a cherry-pick."));
2887 if (is_rebase_i(opts
)) {
2888 struct todo_list done
= TODO_LIST_INIT
;
2890 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2891 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2892 todo_list
->done_nr
= count_commands(&done
);
2894 todo_list
->done_nr
= 0;
2896 todo_list
->total_nr
= todo_list
->done_nr
2897 + count_commands(todo_list
);
2898 todo_list_release(&done
);
2900 todo_list_write_total_nr(todo_list
);
2906 static int git_config_string_dup(char **dest
,
2907 const char *var
, const char *value
)
2910 return config_error_nonbool(var
);
2912 *dest
= xstrdup(value
);
2916 static int populate_opts_cb(const char *key
, const char *value
,
2917 const struct config_context
*ctx
,
2920 struct replay_opts
*opts
= data
;
2925 else if (!strcmp(key
, "options.no-commit"))
2926 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2927 else if (!strcmp(key
, "options.edit"))
2928 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2929 else if (!strcmp(key
, "options.allow-empty"))
2931 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2932 else if (!strcmp(key
, "options.allow-empty-message"))
2933 opts
->allow_empty_message
=
2934 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2935 else if (!strcmp(key
, "options.drop-redundant-commits"))
2936 opts
->drop_redundant_commits
=
2937 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2938 else if (!strcmp(key
, "options.keep-redundant-commits"))
2939 opts
->keep_redundant_commits
=
2940 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2941 else if (!strcmp(key
, "options.signoff"))
2942 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2943 else if (!strcmp(key
, "options.record-origin"))
2944 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2945 else if (!strcmp(key
, "options.allow-ff"))
2946 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2947 else if (!strcmp(key
, "options.mainline"))
2948 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2949 else if (!strcmp(key
, "options.strategy"))
2950 git_config_string_dup(&opts
->strategy
, key
, value
);
2951 else if (!strcmp(key
, "options.gpg-sign"))
2952 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2953 else if (!strcmp(key
, "options.strategy-option")) {
2954 strvec_push(&opts
->xopts
, value
);
2955 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2956 opts
->allow_rerere_auto
=
2957 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2958 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2959 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2960 opts
->explicit_cleanup
= 1;
2961 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2963 return error(_("invalid key: %s"), key
);
2966 return error(_("invalid value for '%s': '%s'"), key
, value
);
2971 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2976 char *strategy_opts_string
= raw_opts
;
2978 if (*strategy_opts_string
== ' ')
2979 strategy_opts_string
++;
2981 count
= split_cmdline(strategy_opts_string
, &argv
);
2983 BUG("could not split '%s': %s", strategy_opts_string
,
2984 split_cmdline_strerror(count
));
2985 for (i
= 0; i
< count
; i
++) {
2986 const char *arg
= argv
[i
];
2988 skip_prefix(arg
, "--", &arg
);
2989 strvec_push(&opts
->xopts
, arg
);
2994 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2997 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2999 opts
->strategy
= strbuf_detach(buf
, NULL
);
3000 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
3003 parse_strategy_opts(opts
, buf
->buf
);
3006 static int read_populate_opts(struct replay_opts
*opts
)
3008 if (is_rebase_i(opts
)) {
3009 struct strbuf buf
= STRBUF_INIT
;
3012 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
3013 READ_ONELINER_SKIP_IF_EMPTY
)) {
3014 if (!starts_with(buf
.buf
, "-S"))
3017 free(opts
->gpg_sign
);
3018 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3023 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3024 READ_ONELINER_SKIP_IF_EMPTY
)) {
3025 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3026 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3027 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3028 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3032 if (file_exists(rebase_path_verbose()))
3035 if (file_exists(rebase_path_quiet()))
3038 if (file_exists(rebase_path_signoff())) {
3043 if (file_exists(rebase_path_cdate_is_adate())) {
3045 opts
->committer_date_is_author_date
= 1;
3048 if (file_exists(rebase_path_ignore_date())) {
3050 opts
->ignore_date
= 1;
3053 if (file_exists(rebase_path_reschedule_failed_exec()))
3054 opts
->reschedule_failed_exec
= 1;
3055 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3056 opts
->reschedule_failed_exec
= 0;
3058 if (file_exists(rebase_path_drop_redundant_commits()))
3059 opts
->drop_redundant_commits
= 1;
3061 if (file_exists(rebase_path_keep_redundant_commits()))
3062 opts
->keep_redundant_commits
= 1;
3064 read_strategy_opts(opts
, &buf
);
3067 if (read_oneliner(&opts
->current_fixups
,
3068 rebase_path_current_fixups(),
3069 READ_ONELINER_SKIP_IF_EMPTY
)) {
3070 const char *p
= opts
->current_fixups
.buf
;
3071 opts
->current_fixup_count
= 1;
3072 while ((p
= strchr(p
, '\n'))) {
3073 opts
->current_fixup_count
++;
3078 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3079 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3080 ret
= error(_("unusable squash-onto"));
3083 opts
->have_squash_onto
= 1;
3087 strbuf_release(&buf
);
3091 if (!file_exists(git_path_opts_file()))
3094 * The function git_parse_source(), called from git_config_from_file(),
3095 * may die() in case of a syntactically incorrect file. We do not care
3096 * about this case, though, because we wrote that file ourselves, so we
3097 * are pretty certain that it is syntactically correct.
3099 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3100 return error(_("malformed options sheet: '%s'"),
3101 git_path_opts_file());
3105 static void write_strategy_opts(struct replay_opts
*opts
)
3107 struct strbuf buf
= STRBUF_INIT
;
3110 * Quote strategy options so that they can be read correctly
3111 * by split_cmdline().
3113 quote_cmdline(&buf
, opts
->xopts
.v
);
3114 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3115 strbuf_release(&buf
);
3118 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3119 struct commit
*onto
, const struct object_id
*orig_head
)
3122 write_file(rebase_path_head_name(), "%s\n", head_name
);
3124 write_file(rebase_path_onto(), "%s\n",
3125 oid_to_hex(&onto
->object
.oid
));
3127 write_file(rebase_path_orig_head(), "%s\n",
3128 oid_to_hex(orig_head
));
3131 write_file(rebase_path_quiet(), "%s", "");
3133 write_file(rebase_path_verbose(), "%s", "");
3135 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3136 if (opts
->xopts
.nr
> 0)
3137 write_strategy_opts(opts
);
3139 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3140 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3141 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3142 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3145 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3147 write_file(rebase_path_signoff(), "--signoff\n");
3148 if (opts
->drop_redundant_commits
)
3149 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3150 if (opts
->keep_redundant_commits
)
3151 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3152 if (opts
->committer_date_is_author_date
)
3153 write_file(rebase_path_cdate_is_adate(), "%s", "");
3154 if (opts
->ignore_date
)
3155 write_file(rebase_path_ignore_date(), "%s", "");
3156 if (opts
->reschedule_failed_exec
)
3157 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3159 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3164 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3165 struct replay_opts
*opts
)
3167 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3168 TODO_PICK
: TODO_REVERT
;
3169 const char *command_string
= todo_command_info
[command
].str
;
3170 const char *encoding
;
3171 struct commit
*commit
;
3173 if (prepare_revs(opts
))
3176 encoding
= get_log_output_encoding();
3178 while ((commit
= get_revision(opts
->revs
))) {
3179 struct todo_item
*item
= append_new_todo(todo_list
);
3180 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3183 const char *subject
;
3186 item
->command
= command
;
3187 item
->commit
= commit
;
3188 item
->arg_offset
= 0;
3190 item
->offset_in_buf
= todo_list
->buf
.len
;
3191 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3192 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3193 short_commit_name(the_repository
, commit
),
3194 subject_len
, subject
);
3195 repo_unuse_commit_buffer(the_repository
, commit
,
3200 return error(_("empty commit set passed"));
3205 static int create_seq_dir(struct repository
*r
)
3207 enum replay_action action
;
3208 const char *in_progress_error
= NULL
;
3209 const char *in_progress_advice
= NULL
;
3210 unsigned int advise_skip
=
3211 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3212 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3214 if (!sequencer_get_last_command(r
, &action
)) {
3217 in_progress_error
= _("revert is already in progress");
3218 in_progress_advice
=
3219 _("try \"git revert (--continue | %s--abort | --quit)\"");
3222 in_progress_error
= _("cherry-pick is already in progress");
3223 in_progress_advice
=
3224 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3227 BUG("unexpected action in create_seq_dir");
3230 if (in_progress_error
) {
3231 error("%s", in_progress_error
);
3232 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3233 advise(in_progress_advice
,
3234 advise_skip
? "--skip | " : "");
3237 if (mkdir(git_path_seq_dir(), 0777) < 0)
3238 return error_errno(_("could not create sequencer directory '%s'"),
3239 git_path_seq_dir());
3244 static int save_head(const char *head
)
3246 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3249 static int rollback_is_safe(void)
3251 struct strbuf sb
= STRBUF_INIT
;
3252 struct object_id expected_head
, actual_head
;
3254 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3256 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3257 strbuf_release(&sb
);
3258 die(_("could not parse %s"), git_path_abort_safety_file());
3260 strbuf_release(&sb
);
3262 else if (errno
== ENOENT
)
3263 oidclr(&expected_head
);
3265 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3267 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3268 oidclr(&actual_head
);
3270 return oideq(&actual_head
, &expected_head
);
3273 static int reset_merge(const struct object_id
*oid
)
3275 struct child_process cmd
= CHILD_PROCESS_INIT
;
3278 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3280 if (!is_null_oid(oid
))
3281 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3283 return run_command(&cmd
);
3286 static int rollback_single_pick(struct repository
*r
)
3288 struct object_id head_oid
;
3290 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3291 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3292 return error(_("no cherry-pick or revert in progress"));
3293 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3294 return error(_("cannot resolve HEAD"));
3295 if (is_null_oid(&head_oid
))
3296 return error(_("cannot abort from a branch yet to be born"));
3297 return reset_merge(&head_oid
);
3300 static int skip_single_pick(void)
3302 struct object_id head
;
3304 if (read_ref_full("HEAD", 0, &head
, NULL
))
3305 return error(_("cannot resolve HEAD"));
3306 return reset_merge(&head
);
3309 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3312 struct object_id oid
;
3313 struct strbuf buf
= STRBUF_INIT
;
3316 f
= fopen(git_path_head_file(), "r");
3317 if (!f
&& errno
== ENOENT
) {
3319 * There is no multiple-cherry-pick in progress.
3320 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3321 * a single-cherry-pick in progress, abort that.
3323 return rollback_single_pick(r
);
3326 return error_errno(_("cannot open '%s'"), git_path_head_file());
3327 if (strbuf_getline_lf(&buf
, f
)) {
3328 error(_("cannot read '%s': %s"), git_path_head_file(),
3329 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3334 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3335 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3336 git_path_head_file());
3339 if (is_null_oid(&oid
)) {
3340 error(_("cannot abort from a branch yet to be born"));
3344 if (!rollback_is_safe()) {
3345 /* Do not error, just do not rollback */
3346 warning(_("You seem to have moved HEAD. "
3347 "Not rewinding, check your HEAD!"));
3349 if (reset_merge(&oid
))
3351 strbuf_release(&buf
);
3352 return sequencer_remove_state(opts
);
3354 strbuf_release(&buf
);
3358 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3360 enum replay_action action
= -1;
3361 sequencer_get_last_command(r
, &action
);
3364 * Check whether the subcommand requested to skip the commit is actually
3365 * in progress and that it's safe to skip the commit.
3367 * opts->action tells us which subcommand requested to skip the commit.
3368 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3369 * action is in progress and we can skip the commit.
3371 * Otherwise we check that the last instruction was related to the
3372 * particular subcommand we're trying to execute and barf if that's not
3375 * Finally we check that the rollback is "safe", i.e., has the HEAD
3376 * moved? In this case, it doesn't make sense to "reset the merge" and
3377 * "skip the commit" as the user already handled this by committing. But
3378 * we'd not want to barf here, instead give advice on how to proceed. We
3379 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3380 * it gets removed when the user commits, so if it still exists we're
3381 * sure the user can't have committed before.
3383 switch (opts
->action
) {
3385 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3386 if (action
!= REPLAY_REVERT
)
3387 return error(_("no revert in progress"));
3388 if (!rollback_is_safe())
3393 if (!refs_ref_exists(get_main_ref_store(r
),
3394 "CHERRY_PICK_HEAD")) {
3395 if (action
!= REPLAY_PICK
)
3396 return error(_("no cherry-pick in progress"));
3397 if (!rollback_is_safe())
3402 BUG("unexpected action in sequencer_skip");
3405 if (skip_single_pick())
3406 return error(_("failed to skip the commit"));
3407 if (!is_directory(git_path_seq_dir()))
3410 return sequencer_continue(r
, opts
);
3413 error(_("there is nothing to skip"));
3415 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3416 advise(_("have you committed already?\n"
3417 "try \"git %s --continue\""),
3418 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3423 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
,
3426 struct lock_file todo_lock
= LOCK_INIT
;
3427 const char *todo_path
= get_todo_path(opts
);
3428 int next
= todo_list
->current
, offset
, fd
;
3431 * rebase -i writes "git-rebase-todo" without the currently executing
3432 * command, appending it to "done" instead.
3434 if (is_rebase_i(opts
) && !reschedule
)
3437 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3439 return error_errno(_("could not lock '%s'"), todo_path
);
3440 offset
= get_item_line_offset(todo_list
, next
);
3441 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3442 todo_list
->buf
.len
- offset
) < 0)
3443 return error_errno(_("could not write to '%s'"), todo_path
);
3444 if (commit_lock_file(&todo_lock
) < 0)
3445 return error(_("failed to finalize '%s'"), todo_path
);
3447 if (is_rebase_i(opts
) && !reschedule
&& next
> 0) {
3448 const char *done
= rebase_path_done();
3449 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3454 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3455 get_item_line_length(todo_list
, next
- 1))
3457 ret
= error_errno(_("could not write to '%s'"), done
);
3459 ret
= error_errno(_("failed to finalize '%s'"), done
);
3465 static int save_opts(struct replay_opts
*opts
)
3467 const char *opts_file
= git_path_opts_file();
3470 if (opts
->no_commit
)
3471 res
|= git_config_set_in_file_gently(opts_file
,
3472 "options.no-commit", "true");
3473 if (opts
->edit
>= 0)
3474 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3475 opts
->edit
? "true" : "false");
3476 if (opts
->allow_empty
)
3477 res
|= git_config_set_in_file_gently(opts_file
,
3478 "options.allow-empty", "true");
3479 if (opts
->allow_empty_message
)
3480 res
|= git_config_set_in_file_gently(opts_file
,
3481 "options.allow-empty-message", "true");
3482 if (opts
->drop_redundant_commits
)
3483 res
|= git_config_set_in_file_gently(opts_file
,
3484 "options.drop-redundant-commits", "true");
3485 if (opts
->keep_redundant_commits
)
3486 res
|= git_config_set_in_file_gently(opts_file
,
3487 "options.keep-redundant-commits", "true");
3489 res
|= git_config_set_in_file_gently(opts_file
,
3490 "options.signoff", "true");
3491 if (opts
->record_origin
)
3492 res
|= git_config_set_in_file_gently(opts_file
,
3493 "options.record-origin", "true");
3495 res
|= git_config_set_in_file_gently(opts_file
,
3496 "options.allow-ff", "true");
3497 if (opts
->mainline
) {
3498 struct strbuf buf
= STRBUF_INIT
;
3499 strbuf_addf(&buf
, "%d", opts
->mainline
);
3500 res
|= git_config_set_in_file_gently(opts_file
,
3501 "options.mainline", buf
.buf
);
3502 strbuf_release(&buf
);
3505 res
|= git_config_set_in_file_gently(opts_file
,
3506 "options.strategy", opts
->strategy
);
3508 res
|= git_config_set_in_file_gently(opts_file
,
3509 "options.gpg-sign", opts
->gpg_sign
);
3510 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3511 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3512 "options.strategy-option",
3513 opts
->xopts
.v
[i
], "^$", 0);
3514 if (opts
->allow_rerere_auto
)
3515 res
|= git_config_set_in_file_gently(opts_file
,
3516 "options.allow-rerere-auto",
3517 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3520 if (opts
->explicit_cleanup
)
3521 res
|= git_config_set_in_file_gently(opts_file
,
3522 "options.default-msg-cleanup",
3523 describe_cleanup_mode(opts
->default_msg_cleanup
));
3527 static int make_patch(struct repository
*r
,
3528 struct commit
*commit
,
3529 struct replay_opts
*opts
)
3531 struct rev_info log_tree_opt
;
3532 const char *subject
;
3533 char hex
[GIT_MAX_HEXSZ
+ 1];
3536 if (!is_rebase_i(opts
))
3537 BUG("make_patch should only be called when rebasing");
3539 oid_to_hex_r(hex
, &commit
->object
.oid
);
3540 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3542 res
|= write_rebase_head(&commit
->object
.oid
);
3544 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3545 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3546 log_tree_opt
.abbrev
= 0;
3547 log_tree_opt
.diff
= 1;
3548 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3549 log_tree_opt
.disable_stdin
= 1;
3550 log_tree_opt
.no_commit_id
= 1;
3551 log_tree_opt
.diffopt
.file
= fopen(rebase_path_patch(), "w");
3552 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3553 if (!log_tree_opt
.diffopt
.file
)
3554 res
|= error_errno(_("could not open '%s'"),
3555 rebase_path_patch());
3557 res
|= log_tree_commit(&log_tree_opt
, commit
);
3558 fclose(log_tree_opt
.diffopt
.file
);
3561 if (!file_exists(rebase_path_message())) {
3562 const char *encoding
= get_commit_output_encoding();
3563 const char *commit_buffer
= repo_logmsg_reencode(r
,
3566 find_commit_subject(commit_buffer
, &subject
);
3567 res
|= write_message(subject
, strlen(subject
), rebase_path_message(), 1);
3568 repo_unuse_commit_buffer(r
, commit
,
3571 release_revisions(&log_tree_opt
);
3576 static int intend_to_amend(void)
3578 struct object_id head
;
3581 if (repo_get_oid(the_repository
, "HEAD", &head
))
3582 return error(_("cannot read HEAD"));
3584 p
= oid_to_hex(&head
);
3585 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3588 static int error_with_patch(struct repository
*r
,
3589 struct commit
*commit
,
3590 const char *subject
, int subject_len
,
3591 struct replay_opts
*opts
,
3592 int exit_code
, int to_amend
)
3595 if (make_patch(r
, commit
, opts
))
3597 } else if (copy_file(rebase_path_message(),
3598 git_path_merge_msg(r
), 0666))
3599 return error(_("unable to copy '%s' to '%s'"),
3600 git_path_merge_msg(r
), rebase_path_message());
3603 if (intend_to_amend())
3607 _("You can amend the commit now, with\n"
3609 " git commit --amend %s\n"
3611 "Once you are satisfied with your changes, run\n"
3613 " git rebase --continue\n"),
3614 gpg_sign_opt_quoted(opts
));
3615 } else if (exit_code
) {
3617 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3618 short_commit_name(r
, commit
), subject_len
, subject
);
3621 * We don't have the hash of the parent so
3622 * just print the line from the todo file.
3624 fprintf_ln(stderr
, _("Could not merge %.*s"),
3625 subject_len
, subject
);
3631 static int error_failed_squash(struct repository
*r
,
3632 struct commit
*commit
,
3633 struct replay_opts
*opts
,
3635 const char *subject
)
3637 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3638 return error(_("could not copy '%s' to '%s'"),
3639 rebase_path_squash_msg(), rebase_path_message());
3640 unlink(git_path_merge_msg(r
));
3641 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3642 return error(_("could not copy '%s' to '%s'"),
3643 rebase_path_message(),
3644 git_path_merge_msg(r
));
3645 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3648 static int do_exec(struct repository
*r
, const char *command_line
)
3650 struct child_process cmd
= CHILD_PROCESS_INIT
;
3653 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3655 strvec_push(&cmd
.args
, command_line
);
3656 strvec_push(&cmd
.env
, "GIT_CHERRY_PICK_HELP");
3657 status
= run_command(&cmd
);
3659 /* force re-reading of the cache */
3660 discard_index(r
->index
);
3661 if (repo_read_index(r
) < 0)
3662 return error(_("could not read index"));
3664 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3667 warning(_("execution failed: %s\n%s"
3668 "You can fix the problem, and then run\n"
3670 " git rebase --continue\n"
3673 dirty
? _("and made changes to the index and/or the "
3674 "working tree.\n") : "");
3676 /* command not found */
3679 warning(_("execution succeeded: %s\nbut "
3680 "left changes to the index and/or the working tree.\n"
3681 "Commit or stash your changes, and then run\n"
3683 " git rebase --continue\n"
3684 "\n"), command_line
);
3691 __attribute__((format (printf
, 2, 3)))
3692 static int safe_append(const char *filename
, const char *fmt
, ...)
3695 struct lock_file lock
= LOCK_INIT
;
3696 int fd
= hold_lock_file_for_update(&lock
, filename
,
3697 LOCK_REPORT_ON_ERROR
);
3698 struct strbuf buf
= STRBUF_INIT
;
3703 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3704 error_errno(_("could not read '%s'"), filename
);
3705 rollback_lock_file(&lock
);
3708 strbuf_complete(&buf
, '\n');
3710 strbuf_vaddf(&buf
, fmt
, ap
);
3713 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3714 error_errno(_("could not write to '%s'"), filename
);
3715 strbuf_release(&buf
);
3716 rollback_lock_file(&lock
);
3719 if (commit_lock_file(&lock
) < 0) {
3720 strbuf_release(&buf
);
3721 return error(_("failed to finalize '%s'"), filename
);
3724 strbuf_release(&buf
);
3728 static int do_label(struct repository
*r
, const char *name
, int len
)
3730 struct ref_store
*refs
= get_main_ref_store(r
);
3731 struct ref_transaction
*transaction
;
3732 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3733 struct strbuf msg
= STRBUF_INIT
;
3735 struct object_id head_oid
;
3737 if (len
== 1 && *name
== '#')
3738 return error(_("illegal label name: '%.*s'"), len
, name
);
3740 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3741 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3743 transaction
= ref_store_transaction_begin(refs
, &err
);
3745 error("%s", err
.buf
);
3747 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3748 error(_("could not read HEAD"));
3750 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3751 NULL
, 0, msg
.buf
, &err
) < 0 ||
3752 ref_transaction_commit(transaction
, &err
)) {
3753 error("%s", err
.buf
);
3756 ref_transaction_free(transaction
);
3757 strbuf_release(&err
);
3758 strbuf_release(&msg
);
3761 ret
= safe_append(rebase_path_refs_to_delete(),
3762 "%s\n", ref_name
.buf
);
3763 strbuf_release(&ref_name
);
3768 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3770 if (!opts
->reflog_action
) {
3771 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3772 opts
->reflog_action
=
3773 xstrdup(opts
->reflog_action
? opts
->reflog_action
3774 : action_name(opts
));
3777 return opts
->reflog_action
;
3780 __attribute__((format (printf
, 3, 4)))
3781 static const char *reflog_message(struct replay_opts
*opts
,
3782 const char *sub_action
, const char *fmt
, ...)
3785 static struct strbuf buf
= STRBUF_INIT
;
3789 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3791 strbuf_addf(&buf
, " (%s)", sub_action
);
3793 strbuf_addstr(&buf
, ": ");
3794 strbuf_vaddf(&buf
, fmt
, ap
);
3801 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3802 int len
, struct strbuf
*buf
)
3804 struct commit
*commit
;
3805 struct object_id oid
;
3808 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3809 if (!read_ref(buf
->buf
, &oid
)) {
3810 commit
= lookup_commit_object(r
, &oid
);
3812 /* fall back to non-rewritten ref or commit */
3813 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3814 commit
= lookup_commit_reference_by_name(buf
->buf
);
3818 error(_("could not resolve '%s'"), buf
->buf
);
3823 static int do_reset(struct repository
*r
,
3824 const char *name
, int len
,
3825 struct replay_opts
*opts
)
3827 struct strbuf ref_name
= STRBUF_INIT
;
3828 struct object_id oid
;
3829 struct lock_file lock
= LOCK_INIT
;
3830 struct tree_desc desc
= { 0 };
3832 struct unpack_trees_options unpack_tree_opts
= { 0 };
3835 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3838 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3839 if (!opts
->have_squash_onto
) {
3841 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3842 NULL
, &opts
->squash_onto
,
3844 return error(_("writing fake root commit"));
3845 opts
->have_squash_onto
= 1;
3846 hex
= oid_to_hex(&opts
->squash_onto
);
3847 if (write_message(hex
, strlen(hex
),
3848 rebase_path_squash_onto(), 0))
3849 return error(_("writing squash-onto"));
3851 oidcpy(&oid
, &opts
->squash_onto
);
3854 struct commit
*commit
;
3856 /* Determine the length of the label */
3857 for (i
= 0; i
< len
; i
++)
3858 if (isspace(name
[i
]))
3862 commit
= lookup_label(r
, name
, len
, &ref_name
);
3867 oid
= commit
->object
.oid
;
3870 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3871 unpack_tree_opts
.head_idx
= 1;
3872 unpack_tree_opts
.src_index
= r
->index
;
3873 unpack_tree_opts
.dst_index
= r
->index
;
3874 unpack_tree_opts
.fn
= oneway_merge
;
3875 unpack_tree_opts
.merge
= 1;
3876 unpack_tree_opts
.update
= 1;
3877 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3878 unpack_tree_opts
.skip_cache_tree_update
= 1;
3879 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3881 if (repo_read_index_unmerged(r
)) {
3882 ret
= error_resolve_conflict(action_name(opts
));
3886 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3887 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3891 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3896 tree
= parse_tree_indirect(&oid
);
3898 return error(_("unable to read tree (%s)"), oid_to_hex(&oid
));
3899 prime_cache_tree(r
, r
->index
, tree
);
3901 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3902 ret
= error(_("could not write index"));
3905 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3906 len
, name
), "HEAD", &oid
,
3907 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3909 free((void *)desc
.buffer
);
3911 rollback_lock_file(&lock
);
3912 strbuf_release(&ref_name
);
3913 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3917 static int do_merge(struct repository
*r
,
3918 struct commit
*commit
,
3919 const char *arg
, int arg_len
,
3920 int flags
, int *check_todo
, struct replay_opts
*opts
)
3922 int run_commit_flags
= 0;
3923 struct strbuf ref_name
= STRBUF_INIT
;
3924 struct commit
*head_commit
, *merge_commit
, *i
;
3925 struct commit_list
*bases
, *j
;
3926 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3927 const char *strategy
= !opts
->xopts
.nr
&&
3929 !strcmp(opts
->strategy
, "recursive") ||
3930 !strcmp(opts
->strategy
, "ort")) ?
3931 NULL
: opts
->strategy
;
3932 struct merge_options o
;
3933 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3934 static struct lock_file lock
;
3937 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3942 head_commit
= lookup_commit_reference_by_name("HEAD");
3944 ret
= error(_("cannot merge without a current revision"));
3949 * For octopus merges, the arg starts with the list of revisions to be
3950 * merged. The list is optionally followed by '#' and the oneline.
3952 merge_arg_len
= oneline_offset
= arg_len
;
3953 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3956 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3957 p
+= 1 + strspn(p
+ 1, " \t\n");
3958 oneline_offset
= p
- arg
;
3961 k
= strcspn(p
, " \t\n");
3964 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3965 if (!merge_commit
) {
3966 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3969 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3971 merge_arg_len
= p
- arg
;
3975 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3979 if (opts
->have_squash_onto
&&
3980 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3982 * When the user tells us to "merge" something into a
3983 * "[new root]", let's simply fast-forward to the merge head.
3985 rollback_lock_file(&lock
);
3987 ret
= error(_("octopus merge cannot be executed on "
3988 "top of a [new root]"));
3990 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3991 &head_commit
->object
.oid
, 0,
3997 * If HEAD is not identical to the first parent of the original merge
3998 * commit, we cannot fast-forward.
4000 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
4001 oideq(&commit
->parents
->item
->object
.oid
,
4002 &head_commit
->object
.oid
);
4005 * If any merge head is different from the original one, we cannot
4008 if (can_fast_forward
) {
4009 struct commit_list
*p
= commit
->parents
->next
;
4011 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
4012 if (!oideq(&j
->item
->object
.oid
,
4013 &p
->item
->object
.oid
)) {
4014 can_fast_forward
= 0;
4018 * If the number of merge heads differs from the original merge
4019 * commit, we cannot fast-forward.
4022 can_fast_forward
= 0;
4025 if (can_fast_forward
) {
4026 rollback_lock_file(&lock
);
4027 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4028 &head_commit
->object
.oid
, 0, opts
);
4029 if (flags
& TODO_EDIT_MERGE_MSG
)
4030 goto fast_forward_edit
;
4036 const char *encoding
= get_commit_output_encoding();
4037 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4043 ret
= error(_("could not get commit message of '%s'"),
4044 oid_to_hex(&commit
->object
.oid
));
4047 write_author_script(message
);
4048 find_commit_subject(message
, &body
);
4050 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4051 repo_unuse_commit_buffer(r
, commit
, message
);
4053 error_errno(_("could not write '%s'"),
4054 git_path_merge_msg(r
));
4058 struct strbuf buf
= STRBUF_INIT
;
4061 strbuf_addf(&buf
, "author %s", git_author_info(0));
4062 write_author_script(buf
.buf
);
4065 if (oneline_offset
< arg_len
) {
4066 p
= arg
+ oneline_offset
;
4067 len
= arg_len
- oneline_offset
;
4069 strbuf_addf(&buf
, "Merge %s '%.*s'",
4070 to_merge
->next
? "branches" : "branch",
4071 merge_arg_len
, arg
);
4076 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4077 strbuf_release(&buf
);
4079 error_errno(_("could not write '%s'"),
4080 git_path_merge_msg(r
));
4085 if (strategy
|| to_merge
->next
) {
4087 struct child_process cmd
= CHILD_PROCESS_INIT
;
4089 if (read_env_script(&cmd
.env
)) {
4090 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4092 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4096 if (opts
->committer_date_is_author_date
)
4097 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4100 author_date_from_env(&cmd
.env
));
4101 if (opts
->ignore_date
)
4102 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4105 strvec_push(&cmd
.args
, "merge");
4106 strvec_push(&cmd
.args
, "-s");
4108 strvec_push(&cmd
.args
, "octopus");
4110 strvec_push(&cmd
.args
, strategy
);
4111 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4112 strvec_pushf(&cmd
.args
,
4113 "-X%s", opts
->xopts
.v
[k
]);
4115 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4116 strvec_push(&cmd
.args
, "--no-edit");
4118 strvec_push(&cmd
.args
, "--edit");
4119 strvec_push(&cmd
.args
, "--no-ff");
4120 strvec_push(&cmd
.args
, "--no-log");
4121 strvec_push(&cmd
.args
, "--no-stat");
4122 strvec_push(&cmd
.args
, "-F");
4123 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4125 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4127 strvec_push(&cmd
.args
, "--no-gpg-sign");
4129 /* Add the tips to be merged */
4130 for (j
= to_merge
; j
; j
= j
->next
)
4131 strvec_push(&cmd
.args
,
4132 oid_to_hex(&j
->item
->object
.oid
));
4134 strbuf_release(&ref_name
);
4135 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4136 NULL
, REF_NO_DEREF
);
4137 rollback_lock_file(&lock
);
4139 ret
= run_command(&cmd
);
4141 /* force re-reading of the cache */
4143 discard_index(r
->index
);
4144 if (repo_read_index(r
) < 0)
4145 ret
= error(_("could not read index"));
4150 merge_commit
= to_merge
->item
;
4151 bases
= repo_get_merge_bases(r
, head_commit
, merge_commit
);
4152 if (bases
&& oideq(&merge_commit
->object
.oid
,
4153 &bases
->item
->object
.oid
)) {
4155 /* skip merging an ancestor of HEAD */
4159 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4160 git_path_merge_head(r
), 0);
4161 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4163 bases
= reverse_commit_list(bases
);
4166 init_merge_options(&o
, r
);
4168 o
.branch2
= ref_name
.buf
;
4169 o
.buffer_output
= 2;
4171 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4173 * TODO: Should use merge_incore_recursive() and
4174 * merge_switch_to_result(), skipping the call to
4175 * merge_switch_to_result() when we don't actually need to
4176 * update the index and working copy immediately.
4178 ret
= merge_ort_recursive(&o
,
4179 head_commit
, merge_commit
, bases
,
4182 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4186 fputs(o
.obuf
.buf
, stdout
);
4187 strbuf_release(&o
.obuf
);
4189 error(_("could not even attempt to merge '%.*s'"),
4190 merge_arg_len
, arg
);
4191 unlink(git_path_merge_msg(r
));
4195 * The return value of merge_recursive() is 1 on clean, and 0 on
4198 * Let's reverse that, so that do_merge() returns 0 upon success and
4199 * 1 upon failed merge (keeping the return value -1 for the cases where
4200 * we will want to reschedule the `merge` command).
4204 if (r
->index
->cache_changed
&&
4205 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4206 ret
= error(_("merge: Unable to write new index file"));
4210 rollback_lock_file(&lock
);
4212 repo_rerere(r
, opts
->allow_rerere_auto
);
4215 * In case of problems, we now want to return a positive
4216 * value (a negative one would indicate that the `merge`
4217 * command needs to be rescheduled).
4219 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4222 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4225 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4226 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4231 strbuf_release(&ref_name
);
4232 rollback_lock_file(&lock
);
4233 free_commit_list(to_merge
);
4237 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4240 struct lock_file lock
= LOCK_INIT
;
4242 struct string_list_item
*item
;
4245 path
= rebase_path_update_refs(the_repository
->gitdir
);
4247 if (!refs_to_oids
->nr
) {
4248 if (unlink(path
) && errno
!= ENOENT
)
4249 result
= error_errno(_("could not unlink: %s"), path
);
4253 if (safe_create_leading_directories(path
)) {
4254 result
= error(_("unable to create leading directories of %s"),
4259 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4260 result
= error(_("another 'rebase' process appears to be running; "
4261 "'%s.lock' already exists"),
4266 fp
= fdopen_lock_file(&lock
, "w");
4268 result
= error_errno(_("could not open '%s' for writing"), path
);
4269 rollback_lock_file(&lock
);
4273 for_each_string_list_item(item
, refs_to_oids
) {
4274 struct update_ref_record
*rec
= item
->util
;
4275 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4276 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4279 result
= commit_lock_file(&lock
);
4287 * Parse the update-refs file for the current rebase, then remove the
4288 * refs that do not appear in the todo_list (and have not had updated
4289 * values stored) and add refs that are in the todo_list but not
4290 * represented in the update-refs file.
4292 * If there are changes to the update-refs list, then write the new state
4295 void todo_list_filter_update_refs(struct repository
*r
,
4296 struct todo_list
*todo_list
)
4300 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4302 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4305 * For each item in the update_refs list, if it has no updated
4306 * value and does not appear in the todo_list, then remove it
4307 * from the update_refs list.
4309 for (i
= 0; i
< update_refs
.nr
; i
++) {
4312 const char *ref
= update_refs
.items
[i
].string
;
4313 size_t reflen
= strlen(ref
);
4314 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4316 /* OID already stored as updated. */
4317 if (!is_null_oid(&rec
->after
))
4320 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4321 struct todo_item
*item
= &todo_list
->items
[j
];
4322 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4324 if (item
->command
!= TODO_UPDATE_REF
)
4327 if (item
->arg_len
!= reflen
||
4328 strncmp(arg
, ref
, reflen
))
4335 free(update_refs
.items
[i
].string
);
4336 free(update_refs
.items
[i
].util
);
4339 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4347 * For each todo_item, check if its ref is in the update_refs list.
4348 * If not, then add it as an un-updated ref.
4350 for (i
= 0; i
< todo_list
->nr
; i
++) {
4351 struct todo_item
*item
= &todo_list
->items
[i
];
4352 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4355 if (item
->command
!= TODO_UPDATE_REF
)
4358 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4359 const char *ref
= update_refs
.items
[j
].string
;
4361 found
= strlen(ref
) == item
->arg_len
&&
4362 !strncmp(ref
, arg
, item
->arg_len
);
4366 struct string_list_item
*inserted
;
4367 struct strbuf argref
= STRBUF_INIT
;
4369 strbuf_add(&argref
, arg
, item
->arg_len
);
4370 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4371 inserted
->util
= init_update_ref_record(argref
.buf
);
4372 strbuf_release(&argref
);
4378 write_update_refs_state(&update_refs
);
4379 string_list_clear(&update_refs
, 1);
4382 static int do_update_ref(struct repository
*r
, const char *refname
)
4384 struct string_list_item
*item
;
4385 struct string_list list
= STRING_LIST_INIT_DUP
;
4387 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4390 for_each_string_list_item(item
, &list
) {
4391 if (!strcmp(item
->string
, refname
)) {
4392 struct update_ref_record
*rec
= item
->util
;
4393 if (read_ref("HEAD", &rec
->after
))
4399 write_update_refs_state(&list
);
4400 string_list_clear(&list
, 1);
4404 static int do_update_refs(struct repository
*r
, int quiet
)
4407 struct string_list_item
*item
;
4408 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4409 struct ref_store
*refs
= get_main_ref_store(r
);
4410 struct strbuf update_msg
= STRBUF_INIT
;
4411 struct strbuf error_msg
= STRBUF_INIT
;
4413 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4416 for_each_string_list_item(item
, &refs_to_oids
) {
4417 struct update_ref_record
*rec
= item
->util
;
4420 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4422 &rec
->after
, &rec
->before
,
4423 0, UPDATE_REFS_MSG_ON_ERR
);
4430 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4432 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4436 (update_msg
.len
|| error_msg
.len
)) {
4438 _("Updated the following refs with %s:\n%s"),
4444 _("Failed to update the following refs with %s:\n%s"),
4449 string_list_clear(&refs_to_oids
, 1);
4450 strbuf_release(&update_msg
);
4451 strbuf_release(&error_msg
);
4455 static int is_final_fixup(struct todo_list
*todo_list
)
4457 int i
= todo_list
->current
;
4459 if (!is_fixup(todo_list
->items
[i
].command
))
4462 while (++i
< todo_list
->nr
)
4463 if (is_fixup(todo_list
->items
[i
].command
))
4465 else if (!is_noop(todo_list
->items
[i
].command
))
4470 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4474 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4475 if (!is_noop(todo_list
->items
[i
].command
))
4476 return todo_list
->items
[i
].command
;
4481 static void create_autostash_internal(struct repository
*r
,
4483 const char *refname
)
4485 struct strbuf buf
= STRBUF_INIT
;
4486 struct lock_file lock_file
= LOCK_INIT
;
4489 if (path
&& refname
)
4490 BUG("can only pass path or refname");
4492 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4493 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4495 repo_update_index_if_able(r
, &lock_file
);
4496 rollback_lock_file(&lock_file
);
4498 if (has_unstaged_changes(r
, 1) ||
4499 has_uncommitted_changes(r
, 1)) {
4500 struct child_process stash
= CHILD_PROCESS_INIT
;
4501 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4502 struct object_id oid
;
4504 strvec_pushl(&stash
.args
,
4505 "stash", "create", "autostash", NULL
);
4509 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4510 die(_("Cannot autostash"));
4511 strbuf_trim_trailing_newline(&buf
);
4512 if (repo_get_oid(r
, buf
.buf
, &oid
))
4513 die(_("Unexpected stash response: '%s'"),
4516 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4519 if (safe_create_leading_directories_const(path
))
4520 die(_("Could not create directory for '%s'"),
4522 write_file(path
, "%s", oid_to_hex(&oid
));
4524 refs_update_ref(get_main_ref_store(r
), "", refname
,
4525 &oid
, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR
);
4528 printf(_("Created autostash: %s\n"), buf
.buf
);
4529 if (reset_head(r
, &ropts
) < 0)
4530 die(_("could not reset --hard"));
4531 discard_index(r
->index
);
4532 if (repo_read_index(r
) < 0)
4533 die(_("could not read index"));
4535 strbuf_release(&buf
);
4538 void create_autostash(struct repository
*r
, const char *path
)
4540 create_autostash_internal(r
, path
, NULL
);
4543 void create_autostash_ref(struct repository
*r
, const char *refname
)
4545 create_autostash_internal(r
, NULL
, refname
);
4548 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4550 struct child_process child
= CHILD_PROCESS_INIT
;
4553 if (attempt_apply
) {
4555 child
.no_stdout
= 1;
4556 child
.no_stderr
= 1;
4557 strvec_push(&child
.args
, "stash");
4558 strvec_push(&child
.args
, "apply");
4559 strvec_push(&child
.args
, stash_oid
);
4560 ret
= run_command(&child
);
4563 if (attempt_apply
&& !ret
)
4564 fprintf(stderr
, _("Applied autostash.\n"));
4566 struct child_process store
= CHILD_PROCESS_INIT
;
4569 strvec_push(&store
.args
, "stash");
4570 strvec_push(&store
.args
, "store");
4571 strvec_push(&store
.args
, "-m");
4572 strvec_push(&store
.args
, "autostash");
4573 strvec_push(&store
.args
, "-q");
4574 strvec_push(&store
.args
, stash_oid
);
4575 if (run_command(&store
))
4576 ret
= error(_("cannot store %s"), stash_oid
);
4580 "Your changes are safe in the stash.\n"
4581 "You can run \"git stash pop\" or"
4582 " \"git stash drop\" at any time.\n"),
4584 _("Applying autostash resulted in conflicts.") :
4585 _("Autostash exists; creating a new stash entry."));
4591 static int apply_save_autostash(const char *path
, int attempt_apply
)
4593 struct strbuf stash_oid
= STRBUF_INIT
;
4596 if (!read_oneliner(&stash_oid
, path
,
4597 READ_ONELINER_SKIP_IF_EMPTY
)) {
4598 strbuf_release(&stash_oid
);
4601 strbuf_trim(&stash_oid
);
4603 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4606 strbuf_release(&stash_oid
);
4610 int save_autostash(const char *path
)
4612 return apply_save_autostash(path
, 0);
4615 int apply_autostash(const char *path
)
4617 return apply_save_autostash(path
, 1);
4620 int apply_autostash_oid(const char *stash_oid
)
4622 return apply_save_autostash_oid(stash_oid
, 1);
4625 static int apply_save_autostash_ref(struct repository
*r
, const char *refname
,
4628 struct object_id stash_oid
;
4629 char stash_oid_hex
[GIT_MAX_HEXSZ
+ 1];
4632 if (!refs_ref_exists(get_main_ref_store(r
), refname
))
4635 if (!refs_resolve_ref_unsafe(get_main_ref_store(r
), refname
,
4636 RESOLVE_REF_READING
, &stash_oid
, &flag
))
4638 if (flag
& REF_ISSYMREF
)
4639 return error(_("autostash reference is a symref"));
4641 oid_to_hex_r(stash_oid_hex
, &stash_oid
);
4642 ret
= apply_save_autostash_oid(stash_oid_hex
, attempt_apply
);
4644 refs_delete_ref(get_main_ref_store(r
), "", refname
,
4645 &stash_oid
, REF_NO_DEREF
);
4650 int save_autostash_ref(struct repository
*r
, const char *refname
)
4652 return apply_save_autostash_ref(r
, refname
, 0);
4655 int apply_autostash_ref(struct repository
*r
, const char *refname
)
4657 return apply_save_autostash_ref(r
, refname
, 1);
4660 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4661 const char *onto_name
, const struct object_id
*onto
,
4662 const struct object_id
*orig_head
)
4664 struct reset_head_opts ropts
= {
4666 .orig_head
= orig_head
,
4667 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4668 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4669 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4671 .default_reflog_action
= sequencer_reflog_action(opts
)
4673 if (reset_head(r
, &ropts
)) {
4674 apply_autostash(rebase_path_autostash());
4675 sequencer_remove_state(opts
);
4676 return error(_("could not detach HEAD"));
4682 static int stopped_at_head(struct repository
*r
)
4684 struct object_id head
;
4685 struct commit
*commit
;
4686 struct commit_message message
;
4688 if (repo_get_oid(r
, "HEAD", &head
) ||
4689 !(commit
= lookup_commit(r
, &head
)) ||
4690 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4691 fprintf(stderr
, _("Stopped at HEAD\n"));
4693 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4694 free_message(commit
, &message
);
4700 static int reread_todo_if_changed(struct repository
*r
,
4701 struct todo_list
*todo_list
,
4702 struct replay_opts
*opts
)
4705 struct strbuf buf
= STRBUF_INIT
;
4707 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4709 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4710 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4711 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4712 /* Reread the todo file if it has changed. */
4713 todo_list_release(todo_list
);
4714 if (read_populate_todo(r
, todo_list
, opts
))
4715 return -1; /* message was printed */
4716 /* `current` will be incremented on return */
4717 todo_list
->current
= -1;
4719 strbuf_release(&buf
);
4724 static const char rescheduled_advice
[] =
4725 N_("Could not execute the todo command\n"
4729 "It has been rescheduled; To edit the command before continuing, please\n"
4730 "edit the todo list first:\n"
4732 " git rebase --edit-todo\n"
4733 " git rebase --continue\n");
4735 static int pick_one_commit(struct repository
*r
,
4736 struct todo_list
*todo_list
,
4737 struct replay_opts
*opts
,
4738 int *check_todo
, int* reschedule
)
4741 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4742 const char *arg
= todo_item_get_arg(todo_list
, item
);
4743 if (is_rebase_i(opts
))
4744 opts
->reflog_message
= reflog_message(
4745 opts
, command_to_string(item
->command
), NULL
);
4747 res
= do_pick_commit(r
, item
, opts
, is_final_fixup(todo_list
),
4749 if (is_rebase_i(opts
) && res
< 0) {
4754 if (item
->command
== TODO_EDIT
) {
4755 struct commit
*commit
= item
->commit
;
4759 fprintf(stderr
, _("Stopped at %s... %.*s\n"),
4760 short_commit_name(r
, commit
), item
->arg_len
, arg
);
4762 return error_with_patch(r
, commit
,
4763 arg
, item
->arg_len
, opts
, res
, !res
);
4765 if (is_rebase_i(opts
) && !res
)
4766 record_in_rewritten(&item
->commit
->object
.oid
,
4767 peek_command(todo_list
, 1));
4768 if (res
&& is_fixup(item
->command
)) {
4771 return error_failed_squash(r
, item
->commit
, opts
,
4772 item
->arg_len
, arg
);
4773 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4775 struct object_id oid
;
4778 * If we are rewording and have either
4779 * fast-forwarded already, or are about to
4780 * create a new root commit, we want to amend,
4781 * otherwise we do not.
4783 if (item
->command
== TODO_REWORD
&&
4784 !repo_get_oid(r
, "HEAD", &oid
) &&
4785 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4786 (opts
->have_squash_onto
&&
4787 oideq(&opts
->squash_onto
, &oid
))))
4790 return res
| error_with_patch(r
, item
->commit
,
4791 arg
, item
->arg_len
, opts
,
4797 static int pick_commits(struct repository
*r
,
4798 struct todo_list
*todo_list
,
4799 struct replay_opts
*opts
)
4801 int res
= 0, reschedule
= 0;
4803 opts
->reflog_message
= sequencer_reflog_action(opts
);
4805 assert(!(opts
->signoff
|| opts
->no_commit
||
4806 opts
->record_origin
|| should_edit(opts
) ||
4807 opts
->committer_date_is_author_date
||
4808 opts
->ignore_date
));
4809 if (read_and_refresh_cache(r
, opts
))
4812 unlink(rebase_path_message());
4813 unlink(rebase_path_stopped_sha());
4814 unlink(rebase_path_amend());
4815 unlink(rebase_path_patch());
4817 while (todo_list
->current
< todo_list
->nr
) {
4818 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4819 const char *arg
= todo_item_get_arg(todo_list
, item
);
4822 if (save_todo(todo_list
, opts
, reschedule
))
4824 if (is_rebase_i(opts
)) {
4825 if (item
->command
!= TODO_COMMENT
) {
4826 FILE *f
= fopen(rebase_path_msgnum(), "w");
4828 todo_list
->done_nr
++;
4831 fprintf(f
, "%d\n", todo_list
->done_nr
);
4835 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4837 todo_list
->total_nr
,
4838 opts
->verbose
? "\n" : "\r");
4840 unlink(rebase_path_author_script());
4841 unlink(git_path_merge_head(r
));
4842 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
4843 NULL
, REF_NO_DEREF
);
4844 refs_delete_ref(get_main_ref_store(r
), "", "REBASE_HEAD",
4845 NULL
, REF_NO_DEREF
);
4847 if (item
->command
== TODO_BREAK
) {
4850 return stopped_at_head(r
);
4853 if (item
->command
<= TODO_SQUASH
) {
4854 res
= pick_one_commit(r
, todo_list
, opts
, &check_todo
,
4856 if (!res
&& item
->command
== TODO_EDIT
)
4858 } else if (item
->command
== TODO_EXEC
) {
4859 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4860 int saved
= *end_of_arg
;
4865 res
= do_exec(r
, arg
);
4866 *end_of_arg
= saved
;
4869 if (opts
->reschedule_failed_exec
)
4873 } else if (item
->command
== TODO_LABEL
) {
4874 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4876 } else if (item
->command
== TODO_RESET
) {
4877 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4879 } else if (item
->command
== TODO_MERGE
) {
4880 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4881 item
->flags
, &check_todo
, opts
)) < 0)
4883 else if (item
->commit
)
4884 record_in_rewritten(&item
->commit
->object
.oid
,
4885 peek_command(todo_list
, 1));
4887 /* failed with merge conflicts */
4888 return error_with_patch(r
, item
->commit
,
4891 } else if (item
->command
== TODO_UPDATE_REF
) {
4892 struct strbuf ref
= STRBUF_INIT
;
4893 strbuf_add(&ref
, arg
, item
->arg_len
);
4894 if ((res
= do_update_ref(r
, ref
.buf
)))
4896 strbuf_release(&ref
);
4897 } else if (!is_noop(item
->command
))
4898 return error(_("unknown command %d"), item
->command
);
4901 advise(_(rescheduled_advice
),
4902 get_item_line_length(todo_list
,
4903 todo_list
->current
),
4904 get_item_line(todo_list
, todo_list
->current
));
4905 if (save_todo(todo_list
, opts
, reschedule
))
4908 write_rebase_head(&item
->commit
->object
.oid
);
4909 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4910 reread_todo_if_changed(r
, todo_list
, opts
)) {
4917 todo_list
->current
++;
4920 if (is_rebase_i(opts
)) {
4921 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4924 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4925 starts_with(head_ref
.buf
, "refs/")) {
4927 struct object_id head
, orig
;
4930 if (repo_get_oid(r
, "HEAD", &head
)) {
4931 res
= error(_("cannot read HEAD"));
4933 strbuf_release(&head_ref
);
4934 strbuf_release(&buf
);
4937 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4938 get_oid_hex(buf
.buf
, &orig
)) {
4939 res
= error(_("could not read orig-head"));
4940 goto cleanup_head_ref
;
4943 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4944 res
= error(_("could not read 'onto'"));
4945 goto cleanup_head_ref
;
4947 msg
= reflog_message(opts
, "finish", "%s onto %s",
4948 head_ref
.buf
, buf
.buf
);
4949 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4950 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4951 res
= error(_("could not update %s"),
4953 goto cleanup_head_ref
;
4955 msg
= reflog_message(opts
, "finish", "returning to %s",
4957 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4958 res
= error(_("could not update HEAD to %s"),
4960 goto cleanup_head_ref
;
4965 if (opts
->verbose
) {
4966 struct rev_info log_tree_opt
;
4967 struct object_id orig
, head
;
4969 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4970 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4971 log_tree_opt
.diff
= 1;
4972 log_tree_opt
.diffopt
.output_format
=
4973 DIFF_FORMAT_DIFFSTAT
;
4974 log_tree_opt
.disable_stdin
= 1;
4976 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4977 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4978 !repo_get_oid(r
, "HEAD", &head
)) {
4979 diff_tree_oid(&orig
, &head
, "",
4980 &log_tree_opt
.diffopt
);
4981 log_tree_diff_flush(&log_tree_opt
);
4983 release_revisions(&log_tree_opt
);
4985 flush_rewritten_pending();
4986 if (!stat(rebase_path_rewritten_list(), &st
) &&
4988 struct child_process child
= CHILD_PROCESS_INIT
;
4989 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4991 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4993 strvec_push(&child
.args
, "notes");
4994 strvec_push(&child
.args
, "copy");
4995 strvec_push(&child
.args
, "--for-rewrite=rebase");
4996 /* we don't care if this copying failed */
4997 run_command(&child
);
4999 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
5000 strvec_push(&hook_opt
.args
, "rebase");
5001 run_hooks_opt("post-rewrite", &hook_opt
);
5003 apply_autostash(rebase_path_autostash());
5009 _("Successfully rebased and updated %s.\n"),
5013 strbuf_release(&buf
);
5014 strbuf_release(&head_ref
);
5016 if (do_update_refs(r
, opts
->quiet
))
5021 * Sequence of picks finished successfully; cleanup by
5022 * removing the .git/sequencer directory
5024 return sequencer_remove_state(opts
);
5027 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
5029 struct child_process cmd
= CHILD_PROCESS_INIT
;
5031 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
5032 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
5033 return error(_("no cherry-pick or revert in progress"));
5036 strvec_push(&cmd
.args
, "commit");
5039 * continue_single_pick() handles the case of recovering from a
5040 * conflict. should_edit() doesn't handle that case; for a conflict,
5041 * we want to edit if the user asked for it, or if they didn't specify
5042 * and stdin is a tty.
5044 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
5046 * Include --cleanup=strip as well because we don't want the
5047 * "# Conflicts:" messages.
5049 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
5051 return run_command(&cmd
);
5054 static int commit_staged_changes(struct repository
*r
,
5055 struct replay_opts
*opts
,
5056 struct todo_list
*todo_list
)
5058 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
5059 unsigned int final_fixup
= 0, is_clean
;
5061 if (has_unstaged_changes(r
, 1))
5062 return error(_("cannot rebase: You have unstaged changes."));
5064 is_clean
= !has_uncommitted_changes(r
, 0);
5066 if (!is_clean
&& !file_exists(rebase_path_message())) {
5067 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
5069 return error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
5071 if (file_exists(rebase_path_amend())) {
5072 struct strbuf rev
= STRBUF_INIT
;
5073 struct object_id head
, to_amend
;
5075 if (repo_get_oid(r
, "HEAD", &head
))
5076 return error(_("cannot amend non-existing commit"));
5077 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
5078 return error(_("invalid file: '%s'"), rebase_path_amend());
5079 if (get_oid_hex(rev
.buf
, &to_amend
))
5080 return error(_("invalid contents: '%s'"),
5081 rebase_path_amend());
5082 if (!is_clean
&& !oideq(&head
, &to_amend
))
5083 return error(_("\nYou have uncommitted changes in your "
5084 "working tree. Please, commit them\n"
5085 "first and then run 'git rebase "
5086 "--continue' again."));
5088 * When skipping a failed fixup/squash, we need to edit the
5089 * commit message, the current fixup list and count, and if it
5090 * was the last fixup/squash in the chain, we need to clean up
5091 * the commit message and if there was a squash, let the user
5094 if (!is_clean
|| !opts
->current_fixup_count
)
5095 ; /* this is not the final fixup */
5096 else if (!oideq(&head
, &to_amend
) ||
5097 !file_exists(rebase_path_stopped_sha())) {
5098 /* was a final fixup or squash done manually? */
5099 if (!is_fixup(peek_command(todo_list
, 0))) {
5100 unlink(rebase_path_fixup_msg());
5101 unlink(rebase_path_squash_msg());
5102 unlink(rebase_path_current_fixups());
5103 strbuf_reset(&opts
->current_fixups
);
5104 opts
->current_fixup_count
= 0;
5107 /* we are in a fixup/squash chain */
5108 const char *p
= opts
->current_fixups
.buf
;
5109 int len
= opts
->current_fixups
.len
;
5111 opts
->current_fixup_count
--;
5113 BUG("Incorrect current_fixups:\n%s", p
);
5114 while (len
&& p
[len
- 1] != '\n')
5116 strbuf_setlen(&opts
->current_fixups
, len
);
5117 if (write_message(p
, len
, rebase_path_current_fixups(),
5119 return error(_("could not write file: '%s'"),
5120 rebase_path_current_fixups());
5123 * If a fixup/squash in a fixup/squash chain failed, the
5124 * commit message is already correct, no need to commit
5127 * Only if it is the final command in the fixup/squash
5128 * chain, and only if the chain is longer than a single
5129 * fixup/squash command (which was just skipped), do we
5130 * actually need to re-commit with a cleaned up commit
5133 if (opts
->current_fixup_count
> 0 &&
5134 !is_fixup(peek_command(todo_list
, 0))) {
5137 * If there was not a single "squash" in the
5138 * chain, we only need to clean up the commit
5139 * message, no need to bother the user with
5140 * opening the commit message in the editor.
5142 if (!starts_with(p
, "squash ") &&
5143 !strstr(p
, "\nsquash "))
5144 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5145 } else if (is_fixup(peek_command(todo_list
, 0))) {
5147 * We need to update the squash message to skip
5148 * the latest commit message.
5151 struct commit
*commit
;
5153 const char *path
= rebase_path_squash_msg();
5154 const char *encoding
= get_commit_output_encoding();
5156 if (parse_head(r
, &commit
))
5157 return error(_("could not parse HEAD"));
5159 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5161 res
= error(_("could not parse commit %s"),
5162 oid_to_hex(&commit
->object
.oid
));
5163 goto unuse_commit_buffer
;
5165 find_commit_subject(p
, &msg
);
5166 if (write_message(msg
, strlen(msg
), path
, 0)) {
5167 res
= error(_("could not write file: "
5169 goto unuse_commit_buffer
;
5171 unuse_commit_buffer
:
5172 repo_unuse_commit_buffer(r
, commit
, p
);
5178 strbuf_release(&rev
);
5183 if (refs_ref_exists(get_main_ref_store(r
),
5184 "CHERRY_PICK_HEAD") &&
5185 refs_delete_ref(get_main_ref_store(r
), "",
5186 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
))
5187 return error(_("could not remove CHERRY_PICK_HEAD"));
5188 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5189 return error_errno(_("could not remove '%s'"),
5190 git_path_merge_msg(r
));
5195 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5197 return error(_("could not commit staged changes."));
5198 unlink(rebase_path_amend());
5199 unlink(git_path_merge_head(r
));
5200 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
5201 NULL
, REF_NO_DEREF
);
5203 unlink(rebase_path_fixup_msg());
5204 unlink(rebase_path_squash_msg());
5206 if (opts
->current_fixup_count
> 0) {
5208 * Whether final fixup or not, we just cleaned up the commit
5211 unlink(rebase_path_current_fixups());
5212 strbuf_reset(&opts
->current_fixups
);
5213 opts
->current_fixup_count
= 0;
5218 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5220 struct todo_list todo_list
= TODO_LIST_INIT
;
5223 if (read_and_refresh_cache(r
, opts
))
5226 if (read_populate_opts(opts
))
5228 if (is_rebase_i(opts
)) {
5229 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5230 goto release_todo_list
;
5232 if (file_exists(rebase_path_dropped())) {
5233 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5234 goto release_todo_list
;
5236 unlink(rebase_path_dropped());
5239 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5240 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5242 goto release_todo_list
;
5244 } else if (!file_exists(get_todo_path(opts
)))
5245 return continue_single_pick(r
, opts
);
5246 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5247 goto release_todo_list
;
5249 if (!is_rebase_i(opts
)) {
5250 /* Verify that the conflict has been resolved */
5251 if (refs_ref_exists(get_main_ref_store(r
),
5252 "CHERRY_PICK_HEAD") ||
5253 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5254 res
= continue_single_pick(r
, opts
);
5256 goto release_todo_list
;
5258 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5259 res
= error_dirty_index(r
, opts
);
5260 goto release_todo_list
;
5262 todo_list
.current
++;
5263 } else if (file_exists(rebase_path_stopped_sha())) {
5264 struct strbuf buf
= STRBUF_INIT
;
5265 struct object_id oid
;
5267 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5268 READ_ONELINER_SKIP_IF_EMPTY
) &&
5269 !get_oid_hex(buf
.buf
, &oid
))
5270 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5271 strbuf_release(&buf
);
5274 res
= pick_commits(r
, &todo_list
, opts
);
5276 todo_list_release(&todo_list
);
5280 static int single_pick(struct repository
*r
,
5281 struct commit
*cmit
,
5282 struct replay_opts
*opts
)
5285 struct todo_item item
;
5287 item
.command
= opts
->action
== REPLAY_PICK
?
5288 TODO_PICK
: TODO_REVERT
;
5291 opts
->reflog_message
= sequencer_reflog_action(opts
);
5292 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5295 int sequencer_pick_revisions(struct repository
*r
,
5296 struct replay_opts
*opts
)
5298 struct todo_list todo_list
= TODO_LIST_INIT
;
5299 struct object_id oid
;
5303 if (read_and_refresh_cache(r
, opts
))
5306 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5307 struct object_id oid
;
5308 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5310 /* This happens when using --stdin. */
5314 if (!repo_get_oid(r
, name
, &oid
)) {
5315 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5316 enum object_type type
= oid_object_info(r
,
5319 return error(_("%s: can't cherry-pick a %s"),
5320 name
, type_name(type
));
5323 return error(_("%s: bad revision"), name
);
5327 * If we were called as "git cherry-pick <commit>", just
5328 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5329 * REVERT_HEAD, and don't touch the sequencer state.
5330 * This means it is possible to cherry-pick in the middle
5331 * of a cherry-pick sequence.
5333 if (opts
->revs
->cmdline
.nr
== 1 &&
5334 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5335 opts
->revs
->no_walk
&&
5336 !opts
->revs
->cmdline
.rev
->flags
) {
5337 struct commit
*cmit
;
5338 if (prepare_revision_walk(opts
->revs
))
5339 return error(_("revision walk setup failed"));
5340 cmit
= get_revision(opts
->revs
);
5342 return error(_("empty commit set passed"));
5343 if (get_revision(opts
->revs
))
5344 BUG("unexpected extra commit from walk");
5345 return single_pick(r
, cmit
, opts
);
5349 * Start a new cherry-pick/ revert sequence; but
5350 * first, make sure that an existing one isn't in
5354 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5355 create_seq_dir(r
) < 0)
5357 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5358 return error(_("can't revert as initial commit"));
5359 if (save_head(oid_to_hex(&oid
)))
5361 if (save_opts(opts
))
5363 update_abort_safety_file();
5364 res
= pick_commits(r
, &todo_list
, opts
);
5365 todo_list_release(&todo_list
);
5369 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5371 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5372 struct strbuf sob
= STRBUF_INIT
;
5375 strbuf_addstr(&sob
, sign_off_header
);
5376 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5377 strbuf_addch(&sob
, '\n');
5380 strbuf_complete_line(msgbuf
);
5383 * If the whole message buffer is equal to the sob, pretend that we
5384 * found a conforming footer with a matching sob
5386 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5387 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5390 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5393 const char *append_newlines
= NULL
;
5394 size_t len
= msgbuf
->len
- ignore_footer
;
5398 * The buffer is completely empty. Leave foom for
5399 * the title and body to be filled in by the user.
5401 append_newlines
= "\n\n";
5402 } else if (len
== 1) {
5404 * Buffer contains a single newline. Add another
5405 * so that we leave room for the title and body.
5407 append_newlines
= "\n";
5408 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5410 * Buffer ends with a single newline. Add another
5411 * so that there is an empty line between the message
5414 append_newlines
= "\n";
5415 } /* else, the buffer already ends with two newlines. */
5417 if (append_newlines
)
5418 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5419 append_newlines
, strlen(append_newlines
));
5422 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5423 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5426 strbuf_release(&sob
);
5429 struct labels_entry
{
5430 struct hashmap_entry entry
;
5431 char label
[FLEX_ARRAY
];
5434 static int labels_cmp(const void *fndata UNUSED
,
5435 const struct hashmap_entry
*eptr
,
5436 const struct hashmap_entry
*entry_or_key
, const void *key
)
5438 const struct labels_entry
*a
, *b
;
5440 a
= container_of(eptr
, const struct labels_entry
, entry
);
5441 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5443 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5446 struct string_entry
{
5447 struct oidmap_entry entry
;
5448 char string
[FLEX_ARRAY
];
5451 struct label_state
{
5452 struct oidmap commit2label
;
5453 struct hashmap labels
;
5455 int max_label_length
;
5458 static const char *label_oid(struct object_id
*oid
, const char *label
,
5459 struct label_state
*state
)
5461 struct labels_entry
*labels_entry
;
5462 struct string_entry
*string_entry
;
5463 struct object_id dummy
;
5466 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5468 return string_entry
->string
;
5471 * For "uninteresting" commits, i.e. commits that are not to be
5472 * rebased, and which can therefore not be labeled, we use a unique
5473 * abbreviation of the commit name. This is slightly more complicated
5474 * than calling repo_find_unique_abbrev() because we also need to make
5475 * sure that the abbreviation does not conflict with any other
5478 * We disallow "interesting" commits to be labeled by a string that
5479 * is a valid full-length hash, to ensure that we always can find an
5480 * abbreviation for any uninteresting commit's names that does not
5481 * clash with any other label.
5483 strbuf_reset(&state
->buf
);
5487 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5488 label
= p
= state
->buf
.buf
;
5490 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5494 * We may need to extend the abbreviated hash so that there is
5495 * no conflicting label.
5497 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5498 size_t i
= strlen(p
) + 1;
5500 oid_to_hex_r(p
, oid
);
5501 for (; i
< the_hash_algo
->hexsz
; i
++) {
5504 if (!hashmap_get_from_hash(&state
->labels
,
5511 struct strbuf
*buf
= &state
->buf
;
5512 int label_is_utf8
= 1; /* start with this assumption */
5513 size_t max_len
= buf
->len
+ state
->max_label_length
;
5516 * Sanitize labels by replacing non-alpha-numeric characters
5517 * (including white-space ones) by dashes, as they might be
5518 * illegal in file names (and hence in ref names).
5520 * Note that we retain non-ASCII UTF-8 characters (identified
5521 * via the most significant bit). They should be all acceptable
5524 * As we will use the labels as names of (loose) refs, it is
5525 * vital that the name not be longer than the maximum component
5526 * size of the file system (`NAME_MAX`). We are careful to
5527 * truncate the label accordingly, allowing for the `.lock`
5528 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5529 * truncating in the middle of a character).
5531 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5532 if (isalnum(*label
) ||
5533 (!label_is_utf8
&& (*label
& 0x80)))
5534 strbuf_addch(buf
, *label
);
5535 else if (*label
& 0x80) {
5536 const char *p
= label
;
5538 utf8_width(&p
, NULL
);
5540 if (buf
->len
+ (p
- label
) > max_len
)
5542 strbuf_add(buf
, label
, p
- label
);
5546 strbuf_addch(buf
, *label
);
5548 /* avoid leading dash and double-dashes */
5549 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5550 strbuf_addch(buf
, '-');
5552 strbuf_addstr(buf
, "rev-");
5553 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5557 if ((buf
->len
== the_hash_algo
->hexsz
&&
5558 !get_oid_hex(label
, &dummy
)) ||
5559 (buf
->len
== 1 && *label
== '#') ||
5560 hashmap_get_from_hash(&state
->labels
,
5561 strihash(label
), label
)) {
5563 * If the label already exists, or if the label is a
5564 * valid full OID, or the label is a '#' (which we use
5565 * as a separator between merge heads and oneline), we
5566 * append a dash and a number to make it unique.
5568 size_t len
= buf
->len
;
5570 for (i
= 2; ; i
++) {
5571 strbuf_setlen(buf
, len
);
5572 strbuf_addf(buf
, "-%d", i
);
5573 if (!hashmap_get_from_hash(&state
->labels
,
5583 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5584 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5585 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5587 FLEX_ALLOC_STR(string_entry
, string
, label
);
5588 oidcpy(&string_entry
->entry
.oid
, oid
);
5589 oidmap_put(&state
->commit2label
, string_entry
);
5591 return string_entry
->string
;
5594 static int make_script_with_merges(struct pretty_print_context
*pp
,
5595 struct rev_info
*revs
, struct strbuf
*out
,
5598 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5599 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5600 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5601 int skipped_commit
= 0;
5602 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5603 struct strbuf label
= STRBUF_INIT
;
5604 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5605 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5606 struct commit
*commit
;
5607 struct oidmap commit2todo
= OIDMAP_INIT
;
5608 struct string_entry
*entry
;
5609 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5610 shown
= OIDSET_INIT
;
5611 struct label_state state
=
5612 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5614 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5615 const char *cmd_pick
= abbr
? "p" : "pick",
5616 *cmd_label
= abbr
? "l" : "label",
5617 *cmd_reset
= abbr
? "t" : "reset",
5618 *cmd_merge
= abbr
? "m" : "merge";
5620 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5622 oidmap_init(&commit2todo
, 0);
5623 oidmap_init(&state
.commit2label
, 0);
5624 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5625 strbuf_init(&state
.buf
, 32);
5627 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5628 struct labels_entry
*onto_label_entry
;
5629 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5630 FLEX_ALLOC_STR(entry
, string
, "onto");
5631 oidcpy(&entry
->entry
.oid
, oid
);
5632 oidmap_put(&state
.commit2label
, entry
);
5634 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5635 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5636 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5641 * - get onelines for all commits
5642 * - gather all branch tips (i.e. 2nd or later parents of merges)
5643 * - label all branch tips
5645 while ((commit
= get_revision(revs
))) {
5646 struct commit_list
*to_merge
;
5647 const char *p1
, *p2
;
5648 struct object_id
*oid
;
5651 tail
= &commit_list_insert(commit
, tail
)->next
;
5652 oidset_insert(&interesting
, &commit
->object
.oid
);
5654 is_empty
= is_original_commit_empty(commit
);
5655 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5656 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5657 warning(_("skipped previously applied commit %s"),
5658 short_commit_name(the_repository
, commit
));
5662 if (is_empty
&& !keep_empty
)
5665 strbuf_reset(&oneline
);
5666 pretty_print_commit(pp
, commit
, &oneline
);
5668 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5670 /* non-merge commit: easy case */
5672 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5673 oid_to_hex(&commit
->object
.oid
),
5676 strbuf_addf(&buf
, " %c empty",
5679 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5680 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5681 oidmap_put(&commit2todo
, entry
);
5686 /* Create a label */
5687 strbuf_reset(&label
);
5688 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5689 (p1
= strchr(p1
, '\'')) &&
5690 (p2
= strchr(++p1
, '\'')))
5691 strbuf_add(&label
, p1
, p2
- p1
);
5692 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5694 (p1
= strstr(p1
, " from ")))
5695 strbuf_addstr(&label
, p1
+ strlen(" from "));
5697 strbuf_addbuf(&label
, &oneline
);
5700 strbuf_addf(&buf
, "%s -C %s",
5701 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5703 /* label the tips of merged branches */
5704 for (; to_merge
; to_merge
= to_merge
->next
) {
5705 oid
= &to_merge
->item
->object
.oid
;
5706 strbuf_addch(&buf
, ' ');
5708 if (!oidset_contains(&interesting
, oid
)) {
5709 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5714 tips_tail
= &commit_list_insert(to_merge
->item
,
5717 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5719 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5721 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5722 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5723 oidmap_put(&commit2todo
, entry
);
5726 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5727 _("use --reapply-cherry-picks to include skipped commits"));
5731 * - label branch points
5732 * - add HEAD to the branch tips
5734 for (iter
= commits
; iter
; iter
= iter
->next
) {
5735 struct commit_list
*parent
= iter
->item
->parents
;
5736 for (; parent
; parent
= parent
->next
) {
5737 struct object_id
*oid
= &parent
->item
->object
.oid
;
5738 if (!oidset_contains(&interesting
, oid
))
5740 if (oidset_insert(&child_seen
, oid
))
5741 label_oid(oid
, "branch-point", &state
);
5744 /* Add HEAD as implicit "tip of branch" */
5746 tips_tail
= &commit_list_insert(iter
->item
,
5751 * Third phase: output the todo list. This is a bit tricky, as we
5752 * want to avoid jumping back and forth between revisions. To
5753 * accomplish that goal, we walk backwards from the branch tips,
5754 * gathering commits not yet shown, reversing the list on the fly,
5755 * then outputting that list (labeling revisions as needed).
5757 strbuf_addf(out
, "%s onto\n", cmd_label
);
5758 for (iter
= tips
; iter
; iter
= iter
->next
) {
5759 struct commit_list
*list
= NULL
, *iter2
;
5761 commit
= iter
->item
;
5762 if (oidset_contains(&shown
, &commit
->object
.oid
))
5764 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5767 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5769 strbuf_addch(out
, '\n');
5771 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5772 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5773 commit_list_insert(commit
, &list
);
5774 if (!commit
->parents
) {
5778 commit
= commit
->parents
->item
;
5782 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5783 rebase_cousins
|| root_with_onto
?
5784 "onto" : "[new root]");
5786 const char *to
= NULL
;
5788 entry
= oidmap_get(&state
.commit2label
,
5789 &commit
->object
.oid
);
5792 else if (!rebase_cousins
)
5793 to
= label_oid(&commit
->object
.oid
, NULL
,
5796 if (!to
|| !strcmp(to
, "onto"))
5797 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5799 strbuf_reset(&oneline
);
5800 pretty_print_commit(pp
, commit
, &oneline
);
5801 strbuf_addf(out
, "%s %s # %s\n",
5802 cmd_reset
, to
, oneline
.buf
);
5806 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5807 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5808 entry
= oidmap_get(&commit2todo
, oid
);
5809 /* only show if not already upstream */
5811 strbuf_addf(out
, "%s\n", entry
->string
);
5812 entry
= oidmap_get(&state
.commit2label
, oid
);
5814 strbuf_addf(out
, "%s %s\n",
5815 cmd_label
, entry
->string
);
5816 oidset_insert(&shown
, oid
);
5819 free_commit_list(list
);
5822 free_commit_list(commits
);
5823 free_commit_list(tips
);
5825 strbuf_release(&label
);
5826 strbuf_release(&oneline
);
5827 strbuf_release(&buf
);
5829 oidmap_free(&commit2todo
, 1);
5830 oidmap_free(&state
.commit2label
, 1);
5831 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5832 strbuf_release(&state
.buf
);
5837 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5838 const char **argv
, unsigned flags
)
5840 char *format
= NULL
;
5841 struct pretty_print_context pp
= {0};
5842 struct rev_info revs
;
5843 struct commit
*commit
;
5844 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5845 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5846 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5847 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5848 int skipped_commit
= 0;
5851 repo_init_revisions(r
, &revs
, NULL
);
5852 revs
.verbose_header
= 1;
5854 revs
.max_parents
= 1;
5855 revs
.cherry_mark
= !reapply_cherry_picks
;
5858 revs
.right_only
= 1;
5859 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5860 revs
.topo_order
= 1;
5862 revs
.pretty_given
= 1;
5863 git_config_get_string("rebase.instructionFormat", &format
);
5864 if (!format
|| !*format
) {
5866 format
= xstrdup("%s");
5868 get_commit_format(format
, &revs
);
5870 pp
.fmt
= revs
.commit_format
;
5871 pp
.output_encoding
= get_log_output_encoding();
5873 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5874 ret
= error(_("make_script: unhandled options"));
5878 if (prepare_revision_walk(&revs
) < 0) {
5879 ret
= error(_("make_script: error preparing revisions"));
5883 if (rebase_merges
) {
5884 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5888 while ((commit
= get_revision(&revs
))) {
5889 int is_empty
= is_original_commit_empty(commit
);
5891 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5892 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5893 warning(_("skipped previously applied commit %s"),
5894 short_commit_name(r
, commit
));
5898 if (is_empty
&& !keep_empty
)
5900 strbuf_addf(out
, "%s %s ", insn
,
5901 oid_to_hex(&commit
->object
.oid
));
5902 pretty_print_commit(&pp
, commit
, out
);
5904 strbuf_addf(out
, " %c empty", comment_line_char
);
5905 strbuf_addch(out
, '\n');
5908 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5909 _("use --reapply-cherry-picks to include skipped commits"));
5911 release_revisions(&revs
);
5916 * Add commands after pick and (series of) squash/fixup commands
5919 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5920 struct string_list
*commands
)
5922 struct strbuf
*buf
= &todo_list
->buf
;
5923 size_t base_offset
= buf
->len
;
5924 int i
, insert
, nr
= 0, alloc
= 0;
5925 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5927 CALLOC_ARRAY(base_items
, commands
->nr
);
5928 for (i
= 0; i
< commands
->nr
; i
++) {
5929 size_t command_len
= strlen(commands
->items
[i
].string
);
5931 strbuf_addstr(buf
, commands
->items
[i
].string
);
5932 strbuf_addch(buf
, '\n');
5934 base_items
[i
].command
= TODO_EXEC
;
5935 base_items
[i
].offset_in_buf
= base_offset
;
5936 base_items
[i
].arg_offset
= base_offset
;
5937 base_items
[i
].arg_len
= command_len
;
5939 base_offset
+= command_len
+ 1;
5943 * Insert <commands> after every pick. Here, fixup/squash chains
5944 * are considered part of the pick, so we insert the commands *after*
5945 * those chains if there are any.
5947 * As we insert the exec commands immediately after rearranging
5948 * any fixups and before the user edits the list, a fixup chain
5949 * can never contain comments (any comments are empty picks that
5950 * have been commented out because the user did not specify
5951 * --keep-empty). So, it is safe to insert an exec command
5952 * without looking at the command following a comment.
5955 for (i
= 0; i
< todo_list
->nr
; i
++) {
5956 enum todo_command command
= todo_list
->items
[i
].command
;
5957 if (insert
&& !is_fixup(command
)) {
5958 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5959 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5965 ALLOC_GROW(items
, nr
+ 1, alloc
);
5966 items
[nr
++] = todo_list
->items
[i
];
5968 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5972 /* insert or append final <commands> */
5974 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5975 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5980 FREE_AND_NULL(todo_list
->items
);
5981 todo_list
->items
= items
;
5983 todo_list
->alloc
= alloc
;
5986 static void todo_list_to_strbuf(struct repository
*r
,
5987 struct todo_list
*todo_list
,
5988 struct strbuf
*buf
, int num
, unsigned flags
)
5990 struct todo_item
*item
;
5991 int i
, max
= todo_list
->nr
;
5993 if (num
> 0 && num
< max
)
5996 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5999 /* if the item is not a command write it and continue */
6000 if (item
->command
>= TODO_COMMENT
) {
6001 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
6002 todo_item_get_arg(todo_list
, item
));
6006 /* add command to the buffer */
6007 cmd
= command_to_char(item
->command
);
6008 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
6009 strbuf_addch(buf
, cmd
);
6011 strbuf_addstr(buf
, command_to_string(item
->command
));
6015 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
6016 short_commit_name(r
, item
->commit
) :
6017 oid_to_hex(&item
->commit
->object
.oid
);
6019 if (item
->command
== TODO_FIXUP
) {
6020 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
6021 strbuf_addstr(buf
, " -c");
6022 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
6023 strbuf_addstr(buf
, " -C");
6027 if (item
->command
== TODO_MERGE
) {
6028 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
6029 strbuf_addstr(buf
, " -c");
6031 strbuf_addstr(buf
, " -C");
6034 strbuf_addf(buf
, " %s", oid
);
6037 /* add all the rest */
6039 strbuf_addch(buf
, '\n');
6041 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
6042 todo_item_get_arg(todo_list
, item
));
6046 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
6047 const char *file
, const char *shortrevisions
,
6048 const char *shortonto
, int num
, unsigned flags
)
6051 struct strbuf buf
= STRBUF_INIT
;
6053 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
6054 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
6055 append_todo_help(count_commands(todo_list
),
6056 shortrevisions
, shortonto
, &buf
);
6058 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
6059 strbuf_release(&buf
);
6064 /* skip picking commits whose parents are unchanged */
6065 static int skip_unnecessary_picks(struct repository
*r
,
6066 struct todo_list
*todo_list
,
6067 struct object_id
*base_oid
)
6069 struct object_id
*parent_oid
;
6072 for (i
= 0; i
< todo_list
->nr
; i
++) {
6073 struct todo_item
*item
= todo_list
->items
+ i
;
6075 if (item
->command
>= TODO_NOOP
)
6077 if (item
->command
!= TODO_PICK
)
6079 if (repo_parse_commit(r
, item
->commit
)) {
6080 return error(_("could not parse commit '%s'"),
6081 oid_to_hex(&item
->commit
->object
.oid
));
6083 if (!item
->commit
->parents
)
6084 break; /* root commit */
6085 if (item
->commit
->parents
->next
)
6086 break; /* merge commit */
6087 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
6088 if (!oideq(parent_oid
, base_oid
))
6090 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6093 const char *done_path
= rebase_path_done();
6095 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6096 error_errno(_("could not write to '%s'"), done_path
);
6100 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6102 todo_list
->current
= 0;
6103 todo_list
->done_nr
+= i
;
6105 if (is_fixup(peek_command(todo_list
, 0)))
6106 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6112 struct todo_add_branch_context
{
6113 struct todo_item
*items
;
6117 struct commit
*commit
;
6118 struct string_list refs_to_oids
;
6121 static int add_decorations_to_list(const struct commit
*commit
,
6122 struct todo_add_branch_context
*ctx
)
6124 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6125 const char *head_ref
= resolve_ref_unsafe("HEAD",
6126 RESOLVE_REF_READING
,
6130 while (decoration
) {
6131 struct todo_item
*item
;
6133 size_t base_offset
= ctx
->buf
->len
;
6136 * If the branch is the current HEAD, then it will be
6137 * updated by the default rebase behavior.
6139 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6140 decoration
= decoration
->next
;
6144 ALLOC_GROW(ctx
->items
,
6147 item
= &ctx
->items
[ctx
->items_nr
];
6148 memset(item
, 0, sizeof(*item
));
6150 /* If the branch is checked out, then leave a comment instead. */
6151 if ((path
= branch_checked_out(decoration
->name
))) {
6152 item
->command
= TODO_COMMENT
;
6153 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6154 decoration
->name
, path
);
6156 struct string_list_item
*sti
;
6157 item
->command
= TODO_UPDATE_REF
;
6158 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6160 sti
= string_list_insert(&ctx
->refs_to_oids
,
6162 sti
->util
= init_update_ref_record(decoration
->name
);
6165 item
->offset_in_buf
= base_offset
;
6166 item
->arg_offset
= base_offset
;
6167 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6170 decoration
= decoration
->next
;
6177 * For each 'pick' command, find out if the commit has a decoration in
6178 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6180 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6183 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6184 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6185 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6186 struct decoration_filter decoration_filter
= {
6187 .include_ref_pattern
= &decorate_refs_include
,
6188 .exclude_ref_pattern
= &decorate_refs_exclude
,
6189 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6191 struct todo_add_branch_context ctx
= {
6192 .buf
= &todo_list
->buf
,
6193 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6196 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6197 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6199 string_list_append(&decorate_refs_include
, "refs/heads/");
6200 load_ref_decorations(&decoration_filter
, 0);
6202 for (i
= 0; i
< todo_list
->nr
; ) {
6203 struct todo_item
*item
= &todo_list
->items
[i
];
6205 /* insert ith item into new list */
6206 ALLOC_GROW(ctx
.items
,
6210 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6213 ctx
.commit
= item
->commit
;
6214 add_decorations_to_list(item
->commit
, &ctx
);
6218 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6220 string_list_clear(&ctx
.refs_to_oids
, 1);
6223 /* we failed, so clean up the new list. */
6228 free(todo_list
->items
);
6229 todo_list
->items
= ctx
.items
;
6230 todo_list
->nr
= ctx
.items_nr
;
6231 todo_list
->alloc
= ctx
.items_alloc
;
6236 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6237 const char *shortrevisions
, const char *onto_name
,
6238 struct commit
*onto
, const struct object_id
*orig_head
,
6239 struct string_list
*commands
, unsigned autosquash
,
6240 unsigned update_refs
,
6241 struct todo_list
*todo_list
)
6243 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6244 const char *todo_file
= rebase_path_todo();
6245 struct todo_list new_todo
= TODO_LIST_INIT
;
6246 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6247 struct object_id oid
= onto
->object
.oid
;
6250 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6253 if (buf
->len
== 0) {
6254 struct todo_item
*item
= append_new_todo(todo_list
);
6255 item
->command
= TODO_NOOP
;
6256 item
->commit
= NULL
;
6257 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6260 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6263 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6267 todo_list_add_exec_commands(todo_list
, commands
);
6269 if (count_commands(todo_list
) == 0) {
6270 apply_autostash(rebase_path_autostash());
6271 sequencer_remove_state(opts
);
6273 return error(_("nothing to do"));
6276 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6280 else if (res
== -2) {
6281 apply_autostash(rebase_path_autostash());
6282 sequencer_remove_state(opts
);
6285 } else if (res
== -3) {
6286 apply_autostash(rebase_path_autostash());
6287 sequencer_remove_state(opts
);
6288 todo_list_release(&new_todo
);
6290 return error(_("nothing to do"));
6291 } else if (res
== -4) {
6292 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6293 todo_list_release(&new_todo
);
6298 /* Expand the commit IDs */
6299 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6300 strbuf_swap(&new_todo
.buf
, &buf2
);
6301 strbuf_release(&buf2
);
6302 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6303 new_todo
.total_nr
= 0;
6304 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6305 BUG("invalid todo list after expanding IDs:\n%s",
6308 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6309 todo_list_release(&new_todo
);
6310 return error(_("could not skip unnecessary pick commands"));
6313 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6314 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6315 todo_list_release(&new_todo
);
6316 return error_errno(_("could not write '%s'"), todo_file
);
6321 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6324 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6327 todo_list_write_total_nr(&new_todo
);
6328 res
= pick_commits(r
, &new_todo
, opts
);
6331 todo_list_release(&new_todo
);
6336 struct subject2item_entry
{
6337 struct hashmap_entry entry
;
6339 char subject
[FLEX_ARRAY
];
6342 static int subject2item_cmp(const void *fndata UNUSED
,
6343 const struct hashmap_entry
*eptr
,
6344 const struct hashmap_entry
*entry_or_key
,
6347 const struct subject2item_entry
*a
, *b
;
6349 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6350 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6352 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6355 define_commit_slab(commit_todo_item
, struct todo_item
*);
6357 static int skip_fixupish(const char *subject
, const char **p
) {
6358 return skip_prefix(subject
, "fixup! ", p
) ||
6359 skip_prefix(subject
, "amend! ", p
) ||
6360 skip_prefix(subject
, "squash! ", p
);
6364 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6365 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6366 * after the former, and change "pick" to "fixup"/"squash".
6368 * Note that if the config has specified a custom instruction format, each log
6369 * message will have to be retrieved from the commit (as the oneline in the
6370 * script cannot be trusted) in order to normalize the autosquash arrangement.
6372 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6374 struct hashmap subject2item
;
6375 int rearranged
= 0, *next
, *tail
, i
, nr
= 0;
6377 struct commit_todo_item commit_todo
;
6378 struct todo_item
*items
= NULL
;
6380 init_commit_todo_item(&commit_todo
);
6382 * The hashmap maps onelines to the respective todo list index.
6384 * If any items need to be rearranged, the next[i] value will indicate
6385 * which item was moved directly after the i'th.
6387 * In that case, last[i] will indicate the index of the latest item to
6388 * be moved to appear after the i'th.
6390 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6391 ALLOC_ARRAY(next
, todo_list
->nr
);
6392 ALLOC_ARRAY(tail
, todo_list
->nr
);
6393 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6394 for (i
= 0; i
< todo_list
->nr
; i
++) {
6395 struct strbuf buf
= STRBUF_INIT
;
6396 struct todo_item
*item
= todo_list
->items
+ i
;
6397 const char *commit_buffer
, *subject
, *p
;
6400 struct subject2item_entry
*entry
;
6402 next
[i
] = tail
[i
] = -1;
6403 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6408 if (is_fixup(item
->command
)) {
6409 clear_commit_todo_item(&commit_todo
);
6410 return error(_("the script was already rearranged."));
6413 repo_parse_commit(the_repository
, item
->commit
);
6414 commit_buffer
= repo_logmsg_reencode(the_repository
,
6417 find_commit_subject(commit_buffer
, &subject
);
6418 format_subject(&buf
, subject
, " ");
6419 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6420 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6422 if (skip_fixupish(subject
, &p
)) {
6423 struct commit
*commit2
;
6428 if (!skip_fixupish(p
, &p
))
6432 entry
= hashmap_get_entry_from_hash(&subject2item
,
6434 struct subject2item_entry
,
6437 /* found by title */
6439 else if (!strchr(p
, ' ') &&
6441 lookup_commit_reference_by_name(p
)) &&
6442 *commit_todo_item_at(&commit_todo
, commit2
))
6443 /* found by commit name */
6444 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6447 /* copy can be a prefix of the commit subject */
6448 for (i2
= 0; i2
< i
; i2
++)
6450 starts_with(subjects
[i2
], p
))
6458 if (starts_with(subject
, "fixup!")) {
6459 todo_list
->items
[i
].command
= TODO_FIXUP
;
6460 } else if (starts_with(subject
, "amend!")) {
6461 todo_list
->items
[i
].command
= TODO_FIXUP
;
6462 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6464 todo_list
->items
[i
].command
= TODO_SQUASH
;
6470 next
[i
] = next
[tail
[i2
]];
6474 } else if (!hashmap_get_from_hash(&subject2item
,
6475 strhash(subject
), subject
)) {
6476 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6478 hashmap_entry_init(&entry
->entry
,
6479 strhash(entry
->subject
));
6480 hashmap_put(&subject2item
, &entry
->entry
);
6483 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6487 ALLOC_ARRAY(items
, todo_list
->nr
);
6489 for (i
= 0; i
< todo_list
->nr
; i
++) {
6490 enum todo_command command
= todo_list
->items
[i
].command
;
6494 * Initially, all commands are 'pick's. If it is a
6495 * fixup or a squash now, we have rearranged it.
6497 if (is_fixup(command
))
6501 items
[nr
++] = todo_list
->items
[cur
];
6506 assert(nr
== todo_list
->nr
);
6507 todo_list
->alloc
= nr
;
6508 FREE_AND_NULL(todo_list
->items
);
6509 todo_list
->items
= items
;
6514 for (i
= 0; i
< todo_list
->nr
; i
++)
6517 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6519 clear_commit_todo_item(&commit_todo
);
6524 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6526 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6527 struct object_id cherry_pick_head
, rebase_head
;
6529 if (file_exists(git_path_seq_dir()))
6530 *whence
= FROM_CHERRY_PICK_MULTI
;
6531 if (file_exists(rebase_path()) &&
6532 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6533 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6534 oideq(&rebase_head
, &cherry_pick_head
))
6535 *whence
= FROM_REBASE_PICK
;
6537 *whence
= FROM_CHERRY_PICK_SINGLE
;
6545 int sequencer_get_update_refs_state(const char *wt_dir
,
6546 struct string_list
*refs
)
6550 struct strbuf ref
= STRBUF_INIT
;
6551 struct strbuf hash
= STRBUF_INIT
;
6552 struct update_ref_record
*rec
= NULL
;
6554 char *path
= rebase_path_update_refs(wt_dir
);
6556 fp
= fopen(path
, "r");
6560 while (strbuf_getline(&ref
, fp
) != EOF
) {
6561 struct string_list_item
*item
;
6563 CALLOC_ARRAY(rec
, 1);
6565 if (strbuf_getline(&hash
, fp
) == EOF
||
6566 get_oid_hex(hash
.buf
, &rec
->before
)) {
6567 warning(_("update-refs file at '%s' is invalid"),
6573 if (strbuf_getline(&hash
, fp
) == EOF
||
6574 get_oid_hex(hash
.buf
, &rec
->after
)) {
6575 warning(_("update-refs file at '%s' is invalid"),
6581 item
= string_list_insert(refs
, ref
.buf
);
6591 strbuf_release(&ref
);
6592 strbuf_release(&hash
);