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(&opts
, sb
->buf
, &info
);
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 struct commit
*head_commit
;
776 struct index_state
*istate
= r
->index
;
778 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
779 return error(_("could not resolve HEAD commit"));
781 head_commit
= lookup_commit(r
, &head_oid
);
784 * If head_commit is NULL, check_commit, called from
785 * lookup_commit, would have indicated that head_commit is not
786 * a commit object already. repo_parse_commit() will return failure
787 * without further complaints in such a case. Otherwise, if
788 * the commit is invalid, repo_parse_commit() will complain. So
789 * there is nothing for us to say here. Just return failure.
791 if (repo_parse_commit(r
, head_commit
))
794 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
797 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
800 static int write_author_script(const char *message
)
802 struct strbuf buf
= STRBUF_INIT
;
807 if (!*message
|| starts_with(message
, "\n")) {
809 /* Missing 'author' line? */
810 unlink(rebase_path_author_script());
812 } else if (skip_prefix(message
, "author ", &message
))
814 else if ((eol
= strchr(message
, '\n')))
819 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
820 while (*message
&& *message
!= '\n' && *message
!= '\r')
821 if (skip_prefix(message
, " <", &message
))
823 else if (*message
!= '\'')
824 strbuf_addch(&buf
, *(message
++));
826 strbuf_addf(&buf
, "'\\%c'", *(message
++));
827 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
828 while (*message
&& *message
!= '\n' && *message
!= '\r')
829 if (skip_prefix(message
, "> ", &message
))
831 else if (*message
!= '\'')
832 strbuf_addch(&buf
, *(message
++));
834 strbuf_addf(&buf
, "'\\%c'", *(message
++));
835 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
836 while (*message
&& *message
!= '\n' && *message
!= '\r')
837 if (*message
!= '\'')
838 strbuf_addch(&buf
, *(message
++));
840 strbuf_addf(&buf
, "'\\%c'", *(message
++));
841 strbuf_addch(&buf
, '\'');
842 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
843 strbuf_release(&buf
);
848 * Take a series of KEY='VALUE' lines where VALUE part is
849 * sq-quoted, and append <KEY, VALUE> at the end of the string list
851 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
854 struct string_list_item
*item
;
856 char *cp
= strchr(buf
, '=');
858 np
= strchrnul(buf
, '\n');
859 return error(_("no key present in '%.*s'"),
860 (int) (np
- buf
), buf
);
862 np
= strchrnul(cp
, '\n');
864 item
= string_list_append(list
, buf
);
866 buf
= np
+ (*np
== '\n');
870 return error(_("unable to dequote value of '%s'"),
872 item
->util
= xstrdup(cp
);
878 * Reads and parses the state directory's "author-script" file, and sets name,
879 * email and date accordingly.
880 * Returns 0 on success, -1 if the file could not be parsed.
882 * The author script is of the format:
884 * GIT_AUTHOR_NAME='$author_name'
885 * GIT_AUTHOR_EMAIL='$author_email'
886 * GIT_AUTHOR_DATE='$author_date'
888 * where $author_name, $author_email and $author_date are quoted. We are strict
889 * with our parsing, as the file was meant to be eval'd in the now-removed
890 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
891 * from what this function expects, it is better to bail out than to do
892 * something that the user does not expect.
894 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
897 struct strbuf buf
= STRBUF_INIT
;
898 struct string_list kv
= STRING_LIST_INIT_DUP
;
899 int retval
= -1; /* assume failure */
900 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
902 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
903 strbuf_release(&buf
);
904 if (errno
== ENOENT
&& allow_missing
)
907 return error_errno(_("could not open '%s' for reading"),
911 if (parse_key_value_squoted(buf
.buf
, &kv
))
914 for (i
= 0; i
< kv
.nr
; i
++) {
915 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
917 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
920 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
922 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
925 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
927 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
931 err
= error(_("unknown variable '%s'"),
936 error(_("missing 'GIT_AUTHOR_NAME'"));
938 error(_("missing 'GIT_AUTHOR_EMAIL'"));
940 error(_("missing 'GIT_AUTHOR_DATE'"));
941 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
943 *name
= kv
.items
[name_i
].util
;
944 *email
= kv
.items
[email_i
].util
;
945 *date
= kv
.items
[date_i
].util
;
948 string_list_clear(&kv
, !!retval
);
949 strbuf_release(&buf
);
954 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
955 * file with shell quoting into struct strvec. Returns -1 on
956 * error, 0 otherwise.
958 static int read_env_script(struct strvec
*env
)
960 char *name
, *email
, *date
;
962 if (read_author_script(rebase_path_author_script(),
963 &name
, &email
, &date
, 0))
966 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
967 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
968 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
976 static char *get_author(const char *message
)
981 a
= find_commit_header(message
, "author", &len
);
983 return xmemdupz(a
, len
);
988 static const char *author_date_from_env(const struct strvec
*env
)
993 for (i
= 0; i
< env
->nr
; i
++)
994 if (skip_prefix(env
->v
[i
],
995 "GIT_AUTHOR_DATE=", &date
))
998 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1001 BUG("GIT_AUTHOR_DATE missing from author script");
1004 static const char staged_changes_advice
[] =
1005 N_("you have staged changes in your working tree\n"
1006 "If these changes are meant to be squashed into the previous commit, run:\n"
1008 " git commit --amend %s\n"
1010 "If they are meant to go into a new commit, run:\n"
1014 "In both cases, once you're done, continue with:\n"
1016 " git rebase --continue\n");
1018 #define ALLOW_EMPTY (1<<0)
1019 #define EDIT_MSG (1<<1)
1020 #define AMEND_MSG (1<<2)
1021 #define CLEANUP_MSG (1<<3)
1022 #define VERIFY_MSG (1<<4)
1023 #define CREATE_ROOT_COMMIT (1<<5)
1024 #define VERBATIM_MSG (1<<6)
1026 static int run_command_silent_on_success(struct child_process
*cmd
)
1028 struct strbuf buf
= STRBUF_INIT
;
1031 cmd
->stdout_to_stderr
= 1;
1032 rc
= pipe_command(cmd
,
1038 fputs(buf
.buf
, stderr
);
1039 strbuf_release(&buf
);
1044 * If we are cherry-pick, and if the merge did not result in
1045 * hand-editing, we will hit this commit and inherit the original
1046 * author date and name.
1048 * If we are revert, or if our cherry-pick results in a hand merge,
1049 * we had better say that the current user is responsible for that.
1051 * An exception is when run_git_commit() is called during an
1052 * interactive rebase: in that case, we will want to retain the
1055 static int run_git_commit(const char *defmsg
,
1056 struct replay_opts
*opts
,
1059 struct child_process cmd
= CHILD_PROCESS_INIT
;
1061 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1062 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1066 if (is_rebase_i(opts
) &&
1067 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1068 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1069 read_env_script(&cmd
.env
)) {
1070 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1072 return error(_(staged_changes_advice
),
1076 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1078 if (opts
->committer_date_is_author_date
)
1079 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1082 author_date_from_env(&cmd
.env
));
1083 if (opts
->ignore_date
)
1084 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1086 strvec_push(&cmd
.args
, "commit");
1088 if (!(flags
& VERIFY_MSG
))
1089 strvec_push(&cmd
.args
, "-n");
1090 if ((flags
& AMEND_MSG
))
1091 strvec_push(&cmd
.args
, "--amend");
1093 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1095 strvec_push(&cmd
.args
, "--no-gpg-sign");
1097 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1098 else if (!(flags
& EDIT_MSG
))
1099 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1100 if ((flags
& CLEANUP_MSG
))
1101 strvec_push(&cmd
.args
, "--cleanup=strip");
1102 if ((flags
& VERBATIM_MSG
))
1103 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1104 if ((flags
& EDIT_MSG
))
1105 strvec_push(&cmd
.args
, "-e");
1106 else if (!(flags
& CLEANUP_MSG
) &&
1107 !opts
->signoff
&& !opts
->record_origin
&&
1108 !opts
->explicit_cleanup
)
1109 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1111 if ((flags
& ALLOW_EMPTY
))
1112 strvec_push(&cmd
.args
, "--allow-empty");
1114 if (!(flags
& EDIT_MSG
))
1115 strvec_push(&cmd
.args
, "--allow-empty-message");
1117 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1118 return run_command_silent_on_success(&cmd
);
1120 return run_command(&cmd
);
1123 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1128 /* Check if the rest is just whitespace and Signed-off-by's. */
1129 for (i
= start
; i
< sb
->len
; i
++) {
1130 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1136 if (strlen(sign_off_header
) <= eol
- i
&&
1137 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1142 if (!isspace(sb
->buf
[i
++]))
1149 void cleanup_message(struct strbuf
*msgbuf
,
1150 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1152 if (verbose
|| /* Truncate the message just before the diff, if any. */
1153 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1154 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1155 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1156 strbuf_stripspace(msgbuf
,
1157 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1161 * Find out if the message in the strbuf contains only whitespace and
1162 * Signed-off-by lines.
1164 int message_is_empty(const struct strbuf
*sb
,
1165 enum commit_msg_cleanup_mode cleanup_mode
)
1167 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1169 return rest_is_empty(sb
, 0);
1173 * See if the user edited the message in the editor or left what
1174 * was in the template intact
1176 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1177 enum commit_msg_cleanup_mode cleanup_mode
)
1179 struct strbuf tmpl
= STRBUF_INIT
;
1182 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1185 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1188 strbuf_stripspace(&tmpl
,
1189 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1190 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1192 strbuf_release(&tmpl
);
1193 return rest_is_empty(sb
, start
- sb
->buf
);
1196 int update_head_with_reflog(const struct commit
*old_head
,
1197 const struct object_id
*new_head
,
1198 const char *action
, const struct strbuf
*msg
,
1201 struct ref_transaction
*transaction
;
1202 struct strbuf sb
= STRBUF_INIT
;
1207 strbuf_addstr(&sb
, action
);
1208 strbuf_addstr(&sb
, ": ");
1211 nl
= strchr(msg
->buf
, '\n');
1213 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1215 strbuf_addbuf(&sb
, msg
);
1216 strbuf_addch(&sb
, '\n');
1219 transaction
= ref_transaction_begin(err
);
1221 ref_transaction_update(transaction
, "HEAD", new_head
,
1222 old_head
? &old_head
->object
.oid
: null_oid(),
1224 ref_transaction_commit(transaction
, err
)) {
1227 ref_transaction_free(transaction
);
1228 strbuf_release(&sb
);
1233 static int run_rewrite_hook(const struct object_id
*oldoid
,
1234 const struct object_id
*newoid
)
1236 struct child_process proc
= CHILD_PROCESS_INIT
;
1238 struct strbuf sb
= STRBUF_INIT
;
1239 const char *hook_path
= find_hook("post-rewrite");
1244 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1246 proc
.stdout_to_stderr
= 1;
1247 proc
.trace2_hook_name
= "post-rewrite";
1249 code
= start_command(&proc
);
1252 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1253 sigchain_push(SIGPIPE
, SIG_IGN
);
1254 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1256 strbuf_release(&sb
);
1257 sigchain_pop(SIGPIPE
);
1258 return finish_command(&proc
);
1261 void commit_post_rewrite(struct repository
*r
,
1262 const struct commit
*old_head
,
1263 const struct object_id
*new_head
)
1265 struct notes_rewrite_cfg
*cfg
;
1267 cfg
= init_copy_notes_for_rewrite("amend");
1269 /* we are amending, so old_head is not NULL */
1270 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1271 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1273 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1276 static int run_prepare_commit_msg_hook(struct repository
*r
,
1281 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1283 name
= git_path_commit_editmsg();
1284 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1293 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1295 ret
= error(_("'prepare-commit-msg' hook failed"));
1300 static const char implicit_ident_advice_noconfig
[] =
1301 N_("Your name and email address were configured automatically based\n"
1302 "on your username and hostname. Please check that they are accurate.\n"
1303 "You can suppress this message by setting them explicitly. Run the\n"
1304 "following command and follow the instructions in your editor to edit\n"
1305 "your configuration file:\n"
1307 " git config --global --edit\n"
1309 "After doing this, you may fix the identity used for this commit with:\n"
1311 " git commit --amend --reset-author\n");
1313 static const char implicit_ident_advice_config
[] =
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:\n"
1318 " git config --global user.name \"Your Name\"\n"
1319 " git config --global user.email you@example.com\n"
1321 "After doing this, you may fix the identity used for this commit with:\n"
1323 " git commit --amend --reset-author\n");
1325 static const char *implicit_ident_advice(void)
1327 char *user_config
= interpolate_path("~/.gitconfig", 0);
1328 char *xdg_config
= xdg_config_home("config");
1329 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1335 return _(implicit_ident_advice_config
);
1337 return _(implicit_ident_advice_noconfig
);
1341 void print_commit_summary(struct repository
*r
,
1343 const struct object_id
*oid
,
1346 struct rev_info rev
;
1347 struct commit
*commit
;
1348 struct strbuf format
= STRBUF_INIT
;
1350 struct pretty_print_context pctx
= {0};
1351 struct strbuf author_ident
= STRBUF_INIT
;
1352 struct strbuf committer_ident
= STRBUF_INIT
;
1353 struct ref_store
*refs
;
1355 commit
= lookup_commit(r
, oid
);
1357 die(_("couldn't look up newly created commit"));
1358 if (repo_parse_commit(r
, commit
))
1359 die(_("could not parse newly created commit"));
1361 strbuf_addstr(&format
, "format:%h] %s");
1363 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1365 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1367 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1368 strbuf_addstr(&format
, "\n Author: ");
1369 strbuf_addbuf_percentquote(&format
, &author_ident
);
1371 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1372 struct strbuf date
= STRBUF_INIT
;
1374 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1375 strbuf_addstr(&format
, "\n Date: ");
1376 strbuf_addbuf_percentquote(&format
, &date
);
1377 strbuf_release(&date
);
1379 if (!committer_ident_sufficiently_given()) {
1380 strbuf_addstr(&format
, "\n Committer: ");
1381 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1382 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1383 strbuf_addch(&format
, '\n');
1384 strbuf_addstr(&format
, implicit_ident_advice());
1387 strbuf_release(&author_ident
);
1388 strbuf_release(&committer_ident
);
1390 repo_init_revisions(r
, &rev
, prefix
);
1391 setup_revisions(0, NULL
, &rev
, NULL
);
1394 rev
.diffopt
.output_format
=
1395 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1397 rev
.verbose_header
= 1;
1398 rev
.show_root_diff
= 1;
1399 get_commit_format(format
.buf
, &rev
);
1400 rev
.always_show_header
= 0;
1401 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1402 diff_setup_done(&rev
.diffopt
);
1404 refs
= get_main_ref_store(r
);
1405 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1407 die(_("unable to resolve HEAD after creating commit"));
1408 if (!strcmp(head
, "HEAD"))
1409 head
= _("detached HEAD");
1411 skip_prefix(head
, "refs/heads/", &head
);
1412 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1413 _(" (root-commit)") : "");
1415 if (!log_tree_commit(&rev
, commit
)) {
1416 rev
.always_show_header
= 1;
1417 rev
.use_terminator
= 1;
1418 log_tree_commit(&rev
, commit
);
1421 release_revisions(&rev
);
1422 strbuf_release(&format
);
1425 static int parse_head(struct repository
*r
, struct commit
**head
)
1427 struct commit
*current_head
;
1428 struct object_id oid
;
1430 if (repo_get_oid(r
, "HEAD", &oid
)) {
1431 current_head
= NULL
;
1433 current_head
= lookup_commit_reference(r
, &oid
);
1435 return error(_("could not parse HEAD"));
1436 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1437 warning(_("HEAD %s is not a commit!"),
1440 if (repo_parse_commit(r
, current_head
))
1441 return error(_("could not parse HEAD commit"));
1443 *head
= current_head
;
1449 * Try to commit without forking 'git commit'. In some cases we need
1450 * to run 'git commit' to display an error message
1453 * -1 - error unable to commit
1455 * 1 - run 'git commit'
1457 static int try_to_commit(struct repository
*r
,
1458 struct strbuf
*msg
, const char *author
,
1459 struct replay_opts
*opts
, unsigned int flags
,
1460 struct object_id
*oid
)
1462 struct object_id tree
;
1463 struct commit
*current_head
= NULL
;
1464 struct commit_list
*parents
= NULL
;
1465 struct commit_extra_header
*extra
= NULL
;
1466 struct strbuf err
= STRBUF_INIT
;
1467 struct strbuf commit_msg
= STRBUF_INIT
;
1468 char *amend_author
= NULL
;
1469 const char *committer
= NULL
;
1470 const char *hook_commit
= NULL
;
1471 enum commit_msg_cleanup_mode cleanup
;
1474 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1475 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1477 if (parse_head(r
, ¤t_head
))
1480 if (flags
& AMEND_MSG
) {
1481 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1482 const char *out_enc
= get_commit_output_encoding();
1483 const char *message
= repo_logmsg_reencode(r
, current_head
,
1487 const char *orig_message
= NULL
;
1489 find_commit_subject(message
, &orig_message
);
1491 strbuf_addstr(msg
, orig_message
);
1492 hook_commit
= "HEAD";
1494 author
= amend_author
= get_author(message
);
1495 repo_unuse_commit_buffer(r
, current_head
,
1498 res
= error(_("unable to parse commit author"));
1501 parents
= copy_commit_list(current_head
->parents
);
1502 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1503 } else if (current_head
&&
1504 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1505 commit_list_insert(current_head
, &parents
);
1508 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1509 res
= error(_("git write-tree failed to write a tree"));
1513 if (!(flags
& ALLOW_EMPTY
)) {
1514 struct commit
*first_parent
= current_head
;
1516 if (flags
& AMEND_MSG
) {
1517 if (current_head
->parents
) {
1518 first_parent
= current_head
->parents
->item
;
1519 if (repo_parse_commit(r
, first_parent
)) {
1520 res
= error(_("could not parse HEAD commit"));
1524 first_parent
= NULL
;
1527 if (oideq(first_parent
1528 ? get_commit_tree_oid(first_parent
)
1529 : the_hash_algo
->empty_tree
,
1531 res
= 1; /* run 'git commit' to display error message */
1536 if (hook_exists("prepare-commit-msg")) {
1537 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1540 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1542 res
= error_errno(_("unable to read commit message "
1544 git_path_commit_editmsg());
1550 if (flags
& CLEANUP_MSG
)
1551 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1552 else if (flags
& VERBATIM_MSG
)
1553 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1554 else if ((opts
->signoff
|| opts
->record_origin
) &&
1555 !opts
->explicit_cleanup
)
1556 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1558 cleanup
= opts
->default_msg_cleanup
;
1560 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1561 strbuf_stripspace(msg
,
1562 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1563 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1564 res
= 1; /* run 'git commit' to display error message */
1568 if (opts
->committer_date_is_author_date
) {
1569 struct ident_split id
;
1570 struct strbuf date
= STRBUF_INIT
;
1572 if (!opts
->ignore_date
) {
1573 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1574 res
= error(_("invalid author identity '%s'"),
1578 if (!id
.date_begin
) {
1580 "corrupt author: missing date information"));
1583 strbuf_addf(&date
, "@%.*s %.*s",
1584 (int)(id
.date_end
- id
.date_begin
),
1586 (int)(id
.tz_end
- id
.tz_begin
),
1591 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1592 getenv("GIT_COMMITTER_EMAIL"),
1593 WANT_COMMITTER_IDENT
,
1594 opts
->ignore_date
? NULL
: date
.buf
,
1596 strbuf_release(&date
);
1601 if (opts
->ignore_date
) {
1602 struct ident_split id
;
1605 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1606 error(_("invalid author identity '%s'"), author
);
1609 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1610 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1611 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1617 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1618 author
, committer
, opts
->gpg_sign
, extra
)) {
1619 res
= error(_("failed to write commit object"));
1623 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1625 res
= error("%s", err
.buf
);
1629 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1630 if (flags
& AMEND_MSG
)
1631 commit_post_rewrite(r
, current_head
, oid
);
1634 free_commit_extra_headers(extra
);
1635 strbuf_release(&err
);
1636 strbuf_release(&commit_msg
);
1642 static int write_rebase_head(struct object_id
*oid
)
1644 if (update_ref("rebase", "REBASE_HEAD", oid
,
1645 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1646 return error(_("could not update %s"), "REBASE_HEAD");
1651 static int do_commit(struct repository
*r
,
1652 const char *msg_file
, const char *author
,
1653 struct replay_opts
*opts
, unsigned int flags
,
1654 struct object_id
*oid
)
1658 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1659 struct object_id oid
;
1660 struct strbuf sb
= STRBUF_INIT
;
1662 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1663 return error_errno(_("unable to read commit message "
1667 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1668 author
, opts
, flags
, &oid
);
1669 strbuf_release(&sb
);
1671 refs_delete_ref(get_main_ref_store(r
), "",
1672 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
);
1673 unlink(git_path_merge_msg(r
));
1674 if (!is_rebase_i(opts
))
1675 print_commit_summary(r
, NULL
, &oid
,
1676 SUMMARY_SHOW_AUTHOR_DATE
);
1681 if (is_rebase_i(opts
) && oid
)
1682 if (write_rebase_head(oid
))
1684 return run_git_commit(msg_file
, opts
, flags
);
1690 static int is_original_commit_empty(struct commit
*commit
)
1692 const struct object_id
*ptree_oid
;
1694 if (repo_parse_commit(the_repository
, commit
))
1695 return error(_("could not parse commit %s"),
1696 oid_to_hex(&commit
->object
.oid
));
1697 if (commit
->parents
) {
1698 struct commit
*parent
= commit
->parents
->item
;
1699 if (repo_parse_commit(the_repository
, parent
))
1700 return error(_("could not parse parent commit %s"),
1701 oid_to_hex(&parent
->object
.oid
));
1702 ptree_oid
= get_commit_tree_oid(parent
);
1704 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1707 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1711 * Should empty commits be allowed? Return status:
1712 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1713 * 0: Halt on empty commit
1714 * 1: Allow empty commit
1715 * 2: Drop empty commit
1717 static int allow_empty(struct repository
*r
,
1718 struct replay_opts
*opts
,
1719 struct commit
*commit
)
1721 int index_unchanged
, originally_empty
;
1726 * (1) we do not allow empty at all and error out.
1728 * (2) we allow ones that were initially empty, and
1729 * just drop the ones that become empty
1731 * (3) we allow ones that were initially empty, but
1732 * halt for the ones that become empty;
1734 * (4) we allow both.
1736 if (!opts
->allow_empty
)
1737 return 0; /* let "git commit" barf as necessary */
1739 index_unchanged
= is_index_unchanged(r
);
1740 if (index_unchanged
< 0)
1741 return index_unchanged
;
1742 if (!index_unchanged
)
1743 return 0; /* we do not have to say --allow-empty */
1745 if (opts
->keep_redundant_commits
)
1748 originally_empty
= is_original_commit_empty(commit
);
1749 if (originally_empty
< 0)
1750 return originally_empty
;
1751 if (originally_empty
)
1753 else if (opts
->drop_redundant_commits
)
1762 } todo_command_info
[] = {
1763 [TODO_PICK
] = { 'p', "pick" },
1764 [TODO_REVERT
] = { 0, "revert" },
1765 [TODO_EDIT
] = { 'e', "edit" },
1766 [TODO_REWORD
] = { 'r', "reword" },
1767 [TODO_FIXUP
] = { 'f', "fixup" },
1768 [TODO_SQUASH
] = { 's', "squash" },
1769 [TODO_EXEC
] = { 'x', "exec" },
1770 [TODO_BREAK
] = { 'b', "break" },
1771 [TODO_LABEL
] = { 'l', "label" },
1772 [TODO_RESET
] = { 't', "reset" },
1773 [TODO_MERGE
] = { 'm', "merge" },
1774 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1775 [TODO_NOOP
] = { 0, "noop" },
1776 [TODO_DROP
] = { 'd', "drop" },
1777 [TODO_COMMENT
] = { 0, NULL
},
1780 static const char *command_to_string(const enum todo_command command
)
1782 if (command
< TODO_COMMENT
)
1783 return todo_command_info
[command
].str
;
1784 die(_("unknown command: %d"), command
);
1787 static char command_to_char(const enum todo_command command
)
1789 if (command
< TODO_COMMENT
)
1790 return todo_command_info
[command
].c
;
1791 return comment_line_char
;
1794 static int is_noop(const enum todo_command command
)
1796 return TODO_NOOP
<= command
;
1799 static int is_fixup(enum todo_command command
)
1801 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1804 /* Does this command create a (non-merge) commit? */
1805 static int is_pick_or_similar(enum todo_command command
)
1820 enum todo_item_flags
{
1821 TODO_EDIT_MERGE_MSG
= (1 << 0),
1822 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1823 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1826 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1827 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1828 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1829 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1830 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1832 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1834 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1835 (flag
& TODO_EDIT_FIXUP_MSG
));
1839 * Wrapper around strbuf_add_commented_lines() which avoids double
1840 * commenting commit subjects.
1842 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1844 const char *s
= str
;
1845 while (len
> 0 && s
[0] == comment_line_char
) {
1847 const char *n
= memchr(s
, '\n', len
);
1852 strbuf_add(buf
, s
, count
);
1856 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1859 /* Does the current fixup chain contain a squash command? */
1860 static int seen_squash(struct replay_opts
*opts
)
1862 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1863 strstr(opts
->current_fixups
.buf
, "\nsquash");
1866 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1868 strbuf_setlen(buf1
, 2);
1869 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1870 strbuf_addch(buf1
, '\n');
1871 strbuf_setlen(buf2
, 2);
1872 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1873 strbuf_addch(buf2
, '\n');
1877 * Comment out any un-commented commit messages, updating the message comments
1878 * to say they will be skipped but do not comment out the empty lines that
1879 * surround commit messages and their comments.
1881 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1883 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1884 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1885 const char *s
, *start
;
1887 size_t orig_msg_len
;
1890 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1891 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1892 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1896 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1898 * Copy the last message, preserving the blank line
1899 * preceding the current line
1901 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1902 copy_lines(msg
, start
, s
- start
- off
);
1904 strbuf_addch(msg
, '\n');
1906 * The next message needs to be commented out but the
1907 * message header is already commented out so just copy
1908 * it and the blank line that follows it.
1910 strbuf_addbuf(msg
, &buf2
);
1912 strbuf_addch(msg
, *next
++);
1914 copy_lines
= add_commented_lines
;
1915 update_comment_bufs(&buf1
, &buf2
, ++i
);
1916 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1917 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1918 copy_lines(msg
, start
, s
- start
- off
);
1921 copy_lines
= strbuf_add
;
1922 update_comment_bufs(&buf1
, &buf2
, ++i
);
1924 s
= strchr(s
, '\n');
1929 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1931 strbuf_release(&buf1
);
1932 strbuf_release(&buf2
);
1935 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1936 enum todo_command command
, struct replay_opts
*opts
,
1939 const char *fixup_msg
;
1940 size_t commented_len
= 0, fixup_off
;
1942 * amend is non-interactive and not normally used with fixup!
1943 * or squash! commits, so only comment out those subjects when
1944 * squashing commit messages.
1946 if (starts_with(body
, "amend!") ||
1947 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1948 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1949 commented_len
= commit_subject_length(body
);
1951 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1952 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1953 ++opts
->current_fixup_count
+ 1);
1954 strbuf_addstr(buf
, "\n\n");
1955 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1956 /* buf->buf may be reallocated so store an offset into the buffer */
1957 fixup_off
= buf
->len
;
1958 strbuf_addstr(buf
, body
+ commented_len
);
1960 /* fixup -C after squash behaves like squash */
1961 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1963 * We're replacing the commit message so we need to
1964 * append the Signed-off-by: trailer if the user
1965 * requested '--signoff'.
1968 append_signoff(buf
, 0, 0);
1970 if ((command
== TODO_FIXUP
) &&
1971 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1972 (file_exists(rebase_path_fixup_msg()) ||
1973 !file_exists(rebase_path_squash_msg()))) {
1974 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1975 if (write_message(fixup_msg
, strlen(fixup_msg
),
1976 rebase_path_fixup_msg(), 0) < 0)
1977 return error(_("cannot write '%s'"),
1978 rebase_path_fixup_msg());
1980 unlink(rebase_path_fixup_msg());
1983 unlink(rebase_path_fixup_msg());
1989 static int update_squash_messages(struct repository
*r
,
1990 enum todo_command command
,
1991 struct commit
*commit
,
1992 struct replay_opts
*opts
,
1995 struct strbuf buf
= STRBUF_INIT
;
1997 const char *message
, *body
;
1998 const char *encoding
= get_commit_output_encoding();
2000 if (opts
->current_fixup_count
> 0) {
2001 struct strbuf header
= STRBUF_INIT
;
2004 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2005 return error(_("could not read '%s'"),
2006 rebase_path_squash_msg());
2008 eol
= buf
.buf
[0] != comment_line_char
?
2009 buf
.buf
: strchrnul(buf
.buf
, '\n');
2011 strbuf_addf(&header
, "%c ", comment_line_char
);
2012 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2013 opts
->current_fixup_count
+ 2);
2014 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2015 strbuf_release(&header
);
2016 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2017 update_squash_message_for_fixup(&buf
);
2019 struct object_id head
;
2020 struct commit
*head_commit
;
2021 const char *head_message
, *body
;
2023 if (repo_get_oid(r
, "HEAD", &head
))
2024 return error(_("need a HEAD to fixup"));
2025 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2026 return error(_("could not read HEAD"));
2027 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2029 return error(_("could not read HEAD's commit message"));
2031 find_commit_subject(head_message
, &body
);
2032 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2033 rebase_path_fixup_msg(), 0) < 0) {
2034 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2035 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2037 strbuf_addf(&buf
, "%c ", comment_line_char
);
2038 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2039 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2040 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2041 _(skip_first_commit_msg_str
) :
2042 _(first_commit_msg_str
));
2043 strbuf_addstr(&buf
, "\n\n");
2044 if (is_fixup_flag(command
, flag
))
2045 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2048 strbuf_addstr(&buf
, body
);
2050 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2053 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2054 return error(_("could not read commit message of %s"),
2055 oid_to_hex(&commit
->object
.oid
));
2056 find_commit_subject(message
, &body
);
2058 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2059 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2060 } else if (command
== TODO_FIXUP
) {
2061 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2062 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2063 ++opts
->current_fixup_count
+ 1);
2064 strbuf_addstr(&buf
, "\n\n");
2065 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2068 return error(_("unknown command: %d"), command
);
2069 repo_unuse_commit_buffer(r
, commit
, message
);
2072 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2074 strbuf_release(&buf
);
2077 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2078 opts
->current_fixups
.len
? "\n" : "",
2079 command_to_string(command
),
2080 oid_to_hex(&commit
->object
.oid
));
2081 res
= write_message(opts
->current_fixups
.buf
,
2082 opts
->current_fixups
.len
,
2083 rebase_path_current_fixups(), 0);
2089 static void flush_rewritten_pending(void)
2091 struct strbuf buf
= STRBUF_INIT
;
2092 struct object_id newoid
;
2095 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2096 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2097 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2098 char *bol
= buf
.buf
, *eol
;
2101 eol
= strchrnul(bol
, '\n');
2102 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2103 bol
, oid_to_hex(&newoid
));
2109 unlink(rebase_path_rewritten_pending());
2111 strbuf_release(&buf
);
2114 static void record_in_rewritten(struct object_id
*oid
,
2115 enum todo_command next_command
)
2117 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2122 fprintf(out
, "%s\n", oid_to_hex(oid
));
2125 if (!is_fixup(next_command
))
2126 flush_rewritten_pending();
2129 static int should_edit(struct replay_opts
*opts
) {
2132 * Note that we only handle the case of non-conflicted
2133 * commits; continue_single_pick() handles the conflicted
2134 * commits itself instead of calling this function.
2136 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2140 static void refer_to_commit(struct replay_opts
*opts
,
2141 struct strbuf
*msgbuf
, struct commit
*commit
)
2143 if (opts
->commit_use_reference
) {
2144 struct pretty_print_context ctx
= {
2145 .abbrev
= DEFAULT_ABBREV
,
2146 .date_mode
.type
= DATE_SHORT
,
2148 repo_format_commit_message(the_repository
, commit
,
2149 "%h (%s, %ad)", msgbuf
, &ctx
);
2151 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2155 static int do_pick_commit(struct repository
*r
,
2156 struct todo_item
*item
,
2157 struct replay_opts
*opts
,
2158 int final_fixup
, int *check_todo
)
2160 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2161 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2162 struct object_id head
;
2163 struct commit
*base
, *next
, *parent
;
2164 const char *base_label
, *next_label
;
2165 char *author
= NULL
;
2166 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2167 struct strbuf msgbuf
= STRBUF_INIT
;
2168 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2169 enum todo_command command
= item
->command
;
2170 struct commit
*commit
= item
->commit
;
2172 if (opts
->no_commit
) {
2174 * We do not intend to commit immediately. We just want to
2175 * merge the differences in, so let's compute the tree
2176 * that represents the "current" state for the merge machinery
2179 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2180 return error(_("your index file is unmerged."));
2182 unborn
= repo_get_oid(r
, "HEAD", &head
);
2183 /* Do we want to generate a root commit? */
2184 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2185 oideq(&head
, &opts
->squash_onto
)) {
2186 if (is_fixup(command
))
2187 return error(_("cannot fixup root commit"));
2188 flags
|= CREATE_ROOT_COMMIT
;
2191 oidcpy(&head
, the_hash_algo
->empty_tree
);
2192 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2194 return error_dirty_index(r
, opts
);
2196 discard_index(r
->index
);
2198 if (!commit
->parents
)
2200 else if (commit
->parents
->next
) {
2201 /* Reverting or cherry-picking a merge commit */
2203 struct commit_list
*p
;
2205 if (!opts
->mainline
)
2206 return error(_("commit %s is a merge but no -m option was given."),
2207 oid_to_hex(&commit
->object
.oid
));
2209 for (cnt
= 1, p
= commit
->parents
;
2210 cnt
!= opts
->mainline
&& p
;
2213 if (cnt
!= opts
->mainline
|| !p
)
2214 return error(_("commit %s does not have parent %d"),
2215 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2217 } else if (1 < opts
->mainline
)
2219 * Non-first parent explicitly specified as mainline for
2222 return error(_("commit %s does not have parent %d"),
2223 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2225 parent
= commit
->parents
->item
;
2227 if (get_message(commit
, &msg
) != 0)
2228 return error(_("cannot get commit message for %s"),
2229 oid_to_hex(&commit
->object
.oid
));
2231 if (opts
->allow_ff
&& !is_fixup(command
) &&
2232 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2233 (!parent
&& unborn
))) {
2234 if (is_rebase_i(opts
))
2235 write_author_script(msg
.message
);
2236 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2238 if (res
|| command
!= TODO_REWORD
)
2242 goto fast_forward_edit
;
2244 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2245 /* TRANSLATORS: The first %s will be a "todo" command like
2246 "revert" or "pick", the second %s a SHA1. */
2247 return error(_("%s: cannot parse parent commit %s"),
2248 command_to_string(command
),
2249 oid_to_hex(&parent
->object
.oid
));
2252 * "commit" is an existing commit. We would want to apply
2253 * the difference it introduces since its first parent "prev"
2254 * on top of the current HEAD if we are cherry-pick. Or the
2255 * reverse of it if we are revert.
2258 if (command
== TODO_REVERT
) {
2259 const char *orig_subject
;
2262 base_label
= msg
.label
;
2264 next_label
= msg
.parent_label
;
2265 if (opts
->commit_use_reference
) {
2266 strbuf_addstr(&msgbuf
,
2267 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2268 } else if (skip_prefix(msg
.subject
, "Revert \"", &orig_subject
) &&
2270 * We don't touch pre-existing repeated reverts, because
2271 * theoretically these can be nested arbitrarily deeply,
2272 * thus requiring excessive complexity to deal with.
2274 !starts_with(orig_subject
, "Revert \"")) {
2275 strbuf_addstr(&msgbuf
, "Reapply \"");
2276 strbuf_addstr(&msgbuf
, orig_subject
);
2278 strbuf_addstr(&msgbuf
, "Revert \"");
2279 strbuf_addstr(&msgbuf
, msg
.subject
);
2280 strbuf_addstr(&msgbuf
, "\"");
2282 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2283 refer_to_commit(opts
, &msgbuf
, commit
);
2285 if (commit
->parents
&& commit
->parents
->next
) {
2286 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2287 refer_to_commit(opts
, &msgbuf
, parent
);
2289 strbuf_addstr(&msgbuf
, ".\n");
2294 base_label
= msg
.parent_label
;
2296 next_label
= msg
.label
;
2298 /* Append the commit log message to msgbuf. */
2299 if (find_commit_subject(msg
.message
, &p
))
2300 strbuf_addstr(&msgbuf
, p
);
2302 if (opts
->record_origin
) {
2303 strbuf_complete_line(&msgbuf
);
2304 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2305 strbuf_addch(&msgbuf
, '\n');
2306 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2307 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2308 strbuf_addstr(&msgbuf
, ")\n");
2310 if (!is_fixup(command
))
2311 author
= get_author(msg
.message
);
2314 if (command
== TODO_REWORD
)
2316 else if (is_fixup(command
)) {
2317 if (update_squash_messages(r
, command
, commit
,
2318 opts
, item
->flags
)) {
2324 msg_file
= rebase_path_squash_msg();
2325 else if (file_exists(rebase_path_fixup_msg())) {
2326 flags
|= VERBATIM_MSG
;
2327 msg_file
= rebase_path_fixup_msg();
2329 const char *dest
= git_path_squash_msg(r
);
2331 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2332 res
= error(_("could not copy '%s' to '%s'"),
2333 rebase_path_squash_msg(), dest
);
2336 unlink(git_path_merge_msg(r
));
2342 if (opts
->signoff
&& !is_fixup(command
))
2343 append_signoff(&msgbuf
, 0, 0);
2345 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2347 else if (!opts
->strategy
||
2348 !strcmp(opts
->strategy
, "recursive") ||
2349 !strcmp(opts
->strategy
, "ort") ||
2350 command
== TODO_REVERT
) {
2351 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2352 &head
, &msgbuf
, opts
);
2356 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2357 git_path_merge_msg(r
), 0);
2359 struct commit_list
*common
= NULL
;
2360 struct commit_list
*remotes
= NULL
;
2362 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2363 git_path_merge_msg(r
), 0);
2365 commit_list_insert(base
, &common
);
2366 commit_list_insert(next
, &remotes
);
2367 res
|= try_merge_command(r
, opts
->strategy
,
2368 opts
->xopts
.nr
, opts
->xopts
.v
,
2369 common
, oid_to_hex(&head
), remotes
);
2370 free_commit_list(common
);
2371 free_commit_list(remotes
);
2375 * If the merge was clean or if it failed due to conflict, we write
2376 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2377 * However, if the merge did not even start, then we don't want to
2380 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2381 command
== TODO_EDIT
) && !opts
->no_commit
&&
2382 (res
== 0 || res
== 1) &&
2383 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2384 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2386 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2387 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2388 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2392 error(command
== TODO_REVERT
2393 ? _("could not revert %s... %s")
2394 : _("could not apply %s... %s"),
2395 short_commit_name(r
, commit
), msg
.subject
);
2396 print_advice(r
, res
== 1, opts
);
2397 repo_rerere(r
, opts
->allow_rerere_auto
);
2402 allow
= allow_empty(r
, opts
, commit
);
2406 } else if (allow
== 1) {
2407 flags
|= ALLOW_EMPTY
;
2408 } else if (allow
== 2) {
2410 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2411 NULL
, REF_NO_DEREF
);
2412 unlink(git_path_merge_msg(r
));
2413 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2414 NULL
, REF_NO_DEREF
);
2416 _("dropping %s %s -- patch contents already upstream\n"),
2417 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2418 } /* else allow == 0 and there's nothing special to do */
2419 if (!opts
->no_commit
&& !drop_commit
) {
2420 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2421 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2422 commit
? &commit
->object
.oid
: NULL
);
2424 res
= error(_("unable to parse commit author"));
2425 *check_todo
= !!(flags
& EDIT_MSG
);
2426 if (!res
&& reword
) {
2428 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2429 VERIFY_MSG
| AMEND_MSG
|
2430 (flags
& ALLOW_EMPTY
));
2436 if (!res
&& final_fixup
) {
2437 unlink(rebase_path_fixup_msg());
2438 unlink(rebase_path_squash_msg());
2439 unlink(rebase_path_current_fixups());
2440 strbuf_reset(&opts
->current_fixups
);
2441 opts
->current_fixup_count
= 0;
2445 free_message(commit
, &msg
);
2447 strbuf_release(&msgbuf
);
2448 update_abort_safety_file();
2453 static int prepare_revs(struct replay_opts
*opts
)
2456 * picking (but not reverting) ranges (but not individual revisions)
2457 * should be done in reverse
2459 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2460 opts
->revs
->reverse
^= 1;
2462 if (prepare_revision_walk(opts
->revs
))
2463 return error(_("revision walk setup failed"));
2468 static int read_and_refresh_cache(struct repository
*r
,
2469 struct replay_opts
*opts
)
2471 struct lock_file index_lock
= LOCK_INIT
;
2472 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2473 if (repo_read_index(r
) < 0) {
2474 rollback_lock_file(&index_lock
);
2475 return error(_("git %s: failed to read the index"),
2478 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2480 if (index_fd
>= 0) {
2481 if (write_locked_index(r
->index
, &index_lock
,
2482 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2483 return error(_("git %s: failed to refresh the index"),
2489 * If we are resolving merges in any way other than "ort", then
2490 * expand the sparse index.
2492 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2493 ensure_full_index(r
->index
);
2497 void todo_list_release(struct todo_list
*todo_list
)
2499 strbuf_release(&todo_list
->buf
);
2500 FREE_AND_NULL(todo_list
->items
);
2501 todo_list
->nr
= todo_list
->alloc
= 0;
2504 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2506 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2507 return todo_list
->items
+ todo_list
->nr
++;
2510 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2511 struct todo_item
*item
)
2513 return todo_list
->buf
.buf
+ item
->arg_offset
;
2516 static int is_command(enum todo_command command
, const char **bol
)
2518 const char *str
= todo_command_info
[command
].str
;
2519 const char nick
= todo_command_info
[command
].c
;
2520 const char *p
= *bol
;
2522 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2523 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2527 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2532 * '#' is not a valid label as the merge command uses it to
2533 * separate merge parents from the commit subject.
2535 if (!strcmp(arg
, "#") ||
2536 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2537 return error(_("'%s' is not a valid label"), arg
);
2540 case TODO_UPDATE_REF
:
2541 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2542 return error(_("'%s' is not a valid refname"), arg
);
2543 if (check_refname_format(arg
, 0))
2544 return error(_("update-ref requires a fully qualified "
2545 "refname e.g. refs/heads/%s"), arg
);
2549 BUG("unexpected todo_command");
2555 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2556 const char *buf
, const char *bol
, char *eol
)
2558 struct object_id commit_oid
;
2559 char *end_of_object_name
;
2560 int i
, saved
, status
, padding
;
2565 bol
+= strspn(bol
, " \t");
2567 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2568 item
->command
= TODO_COMMENT
;
2569 item
->commit
= NULL
;
2570 item
->arg_offset
= bol
- buf
;
2571 item
->arg_len
= eol
- bol
;
2575 for (i
= 0; i
< TODO_COMMENT
; i
++)
2576 if (is_command(i
, &bol
)) {
2580 if (i
>= TODO_COMMENT
)
2581 return error(_("invalid command '%.*s'"),
2582 (int)strcspn(bol
, " \t\r\n"), bol
);
2584 /* Eat up extra spaces/ tabs before object name */
2585 padding
= strspn(bol
, " \t");
2588 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2590 return error(_("%s does not accept arguments: '%s'"),
2591 command_to_string(item
->command
), bol
);
2592 item
->commit
= NULL
;
2593 item
->arg_offset
= bol
- buf
;
2594 item
->arg_len
= eol
- bol
;
2599 return error(_("missing arguments for %s"),
2600 command_to_string(item
->command
));
2602 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2603 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2606 item
->commit
= NULL
;
2607 item
->arg_offset
= bol
- buf
;
2608 item
->arg_len
= (int)(eol
- bol
);
2609 if (item
->command
== TODO_LABEL
||
2610 item
->command
== TODO_UPDATE_REF
) {
2613 ret
= check_label_or_ref_arg(item
->command
, bol
);
2619 if (item
->command
== TODO_FIXUP
) {
2620 if (skip_prefix(bol
, "-C", &bol
)) {
2621 bol
+= strspn(bol
, " \t");
2622 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2623 } else if (skip_prefix(bol
, "-c", &bol
)) {
2624 bol
+= strspn(bol
, " \t");
2625 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2629 if (item
->command
== TODO_MERGE
) {
2630 if (skip_prefix(bol
, "-C", &bol
))
2631 bol
+= strspn(bol
, " \t");
2632 else if (skip_prefix(bol
, "-c", &bol
)) {
2633 bol
+= strspn(bol
, " \t");
2634 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2636 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2637 item
->commit
= NULL
;
2638 item
->arg_offset
= bol
- buf
;
2639 item
->arg_len
= (int)(eol
- bol
);
2644 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2645 saved
= *end_of_object_name
;
2646 *end_of_object_name
= '\0';
2647 status
= repo_get_oid(r
, bol
, &commit_oid
);
2649 error(_("could not parse '%s'"), bol
); /* return later */
2650 *end_of_object_name
= saved
;
2652 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2653 item
->arg_offset
= bol
- buf
;
2654 item
->arg_len
= (int)(eol
- bol
);
2659 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2660 return item
->commit
? 0 : -1;
2663 int sequencer_get_last_command(struct repository
*r UNUSED
, enum replay_action
*action
)
2665 const char *todo_file
, *bol
;
2666 struct strbuf buf
= STRBUF_INIT
;
2669 todo_file
= git_path_todo_file();
2670 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2671 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2674 return error_errno("unable to open '%s'", todo_file
);
2676 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2677 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2678 *action
= REPLAY_PICK
;
2679 else if (is_command(TODO_REVERT
, &bol
) &&
2680 (*bol
== ' ' || *bol
== '\t'))
2681 *action
= REPLAY_REVERT
;
2685 strbuf_release(&buf
);
2690 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2691 struct todo_list
*todo_list
)
2693 struct todo_item
*item
;
2694 char *p
= buf
, *next_p
;
2695 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2697 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2699 for (i
= 1; *p
; i
++, p
= next_p
) {
2700 char *eol
= strchrnul(p
, '\n');
2702 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2704 if (p
!= eol
&& eol
[-1] == '\r')
2705 eol
--; /* strip Carriage Return */
2707 item
= append_new_todo(todo_list
);
2708 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2709 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2710 res
= error(_("invalid line %d: %.*s"),
2711 i
, (int)(eol
- p
), p
);
2712 item
->command
= TODO_COMMENT
+ 1;
2713 item
->arg_offset
= p
- buf
;
2714 item
->arg_len
= (int)(eol
- p
);
2715 item
->commit
= NULL
;
2718 if (item
->command
!= TODO_COMMENT
)
2719 todo_list
->total_nr
++;
2723 else if (is_fixup(item
->command
))
2724 res
= error(_("cannot '%s' without a previous commit"),
2725 command_to_string(item
->command
));
2726 else if (!is_noop(item
->command
))
2733 static int count_commands(struct todo_list
*todo_list
)
2737 for (i
= 0; i
< todo_list
->nr
; i
++)
2738 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2744 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2746 return index
< todo_list
->nr
?
2747 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2750 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2752 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2755 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2757 return get_item_line_offset(todo_list
, index
+ 1)
2758 - get_item_line_offset(todo_list
, index
);
2761 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2766 fd
= open(path
, O_RDONLY
);
2768 return error_errno(_("could not open '%s'"), path
);
2769 len
= strbuf_read(sb
, fd
, 0);
2772 return error(_("could not read '%s'."), path
);
2776 static int have_finished_the_last_pick(void)
2778 struct strbuf buf
= STRBUF_INIT
;
2780 const char *todo_path
= git_path_todo_file();
2783 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2784 if (errno
== ENOENT
) {
2787 error_errno("unable to open '%s'", todo_path
);
2791 /* If there is only one line then we are done */
2792 eol
= strchr(buf
.buf
, '\n');
2793 if (!eol
|| !eol
[1])
2796 strbuf_release(&buf
);
2801 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2803 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2804 int need_cleanup
= 0;
2806 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2807 if (!refs_delete_ref(get_main_ref_store(r
), "",
2808 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
) &&
2810 warning(_("cancelling a cherry picking in progress"));
2811 opts
.action
= REPLAY_PICK
;
2815 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2816 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2817 NULL
, REF_NO_DEREF
) &&
2819 warning(_("cancelling a revert in progress"));
2820 opts
.action
= REPLAY_REVERT
;
2824 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2825 NULL
, REF_NO_DEREF
);
2830 if (!have_finished_the_last_pick())
2833 sequencer_remove_state(&opts
);
2836 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2838 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2841 fprintf(f
, "%d\n", todo_list
->total_nr
);
2846 static int read_populate_todo(struct repository
*r
,
2847 struct todo_list
*todo_list
,
2848 struct replay_opts
*opts
)
2850 const char *todo_file
= get_todo_path(opts
);
2853 strbuf_reset(&todo_list
->buf
);
2854 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2857 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2859 if (is_rebase_i(opts
))
2860 return error(_("please fix this using "
2861 "'git rebase --edit-todo'."));
2862 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2865 if (!todo_list
->nr
&&
2866 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2867 return error(_("no commits parsed."));
2869 if (!is_rebase_i(opts
)) {
2870 enum todo_command valid
=
2871 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2874 for (i
= 0; i
< todo_list
->nr
; i
++)
2875 if (valid
== todo_list
->items
[i
].command
)
2877 else if (valid
== TODO_PICK
)
2878 return error(_("cannot cherry-pick during a revert."));
2880 return error(_("cannot revert during a cherry-pick."));
2883 if (is_rebase_i(opts
)) {
2884 struct todo_list done
= TODO_LIST_INIT
;
2886 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2887 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2888 todo_list
->done_nr
= count_commands(&done
);
2890 todo_list
->done_nr
= 0;
2892 todo_list
->total_nr
= todo_list
->done_nr
2893 + count_commands(todo_list
);
2894 todo_list_release(&done
);
2896 todo_list_write_total_nr(todo_list
);
2902 static int git_config_string_dup(char **dest
,
2903 const char *var
, const char *value
)
2906 return config_error_nonbool(var
);
2908 *dest
= xstrdup(value
);
2912 static int populate_opts_cb(const char *key
, const char *value
,
2913 const struct config_context
*ctx
,
2916 struct replay_opts
*opts
= data
;
2921 else if (!strcmp(key
, "options.no-commit"))
2922 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2923 else if (!strcmp(key
, "options.edit"))
2924 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2925 else if (!strcmp(key
, "options.allow-empty"))
2927 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2928 else if (!strcmp(key
, "options.allow-empty-message"))
2929 opts
->allow_empty_message
=
2930 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2931 else if (!strcmp(key
, "options.keep-redundant-commits"))
2932 opts
->keep_redundant_commits
=
2933 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2934 else if (!strcmp(key
, "options.signoff"))
2935 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2936 else if (!strcmp(key
, "options.record-origin"))
2937 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2938 else if (!strcmp(key
, "options.allow-ff"))
2939 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2940 else if (!strcmp(key
, "options.mainline"))
2941 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2942 else if (!strcmp(key
, "options.strategy"))
2943 git_config_string_dup(&opts
->strategy
, key
, value
);
2944 else if (!strcmp(key
, "options.gpg-sign"))
2945 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2946 else if (!strcmp(key
, "options.strategy-option")) {
2947 strvec_push(&opts
->xopts
, value
);
2948 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2949 opts
->allow_rerere_auto
=
2950 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2951 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2952 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2953 opts
->explicit_cleanup
= 1;
2954 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2956 return error(_("invalid key: %s"), key
);
2959 return error(_("invalid value for '%s': '%s'"), key
, value
);
2964 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2969 char *strategy_opts_string
= raw_opts
;
2971 if (*strategy_opts_string
== ' ')
2972 strategy_opts_string
++;
2974 count
= split_cmdline(strategy_opts_string
, &argv
);
2976 BUG("could not split '%s': %s", strategy_opts_string
,
2977 split_cmdline_strerror(count
));
2978 for (i
= 0; i
< count
; i
++) {
2979 const char *arg
= argv
[i
];
2981 skip_prefix(arg
, "--", &arg
);
2982 strvec_push(&opts
->xopts
, arg
);
2987 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2990 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2992 opts
->strategy
= strbuf_detach(buf
, NULL
);
2993 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2996 parse_strategy_opts(opts
, buf
->buf
);
2999 static int read_populate_opts(struct replay_opts
*opts
)
3001 if (is_rebase_i(opts
)) {
3002 struct strbuf buf
= STRBUF_INIT
;
3005 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
3006 READ_ONELINER_SKIP_IF_EMPTY
)) {
3007 if (!starts_with(buf
.buf
, "-S"))
3010 free(opts
->gpg_sign
);
3011 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3016 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3017 READ_ONELINER_SKIP_IF_EMPTY
)) {
3018 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3019 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3020 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3021 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3025 if (file_exists(rebase_path_verbose()))
3028 if (file_exists(rebase_path_quiet()))
3031 if (file_exists(rebase_path_signoff())) {
3036 if (file_exists(rebase_path_cdate_is_adate())) {
3038 opts
->committer_date_is_author_date
= 1;
3041 if (file_exists(rebase_path_ignore_date())) {
3043 opts
->ignore_date
= 1;
3046 if (file_exists(rebase_path_reschedule_failed_exec()))
3047 opts
->reschedule_failed_exec
= 1;
3048 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3049 opts
->reschedule_failed_exec
= 0;
3051 if (file_exists(rebase_path_drop_redundant_commits()))
3052 opts
->drop_redundant_commits
= 1;
3054 if (file_exists(rebase_path_keep_redundant_commits()))
3055 opts
->keep_redundant_commits
= 1;
3057 read_strategy_opts(opts
, &buf
);
3060 if (read_oneliner(&opts
->current_fixups
,
3061 rebase_path_current_fixups(),
3062 READ_ONELINER_SKIP_IF_EMPTY
)) {
3063 const char *p
= opts
->current_fixups
.buf
;
3064 opts
->current_fixup_count
= 1;
3065 while ((p
= strchr(p
, '\n'))) {
3066 opts
->current_fixup_count
++;
3071 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3072 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3073 ret
= error(_("unusable squash-onto"));
3076 opts
->have_squash_onto
= 1;
3080 strbuf_release(&buf
);
3084 if (!file_exists(git_path_opts_file()))
3087 * The function git_parse_source(), called from git_config_from_file(),
3088 * may die() in case of a syntactically incorrect file. We do not care
3089 * about this case, though, because we wrote that file ourselves, so we
3090 * are pretty certain that it is syntactically correct.
3092 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3093 return error(_("malformed options sheet: '%s'"),
3094 git_path_opts_file());
3098 static void write_strategy_opts(struct replay_opts
*opts
)
3100 struct strbuf buf
= STRBUF_INIT
;
3103 * Quote strategy options so that they can be read correctly
3104 * by split_cmdline().
3106 quote_cmdline(&buf
, opts
->xopts
.v
);
3107 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3108 strbuf_release(&buf
);
3111 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3112 struct commit
*onto
, const struct object_id
*orig_head
)
3115 write_file(rebase_path_head_name(), "%s\n", head_name
);
3117 write_file(rebase_path_onto(), "%s\n",
3118 oid_to_hex(&onto
->object
.oid
));
3120 write_file(rebase_path_orig_head(), "%s\n",
3121 oid_to_hex(orig_head
));
3124 write_file(rebase_path_quiet(), "%s", "");
3126 write_file(rebase_path_verbose(), "%s", "");
3128 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3129 if (opts
->xopts
.nr
> 0)
3130 write_strategy_opts(opts
);
3132 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3133 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3134 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3135 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3138 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3140 write_file(rebase_path_signoff(), "--signoff\n");
3141 if (opts
->drop_redundant_commits
)
3142 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3143 if (opts
->keep_redundant_commits
)
3144 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3145 if (opts
->committer_date_is_author_date
)
3146 write_file(rebase_path_cdate_is_adate(), "%s", "");
3147 if (opts
->ignore_date
)
3148 write_file(rebase_path_ignore_date(), "%s", "");
3149 if (opts
->reschedule_failed_exec
)
3150 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3152 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3157 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3158 struct replay_opts
*opts
)
3160 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3161 TODO_PICK
: TODO_REVERT
;
3162 const char *command_string
= todo_command_info
[command
].str
;
3163 const char *encoding
;
3164 struct commit
*commit
;
3166 if (prepare_revs(opts
))
3169 encoding
= get_log_output_encoding();
3171 while ((commit
= get_revision(opts
->revs
))) {
3172 struct todo_item
*item
= append_new_todo(todo_list
);
3173 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3176 const char *subject
;
3179 item
->command
= command
;
3180 item
->commit
= commit
;
3181 item
->arg_offset
= 0;
3183 item
->offset_in_buf
= todo_list
->buf
.len
;
3184 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3185 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3186 short_commit_name(the_repository
, commit
),
3187 subject_len
, subject
);
3188 repo_unuse_commit_buffer(the_repository
, commit
,
3193 return error(_("empty commit set passed"));
3198 static int create_seq_dir(struct repository
*r
)
3200 enum replay_action action
;
3201 const char *in_progress_error
= NULL
;
3202 const char *in_progress_advice
= NULL
;
3203 unsigned int advise_skip
=
3204 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3205 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3207 if (!sequencer_get_last_command(r
, &action
)) {
3210 in_progress_error
= _("revert is already in progress");
3211 in_progress_advice
=
3212 _("try \"git revert (--continue | %s--abort | --quit)\"");
3215 in_progress_error
= _("cherry-pick is already in progress");
3216 in_progress_advice
=
3217 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3220 BUG("unexpected action in create_seq_dir");
3223 if (in_progress_error
) {
3224 error("%s", in_progress_error
);
3225 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3226 advise(in_progress_advice
,
3227 advise_skip
? "--skip | " : "");
3230 if (mkdir(git_path_seq_dir(), 0777) < 0)
3231 return error_errno(_("could not create sequencer directory '%s'"),
3232 git_path_seq_dir());
3237 static int save_head(const char *head
)
3239 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3242 static int rollback_is_safe(void)
3244 struct strbuf sb
= STRBUF_INIT
;
3245 struct object_id expected_head
, actual_head
;
3247 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3249 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3250 strbuf_release(&sb
);
3251 die(_("could not parse %s"), git_path_abort_safety_file());
3253 strbuf_release(&sb
);
3255 else if (errno
== ENOENT
)
3256 oidclr(&expected_head
);
3258 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3260 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3261 oidclr(&actual_head
);
3263 return oideq(&actual_head
, &expected_head
);
3266 static int reset_merge(const struct object_id
*oid
)
3268 struct child_process cmd
= CHILD_PROCESS_INIT
;
3271 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3273 if (!is_null_oid(oid
))
3274 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3276 return run_command(&cmd
);
3279 static int rollback_single_pick(struct repository
*r
)
3281 struct object_id head_oid
;
3283 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3284 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3285 return error(_("no cherry-pick or revert in progress"));
3286 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3287 return error(_("cannot resolve HEAD"));
3288 if (is_null_oid(&head_oid
))
3289 return error(_("cannot abort from a branch yet to be born"));
3290 return reset_merge(&head_oid
);
3293 static int skip_single_pick(void)
3295 struct object_id head
;
3297 if (read_ref_full("HEAD", 0, &head
, NULL
))
3298 return error(_("cannot resolve HEAD"));
3299 return reset_merge(&head
);
3302 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3305 struct object_id oid
;
3306 struct strbuf buf
= STRBUF_INIT
;
3309 f
= fopen(git_path_head_file(), "r");
3310 if (!f
&& errno
== ENOENT
) {
3312 * There is no multiple-cherry-pick in progress.
3313 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3314 * a single-cherry-pick in progress, abort that.
3316 return rollback_single_pick(r
);
3319 return error_errno(_("cannot open '%s'"), git_path_head_file());
3320 if (strbuf_getline_lf(&buf
, f
)) {
3321 error(_("cannot read '%s': %s"), git_path_head_file(),
3322 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3327 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3328 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3329 git_path_head_file());
3332 if (is_null_oid(&oid
)) {
3333 error(_("cannot abort from a branch yet to be born"));
3337 if (!rollback_is_safe()) {
3338 /* Do not error, just do not rollback */
3339 warning(_("You seem to have moved HEAD. "
3340 "Not rewinding, check your HEAD!"));
3342 if (reset_merge(&oid
))
3344 strbuf_release(&buf
);
3345 return sequencer_remove_state(opts
);
3347 strbuf_release(&buf
);
3351 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3353 enum replay_action action
= -1;
3354 sequencer_get_last_command(r
, &action
);
3357 * Check whether the subcommand requested to skip the commit is actually
3358 * in progress and that it's safe to skip the commit.
3360 * opts->action tells us which subcommand requested to skip the commit.
3361 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3362 * action is in progress and we can skip the commit.
3364 * Otherwise we check that the last instruction was related to the
3365 * particular subcommand we're trying to execute and barf if that's not
3368 * Finally we check that the rollback is "safe", i.e., has the HEAD
3369 * moved? In this case, it doesn't make sense to "reset the merge" and
3370 * "skip the commit" as the user already handled this by committing. But
3371 * we'd not want to barf here, instead give advice on how to proceed. We
3372 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3373 * it gets removed when the user commits, so if it still exists we're
3374 * sure the user can't have committed before.
3376 switch (opts
->action
) {
3378 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3379 if (action
!= REPLAY_REVERT
)
3380 return error(_("no revert in progress"));
3381 if (!rollback_is_safe())
3386 if (!refs_ref_exists(get_main_ref_store(r
),
3387 "CHERRY_PICK_HEAD")) {
3388 if (action
!= REPLAY_PICK
)
3389 return error(_("no cherry-pick in progress"));
3390 if (!rollback_is_safe())
3395 BUG("unexpected action in sequencer_skip");
3398 if (skip_single_pick())
3399 return error(_("failed to skip the commit"));
3400 if (!is_directory(git_path_seq_dir()))
3403 return sequencer_continue(r
, opts
);
3406 error(_("there is nothing to skip"));
3408 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3409 advise(_("have you committed already?\n"
3410 "try \"git %s --continue\""),
3411 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3416 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
,
3419 struct lock_file todo_lock
= LOCK_INIT
;
3420 const char *todo_path
= get_todo_path(opts
);
3421 int next
= todo_list
->current
, offset
, fd
;
3424 * rebase -i writes "git-rebase-todo" without the currently executing
3425 * command, appending it to "done" instead.
3427 if (is_rebase_i(opts
) && !reschedule
)
3430 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3432 return error_errno(_("could not lock '%s'"), todo_path
);
3433 offset
= get_item_line_offset(todo_list
, next
);
3434 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3435 todo_list
->buf
.len
- offset
) < 0)
3436 return error_errno(_("could not write to '%s'"), todo_path
);
3437 if (commit_lock_file(&todo_lock
) < 0)
3438 return error(_("failed to finalize '%s'"), todo_path
);
3440 if (is_rebase_i(opts
) && !reschedule
&& next
> 0) {
3441 const char *done
= rebase_path_done();
3442 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3447 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3448 get_item_line_length(todo_list
, next
- 1))
3450 ret
= error_errno(_("could not write to '%s'"), done
);
3452 ret
= error_errno(_("failed to finalize '%s'"), done
);
3458 static int save_opts(struct replay_opts
*opts
)
3460 const char *opts_file
= git_path_opts_file();
3463 if (opts
->no_commit
)
3464 res
|= git_config_set_in_file_gently(opts_file
,
3465 "options.no-commit", "true");
3466 if (opts
->edit
>= 0)
3467 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3468 opts
->edit
? "true" : "false");
3469 if (opts
->allow_empty
)
3470 res
|= git_config_set_in_file_gently(opts_file
,
3471 "options.allow-empty", "true");
3472 if (opts
->allow_empty_message
)
3473 res
|= git_config_set_in_file_gently(opts_file
,
3474 "options.allow-empty-message", "true");
3475 if (opts
->keep_redundant_commits
)
3476 res
|= git_config_set_in_file_gently(opts_file
,
3477 "options.keep-redundant-commits", "true");
3479 res
|= git_config_set_in_file_gently(opts_file
,
3480 "options.signoff", "true");
3481 if (opts
->record_origin
)
3482 res
|= git_config_set_in_file_gently(opts_file
,
3483 "options.record-origin", "true");
3485 res
|= git_config_set_in_file_gently(opts_file
,
3486 "options.allow-ff", "true");
3487 if (opts
->mainline
) {
3488 struct strbuf buf
= STRBUF_INIT
;
3489 strbuf_addf(&buf
, "%d", opts
->mainline
);
3490 res
|= git_config_set_in_file_gently(opts_file
,
3491 "options.mainline", buf
.buf
);
3492 strbuf_release(&buf
);
3495 res
|= git_config_set_in_file_gently(opts_file
,
3496 "options.strategy", opts
->strategy
);
3498 res
|= git_config_set_in_file_gently(opts_file
,
3499 "options.gpg-sign", opts
->gpg_sign
);
3500 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3501 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3502 "options.strategy-option",
3503 opts
->xopts
.v
[i
], "^$", 0);
3504 if (opts
->allow_rerere_auto
)
3505 res
|= git_config_set_in_file_gently(opts_file
,
3506 "options.allow-rerere-auto",
3507 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3510 if (opts
->explicit_cleanup
)
3511 res
|= git_config_set_in_file_gently(opts_file
,
3512 "options.default-msg-cleanup",
3513 describe_cleanup_mode(opts
->default_msg_cleanup
));
3517 static int make_patch(struct repository
*r
,
3518 struct commit
*commit
,
3519 struct replay_opts
*opts
)
3521 struct rev_info log_tree_opt
;
3522 const char *subject
;
3523 char hex
[GIT_MAX_HEXSZ
+ 1];
3526 if (!is_rebase_i(opts
))
3527 BUG("make_patch should only be called when rebasing");
3529 oid_to_hex_r(hex
, &commit
->object
.oid
);
3530 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3532 res
|= write_rebase_head(&commit
->object
.oid
);
3534 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3535 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3536 log_tree_opt
.abbrev
= 0;
3537 log_tree_opt
.diff
= 1;
3538 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3539 log_tree_opt
.disable_stdin
= 1;
3540 log_tree_opt
.no_commit_id
= 1;
3541 log_tree_opt
.diffopt
.file
= fopen(rebase_path_patch(), "w");
3542 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3543 if (!log_tree_opt
.diffopt
.file
)
3544 res
|= error_errno(_("could not open '%s'"),
3545 rebase_path_patch());
3547 res
|= log_tree_commit(&log_tree_opt
, commit
);
3548 fclose(log_tree_opt
.diffopt
.file
);
3551 if (!file_exists(rebase_path_message())) {
3552 const char *encoding
= get_commit_output_encoding();
3553 const char *commit_buffer
= repo_logmsg_reencode(r
,
3556 find_commit_subject(commit_buffer
, &subject
);
3557 res
|= write_message(subject
, strlen(subject
), rebase_path_message(), 1);
3558 repo_unuse_commit_buffer(r
, commit
,
3561 release_revisions(&log_tree_opt
);
3566 static int intend_to_amend(void)
3568 struct object_id head
;
3571 if (repo_get_oid(the_repository
, "HEAD", &head
))
3572 return error(_("cannot read HEAD"));
3574 p
= oid_to_hex(&head
);
3575 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3578 static int error_with_patch(struct repository
*r
,
3579 struct commit
*commit
,
3580 const char *subject
, int subject_len
,
3581 struct replay_opts
*opts
,
3582 int exit_code
, int to_amend
)
3585 if (make_patch(r
, commit
, opts
))
3587 } else if (copy_file(rebase_path_message(),
3588 git_path_merge_msg(r
), 0666))
3589 return error(_("unable to copy '%s' to '%s'"),
3590 git_path_merge_msg(r
), rebase_path_message());
3593 if (intend_to_amend())
3597 _("You can amend the commit now, with\n"
3599 " git commit --amend %s\n"
3601 "Once you are satisfied with your changes, run\n"
3603 " git rebase --continue\n"),
3604 gpg_sign_opt_quoted(opts
));
3605 } else if (exit_code
) {
3607 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3608 short_commit_name(r
, commit
), subject_len
, subject
);
3611 * We don't have the hash of the parent so
3612 * just print the line from the todo file.
3614 fprintf_ln(stderr
, _("Could not merge %.*s"),
3615 subject_len
, subject
);
3621 static int error_failed_squash(struct repository
*r
,
3622 struct commit
*commit
,
3623 struct replay_opts
*opts
,
3625 const char *subject
)
3627 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3628 return error(_("could not copy '%s' to '%s'"),
3629 rebase_path_squash_msg(), rebase_path_message());
3630 unlink(git_path_merge_msg(r
));
3631 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3632 return error(_("could not copy '%s' to '%s'"),
3633 rebase_path_message(),
3634 git_path_merge_msg(r
));
3635 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3638 static int do_exec(struct repository
*r
, const char *command_line
)
3640 struct child_process cmd
= CHILD_PROCESS_INIT
;
3643 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3645 strvec_push(&cmd
.args
, command_line
);
3646 strvec_push(&cmd
.env
, "GIT_CHERRY_PICK_HELP");
3647 status
= run_command(&cmd
);
3649 /* force re-reading of the cache */
3650 discard_index(r
->index
);
3651 if (repo_read_index(r
) < 0)
3652 return error(_("could not read index"));
3654 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3657 warning(_("execution failed: %s\n%s"
3658 "You can fix the problem, and then run\n"
3660 " git rebase --continue\n"
3663 dirty
? _("and made changes to the index and/or the "
3664 "working tree.\n") : "");
3666 /* command not found */
3669 warning(_("execution succeeded: %s\nbut "
3670 "left changes to the index and/or the working tree.\n"
3671 "Commit or stash your changes, and then run\n"
3673 " git rebase --continue\n"
3674 "\n"), command_line
);
3681 __attribute__((format (printf
, 2, 3)))
3682 static int safe_append(const char *filename
, const char *fmt
, ...)
3685 struct lock_file lock
= LOCK_INIT
;
3686 int fd
= hold_lock_file_for_update(&lock
, filename
,
3687 LOCK_REPORT_ON_ERROR
);
3688 struct strbuf buf
= STRBUF_INIT
;
3693 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3694 error_errno(_("could not read '%s'"), filename
);
3695 rollback_lock_file(&lock
);
3698 strbuf_complete(&buf
, '\n');
3700 strbuf_vaddf(&buf
, fmt
, ap
);
3703 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3704 error_errno(_("could not write to '%s'"), filename
);
3705 strbuf_release(&buf
);
3706 rollback_lock_file(&lock
);
3709 if (commit_lock_file(&lock
) < 0) {
3710 strbuf_release(&buf
);
3711 return error(_("failed to finalize '%s'"), filename
);
3714 strbuf_release(&buf
);
3718 static int do_label(struct repository
*r
, const char *name
, int len
)
3720 struct ref_store
*refs
= get_main_ref_store(r
);
3721 struct ref_transaction
*transaction
;
3722 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3723 struct strbuf msg
= STRBUF_INIT
;
3725 struct object_id head_oid
;
3727 if (len
== 1 && *name
== '#')
3728 return error(_("illegal label name: '%.*s'"), len
, name
);
3730 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3731 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3733 transaction
= ref_store_transaction_begin(refs
, &err
);
3735 error("%s", err
.buf
);
3737 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3738 error(_("could not read HEAD"));
3740 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3741 NULL
, 0, msg
.buf
, &err
) < 0 ||
3742 ref_transaction_commit(transaction
, &err
)) {
3743 error("%s", err
.buf
);
3746 ref_transaction_free(transaction
);
3747 strbuf_release(&err
);
3748 strbuf_release(&msg
);
3751 ret
= safe_append(rebase_path_refs_to_delete(),
3752 "%s\n", ref_name
.buf
);
3753 strbuf_release(&ref_name
);
3758 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3760 if (!opts
->reflog_action
) {
3761 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3762 opts
->reflog_action
=
3763 xstrdup(opts
->reflog_action
? opts
->reflog_action
3764 : action_name(opts
));
3767 return opts
->reflog_action
;
3770 __attribute__((format (printf
, 3, 4)))
3771 static const char *reflog_message(struct replay_opts
*opts
,
3772 const char *sub_action
, const char *fmt
, ...)
3775 static struct strbuf buf
= STRBUF_INIT
;
3779 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3781 strbuf_addf(&buf
, " (%s)", sub_action
);
3783 strbuf_addstr(&buf
, ": ");
3784 strbuf_vaddf(&buf
, fmt
, ap
);
3791 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3792 int len
, struct strbuf
*buf
)
3794 struct commit
*commit
;
3795 struct object_id oid
;
3798 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3799 if (!read_ref(buf
->buf
, &oid
)) {
3800 commit
= lookup_commit_object(r
, &oid
);
3802 /* fall back to non-rewritten ref or commit */
3803 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3804 commit
= lookup_commit_reference_by_name(buf
->buf
);
3808 error(_("could not resolve '%s'"), buf
->buf
);
3813 static int do_reset(struct repository
*r
,
3814 const char *name
, int len
,
3815 struct replay_opts
*opts
)
3817 struct strbuf ref_name
= STRBUF_INIT
;
3818 struct object_id oid
;
3819 struct lock_file lock
= LOCK_INIT
;
3820 struct tree_desc desc
= { 0 };
3822 struct unpack_trees_options unpack_tree_opts
= { 0 };
3825 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3828 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3829 if (!opts
->have_squash_onto
) {
3831 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3832 NULL
, &opts
->squash_onto
,
3834 return error(_("writing fake root commit"));
3835 opts
->have_squash_onto
= 1;
3836 hex
= oid_to_hex(&opts
->squash_onto
);
3837 if (write_message(hex
, strlen(hex
),
3838 rebase_path_squash_onto(), 0))
3839 return error(_("writing squash-onto"));
3841 oidcpy(&oid
, &opts
->squash_onto
);
3844 struct commit
*commit
;
3846 /* Determine the length of the label */
3847 for (i
= 0; i
< len
; i
++)
3848 if (isspace(name
[i
]))
3852 commit
= lookup_label(r
, name
, len
, &ref_name
);
3857 oid
= commit
->object
.oid
;
3860 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3861 unpack_tree_opts
.head_idx
= 1;
3862 unpack_tree_opts
.src_index
= r
->index
;
3863 unpack_tree_opts
.dst_index
= r
->index
;
3864 unpack_tree_opts
.fn
= oneway_merge
;
3865 unpack_tree_opts
.merge
= 1;
3866 unpack_tree_opts
.update
= 1;
3867 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3868 unpack_tree_opts
.skip_cache_tree_update
= 1;
3869 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3871 if (repo_read_index_unmerged(r
)) {
3872 ret
= error_resolve_conflict(action_name(opts
));
3876 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3877 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3881 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3886 tree
= parse_tree_indirect(&oid
);
3888 return error(_("unable to read tree (%s)"), oid_to_hex(&oid
));
3889 prime_cache_tree(r
, r
->index
, tree
);
3891 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3892 ret
= error(_("could not write index"));
3895 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3896 len
, name
), "HEAD", &oid
,
3897 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3899 free((void *)desc
.buffer
);
3901 rollback_lock_file(&lock
);
3902 strbuf_release(&ref_name
);
3903 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3907 static int do_merge(struct repository
*r
,
3908 struct commit
*commit
,
3909 const char *arg
, int arg_len
,
3910 int flags
, int *check_todo
, struct replay_opts
*opts
)
3912 int run_commit_flags
= 0;
3913 struct strbuf ref_name
= STRBUF_INIT
;
3914 struct commit
*head_commit
, *merge_commit
, *i
;
3915 struct commit_list
*bases
= NULL
, *j
;
3916 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3917 const char *strategy
= !opts
->xopts
.nr
&&
3919 !strcmp(opts
->strategy
, "recursive") ||
3920 !strcmp(opts
->strategy
, "ort")) ?
3921 NULL
: opts
->strategy
;
3922 struct merge_options o
;
3923 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3924 static struct lock_file lock
;
3927 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3932 head_commit
= lookup_commit_reference_by_name("HEAD");
3934 ret
= error(_("cannot merge without a current revision"));
3939 * For octopus merges, the arg starts with the list of revisions to be
3940 * merged. The list is optionally followed by '#' and the oneline.
3942 merge_arg_len
= oneline_offset
= arg_len
;
3943 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3946 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3947 p
+= 1 + strspn(p
+ 1, " \t\n");
3948 oneline_offset
= p
- arg
;
3951 k
= strcspn(p
, " \t\n");
3954 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3955 if (!merge_commit
) {
3956 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3959 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3961 merge_arg_len
= p
- arg
;
3965 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3969 if (opts
->have_squash_onto
&&
3970 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3972 * When the user tells us to "merge" something into a
3973 * "[new root]", let's simply fast-forward to the merge head.
3975 rollback_lock_file(&lock
);
3977 ret
= error(_("octopus merge cannot be executed on "
3978 "top of a [new root]"));
3980 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3981 &head_commit
->object
.oid
, 0,
3987 * If HEAD is not identical to the first parent of the original merge
3988 * commit, we cannot fast-forward.
3990 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3991 oideq(&commit
->parents
->item
->object
.oid
,
3992 &head_commit
->object
.oid
);
3995 * If any merge head is different from the original one, we cannot
3998 if (can_fast_forward
) {
3999 struct commit_list
*p
= commit
->parents
->next
;
4001 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
4002 if (!oideq(&j
->item
->object
.oid
,
4003 &p
->item
->object
.oid
)) {
4004 can_fast_forward
= 0;
4008 * If the number of merge heads differs from the original merge
4009 * commit, we cannot fast-forward.
4012 can_fast_forward
= 0;
4015 if (can_fast_forward
) {
4016 rollback_lock_file(&lock
);
4017 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4018 &head_commit
->object
.oid
, 0, opts
);
4019 if (flags
& TODO_EDIT_MERGE_MSG
)
4020 goto fast_forward_edit
;
4026 const char *encoding
= get_commit_output_encoding();
4027 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4033 ret
= error(_("could not get commit message of '%s'"),
4034 oid_to_hex(&commit
->object
.oid
));
4037 write_author_script(message
);
4038 find_commit_subject(message
, &body
);
4040 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4041 repo_unuse_commit_buffer(r
, commit
, message
);
4043 error_errno(_("could not write '%s'"),
4044 git_path_merge_msg(r
));
4048 struct strbuf buf
= STRBUF_INIT
;
4051 strbuf_addf(&buf
, "author %s", git_author_info(0));
4052 write_author_script(buf
.buf
);
4055 if (oneline_offset
< arg_len
) {
4056 p
= arg
+ oneline_offset
;
4057 len
= arg_len
- oneline_offset
;
4059 strbuf_addf(&buf
, "Merge %s '%.*s'",
4060 to_merge
->next
? "branches" : "branch",
4061 merge_arg_len
, arg
);
4066 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4067 strbuf_release(&buf
);
4069 error_errno(_("could not write '%s'"),
4070 git_path_merge_msg(r
));
4075 if (strategy
|| to_merge
->next
) {
4077 struct child_process cmd
= CHILD_PROCESS_INIT
;
4079 if (read_env_script(&cmd
.env
)) {
4080 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4082 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4086 if (opts
->committer_date_is_author_date
)
4087 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4090 author_date_from_env(&cmd
.env
));
4091 if (opts
->ignore_date
)
4092 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4095 strvec_push(&cmd
.args
, "merge");
4096 strvec_push(&cmd
.args
, "-s");
4098 strvec_push(&cmd
.args
, "octopus");
4100 strvec_push(&cmd
.args
, strategy
);
4101 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4102 strvec_pushf(&cmd
.args
,
4103 "-X%s", opts
->xopts
.v
[k
]);
4105 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4106 strvec_push(&cmd
.args
, "--no-edit");
4108 strvec_push(&cmd
.args
, "--edit");
4109 strvec_push(&cmd
.args
, "--no-ff");
4110 strvec_push(&cmd
.args
, "--no-log");
4111 strvec_push(&cmd
.args
, "--no-stat");
4112 strvec_push(&cmd
.args
, "-F");
4113 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4115 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4117 strvec_push(&cmd
.args
, "--no-gpg-sign");
4119 /* Add the tips to be merged */
4120 for (j
= to_merge
; j
; j
= j
->next
)
4121 strvec_push(&cmd
.args
,
4122 oid_to_hex(&j
->item
->object
.oid
));
4124 strbuf_release(&ref_name
);
4125 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4126 NULL
, REF_NO_DEREF
);
4127 rollback_lock_file(&lock
);
4129 ret
= run_command(&cmd
);
4131 /* force re-reading of the cache */
4133 discard_index(r
->index
);
4134 if (repo_read_index(r
) < 0)
4135 ret
= error(_("could not read index"));
4140 merge_commit
= to_merge
->item
;
4141 if (repo_get_merge_bases(r
, head_commit
, merge_commit
, &bases
) < 0) {
4146 if (bases
&& oideq(&merge_commit
->object
.oid
,
4147 &bases
->item
->object
.oid
)) {
4149 /* skip merging an ancestor of HEAD */
4153 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4154 git_path_merge_head(r
), 0);
4155 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4157 bases
= reverse_commit_list(bases
);
4160 init_merge_options(&o
, r
);
4162 o
.branch2
= ref_name
.buf
;
4163 o
.buffer_output
= 2;
4165 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4167 * TODO: Should use merge_incore_recursive() and
4168 * merge_switch_to_result(), skipping the call to
4169 * merge_switch_to_result() when we don't actually need to
4170 * update the index and working copy immediately.
4172 ret
= merge_ort_recursive(&o
,
4173 head_commit
, merge_commit
, bases
,
4176 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4180 fputs(o
.obuf
.buf
, stdout
);
4181 strbuf_release(&o
.obuf
);
4183 error(_("could not even attempt to merge '%.*s'"),
4184 merge_arg_len
, arg
);
4185 unlink(git_path_merge_msg(r
));
4189 * The return value of merge_recursive() is 1 on clean, and 0 on
4192 * Let's reverse that, so that do_merge() returns 0 upon success and
4193 * 1 upon failed merge (keeping the return value -1 for the cases where
4194 * we will want to reschedule the `merge` command).
4198 if (r
->index
->cache_changed
&&
4199 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4200 ret
= error(_("merge: Unable to write new index file"));
4204 rollback_lock_file(&lock
);
4206 repo_rerere(r
, opts
->allow_rerere_auto
);
4209 * In case of problems, we now want to return a positive
4210 * value (a negative one would indicate that the `merge`
4211 * command needs to be rescheduled).
4213 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4216 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4219 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4220 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4225 strbuf_release(&ref_name
);
4226 rollback_lock_file(&lock
);
4227 free_commit_list(to_merge
);
4231 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4234 struct lock_file lock
= LOCK_INIT
;
4236 struct string_list_item
*item
;
4239 path
= rebase_path_update_refs(the_repository
->gitdir
);
4241 if (!refs_to_oids
->nr
) {
4242 if (unlink(path
) && errno
!= ENOENT
)
4243 result
= error_errno(_("could not unlink: %s"), path
);
4247 if (safe_create_leading_directories(path
)) {
4248 result
= error(_("unable to create leading directories of %s"),
4253 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4254 result
= error(_("another 'rebase' process appears to be running; "
4255 "'%s.lock' already exists"),
4260 fp
= fdopen_lock_file(&lock
, "w");
4262 result
= error_errno(_("could not open '%s' for writing"), path
);
4263 rollback_lock_file(&lock
);
4267 for_each_string_list_item(item
, refs_to_oids
) {
4268 struct update_ref_record
*rec
= item
->util
;
4269 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4270 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4273 result
= commit_lock_file(&lock
);
4281 * Parse the update-refs file for the current rebase, then remove the
4282 * refs that do not appear in the todo_list (and have not had updated
4283 * values stored) and add refs that are in the todo_list but not
4284 * represented in the update-refs file.
4286 * If there are changes to the update-refs list, then write the new state
4289 void todo_list_filter_update_refs(struct repository
*r
,
4290 struct todo_list
*todo_list
)
4294 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4296 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4299 * For each item in the update_refs list, if it has no updated
4300 * value and does not appear in the todo_list, then remove it
4301 * from the update_refs list.
4303 for (i
= 0; i
< update_refs
.nr
; i
++) {
4306 const char *ref
= update_refs
.items
[i
].string
;
4307 size_t reflen
= strlen(ref
);
4308 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4310 /* OID already stored as updated. */
4311 if (!is_null_oid(&rec
->after
))
4314 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4315 struct todo_item
*item
= &todo_list
->items
[j
];
4316 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4318 if (item
->command
!= TODO_UPDATE_REF
)
4321 if (item
->arg_len
!= reflen
||
4322 strncmp(arg
, ref
, reflen
))
4329 free(update_refs
.items
[i
].string
);
4330 free(update_refs
.items
[i
].util
);
4333 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4341 * For each todo_item, check if its ref is in the update_refs list.
4342 * If not, then add it as an un-updated ref.
4344 for (i
= 0; i
< todo_list
->nr
; i
++) {
4345 struct todo_item
*item
= &todo_list
->items
[i
];
4346 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4349 if (item
->command
!= TODO_UPDATE_REF
)
4352 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4353 const char *ref
= update_refs
.items
[j
].string
;
4355 found
= strlen(ref
) == item
->arg_len
&&
4356 !strncmp(ref
, arg
, item
->arg_len
);
4360 struct string_list_item
*inserted
;
4361 struct strbuf argref
= STRBUF_INIT
;
4363 strbuf_add(&argref
, arg
, item
->arg_len
);
4364 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4365 inserted
->util
= init_update_ref_record(argref
.buf
);
4366 strbuf_release(&argref
);
4372 write_update_refs_state(&update_refs
);
4373 string_list_clear(&update_refs
, 1);
4376 static int do_update_ref(struct repository
*r
, const char *refname
)
4378 struct string_list_item
*item
;
4379 struct string_list list
= STRING_LIST_INIT_DUP
;
4381 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4384 for_each_string_list_item(item
, &list
) {
4385 if (!strcmp(item
->string
, refname
)) {
4386 struct update_ref_record
*rec
= item
->util
;
4387 if (read_ref("HEAD", &rec
->after
))
4393 write_update_refs_state(&list
);
4394 string_list_clear(&list
, 1);
4398 static int do_update_refs(struct repository
*r
, int quiet
)
4401 struct string_list_item
*item
;
4402 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4403 struct ref_store
*refs
= get_main_ref_store(r
);
4404 struct strbuf update_msg
= STRBUF_INIT
;
4405 struct strbuf error_msg
= STRBUF_INIT
;
4407 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4410 for_each_string_list_item(item
, &refs_to_oids
) {
4411 struct update_ref_record
*rec
= item
->util
;
4414 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4416 &rec
->after
, &rec
->before
,
4417 0, UPDATE_REFS_MSG_ON_ERR
);
4424 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4426 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4430 (update_msg
.len
|| error_msg
.len
)) {
4432 _("Updated the following refs with %s:\n%s"),
4438 _("Failed to update the following refs with %s:\n%s"),
4443 string_list_clear(&refs_to_oids
, 1);
4444 strbuf_release(&update_msg
);
4445 strbuf_release(&error_msg
);
4449 static int is_final_fixup(struct todo_list
*todo_list
)
4451 int i
= todo_list
->current
;
4453 if (!is_fixup(todo_list
->items
[i
].command
))
4456 while (++i
< todo_list
->nr
)
4457 if (is_fixup(todo_list
->items
[i
].command
))
4459 else if (!is_noop(todo_list
->items
[i
].command
))
4464 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4468 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4469 if (!is_noop(todo_list
->items
[i
].command
))
4470 return todo_list
->items
[i
].command
;
4475 static void create_autostash_internal(struct repository
*r
,
4477 const char *refname
)
4479 struct strbuf buf
= STRBUF_INIT
;
4480 struct lock_file lock_file
= LOCK_INIT
;
4483 if (path
&& refname
)
4484 BUG("can only pass path or refname");
4486 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4487 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4489 repo_update_index_if_able(r
, &lock_file
);
4490 rollback_lock_file(&lock_file
);
4492 if (has_unstaged_changes(r
, 1) ||
4493 has_uncommitted_changes(r
, 1)) {
4494 struct child_process stash
= CHILD_PROCESS_INIT
;
4495 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4496 struct object_id oid
;
4498 strvec_pushl(&stash
.args
,
4499 "stash", "create", "autostash", NULL
);
4503 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4504 die(_("Cannot autostash"));
4505 strbuf_trim_trailing_newline(&buf
);
4506 if (repo_get_oid(r
, buf
.buf
, &oid
))
4507 die(_("Unexpected stash response: '%s'"),
4510 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4513 if (safe_create_leading_directories_const(path
))
4514 die(_("Could not create directory for '%s'"),
4516 write_file(path
, "%s", oid_to_hex(&oid
));
4518 refs_update_ref(get_main_ref_store(r
), "", refname
,
4519 &oid
, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR
);
4522 printf(_("Created autostash: %s\n"), buf
.buf
);
4523 if (reset_head(r
, &ropts
) < 0)
4524 die(_("could not reset --hard"));
4525 discard_index(r
->index
);
4526 if (repo_read_index(r
) < 0)
4527 die(_("could not read index"));
4529 strbuf_release(&buf
);
4532 void create_autostash(struct repository
*r
, const char *path
)
4534 create_autostash_internal(r
, path
, NULL
);
4537 void create_autostash_ref(struct repository
*r
, const char *refname
)
4539 create_autostash_internal(r
, NULL
, refname
);
4542 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4544 struct child_process child
= CHILD_PROCESS_INIT
;
4547 if (attempt_apply
) {
4549 child
.no_stdout
= 1;
4550 child
.no_stderr
= 1;
4551 strvec_push(&child
.args
, "stash");
4552 strvec_push(&child
.args
, "apply");
4553 strvec_push(&child
.args
, stash_oid
);
4554 ret
= run_command(&child
);
4557 if (attempt_apply
&& !ret
)
4558 fprintf(stderr
, _("Applied autostash.\n"));
4560 struct child_process store
= CHILD_PROCESS_INIT
;
4563 strvec_push(&store
.args
, "stash");
4564 strvec_push(&store
.args
, "store");
4565 strvec_push(&store
.args
, "-m");
4566 strvec_push(&store
.args
, "autostash");
4567 strvec_push(&store
.args
, "-q");
4568 strvec_push(&store
.args
, stash_oid
);
4569 if (run_command(&store
))
4570 ret
= error(_("cannot store %s"), stash_oid
);
4574 "Your changes are safe in the stash.\n"
4575 "You can run \"git stash pop\" or"
4576 " \"git stash drop\" at any time.\n"),
4578 _("Applying autostash resulted in conflicts.") :
4579 _("Autostash exists; creating a new stash entry."));
4585 static int apply_save_autostash(const char *path
, int attempt_apply
)
4587 struct strbuf stash_oid
= STRBUF_INIT
;
4590 if (!read_oneliner(&stash_oid
, path
,
4591 READ_ONELINER_SKIP_IF_EMPTY
)) {
4592 strbuf_release(&stash_oid
);
4595 strbuf_trim(&stash_oid
);
4597 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4600 strbuf_release(&stash_oid
);
4604 int save_autostash(const char *path
)
4606 return apply_save_autostash(path
, 0);
4609 int apply_autostash(const char *path
)
4611 return apply_save_autostash(path
, 1);
4614 int apply_autostash_oid(const char *stash_oid
)
4616 return apply_save_autostash_oid(stash_oid
, 1);
4619 static int apply_save_autostash_ref(struct repository
*r
, const char *refname
,
4622 struct object_id stash_oid
;
4623 char stash_oid_hex
[GIT_MAX_HEXSZ
+ 1];
4626 if (!refs_ref_exists(get_main_ref_store(r
), refname
))
4629 if (!refs_resolve_ref_unsafe(get_main_ref_store(r
), refname
,
4630 RESOLVE_REF_READING
, &stash_oid
, &flag
))
4632 if (flag
& REF_ISSYMREF
)
4633 return error(_("autostash reference is a symref"));
4635 oid_to_hex_r(stash_oid_hex
, &stash_oid
);
4636 ret
= apply_save_autostash_oid(stash_oid_hex
, attempt_apply
);
4638 refs_delete_ref(get_main_ref_store(r
), "", refname
,
4639 &stash_oid
, REF_NO_DEREF
);
4644 int save_autostash_ref(struct repository
*r
, const char *refname
)
4646 return apply_save_autostash_ref(r
, refname
, 0);
4649 int apply_autostash_ref(struct repository
*r
, const char *refname
)
4651 return apply_save_autostash_ref(r
, refname
, 1);
4654 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4655 const char *onto_name
, const struct object_id
*onto
,
4656 const struct object_id
*orig_head
)
4658 struct reset_head_opts ropts
= {
4660 .orig_head
= orig_head
,
4661 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4662 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4663 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4665 .default_reflog_action
= sequencer_reflog_action(opts
)
4667 if (reset_head(r
, &ropts
)) {
4668 apply_autostash(rebase_path_autostash());
4669 sequencer_remove_state(opts
);
4670 return error(_("could not detach HEAD"));
4676 static int stopped_at_head(struct repository
*r
)
4678 struct object_id head
;
4679 struct commit
*commit
;
4680 struct commit_message message
;
4682 if (repo_get_oid(r
, "HEAD", &head
) ||
4683 !(commit
= lookup_commit(r
, &head
)) ||
4684 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4685 fprintf(stderr
, _("Stopped at HEAD\n"));
4687 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4688 free_message(commit
, &message
);
4694 static int reread_todo_if_changed(struct repository
*r
,
4695 struct todo_list
*todo_list
,
4696 struct replay_opts
*opts
)
4699 struct strbuf buf
= STRBUF_INIT
;
4701 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4703 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4704 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4705 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4706 /* Reread the todo file if it has changed. */
4707 todo_list_release(todo_list
);
4708 if (read_populate_todo(r
, todo_list
, opts
))
4709 return -1; /* message was printed */
4710 /* `current` will be incremented on return */
4711 todo_list
->current
= -1;
4713 strbuf_release(&buf
);
4718 static const char rescheduled_advice
[] =
4719 N_("Could not execute the todo command\n"
4723 "It has been rescheduled; To edit the command before continuing, please\n"
4724 "edit the todo list first:\n"
4726 " git rebase --edit-todo\n"
4727 " git rebase --continue\n");
4729 static int pick_one_commit(struct repository
*r
,
4730 struct todo_list
*todo_list
,
4731 struct replay_opts
*opts
,
4732 int *check_todo
, int* reschedule
)
4735 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4736 const char *arg
= todo_item_get_arg(todo_list
, item
);
4737 if (is_rebase_i(opts
))
4738 opts
->reflog_message
= reflog_message(
4739 opts
, command_to_string(item
->command
), NULL
);
4741 res
= do_pick_commit(r
, item
, opts
, is_final_fixup(todo_list
),
4743 if (is_rebase_i(opts
) && res
< 0) {
4748 if (item
->command
== TODO_EDIT
) {
4749 struct commit
*commit
= item
->commit
;
4753 fprintf(stderr
, _("Stopped at %s... %.*s\n"),
4754 short_commit_name(r
, commit
), item
->arg_len
, arg
);
4756 return error_with_patch(r
, commit
,
4757 arg
, item
->arg_len
, opts
, res
, !res
);
4759 if (is_rebase_i(opts
) && !res
)
4760 record_in_rewritten(&item
->commit
->object
.oid
,
4761 peek_command(todo_list
, 1));
4762 if (res
&& is_fixup(item
->command
)) {
4765 return error_failed_squash(r
, item
->commit
, opts
,
4766 item
->arg_len
, arg
);
4767 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4769 struct object_id oid
;
4772 * If we are rewording and have either
4773 * fast-forwarded already, or are about to
4774 * create a new root commit, we want to amend,
4775 * otherwise we do not.
4777 if (item
->command
== TODO_REWORD
&&
4778 !repo_get_oid(r
, "HEAD", &oid
) &&
4779 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4780 (opts
->have_squash_onto
&&
4781 oideq(&opts
->squash_onto
, &oid
))))
4784 return res
| error_with_patch(r
, item
->commit
,
4785 arg
, item
->arg_len
, opts
,
4791 static int pick_commits(struct repository
*r
,
4792 struct todo_list
*todo_list
,
4793 struct replay_opts
*opts
)
4795 int res
= 0, reschedule
= 0;
4797 opts
->reflog_message
= sequencer_reflog_action(opts
);
4799 assert(!(opts
->signoff
|| opts
->no_commit
||
4800 opts
->record_origin
|| should_edit(opts
) ||
4801 opts
->committer_date_is_author_date
||
4802 opts
->ignore_date
));
4803 if (read_and_refresh_cache(r
, opts
))
4806 unlink(rebase_path_message());
4807 unlink(rebase_path_stopped_sha());
4808 unlink(rebase_path_amend());
4809 unlink(rebase_path_patch());
4811 while (todo_list
->current
< todo_list
->nr
) {
4812 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4813 const char *arg
= todo_item_get_arg(todo_list
, item
);
4816 if (save_todo(todo_list
, opts
, reschedule
))
4818 if (is_rebase_i(opts
)) {
4819 if (item
->command
!= TODO_COMMENT
) {
4820 FILE *f
= fopen(rebase_path_msgnum(), "w");
4822 todo_list
->done_nr
++;
4825 fprintf(f
, "%d\n", todo_list
->done_nr
);
4829 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4831 todo_list
->total_nr
,
4832 opts
->verbose
? "\n" : "\r");
4834 unlink(rebase_path_author_script());
4835 unlink(git_path_merge_head(r
));
4836 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
4837 NULL
, REF_NO_DEREF
);
4838 refs_delete_ref(get_main_ref_store(r
), "", "REBASE_HEAD",
4839 NULL
, REF_NO_DEREF
);
4841 if (item
->command
== TODO_BREAK
) {
4844 return stopped_at_head(r
);
4847 if (item
->command
<= TODO_SQUASH
) {
4848 res
= pick_one_commit(r
, todo_list
, opts
, &check_todo
,
4850 if (!res
&& item
->command
== TODO_EDIT
)
4852 } else if (item
->command
== TODO_EXEC
) {
4853 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4854 int saved
= *end_of_arg
;
4859 res
= do_exec(r
, arg
);
4860 *end_of_arg
= saved
;
4863 if (opts
->reschedule_failed_exec
)
4867 } else if (item
->command
== TODO_LABEL
) {
4868 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4870 } else if (item
->command
== TODO_RESET
) {
4871 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4873 } else if (item
->command
== TODO_MERGE
) {
4874 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4875 item
->flags
, &check_todo
, opts
)) < 0)
4877 else if (item
->commit
)
4878 record_in_rewritten(&item
->commit
->object
.oid
,
4879 peek_command(todo_list
, 1));
4881 /* failed with merge conflicts */
4882 return error_with_patch(r
, item
->commit
,
4885 } else if (item
->command
== TODO_UPDATE_REF
) {
4886 struct strbuf ref
= STRBUF_INIT
;
4887 strbuf_add(&ref
, arg
, item
->arg_len
);
4888 if ((res
= do_update_ref(r
, ref
.buf
)))
4890 strbuf_release(&ref
);
4891 } else if (!is_noop(item
->command
))
4892 return error(_("unknown command %d"), item
->command
);
4895 advise(_(rescheduled_advice
),
4896 get_item_line_length(todo_list
,
4897 todo_list
->current
),
4898 get_item_line(todo_list
, todo_list
->current
));
4899 if (save_todo(todo_list
, opts
, reschedule
))
4902 write_rebase_head(&item
->commit
->object
.oid
);
4903 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4904 reread_todo_if_changed(r
, todo_list
, opts
)) {
4911 todo_list
->current
++;
4914 if (is_rebase_i(opts
)) {
4915 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4918 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4919 starts_with(head_ref
.buf
, "refs/")) {
4921 struct object_id head
, orig
;
4924 if (repo_get_oid(r
, "HEAD", &head
)) {
4925 res
= error(_("cannot read HEAD"));
4927 strbuf_release(&head_ref
);
4928 strbuf_release(&buf
);
4931 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4932 get_oid_hex(buf
.buf
, &orig
)) {
4933 res
= error(_("could not read orig-head"));
4934 goto cleanup_head_ref
;
4937 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4938 res
= error(_("could not read 'onto'"));
4939 goto cleanup_head_ref
;
4941 msg
= reflog_message(opts
, "finish", "%s onto %s",
4942 head_ref
.buf
, buf
.buf
);
4943 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4944 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4945 res
= error(_("could not update %s"),
4947 goto cleanup_head_ref
;
4949 msg
= reflog_message(opts
, "finish", "returning to %s",
4951 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4952 res
= error(_("could not update HEAD to %s"),
4954 goto cleanup_head_ref
;
4959 if (opts
->verbose
) {
4960 struct rev_info log_tree_opt
;
4961 struct object_id orig
, head
;
4963 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4964 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4965 log_tree_opt
.diff
= 1;
4966 log_tree_opt
.diffopt
.output_format
=
4967 DIFF_FORMAT_DIFFSTAT
;
4968 log_tree_opt
.disable_stdin
= 1;
4970 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4971 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4972 !repo_get_oid(r
, "HEAD", &head
)) {
4973 diff_tree_oid(&orig
, &head
, "",
4974 &log_tree_opt
.diffopt
);
4975 log_tree_diff_flush(&log_tree_opt
);
4977 release_revisions(&log_tree_opt
);
4979 flush_rewritten_pending();
4980 if (!stat(rebase_path_rewritten_list(), &st
) &&
4982 struct child_process child
= CHILD_PROCESS_INIT
;
4983 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4985 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4987 strvec_push(&child
.args
, "notes");
4988 strvec_push(&child
.args
, "copy");
4989 strvec_push(&child
.args
, "--for-rewrite=rebase");
4990 /* we don't care if this copying failed */
4991 run_command(&child
);
4993 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4994 strvec_push(&hook_opt
.args
, "rebase");
4995 run_hooks_opt("post-rewrite", &hook_opt
);
4997 apply_autostash(rebase_path_autostash());
5003 _("Successfully rebased and updated %s.\n"),
5007 strbuf_release(&buf
);
5008 strbuf_release(&head_ref
);
5010 if (do_update_refs(r
, opts
->quiet
))
5015 * Sequence of picks finished successfully; cleanup by
5016 * removing the .git/sequencer directory
5018 return sequencer_remove_state(opts
);
5021 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
5023 struct child_process cmd
= CHILD_PROCESS_INIT
;
5025 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
5026 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
5027 return error(_("no cherry-pick or revert in progress"));
5030 strvec_push(&cmd
.args
, "commit");
5033 * continue_single_pick() handles the case of recovering from a
5034 * conflict. should_edit() doesn't handle that case; for a conflict,
5035 * we want to edit if the user asked for it, or if they didn't specify
5036 * and stdin is a tty.
5038 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
5040 * Include --cleanup=strip as well because we don't want the
5041 * "# Conflicts:" messages.
5043 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
5045 return run_command(&cmd
);
5048 static int commit_staged_changes(struct repository
*r
,
5049 struct replay_opts
*opts
,
5050 struct todo_list
*todo_list
)
5052 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
5053 unsigned int final_fixup
= 0, is_clean
;
5055 if (has_unstaged_changes(r
, 1))
5056 return error(_("cannot rebase: You have unstaged changes."));
5058 is_clean
= !has_uncommitted_changes(r
, 0);
5060 if (!is_clean
&& !file_exists(rebase_path_message())) {
5061 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
5063 return error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
5065 if (file_exists(rebase_path_amend())) {
5066 struct strbuf rev
= STRBUF_INIT
;
5067 struct object_id head
, to_amend
;
5069 if (repo_get_oid(r
, "HEAD", &head
))
5070 return error(_("cannot amend non-existing commit"));
5071 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
5072 return error(_("invalid file: '%s'"), rebase_path_amend());
5073 if (get_oid_hex(rev
.buf
, &to_amend
))
5074 return error(_("invalid contents: '%s'"),
5075 rebase_path_amend());
5076 if (!is_clean
&& !oideq(&head
, &to_amend
))
5077 return error(_("\nYou have uncommitted changes in your "
5078 "working tree. Please, commit them\n"
5079 "first and then run 'git rebase "
5080 "--continue' again."));
5082 * When skipping a failed fixup/squash, we need to edit the
5083 * commit message, the current fixup list and count, and if it
5084 * was the last fixup/squash in the chain, we need to clean up
5085 * the commit message and if there was a squash, let the user
5088 if (!is_clean
|| !opts
->current_fixup_count
)
5089 ; /* this is not the final fixup */
5090 else if (!oideq(&head
, &to_amend
) ||
5091 !file_exists(rebase_path_stopped_sha())) {
5092 /* was a final fixup or squash done manually? */
5093 if (!is_fixup(peek_command(todo_list
, 0))) {
5094 unlink(rebase_path_fixup_msg());
5095 unlink(rebase_path_squash_msg());
5096 unlink(rebase_path_current_fixups());
5097 strbuf_reset(&opts
->current_fixups
);
5098 opts
->current_fixup_count
= 0;
5101 /* we are in a fixup/squash chain */
5102 const char *p
= opts
->current_fixups
.buf
;
5103 int len
= opts
->current_fixups
.len
;
5105 opts
->current_fixup_count
--;
5107 BUG("Incorrect current_fixups:\n%s", p
);
5108 while (len
&& p
[len
- 1] != '\n')
5110 strbuf_setlen(&opts
->current_fixups
, len
);
5111 if (write_message(p
, len
, rebase_path_current_fixups(),
5113 return error(_("could not write file: '%s'"),
5114 rebase_path_current_fixups());
5117 * If a fixup/squash in a fixup/squash chain failed, the
5118 * commit message is already correct, no need to commit
5121 * Only if it is the final command in the fixup/squash
5122 * chain, and only if the chain is longer than a single
5123 * fixup/squash command (which was just skipped), do we
5124 * actually need to re-commit with a cleaned up commit
5127 if (opts
->current_fixup_count
> 0 &&
5128 !is_fixup(peek_command(todo_list
, 0))) {
5131 * If there was not a single "squash" in the
5132 * chain, we only need to clean up the commit
5133 * message, no need to bother the user with
5134 * opening the commit message in the editor.
5136 if (!starts_with(p
, "squash ") &&
5137 !strstr(p
, "\nsquash "))
5138 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5139 } else if (is_fixup(peek_command(todo_list
, 0))) {
5141 * We need to update the squash message to skip
5142 * the latest commit message.
5145 struct commit
*commit
;
5147 const char *path
= rebase_path_squash_msg();
5148 const char *encoding
= get_commit_output_encoding();
5150 if (parse_head(r
, &commit
))
5151 return error(_("could not parse HEAD"));
5153 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5155 res
= error(_("could not parse commit %s"),
5156 oid_to_hex(&commit
->object
.oid
));
5157 goto unuse_commit_buffer
;
5159 find_commit_subject(p
, &msg
);
5160 if (write_message(msg
, strlen(msg
), path
, 0)) {
5161 res
= error(_("could not write file: "
5163 goto unuse_commit_buffer
;
5165 unuse_commit_buffer
:
5166 repo_unuse_commit_buffer(r
, commit
, p
);
5172 strbuf_release(&rev
);
5177 if (refs_ref_exists(get_main_ref_store(r
),
5178 "CHERRY_PICK_HEAD") &&
5179 refs_delete_ref(get_main_ref_store(r
), "",
5180 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
))
5181 return error(_("could not remove CHERRY_PICK_HEAD"));
5182 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5183 return error_errno(_("could not remove '%s'"),
5184 git_path_merge_msg(r
));
5189 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5191 return error(_("could not commit staged changes."));
5192 unlink(rebase_path_amend());
5193 unlink(git_path_merge_head(r
));
5194 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
5195 NULL
, REF_NO_DEREF
);
5197 unlink(rebase_path_fixup_msg());
5198 unlink(rebase_path_squash_msg());
5200 if (opts
->current_fixup_count
> 0) {
5202 * Whether final fixup or not, we just cleaned up the commit
5205 unlink(rebase_path_current_fixups());
5206 strbuf_reset(&opts
->current_fixups
);
5207 opts
->current_fixup_count
= 0;
5212 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5214 struct todo_list todo_list
= TODO_LIST_INIT
;
5217 if (read_and_refresh_cache(r
, opts
))
5220 if (read_populate_opts(opts
))
5222 if (is_rebase_i(opts
)) {
5223 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5224 goto release_todo_list
;
5226 if (file_exists(rebase_path_dropped())) {
5227 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5228 goto release_todo_list
;
5230 unlink(rebase_path_dropped());
5233 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5234 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5236 goto release_todo_list
;
5238 } else if (!file_exists(get_todo_path(opts
)))
5239 return continue_single_pick(r
, opts
);
5240 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5241 goto release_todo_list
;
5243 if (!is_rebase_i(opts
)) {
5244 /* Verify that the conflict has been resolved */
5245 if (refs_ref_exists(get_main_ref_store(r
),
5246 "CHERRY_PICK_HEAD") ||
5247 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5248 res
= continue_single_pick(r
, opts
);
5250 goto release_todo_list
;
5252 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5253 res
= error_dirty_index(r
, opts
);
5254 goto release_todo_list
;
5256 todo_list
.current
++;
5257 } else if (file_exists(rebase_path_stopped_sha())) {
5258 struct strbuf buf
= STRBUF_INIT
;
5259 struct object_id oid
;
5261 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5262 READ_ONELINER_SKIP_IF_EMPTY
) &&
5263 !get_oid_hex(buf
.buf
, &oid
))
5264 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5265 strbuf_release(&buf
);
5268 res
= pick_commits(r
, &todo_list
, opts
);
5270 todo_list_release(&todo_list
);
5274 static int single_pick(struct repository
*r
,
5275 struct commit
*cmit
,
5276 struct replay_opts
*opts
)
5279 struct todo_item item
;
5281 item
.command
= opts
->action
== REPLAY_PICK
?
5282 TODO_PICK
: TODO_REVERT
;
5285 opts
->reflog_message
= sequencer_reflog_action(opts
);
5286 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5289 int sequencer_pick_revisions(struct repository
*r
,
5290 struct replay_opts
*opts
)
5292 struct todo_list todo_list
= TODO_LIST_INIT
;
5293 struct object_id oid
;
5297 if (read_and_refresh_cache(r
, opts
))
5300 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5301 struct object_id oid
;
5302 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5304 /* This happens when using --stdin. */
5308 if (!repo_get_oid(r
, name
, &oid
)) {
5309 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5310 enum object_type type
= oid_object_info(r
,
5313 return error(_("%s: can't cherry-pick a %s"),
5314 name
, type_name(type
));
5317 return error(_("%s: bad revision"), name
);
5321 * If we were called as "git cherry-pick <commit>", just
5322 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5323 * REVERT_HEAD, and don't touch the sequencer state.
5324 * This means it is possible to cherry-pick in the middle
5325 * of a cherry-pick sequence.
5327 if (opts
->revs
->cmdline
.nr
== 1 &&
5328 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5329 opts
->revs
->no_walk
&&
5330 !opts
->revs
->cmdline
.rev
->flags
) {
5331 struct commit
*cmit
;
5332 if (prepare_revision_walk(opts
->revs
))
5333 return error(_("revision walk setup failed"));
5334 cmit
= get_revision(opts
->revs
);
5336 return error(_("empty commit set passed"));
5337 if (get_revision(opts
->revs
))
5338 BUG("unexpected extra commit from walk");
5339 return single_pick(r
, cmit
, opts
);
5343 * Start a new cherry-pick/ revert sequence; but
5344 * first, make sure that an existing one isn't in
5348 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5349 create_seq_dir(r
) < 0)
5351 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5352 return error(_("can't revert as initial commit"));
5353 if (save_head(oid_to_hex(&oid
)))
5355 if (save_opts(opts
))
5357 update_abort_safety_file();
5358 res
= pick_commits(r
, &todo_list
, opts
);
5359 todo_list_release(&todo_list
);
5363 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5365 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5366 struct strbuf sob
= STRBUF_INIT
;
5369 strbuf_addstr(&sob
, sign_off_header
);
5370 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5371 strbuf_addch(&sob
, '\n');
5374 strbuf_complete_line(msgbuf
);
5377 * If the whole message buffer is equal to the sob, pretend that we
5378 * found a conforming footer with a matching sob
5380 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5381 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5384 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5387 const char *append_newlines
= NULL
;
5388 size_t len
= msgbuf
->len
- ignore_footer
;
5392 * The buffer is completely empty. Leave foom for
5393 * the title and body to be filled in by the user.
5395 append_newlines
= "\n\n";
5396 } else if (len
== 1) {
5398 * Buffer contains a single newline. Add another
5399 * so that we leave room for the title and body.
5401 append_newlines
= "\n";
5402 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5404 * Buffer ends with a single newline. Add another
5405 * so that there is an empty line between the message
5408 append_newlines
= "\n";
5409 } /* else, the buffer already ends with two newlines. */
5411 if (append_newlines
)
5412 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5413 append_newlines
, strlen(append_newlines
));
5416 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5417 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5420 strbuf_release(&sob
);
5423 struct labels_entry
{
5424 struct hashmap_entry entry
;
5425 char label
[FLEX_ARRAY
];
5428 static int labels_cmp(const void *fndata UNUSED
,
5429 const struct hashmap_entry
*eptr
,
5430 const struct hashmap_entry
*entry_or_key
, const void *key
)
5432 const struct labels_entry
*a
, *b
;
5434 a
= container_of(eptr
, const struct labels_entry
, entry
);
5435 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5437 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5440 struct string_entry
{
5441 struct oidmap_entry entry
;
5442 char string
[FLEX_ARRAY
];
5445 struct label_state
{
5446 struct oidmap commit2label
;
5447 struct hashmap labels
;
5449 int max_label_length
;
5452 static const char *label_oid(struct object_id
*oid
, const char *label
,
5453 struct label_state
*state
)
5455 struct labels_entry
*labels_entry
;
5456 struct string_entry
*string_entry
;
5457 struct object_id dummy
;
5460 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5462 return string_entry
->string
;
5465 * For "uninteresting" commits, i.e. commits that are not to be
5466 * rebased, and which can therefore not be labeled, we use a unique
5467 * abbreviation of the commit name. This is slightly more complicated
5468 * than calling repo_find_unique_abbrev() because we also need to make
5469 * sure that the abbreviation does not conflict with any other
5472 * We disallow "interesting" commits to be labeled by a string that
5473 * is a valid full-length hash, to ensure that we always can find an
5474 * abbreviation for any uninteresting commit's names that does not
5475 * clash with any other label.
5477 strbuf_reset(&state
->buf
);
5481 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5482 label
= p
= state
->buf
.buf
;
5484 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5488 * We may need to extend the abbreviated hash so that there is
5489 * no conflicting label.
5491 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5492 size_t i
= strlen(p
) + 1;
5494 oid_to_hex_r(p
, oid
);
5495 for (; i
< the_hash_algo
->hexsz
; i
++) {
5498 if (!hashmap_get_from_hash(&state
->labels
,
5505 struct strbuf
*buf
= &state
->buf
;
5506 int label_is_utf8
= 1; /* start with this assumption */
5507 size_t max_len
= buf
->len
+ state
->max_label_length
;
5510 * Sanitize labels by replacing non-alpha-numeric characters
5511 * (including white-space ones) by dashes, as they might be
5512 * illegal in file names (and hence in ref names).
5514 * Note that we retain non-ASCII UTF-8 characters (identified
5515 * via the most significant bit). They should be all acceptable
5518 * As we will use the labels as names of (loose) refs, it is
5519 * vital that the name not be longer than the maximum component
5520 * size of the file system (`NAME_MAX`). We are careful to
5521 * truncate the label accordingly, allowing for the `.lock`
5522 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5523 * truncating in the middle of a character).
5525 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5526 if (isalnum(*label
) ||
5527 (!label_is_utf8
&& (*label
& 0x80)))
5528 strbuf_addch(buf
, *label
);
5529 else if (*label
& 0x80) {
5530 const char *p
= label
;
5532 utf8_width(&p
, NULL
);
5534 if (buf
->len
+ (p
- label
) > max_len
)
5536 strbuf_add(buf
, label
, p
- label
);
5540 strbuf_addch(buf
, *label
);
5542 /* avoid leading dash and double-dashes */
5543 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5544 strbuf_addch(buf
, '-');
5546 strbuf_addstr(buf
, "rev-");
5547 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5551 if ((buf
->len
== the_hash_algo
->hexsz
&&
5552 !get_oid_hex(label
, &dummy
)) ||
5553 (buf
->len
== 1 && *label
== '#') ||
5554 hashmap_get_from_hash(&state
->labels
,
5555 strihash(label
), label
)) {
5557 * If the label already exists, or if the label is a
5558 * valid full OID, or the label is a '#' (which we use
5559 * as a separator between merge heads and oneline), we
5560 * append a dash and a number to make it unique.
5562 size_t len
= buf
->len
;
5564 for (i
= 2; ; i
++) {
5565 strbuf_setlen(buf
, len
);
5566 strbuf_addf(buf
, "-%d", i
);
5567 if (!hashmap_get_from_hash(&state
->labels
,
5577 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5578 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5579 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5581 FLEX_ALLOC_STR(string_entry
, string
, label
);
5582 oidcpy(&string_entry
->entry
.oid
, oid
);
5583 oidmap_put(&state
->commit2label
, string_entry
);
5585 return string_entry
->string
;
5588 static int make_script_with_merges(struct pretty_print_context
*pp
,
5589 struct rev_info
*revs
, struct strbuf
*out
,
5592 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5593 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5594 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5595 int skipped_commit
= 0;
5596 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5597 struct strbuf label
= STRBUF_INIT
;
5598 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5599 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5600 struct commit
*commit
;
5601 struct oidmap commit2todo
= OIDMAP_INIT
;
5602 struct string_entry
*entry
;
5603 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5604 shown
= OIDSET_INIT
;
5605 struct label_state state
=
5606 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5608 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5609 const char *cmd_pick
= abbr
? "p" : "pick",
5610 *cmd_label
= abbr
? "l" : "label",
5611 *cmd_reset
= abbr
? "t" : "reset",
5612 *cmd_merge
= abbr
? "m" : "merge";
5614 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5616 oidmap_init(&commit2todo
, 0);
5617 oidmap_init(&state
.commit2label
, 0);
5618 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5619 strbuf_init(&state
.buf
, 32);
5621 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5622 struct labels_entry
*onto_label_entry
;
5623 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5624 FLEX_ALLOC_STR(entry
, string
, "onto");
5625 oidcpy(&entry
->entry
.oid
, oid
);
5626 oidmap_put(&state
.commit2label
, entry
);
5628 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5629 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5630 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5635 * - get onelines for all commits
5636 * - gather all branch tips (i.e. 2nd or later parents of merges)
5637 * - label all branch tips
5639 while ((commit
= get_revision(revs
))) {
5640 struct commit_list
*to_merge
;
5641 const char *p1
, *p2
;
5642 struct object_id
*oid
;
5645 tail
= &commit_list_insert(commit
, tail
)->next
;
5646 oidset_insert(&interesting
, &commit
->object
.oid
);
5648 is_empty
= is_original_commit_empty(commit
);
5649 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5650 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5651 warning(_("skipped previously applied commit %s"),
5652 short_commit_name(the_repository
, commit
));
5656 if (is_empty
&& !keep_empty
)
5659 strbuf_reset(&oneline
);
5660 pretty_print_commit(pp
, commit
, &oneline
);
5662 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5664 /* non-merge commit: easy case */
5666 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5667 oid_to_hex(&commit
->object
.oid
),
5670 strbuf_addf(&buf
, " %c empty",
5673 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5674 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5675 oidmap_put(&commit2todo
, entry
);
5680 /* Create a label */
5681 strbuf_reset(&label
);
5682 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5683 (p1
= strchr(p1
, '\'')) &&
5684 (p2
= strchr(++p1
, '\'')))
5685 strbuf_add(&label
, p1
, p2
- p1
);
5686 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5688 (p1
= strstr(p1
, " from ")))
5689 strbuf_addstr(&label
, p1
+ strlen(" from "));
5691 strbuf_addbuf(&label
, &oneline
);
5694 strbuf_addf(&buf
, "%s -C %s",
5695 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5697 /* label the tips of merged branches */
5698 for (; to_merge
; to_merge
= to_merge
->next
) {
5699 oid
= &to_merge
->item
->object
.oid
;
5700 strbuf_addch(&buf
, ' ');
5702 if (!oidset_contains(&interesting
, oid
)) {
5703 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5708 tips_tail
= &commit_list_insert(to_merge
->item
,
5711 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5713 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5715 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5716 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5717 oidmap_put(&commit2todo
, entry
);
5720 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5721 _("use --reapply-cherry-picks to include skipped commits"));
5725 * - label branch points
5726 * - add HEAD to the branch tips
5728 for (iter
= commits
; iter
; iter
= iter
->next
) {
5729 struct commit_list
*parent
= iter
->item
->parents
;
5730 for (; parent
; parent
= parent
->next
) {
5731 struct object_id
*oid
= &parent
->item
->object
.oid
;
5732 if (!oidset_contains(&interesting
, oid
))
5734 if (oidset_insert(&child_seen
, oid
))
5735 label_oid(oid
, "branch-point", &state
);
5738 /* Add HEAD as implicit "tip of branch" */
5740 tips_tail
= &commit_list_insert(iter
->item
,
5745 * Third phase: output the todo list. This is a bit tricky, as we
5746 * want to avoid jumping back and forth between revisions. To
5747 * accomplish that goal, we walk backwards from the branch tips,
5748 * gathering commits not yet shown, reversing the list on the fly,
5749 * then outputting that list (labeling revisions as needed).
5751 strbuf_addf(out
, "%s onto\n", cmd_label
);
5752 for (iter
= tips
; iter
; iter
= iter
->next
) {
5753 struct commit_list
*list
= NULL
, *iter2
;
5755 commit
= iter
->item
;
5756 if (oidset_contains(&shown
, &commit
->object
.oid
))
5758 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5761 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5763 strbuf_addch(out
, '\n');
5765 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5766 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5767 commit_list_insert(commit
, &list
);
5768 if (!commit
->parents
) {
5772 commit
= commit
->parents
->item
;
5776 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5777 rebase_cousins
|| root_with_onto
?
5778 "onto" : "[new root]");
5780 const char *to
= NULL
;
5782 entry
= oidmap_get(&state
.commit2label
,
5783 &commit
->object
.oid
);
5786 else if (!rebase_cousins
)
5787 to
= label_oid(&commit
->object
.oid
, NULL
,
5790 if (!to
|| !strcmp(to
, "onto"))
5791 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5793 strbuf_reset(&oneline
);
5794 pretty_print_commit(pp
, commit
, &oneline
);
5795 strbuf_addf(out
, "%s %s # %s\n",
5796 cmd_reset
, to
, oneline
.buf
);
5800 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5801 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5802 entry
= oidmap_get(&commit2todo
, oid
);
5803 /* only show if not already upstream */
5805 strbuf_addf(out
, "%s\n", entry
->string
);
5806 entry
= oidmap_get(&state
.commit2label
, oid
);
5808 strbuf_addf(out
, "%s %s\n",
5809 cmd_label
, entry
->string
);
5810 oidset_insert(&shown
, oid
);
5813 free_commit_list(list
);
5816 free_commit_list(commits
);
5817 free_commit_list(tips
);
5819 strbuf_release(&label
);
5820 strbuf_release(&oneline
);
5821 strbuf_release(&buf
);
5823 oidmap_free(&commit2todo
, 1);
5824 oidmap_free(&state
.commit2label
, 1);
5825 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5826 strbuf_release(&state
.buf
);
5831 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5832 const char **argv
, unsigned flags
)
5834 char *format
= NULL
;
5835 struct pretty_print_context pp
= {0};
5836 struct rev_info revs
;
5837 struct commit
*commit
;
5838 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5839 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5840 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5841 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5842 int skipped_commit
= 0;
5845 repo_init_revisions(r
, &revs
, NULL
);
5846 revs
.verbose_header
= 1;
5848 revs
.max_parents
= 1;
5849 revs
.cherry_mark
= !reapply_cherry_picks
;
5852 revs
.right_only
= 1;
5853 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5854 revs
.topo_order
= 1;
5856 revs
.pretty_given
= 1;
5857 git_config_get_string("rebase.instructionFormat", &format
);
5858 if (!format
|| !*format
) {
5860 format
= xstrdup("%s");
5862 get_commit_format(format
, &revs
);
5864 pp
.fmt
= revs
.commit_format
;
5865 pp
.output_encoding
= get_log_output_encoding();
5867 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5868 ret
= error(_("make_script: unhandled options"));
5872 if (prepare_revision_walk(&revs
) < 0) {
5873 ret
= error(_("make_script: error preparing revisions"));
5877 if (rebase_merges
) {
5878 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5882 while ((commit
= get_revision(&revs
))) {
5883 int is_empty
= is_original_commit_empty(commit
);
5885 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5886 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5887 warning(_("skipped previously applied commit %s"),
5888 short_commit_name(r
, commit
));
5892 if (is_empty
&& !keep_empty
)
5894 strbuf_addf(out
, "%s %s ", insn
,
5895 oid_to_hex(&commit
->object
.oid
));
5896 pretty_print_commit(&pp
, commit
, out
);
5898 strbuf_addf(out
, " %c empty", comment_line_char
);
5899 strbuf_addch(out
, '\n');
5902 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5903 _("use --reapply-cherry-picks to include skipped commits"));
5905 release_revisions(&revs
);
5910 * Add commands after pick and (series of) squash/fixup commands
5913 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5914 struct string_list
*commands
)
5916 struct strbuf
*buf
= &todo_list
->buf
;
5917 size_t base_offset
= buf
->len
;
5918 int i
, insert
, nr
= 0, alloc
= 0;
5919 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5921 CALLOC_ARRAY(base_items
, commands
->nr
);
5922 for (i
= 0; i
< commands
->nr
; i
++) {
5923 size_t command_len
= strlen(commands
->items
[i
].string
);
5925 strbuf_addstr(buf
, commands
->items
[i
].string
);
5926 strbuf_addch(buf
, '\n');
5928 base_items
[i
].command
= TODO_EXEC
;
5929 base_items
[i
].offset_in_buf
= base_offset
;
5930 base_items
[i
].arg_offset
= base_offset
;
5931 base_items
[i
].arg_len
= command_len
;
5933 base_offset
+= command_len
+ 1;
5937 * Insert <commands> after every pick. Here, fixup/squash chains
5938 * are considered part of the pick, so we insert the commands *after*
5939 * those chains if there are any.
5941 * As we insert the exec commands immediately after rearranging
5942 * any fixups and before the user edits the list, a fixup chain
5943 * can never contain comments (any comments are empty picks that
5944 * have been commented out because the user did not specify
5945 * --keep-empty). So, it is safe to insert an exec command
5946 * without looking at the command following a comment.
5949 for (i
= 0; i
< todo_list
->nr
; i
++) {
5950 enum todo_command command
= todo_list
->items
[i
].command
;
5951 if (insert
&& !is_fixup(command
)) {
5952 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5953 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5959 ALLOC_GROW(items
, nr
+ 1, alloc
);
5960 items
[nr
++] = todo_list
->items
[i
];
5962 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5966 /* insert or append final <commands> */
5968 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5969 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5974 FREE_AND_NULL(todo_list
->items
);
5975 todo_list
->items
= items
;
5977 todo_list
->alloc
= alloc
;
5980 static void todo_list_to_strbuf(struct repository
*r
,
5981 struct todo_list
*todo_list
,
5982 struct strbuf
*buf
, int num
, unsigned flags
)
5984 struct todo_item
*item
;
5985 int i
, max
= todo_list
->nr
;
5987 if (num
> 0 && num
< max
)
5990 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5993 /* if the item is not a command write it and continue */
5994 if (item
->command
>= TODO_COMMENT
) {
5995 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5996 todo_item_get_arg(todo_list
, item
));
6000 /* add command to the buffer */
6001 cmd
= command_to_char(item
->command
);
6002 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
6003 strbuf_addch(buf
, cmd
);
6005 strbuf_addstr(buf
, command_to_string(item
->command
));
6009 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
6010 short_commit_name(r
, item
->commit
) :
6011 oid_to_hex(&item
->commit
->object
.oid
);
6013 if (item
->command
== TODO_FIXUP
) {
6014 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
6015 strbuf_addstr(buf
, " -c");
6016 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
6017 strbuf_addstr(buf
, " -C");
6021 if (item
->command
== TODO_MERGE
) {
6022 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
6023 strbuf_addstr(buf
, " -c");
6025 strbuf_addstr(buf
, " -C");
6028 strbuf_addf(buf
, " %s", oid
);
6031 /* add all the rest */
6033 strbuf_addch(buf
, '\n');
6035 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
6036 todo_item_get_arg(todo_list
, item
));
6040 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
6041 const char *file
, const char *shortrevisions
,
6042 const char *shortonto
, int num
, unsigned flags
)
6045 struct strbuf buf
= STRBUF_INIT
;
6047 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
6048 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
6049 append_todo_help(count_commands(todo_list
),
6050 shortrevisions
, shortonto
, &buf
);
6052 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
6053 strbuf_release(&buf
);
6058 /* skip picking commits whose parents are unchanged */
6059 static int skip_unnecessary_picks(struct repository
*r
,
6060 struct todo_list
*todo_list
,
6061 struct object_id
*base_oid
)
6063 struct object_id
*parent_oid
;
6066 for (i
= 0; i
< todo_list
->nr
; i
++) {
6067 struct todo_item
*item
= todo_list
->items
+ i
;
6069 if (item
->command
>= TODO_NOOP
)
6071 if (item
->command
!= TODO_PICK
)
6073 if (repo_parse_commit(r
, item
->commit
)) {
6074 return error(_("could not parse commit '%s'"),
6075 oid_to_hex(&item
->commit
->object
.oid
));
6077 if (!item
->commit
->parents
)
6078 break; /* root commit */
6079 if (item
->commit
->parents
->next
)
6080 break; /* merge commit */
6081 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
6082 if (!oideq(parent_oid
, base_oid
))
6084 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6087 const char *done_path
= rebase_path_done();
6089 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6090 error_errno(_("could not write to '%s'"), done_path
);
6094 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6096 todo_list
->current
= 0;
6097 todo_list
->done_nr
+= i
;
6099 if (is_fixup(peek_command(todo_list
, 0)))
6100 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6106 struct todo_add_branch_context
{
6107 struct todo_item
*items
;
6111 struct commit
*commit
;
6112 struct string_list refs_to_oids
;
6115 static int add_decorations_to_list(const struct commit
*commit
,
6116 struct todo_add_branch_context
*ctx
)
6118 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6119 const char *head_ref
= resolve_ref_unsafe("HEAD",
6120 RESOLVE_REF_READING
,
6124 while (decoration
) {
6125 struct todo_item
*item
;
6127 size_t base_offset
= ctx
->buf
->len
;
6130 * If the branch is the current HEAD, then it will be
6131 * updated by the default rebase behavior.
6133 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6134 decoration
= decoration
->next
;
6138 ALLOC_GROW(ctx
->items
,
6141 item
= &ctx
->items
[ctx
->items_nr
];
6142 memset(item
, 0, sizeof(*item
));
6144 /* If the branch is checked out, then leave a comment instead. */
6145 if ((path
= branch_checked_out(decoration
->name
))) {
6146 item
->command
= TODO_COMMENT
;
6147 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6148 decoration
->name
, path
);
6150 struct string_list_item
*sti
;
6151 item
->command
= TODO_UPDATE_REF
;
6152 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6154 sti
= string_list_insert(&ctx
->refs_to_oids
,
6156 sti
->util
= init_update_ref_record(decoration
->name
);
6159 item
->offset_in_buf
= base_offset
;
6160 item
->arg_offset
= base_offset
;
6161 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6164 decoration
= decoration
->next
;
6171 * For each 'pick' command, find out if the commit has a decoration in
6172 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6174 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6177 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6178 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6179 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6180 struct decoration_filter decoration_filter
= {
6181 .include_ref_pattern
= &decorate_refs_include
,
6182 .exclude_ref_pattern
= &decorate_refs_exclude
,
6183 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6185 struct todo_add_branch_context ctx
= {
6186 .buf
= &todo_list
->buf
,
6187 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6190 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6191 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6193 string_list_append(&decorate_refs_include
, "refs/heads/");
6194 load_ref_decorations(&decoration_filter
, 0);
6196 for (i
= 0; i
< todo_list
->nr
; ) {
6197 struct todo_item
*item
= &todo_list
->items
[i
];
6199 /* insert ith item into new list */
6200 ALLOC_GROW(ctx
.items
,
6204 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6207 ctx
.commit
= item
->commit
;
6208 add_decorations_to_list(item
->commit
, &ctx
);
6212 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6214 string_list_clear(&ctx
.refs_to_oids
, 1);
6217 /* we failed, so clean up the new list. */
6222 free(todo_list
->items
);
6223 todo_list
->items
= ctx
.items
;
6224 todo_list
->nr
= ctx
.items_nr
;
6225 todo_list
->alloc
= ctx
.items_alloc
;
6230 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6231 const char *shortrevisions
, const char *onto_name
,
6232 struct commit
*onto
, const struct object_id
*orig_head
,
6233 struct string_list
*commands
, unsigned autosquash
,
6234 unsigned update_refs
,
6235 struct todo_list
*todo_list
)
6237 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6238 const char *todo_file
= rebase_path_todo();
6239 struct todo_list new_todo
= TODO_LIST_INIT
;
6240 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6241 struct object_id oid
= onto
->object
.oid
;
6244 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6247 if (buf
->len
== 0) {
6248 struct todo_item
*item
= append_new_todo(todo_list
);
6249 item
->command
= TODO_NOOP
;
6250 item
->commit
= NULL
;
6251 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6254 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6257 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6261 todo_list_add_exec_commands(todo_list
, commands
);
6263 if (count_commands(todo_list
) == 0) {
6264 apply_autostash(rebase_path_autostash());
6265 sequencer_remove_state(opts
);
6267 return error(_("nothing to do"));
6270 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6274 else if (res
== -2) {
6275 apply_autostash(rebase_path_autostash());
6276 sequencer_remove_state(opts
);
6279 } else if (res
== -3) {
6280 apply_autostash(rebase_path_autostash());
6281 sequencer_remove_state(opts
);
6282 todo_list_release(&new_todo
);
6284 return error(_("nothing to do"));
6285 } else if (res
== -4) {
6286 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6287 todo_list_release(&new_todo
);
6292 /* Expand the commit IDs */
6293 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6294 strbuf_swap(&new_todo
.buf
, &buf2
);
6295 strbuf_release(&buf2
);
6296 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6297 new_todo
.total_nr
= 0;
6298 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6299 BUG("invalid todo list after expanding IDs:\n%s",
6302 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6303 todo_list_release(&new_todo
);
6304 return error(_("could not skip unnecessary pick commands"));
6307 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6308 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6309 todo_list_release(&new_todo
);
6310 return error_errno(_("could not write '%s'"), todo_file
);
6315 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6318 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6321 todo_list_write_total_nr(&new_todo
);
6322 res
= pick_commits(r
, &new_todo
, opts
);
6325 todo_list_release(&new_todo
);
6330 struct subject2item_entry
{
6331 struct hashmap_entry entry
;
6333 char subject
[FLEX_ARRAY
];
6336 static int subject2item_cmp(const void *fndata UNUSED
,
6337 const struct hashmap_entry
*eptr
,
6338 const struct hashmap_entry
*entry_or_key
,
6341 const struct subject2item_entry
*a
, *b
;
6343 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6344 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6346 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6349 define_commit_slab(commit_todo_item
, struct todo_item
*);
6351 static int skip_fixupish(const char *subject
, const char **p
) {
6352 return skip_prefix(subject
, "fixup! ", p
) ||
6353 skip_prefix(subject
, "amend! ", p
) ||
6354 skip_prefix(subject
, "squash! ", p
);
6358 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6359 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6360 * after the former, and change "pick" to "fixup"/"squash".
6362 * Note that if the config has specified a custom instruction format, each log
6363 * message will have to be retrieved from the commit (as the oneline in the
6364 * script cannot be trusted) in order to normalize the autosquash arrangement.
6366 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6368 struct hashmap subject2item
;
6369 int rearranged
= 0, *next
, *tail
, i
, nr
= 0;
6371 struct commit_todo_item commit_todo
;
6372 struct todo_item
*items
= NULL
;
6374 init_commit_todo_item(&commit_todo
);
6376 * The hashmap maps onelines to the respective todo list index.
6378 * If any items need to be rearranged, the next[i] value will indicate
6379 * which item was moved directly after the i'th.
6381 * In that case, last[i] will indicate the index of the latest item to
6382 * be moved to appear after the i'th.
6384 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6385 ALLOC_ARRAY(next
, todo_list
->nr
);
6386 ALLOC_ARRAY(tail
, todo_list
->nr
);
6387 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6388 for (i
= 0; i
< todo_list
->nr
; i
++) {
6389 struct strbuf buf
= STRBUF_INIT
;
6390 struct todo_item
*item
= todo_list
->items
+ i
;
6391 const char *commit_buffer
, *subject
, *p
;
6394 struct subject2item_entry
*entry
;
6396 next
[i
] = tail
[i
] = -1;
6397 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6402 if (is_fixup(item
->command
)) {
6403 clear_commit_todo_item(&commit_todo
);
6404 return error(_("the script was already rearranged."));
6407 repo_parse_commit(the_repository
, item
->commit
);
6408 commit_buffer
= repo_logmsg_reencode(the_repository
,
6411 find_commit_subject(commit_buffer
, &subject
);
6412 format_subject(&buf
, subject
, " ");
6413 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6414 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6416 if (skip_fixupish(subject
, &p
)) {
6417 struct commit
*commit2
;
6422 if (!skip_fixupish(p
, &p
))
6426 entry
= hashmap_get_entry_from_hash(&subject2item
,
6428 struct subject2item_entry
,
6431 /* found by title */
6433 else if (!strchr(p
, ' ') &&
6435 lookup_commit_reference_by_name(p
)) &&
6436 *commit_todo_item_at(&commit_todo
, commit2
))
6437 /* found by commit name */
6438 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6441 /* copy can be a prefix of the commit subject */
6442 for (i2
= 0; i2
< i
; i2
++)
6444 starts_with(subjects
[i2
], p
))
6452 if (starts_with(subject
, "fixup!")) {
6453 todo_list
->items
[i
].command
= TODO_FIXUP
;
6454 } else if (starts_with(subject
, "amend!")) {
6455 todo_list
->items
[i
].command
= TODO_FIXUP
;
6456 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6458 todo_list
->items
[i
].command
= TODO_SQUASH
;
6464 next
[i
] = next
[tail
[i2
]];
6468 } else if (!hashmap_get_from_hash(&subject2item
,
6469 strhash(subject
), subject
)) {
6470 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6472 hashmap_entry_init(&entry
->entry
,
6473 strhash(entry
->subject
));
6474 hashmap_put(&subject2item
, &entry
->entry
);
6477 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6481 ALLOC_ARRAY(items
, todo_list
->nr
);
6483 for (i
= 0; i
< todo_list
->nr
; i
++) {
6484 enum todo_command command
= todo_list
->items
[i
].command
;
6488 * Initially, all commands are 'pick's. If it is a
6489 * fixup or a squash now, we have rearranged it.
6491 if (is_fixup(command
))
6495 items
[nr
++] = todo_list
->items
[cur
];
6500 assert(nr
== todo_list
->nr
);
6501 todo_list
->alloc
= nr
;
6502 FREE_AND_NULL(todo_list
->items
);
6503 todo_list
->items
= items
;
6508 for (i
= 0; i
< todo_list
->nr
; i
++)
6511 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6513 clear_commit_todo_item(&commit_todo
);
6518 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6520 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6521 struct object_id cherry_pick_head
, rebase_head
;
6523 if (file_exists(git_path_seq_dir()))
6524 *whence
= FROM_CHERRY_PICK_MULTI
;
6525 if (file_exists(rebase_path()) &&
6526 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6527 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6528 oideq(&rebase_head
, &cherry_pick_head
))
6529 *whence
= FROM_REBASE_PICK
;
6531 *whence
= FROM_CHERRY_PICK_SINGLE
;
6539 int sequencer_get_update_refs_state(const char *wt_dir
,
6540 struct string_list
*refs
)
6544 struct strbuf ref
= STRBUF_INIT
;
6545 struct strbuf hash
= STRBUF_INIT
;
6546 struct update_ref_record
*rec
= NULL
;
6548 char *path
= rebase_path_update_refs(wt_dir
);
6550 fp
= fopen(path
, "r");
6554 while (strbuf_getline(&ref
, fp
) != EOF
) {
6555 struct string_list_item
*item
;
6557 CALLOC_ARRAY(rec
, 1);
6559 if (strbuf_getline(&hash
, fp
) == EOF
||
6560 get_oid_hex(hash
.buf
, &rec
->before
)) {
6561 warning(_("update-refs file at '%s' is invalid"),
6567 if (strbuf_getline(&hash
, fp
) == EOF
||
6568 get_oid_hex(hash
.buf
, &rec
->after
)) {
6569 warning(_("update-refs file at '%s' is invalid"),
6575 item
= string_list_insert(refs
, ref
.buf
);
6585 strbuf_release(&ref
);
6586 strbuf_release(&hash
);