7 #include "environment.h"
12 #include "object-file.h"
13 #include "object-name.h"
14 #include "object-store.h"
18 #include "sequencer.h"
20 #include "run-command.h"
24 #include "cache-tree.h"
28 #include "merge-ort.h"
29 #include "merge-ort-wrappers.h"
35 #include "wt-status.h"
37 #include "notes-utils.h"
39 #include "unpack-trees.h"
43 #include "commit-slab.h"
45 #include "commit-reach.h"
46 #include "rebase-interactive.h"
51 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
54 * To accommodate common filesystem limitations, where the loose refs' file
55 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
56 * --rebase-merges` need to be truncated if the corresponding commit subjects
58 * Add some margin to stay clear from reaching `NAME_MAX`.
60 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
62 static const char sign_off_header
[] = "Signed-off-by: ";
63 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
65 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
67 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
69 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
70 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
71 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
72 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
74 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
76 * The file containing rebase commands, comments, and empty lines.
77 * This file is created by "git rebase -i" then edited by the user. As
78 * the lines are processed, they are removed from the front of this
79 * file and written to the tail of 'done'.
81 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
82 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
84 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
87 * The rebase command lines that have already been processed. A line
88 * is moved here when it is first handled, before any associated user
91 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
93 * The file to keep track of how many commands were already processed (e.g.
96 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
98 * The file to keep track of how many commands are to be processed in total
99 * (e.g. for the prompt).
101 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
103 * The commit message that is planned to be used for any changes that
104 * need to be committed following a user interaction.
106 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
108 * The file into which is accumulated the suggested commit message for
109 * squash/fixup commands. When the first of a series of squash/fixups
110 * is seen, the file is created and the commit message from the
111 * previous commit and from the first squash/fixup commit are written
112 * to it. The commit message for each subsequent squash/fixup commit
113 * is appended to the file as it is processed.
115 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
117 * If the current series of squash/fixups has not yet included a squash
118 * command, then this file exists and holds the commit message of the
119 * original "pick" commit. (If the series ends without a "squash"
120 * command, then this can be used as the commit message of the combined
121 * commit without opening the editor.)
123 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
125 * This file contains the list fixup/squash commands that have been
126 * accumulated into message-fixup or message-squash so far.
128 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
130 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
131 * GIT_AUTHOR_DATE that will be used for the commit that is currently
134 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
136 * When an "edit" rebase command is being processed, the SHA1 of the
137 * commit to be edited is recorded in this file. When "git rebase
138 * --continue" is executed, if there are any staged changes then they
139 * will be amended to the HEAD commit, but only provided the HEAD
140 * commit is still the commit to be edited. When any other rebase
141 * command is processed, this file is deleted.
143 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
145 * When we stop at a given patch via the "edit" command, this file contains
146 * the commit object name of the corresponding patch.
148 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
150 * For the post-rewrite hook, we make a list of rewritten commits and
151 * their new sha1s. The rewritten-pending list keeps the sha1s of
152 * commits that have been processed, but not committed yet,
153 * e.g. because they are waiting for a 'squash' command.
155 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
156 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
157 "rebase-merge/rewritten-pending")
160 * The path of the file containing the OID of the "squash onto" commit, i.e.
161 * the dummy commit used for `reset [new root]`.
163 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
166 * The path of the file listing refs that need to be deleted after the rebase
167 * finishes. This is used by the `label` command to record the need for cleanup.
169 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
172 * The update-refs file stores a list of refs that will be updated at the end
173 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
174 * update the OIDs for the refs in this file, but the refs are not updated
175 * until the end of the rebase sequence.
177 * rebase_path_update_refs() returns the path to this file for a given
178 * worktree directory. For the current worktree, pass the_repository->gitdir.
180 static char *rebase_path_update_refs(const char *wt_git_dir
)
182 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
186 * The following files are written by git-rebase just after parsing the
189 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
190 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
191 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
192 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
193 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
194 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
195 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
196 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
197 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
198 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
199 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
200 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
201 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
202 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
203 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
204 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
205 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
208 * A 'struct update_refs_record' represents a value in the update-refs
209 * list. We use a string_list to map refs to these (before, after) pairs.
211 struct update_ref_record
{
212 struct object_id before
;
213 struct object_id after
;
216 static struct update_ref_record
*init_update_ref_record(const char *ref
)
218 struct update_ref_record
*rec
;
220 CALLOC_ARRAY(rec
, 1);
222 oidcpy(&rec
->before
, null_oid());
223 oidcpy(&rec
->after
, null_oid());
225 /* This may fail, but that's fine, we will keep the null OID. */
226 read_ref(ref
, &rec
->before
);
231 static int git_sequencer_config(const char *k
, const char *v
, void *cb
)
233 struct replay_opts
*opts
= cb
;
236 if (!strcmp(k
, "commit.cleanup")) {
239 status
= git_config_string(&s
, k
, v
);
243 if (!strcmp(s
, "verbatim")) {
244 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
245 opts
->explicit_cleanup
= 1;
246 } else if (!strcmp(s
, "whitespace")) {
247 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
248 opts
->explicit_cleanup
= 1;
249 } else if (!strcmp(s
, "strip")) {
250 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
251 opts
->explicit_cleanup
= 1;
252 } else if (!strcmp(s
, "scissors")) {
253 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
254 opts
->explicit_cleanup
= 1;
256 warning(_("invalid commit message cleanup mode '%s'"),
264 if (!strcmp(k
, "commit.gpgsign")) {
265 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
269 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
270 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
273 * pull.twohead is allowed to be multi-valued; we only
274 * care about the first value.
276 char *tmp
= strchr(opts
->default_strategy
, ' ');
283 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
284 opts
->commit_use_reference
= git_config_bool(k
, v
);
286 return git_diff_basic_config(k
, v
, NULL
);
289 void sequencer_init_config(struct replay_opts
*opts
)
291 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
292 git_config(git_sequencer_config
, opts
);
295 static inline int is_rebase_i(const struct replay_opts
*opts
)
297 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
300 static const char *get_dir(const struct replay_opts
*opts
)
302 if (is_rebase_i(opts
))
303 return rebase_path();
304 return git_path_seq_dir();
307 static const char *get_todo_path(const struct replay_opts
*opts
)
309 if (is_rebase_i(opts
))
310 return rebase_path_todo();
311 return git_path_todo_file();
315 * Returns 0 for non-conforming footer
316 * Returns 1 for conforming footer
317 * Returns 2 when sob exists within conforming footer
318 * Returns 3 when sob exists within conforming footer as last entry
320 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
321 size_t ignore_footer
)
323 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
324 struct trailer_info info
;
326 int found_sob
= 0, found_sob_last
= 0;
332 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
333 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
336 trailer_info_get(&info
, sb
->buf
, &opts
);
339 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
341 if (info
.trailer_start
== info
.trailer_end
)
344 for (i
= 0; i
< info
.trailer_nr
; i
++)
345 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
347 if (i
== info
.trailer_nr
- 1)
351 trailer_info_release(&info
);
360 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
362 static struct strbuf buf
= STRBUF_INIT
;
366 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
370 void replay_opts_release(struct replay_opts
*opts
)
372 free(opts
->gpg_sign
);
373 free(opts
->reflog_action
);
374 free(opts
->default_strategy
);
375 free(opts
->strategy
);
376 strvec_clear (&opts
->xopts
);
377 strbuf_release(&opts
->current_fixups
);
379 release_revisions(opts
->revs
);
383 int sequencer_remove_state(struct replay_opts
*opts
)
385 struct strbuf buf
= STRBUF_INIT
;
388 if (is_rebase_i(opts
) &&
389 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
392 char *eol
= strchr(p
, '\n');
395 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
396 warning(_("could not delete '%s'"), p
);
406 strbuf_addstr(&buf
, get_dir(opts
));
407 if (remove_dir_recursively(&buf
, 0))
408 ret
= error(_("could not remove '%s'"), buf
.buf
);
409 strbuf_release(&buf
);
414 static const char *action_name(const struct replay_opts
*opts
)
416 switch (opts
->action
) {
420 return N_("cherry-pick");
421 case REPLAY_INTERACTIVE_REBASE
:
424 die(_("unknown action: %d"), opts
->action
);
427 struct commit_message
{
434 static const char *short_commit_name(struct commit
*commit
)
436 return repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
,
440 static int get_message(struct commit
*commit
, struct commit_message
*out
)
442 const char *abbrev
, *subject
;
445 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
446 get_commit_output_encoding());
447 abbrev
= short_commit_name(commit
);
449 subject_len
= find_commit_subject(out
->message
, &subject
);
451 out
->subject
= xmemdupz(subject
, subject_len
);
452 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
453 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
458 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
460 free(msg
->parent_label
);
463 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
466 static void print_advice(struct repository
*r
, int show_hint
,
467 struct replay_opts
*opts
)
469 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
474 * A conflict has occurred but the porcelain
475 * (typically rebase --interactive) wants to take care
476 * of the commit itself so remove CHERRY_PICK_HEAD
478 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
485 advise(_("after resolving the conflicts, mark the corrected paths\n"
486 "with 'git add <paths>' or 'git rm <paths>'"));
487 else if (opts
->action
== REPLAY_PICK
)
488 advise(_("After resolving the conflicts, mark them with\n"
489 "\"git add/rm <pathspec>\", then run\n"
490 "\"git cherry-pick --continue\".\n"
491 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
492 "To abort and get back to the state before \"git cherry-pick\",\n"
493 "run \"git cherry-pick --abort\"."));
494 else if (opts
->action
== REPLAY_REVERT
)
495 advise(_("After resolving the conflicts, mark them with\n"
496 "\"git add/rm <pathspec>\", then run\n"
497 "\"git revert --continue\".\n"
498 "You can instead skip this commit with \"git revert --skip\".\n"
499 "To abort and get back to the state before \"git revert\",\n"
500 "run \"git revert --abort\"."));
502 BUG("unexpected pick action in print_advice()");
506 static int write_message(const void *buf
, size_t len
, const char *filename
,
509 struct lock_file msg_file
= LOCK_INIT
;
511 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
513 return error_errno(_("could not lock '%s'"), filename
);
514 if (write_in_full(msg_fd
, buf
, len
) < 0) {
515 error_errno(_("could not write to '%s'"), filename
);
516 rollback_lock_file(&msg_file
);
519 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
520 error_errno(_("could not write eol to '%s'"), filename
);
521 rollback_lock_file(&msg_file
);
524 if (commit_lock_file(&msg_file
) < 0)
525 return error(_("failed to finalize '%s'"), filename
);
530 int read_oneliner(struct strbuf
*buf
,
531 const char *path
, unsigned flags
)
533 int orig_len
= buf
->len
;
535 if (strbuf_read_file(buf
, path
, 0) < 0) {
536 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
537 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
538 warning_errno(_("could not read '%s'"), path
);
542 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
543 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
545 buf
->buf
[buf
->len
] = '\0';
548 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
554 static struct tree
*empty_tree(struct repository
*r
)
556 return lookup_tree(r
, the_hash_algo
->empty_tree
);
559 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
561 if (repo_read_index_unmerged(repo
))
562 return error_resolve_conflict(action_name(opts
));
564 error(_("your local changes would be overwritten by %s."),
565 _(action_name(opts
)));
567 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
568 advise(_("commit your changes or stash them to proceed."));
572 static void update_abort_safety_file(void)
574 struct object_id head
;
576 /* Do nothing on a single-pick */
577 if (!file_exists(git_path_seq_dir()))
580 if (!repo_get_oid(the_repository
, "HEAD", &head
))
581 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
583 write_file(git_path_abort_safety_file(), "%s", "");
586 static int fast_forward_to(struct repository
*r
,
587 const struct object_id
*to
,
588 const struct object_id
*from
,
590 struct replay_opts
*opts
)
592 struct ref_transaction
*transaction
;
593 struct strbuf sb
= STRBUF_INIT
;
594 struct strbuf err
= STRBUF_INIT
;
597 if (checkout_fast_forward(r
, from
, to
, 1))
598 return -1; /* the callee should have complained already */
600 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
602 transaction
= ref_transaction_begin(&err
);
604 ref_transaction_update(transaction
, "HEAD",
605 to
, unborn
&& !is_rebase_i(opts
) ?
608 ref_transaction_commit(transaction
, &err
)) {
609 ref_transaction_free(transaction
);
610 error("%s", err
.buf
);
612 strbuf_release(&err
);
617 strbuf_release(&err
);
618 ref_transaction_free(transaction
);
619 update_abort_safety_file();
623 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
626 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
627 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
628 COMMIT_MSG_CLEANUP_SPACE
;
629 else if (!strcmp(cleanup_arg
, "verbatim"))
630 return COMMIT_MSG_CLEANUP_NONE
;
631 else if (!strcmp(cleanup_arg
, "whitespace"))
632 return COMMIT_MSG_CLEANUP_SPACE
;
633 else if (!strcmp(cleanup_arg
, "strip"))
634 return COMMIT_MSG_CLEANUP_ALL
;
635 else if (!strcmp(cleanup_arg
, "scissors"))
636 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
637 COMMIT_MSG_CLEANUP_SPACE
;
639 die(_("Invalid cleanup mode %s"), cleanup_arg
);
643 * NB using int rather than enum cleanup_mode to stop clang's
644 * -Wtautological-constant-out-of-range-compare complaining that the comparison
647 static const char *describe_cleanup_mode(int cleanup_mode
)
649 static const char *modes
[] = { "whitespace",
654 if (cleanup_mode
< ARRAY_SIZE(modes
))
655 return modes
[cleanup_mode
];
657 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
660 void append_conflicts_hint(struct index_state
*istate
,
661 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
665 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
666 strbuf_addch(msgbuf
, '\n');
667 wt_status_append_cut_line(msgbuf
);
668 strbuf_addch(msgbuf
, comment_line_char
);
671 strbuf_addch(msgbuf
, '\n');
672 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
673 for (i
= 0; i
< istate
->cache_nr
;) {
674 const struct cache_entry
*ce
= istate
->cache
[i
++];
676 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
677 while (i
< istate
->cache_nr
&&
678 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
684 static int do_recursive_merge(struct repository
*r
,
685 struct commit
*base
, struct commit
*next
,
686 const char *base_label
, const char *next_label
,
687 struct object_id
*head
, struct strbuf
*msgbuf
,
688 struct replay_opts
*opts
)
690 struct merge_options o
;
691 struct merge_result result
;
692 struct tree
*next_tree
, *base_tree
, *head_tree
;
693 int clean
, show_output
;
695 struct lock_file index_lock
= LOCK_INIT
;
697 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
702 init_merge_options(&o
, r
);
703 o
.ancestor
= base
? base_label
: "(empty tree)";
705 o
.branch2
= next
? next_label
: "(empty tree)";
706 if (is_rebase_i(opts
))
708 o
.show_rename_progress
= 1;
710 head_tree
= parse_tree_indirect(head
);
711 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
712 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
714 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
715 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
717 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
718 memset(&result
, 0, sizeof(result
));
719 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
721 show_output
= !is_rebase_i(opts
) || !result
.clean
;
723 * TODO: merge_switch_to_result will update index/working tree;
724 * we only really want to do that if !result.clean || this is
725 * the final patch to be picked. But determining this is the
726 * final patch would take some work, and "head_tree" would need
727 * to be replace with the tree the index matched before we
728 * started doing any picks.
730 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
731 clean
= result
.clean
;
733 ensure_full_index(r
->index
);
734 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
735 if (is_rebase_i(opts
) && clean
<= 0)
736 fputs(o
.obuf
.buf
, stdout
);
737 strbuf_release(&o
.obuf
);
740 rollback_lock_file(&index_lock
);
744 if (write_locked_index(r
->index
, &index_lock
,
745 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
747 * TRANSLATORS: %s will be "revert", "cherry-pick" or
750 return error(_("%s: Unable to write new index file"),
751 _(action_name(opts
)));
754 append_conflicts_hint(r
->index
, msgbuf
,
755 opts
->default_msg_cleanup
);
760 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
762 if (!cache_tree_fully_valid(istate
->cache_tree
))
763 if (cache_tree_update(istate
, 0)) {
764 error(_("unable to update cache tree"));
768 return &istate
->cache_tree
->oid
;
771 static int is_index_unchanged(struct repository
*r
)
773 struct object_id head_oid
, *cache_tree_oid
;
774 struct commit
*head_commit
;
775 struct index_state
*istate
= r
->index
;
777 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
778 return error(_("could not resolve HEAD commit"));
780 head_commit
= lookup_commit(r
, &head_oid
);
783 * If head_commit is NULL, check_commit, called from
784 * lookup_commit, would have indicated that head_commit is not
785 * a commit object already. repo_parse_commit() will return failure
786 * without further complaints in such a case. Otherwise, if
787 * the commit is invalid, repo_parse_commit() will complain. So
788 * there is nothing for us to say here. Just return failure.
790 if (repo_parse_commit(r
, head_commit
))
793 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
796 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
799 static int write_author_script(const char *message
)
801 struct strbuf buf
= STRBUF_INIT
;
806 if (!*message
|| starts_with(message
, "\n")) {
808 /* Missing 'author' line? */
809 unlink(rebase_path_author_script());
811 } else if (skip_prefix(message
, "author ", &message
))
813 else if ((eol
= strchr(message
, '\n')))
818 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
819 while (*message
&& *message
!= '\n' && *message
!= '\r')
820 if (skip_prefix(message
, " <", &message
))
822 else if (*message
!= '\'')
823 strbuf_addch(&buf
, *(message
++));
825 strbuf_addf(&buf
, "'\\%c'", *(message
++));
826 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
827 while (*message
&& *message
!= '\n' && *message
!= '\r')
828 if (skip_prefix(message
, "> ", &message
))
830 else if (*message
!= '\'')
831 strbuf_addch(&buf
, *(message
++));
833 strbuf_addf(&buf
, "'\\%c'", *(message
++));
834 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
835 while (*message
&& *message
!= '\n' && *message
!= '\r')
836 if (*message
!= '\'')
837 strbuf_addch(&buf
, *(message
++));
839 strbuf_addf(&buf
, "'\\%c'", *(message
++));
840 strbuf_addch(&buf
, '\'');
841 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
842 strbuf_release(&buf
);
847 * Take a series of KEY='VALUE' lines where VALUE part is
848 * sq-quoted, and append <KEY, VALUE> at the end of the string list
850 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
853 struct string_list_item
*item
;
855 char *cp
= strchr(buf
, '=');
857 np
= strchrnul(buf
, '\n');
858 return error(_("no key present in '%.*s'"),
859 (int) (np
- buf
), buf
);
861 np
= strchrnul(cp
, '\n');
863 item
= string_list_append(list
, buf
);
865 buf
= np
+ (*np
== '\n');
869 return error(_("unable to dequote value of '%s'"),
871 item
->util
= xstrdup(cp
);
877 * Reads and parses the state directory's "author-script" file, and sets name,
878 * email and date accordingly.
879 * Returns 0 on success, -1 if the file could not be parsed.
881 * The author script is of the format:
883 * GIT_AUTHOR_NAME='$author_name'
884 * GIT_AUTHOR_EMAIL='$author_email'
885 * GIT_AUTHOR_DATE='$author_date'
887 * where $author_name, $author_email and $author_date are quoted. We are strict
888 * with our parsing, as the file was meant to be eval'd in the now-removed
889 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
890 * from what this function expects, it is better to bail out than to do
891 * something that the user does not expect.
893 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
896 struct strbuf buf
= STRBUF_INIT
;
897 struct string_list kv
= STRING_LIST_INIT_DUP
;
898 int retval
= -1; /* assume failure */
899 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
901 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
902 strbuf_release(&buf
);
903 if (errno
== ENOENT
&& allow_missing
)
906 return error_errno(_("could not open '%s' for reading"),
910 if (parse_key_value_squoted(buf
.buf
, &kv
))
913 for (i
= 0; i
< kv
.nr
; i
++) {
914 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
916 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
919 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
921 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
924 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
926 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
930 err
= error(_("unknown variable '%s'"),
935 error(_("missing 'GIT_AUTHOR_NAME'"));
937 error(_("missing 'GIT_AUTHOR_EMAIL'"));
939 error(_("missing 'GIT_AUTHOR_DATE'"));
940 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
942 *name
= kv
.items
[name_i
].util
;
943 *email
= kv
.items
[email_i
].util
;
944 *date
= kv
.items
[date_i
].util
;
947 string_list_clear(&kv
, !!retval
);
948 strbuf_release(&buf
);
953 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
954 * file with shell quoting into struct strvec. Returns -1 on
955 * error, 0 otherwise.
957 static int read_env_script(struct strvec
*env
)
959 char *name
, *email
, *date
;
961 if (read_author_script(rebase_path_author_script(),
962 &name
, &email
, &date
, 0))
965 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
966 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
967 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
975 static char *get_author(const char *message
)
980 a
= find_commit_header(message
, "author", &len
);
982 return xmemdupz(a
, len
);
987 static const char *author_date_from_env(const struct strvec
*env
)
992 for (i
= 0; i
< env
->nr
; i
++)
993 if (skip_prefix(env
->v
[i
],
994 "GIT_AUTHOR_DATE=", &date
))
997 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1000 BUG("GIT_AUTHOR_DATE missing from author script");
1003 static const char staged_changes_advice
[] =
1004 N_("you have staged changes in your working tree\n"
1005 "If these changes are meant to be squashed into the previous commit, run:\n"
1007 " git commit --amend %s\n"
1009 "If they are meant to go into a new commit, run:\n"
1013 "In both cases, once you're done, continue with:\n"
1015 " git rebase --continue\n");
1017 #define ALLOW_EMPTY (1<<0)
1018 #define EDIT_MSG (1<<1)
1019 #define AMEND_MSG (1<<2)
1020 #define CLEANUP_MSG (1<<3)
1021 #define VERIFY_MSG (1<<4)
1022 #define CREATE_ROOT_COMMIT (1<<5)
1023 #define VERBATIM_MSG (1<<6)
1025 static int run_command_silent_on_success(struct child_process
*cmd
)
1027 struct strbuf buf
= STRBUF_INIT
;
1030 cmd
->stdout_to_stderr
= 1;
1031 rc
= pipe_command(cmd
,
1037 fputs(buf
.buf
, stderr
);
1038 strbuf_release(&buf
);
1043 * If we are cherry-pick, and if the merge did not result in
1044 * hand-editing, we will hit this commit and inherit the original
1045 * author date and name.
1047 * If we are revert, or if our cherry-pick results in a hand merge,
1048 * we had better say that the current user is responsible for that.
1050 * An exception is when run_git_commit() is called during an
1051 * interactive rebase: in that case, we will want to retain the
1054 static int run_git_commit(const char *defmsg
,
1055 struct replay_opts
*opts
,
1058 struct child_process cmd
= CHILD_PROCESS_INIT
;
1060 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1061 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1065 if (is_rebase_i(opts
) &&
1066 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1067 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1068 read_env_script(&cmd
.env
)) {
1069 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1071 return error(_(staged_changes_advice
),
1075 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1077 if (opts
->committer_date_is_author_date
)
1078 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1081 author_date_from_env(&cmd
.env
));
1082 if (opts
->ignore_date
)
1083 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1085 strvec_push(&cmd
.args
, "commit");
1087 if (!(flags
& VERIFY_MSG
))
1088 strvec_push(&cmd
.args
, "-n");
1089 if ((flags
& AMEND_MSG
))
1090 strvec_push(&cmd
.args
, "--amend");
1092 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1094 strvec_push(&cmd
.args
, "--no-gpg-sign");
1096 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1097 else if (!(flags
& EDIT_MSG
))
1098 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1099 if ((flags
& CLEANUP_MSG
))
1100 strvec_push(&cmd
.args
, "--cleanup=strip");
1101 if ((flags
& VERBATIM_MSG
))
1102 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1103 if ((flags
& EDIT_MSG
))
1104 strvec_push(&cmd
.args
, "-e");
1105 else if (!(flags
& CLEANUP_MSG
) &&
1106 !opts
->signoff
&& !opts
->record_origin
&&
1107 !opts
->explicit_cleanup
)
1108 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1110 if ((flags
& ALLOW_EMPTY
))
1111 strvec_push(&cmd
.args
, "--allow-empty");
1113 if (!(flags
& EDIT_MSG
))
1114 strvec_push(&cmd
.args
, "--allow-empty-message");
1116 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1117 return run_command_silent_on_success(&cmd
);
1119 return run_command(&cmd
);
1122 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1127 /* Check if the rest is just whitespace and Signed-off-by's. */
1128 for (i
= start
; i
< sb
->len
; i
++) {
1129 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1135 if (strlen(sign_off_header
) <= eol
- i
&&
1136 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1141 if (!isspace(sb
->buf
[i
++]))
1148 void cleanup_message(struct strbuf
*msgbuf
,
1149 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1151 if (verbose
|| /* Truncate the message just before the diff, if any. */
1152 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1153 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1154 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1155 strbuf_stripspace(msgbuf
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
1159 * Find out if the message in the strbuf contains only whitespace and
1160 * Signed-off-by lines.
1162 int message_is_empty(const struct strbuf
*sb
,
1163 enum commit_msg_cleanup_mode cleanup_mode
)
1165 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1167 return rest_is_empty(sb
, 0);
1171 * See if the user edited the message in the editor or left what
1172 * was in the template intact
1174 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1175 enum commit_msg_cleanup_mode cleanup_mode
)
1177 struct strbuf tmpl
= STRBUF_INIT
;
1180 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1183 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1186 strbuf_stripspace(&tmpl
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
1187 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1189 strbuf_release(&tmpl
);
1190 return rest_is_empty(sb
, start
- sb
->buf
);
1193 int update_head_with_reflog(const struct commit
*old_head
,
1194 const struct object_id
*new_head
,
1195 const char *action
, const struct strbuf
*msg
,
1198 struct ref_transaction
*transaction
;
1199 struct strbuf sb
= STRBUF_INIT
;
1204 strbuf_addstr(&sb
, action
);
1205 strbuf_addstr(&sb
, ": ");
1208 nl
= strchr(msg
->buf
, '\n');
1210 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1212 strbuf_addbuf(&sb
, msg
);
1213 strbuf_addch(&sb
, '\n');
1216 transaction
= ref_transaction_begin(err
);
1218 ref_transaction_update(transaction
, "HEAD", new_head
,
1219 old_head
? &old_head
->object
.oid
: null_oid(),
1221 ref_transaction_commit(transaction
, err
)) {
1224 ref_transaction_free(transaction
);
1225 strbuf_release(&sb
);
1230 static int run_rewrite_hook(const struct object_id
*oldoid
,
1231 const struct object_id
*newoid
)
1233 struct child_process proc
= CHILD_PROCESS_INIT
;
1235 struct strbuf sb
= STRBUF_INIT
;
1236 const char *hook_path
= find_hook("post-rewrite");
1241 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1243 proc
.stdout_to_stderr
= 1;
1244 proc
.trace2_hook_name
= "post-rewrite";
1246 code
= start_command(&proc
);
1249 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1250 sigchain_push(SIGPIPE
, SIG_IGN
);
1251 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1253 strbuf_release(&sb
);
1254 sigchain_pop(SIGPIPE
);
1255 return finish_command(&proc
);
1258 void commit_post_rewrite(struct repository
*r
,
1259 const struct commit
*old_head
,
1260 const struct object_id
*new_head
)
1262 struct notes_rewrite_cfg
*cfg
;
1264 cfg
= init_copy_notes_for_rewrite("amend");
1266 /* we are amending, so old_head is not NULL */
1267 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1268 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1270 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1273 static int run_prepare_commit_msg_hook(struct repository
*r
,
1278 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1280 name
= git_path_commit_editmsg();
1281 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1290 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1292 ret
= error(_("'prepare-commit-msg' hook failed"));
1297 static const char implicit_ident_advice_noconfig
[] =
1298 N_("Your name and email address were configured automatically based\n"
1299 "on your username and hostname. Please check that they are accurate.\n"
1300 "You can suppress this message by setting them explicitly. Run the\n"
1301 "following command and follow the instructions in your editor to edit\n"
1302 "your configuration file:\n"
1304 " git config --global --edit\n"
1306 "After doing this, you may fix the identity used for this commit with:\n"
1308 " git commit --amend --reset-author\n");
1310 static const char implicit_ident_advice_config
[] =
1311 N_("Your name and email address were configured automatically based\n"
1312 "on your username and hostname. Please check that they are accurate.\n"
1313 "You can suppress this message by setting them explicitly:\n"
1315 " git config --global user.name \"Your Name\"\n"
1316 " git config --global user.email you@example.com\n"
1318 "After doing this, you may fix the identity used for this commit with:\n"
1320 " git commit --amend --reset-author\n");
1322 static const char *implicit_ident_advice(void)
1324 char *user_config
= interpolate_path("~/.gitconfig", 0);
1325 char *xdg_config
= xdg_config_home("config");
1326 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1332 return _(implicit_ident_advice_config
);
1334 return _(implicit_ident_advice_noconfig
);
1338 void print_commit_summary(struct repository
*r
,
1340 const struct object_id
*oid
,
1343 struct rev_info rev
;
1344 struct commit
*commit
;
1345 struct strbuf format
= STRBUF_INIT
;
1347 struct pretty_print_context pctx
= {0};
1348 struct strbuf author_ident
= STRBUF_INIT
;
1349 struct strbuf committer_ident
= STRBUF_INIT
;
1350 struct ref_store
*refs
;
1352 commit
= lookup_commit(r
, oid
);
1354 die(_("couldn't look up newly created commit"));
1355 if (repo_parse_commit(r
, commit
))
1356 die(_("could not parse newly created commit"));
1358 strbuf_addstr(&format
, "format:%h] %s");
1360 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1362 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1364 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1365 strbuf_addstr(&format
, "\n Author: ");
1366 strbuf_addbuf_percentquote(&format
, &author_ident
);
1368 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1369 struct strbuf date
= STRBUF_INIT
;
1371 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1372 strbuf_addstr(&format
, "\n Date: ");
1373 strbuf_addbuf_percentquote(&format
, &date
);
1374 strbuf_release(&date
);
1376 if (!committer_ident_sufficiently_given()) {
1377 strbuf_addstr(&format
, "\n Committer: ");
1378 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1379 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1380 strbuf_addch(&format
, '\n');
1381 strbuf_addstr(&format
, implicit_ident_advice());
1384 strbuf_release(&author_ident
);
1385 strbuf_release(&committer_ident
);
1387 repo_init_revisions(r
, &rev
, prefix
);
1388 setup_revisions(0, NULL
, &rev
, NULL
);
1391 rev
.diffopt
.output_format
=
1392 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1394 rev
.verbose_header
= 1;
1395 rev
.show_root_diff
= 1;
1396 get_commit_format(format
.buf
, &rev
);
1397 rev
.always_show_header
= 0;
1398 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1399 diff_setup_done(&rev
.diffopt
);
1401 refs
= get_main_ref_store(r
);
1402 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1404 die(_("unable to resolve HEAD after creating commit"));
1405 if (!strcmp(head
, "HEAD"))
1406 head
= _("detached HEAD");
1408 skip_prefix(head
, "refs/heads/", &head
);
1409 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1410 _(" (root-commit)") : "");
1412 if (!log_tree_commit(&rev
, commit
)) {
1413 rev
.always_show_header
= 1;
1414 rev
.use_terminator
= 1;
1415 log_tree_commit(&rev
, commit
);
1418 release_revisions(&rev
);
1419 strbuf_release(&format
);
1422 static int parse_head(struct repository
*r
, struct commit
**head
)
1424 struct commit
*current_head
;
1425 struct object_id oid
;
1427 if (repo_get_oid(r
, "HEAD", &oid
)) {
1428 current_head
= NULL
;
1430 current_head
= lookup_commit_reference(r
, &oid
);
1432 return error(_("could not parse HEAD"));
1433 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1434 warning(_("HEAD %s is not a commit!"),
1437 if (repo_parse_commit(r
, current_head
))
1438 return error(_("could not parse HEAD commit"));
1440 *head
= current_head
;
1446 * Try to commit without forking 'git commit'. In some cases we need
1447 * to run 'git commit' to display an error message
1450 * -1 - error unable to commit
1452 * 1 - run 'git commit'
1454 static int try_to_commit(struct repository
*r
,
1455 struct strbuf
*msg
, const char *author
,
1456 struct replay_opts
*opts
, unsigned int flags
,
1457 struct object_id
*oid
)
1459 struct object_id tree
;
1460 struct commit
*current_head
= NULL
;
1461 struct commit_list
*parents
= NULL
;
1462 struct commit_extra_header
*extra
= NULL
;
1463 struct strbuf err
= STRBUF_INIT
;
1464 struct strbuf commit_msg
= STRBUF_INIT
;
1465 char *amend_author
= NULL
;
1466 const char *committer
= NULL
;
1467 const char *hook_commit
= NULL
;
1468 enum commit_msg_cleanup_mode cleanup
;
1471 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1472 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1474 if (parse_head(r
, ¤t_head
))
1477 if (flags
& AMEND_MSG
) {
1478 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1479 const char *out_enc
= get_commit_output_encoding();
1480 const char *message
= repo_logmsg_reencode(r
, current_head
,
1484 const char *orig_message
= NULL
;
1486 find_commit_subject(message
, &orig_message
);
1488 strbuf_addstr(msg
, orig_message
);
1489 hook_commit
= "HEAD";
1491 author
= amend_author
= get_author(message
);
1492 repo_unuse_commit_buffer(r
, current_head
,
1495 res
= error(_("unable to parse commit author"));
1498 parents
= copy_commit_list(current_head
->parents
);
1499 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1500 } else if (current_head
&&
1501 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1502 commit_list_insert(current_head
, &parents
);
1505 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1506 res
= error(_("git write-tree failed to write a tree"));
1510 if (!(flags
& ALLOW_EMPTY
)) {
1511 struct commit
*first_parent
= current_head
;
1513 if (flags
& AMEND_MSG
) {
1514 if (current_head
->parents
) {
1515 first_parent
= current_head
->parents
->item
;
1516 if (repo_parse_commit(r
, first_parent
)) {
1517 res
= error(_("could not parse HEAD commit"));
1521 first_parent
= NULL
;
1524 if (oideq(first_parent
1525 ? get_commit_tree_oid(first_parent
)
1526 : the_hash_algo
->empty_tree
,
1528 res
= 1; /* run 'git commit' to display error message */
1533 if (hook_exists("prepare-commit-msg")) {
1534 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1537 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1539 res
= error_errno(_("unable to read commit message "
1541 git_path_commit_editmsg());
1547 if (flags
& CLEANUP_MSG
)
1548 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1549 else if (flags
& VERBATIM_MSG
)
1550 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1551 else if ((opts
->signoff
|| opts
->record_origin
) &&
1552 !opts
->explicit_cleanup
)
1553 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1555 cleanup
= opts
->default_msg_cleanup
;
1557 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1558 strbuf_stripspace(msg
, cleanup
== COMMIT_MSG_CLEANUP_ALL
);
1559 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1560 res
= 1; /* run 'git commit' to display error message */
1564 if (opts
->committer_date_is_author_date
) {
1565 struct ident_split id
;
1566 struct strbuf date
= STRBUF_INIT
;
1568 if (!opts
->ignore_date
) {
1569 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1570 res
= error(_("invalid author identity '%s'"),
1574 if (!id
.date_begin
) {
1576 "corrupt author: missing date information"));
1579 strbuf_addf(&date
, "@%.*s %.*s",
1580 (int)(id
.date_end
- id
.date_begin
),
1582 (int)(id
.tz_end
- id
.tz_begin
),
1587 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1588 getenv("GIT_COMMITTER_EMAIL"),
1589 WANT_COMMITTER_IDENT
,
1590 opts
->ignore_date
? NULL
: date
.buf
,
1592 strbuf_release(&date
);
1597 if (opts
->ignore_date
) {
1598 struct ident_split id
;
1601 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1602 error(_("invalid author identity '%s'"), author
);
1605 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1606 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1607 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1613 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1614 author
, committer
, opts
->gpg_sign
, extra
)) {
1615 res
= error(_("failed to write commit object"));
1619 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1621 res
= error("%s", err
.buf
);
1625 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1626 if (flags
& AMEND_MSG
)
1627 commit_post_rewrite(r
, current_head
, oid
);
1630 free_commit_extra_headers(extra
);
1631 strbuf_release(&err
);
1632 strbuf_release(&commit_msg
);
1638 static int write_rebase_head(struct object_id
*oid
)
1640 if (update_ref("rebase", "REBASE_HEAD", oid
,
1641 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1642 return error(_("could not update %s"), "REBASE_HEAD");
1647 static int do_commit(struct repository
*r
,
1648 const char *msg_file
, const char *author
,
1649 struct replay_opts
*opts
, unsigned int flags
,
1650 struct object_id
*oid
)
1654 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1655 struct object_id oid
;
1656 struct strbuf sb
= STRBUF_INIT
;
1658 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1659 return error_errno(_("unable to read commit message "
1663 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1664 author
, opts
, flags
, &oid
);
1665 strbuf_release(&sb
);
1667 refs_delete_ref(get_main_ref_store(r
), "",
1668 "CHERRY_PICK_HEAD", NULL
, 0);
1669 unlink(git_path_merge_msg(r
));
1670 if (!is_rebase_i(opts
))
1671 print_commit_summary(r
, NULL
, &oid
,
1672 SUMMARY_SHOW_AUTHOR_DATE
);
1677 if (is_rebase_i(opts
) && oid
)
1678 if (write_rebase_head(oid
))
1680 return run_git_commit(msg_file
, opts
, flags
);
1686 static int is_original_commit_empty(struct commit
*commit
)
1688 const struct object_id
*ptree_oid
;
1690 if (repo_parse_commit(the_repository
, commit
))
1691 return error(_("could not parse commit %s"),
1692 oid_to_hex(&commit
->object
.oid
));
1693 if (commit
->parents
) {
1694 struct commit
*parent
= commit
->parents
->item
;
1695 if (repo_parse_commit(the_repository
, parent
))
1696 return error(_("could not parse parent commit %s"),
1697 oid_to_hex(&parent
->object
.oid
));
1698 ptree_oid
= get_commit_tree_oid(parent
);
1700 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1703 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1707 * Should empty commits be allowed? Return status:
1708 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1709 * 0: Halt on empty commit
1710 * 1: Allow empty commit
1711 * 2: Drop empty commit
1713 static int allow_empty(struct repository
*r
,
1714 struct replay_opts
*opts
,
1715 struct commit
*commit
)
1717 int index_unchanged
, originally_empty
;
1722 * (1) we do not allow empty at all and error out.
1724 * (2) we allow ones that were initially empty, and
1725 * just drop the ones that become empty
1727 * (3) we allow ones that were initially empty, but
1728 * halt for the ones that become empty;
1730 * (4) we allow both.
1732 if (!opts
->allow_empty
)
1733 return 0; /* let "git commit" barf as necessary */
1735 index_unchanged
= is_index_unchanged(r
);
1736 if (index_unchanged
< 0)
1737 return index_unchanged
;
1738 if (!index_unchanged
)
1739 return 0; /* we do not have to say --allow-empty */
1741 if (opts
->keep_redundant_commits
)
1744 originally_empty
= is_original_commit_empty(commit
);
1745 if (originally_empty
< 0)
1746 return originally_empty
;
1747 if (originally_empty
)
1749 else if (opts
->drop_redundant_commits
)
1758 } todo_command_info
[] = {
1759 [TODO_PICK
] = { 'p', "pick" },
1760 [TODO_REVERT
] = { 0, "revert" },
1761 [TODO_EDIT
] = { 'e', "edit" },
1762 [TODO_REWORD
] = { 'r', "reword" },
1763 [TODO_FIXUP
] = { 'f', "fixup" },
1764 [TODO_SQUASH
] = { 's', "squash" },
1765 [TODO_EXEC
] = { 'x', "exec" },
1766 [TODO_BREAK
] = { 'b', "break" },
1767 [TODO_LABEL
] = { 'l', "label" },
1768 [TODO_RESET
] = { 't', "reset" },
1769 [TODO_MERGE
] = { 'm', "merge" },
1770 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1771 [TODO_NOOP
] = { 0, "noop" },
1772 [TODO_DROP
] = { 'd', "drop" },
1773 [TODO_COMMENT
] = { 0, NULL
},
1776 static const char *command_to_string(const enum todo_command command
)
1778 if (command
< TODO_COMMENT
)
1779 return todo_command_info
[command
].str
;
1780 die(_("unknown command: %d"), command
);
1783 static char command_to_char(const enum todo_command command
)
1785 if (command
< TODO_COMMENT
)
1786 return todo_command_info
[command
].c
;
1787 return comment_line_char
;
1790 static int is_noop(const enum todo_command command
)
1792 return TODO_NOOP
<= command
;
1795 static int is_fixup(enum todo_command command
)
1797 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1800 /* Does this command create a (non-merge) commit? */
1801 static int is_pick_or_similar(enum todo_command command
)
1816 enum todo_item_flags
{
1817 TODO_EDIT_MERGE_MSG
= (1 << 0),
1818 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1819 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1822 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1823 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1824 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1825 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1826 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1828 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1830 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1831 (flag
& TODO_EDIT_FIXUP_MSG
));
1835 * Wrapper around strbuf_add_commented_lines() which avoids double
1836 * commenting commit subjects.
1838 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1840 const char *s
= str
;
1841 while (len
> 0 && s
[0] == comment_line_char
) {
1843 const char *n
= memchr(s
, '\n', len
);
1848 strbuf_add(buf
, s
, count
);
1852 strbuf_add_commented_lines(buf
, s
, len
);
1855 /* Does the current fixup chain contain a squash command? */
1856 static int seen_squash(struct replay_opts
*opts
)
1858 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1859 strstr(opts
->current_fixups
.buf
, "\nsquash");
1862 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1864 strbuf_setlen(buf1
, 2);
1865 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1866 strbuf_addch(buf1
, '\n');
1867 strbuf_setlen(buf2
, 2);
1868 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1869 strbuf_addch(buf2
, '\n');
1873 * Comment out any un-commented commit messages, updating the message comments
1874 * to say they will be skipped but do not comment out the empty lines that
1875 * surround commit messages and their comments.
1877 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1879 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1880 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1881 const char *s
, *start
;
1883 size_t orig_msg_len
;
1886 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1887 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1888 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1892 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1894 * Copy the last message, preserving the blank line
1895 * preceding the current line
1897 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1898 copy_lines(msg
, start
, s
- start
- off
);
1900 strbuf_addch(msg
, '\n');
1902 * The next message needs to be commented out but the
1903 * message header is already commented out so just copy
1904 * it and the blank line that follows it.
1906 strbuf_addbuf(msg
, &buf2
);
1908 strbuf_addch(msg
, *next
++);
1910 copy_lines
= add_commented_lines
;
1911 update_comment_bufs(&buf1
, &buf2
, ++i
);
1912 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1913 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1914 copy_lines(msg
, start
, s
- start
- off
);
1917 copy_lines
= strbuf_add
;
1918 update_comment_bufs(&buf1
, &buf2
, ++i
);
1920 s
= strchr(s
, '\n');
1925 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1927 strbuf_release(&buf1
);
1928 strbuf_release(&buf2
);
1931 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1932 enum todo_command command
, struct replay_opts
*opts
,
1935 const char *fixup_msg
;
1936 size_t commented_len
= 0, fixup_off
;
1938 * amend is non-interactive and not normally used with fixup!
1939 * or squash! commits, so only comment out those subjects when
1940 * squashing commit messages.
1942 if (starts_with(body
, "amend!") ||
1943 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1944 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1945 commented_len
= commit_subject_length(body
);
1947 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1948 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1949 ++opts
->current_fixup_count
+ 1);
1950 strbuf_addstr(buf
, "\n\n");
1951 strbuf_add_commented_lines(buf
, body
, commented_len
);
1952 /* buf->buf may be reallocated so store an offset into the buffer */
1953 fixup_off
= buf
->len
;
1954 strbuf_addstr(buf
, body
+ commented_len
);
1956 /* fixup -C after squash behaves like squash */
1957 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1959 * We're replacing the commit message so we need to
1960 * append the Signed-off-by: trailer if the user
1961 * requested '--signoff'.
1964 append_signoff(buf
, 0, 0);
1966 if ((command
== TODO_FIXUP
) &&
1967 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1968 (file_exists(rebase_path_fixup_msg()) ||
1969 !file_exists(rebase_path_squash_msg()))) {
1970 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1971 if (write_message(fixup_msg
, strlen(fixup_msg
),
1972 rebase_path_fixup_msg(), 0) < 0)
1973 return error(_("cannot write '%s'"),
1974 rebase_path_fixup_msg());
1976 unlink(rebase_path_fixup_msg());
1979 unlink(rebase_path_fixup_msg());
1985 static int update_squash_messages(struct repository
*r
,
1986 enum todo_command command
,
1987 struct commit
*commit
,
1988 struct replay_opts
*opts
,
1991 struct strbuf buf
= STRBUF_INIT
;
1993 const char *message
, *body
;
1994 const char *encoding
= get_commit_output_encoding();
1996 if (opts
->current_fixup_count
> 0) {
1997 struct strbuf header
= STRBUF_INIT
;
2000 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2001 return error(_("could not read '%s'"),
2002 rebase_path_squash_msg());
2004 eol
= buf
.buf
[0] != comment_line_char
?
2005 buf
.buf
: strchrnul(buf
.buf
, '\n');
2007 strbuf_addf(&header
, "%c ", comment_line_char
);
2008 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2009 opts
->current_fixup_count
+ 2);
2010 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2011 strbuf_release(&header
);
2012 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2013 update_squash_message_for_fixup(&buf
);
2015 struct object_id head
;
2016 struct commit
*head_commit
;
2017 const char *head_message
, *body
;
2019 if (repo_get_oid(r
, "HEAD", &head
))
2020 return error(_("need a HEAD to fixup"));
2021 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2022 return error(_("could not read HEAD"));
2023 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2025 return error(_("could not read HEAD's commit message"));
2027 find_commit_subject(head_message
, &body
);
2028 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2029 rebase_path_fixup_msg(), 0) < 0) {
2030 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2031 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2033 strbuf_addf(&buf
, "%c ", comment_line_char
);
2034 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2035 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2036 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2037 _(skip_first_commit_msg_str
) :
2038 _(first_commit_msg_str
));
2039 strbuf_addstr(&buf
, "\n\n");
2040 if (is_fixup_flag(command
, flag
))
2041 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
2043 strbuf_addstr(&buf
, body
);
2045 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2048 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2049 return error(_("could not read commit message of %s"),
2050 oid_to_hex(&commit
->object
.oid
));
2051 find_commit_subject(message
, &body
);
2053 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2054 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2055 } else if (command
== TODO_FIXUP
) {
2056 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2057 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2058 ++opts
->current_fixup_count
+ 1);
2059 strbuf_addstr(&buf
, "\n\n");
2060 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
2062 return error(_("unknown command: %d"), command
);
2063 repo_unuse_commit_buffer(r
, commit
, message
);
2066 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2068 strbuf_release(&buf
);
2071 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2072 opts
->current_fixups
.len
? "\n" : "",
2073 command_to_string(command
),
2074 oid_to_hex(&commit
->object
.oid
));
2075 res
= write_message(opts
->current_fixups
.buf
,
2076 opts
->current_fixups
.len
,
2077 rebase_path_current_fixups(), 0);
2083 static void flush_rewritten_pending(void)
2085 struct strbuf buf
= STRBUF_INIT
;
2086 struct object_id newoid
;
2089 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2090 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2091 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2092 char *bol
= buf
.buf
, *eol
;
2095 eol
= strchrnul(bol
, '\n');
2096 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2097 bol
, oid_to_hex(&newoid
));
2103 unlink(rebase_path_rewritten_pending());
2105 strbuf_release(&buf
);
2108 static void record_in_rewritten(struct object_id
*oid
,
2109 enum todo_command next_command
)
2111 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2116 fprintf(out
, "%s\n", oid_to_hex(oid
));
2119 if (!is_fixup(next_command
))
2120 flush_rewritten_pending();
2123 static int should_edit(struct replay_opts
*opts
) {
2126 * Note that we only handle the case of non-conflicted
2127 * commits; continue_single_pick() handles the conflicted
2128 * commits itself instead of calling this function.
2130 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2134 static void refer_to_commit(struct replay_opts
*opts
,
2135 struct strbuf
*msgbuf
, struct commit
*commit
)
2137 if (opts
->commit_use_reference
) {
2138 struct pretty_print_context ctx
= {
2139 .abbrev
= DEFAULT_ABBREV
,
2140 .date_mode
.type
= DATE_SHORT
,
2142 repo_format_commit_message(the_repository
, commit
,
2143 "%h (%s, %ad)", msgbuf
, &ctx
);
2145 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2149 static int do_pick_commit(struct repository
*r
,
2150 struct todo_item
*item
,
2151 struct replay_opts
*opts
,
2152 int final_fixup
, int *check_todo
)
2154 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2155 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2156 struct object_id head
;
2157 struct commit
*base
, *next
, *parent
;
2158 const char *base_label
, *next_label
;
2159 char *author
= NULL
;
2160 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2161 struct strbuf msgbuf
= STRBUF_INIT
;
2162 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2163 enum todo_command command
= item
->command
;
2164 struct commit
*commit
= item
->commit
;
2166 if (opts
->no_commit
) {
2168 * We do not intend to commit immediately. We just want to
2169 * merge the differences in, so let's compute the tree
2170 * that represents the "current" state for the merge machinery
2173 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2174 return error(_("your index file is unmerged."));
2176 unborn
= repo_get_oid(r
, "HEAD", &head
);
2177 /* Do we want to generate a root commit? */
2178 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2179 oideq(&head
, &opts
->squash_onto
)) {
2180 if (is_fixup(command
))
2181 return error(_("cannot fixup root commit"));
2182 flags
|= CREATE_ROOT_COMMIT
;
2185 oidcpy(&head
, the_hash_algo
->empty_tree
);
2186 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2188 return error_dirty_index(r
, opts
);
2190 discard_index(r
->index
);
2192 if (!commit
->parents
)
2194 else if (commit
->parents
->next
) {
2195 /* Reverting or cherry-picking a merge commit */
2197 struct commit_list
*p
;
2199 if (!opts
->mainline
)
2200 return error(_("commit %s is a merge but no -m option was given."),
2201 oid_to_hex(&commit
->object
.oid
));
2203 for (cnt
= 1, p
= commit
->parents
;
2204 cnt
!= opts
->mainline
&& p
;
2207 if (cnt
!= opts
->mainline
|| !p
)
2208 return error(_("commit %s does not have parent %d"),
2209 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2211 } else if (1 < opts
->mainline
)
2213 * Non-first parent explicitly specified as mainline for
2216 return error(_("commit %s does not have parent %d"),
2217 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2219 parent
= commit
->parents
->item
;
2221 if (get_message(commit
, &msg
) != 0)
2222 return error(_("cannot get commit message for %s"),
2223 oid_to_hex(&commit
->object
.oid
));
2225 if (opts
->allow_ff
&& !is_fixup(command
) &&
2226 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2227 (!parent
&& unborn
))) {
2228 if (is_rebase_i(opts
))
2229 write_author_script(msg
.message
);
2230 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2232 if (res
|| command
!= TODO_REWORD
)
2236 goto fast_forward_edit
;
2238 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2239 /* TRANSLATORS: The first %s will be a "todo" command like
2240 "revert" or "pick", the second %s a SHA1. */
2241 return error(_("%s: cannot parse parent commit %s"),
2242 command_to_string(command
),
2243 oid_to_hex(&parent
->object
.oid
));
2246 * "commit" is an existing commit. We would want to apply
2247 * the difference it introduces since its first parent "prev"
2248 * on top of the current HEAD if we are cherry-pick. Or the
2249 * reverse of it if we are revert.
2252 if (command
== TODO_REVERT
) {
2254 base_label
= msg
.label
;
2256 next_label
= msg
.parent_label
;
2257 if (opts
->commit_use_reference
) {
2258 strbuf_addstr(&msgbuf
,
2259 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2261 strbuf_addstr(&msgbuf
, "Revert \"");
2262 strbuf_addstr(&msgbuf
, msg
.subject
);
2263 strbuf_addstr(&msgbuf
, "\"");
2265 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2266 refer_to_commit(opts
, &msgbuf
, commit
);
2268 if (commit
->parents
&& commit
->parents
->next
) {
2269 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2270 refer_to_commit(opts
, &msgbuf
, parent
);
2272 strbuf_addstr(&msgbuf
, ".\n");
2277 base_label
= msg
.parent_label
;
2279 next_label
= msg
.label
;
2281 /* Append the commit log message to msgbuf. */
2282 if (find_commit_subject(msg
.message
, &p
))
2283 strbuf_addstr(&msgbuf
, p
);
2285 if (opts
->record_origin
) {
2286 strbuf_complete_line(&msgbuf
);
2287 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2288 strbuf_addch(&msgbuf
, '\n');
2289 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2290 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2291 strbuf_addstr(&msgbuf
, ")\n");
2293 if (!is_fixup(command
))
2294 author
= get_author(msg
.message
);
2297 if (command
== TODO_REWORD
)
2299 else if (is_fixup(command
)) {
2300 if (update_squash_messages(r
, command
, commit
,
2301 opts
, item
->flags
)) {
2307 msg_file
= rebase_path_squash_msg();
2308 else if (file_exists(rebase_path_fixup_msg())) {
2309 flags
|= VERBATIM_MSG
;
2310 msg_file
= rebase_path_fixup_msg();
2312 const char *dest
= git_path_squash_msg(r
);
2314 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2315 res
= error(_("could not rename '%s' to '%s'"),
2316 rebase_path_squash_msg(), dest
);
2319 unlink(git_path_merge_msg(r
));
2325 if (opts
->signoff
&& !is_fixup(command
))
2326 append_signoff(&msgbuf
, 0, 0);
2328 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2330 else if (!opts
->strategy
||
2331 !strcmp(opts
->strategy
, "recursive") ||
2332 !strcmp(opts
->strategy
, "ort") ||
2333 command
== TODO_REVERT
) {
2334 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2335 &head
, &msgbuf
, opts
);
2339 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2340 git_path_merge_msg(r
), 0);
2342 struct commit_list
*common
= NULL
;
2343 struct commit_list
*remotes
= NULL
;
2345 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2346 git_path_merge_msg(r
), 0);
2348 commit_list_insert(base
, &common
);
2349 commit_list_insert(next
, &remotes
);
2350 res
|= try_merge_command(r
, opts
->strategy
,
2351 opts
->xopts
.nr
, opts
->xopts
.v
,
2352 common
, oid_to_hex(&head
), remotes
);
2353 free_commit_list(common
);
2354 free_commit_list(remotes
);
2358 * If the merge was clean or if it failed due to conflict, we write
2359 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2360 * However, if the merge did not even start, then we don't want to
2363 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2364 command
== TODO_EDIT
) && !opts
->no_commit
&&
2365 (res
== 0 || res
== 1) &&
2366 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2367 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2369 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2370 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2371 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2375 error(command
== TODO_REVERT
2376 ? _("could not revert %s... %s")
2377 : _("could not apply %s... %s"),
2378 short_commit_name(commit
), msg
.subject
);
2379 print_advice(r
, res
== 1, opts
);
2380 repo_rerere(r
, opts
->allow_rerere_auto
);
2385 allow
= allow_empty(r
, opts
, commit
);
2389 } else if (allow
== 1) {
2390 flags
|= ALLOW_EMPTY
;
2391 } else if (allow
== 2) {
2393 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2395 unlink(git_path_merge_msg(r
));
2396 unlink(git_path_auto_merge(r
));
2398 _("dropping %s %s -- patch contents already upstream\n"),
2399 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2400 } /* else allow == 0 and there's nothing special to do */
2401 if (!opts
->no_commit
&& !drop_commit
) {
2402 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2403 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2404 commit
? &commit
->object
.oid
: NULL
);
2406 res
= error(_("unable to parse commit author"));
2407 *check_todo
= !!(flags
& EDIT_MSG
);
2408 if (!res
&& reword
) {
2410 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2411 VERIFY_MSG
| AMEND_MSG
|
2412 (flags
& ALLOW_EMPTY
));
2418 if (!res
&& final_fixup
) {
2419 unlink(rebase_path_fixup_msg());
2420 unlink(rebase_path_squash_msg());
2421 unlink(rebase_path_current_fixups());
2422 strbuf_reset(&opts
->current_fixups
);
2423 opts
->current_fixup_count
= 0;
2427 free_message(commit
, &msg
);
2429 strbuf_release(&msgbuf
);
2430 update_abort_safety_file();
2435 static int prepare_revs(struct replay_opts
*opts
)
2438 * picking (but not reverting) ranges (but not individual revisions)
2439 * should be done in reverse
2441 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2442 opts
->revs
->reverse
^= 1;
2444 if (prepare_revision_walk(opts
->revs
))
2445 return error(_("revision walk setup failed"));
2450 static int read_and_refresh_cache(struct repository
*r
,
2451 struct replay_opts
*opts
)
2453 struct lock_file index_lock
= LOCK_INIT
;
2454 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2455 if (repo_read_index(r
) < 0) {
2456 rollback_lock_file(&index_lock
);
2457 return error(_("git %s: failed to read the index"),
2460 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2462 if (index_fd
>= 0) {
2463 if (write_locked_index(r
->index
, &index_lock
,
2464 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2465 return error(_("git %s: failed to refresh the index"),
2471 * If we are resolving merges in any way other than "ort", then
2472 * expand the sparse index.
2474 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2475 ensure_full_index(r
->index
);
2479 void todo_list_release(struct todo_list
*todo_list
)
2481 strbuf_release(&todo_list
->buf
);
2482 FREE_AND_NULL(todo_list
->items
);
2483 todo_list
->nr
= todo_list
->alloc
= 0;
2486 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2488 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2489 return todo_list
->items
+ todo_list
->nr
++;
2492 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2493 struct todo_item
*item
)
2495 return todo_list
->buf
.buf
+ item
->arg_offset
;
2498 static int is_command(enum todo_command command
, const char **bol
)
2500 const char *str
= todo_command_info
[command
].str
;
2501 const char nick
= todo_command_info
[command
].c
;
2502 const char *p
= *bol
;
2504 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2505 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2509 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2514 * '#' is not a valid label as the merge command uses it to
2515 * separate merge parents from the commit subject.
2517 if (!strcmp(arg
, "#") ||
2518 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2519 return error(_("'%s' is not a valid label"), arg
);
2522 case TODO_UPDATE_REF
:
2523 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2524 return error(_("'%s' is not a valid refname"), arg
);
2525 if (check_refname_format(arg
, 0))
2526 return error(_("update-ref requires a fully qualified "
2527 "refname e.g. refs/heads/%s"), arg
);
2531 BUG("unexpected todo_command");
2537 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2538 const char *buf
, const char *bol
, char *eol
)
2540 struct object_id commit_oid
;
2541 char *end_of_object_name
;
2542 int i
, saved
, status
, padding
;
2547 bol
+= strspn(bol
, " \t");
2549 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2550 item
->command
= TODO_COMMENT
;
2551 item
->commit
= NULL
;
2552 item
->arg_offset
= bol
- buf
;
2553 item
->arg_len
= eol
- bol
;
2557 for (i
= 0; i
< TODO_COMMENT
; i
++)
2558 if (is_command(i
, &bol
)) {
2562 if (i
>= TODO_COMMENT
)
2563 return error(_("invalid command '%.*s'"),
2564 (int)strcspn(bol
, " \t\r\n"), bol
);
2566 /* Eat up extra spaces/ tabs before object name */
2567 padding
= strspn(bol
, " \t");
2570 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2572 return error(_("%s does not accept arguments: '%s'"),
2573 command_to_string(item
->command
), bol
);
2574 item
->commit
= NULL
;
2575 item
->arg_offset
= bol
- buf
;
2576 item
->arg_len
= eol
- bol
;
2581 return error(_("missing arguments for %s"),
2582 command_to_string(item
->command
));
2584 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2585 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2588 item
->commit
= NULL
;
2589 item
->arg_offset
= bol
- buf
;
2590 item
->arg_len
= (int)(eol
- bol
);
2591 if (item
->command
== TODO_LABEL
||
2592 item
->command
== TODO_UPDATE_REF
) {
2595 ret
= check_label_or_ref_arg(item
->command
, bol
);
2601 if (item
->command
== TODO_FIXUP
) {
2602 if (skip_prefix(bol
, "-C", &bol
)) {
2603 bol
+= strspn(bol
, " \t");
2604 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2605 } else if (skip_prefix(bol
, "-c", &bol
)) {
2606 bol
+= strspn(bol
, " \t");
2607 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2611 if (item
->command
== TODO_MERGE
) {
2612 if (skip_prefix(bol
, "-C", &bol
))
2613 bol
+= strspn(bol
, " \t");
2614 else if (skip_prefix(bol
, "-c", &bol
)) {
2615 bol
+= strspn(bol
, " \t");
2616 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2618 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2619 item
->commit
= NULL
;
2620 item
->arg_offset
= bol
- buf
;
2621 item
->arg_len
= (int)(eol
- bol
);
2626 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2627 saved
= *end_of_object_name
;
2628 *end_of_object_name
= '\0';
2629 status
= repo_get_oid(r
, bol
, &commit_oid
);
2631 error(_("could not parse '%s'"), bol
); /* return later */
2632 *end_of_object_name
= saved
;
2634 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2635 item
->arg_offset
= bol
- buf
;
2636 item
->arg_len
= (int)(eol
- bol
);
2641 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2642 return item
->commit
? 0 : -1;
2645 int sequencer_get_last_command(struct repository
*r
, enum replay_action
*action
)
2647 const char *todo_file
, *bol
;
2648 struct strbuf buf
= STRBUF_INIT
;
2651 todo_file
= git_path_todo_file();
2652 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2653 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2656 return error_errno("unable to open '%s'", todo_file
);
2658 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2659 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2660 *action
= REPLAY_PICK
;
2661 else if (is_command(TODO_REVERT
, &bol
) &&
2662 (*bol
== ' ' || *bol
== '\t'))
2663 *action
= REPLAY_REVERT
;
2667 strbuf_release(&buf
);
2672 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2673 struct todo_list
*todo_list
)
2675 struct todo_item
*item
;
2676 char *p
= buf
, *next_p
;
2677 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2679 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2681 for (i
= 1; *p
; i
++, p
= next_p
) {
2682 char *eol
= strchrnul(p
, '\n');
2684 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2686 if (p
!= eol
&& eol
[-1] == '\r')
2687 eol
--; /* strip Carriage Return */
2689 item
= append_new_todo(todo_list
);
2690 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2691 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2692 res
= error(_("invalid line %d: %.*s"),
2693 i
, (int)(eol
- p
), p
);
2694 item
->command
= TODO_COMMENT
+ 1;
2695 item
->arg_offset
= p
- buf
;
2696 item
->arg_len
= (int)(eol
- p
);
2697 item
->commit
= NULL
;
2700 if (item
->command
!= TODO_COMMENT
)
2701 todo_list
->total_nr
++;
2705 else if (is_fixup(item
->command
))
2706 return error(_("cannot '%s' without a previous commit"),
2707 command_to_string(item
->command
));
2708 else if (!is_noop(item
->command
))
2715 static int count_commands(struct todo_list
*todo_list
)
2719 for (i
= 0; i
< todo_list
->nr
; i
++)
2720 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2726 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2728 return index
< todo_list
->nr
?
2729 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2732 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2734 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2737 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2739 return get_item_line_offset(todo_list
, index
+ 1)
2740 - get_item_line_offset(todo_list
, index
);
2743 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2748 fd
= open(path
, O_RDONLY
);
2750 return error_errno(_("could not open '%s'"), path
);
2751 len
= strbuf_read(sb
, fd
, 0);
2754 return error(_("could not read '%s'."), path
);
2758 static int have_finished_the_last_pick(void)
2760 struct strbuf buf
= STRBUF_INIT
;
2762 const char *todo_path
= git_path_todo_file();
2765 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2766 if (errno
== ENOENT
) {
2769 error_errno("unable to open '%s'", todo_path
);
2773 /* If there is only one line then we are done */
2774 eol
= strchr(buf
.buf
, '\n');
2775 if (!eol
|| !eol
[1])
2778 strbuf_release(&buf
);
2783 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2785 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2786 int need_cleanup
= 0;
2788 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2789 if (!refs_delete_ref(get_main_ref_store(r
), "",
2790 "CHERRY_PICK_HEAD", NULL
, 0) &&
2792 warning(_("cancelling a cherry picking in progress"));
2793 opts
.action
= REPLAY_PICK
;
2797 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2798 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2801 warning(_("cancelling a revert in progress"));
2802 opts
.action
= REPLAY_REVERT
;
2806 unlink(git_path_auto_merge(r
));
2811 if (!have_finished_the_last_pick())
2814 sequencer_remove_state(&opts
);
2817 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2819 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2822 fprintf(f
, "%d\n", todo_list
->total_nr
);
2827 static int read_populate_todo(struct repository
*r
,
2828 struct todo_list
*todo_list
,
2829 struct replay_opts
*opts
)
2831 const char *todo_file
= get_todo_path(opts
);
2834 strbuf_reset(&todo_list
->buf
);
2835 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2838 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2840 if (is_rebase_i(opts
))
2841 return error(_("please fix this using "
2842 "'git rebase --edit-todo'."));
2843 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2846 if (!todo_list
->nr
&&
2847 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2848 return error(_("no commits parsed."));
2850 if (!is_rebase_i(opts
)) {
2851 enum todo_command valid
=
2852 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2855 for (i
= 0; i
< todo_list
->nr
; i
++)
2856 if (valid
== todo_list
->items
[i
].command
)
2858 else if (valid
== TODO_PICK
)
2859 return error(_("cannot cherry-pick during a revert."));
2861 return error(_("cannot revert during a cherry-pick."));
2864 if (is_rebase_i(opts
)) {
2865 struct todo_list done
= TODO_LIST_INIT
;
2867 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2868 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2869 todo_list
->done_nr
= count_commands(&done
);
2871 todo_list
->done_nr
= 0;
2873 todo_list
->total_nr
= todo_list
->done_nr
2874 + count_commands(todo_list
);
2875 todo_list_release(&done
);
2877 todo_list_write_total_nr(todo_list
);
2883 static int git_config_string_dup(char **dest
,
2884 const char *var
, const char *value
)
2887 return config_error_nonbool(var
);
2889 *dest
= xstrdup(value
);
2893 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
2895 struct replay_opts
*opts
= data
;
2900 else if (!strcmp(key
, "options.no-commit"))
2901 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
2902 else if (!strcmp(key
, "options.edit"))
2903 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
2904 else if (!strcmp(key
, "options.allow-empty"))
2906 git_config_bool_or_int(key
, value
, &error_flag
);
2907 else if (!strcmp(key
, "options.allow-empty-message"))
2908 opts
->allow_empty_message
=
2909 git_config_bool_or_int(key
, value
, &error_flag
);
2910 else if (!strcmp(key
, "options.keep-redundant-commits"))
2911 opts
->keep_redundant_commits
=
2912 git_config_bool_or_int(key
, value
, &error_flag
);
2913 else if (!strcmp(key
, "options.signoff"))
2914 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
2915 else if (!strcmp(key
, "options.record-origin"))
2916 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
2917 else if (!strcmp(key
, "options.allow-ff"))
2918 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
2919 else if (!strcmp(key
, "options.mainline"))
2920 opts
->mainline
= git_config_int(key
, value
);
2921 else if (!strcmp(key
, "options.strategy"))
2922 git_config_string_dup(&opts
->strategy
, key
, value
);
2923 else if (!strcmp(key
, "options.gpg-sign"))
2924 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2925 else if (!strcmp(key
, "options.strategy-option")) {
2926 strvec_push(&opts
->xopts
, value
);
2927 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2928 opts
->allow_rerere_auto
=
2929 git_config_bool_or_int(key
, value
, &error_flag
) ?
2930 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2931 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2932 opts
->explicit_cleanup
= 1;
2933 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2935 return error(_("invalid key: %s"), key
);
2938 return error(_("invalid value for '%s': '%s'"), key
, value
);
2943 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2948 char *strategy_opts_string
= raw_opts
;
2950 if (*strategy_opts_string
== ' ')
2951 strategy_opts_string
++;
2953 count
= split_cmdline(strategy_opts_string
, &argv
);
2955 BUG("could not split '%s': %s", strategy_opts_string
,
2956 split_cmdline_strerror(count
));
2957 for (i
= 0; i
< count
; i
++) {
2958 const char *arg
= argv
[i
];
2960 skip_prefix(arg
, "--", &arg
);
2961 strvec_push(&opts
->xopts
, arg
);
2966 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2969 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2971 opts
->strategy
= strbuf_detach(buf
, NULL
);
2972 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2975 parse_strategy_opts(opts
, buf
->buf
);
2978 static int read_populate_opts(struct replay_opts
*opts
)
2980 if (is_rebase_i(opts
)) {
2981 struct strbuf buf
= STRBUF_INIT
;
2984 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
2985 READ_ONELINER_SKIP_IF_EMPTY
)) {
2986 if (!starts_with(buf
.buf
, "-S"))
2989 free(opts
->gpg_sign
);
2990 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
2995 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
2996 READ_ONELINER_SKIP_IF_EMPTY
)) {
2997 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
2998 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
2999 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3000 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3004 if (file_exists(rebase_path_verbose()))
3007 if (file_exists(rebase_path_quiet()))
3010 if (file_exists(rebase_path_signoff())) {
3015 if (file_exists(rebase_path_cdate_is_adate())) {
3017 opts
->committer_date_is_author_date
= 1;
3020 if (file_exists(rebase_path_ignore_date())) {
3022 opts
->ignore_date
= 1;
3025 if (file_exists(rebase_path_reschedule_failed_exec()))
3026 opts
->reschedule_failed_exec
= 1;
3027 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3028 opts
->reschedule_failed_exec
= 0;
3030 if (file_exists(rebase_path_drop_redundant_commits()))
3031 opts
->drop_redundant_commits
= 1;
3033 if (file_exists(rebase_path_keep_redundant_commits()))
3034 opts
->keep_redundant_commits
= 1;
3036 read_strategy_opts(opts
, &buf
);
3039 if (read_oneliner(&opts
->current_fixups
,
3040 rebase_path_current_fixups(),
3041 READ_ONELINER_SKIP_IF_EMPTY
)) {
3042 const char *p
= opts
->current_fixups
.buf
;
3043 opts
->current_fixup_count
= 1;
3044 while ((p
= strchr(p
, '\n'))) {
3045 opts
->current_fixup_count
++;
3050 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3051 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3052 ret
= error(_("unusable squash-onto"));
3055 opts
->have_squash_onto
= 1;
3059 strbuf_release(&buf
);
3063 if (!file_exists(git_path_opts_file()))
3066 * The function git_parse_source(), called from git_config_from_file(),
3067 * may die() in case of a syntactically incorrect file. We do not care
3068 * about this case, though, because we wrote that file ourselves, so we
3069 * are pretty certain that it is syntactically correct.
3071 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3072 return error(_("malformed options sheet: '%s'"),
3073 git_path_opts_file());
3077 static void write_strategy_opts(struct replay_opts
*opts
)
3079 struct strbuf buf
= STRBUF_INIT
;
3082 * Quote strategy options so that they can be read correctly
3083 * by split_cmdline().
3085 quote_cmdline(&buf
, opts
->xopts
.v
);
3086 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3087 strbuf_release(&buf
);
3090 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3091 struct commit
*onto
, const struct object_id
*orig_head
)
3094 write_file(rebase_path_head_name(), "%s\n", head_name
);
3096 write_file(rebase_path_onto(), "%s\n",
3097 oid_to_hex(&onto
->object
.oid
));
3099 write_file(rebase_path_orig_head(), "%s\n",
3100 oid_to_hex(orig_head
));
3103 write_file(rebase_path_quiet(), "%s", "");
3105 write_file(rebase_path_verbose(), "%s", "");
3107 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3108 if (opts
->xopts
.nr
> 0)
3109 write_strategy_opts(opts
);
3111 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3112 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3113 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3114 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3117 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3119 write_file(rebase_path_signoff(), "--signoff\n");
3120 if (opts
->drop_redundant_commits
)
3121 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3122 if (opts
->keep_redundant_commits
)
3123 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3124 if (opts
->committer_date_is_author_date
)
3125 write_file(rebase_path_cdate_is_adate(), "%s", "");
3126 if (opts
->ignore_date
)
3127 write_file(rebase_path_ignore_date(), "%s", "");
3128 if (opts
->reschedule_failed_exec
)
3129 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3131 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3136 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3137 struct replay_opts
*opts
)
3139 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3140 TODO_PICK
: TODO_REVERT
;
3141 const char *command_string
= todo_command_info
[command
].str
;
3142 const char *encoding
;
3143 struct commit
*commit
;
3145 if (prepare_revs(opts
))
3148 encoding
= get_log_output_encoding();
3150 while ((commit
= get_revision(opts
->revs
))) {
3151 struct todo_item
*item
= append_new_todo(todo_list
);
3152 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3155 const char *subject
;
3158 item
->command
= command
;
3159 item
->commit
= commit
;
3160 item
->arg_offset
= 0;
3162 item
->offset_in_buf
= todo_list
->buf
.len
;
3163 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3164 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3165 short_commit_name(commit
), subject_len
, subject
);
3166 repo_unuse_commit_buffer(the_repository
, commit
,
3171 return error(_("empty commit set passed"));
3176 static int create_seq_dir(struct repository
*r
)
3178 enum replay_action action
;
3179 const char *in_progress_error
= NULL
;
3180 const char *in_progress_advice
= NULL
;
3181 unsigned int advise_skip
=
3182 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3183 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3185 if (!sequencer_get_last_command(r
, &action
)) {
3188 in_progress_error
= _("revert is already in progress");
3189 in_progress_advice
=
3190 _("try \"git revert (--continue | %s--abort | --quit)\"");
3193 in_progress_error
= _("cherry-pick is already in progress");
3194 in_progress_advice
=
3195 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3198 BUG("unexpected action in create_seq_dir");
3201 if (in_progress_error
) {
3202 error("%s", in_progress_error
);
3203 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3204 advise(in_progress_advice
,
3205 advise_skip
? "--skip | " : "");
3208 if (mkdir(git_path_seq_dir(), 0777) < 0)
3209 return error_errno(_("could not create sequencer directory '%s'"),
3210 git_path_seq_dir());
3215 static int save_head(const char *head
)
3217 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3220 static int rollback_is_safe(void)
3222 struct strbuf sb
= STRBUF_INIT
;
3223 struct object_id expected_head
, actual_head
;
3225 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3227 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3228 strbuf_release(&sb
);
3229 die(_("could not parse %s"), git_path_abort_safety_file());
3231 strbuf_release(&sb
);
3233 else if (errno
== ENOENT
)
3234 oidclr(&expected_head
);
3236 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3238 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3239 oidclr(&actual_head
);
3241 return oideq(&actual_head
, &expected_head
);
3244 static int reset_merge(const struct object_id
*oid
)
3246 struct child_process cmd
= CHILD_PROCESS_INIT
;
3249 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3251 if (!is_null_oid(oid
))
3252 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3254 return run_command(&cmd
);
3257 static int rollback_single_pick(struct repository
*r
)
3259 struct object_id head_oid
;
3261 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3262 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3263 return error(_("no cherry-pick or revert in progress"));
3264 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3265 return error(_("cannot resolve HEAD"));
3266 if (is_null_oid(&head_oid
))
3267 return error(_("cannot abort from a branch yet to be born"));
3268 return reset_merge(&head_oid
);
3271 static int skip_single_pick(void)
3273 struct object_id head
;
3275 if (read_ref_full("HEAD", 0, &head
, NULL
))
3276 return error(_("cannot resolve HEAD"));
3277 return reset_merge(&head
);
3280 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3283 struct object_id oid
;
3284 struct strbuf buf
= STRBUF_INIT
;
3287 f
= fopen(git_path_head_file(), "r");
3288 if (!f
&& errno
== ENOENT
) {
3290 * There is no multiple-cherry-pick in progress.
3291 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3292 * a single-cherry-pick in progress, abort that.
3294 return rollback_single_pick(r
);
3297 return error_errno(_("cannot open '%s'"), git_path_head_file());
3298 if (strbuf_getline_lf(&buf
, f
)) {
3299 error(_("cannot read '%s': %s"), git_path_head_file(),
3300 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3305 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3306 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3307 git_path_head_file());
3310 if (is_null_oid(&oid
)) {
3311 error(_("cannot abort from a branch yet to be born"));
3315 if (!rollback_is_safe()) {
3316 /* Do not error, just do not rollback */
3317 warning(_("You seem to have moved HEAD. "
3318 "Not rewinding, check your HEAD!"));
3320 if (reset_merge(&oid
))
3322 strbuf_release(&buf
);
3323 return sequencer_remove_state(opts
);
3325 strbuf_release(&buf
);
3329 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3331 enum replay_action action
= -1;
3332 sequencer_get_last_command(r
, &action
);
3335 * Check whether the subcommand requested to skip the commit is actually
3336 * in progress and that it's safe to skip the commit.
3338 * opts->action tells us which subcommand requested to skip the commit.
3339 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3340 * action is in progress and we can skip the commit.
3342 * Otherwise we check that the last instruction was related to the
3343 * particular subcommand we're trying to execute and barf if that's not
3346 * Finally we check that the rollback is "safe", i.e., has the HEAD
3347 * moved? In this case, it doesn't make sense to "reset the merge" and
3348 * "skip the commit" as the user already handled this by committing. But
3349 * we'd not want to barf here, instead give advice on how to proceed. We
3350 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3351 * it gets removed when the user commits, so if it still exists we're
3352 * sure the user can't have committed before.
3354 switch (opts
->action
) {
3356 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3357 if (action
!= REPLAY_REVERT
)
3358 return error(_("no revert in progress"));
3359 if (!rollback_is_safe())
3364 if (!refs_ref_exists(get_main_ref_store(r
),
3365 "CHERRY_PICK_HEAD")) {
3366 if (action
!= REPLAY_PICK
)
3367 return error(_("no cherry-pick in progress"));
3368 if (!rollback_is_safe())
3373 BUG("unexpected action in sequencer_skip");
3376 if (skip_single_pick())
3377 return error(_("failed to skip the commit"));
3378 if (!is_directory(git_path_seq_dir()))
3381 return sequencer_continue(r
, opts
);
3384 error(_("there is nothing to skip"));
3386 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3387 advise(_("have you committed already?\n"
3388 "try \"git %s --continue\""),
3389 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3394 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
3396 struct lock_file todo_lock
= LOCK_INIT
;
3397 const char *todo_path
= get_todo_path(opts
);
3398 int next
= todo_list
->current
, offset
, fd
;
3401 * rebase -i writes "git-rebase-todo" without the currently executing
3402 * command, appending it to "done" instead.
3404 if (is_rebase_i(opts
))
3407 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3409 return error_errno(_("could not lock '%s'"), todo_path
);
3410 offset
= get_item_line_offset(todo_list
, next
);
3411 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3412 todo_list
->buf
.len
- offset
) < 0)
3413 return error_errno(_("could not write to '%s'"), todo_path
);
3414 if (commit_lock_file(&todo_lock
) < 0)
3415 return error(_("failed to finalize '%s'"), todo_path
);
3417 if (is_rebase_i(opts
) && next
> 0) {
3418 const char *done
= rebase_path_done();
3419 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3424 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3425 get_item_line_length(todo_list
, next
- 1))
3427 ret
= error_errno(_("could not write to '%s'"), done
);
3429 ret
= error_errno(_("failed to finalize '%s'"), done
);
3435 static int save_opts(struct replay_opts
*opts
)
3437 const char *opts_file
= git_path_opts_file();
3440 if (opts
->no_commit
)
3441 res
|= git_config_set_in_file_gently(opts_file
,
3442 "options.no-commit", "true");
3443 if (opts
->edit
>= 0)
3444 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3445 opts
->edit
? "true" : "false");
3446 if (opts
->allow_empty
)
3447 res
|= git_config_set_in_file_gently(opts_file
,
3448 "options.allow-empty", "true");
3449 if (opts
->allow_empty_message
)
3450 res
|= git_config_set_in_file_gently(opts_file
,
3451 "options.allow-empty-message", "true");
3452 if (opts
->keep_redundant_commits
)
3453 res
|= git_config_set_in_file_gently(opts_file
,
3454 "options.keep-redundant-commits", "true");
3456 res
|= git_config_set_in_file_gently(opts_file
,
3457 "options.signoff", "true");
3458 if (opts
->record_origin
)
3459 res
|= git_config_set_in_file_gently(opts_file
,
3460 "options.record-origin", "true");
3462 res
|= git_config_set_in_file_gently(opts_file
,
3463 "options.allow-ff", "true");
3464 if (opts
->mainline
) {
3465 struct strbuf buf
= STRBUF_INIT
;
3466 strbuf_addf(&buf
, "%d", opts
->mainline
);
3467 res
|= git_config_set_in_file_gently(opts_file
,
3468 "options.mainline", buf
.buf
);
3469 strbuf_release(&buf
);
3472 res
|= git_config_set_in_file_gently(opts_file
,
3473 "options.strategy", opts
->strategy
);
3475 res
|= git_config_set_in_file_gently(opts_file
,
3476 "options.gpg-sign", opts
->gpg_sign
);
3477 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3478 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3479 "options.strategy-option",
3480 opts
->xopts
.v
[i
], "^$", 0);
3481 if (opts
->allow_rerere_auto
)
3482 res
|= git_config_set_in_file_gently(opts_file
,
3483 "options.allow-rerere-auto",
3484 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3487 if (opts
->explicit_cleanup
)
3488 res
|= git_config_set_in_file_gently(opts_file
,
3489 "options.default-msg-cleanup",
3490 describe_cleanup_mode(opts
->default_msg_cleanup
));
3494 static int make_patch(struct repository
*r
,
3495 struct commit
*commit
,
3496 struct replay_opts
*opts
)
3498 struct strbuf buf
= STRBUF_INIT
;
3499 struct rev_info log_tree_opt
;
3500 const char *subject
;
3501 char hex
[GIT_MAX_HEXSZ
+ 1];
3504 oid_to_hex_r(hex
, &commit
->object
.oid
);
3505 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3507 res
|= write_rebase_head(&commit
->object
.oid
);
3509 strbuf_addf(&buf
, "%s/patch", get_dir(opts
));
3510 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3511 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3512 log_tree_opt
.abbrev
= 0;
3513 log_tree_opt
.diff
= 1;
3514 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3515 log_tree_opt
.disable_stdin
= 1;
3516 log_tree_opt
.no_commit_id
= 1;
3517 log_tree_opt
.diffopt
.file
= fopen(buf
.buf
, "w");
3518 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3519 if (!log_tree_opt
.diffopt
.file
)
3520 res
|= error_errno(_("could not open '%s'"), buf
.buf
);
3522 res
|= log_tree_commit(&log_tree_opt
, commit
);
3523 fclose(log_tree_opt
.diffopt
.file
);
3527 strbuf_addf(&buf
, "%s/message", get_dir(opts
));
3528 if (!file_exists(buf
.buf
)) {
3529 const char *encoding
= get_commit_output_encoding();
3530 const char *commit_buffer
= repo_logmsg_reencode(r
,
3533 find_commit_subject(commit_buffer
, &subject
);
3534 res
|= write_message(subject
, strlen(subject
), buf
.buf
, 1);
3535 repo_unuse_commit_buffer(r
, commit
,
3538 strbuf_release(&buf
);
3539 release_revisions(&log_tree_opt
);
3544 static int intend_to_amend(void)
3546 struct object_id head
;
3549 if (repo_get_oid(the_repository
, "HEAD", &head
))
3550 return error(_("cannot read HEAD"));
3552 p
= oid_to_hex(&head
);
3553 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3556 static int error_with_patch(struct repository
*r
,
3557 struct commit
*commit
,
3558 const char *subject
, int subject_len
,
3559 struct replay_opts
*opts
,
3560 int exit_code
, int to_amend
)
3563 if (make_patch(r
, commit
, opts
))
3565 } else if (copy_file(rebase_path_message(),
3566 git_path_merge_msg(r
), 0666))
3567 return error(_("unable to copy '%s' to '%s'"),
3568 git_path_merge_msg(r
), rebase_path_message());
3571 if (intend_to_amend())
3575 _("You can amend the commit now, with\n"
3577 " git commit --amend %s\n"
3579 "Once you are satisfied with your changes, run\n"
3581 " git rebase --continue\n"),
3582 gpg_sign_opt_quoted(opts
));
3583 } else if (exit_code
) {
3585 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3586 short_commit_name(commit
), subject_len
, subject
);
3589 * We don't have the hash of the parent so
3590 * just print the line from the todo file.
3592 fprintf_ln(stderr
, _("Could not merge %.*s"),
3593 subject_len
, subject
);
3599 static int error_failed_squash(struct repository
*r
,
3600 struct commit
*commit
,
3601 struct replay_opts
*opts
,
3603 const char *subject
)
3605 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3606 return error(_("could not copy '%s' to '%s'"),
3607 rebase_path_squash_msg(), rebase_path_message());
3608 unlink(git_path_merge_msg(r
));
3609 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3610 return error(_("could not copy '%s' to '%s'"),
3611 rebase_path_message(),
3612 git_path_merge_msg(r
));
3613 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3616 static int do_exec(struct repository
*r
, const char *command_line
)
3618 struct child_process cmd
= CHILD_PROCESS_INIT
;
3621 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3623 strvec_push(&cmd
.args
, command_line
);
3624 status
= run_command(&cmd
);
3626 /* force re-reading of the cache */
3627 discard_index(r
->index
);
3628 if (repo_read_index(r
) < 0)
3629 return error(_("could not read index"));
3631 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3634 warning(_("execution failed: %s\n%s"
3635 "You can fix the problem, and then run\n"
3637 " git rebase --continue\n"
3640 dirty
? _("and made changes to the index and/or the "
3641 "working tree.\n") : "");
3643 /* command not found */
3646 warning(_("execution succeeded: %s\nbut "
3647 "left changes to the index and/or the working tree.\n"
3648 "Commit or stash your changes, and then run\n"
3650 " git rebase --continue\n"
3651 "\n"), command_line
);
3658 __attribute__((format (printf
, 2, 3)))
3659 static int safe_append(const char *filename
, const char *fmt
, ...)
3662 struct lock_file lock
= LOCK_INIT
;
3663 int fd
= hold_lock_file_for_update(&lock
, filename
,
3664 LOCK_REPORT_ON_ERROR
);
3665 struct strbuf buf
= STRBUF_INIT
;
3670 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3671 error_errno(_("could not read '%s'"), filename
);
3672 rollback_lock_file(&lock
);
3675 strbuf_complete(&buf
, '\n');
3677 strbuf_vaddf(&buf
, fmt
, ap
);
3680 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3681 error_errno(_("could not write to '%s'"), filename
);
3682 strbuf_release(&buf
);
3683 rollback_lock_file(&lock
);
3686 if (commit_lock_file(&lock
) < 0) {
3687 strbuf_release(&buf
);
3688 return error(_("failed to finalize '%s'"), filename
);
3691 strbuf_release(&buf
);
3695 static int do_label(struct repository
*r
, const char *name
, int len
)
3697 struct ref_store
*refs
= get_main_ref_store(r
);
3698 struct ref_transaction
*transaction
;
3699 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3700 struct strbuf msg
= STRBUF_INIT
;
3702 struct object_id head_oid
;
3704 if (len
== 1 && *name
== '#')
3705 return error(_("illegal label name: '%.*s'"), len
, name
);
3707 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3708 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3710 transaction
= ref_store_transaction_begin(refs
, &err
);
3712 error("%s", err
.buf
);
3714 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3715 error(_("could not read HEAD"));
3717 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3718 NULL
, 0, msg
.buf
, &err
) < 0 ||
3719 ref_transaction_commit(transaction
, &err
)) {
3720 error("%s", err
.buf
);
3723 ref_transaction_free(transaction
);
3724 strbuf_release(&err
);
3725 strbuf_release(&msg
);
3728 ret
= safe_append(rebase_path_refs_to_delete(),
3729 "%s\n", ref_name
.buf
);
3730 strbuf_release(&ref_name
);
3735 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3737 if (!opts
->reflog_action
) {
3738 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3739 opts
->reflog_action
=
3740 xstrdup(opts
->reflog_action
? opts
->reflog_action
3741 : action_name(opts
));
3744 return opts
->reflog_action
;
3747 __attribute__((format (printf
, 3, 4)))
3748 static const char *reflog_message(struct replay_opts
*opts
,
3749 const char *sub_action
, const char *fmt
, ...)
3752 static struct strbuf buf
= STRBUF_INIT
;
3756 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3758 strbuf_addf(&buf
, " (%s)", sub_action
);
3760 strbuf_addstr(&buf
, ": ");
3761 strbuf_vaddf(&buf
, fmt
, ap
);
3768 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3769 int len
, struct strbuf
*buf
)
3771 struct commit
*commit
;
3772 struct object_id oid
;
3775 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3776 if (!read_ref(buf
->buf
, &oid
)) {
3777 commit
= lookup_commit_object(r
, &oid
);
3779 /* fall back to non-rewritten ref or commit */
3780 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3781 commit
= lookup_commit_reference_by_name(buf
->buf
);
3785 error(_("could not resolve '%s'"), buf
->buf
);
3790 static int do_reset(struct repository
*r
,
3791 const char *name
, int len
,
3792 struct replay_opts
*opts
)
3794 struct strbuf ref_name
= STRBUF_INIT
;
3795 struct object_id oid
;
3796 struct lock_file lock
= LOCK_INIT
;
3797 struct tree_desc desc
= { 0 };
3799 struct unpack_trees_options unpack_tree_opts
= { 0 };
3802 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3805 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3806 if (!opts
->have_squash_onto
) {
3808 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3809 NULL
, &opts
->squash_onto
,
3811 return error(_("writing fake root commit"));
3812 opts
->have_squash_onto
= 1;
3813 hex
= oid_to_hex(&opts
->squash_onto
);
3814 if (write_message(hex
, strlen(hex
),
3815 rebase_path_squash_onto(), 0))
3816 return error(_("writing squash-onto"));
3818 oidcpy(&oid
, &opts
->squash_onto
);
3821 struct commit
*commit
;
3823 /* Determine the length of the label */
3824 for (i
= 0; i
< len
; i
++)
3825 if (isspace(name
[i
]))
3829 commit
= lookup_label(r
, name
, len
, &ref_name
);
3834 oid
= commit
->object
.oid
;
3837 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3838 unpack_tree_opts
.head_idx
= 1;
3839 unpack_tree_opts
.src_index
= r
->index
;
3840 unpack_tree_opts
.dst_index
= r
->index
;
3841 unpack_tree_opts
.fn
= oneway_merge
;
3842 unpack_tree_opts
.merge
= 1;
3843 unpack_tree_opts
.update
= 1;
3844 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3845 unpack_tree_opts
.skip_cache_tree_update
= 1;
3846 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3848 if (repo_read_index_unmerged(r
)) {
3849 ret
= error_resolve_conflict(action_name(opts
));
3853 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3854 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3858 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3863 tree
= parse_tree_indirect(&oid
);
3864 prime_cache_tree(r
, r
->index
, tree
);
3866 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3867 ret
= error(_("could not write index"));
3870 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3871 len
, name
), "HEAD", &oid
,
3872 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3874 free((void *)desc
.buffer
);
3876 rollback_lock_file(&lock
);
3877 strbuf_release(&ref_name
);
3878 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3882 static int do_merge(struct repository
*r
,
3883 struct commit
*commit
,
3884 const char *arg
, int arg_len
,
3885 int flags
, int *check_todo
, struct replay_opts
*opts
)
3887 int run_commit_flags
= 0;
3888 struct strbuf ref_name
= STRBUF_INIT
;
3889 struct commit
*head_commit
, *merge_commit
, *i
;
3890 struct commit_list
*bases
, *j
;
3891 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3892 const char *strategy
= !opts
->xopts
.nr
&&
3894 !strcmp(opts
->strategy
, "recursive") ||
3895 !strcmp(opts
->strategy
, "ort")) ?
3896 NULL
: opts
->strategy
;
3897 struct merge_options o
;
3898 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3899 static struct lock_file lock
;
3902 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3907 head_commit
= lookup_commit_reference_by_name("HEAD");
3909 ret
= error(_("cannot merge without a current revision"));
3914 * For octopus merges, the arg starts with the list of revisions to be
3915 * merged. The list is optionally followed by '#' and the oneline.
3917 merge_arg_len
= oneline_offset
= arg_len
;
3918 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3921 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3922 p
+= 1 + strspn(p
+ 1, " \t\n");
3923 oneline_offset
= p
- arg
;
3926 k
= strcspn(p
, " \t\n");
3929 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3930 if (!merge_commit
) {
3931 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3934 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3936 merge_arg_len
= p
- arg
;
3940 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3944 if (opts
->have_squash_onto
&&
3945 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3947 * When the user tells us to "merge" something into a
3948 * "[new root]", let's simply fast-forward to the merge head.
3950 rollback_lock_file(&lock
);
3952 ret
= error(_("octopus merge cannot be executed on "
3953 "top of a [new root]"));
3955 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3956 &head_commit
->object
.oid
, 0,
3962 * If HEAD is not identical to the first parent of the original merge
3963 * commit, we cannot fast-forward.
3965 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3966 oideq(&commit
->parents
->item
->object
.oid
,
3967 &head_commit
->object
.oid
);
3970 * If any merge head is different from the original one, we cannot
3973 if (can_fast_forward
) {
3974 struct commit_list
*p
= commit
->parents
->next
;
3976 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
3977 if (!oideq(&j
->item
->object
.oid
,
3978 &p
->item
->object
.oid
)) {
3979 can_fast_forward
= 0;
3983 * If the number of merge heads differs from the original merge
3984 * commit, we cannot fast-forward.
3987 can_fast_forward
= 0;
3990 if (can_fast_forward
) {
3991 rollback_lock_file(&lock
);
3992 ret
= fast_forward_to(r
, &commit
->object
.oid
,
3993 &head_commit
->object
.oid
, 0, opts
);
3994 if (flags
& TODO_EDIT_MERGE_MSG
)
3995 goto fast_forward_edit
;
4001 const char *encoding
= get_commit_output_encoding();
4002 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4008 ret
= error(_("could not get commit message of '%s'"),
4009 oid_to_hex(&commit
->object
.oid
));
4012 write_author_script(message
);
4013 find_commit_subject(message
, &body
);
4015 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4016 repo_unuse_commit_buffer(r
, commit
, message
);
4018 error_errno(_("could not write '%s'"),
4019 git_path_merge_msg(r
));
4023 struct strbuf buf
= STRBUF_INIT
;
4026 strbuf_addf(&buf
, "author %s", git_author_info(0));
4027 write_author_script(buf
.buf
);
4030 if (oneline_offset
< arg_len
) {
4031 p
= arg
+ oneline_offset
;
4032 len
= arg_len
- oneline_offset
;
4034 strbuf_addf(&buf
, "Merge %s '%.*s'",
4035 to_merge
->next
? "branches" : "branch",
4036 merge_arg_len
, arg
);
4041 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4042 strbuf_release(&buf
);
4044 error_errno(_("could not write '%s'"),
4045 git_path_merge_msg(r
));
4050 if (strategy
|| to_merge
->next
) {
4052 struct child_process cmd
= CHILD_PROCESS_INIT
;
4054 if (read_env_script(&cmd
.env
)) {
4055 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4057 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4061 if (opts
->committer_date_is_author_date
)
4062 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4065 author_date_from_env(&cmd
.env
));
4066 if (opts
->ignore_date
)
4067 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4070 strvec_push(&cmd
.args
, "merge");
4071 strvec_push(&cmd
.args
, "-s");
4073 strvec_push(&cmd
.args
, "octopus");
4075 strvec_push(&cmd
.args
, strategy
);
4076 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4077 strvec_pushf(&cmd
.args
,
4078 "-X%s", opts
->xopts
.v
[k
]);
4080 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4081 strvec_push(&cmd
.args
, "--no-edit");
4083 strvec_push(&cmd
.args
, "--edit");
4084 strvec_push(&cmd
.args
, "--no-ff");
4085 strvec_push(&cmd
.args
, "--no-log");
4086 strvec_push(&cmd
.args
, "--no-stat");
4087 strvec_push(&cmd
.args
, "-F");
4088 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4090 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4092 strvec_push(&cmd
.args
, "--no-gpg-sign");
4094 /* Add the tips to be merged */
4095 for (j
= to_merge
; j
; j
= j
->next
)
4096 strvec_push(&cmd
.args
,
4097 oid_to_hex(&j
->item
->object
.oid
));
4099 strbuf_release(&ref_name
);
4100 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4102 rollback_lock_file(&lock
);
4104 ret
= run_command(&cmd
);
4106 /* force re-reading of the cache */
4108 discard_index(r
->index
);
4109 if (repo_read_index(r
) < 0)
4110 ret
= error(_("could not read index"));
4115 merge_commit
= to_merge
->item
;
4116 bases
= repo_get_merge_bases(r
, head_commit
, merge_commit
);
4117 if (bases
&& oideq(&merge_commit
->object
.oid
,
4118 &bases
->item
->object
.oid
)) {
4120 /* skip merging an ancestor of HEAD */
4124 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4125 git_path_merge_head(r
), 0);
4126 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4128 bases
= reverse_commit_list(bases
);
4131 init_merge_options(&o
, r
);
4133 o
.branch2
= ref_name
.buf
;
4134 o
.buffer_output
= 2;
4136 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4138 * TODO: Should use merge_incore_recursive() and
4139 * merge_switch_to_result(), skipping the call to
4140 * merge_switch_to_result() when we don't actually need to
4141 * update the index and working copy immediately.
4143 ret
= merge_ort_recursive(&o
,
4144 head_commit
, merge_commit
, bases
,
4147 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4151 fputs(o
.obuf
.buf
, stdout
);
4152 strbuf_release(&o
.obuf
);
4154 error(_("could not even attempt to merge '%.*s'"),
4155 merge_arg_len
, arg
);
4159 * The return value of merge_recursive() is 1 on clean, and 0 on
4162 * Let's reverse that, so that do_merge() returns 0 upon success and
4163 * 1 upon failed merge (keeping the return value -1 for the cases where
4164 * we will want to reschedule the `merge` command).
4168 if (r
->index
->cache_changed
&&
4169 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4170 ret
= error(_("merge: Unable to write new index file"));
4174 rollback_lock_file(&lock
);
4176 repo_rerere(r
, opts
->allow_rerere_auto
);
4179 * In case of problems, we now want to return a positive
4180 * value (a negative one would indicate that the `merge`
4181 * command needs to be rescheduled).
4183 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4186 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4189 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4190 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4195 strbuf_release(&ref_name
);
4196 rollback_lock_file(&lock
);
4197 free_commit_list(to_merge
);
4201 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4204 struct lock_file lock
= LOCK_INIT
;
4206 struct string_list_item
*item
;
4209 path
= rebase_path_update_refs(the_repository
->gitdir
);
4211 if (!refs_to_oids
->nr
) {
4212 if (unlink(path
) && errno
!= ENOENT
)
4213 result
= error_errno(_("could not unlink: %s"), path
);
4217 if (safe_create_leading_directories(path
)) {
4218 result
= error(_("unable to create leading directories of %s"),
4223 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4224 result
= error(_("another 'rebase' process appears to be running; "
4225 "'%s.lock' already exists"),
4230 fp
= fdopen_lock_file(&lock
, "w");
4232 result
= error_errno(_("could not open '%s' for writing"), path
);
4233 rollback_lock_file(&lock
);
4237 for_each_string_list_item(item
, refs_to_oids
) {
4238 struct update_ref_record
*rec
= item
->util
;
4239 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4240 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4243 result
= commit_lock_file(&lock
);
4251 * Parse the update-refs file for the current rebase, then remove the
4252 * refs that do not appear in the todo_list (and have not had updated
4253 * values stored) and add refs that are in the todo_list but not
4254 * represented in the update-refs file.
4256 * If there are changes to the update-refs list, then write the new state
4259 void todo_list_filter_update_refs(struct repository
*r
,
4260 struct todo_list
*todo_list
)
4264 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4266 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4269 * For each item in the update_refs list, if it has no updated
4270 * value and does not appear in the todo_list, then remove it
4271 * from the update_refs list.
4273 for (i
= 0; i
< update_refs
.nr
; i
++) {
4276 const char *ref
= update_refs
.items
[i
].string
;
4277 size_t reflen
= strlen(ref
);
4278 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4280 /* OID already stored as updated. */
4281 if (!is_null_oid(&rec
->after
))
4284 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4285 struct todo_item
*item
= &todo_list
->items
[j
];
4286 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4288 if (item
->command
!= TODO_UPDATE_REF
)
4291 if (item
->arg_len
!= reflen
||
4292 strncmp(arg
, ref
, reflen
))
4299 free(update_refs
.items
[i
].string
);
4300 free(update_refs
.items
[i
].util
);
4303 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4311 * For each todo_item, check if its ref is in the update_refs list.
4312 * If not, then add it as an un-updated ref.
4314 for (i
= 0; i
< todo_list
->nr
; i
++) {
4315 struct todo_item
*item
= &todo_list
->items
[i
];
4316 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4319 if (item
->command
!= TODO_UPDATE_REF
)
4322 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4323 const char *ref
= update_refs
.items
[j
].string
;
4325 found
= strlen(ref
) == item
->arg_len
&&
4326 !strncmp(ref
, arg
, item
->arg_len
);
4330 struct string_list_item
*inserted
;
4331 struct strbuf argref
= STRBUF_INIT
;
4333 strbuf_add(&argref
, arg
, item
->arg_len
);
4334 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4335 inserted
->util
= init_update_ref_record(argref
.buf
);
4336 strbuf_release(&argref
);
4342 write_update_refs_state(&update_refs
);
4343 string_list_clear(&update_refs
, 1);
4346 static int do_update_ref(struct repository
*r
, const char *refname
)
4348 struct string_list_item
*item
;
4349 struct string_list list
= STRING_LIST_INIT_DUP
;
4351 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4354 for_each_string_list_item(item
, &list
) {
4355 if (!strcmp(item
->string
, refname
)) {
4356 struct update_ref_record
*rec
= item
->util
;
4357 if (read_ref("HEAD", &rec
->after
))
4363 write_update_refs_state(&list
);
4364 string_list_clear(&list
, 1);
4368 static int do_update_refs(struct repository
*r
, int quiet
)
4371 struct string_list_item
*item
;
4372 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4373 struct ref_store
*refs
= get_main_ref_store(r
);
4374 struct strbuf update_msg
= STRBUF_INIT
;
4375 struct strbuf error_msg
= STRBUF_INIT
;
4377 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4380 for_each_string_list_item(item
, &refs_to_oids
) {
4381 struct update_ref_record
*rec
= item
->util
;
4384 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4386 &rec
->after
, &rec
->before
,
4387 0, UPDATE_REFS_MSG_ON_ERR
);
4394 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4396 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4400 (update_msg
.len
|| error_msg
.len
)) {
4402 _("Updated the following refs with %s:\n%s"),
4408 _("Failed to update the following refs with %s:\n%s"),
4413 string_list_clear(&refs_to_oids
, 1);
4414 strbuf_release(&update_msg
);
4415 strbuf_release(&error_msg
);
4419 static int is_final_fixup(struct todo_list
*todo_list
)
4421 int i
= todo_list
->current
;
4423 if (!is_fixup(todo_list
->items
[i
].command
))
4426 while (++i
< todo_list
->nr
)
4427 if (is_fixup(todo_list
->items
[i
].command
))
4429 else if (!is_noop(todo_list
->items
[i
].command
))
4434 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4438 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4439 if (!is_noop(todo_list
->items
[i
].command
))
4440 return todo_list
->items
[i
].command
;
4445 void create_autostash(struct repository
*r
, const char *path
)
4447 struct strbuf buf
= STRBUF_INIT
;
4448 struct lock_file lock_file
= LOCK_INIT
;
4451 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4452 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4454 repo_update_index_if_able(r
, &lock_file
);
4455 rollback_lock_file(&lock_file
);
4457 if (has_unstaged_changes(r
, 1) ||
4458 has_uncommitted_changes(r
, 1)) {
4459 struct child_process stash
= CHILD_PROCESS_INIT
;
4460 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4461 struct object_id oid
;
4463 strvec_pushl(&stash
.args
,
4464 "stash", "create", "autostash", NULL
);
4468 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4469 die(_("Cannot autostash"));
4470 strbuf_trim_trailing_newline(&buf
);
4471 if (repo_get_oid(r
, buf
.buf
, &oid
))
4472 die(_("Unexpected stash response: '%s'"),
4475 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4477 if (safe_create_leading_directories_const(path
))
4478 die(_("Could not create directory for '%s'"),
4480 write_file(path
, "%s", oid_to_hex(&oid
));
4481 printf(_("Created autostash: %s\n"), buf
.buf
);
4482 if (reset_head(r
, &ropts
) < 0)
4483 die(_("could not reset --hard"));
4484 discard_index(r
->index
);
4485 if (repo_read_index(r
) < 0)
4486 die(_("could not read index"));
4488 strbuf_release(&buf
);
4491 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4493 struct child_process child
= CHILD_PROCESS_INIT
;
4496 if (attempt_apply
) {
4498 child
.no_stdout
= 1;
4499 child
.no_stderr
= 1;
4500 strvec_push(&child
.args
, "stash");
4501 strvec_push(&child
.args
, "apply");
4502 strvec_push(&child
.args
, stash_oid
);
4503 ret
= run_command(&child
);
4506 if (attempt_apply
&& !ret
)
4507 fprintf(stderr
, _("Applied autostash.\n"));
4509 struct child_process store
= CHILD_PROCESS_INIT
;
4512 strvec_push(&store
.args
, "stash");
4513 strvec_push(&store
.args
, "store");
4514 strvec_push(&store
.args
, "-m");
4515 strvec_push(&store
.args
, "autostash");
4516 strvec_push(&store
.args
, "-q");
4517 strvec_push(&store
.args
, stash_oid
);
4518 if (run_command(&store
))
4519 ret
= error(_("cannot store %s"), stash_oid
);
4523 "Your changes are safe in the stash.\n"
4524 "You can run \"git stash pop\" or"
4525 " \"git stash drop\" at any time.\n"),
4527 _("Applying autostash resulted in conflicts.") :
4528 _("Autostash exists; creating a new stash entry."));
4534 static int apply_save_autostash(const char *path
, int attempt_apply
)
4536 struct strbuf stash_oid
= STRBUF_INIT
;
4539 if (!read_oneliner(&stash_oid
, path
,
4540 READ_ONELINER_SKIP_IF_EMPTY
)) {
4541 strbuf_release(&stash_oid
);
4544 strbuf_trim(&stash_oid
);
4546 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4549 strbuf_release(&stash_oid
);
4553 int save_autostash(const char *path
)
4555 return apply_save_autostash(path
, 0);
4558 int apply_autostash(const char *path
)
4560 return apply_save_autostash(path
, 1);
4563 int apply_autostash_oid(const char *stash_oid
)
4565 return apply_save_autostash_oid(stash_oid
, 1);
4568 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4569 const char *onto_name
, const struct object_id
*onto
,
4570 const struct object_id
*orig_head
)
4572 struct reset_head_opts ropts
= {
4574 .orig_head
= orig_head
,
4575 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4576 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4577 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4579 .default_reflog_action
= sequencer_reflog_action(opts
)
4581 if (reset_head(r
, &ropts
)) {
4582 apply_autostash(rebase_path_autostash());
4583 sequencer_remove_state(opts
);
4584 return error(_("could not detach HEAD"));
4590 static int stopped_at_head(struct repository
*r
)
4592 struct object_id head
;
4593 struct commit
*commit
;
4594 struct commit_message message
;
4596 if (repo_get_oid(r
, "HEAD", &head
) ||
4597 !(commit
= lookup_commit(r
, &head
)) ||
4598 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4599 fprintf(stderr
, _("Stopped at HEAD\n"));
4601 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4602 free_message(commit
, &message
);
4608 static int reread_todo_if_changed(struct repository
*r
,
4609 struct todo_list
*todo_list
,
4610 struct replay_opts
*opts
)
4613 struct strbuf buf
= STRBUF_INIT
;
4615 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4617 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4618 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4619 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4620 /* Reread the todo file if it has changed. */
4621 todo_list_release(todo_list
);
4622 if (read_populate_todo(r
, todo_list
, opts
))
4623 return -1; /* message was printed */
4624 /* `current` will be incremented on return */
4625 todo_list
->current
= -1;
4627 strbuf_release(&buf
);
4632 static const char rescheduled_advice
[] =
4633 N_("Could not execute the todo command\n"
4637 "It has been rescheduled; To edit the command before continuing, please\n"
4638 "edit the todo list first:\n"
4640 " git rebase --edit-todo\n"
4641 " git rebase --continue\n");
4643 static int pick_commits(struct repository
*r
,
4644 struct todo_list
*todo_list
,
4645 struct replay_opts
*opts
)
4647 int res
= 0, reschedule
= 0;
4649 opts
->reflog_message
= sequencer_reflog_action(opts
);
4651 assert(!(opts
->signoff
|| opts
->no_commit
||
4652 opts
->record_origin
|| should_edit(opts
) ||
4653 opts
->committer_date_is_author_date
||
4654 opts
->ignore_date
));
4655 if (read_and_refresh_cache(r
, opts
))
4658 while (todo_list
->current
< todo_list
->nr
) {
4659 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4660 const char *arg
= todo_item_get_arg(todo_list
, item
);
4663 if (save_todo(todo_list
, opts
))
4665 if (is_rebase_i(opts
)) {
4666 if (item
->command
!= TODO_COMMENT
) {
4667 FILE *f
= fopen(rebase_path_msgnum(), "w");
4669 todo_list
->done_nr
++;
4672 fprintf(f
, "%d\n", todo_list
->done_nr
);
4676 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4678 todo_list
->total_nr
,
4679 opts
->verbose
? "\n" : "\r");
4681 unlink(rebase_path_message());
4682 unlink(rebase_path_author_script());
4683 unlink(rebase_path_stopped_sha());
4684 unlink(rebase_path_amend());
4685 unlink(git_path_merge_head(r
));
4686 unlink(git_path_auto_merge(r
));
4687 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
4689 if (item
->command
== TODO_BREAK
) {
4692 return stopped_at_head(r
);
4695 if (item
->command
<= TODO_SQUASH
) {
4696 if (is_rebase_i(opts
))
4697 opts
->reflog_message
= reflog_message(opts
,
4698 command_to_string(item
->command
), NULL
);
4700 res
= do_pick_commit(r
, item
, opts
,
4701 is_final_fixup(todo_list
),
4703 if (is_rebase_i(opts
) && res
< 0) {
4705 advise(_(rescheduled_advice
),
4706 get_item_line_length(todo_list
,
4707 todo_list
->current
),
4708 get_item_line(todo_list
,
4709 todo_list
->current
));
4710 todo_list
->current
--;
4711 if (save_todo(todo_list
, opts
))
4714 if (item
->command
== TODO_EDIT
) {
4715 struct commit
*commit
= item
->commit
;
4720 _("Stopped at %s... %.*s\n"),
4721 short_commit_name(commit
),
4722 item
->arg_len
, arg
);
4724 return error_with_patch(r
, commit
,
4725 arg
, item
->arg_len
, opts
, res
, !res
);
4727 if (is_rebase_i(opts
) && !res
)
4728 record_in_rewritten(&item
->commit
->object
.oid
,
4729 peek_command(todo_list
, 1));
4730 if (res
&& is_fixup(item
->command
)) {
4733 return error_failed_squash(r
, item
->commit
, opts
,
4734 item
->arg_len
, arg
);
4735 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4737 struct object_id oid
;
4740 * If we are rewording and have either
4741 * fast-forwarded already, or are about to
4742 * create a new root commit, we want to amend,
4743 * otherwise we do not.
4745 if (item
->command
== TODO_REWORD
&&
4746 !repo_get_oid(r
, "HEAD", &oid
) &&
4747 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4748 (opts
->have_squash_onto
&&
4749 oideq(&opts
->squash_onto
, &oid
))))
4752 return res
| error_with_patch(r
, item
->commit
,
4753 arg
, item
->arg_len
, opts
,
4756 } else if (item
->command
== TODO_EXEC
) {
4757 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4758 int saved
= *end_of_arg
;
4763 res
= do_exec(r
, arg
);
4764 *end_of_arg
= saved
;
4767 if (opts
->reschedule_failed_exec
)
4771 } else if (item
->command
== TODO_LABEL
) {
4772 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4774 } else if (item
->command
== TODO_RESET
) {
4775 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4777 } else if (item
->command
== TODO_MERGE
) {
4778 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4779 item
->flags
, &check_todo
, opts
)) < 0)
4781 else if (item
->commit
)
4782 record_in_rewritten(&item
->commit
->object
.oid
,
4783 peek_command(todo_list
, 1));
4785 /* failed with merge conflicts */
4786 return error_with_patch(r
, item
->commit
,
4789 } else if (item
->command
== TODO_UPDATE_REF
) {
4790 struct strbuf ref
= STRBUF_INIT
;
4791 strbuf_add(&ref
, arg
, item
->arg_len
);
4792 if ((res
= do_update_ref(r
, ref
.buf
)))
4794 strbuf_release(&ref
);
4795 } else if (!is_noop(item
->command
))
4796 return error(_("unknown command %d"), item
->command
);
4799 advise(_(rescheduled_advice
),
4800 get_item_line_length(todo_list
,
4801 todo_list
->current
),
4802 get_item_line(todo_list
, todo_list
->current
));
4803 todo_list
->current
--;
4804 if (save_todo(todo_list
, opts
))
4807 return error_with_patch(r
,
4811 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4812 reread_todo_if_changed(r
, todo_list
, opts
)) {
4816 todo_list
->current
++;
4821 if (is_rebase_i(opts
)) {
4822 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4825 /* Stopped in the middle, as planned? */
4826 if (todo_list
->current
< todo_list
->nr
)
4829 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4830 starts_with(head_ref
.buf
, "refs/")) {
4832 struct object_id head
, orig
;
4835 if (repo_get_oid(r
, "HEAD", &head
)) {
4836 res
= error(_("cannot read HEAD"));
4838 strbuf_release(&head_ref
);
4839 strbuf_release(&buf
);
4842 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4843 get_oid_hex(buf
.buf
, &orig
)) {
4844 res
= error(_("could not read orig-head"));
4845 goto cleanup_head_ref
;
4848 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4849 res
= error(_("could not read 'onto'"));
4850 goto cleanup_head_ref
;
4852 msg
= reflog_message(opts
, "finish", "%s onto %s",
4853 head_ref
.buf
, buf
.buf
);
4854 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4855 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4856 res
= error(_("could not update %s"),
4858 goto cleanup_head_ref
;
4860 msg
= reflog_message(opts
, "finish", "returning to %s",
4862 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4863 res
= error(_("could not update HEAD to %s"),
4865 goto cleanup_head_ref
;
4870 if (opts
->verbose
) {
4871 struct rev_info log_tree_opt
;
4872 struct object_id orig
, head
;
4874 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4875 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4876 log_tree_opt
.diff
= 1;
4877 log_tree_opt
.diffopt
.output_format
=
4878 DIFF_FORMAT_DIFFSTAT
;
4879 log_tree_opt
.disable_stdin
= 1;
4881 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4882 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4883 !repo_get_oid(r
, "HEAD", &head
)) {
4884 diff_tree_oid(&orig
, &head
, "",
4885 &log_tree_opt
.diffopt
);
4886 log_tree_diff_flush(&log_tree_opt
);
4888 release_revisions(&log_tree_opt
);
4890 flush_rewritten_pending();
4891 if (!stat(rebase_path_rewritten_list(), &st
) &&
4893 struct child_process child
= CHILD_PROCESS_INIT
;
4894 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4896 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4898 strvec_push(&child
.args
, "notes");
4899 strvec_push(&child
.args
, "copy");
4900 strvec_push(&child
.args
, "--for-rewrite=rebase");
4901 /* we don't care if this copying failed */
4902 run_command(&child
);
4904 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4905 strvec_push(&hook_opt
.args
, "rebase");
4906 run_hooks_opt("post-rewrite", &hook_opt
);
4908 apply_autostash(rebase_path_autostash());
4914 _("Successfully rebased and updated %s.\n"),
4918 strbuf_release(&buf
);
4919 strbuf_release(&head_ref
);
4921 if (do_update_refs(r
, opts
->quiet
))
4926 * Sequence of picks finished successfully; cleanup by
4927 * removing the .git/sequencer directory
4929 return sequencer_remove_state(opts
);
4932 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
4934 struct child_process cmd
= CHILD_PROCESS_INIT
;
4936 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
4937 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
4938 return error(_("no cherry-pick or revert in progress"));
4941 strvec_push(&cmd
.args
, "commit");
4944 * continue_single_pick() handles the case of recovering from a
4945 * conflict. should_edit() doesn't handle that case; for a conflict,
4946 * we want to edit if the user asked for it, or if they didn't specify
4947 * and stdin is a tty.
4949 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
4951 * Include --cleanup=strip as well because we don't want the
4952 * "# Conflicts:" messages.
4954 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
4956 return run_command(&cmd
);
4959 static int commit_staged_changes(struct repository
*r
,
4960 struct replay_opts
*opts
,
4961 struct todo_list
*todo_list
)
4963 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
4964 unsigned int final_fixup
= 0, is_clean
;
4966 if (has_unstaged_changes(r
, 1))
4967 return error(_("cannot rebase: You have unstaged changes."));
4969 is_clean
= !has_uncommitted_changes(r
, 0);
4971 if (file_exists(rebase_path_amend())) {
4972 struct strbuf rev
= STRBUF_INIT
;
4973 struct object_id head
, to_amend
;
4975 if (repo_get_oid(r
, "HEAD", &head
))
4976 return error(_("cannot amend non-existing commit"));
4977 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
4978 return error(_("invalid file: '%s'"), rebase_path_amend());
4979 if (get_oid_hex(rev
.buf
, &to_amend
))
4980 return error(_("invalid contents: '%s'"),
4981 rebase_path_amend());
4982 if (!is_clean
&& !oideq(&head
, &to_amend
))
4983 return error(_("\nYou have uncommitted changes in your "
4984 "working tree. Please, commit them\n"
4985 "first and then run 'git rebase "
4986 "--continue' again."));
4988 * When skipping a failed fixup/squash, we need to edit the
4989 * commit message, the current fixup list and count, and if it
4990 * was the last fixup/squash in the chain, we need to clean up
4991 * the commit message and if there was a squash, let the user
4994 if (!is_clean
|| !opts
->current_fixup_count
)
4995 ; /* this is not the final fixup */
4996 else if (!oideq(&head
, &to_amend
) ||
4997 !file_exists(rebase_path_stopped_sha())) {
4998 /* was a final fixup or squash done manually? */
4999 if (!is_fixup(peek_command(todo_list
, 0))) {
5000 unlink(rebase_path_fixup_msg());
5001 unlink(rebase_path_squash_msg());
5002 unlink(rebase_path_current_fixups());
5003 strbuf_reset(&opts
->current_fixups
);
5004 opts
->current_fixup_count
= 0;
5007 /* we are in a fixup/squash chain */
5008 const char *p
= opts
->current_fixups
.buf
;
5009 int len
= opts
->current_fixups
.len
;
5011 opts
->current_fixup_count
--;
5013 BUG("Incorrect current_fixups:\n%s", p
);
5014 while (len
&& p
[len
- 1] != '\n')
5016 strbuf_setlen(&opts
->current_fixups
, len
);
5017 if (write_message(p
, len
, rebase_path_current_fixups(),
5019 return error(_("could not write file: '%s'"),
5020 rebase_path_current_fixups());
5023 * If a fixup/squash in a fixup/squash chain failed, the
5024 * commit message is already correct, no need to commit
5027 * Only if it is the final command in the fixup/squash
5028 * chain, and only if the chain is longer than a single
5029 * fixup/squash command (which was just skipped), do we
5030 * actually need to re-commit with a cleaned up commit
5033 if (opts
->current_fixup_count
> 0 &&
5034 !is_fixup(peek_command(todo_list
, 0))) {
5037 * If there was not a single "squash" in the
5038 * chain, we only need to clean up the commit
5039 * message, no need to bother the user with
5040 * opening the commit message in the editor.
5042 if (!starts_with(p
, "squash ") &&
5043 !strstr(p
, "\nsquash "))
5044 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5045 } else if (is_fixup(peek_command(todo_list
, 0))) {
5047 * We need to update the squash message to skip
5048 * the latest commit message.
5050 struct commit
*commit
;
5051 const char *path
= rebase_path_squash_msg();
5052 const char *encoding
= get_commit_output_encoding();
5054 if (parse_head(r
, &commit
) ||
5055 !(p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)) ||
5056 write_message(p
, strlen(p
), path
, 0)) {
5057 repo_unuse_commit_buffer(r
, commit
, p
);
5058 return error(_("could not write file: "
5061 repo_unuse_commit_buffer(r
,
5066 strbuf_release(&rev
);
5071 if (refs_ref_exists(get_main_ref_store(r
),
5072 "CHERRY_PICK_HEAD") &&
5073 refs_delete_ref(get_main_ref_store(r
), "",
5074 "CHERRY_PICK_HEAD", NULL
, 0))
5075 return error(_("could not remove CHERRY_PICK_HEAD"));
5076 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5077 return error_errno(_("could not remove '%s'"),
5078 git_path_merge_msg(r
));
5083 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5085 return error(_("could not commit staged changes."));
5086 unlink(rebase_path_amend());
5087 unlink(git_path_merge_head(r
));
5088 unlink(git_path_auto_merge(r
));
5090 unlink(rebase_path_fixup_msg());
5091 unlink(rebase_path_squash_msg());
5093 if (opts
->current_fixup_count
> 0) {
5095 * Whether final fixup or not, we just cleaned up the commit
5098 unlink(rebase_path_current_fixups());
5099 strbuf_reset(&opts
->current_fixups
);
5100 opts
->current_fixup_count
= 0;
5105 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5107 struct todo_list todo_list
= TODO_LIST_INIT
;
5110 if (read_and_refresh_cache(r
, opts
))
5113 if (read_populate_opts(opts
))
5115 if (is_rebase_i(opts
)) {
5116 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5117 goto release_todo_list
;
5119 if (file_exists(rebase_path_dropped())) {
5120 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5121 goto release_todo_list
;
5123 unlink(rebase_path_dropped());
5126 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5127 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5129 goto release_todo_list
;
5131 } else if (!file_exists(get_todo_path(opts
)))
5132 return continue_single_pick(r
, opts
);
5133 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5134 goto release_todo_list
;
5136 if (!is_rebase_i(opts
)) {
5137 /* Verify that the conflict has been resolved */
5138 if (refs_ref_exists(get_main_ref_store(r
),
5139 "CHERRY_PICK_HEAD") ||
5140 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5141 res
= continue_single_pick(r
, opts
);
5143 goto release_todo_list
;
5145 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5146 res
= error_dirty_index(r
, opts
);
5147 goto release_todo_list
;
5149 todo_list
.current
++;
5150 } else if (file_exists(rebase_path_stopped_sha())) {
5151 struct strbuf buf
= STRBUF_INIT
;
5152 struct object_id oid
;
5154 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5155 READ_ONELINER_SKIP_IF_EMPTY
) &&
5156 !get_oid_hex(buf
.buf
, &oid
))
5157 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5158 strbuf_release(&buf
);
5161 res
= pick_commits(r
, &todo_list
, opts
);
5163 todo_list_release(&todo_list
);
5167 static int single_pick(struct repository
*r
,
5168 struct commit
*cmit
,
5169 struct replay_opts
*opts
)
5172 struct todo_item item
;
5174 item
.command
= opts
->action
== REPLAY_PICK
?
5175 TODO_PICK
: TODO_REVERT
;
5178 opts
->reflog_message
= sequencer_reflog_action(opts
);
5179 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5182 int sequencer_pick_revisions(struct repository
*r
,
5183 struct replay_opts
*opts
)
5185 struct todo_list todo_list
= TODO_LIST_INIT
;
5186 struct object_id oid
;
5190 if (read_and_refresh_cache(r
, opts
))
5193 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5194 struct object_id oid
;
5195 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5197 /* This happens when using --stdin. */
5201 if (!repo_get_oid(r
, name
, &oid
)) {
5202 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5203 enum object_type type
= oid_object_info(r
,
5206 return error(_("%s: can't cherry-pick a %s"),
5207 name
, type_name(type
));
5210 return error(_("%s: bad revision"), name
);
5214 * If we were called as "git cherry-pick <commit>", just
5215 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5216 * REVERT_HEAD, and don't touch the sequencer state.
5217 * This means it is possible to cherry-pick in the middle
5218 * of a cherry-pick sequence.
5220 if (opts
->revs
->cmdline
.nr
== 1 &&
5221 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5222 opts
->revs
->no_walk
&&
5223 !opts
->revs
->cmdline
.rev
->flags
) {
5224 struct commit
*cmit
;
5225 if (prepare_revision_walk(opts
->revs
))
5226 return error(_("revision walk setup failed"));
5227 cmit
= get_revision(opts
->revs
);
5229 return error(_("empty commit set passed"));
5230 if (get_revision(opts
->revs
))
5231 BUG("unexpected extra commit from walk");
5232 return single_pick(r
, cmit
, opts
);
5236 * Start a new cherry-pick/ revert sequence; but
5237 * first, make sure that an existing one isn't in
5241 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5242 create_seq_dir(r
) < 0)
5244 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5245 return error(_("can't revert as initial commit"));
5246 if (save_head(oid_to_hex(&oid
)))
5248 if (save_opts(opts
))
5250 update_abort_safety_file();
5251 res
= pick_commits(r
, &todo_list
, opts
);
5252 todo_list_release(&todo_list
);
5256 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5258 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5259 struct strbuf sob
= STRBUF_INIT
;
5262 strbuf_addstr(&sob
, sign_off_header
);
5263 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5264 strbuf_addch(&sob
, '\n');
5267 strbuf_complete_line(msgbuf
);
5270 * If the whole message buffer is equal to the sob, pretend that we
5271 * found a conforming footer with a matching sob
5273 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5274 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5277 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5280 const char *append_newlines
= NULL
;
5281 size_t len
= msgbuf
->len
- ignore_footer
;
5285 * The buffer is completely empty. Leave foom for
5286 * the title and body to be filled in by the user.
5288 append_newlines
= "\n\n";
5289 } else if (len
== 1) {
5291 * Buffer contains a single newline. Add another
5292 * so that we leave room for the title and body.
5294 append_newlines
= "\n";
5295 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5297 * Buffer ends with a single newline. Add another
5298 * so that there is an empty line between the message
5301 append_newlines
= "\n";
5302 } /* else, the buffer already ends with two newlines. */
5304 if (append_newlines
)
5305 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5306 append_newlines
, strlen(append_newlines
));
5309 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5310 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5313 strbuf_release(&sob
);
5316 struct labels_entry
{
5317 struct hashmap_entry entry
;
5318 char label
[FLEX_ARRAY
];
5321 static int labels_cmp(const void *fndata UNUSED
,
5322 const struct hashmap_entry
*eptr
,
5323 const struct hashmap_entry
*entry_or_key
, const void *key
)
5325 const struct labels_entry
*a
, *b
;
5327 a
= container_of(eptr
, const struct labels_entry
, entry
);
5328 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5330 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5333 struct string_entry
{
5334 struct oidmap_entry entry
;
5335 char string
[FLEX_ARRAY
];
5338 struct label_state
{
5339 struct oidmap commit2label
;
5340 struct hashmap labels
;
5342 int max_label_length
;
5345 static const char *label_oid(struct object_id
*oid
, const char *label
,
5346 struct label_state
*state
)
5348 struct labels_entry
*labels_entry
;
5349 struct string_entry
*string_entry
;
5350 struct object_id dummy
;
5353 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5355 return string_entry
->string
;
5358 * For "uninteresting" commits, i.e. commits that are not to be
5359 * rebased, and which can therefore not be labeled, we use a unique
5360 * abbreviation of the commit name. This is slightly more complicated
5361 * than calling repo_find_unique_abbrev() because we also need to make
5362 * sure that the abbreviation does not conflict with any other
5365 * We disallow "interesting" commits to be labeled by a string that
5366 * is a valid full-length hash, to ensure that we always can find an
5367 * abbreviation for any uninteresting commit's names that does not
5368 * clash with any other label.
5370 strbuf_reset(&state
->buf
);
5374 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5375 label
= p
= state
->buf
.buf
;
5377 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5381 * We may need to extend the abbreviated hash so that there is
5382 * no conflicting label.
5384 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5385 size_t i
= strlen(p
) + 1;
5387 oid_to_hex_r(p
, oid
);
5388 for (; i
< the_hash_algo
->hexsz
; i
++) {
5391 if (!hashmap_get_from_hash(&state
->labels
,
5398 struct strbuf
*buf
= &state
->buf
;
5399 int label_is_utf8
= 1; /* start with this assumption */
5400 size_t max_len
= buf
->len
+ state
->max_label_length
;
5403 * Sanitize labels by replacing non-alpha-numeric characters
5404 * (including white-space ones) by dashes, as they might be
5405 * illegal in file names (and hence in ref names).
5407 * Note that we retain non-ASCII UTF-8 characters (identified
5408 * via the most significant bit). They should be all acceptable
5411 * As we will use the labels as names of (loose) refs, it is
5412 * vital that the name not be longer than the maximum component
5413 * size of the file system (`NAME_MAX`). We are careful to
5414 * truncate the label accordingly, allowing for the `.lock`
5415 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5416 * truncating in the middle of a character).
5418 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5419 if (isalnum(*label
) ||
5420 (!label_is_utf8
&& (*label
& 0x80)))
5421 strbuf_addch(buf
, *label
);
5422 else if (*label
& 0x80) {
5423 const char *p
= label
;
5425 utf8_width(&p
, NULL
);
5427 if (buf
->len
+ (p
- label
) > max_len
)
5429 strbuf_add(buf
, label
, p
- label
);
5433 strbuf_addch(buf
, *label
);
5435 /* avoid leading dash and double-dashes */
5436 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5437 strbuf_addch(buf
, '-');
5439 strbuf_addstr(buf
, "rev-");
5440 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5444 if ((buf
->len
== the_hash_algo
->hexsz
&&
5445 !get_oid_hex(label
, &dummy
)) ||
5446 (buf
->len
== 1 && *label
== '#') ||
5447 hashmap_get_from_hash(&state
->labels
,
5448 strihash(label
), label
)) {
5450 * If the label already exists, or if the label is a
5451 * valid full OID, or the label is a '#' (which we use
5452 * as a separator between merge heads and oneline), we
5453 * append a dash and a number to make it unique.
5455 size_t len
= buf
->len
;
5457 for (i
= 2; ; i
++) {
5458 strbuf_setlen(buf
, len
);
5459 strbuf_addf(buf
, "-%d", i
);
5460 if (!hashmap_get_from_hash(&state
->labels
,
5470 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5471 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5472 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5474 FLEX_ALLOC_STR(string_entry
, string
, label
);
5475 oidcpy(&string_entry
->entry
.oid
, oid
);
5476 oidmap_put(&state
->commit2label
, string_entry
);
5478 return string_entry
->string
;
5481 static int make_script_with_merges(struct pretty_print_context
*pp
,
5482 struct rev_info
*revs
, struct strbuf
*out
,
5485 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5486 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5487 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5488 int skipped_commit
= 0;
5489 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5490 struct strbuf label
= STRBUF_INIT
;
5491 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5492 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5493 struct commit
*commit
;
5494 struct oidmap commit2todo
= OIDMAP_INIT
;
5495 struct string_entry
*entry
;
5496 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5497 shown
= OIDSET_INIT
;
5498 struct label_state state
=
5499 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5501 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5502 const char *cmd_pick
= abbr
? "p" : "pick",
5503 *cmd_label
= abbr
? "l" : "label",
5504 *cmd_reset
= abbr
? "t" : "reset",
5505 *cmd_merge
= abbr
? "m" : "merge";
5507 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5509 oidmap_init(&commit2todo
, 0);
5510 oidmap_init(&state
.commit2label
, 0);
5511 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5512 strbuf_init(&state
.buf
, 32);
5514 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5515 struct labels_entry
*onto_label_entry
;
5516 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5517 FLEX_ALLOC_STR(entry
, string
, "onto");
5518 oidcpy(&entry
->entry
.oid
, oid
);
5519 oidmap_put(&state
.commit2label
, entry
);
5521 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5522 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5523 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5528 * - get onelines for all commits
5529 * - gather all branch tips (i.e. 2nd or later parents of merges)
5530 * - label all branch tips
5532 while ((commit
= get_revision(revs
))) {
5533 struct commit_list
*to_merge
;
5534 const char *p1
, *p2
;
5535 struct object_id
*oid
;
5538 tail
= &commit_list_insert(commit
, tail
)->next
;
5539 oidset_insert(&interesting
, &commit
->object
.oid
);
5541 is_empty
= is_original_commit_empty(commit
);
5542 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5543 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5544 warning(_("skipped previously applied commit %s"),
5545 short_commit_name(commit
));
5549 if (is_empty
&& !keep_empty
)
5552 strbuf_reset(&oneline
);
5553 pretty_print_commit(pp
, commit
, &oneline
);
5555 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5557 /* non-merge commit: easy case */
5559 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5560 oid_to_hex(&commit
->object
.oid
),
5563 strbuf_addf(&buf
, " %c empty",
5566 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5567 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5568 oidmap_put(&commit2todo
, entry
);
5573 /* Create a label */
5574 strbuf_reset(&label
);
5575 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5576 (p1
= strchr(p1
, '\'')) &&
5577 (p2
= strchr(++p1
, '\'')))
5578 strbuf_add(&label
, p1
, p2
- p1
);
5579 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5581 (p1
= strstr(p1
, " from ")))
5582 strbuf_addstr(&label
, p1
+ strlen(" from "));
5584 strbuf_addbuf(&label
, &oneline
);
5587 strbuf_addf(&buf
, "%s -C %s",
5588 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5590 /* label the tips of merged branches */
5591 for (; to_merge
; to_merge
= to_merge
->next
) {
5592 oid
= &to_merge
->item
->object
.oid
;
5593 strbuf_addch(&buf
, ' ');
5595 if (!oidset_contains(&interesting
, oid
)) {
5596 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5601 tips_tail
= &commit_list_insert(to_merge
->item
,
5604 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5606 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5608 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5609 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5610 oidmap_put(&commit2todo
, entry
);
5613 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5614 _("use --reapply-cherry-picks to include skipped commits"));
5618 * - label branch points
5619 * - add HEAD to the branch tips
5621 for (iter
= commits
; iter
; iter
= iter
->next
) {
5622 struct commit_list
*parent
= iter
->item
->parents
;
5623 for (; parent
; parent
= parent
->next
) {
5624 struct object_id
*oid
= &parent
->item
->object
.oid
;
5625 if (!oidset_contains(&interesting
, oid
))
5627 if (oidset_insert(&child_seen
, oid
))
5628 label_oid(oid
, "branch-point", &state
);
5631 /* Add HEAD as implicit "tip of branch" */
5633 tips_tail
= &commit_list_insert(iter
->item
,
5638 * Third phase: output the todo list. This is a bit tricky, as we
5639 * want to avoid jumping back and forth between revisions. To
5640 * accomplish that goal, we walk backwards from the branch tips,
5641 * gathering commits not yet shown, reversing the list on the fly,
5642 * then outputting that list (labeling revisions as needed).
5644 strbuf_addf(out
, "%s onto\n", cmd_label
);
5645 for (iter
= tips
; iter
; iter
= iter
->next
) {
5646 struct commit_list
*list
= NULL
, *iter2
;
5648 commit
= iter
->item
;
5649 if (oidset_contains(&shown
, &commit
->object
.oid
))
5651 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5654 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5656 strbuf_addch(out
, '\n');
5658 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5659 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5660 commit_list_insert(commit
, &list
);
5661 if (!commit
->parents
) {
5665 commit
= commit
->parents
->item
;
5669 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5670 rebase_cousins
|| root_with_onto
?
5671 "onto" : "[new root]");
5673 const char *to
= NULL
;
5675 entry
= oidmap_get(&state
.commit2label
,
5676 &commit
->object
.oid
);
5679 else if (!rebase_cousins
)
5680 to
= label_oid(&commit
->object
.oid
, NULL
,
5683 if (!to
|| !strcmp(to
, "onto"))
5684 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5686 strbuf_reset(&oneline
);
5687 pretty_print_commit(pp
, commit
, &oneline
);
5688 strbuf_addf(out
, "%s %s # %s\n",
5689 cmd_reset
, to
, oneline
.buf
);
5693 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5694 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5695 entry
= oidmap_get(&commit2todo
, oid
);
5696 /* only show if not already upstream */
5698 strbuf_addf(out
, "%s\n", entry
->string
);
5699 entry
= oidmap_get(&state
.commit2label
, oid
);
5701 strbuf_addf(out
, "%s %s\n",
5702 cmd_label
, entry
->string
);
5703 oidset_insert(&shown
, oid
);
5706 free_commit_list(list
);
5709 free_commit_list(commits
);
5710 free_commit_list(tips
);
5712 strbuf_release(&label
);
5713 strbuf_release(&oneline
);
5714 strbuf_release(&buf
);
5716 oidmap_free(&commit2todo
, 1);
5717 oidmap_free(&state
.commit2label
, 1);
5718 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5719 strbuf_release(&state
.buf
);
5724 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5725 const char **argv
, unsigned flags
)
5727 char *format
= NULL
;
5728 struct pretty_print_context pp
= {0};
5729 struct rev_info revs
;
5730 struct commit
*commit
;
5731 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5732 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5733 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5734 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5735 int skipped_commit
= 0;
5738 repo_init_revisions(r
, &revs
, NULL
);
5739 revs
.verbose_header
= 1;
5741 revs
.max_parents
= 1;
5742 revs
.cherry_mark
= !reapply_cherry_picks
;
5745 revs
.right_only
= 1;
5746 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5747 revs
.topo_order
= 1;
5749 revs
.pretty_given
= 1;
5750 git_config_get_string("rebase.instructionFormat", &format
);
5751 if (!format
|| !*format
) {
5753 format
= xstrdup("%s");
5755 get_commit_format(format
, &revs
);
5757 pp
.fmt
= revs
.commit_format
;
5758 pp
.output_encoding
= get_log_output_encoding();
5760 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5761 ret
= error(_("make_script: unhandled options"));
5765 if (prepare_revision_walk(&revs
) < 0) {
5766 ret
= error(_("make_script: error preparing revisions"));
5770 if (rebase_merges
) {
5771 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5775 while ((commit
= get_revision(&revs
))) {
5776 int is_empty
= is_original_commit_empty(commit
);
5778 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5779 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5780 warning(_("skipped previously applied commit %s"),
5781 short_commit_name(commit
));
5785 if (is_empty
&& !keep_empty
)
5787 strbuf_addf(out
, "%s %s ", insn
,
5788 oid_to_hex(&commit
->object
.oid
));
5789 pretty_print_commit(&pp
, commit
, out
);
5791 strbuf_addf(out
, " %c empty", comment_line_char
);
5792 strbuf_addch(out
, '\n');
5795 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5796 _("use --reapply-cherry-picks to include skipped commits"));
5798 release_revisions(&revs
);
5803 * Add commands after pick and (series of) squash/fixup commands
5806 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5807 struct string_list
*commands
)
5809 struct strbuf
*buf
= &todo_list
->buf
;
5810 size_t base_offset
= buf
->len
;
5811 int i
, insert
, nr
= 0, alloc
= 0;
5812 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5814 CALLOC_ARRAY(base_items
, commands
->nr
);
5815 for (i
= 0; i
< commands
->nr
; i
++) {
5816 size_t command_len
= strlen(commands
->items
[i
].string
);
5818 strbuf_addstr(buf
, commands
->items
[i
].string
);
5819 strbuf_addch(buf
, '\n');
5821 base_items
[i
].command
= TODO_EXEC
;
5822 base_items
[i
].offset_in_buf
= base_offset
;
5823 base_items
[i
].arg_offset
= base_offset
;
5824 base_items
[i
].arg_len
= command_len
;
5826 base_offset
+= command_len
+ 1;
5830 * Insert <commands> after every pick. Here, fixup/squash chains
5831 * are considered part of the pick, so we insert the commands *after*
5832 * those chains if there are any.
5834 * As we insert the exec commands immediately after rearranging
5835 * any fixups and before the user edits the list, a fixup chain
5836 * can never contain comments (any comments are empty picks that
5837 * have been commented out because the user did not specify
5838 * --keep-empty). So, it is safe to insert an exec command
5839 * without looking at the command following a comment.
5842 for (i
= 0; i
< todo_list
->nr
; i
++) {
5843 enum todo_command command
= todo_list
->items
[i
].command
;
5844 if (insert
&& !is_fixup(command
)) {
5845 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5846 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5852 ALLOC_GROW(items
, nr
+ 1, alloc
);
5853 items
[nr
++] = todo_list
->items
[i
];
5855 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5859 /* insert or append final <commands> */
5861 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5862 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5867 FREE_AND_NULL(todo_list
->items
);
5868 todo_list
->items
= items
;
5870 todo_list
->alloc
= alloc
;
5873 static void todo_list_to_strbuf(struct repository
*r
, struct todo_list
*todo_list
,
5874 struct strbuf
*buf
, int num
, unsigned flags
)
5876 struct todo_item
*item
;
5877 int i
, max
= todo_list
->nr
;
5879 if (num
> 0 && num
< max
)
5882 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5885 /* if the item is not a command write it and continue */
5886 if (item
->command
>= TODO_COMMENT
) {
5887 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5888 todo_item_get_arg(todo_list
, item
));
5892 /* add command to the buffer */
5893 cmd
= command_to_char(item
->command
);
5894 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5895 strbuf_addch(buf
, cmd
);
5897 strbuf_addstr(buf
, command_to_string(item
->command
));
5901 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5902 short_commit_name(item
->commit
) :
5903 oid_to_hex(&item
->commit
->object
.oid
);
5905 if (item
->command
== TODO_FIXUP
) {
5906 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
5907 strbuf_addstr(buf
, " -c");
5908 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
5909 strbuf_addstr(buf
, " -C");
5913 if (item
->command
== TODO_MERGE
) {
5914 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5915 strbuf_addstr(buf
, " -c");
5917 strbuf_addstr(buf
, " -C");
5920 strbuf_addf(buf
, " %s", oid
);
5923 /* add all the rest */
5925 strbuf_addch(buf
, '\n');
5927 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5928 todo_item_get_arg(todo_list
, item
));
5932 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5933 const char *file
, const char *shortrevisions
,
5934 const char *shortonto
, int num
, unsigned flags
)
5937 struct strbuf buf
= STRBUF_INIT
;
5939 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5940 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5941 append_todo_help(count_commands(todo_list
),
5942 shortrevisions
, shortonto
, &buf
);
5944 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5945 strbuf_release(&buf
);
5950 /* skip picking commits whose parents are unchanged */
5951 static int skip_unnecessary_picks(struct repository
*r
,
5952 struct todo_list
*todo_list
,
5953 struct object_id
*base_oid
)
5955 struct object_id
*parent_oid
;
5958 for (i
= 0; i
< todo_list
->nr
; i
++) {
5959 struct todo_item
*item
= todo_list
->items
+ i
;
5961 if (item
->command
>= TODO_NOOP
)
5963 if (item
->command
!= TODO_PICK
)
5965 if (repo_parse_commit(r
, item
->commit
)) {
5966 return error(_("could not parse commit '%s'"),
5967 oid_to_hex(&item
->commit
->object
.oid
));
5969 if (!item
->commit
->parents
)
5970 break; /* root commit */
5971 if (item
->commit
->parents
->next
)
5972 break; /* merge commit */
5973 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
5974 if (!oideq(parent_oid
, base_oid
))
5976 oidcpy(base_oid
, &item
->commit
->object
.oid
);
5979 const char *done_path
= rebase_path_done();
5981 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
5982 error_errno(_("could not write to '%s'"), done_path
);
5986 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
5988 todo_list
->current
= 0;
5989 todo_list
->done_nr
+= i
;
5991 if (is_fixup(peek_command(todo_list
, 0)))
5992 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
5998 struct todo_add_branch_context
{
5999 struct todo_item
*items
;
6003 struct commit
*commit
;
6004 struct string_list refs_to_oids
;
6007 static int add_decorations_to_list(const struct commit
*commit
,
6008 struct todo_add_branch_context
*ctx
)
6010 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6011 const char *head_ref
= resolve_ref_unsafe("HEAD",
6012 RESOLVE_REF_READING
,
6016 while (decoration
) {
6017 struct todo_item
*item
;
6019 size_t base_offset
= ctx
->buf
->len
;
6022 * If the branch is the current HEAD, then it will be
6023 * updated by the default rebase behavior.
6025 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6026 decoration
= decoration
->next
;
6030 ALLOC_GROW(ctx
->items
,
6033 item
= &ctx
->items
[ctx
->items_nr
];
6034 memset(item
, 0, sizeof(*item
));
6036 /* If the branch is checked out, then leave a comment instead. */
6037 if ((path
= branch_checked_out(decoration
->name
))) {
6038 item
->command
= TODO_COMMENT
;
6039 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6040 decoration
->name
, path
);
6042 struct string_list_item
*sti
;
6043 item
->command
= TODO_UPDATE_REF
;
6044 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6046 sti
= string_list_insert(&ctx
->refs_to_oids
,
6048 sti
->util
= init_update_ref_record(decoration
->name
);
6051 item
->offset_in_buf
= base_offset
;
6052 item
->arg_offset
= base_offset
;
6053 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6056 decoration
= decoration
->next
;
6063 * For each 'pick' command, find out if the commit has a decoration in
6064 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6066 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6069 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6070 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6071 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6072 struct decoration_filter decoration_filter
= {
6073 .include_ref_pattern
= &decorate_refs_include
,
6074 .exclude_ref_pattern
= &decorate_refs_exclude
,
6075 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6077 struct todo_add_branch_context ctx
= {
6078 .buf
= &todo_list
->buf
,
6079 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6082 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6083 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6085 string_list_append(&decorate_refs_include
, "refs/heads/");
6086 load_ref_decorations(&decoration_filter
, 0);
6088 for (i
= 0; i
< todo_list
->nr
; ) {
6089 struct todo_item
*item
= &todo_list
->items
[i
];
6091 /* insert ith item into new list */
6092 ALLOC_GROW(ctx
.items
,
6096 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6099 ctx
.commit
= item
->commit
;
6100 add_decorations_to_list(item
->commit
, &ctx
);
6104 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6106 string_list_clear(&ctx
.refs_to_oids
, 1);
6109 /* we failed, so clean up the new list. */
6114 free(todo_list
->items
);
6115 todo_list
->items
= ctx
.items
;
6116 todo_list
->nr
= ctx
.items_nr
;
6117 todo_list
->alloc
= ctx
.items_alloc
;
6122 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6123 const char *shortrevisions
, const char *onto_name
,
6124 struct commit
*onto
, const struct object_id
*orig_head
,
6125 struct string_list
*commands
, unsigned autosquash
,
6126 unsigned update_refs
,
6127 struct todo_list
*todo_list
)
6129 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6130 const char *todo_file
= rebase_path_todo();
6131 struct todo_list new_todo
= TODO_LIST_INIT
;
6132 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6133 struct object_id oid
= onto
->object
.oid
;
6136 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6139 if (buf
->len
== 0) {
6140 struct todo_item
*item
= append_new_todo(todo_list
);
6141 item
->command
= TODO_NOOP
;
6142 item
->commit
= NULL
;
6143 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6146 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6149 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6153 todo_list_add_exec_commands(todo_list
, commands
);
6155 if (count_commands(todo_list
) == 0) {
6156 apply_autostash(rebase_path_autostash());
6157 sequencer_remove_state(opts
);
6159 return error(_("nothing to do"));
6162 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6166 else if (res
== -2) {
6167 apply_autostash(rebase_path_autostash());
6168 sequencer_remove_state(opts
);
6171 } else if (res
== -3) {
6172 apply_autostash(rebase_path_autostash());
6173 sequencer_remove_state(opts
);
6174 todo_list_release(&new_todo
);
6176 return error(_("nothing to do"));
6177 } else if (res
== -4) {
6178 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6179 todo_list_release(&new_todo
);
6184 /* Expand the commit IDs */
6185 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6186 strbuf_swap(&new_todo
.buf
, &buf2
);
6187 strbuf_release(&buf2
);
6188 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6189 new_todo
.total_nr
= 0;
6190 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6191 BUG("invalid todo list after expanding IDs:\n%s",
6194 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6195 todo_list_release(&new_todo
);
6196 return error(_("could not skip unnecessary pick commands"));
6199 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6200 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6201 todo_list_release(&new_todo
);
6202 return error_errno(_("could not write '%s'"), todo_file
);
6207 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6210 if (require_clean_work_tree(r
, "rebase", "", 1, 1))
6213 todo_list_write_total_nr(&new_todo
);
6214 res
= pick_commits(r
, &new_todo
, opts
);
6217 todo_list_release(&new_todo
);
6222 struct subject2item_entry
{
6223 struct hashmap_entry entry
;
6225 char subject
[FLEX_ARRAY
];
6228 static int subject2item_cmp(const void *fndata UNUSED
,
6229 const struct hashmap_entry
*eptr
,
6230 const struct hashmap_entry
*entry_or_key
,
6233 const struct subject2item_entry
*a
, *b
;
6235 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6236 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6238 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6241 define_commit_slab(commit_todo_item
, struct todo_item
*);
6243 static int skip_fixupish(const char *subject
, const char **p
) {
6244 return skip_prefix(subject
, "fixup! ", p
) ||
6245 skip_prefix(subject
, "amend! ", p
) ||
6246 skip_prefix(subject
, "squash! ", p
);
6250 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6251 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6252 * after the former, and change "pick" to "fixup"/"squash".
6254 * Note that if the config has specified a custom instruction format, each log
6255 * message will have to be retrieved from the commit (as the oneline in the
6256 * script cannot be trusted) in order to normalize the autosquash arrangement.
6258 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6260 struct hashmap subject2item
;
6261 int rearranged
= 0, *next
, *tail
, i
, nr
= 0, alloc
= 0;
6263 struct commit_todo_item commit_todo
;
6264 struct todo_item
*items
= NULL
;
6266 init_commit_todo_item(&commit_todo
);
6268 * The hashmap maps onelines to the respective todo list index.
6270 * If any items need to be rearranged, the next[i] value will indicate
6271 * which item was moved directly after the i'th.
6273 * In that case, last[i] will indicate the index of the latest item to
6274 * be moved to appear after the i'th.
6276 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6277 ALLOC_ARRAY(next
, todo_list
->nr
);
6278 ALLOC_ARRAY(tail
, todo_list
->nr
);
6279 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6280 for (i
= 0; i
< todo_list
->nr
; i
++) {
6281 struct strbuf buf
= STRBUF_INIT
;
6282 struct todo_item
*item
= todo_list
->items
+ i
;
6283 const char *commit_buffer
, *subject
, *p
;
6286 struct subject2item_entry
*entry
;
6288 next
[i
] = tail
[i
] = -1;
6289 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6294 if (is_fixup(item
->command
)) {
6295 clear_commit_todo_item(&commit_todo
);
6296 return error(_("the script was already rearranged."));
6299 repo_parse_commit(the_repository
, item
->commit
);
6300 commit_buffer
= repo_logmsg_reencode(the_repository
,
6303 find_commit_subject(commit_buffer
, &subject
);
6304 format_subject(&buf
, subject
, " ");
6305 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6306 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6308 if (skip_fixupish(subject
, &p
)) {
6309 struct commit
*commit2
;
6314 if (!skip_fixupish(p
, &p
))
6318 entry
= hashmap_get_entry_from_hash(&subject2item
,
6320 struct subject2item_entry
,
6323 /* found by title */
6325 else if (!strchr(p
, ' ') &&
6327 lookup_commit_reference_by_name(p
)) &&
6328 *commit_todo_item_at(&commit_todo
, commit2
))
6329 /* found by commit name */
6330 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6333 /* copy can be a prefix of the commit subject */
6334 for (i2
= 0; i2
< i
; i2
++)
6336 starts_with(subjects
[i2
], p
))
6344 if (starts_with(subject
, "fixup!")) {
6345 todo_list
->items
[i
].command
= TODO_FIXUP
;
6346 } else if (starts_with(subject
, "amend!")) {
6347 todo_list
->items
[i
].command
= TODO_FIXUP
;
6348 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6350 todo_list
->items
[i
].command
= TODO_SQUASH
;
6356 next
[i
] = next
[tail
[i2
]];
6360 } else if (!hashmap_get_from_hash(&subject2item
,
6361 strhash(subject
), subject
)) {
6362 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6364 hashmap_entry_init(&entry
->entry
,
6365 strhash(entry
->subject
));
6366 hashmap_put(&subject2item
, &entry
->entry
);
6369 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6373 for (i
= 0; i
< todo_list
->nr
; i
++) {
6374 enum todo_command command
= todo_list
->items
[i
].command
;
6378 * Initially, all commands are 'pick's. If it is a
6379 * fixup or a squash now, we have rearranged it.
6381 if (is_fixup(command
))
6385 ALLOC_GROW(items
, nr
+ 1, alloc
);
6386 items
[nr
++] = todo_list
->items
[cur
];
6391 FREE_AND_NULL(todo_list
->items
);
6392 todo_list
->items
= items
;
6394 todo_list
->alloc
= alloc
;
6399 for (i
= 0; i
< todo_list
->nr
; i
++)
6402 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6404 clear_commit_todo_item(&commit_todo
);
6409 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6411 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6412 struct object_id cherry_pick_head
, rebase_head
;
6414 if (file_exists(git_path_seq_dir()))
6415 *whence
= FROM_CHERRY_PICK_MULTI
;
6416 if (file_exists(rebase_path()) &&
6417 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6418 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6419 oideq(&rebase_head
, &cherry_pick_head
))
6420 *whence
= FROM_REBASE_PICK
;
6422 *whence
= FROM_CHERRY_PICK_SINGLE
;
6430 int sequencer_get_update_refs_state(const char *wt_dir
,
6431 struct string_list
*refs
)
6435 struct strbuf ref
= STRBUF_INIT
;
6436 struct strbuf hash
= STRBUF_INIT
;
6437 struct update_ref_record
*rec
= NULL
;
6439 char *path
= rebase_path_update_refs(wt_dir
);
6441 fp
= fopen(path
, "r");
6445 while (strbuf_getline(&ref
, fp
) != EOF
) {
6446 struct string_list_item
*item
;
6448 CALLOC_ARRAY(rec
, 1);
6450 if (strbuf_getline(&hash
, fp
) == EOF
||
6451 get_oid_hex(hash
.buf
, &rec
->before
)) {
6452 warning(_("update-refs file at '%s' is invalid"),
6458 if (strbuf_getline(&hash
, fp
) == EOF
||
6459 get_oid_hex(hash
.buf
, &rec
->after
)) {
6460 warning(_("update-refs file at '%s' is invalid"),
6466 item
= string_list_insert(refs
, ref
.buf
);
6476 strbuf_release(&ref
);
6477 strbuf_release(&hash
);