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");
470 advise_if_enabled(ADVICE_MERGE_CONFLICT
, "%s", msg
);
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_if_enabled(ADVICE_MERGE_CONFLICT
,
484 _("after resolving the conflicts, mark the corrected paths\n"
485 "with 'git add <paths>' or 'git rm <paths>'"));
486 else if (opts
->action
== REPLAY_PICK
)
487 advise_if_enabled(ADVICE_MERGE_CONFLICT
,
488 _("After resolving the conflicts, mark them with\n"
489 "\"git add/rm <pathspec>\", then run\n"
490 "\"git cherry-pick --continue\".\n"
491 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
492 "To abort and get back to the state before \"git cherry-pick\",\n"
493 "run \"git cherry-pick --abort\"."));
494 else if (opts
->action
== REPLAY_REVERT
)
495 advise_if_enabled(ADVICE_MERGE_CONFLICT
,
496 _("After resolving the conflicts, mark them with\n"
497 "\"git add/rm <pathspec>\", then run\n"
498 "\"git revert --continue\".\n"
499 "You can instead skip this commit with \"git revert --skip\".\n"
500 "To abort and get back to the state before \"git revert\",\n"
501 "run \"git revert --abort\"."));
503 BUG("unexpected pick action in print_advice()");
507 static int write_message(const void *buf
, size_t len
, const char *filename
,
510 struct lock_file msg_file
= LOCK_INIT
;
512 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
514 return error_errno(_("could not lock '%s'"), filename
);
515 if (write_in_full(msg_fd
, buf
, len
) < 0) {
516 error_errno(_("could not write to '%s'"), filename
);
517 rollback_lock_file(&msg_file
);
520 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
521 error_errno(_("could not write eol to '%s'"), filename
);
522 rollback_lock_file(&msg_file
);
525 if (commit_lock_file(&msg_file
) < 0)
526 return error(_("failed to finalize '%s'"), filename
);
531 int read_oneliner(struct strbuf
*buf
,
532 const char *path
, unsigned flags
)
534 int orig_len
= buf
->len
;
536 if (strbuf_read_file(buf
, path
, 0) < 0) {
537 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
538 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
539 warning_errno(_("could not read '%s'"), path
);
543 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
544 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
546 buf
->buf
[buf
->len
] = '\0';
549 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
555 static struct tree
*empty_tree(struct repository
*r
)
557 return lookup_tree(r
, the_hash_algo
->empty_tree
);
560 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
562 if (repo_read_index_unmerged(repo
))
563 return error_resolve_conflict(action_name(opts
));
565 error(_("your local changes would be overwritten by %s."),
566 _(action_name(opts
)));
568 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
569 advise(_("commit your changes or stash them to proceed."));
573 static void update_abort_safety_file(void)
575 struct object_id head
;
577 /* Do nothing on a single-pick */
578 if (!file_exists(git_path_seq_dir()))
581 if (!repo_get_oid(the_repository
, "HEAD", &head
))
582 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
584 write_file(git_path_abort_safety_file(), "%s", "");
587 static int fast_forward_to(struct repository
*r
,
588 const struct object_id
*to
,
589 const struct object_id
*from
,
591 struct replay_opts
*opts
)
593 struct ref_transaction
*transaction
;
594 struct strbuf sb
= STRBUF_INIT
;
595 struct strbuf err
= STRBUF_INIT
;
598 if (checkout_fast_forward(r
, from
, to
, 1))
599 return -1; /* the callee should have complained already */
601 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
603 transaction
= ref_transaction_begin(&err
);
605 ref_transaction_update(transaction
, "HEAD",
606 to
, unborn
&& !is_rebase_i(opts
) ?
609 ref_transaction_commit(transaction
, &err
)) {
610 ref_transaction_free(transaction
);
611 error("%s", err
.buf
);
613 strbuf_release(&err
);
618 strbuf_release(&err
);
619 ref_transaction_free(transaction
);
620 update_abort_safety_file();
624 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
627 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
628 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
629 COMMIT_MSG_CLEANUP_SPACE
;
630 else if (!strcmp(cleanup_arg
, "verbatim"))
631 return COMMIT_MSG_CLEANUP_NONE
;
632 else if (!strcmp(cleanup_arg
, "whitespace"))
633 return COMMIT_MSG_CLEANUP_SPACE
;
634 else if (!strcmp(cleanup_arg
, "strip"))
635 return COMMIT_MSG_CLEANUP_ALL
;
636 else if (!strcmp(cleanup_arg
, "scissors"))
637 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
638 COMMIT_MSG_CLEANUP_SPACE
;
640 die(_("Invalid cleanup mode %s"), cleanup_arg
);
644 * NB using int rather than enum cleanup_mode to stop clang's
645 * -Wtautological-constant-out-of-range-compare complaining that the comparison
648 static const char *describe_cleanup_mode(int cleanup_mode
)
650 static const char *modes
[] = { "whitespace",
655 if (cleanup_mode
< ARRAY_SIZE(modes
))
656 return modes
[cleanup_mode
];
658 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
661 void append_conflicts_hint(struct index_state
*istate
,
662 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
666 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
667 strbuf_addch(msgbuf
, '\n');
668 wt_status_append_cut_line(msgbuf
);
669 strbuf_addch(msgbuf
, comment_line_char
);
672 strbuf_addch(msgbuf
, '\n');
673 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
674 for (i
= 0; i
< istate
->cache_nr
;) {
675 const struct cache_entry
*ce
= istate
->cache
[i
++];
677 strbuf_commented_addf(msgbuf
, comment_line_char
,
679 while (i
< istate
->cache_nr
&&
680 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
686 static int do_recursive_merge(struct repository
*r
,
687 struct commit
*base
, struct commit
*next
,
688 const char *base_label
, const char *next_label
,
689 struct object_id
*head
, struct strbuf
*msgbuf
,
690 struct replay_opts
*opts
)
692 struct merge_options o
;
693 struct merge_result result
;
694 struct tree
*next_tree
, *base_tree
, *head_tree
;
695 int clean
, show_output
;
697 struct lock_file index_lock
= LOCK_INIT
;
699 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
704 init_merge_options(&o
, r
);
705 o
.ancestor
= base
? base_label
: "(empty tree)";
707 o
.branch2
= next
? next_label
: "(empty tree)";
708 if (is_rebase_i(opts
))
710 o
.show_rename_progress
= 1;
712 head_tree
= parse_tree_indirect(head
);
714 return error(_("unable to read tree (%s)"), oid_to_hex(head
));
715 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
716 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
718 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
719 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
721 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
722 memset(&result
, 0, sizeof(result
));
723 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
725 show_output
= !is_rebase_i(opts
) || !result
.clean
;
727 * TODO: merge_switch_to_result will update index/working tree;
728 * we only really want to do that if !result.clean || this is
729 * the final patch to be picked. But determining this is the
730 * final patch would take some work, and "head_tree" would need
731 * to be replace with the tree the index matched before we
732 * started doing any picks.
734 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
735 clean
= result
.clean
;
737 ensure_full_index(r
->index
);
738 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
739 if (is_rebase_i(opts
) && clean
<= 0)
740 fputs(o
.obuf
.buf
, stdout
);
741 strbuf_release(&o
.obuf
);
744 rollback_lock_file(&index_lock
);
748 if (write_locked_index(r
->index
, &index_lock
,
749 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
751 * TRANSLATORS: %s will be "revert", "cherry-pick" or
754 return error(_("%s: Unable to write new index file"),
755 _(action_name(opts
)));
758 append_conflicts_hint(r
->index
, msgbuf
,
759 opts
->default_msg_cleanup
);
764 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
766 if (!cache_tree_fully_valid(istate
->cache_tree
))
767 if (cache_tree_update(istate
, 0)) {
768 error(_("unable to update cache tree"));
772 return &istate
->cache_tree
->oid
;
775 static int is_index_unchanged(struct repository
*r
)
777 struct object_id head_oid
, *cache_tree_oid
;
778 struct commit
*head_commit
;
779 struct index_state
*istate
= r
->index
;
781 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
782 return error(_("could not resolve HEAD commit"));
784 head_commit
= lookup_commit(r
, &head_oid
);
787 * If head_commit is NULL, check_commit, called from
788 * lookup_commit, would have indicated that head_commit is not
789 * a commit object already. repo_parse_commit() will return failure
790 * without further complaints in such a case. Otherwise, if
791 * the commit is invalid, repo_parse_commit() will complain. So
792 * there is nothing for us to say here. Just return failure.
794 if (repo_parse_commit(r
, head_commit
))
797 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
800 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
803 static int write_author_script(const char *message
)
805 struct strbuf buf
= STRBUF_INIT
;
810 if (!*message
|| starts_with(message
, "\n")) {
812 /* Missing 'author' line? */
813 unlink(rebase_path_author_script());
815 } else if (skip_prefix(message
, "author ", &message
))
817 else if ((eol
= strchr(message
, '\n')))
822 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
823 while (*message
&& *message
!= '\n' && *message
!= '\r')
824 if (skip_prefix(message
, " <", &message
))
826 else if (*message
!= '\'')
827 strbuf_addch(&buf
, *(message
++));
829 strbuf_addf(&buf
, "'\\%c'", *(message
++));
830 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
831 while (*message
&& *message
!= '\n' && *message
!= '\r')
832 if (skip_prefix(message
, "> ", &message
))
834 else if (*message
!= '\'')
835 strbuf_addch(&buf
, *(message
++));
837 strbuf_addf(&buf
, "'\\%c'", *(message
++));
838 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
839 while (*message
&& *message
!= '\n' && *message
!= '\r')
840 if (*message
!= '\'')
841 strbuf_addch(&buf
, *(message
++));
843 strbuf_addf(&buf
, "'\\%c'", *(message
++));
844 strbuf_addch(&buf
, '\'');
845 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
846 strbuf_release(&buf
);
851 * Take a series of KEY='VALUE' lines where VALUE part is
852 * sq-quoted, and append <KEY, VALUE> at the end of the string list
854 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
857 struct string_list_item
*item
;
859 char *cp
= strchr(buf
, '=');
861 np
= strchrnul(buf
, '\n');
862 return error(_("no key present in '%.*s'"),
863 (int) (np
- buf
), buf
);
865 np
= strchrnul(cp
, '\n');
867 item
= string_list_append(list
, buf
);
869 buf
= np
+ (*np
== '\n');
873 return error(_("unable to dequote value of '%s'"),
875 item
->util
= xstrdup(cp
);
881 * Reads and parses the state directory's "author-script" file, and sets name,
882 * email and date accordingly.
883 * Returns 0 on success, -1 if the file could not be parsed.
885 * The author script is of the format:
887 * GIT_AUTHOR_NAME='$author_name'
888 * GIT_AUTHOR_EMAIL='$author_email'
889 * GIT_AUTHOR_DATE='$author_date'
891 * where $author_name, $author_email and $author_date are quoted. We are strict
892 * with our parsing, as the file was meant to be eval'd in the now-removed
893 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
894 * from what this function expects, it is better to bail out than to do
895 * something that the user does not expect.
897 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
900 struct strbuf buf
= STRBUF_INIT
;
901 struct string_list kv
= STRING_LIST_INIT_DUP
;
902 int retval
= -1; /* assume failure */
903 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
905 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
906 strbuf_release(&buf
);
907 if (errno
== ENOENT
&& allow_missing
)
910 return error_errno(_("could not open '%s' for reading"),
914 if (parse_key_value_squoted(buf
.buf
, &kv
))
917 for (i
= 0; i
< kv
.nr
; i
++) {
918 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
920 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
923 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
925 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
928 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
930 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
934 err
= error(_("unknown variable '%s'"),
939 error(_("missing 'GIT_AUTHOR_NAME'"));
941 error(_("missing 'GIT_AUTHOR_EMAIL'"));
943 error(_("missing 'GIT_AUTHOR_DATE'"));
944 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
946 *name
= kv
.items
[name_i
].util
;
947 *email
= kv
.items
[email_i
].util
;
948 *date
= kv
.items
[date_i
].util
;
951 string_list_clear(&kv
, !!retval
);
952 strbuf_release(&buf
);
957 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
958 * file with shell quoting into struct strvec. Returns -1 on
959 * error, 0 otherwise.
961 static int read_env_script(struct strvec
*env
)
963 char *name
, *email
, *date
;
965 if (read_author_script(rebase_path_author_script(),
966 &name
, &email
, &date
, 0))
969 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
970 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
971 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
979 static char *get_author(const char *message
)
984 a
= find_commit_header(message
, "author", &len
);
986 return xmemdupz(a
, len
);
991 static const char *author_date_from_env(const struct strvec
*env
)
996 for (i
= 0; i
< env
->nr
; i
++)
997 if (skip_prefix(env
->v
[i
],
998 "GIT_AUTHOR_DATE=", &date
))
1001 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1002 * reading the script
1004 BUG("GIT_AUTHOR_DATE missing from author script");
1007 static const char staged_changes_advice
[] =
1008 N_("you have staged changes in your working tree\n"
1009 "If these changes are meant to be squashed into the previous commit, run:\n"
1011 " git commit --amend %s\n"
1013 "If they are meant to go into a new commit, run:\n"
1017 "In both cases, once you're done, continue with:\n"
1019 " git rebase --continue\n");
1021 #define ALLOW_EMPTY (1<<0)
1022 #define EDIT_MSG (1<<1)
1023 #define AMEND_MSG (1<<2)
1024 #define CLEANUP_MSG (1<<3)
1025 #define VERIFY_MSG (1<<4)
1026 #define CREATE_ROOT_COMMIT (1<<5)
1027 #define VERBATIM_MSG (1<<6)
1029 static int run_command_silent_on_success(struct child_process
*cmd
)
1031 struct strbuf buf
= STRBUF_INIT
;
1034 cmd
->stdout_to_stderr
= 1;
1035 rc
= pipe_command(cmd
,
1041 fputs(buf
.buf
, stderr
);
1042 strbuf_release(&buf
);
1047 * If we are cherry-pick, and if the merge did not result in
1048 * hand-editing, we will hit this commit and inherit the original
1049 * author date and name.
1051 * If we are revert, or if our cherry-pick results in a hand merge,
1052 * we had better say that the current user is responsible for that.
1054 * An exception is when run_git_commit() is called during an
1055 * interactive rebase: in that case, we will want to retain the
1058 static int run_git_commit(const char *defmsg
,
1059 struct replay_opts
*opts
,
1062 struct child_process cmd
= CHILD_PROCESS_INIT
;
1064 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1065 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1069 if (is_rebase_i(opts
) &&
1070 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1071 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1072 read_env_script(&cmd
.env
)) {
1073 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1075 return error(_(staged_changes_advice
),
1079 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1081 if (opts
->committer_date_is_author_date
)
1082 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1085 author_date_from_env(&cmd
.env
));
1086 if (opts
->ignore_date
)
1087 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1089 strvec_push(&cmd
.args
, "commit");
1091 if (!(flags
& VERIFY_MSG
))
1092 strvec_push(&cmd
.args
, "-n");
1093 if ((flags
& AMEND_MSG
))
1094 strvec_push(&cmd
.args
, "--amend");
1096 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1098 strvec_push(&cmd
.args
, "--no-gpg-sign");
1100 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1101 else if (!(flags
& EDIT_MSG
))
1102 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1103 if ((flags
& CLEANUP_MSG
))
1104 strvec_push(&cmd
.args
, "--cleanup=strip");
1105 if ((flags
& VERBATIM_MSG
))
1106 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1107 if ((flags
& EDIT_MSG
))
1108 strvec_push(&cmd
.args
, "-e");
1109 else if (!(flags
& CLEANUP_MSG
) &&
1110 !opts
->signoff
&& !opts
->record_origin
&&
1111 !opts
->explicit_cleanup
)
1112 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1114 if ((flags
& ALLOW_EMPTY
))
1115 strvec_push(&cmd
.args
, "--allow-empty");
1117 if (!(flags
& EDIT_MSG
))
1118 strvec_push(&cmd
.args
, "--allow-empty-message");
1120 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1121 return run_command_silent_on_success(&cmd
);
1123 return run_command(&cmd
);
1126 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1131 /* Check if the rest is just whitespace and Signed-off-by's. */
1132 for (i
= start
; i
< sb
->len
; i
++) {
1133 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1139 if (strlen(sign_off_header
) <= eol
- i
&&
1140 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1145 if (!isspace(sb
->buf
[i
++]))
1152 void cleanup_message(struct strbuf
*msgbuf
,
1153 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1155 if (verbose
|| /* Truncate the message just before the diff, if any. */
1156 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1157 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1158 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1159 strbuf_stripspace(msgbuf
,
1160 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1164 * Find out if the message in the strbuf contains only whitespace and
1165 * Signed-off-by lines.
1167 int message_is_empty(const struct strbuf
*sb
,
1168 enum commit_msg_cleanup_mode cleanup_mode
)
1170 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1172 return rest_is_empty(sb
, 0);
1176 * See if the user edited the message in the editor or left what
1177 * was in the template intact
1179 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1180 enum commit_msg_cleanup_mode cleanup_mode
)
1182 struct strbuf tmpl
= STRBUF_INIT
;
1185 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1188 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1191 strbuf_stripspace(&tmpl
,
1192 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1193 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1195 strbuf_release(&tmpl
);
1196 return rest_is_empty(sb
, start
- sb
->buf
);
1199 int update_head_with_reflog(const struct commit
*old_head
,
1200 const struct object_id
*new_head
,
1201 const char *action
, const struct strbuf
*msg
,
1204 struct ref_transaction
*transaction
;
1205 struct strbuf sb
= STRBUF_INIT
;
1210 strbuf_addstr(&sb
, action
);
1211 strbuf_addstr(&sb
, ": ");
1214 nl
= strchr(msg
->buf
, '\n');
1216 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1218 strbuf_addbuf(&sb
, msg
);
1219 strbuf_addch(&sb
, '\n');
1222 transaction
= ref_transaction_begin(err
);
1224 ref_transaction_update(transaction
, "HEAD", new_head
,
1225 old_head
? &old_head
->object
.oid
: null_oid(),
1227 ref_transaction_commit(transaction
, err
)) {
1230 ref_transaction_free(transaction
);
1231 strbuf_release(&sb
);
1236 static int run_rewrite_hook(const struct object_id
*oldoid
,
1237 const struct object_id
*newoid
)
1239 struct child_process proc
= CHILD_PROCESS_INIT
;
1241 struct strbuf sb
= STRBUF_INIT
;
1242 const char *hook_path
= find_hook("post-rewrite");
1247 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1249 proc
.stdout_to_stderr
= 1;
1250 proc
.trace2_hook_name
= "post-rewrite";
1252 code
= start_command(&proc
);
1255 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1256 sigchain_push(SIGPIPE
, SIG_IGN
);
1257 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1259 strbuf_release(&sb
);
1260 sigchain_pop(SIGPIPE
);
1261 return finish_command(&proc
);
1264 void commit_post_rewrite(struct repository
*r
,
1265 const struct commit
*old_head
,
1266 const struct object_id
*new_head
)
1268 struct notes_rewrite_cfg
*cfg
;
1270 cfg
= init_copy_notes_for_rewrite("amend");
1272 /* we are amending, so old_head is not NULL */
1273 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1274 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1276 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1279 static int run_prepare_commit_msg_hook(struct repository
*r
,
1284 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1286 name
= git_path_commit_editmsg();
1287 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1296 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1298 ret
= error(_("'prepare-commit-msg' hook failed"));
1303 static const char implicit_ident_advice_noconfig
[] =
1304 N_("Your name and email address were configured automatically based\n"
1305 "on your username and hostname. Please check that they are accurate.\n"
1306 "You can suppress this message by setting them explicitly. Run the\n"
1307 "following command and follow the instructions in your editor to edit\n"
1308 "your configuration file:\n"
1310 " git config --global --edit\n"
1312 "After doing this, you may fix the identity used for this commit with:\n"
1314 " git commit --amend --reset-author\n");
1316 static const char implicit_ident_advice_config
[] =
1317 N_("Your name and email address were configured automatically based\n"
1318 "on your username and hostname. Please check that they are accurate.\n"
1319 "You can suppress this message by setting them explicitly:\n"
1321 " git config --global user.name \"Your Name\"\n"
1322 " git config --global user.email you@example.com\n"
1324 "After doing this, you may fix the identity used for this commit with:\n"
1326 " git commit --amend --reset-author\n");
1328 static const char *implicit_ident_advice(void)
1330 char *user_config
= interpolate_path("~/.gitconfig", 0);
1331 char *xdg_config
= xdg_config_home("config");
1332 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1338 return _(implicit_ident_advice_config
);
1340 return _(implicit_ident_advice_noconfig
);
1344 void print_commit_summary(struct repository
*r
,
1346 const struct object_id
*oid
,
1349 struct rev_info rev
;
1350 struct commit
*commit
;
1351 struct strbuf format
= STRBUF_INIT
;
1353 struct pretty_print_context pctx
= {0};
1354 struct strbuf author_ident
= STRBUF_INIT
;
1355 struct strbuf committer_ident
= STRBUF_INIT
;
1356 struct ref_store
*refs
;
1358 commit
= lookup_commit(r
, oid
);
1360 die(_("couldn't look up newly created commit"));
1361 if (repo_parse_commit(r
, commit
))
1362 die(_("could not parse newly created commit"));
1364 strbuf_addstr(&format
, "format:%h] %s");
1366 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1368 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1370 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1371 strbuf_addstr(&format
, "\n Author: ");
1372 strbuf_addbuf_percentquote(&format
, &author_ident
);
1374 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1375 struct strbuf date
= STRBUF_INIT
;
1377 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1378 strbuf_addstr(&format
, "\n Date: ");
1379 strbuf_addbuf_percentquote(&format
, &date
);
1380 strbuf_release(&date
);
1382 if (!committer_ident_sufficiently_given()) {
1383 strbuf_addstr(&format
, "\n Committer: ");
1384 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1385 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1386 strbuf_addch(&format
, '\n');
1387 strbuf_addstr(&format
, implicit_ident_advice());
1390 strbuf_release(&author_ident
);
1391 strbuf_release(&committer_ident
);
1393 repo_init_revisions(r
, &rev
, prefix
);
1394 setup_revisions(0, NULL
, &rev
, NULL
);
1397 rev
.diffopt
.output_format
=
1398 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1400 rev
.verbose_header
= 1;
1401 rev
.show_root_diff
= 1;
1402 get_commit_format(format
.buf
, &rev
);
1403 rev
.always_show_header
= 0;
1404 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1405 diff_setup_done(&rev
.diffopt
);
1407 refs
= get_main_ref_store(r
);
1408 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1410 die(_("unable to resolve HEAD after creating commit"));
1411 if (!strcmp(head
, "HEAD"))
1412 head
= _("detached HEAD");
1414 skip_prefix(head
, "refs/heads/", &head
);
1415 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1416 _(" (root-commit)") : "");
1418 if (!log_tree_commit(&rev
, commit
)) {
1419 rev
.always_show_header
= 1;
1420 rev
.use_terminator
= 1;
1421 log_tree_commit(&rev
, commit
);
1424 release_revisions(&rev
);
1425 strbuf_release(&format
);
1428 static int parse_head(struct repository
*r
, struct commit
**head
)
1430 struct commit
*current_head
;
1431 struct object_id oid
;
1433 if (repo_get_oid(r
, "HEAD", &oid
)) {
1434 current_head
= NULL
;
1436 current_head
= lookup_commit_reference(r
, &oid
);
1438 return error(_("could not parse HEAD"));
1439 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1440 warning(_("HEAD %s is not a commit!"),
1443 if (repo_parse_commit(r
, current_head
))
1444 return error(_("could not parse HEAD commit"));
1446 *head
= current_head
;
1452 * Try to commit without forking 'git commit'. In some cases we need
1453 * to run 'git commit' to display an error message
1456 * -1 - error unable to commit
1458 * 1 - run 'git commit'
1460 static int try_to_commit(struct repository
*r
,
1461 struct strbuf
*msg
, const char *author
,
1462 struct replay_opts
*opts
, unsigned int flags
,
1463 struct object_id
*oid
)
1465 struct object_id tree
;
1466 struct commit
*current_head
= NULL
;
1467 struct commit_list
*parents
= NULL
;
1468 struct commit_extra_header
*extra
= NULL
;
1469 struct strbuf err
= STRBUF_INIT
;
1470 struct strbuf commit_msg
= STRBUF_INIT
;
1471 char *amend_author
= NULL
;
1472 const char *committer
= NULL
;
1473 const char *hook_commit
= NULL
;
1474 enum commit_msg_cleanup_mode cleanup
;
1477 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1478 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1480 if (parse_head(r
, ¤t_head
))
1483 if (flags
& AMEND_MSG
) {
1484 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1485 const char *out_enc
= get_commit_output_encoding();
1486 const char *message
= repo_logmsg_reencode(r
, current_head
,
1490 const char *orig_message
= NULL
;
1492 find_commit_subject(message
, &orig_message
);
1494 strbuf_addstr(msg
, orig_message
);
1495 hook_commit
= "HEAD";
1497 author
= amend_author
= get_author(message
);
1498 repo_unuse_commit_buffer(r
, current_head
,
1501 res
= error(_("unable to parse commit author"));
1504 parents
= copy_commit_list(current_head
->parents
);
1505 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1506 } else if (current_head
&&
1507 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1508 commit_list_insert(current_head
, &parents
);
1511 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1512 res
= error(_("git write-tree failed to write a tree"));
1516 if (!(flags
& ALLOW_EMPTY
)) {
1517 struct commit
*first_parent
= current_head
;
1519 if (flags
& AMEND_MSG
) {
1520 if (current_head
->parents
) {
1521 first_parent
= current_head
->parents
->item
;
1522 if (repo_parse_commit(r
, first_parent
)) {
1523 res
= error(_("could not parse HEAD commit"));
1527 first_parent
= NULL
;
1530 if (oideq(first_parent
1531 ? get_commit_tree_oid(first_parent
)
1532 : the_hash_algo
->empty_tree
,
1534 res
= 1; /* run 'git commit' to display error message */
1539 if (hook_exists("prepare-commit-msg")) {
1540 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1543 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1545 res
= error_errno(_("unable to read commit message "
1547 git_path_commit_editmsg());
1553 if (flags
& CLEANUP_MSG
)
1554 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1555 else if (flags
& VERBATIM_MSG
)
1556 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1557 else if ((opts
->signoff
|| opts
->record_origin
) &&
1558 !opts
->explicit_cleanup
)
1559 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1561 cleanup
= opts
->default_msg_cleanup
;
1563 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1564 strbuf_stripspace(msg
,
1565 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1566 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1567 res
= 1; /* run 'git commit' to display error message */
1571 if (opts
->committer_date_is_author_date
) {
1572 struct ident_split id
;
1573 struct strbuf date
= STRBUF_INIT
;
1575 if (!opts
->ignore_date
) {
1576 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1577 res
= error(_("invalid author identity '%s'"),
1581 if (!id
.date_begin
) {
1583 "corrupt author: missing date information"));
1586 strbuf_addf(&date
, "@%.*s %.*s",
1587 (int)(id
.date_end
- id
.date_begin
),
1589 (int)(id
.tz_end
- id
.tz_begin
),
1594 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1595 getenv("GIT_COMMITTER_EMAIL"),
1596 WANT_COMMITTER_IDENT
,
1597 opts
->ignore_date
? NULL
: date
.buf
,
1599 strbuf_release(&date
);
1604 if (opts
->ignore_date
) {
1605 struct ident_split id
;
1608 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1609 error(_("invalid author identity '%s'"), author
);
1612 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1613 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1614 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1620 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1621 author
, committer
, opts
->gpg_sign
, extra
)) {
1622 res
= error(_("failed to write commit object"));
1626 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1628 res
= error("%s", err
.buf
);
1632 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1633 if (flags
& AMEND_MSG
)
1634 commit_post_rewrite(r
, current_head
, oid
);
1637 free_commit_extra_headers(extra
);
1638 strbuf_release(&err
);
1639 strbuf_release(&commit_msg
);
1645 static int write_rebase_head(struct object_id
*oid
)
1647 if (update_ref("rebase", "REBASE_HEAD", oid
,
1648 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1649 return error(_("could not update %s"), "REBASE_HEAD");
1654 static int do_commit(struct repository
*r
,
1655 const char *msg_file
, const char *author
,
1656 struct replay_opts
*opts
, unsigned int flags
,
1657 struct object_id
*oid
)
1661 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1662 struct object_id oid
;
1663 struct strbuf sb
= STRBUF_INIT
;
1665 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1666 return error_errno(_("unable to read commit message "
1670 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1671 author
, opts
, flags
, &oid
);
1672 strbuf_release(&sb
);
1674 refs_delete_ref(get_main_ref_store(r
), "",
1675 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
);
1676 unlink(git_path_merge_msg(r
));
1677 if (!is_rebase_i(opts
))
1678 print_commit_summary(r
, NULL
, &oid
,
1679 SUMMARY_SHOW_AUTHOR_DATE
);
1684 if (is_rebase_i(opts
) && oid
)
1685 if (write_rebase_head(oid
))
1687 return run_git_commit(msg_file
, opts
, flags
);
1693 static int is_original_commit_empty(struct commit
*commit
)
1695 const struct object_id
*ptree_oid
;
1697 if (repo_parse_commit(the_repository
, commit
))
1698 return error(_("could not parse commit %s"),
1699 oid_to_hex(&commit
->object
.oid
));
1700 if (commit
->parents
) {
1701 struct commit
*parent
= commit
->parents
->item
;
1702 if (repo_parse_commit(the_repository
, parent
))
1703 return error(_("could not parse parent commit %s"),
1704 oid_to_hex(&parent
->object
.oid
));
1705 ptree_oid
= get_commit_tree_oid(parent
);
1707 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1710 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1714 * Should empty commits be allowed? Return status:
1715 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1716 * 0: Halt on empty commit
1717 * 1: Allow empty commit
1718 * 2: Drop empty commit
1720 static int allow_empty(struct repository
*r
,
1721 struct replay_opts
*opts
,
1722 struct commit
*commit
)
1724 int index_unchanged
, originally_empty
;
1729 * (1) we do not allow empty at all and error out.
1731 * (2) we allow ones that were initially empty, and
1732 * just drop the ones that become empty
1734 * (3) we allow ones that were initially empty, but
1735 * halt for the ones that become empty;
1737 * (4) we allow both.
1739 if (!opts
->allow_empty
)
1740 return 0; /* let "git commit" barf as necessary */
1742 index_unchanged
= is_index_unchanged(r
);
1743 if (index_unchanged
< 0)
1744 return index_unchanged
;
1745 if (!index_unchanged
)
1746 return 0; /* we do not have to say --allow-empty */
1748 if (opts
->keep_redundant_commits
)
1751 originally_empty
= is_original_commit_empty(commit
);
1752 if (originally_empty
< 0)
1753 return originally_empty
;
1754 if (originally_empty
)
1756 else if (opts
->drop_redundant_commits
)
1765 } todo_command_info
[] = {
1766 [TODO_PICK
] = { 'p', "pick" },
1767 [TODO_REVERT
] = { 0, "revert" },
1768 [TODO_EDIT
] = { 'e', "edit" },
1769 [TODO_REWORD
] = { 'r', "reword" },
1770 [TODO_FIXUP
] = { 'f', "fixup" },
1771 [TODO_SQUASH
] = { 's', "squash" },
1772 [TODO_EXEC
] = { 'x', "exec" },
1773 [TODO_BREAK
] = { 'b', "break" },
1774 [TODO_LABEL
] = { 'l', "label" },
1775 [TODO_RESET
] = { 't', "reset" },
1776 [TODO_MERGE
] = { 'm', "merge" },
1777 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1778 [TODO_NOOP
] = { 0, "noop" },
1779 [TODO_DROP
] = { 'd', "drop" },
1780 [TODO_COMMENT
] = { 0, NULL
},
1783 static const char *command_to_string(const enum todo_command command
)
1785 if (command
< TODO_COMMENT
)
1786 return todo_command_info
[command
].str
;
1787 die(_("unknown command: %d"), command
);
1790 static char command_to_char(const enum todo_command command
)
1792 if (command
< TODO_COMMENT
)
1793 return todo_command_info
[command
].c
;
1794 return comment_line_char
;
1797 static int is_noop(const enum todo_command command
)
1799 return TODO_NOOP
<= command
;
1802 static int is_fixup(enum todo_command command
)
1804 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1807 /* Does this command create a (non-merge) commit? */
1808 static int is_pick_or_similar(enum todo_command command
)
1823 enum todo_item_flags
{
1824 TODO_EDIT_MERGE_MSG
= (1 << 0),
1825 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1826 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1829 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1830 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1831 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1832 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1833 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1835 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1837 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1838 (flag
& TODO_EDIT_FIXUP_MSG
));
1842 * Wrapper around strbuf_add_commented_lines() which avoids double
1843 * commenting commit subjects.
1845 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1847 const char *s
= str
;
1848 while (len
> 0 && s
[0] == comment_line_char
) {
1850 const char *n
= memchr(s
, '\n', len
);
1855 strbuf_add(buf
, s
, count
);
1859 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1862 /* Does the current fixup chain contain a squash command? */
1863 static int seen_squash(struct replay_opts
*opts
)
1865 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1866 strstr(opts
->current_fixups
.buf
, "\nsquash");
1869 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1871 strbuf_setlen(buf1
, 2);
1872 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1873 strbuf_addch(buf1
, '\n');
1874 strbuf_setlen(buf2
, 2);
1875 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1876 strbuf_addch(buf2
, '\n');
1880 * Comment out any un-commented commit messages, updating the message comments
1881 * to say they will be skipped but do not comment out the empty lines that
1882 * surround commit messages and their comments.
1884 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1886 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1887 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1888 const char *s
, *start
;
1890 size_t orig_msg_len
;
1893 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1894 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1895 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1899 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1901 * Copy the last message, preserving the blank line
1902 * preceding the current line
1904 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1905 copy_lines(msg
, start
, s
- start
- off
);
1907 strbuf_addch(msg
, '\n');
1909 * The next message needs to be commented out but the
1910 * message header is already commented out so just copy
1911 * it and the blank line that follows it.
1913 strbuf_addbuf(msg
, &buf2
);
1915 strbuf_addch(msg
, *next
++);
1917 copy_lines
= add_commented_lines
;
1918 update_comment_bufs(&buf1
, &buf2
, ++i
);
1919 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1920 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1921 copy_lines(msg
, start
, s
- start
- off
);
1924 copy_lines
= strbuf_add
;
1925 update_comment_bufs(&buf1
, &buf2
, ++i
);
1927 s
= strchr(s
, '\n');
1932 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1934 strbuf_release(&buf1
);
1935 strbuf_release(&buf2
);
1938 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1939 enum todo_command command
, struct replay_opts
*opts
,
1942 const char *fixup_msg
;
1943 size_t commented_len
= 0, fixup_off
;
1945 * amend is non-interactive and not normally used with fixup!
1946 * or squash! commits, so only comment out those subjects when
1947 * squashing commit messages.
1949 if (starts_with(body
, "amend!") ||
1950 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1951 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1952 commented_len
= commit_subject_length(body
);
1954 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1955 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1956 ++opts
->current_fixup_count
+ 1);
1957 strbuf_addstr(buf
, "\n\n");
1958 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1959 /* buf->buf may be reallocated so store an offset into the buffer */
1960 fixup_off
= buf
->len
;
1961 strbuf_addstr(buf
, body
+ commented_len
);
1963 /* fixup -C after squash behaves like squash */
1964 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1966 * We're replacing the commit message so we need to
1967 * append the Signed-off-by: trailer if the user
1968 * requested '--signoff'.
1971 append_signoff(buf
, 0, 0);
1973 if ((command
== TODO_FIXUP
) &&
1974 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1975 (file_exists(rebase_path_fixup_msg()) ||
1976 !file_exists(rebase_path_squash_msg()))) {
1977 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1978 if (write_message(fixup_msg
, strlen(fixup_msg
),
1979 rebase_path_fixup_msg(), 0) < 0)
1980 return error(_("cannot write '%s'"),
1981 rebase_path_fixup_msg());
1983 unlink(rebase_path_fixup_msg());
1986 unlink(rebase_path_fixup_msg());
1992 static int update_squash_messages(struct repository
*r
,
1993 enum todo_command command
,
1994 struct commit
*commit
,
1995 struct replay_opts
*opts
,
1998 struct strbuf buf
= STRBUF_INIT
;
2000 const char *message
, *body
;
2001 const char *encoding
= get_commit_output_encoding();
2003 if (opts
->current_fixup_count
> 0) {
2004 struct strbuf header
= STRBUF_INIT
;
2007 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2008 return error(_("could not read '%s'"),
2009 rebase_path_squash_msg());
2011 eol
= buf
.buf
[0] != comment_line_char
?
2012 buf
.buf
: strchrnul(buf
.buf
, '\n');
2014 strbuf_addf(&header
, "%c ", comment_line_char
);
2015 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2016 opts
->current_fixup_count
+ 2);
2017 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2018 strbuf_release(&header
);
2019 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2020 update_squash_message_for_fixup(&buf
);
2022 struct object_id head
;
2023 struct commit
*head_commit
;
2024 const char *head_message
, *body
;
2026 if (repo_get_oid(r
, "HEAD", &head
))
2027 return error(_("need a HEAD to fixup"));
2028 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2029 return error(_("could not read HEAD"));
2030 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2032 return error(_("could not read HEAD's commit message"));
2034 find_commit_subject(head_message
, &body
);
2035 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2036 rebase_path_fixup_msg(), 0) < 0) {
2037 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2038 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2040 strbuf_addf(&buf
, "%c ", comment_line_char
);
2041 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2042 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2043 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2044 _(skip_first_commit_msg_str
) :
2045 _(first_commit_msg_str
));
2046 strbuf_addstr(&buf
, "\n\n");
2047 if (is_fixup_flag(command
, flag
))
2048 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2051 strbuf_addstr(&buf
, body
);
2053 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2056 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2057 return error(_("could not read commit message of %s"),
2058 oid_to_hex(&commit
->object
.oid
));
2059 find_commit_subject(message
, &body
);
2061 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2062 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2063 } else if (command
== TODO_FIXUP
) {
2064 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2065 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2066 ++opts
->current_fixup_count
+ 1);
2067 strbuf_addstr(&buf
, "\n\n");
2068 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2071 return error(_("unknown command: %d"), command
);
2072 repo_unuse_commit_buffer(r
, commit
, message
);
2075 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2077 strbuf_release(&buf
);
2080 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2081 opts
->current_fixups
.len
? "\n" : "",
2082 command_to_string(command
),
2083 oid_to_hex(&commit
->object
.oid
));
2084 res
= write_message(opts
->current_fixups
.buf
,
2085 opts
->current_fixups
.len
,
2086 rebase_path_current_fixups(), 0);
2092 static void flush_rewritten_pending(void)
2094 struct strbuf buf
= STRBUF_INIT
;
2095 struct object_id newoid
;
2098 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2099 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2100 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2101 char *bol
= buf
.buf
, *eol
;
2104 eol
= strchrnul(bol
, '\n');
2105 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2106 bol
, oid_to_hex(&newoid
));
2112 unlink(rebase_path_rewritten_pending());
2114 strbuf_release(&buf
);
2117 static void record_in_rewritten(struct object_id
*oid
,
2118 enum todo_command next_command
)
2120 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2125 fprintf(out
, "%s\n", oid_to_hex(oid
));
2128 if (!is_fixup(next_command
))
2129 flush_rewritten_pending();
2132 static int should_edit(struct replay_opts
*opts
) {
2135 * Note that we only handle the case of non-conflicted
2136 * commits; continue_single_pick() handles the conflicted
2137 * commits itself instead of calling this function.
2139 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2143 static void refer_to_commit(struct replay_opts
*opts
,
2144 struct strbuf
*msgbuf
, struct commit
*commit
)
2146 if (opts
->commit_use_reference
) {
2147 struct pretty_print_context ctx
= {
2148 .abbrev
= DEFAULT_ABBREV
,
2149 .date_mode
.type
= DATE_SHORT
,
2151 repo_format_commit_message(the_repository
, commit
,
2152 "%h (%s, %ad)", msgbuf
, &ctx
);
2154 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2158 static int do_pick_commit(struct repository
*r
,
2159 struct todo_item
*item
,
2160 struct replay_opts
*opts
,
2161 int final_fixup
, int *check_todo
)
2163 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2164 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2165 struct object_id head
;
2166 struct commit
*base
, *next
, *parent
;
2167 const char *base_label
, *next_label
;
2168 char *author
= NULL
;
2169 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2170 struct strbuf msgbuf
= STRBUF_INIT
;
2171 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2172 enum todo_command command
= item
->command
;
2173 struct commit
*commit
= item
->commit
;
2175 if (opts
->no_commit
) {
2177 * We do not intend to commit immediately. We just want to
2178 * merge the differences in, so let's compute the tree
2179 * that represents the "current" state for the merge machinery
2182 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2183 return error(_("your index file is unmerged."));
2185 unborn
= repo_get_oid(r
, "HEAD", &head
);
2186 /* Do we want to generate a root commit? */
2187 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2188 oideq(&head
, &opts
->squash_onto
)) {
2189 if (is_fixup(command
))
2190 return error(_("cannot fixup root commit"));
2191 flags
|= CREATE_ROOT_COMMIT
;
2194 oidcpy(&head
, the_hash_algo
->empty_tree
);
2195 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2197 return error_dirty_index(r
, opts
);
2199 discard_index(r
->index
);
2201 if (!commit
->parents
)
2203 else if (commit
->parents
->next
) {
2204 /* Reverting or cherry-picking a merge commit */
2206 struct commit_list
*p
;
2208 if (!opts
->mainline
)
2209 return error(_("commit %s is a merge but no -m option was given."),
2210 oid_to_hex(&commit
->object
.oid
));
2212 for (cnt
= 1, p
= commit
->parents
;
2213 cnt
!= opts
->mainline
&& p
;
2216 if (cnt
!= opts
->mainline
|| !p
)
2217 return error(_("commit %s does not have parent %d"),
2218 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2220 } else if (1 < opts
->mainline
)
2222 * Non-first parent explicitly specified as mainline for
2225 return error(_("commit %s does not have parent %d"),
2226 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2228 parent
= commit
->parents
->item
;
2230 if (get_message(commit
, &msg
) != 0)
2231 return error(_("cannot get commit message for %s"),
2232 oid_to_hex(&commit
->object
.oid
));
2234 if (opts
->allow_ff
&& !is_fixup(command
) &&
2235 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2236 (!parent
&& unborn
))) {
2237 if (is_rebase_i(opts
))
2238 write_author_script(msg
.message
);
2239 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2241 if (res
|| command
!= TODO_REWORD
)
2245 goto fast_forward_edit
;
2247 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2248 /* TRANSLATORS: The first %s will be a "todo" command like
2249 "revert" or "pick", the second %s a SHA1. */
2250 return error(_("%s: cannot parse parent commit %s"),
2251 command_to_string(command
),
2252 oid_to_hex(&parent
->object
.oid
));
2255 * "commit" is an existing commit. We would want to apply
2256 * the difference it introduces since its first parent "prev"
2257 * on top of the current HEAD if we are cherry-pick. Or the
2258 * reverse of it if we are revert.
2261 if (command
== TODO_REVERT
) {
2262 const char *orig_subject
;
2265 base_label
= msg
.label
;
2267 next_label
= msg
.parent_label
;
2268 if (opts
->commit_use_reference
) {
2269 strbuf_addstr(&msgbuf
,
2270 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2271 } else if (skip_prefix(msg
.subject
, "Revert \"", &orig_subject
) &&
2273 * We don't touch pre-existing repeated reverts, because
2274 * theoretically these can be nested arbitrarily deeply,
2275 * thus requiring excessive complexity to deal with.
2277 !starts_with(orig_subject
, "Revert \"")) {
2278 strbuf_addstr(&msgbuf
, "Reapply \"");
2279 strbuf_addstr(&msgbuf
, orig_subject
);
2281 strbuf_addstr(&msgbuf
, "Revert \"");
2282 strbuf_addstr(&msgbuf
, msg
.subject
);
2283 strbuf_addstr(&msgbuf
, "\"");
2285 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2286 refer_to_commit(opts
, &msgbuf
, commit
);
2288 if (commit
->parents
&& commit
->parents
->next
) {
2289 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2290 refer_to_commit(opts
, &msgbuf
, parent
);
2292 strbuf_addstr(&msgbuf
, ".\n");
2297 base_label
= msg
.parent_label
;
2299 next_label
= msg
.label
;
2301 /* Append the commit log message to msgbuf. */
2302 if (find_commit_subject(msg
.message
, &p
))
2303 strbuf_addstr(&msgbuf
, p
);
2305 if (opts
->record_origin
) {
2306 strbuf_complete_line(&msgbuf
);
2307 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2308 strbuf_addch(&msgbuf
, '\n');
2309 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2310 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2311 strbuf_addstr(&msgbuf
, ")\n");
2313 if (!is_fixup(command
))
2314 author
= get_author(msg
.message
);
2317 if (command
== TODO_REWORD
)
2319 else if (is_fixup(command
)) {
2320 if (update_squash_messages(r
, command
, commit
,
2321 opts
, item
->flags
)) {
2327 msg_file
= rebase_path_squash_msg();
2328 else if (file_exists(rebase_path_fixup_msg())) {
2329 flags
|= VERBATIM_MSG
;
2330 msg_file
= rebase_path_fixup_msg();
2332 const char *dest
= git_path_squash_msg(r
);
2334 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2335 res
= error(_("could not copy '%s' to '%s'"),
2336 rebase_path_squash_msg(), dest
);
2339 unlink(git_path_merge_msg(r
));
2345 if (opts
->signoff
&& !is_fixup(command
))
2346 append_signoff(&msgbuf
, 0, 0);
2348 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2350 else if (!opts
->strategy
||
2351 !strcmp(opts
->strategy
, "recursive") ||
2352 !strcmp(opts
->strategy
, "ort") ||
2353 command
== TODO_REVERT
) {
2354 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2355 &head
, &msgbuf
, opts
);
2359 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2360 git_path_merge_msg(r
), 0);
2362 struct commit_list
*common
= NULL
;
2363 struct commit_list
*remotes
= NULL
;
2365 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2366 git_path_merge_msg(r
), 0);
2368 commit_list_insert(base
, &common
);
2369 commit_list_insert(next
, &remotes
);
2370 res
|= try_merge_command(r
, opts
->strategy
,
2371 opts
->xopts
.nr
, opts
->xopts
.v
,
2372 common
, oid_to_hex(&head
), remotes
);
2373 free_commit_list(common
);
2374 free_commit_list(remotes
);
2378 * If the merge was clean or if it failed due to conflict, we write
2379 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2380 * However, if the merge did not even start, then we don't want to
2383 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2384 command
== TODO_EDIT
) && !opts
->no_commit
&&
2385 (res
== 0 || res
== 1) &&
2386 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2387 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2389 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2390 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2391 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2395 error(command
== TODO_REVERT
2396 ? _("could not revert %s... %s")
2397 : _("could not apply %s... %s"),
2398 short_commit_name(r
, commit
), msg
.subject
);
2399 print_advice(r
, res
== 1, opts
);
2400 repo_rerere(r
, opts
->allow_rerere_auto
);
2405 allow
= allow_empty(r
, opts
, commit
);
2409 } else if (allow
== 1) {
2410 flags
|= ALLOW_EMPTY
;
2411 } else if (allow
== 2) {
2413 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2414 NULL
, REF_NO_DEREF
);
2415 unlink(git_path_merge_msg(r
));
2416 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2417 NULL
, REF_NO_DEREF
);
2419 _("dropping %s %s -- patch contents already upstream\n"),
2420 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2421 } /* else allow == 0 and there's nothing special to do */
2422 if (!opts
->no_commit
&& !drop_commit
) {
2423 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2424 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2425 commit
? &commit
->object
.oid
: NULL
);
2427 res
= error(_("unable to parse commit author"));
2428 *check_todo
= !!(flags
& EDIT_MSG
);
2429 if (!res
&& reword
) {
2431 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2432 VERIFY_MSG
| AMEND_MSG
|
2433 (flags
& ALLOW_EMPTY
));
2439 if (!res
&& final_fixup
) {
2440 unlink(rebase_path_fixup_msg());
2441 unlink(rebase_path_squash_msg());
2442 unlink(rebase_path_current_fixups());
2443 strbuf_reset(&opts
->current_fixups
);
2444 opts
->current_fixup_count
= 0;
2448 free_message(commit
, &msg
);
2450 strbuf_release(&msgbuf
);
2451 update_abort_safety_file();
2456 static int prepare_revs(struct replay_opts
*opts
)
2459 * picking (but not reverting) ranges (but not individual revisions)
2460 * should be done in reverse
2462 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2463 opts
->revs
->reverse
^= 1;
2465 if (prepare_revision_walk(opts
->revs
))
2466 return error(_("revision walk setup failed"));
2471 static int read_and_refresh_cache(struct repository
*r
,
2472 struct replay_opts
*opts
)
2474 struct lock_file index_lock
= LOCK_INIT
;
2475 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2476 if (repo_read_index(r
) < 0) {
2477 rollback_lock_file(&index_lock
);
2478 return error(_("git %s: failed to read the index"),
2481 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2483 if (index_fd
>= 0) {
2484 if (write_locked_index(r
->index
, &index_lock
,
2485 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2486 return error(_("git %s: failed to refresh the index"),
2492 * If we are resolving merges in any way other than "ort", then
2493 * expand the sparse index.
2495 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2496 ensure_full_index(r
->index
);
2500 void todo_list_release(struct todo_list
*todo_list
)
2502 strbuf_release(&todo_list
->buf
);
2503 FREE_AND_NULL(todo_list
->items
);
2504 todo_list
->nr
= todo_list
->alloc
= 0;
2507 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2509 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2510 return todo_list
->items
+ todo_list
->nr
++;
2513 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2514 struct todo_item
*item
)
2516 return todo_list
->buf
.buf
+ item
->arg_offset
;
2519 static int is_command(enum todo_command command
, const char **bol
)
2521 const char *str
= todo_command_info
[command
].str
;
2522 const char nick
= todo_command_info
[command
].c
;
2523 const char *p
= *bol
;
2525 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2526 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2530 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2535 * '#' is not a valid label as the merge command uses it to
2536 * separate merge parents from the commit subject.
2538 if (!strcmp(arg
, "#") ||
2539 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2540 return error(_("'%s' is not a valid label"), arg
);
2543 case TODO_UPDATE_REF
:
2544 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2545 return error(_("'%s' is not a valid refname"), arg
);
2546 if (check_refname_format(arg
, 0))
2547 return error(_("update-ref requires a fully qualified "
2548 "refname e.g. refs/heads/%s"), arg
);
2552 BUG("unexpected todo_command");
2558 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2559 const char *buf
, const char *bol
, char *eol
)
2561 struct object_id commit_oid
;
2562 char *end_of_object_name
;
2563 int i
, saved
, status
, padding
;
2568 bol
+= strspn(bol
, " \t");
2570 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2571 item
->command
= TODO_COMMENT
;
2572 item
->commit
= NULL
;
2573 item
->arg_offset
= bol
- buf
;
2574 item
->arg_len
= eol
- bol
;
2578 for (i
= 0; i
< TODO_COMMENT
; i
++)
2579 if (is_command(i
, &bol
)) {
2583 if (i
>= TODO_COMMENT
)
2584 return error(_("invalid command '%.*s'"),
2585 (int)strcspn(bol
, " \t\r\n"), bol
);
2587 /* Eat up extra spaces/ tabs before object name */
2588 padding
= strspn(bol
, " \t");
2591 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2593 return error(_("%s does not accept arguments: '%s'"),
2594 command_to_string(item
->command
), bol
);
2595 item
->commit
= NULL
;
2596 item
->arg_offset
= bol
- buf
;
2597 item
->arg_len
= eol
- bol
;
2602 return error(_("missing arguments for %s"),
2603 command_to_string(item
->command
));
2605 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2606 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2609 item
->commit
= NULL
;
2610 item
->arg_offset
= bol
- buf
;
2611 item
->arg_len
= (int)(eol
- bol
);
2612 if (item
->command
== TODO_LABEL
||
2613 item
->command
== TODO_UPDATE_REF
) {
2616 ret
= check_label_or_ref_arg(item
->command
, bol
);
2622 if (item
->command
== TODO_FIXUP
) {
2623 if (skip_prefix(bol
, "-C", &bol
)) {
2624 bol
+= strspn(bol
, " \t");
2625 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2626 } else if (skip_prefix(bol
, "-c", &bol
)) {
2627 bol
+= strspn(bol
, " \t");
2628 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2632 if (item
->command
== TODO_MERGE
) {
2633 if (skip_prefix(bol
, "-C", &bol
))
2634 bol
+= strspn(bol
, " \t");
2635 else if (skip_prefix(bol
, "-c", &bol
)) {
2636 bol
+= strspn(bol
, " \t");
2637 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2639 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2640 item
->commit
= NULL
;
2641 item
->arg_offset
= bol
- buf
;
2642 item
->arg_len
= (int)(eol
- bol
);
2647 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2648 saved
= *end_of_object_name
;
2649 *end_of_object_name
= '\0';
2650 status
= repo_get_oid(r
, bol
, &commit_oid
);
2652 error(_("could not parse '%s'"), bol
); /* return later */
2653 *end_of_object_name
= saved
;
2655 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2656 item
->arg_offset
= bol
- buf
;
2657 item
->arg_len
= (int)(eol
- bol
);
2662 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2663 return item
->commit
? 0 : -1;
2666 int sequencer_get_last_command(struct repository
*r UNUSED
, enum replay_action
*action
)
2668 const char *todo_file
, *bol
;
2669 struct strbuf buf
= STRBUF_INIT
;
2672 todo_file
= git_path_todo_file();
2673 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2674 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2677 return error_errno("unable to open '%s'", todo_file
);
2679 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2680 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2681 *action
= REPLAY_PICK
;
2682 else if (is_command(TODO_REVERT
, &bol
) &&
2683 (*bol
== ' ' || *bol
== '\t'))
2684 *action
= REPLAY_REVERT
;
2688 strbuf_release(&buf
);
2693 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2694 struct todo_list
*todo_list
)
2696 struct todo_item
*item
;
2697 char *p
= buf
, *next_p
;
2698 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2700 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2702 for (i
= 1; *p
; i
++, p
= next_p
) {
2703 char *eol
= strchrnul(p
, '\n');
2705 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2707 if (p
!= eol
&& eol
[-1] == '\r')
2708 eol
--; /* strip Carriage Return */
2710 item
= append_new_todo(todo_list
);
2711 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2712 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2713 res
= error(_("invalid line %d: %.*s"),
2714 i
, (int)(eol
- p
), p
);
2715 item
->command
= TODO_COMMENT
+ 1;
2716 item
->arg_offset
= p
- buf
;
2717 item
->arg_len
= (int)(eol
- p
);
2718 item
->commit
= NULL
;
2721 if (item
->command
!= TODO_COMMENT
)
2722 todo_list
->total_nr
++;
2726 else if (is_fixup(item
->command
))
2727 res
= error(_("cannot '%s' without a previous commit"),
2728 command_to_string(item
->command
));
2729 else if (!is_noop(item
->command
))
2736 static int count_commands(struct todo_list
*todo_list
)
2740 for (i
= 0; i
< todo_list
->nr
; i
++)
2741 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2747 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2749 return index
< todo_list
->nr
?
2750 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2753 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2755 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2758 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2760 return get_item_line_offset(todo_list
, index
+ 1)
2761 - get_item_line_offset(todo_list
, index
);
2764 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2769 fd
= open(path
, O_RDONLY
);
2771 return error_errno(_("could not open '%s'"), path
);
2772 len
= strbuf_read(sb
, fd
, 0);
2775 return error(_("could not read '%s'."), path
);
2779 static int have_finished_the_last_pick(void)
2781 struct strbuf buf
= STRBUF_INIT
;
2783 const char *todo_path
= git_path_todo_file();
2786 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2787 if (errno
== ENOENT
) {
2790 error_errno("unable to open '%s'", todo_path
);
2794 /* If there is only one line then we are done */
2795 eol
= strchr(buf
.buf
, '\n');
2796 if (!eol
|| !eol
[1])
2799 strbuf_release(&buf
);
2804 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2806 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2807 int need_cleanup
= 0;
2809 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2810 if (!refs_delete_ref(get_main_ref_store(r
), "",
2811 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
) &&
2813 warning(_("cancelling a cherry picking in progress"));
2814 opts
.action
= REPLAY_PICK
;
2818 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2819 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2820 NULL
, REF_NO_DEREF
) &&
2822 warning(_("cancelling a revert in progress"));
2823 opts
.action
= REPLAY_REVERT
;
2827 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2828 NULL
, REF_NO_DEREF
);
2833 if (!have_finished_the_last_pick())
2836 sequencer_remove_state(&opts
);
2839 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2841 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2844 fprintf(f
, "%d\n", todo_list
->total_nr
);
2849 static int read_populate_todo(struct repository
*r
,
2850 struct todo_list
*todo_list
,
2851 struct replay_opts
*opts
)
2853 const char *todo_file
= get_todo_path(opts
);
2856 strbuf_reset(&todo_list
->buf
);
2857 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2860 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2862 if (is_rebase_i(opts
))
2863 return error(_("please fix this using "
2864 "'git rebase --edit-todo'."));
2865 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2868 if (!todo_list
->nr
&&
2869 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2870 return error(_("no commits parsed."));
2872 if (!is_rebase_i(opts
)) {
2873 enum todo_command valid
=
2874 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2877 for (i
= 0; i
< todo_list
->nr
; i
++)
2878 if (valid
== todo_list
->items
[i
].command
)
2880 else if (valid
== TODO_PICK
)
2881 return error(_("cannot cherry-pick during a revert."));
2883 return error(_("cannot revert during a cherry-pick."));
2886 if (is_rebase_i(opts
)) {
2887 struct todo_list done
= TODO_LIST_INIT
;
2889 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2890 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2891 todo_list
->done_nr
= count_commands(&done
);
2893 todo_list
->done_nr
= 0;
2895 todo_list
->total_nr
= todo_list
->done_nr
2896 + count_commands(todo_list
);
2897 todo_list_release(&done
);
2899 todo_list_write_total_nr(todo_list
);
2905 static int git_config_string_dup(char **dest
,
2906 const char *var
, const char *value
)
2909 return config_error_nonbool(var
);
2911 *dest
= xstrdup(value
);
2915 static int populate_opts_cb(const char *key
, const char *value
,
2916 const struct config_context
*ctx
,
2919 struct replay_opts
*opts
= data
;
2924 else if (!strcmp(key
, "options.no-commit"))
2925 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2926 else if (!strcmp(key
, "options.edit"))
2927 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2928 else if (!strcmp(key
, "options.allow-empty"))
2930 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2931 else if (!strcmp(key
, "options.allow-empty-message"))
2932 opts
->allow_empty_message
=
2933 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2934 else if (!strcmp(key
, "options.keep-redundant-commits"))
2935 opts
->keep_redundant_commits
=
2936 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2937 else if (!strcmp(key
, "options.signoff"))
2938 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2939 else if (!strcmp(key
, "options.record-origin"))
2940 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2941 else if (!strcmp(key
, "options.allow-ff"))
2942 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2943 else if (!strcmp(key
, "options.mainline"))
2944 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2945 else if (!strcmp(key
, "options.strategy"))
2946 git_config_string_dup(&opts
->strategy
, key
, value
);
2947 else if (!strcmp(key
, "options.gpg-sign"))
2948 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2949 else if (!strcmp(key
, "options.strategy-option")) {
2950 strvec_push(&opts
->xopts
, value
);
2951 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2952 opts
->allow_rerere_auto
=
2953 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2954 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2955 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2956 opts
->explicit_cleanup
= 1;
2957 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2959 return error(_("invalid key: %s"), key
);
2962 return error(_("invalid value for '%s': '%s'"), key
, value
);
2967 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2972 char *strategy_opts_string
= raw_opts
;
2974 if (*strategy_opts_string
== ' ')
2975 strategy_opts_string
++;
2977 count
= split_cmdline(strategy_opts_string
, &argv
);
2979 BUG("could not split '%s': %s", strategy_opts_string
,
2980 split_cmdline_strerror(count
));
2981 for (i
= 0; i
< count
; i
++) {
2982 const char *arg
= argv
[i
];
2984 skip_prefix(arg
, "--", &arg
);
2985 strvec_push(&opts
->xopts
, arg
);
2990 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2993 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2995 opts
->strategy
= strbuf_detach(buf
, NULL
);
2996 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2999 parse_strategy_opts(opts
, buf
->buf
);
3002 static int read_populate_opts(struct replay_opts
*opts
)
3004 if (is_rebase_i(opts
)) {
3005 struct strbuf buf
= STRBUF_INIT
;
3008 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
3009 READ_ONELINER_SKIP_IF_EMPTY
)) {
3010 if (!starts_with(buf
.buf
, "-S"))
3013 free(opts
->gpg_sign
);
3014 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3019 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3020 READ_ONELINER_SKIP_IF_EMPTY
)) {
3021 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3022 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3023 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3024 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3028 if (file_exists(rebase_path_verbose()))
3031 if (file_exists(rebase_path_quiet()))
3034 if (file_exists(rebase_path_signoff())) {
3039 if (file_exists(rebase_path_cdate_is_adate())) {
3041 opts
->committer_date_is_author_date
= 1;
3044 if (file_exists(rebase_path_ignore_date())) {
3046 opts
->ignore_date
= 1;
3049 if (file_exists(rebase_path_reschedule_failed_exec()))
3050 opts
->reschedule_failed_exec
= 1;
3051 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3052 opts
->reschedule_failed_exec
= 0;
3054 if (file_exists(rebase_path_drop_redundant_commits()))
3055 opts
->drop_redundant_commits
= 1;
3057 if (file_exists(rebase_path_keep_redundant_commits()))
3058 opts
->keep_redundant_commits
= 1;
3060 read_strategy_opts(opts
, &buf
);
3063 if (read_oneliner(&opts
->current_fixups
,
3064 rebase_path_current_fixups(),
3065 READ_ONELINER_SKIP_IF_EMPTY
)) {
3066 const char *p
= opts
->current_fixups
.buf
;
3067 opts
->current_fixup_count
= 1;
3068 while ((p
= strchr(p
, '\n'))) {
3069 opts
->current_fixup_count
++;
3074 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3075 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3076 ret
= error(_("unusable squash-onto"));
3079 opts
->have_squash_onto
= 1;
3083 strbuf_release(&buf
);
3087 if (!file_exists(git_path_opts_file()))
3090 * The function git_parse_source(), called from git_config_from_file(),
3091 * may die() in case of a syntactically incorrect file. We do not care
3092 * about this case, though, because we wrote that file ourselves, so we
3093 * are pretty certain that it is syntactically correct.
3095 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3096 return error(_("malformed options sheet: '%s'"),
3097 git_path_opts_file());
3101 static void write_strategy_opts(struct replay_opts
*opts
)
3103 struct strbuf buf
= STRBUF_INIT
;
3106 * Quote strategy options so that they can be read correctly
3107 * by split_cmdline().
3109 quote_cmdline(&buf
, opts
->xopts
.v
);
3110 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3111 strbuf_release(&buf
);
3114 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3115 struct commit
*onto
, const struct object_id
*orig_head
)
3118 write_file(rebase_path_head_name(), "%s\n", head_name
);
3120 write_file(rebase_path_onto(), "%s\n",
3121 oid_to_hex(&onto
->object
.oid
));
3123 write_file(rebase_path_orig_head(), "%s\n",
3124 oid_to_hex(orig_head
));
3127 write_file(rebase_path_quiet(), "%s", "");
3129 write_file(rebase_path_verbose(), "%s", "");
3131 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3132 if (opts
->xopts
.nr
> 0)
3133 write_strategy_opts(opts
);
3135 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3136 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3137 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3138 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3141 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3143 write_file(rebase_path_signoff(), "--signoff\n");
3144 if (opts
->drop_redundant_commits
)
3145 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3146 if (opts
->keep_redundant_commits
)
3147 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3148 if (opts
->committer_date_is_author_date
)
3149 write_file(rebase_path_cdate_is_adate(), "%s", "");
3150 if (opts
->ignore_date
)
3151 write_file(rebase_path_ignore_date(), "%s", "");
3152 if (opts
->reschedule_failed_exec
)
3153 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3155 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3160 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3161 struct replay_opts
*opts
)
3163 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3164 TODO_PICK
: TODO_REVERT
;
3165 const char *command_string
= todo_command_info
[command
].str
;
3166 const char *encoding
;
3167 struct commit
*commit
;
3169 if (prepare_revs(opts
))
3172 encoding
= get_log_output_encoding();
3174 while ((commit
= get_revision(opts
->revs
))) {
3175 struct todo_item
*item
= append_new_todo(todo_list
);
3176 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3179 const char *subject
;
3182 item
->command
= command
;
3183 item
->commit
= commit
;
3184 item
->arg_offset
= 0;
3186 item
->offset_in_buf
= todo_list
->buf
.len
;
3187 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3188 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3189 short_commit_name(the_repository
, commit
),
3190 subject_len
, subject
);
3191 repo_unuse_commit_buffer(the_repository
, commit
,
3196 return error(_("empty commit set passed"));
3201 static int create_seq_dir(struct repository
*r
)
3203 enum replay_action action
;
3204 const char *in_progress_error
= NULL
;
3205 const char *in_progress_advice
= NULL
;
3206 unsigned int advise_skip
=
3207 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3208 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3210 if (!sequencer_get_last_command(r
, &action
)) {
3213 in_progress_error
= _("revert is already in progress");
3214 in_progress_advice
=
3215 _("try \"git revert (--continue | %s--abort | --quit)\"");
3218 in_progress_error
= _("cherry-pick is already in progress");
3219 in_progress_advice
=
3220 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3223 BUG("unexpected action in create_seq_dir");
3226 if (in_progress_error
) {
3227 error("%s", in_progress_error
);
3228 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3229 advise(in_progress_advice
,
3230 advise_skip
? "--skip | " : "");
3233 if (mkdir(git_path_seq_dir(), 0777) < 0)
3234 return error_errno(_("could not create sequencer directory '%s'"),
3235 git_path_seq_dir());
3240 static int save_head(const char *head
)
3242 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3245 static int rollback_is_safe(void)
3247 struct strbuf sb
= STRBUF_INIT
;
3248 struct object_id expected_head
, actual_head
;
3250 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3252 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3253 strbuf_release(&sb
);
3254 die(_("could not parse %s"), git_path_abort_safety_file());
3256 strbuf_release(&sb
);
3258 else if (errno
== ENOENT
)
3259 oidclr(&expected_head
);
3261 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3263 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3264 oidclr(&actual_head
);
3266 return oideq(&actual_head
, &expected_head
);
3269 static int reset_merge(const struct object_id
*oid
)
3271 struct child_process cmd
= CHILD_PROCESS_INIT
;
3274 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3276 if (!is_null_oid(oid
))
3277 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3279 return run_command(&cmd
);
3282 static int rollback_single_pick(struct repository
*r
)
3284 struct object_id head_oid
;
3286 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3287 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3288 return error(_("no cherry-pick or revert in progress"));
3289 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3290 return error(_("cannot resolve HEAD"));
3291 if (is_null_oid(&head_oid
))
3292 return error(_("cannot abort from a branch yet to be born"));
3293 return reset_merge(&head_oid
);
3296 static int skip_single_pick(void)
3298 struct object_id head
;
3300 if (read_ref_full("HEAD", 0, &head
, NULL
))
3301 return error(_("cannot resolve HEAD"));
3302 return reset_merge(&head
);
3305 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3308 struct object_id oid
;
3309 struct strbuf buf
= STRBUF_INIT
;
3312 f
= fopen(git_path_head_file(), "r");
3313 if (!f
&& errno
== ENOENT
) {
3315 * There is no multiple-cherry-pick in progress.
3316 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3317 * a single-cherry-pick in progress, abort that.
3319 return rollback_single_pick(r
);
3322 return error_errno(_("cannot open '%s'"), git_path_head_file());
3323 if (strbuf_getline_lf(&buf
, f
)) {
3324 error(_("cannot read '%s': %s"), git_path_head_file(),
3325 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3330 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3331 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3332 git_path_head_file());
3335 if (is_null_oid(&oid
)) {
3336 error(_("cannot abort from a branch yet to be born"));
3340 if (!rollback_is_safe()) {
3341 /* Do not error, just do not rollback */
3342 warning(_("You seem to have moved HEAD. "
3343 "Not rewinding, check your HEAD!"));
3345 if (reset_merge(&oid
))
3347 strbuf_release(&buf
);
3348 return sequencer_remove_state(opts
);
3350 strbuf_release(&buf
);
3354 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3356 enum replay_action action
= -1;
3357 sequencer_get_last_command(r
, &action
);
3360 * Check whether the subcommand requested to skip the commit is actually
3361 * in progress and that it's safe to skip the commit.
3363 * opts->action tells us which subcommand requested to skip the commit.
3364 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3365 * action is in progress and we can skip the commit.
3367 * Otherwise we check that the last instruction was related to the
3368 * particular subcommand we're trying to execute and barf if that's not
3371 * Finally we check that the rollback is "safe", i.e., has the HEAD
3372 * moved? In this case, it doesn't make sense to "reset the merge" and
3373 * "skip the commit" as the user already handled this by committing. But
3374 * we'd not want to barf here, instead give advice on how to proceed. We
3375 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3376 * it gets removed when the user commits, so if it still exists we're
3377 * sure the user can't have committed before.
3379 switch (opts
->action
) {
3381 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3382 if (action
!= REPLAY_REVERT
)
3383 return error(_("no revert in progress"));
3384 if (!rollback_is_safe())
3389 if (!refs_ref_exists(get_main_ref_store(r
),
3390 "CHERRY_PICK_HEAD")) {
3391 if (action
!= REPLAY_PICK
)
3392 return error(_("no cherry-pick in progress"));
3393 if (!rollback_is_safe())
3398 BUG("unexpected action in sequencer_skip");
3401 if (skip_single_pick())
3402 return error(_("failed to skip the commit"));
3403 if (!is_directory(git_path_seq_dir()))
3406 return sequencer_continue(r
, opts
);
3409 error(_("there is nothing to skip"));
3411 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3412 advise(_("have you committed already?\n"
3413 "try \"git %s --continue\""),
3414 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3419 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
,
3422 struct lock_file todo_lock
= LOCK_INIT
;
3423 const char *todo_path
= get_todo_path(opts
);
3424 int next
= todo_list
->current
, offset
, fd
;
3427 * rebase -i writes "git-rebase-todo" without the currently executing
3428 * command, appending it to "done" instead.
3430 if (is_rebase_i(opts
) && !reschedule
)
3433 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3435 return error_errno(_("could not lock '%s'"), todo_path
);
3436 offset
= get_item_line_offset(todo_list
, next
);
3437 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3438 todo_list
->buf
.len
- offset
) < 0)
3439 return error_errno(_("could not write to '%s'"), todo_path
);
3440 if (commit_lock_file(&todo_lock
) < 0)
3441 return error(_("failed to finalize '%s'"), todo_path
);
3443 if (is_rebase_i(opts
) && !reschedule
&& next
> 0) {
3444 const char *done
= rebase_path_done();
3445 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3450 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3451 get_item_line_length(todo_list
, next
- 1))
3453 ret
= error_errno(_("could not write to '%s'"), done
);
3455 ret
= error_errno(_("failed to finalize '%s'"), done
);
3461 static int save_opts(struct replay_opts
*opts
)
3463 const char *opts_file
= git_path_opts_file();
3466 if (opts
->no_commit
)
3467 res
|= git_config_set_in_file_gently(opts_file
,
3468 "options.no-commit", "true");
3469 if (opts
->edit
>= 0)
3470 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3471 opts
->edit
? "true" : "false");
3472 if (opts
->allow_empty
)
3473 res
|= git_config_set_in_file_gently(opts_file
,
3474 "options.allow-empty", "true");
3475 if (opts
->allow_empty_message
)
3476 res
|= git_config_set_in_file_gently(opts_file
,
3477 "options.allow-empty-message", "true");
3478 if (opts
->keep_redundant_commits
)
3479 res
|= git_config_set_in_file_gently(opts_file
,
3480 "options.keep-redundant-commits", "true");
3482 res
|= git_config_set_in_file_gently(opts_file
,
3483 "options.signoff", "true");
3484 if (opts
->record_origin
)
3485 res
|= git_config_set_in_file_gently(opts_file
,
3486 "options.record-origin", "true");
3488 res
|= git_config_set_in_file_gently(opts_file
,
3489 "options.allow-ff", "true");
3490 if (opts
->mainline
) {
3491 struct strbuf buf
= STRBUF_INIT
;
3492 strbuf_addf(&buf
, "%d", opts
->mainline
);
3493 res
|= git_config_set_in_file_gently(opts_file
,
3494 "options.mainline", buf
.buf
);
3495 strbuf_release(&buf
);
3498 res
|= git_config_set_in_file_gently(opts_file
,
3499 "options.strategy", opts
->strategy
);
3501 res
|= git_config_set_in_file_gently(opts_file
,
3502 "options.gpg-sign", opts
->gpg_sign
);
3503 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3504 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3505 "options.strategy-option",
3506 opts
->xopts
.v
[i
], "^$", 0);
3507 if (opts
->allow_rerere_auto
)
3508 res
|= git_config_set_in_file_gently(opts_file
,
3509 "options.allow-rerere-auto",
3510 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3513 if (opts
->explicit_cleanup
)
3514 res
|= git_config_set_in_file_gently(opts_file
,
3515 "options.default-msg-cleanup",
3516 describe_cleanup_mode(opts
->default_msg_cleanup
));
3520 static int make_patch(struct repository
*r
,
3521 struct commit
*commit
,
3522 struct replay_opts
*opts
)
3524 struct rev_info log_tree_opt
;
3525 const char *subject
;
3526 char hex
[GIT_MAX_HEXSZ
+ 1];
3529 if (!is_rebase_i(opts
))
3530 BUG("make_patch should only be called when rebasing");
3532 oid_to_hex_r(hex
, &commit
->object
.oid
);
3533 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3535 res
|= write_rebase_head(&commit
->object
.oid
);
3537 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3538 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3539 log_tree_opt
.abbrev
= 0;
3540 log_tree_opt
.diff
= 1;
3541 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3542 log_tree_opt
.disable_stdin
= 1;
3543 log_tree_opt
.no_commit_id
= 1;
3544 log_tree_opt
.diffopt
.file
= fopen(rebase_path_patch(), "w");
3545 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3546 if (!log_tree_opt
.diffopt
.file
)
3547 res
|= error_errno(_("could not open '%s'"),
3548 rebase_path_patch());
3550 res
|= log_tree_commit(&log_tree_opt
, commit
);
3551 fclose(log_tree_opt
.diffopt
.file
);
3554 if (!file_exists(rebase_path_message())) {
3555 const char *encoding
= get_commit_output_encoding();
3556 const char *commit_buffer
= repo_logmsg_reencode(r
,
3559 find_commit_subject(commit_buffer
, &subject
);
3560 res
|= write_message(subject
, strlen(subject
), rebase_path_message(), 1);
3561 repo_unuse_commit_buffer(r
, commit
,
3564 release_revisions(&log_tree_opt
);
3569 static int intend_to_amend(void)
3571 struct object_id head
;
3574 if (repo_get_oid(the_repository
, "HEAD", &head
))
3575 return error(_("cannot read HEAD"));
3577 p
= oid_to_hex(&head
);
3578 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3581 static int error_with_patch(struct repository
*r
,
3582 struct commit
*commit
,
3583 const char *subject
, int subject_len
,
3584 struct replay_opts
*opts
,
3585 int exit_code
, int to_amend
)
3588 if (make_patch(r
, commit
, opts
))
3590 } else if (copy_file(rebase_path_message(),
3591 git_path_merge_msg(r
), 0666))
3592 return error(_("unable to copy '%s' to '%s'"),
3593 git_path_merge_msg(r
), rebase_path_message());
3596 if (intend_to_amend())
3600 _("You can amend the commit now, with\n"
3602 " git commit --amend %s\n"
3604 "Once you are satisfied with your changes, run\n"
3606 " git rebase --continue\n"),
3607 gpg_sign_opt_quoted(opts
));
3608 } else if (exit_code
) {
3610 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3611 short_commit_name(r
, commit
), subject_len
, subject
);
3614 * We don't have the hash of the parent so
3615 * just print the line from the todo file.
3617 fprintf_ln(stderr
, _("Could not merge %.*s"),
3618 subject_len
, subject
);
3624 static int error_failed_squash(struct repository
*r
,
3625 struct commit
*commit
,
3626 struct replay_opts
*opts
,
3628 const char *subject
)
3630 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3631 return error(_("could not copy '%s' to '%s'"),
3632 rebase_path_squash_msg(), rebase_path_message());
3633 unlink(git_path_merge_msg(r
));
3634 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3635 return error(_("could not copy '%s' to '%s'"),
3636 rebase_path_message(),
3637 git_path_merge_msg(r
));
3638 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3641 static int do_exec(struct repository
*r
, const char *command_line
)
3643 struct child_process cmd
= CHILD_PROCESS_INIT
;
3646 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3648 strvec_push(&cmd
.args
, command_line
);
3649 strvec_push(&cmd
.env
, "GIT_CHERRY_PICK_HELP");
3650 status
= run_command(&cmd
);
3652 /* force re-reading of the cache */
3653 discard_index(r
->index
);
3654 if (repo_read_index(r
) < 0)
3655 return error(_("could not read index"));
3657 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3660 warning(_("execution failed: %s\n%s"
3661 "You can fix the problem, and then run\n"
3663 " git rebase --continue\n"
3666 dirty
? _("and made changes to the index and/or the "
3667 "working tree.\n") : "");
3669 /* command not found */
3672 warning(_("execution succeeded: %s\nbut "
3673 "left changes to the index and/or the working tree.\n"
3674 "Commit or stash your changes, and then run\n"
3676 " git rebase --continue\n"
3677 "\n"), command_line
);
3684 __attribute__((format (printf
, 2, 3)))
3685 static int safe_append(const char *filename
, const char *fmt
, ...)
3688 struct lock_file lock
= LOCK_INIT
;
3689 int fd
= hold_lock_file_for_update(&lock
, filename
,
3690 LOCK_REPORT_ON_ERROR
);
3691 struct strbuf buf
= STRBUF_INIT
;
3696 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3697 error_errno(_("could not read '%s'"), filename
);
3698 rollback_lock_file(&lock
);
3701 strbuf_complete(&buf
, '\n');
3703 strbuf_vaddf(&buf
, fmt
, ap
);
3706 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3707 error_errno(_("could not write to '%s'"), filename
);
3708 strbuf_release(&buf
);
3709 rollback_lock_file(&lock
);
3712 if (commit_lock_file(&lock
) < 0) {
3713 strbuf_release(&buf
);
3714 return error(_("failed to finalize '%s'"), filename
);
3717 strbuf_release(&buf
);
3721 static int do_label(struct repository
*r
, const char *name
, int len
)
3723 struct ref_store
*refs
= get_main_ref_store(r
);
3724 struct ref_transaction
*transaction
;
3725 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3726 struct strbuf msg
= STRBUF_INIT
;
3728 struct object_id head_oid
;
3730 if (len
== 1 && *name
== '#')
3731 return error(_("illegal label name: '%.*s'"), len
, name
);
3733 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3734 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3736 transaction
= ref_store_transaction_begin(refs
, &err
);
3738 error("%s", err
.buf
);
3740 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3741 error(_("could not read HEAD"));
3743 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3744 NULL
, 0, msg
.buf
, &err
) < 0 ||
3745 ref_transaction_commit(transaction
, &err
)) {
3746 error("%s", err
.buf
);
3749 ref_transaction_free(transaction
);
3750 strbuf_release(&err
);
3751 strbuf_release(&msg
);
3754 ret
= safe_append(rebase_path_refs_to_delete(),
3755 "%s\n", ref_name
.buf
);
3756 strbuf_release(&ref_name
);
3761 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3763 if (!opts
->reflog_action
) {
3764 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3765 opts
->reflog_action
=
3766 xstrdup(opts
->reflog_action
? opts
->reflog_action
3767 : action_name(opts
));
3770 return opts
->reflog_action
;
3773 __attribute__((format (printf
, 3, 4)))
3774 static const char *reflog_message(struct replay_opts
*opts
,
3775 const char *sub_action
, const char *fmt
, ...)
3778 static struct strbuf buf
= STRBUF_INIT
;
3782 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3784 strbuf_addf(&buf
, " (%s)", sub_action
);
3786 strbuf_addstr(&buf
, ": ");
3787 strbuf_vaddf(&buf
, fmt
, ap
);
3794 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3795 int len
, struct strbuf
*buf
)
3797 struct commit
*commit
;
3798 struct object_id oid
;
3801 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3802 if (!read_ref(buf
->buf
, &oid
)) {
3803 commit
= lookup_commit_object(r
, &oid
);
3805 /* fall back to non-rewritten ref or commit */
3806 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3807 commit
= lookup_commit_reference_by_name(buf
->buf
);
3811 error(_("could not resolve '%s'"), buf
->buf
);
3816 static int do_reset(struct repository
*r
,
3817 const char *name
, int len
,
3818 struct replay_opts
*opts
)
3820 struct strbuf ref_name
= STRBUF_INIT
;
3821 struct object_id oid
;
3822 struct lock_file lock
= LOCK_INIT
;
3823 struct tree_desc desc
= { 0 };
3825 struct unpack_trees_options unpack_tree_opts
= { 0 };
3828 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3831 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3832 if (!opts
->have_squash_onto
) {
3834 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3835 NULL
, &opts
->squash_onto
,
3837 return error(_("writing fake root commit"));
3838 opts
->have_squash_onto
= 1;
3839 hex
= oid_to_hex(&opts
->squash_onto
);
3840 if (write_message(hex
, strlen(hex
),
3841 rebase_path_squash_onto(), 0))
3842 return error(_("writing squash-onto"));
3844 oidcpy(&oid
, &opts
->squash_onto
);
3847 struct commit
*commit
;
3849 /* Determine the length of the label */
3850 for (i
= 0; i
< len
; i
++)
3851 if (isspace(name
[i
]))
3855 commit
= lookup_label(r
, name
, len
, &ref_name
);
3860 oid
= commit
->object
.oid
;
3863 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3864 unpack_tree_opts
.head_idx
= 1;
3865 unpack_tree_opts
.src_index
= r
->index
;
3866 unpack_tree_opts
.dst_index
= r
->index
;
3867 unpack_tree_opts
.fn
= oneway_merge
;
3868 unpack_tree_opts
.merge
= 1;
3869 unpack_tree_opts
.update
= 1;
3870 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3871 unpack_tree_opts
.skip_cache_tree_update
= 1;
3872 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3874 if (repo_read_index_unmerged(r
)) {
3875 ret
= error_resolve_conflict(action_name(opts
));
3879 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3880 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3884 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3889 tree
= parse_tree_indirect(&oid
);
3891 return error(_("unable to read tree (%s)"), oid_to_hex(&oid
));
3892 prime_cache_tree(r
, r
->index
, tree
);
3894 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3895 ret
= error(_("could not write index"));
3898 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3899 len
, name
), "HEAD", &oid
,
3900 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3902 free((void *)desc
.buffer
);
3904 rollback_lock_file(&lock
);
3905 strbuf_release(&ref_name
);
3906 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3910 static int do_merge(struct repository
*r
,
3911 struct commit
*commit
,
3912 const char *arg
, int arg_len
,
3913 int flags
, int *check_todo
, struct replay_opts
*opts
)
3915 int run_commit_flags
= 0;
3916 struct strbuf ref_name
= STRBUF_INIT
;
3917 struct commit
*head_commit
, *merge_commit
, *i
;
3918 struct commit_list
*bases
= NULL
, *j
;
3919 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3920 const char *strategy
= !opts
->xopts
.nr
&&
3922 !strcmp(opts
->strategy
, "recursive") ||
3923 !strcmp(opts
->strategy
, "ort")) ?
3924 NULL
: opts
->strategy
;
3925 struct merge_options o
;
3926 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3927 static struct lock_file lock
;
3930 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3935 head_commit
= lookup_commit_reference_by_name("HEAD");
3937 ret
= error(_("cannot merge without a current revision"));
3942 * For octopus merges, the arg starts with the list of revisions to be
3943 * merged. The list is optionally followed by '#' and the oneline.
3945 merge_arg_len
= oneline_offset
= arg_len
;
3946 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3949 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3950 p
+= 1 + strspn(p
+ 1, " \t\n");
3951 oneline_offset
= p
- arg
;
3954 k
= strcspn(p
, " \t\n");
3957 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3958 if (!merge_commit
) {
3959 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3962 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3964 merge_arg_len
= p
- arg
;
3968 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3972 if (opts
->have_squash_onto
&&
3973 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3975 * When the user tells us to "merge" something into a
3976 * "[new root]", let's simply fast-forward to the merge head.
3978 rollback_lock_file(&lock
);
3980 ret
= error(_("octopus merge cannot be executed on "
3981 "top of a [new root]"));
3983 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3984 &head_commit
->object
.oid
, 0,
3990 * If HEAD is not identical to the first parent of the original merge
3991 * commit, we cannot fast-forward.
3993 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3994 oideq(&commit
->parents
->item
->object
.oid
,
3995 &head_commit
->object
.oid
);
3998 * If any merge head is different from the original one, we cannot
4001 if (can_fast_forward
) {
4002 struct commit_list
*p
= commit
->parents
->next
;
4004 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
4005 if (!oideq(&j
->item
->object
.oid
,
4006 &p
->item
->object
.oid
)) {
4007 can_fast_forward
= 0;
4011 * If the number of merge heads differs from the original merge
4012 * commit, we cannot fast-forward.
4015 can_fast_forward
= 0;
4018 if (can_fast_forward
) {
4019 rollback_lock_file(&lock
);
4020 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4021 &head_commit
->object
.oid
, 0, opts
);
4022 if (flags
& TODO_EDIT_MERGE_MSG
)
4023 goto fast_forward_edit
;
4029 const char *encoding
= get_commit_output_encoding();
4030 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4036 ret
= error(_("could not get commit message of '%s'"),
4037 oid_to_hex(&commit
->object
.oid
));
4040 write_author_script(message
);
4041 find_commit_subject(message
, &body
);
4043 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4044 repo_unuse_commit_buffer(r
, commit
, message
);
4046 error_errno(_("could not write '%s'"),
4047 git_path_merge_msg(r
));
4051 struct strbuf buf
= STRBUF_INIT
;
4054 strbuf_addf(&buf
, "author %s", git_author_info(0));
4055 write_author_script(buf
.buf
);
4058 if (oneline_offset
< arg_len
) {
4059 p
= arg
+ oneline_offset
;
4060 len
= arg_len
- oneline_offset
;
4062 strbuf_addf(&buf
, "Merge %s '%.*s'",
4063 to_merge
->next
? "branches" : "branch",
4064 merge_arg_len
, arg
);
4069 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4070 strbuf_release(&buf
);
4072 error_errno(_("could not write '%s'"),
4073 git_path_merge_msg(r
));
4078 if (strategy
|| to_merge
->next
) {
4080 struct child_process cmd
= CHILD_PROCESS_INIT
;
4082 if (read_env_script(&cmd
.env
)) {
4083 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4085 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4089 if (opts
->committer_date_is_author_date
)
4090 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4093 author_date_from_env(&cmd
.env
));
4094 if (opts
->ignore_date
)
4095 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4098 strvec_push(&cmd
.args
, "merge");
4099 strvec_push(&cmd
.args
, "-s");
4101 strvec_push(&cmd
.args
, "octopus");
4103 strvec_push(&cmd
.args
, strategy
);
4104 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4105 strvec_pushf(&cmd
.args
,
4106 "-X%s", opts
->xopts
.v
[k
]);
4108 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4109 strvec_push(&cmd
.args
, "--no-edit");
4111 strvec_push(&cmd
.args
, "--edit");
4112 strvec_push(&cmd
.args
, "--no-ff");
4113 strvec_push(&cmd
.args
, "--no-log");
4114 strvec_push(&cmd
.args
, "--no-stat");
4115 strvec_push(&cmd
.args
, "-F");
4116 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4118 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4120 strvec_push(&cmd
.args
, "--no-gpg-sign");
4122 /* Add the tips to be merged */
4123 for (j
= to_merge
; j
; j
= j
->next
)
4124 strvec_push(&cmd
.args
,
4125 oid_to_hex(&j
->item
->object
.oid
));
4127 strbuf_release(&ref_name
);
4128 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4129 NULL
, REF_NO_DEREF
);
4130 rollback_lock_file(&lock
);
4132 ret
= run_command(&cmd
);
4134 /* force re-reading of the cache */
4136 discard_index(r
->index
);
4137 if (repo_read_index(r
) < 0)
4138 ret
= error(_("could not read index"));
4143 merge_commit
= to_merge
->item
;
4144 if (repo_get_merge_bases(r
, head_commit
, merge_commit
, &bases
) < 0) {
4149 if (bases
&& oideq(&merge_commit
->object
.oid
,
4150 &bases
->item
->object
.oid
)) {
4152 /* skip merging an ancestor of HEAD */
4156 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4157 git_path_merge_head(r
), 0);
4158 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4160 bases
= reverse_commit_list(bases
);
4163 init_merge_options(&o
, r
);
4165 o
.branch2
= ref_name
.buf
;
4166 o
.buffer_output
= 2;
4168 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4170 * TODO: Should use merge_incore_recursive() and
4171 * merge_switch_to_result(), skipping the call to
4172 * merge_switch_to_result() when we don't actually need to
4173 * update the index and working copy immediately.
4175 ret
= merge_ort_recursive(&o
,
4176 head_commit
, merge_commit
, bases
,
4179 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4183 fputs(o
.obuf
.buf
, stdout
);
4184 strbuf_release(&o
.obuf
);
4186 error(_("could not even attempt to merge '%.*s'"),
4187 merge_arg_len
, arg
);
4188 unlink(git_path_merge_msg(r
));
4192 * The return value of merge_recursive() is 1 on clean, and 0 on
4195 * Let's reverse that, so that do_merge() returns 0 upon success and
4196 * 1 upon failed merge (keeping the return value -1 for the cases where
4197 * we will want to reschedule the `merge` command).
4201 if (r
->index
->cache_changed
&&
4202 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4203 ret
= error(_("merge: Unable to write new index file"));
4207 rollback_lock_file(&lock
);
4209 repo_rerere(r
, opts
->allow_rerere_auto
);
4212 * In case of problems, we now want to return a positive
4213 * value (a negative one would indicate that the `merge`
4214 * command needs to be rescheduled).
4216 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4219 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4222 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4223 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4228 strbuf_release(&ref_name
);
4229 rollback_lock_file(&lock
);
4230 free_commit_list(to_merge
);
4234 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4237 struct lock_file lock
= LOCK_INIT
;
4239 struct string_list_item
*item
;
4242 path
= rebase_path_update_refs(the_repository
->gitdir
);
4244 if (!refs_to_oids
->nr
) {
4245 if (unlink(path
) && errno
!= ENOENT
)
4246 result
= error_errno(_("could not unlink: %s"), path
);
4250 if (safe_create_leading_directories(path
)) {
4251 result
= error(_("unable to create leading directories of %s"),
4256 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4257 result
= error(_("another 'rebase' process appears to be running; "
4258 "'%s.lock' already exists"),
4263 fp
= fdopen_lock_file(&lock
, "w");
4265 result
= error_errno(_("could not open '%s' for writing"), path
);
4266 rollback_lock_file(&lock
);
4270 for_each_string_list_item(item
, refs_to_oids
) {
4271 struct update_ref_record
*rec
= item
->util
;
4272 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4273 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4276 result
= commit_lock_file(&lock
);
4284 * Parse the update-refs file for the current rebase, then remove the
4285 * refs that do not appear in the todo_list (and have not had updated
4286 * values stored) and add refs that are in the todo_list but not
4287 * represented in the update-refs file.
4289 * If there are changes to the update-refs list, then write the new state
4292 void todo_list_filter_update_refs(struct repository
*r
,
4293 struct todo_list
*todo_list
)
4297 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4299 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4302 * For each item in the update_refs list, if it has no updated
4303 * value and does not appear in the todo_list, then remove it
4304 * from the update_refs list.
4306 for (i
= 0; i
< update_refs
.nr
; i
++) {
4309 const char *ref
= update_refs
.items
[i
].string
;
4310 size_t reflen
= strlen(ref
);
4311 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4313 /* OID already stored as updated. */
4314 if (!is_null_oid(&rec
->after
))
4317 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4318 struct todo_item
*item
= &todo_list
->items
[j
];
4319 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4321 if (item
->command
!= TODO_UPDATE_REF
)
4324 if (item
->arg_len
!= reflen
||
4325 strncmp(arg
, ref
, reflen
))
4332 free(update_refs
.items
[i
].string
);
4333 free(update_refs
.items
[i
].util
);
4336 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4344 * For each todo_item, check if its ref is in the update_refs list.
4345 * If not, then add it as an un-updated ref.
4347 for (i
= 0; i
< todo_list
->nr
; i
++) {
4348 struct todo_item
*item
= &todo_list
->items
[i
];
4349 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4352 if (item
->command
!= TODO_UPDATE_REF
)
4355 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4356 const char *ref
= update_refs
.items
[j
].string
;
4358 found
= strlen(ref
) == item
->arg_len
&&
4359 !strncmp(ref
, arg
, item
->arg_len
);
4363 struct string_list_item
*inserted
;
4364 struct strbuf argref
= STRBUF_INIT
;
4366 strbuf_add(&argref
, arg
, item
->arg_len
);
4367 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4368 inserted
->util
= init_update_ref_record(argref
.buf
);
4369 strbuf_release(&argref
);
4375 write_update_refs_state(&update_refs
);
4376 string_list_clear(&update_refs
, 1);
4379 static int do_update_ref(struct repository
*r
, const char *refname
)
4381 struct string_list_item
*item
;
4382 struct string_list list
= STRING_LIST_INIT_DUP
;
4384 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4387 for_each_string_list_item(item
, &list
) {
4388 if (!strcmp(item
->string
, refname
)) {
4389 struct update_ref_record
*rec
= item
->util
;
4390 if (read_ref("HEAD", &rec
->after
))
4396 write_update_refs_state(&list
);
4397 string_list_clear(&list
, 1);
4401 static int do_update_refs(struct repository
*r
, int quiet
)
4404 struct string_list_item
*item
;
4405 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4406 struct ref_store
*refs
= get_main_ref_store(r
);
4407 struct strbuf update_msg
= STRBUF_INIT
;
4408 struct strbuf error_msg
= STRBUF_INIT
;
4410 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4413 for_each_string_list_item(item
, &refs_to_oids
) {
4414 struct update_ref_record
*rec
= item
->util
;
4417 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4419 &rec
->after
, &rec
->before
,
4420 0, UPDATE_REFS_MSG_ON_ERR
);
4427 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4429 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4433 (update_msg
.len
|| error_msg
.len
)) {
4435 _("Updated the following refs with %s:\n%s"),
4441 _("Failed to update the following refs with %s:\n%s"),
4446 string_list_clear(&refs_to_oids
, 1);
4447 strbuf_release(&update_msg
);
4448 strbuf_release(&error_msg
);
4452 static int is_final_fixup(struct todo_list
*todo_list
)
4454 int i
= todo_list
->current
;
4456 if (!is_fixup(todo_list
->items
[i
].command
))
4459 while (++i
< todo_list
->nr
)
4460 if (is_fixup(todo_list
->items
[i
].command
))
4462 else if (!is_noop(todo_list
->items
[i
].command
))
4467 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4471 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4472 if (!is_noop(todo_list
->items
[i
].command
))
4473 return todo_list
->items
[i
].command
;
4478 static void create_autostash_internal(struct repository
*r
,
4480 const char *refname
)
4482 struct strbuf buf
= STRBUF_INIT
;
4483 struct lock_file lock_file
= LOCK_INIT
;
4486 if (path
&& refname
)
4487 BUG("can only pass path or refname");
4489 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4490 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4492 repo_update_index_if_able(r
, &lock_file
);
4493 rollback_lock_file(&lock_file
);
4495 if (has_unstaged_changes(r
, 1) ||
4496 has_uncommitted_changes(r
, 1)) {
4497 struct child_process stash
= CHILD_PROCESS_INIT
;
4498 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4499 struct object_id oid
;
4501 strvec_pushl(&stash
.args
,
4502 "stash", "create", "autostash", NULL
);
4506 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4507 die(_("Cannot autostash"));
4508 strbuf_trim_trailing_newline(&buf
);
4509 if (repo_get_oid(r
, buf
.buf
, &oid
))
4510 die(_("Unexpected stash response: '%s'"),
4513 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4516 if (safe_create_leading_directories_const(path
))
4517 die(_("Could not create directory for '%s'"),
4519 write_file(path
, "%s", oid_to_hex(&oid
));
4521 refs_update_ref(get_main_ref_store(r
), "", refname
,
4522 &oid
, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR
);
4525 printf(_("Created autostash: %s\n"), buf
.buf
);
4526 if (reset_head(r
, &ropts
) < 0)
4527 die(_("could not reset --hard"));
4528 discard_index(r
->index
);
4529 if (repo_read_index(r
) < 0)
4530 die(_("could not read index"));
4532 strbuf_release(&buf
);
4535 void create_autostash(struct repository
*r
, const char *path
)
4537 create_autostash_internal(r
, path
, NULL
);
4540 void create_autostash_ref(struct repository
*r
, const char *refname
)
4542 create_autostash_internal(r
, NULL
, refname
);
4545 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4547 struct child_process child
= CHILD_PROCESS_INIT
;
4550 if (attempt_apply
) {
4552 child
.no_stdout
= 1;
4553 child
.no_stderr
= 1;
4554 strvec_push(&child
.args
, "stash");
4555 strvec_push(&child
.args
, "apply");
4556 strvec_push(&child
.args
, stash_oid
);
4557 ret
= run_command(&child
);
4560 if (attempt_apply
&& !ret
)
4561 fprintf(stderr
, _("Applied autostash.\n"));
4563 struct child_process store
= CHILD_PROCESS_INIT
;
4566 strvec_push(&store
.args
, "stash");
4567 strvec_push(&store
.args
, "store");
4568 strvec_push(&store
.args
, "-m");
4569 strvec_push(&store
.args
, "autostash");
4570 strvec_push(&store
.args
, "-q");
4571 strvec_push(&store
.args
, stash_oid
);
4572 if (run_command(&store
))
4573 ret
= error(_("cannot store %s"), stash_oid
);
4577 "Your changes are safe in the stash.\n"
4578 "You can run \"git stash pop\" or"
4579 " \"git stash drop\" at any time.\n"),
4581 _("Applying autostash resulted in conflicts.") :
4582 _("Autostash exists; creating a new stash entry."));
4588 static int apply_save_autostash(const char *path
, int attempt_apply
)
4590 struct strbuf stash_oid
= STRBUF_INIT
;
4593 if (!read_oneliner(&stash_oid
, path
,
4594 READ_ONELINER_SKIP_IF_EMPTY
)) {
4595 strbuf_release(&stash_oid
);
4598 strbuf_trim(&stash_oid
);
4600 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4603 strbuf_release(&stash_oid
);
4607 int save_autostash(const char *path
)
4609 return apply_save_autostash(path
, 0);
4612 int apply_autostash(const char *path
)
4614 return apply_save_autostash(path
, 1);
4617 int apply_autostash_oid(const char *stash_oid
)
4619 return apply_save_autostash_oid(stash_oid
, 1);
4622 static int apply_save_autostash_ref(struct repository
*r
, const char *refname
,
4625 struct object_id stash_oid
;
4626 char stash_oid_hex
[GIT_MAX_HEXSZ
+ 1];
4629 if (!refs_ref_exists(get_main_ref_store(r
), refname
))
4632 if (!refs_resolve_ref_unsafe(get_main_ref_store(r
), refname
,
4633 RESOLVE_REF_READING
, &stash_oid
, &flag
))
4635 if (flag
& REF_ISSYMREF
)
4636 return error(_("autostash reference is a symref"));
4638 oid_to_hex_r(stash_oid_hex
, &stash_oid
);
4639 ret
= apply_save_autostash_oid(stash_oid_hex
, attempt_apply
);
4641 refs_delete_ref(get_main_ref_store(r
), "", refname
,
4642 &stash_oid
, REF_NO_DEREF
);
4647 int save_autostash_ref(struct repository
*r
, const char *refname
)
4649 return apply_save_autostash_ref(r
, refname
, 0);
4652 int apply_autostash_ref(struct repository
*r
, const char *refname
)
4654 return apply_save_autostash_ref(r
, refname
, 1);
4657 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4658 const char *onto_name
, const struct object_id
*onto
,
4659 const struct object_id
*orig_head
)
4661 struct reset_head_opts ropts
= {
4663 .orig_head
= orig_head
,
4664 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4665 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4666 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4668 .default_reflog_action
= sequencer_reflog_action(opts
)
4670 if (reset_head(r
, &ropts
)) {
4671 apply_autostash(rebase_path_autostash());
4672 sequencer_remove_state(opts
);
4673 return error(_("could not detach HEAD"));
4679 static int stopped_at_head(struct repository
*r
)
4681 struct object_id head
;
4682 struct commit
*commit
;
4683 struct commit_message message
;
4685 if (repo_get_oid(r
, "HEAD", &head
) ||
4686 !(commit
= lookup_commit(r
, &head
)) ||
4687 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4688 fprintf(stderr
, _("Stopped at HEAD\n"));
4690 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4691 free_message(commit
, &message
);
4697 static int reread_todo_if_changed(struct repository
*r
,
4698 struct todo_list
*todo_list
,
4699 struct replay_opts
*opts
)
4702 struct strbuf buf
= STRBUF_INIT
;
4704 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4706 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4707 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4708 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4709 /* Reread the todo file if it has changed. */
4710 todo_list_release(todo_list
);
4711 if (read_populate_todo(r
, todo_list
, opts
))
4712 return -1; /* message was printed */
4713 /* `current` will be incremented on return */
4714 todo_list
->current
= -1;
4716 strbuf_release(&buf
);
4721 static const char rescheduled_advice
[] =
4722 N_("Could not execute the todo command\n"
4726 "It has been rescheduled; To edit the command before continuing, please\n"
4727 "edit the todo list first:\n"
4729 " git rebase --edit-todo\n"
4730 " git rebase --continue\n");
4732 static int pick_one_commit(struct repository
*r
,
4733 struct todo_list
*todo_list
,
4734 struct replay_opts
*opts
,
4735 int *check_todo
, int* reschedule
)
4738 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4739 const char *arg
= todo_item_get_arg(todo_list
, item
);
4740 if (is_rebase_i(opts
))
4741 opts
->reflog_message
= reflog_message(
4742 opts
, command_to_string(item
->command
), NULL
);
4744 res
= do_pick_commit(r
, item
, opts
, is_final_fixup(todo_list
),
4746 if (is_rebase_i(opts
) && res
< 0) {
4751 if (item
->command
== TODO_EDIT
) {
4752 struct commit
*commit
= item
->commit
;
4756 fprintf(stderr
, _("Stopped at %s... %.*s\n"),
4757 short_commit_name(r
, commit
), item
->arg_len
, arg
);
4759 return error_with_patch(r
, commit
,
4760 arg
, item
->arg_len
, opts
, res
, !res
);
4762 if (is_rebase_i(opts
) && !res
)
4763 record_in_rewritten(&item
->commit
->object
.oid
,
4764 peek_command(todo_list
, 1));
4765 if (res
&& is_fixup(item
->command
)) {
4768 return error_failed_squash(r
, item
->commit
, opts
,
4769 item
->arg_len
, arg
);
4770 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4772 struct object_id oid
;
4775 * If we are rewording and have either
4776 * fast-forwarded already, or are about to
4777 * create a new root commit, we want to amend,
4778 * otherwise we do not.
4780 if (item
->command
== TODO_REWORD
&&
4781 !repo_get_oid(r
, "HEAD", &oid
) &&
4782 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4783 (opts
->have_squash_onto
&&
4784 oideq(&opts
->squash_onto
, &oid
))))
4787 return res
| error_with_patch(r
, item
->commit
,
4788 arg
, item
->arg_len
, opts
,
4794 static int pick_commits(struct repository
*r
,
4795 struct todo_list
*todo_list
,
4796 struct replay_opts
*opts
)
4798 int res
= 0, reschedule
= 0;
4800 opts
->reflog_message
= sequencer_reflog_action(opts
);
4802 assert(!(opts
->signoff
|| opts
->no_commit
||
4803 opts
->record_origin
|| should_edit(opts
) ||
4804 opts
->committer_date_is_author_date
||
4805 opts
->ignore_date
));
4806 if (read_and_refresh_cache(r
, opts
))
4809 unlink(rebase_path_message());
4810 unlink(rebase_path_stopped_sha());
4811 unlink(rebase_path_amend());
4812 unlink(rebase_path_patch());
4814 while (todo_list
->current
< todo_list
->nr
) {
4815 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4816 const char *arg
= todo_item_get_arg(todo_list
, item
);
4819 if (save_todo(todo_list
, opts
, reschedule
))
4821 if (is_rebase_i(opts
)) {
4822 if (item
->command
!= TODO_COMMENT
) {
4823 FILE *f
= fopen(rebase_path_msgnum(), "w");
4825 todo_list
->done_nr
++;
4828 fprintf(f
, "%d\n", todo_list
->done_nr
);
4832 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4834 todo_list
->total_nr
,
4835 opts
->verbose
? "\n" : "\r");
4837 unlink(rebase_path_author_script());
4838 unlink(git_path_merge_head(r
));
4839 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
4840 NULL
, REF_NO_DEREF
);
4841 refs_delete_ref(get_main_ref_store(r
), "", "REBASE_HEAD",
4842 NULL
, REF_NO_DEREF
);
4844 if (item
->command
== TODO_BREAK
) {
4847 return stopped_at_head(r
);
4850 if (item
->command
<= TODO_SQUASH
) {
4851 res
= pick_one_commit(r
, todo_list
, opts
, &check_todo
,
4853 if (!res
&& item
->command
== TODO_EDIT
)
4855 } else if (item
->command
== TODO_EXEC
) {
4856 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4857 int saved
= *end_of_arg
;
4862 res
= do_exec(r
, arg
);
4863 *end_of_arg
= saved
;
4866 if (opts
->reschedule_failed_exec
)
4870 } else if (item
->command
== TODO_LABEL
) {
4871 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4873 } else if (item
->command
== TODO_RESET
) {
4874 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4876 } else if (item
->command
== TODO_MERGE
) {
4877 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4878 item
->flags
, &check_todo
, opts
)) < 0)
4880 else if (item
->commit
)
4881 record_in_rewritten(&item
->commit
->object
.oid
,
4882 peek_command(todo_list
, 1));
4884 /* failed with merge conflicts */
4885 return error_with_patch(r
, item
->commit
,
4888 } else if (item
->command
== TODO_UPDATE_REF
) {
4889 struct strbuf ref
= STRBUF_INIT
;
4890 strbuf_add(&ref
, arg
, item
->arg_len
);
4891 if ((res
= do_update_ref(r
, ref
.buf
)))
4893 strbuf_release(&ref
);
4894 } else if (!is_noop(item
->command
))
4895 return error(_("unknown command %d"), item
->command
);
4898 advise(_(rescheduled_advice
),
4899 get_item_line_length(todo_list
,
4900 todo_list
->current
),
4901 get_item_line(todo_list
, todo_list
->current
));
4902 if (save_todo(todo_list
, opts
, reschedule
))
4905 write_rebase_head(&item
->commit
->object
.oid
);
4906 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4907 reread_todo_if_changed(r
, todo_list
, opts
)) {
4914 todo_list
->current
++;
4917 if (is_rebase_i(opts
)) {
4918 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4921 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4922 starts_with(head_ref
.buf
, "refs/")) {
4924 struct object_id head
, orig
;
4927 if (repo_get_oid(r
, "HEAD", &head
)) {
4928 res
= error(_("cannot read HEAD"));
4930 strbuf_release(&head_ref
);
4931 strbuf_release(&buf
);
4934 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4935 get_oid_hex(buf
.buf
, &orig
)) {
4936 res
= error(_("could not read orig-head"));
4937 goto cleanup_head_ref
;
4940 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4941 res
= error(_("could not read 'onto'"));
4942 goto cleanup_head_ref
;
4944 msg
= reflog_message(opts
, "finish", "%s onto %s",
4945 head_ref
.buf
, buf
.buf
);
4946 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4947 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4948 res
= error(_("could not update %s"),
4950 goto cleanup_head_ref
;
4952 msg
= reflog_message(opts
, "finish", "returning to %s",
4954 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4955 res
= error(_("could not update HEAD to %s"),
4957 goto cleanup_head_ref
;
4962 if (opts
->verbose
) {
4963 struct rev_info log_tree_opt
;
4964 struct object_id orig
, head
;
4966 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4967 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4968 log_tree_opt
.diff
= 1;
4969 log_tree_opt
.diffopt
.output_format
=
4970 DIFF_FORMAT_DIFFSTAT
;
4971 log_tree_opt
.disable_stdin
= 1;
4973 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4974 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4975 !repo_get_oid(r
, "HEAD", &head
)) {
4976 diff_tree_oid(&orig
, &head
, "",
4977 &log_tree_opt
.diffopt
);
4978 log_tree_diff_flush(&log_tree_opt
);
4980 release_revisions(&log_tree_opt
);
4982 flush_rewritten_pending();
4983 if (!stat(rebase_path_rewritten_list(), &st
) &&
4985 struct child_process child
= CHILD_PROCESS_INIT
;
4986 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4988 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4990 strvec_push(&child
.args
, "notes");
4991 strvec_push(&child
.args
, "copy");
4992 strvec_push(&child
.args
, "--for-rewrite=rebase");
4993 /* we don't care if this copying failed */
4994 run_command(&child
);
4996 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4997 strvec_push(&hook_opt
.args
, "rebase");
4998 run_hooks_opt("post-rewrite", &hook_opt
);
5000 apply_autostash(rebase_path_autostash());
5006 _("Successfully rebased and updated %s.\n"),
5010 strbuf_release(&buf
);
5011 strbuf_release(&head_ref
);
5013 if (do_update_refs(r
, opts
->quiet
))
5018 * Sequence of picks finished successfully; cleanup by
5019 * removing the .git/sequencer directory
5021 return sequencer_remove_state(opts
);
5024 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
5026 struct child_process cmd
= CHILD_PROCESS_INIT
;
5028 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
5029 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
5030 return error(_("no cherry-pick or revert in progress"));
5033 strvec_push(&cmd
.args
, "commit");
5036 * continue_single_pick() handles the case of recovering from a
5037 * conflict. should_edit() doesn't handle that case; for a conflict,
5038 * we want to edit if the user asked for it, or if they didn't specify
5039 * and stdin is a tty.
5041 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
5043 * Include --cleanup=strip as well because we don't want the
5044 * "# Conflicts:" messages.
5046 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
5048 return run_command(&cmd
);
5051 static int commit_staged_changes(struct repository
*r
,
5052 struct replay_opts
*opts
,
5053 struct todo_list
*todo_list
)
5055 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
5056 unsigned int final_fixup
= 0, is_clean
;
5058 if (has_unstaged_changes(r
, 1))
5059 return error(_("cannot rebase: You have unstaged changes."));
5061 is_clean
= !has_uncommitted_changes(r
, 0);
5063 if (!is_clean
&& !file_exists(rebase_path_message())) {
5064 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
5066 return error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
5068 if (file_exists(rebase_path_amend())) {
5069 struct strbuf rev
= STRBUF_INIT
;
5070 struct object_id head
, to_amend
;
5072 if (repo_get_oid(r
, "HEAD", &head
))
5073 return error(_("cannot amend non-existing commit"));
5074 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
5075 return error(_("invalid file: '%s'"), rebase_path_amend());
5076 if (get_oid_hex(rev
.buf
, &to_amend
))
5077 return error(_("invalid contents: '%s'"),
5078 rebase_path_amend());
5079 if (!is_clean
&& !oideq(&head
, &to_amend
))
5080 return error(_("\nYou have uncommitted changes in your "
5081 "working tree. Please, commit them\n"
5082 "first and then run 'git rebase "
5083 "--continue' again."));
5085 * When skipping a failed fixup/squash, we need to edit the
5086 * commit message, the current fixup list and count, and if it
5087 * was the last fixup/squash in the chain, we need to clean up
5088 * the commit message and if there was a squash, let the user
5091 if (!is_clean
|| !opts
->current_fixup_count
)
5092 ; /* this is not the final fixup */
5093 else if (!oideq(&head
, &to_amend
) ||
5094 !file_exists(rebase_path_stopped_sha())) {
5095 /* was a final fixup or squash done manually? */
5096 if (!is_fixup(peek_command(todo_list
, 0))) {
5097 unlink(rebase_path_fixup_msg());
5098 unlink(rebase_path_squash_msg());
5099 unlink(rebase_path_current_fixups());
5100 strbuf_reset(&opts
->current_fixups
);
5101 opts
->current_fixup_count
= 0;
5104 /* we are in a fixup/squash chain */
5105 const char *p
= opts
->current_fixups
.buf
;
5106 int len
= opts
->current_fixups
.len
;
5108 opts
->current_fixup_count
--;
5110 BUG("Incorrect current_fixups:\n%s", p
);
5111 while (len
&& p
[len
- 1] != '\n')
5113 strbuf_setlen(&opts
->current_fixups
, len
);
5114 if (write_message(p
, len
, rebase_path_current_fixups(),
5116 return error(_("could not write file: '%s'"),
5117 rebase_path_current_fixups());
5120 * If a fixup/squash in a fixup/squash chain failed, the
5121 * commit message is already correct, no need to commit
5124 * Only if it is the final command in the fixup/squash
5125 * chain, and only if the chain is longer than a single
5126 * fixup/squash command (which was just skipped), do we
5127 * actually need to re-commit with a cleaned up commit
5130 if (opts
->current_fixup_count
> 0 &&
5131 !is_fixup(peek_command(todo_list
, 0))) {
5134 * If there was not a single "squash" in the
5135 * chain, we only need to clean up the commit
5136 * message, no need to bother the user with
5137 * opening the commit message in the editor.
5139 if (!starts_with(p
, "squash ") &&
5140 !strstr(p
, "\nsquash "))
5141 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5142 } else if (is_fixup(peek_command(todo_list
, 0))) {
5144 * We need to update the squash message to skip
5145 * the latest commit message.
5148 struct commit
*commit
;
5150 const char *path
= rebase_path_squash_msg();
5151 const char *encoding
= get_commit_output_encoding();
5153 if (parse_head(r
, &commit
))
5154 return error(_("could not parse HEAD"));
5156 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5158 res
= error(_("could not parse commit %s"),
5159 oid_to_hex(&commit
->object
.oid
));
5160 goto unuse_commit_buffer
;
5162 find_commit_subject(p
, &msg
);
5163 if (write_message(msg
, strlen(msg
), path
, 0)) {
5164 res
= error(_("could not write file: "
5166 goto unuse_commit_buffer
;
5168 unuse_commit_buffer
:
5169 repo_unuse_commit_buffer(r
, commit
, p
);
5175 strbuf_release(&rev
);
5180 if (refs_ref_exists(get_main_ref_store(r
),
5181 "CHERRY_PICK_HEAD") &&
5182 refs_delete_ref(get_main_ref_store(r
), "",
5183 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
))
5184 return error(_("could not remove CHERRY_PICK_HEAD"));
5185 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5186 return error_errno(_("could not remove '%s'"),
5187 git_path_merge_msg(r
));
5192 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5194 return error(_("could not commit staged changes."));
5195 unlink(rebase_path_amend());
5196 unlink(git_path_merge_head(r
));
5197 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
5198 NULL
, REF_NO_DEREF
);
5200 unlink(rebase_path_fixup_msg());
5201 unlink(rebase_path_squash_msg());
5203 if (opts
->current_fixup_count
> 0) {
5205 * Whether final fixup or not, we just cleaned up the commit
5208 unlink(rebase_path_current_fixups());
5209 strbuf_reset(&opts
->current_fixups
);
5210 opts
->current_fixup_count
= 0;
5215 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5217 struct todo_list todo_list
= TODO_LIST_INIT
;
5220 if (read_and_refresh_cache(r
, opts
))
5223 if (read_populate_opts(opts
))
5225 if (is_rebase_i(opts
)) {
5226 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5227 goto release_todo_list
;
5229 if (file_exists(rebase_path_dropped())) {
5230 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5231 goto release_todo_list
;
5233 unlink(rebase_path_dropped());
5236 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5237 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5239 goto release_todo_list
;
5241 } else if (!file_exists(get_todo_path(opts
)))
5242 return continue_single_pick(r
, opts
);
5243 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5244 goto release_todo_list
;
5246 if (!is_rebase_i(opts
)) {
5247 /* Verify that the conflict has been resolved */
5248 if (refs_ref_exists(get_main_ref_store(r
),
5249 "CHERRY_PICK_HEAD") ||
5250 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5251 res
= continue_single_pick(r
, opts
);
5253 goto release_todo_list
;
5255 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5256 res
= error_dirty_index(r
, opts
);
5257 goto release_todo_list
;
5259 todo_list
.current
++;
5260 } else if (file_exists(rebase_path_stopped_sha())) {
5261 struct strbuf buf
= STRBUF_INIT
;
5262 struct object_id oid
;
5264 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5265 READ_ONELINER_SKIP_IF_EMPTY
) &&
5266 !get_oid_hex(buf
.buf
, &oid
))
5267 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5268 strbuf_release(&buf
);
5271 res
= pick_commits(r
, &todo_list
, opts
);
5273 todo_list_release(&todo_list
);
5277 static int single_pick(struct repository
*r
,
5278 struct commit
*cmit
,
5279 struct replay_opts
*opts
)
5282 struct todo_item item
;
5284 item
.command
= opts
->action
== REPLAY_PICK
?
5285 TODO_PICK
: TODO_REVERT
;
5288 opts
->reflog_message
= sequencer_reflog_action(opts
);
5289 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5292 int sequencer_pick_revisions(struct repository
*r
,
5293 struct replay_opts
*opts
)
5295 struct todo_list todo_list
= TODO_LIST_INIT
;
5296 struct object_id oid
;
5300 if (read_and_refresh_cache(r
, opts
))
5303 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5304 struct object_id oid
;
5305 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5307 /* This happens when using --stdin. */
5311 if (!repo_get_oid(r
, name
, &oid
)) {
5312 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5313 enum object_type type
= oid_object_info(r
,
5316 return error(_("%s: can't cherry-pick a %s"),
5317 name
, type_name(type
));
5320 return error(_("%s: bad revision"), name
);
5324 * If we were called as "git cherry-pick <commit>", just
5325 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5326 * REVERT_HEAD, and don't touch the sequencer state.
5327 * This means it is possible to cherry-pick in the middle
5328 * of a cherry-pick sequence.
5330 if (opts
->revs
->cmdline
.nr
== 1 &&
5331 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5332 opts
->revs
->no_walk
&&
5333 !opts
->revs
->cmdline
.rev
->flags
) {
5334 struct commit
*cmit
;
5335 if (prepare_revision_walk(opts
->revs
))
5336 return error(_("revision walk setup failed"));
5337 cmit
= get_revision(opts
->revs
);
5339 return error(_("empty commit set passed"));
5340 if (get_revision(opts
->revs
))
5341 BUG("unexpected extra commit from walk");
5342 return single_pick(r
, cmit
, opts
);
5346 * Start a new cherry-pick/ revert sequence; but
5347 * first, make sure that an existing one isn't in
5351 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5352 create_seq_dir(r
) < 0)
5354 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5355 return error(_("can't revert as initial commit"));
5356 if (save_head(oid_to_hex(&oid
)))
5358 if (save_opts(opts
))
5360 update_abort_safety_file();
5361 res
= pick_commits(r
, &todo_list
, opts
);
5362 todo_list_release(&todo_list
);
5366 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5368 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5369 struct strbuf sob
= STRBUF_INIT
;
5372 strbuf_addstr(&sob
, sign_off_header
);
5373 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5374 strbuf_addch(&sob
, '\n');
5377 strbuf_complete_line(msgbuf
);
5380 * If the whole message buffer is equal to the sob, pretend that we
5381 * found a conforming footer with a matching sob
5383 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5384 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5387 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5390 const char *append_newlines
= NULL
;
5391 size_t len
= msgbuf
->len
- ignore_footer
;
5395 * The buffer is completely empty. Leave foom for
5396 * the title and body to be filled in by the user.
5398 append_newlines
= "\n\n";
5399 } else if (len
== 1) {
5401 * Buffer contains a single newline. Add another
5402 * so that we leave room for the title and body.
5404 append_newlines
= "\n";
5405 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5407 * Buffer ends with a single newline. Add another
5408 * so that there is an empty line between the message
5411 append_newlines
= "\n";
5412 } /* else, the buffer already ends with two newlines. */
5414 if (append_newlines
)
5415 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5416 append_newlines
, strlen(append_newlines
));
5419 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5420 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5423 strbuf_release(&sob
);
5426 struct labels_entry
{
5427 struct hashmap_entry entry
;
5428 char label
[FLEX_ARRAY
];
5431 static int labels_cmp(const void *fndata UNUSED
,
5432 const struct hashmap_entry
*eptr
,
5433 const struct hashmap_entry
*entry_or_key
, const void *key
)
5435 const struct labels_entry
*a
, *b
;
5437 a
= container_of(eptr
, const struct labels_entry
, entry
);
5438 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5440 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5443 struct string_entry
{
5444 struct oidmap_entry entry
;
5445 char string
[FLEX_ARRAY
];
5448 struct label_state
{
5449 struct oidmap commit2label
;
5450 struct hashmap labels
;
5452 int max_label_length
;
5455 static const char *label_oid(struct object_id
*oid
, const char *label
,
5456 struct label_state
*state
)
5458 struct labels_entry
*labels_entry
;
5459 struct string_entry
*string_entry
;
5460 struct object_id dummy
;
5463 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5465 return string_entry
->string
;
5468 * For "uninteresting" commits, i.e. commits that are not to be
5469 * rebased, and which can therefore not be labeled, we use a unique
5470 * abbreviation of the commit name. This is slightly more complicated
5471 * than calling repo_find_unique_abbrev() because we also need to make
5472 * sure that the abbreviation does not conflict with any other
5475 * We disallow "interesting" commits to be labeled by a string that
5476 * is a valid full-length hash, to ensure that we always can find an
5477 * abbreviation for any uninteresting commit's names that does not
5478 * clash with any other label.
5480 strbuf_reset(&state
->buf
);
5484 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5485 label
= p
= state
->buf
.buf
;
5487 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5491 * We may need to extend the abbreviated hash so that there is
5492 * no conflicting label.
5494 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5495 size_t i
= strlen(p
) + 1;
5497 oid_to_hex_r(p
, oid
);
5498 for (; i
< the_hash_algo
->hexsz
; i
++) {
5501 if (!hashmap_get_from_hash(&state
->labels
,
5508 struct strbuf
*buf
= &state
->buf
;
5509 int label_is_utf8
= 1; /* start with this assumption */
5510 size_t max_len
= buf
->len
+ state
->max_label_length
;
5513 * Sanitize labels by replacing non-alpha-numeric characters
5514 * (including white-space ones) by dashes, as they might be
5515 * illegal in file names (and hence in ref names).
5517 * Note that we retain non-ASCII UTF-8 characters (identified
5518 * via the most significant bit). They should be all acceptable
5521 * As we will use the labels as names of (loose) refs, it is
5522 * vital that the name not be longer than the maximum component
5523 * size of the file system (`NAME_MAX`). We are careful to
5524 * truncate the label accordingly, allowing for the `.lock`
5525 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5526 * truncating in the middle of a character).
5528 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5529 if (isalnum(*label
) ||
5530 (!label_is_utf8
&& (*label
& 0x80)))
5531 strbuf_addch(buf
, *label
);
5532 else if (*label
& 0x80) {
5533 const char *p
= label
;
5535 utf8_width(&p
, NULL
);
5537 if (buf
->len
+ (p
- label
) > max_len
)
5539 strbuf_add(buf
, label
, p
- label
);
5543 strbuf_addch(buf
, *label
);
5545 /* avoid leading dash and double-dashes */
5546 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5547 strbuf_addch(buf
, '-');
5549 strbuf_addstr(buf
, "rev-");
5550 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5554 if ((buf
->len
== the_hash_algo
->hexsz
&&
5555 !get_oid_hex(label
, &dummy
)) ||
5556 (buf
->len
== 1 && *label
== '#') ||
5557 hashmap_get_from_hash(&state
->labels
,
5558 strihash(label
), label
)) {
5560 * If the label already exists, or if the label is a
5561 * valid full OID, or the label is a '#' (which we use
5562 * as a separator between merge heads and oneline), we
5563 * append a dash and a number to make it unique.
5565 size_t len
= buf
->len
;
5567 for (i
= 2; ; i
++) {
5568 strbuf_setlen(buf
, len
);
5569 strbuf_addf(buf
, "-%d", i
);
5570 if (!hashmap_get_from_hash(&state
->labels
,
5580 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5581 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5582 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5584 FLEX_ALLOC_STR(string_entry
, string
, label
);
5585 oidcpy(&string_entry
->entry
.oid
, oid
);
5586 oidmap_put(&state
->commit2label
, string_entry
);
5588 return string_entry
->string
;
5591 static int make_script_with_merges(struct pretty_print_context
*pp
,
5592 struct rev_info
*revs
, struct strbuf
*out
,
5595 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5596 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5597 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5598 int skipped_commit
= 0;
5599 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5600 struct strbuf label
= STRBUF_INIT
;
5601 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5602 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5603 struct commit
*commit
;
5604 struct oidmap commit2todo
= OIDMAP_INIT
;
5605 struct string_entry
*entry
;
5606 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5607 shown
= OIDSET_INIT
;
5608 struct label_state state
=
5609 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5611 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5612 const char *cmd_pick
= abbr
? "p" : "pick",
5613 *cmd_label
= abbr
? "l" : "label",
5614 *cmd_reset
= abbr
? "t" : "reset",
5615 *cmd_merge
= abbr
? "m" : "merge";
5617 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5619 oidmap_init(&commit2todo
, 0);
5620 oidmap_init(&state
.commit2label
, 0);
5621 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5622 strbuf_init(&state
.buf
, 32);
5624 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5625 struct labels_entry
*onto_label_entry
;
5626 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5627 FLEX_ALLOC_STR(entry
, string
, "onto");
5628 oidcpy(&entry
->entry
.oid
, oid
);
5629 oidmap_put(&state
.commit2label
, entry
);
5631 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5632 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5633 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5638 * - get onelines for all commits
5639 * - gather all branch tips (i.e. 2nd or later parents of merges)
5640 * - label all branch tips
5642 while ((commit
= get_revision(revs
))) {
5643 struct commit_list
*to_merge
;
5644 const char *p1
, *p2
;
5645 struct object_id
*oid
;
5648 tail
= &commit_list_insert(commit
, tail
)->next
;
5649 oidset_insert(&interesting
, &commit
->object
.oid
);
5651 is_empty
= is_original_commit_empty(commit
);
5652 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5653 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5654 warning(_("skipped previously applied commit %s"),
5655 short_commit_name(the_repository
, commit
));
5659 if (is_empty
&& !keep_empty
)
5662 strbuf_reset(&oneline
);
5663 pretty_print_commit(pp
, commit
, &oneline
);
5665 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5667 /* non-merge commit: easy case */
5669 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5670 oid_to_hex(&commit
->object
.oid
),
5673 strbuf_addf(&buf
, " %c empty",
5676 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5677 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5678 oidmap_put(&commit2todo
, entry
);
5683 /* Create a label */
5684 strbuf_reset(&label
);
5685 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5686 (p1
= strchr(p1
, '\'')) &&
5687 (p2
= strchr(++p1
, '\'')))
5688 strbuf_add(&label
, p1
, p2
- p1
);
5689 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5691 (p1
= strstr(p1
, " from ")))
5692 strbuf_addstr(&label
, p1
+ strlen(" from "));
5694 strbuf_addbuf(&label
, &oneline
);
5697 strbuf_addf(&buf
, "%s -C %s",
5698 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5700 /* label the tips of merged branches */
5701 for (; to_merge
; to_merge
= to_merge
->next
) {
5702 oid
= &to_merge
->item
->object
.oid
;
5703 strbuf_addch(&buf
, ' ');
5705 if (!oidset_contains(&interesting
, oid
)) {
5706 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5711 tips_tail
= &commit_list_insert(to_merge
->item
,
5714 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5716 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5718 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5719 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5720 oidmap_put(&commit2todo
, entry
);
5723 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5724 _("use --reapply-cherry-picks to include skipped commits"));
5728 * - label branch points
5729 * - add HEAD to the branch tips
5731 for (iter
= commits
; iter
; iter
= iter
->next
) {
5732 struct commit_list
*parent
= iter
->item
->parents
;
5733 for (; parent
; parent
= parent
->next
) {
5734 struct object_id
*oid
= &parent
->item
->object
.oid
;
5735 if (!oidset_contains(&interesting
, oid
))
5737 if (oidset_insert(&child_seen
, oid
))
5738 label_oid(oid
, "branch-point", &state
);
5741 /* Add HEAD as implicit "tip of branch" */
5743 tips_tail
= &commit_list_insert(iter
->item
,
5748 * Third phase: output the todo list. This is a bit tricky, as we
5749 * want to avoid jumping back and forth between revisions. To
5750 * accomplish that goal, we walk backwards from the branch tips,
5751 * gathering commits not yet shown, reversing the list on the fly,
5752 * then outputting that list (labeling revisions as needed).
5754 strbuf_addf(out
, "%s onto\n", cmd_label
);
5755 for (iter
= tips
; iter
; iter
= iter
->next
) {
5756 struct commit_list
*list
= NULL
, *iter2
;
5758 commit
= iter
->item
;
5759 if (oidset_contains(&shown
, &commit
->object
.oid
))
5761 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5764 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5766 strbuf_addch(out
, '\n');
5768 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5769 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5770 commit_list_insert(commit
, &list
);
5771 if (!commit
->parents
) {
5775 commit
= commit
->parents
->item
;
5779 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5780 rebase_cousins
|| root_with_onto
?
5781 "onto" : "[new root]");
5783 const char *to
= NULL
;
5785 entry
= oidmap_get(&state
.commit2label
,
5786 &commit
->object
.oid
);
5789 else if (!rebase_cousins
)
5790 to
= label_oid(&commit
->object
.oid
, NULL
,
5793 if (!to
|| !strcmp(to
, "onto"))
5794 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5796 strbuf_reset(&oneline
);
5797 pretty_print_commit(pp
, commit
, &oneline
);
5798 strbuf_addf(out
, "%s %s # %s\n",
5799 cmd_reset
, to
, oneline
.buf
);
5803 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5804 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5805 entry
= oidmap_get(&commit2todo
, oid
);
5806 /* only show if not already upstream */
5808 strbuf_addf(out
, "%s\n", entry
->string
);
5809 entry
= oidmap_get(&state
.commit2label
, oid
);
5811 strbuf_addf(out
, "%s %s\n",
5812 cmd_label
, entry
->string
);
5813 oidset_insert(&shown
, oid
);
5816 free_commit_list(list
);
5819 free_commit_list(commits
);
5820 free_commit_list(tips
);
5822 strbuf_release(&label
);
5823 strbuf_release(&oneline
);
5824 strbuf_release(&buf
);
5826 oidmap_free(&commit2todo
, 1);
5827 oidmap_free(&state
.commit2label
, 1);
5828 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5829 strbuf_release(&state
.buf
);
5834 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5835 const char **argv
, unsigned flags
)
5837 char *format
= NULL
;
5838 struct pretty_print_context pp
= {0};
5839 struct rev_info revs
;
5840 struct commit
*commit
;
5841 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5842 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5843 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5844 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5845 int skipped_commit
= 0;
5848 repo_init_revisions(r
, &revs
, NULL
);
5849 revs
.verbose_header
= 1;
5851 revs
.max_parents
= 1;
5852 revs
.cherry_mark
= !reapply_cherry_picks
;
5855 revs
.right_only
= 1;
5856 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5857 revs
.topo_order
= 1;
5859 revs
.pretty_given
= 1;
5860 git_config_get_string("rebase.instructionFormat", &format
);
5861 if (!format
|| !*format
) {
5863 format
= xstrdup("%s");
5865 get_commit_format(format
, &revs
);
5867 pp
.fmt
= revs
.commit_format
;
5868 pp
.output_encoding
= get_log_output_encoding();
5870 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5871 ret
= error(_("make_script: unhandled options"));
5875 if (prepare_revision_walk(&revs
) < 0) {
5876 ret
= error(_("make_script: error preparing revisions"));
5880 if (rebase_merges
) {
5881 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5885 while ((commit
= get_revision(&revs
))) {
5886 int is_empty
= is_original_commit_empty(commit
);
5888 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5889 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5890 warning(_("skipped previously applied commit %s"),
5891 short_commit_name(r
, commit
));
5895 if (is_empty
&& !keep_empty
)
5897 strbuf_addf(out
, "%s %s ", insn
,
5898 oid_to_hex(&commit
->object
.oid
));
5899 pretty_print_commit(&pp
, commit
, out
);
5901 strbuf_addf(out
, " %c empty", comment_line_char
);
5902 strbuf_addch(out
, '\n');
5905 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5906 _("use --reapply-cherry-picks to include skipped commits"));
5908 release_revisions(&revs
);
5913 * Add commands after pick and (series of) squash/fixup commands
5916 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5917 struct string_list
*commands
)
5919 struct strbuf
*buf
= &todo_list
->buf
;
5920 size_t base_offset
= buf
->len
;
5921 int i
, insert
, nr
= 0, alloc
= 0;
5922 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5924 CALLOC_ARRAY(base_items
, commands
->nr
);
5925 for (i
= 0; i
< commands
->nr
; i
++) {
5926 size_t command_len
= strlen(commands
->items
[i
].string
);
5928 strbuf_addstr(buf
, commands
->items
[i
].string
);
5929 strbuf_addch(buf
, '\n');
5931 base_items
[i
].command
= TODO_EXEC
;
5932 base_items
[i
].offset_in_buf
= base_offset
;
5933 base_items
[i
].arg_offset
= base_offset
;
5934 base_items
[i
].arg_len
= command_len
;
5936 base_offset
+= command_len
+ 1;
5940 * Insert <commands> after every pick. Here, fixup/squash chains
5941 * are considered part of the pick, so we insert the commands *after*
5942 * those chains if there are any.
5944 * As we insert the exec commands immediately after rearranging
5945 * any fixups and before the user edits the list, a fixup chain
5946 * can never contain comments (any comments are empty picks that
5947 * have been commented out because the user did not specify
5948 * --keep-empty). So, it is safe to insert an exec command
5949 * without looking at the command following a comment.
5952 for (i
= 0; i
< todo_list
->nr
; i
++) {
5953 enum todo_command command
= todo_list
->items
[i
].command
;
5954 if (insert
&& !is_fixup(command
)) {
5955 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5956 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5962 ALLOC_GROW(items
, nr
+ 1, alloc
);
5963 items
[nr
++] = todo_list
->items
[i
];
5965 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5969 /* insert or append final <commands> */
5971 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5972 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5977 FREE_AND_NULL(todo_list
->items
);
5978 todo_list
->items
= items
;
5980 todo_list
->alloc
= alloc
;
5983 static void todo_list_to_strbuf(struct repository
*r
,
5984 struct todo_list
*todo_list
,
5985 struct strbuf
*buf
, int num
, unsigned flags
)
5987 struct todo_item
*item
;
5988 int i
, max
= todo_list
->nr
;
5990 if (num
> 0 && num
< max
)
5993 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5996 /* if the item is not a command write it and continue */
5997 if (item
->command
>= TODO_COMMENT
) {
5998 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5999 todo_item_get_arg(todo_list
, item
));
6003 /* add command to the buffer */
6004 cmd
= command_to_char(item
->command
);
6005 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
6006 strbuf_addch(buf
, cmd
);
6008 strbuf_addstr(buf
, command_to_string(item
->command
));
6012 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
6013 short_commit_name(r
, item
->commit
) :
6014 oid_to_hex(&item
->commit
->object
.oid
);
6016 if (item
->command
== TODO_FIXUP
) {
6017 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
6018 strbuf_addstr(buf
, " -c");
6019 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
6020 strbuf_addstr(buf
, " -C");
6024 if (item
->command
== TODO_MERGE
) {
6025 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
6026 strbuf_addstr(buf
, " -c");
6028 strbuf_addstr(buf
, " -C");
6031 strbuf_addf(buf
, " %s", oid
);
6034 /* add all the rest */
6036 strbuf_addch(buf
, '\n');
6038 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
6039 todo_item_get_arg(todo_list
, item
));
6043 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
6044 const char *file
, const char *shortrevisions
,
6045 const char *shortonto
, int num
, unsigned flags
)
6048 struct strbuf buf
= STRBUF_INIT
;
6050 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
6051 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
6052 append_todo_help(count_commands(todo_list
),
6053 shortrevisions
, shortonto
, &buf
);
6055 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
6056 strbuf_release(&buf
);
6061 /* skip picking commits whose parents are unchanged */
6062 static int skip_unnecessary_picks(struct repository
*r
,
6063 struct todo_list
*todo_list
,
6064 struct object_id
*base_oid
)
6066 struct object_id
*parent_oid
;
6069 for (i
= 0; i
< todo_list
->nr
; i
++) {
6070 struct todo_item
*item
= todo_list
->items
+ i
;
6072 if (item
->command
>= TODO_NOOP
)
6074 if (item
->command
!= TODO_PICK
)
6076 if (repo_parse_commit(r
, item
->commit
)) {
6077 return error(_("could not parse commit '%s'"),
6078 oid_to_hex(&item
->commit
->object
.oid
));
6080 if (!item
->commit
->parents
)
6081 break; /* root commit */
6082 if (item
->commit
->parents
->next
)
6083 break; /* merge commit */
6084 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
6085 if (!oideq(parent_oid
, base_oid
))
6087 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6090 const char *done_path
= rebase_path_done();
6092 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6093 error_errno(_("could not write to '%s'"), done_path
);
6097 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6099 todo_list
->current
= 0;
6100 todo_list
->done_nr
+= i
;
6102 if (is_fixup(peek_command(todo_list
, 0)))
6103 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6109 struct todo_add_branch_context
{
6110 struct todo_item
*items
;
6114 struct commit
*commit
;
6115 struct string_list refs_to_oids
;
6118 static int add_decorations_to_list(const struct commit
*commit
,
6119 struct todo_add_branch_context
*ctx
)
6121 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6122 const char *head_ref
= resolve_ref_unsafe("HEAD",
6123 RESOLVE_REF_READING
,
6127 while (decoration
) {
6128 struct todo_item
*item
;
6130 size_t base_offset
= ctx
->buf
->len
;
6133 * If the branch is the current HEAD, then it will be
6134 * updated by the default rebase behavior.
6136 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6137 decoration
= decoration
->next
;
6141 ALLOC_GROW(ctx
->items
,
6144 item
= &ctx
->items
[ctx
->items_nr
];
6145 memset(item
, 0, sizeof(*item
));
6147 /* If the branch is checked out, then leave a comment instead. */
6148 if ((path
= branch_checked_out(decoration
->name
))) {
6149 item
->command
= TODO_COMMENT
;
6150 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6151 decoration
->name
, path
);
6153 struct string_list_item
*sti
;
6154 item
->command
= TODO_UPDATE_REF
;
6155 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6157 sti
= string_list_insert(&ctx
->refs_to_oids
,
6159 sti
->util
= init_update_ref_record(decoration
->name
);
6162 item
->offset_in_buf
= base_offset
;
6163 item
->arg_offset
= base_offset
;
6164 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6167 decoration
= decoration
->next
;
6174 * For each 'pick' command, find out if the commit has a decoration in
6175 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6177 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6180 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6181 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6182 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6183 struct decoration_filter decoration_filter
= {
6184 .include_ref_pattern
= &decorate_refs_include
,
6185 .exclude_ref_pattern
= &decorate_refs_exclude
,
6186 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6188 struct todo_add_branch_context ctx
= {
6189 .buf
= &todo_list
->buf
,
6190 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6193 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6194 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6196 string_list_append(&decorate_refs_include
, "refs/heads/");
6197 load_ref_decorations(&decoration_filter
, 0);
6199 for (i
= 0; i
< todo_list
->nr
; ) {
6200 struct todo_item
*item
= &todo_list
->items
[i
];
6202 /* insert ith item into new list */
6203 ALLOC_GROW(ctx
.items
,
6207 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6210 ctx
.commit
= item
->commit
;
6211 add_decorations_to_list(item
->commit
, &ctx
);
6215 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6217 string_list_clear(&ctx
.refs_to_oids
, 1);
6220 /* we failed, so clean up the new list. */
6225 free(todo_list
->items
);
6226 todo_list
->items
= ctx
.items
;
6227 todo_list
->nr
= ctx
.items_nr
;
6228 todo_list
->alloc
= ctx
.items_alloc
;
6233 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6234 const char *shortrevisions
, const char *onto_name
,
6235 struct commit
*onto
, const struct object_id
*orig_head
,
6236 struct string_list
*commands
, unsigned autosquash
,
6237 unsigned update_refs
,
6238 struct todo_list
*todo_list
)
6240 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6241 const char *todo_file
= rebase_path_todo();
6242 struct todo_list new_todo
= TODO_LIST_INIT
;
6243 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6244 struct object_id oid
= onto
->object
.oid
;
6247 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6250 if (buf
->len
== 0) {
6251 struct todo_item
*item
= append_new_todo(todo_list
);
6252 item
->command
= TODO_NOOP
;
6253 item
->commit
= NULL
;
6254 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6257 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6260 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6264 todo_list_add_exec_commands(todo_list
, commands
);
6266 if (count_commands(todo_list
) == 0) {
6267 apply_autostash(rebase_path_autostash());
6268 sequencer_remove_state(opts
);
6270 return error(_("nothing to do"));
6273 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6277 else if (res
== -2) {
6278 apply_autostash(rebase_path_autostash());
6279 sequencer_remove_state(opts
);
6282 } else if (res
== -3) {
6283 apply_autostash(rebase_path_autostash());
6284 sequencer_remove_state(opts
);
6285 todo_list_release(&new_todo
);
6287 return error(_("nothing to do"));
6288 } else if (res
== -4) {
6289 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6290 todo_list_release(&new_todo
);
6295 /* Expand the commit IDs */
6296 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6297 strbuf_swap(&new_todo
.buf
, &buf2
);
6298 strbuf_release(&buf2
);
6299 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6300 new_todo
.total_nr
= 0;
6301 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6302 BUG("invalid todo list after expanding IDs:\n%s",
6305 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6306 todo_list_release(&new_todo
);
6307 return error(_("could not skip unnecessary pick commands"));
6310 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6311 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6312 todo_list_release(&new_todo
);
6313 return error_errno(_("could not write '%s'"), todo_file
);
6318 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6321 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6324 todo_list_write_total_nr(&new_todo
);
6325 res
= pick_commits(r
, &new_todo
, opts
);
6328 todo_list_release(&new_todo
);
6333 struct subject2item_entry
{
6334 struct hashmap_entry entry
;
6336 char subject
[FLEX_ARRAY
];
6339 static int subject2item_cmp(const void *fndata UNUSED
,
6340 const struct hashmap_entry
*eptr
,
6341 const struct hashmap_entry
*entry_or_key
,
6344 const struct subject2item_entry
*a
, *b
;
6346 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6347 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6349 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6352 define_commit_slab(commit_todo_item
, struct todo_item
*);
6354 static int skip_fixupish(const char *subject
, const char **p
) {
6355 return skip_prefix(subject
, "fixup! ", p
) ||
6356 skip_prefix(subject
, "amend! ", p
) ||
6357 skip_prefix(subject
, "squash! ", p
);
6361 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6362 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6363 * after the former, and change "pick" to "fixup"/"squash".
6365 * Note that if the config has specified a custom instruction format, each log
6366 * message will have to be retrieved from the commit (as the oneline in the
6367 * script cannot be trusted) in order to normalize the autosquash arrangement.
6369 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6371 struct hashmap subject2item
;
6372 int rearranged
= 0, *next
, *tail
, i
, nr
= 0;
6374 struct commit_todo_item commit_todo
;
6375 struct todo_item
*items
= NULL
;
6377 init_commit_todo_item(&commit_todo
);
6379 * The hashmap maps onelines to the respective todo list index.
6381 * If any items need to be rearranged, the next[i] value will indicate
6382 * which item was moved directly after the i'th.
6384 * In that case, last[i] will indicate the index of the latest item to
6385 * be moved to appear after the i'th.
6387 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6388 ALLOC_ARRAY(next
, todo_list
->nr
);
6389 ALLOC_ARRAY(tail
, todo_list
->nr
);
6390 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6391 for (i
= 0; i
< todo_list
->nr
; i
++) {
6392 struct strbuf buf
= STRBUF_INIT
;
6393 struct todo_item
*item
= todo_list
->items
+ i
;
6394 const char *commit_buffer
, *subject
, *p
;
6397 struct subject2item_entry
*entry
;
6399 next
[i
] = tail
[i
] = -1;
6400 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6405 if (is_fixup(item
->command
)) {
6406 clear_commit_todo_item(&commit_todo
);
6407 return error(_("the script was already rearranged."));
6410 repo_parse_commit(the_repository
, item
->commit
);
6411 commit_buffer
= repo_logmsg_reencode(the_repository
,
6414 find_commit_subject(commit_buffer
, &subject
);
6415 format_subject(&buf
, subject
, " ");
6416 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6417 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6419 if (skip_fixupish(subject
, &p
)) {
6420 struct commit
*commit2
;
6425 if (!skip_fixupish(p
, &p
))
6429 entry
= hashmap_get_entry_from_hash(&subject2item
,
6431 struct subject2item_entry
,
6434 /* found by title */
6436 else if (!strchr(p
, ' ') &&
6438 lookup_commit_reference_by_name(p
)) &&
6439 *commit_todo_item_at(&commit_todo
, commit2
))
6440 /* found by commit name */
6441 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6444 /* copy can be a prefix of the commit subject */
6445 for (i2
= 0; i2
< i
; i2
++)
6447 starts_with(subjects
[i2
], p
))
6455 if (starts_with(subject
, "fixup!")) {
6456 todo_list
->items
[i
].command
= TODO_FIXUP
;
6457 } else if (starts_with(subject
, "amend!")) {
6458 todo_list
->items
[i
].command
= TODO_FIXUP
;
6459 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6461 todo_list
->items
[i
].command
= TODO_SQUASH
;
6467 next
[i
] = next
[tail
[i2
]];
6471 } else if (!hashmap_get_from_hash(&subject2item
,
6472 strhash(subject
), subject
)) {
6473 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6475 hashmap_entry_init(&entry
->entry
,
6476 strhash(entry
->subject
));
6477 hashmap_put(&subject2item
, &entry
->entry
);
6480 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6484 ALLOC_ARRAY(items
, todo_list
->nr
);
6486 for (i
= 0; i
< todo_list
->nr
; i
++) {
6487 enum todo_command command
= todo_list
->items
[i
].command
;
6491 * Initially, all commands are 'pick's. If it is a
6492 * fixup or a squash now, we have rearranged it.
6494 if (is_fixup(command
))
6498 items
[nr
++] = todo_list
->items
[cur
];
6503 assert(nr
== todo_list
->nr
);
6504 todo_list
->alloc
= nr
;
6505 FREE_AND_NULL(todo_list
->items
);
6506 todo_list
->items
= items
;
6511 for (i
= 0; i
< todo_list
->nr
; i
++)
6514 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6516 clear_commit_todo_item(&commit_todo
);
6521 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6523 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6524 struct object_id cherry_pick_head
, rebase_head
;
6526 if (file_exists(git_path_seq_dir()))
6527 *whence
= FROM_CHERRY_PICK_MULTI
;
6528 if (file_exists(rebase_path()) &&
6529 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6530 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6531 oideq(&rebase_head
, &cherry_pick_head
))
6532 *whence
= FROM_REBASE_PICK
;
6534 *whence
= FROM_CHERRY_PICK_SINGLE
;
6542 int sequencer_get_update_refs_state(const char *wt_dir
,
6543 struct string_list
*refs
)
6547 struct strbuf ref
= STRBUF_INIT
;
6548 struct strbuf hash
= STRBUF_INIT
;
6549 struct update_ref_record
*rec
= NULL
;
6551 char *path
= rebase_path_update_refs(wt_dir
);
6553 fp
= fopen(path
, "r");
6557 while (strbuf_getline(&ref
, fp
) != EOF
) {
6558 struct string_list_item
*item
;
6560 CALLOC_ARRAY(rec
, 1);
6562 if (strbuf_getline(&hash
, fp
) == EOF
||
6563 get_oid_hex(hash
.buf
, &rec
->before
)) {
6564 warning(_("update-refs file at '%s' is invalid"),
6570 if (strbuf_getline(&hash
, fp
) == EOF
||
6571 get_oid_hex(hash
.buf
, &rec
->after
)) {
6572 warning(_("update-refs file at '%s' is invalid"),
6578 item
= string_list_insert(refs
, ref
.buf
);
6588 strbuf_release(&ref
);
6589 strbuf_release(&hash
);