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"
19 #include "run-command.h"
23 #include "cache-tree.h"
29 #include "merge-ort.h"
30 #include "merge-ort-wrappers.h"
32 #include "sparse-index.h"
37 #include "wt-status.h"
39 #include "notes-utils.h"
41 #include "unpack-trees.h"
45 #include "commit-slab.h"
47 #include "commit-reach.h"
48 #include "rebase-interactive.h"
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
59 * Add some margin to stay clear from reaching `NAME_MAX`.
61 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
63 static const char sign_off_header
[] = "Signed-off-by: ";
64 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
66 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
68 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
70 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
71 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
72 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
73 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
75 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
82 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
83 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
85 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
92 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
94 * The file to keep track of how many commands were already processed (e.g.
97 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
102 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
107 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
116 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
124 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
129 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
135 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
144 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
146 * When we stop at a given patch via the "edit" command, this file contains
147 * the commit object name of the corresponding patch.
149 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
151 * When we stop for the user to resolve conflicts this file contains
152 * the patch of the commit that is being picked.
154 static GIT_PATH_FUNC(rebase_path_patch
, "rebase-merge/patch")
156 * For the post-rewrite hook, we make a list of rewritten commits and
157 * their new sha1s. The rewritten-pending list keeps the sha1s of
158 * commits that have been processed, but not committed yet,
159 * e.g. because they are waiting for a 'squash' command.
161 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
162 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
163 "rebase-merge/rewritten-pending")
166 * The path of the file containing the OID of the "squash onto" commit, i.e.
167 * the dummy commit used for `reset [new root]`.
169 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
172 * The path of the file listing refs that need to be deleted after the rebase
173 * finishes. This is used by the `label` command to record the need for cleanup.
175 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
178 * The update-refs file stores a list of refs that will be updated at the end
179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
180 * update the OIDs for the refs in this file, but the refs are not updated
181 * until the end of the rebase sequence.
183 * rebase_path_update_refs() returns the path to this file for a given
184 * worktree directory. For the current worktree, pass the_repository->gitdir.
186 static char *rebase_path_update_refs(const char *wt_git_dir
)
188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
192 * The following files are written by git-rebase just after parsing the
195 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
196 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
197 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
198 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
199 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
200 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
201 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
202 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
203 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
204 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
205 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
206 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
207 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
208 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
209 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
210 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
211 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
214 * A 'struct update_refs_record' represents a value in the update-refs
215 * list. We use a string_list to map refs to these (before, after) pairs.
217 struct update_ref_record
{
218 struct object_id before
;
219 struct object_id after
;
222 static struct update_ref_record
*init_update_ref_record(const char *ref
)
224 struct update_ref_record
*rec
;
226 CALLOC_ARRAY(rec
, 1);
228 oidcpy(&rec
->before
, null_oid());
229 oidcpy(&rec
->after
, null_oid());
231 /* This may fail, but that's fine, we will keep the null OID. */
232 read_ref(ref
, &rec
->before
);
237 static int git_sequencer_config(const char *k
, const char *v
,
238 const struct config_context
*ctx
, void *cb
)
240 struct replay_opts
*opts
= cb
;
243 if (!strcmp(k
, "commit.cleanup")) {
246 status
= git_config_string(&s
, k
, v
);
250 if (!strcmp(s
, "verbatim")) {
251 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
252 opts
->explicit_cleanup
= 1;
253 } else if (!strcmp(s
, "whitespace")) {
254 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
255 opts
->explicit_cleanup
= 1;
256 } else if (!strcmp(s
, "strip")) {
257 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
258 opts
->explicit_cleanup
= 1;
259 } else if (!strcmp(s
, "scissors")) {
260 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
261 opts
->explicit_cleanup
= 1;
263 warning(_("invalid commit message cleanup mode '%s'"),
271 if (!strcmp(k
, "commit.gpgsign")) {
272 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
276 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
277 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
280 * pull.twohead is allowed to be multi-valued; we only
281 * care about the first value.
283 char *tmp
= strchr(opts
->default_strategy
, ' ');
290 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
291 opts
->commit_use_reference
= git_config_bool(k
, v
);
293 return git_diff_basic_config(k
, v
, ctx
, NULL
);
296 void sequencer_init_config(struct replay_opts
*opts
)
298 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
299 git_config(git_sequencer_config
, opts
);
302 static inline int is_rebase_i(const struct replay_opts
*opts
)
304 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
307 static const char *get_dir(const struct replay_opts
*opts
)
309 if (is_rebase_i(opts
))
310 return rebase_path();
311 return git_path_seq_dir();
314 static const char *get_todo_path(const struct replay_opts
*opts
)
316 if (is_rebase_i(opts
))
317 return rebase_path_todo();
318 return git_path_todo_file();
322 * Returns 0 for non-conforming footer
323 * Returns 1 for conforming footer
324 * Returns 2 when sob exists within conforming footer
325 * Returns 3 when sob exists within conforming footer as last entry
327 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
328 size_t ignore_footer
)
330 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
331 struct trailer_info info
;
333 int found_sob
= 0, found_sob_last
= 0;
339 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
340 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
343 trailer_info_get(&info
, sb
->buf
, &opts
);
346 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
348 if (info
.trailer_start
== info
.trailer_end
)
351 for (i
= 0; i
< info
.trailer_nr
; i
++)
352 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
354 if (i
== info
.trailer_nr
- 1)
358 trailer_info_release(&info
);
367 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
369 static struct strbuf buf
= STRBUF_INIT
;
373 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
377 void replay_opts_release(struct replay_opts
*opts
)
379 free(opts
->gpg_sign
);
380 free(opts
->reflog_action
);
381 free(opts
->default_strategy
);
382 free(opts
->strategy
);
383 strvec_clear (&opts
->xopts
);
384 strbuf_release(&opts
->current_fixups
);
386 release_revisions(opts
->revs
);
390 int sequencer_remove_state(struct replay_opts
*opts
)
392 struct strbuf buf
= STRBUF_INIT
;
395 if (is_rebase_i(opts
) &&
396 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
399 char *eol
= strchr(p
, '\n');
402 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
403 warning(_("could not delete '%s'"), p
);
413 strbuf_addstr(&buf
, get_dir(opts
));
414 if (remove_dir_recursively(&buf
, 0))
415 ret
= error(_("could not remove '%s'"), buf
.buf
);
416 strbuf_release(&buf
);
421 static const char *action_name(const struct replay_opts
*opts
)
423 switch (opts
->action
) {
427 return N_("cherry-pick");
428 case REPLAY_INTERACTIVE_REBASE
:
431 die(_("unknown action: %d"), opts
->action
);
434 struct commit_message
{
441 static const char *short_commit_name(struct repository
*r
, struct commit
*commit
)
443 return repo_find_unique_abbrev(r
, &commit
->object
.oid
, DEFAULT_ABBREV
);
446 static int get_message(struct commit
*commit
, struct commit_message
*out
)
448 const char *abbrev
, *subject
;
451 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
452 get_commit_output_encoding());
453 abbrev
= short_commit_name(the_repository
, commit
);
455 subject_len
= find_commit_subject(out
->message
, &subject
);
457 out
->subject
= xmemdupz(subject
, subject_len
);
458 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
459 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
464 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
466 free(msg
->parent_label
);
469 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
472 static void print_advice(struct repository
*r
, int show_hint
,
473 struct replay_opts
*opts
)
475 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
480 * A conflict has occurred but the porcelain
481 * (typically rebase --interactive) wants to take care
482 * of the commit itself so remove CHERRY_PICK_HEAD
484 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
491 advise(_("after resolving the conflicts, mark the corrected paths\n"
492 "with 'git add <paths>' or 'git rm <paths>'"));
493 else if (opts
->action
== REPLAY_PICK
)
494 advise(_("After resolving the conflicts, mark them with\n"
495 "\"git add/rm <pathspec>\", then run\n"
496 "\"git cherry-pick --continue\".\n"
497 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
498 "To abort and get back to the state before \"git cherry-pick\",\n"
499 "run \"git cherry-pick --abort\"."));
500 else if (opts
->action
== REPLAY_REVERT
)
501 advise(_("After resolving the conflicts, mark them with\n"
502 "\"git add/rm <pathspec>\", then run\n"
503 "\"git revert --continue\".\n"
504 "You can instead skip this commit with \"git revert --skip\".\n"
505 "To abort and get back to the state before \"git revert\",\n"
506 "run \"git revert --abort\"."));
508 BUG("unexpected pick action in print_advice()");
512 static int write_message(const void *buf
, size_t len
, const char *filename
,
515 struct lock_file msg_file
= LOCK_INIT
;
517 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
519 return error_errno(_("could not lock '%s'"), filename
);
520 if (write_in_full(msg_fd
, buf
, len
) < 0) {
521 error_errno(_("could not write to '%s'"), filename
);
522 rollback_lock_file(&msg_file
);
525 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
526 error_errno(_("could not write eol to '%s'"), filename
);
527 rollback_lock_file(&msg_file
);
530 if (commit_lock_file(&msg_file
) < 0)
531 return error(_("failed to finalize '%s'"), filename
);
536 int read_oneliner(struct strbuf
*buf
,
537 const char *path
, unsigned flags
)
539 int orig_len
= buf
->len
;
541 if (strbuf_read_file(buf
, path
, 0) < 0) {
542 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
543 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
544 warning_errno(_("could not read '%s'"), path
);
548 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
549 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
551 buf
->buf
[buf
->len
] = '\0';
554 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
560 static struct tree
*empty_tree(struct repository
*r
)
562 return lookup_tree(r
, the_hash_algo
->empty_tree
);
565 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
567 if (repo_read_index_unmerged(repo
))
568 return error_resolve_conflict(action_name(opts
));
570 error(_("your local changes would be overwritten by %s."),
571 _(action_name(opts
)));
573 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
574 advise(_("commit your changes or stash them to proceed."));
578 static void update_abort_safety_file(void)
580 struct object_id head
;
582 /* Do nothing on a single-pick */
583 if (!file_exists(git_path_seq_dir()))
586 if (!repo_get_oid(the_repository
, "HEAD", &head
))
587 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
589 write_file(git_path_abort_safety_file(), "%s", "");
592 static int fast_forward_to(struct repository
*r
,
593 const struct object_id
*to
,
594 const struct object_id
*from
,
596 struct replay_opts
*opts
)
598 struct ref_transaction
*transaction
;
599 struct strbuf sb
= STRBUF_INIT
;
600 struct strbuf err
= STRBUF_INIT
;
603 if (checkout_fast_forward(r
, from
, to
, 1))
604 return -1; /* the callee should have complained already */
606 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
608 transaction
= ref_transaction_begin(&err
);
610 ref_transaction_update(transaction
, "HEAD",
611 to
, unborn
&& !is_rebase_i(opts
) ?
614 ref_transaction_commit(transaction
, &err
)) {
615 ref_transaction_free(transaction
);
616 error("%s", err
.buf
);
618 strbuf_release(&err
);
623 strbuf_release(&err
);
624 ref_transaction_free(transaction
);
625 update_abort_safety_file();
629 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
632 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
633 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
634 COMMIT_MSG_CLEANUP_SPACE
;
635 else if (!strcmp(cleanup_arg
, "verbatim"))
636 return COMMIT_MSG_CLEANUP_NONE
;
637 else if (!strcmp(cleanup_arg
, "whitespace"))
638 return COMMIT_MSG_CLEANUP_SPACE
;
639 else if (!strcmp(cleanup_arg
, "strip"))
640 return COMMIT_MSG_CLEANUP_ALL
;
641 else if (!strcmp(cleanup_arg
, "scissors"))
642 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
643 COMMIT_MSG_CLEANUP_SPACE
;
645 die(_("Invalid cleanup mode %s"), cleanup_arg
);
649 * NB using int rather than enum cleanup_mode to stop clang's
650 * -Wtautological-constant-out-of-range-compare complaining that the comparison
653 static const char *describe_cleanup_mode(int cleanup_mode
)
655 static const char *modes
[] = { "whitespace",
660 if (cleanup_mode
< ARRAY_SIZE(modes
))
661 return modes
[cleanup_mode
];
663 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
666 void append_conflicts_hint(struct index_state
*istate
,
667 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
671 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
672 strbuf_addch(msgbuf
, '\n');
673 wt_status_append_cut_line(msgbuf
);
674 strbuf_addch(msgbuf
, comment_line_char
);
677 strbuf_addch(msgbuf
, '\n');
678 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
679 for (i
= 0; i
< istate
->cache_nr
;) {
680 const struct cache_entry
*ce
= istate
->cache
[i
++];
682 strbuf_commented_addf(msgbuf
, comment_line_char
,
684 while (i
< istate
->cache_nr
&&
685 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
691 static int do_recursive_merge(struct repository
*r
,
692 struct commit
*base
, struct commit
*next
,
693 const char *base_label
, const char *next_label
,
694 struct object_id
*head
, struct strbuf
*msgbuf
,
695 struct replay_opts
*opts
)
697 struct merge_options o
;
698 struct merge_result result
;
699 struct tree
*next_tree
, *base_tree
, *head_tree
;
700 int clean
, show_output
;
702 struct lock_file index_lock
= LOCK_INIT
;
704 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
709 init_merge_options(&o
, r
);
710 o
.ancestor
= base
? base_label
: "(empty tree)";
712 o
.branch2
= next
? next_label
: "(empty tree)";
713 if (is_rebase_i(opts
))
715 o
.show_rename_progress
= 1;
717 head_tree
= parse_tree_indirect(head
);
718 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
719 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
721 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
722 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
724 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
725 memset(&result
, 0, sizeof(result
));
726 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
728 show_output
= !is_rebase_i(opts
) || !result
.clean
;
730 * TODO: merge_switch_to_result will update index/working tree;
731 * we only really want to do that if !result.clean || this is
732 * the final patch to be picked. But determining this is the
733 * final patch would take some work, and "head_tree" would need
734 * to be replace with the tree the index matched before we
735 * started doing any picks.
737 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
738 clean
= result
.clean
;
740 ensure_full_index(r
->index
);
741 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
742 if (is_rebase_i(opts
) && clean
<= 0)
743 fputs(o
.obuf
.buf
, stdout
);
744 strbuf_release(&o
.obuf
);
747 rollback_lock_file(&index_lock
);
751 if (write_locked_index(r
->index
, &index_lock
,
752 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
754 * TRANSLATORS: %s will be "revert", "cherry-pick" or
757 return error(_("%s: Unable to write new index file"),
758 _(action_name(opts
)));
761 append_conflicts_hint(r
->index
, msgbuf
,
762 opts
->default_msg_cleanup
);
767 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
769 if (!cache_tree_fully_valid(istate
->cache_tree
))
770 if (cache_tree_update(istate
, 0)) {
771 error(_("unable to update cache tree"));
775 return &istate
->cache_tree
->oid
;
778 static int is_index_unchanged(struct repository
*r
)
780 struct object_id head_oid
, *cache_tree_oid
;
781 struct commit
*head_commit
;
782 struct index_state
*istate
= r
->index
;
784 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
785 return error(_("could not resolve HEAD commit"));
787 head_commit
= lookup_commit(r
, &head_oid
);
790 * If head_commit is NULL, check_commit, called from
791 * lookup_commit, would have indicated that head_commit is not
792 * a commit object already. repo_parse_commit() will return failure
793 * without further complaints in such a case. Otherwise, if
794 * the commit is invalid, repo_parse_commit() will complain. So
795 * there is nothing for us to say here. Just return failure.
797 if (repo_parse_commit(r
, head_commit
))
800 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
803 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
806 static int write_author_script(const char *message
)
808 struct strbuf buf
= STRBUF_INIT
;
813 if (!*message
|| starts_with(message
, "\n")) {
815 /* Missing 'author' line? */
816 unlink(rebase_path_author_script());
818 } else if (skip_prefix(message
, "author ", &message
))
820 else if ((eol
= strchr(message
, '\n')))
825 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
826 while (*message
&& *message
!= '\n' && *message
!= '\r')
827 if (skip_prefix(message
, " <", &message
))
829 else if (*message
!= '\'')
830 strbuf_addch(&buf
, *(message
++));
832 strbuf_addf(&buf
, "'\\%c'", *(message
++));
833 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
834 while (*message
&& *message
!= '\n' && *message
!= '\r')
835 if (skip_prefix(message
, "> ", &message
))
837 else if (*message
!= '\'')
838 strbuf_addch(&buf
, *(message
++));
840 strbuf_addf(&buf
, "'\\%c'", *(message
++));
841 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
842 while (*message
&& *message
!= '\n' && *message
!= '\r')
843 if (*message
!= '\'')
844 strbuf_addch(&buf
, *(message
++));
846 strbuf_addf(&buf
, "'\\%c'", *(message
++));
847 strbuf_addch(&buf
, '\'');
848 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
849 strbuf_release(&buf
);
854 * Take a series of KEY='VALUE' lines where VALUE part is
855 * sq-quoted, and append <KEY, VALUE> at the end of the string list
857 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
860 struct string_list_item
*item
;
862 char *cp
= strchr(buf
, '=');
864 np
= strchrnul(buf
, '\n');
865 return error(_("no key present in '%.*s'"),
866 (int) (np
- buf
), buf
);
868 np
= strchrnul(cp
, '\n');
870 item
= string_list_append(list
, buf
);
872 buf
= np
+ (*np
== '\n');
876 return error(_("unable to dequote value of '%s'"),
878 item
->util
= xstrdup(cp
);
884 * Reads and parses the state directory's "author-script" file, and sets name,
885 * email and date accordingly.
886 * Returns 0 on success, -1 if the file could not be parsed.
888 * The author script is of the format:
890 * GIT_AUTHOR_NAME='$author_name'
891 * GIT_AUTHOR_EMAIL='$author_email'
892 * GIT_AUTHOR_DATE='$author_date'
894 * where $author_name, $author_email and $author_date are quoted. We are strict
895 * with our parsing, as the file was meant to be eval'd in the now-removed
896 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
897 * from what this function expects, it is better to bail out than to do
898 * something that the user does not expect.
900 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
903 struct strbuf buf
= STRBUF_INIT
;
904 struct string_list kv
= STRING_LIST_INIT_DUP
;
905 int retval
= -1; /* assume failure */
906 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
908 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
909 strbuf_release(&buf
);
910 if (errno
== ENOENT
&& allow_missing
)
913 return error_errno(_("could not open '%s' for reading"),
917 if (parse_key_value_squoted(buf
.buf
, &kv
))
920 for (i
= 0; i
< kv
.nr
; i
++) {
921 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
923 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
926 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
928 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
931 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
933 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
937 err
= error(_("unknown variable '%s'"),
942 error(_("missing 'GIT_AUTHOR_NAME'"));
944 error(_("missing 'GIT_AUTHOR_EMAIL'"));
946 error(_("missing 'GIT_AUTHOR_DATE'"));
947 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
949 *name
= kv
.items
[name_i
].util
;
950 *email
= kv
.items
[email_i
].util
;
951 *date
= kv
.items
[date_i
].util
;
954 string_list_clear(&kv
, !!retval
);
955 strbuf_release(&buf
);
960 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
961 * file with shell quoting into struct strvec. Returns -1 on
962 * error, 0 otherwise.
964 static int read_env_script(struct strvec
*env
)
966 char *name
, *email
, *date
;
968 if (read_author_script(rebase_path_author_script(),
969 &name
, &email
, &date
, 0))
972 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
973 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
974 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
982 static char *get_author(const char *message
)
987 a
= find_commit_header(message
, "author", &len
);
989 return xmemdupz(a
, len
);
994 static const char *author_date_from_env(const struct strvec
*env
)
999 for (i
= 0; i
< env
->nr
; i
++)
1000 if (skip_prefix(env
->v
[i
],
1001 "GIT_AUTHOR_DATE=", &date
))
1004 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1005 * reading the script
1007 BUG("GIT_AUTHOR_DATE missing from author script");
1010 static const char staged_changes_advice
[] =
1011 N_("you have staged changes in your working tree\n"
1012 "If these changes are meant to be squashed into the previous commit, run:\n"
1014 " git commit --amend %s\n"
1016 "If they are meant to go into a new commit, run:\n"
1020 "In both cases, once you're done, continue with:\n"
1022 " git rebase --continue\n");
1024 #define ALLOW_EMPTY (1<<0)
1025 #define EDIT_MSG (1<<1)
1026 #define AMEND_MSG (1<<2)
1027 #define CLEANUP_MSG (1<<3)
1028 #define VERIFY_MSG (1<<4)
1029 #define CREATE_ROOT_COMMIT (1<<5)
1030 #define VERBATIM_MSG (1<<6)
1032 static int run_command_silent_on_success(struct child_process
*cmd
)
1034 struct strbuf buf
= STRBUF_INIT
;
1037 cmd
->stdout_to_stderr
= 1;
1038 rc
= pipe_command(cmd
,
1044 fputs(buf
.buf
, stderr
);
1045 strbuf_release(&buf
);
1050 * If we are cherry-pick, and if the merge did not result in
1051 * hand-editing, we will hit this commit and inherit the original
1052 * author date and name.
1054 * If we are revert, or if our cherry-pick results in a hand merge,
1055 * we had better say that the current user is responsible for that.
1057 * An exception is when run_git_commit() is called during an
1058 * interactive rebase: in that case, we will want to retain the
1061 static int run_git_commit(const char *defmsg
,
1062 struct replay_opts
*opts
,
1065 struct child_process cmd
= CHILD_PROCESS_INIT
;
1067 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1068 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1072 if (is_rebase_i(opts
) &&
1073 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1074 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1075 read_env_script(&cmd
.env
)) {
1076 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1078 return error(_(staged_changes_advice
),
1082 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1084 if (opts
->committer_date_is_author_date
)
1085 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1088 author_date_from_env(&cmd
.env
));
1089 if (opts
->ignore_date
)
1090 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1092 strvec_push(&cmd
.args
, "commit");
1094 if (!(flags
& VERIFY_MSG
))
1095 strvec_push(&cmd
.args
, "-n");
1096 if ((flags
& AMEND_MSG
))
1097 strvec_push(&cmd
.args
, "--amend");
1099 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1101 strvec_push(&cmd
.args
, "--no-gpg-sign");
1103 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1104 else if (!(flags
& EDIT_MSG
))
1105 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1106 if ((flags
& CLEANUP_MSG
))
1107 strvec_push(&cmd
.args
, "--cleanup=strip");
1108 if ((flags
& VERBATIM_MSG
))
1109 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1110 if ((flags
& EDIT_MSG
))
1111 strvec_push(&cmd
.args
, "-e");
1112 else if (!(flags
& CLEANUP_MSG
) &&
1113 !opts
->signoff
&& !opts
->record_origin
&&
1114 !opts
->explicit_cleanup
)
1115 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1117 if ((flags
& ALLOW_EMPTY
))
1118 strvec_push(&cmd
.args
, "--allow-empty");
1120 if (!(flags
& EDIT_MSG
))
1121 strvec_push(&cmd
.args
, "--allow-empty-message");
1123 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1124 return run_command_silent_on_success(&cmd
);
1126 return run_command(&cmd
);
1129 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1134 /* Check if the rest is just whitespace and Signed-off-by's. */
1135 for (i
= start
; i
< sb
->len
; i
++) {
1136 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1142 if (strlen(sign_off_header
) <= eol
- i
&&
1143 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1148 if (!isspace(sb
->buf
[i
++]))
1155 void cleanup_message(struct strbuf
*msgbuf
,
1156 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1158 if (verbose
|| /* Truncate the message just before the diff, if any. */
1159 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1160 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1161 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1162 strbuf_stripspace(msgbuf
,
1163 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1167 * Find out if the message in the strbuf contains only whitespace and
1168 * Signed-off-by lines.
1170 int message_is_empty(const struct strbuf
*sb
,
1171 enum commit_msg_cleanup_mode cleanup_mode
)
1173 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1175 return rest_is_empty(sb
, 0);
1179 * See if the user edited the message in the editor or left what
1180 * was in the template intact
1182 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1183 enum commit_msg_cleanup_mode cleanup_mode
)
1185 struct strbuf tmpl
= STRBUF_INIT
;
1188 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1191 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1194 strbuf_stripspace(&tmpl
,
1195 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1196 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1198 strbuf_release(&tmpl
);
1199 return rest_is_empty(sb
, start
- sb
->buf
);
1202 int update_head_with_reflog(const struct commit
*old_head
,
1203 const struct object_id
*new_head
,
1204 const char *action
, const struct strbuf
*msg
,
1207 struct ref_transaction
*transaction
;
1208 struct strbuf sb
= STRBUF_INIT
;
1213 strbuf_addstr(&sb
, action
);
1214 strbuf_addstr(&sb
, ": ");
1217 nl
= strchr(msg
->buf
, '\n');
1219 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1221 strbuf_addbuf(&sb
, msg
);
1222 strbuf_addch(&sb
, '\n');
1225 transaction
= ref_transaction_begin(err
);
1227 ref_transaction_update(transaction
, "HEAD", new_head
,
1228 old_head
? &old_head
->object
.oid
: null_oid(),
1230 ref_transaction_commit(transaction
, err
)) {
1233 ref_transaction_free(transaction
);
1234 strbuf_release(&sb
);
1239 static int run_rewrite_hook(const struct object_id
*oldoid
,
1240 const struct object_id
*newoid
)
1242 struct child_process proc
= CHILD_PROCESS_INIT
;
1244 struct strbuf sb
= STRBUF_INIT
;
1245 const char *hook_path
= find_hook("post-rewrite");
1250 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1252 proc
.stdout_to_stderr
= 1;
1253 proc
.trace2_hook_name
= "post-rewrite";
1255 code
= start_command(&proc
);
1258 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1259 sigchain_push(SIGPIPE
, SIG_IGN
);
1260 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1262 strbuf_release(&sb
);
1263 sigchain_pop(SIGPIPE
);
1264 return finish_command(&proc
);
1267 void commit_post_rewrite(struct repository
*r
,
1268 const struct commit
*old_head
,
1269 const struct object_id
*new_head
)
1271 struct notes_rewrite_cfg
*cfg
;
1273 cfg
= init_copy_notes_for_rewrite("amend");
1275 /* we are amending, so old_head is not NULL */
1276 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1277 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1279 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1282 static int run_prepare_commit_msg_hook(struct repository
*r
,
1287 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1289 name
= git_path_commit_editmsg();
1290 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1299 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1301 ret
= error(_("'prepare-commit-msg' hook failed"));
1306 static const char implicit_ident_advice_noconfig
[] =
1307 N_("Your name and email address were configured automatically based\n"
1308 "on your username and hostname. Please check that they are accurate.\n"
1309 "You can suppress this message by setting them explicitly. Run the\n"
1310 "following command and follow the instructions in your editor to edit\n"
1311 "your configuration file:\n"
1313 " git config --global --edit\n"
1315 "After doing this, you may fix the identity used for this commit with:\n"
1317 " git commit --amend --reset-author\n");
1319 static const char implicit_ident_advice_config
[] =
1320 N_("Your name and email address were configured automatically based\n"
1321 "on your username and hostname. Please check that they are accurate.\n"
1322 "You can suppress this message by setting them explicitly:\n"
1324 " git config --global user.name \"Your Name\"\n"
1325 " git config --global user.email you@example.com\n"
1327 "After doing this, you may fix the identity used for this commit with:\n"
1329 " git commit --amend --reset-author\n");
1331 static const char *implicit_ident_advice(void)
1333 char *user_config
= interpolate_path("~/.gitconfig", 0);
1334 char *xdg_config
= xdg_config_home("config");
1335 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1341 return _(implicit_ident_advice_config
);
1343 return _(implicit_ident_advice_noconfig
);
1347 void print_commit_summary(struct repository
*r
,
1349 const struct object_id
*oid
,
1352 struct rev_info rev
;
1353 struct commit
*commit
;
1354 struct strbuf format
= STRBUF_INIT
;
1356 struct pretty_print_context pctx
= {0};
1357 struct strbuf author_ident
= STRBUF_INIT
;
1358 struct strbuf committer_ident
= STRBUF_INIT
;
1359 struct ref_store
*refs
;
1361 commit
= lookup_commit(r
, oid
);
1363 die(_("couldn't look up newly created commit"));
1364 if (repo_parse_commit(r
, commit
))
1365 die(_("could not parse newly created commit"));
1367 strbuf_addstr(&format
, "format:%h] %s");
1369 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1371 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1373 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1374 strbuf_addstr(&format
, "\n Author: ");
1375 strbuf_addbuf_percentquote(&format
, &author_ident
);
1377 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1378 struct strbuf date
= STRBUF_INIT
;
1380 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1381 strbuf_addstr(&format
, "\n Date: ");
1382 strbuf_addbuf_percentquote(&format
, &date
);
1383 strbuf_release(&date
);
1385 if (!committer_ident_sufficiently_given()) {
1386 strbuf_addstr(&format
, "\n Committer: ");
1387 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1388 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1389 strbuf_addch(&format
, '\n');
1390 strbuf_addstr(&format
, implicit_ident_advice());
1393 strbuf_release(&author_ident
);
1394 strbuf_release(&committer_ident
);
1396 repo_init_revisions(r
, &rev
, prefix
);
1397 setup_revisions(0, NULL
, &rev
, NULL
);
1400 rev
.diffopt
.output_format
=
1401 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1403 rev
.verbose_header
= 1;
1404 rev
.show_root_diff
= 1;
1405 get_commit_format(format
.buf
, &rev
);
1406 rev
.always_show_header
= 0;
1407 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1408 diff_setup_done(&rev
.diffopt
);
1410 refs
= get_main_ref_store(r
);
1411 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1413 die(_("unable to resolve HEAD after creating commit"));
1414 if (!strcmp(head
, "HEAD"))
1415 head
= _("detached HEAD");
1417 skip_prefix(head
, "refs/heads/", &head
);
1418 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1419 _(" (root-commit)") : "");
1421 if (!log_tree_commit(&rev
, commit
)) {
1422 rev
.always_show_header
= 1;
1423 rev
.use_terminator
= 1;
1424 log_tree_commit(&rev
, commit
);
1427 release_revisions(&rev
);
1428 strbuf_release(&format
);
1431 static int parse_head(struct repository
*r
, struct commit
**head
)
1433 struct commit
*current_head
;
1434 struct object_id oid
;
1436 if (repo_get_oid(r
, "HEAD", &oid
)) {
1437 current_head
= NULL
;
1439 current_head
= lookup_commit_reference(r
, &oid
);
1441 return error(_("could not parse HEAD"));
1442 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1443 warning(_("HEAD %s is not a commit!"),
1446 if (repo_parse_commit(r
, current_head
))
1447 return error(_("could not parse HEAD commit"));
1449 *head
= current_head
;
1455 * Try to commit without forking 'git commit'. In some cases we need
1456 * to run 'git commit' to display an error message
1459 * -1 - error unable to commit
1461 * 1 - run 'git commit'
1463 static int try_to_commit(struct repository
*r
,
1464 struct strbuf
*msg
, const char *author
,
1465 struct replay_opts
*opts
, unsigned int flags
,
1466 struct object_id
*oid
)
1468 struct object_id tree
;
1469 struct commit
*current_head
= NULL
;
1470 struct commit_list
*parents
= NULL
;
1471 struct commit_extra_header
*extra
= NULL
;
1472 struct strbuf err
= STRBUF_INIT
;
1473 struct strbuf commit_msg
= STRBUF_INIT
;
1474 char *amend_author
= NULL
;
1475 const char *committer
= NULL
;
1476 const char *hook_commit
= NULL
;
1477 enum commit_msg_cleanup_mode cleanup
;
1480 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1481 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1483 if (parse_head(r
, ¤t_head
))
1486 if (flags
& AMEND_MSG
) {
1487 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1488 const char *out_enc
= get_commit_output_encoding();
1489 const char *message
= repo_logmsg_reencode(r
, current_head
,
1493 const char *orig_message
= NULL
;
1495 find_commit_subject(message
, &orig_message
);
1497 strbuf_addstr(msg
, orig_message
);
1498 hook_commit
= "HEAD";
1500 author
= amend_author
= get_author(message
);
1501 repo_unuse_commit_buffer(r
, current_head
,
1504 res
= error(_("unable to parse commit author"));
1507 parents
= copy_commit_list(current_head
->parents
);
1508 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1509 } else if (current_head
&&
1510 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1511 commit_list_insert(current_head
, &parents
);
1514 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1515 res
= error(_("git write-tree failed to write a tree"));
1519 if (!(flags
& ALLOW_EMPTY
)) {
1520 struct commit
*first_parent
= current_head
;
1522 if (flags
& AMEND_MSG
) {
1523 if (current_head
->parents
) {
1524 first_parent
= current_head
->parents
->item
;
1525 if (repo_parse_commit(r
, first_parent
)) {
1526 res
= error(_("could not parse HEAD commit"));
1530 first_parent
= NULL
;
1533 if (oideq(first_parent
1534 ? get_commit_tree_oid(first_parent
)
1535 : the_hash_algo
->empty_tree
,
1537 res
= 1; /* run 'git commit' to display error message */
1542 if (hook_exists("prepare-commit-msg")) {
1543 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1546 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1548 res
= error_errno(_("unable to read commit message "
1550 git_path_commit_editmsg());
1556 if (flags
& CLEANUP_MSG
)
1557 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1558 else if (flags
& VERBATIM_MSG
)
1559 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1560 else if ((opts
->signoff
|| opts
->record_origin
) &&
1561 !opts
->explicit_cleanup
)
1562 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1564 cleanup
= opts
->default_msg_cleanup
;
1566 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1567 strbuf_stripspace(msg
,
1568 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1569 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1570 res
= 1; /* run 'git commit' to display error message */
1574 if (opts
->committer_date_is_author_date
) {
1575 struct ident_split id
;
1576 struct strbuf date
= STRBUF_INIT
;
1578 if (!opts
->ignore_date
) {
1579 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1580 res
= error(_("invalid author identity '%s'"),
1584 if (!id
.date_begin
) {
1586 "corrupt author: missing date information"));
1589 strbuf_addf(&date
, "@%.*s %.*s",
1590 (int)(id
.date_end
- id
.date_begin
),
1592 (int)(id
.tz_end
- id
.tz_begin
),
1597 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1598 getenv("GIT_COMMITTER_EMAIL"),
1599 WANT_COMMITTER_IDENT
,
1600 opts
->ignore_date
? NULL
: date
.buf
,
1602 strbuf_release(&date
);
1607 if (opts
->ignore_date
) {
1608 struct ident_split id
;
1611 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1612 error(_("invalid author identity '%s'"), author
);
1615 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1616 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1617 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1623 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1624 author
, committer
, opts
->gpg_sign
, extra
)) {
1625 res
= error(_("failed to write commit object"));
1629 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1631 res
= error("%s", err
.buf
);
1635 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1636 if (flags
& AMEND_MSG
)
1637 commit_post_rewrite(r
, current_head
, oid
);
1640 free_commit_extra_headers(extra
);
1641 strbuf_release(&err
);
1642 strbuf_release(&commit_msg
);
1648 static int write_rebase_head(struct object_id
*oid
)
1650 if (update_ref("rebase", "REBASE_HEAD", oid
,
1651 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1652 return error(_("could not update %s"), "REBASE_HEAD");
1657 static int do_commit(struct repository
*r
,
1658 const char *msg_file
, const char *author
,
1659 struct replay_opts
*opts
, unsigned int flags
,
1660 struct object_id
*oid
)
1664 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1665 struct object_id oid
;
1666 struct strbuf sb
= STRBUF_INIT
;
1668 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1669 return error_errno(_("unable to read commit message "
1673 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1674 author
, opts
, flags
, &oid
);
1675 strbuf_release(&sb
);
1677 refs_delete_ref(get_main_ref_store(r
), "",
1678 "CHERRY_PICK_HEAD", NULL
, 0);
1679 unlink(git_path_merge_msg(r
));
1680 if (!is_rebase_i(opts
))
1681 print_commit_summary(r
, NULL
, &oid
,
1682 SUMMARY_SHOW_AUTHOR_DATE
);
1687 if (is_rebase_i(opts
) && oid
)
1688 if (write_rebase_head(oid
))
1690 return run_git_commit(msg_file
, opts
, flags
);
1696 static int is_original_commit_empty(struct commit
*commit
)
1698 const struct object_id
*ptree_oid
;
1700 if (repo_parse_commit(the_repository
, commit
))
1701 return error(_("could not parse commit %s"),
1702 oid_to_hex(&commit
->object
.oid
));
1703 if (commit
->parents
) {
1704 struct commit
*parent
= commit
->parents
->item
;
1705 if (repo_parse_commit(the_repository
, parent
))
1706 return error(_("could not parse parent commit %s"),
1707 oid_to_hex(&parent
->object
.oid
));
1708 ptree_oid
= get_commit_tree_oid(parent
);
1710 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1713 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1717 * Should empty commits be allowed? Return status:
1718 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1719 * 0: Halt on empty commit
1720 * 1: Allow empty commit
1721 * 2: Drop empty commit
1723 static int allow_empty(struct repository
*r
,
1724 struct replay_opts
*opts
,
1725 struct commit
*commit
)
1727 int index_unchanged
, originally_empty
;
1732 * (1) we do not allow empty at all and error out.
1734 * (2) we allow ones that were initially empty, and
1735 * just drop the ones that become empty
1737 * (3) we allow ones that were initially empty, but
1738 * halt for the ones that become empty;
1740 * (4) we allow both.
1742 if (!opts
->allow_empty
)
1743 return 0; /* let "git commit" barf as necessary */
1745 index_unchanged
= is_index_unchanged(r
);
1746 if (index_unchanged
< 0)
1747 return index_unchanged
;
1748 if (!index_unchanged
)
1749 return 0; /* we do not have to say --allow-empty */
1751 if (opts
->keep_redundant_commits
)
1754 originally_empty
= is_original_commit_empty(commit
);
1755 if (originally_empty
< 0)
1756 return originally_empty
;
1757 if (originally_empty
)
1759 else if (opts
->drop_redundant_commits
)
1768 } todo_command_info
[] = {
1769 [TODO_PICK
] = { 'p', "pick" },
1770 [TODO_REVERT
] = { 0, "revert" },
1771 [TODO_EDIT
] = { 'e', "edit" },
1772 [TODO_REWORD
] = { 'r', "reword" },
1773 [TODO_FIXUP
] = { 'f', "fixup" },
1774 [TODO_SQUASH
] = { 's', "squash" },
1775 [TODO_EXEC
] = { 'x', "exec" },
1776 [TODO_BREAK
] = { 'b', "break" },
1777 [TODO_LABEL
] = { 'l', "label" },
1778 [TODO_RESET
] = { 't', "reset" },
1779 [TODO_MERGE
] = { 'm', "merge" },
1780 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1781 [TODO_NOOP
] = { 0, "noop" },
1782 [TODO_DROP
] = { 'd', "drop" },
1783 [TODO_COMMENT
] = { 0, NULL
},
1786 static const char *command_to_string(const enum todo_command command
)
1788 if (command
< TODO_COMMENT
)
1789 return todo_command_info
[command
].str
;
1790 die(_("unknown command: %d"), command
);
1793 static char command_to_char(const enum todo_command command
)
1795 if (command
< TODO_COMMENT
)
1796 return todo_command_info
[command
].c
;
1797 return comment_line_char
;
1800 static int is_noop(const enum todo_command command
)
1802 return TODO_NOOP
<= command
;
1805 static int is_fixup(enum todo_command command
)
1807 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1810 /* Does this command create a (non-merge) commit? */
1811 static int is_pick_or_similar(enum todo_command command
)
1826 enum todo_item_flags
{
1827 TODO_EDIT_MERGE_MSG
= (1 << 0),
1828 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1829 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1832 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1833 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1834 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1835 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1836 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1838 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1840 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1841 (flag
& TODO_EDIT_FIXUP_MSG
));
1845 * Wrapper around strbuf_add_commented_lines() which avoids double
1846 * commenting commit subjects.
1848 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1850 const char *s
= str
;
1851 while (len
> 0 && s
[0] == comment_line_char
) {
1853 const char *n
= memchr(s
, '\n', len
);
1858 strbuf_add(buf
, s
, count
);
1862 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1865 /* Does the current fixup chain contain a squash command? */
1866 static int seen_squash(struct replay_opts
*opts
)
1868 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1869 strstr(opts
->current_fixups
.buf
, "\nsquash");
1872 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1874 strbuf_setlen(buf1
, 2);
1875 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1876 strbuf_addch(buf1
, '\n');
1877 strbuf_setlen(buf2
, 2);
1878 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1879 strbuf_addch(buf2
, '\n');
1883 * Comment out any un-commented commit messages, updating the message comments
1884 * to say they will be skipped but do not comment out the empty lines that
1885 * surround commit messages and their comments.
1887 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1889 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1890 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1891 const char *s
, *start
;
1893 size_t orig_msg_len
;
1896 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1897 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1898 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1902 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1904 * Copy the last message, preserving the blank line
1905 * preceding the current line
1907 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1908 copy_lines(msg
, start
, s
- start
- off
);
1910 strbuf_addch(msg
, '\n');
1912 * The next message needs to be commented out but the
1913 * message header is already commented out so just copy
1914 * it and the blank line that follows it.
1916 strbuf_addbuf(msg
, &buf2
);
1918 strbuf_addch(msg
, *next
++);
1920 copy_lines
= add_commented_lines
;
1921 update_comment_bufs(&buf1
, &buf2
, ++i
);
1922 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1923 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1924 copy_lines(msg
, start
, s
- start
- off
);
1927 copy_lines
= strbuf_add
;
1928 update_comment_bufs(&buf1
, &buf2
, ++i
);
1930 s
= strchr(s
, '\n');
1935 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1937 strbuf_release(&buf1
);
1938 strbuf_release(&buf2
);
1941 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1942 enum todo_command command
, struct replay_opts
*opts
,
1945 const char *fixup_msg
;
1946 size_t commented_len
= 0, fixup_off
;
1948 * amend is non-interactive and not normally used with fixup!
1949 * or squash! commits, so only comment out those subjects when
1950 * squashing commit messages.
1952 if (starts_with(body
, "amend!") ||
1953 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1954 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1955 commented_len
= commit_subject_length(body
);
1957 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1958 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1959 ++opts
->current_fixup_count
+ 1);
1960 strbuf_addstr(buf
, "\n\n");
1961 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1962 /* buf->buf may be reallocated so store an offset into the buffer */
1963 fixup_off
= buf
->len
;
1964 strbuf_addstr(buf
, body
+ commented_len
);
1966 /* fixup -C after squash behaves like squash */
1967 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1969 * We're replacing the commit message so we need to
1970 * append the Signed-off-by: trailer if the user
1971 * requested '--signoff'.
1974 append_signoff(buf
, 0, 0);
1976 if ((command
== TODO_FIXUP
) &&
1977 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1978 (file_exists(rebase_path_fixup_msg()) ||
1979 !file_exists(rebase_path_squash_msg()))) {
1980 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1981 if (write_message(fixup_msg
, strlen(fixup_msg
),
1982 rebase_path_fixup_msg(), 0) < 0)
1983 return error(_("cannot write '%s'"),
1984 rebase_path_fixup_msg());
1986 unlink(rebase_path_fixup_msg());
1989 unlink(rebase_path_fixup_msg());
1995 static int update_squash_messages(struct repository
*r
,
1996 enum todo_command command
,
1997 struct commit
*commit
,
1998 struct replay_opts
*opts
,
2001 struct strbuf buf
= STRBUF_INIT
;
2003 const char *message
, *body
;
2004 const char *encoding
= get_commit_output_encoding();
2006 if (opts
->current_fixup_count
> 0) {
2007 struct strbuf header
= STRBUF_INIT
;
2010 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2011 return error(_("could not read '%s'"),
2012 rebase_path_squash_msg());
2014 eol
= buf
.buf
[0] != comment_line_char
?
2015 buf
.buf
: strchrnul(buf
.buf
, '\n');
2017 strbuf_addf(&header
, "%c ", comment_line_char
);
2018 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2019 opts
->current_fixup_count
+ 2);
2020 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2021 strbuf_release(&header
);
2022 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2023 update_squash_message_for_fixup(&buf
);
2025 struct object_id head
;
2026 struct commit
*head_commit
;
2027 const char *head_message
, *body
;
2029 if (repo_get_oid(r
, "HEAD", &head
))
2030 return error(_("need a HEAD to fixup"));
2031 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2032 return error(_("could not read HEAD"));
2033 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2035 return error(_("could not read HEAD's commit message"));
2037 find_commit_subject(head_message
, &body
);
2038 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2039 rebase_path_fixup_msg(), 0) < 0) {
2040 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2041 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2043 strbuf_addf(&buf
, "%c ", comment_line_char
);
2044 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2045 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2046 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2047 _(skip_first_commit_msg_str
) :
2048 _(first_commit_msg_str
));
2049 strbuf_addstr(&buf
, "\n\n");
2050 if (is_fixup_flag(command
, flag
))
2051 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2054 strbuf_addstr(&buf
, body
);
2056 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2059 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2060 return error(_("could not read commit message of %s"),
2061 oid_to_hex(&commit
->object
.oid
));
2062 find_commit_subject(message
, &body
);
2064 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2065 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2066 } else if (command
== TODO_FIXUP
) {
2067 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2068 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2069 ++opts
->current_fixup_count
+ 1);
2070 strbuf_addstr(&buf
, "\n\n");
2071 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2074 return error(_("unknown command: %d"), command
);
2075 repo_unuse_commit_buffer(r
, commit
, message
);
2078 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2080 strbuf_release(&buf
);
2083 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2084 opts
->current_fixups
.len
? "\n" : "",
2085 command_to_string(command
),
2086 oid_to_hex(&commit
->object
.oid
));
2087 res
= write_message(opts
->current_fixups
.buf
,
2088 opts
->current_fixups
.len
,
2089 rebase_path_current_fixups(), 0);
2095 static void flush_rewritten_pending(void)
2097 struct strbuf buf
= STRBUF_INIT
;
2098 struct object_id newoid
;
2101 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2102 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2103 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2104 char *bol
= buf
.buf
, *eol
;
2107 eol
= strchrnul(bol
, '\n');
2108 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2109 bol
, oid_to_hex(&newoid
));
2115 unlink(rebase_path_rewritten_pending());
2117 strbuf_release(&buf
);
2120 static void record_in_rewritten(struct object_id
*oid
,
2121 enum todo_command next_command
)
2123 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2128 fprintf(out
, "%s\n", oid_to_hex(oid
));
2131 if (!is_fixup(next_command
))
2132 flush_rewritten_pending();
2135 static int should_edit(struct replay_opts
*opts
) {
2138 * Note that we only handle the case of non-conflicted
2139 * commits; continue_single_pick() handles the conflicted
2140 * commits itself instead of calling this function.
2142 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2146 static void refer_to_commit(struct replay_opts
*opts
,
2147 struct strbuf
*msgbuf
, struct commit
*commit
)
2149 if (opts
->commit_use_reference
) {
2150 struct pretty_print_context ctx
= {
2151 .abbrev
= DEFAULT_ABBREV
,
2152 .date_mode
.type
= DATE_SHORT
,
2154 repo_format_commit_message(the_repository
, commit
,
2155 "%h (%s, %ad)", msgbuf
, &ctx
);
2157 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2161 static int do_pick_commit(struct repository
*r
,
2162 struct todo_item
*item
,
2163 struct replay_opts
*opts
,
2164 int final_fixup
, int *check_todo
)
2166 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2167 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2168 struct object_id head
;
2169 struct commit
*base
, *next
, *parent
;
2170 const char *base_label
, *next_label
;
2171 char *author
= NULL
;
2172 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2173 struct strbuf msgbuf
= STRBUF_INIT
;
2174 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2175 enum todo_command command
= item
->command
;
2176 struct commit
*commit
= item
->commit
;
2178 if (opts
->no_commit
) {
2180 * We do not intend to commit immediately. We just want to
2181 * merge the differences in, so let's compute the tree
2182 * that represents the "current" state for the merge machinery
2185 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2186 return error(_("your index file is unmerged."));
2188 unborn
= repo_get_oid(r
, "HEAD", &head
);
2189 /* Do we want to generate a root commit? */
2190 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2191 oideq(&head
, &opts
->squash_onto
)) {
2192 if (is_fixup(command
))
2193 return error(_("cannot fixup root commit"));
2194 flags
|= CREATE_ROOT_COMMIT
;
2197 oidcpy(&head
, the_hash_algo
->empty_tree
);
2198 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2200 return error_dirty_index(r
, opts
);
2202 discard_index(r
->index
);
2204 if (!commit
->parents
)
2206 else if (commit
->parents
->next
) {
2207 /* Reverting or cherry-picking a merge commit */
2209 struct commit_list
*p
;
2211 if (!opts
->mainline
)
2212 return error(_("commit %s is a merge but no -m option was given."),
2213 oid_to_hex(&commit
->object
.oid
));
2215 for (cnt
= 1, p
= commit
->parents
;
2216 cnt
!= opts
->mainline
&& p
;
2219 if (cnt
!= opts
->mainline
|| !p
)
2220 return error(_("commit %s does not have parent %d"),
2221 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2223 } else if (1 < opts
->mainline
)
2225 * Non-first parent explicitly specified as mainline for
2228 return error(_("commit %s does not have parent %d"),
2229 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2231 parent
= commit
->parents
->item
;
2233 if (get_message(commit
, &msg
) != 0)
2234 return error(_("cannot get commit message for %s"),
2235 oid_to_hex(&commit
->object
.oid
));
2237 if (opts
->allow_ff
&& !is_fixup(command
) &&
2238 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2239 (!parent
&& unborn
))) {
2240 if (is_rebase_i(opts
))
2241 write_author_script(msg
.message
);
2242 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2244 if (res
|| command
!= TODO_REWORD
)
2248 goto fast_forward_edit
;
2250 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2251 /* TRANSLATORS: The first %s will be a "todo" command like
2252 "revert" or "pick", the second %s a SHA1. */
2253 return error(_("%s: cannot parse parent commit %s"),
2254 command_to_string(command
),
2255 oid_to_hex(&parent
->object
.oid
));
2258 * "commit" is an existing commit. We would want to apply
2259 * the difference it introduces since its first parent "prev"
2260 * on top of the current HEAD if we are cherry-pick. Or the
2261 * reverse of it if we are revert.
2264 if (command
== TODO_REVERT
) {
2265 const char *orig_subject
;
2268 base_label
= msg
.label
;
2270 next_label
= msg
.parent_label
;
2271 if (opts
->commit_use_reference
) {
2272 strbuf_addstr(&msgbuf
,
2273 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2274 } else if (skip_prefix(msg
.subject
, "Revert \"", &orig_subject
) &&
2276 * We don't touch pre-existing repeated reverts, because
2277 * theoretically these can be nested arbitrarily deeply,
2278 * thus requiring excessive complexity to deal with.
2280 !starts_with(orig_subject
, "Revert \"")) {
2281 strbuf_addstr(&msgbuf
, "Reapply \"");
2282 strbuf_addstr(&msgbuf
, orig_subject
);
2284 strbuf_addstr(&msgbuf
, "Revert \"");
2285 strbuf_addstr(&msgbuf
, msg
.subject
);
2286 strbuf_addstr(&msgbuf
, "\"");
2288 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2289 refer_to_commit(opts
, &msgbuf
, commit
);
2291 if (commit
->parents
&& commit
->parents
->next
) {
2292 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2293 refer_to_commit(opts
, &msgbuf
, parent
);
2295 strbuf_addstr(&msgbuf
, ".\n");
2300 base_label
= msg
.parent_label
;
2302 next_label
= msg
.label
;
2304 /* Append the commit log message to msgbuf. */
2305 if (find_commit_subject(msg
.message
, &p
))
2306 strbuf_addstr(&msgbuf
, p
);
2308 if (opts
->record_origin
) {
2309 strbuf_complete_line(&msgbuf
);
2310 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2311 strbuf_addch(&msgbuf
, '\n');
2312 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2313 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2314 strbuf_addstr(&msgbuf
, ")\n");
2316 if (!is_fixup(command
))
2317 author
= get_author(msg
.message
);
2320 if (command
== TODO_REWORD
)
2322 else if (is_fixup(command
)) {
2323 if (update_squash_messages(r
, command
, commit
,
2324 opts
, item
->flags
)) {
2330 msg_file
= rebase_path_squash_msg();
2331 else if (file_exists(rebase_path_fixup_msg())) {
2332 flags
|= VERBATIM_MSG
;
2333 msg_file
= rebase_path_fixup_msg();
2335 const char *dest
= git_path_squash_msg(r
);
2337 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2338 res
= error(_("could not copy '%s' to '%s'"),
2339 rebase_path_squash_msg(), dest
);
2342 unlink(git_path_merge_msg(r
));
2348 if (opts
->signoff
&& !is_fixup(command
))
2349 append_signoff(&msgbuf
, 0, 0);
2351 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2353 else if (!opts
->strategy
||
2354 !strcmp(opts
->strategy
, "recursive") ||
2355 !strcmp(opts
->strategy
, "ort") ||
2356 command
== TODO_REVERT
) {
2357 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2358 &head
, &msgbuf
, opts
);
2362 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2363 git_path_merge_msg(r
), 0);
2365 struct commit_list
*common
= NULL
;
2366 struct commit_list
*remotes
= NULL
;
2368 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2369 git_path_merge_msg(r
), 0);
2371 commit_list_insert(base
, &common
);
2372 commit_list_insert(next
, &remotes
);
2373 res
|= try_merge_command(r
, opts
->strategy
,
2374 opts
->xopts
.nr
, opts
->xopts
.v
,
2375 common
, oid_to_hex(&head
), remotes
);
2376 free_commit_list(common
);
2377 free_commit_list(remotes
);
2381 * If the merge was clean or if it failed due to conflict, we write
2382 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2383 * However, if the merge did not even start, then we don't want to
2386 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2387 command
== TODO_EDIT
) && !opts
->no_commit
&&
2388 (res
== 0 || res
== 1) &&
2389 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2390 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2392 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2393 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2394 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2398 error(command
== TODO_REVERT
2399 ? _("could not revert %s... %s")
2400 : _("could not apply %s... %s"),
2401 short_commit_name(r
, commit
), msg
.subject
);
2402 print_advice(r
, res
== 1, opts
);
2403 repo_rerere(r
, opts
->allow_rerere_auto
);
2408 allow
= allow_empty(r
, opts
, commit
);
2412 } else if (allow
== 1) {
2413 flags
|= ALLOW_EMPTY
;
2414 } else if (allow
== 2) {
2416 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2418 unlink(git_path_merge_msg(r
));
2419 unlink(git_path_auto_merge(r
));
2421 _("dropping %s %s -- patch contents already upstream\n"),
2422 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2423 } /* else allow == 0 and there's nothing special to do */
2424 if (!opts
->no_commit
&& !drop_commit
) {
2425 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2426 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2427 commit
? &commit
->object
.oid
: NULL
);
2429 res
= error(_("unable to parse commit author"));
2430 *check_todo
= !!(flags
& EDIT_MSG
);
2431 if (!res
&& reword
) {
2433 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2434 VERIFY_MSG
| AMEND_MSG
|
2435 (flags
& ALLOW_EMPTY
));
2441 if (!res
&& final_fixup
) {
2442 unlink(rebase_path_fixup_msg());
2443 unlink(rebase_path_squash_msg());
2444 unlink(rebase_path_current_fixups());
2445 strbuf_reset(&opts
->current_fixups
);
2446 opts
->current_fixup_count
= 0;
2450 free_message(commit
, &msg
);
2452 strbuf_release(&msgbuf
);
2453 update_abort_safety_file();
2458 static int prepare_revs(struct replay_opts
*opts
)
2461 * picking (but not reverting) ranges (but not individual revisions)
2462 * should be done in reverse
2464 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2465 opts
->revs
->reverse
^= 1;
2467 if (prepare_revision_walk(opts
->revs
))
2468 return error(_("revision walk setup failed"));
2473 static int read_and_refresh_cache(struct repository
*r
,
2474 struct replay_opts
*opts
)
2476 struct lock_file index_lock
= LOCK_INIT
;
2477 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2478 if (repo_read_index(r
) < 0) {
2479 rollback_lock_file(&index_lock
);
2480 return error(_("git %s: failed to read the index"),
2483 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2485 if (index_fd
>= 0) {
2486 if (write_locked_index(r
->index
, &index_lock
,
2487 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2488 return error(_("git %s: failed to refresh the index"),
2494 * If we are resolving merges in any way other than "ort", then
2495 * expand the sparse index.
2497 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2498 ensure_full_index(r
->index
);
2502 void todo_list_release(struct todo_list
*todo_list
)
2504 strbuf_release(&todo_list
->buf
);
2505 FREE_AND_NULL(todo_list
->items
);
2506 todo_list
->nr
= todo_list
->alloc
= 0;
2509 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2511 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2512 return todo_list
->items
+ todo_list
->nr
++;
2515 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2516 struct todo_item
*item
)
2518 return todo_list
->buf
.buf
+ item
->arg_offset
;
2521 static int is_command(enum todo_command command
, const char **bol
)
2523 const char *str
= todo_command_info
[command
].str
;
2524 const char nick
= todo_command_info
[command
].c
;
2525 const char *p
= *bol
;
2527 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2528 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2532 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2537 * '#' is not a valid label as the merge command uses it to
2538 * separate merge parents from the commit subject.
2540 if (!strcmp(arg
, "#") ||
2541 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2542 return error(_("'%s' is not a valid label"), arg
);
2545 case TODO_UPDATE_REF
:
2546 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2547 return error(_("'%s' is not a valid refname"), arg
);
2548 if (check_refname_format(arg
, 0))
2549 return error(_("update-ref requires a fully qualified "
2550 "refname e.g. refs/heads/%s"), arg
);
2554 BUG("unexpected todo_command");
2560 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2561 const char *buf
, const char *bol
, char *eol
)
2563 struct object_id commit_oid
;
2564 char *end_of_object_name
;
2565 int i
, saved
, status
, padding
;
2570 bol
+= strspn(bol
, " \t");
2572 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2573 item
->command
= TODO_COMMENT
;
2574 item
->commit
= NULL
;
2575 item
->arg_offset
= bol
- buf
;
2576 item
->arg_len
= eol
- bol
;
2580 for (i
= 0; i
< TODO_COMMENT
; i
++)
2581 if (is_command(i
, &bol
)) {
2585 if (i
>= TODO_COMMENT
)
2586 return error(_("invalid command '%.*s'"),
2587 (int)strcspn(bol
, " \t\r\n"), bol
);
2589 /* Eat up extra spaces/ tabs before object name */
2590 padding
= strspn(bol
, " \t");
2593 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2595 return error(_("%s does not accept arguments: '%s'"),
2596 command_to_string(item
->command
), bol
);
2597 item
->commit
= NULL
;
2598 item
->arg_offset
= bol
- buf
;
2599 item
->arg_len
= eol
- bol
;
2604 return error(_("missing arguments for %s"),
2605 command_to_string(item
->command
));
2607 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2608 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2611 item
->commit
= NULL
;
2612 item
->arg_offset
= bol
- buf
;
2613 item
->arg_len
= (int)(eol
- bol
);
2614 if (item
->command
== TODO_LABEL
||
2615 item
->command
== TODO_UPDATE_REF
) {
2618 ret
= check_label_or_ref_arg(item
->command
, bol
);
2624 if (item
->command
== TODO_FIXUP
) {
2625 if (skip_prefix(bol
, "-C", &bol
)) {
2626 bol
+= strspn(bol
, " \t");
2627 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2628 } else if (skip_prefix(bol
, "-c", &bol
)) {
2629 bol
+= strspn(bol
, " \t");
2630 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2634 if (item
->command
== TODO_MERGE
) {
2635 if (skip_prefix(bol
, "-C", &bol
))
2636 bol
+= strspn(bol
, " \t");
2637 else if (skip_prefix(bol
, "-c", &bol
)) {
2638 bol
+= strspn(bol
, " \t");
2639 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2641 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2642 item
->commit
= NULL
;
2643 item
->arg_offset
= bol
- buf
;
2644 item
->arg_len
= (int)(eol
- bol
);
2649 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2650 saved
= *end_of_object_name
;
2651 *end_of_object_name
= '\0';
2652 status
= repo_get_oid(r
, bol
, &commit_oid
);
2654 error(_("could not parse '%s'"), bol
); /* return later */
2655 *end_of_object_name
= saved
;
2657 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2658 item
->arg_offset
= bol
- buf
;
2659 item
->arg_len
= (int)(eol
- bol
);
2664 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2665 return item
->commit
? 0 : -1;
2668 int sequencer_get_last_command(struct repository
*r UNUSED
, enum replay_action
*action
)
2670 const char *todo_file
, *bol
;
2671 struct strbuf buf
= STRBUF_INIT
;
2674 todo_file
= git_path_todo_file();
2675 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2676 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2679 return error_errno("unable to open '%s'", todo_file
);
2681 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2682 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2683 *action
= REPLAY_PICK
;
2684 else if (is_command(TODO_REVERT
, &bol
) &&
2685 (*bol
== ' ' || *bol
== '\t'))
2686 *action
= REPLAY_REVERT
;
2690 strbuf_release(&buf
);
2695 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2696 struct todo_list
*todo_list
)
2698 struct todo_item
*item
;
2699 char *p
= buf
, *next_p
;
2700 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2702 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2704 for (i
= 1; *p
; i
++, p
= next_p
) {
2705 char *eol
= strchrnul(p
, '\n');
2707 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2709 if (p
!= eol
&& eol
[-1] == '\r')
2710 eol
--; /* strip Carriage Return */
2712 item
= append_new_todo(todo_list
);
2713 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2714 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2715 res
= error(_("invalid line %d: %.*s"),
2716 i
, (int)(eol
- p
), p
);
2717 item
->command
= TODO_COMMENT
+ 1;
2718 item
->arg_offset
= p
- buf
;
2719 item
->arg_len
= (int)(eol
- p
);
2720 item
->commit
= NULL
;
2723 if (item
->command
!= TODO_COMMENT
)
2724 todo_list
->total_nr
++;
2728 else if (is_fixup(item
->command
))
2729 res
= error(_("cannot '%s' without a previous commit"),
2730 command_to_string(item
->command
));
2731 else if (!is_noop(item
->command
))
2738 static int count_commands(struct todo_list
*todo_list
)
2742 for (i
= 0; i
< todo_list
->nr
; i
++)
2743 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2749 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2751 return index
< todo_list
->nr
?
2752 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2755 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2757 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2760 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2762 return get_item_line_offset(todo_list
, index
+ 1)
2763 - get_item_line_offset(todo_list
, index
);
2766 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2771 fd
= open(path
, O_RDONLY
);
2773 return error_errno(_("could not open '%s'"), path
);
2774 len
= strbuf_read(sb
, fd
, 0);
2777 return error(_("could not read '%s'."), path
);
2781 static int have_finished_the_last_pick(void)
2783 struct strbuf buf
= STRBUF_INIT
;
2785 const char *todo_path
= git_path_todo_file();
2788 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2789 if (errno
== ENOENT
) {
2792 error_errno("unable to open '%s'", todo_path
);
2796 /* If there is only one line then we are done */
2797 eol
= strchr(buf
.buf
, '\n');
2798 if (!eol
|| !eol
[1])
2801 strbuf_release(&buf
);
2806 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2808 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2809 int need_cleanup
= 0;
2811 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2812 if (!refs_delete_ref(get_main_ref_store(r
), "",
2813 "CHERRY_PICK_HEAD", NULL
, 0) &&
2815 warning(_("cancelling a cherry picking in progress"));
2816 opts
.action
= REPLAY_PICK
;
2820 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2821 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2824 warning(_("cancelling a revert in progress"));
2825 opts
.action
= REPLAY_REVERT
;
2829 unlink(git_path_auto_merge(r
));
2834 if (!have_finished_the_last_pick())
2837 sequencer_remove_state(&opts
);
2840 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2842 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2845 fprintf(f
, "%d\n", todo_list
->total_nr
);
2850 static int read_populate_todo(struct repository
*r
,
2851 struct todo_list
*todo_list
,
2852 struct replay_opts
*opts
)
2854 const char *todo_file
= get_todo_path(opts
);
2857 strbuf_reset(&todo_list
->buf
);
2858 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2861 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2863 if (is_rebase_i(opts
))
2864 return error(_("please fix this using "
2865 "'git rebase --edit-todo'."));
2866 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2869 if (!todo_list
->nr
&&
2870 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2871 return error(_("no commits parsed."));
2873 if (!is_rebase_i(opts
)) {
2874 enum todo_command valid
=
2875 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2878 for (i
= 0; i
< todo_list
->nr
; i
++)
2879 if (valid
== todo_list
->items
[i
].command
)
2881 else if (valid
== TODO_PICK
)
2882 return error(_("cannot cherry-pick during a revert."));
2884 return error(_("cannot revert during a cherry-pick."));
2887 if (is_rebase_i(opts
)) {
2888 struct todo_list done
= TODO_LIST_INIT
;
2890 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2891 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2892 todo_list
->done_nr
= count_commands(&done
);
2894 todo_list
->done_nr
= 0;
2896 todo_list
->total_nr
= todo_list
->done_nr
2897 + count_commands(todo_list
);
2898 todo_list_release(&done
);
2900 todo_list_write_total_nr(todo_list
);
2906 static int git_config_string_dup(char **dest
,
2907 const char *var
, const char *value
)
2910 return config_error_nonbool(var
);
2912 *dest
= xstrdup(value
);
2916 static int populate_opts_cb(const char *key
, const char *value
,
2917 const struct config_context
*ctx
,
2920 struct replay_opts
*opts
= data
;
2925 else if (!strcmp(key
, "options.no-commit"))
2926 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2927 else if (!strcmp(key
, "options.edit"))
2928 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2929 else if (!strcmp(key
, "options.allow-empty"))
2931 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2932 else if (!strcmp(key
, "options.allow-empty-message"))
2933 opts
->allow_empty_message
=
2934 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2935 else if (!strcmp(key
, "options.keep-redundant-commits"))
2936 opts
->keep_redundant_commits
=
2937 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2938 else if (!strcmp(key
, "options.signoff"))
2939 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2940 else if (!strcmp(key
, "options.record-origin"))
2941 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2942 else if (!strcmp(key
, "options.allow-ff"))
2943 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2944 else if (!strcmp(key
, "options.mainline"))
2945 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2946 else if (!strcmp(key
, "options.strategy"))
2947 git_config_string_dup(&opts
->strategy
, key
, value
);
2948 else if (!strcmp(key
, "options.gpg-sign"))
2949 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2950 else if (!strcmp(key
, "options.strategy-option")) {
2951 strvec_push(&opts
->xopts
, value
);
2952 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2953 opts
->allow_rerere_auto
=
2954 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2955 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2956 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2957 opts
->explicit_cleanup
= 1;
2958 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2960 return error(_("invalid key: %s"), key
);
2963 return error(_("invalid value for '%s': '%s'"), key
, value
);
2968 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2973 char *strategy_opts_string
= raw_opts
;
2975 if (*strategy_opts_string
== ' ')
2976 strategy_opts_string
++;
2978 count
= split_cmdline(strategy_opts_string
, &argv
);
2980 BUG("could not split '%s': %s", strategy_opts_string
,
2981 split_cmdline_strerror(count
));
2982 for (i
= 0; i
< count
; i
++) {
2983 const char *arg
= argv
[i
];
2985 skip_prefix(arg
, "--", &arg
);
2986 strvec_push(&opts
->xopts
, arg
);
2991 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2994 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2996 opts
->strategy
= strbuf_detach(buf
, NULL
);
2997 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
3000 parse_strategy_opts(opts
, buf
->buf
);
3003 static int read_populate_opts(struct replay_opts
*opts
)
3005 if (is_rebase_i(opts
)) {
3006 struct strbuf buf
= STRBUF_INIT
;
3009 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
3010 READ_ONELINER_SKIP_IF_EMPTY
)) {
3011 if (!starts_with(buf
.buf
, "-S"))
3014 free(opts
->gpg_sign
);
3015 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3020 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3021 READ_ONELINER_SKIP_IF_EMPTY
)) {
3022 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3023 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3024 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3025 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3029 if (file_exists(rebase_path_verbose()))
3032 if (file_exists(rebase_path_quiet()))
3035 if (file_exists(rebase_path_signoff())) {
3040 if (file_exists(rebase_path_cdate_is_adate())) {
3042 opts
->committer_date_is_author_date
= 1;
3045 if (file_exists(rebase_path_ignore_date())) {
3047 opts
->ignore_date
= 1;
3050 if (file_exists(rebase_path_reschedule_failed_exec()))
3051 opts
->reschedule_failed_exec
= 1;
3052 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3053 opts
->reschedule_failed_exec
= 0;
3055 if (file_exists(rebase_path_drop_redundant_commits()))
3056 opts
->drop_redundant_commits
= 1;
3058 if (file_exists(rebase_path_keep_redundant_commits()))
3059 opts
->keep_redundant_commits
= 1;
3061 read_strategy_opts(opts
, &buf
);
3064 if (read_oneliner(&opts
->current_fixups
,
3065 rebase_path_current_fixups(),
3066 READ_ONELINER_SKIP_IF_EMPTY
)) {
3067 const char *p
= opts
->current_fixups
.buf
;
3068 opts
->current_fixup_count
= 1;
3069 while ((p
= strchr(p
, '\n'))) {
3070 opts
->current_fixup_count
++;
3075 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3076 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3077 ret
= error(_("unusable squash-onto"));
3080 opts
->have_squash_onto
= 1;
3084 strbuf_release(&buf
);
3088 if (!file_exists(git_path_opts_file()))
3091 * The function git_parse_source(), called from git_config_from_file(),
3092 * may die() in case of a syntactically incorrect file. We do not care
3093 * about this case, though, because we wrote that file ourselves, so we
3094 * are pretty certain that it is syntactically correct.
3096 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3097 return error(_("malformed options sheet: '%s'"),
3098 git_path_opts_file());
3102 static void write_strategy_opts(struct replay_opts
*opts
)
3104 struct strbuf buf
= STRBUF_INIT
;
3107 * Quote strategy options so that they can be read correctly
3108 * by split_cmdline().
3110 quote_cmdline(&buf
, opts
->xopts
.v
);
3111 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3112 strbuf_release(&buf
);
3115 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3116 struct commit
*onto
, const struct object_id
*orig_head
)
3119 write_file(rebase_path_head_name(), "%s\n", head_name
);
3121 write_file(rebase_path_onto(), "%s\n",
3122 oid_to_hex(&onto
->object
.oid
));
3124 write_file(rebase_path_orig_head(), "%s\n",
3125 oid_to_hex(orig_head
));
3128 write_file(rebase_path_quiet(), "%s", "");
3130 write_file(rebase_path_verbose(), "%s", "");
3132 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3133 if (opts
->xopts
.nr
> 0)
3134 write_strategy_opts(opts
);
3136 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3137 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3138 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3139 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3142 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3144 write_file(rebase_path_signoff(), "--signoff\n");
3145 if (opts
->drop_redundant_commits
)
3146 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3147 if (opts
->keep_redundant_commits
)
3148 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3149 if (opts
->committer_date_is_author_date
)
3150 write_file(rebase_path_cdate_is_adate(), "%s", "");
3151 if (opts
->ignore_date
)
3152 write_file(rebase_path_ignore_date(), "%s", "");
3153 if (opts
->reschedule_failed_exec
)
3154 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3156 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3161 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3162 struct replay_opts
*opts
)
3164 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3165 TODO_PICK
: TODO_REVERT
;
3166 const char *command_string
= todo_command_info
[command
].str
;
3167 const char *encoding
;
3168 struct commit
*commit
;
3170 if (prepare_revs(opts
))
3173 encoding
= get_log_output_encoding();
3175 while ((commit
= get_revision(opts
->revs
))) {
3176 struct todo_item
*item
= append_new_todo(todo_list
);
3177 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3180 const char *subject
;
3183 item
->command
= command
;
3184 item
->commit
= commit
;
3185 item
->arg_offset
= 0;
3187 item
->offset_in_buf
= todo_list
->buf
.len
;
3188 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3189 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3190 short_commit_name(the_repository
, commit
),
3191 subject_len
, subject
);
3192 repo_unuse_commit_buffer(the_repository
, commit
,
3197 return error(_("empty commit set passed"));
3202 static int create_seq_dir(struct repository
*r
)
3204 enum replay_action action
;
3205 const char *in_progress_error
= NULL
;
3206 const char *in_progress_advice
= NULL
;
3207 unsigned int advise_skip
=
3208 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3209 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3211 if (!sequencer_get_last_command(r
, &action
)) {
3214 in_progress_error
= _("revert is already in progress");
3215 in_progress_advice
=
3216 _("try \"git revert (--continue | %s--abort | --quit)\"");
3219 in_progress_error
= _("cherry-pick is already in progress");
3220 in_progress_advice
=
3221 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3224 BUG("unexpected action in create_seq_dir");
3227 if (in_progress_error
) {
3228 error("%s", in_progress_error
);
3229 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3230 advise(in_progress_advice
,
3231 advise_skip
? "--skip | " : "");
3234 if (mkdir(git_path_seq_dir(), 0777) < 0)
3235 return error_errno(_("could not create sequencer directory '%s'"),
3236 git_path_seq_dir());
3241 static int save_head(const char *head
)
3243 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3246 static int rollback_is_safe(void)
3248 struct strbuf sb
= STRBUF_INIT
;
3249 struct object_id expected_head
, actual_head
;
3251 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3253 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3254 strbuf_release(&sb
);
3255 die(_("could not parse %s"), git_path_abort_safety_file());
3257 strbuf_release(&sb
);
3259 else if (errno
== ENOENT
)
3260 oidclr(&expected_head
);
3262 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3264 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3265 oidclr(&actual_head
);
3267 return oideq(&actual_head
, &expected_head
);
3270 static int reset_merge(const struct object_id
*oid
)
3272 struct child_process cmd
= CHILD_PROCESS_INIT
;
3275 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3277 if (!is_null_oid(oid
))
3278 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3280 return run_command(&cmd
);
3283 static int rollback_single_pick(struct repository
*r
)
3285 struct object_id head_oid
;
3287 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3288 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3289 return error(_("no cherry-pick or revert in progress"));
3290 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3291 return error(_("cannot resolve HEAD"));
3292 if (is_null_oid(&head_oid
))
3293 return error(_("cannot abort from a branch yet to be born"));
3294 return reset_merge(&head_oid
);
3297 static int skip_single_pick(void)
3299 struct object_id head
;
3301 if (read_ref_full("HEAD", 0, &head
, NULL
))
3302 return error(_("cannot resolve HEAD"));
3303 return reset_merge(&head
);
3306 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3309 struct object_id oid
;
3310 struct strbuf buf
= STRBUF_INIT
;
3313 f
= fopen(git_path_head_file(), "r");
3314 if (!f
&& errno
== ENOENT
) {
3316 * There is no multiple-cherry-pick in progress.
3317 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3318 * a single-cherry-pick in progress, abort that.
3320 return rollback_single_pick(r
);
3323 return error_errno(_("cannot open '%s'"), git_path_head_file());
3324 if (strbuf_getline_lf(&buf
, f
)) {
3325 error(_("cannot read '%s': %s"), git_path_head_file(),
3326 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3331 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3332 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3333 git_path_head_file());
3336 if (is_null_oid(&oid
)) {
3337 error(_("cannot abort from a branch yet to be born"));
3341 if (!rollback_is_safe()) {
3342 /* Do not error, just do not rollback */
3343 warning(_("You seem to have moved HEAD. "
3344 "Not rewinding, check your HEAD!"));
3346 if (reset_merge(&oid
))
3348 strbuf_release(&buf
);
3349 return sequencer_remove_state(opts
);
3351 strbuf_release(&buf
);
3355 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3357 enum replay_action action
= -1;
3358 sequencer_get_last_command(r
, &action
);
3361 * Check whether the subcommand requested to skip the commit is actually
3362 * in progress and that it's safe to skip the commit.
3364 * opts->action tells us which subcommand requested to skip the commit.
3365 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3366 * action is in progress and we can skip the commit.
3368 * Otherwise we check that the last instruction was related to the
3369 * particular subcommand we're trying to execute and barf if that's not
3372 * Finally we check that the rollback is "safe", i.e., has the HEAD
3373 * moved? In this case, it doesn't make sense to "reset the merge" and
3374 * "skip the commit" as the user already handled this by committing. But
3375 * we'd not want to barf here, instead give advice on how to proceed. We
3376 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3377 * it gets removed when the user commits, so if it still exists we're
3378 * sure the user can't have committed before.
3380 switch (opts
->action
) {
3382 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3383 if (action
!= REPLAY_REVERT
)
3384 return error(_("no revert in progress"));
3385 if (!rollback_is_safe())
3390 if (!refs_ref_exists(get_main_ref_store(r
),
3391 "CHERRY_PICK_HEAD")) {
3392 if (action
!= REPLAY_PICK
)
3393 return error(_("no cherry-pick in progress"));
3394 if (!rollback_is_safe())
3399 BUG("unexpected action in sequencer_skip");
3402 if (skip_single_pick())
3403 return error(_("failed to skip the commit"));
3404 if (!is_directory(git_path_seq_dir()))
3407 return sequencer_continue(r
, opts
);
3410 error(_("there is nothing to skip"));
3412 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3413 advise(_("have you committed already?\n"
3414 "try \"git %s --continue\""),
3415 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3420 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
,
3423 struct lock_file todo_lock
= LOCK_INIT
;
3424 const char *todo_path
= get_todo_path(opts
);
3425 int next
= todo_list
->current
, offset
, fd
;
3428 * rebase -i writes "git-rebase-todo" without the currently executing
3429 * command, appending it to "done" instead.
3431 if (is_rebase_i(opts
) && !reschedule
)
3434 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3436 return error_errno(_("could not lock '%s'"), todo_path
);
3437 offset
= get_item_line_offset(todo_list
, next
);
3438 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3439 todo_list
->buf
.len
- offset
) < 0)
3440 return error_errno(_("could not write to '%s'"), todo_path
);
3441 if (commit_lock_file(&todo_lock
) < 0)
3442 return error(_("failed to finalize '%s'"), todo_path
);
3444 if (is_rebase_i(opts
) && !reschedule
&& next
> 0) {
3445 const char *done
= rebase_path_done();
3446 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3451 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3452 get_item_line_length(todo_list
, next
- 1))
3454 ret
= error_errno(_("could not write to '%s'"), done
);
3456 ret
= error_errno(_("failed to finalize '%s'"), done
);
3462 static int save_opts(struct replay_opts
*opts
)
3464 const char *opts_file
= git_path_opts_file();
3467 if (opts
->no_commit
)
3468 res
|= git_config_set_in_file_gently(opts_file
,
3469 "options.no-commit", "true");
3470 if (opts
->edit
>= 0)
3471 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3472 opts
->edit
? "true" : "false");
3473 if (opts
->allow_empty
)
3474 res
|= git_config_set_in_file_gently(opts_file
,
3475 "options.allow-empty", "true");
3476 if (opts
->allow_empty_message
)
3477 res
|= git_config_set_in_file_gently(opts_file
,
3478 "options.allow-empty-message", "true");
3479 if (opts
->keep_redundant_commits
)
3480 res
|= git_config_set_in_file_gently(opts_file
,
3481 "options.keep-redundant-commits", "true");
3483 res
|= git_config_set_in_file_gently(opts_file
,
3484 "options.signoff", "true");
3485 if (opts
->record_origin
)
3486 res
|= git_config_set_in_file_gently(opts_file
,
3487 "options.record-origin", "true");
3489 res
|= git_config_set_in_file_gently(opts_file
,
3490 "options.allow-ff", "true");
3491 if (opts
->mainline
) {
3492 struct strbuf buf
= STRBUF_INIT
;
3493 strbuf_addf(&buf
, "%d", opts
->mainline
);
3494 res
|= git_config_set_in_file_gently(opts_file
,
3495 "options.mainline", buf
.buf
);
3496 strbuf_release(&buf
);
3499 res
|= git_config_set_in_file_gently(opts_file
,
3500 "options.strategy", opts
->strategy
);
3502 res
|= git_config_set_in_file_gently(opts_file
,
3503 "options.gpg-sign", opts
->gpg_sign
);
3504 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3505 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3506 "options.strategy-option",
3507 opts
->xopts
.v
[i
], "^$", 0);
3508 if (opts
->allow_rerere_auto
)
3509 res
|= git_config_set_in_file_gently(opts_file
,
3510 "options.allow-rerere-auto",
3511 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3514 if (opts
->explicit_cleanup
)
3515 res
|= git_config_set_in_file_gently(opts_file
,
3516 "options.default-msg-cleanup",
3517 describe_cleanup_mode(opts
->default_msg_cleanup
));
3521 static int make_patch(struct repository
*r
,
3522 struct commit
*commit
,
3523 struct replay_opts
*opts
)
3525 struct rev_info log_tree_opt
;
3526 const char *subject
;
3527 char hex
[GIT_MAX_HEXSZ
+ 1];
3530 if (!is_rebase_i(opts
))
3531 BUG("make_patch should only be called when rebasing");
3533 oid_to_hex_r(hex
, &commit
->object
.oid
);
3534 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3536 res
|= write_rebase_head(&commit
->object
.oid
);
3538 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3539 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3540 log_tree_opt
.abbrev
= 0;
3541 log_tree_opt
.diff
= 1;
3542 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3543 log_tree_opt
.disable_stdin
= 1;
3544 log_tree_opt
.no_commit_id
= 1;
3545 log_tree_opt
.diffopt
.file
= fopen(rebase_path_patch(), "w");
3546 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3547 if (!log_tree_opt
.diffopt
.file
)
3548 res
|= error_errno(_("could not open '%s'"),
3549 rebase_path_patch());
3551 res
|= log_tree_commit(&log_tree_opt
, commit
);
3552 fclose(log_tree_opt
.diffopt
.file
);
3555 if (!file_exists(rebase_path_message())) {
3556 const char *encoding
= get_commit_output_encoding();
3557 const char *commit_buffer
= repo_logmsg_reencode(r
,
3560 find_commit_subject(commit_buffer
, &subject
);
3561 res
|= write_message(subject
, strlen(subject
), rebase_path_message(), 1);
3562 repo_unuse_commit_buffer(r
, commit
,
3565 release_revisions(&log_tree_opt
);
3570 static int intend_to_amend(void)
3572 struct object_id head
;
3575 if (repo_get_oid(the_repository
, "HEAD", &head
))
3576 return error(_("cannot read HEAD"));
3578 p
= oid_to_hex(&head
);
3579 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3582 static int error_with_patch(struct repository
*r
,
3583 struct commit
*commit
,
3584 const char *subject
, int subject_len
,
3585 struct replay_opts
*opts
,
3586 int exit_code
, int to_amend
)
3589 if (make_patch(r
, commit
, opts
))
3591 } else if (copy_file(rebase_path_message(),
3592 git_path_merge_msg(r
), 0666))
3593 return error(_("unable to copy '%s' to '%s'"),
3594 git_path_merge_msg(r
), rebase_path_message());
3597 if (intend_to_amend())
3601 _("You can amend the commit now, with\n"
3603 " git commit --amend %s\n"
3605 "Once you are satisfied with your changes, run\n"
3607 " git rebase --continue\n"),
3608 gpg_sign_opt_quoted(opts
));
3609 } else if (exit_code
) {
3611 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3612 short_commit_name(r
, commit
), subject_len
, subject
);
3615 * We don't have the hash of the parent so
3616 * just print the line from the todo file.
3618 fprintf_ln(stderr
, _("Could not merge %.*s"),
3619 subject_len
, subject
);
3625 static int error_failed_squash(struct repository
*r
,
3626 struct commit
*commit
,
3627 struct replay_opts
*opts
,
3629 const char *subject
)
3631 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3632 return error(_("could not copy '%s' to '%s'"),
3633 rebase_path_squash_msg(), rebase_path_message());
3634 unlink(git_path_merge_msg(r
));
3635 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3636 return error(_("could not copy '%s' to '%s'"),
3637 rebase_path_message(),
3638 git_path_merge_msg(r
));
3639 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3642 static int do_exec(struct repository
*r
, const char *command_line
)
3644 struct child_process cmd
= CHILD_PROCESS_INIT
;
3647 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3649 strvec_push(&cmd
.args
, command_line
);
3650 strvec_push(&cmd
.env
, "GIT_CHERRY_PICK_HELP");
3651 status
= run_command(&cmd
);
3653 /* force re-reading of the cache */
3654 discard_index(r
->index
);
3655 if (repo_read_index(r
) < 0)
3656 return error(_("could not read index"));
3658 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3661 warning(_("execution failed: %s\n%s"
3662 "You can fix the problem, and then run\n"
3664 " git rebase --continue\n"
3667 dirty
? _("and made changes to the index and/or the "
3668 "working tree.\n") : "");
3670 /* command not found */
3673 warning(_("execution succeeded: %s\nbut "
3674 "left changes to the index and/or the working tree.\n"
3675 "Commit or stash your changes, and then run\n"
3677 " git rebase --continue\n"
3678 "\n"), command_line
);
3685 __attribute__((format (printf
, 2, 3)))
3686 static int safe_append(const char *filename
, const char *fmt
, ...)
3689 struct lock_file lock
= LOCK_INIT
;
3690 int fd
= hold_lock_file_for_update(&lock
, filename
,
3691 LOCK_REPORT_ON_ERROR
);
3692 struct strbuf buf
= STRBUF_INIT
;
3697 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3698 error_errno(_("could not read '%s'"), filename
);
3699 rollback_lock_file(&lock
);
3702 strbuf_complete(&buf
, '\n');
3704 strbuf_vaddf(&buf
, fmt
, ap
);
3707 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3708 error_errno(_("could not write to '%s'"), filename
);
3709 strbuf_release(&buf
);
3710 rollback_lock_file(&lock
);
3713 if (commit_lock_file(&lock
) < 0) {
3714 strbuf_release(&buf
);
3715 return error(_("failed to finalize '%s'"), filename
);
3718 strbuf_release(&buf
);
3722 static int do_label(struct repository
*r
, const char *name
, int len
)
3724 struct ref_store
*refs
= get_main_ref_store(r
);
3725 struct ref_transaction
*transaction
;
3726 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3727 struct strbuf msg
= STRBUF_INIT
;
3729 struct object_id head_oid
;
3731 if (len
== 1 && *name
== '#')
3732 return error(_("illegal label name: '%.*s'"), len
, name
);
3734 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3735 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3737 transaction
= ref_store_transaction_begin(refs
, &err
);
3739 error("%s", err
.buf
);
3741 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3742 error(_("could not read HEAD"));
3744 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3745 NULL
, 0, msg
.buf
, &err
) < 0 ||
3746 ref_transaction_commit(transaction
, &err
)) {
3747 error("%s", err
.buf
);
3750 ref_transaction_free(transaction
);
3751 strbuf_release(&err
);
3752 strbuf_release(&msg
);
3755 ret
= safe_append(rebase_path_refs_to_delete(),
3756 "%s\n", ref_name
.buf
);
3757 strbuf_release(&ref_name
);
3762 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3764 if (!opts
->reflog_action
) {
3765 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3766 opts
->reflog_action
=
3767 xstrdup(opts
->reflog_action
? opts
->reflog_action
3768 : action_name(opts
));
3771 return opts
->reflog_action
;
3774 __attribute__((format (printf
, 3, 4)))
3775 static const char *reflog_message(struct replay_opts
*opts
,
3776 const char *sub_action
, const char *fmt
, ...)
3779 static struct strbuf buf
= STRBUF_INIT
;
3783 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3785 strbuf_addf(&buf
, " (%s)", sub_action
);
3787 strbuf_addstr(&buf
, ": ");
3788 strbuf_vaddf(&buf
, fmt
, ap
);
3795 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3796 int len
, struct strbuf
*buf
)
3798 struct commit
*commit
;
3799 struct object_id oid
;
3802 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3803 if (!read_ref(buf
->buf
, &oid
)) {
3804 commit
= lookup_commit_object(r
, &oid
);
3806 /* fall back to non-rewritten ref or commit */
3807 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3808 commit
= lookup_commit_reference_by_name(buf
->buf
);
3812 error(_("could not resolve '%s'"), buf
->buf
);
3817 static int do_reset(struct repository
*r
,
3818 const char *name
, int len
,
3819 struct replay_opts
*opts
)
3821 struct strbuf ref_name
= STRBUF_INIT
;
3822 struct object_id oid
;
3823 struct lock_file lock
= LOCK_INIT
;
3824 struct tree_desc desc
= { 0 };
3826 struct unpack_trees_options unpack_tree_opts
= { 0 };
3829 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3832 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3833 if (!opts
->have_squash_onto
) {
3835 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3836 NULL
, &opts
->squash_onto
,
3838 return error(_("writing fake root commit"));
3839 opts
->have_squash_onto
= 1;
3840 hex
= oid_to_hex(&opts
->squash_onto
);
3841 if (write_message(hex
, strlen(hex
),
3842 rebase_path_squash_onto(), 0))
3843 return error(_("writing squash-onto"));
3845 oidcpy(&oid
, &opts
->squash_onto
);
3848 struct commit
*commit
;
3850 /* Determine the length of the label */
3851 for (i
= 0; i
< len
; i
++)
3852 if (isspace(name
[i
]))
3856 commit
= lookup_label(r
, name
, len
, &ref_name
);
3861 oid
= commit
->object
.oid
;
3864 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3865 unpack_tree_opts
.head_idx
= 1;
3866 unpack_tree_opts
.src_index
= r
->index
;
3867 unpack_tree_opts
.dst_index
= r
->index
;
3868 unpack_tree_opts
.fn
= oneway_merge
;
3869 unpack_tree_opts
.merge
= 1;
3870 unpack_tree_opts
.update
= 1;
3871 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3872 unpack_tree_opts
.skip_cache_tree_update
= 1;
3873 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3875 if (repo_read_index_unmerged(r
)) {
3876 ret
= error_resolve_conflict(action_name(opts
));
3880 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3881 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3885 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3890 tree
= parse_tree_indirect(&oid
);
3891 prime_cache_tree(r
, r
->index
, tree
);
3893 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3894 ret
= error(_("could not write index"));
3897 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3898 len
, name
), "HEAD", &oid
,
3899 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3901 free((void *)desc
.buffer
);
3903 rollback_lock_file(&lock
);
3904 strbuf_release(&ref_name
);
3905 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3909 static int do_merge(struct repository
*r
,
3910 struct commit
*commit
,
3911 const char *arg
, int arg_len
,
3912 int flags
, int *check_todo
, struct replay_opts
*opts
)
3914 int run_commit_flags
= 0;
3915 struct strbuf ref_name
= STRBUF_INIT
;
3916 struct commit
*head_commit
, *merge_commit
, *i
;
3917 struct commit_list
*bases
, *j
;
3918 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3919 const char *strategy
= !opts
->xopts
.nr
&&
3921 !strcmp(opts
->strategy
, "recursive") ||
3922 !strcmp(opts
->strategy
, "ort")) ?
3923 NULL
: opts
->strategy
;
3924 struct merge_options o
;
3925 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3926 static struct lock_file lock
;
3929 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3934 head_commit
= lookup_commit_reference_by_name("HEAD");
3936 ret
= error(_("cannot merge without a current revision"));
3941 * For octopus merges, the arg starts with the list of revisions to be
3942 * merged. The list is optionally followed by '#' and the oneline.
3944 merge_arg_len
= oneline_offset
= arg_len
;
3945 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3948 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3949 p
+= 1 + strspn(p
+ 1, " \t\n");
3950 oneline_offset
= p
- arg
;
3953 k
= strcspn(p
, " \t\n");
3956 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3957 if (!merge_commit
) {
3958 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3961 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3963 merge_arg_len
= p
- arg
;
3967 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3971 if (opts
->have_squash_onto
&&
3972 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3974 * When the user tells us to "merge" something into a
3975 * "[new root]", let's simply fast-forward to the merge head.
3977 rollback_lock_file(&lock
);
3979 ret
= error(_("octopus merge cannot be executed on "
3980 "top of a [new root]"));
3982 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3983 &head_commit
->object
.oid
, 0,
3989 * If HEAD is not identical to the first parent of the original merge
3990 * commit, we cannot fast-forward.
3992 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3993 oideq(&commit
->parents
->item
->object
.oid
,
3994 &head_commit
->object
.oid
);
3997 * If any merge head is different from the original one, we cannot
4000 if (can_fast_forward
) {
4001 struct commit_list
*p
= commit
->parents
->next
;
4003 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
4004 if (!oideq(&j
->item
->object
.oid
,
4005 &p
->item
->object
.oid
)) {
4006 can_fast_forward
= 0;
4010 * If the number of merge heads differs from the original merge
4011 * commit, we cannot fast-forward.
4014 can_fast_forward
= 0;
4017 if (can_fast_forward
) {
4018 rollback_lock_file(&lock
);
4019 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4020 &head_commit
->object
.oid
, 0, opts
);
4021 if (flags
& TODO_EDIT_MERGE_MSG
)
4022 goto fast_forward_edit
;
4028 const char *encoding
= get_commit_output_encoding();
4029 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4035 ret
= error(_("could not get commit message of '%s'"),
4036 oid_to_hex(&commit
->object
.oid
));
4039 write_author_script(message
);
4040 find_commit_subject(message
, &body
);
4042 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4043 repo_unuse_commit_buffer(r
, commit
, message
);
4045 error_errno(_("could not write '%s'"),
4046 git_path_merge_msg(r
));
4050 struct strbuf buf
= STRBUF_INIT
;
4053 strbuf_addf(&buf
, "author %s", git_author_info(0));
4054 write_author_script(buf
.buf
);
4057 if (oneline_offset
< arg_len
) {
4058 p
= arg
+ oneline_offset
;
4059 len
= arg_len
- oneline_offset
;
4061 strbuf_addf(&buf
, "Merge %s '%.*s'",
4062 to_merge
->next
? "branches" : "branch",
4063 merge_arg_len
, arg
);
4068 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4069 strbuf_release(&buf
);
4071 error_errno(_("could not write '%s'"),
4072 git_path_merge_msg(r
));
4077 if (strategy
|| to_merge
->next
) {
4079 struct child_process cmd
= CHILD_PROCESS_INIT
;
4081 if (read_env_script(&cmd
.env
)) {
4082 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4084 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4088 if (opts
->committer_date_is_author_date
)
4089 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4092 author_date_from_env(&cmd
.env
));
4093 if (opts
->ignore_date
)
4094 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4097 strvec_push(&cmd
.args
, "merge");
4098 strvec_push(&cmd
.args
, "-s");
4100 strvec_push(&cmd
.args
, "octopus");
4102 strvec_push(&cmd
.args
, strategy
);
4103 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4104 strvec_pushf(&cmd
.args
,
4105 "-X%s", opts
->xopts
.v
[k
]);
4107 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4108 strvec_push(&cmd
.args
, "--no-edit");
4110 strvec_push(&cmd
.args
, "--edit");
4111 strvec_push(&cmd
.args
, "--no-ff");
4112 strvec_push(&cmd
.args
, "--no-log");
4113 strvec_push(&cmd
.args
, "--no-stat");
4114 strvec_push(&cmd
.args
, "-F");
4115 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4117 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4119 strvec_push(&cmd
.args
, "--no-gpg-sign");
4121 /* Add the tips to be merged */
4122 for (j
= to_merge
; j
; j
= j
->next
)
4123 strvec_push(&cmd
.args
,
4124 oid_to_hex(&j
->item
->object
.oid
));
4126 strbuf_release(&ref_name
);
4127 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4129 rollback_lock_file(&lock
);
4131 ret
= run_command(&cmd
);
4133 /* force re-reading of the cache */
4135 discard_index(r
->index
);
4136 if (repo_read_index(r
) < 0)
4137 ret
= error(_("could not read index"));
4142 merge_commit
= to_merge
->item
;
4143 bases
= repo_get_merge_bases(r
, head_commit
, merge_commit
);
4144 if (bases
&& oideq(&merge_commit
->object
.oid
,
4145 &bases
->item
->object
.oid
)) {
4147 /* skip merging an ancestor of HEAD */
4151 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4152 git_path_merge_head(r
), 0);
4153 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4155 bases
= reverse_commit_list(bases
);
4158 init_merge_options(&o
, r
);
4160 o
.branch2
= ref_name
.buf
;
4161 o
.buffer_output
= 2;
4163 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4165 * TODO: Should use merge_incore_recursive() and
4166 * merge_switch_to_result(), skipping the call to
4167 * merge_switch_to_result() when we don't actually need to
4168 * update the index and working copy immediately.
4170 ret
= merge_ort_recursive(&o
,
4171 head_commit
, merge_commit
, bases
,
4174 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4178 fputs(o
.obuf
.buf
, stdout
);
4179 strbuf_release(&o
.obuf
);
4181 error(_("could not even attempt to merge '%.*s'"),
4182 merge_arg_len
, arg
);
4183 unlink(git_path_merge_msg(r
));
4187 * The return value of merge_recursive() is 1 on clean, and 0 on
4190 * Let's reverse that, so that do_merge() returns 0 upon success and
4191 * 1 upon failed merge (keeping the return value -1 for the cases where
4192 * we will want to reschedule the `merge` command).
4196 if (r
->index
->cache_changed
&&
4197 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4198 ret
= error(_("merge: Unable to write new index file"));
4202 rollback_lock_file(&lock
);
4204 repo_rerere(r
, opts
->allow_rerere_auto
);
4207 * In case of problems, we now want to return a positive
4208 * value (a negative one would indicate that the `merge`
4209 * command needs to be rescheduled).
4211 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4214 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4217 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4218 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4223 strbuf_release(&ref_name
);
4224 rollback_lock_file(&lock
);
4225 free_commit_list(to_merge
);
4229 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4232 struct lock_file lock
= LOCK_INIT
;
4234 struct string_list_item
*item
;
4237 path
= rebase_path_update_refs(the_repository
->gitdir
);
4239 if (!refs_to_oids
->nr
) {
4240 if (unlink(path
) && errno
!= ENOENT
)
4241 result
= error_errno(_("could not unlink: %s"), path
);
4245 if (safe_create_leading_directories(path
)) {
4246 result
= error(_("unable to create leading directories of %s"),
4251 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4252 result
= error(_("another 'rebase' process appears to be running; "
4253 "'%s.lock' already exists"),
4258 fp
= fdopen_lock_file(&lock
, "w");
4260 result
= error_errno(_("could not open '%s' for writing"), path
);
4261 rollback_lock_file(&lock
);
4265 for_each_string_list_item(item
, refs_to_oids
) {
4266 struct update_ref_record
*rec
= item
->util
;
4267 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4268 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4271 result
= commit_lock_file(&lock
);
4279 * Parse the update-refs file for the current rebase, then remove the
4280 * refs that do not appear in the todo_list (and have not had updated
4281 * values stored) and add refs that are in the todo_list but not
4282 * represented in the update-refs file.
4284 * If there are changes to the update-refs list, then write the new state
4287 void todo_list_filter_update_refs(struct repository
*r
,
4288 struct todo_list
*todo_list
)
4292 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4294 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4297 * For each item in the update_refs list, if it has no updated
4298 * value and does not appear in the todo_list, then remove it
4299 * from the update_refs list.
4301 for (i
= 0; i
< update_refs
.nr
; i
++) {
4304 const char *ref
= update_refs
.items
[i
].string
;
4305 size_t reflen
= strlen(ref
);
4306 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4308 /* OID already stored as updated. */
4309 if (!is_null_oid(&rec
->after
))
4312 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4313 struct todo_item
*item
= &todo_list
->items
[j
];
4314 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4316 if (item
->command
!= TODO_UPDATE_REF
)
4319 if (item
->arg_len
!= reflen
||
4320 strncmp(arg
, ref
, reflen
))
4327 free(update_refs
.items
[i
].string
);
4328 free(update_refs
.items
[i
].util
);
4331 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4339 * For each todo_item, check if its ref is in the update_refs list.
4340 * If not, then add it as an un-updated ref.
4342 for (i
= 0; i
< todo_list
->nr
; i
++) {
4343 struct todo_item
*item
= &todo_list
->items
[i
];
4344 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4347 if (item
->command
!= TODO_UPDATE_REF
)
4350 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4351 const char *ref
= update_refs
.items
[j
].string
;
4353 found
= strlen(ref
) == item
->arg_len
&&
4354 !strncmp(ref
, arg
, item
->arg_len
);
4358 struct string_list_item
*inserted
;
4359 struct strbuf argref
= STRBUF_INIT
;
4361 strbuf_add(&argref
, arg
, item
->arg_len
);
4362 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4363 inserted
->util
= init_update_ref_record(argref
.buf
);
4364 strbuf_release(&argref
);
4370 write_update_refs_state(&update_refs
);
4371 string_list_clear(&update_refs
, 1);
4374 static int do_update_ref(struct repository
*r
, const char *refname
)
4376 struct string_list_item
*item
;
4377 struct string_list list
= STRING_LIST_INIT_DUP
;
4379 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4382 for_each_string_list_item(item
, &list
) {
4383 if (!strcmp(item
->string
, refname
)) {
4384 struct update_ref_record
*rec
= item
->util
;
4385 if (read_ref("HEAD", &rec
->after
))
4391 write_update_refs_state(&list
);
4392 string_list_clear(&list
, 1);
4396 static int do_update_refs(struct repository
*r
, int quiet
)
4399 struct string_list_item
*item
;
4400 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4401 struct ref_store
*refs
= get_main_ref_store(r
);
4402 struct strbuf update_msg
= STRBUF_INIT
;
4403 struct strbuf error_msg
= STRBUF_INIT
;
4405 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4408 for_each_string_list_item(item
, &refs_to_oids
) {
4409 struct update_ref_record
*rec
= item
->util
;
4412 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4414 &rec
->after
, &rec
->before
,
4415 0, UPDATE_REFS_MSG_ON_ERR
);
4422 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4424 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4428 (update_msg
.len
|| error_msg
.len
)) {
4430 _("Updated the following refs with %s:\n%s"),
4436 _("Failed to update the following refs with %s:\n%s"),
4441 string_list_clear(&refs_to_oids
, 1);
4442 strbuf_release(&update_msg
);
4443 strbuf_release(&error_msg
);
4447 static int is_final_fixup(struct todo_list
*todo_list
)
4449 int i
= todo_list
->current
;
4451 if (!is_fixup(todo_list
->items
[i
].command
))
4454 while (++i
< todo_list
->nr
)
4455 if (is_fixup(todo_list
->items
[i
].command
))
4457 else if (!is_noop(todo_list
->items
[i
].command
))
4462 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4466 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4467 if (!is_noop(todo_list
->items
[i
].command
))
4468 return todo_list
->items
[i
].command
;
4473 void create_autostash(struct repository
*r
, const char *path
)
4475 struct strbuf buf
= STRBUF_INIT
;
4476 struct lock_file lock_file
= LOCK_INIT
;
4479 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4480 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4482 repo_update_index_if_able(r
, &lock_file
);
4483 rollback_lock_file(&lock_file
);
4485 if (has_unstaged_changes(r
, 1) ||
4486 has_uncommitted_changes(r
, 1)) {
4487 struct child_process stash
= CHILD_PROCESS_INIT
;
4488 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4489 struct object_id oid
;
4491 strvec_pushl(&stash
.args
,
4492 "stash", "create", "autostash", NULL
);
4496 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4497 die(_("Cannot autostash"));
4498 strbuf_trim_trailing_newline(&buf
);
4499 if (repo_get_oid(r
, buf
.buf
, &oid
))
4500 die(_("Unexpected stash response: '%s'"),
4503 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4505 if (safe_create_leading_directories_const(path
))
4506 die(_("Could not create directory for '%s'"),
4508 write_file(path
, "%s", oid_to_hex(&oid
));
4509 printf(_("Created autostash: %s\n"), buf
.buf
);
4510 if (reset_head(r
, &ropts
) < 0)
4511 die(_("could not reset --hard"));
4512 discard_index(r
->index
);
4513 if (repo_read_index(r
) < 0)
4514 die(_("could not read index"));
4516 strbuf_release(&buf
);
4519 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4521 struct child_process child
= CHILD_PROCESS_INIT
;
4524 if (attempt_apply
) {
4526 child
.no_stdout
= 1;
4527 child
.no_stderr
= 1;
4528 strvec_push(&child
.args
, "stash");
4529 strvec_push(&child
.args
, "apply");
4530 strvec_push(&child
.args
, stash_oid
);
4531 ret
= run_command(&child
);
4534 if (attempt_apply
&& !ret
)
4535 fprintf(stderr
, _("Applied autostash.\n"));
4537 struct child_process store
= CHILD_PROCESS_INIT
;
4540 strvec_push(&store
.args
, "stash");
4541 strvec_push(&store
.args
, "store");
4542 strvec_push(&store
.args
, "-m");
4543 strvec_push(&store
.args
, "autostash");
4544 strvec_push(&store
.args
, "-q");
4545 strvec_push(&store
.args
, stash_oid
);
4546 if (run_command(&store
))
4547 ret
= error(_("cannot store %s"), stash_oid
);
4551 "Your changes are safe in the stash.\n"
4552 "You can run \"git stash pop\" or"
4553 " \"git stash drop\" at any time.\n"),
4555 _("Applying autostash resulted in conflicts.") :
4556 _("Autostash exists; creating a new stash entry."));
4562 static int apply_save_autostash(const char *path
, int attempt_apply
)
4564 struct strbuf stash_oid
= STRBUF_INIT
;
4567 if (!read_oneliner(&stash_oid
, path
,
4568 READ_ONELINER_SKIP_IF_EMPTY
)) {
4569 strbuf_release(&stash_oid
);
4572 strbuf_trim(&stash_oid
);
4574 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4577 strbuf_release(&stash_oid
);
4581 int save_autostash(const char *path
)
4583 return apply_save_autostash(path
, 0);
4586 int apply_autostash(const char *path
)
4588 return apply_save_autostash(path
, 1);
4591 int apply_autostash_oid(const char *stash_oid
)
4593 return apply_save_autostash_oid(stash_oid
, 1);
4596 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4597 const char *onto_name
, const struct object_id
*onto
,
4598 const struct object_id
*orig_head
)
4600 struct reset_head_opts ropts
= {
4602 .orig_head
= orig_head
,
4603 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4604 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4605 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4607 .default_reflog_action
= sequencer_reflog_action(opts
)
4609 if (reset_head(r
, &ropts
)) {
4610 apply_autostash(rebase_path_autostash());
4611 sequencer_remove_state(opts
);
4612 return error(_("could not detach HEAD"));
4618 static int stopped_at_head(struct repository
*r
)
4620 struct object_id head
;
4621 struct commit
*commit
;
4622 struct commit_message message
;
4624 if (repo_get_oid(r
, "HEAD", &head
) ||
4625 !(commit
= lookup_commit(r
, &head
)) ||
4626 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4627 fprintf(stderr
, _("Stopped at HEAD\n"));
4629 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4630 free_message(commit
, &message
);
4636 static int reread_todo_if_changed(struct repository
*r
,
4637 struct todo_list
*todo_list
,
4638 struct replay_opts
*opts
)
4641 struct strbuf buf
= STRBUF_INIT
;
4643 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4645 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4646 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4647 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4648 /* Reread the todo file if it has changed. */
4649 todo_list_release(todo_list
);
4650 if (read_populate_todo(r
, todo_list
, opts
))
4651 return -1; /* message was printed */
4652 /* `current` will be incremented on return */
4653 todo_list
->current
= -1;
4655 strbuf_release(&buf
);
4660 static const char rescheduled_advice
[] =
4661 N_("Could not execute the todo command\n"
4665 "It has been rescheduled; To edit the command before continuing, please\n"
4666 "edit the todo list first:\n"
4668 " git rebase --edit-todo\n"
4669 " git rebase --continue\n");
4671 static int pick_one_commit(struct repository
*r
,
4672 struct todo_list
*todo_list
,
4673 struct replay_opts
*opts
,
4674 int *check_todo
, int* reschedule
)
4677 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4678 const char *arg
= todo_item_get_arg(todo_list
, item
);
4679 if (is_rebase_i(opts
))
4680 opts
->reflog_message
= reflog_message(
4681 opts
, command_to_string(item
->command
), NULL
);
4683 res
= do_pick_commit(r
, item
, opts
, is_final_fixup(todo_list
),
4685 if (is_rebase_i(opts
) && res
< 0) {
4690 if (item
->command
== TODO_EDIT
) {
4691 struct commit
*commit
= item
->commit
;
4695 fprintf(stderr
, _("Stopped at %s... %.*s\n"),
4696 short_commit_name(r
, commit
), item
->arg_len
, arg
);
4698 return error_with_patch(r
, commit
,
4699 arg
, item
->arg_len
, opts
, res
, !res
);
4701 if (is_rebase_i(opts
) && !res
)
4702 record_in_rewritten(&item
->commit
->object
.oid
,
4703 peek_command(todo_list
, 1));
4704 if (res
&& is_fixup(item
->command
)) {
4707 return error_failed_squash(r
, item
->commit
, opts
,
4708 item
->arg_len
, arg
);
4709 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4711 struct object_id oid
;
4714 * If we are rewording and have either
4715 * fast-forwarded already, or are about to
4716 * create a new root commit, we want to amend,
4717 * otherwise we do not.
4719 if (item
->command
== TODO_REWORD
&&
4720 !repo_get_oid(r
, "HEAD", &oid
) &&
4721 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4722 (opts
->have_squash_onto
&&
4723 oideq(&opts
->squash_onto
, &oid
))))
4726 return res
| error_with_patch(r
, item
->commit
,
4727 arg
, item
->arg_len
, opts
,
4733 static int pick_commits(struct repository
*r
,
4734 struct todo_list
*todo_list
,
4735 struct replay_opts
*opts
)
4737 int res
= 0, reschedule
= 0;
4739 opts
->reflog_message
= sequencer_reflog_action(opts
);
4741 assert(!(opts
->signoff
|| opts
->no_commit
||
4742 opts
->record_origin
|| should_edit(opts
) ||
4743 opts
->committer_date_is_author_date
||
4744 opts
->ignore_date
));
4745 if (read_and_refresh_cache(r
, opts
))
4748 unlink(rebase_path_message());
4749 unlink(rebase_path_stopped_sha());
4750 unlink(rebase_path_amend());
4751 unlink(rebase_path_patch());
4753 while (todo_list
->current
< todo_list
->nr
) {
4754 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4755 const char *arg
= todo_item_get_arg(todo_list
, item
);
4758 if (save_todo(todo_list
, opts
, reschedule
))
4760 if (is_rebase_i(opts
)) {
4761 if (item
->command
!= TODO_COMMENT
) {
4762 FILE *f
= fopen(rebase_path_msgnum(), "w");
4764 todo_list
->done_nr
++;
4767 fprintf(f
, "%d\n", todo_list
->done_nr
);
4771 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4773 todo_list
->total_nr
,
4774 opts
->verbose
? "\n" : "\r");
4776 unlink(rebase_path_author_script());
4777 unlink(git_path_merge_head(r
));
4778 unlink(git_path_auto_merge(r
));
4779 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
4781 if (item
->command
== TODO_BREAK
) {
4784 return stopped_at_head(r
);
4787 if (item
->command
<= TODO_SQUASH
) {
4788 res
= pick_one_commit(r
, todo_list
, opts
, &check_todo
,
4790 if (!res
&& item
->command
== TODO_EDIT
)
4792 } else if (item
->command
== TODO_EXEC
) {
4793 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4794 int saved
= *end_of_arg
;
4799 res
= do_exec(r
, arg
);
4800 *end_of_arg
= saved
;
4803 if (opts
->reschedule_failed_exec
)
4807 } else if (item
->command
== TODO_LABEL
) {
4808 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4810 } else if (item
->command
== TODO_RESET
) {
4811 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4813 } else if (item
->command
== TODO_MERGE
) {
4814 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4815 item
->flags
, &check_todo
, opts
)) < 0)
4817 else if (item
->commit
)
4818 record_in_rewritten(&item
->commit
->object
.oid
,
4819 peek_command(todo_list
, 1));
4821 /* failed with merge conflicts */
4822 return error_with_patch(r
, item
->commit
,
4825 } else if (item
->command
== TODO_UPDATE_REF
) {
4826 struct strbuf ref
= STRBUF_INIT
;
4827 strbuf_add(&ref
, arg
, item
->arg_len
);
4828 if ((res
= do_update_ref(r
, ref
.buf
)))
4830 strbuf_release(&ref
);
4831 } else if (!is_noop(item
->command
))
4832 return error(_("unknown command %d"), item
->command
);
4835 advise(_(rescheduled_advice
),
4836 get_item_line_length(todo_list
,
4837 todo_list
->current
),
4838 get_item_line(todo_list
, todo_list
->current
));
4839 if (save_todo(todo_list
, opts
, reschedule
))
4842 write_rebase_head(&item
->commit
->object
.oid
);
4843 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4844 reread_todo_if_changed(r
, todo_list
, opts
)) {
4851 todo_list
->current
++;
4854 if (is_rebase_i(opts
)) {
4855 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4858 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4859 starts_with(head_ref
.buf
, "refs/")) {
4861 struct object_id head
, orig
;
4864 if (repo_get_oid(r
, "HEAD", &head
)) {
4865 res
= error(_("cannot read HEAD"));
4867 strbuf_release(&head_ref
);
4868 strbuf_release(&buf
);
4871 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4872 get_oid_hex(buf
.buf
, &orig
)) {
4873 res
= error(_("could not read orig-head"));
4874 goto cleanup_head_ref
;
4877 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4878 res
= error(_("could not read 'onto'"));
4879 goto cleanup_head_ref
;
4881 msg
= reflog_message(opts
, "finish", "%s onto %s",
4882 head_ref
.buf
, buf
.buf
);
4883 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4884 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4885 res
= error(_("could not update %s"),
4887 goto cleanup_head_ref
;
4889 msg
= reflog_message(opts
, "finish", "returning to %s",
4891 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4892 res
= error(_("could not update HEAD to %s"),
4894 goto cleanup_head_ref
;
4899 if (opts
->verbose
) {
4900 struct rev_info log_tree_opt
;
4901 struct object_id orig
, head
;
4903 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4904 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4905 log_tree_opt
.diff
= 1;
4906 log_tree_opt
.diffopt
.output_format
=
4907 DIFF_FORMAT_DIFFSTAT
;
4908 log_tree_opt
.disable_stdin
= 1;
4910 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4911 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4912 !repo_get_oid(r
, "HEAD", &head
)) {
4913 diff_tree_oid(&orig
, &head
, "",
4914 &log_tree_opt
.diffopt
);
4915 log_tree_diff_flush(&log_tree_opt
);
4917 release_revisions(&log_tree_opt
);
4919 flush_rewritten_pending();
4920 if (!stat(rebase_path_rewritten_list(), &st
) &&
4922 struct child_process child
= CHILD_PROCESS_INIT
;
4923 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4925 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4927 strvec_push(&child
.args
, "notes");
4928 strvec_push(&child
.args
, "copy");
4929 strvec_push(&child
.args
, "--for-rewrite=rebase");
4930 /* we don't care if this copying failed */
4931 run_command(&child
);
4933 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4934 strvec_push(&hook_opt
.args
, "rebase");
4935 run_hooks_opt("post-rewrite", &hook_opt
);
4937 apply_autostash(rebase_path_autostash());
4943 _("Successfully rebased and updated %s.\n"),
4947 strbuf_release(&buf
);
4948 strbuf_release(&head_ref
);
4950 if (do_update_refs(r
, opts
->quiet
))
4955 * Sequence of picks finished successfully; cleanup by
4956 * removing the .git/sequencer directory
4958 return sequencer_remove_state(opts
);
4961 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
4963 struct child_process cmd
= CHILD_PROCESS_INIT
;
4965 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
4966 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
4967 return error(_("no cherry-pick or revert in progress"));
4970 strvec_push(&cmd
.args
, "commit");
4973 * continue_single_pick() handles the case of recovering from a
4974 * conflict. should_edit() doesn't handle that case; for a conflict,
4975 * we want to edit if the user asked for it, or if they didn't specify
4976 * and stdin is a tty.
4978 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
4980 * Include --cleanup=strip as well because we don't want the
4981 * "# Conflicts:" messages.
4983 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
4985 return run_command(&cmd
);
4988 static int commit_staged_changes(struct repository
*r
,
4989 struct replay_opts
*opts
,
4990 struct todo_list
*todo_list
)
4992 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
4993 unsigned int final_fixup
= 0, is_clean
;
4995 if (has_unstaged_changes(r
, 1))
4996 return error(_("cannot rebase: You have unstaged changes."));
4998 is_clean
= !has_uncommitted_changes(r
, 0);
5000 if (!is_clean
&& !file_exists(rebase_path_message())) {
5001 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
5003 return error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
5005 if (file_exists(rebase_path_amend())) {
5006 struct strbuf rev
= STRBUF_INIT
;
5007 struct object_id head
, to_amend
;
5009 if (repo_get_oid(r
, "HEAD", &head
))
5010 return error(_("cannot amend non-existing commit"));
5011 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
5012 return error(_("invalid file: '%s'"), rebase_path_amend());
5013 if (get_oid_hex(rev
.buf
, &to_amend
))
5014 return error(_("invalid contents: '%s'"),
5015 rebase_path_amend());
5016 if (!is_clean
&& !oideq(&head
, &to_amend
))
5017 return error(_("\nYou have uncommitted changes in your "
5018 "working tree. Please, commit them\n"
5019 "first and then run 'git rebase "
5020 "--continue' again."));
5022 * When skipping a failed fixup/squash, we need to edit the
5023 * commit message, the current fixup list and count, and if it
5024 * was the last fixup/squash in the chain, we need to clean up
5025 * the commit message and if there was a squash, let the user
5028 if (!is_clean
|| !opts
->current_fixup_count
)
5029 ; /* this is not the final fixup */
5030 else if (!oideq(&head
, &to_amend
) ||
5031 !file_exists(rebase_path_stopped_sha())) {
5032 /* was a final fixup or squash done manually? */
5033 if (!is_fixup(peek_command(todo_list
, 0))) {
5034 unlink(rebase_path_fixup_msg());
5035 unlink(rebase_path_squash_msg());
5036 unlink(rebase_path_current_fixups());
5037 strbuf_reset(&opts
->current_fixups
);
5038 opts
->current_fixup_count
= 0;
5041 /* we are in a fixup/squash chain */
5042 const char *p
= opts
->current_fixups
.buf
;
5043 int len
= opts
->current_fixups
.len
;
5045 opts
->current_fixup_count
--;
5047 BUG("Incorrect current_fixups:\n%s", p
);
5048 while (len
&& p
[len
- 1] != '\n')
5050 strbuf_setlen(&opts
->current_fixups
, len
);
5051 if (write_message(p
, len
, rebase_path_current_fixups(),
5053 return error(_("could not write file: '%s'"),
5054 rebase_path_current_fixups());
5057 * If a fixup/squash in a fixup/squash chain failed, the
5058 * commit message is already correct, no need to commit
5061 * Only if it is the final command in the fixup/squash
5062 * chain, and only if the chain is longer than a single
5063 * fixup/squash command (which was just skipped), do we
5064 * actually need to re-commit with a cleaned up commit
5067 if (opts
->current_fixup_count
> 0 &&
5068 !is_fixup(peek_command(todo_list
, 0))) {
5071 * If there was not a single "squash" in the
5072 * chain, we only need to clean up the commit
5073 * message, no need to bother the user with
5074 * opening the commit message in the editor.
5076 if (!starts_with(p
, "squash ") &&
5077 !strstr(p
, "\nsquash "))
5078 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5079 } else if (is_fixup(peek_command(todo_list
, 0))) {
5081 * We need to update the squash message to skip
5082 * the latest commit message.
5085 struct commit
*commit
;
5087 const char *path
= rebase_path_squash_msg();
5088 const char *encoding
= get_commit_output_encoding();
5090 if (parse_head(r
, &commit
))
5091 return error(_("could not parse HEAD"));
5093 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5095 res
= error(_("could not parse commit %s"),
5096 oid_to_hex(&commit
->object
.oid
));
5097 goto unuse_commit_buffer
;
5099 find_commit_subject(p
, &msg
);
5100 if (write_message(msg
, strlen(msg
), path
, 0)) {
5101 res
= error(_("could not write file: "
5103 goto unuse_commit_buffer
;
5105 unuse_commit_buffer
:
5106 repo_unuse_commit_buffer(r
, commit
, p
);
5112 strbuf_release(&rev
);
5117 if (refs_ref_exists(get_main_ref_store(r
),
5118 "CHERRY_PICK_HEAD") &&
5119 refs_delete_ref(get_main_ref_store(r
), "",
5120 "CHERRY_PICK_HEAD", NULL
, 0))
5121 return error(_("could not remove CHERRY_PICK_HEAD"));
5122 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5123 return error_errno(_("could not remove '%s'"),
5124 git_path_merge_msg(r
));
5129 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5131 return error(_("could not commit staged changes."));
5132 unlink(rebase_path_amend());
5133 unlink(git_path_merge_head(r
));
5134 unlink(git_path_auto_merge(r
));
5136 unlink(rebase_path_fixup_msg());
5137 unlink(rebase_path_squash_msg());
5139 if (opts
->current_fixup_count
> 0) {
5141 * Whether final fixup or not, we just cleaned up the commit
5144 unlink(rebase_path_current_fixups());
5145 strbuf_reset(&opts
->current_fixups
);
5146 opts
->current_fixup_count
= 0;
5151 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5153 struct todo_list todo_list
= TODO_LIST_INIT
;
5156 if (read_and_refresh_cache(r
, opts
))
5159 if (read_populate_opts(opts
))
5161 if (is_rebase_i(opts
)) {
5162 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5163 goto release_todo_list
;
5165 if (file_exists(rebase_path_dropped())) {
5166 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5167 goto release_todo_list
;
5169 unlink(rebase_path_dropped());
5172 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5173 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5175 goto release_todo_list
;
5177 } else if (!file_exists(get_todo_path(opts
)))
5178 return continue_single_pick(r
, opts
);
5179 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5180 goto release_todo_list
;
5182 if (!is_rebase_i(opts
)) {
5183 /* Verify that the conflict has been resolved */
5184 if (refs_ref_exists(get_main_ref_store(r
),
5185 "CHERRY_PICK_HEAD") ||
5186 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5187 res
= continue_single_pick(r
, opts
);
5189 goto release_todo_list
;
5191 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5192 res
= error_dirty_index(r
, opts
);
5193 goto release_todo_list
;
5195 todo_list
.current
++;
5196 } else if (file_exists(rebase_path_stopped_sha())) {
5197 struct strbuf buf
= STRBUF_INIT
;
5198 struct object_id oid
;
5200 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5201 READ_ONELINER_SKIP_IF_EMPTY
) &&
5202 !get_oid_hex(buf
.buf
, &oid
))
5203 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5204 strbuf_release(&buf
);
5207 res
= pick_commits(r
, &todo_list
, opts
);
5209 todo_list_release(&todo_list
);
5213 static int single_pick(struct repository
*r
,
5214 struct commit
*cmit
,
5215 struct replay_opts
*opts
)
5218 struct todo_item item
;
5220 item
.command
= opts
->action
== REPLAY_PICK
?
5221 TODO_PICK
: TODO_REVERT
;
5224 opts
->reflog_message
= sequencer_reflog_action(opts
);
5225 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5228 int sequencer_pick_revisions(struct repository
*r
,
5229 struct replay_opts
*opts
)
5231 struct todo_list todo_list
= TODO_LIST_INIT
;
5232 struct object_id oid
;
5236 if (read_and_refresh_cache(r
, opts
))
5239 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5240 struct object_id oid
;
5241 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5243 /* This happens when using --stdin. */
5247 if (!repo_get_oid(r
, name
, &oid
)) {
5248 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5249 enum object_type type
= oid_object_info(r
,
5252 return error(_("%s: can't cherry-pick a %s"),
5253 name
, type_name(type
));
5256 return error(_("%s: bad revision"), name
);
5260 * If we were called as "git cherry-pick <commit>", just
5261 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5262 * REVERT_HEAD, and don't touch the sequencer state.
5263 * This means it is possible to cherry-pick in the middle
5264 * of a cherry-pick sequence.
5266 if (opts
->revs
->cmdline
.nr
== 1 &&
5267 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5268 opts
->revs
->no_walk
&&
5269 !opts
->revs
->cmdline
.rev
->flags
) {
5270 struct commit
*cmit
;
5271 if (prepare_revision_walk(opts
->revs
))
5272 return error(_("revision walk setup failed"));
5273 cmit
= get_revision(opts
->revs
);
5275 return error(_("empty commit set passed"));
5276 if (get_revision(opts
->revs
))
5277 BUG("unexpected extra commit from walk");
5278 return single_pick(r
, cmit
, opts
);
5282 * Start a new cherry-pick/ revert sequence; but
5283 * first, make sure that an existing one isn't in
5287 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5288 create_seq_dir(r
) < 0)
5290 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5291 return error(_("can't revert as initial commit"));
5292 if (save_head(oid_to_hex(&oid
)))
5294 if (save_opts(opts
))
5296 update_abort_safety_file();
5297 res
= pick_commits(r
, &todo_list
, opts
);
5298 todo_list_release(&todo_list
);
5302 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5304 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5305 struct strbuf sob
= STRBUF_INIT
;
5308 strbuf_addstr(&sob
, sign_off_header
);
5309 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5310 strbuf_addch(&sob
, '\n');
5313 strbuf_complete_line(msgbuf
);
5316 * If the whole message buffer is equal to the sob, pretend that we
5317 * found a conforming footer with a matching sob
5319 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5320 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5323 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5326 const char *append_newlines
= NULL
;
5327 size_t len
= msgbuf
->len
- ignore_footer
;
5331 * The buffer is completely empty. Leave foom for
5332 * the title and body to be filled in by the user.
5334 append_newlines
= "\n\n";
5335 } else if (len
== 1) {
5337 * Buffer contains a single newline. Add another
5338 * so that we leave room for the title and body.
5340 append_newlines
= "\n";
5341 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5343 * Buffer ends with a single newline. Add another
5344 * so that there is an empty line between the message
5347 append_newlines
= "\n";
5348 } /* else, the buffer already ends with two newlines. */
5350 if (append_newlines
)
5351 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5352 append_newlines
, strlen(append_newlines
));
5355 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5356 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5359 strbuf_release(&sob
);
5362 struct labels_entry
{
5363 struct hashmap_entry entry
;
5364 char label
[FLEX_ARRAY
];
5367 static int labels_cmp(const void *fndata UNUSED
,
5368 const struct hashmap_entry
*eptr
,
5369 const struct hashmap_entry
*entry_or_key
, const void *key
)
5371 const struct labels_entry
*a
, *b
;
5373 a
= container_of(eptr
, const struct labels_entry
, entry
);
5374 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5376 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5379 struct string_entry
{
5380 struct oidmap_entry entry
;
5381 char string
[FLEX_ARRAY
];
5384 struct label_state
{
5385 struct oidmap commit2label
;
5386 struct hashmap labels
;
5388 int max_label_length
;
5391 static const char *label_oid(struct object_id
*oid
, const char *label
,
5392 struct label_state
*state
)
5394 struct labels_entry
*labels_entry
;
5395 struct string_entry
*string_entry
;
5396 struct object_id dummy
;
5399 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5401 return string_entry
->string
;
5404 * For "uninteresting" commits, i.e. commits that are not to be
5405 * rebased, and which can therefore not be labeled, we use a unique
5406 * abbreviation of the commit name. This is slightly more complicated
5407 * than calling repo_find_unique_abbrev() because we also need to make
5408 * sure that the abbreviation does not conflict with any other
5411 * We disallow "interesting" commits to be labeled by a string that
5412 * is a valid full-length hash, to ensure that we always can find an
5413 * abbreviation for any uninteresting commit's names that does not
5414 * clash with any other label.
5416 strbuf_reset(&state
->buf
);
5420 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5421 label
= p
= state
->buf
.buf
;
5423 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5427 * We may need to extend the abbreviated hash so that there is
5428 * no conflicting label.
5430 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5431 size_t i
= strlen(p
) + 1;
5433 oid_to_hex_r(p
, oid
);
5434 for (; i
< the_hash_algo
->hexsz
; i
++) {
5437 if (!hashmap_get_from_hash(&state
->labels
,
5444 struct strbuf
*buf
= &state
->buf
;
5445 int label_is_utf8
= 1; /* start with this assumption */
5446 size_t max_len
= buf
->len
+ state
->max_label_length
;
5449 * Sanitize labels by replacing non-alpha-numeric characters
5450 * (including white-space ones) by dashes, as they might be
5451 * illegal in file names (and hence in ref names).
5453 * Note that we retain non-ASCII UTF-8 characters (identified
5454 * via the most significant bit). They should be all acceptable
5457 * As we will use the labels as names of (loose) refs, it is
5458 * vital that the name not be longer than the maximum component
5459 * size of the file system (`NAME_MAX`). We are careful to
5460 * truncate the label accordingly, allowing for the `.lock`
5461 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5462 * truncating in the middle of a character).
5464 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5465 if (isalnum(*label
) ||
5466 (!label_is_utf8
&& (*label
& 0x80)))
5467 strbuf_addch(buf
, *label
);
5468 else if (*label
& 0x80) {
5469 const char *p
= label
;
5471 utf8_width(&p
, NULL
);
5473 if (buf
->len
+ (p
- label
) > max_len
)
5475 strbuf_add(buf
, label
, p
- label
);
5479 strbuf_addch(buf
, *label
);
5481 /* avoid leading dash and double-dashes */
5482 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5483 strbuf_addch(buf
, '-');
5485 strbuf_addstr(buf
, "rev-");
5486 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5490 if ((buf
->len
== the_hash_algo
->hexsz
&&
5491 !get_oid_hex(label
, &dummy
)) ||
5492 (buf
->len
== 1 && *label
== '#') ||
5493 hashmap_get_from_hash(&state
->labels
,
5494 strihash(label
), label
)) {
5496 * If the label already exists, or if the label is a
5497 * valid full OID, or the label is a '#' (which we use
5498 * as a separator between merge heads and oneline), we
5499 * append a dash and a number to make it unique.
5501 size_t len
= buf
->len
;
5503 for (i
= 2; ; i
++) {
5504 strbuf_setlen(buf
, len
);
5505 strbuf_addf(buf
, "-%d", i
);
5506 if (!hashmap_get_from_hash(&state
->labels
,
5516 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5517 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5518 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5520 FLEX_ALLOC_STR(string_entry
, string
, label
);
5521 oidcpy(&string_entry
->entry
.oid
, oid
);
5522 oidmap_put(&state
->commit2label
, string_entry
);
5524 return string_entry
->string
;
5527 static int make_script_with_merges(struct pretty_print_context
*pp
,
5528 struct rev_info
*revs
, struct strbuf
*out
,
5531 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5532 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5533 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5534 int skipped_commit
= 0;
5535 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5536 struct strbuf label
= STRBUF_INIT
;
5537 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5538 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5539 struct commit
*commit
;
5540 struct oidmap commit2todo
= OIDMAP_INIT
;
5541 struct string_entry
*entry
;
5542 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5543 shown
= OIDSET_INIT
;
5544 struct label_state state
=
5545 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5547 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5548 const char *cmd_pick
= abbr
? "p" : "pick",
5549 *cmd_label
= abbr
? "l" : "label",
5550 *cmd_reset
= abbr
? "t" : "reset",
5551 *cmd_merge
= abbr
? "m" : "merge";
5553 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5555 oidmap_init(&commit2todo
, 0);
5556 oidmap_init(&state
.commit2label
, 0);
5557 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5558 strbuf_init(&state
.buf
, 32);
5560 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5561 struct labels_entry
*onto_label_entry
;
5562 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5563 FLEX_ALLOC_STR(entry
, string
, "onto");
5564 oidcpy(&entry
->entry
.oid
, oid
);
5565 oidmap_put(&state
.commit2label
, entry
);
5567 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5568 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5569 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5574 * - get onelines for all commits
5575 * - gather all branch tips (i.e. 2nd or later parents of merges)
5576 * - label all branch tips
5578 while ((commit
= get_revision(revs
))) {
5579 struct commit_list
*to_merge
;
5580 const char *p1
, *p2
;
5581 struct object_id
*oid
;
5584 tail
= &commit_list_insert(commit
, tail
)->next
;
5585 oidset_insert(&interesting
, &commit
->object
.oid
);
5587 is_empty
= is_original_commit_empty(commit
);
5588 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5589 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5590 warning(_("skipped previously applied commit %s"),
5591 short_commit_name(the_repository
, commit
));
5595 if (is_empty
&& !keep_empty
)
5598 strbuf_reset(&oneline
);
5599 pretty_print_commit(pp
, commit
, &oneline
);
5601 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5603 /* non-merge commit: easy case */
5605 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5606 oid_to_hex(&commit
->object
.oid
),
5609 strbuf_addf(&buf
, " %c empty",
5612 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5613 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5614 oidmap_put(&commit2todo
, entry
);
5619 /* Create a label */
5620 strbuf_reset(&label
);
5621 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5622 (p1
= strchr(p1
, '\'')) &&
5623 (p2
= strchr(++p1
, '\'')))
5624 strbuf_add(&label
, p1
, p2
- p1
);
5625 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5627 (p1
= strstr(p1
, " from ")))
5628 strbuf_addstr(&label
, p1
+ strlen(" from "));
5630 strbuf_addbuf(&label
, &oneline
);
5633 strbuf_addf(&buf
, "%s -C %s",
5634 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5636 /* label the tips of merged branches */
5637 for (; to_merge
; to_merge
= to_merge
->next
) {
5638 oid
= &to_merge
->item
->object
.oid
;
5639 strbuf_addch(&buf
, ' ');
5641 if (!oidset_contains(&interesting
, oid
)) {
5642 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5647 tips_tail
= &commit_list_insert(to_merge
->item
,
5650 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5652 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5654 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5655 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5656 oidmap_put(&commit2todo
, entry
);
5659 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5660 _("use --reapply-cherry-picks to include skipped commits"));
5664 * - label branch points
5665 * - add HEAD to the branch tips
5667 for (iter
= commits
; iter
; iter
= iter
->next
) {
5668 struct commit_list
*parent
= iter
->item
->parents
;
5669 for (; parent
; parent
= parent
->next
) {
5670 struct object_id
*oid
= &parent
->item
->object
.oid
;
5671 if (!oidset_contains(&interesting
, oid
))
5673 if (oidset_insert(&child_seen
, oid
))
5674 label_oid(oid
, "branch-point", &state
);
5677 /* Add HEAD as implicit "tip of branch" */
5679 tips_tail
= &commit_list_insert(iter
->item
,
5684 * Third phase: output the todo list. This is a bit tricky, as we
5685 * want to avoid jumping back and forth between revisions. To
5686 * accomplish that goal, we walk backwards from the branch tips,
5687 * gathering commits not yet shown, reversing the list on the fly,
5688 * then outputting that list (labeling revisions as needed).
5690 strbuf_addf(out
, "%s onto\n", cmd_label
);
5691 for (iter
= tips
; iter
; iter
= iter
->next
) {
5692 struct commit_list
*list
= NULL
, *iter2
;
5694 commit
= iter
->item
;
5695 if (oidset_contains(&shown
, &commit
->object
.oid
))
5697 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5700 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5702 strbuf_addch(out
, '\n');
5704 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5705 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5706 commit_list_insert(commit
, &list
);
5707 if (!commit
->parents
) {
5711 commit
= commit
->parents
->item
;
5715 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5716 rebase_cousins
|| root_with_onto
?
5717 "onto" : "[new root]");
5719 const char *to
= NULL
;
5721 entry
= oidmap_get(&state
.commit2label
,
5722 &commit
->object
.oid
);
5725 else if (!rebase_cousins
)
5726 to
= label_oid(&commit
->object
.oid
, NULL
,
5729 if (!to
|| !strcmp(to
, "onto"))
5730 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5732 strbuf_reset(&oneline
);
5733 pretty_print_commit(pp
, commit
, &oneline
);
5734 strbuf_addf(out
, "%s %s # %s\n",
5735 cmd_reset
, to
, oneline
.buf
);
5739 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5740 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5741 entry
= oidmap_get(&commit2todo
, oid
);
5742 /* only show if not already upstream */
5744 strbuf_addf(out
, "%s\n", entry
->string
);
5745 entry
= oidmap_get(&state
.commit2label
, oid
);
5747 strbuf_addf(out
, "%s %s\n",
5748 cmd_label
, entry
->string
);
5749 oidset_insert(&shown
, oid
);
5752 free_commit_list(list
);
5755 free_commit_list(commits
);
5756 free_commit_list(tips
);
5758 strbuf_release(&label
);
5759 strbuf_release(&oneline
);
5760 strbuf_release(&buf
);
5762 oidmap_free(&commit2todo
, 1);
5763 oidmap_free(&state
.commit2label
, 1);
5764 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5765 strbuf_release(&state
.buf
);
5770 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5771 const char **argv
, unsigned flags
)
5773 char *format
= NULL
;
5774 struct pretty_print_context pp
= {0};
5775 struct rev_info revs
;
5776 struct commit
*commit
;
5777 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5778 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5779 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5780 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5781 int skipped_commit
= 0;
5784 repo_init_revisions(r
, &revs
, NULL
);
5785 revs
.verbose_header
= 1;
5787 revs
.max_parents
= 1;
5788 revs
.cherry_mark
= !reapply_cherry_picks
;
5791 revs
.right_only
= 1;
5792 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5793 revs
.topo_order
= 1;
5795 revs
.pretty_given
= 1;
5796 git_config_get_string("rebase.instructionFormat", &format
);
5797 if (!format
|| !*format
) {
5799 format
= xstrdup("%s");
5801 get_commit_format(format
, &revs
);
5803 pp
.fmt
= revs
.commit_format
;
5804 pp
.output_encoding
= get_log_output_encoding();
5806 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5807 ret
= error(_("make_script: unhandled options"));
5811 if (prepare_revision_walk(&revs
) < 0) {
5812 ret
= error(_("make_script: error preparing revisions"));
5816 if (rebase_merges
) {
5817 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5821 while ((commit
= get_revision(&revs
))) {
5822 int is_empty
= is_original_commit_empty(commit
);
5824 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5825 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5826 warning(_("skipped previously applied commit %s"),
5827 short_commit_name(r
, commit
));
5831 if (is_empty
&& !keep_empty
)
5833 strbuf_addf(out
, "%s %s ", insn
,
5834 oid_to_hex(&commit
->object
.oid
));
5835 pretty_print_commit(&pp
, commit
, out
);
5837 strbuf_addf(out
, " %c empty", comment_line_char
);
5838 strbuf_addch(out
, '\n');
5841 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5842 _("use --reapply-cherry-picks to include skipped commits"));
5844 release_revisions(&revs
);
5849 * Add commands after pick and (series of) squash/fixup commands
5852 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5853 struct string_list
*commands
)
5855 struct strbuf
*buf
= &todo_list
->buf
;
5856 size_t base_offset
= buf
->len
;
5857 int i
, insert
, nr
= 0, alloc
= 0;
5858 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5860 CALLOC_ARRAY(base_items
, commands
->nr
);
5861 for (i
= 0; i
< commands
->nr
; i
++) {
5862 size_t command_len
= strlen(commands
->items
[i
].string
);
5864 strbuf_addstr(buf
, commands
->items
[i
].string
);
5865 strbuf_addch(buf
, '\n');
5867 base_items
[i
].command
= TODO_EXEC
;
5868 base_items
[i
].offset_in_buf
= base_offset
;
5869 base_items
[i
].arg_offset
= base_offset
;
5870 base_items
[i
].arg_len
= command_len
;
5872 base_offset
+= command_len
+ 1;
5876 * Insert <commands> after every pick. Here, fixup/squash chains
5877 * are considered part of the pick, so we insert the commands *after*
5878 * those chains if there are any.
5880 * As we insert the exec commands immediately after rearranging
5881 * any fixups and before the user edits the list, a fixup chain
5882 * can never contain comments (any comments are empty picks that
5883 * have been commented out because the user did not specify
5884 * --keep-empty). So, it is safe to insert an exec command
5885 * without looking at the command following a comment.
5888 for (i
= 0; i
< todo_list
->nr
; i
++) {
5889 enum todo_command command
= todo_list
->items
[i
].command
;
5890 if (insert
&& !is_fixup(command
)) {
5891 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5892 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5898 ALLOC_GROW(items
, nr
+ 1, alloc
);
5899 items
[nr
++] = todo_list
->items
[i
];
5901 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5905 /* insert or append final <commands> */
5907 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5908 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5913 FREE_AND_NULL(todo_list
->items
);
5914 todo_list
->items
= items
;
5916 todo_list
->alloc
= alloc
;
5919 static void todo_list_to_strbuf(struct repository
*r
,
5920 struct todo_list
*todo_list
,
5921 struct strbuf
*buf
, int num
, unsigned flags
)
5923 struct todo_item
*item
;
5924 int i
, max
= todo_list
->nr
;
5926 if (num
> 0 && num
< max
)
5929 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5932 /* if the item is not a command write it and continue */
5933 if (item
->command
>= TODO_COMMENT
) {
5934 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5935 todo_item_get_arg(todo_list
, item
));
5939 /* add command to the buffer */
5940 cmd
= command_to_char(item
->command
);
5941 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5942 strbuf_addch(buf
, cmd
);
5944 strbuf_addstr(buf
, command_to_string(item
->command
));
5948 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5949 short_commit_name(r
, item
->commit
) :
5950 oid_to_hex(&item
->commit
->object
.oid
);
5952 if (item
->command
== TODO_FIXUP
) {
5953 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
5954 strbuf_addstr(buf
, " -c");
5955 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
5956 strbuf_addstr(buf
, " -C");
5960 if (item
->command
== TODO_MERGE
) {
5961 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5962 strbuf_addstr(buf
, " -c");
5964 strbuf_addstr(buf
, " -C");
5967 strbuf_addf(buf
, " %s", oid
);
5970 /* add all the rest */
5972 strbuf_addch(buf
, '\n');
5974 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5975 todo_item_get_arg(todo_list
, item
));
5979 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5980 const char *file
, const char *shortrevisions
,
5981 const char *shortonto
, int num
, unsigned flags
)
5984 struct strbuf buf
= STRBUF_INIT
;
5986 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5987 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5988 append_todo_help(count_commands(todo_list
),
5989 shortrevisions
, shortonto
, &buf
);
5991 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5992 strbuf_release(&buf
);
5997 /* skip picking commits whose parents are unchanged */
5998 static int skip_unnecessary_picks(struct repository
*r
,
5999 struct todo_list
*todo_list
,
6000 struct object_id
*base_oid
)
6002 struct object_id
*parent_oid
;
6005 for (i
= 0; i
< todo_list
->nr
; i
++) {
6006 struct todo_item
*item
= todo_list
->items
+ i
;
6008 if (item
->command
>= TODO_NOOP
)
6010 if (item
->command
!= TODO_PICK
)
6012 if (repo_parse_commit(r
, item
->commit
)) {
6013 return error(_("could not parse commit '%s'"),
6014 oid_to_hex(&item
->commit
->object
.oid
));
6016 if (!item
->commit
->parents
)
6017 break; /* root commit */
6018 if (item
->commit
->parents
->next
)
6019 break; /* merge commit */
6020 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
6021 if (!oideq(parent_oid
, base_oid
))
6023 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6026 const char *done_path
= rebase_path_done();
6028 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6029 error_errno(_("could not write to '%s'"), done_path
);
6033 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6035 todo_list
->current
= 0;
6036 todo_list
->done_nr
+= i
;
6038 if (is_fixup(peek_command(todo_list
, 0)))
6039 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6045 struct todo_add_branch_context
{
6046 struct todo_item
*items
;
6050 struct commit
*commit
;
6051 struct string_list refs_to_oids
;
6054 static int add_decorations_to_list(const struct commit
*commit
,
6055 struct todo_add_branch_context
*ctx
)
6057 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6058 const char *head_ref
= resolve_ref_unsafe("HEAD",
6059 RESOLVE_REF_READING
,
6063 while (decoration
) {
6064 struct todo_item
*item
;
6066 size_t base_offset
= ctx
->buf
->len
;
6069 * If the branch is the current HEAD, then it will be
6070 * updated by the default rebase behavior.
6072 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6073 decoration
= decoration
->next
;
6077 ALLOC_GROW(ctx
->items
,
6080 item
= &ctx
->items
[ctx
->items_nr
];
6081 memset(item
, 0, sizeof(*item
));
6083 /* If the branch is checked out, then leave a comment instead. */
6084 if ((path
= branch_checked_out(decoration
->name
))) {
6085 item
->command
= TODO_COMMENT
;
6086 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6087 decoration
->name
, path
);
6089 struct string_list_item
*sti
;
6090 item
->command
= TODO_UPDATE_REF
;
6091 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6093 sti
= string_list_insert(&ctx
->refs_to_oids
,
6095 sti
->util
= init_update_ref_record(decoration
->name
);
6098 item
->offset_in_buf
= base_offset
;
6099 item
->arg_offset
= base_offset
;
6100 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6103 decoration
= decoration
->next
;
6110 * For each 'pick' command, find out if the commit has a decoration in
6111 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6113 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6116 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6117 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6118 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6119 struct decoration_filter decoration_filter
= {
6120 .include_ref_pattern
= &decorate_refs_include
,
6121 .exclude_ref_pattern
= &decorate_refs_exclude
,
6122 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6124 struct todo_add_branch_context ctx
= {
6125 .buf
= &todo_list
->buf
,
6126 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6129 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6130 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6132 string_list_append(&decorate_refs_include
, "refs/heads/");
6133 load_ref_decorations(&decoration_filter
, 0);
6135 for (i
= 0; i
< todo_list
->nr
; ) {
6136 struct todo_item
*item
= &todo_list
->items
[i
];
6138 /* insert ith item into new list */
6139 ALLOC_GROW(ctx
.items
,
6143 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6146 ctx
.commit
= item
->commit
;
6147 add_decorations_to_list(item
->commit
, &ctx
);
6151 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6153 string_list_clear(&ctx
.refs_to_oids
, 1);
6156 /* we failed, so clean up the new list. */
6161 free(todo_list
->items
);
6162 todo_list
->items
= ctx
.items
;
6163 todo_list
->nr
= ctx
.items_nr
;
6164 todo_list
->alloc
= ctx
.items_alloc
;
6169 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6170 const char *shortrevisions
, const char *onto_name
,
6171 struct commit
*onto
, const struct object_id
*orig_head
,
6172 struct string_list
*commands
, unsigned autosquash
,
6173 unsigned update_refs
,
6174 struct todo_list
*todo_list
)
6176 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6177 const char *todo_file
= rebase_path_todo();
6178 struct todo_list new_todo
= TODO_LIST_INIT
;
6179 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6180 struct object_id oid
= onto
->object
.oid
;
6183 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6186 if (buf
->len
== 0) {
6187 struct todo_item
*item
= append_new_todo(todo_list
);
6188 item
->command
= TODO_NOOP
;
6189 item
->commit
= NULL
;
6190 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6193 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6196 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6200 todo_list_add_exec_commands(todo_list
, commands
);
6202 if (count_commands(todo_list
) == 0) {
6203 apply_autostash(rebase_path_autostash());
6204 sequencer_remove_state(opts
);
6206 return error(_("nothing to do"));
6209 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6213 else if (res
== -2) {
6214 apply_autostash(rebase_path_autostash());
6215 sequencer_remove_state(opts
);
6218 } else if (res
== -3) {
6219 apply_autostash(rebase_path_autostash());
6220 sequencer_remove_state(opts
);
6221 todo_list_release(&new_todo
);
6223 return error(_("nothing to do"));
6224 } else if (res
== -4) {
6225 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6226 todo_list_release(&new_todo
);
6231 /* Expand the commit IDs */
6232 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6233 strbuf_swap(&new_todo
.buf
, &buf2
);
6234 strbuf_release(&buf2
);
6235 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6236 new_todo
.total_nr
= 0;
6237 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6238 BUG("invalid todo list after expanding IDs:\n%s",
6241 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6242 todo_list_release(&new_todo
);
6243 return error(_("could not skip unnecessary pick commands"));
6246 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6247 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6248 todo_list_release(&new_todo
);
6249 return error_errno(_("could not write '%s'"), todo_file
);
6254 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6257 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6260 todo_list_write_total_nr(&new_todo
);
6261 res
= pick_commits(r
, &new_todo
, opts
);
6264 todo_list_release(&new_todo
);
6269 struct subject2item_entry
{
6270 struct hashmap_entry entry
;
6272 char subject
[FLEX_ARRAY
];
6275 static int subject2item_cmp(const void *fndata UNUSED
,
6276 const struct hashmap_entry
*eptr
,
6277 const struct hashmap_entry
*entry_or_key
,
6280 const struct subject2item_entry
*a
, *b
;
6282 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6283 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6285 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6288 define_commit_slab(commit_todo_item
, struct todo_item
*);
6290 static int skip_fixupish(const char *subject
, const char **p
) {
6291 return skip_prefix(subject
, "fixup! ", p
) ||
6292 skip_prefix(subject
, "amend! ", p
) ||
6293 skip_prefix(subject
, "squash! ", p
);
6297 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6298 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6299 * after the former, and change "pick" to "fixup"/"squash".
6301 * Note that if the config has specified a custom instruction format, each log
6302 * message will have to be retrieved from the commit (as the oneline in the
6303 * script cannot be trusted) in order to normalize the autosquash arrangement.
6305 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6307 struct hashmap subject2item
;
6308 int rearranged
= 0, *next
, *tail
, i
, nr
= 0;
6310 struct commit_todo_item commit_todo
;
6311 struct todo_item
*items
= NULL
;
6313 init_commit_todo_item(&commit_todo
);
6315 * The hashmap maps onelines to the respective todo list index.
6317 * If any items need to be rearranged, the next[i] value will indicate
6318 * which item was moved directly after the i'th.
6320 * In that case, last[i] will indicate the index of the latest item to
6321 * be moved to appear after the i'th.
6323 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6324 ALLOC_ARRAY(next
, todo_list
->nr
);
6325 ALLOC_ARRAY(tail
, todo_list
->nr
);
6326 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6327 for (i
= 0; i
< todo_list
->nr
; i
++) {
6328 struct strbuf buf
= STRBUF_INIT
;
6329 struct todo_item
*item
= todo_list
->items
+ i
;
6330 const char *commit_buffer
, *subject
, *p
;
6333 struct subject2item_entry
*entry
;
6335 next
[i
] = tail
[i
] = -1;
6336 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6341 if (is_fixup(item
->command
)) {
6342 clear_commit_todo_item(&commit_todo
);
6343 return error(_("the script was already rearranged."));
6346 repo_parse_commit(the_repository
, item
->commit
);
6347 commit_buffer
= repo_logmsg_reencode(the_repository
,
6350 find_commit_subject(commit_buffer
, &subject
);
6351 format_subject(&buf
, subject
, " ");
6352 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6353 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6355 if (skip_fixupish(subject
, &p
)) {
6356 struct commit
*commit2
;
6361 if (!skip_fixupish(p
, &p
))
6365 entry
= hashmap_get_entry_from_hash(&subject2item
,
6367 struct subject2item_entry
,
6370 /* found by title */
6372 else if (!strchr(p
, ' ') &&
6374 lookup_commit_reference_by_name(p
)) &&
6375 *commit_todo_item_at(&commit_todo
, commit2
))
6376 /* found by commit name */
6377 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6380 /* copy can be a prefix of the commit subject */
6381 for (i2
= 0; i2
< i
; i2
++)
6383 starts_with(subjects
[i2
], p
))
6391 if (starts_with(subject
, "fixup!")) {
6392 todo_list
->items
[i
].command
= TODO_FIXUP
;
6393 } else if (starts_with(subject
, "amend!")) {
6394 todo_list
->items
[i
].command
= TODO_FIXUP
;
6395 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6397 todo_list
->items
[i
].command
= TODO_SQUASH
;
6403 next
[i
] = next
[tail
[i2
]];
6407 } else if (!hashmap_get_from_hash(&subject2item
,
6408 strhash(subject
), subject
)) {
6409 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6411 hashmap_entry_init(&entry
->entry
,
6412 strhash(entry
->subject
));
6413 hashmap_put(&subject2item
, &entry
->entry
);
6416 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6420 ALLOC_ARRAY(items
, todo_list
->nr
);
6422 for (i
= 0; i
< todo_list
->nr
; i
++) {
6423 enum todo_command command
= todo_list
->items
[i
].command
;
6427 * Initially, all commands are 'pick's. If it is a
6428 * fixup or a squash now, we have rearranged it.
6430 if (is_fixup(command
))
6434 items
[nr
++] = todo_list
->items
[cur
];
6439 assert(nr
== todo_list
->nr
);
6440 todo_list
->alloc
= nr
;
6441 FREE_AND_NULL(todo_list
->items
);
6442 todo_list
->items
= items
;
6447 for (i
= 0; i
< todo_list
->nr
; i
++)
6450 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6452 clear_commit_todo_item(&commit_todo
);
6457 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6459 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6460 struct object_id cherry_pick_head
, rebase_head
;
6462 if (file_exists(git_path_seq_dir()))
6463 *whence
= FROM_CHERRY_PICK_MULTI
;
6464 if (file_exists(rebase_path()) &&
6465 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6466 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6467 oideq(&rebase_head
, &cherry_pick_head
))
6468 *whence
= FROM_REBASE_PICK
;
6470 *whence
= FROM_CHERRY_PICK_SINGLE
;
6478 int sequencer_get_update_refs_state(const char *wt_dir
,
6479 struct string_list
*refs
)
6483 struct strbuf ref
= STRBUF_INIT
;
6484 struct strbuf hash
= STRBUF_INIT
;
6485 struct update_ref_record
*rec
= NULL
;
6487 char *path
= rebase_path_update_refs(wt_dir
);
6489 fp
= fopen(path
, "r");
6493 while (strbuf_getline(&ref
, fp
) != EOF
) {
6494 struct string_list_item
*item
;
6496 CALLOC_ARRAY(rec
, 1);
6498 if (strbuf_getline(&hash
, fp
) == EOF
||
6499 get_oid_hex(hash
.buf
, &rec
->before
)) {
6500 warning(_("update-refs file at '%s' is invalid"),
6506 if (strbuf_getline(&hash
, fp
) == EOF
||
6507 get_oid_hex(hash
.buf
, &rec
->after
)) {
6508 warning(_("update-refs file at '%s' is invalid"),
6514 item
= string_list_insert(refs
, ref
.buf
);
6524 strbuf_release(&ref
);
6525 strbuf_release(&hash
);