1 #include "git-compat-util.h"
7 #include "environment.h"
12 #include "object-file.h"
13 #include "object-name.h"
14 #include "object-store-ll.h"
18 #include "sequencer.h"
20 #include "run-command.h"
24 #include "cache-tree.h"
30 #include "merge-ort.h"
31 #include "merge-ort-wrappers.h"
33 #include "sparse-index.h"
38 #include "wt-status.h"
40 #include "notes-utils.h"
42 #include "unpack-trees.h"
46 #include "commit-slab.h"
48 #include "commit-reach.h"
49 #include "rebase-interactive.h"
54 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
56 static const char sign_off_header
[] = "Signed-off-by: ";
57 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
59 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
61 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
63 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
64 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
65 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
66 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
68 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
70 * The file containing rebase commands, comments, and empty lines.
71 * This file is created by "git rebase -i" then edited by the user. As
72 * the lines are processed, they are removed from the front of this
73 * file and written to the tail of 'done'.
75 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
76 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
78 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
81 * The rebase command lines that have already been processed. A line
82 * is moved here when it is first handled, before any associated user
85 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
87 * The file to keep track of how many commands were already processed (e.g.
90 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
92 * The file to keep track of how many commands are to be processed in total
93 * (e.g. for the prompt).
95 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
97 * The commit message that is planned to be used for any changes that
98 * need to be committed following a user interaction.
100 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
102 * The file into which is accumulated the suggested commit message for
103 * squash/fixup commands. When the first of a series of squash/fixups
104 * is seen, the file is created and the commit message from the
105 * previous commit and from the first squash/fixup commit are written
106 * to it. The commit message for each subsequent squash/fixup commit
107 * is appended to the file as it is processed.
109 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
111 * If the current series of squash/fixups has not yet included a squash
112 * command, then this file exists and holds the commit message of the
113 * original "pick" commit. (If the series ends without a "squash"
114 * command, then this can be used as the commit message of the combined
115 * commit without opening the editor.)
117 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
119 * This file contains the list fixup/squash commands that have been
120 * accumulated into message-fixup or message-squash so far.
122 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
124 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
125 * GIT_AUTHOR_DATE that will be used for the commit that is currently
128 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
130 * When an "edit" rebase command is being processed, the SHA1 of the
131 * commit to be edited is recorded in this file. When "git rebase
132 * --continue" is executed, if there are any staged changes then they
133 * will be amended to the HEAD commit, but only provided the HEAD
134 * commit is still the commit to be edited. When any other rebase
135 * command is processed, this file is deleted.
137 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
139 * When we stop at a given patch via the "edit" command, this file contains
140 * the commit object name of the corresponding patch.
142 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
144 * For the post-rewrite hook, we make a list of rewritten commits and
145 * their new sha1s. The rewritten-pending list keeps the sha1s of
146 * commits that have been processed, but not committed yet,
147 * e.g. because they are waiting for a 'squash' command.
149 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
150 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
151 "rebase-merge/rewritten-pending")
154 * The path of the file containing the OID of the "squash onto" commit, i.e.
155 * the dummy commit used for `reset [new root]`.
157 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
160 * The path of the file listing refs that need to be deleted after the rebase
161 * finishes. This is used by the `label` command to record the need for cleanup.
163 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
166 * The update-refs file stores a list of refs that will be updated at the end
167 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
168 * update the OIDs for the refs in this file, but the refs are not updated
169 * until the end of the rebase sequence.
171 * rebase_path_update_refs() returns the path to this file for a given
172 * worktree directory. For the current worktree, pass the_repository->gitdir.
174 static char *rebase_path_update_refs(const char *wt_git_dir
)
176 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
180 * The following files are written by git-rebase just after parsing the
183 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
184 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
185 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
186 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
187 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
188 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
189 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
190 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
191 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
192 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
193 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
194 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
195 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
196 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
197 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
198 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
199 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
202 * A 'struct update_refs_record' represents a value in the update-refs
203 * list. We use a string_list to map refs to these (before, after) pairs.
205 struct update_ref_record
{
206 struct object_id before
;
207 struct object_id after
;
210 static struct update_ref_record
*init_update_ref_record(const char *ref
)
212 struct update_ref_record
*rec
;
214 CALLOC_ARRAY(rec
, 1);
216 oidcpy(&rec
->before
, null_oid());
217 oidcpy(&rec
->after
, null_oid());
219 /* This may fail, but that's fine, we will keep the null OID. */
220 read_ref(ref
, &rec
->before
);
225 static int git_sequencer_config(const char *k
, const char *v
, void *cb
)
227 struct replay_opts
*opts
= cb
;
230 if (!strcmp(k
, "commit.cleanup")) {
233 status
= git_config_string(&s
, k
, v
);
237 if (!strcmp(s
, "verbatim")) {
238 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
239 opts
->explicit_cleanup
= 1;
240 } else if (!strcmp(s
, "whitespace")) {
241 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
242 opts
->explicit_cleanup
= 1;
243 } else if (!strcmp(s
, "strip")) {
244 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
245 opts
->explicit_cleanup
= 1;
246 } else if (!strcmp(s
, "scissors")) {
247 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
248 opts
->explicit_cleanup
= 1;
250 warning(_("invalid commit message cleanup mode '%s'"),
258 if (!strcmp(k
, "commit.gpgsign")) {
259 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
263 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
264 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
267 * pull.twohead is allowed to be multi-valued; we only
268 * care about the first value.
270 char *tmp
= strchr(opts
->default_strategy
, ' ');
277 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
278 opts
->commit_use_reference
= git_config_bool(k
, v
);
280 return git_diff_basic_config(k
, v
, NULL
);
283 void sequencer_init_config(struct replay_opts
*opts
)
285 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
286 git_config(git_sequencer_config
, opts
);
289 static inline int is_rebase_i(const struct replay_opts
*opts
)
291 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
294 static const char *get_dir(const struct replay_opts
*opts
)
296 if (is_rebase_i(opts
))
297 return rebase_path();
298 return git_path_seq_dir();
301 static const char *get_todo_path(const struct replay_opts
*opts
)
303 if (is_rebase_i(opts
))
304 return rebase_path_todo();
305 return git_path_todo_file();
309 * Returns 0 for non-conforming footer
310 * Returns 1 for conforming footer
311 * Returns 2 when sob exists within conforming footer
312 * Returns 3 when sob exists within conforming footer as last entry
314 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
315 size_t ignore_footer
)
317 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
318 struct trailer_info info
;
320 int found_sob
= 0, found_sob_last
= 0;
326 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
327 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
330 trailer_info_get(&info
, sb
->buf
, &opts
);
333 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
335 if (info
.trailer_start
== info
.trailer_end
)
338 for (i
= 0; i
< info
.trailer_nr
; i
++)
339 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
341 if (i
== info
.trailer_nr
- 1)
345 trailer_info_release(&info
);
354 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
356 static struct strbuf buf
= STRBUF_INIT
;
360 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
364 void replay_opts_release(struct replay_opts
*opts
)
366 free(opts
->gpg_sign
);
367 free(opts
->reflog_action
);
368 free(opts
->default_strategy
);
369 free(opts
->strategy
);
370 strvec_clear (&opts
->xopts
);
371 strbuf_release(&opts
->current_fixups
);
373 release_revisions(opts
->revs
);
377 int sequencer_remove_state(struct replay_opts
*opts
)
379 struct strbuf buf
= STRBUF_INIT
;
382 if (is_rebase_i(opts
) &&
383 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
386 char *eol
= strchr(p
, '\n');
389 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
390 warning(_("could not delete '%s'"), p
);
400 strbuf_addstr(&buf
, get_dir(opts
));
401 if (remove_dir_recursively(&buf
, 0))
402 ret
= error(_("could not remove '%s'"), buf
.buf
);
403 strbuf_release(&buf
);
408 static const char *action_name(const struct replay_opts
*opts
)
410 switch (opts
->action
) {
414 return N_("cherry-pick");
415 case REPLAY_INTERACTIVE_REBASE
:
418 die(_("unknown action: %d"), opts
->action
);
421 struct commit_message
{
428 static const char *short_commit_name(struct commit
*commit
)
430 return repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
,
434 static int get_message(struct commit
*commit
, struct commit_message
*out
)
436 const char *abbrev
, *subject
;
439 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
440 get_commit_output_encoding());
441 abbrev
= short_commit_name(commit
);
443 subject_len
= find_commit_subject(out
->message
, &subject
);
445 out
->subject
= xmemdupz(subject
, subject_len
);
446 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
447 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
452 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
454 free(msg
->parent_label
);
457 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
460 static void print_advice(struct repository
*r
, int show_hint
,
461 struct replay_opts
*opts
)
463 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
468 * A conflict has occurred but the porcelain
469 * (typically rebase --interactive) wants to take care
470 * of the commit itself so remove CHERRY_PICK_HEAD
472 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
479 advise(_("after resolving the conflicts, mark the corrected paths\n"
480 "with 'git add <paths>' or 'git rm <paths>'"));
481 else if (opts
->action
== REPLAY_PICK
)
482 advise(_("After resolving the conflicts, mark them with\n"
483 "\"git add/rm <pathspec>\", then run\n"
484 "\"git cherry-pick --continue\".\n"
485 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
486 "To abort and get back to the state before \"git cherry-pick\",\n"
487 "run \"git cherry-pick --abort\"."));
488 else if (opts
->action
== REPLAY_REVERT
)
489 advise(_("After resolving the conflicts, mark them with\n"
490 "\"git add/rm <pathspec>\", then run\n"
491 "\"git revert --continue\".\n"
492 "You can instead skip this commit with \"git revert --skip\".\n"
493 "To abort and get back to the state before \"git revert\",\n"
494 "run \"git revert --abort\"."));
496 BUG("unexpected pick action in print_advice()");
500 static int write_message(const void *buf
, size_t len
, const char *filename
,
503 struct lock_file msg_file
= LOCK_INIT
;
505 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
507 return error_errno(_("could not lock '%s'"), filename
);
508 if (write_in_full(msg_fd
, buf
, len
) < 0) {
509 error_errno(_("could not write to '%s'"), filename
);
510 rollback_lock_file(&msg_file
);
513 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
514 error_errno(_("could not write eol to '%s'"), filename
);
515 rollback_lock_file(&msg_file
);
518 if (commit_lock_file(&msg_file
) < 0)
519 return error(_("failed to finalize '%s'"), filename
);
524 int read_oneliner(struct strbuf
*buf
,
525 const char *path
, unsigned flags
)
527 int orig_len
= buf
->len
;
529 if (strbuf_read_file(buf
, path
, 0) < 0) {
530 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
531 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
532 warning_errno(_("could not read '%s'"), path
);
536 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
537 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
539 buf
->buf
[buf
->len
] = '\0';
542 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
548 static struct tree
*empty_tree(struct repository
*r
)
550 return lookup_tree(r
, the_hash_algo
->empty_tree
);
553 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
555 if (repo_read_index_unmerged(repo
))
556 return error_resolve_conflict(action_name(opts
));
558 error(_("your local changes would be overwritten by %s."),
559 _(action_name(opts
)));
561 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
562 advise(_("commit your changes or stash them to proceed."));
566 static void update_abort_safety_file(void)
568 struct object_id head
;
570 /* Do nothing on a single-pick */
571 if (!file_exists(git_path_seq_dir()))
574 if (!repo_get_oid(the_repository
, "HEAD", &head
))
575 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
577 write_file(git_path_abort_safety_file(), "%s", "");
580 static int fast_forward_to(struct repository
*r
,
581 const struct object_id
*to
,
582 const struct object_id
*from
,
584 struct replay_opts
*opts
)
586 struct ref_transaction
*transaction
;
587 struct strbuf sb
= STRBUF_INIT
;
588 struct strbuf err
= STRBUF_INIT
;
591 if (checkout_fast_forward(r
, from
, to
, 1))
592 return -1; /* the callee should have complained already */
594 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
596 transaction
= ref_transaction_begin(&err
);
598 ref_transaction_update(transaction
, "HEAD",
599 to
, unborn
&& !is_rebase_i(opts
) ?
602 ref_transaction_commit(transaction
, &err
)) {
603 ref_transaction_free(transaction
);
604 error("%s", err
.buf
);
606 strbuf_release(&err
);
611 strbuf_release(&err
);
612 ref_transaction_free(transaction
);
613 update_abort_safety_file();
617 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
620 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
621 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
622 COMMIT_MSG_CLEANUP_SPACE
;
623 else if (!strcmp(cleanup_arg
, "verbatim"))
624 return COMMIT_MSG_CLEANUP_NONE
;
625 else if (!strcmp(cleanup_arg
, "whitespace"))
626 return COMMIT_MSG_CLEANUP_SPACE
;
627 else if (!strcmp(cleanup_arg
, "strip"))
628 return COMMIT_MSG_CLEANUP_ALL
;
629 else if (!strcmp(cleanup_arg
, "scissors"))
630 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
631 COMMIT_MSG_CLEANUP_SPACE
;
633 die(_("Invalid cleanup mode %s"), cleanup_arg
);
637 * NB using int rather than enum cleanup_mode to stop clang's
638 * -Wtautological-constant-out-of-range-compare complaining that the comparison
641 static const char *describe_cleanup_mode(int cleanup_mode
)
643 static const char *modes
[] = { "whitespace",
648 if (cleanup_mode
< ARRAY_SIZE(modes
))
649 return modes
[cleanup_mode
];
651 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
654 void append_conflicts_hint(struct index_state
*istate
,
655 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
659 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
660 strbuf_addch(msgbuf
, '\n');
661 wt_status_append_cut_line(msgbuf
);
662 strbuf_addch(msgbuf
, comment_line_char
);
665 strbuf_addch(msgbuf
, '\n');
666 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
667 for (i
= 0; i
< istate
->cache_nr
;) {
668 const struct cache_entry
*ce
= istate
->cache
[i
++];
670 strbuf_commented_addf(msgbuf
, comment_line_char
,
672 while (i
< istate
->cache_nr
&&
673 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
679 static int do_recursive_merge(struct repository
*r
,
680 struct commit
*base
, struct commit
*next
,
681 const char *base_label
, const char *next_label
,
682 struct object_id
*head
, struct strbuf
*msgbuf
,
683 struct replay_opts
*opts
)
685 struct merge_options o
;
686 struct merge_result result
;
687 struct tree
*next_tree
, *base_tree
, *head_tree
;
688 int clean
, show_output
;
690 struct lock_file index_lock
= LOCK_INIT
;
692 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
697 init_merge_options(&o
, r
);
698 o
.ancestor
= base
? base_label
: "(empty tree)";
700 o
.branch2
= next
? next_label
: "(empty tree)";
701 if (is_rebase_i(opts
))
703 o
.show_rename_progress
= 1;
705 head_tree
= parse_tree_indirect(head
);
706 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
707 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
709 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
710 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
712 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
713 memset(&result
, 0, sizeof(result
));
714 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
716 show_output
= !is_rebase_i(opts
) || !result
.clean
;
718 * TODO: merge_switch_to_result will update index/working tree;
719 * we only really want to do that if !result.clean || this is
720 * the final patch to be picked. But determining this is the
721 * final patch would take some work, and "head_tree" would need
722 * to be replace with the tree the index matched before we
723 * started doing any picks.
725 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
726 clean
= result
.clean
;
728 ensure_full_index(r
->index
);
729 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
730 if (is_rebase_i(opts
) && clean
<= 0)
731 fputs(o
.obuf
.buf
, stdout
);
732 strbuf_release(&o
.obuf
);
735 rollback_lock_file(&index_lock
);
739 if (write_locked_index(r
->index
, &index_lock
,
740 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
742 * TRANSLATORS: %s will be "revert", "cherry-pick" or
745 return error(_("%s: Unable to write new index file"),
746 _(action_name(opts
)));
749 append_conflicts_hint(r
->index
, msgbuf
,
750 opts
->default_msg_cleanup
);
755 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
757 if (!cache_tree_fully_valid(istate
->cache_tree
))
758 if (cache_tree_update(istate
, 0)) {
759 error(_("unable to update cache tree"));
763 return &istate
->cache_tree
->oid
;
766 static int is_index_unchanged(struct repository
*r
)
768 struct object_id head_oid
, *cache_tree_oid
;
769 struct commit
*head_commit
;
770 struct index_state
*istate
= r
->index
;
772 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
773 return error(_("could not resolve HEAD commit"));
775 head_commit
= lookup_commit(r
, &head_oid
);
778 * If head_commit is NULL, check_commit, called from
779 * lookup_commit, would have indicated that head_commit is not
780 * a commit object already. repo_parse_commit() will return failure
781 * without further complaints in such a case. Otherwise, if
782 * the commit is invalid, repo_parse_commit() will complain. So
783 * there is nothing for us to say here. Just return failure.
785 if (repo_parse_commit(r
, head_commit
))
788 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
791 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
794 static int write_author_script(const char *message
)
796 struct strbuf buf
= STRBUF_INIT
;
801 if (!*message
|| starts_with(message
, "\n")) {
803 /* Missing 'author' line? */
804 unlink(rebase_path_author_script());
806 } else if (skip_prefix(message
, "author ", &message
))
808 else if ((eol
= strchr(message
, '\n')))
813 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
814 while (*message
&& *message
!= '\n' && *message
!= '\r')
815 if (skip_prefix(message
, " <", &message
))
817 else if (*message
!= '\'')
818 strbuf_addch(&buf
, *(message
++));
820 strbuf_addf(&buf
, "'\\%c'", *(message
++));
821 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
822 while (*message
&& *message
!= '\n' && *message
!= '\r')
823 if (skip_prefix(message
, "> ", &message
))
825 else if (*message
!= '\'')
826 strbuf_addch(&buf
, *(message
++));
828 strbuf_addf(&buf
, "'\\%c'", *(message
++));
829 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
830 while (*message
&& *message
!= '\n' && *message
!= '\r')
831 if (*message
!= '\'')
832 strbuf_addch(&buf
, *(message
++));
834 strbuf_addf(&buf
, "'\\%c'", *(message
++));
835 strbuf_addch(&buf
, '\'');
836 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
837 strbuf_release(&buf
);
842 * Take a series of KEY='VALUE' lines where VALUE part is
843 * sq-quoted, and append <KEY, VALUE> at the end of the string list
845 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
848 struct string_list_item
*item
;
850 char *cp
= strchr(buf
, '=');
852 np
= strchrnul(buf
, '\n');
853 return error(_("no key present in '%.*s'"),
854 (int) (np
- buf
), buf
);
856 np
= strchrnul(cp
, '\n');
858 item
= string_list_append(list
, buf
);
860 buf
= np
+ (*np
== '\n');
864 return error(_("unable to dequote value of '%s'"),
866 item
->util
= xstrdup(cp
);
872 * Reads and parses the state directory's "author-script" file, and sets name,
873 * email and date accordingly.
874 * Returns 0 on success, -1 if the file could not be parsed.
876 * The author script is of the format:
878 * GIT_AUTHOR_NAME='$author_name'
879 * GIT_AUTHOR_EMAIL='$author_email'
880 * GIT_AUTHOR_DATE='$author_date'
882 * where $author_name, $author_email and $author_date are quoted. We are strict
883 * with our parsing, as the file was meant to be eval'd in the now-removed
884 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
885 * from what this function expects, it is better to bail out than to do
886 * something that the user does not expect.
888 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
891 struct strbuf buf
= STRBUF_INIT
;
892 struct string_list kv
= STRING_LIST_INIT_DUP
;
893 int retval
= -1; /* assume failure */
894 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
896 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
897 strbuf_release(&buf
);
898 if (errno
== ENOENT
&& allow_missing
)
901 return error_errno(_("could not open '%s' for reading"),
905 if (parse_key_value_squoted(buf
.buf
, &kv
))
908 for (i
= 0; i
< kv
.nr
; i
++) {
909 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
911 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
914 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
916 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
919 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
921 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
925 err
= error(_("unknown variable '%s'"),
930 error(_("missing 'GIT_AUTHOR_NAME'"));
932 error(_("missing 'GIT_AUTHOR_EMAIL'"));
934 error(_("missing 'GIT_AUTHOR_DATE'"));
935 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
937 *name
= kv
.items
[name_i
].util
;
938 *email
= kv
.items
[email_i
].util
;
939 *date
= kv
.items
[date_i
].util
;
942 string_list_clear(&kv
, !!retval
);
943 strbuf_release(&buf
);
948 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
949 * file with shell quoting into struct strvec. Returns -1 on
950 * error, 0 otherwise.
952 static int read_env_script(struct strvec
*env
)
954 char *name
, *email
, *date
;
956 if (read_author_script(rebase_path_author_script(),
957 &name
, &email
, &date
, 0))
960 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
961 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
962 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
970 static char *get_author(const char *message
)
975 a
= find_commit_header(message
, "author", &len
);
977 return xmemdupz(a
, len
);
982 static const char *author_date_from_env(const struct strvec
*env
)
987 for (i
= 0; i
< env
->nr
; i
++)
988 if (skip_prefix(env
->v
[i
],
989 "GIT_AUTHOR_DATE=", &date
))
992 * If GIT_AUTHOR_DATE is missing we should have already errored out when
995 BUG("GIT_AUTHOR_DATE missing from author script");
998 static const char staged_changes_advice
[] =
999 N_("you have staged changes in your working tree\n"
1000 "If these changes are meant to be squashed into the previous commit, run:\n"
1002 " git commit --amend %s\n"
1004 "If they are meant to go into a new commit, run:\n"
1008 "In both cases, once you're done, continue with:\n"
1010 " git rebase --continue\n");
1012 #define ALLOW_EMPTY (1<<0)
1013 #define EDIT_MSG (1<<1)
1014 #define AMEND_MSG (1<<2)
1015 #define CLEANUP_MSG (1<<3)
1016 #define VERIFY_MSG (1<<4)
1017 #define CREATE_ROOT_COMMIT (1<<5)
1018 #define VERBATIM_MSG (1<<6)
1020 static int run_command_silent_on_success(struct child_process
*cmd
)
1022 struct strbuf buf
= STRBUF_INIT
;
1025 cmd
->stdout_to_stderr
= 1;
1026 rc
= pipe_command(cmd
,
1032 fputs(buf
.buf
, stderr
);
1033 strbuf_release(&buf
);
1038 * If we are cherry-pick, and if the merge did not result in
1039 * hand-editing, we will hit this commit and inherit the original
1040 * author date and name.
1042 * If we are revert, or if our cherry-pick results in a hand merge,
1043 * we had better say that the current user is responsible for that.
1045 * An exception is when run_git_commit() is called during an
1046 * interactive rebase: in that case, we will want to retain the
1049 static int run_git_commit(const char *defmsg
,
1050 struct replay_opts
*opts
,
1053 struct child_process cmd
= CHILD_PROCESS_INIT
;
1055 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1056 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1060 if (is_rebase_i(opts
) &&
1061 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1062 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1063 read_env_script(&cmd
.env
)) {
1064 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1066 return error(_(staged_changes_advice
),
1070 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1072 if (opts
->committer_date_is_author_date
)
1073 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1076 author_date_from_env(&cmd
.env
));
1077 if (opts
->ignore_date
)
1078 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1080 strvec_push(&cmd
.args
, "commit");
1082 if (!(flags
& VERIFY_MSG
))
1083 strvec_push(&cmd
.args
, "-n");
1084 if ((flags
& AMEND_MSG
))
1085 strvec_push(&cmd
.args
, "--amend");
1087 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1089 strvec_push(&cmd
.args
, "--no-gpg-sign");
1091 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1092 else if (!(flags
& EDIT_MSG
))
1093 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1094 if ((flags
& CLEANUP_MSG
))
1095 strvec_push(&cmd
.args
, "--cleanup=strip");
1096 if ((flags
& VERBATIM_MSG
))
1097 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1098 if ((flags
& EDIT_MSG
))
1099 strvec_push(&cmd
.args
, "-e");
1100 else if (!(flags
& CLEANUP_MSG
) &&
1101 !opts
->signoff
&& !opts
->record_origin
&&
1102 !opts
->explicit_cleanup
)
1103 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1105 if ((flags
& ALLOW_EMPTY
))
1106 strvec_push(&cmd
.args
, "--allow-empty");
1108 if (!(flags
& EDIT_MSG
))
1109 strvec_push(&cmd
.args
, "--allow-empty-message");
1111 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1112 return run_command_silent_on_success(&cmd
);
1114 return run_command(&cmd
);
1117 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1122 /* Check if the rest is just whitespace and Signed-off-by's. */
1123 for (i
= start
; i
< sb
->len
; i
++) {
1124 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1130 if (strlen(sign_off_header
) <= eol
- i
&&
1131 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1136 if (!isspace(sb
->buf
[i
++]))
1143 void cleanup_message(struct strbuf
*msgbuf
,
1144 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1146 if (verbose
|| /* Truncate the message just before the diff, if any. */
1147 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1148 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1149 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1150 strbuf_stripspace(msgbuf
,
1151 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1155 * Find out if the message in the strbuf contains only whitespace and
1156 * Signed-off-by lines.
1158 int message_is_empty(const struct strbuf
*sb
,
1159 enum commit_msg_cleanup_mode cleanup_mode
)
1161 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1163 return rest_is_empty(sb
, 0);
1167 * See if the user edited the message in the editor or left what
1168 * was in the template intact
1170 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1171 enum commit_msg_cleanup_mode cleanup_mode
)
1173 struct strbuf tmpl
= STRBUF_INIT
;
1176 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1179 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1182 strbuf_stripspace(&tmpl
,
1183 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1184 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1186 strbuf_release(&tmpl
);
1187 return rest_is_empty(sb
, start
- sb
->buf
);
1190 int update_head_with_reflog(const struct commit
*old_head
,
1191 const struct object_id
*new_head
,
1192 const char *action
, const struct strbuf
*msg
,
1195 struct ref_transaction
*transaction
;
1196 struct strbuf sb
= STRBUF_INIT
;
1201 strbuf_addstr(&sb
, action
);
1202 strbuf_addstr(&sb
, ": ");
1205 nl
= strchr(msg
->buf
, '\n');
1207 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1209 strbuf_addbuf(&sb
, msg
);
1210 strbuf_addch(&sb
, '\n');
1213 transaction
= ref_transaction_begin(err
);
1215 ref_transaction_update(transaction
, "HEAD", new_head
,
1216 old_head
? &old_head
->object
.oid
: null_oid(),
1218 ref_transaction_commit(transaction
, err
)) {
1221 ref_transaction_free(transaction
);
1222 strbuf_release(&sb
);
1227 static int run_rewrite_hook(const struct object_id
*oldoid
,
1228 const struct object_id
*newoid
)
1230 struct child_process proc
= CHILD_PROCESS_INIT
;
1232 struct strbuf sb
= STRBUF_INIT
;
1233 const char *hook_path
= find_hook("post-rewrite");
1238 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1240 proc
.stdout_to_stderr
= 1;
1241 proc
.trace2_hook_name
= "post-rewrite";
1243 code
= start_command(&proc
);
1246 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1247 sigchain_push(SIGPIPE
, SIG_IGN
);
1248 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1250 strbuf_release(&sb
);
1251 sigchain_pop(SIGPIPE
);
1252 return finish_command(&proc
);
1255 void commit_post_rewrite(struct repository
*r
,
1256 const struct commit
*old_head
,
1257 const struct object_id
*new_head
)
1259 struct notes_rewrite_cfg
*cfg
;
1261 cfg
= init_copy_notes_for_rewrite("amend");
1263 /* we are amending, so old_head is not NULL */
1264 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1265 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1267 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1270 static int run_prepare_commit_msg_hook(struct repository
*r
,
1275 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1277 name
= git_path_commit_editmsg();
1278 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1287 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1289 ret
= error(_("'prepare-commit-msg' hook failed"));
1294 static const char implicit_ident_advice_noconfig
[] =
1295 N_("Your name and email address were configured automatically based\n"
1296 "on your username and hostname. Please check that they are accurate.\n"
1297 "You can suppress this message by setting them explicitly. Run the\n"
1298 "following command and follow the instructions in your editor to edit\n"
1299 "your configuration file:\n"
1301 " git config --global --edit\n"
1303 "After doing this, you may fix the identity used for this commit with:\n"
1305 " git commit --amend --reset-author\n");
1307 static const char implicit_ident_advice_config
[] =
1308 N_("Your name and email address were configured automatically based\n"
1309 "on your username and hostname. Please check that they are accurate.\n"
1310 "You can suppress this message by setting them explicitly:\n"
1312 " git config --global user.name \"Your Name\"\n"
1313 " git config --global user.email you@example.com\n"
1315 "After doing this, you may fix the identity used for this commit with:\n"
1317 " git commit --amend --reset-author\n");
1319 static const char *implicit_ident_advice(void)
1321 char *user_config
= interpolate_path("~/.gitconfig", 0);
1322 char *xdg_config
= xdg_config_home("config");
1323 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1329 return _(implicit_ident_advice_config
);
1331 return _(implicit_ident_advice_noconfig
);
1335 void print_commit_summary(struct repository
*r
,
1337 const struct object_id
*oid
,
1340 struct rev_info rev
;
1341 struct commit
*commit
;
1342 struct strbuf format
= STRBUF_INIT
;
1344 struct pretty_print_context pctx
= {0};
1345 struct strbuf author_ident
= STRBUF_INIT
;
1346 struct strbuf committer_ident
= STRBUF_INIT
;
1347 struct ref_store
*refs
;
1349 commit
= lookup_commit(r
, oid
);
1351 die(_("couldn't look up newly created commit"));
1352 if (repo_parse_commit(r
, commit
))
1353 die(_("could not parse newly created commit"));
1355 strbuf_addstr(&format
, "format:%h] %s");
1357 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1359 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1361 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1362 strbuf_addstr(&format
, "\n Author: ");
1363 strbuf_addbuf_percentquote(&format
, &author_ident
);
1365 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1366 struct strbuf date
= STRBUF_INIT
;
1368 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1369 strbuf_addstr(&format
, "\n Date: ");
1370 strbuf_addbuf_percentquote(&format
, &date
);
1371 strbuf_release(&date
);
1373 if (!committer_ident_sufficiently_given()) {
1374 strbuf_addstr(&format
, "\n Committer: ");
1375 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1376 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1377 strbuf_addch(&format
, '\n');
1378 strbuf_addstr(&format
, implicit_ident_advice());
1381 strbuf_release(&author_ident
);
1382 strbuf_release(&committer_ident
);
1384 repo_init_revisions(r
, &rev
, prefix
);
1385 setup_revisions(0, NULL
, &rev
, NULL
);
1388 rev
.diffopt
.output_format
=
1389 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1391 rev
.verbose_header
= 1;
1392 rev
.show_root_diff
= 1;
1393 get_commit_format(format
.buf
, &rev
);
1394 rev
.always_show_header
= 0;
1395 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1396 diff_setup_done(&rev
.diffopt
);
1398 refs
= get_main_ref_store(r
);
1399 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1401 die(_("unable to resolve HEAD after creating commit"));
1402 if (!strcmp(head
, "HEAD"))
1403 head
= _("detached HEAD");
1405 skip_prefix(head
, "refs/heads/", &head
);
1406 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1407 _(" (root-commit)") : "");
1409 if (!log_tree_commit(&rev
, commit
)) {
1410 rev
.always_show_header
= 1;
1411 rev
.use_terminator
= 1;
1412 log_tree_commit(&rev
, commit
);
1415 release_revisions(&rev
);
1416 strbuf_release(&format
);
1419 static int parse_head(struct repository
*r
, struct commit
**head
)
1421 struct commit
*current_head
;
1422 struct object_id oid
;
1424 if (repo_get_oid(r
, "HEAD", &oid
)) {
1425 current_head
= NULL
;
1427 current_head
= lookup_commit_reference(r
, &oid
);
1429 return error(_("could not parse HEAD"));
1430 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1431 warning(_("HEAD %s is not a commit!"),
1434 if (repo_parse_commit(r
, current_head
))
1435 return error(_("could not parse HEAD commit"));
1437 *head
= current_head
;
1443 * Try to commit without forking 'git commit'. In some cases we need
1444 * to run 'git commit' to display an error message
1447 * -1 - error unable to commit
1449 * 1 - run 'git commit'
1451 static int try_to_commit(struct repository
*r
,
1452 struct strbuf
*msg
, const char *author
,
1453 struct replay_opts
*opts
, unsigned int flags
,
1454 struct object_id
*oid
)
1456 struct object_id tree
;
1457 struct commit
*current_head
= NULL
;
1458 struct commit_list
*parents
= NULL
;
1459 struct commit_extra_header
*extra
= NULL
;
1460 struct strbuf err
= STRBUF_INIT
;
1461 struct strbuf commit_msg
= STRBUF_INIT
;
1462 char *amend_author
= NULL
;
1463 const char *committer
= NULL
;
1464 const char *hook_commit
= NULL
;
1465 enum commit_msg_cleanup_mode cleanup
;
1468 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1469 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1471 if (parse_head(r
, ¤t_head
))
1474 if (flags
& AMEND_MSG
) {
1475 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1476 const char *out_enc
= get_commit_output_encoding();
1477 const char *message
= repo_logmsg_reencode(r
, current_head
,
1481 const char *orig_message
= NULL
;
1483 find_commit_subject(message
, &orig_message
);
1485 strbuf_addstr(msg
, orig_message
);
1486 hook_commit
= "HEAD";
1488 author
= amend_author
= get_author(message
);
1489 repo_unuse_commit_buffer(r
, current_head
,
1492 res
= error(_("unable to parse commit author"));
1495 parents
= copy_commit_list(current_head
->parents
);
1496 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1497 } else if (current_head
&&
1498 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1499 commit_list_insert(current_head
, &parents
);
1502 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1503 res
= error(_("git write-tree failed to write a tree"));
1507 if (!(flags
& ALLOW_EMPTY
)) {
1508 struct commit
*first_parent
= current_head
;
1510 if (flags
& AMEND_MSG
) {
1511 if (current_head
->parents
) {
1512 first_parent
= current_head
->parents
->item
;
1513 if (repo_parse_commit(r
, first_parent
)) {
1514 res
= error(_("could not parse HEAD commit"));
1518 first_parent
= NULL
;
1521 if (oideq(first_parent
1522 ? get_commit_tree_oid(first_parent
)
1523 : the_hash_algo
->empty_tree
,
1525 res
= 1; /* run 'git commit' to display error message */
1530 if (hook_exists("prepare-commit-msg")) {
1531 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1534 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1536 res
= error_errno(_("unable to read commit message "
1538 git_path_commit_editmsg());
1544 if (flags
& CLEANUP_MSG
)
1545 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1546 else if (flags
& VERBATIM_MSG
)
1547 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1548 else if ((opts
->signoff
|| opts
->record_origin
) &&
1549 !opts
->explicit_cleanup
)
1550 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1552 cleanup
= opts
->default_msg_cleanup
;
1554 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1555 strbuf_stripspace(msg
,
1556 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1557 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1558 res
= 1; /* run 'git commit' to display error message */
1562 if (opts
->committer_date_is_author_date
) {
1563 struct ident_split id
;
1564 struct strbuf date
= STRBUF_INIT
;
1566 if (!opts
->ignore_date
) {
1567 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1568 res
= error(_("invalid author identity '%s'"),
1572 if (!id
.date_begin
) {
1574 "corrupt author: missing date information"));
1577 strbuf_addf(&date
, "@%.*s %.*s",
1578 (int)(id
.date_end
- id
.date_begin
),
1580 (int)(id
.tz_end
- id
.tz_begin
),
1585 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1586 getenv("GIT_COMMITTER_EMAIL"),
1587 WANT_COMMITTER_IDENT
,
1588 opts
->ignore_date
? NULL
: date
.buf
,
1590 strbuf_release(&date
);
1595 if (opts
->ignore_date
) {
1596 struct ident_split id
;
1599 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1600 error(_("invalid author identity '%s'"), author
);
1603 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1604 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1605 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1611 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1612 author
, committer
, opts
->gpg_sign
, extra
)) {
1613 res
= error(_("failed to write commit object"));
1617 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1619 res
= error("%s", err
.buf
);
1623 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1624 if (flags
& AMEND_MSG
)
1625 commit_post_rewrite(r
, current_head
, oid
);
1628 free_commit_extra_headers(extra
);
1629 strbuf_release(&err
);
1630 strbuf_release(&commit_msg
);
1636 static int write_rebase_head(struct object_id
*oid
)
1638 if (update_ref("rebase", "REBASE_HEAD", oid
,
1639 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1640 return error(_("could not update %s"), "REBASE_HEAD");
1645 static int do_commit(struct repository
*r
,
1646 const char *msg_file
, const char *author
,
1647 struct replay_opts
*opts
, unsigned int flags
,
1648 struct object_id
*oid
)
1652 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1653 struct object_id oid
;
1654 struct strbuf sb
= STRBUF_INIT
;
1656 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1657 return error_errno(_("unable to read commit message "
1661 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1662 author
, opts
, flags
, &oid
);
1663 strbuf_release(&sb
);
1665 refs_delete_ref(get_main_ref_store(r
), "",
1666 "CHERRY_PICK_HEAD", NULL
, 0);
1667 unlink(git_path_merge_msg(r
));
1668 if (!is_rebase_i(opts
))
1669 print_commit_summary(r
, NULL
, &oid
,
1670 SUMMARY_SHOW_AUTHOR_DATE
);
1675 if (is_rebase_i(opts
) && oid
)
1676 if (write_rebase_head(oid
))
1678 return run_git_commit(msg_file
, opts
, flags
);
1684 static int is_original_commit_empty(struct commit
*commit
)
1686 const struct object_id
*ptree_oid
;
1688 if (repo_parse_commit(the_repository
, commit
))
1689 return error(_("could not parse commit %s"),
1690 oid_to_hex(&commit
->object
.oid
));
1691 if (commit
->parents
) {
1692 struct commit
*parent
= commit
->parents
->item
;
1693 if (repo_parse_commit(the_repository
, parent
))
1694 return error(_("could not parse parent commit %s"),
1695 oid_to_hex(&parent
->object
.oid
));
1696 ptree_oid
= get_commit_tree_oid(parent
);
1698 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1701 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1705 * Should empty commits be allowed? Return status:
1706 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1707 * 0: Halt on empty commit
1708 * 1: Allow empty commit
1709 * 2: Drop empty commit
1711 static int allow_empty(struct repository
*r
,
1712 struct replay_opts
*opts
,
1713 struct commit
*commit
)
1715 int index_unchanged
, originally_empty
;
1720 * (1) we do not allow empty at all and error out.
1722 * (2) we allow ones that were initially empty, and
1723 * just drop the ones that become empty
1725 * (3) we allow ones that were initially empty, but
1726 * halt for the ones that become empty;
1728 * (4) we allow both.
1730 if (!opts
->allow_empty
)
1731 return 0; /* let "git commit" barf as necessary */
1733 index_unchanged
= is_index_unchanged(r
);
1734 if (index_unchanged
< 0)
1735 return index_unchanged
;
1736 if (!index_unchanged
)
1737 return 0; /* we do not have to say --allow-empty */
1739 if (opts
->keep_redundant_commits
)
1742 originally_empty
= is_original_commit_empty(commit
);
1743 if (originally_empty
< 0)
1744 return originally_empty
;
1745 if (originally_empty
)
1747 else if (opts
->drop_redundant_commits
)
1756 } todo_command_info
[] = {
1757 [TODO_PICK
] = { 'p', "pick" },
1758 [TODO_REVERT
] = { 0, "revert" },
1759 [TODO_EDIT
] = { 'e', "edit" },
1760 [TODO_REWORD
] = { 'r', "reword" },
1761 [TODO_FIXUP
] = { 'f', "fixup" },
1762 [TODO_SQUASH
] = { 's', "squash" },
1763 [TODO_EXEC
] = { 'x', "exec" },
1764 [TODO_BREAK
] = { 'b', "break" },
1765 [TODO_LABEL
] = { 'l', "label" },
1766 [TODO_RESET
] = { 't', "reset" },
1767 [TODO_MERGE
] = { 'm', "merge" },
1768 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1769 [TODO_NOOP
] = { 0, "noop" },
1770 [TODO_DROP
] = { 'd', "drop" },
1771 [TODO_COMMENT
] = { 0, NULL
},
1774 static const char *command_to_string(const enum todo_command command
)
1776 if (command
< TODO_COMMENT
)
1777 return todo_command_info
[command
].str
;
1778 die(_("unknown command: %d"), command
);
1781 static char command_to_char(const enum todo_command command
)
1783 if (command
< TODO_COMMENT
)
1784 return todo_command_info
[command
].c
;
1785 return comment_line_char
;
1788 static int is_noop(const enum todo_command command
)
1790 return TODO_NOOP
<= command
;
1793 static int is_fixup(enum todo_command command
)
1795 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1798 /* Does this command create a (non-merge) commit? */
1799 static int is_pick_or_similar(enum todo_command command
)
1814 enum todo_item_flags
{
1815 TODO_EDIT_MERGE_MSG
= (1 << 0),
1816 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1817 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1820 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1821 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1822 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1823 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1824 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1826 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1828 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1829 (flag
& TODO_EDIT_FIXUP_MSG
));
1833 * Wrapper around strbuf_add_commented_lines() which avoids double
1834 * commenting commit subjects.
1836 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1838 const char *s
= str
;
1839 while (len
> 0 && s
[0] == comment_line_char
) {
1841 const char *n
= memchr(s
, '\n', len
);
1846 strbuf_add(buf
, s
, count
);
1850 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1853 /* Does the current fixup chain contain a squash command? */
1854 static int seen_squash(struct replay_opts
*opts
)
1856 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1857 strstr(opts
->current_fixups
.buf
, "\nsquash");
1860 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1862 strbuf_setlen(buf1
, 2);
1863 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1864 strbuf_addch(buf1
, '\n');
1865 strbuf_setlen(buf2
, 2);
1866 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1867 strbuf_addch(buf2
, '\n');
1871 * Comment out any un-commented commit messages, updating the message comments
1872 * to say they will be skipped but do not comment out the empty lines that
1873 * surround commit messages and their comments.
1875 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1877 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1878 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1879 const char *s
, *start
;
1881 size_t orig_msg_len
;
1884 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1885 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1886 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1890 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1892 * Copy the last message, preserving the blank line
1893 * preceding the current line
1895 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1896 copy_lines(msg
, start
, s
- start
- off
);
1898 strbuf_addch(msg
, '\n');
1900 * The next message needs to be commented out but the
1901 * message header is already commented out so just copy
1902 * it and the blank line that follows it.
1904 strbuf_addbuf(msg
, &buf2
);
1906 strbuf_addch(msg
, *next
++);
1908 copy_lines
= add_commented_lines
;
1909 update_comment_bufs(&buf1
, &buf2
, ++i
);
1910 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1911 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1912 copy_lines(msg
, start
, s
- start
- off
);
1915 copy_lines
= strbuf_add
;
1916 update_comment_bufs(&buf1
, &buf2
, ++i
);
1918 s
= strchr(s
, '\n');
1923 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1925 strbuf_release(&buf1
);
1926 strbuf_release(&buf2
);
1929 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1930 enum todo_command command
, struct replay_opts
*opts
,
1933 const char *fixup_msg
;
1934 size_t commented_len
= 0, fixup_off
;
1936 * amend is non-interactive and not normally used with fixup!
1937 * or squash! commits, so only comment out those subjects when
1938 * squashing commit messages.
1940 if (starts_with(body
, "amend!") ||
1941 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1942 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1943 commented_len
= commit_subject_length(body
);
1945 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1946 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1947 ++opts
->current_fixup_count
+ 1);
1948 strbuf_addstr(buf
, "\n\n");
1949 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1950 /* buf->buf may be reallocated so store an offset into the buffer */
1951 fixup_off
= buf
->len
;
1952 strbuf_addstr(buf
, body
+ commented_len
);
1954 /* fixup -C after squash behaves like squash */
1955 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1957 * We're replacing the commit message so we need to
1958 * append the Signed-off-by: trailer if the user
1959 * requested '--signoff'.
1962 append_signoff(buf
, 0, 0);
1964 if ((command
== TODO_FIXUP
) &&
1965 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1966 (file_exists(rebase_path_fixup_msg()) ||
1967 !file_exists(rebase_path_squash_msg()))) {
1968 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1969 if (write_message(fixup_msg
, strlen(fixup_msg
),
1970 rebase_path_fixup_msg(), 0) < 0)
1971 return error(_("cannot write '%s'"),
1972 rebase_path_fixup_msg());
1974 unlink(rebase_path_fixup_msg());
1977 unlink(rebase_path_fixup_msg());
1983 static int update_squash_messages(struct repository
*r
,
1984 enum todo_command command
,
1985 struct commit
*commit
,
1986 struct replay_opts
*opts
,
1989 struct strbuf buf
= STRBUF_INIT
;
1991 const char *message
, *body
;
1992 const char *encoding
= get_commit_output_encoding();
1994 if (opts
->current_fixup_count
> 0) {
1995 struct strbuf header
= STRBUF_INIT
;
1998 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
1999 return error(_("could not read '%s'"),
2000 rebase_path_squash_msg());
2002 eol
= buf
.buf
[0] != comment_line_char
?
2003 buf
.buf
: strchrnul(buf
.buf
, '\n');
2005 strbuf_addf(&header
, "%c ", comment_line_char
);
2006 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2007 opts
->current_fixup_count
+ 2);
2008 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2009 strbuf_release(&header
);
2010 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2011 update_squash_message_for_fixup(&buf
);
2013 struct object_id head
;
2014 struct commit
*head_commit
;
2015 const char *head_message
, *body
;
2017 if (repo_get_oid(r
, "HEAD", &head
))
2018 return error(_("need a HEAD to fixup"));
2019 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2020 return error(_("could not read HEAD"));
2021 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2023 return error(_("could not read HEAD's commit message"));
2025 find_commit_subject(head_message
, &body
);
2026 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2027 rebase_path_fixup_msg(), 0) < 0) {
2028 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2029 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2031 strbuf_addf(&buf
, "%c ", comment_line_char
);
2032 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2033 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2034 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2035 _(skip_first_commit_msg_str
) :
2036 _(first_commit_msg_str
));
2037 strbuf_addstr(&buf
, "\n\n");
2038 if (is_fixup_flag(command
, flag
))
2039 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2042 strbuf_addstr(&buf
, body
);
2044 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2047 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2048 return error(_("could not read commit message of %s"),
2049 oid_to_hex(&commit
->object
.oid
));
2050 find_commit_subject(message
, &body
);
2052 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2053 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2054 } else if (command
== TODO_FIXUP
) {
2055 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2056 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2057 ++opts
->current_fixup_count
+ 1);
2058 strbuf_addstr(&buf
, "\n\n");
2059 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
;
5344 static const char *label_oid(struct object_id
*oid
, const char *label
,
5345 struct label_state
*state
)
5347 struct labels_entry
*labels_entry
;
5348 struct string_entry
*string_entry
;
5349 struct object_id dummy
;
5352 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5354 return string_entry
->string
;
5357 * For "uninteresting" commits, i.e. commits that are not to be
5358 * rebased, and which can therefore not be labeled, we use a unique
5359 * abbreviation of the commit name. This is slightly more complicated
5360 * than calling repo_find_unique_abbrev() because we also need to make
5361 * sure that the abbreviation does not conflict with any other
5364 * We disallow "interesting" commits to be labeled by a string that
5365 * is a valid full-length hash, to ensure that we always can find an
5366 * abbreviation for any uninteresting commit's names that does not
5367 * clash with any other label.
5369 strbuf_reset(&state
->buf
);
5373 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5374 label
= p
= state
->buf
.buf
;
5376 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5380 * We may need to extend the abbreviated hash so that there is
5381 * no conflicting label.
5383 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5384 size_t i
= strlen(p
) + 1;
5386 oid_to_hex_r(p
, oid
);
5387 for (; i
< the_hash_algo
->hexsz
; i
++) {
5390 if (!hashmap_get_from_hash(&state
->labels
,
5397 struct strbuf
*buf
= &state
->buf
;
5400 * Sanitize labels by replacing non-alpha-numeric characters
5401 * (including white-space ones) by dashes, as they might be
5402 * illegal in file names (and hence in ref names).
5404 * Note that we retain non-ASCII UTF-8 characters (identified
5405 * via the most significant bit). They should be all acceptable
5406 * in file names. We do not validate the UTF-8 here, that's not
5407 * the job of this function.
5409 for (; *label
; label
++)
5410 if ((*label
& 0x80) || isalnum(*label
))
5411 strbuf_addch(buf
, *label
);
5412 /* avoid leading dash and double-dashes */
5413 else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5414 strbuf_addch(buf
, '-');
5416 strbuf_addstr(buf
, "rev-");
5417 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5421 if ((buf
->len
== the_hash_algo
->hexsz
&&
5422 !get_oid_hex(label
, &dummy
)) ||
5423 (buf
->len
== 1 && *label
== '#') ||
5424 hashmap_get_from_hash(&state
->labels
,
5425 strihash(label
), label
)) {
5427 * If the label already exists, or if the label is a
5428 * valid full OID, or the label is a '#' (which we use
5429 * as a separator between merge heads and oneline), we
5430 * append a dash and a number to make it unique.
5432 size_t len
= buf
->len
;
5434 for (i
= 2; ; i
++) {
5435 strbuf_setlen(buf
, len
);
5436 strbuf_addf(buf
, "-%d", i
);
5437 if (!hashmap_get_from_hash(&state
->labels
,
5447 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5448 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5449 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5451 FLEX_ALLOC_STR(string_entry
, string
, label
);
5452 oidcpy(&string_entry
->entry
.oid
, oid
);
5453 oidmap_put(&state
->commit2label
, string_entry
);
5455 return string_entry
->string
;
5458 static int make_script_with_merges(struct pretty_print_context
*pp
,
5459 struct rev_info
*revs
, struct strbuf
*out
,
5462 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5463 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5464 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5465 int skipped_commit
= 0;
5466 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5467 struct strbuf label
= STRBUF_INIT
;
5468 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5469 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5470 struct commit
*commit
;
5471 struct oidmap commit2todo
= OIDMAP_INIT
;
5472 struct string_entry
*entry
;
5473 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5474 shown
= OIDSET_INIT
;
5475 struct label_state state
= { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
};
5477 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5478 const char *cmd_pick
= abbr
? "p" : "pick",
5479 *cmd_label
= abbr
? "l" : "label",
5480 *cmd_reset
= abbr
? "t" : "reset",
5481 *cmd_merge
= abbr
? "m" : "merge";
5483 oidmap_init(&commit2todo
, 0);
5484 oidmap_init(&state
.commit2label
, 0);
5485 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5486 strbuf_init(&state
.buf
, 32);
5488 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5489 struct labels_entry
*onto_label_entry
;
5490 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5491 FLEX_ALLOC_STR(entry
, string
, "onto");
5492 oidcpy(&entry
->entry
.oid
, oid
);
5493 oidmap_put(&state
.commit2label
, entry
);
5495 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5496 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5497 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5502 * - get onelines for all commits
5503 * - gather all branch tips (i.e. 2nd or later parents of merges)
5504 * - label all branch tips
5506 while ((commit
= get_revision(revs
))) {
5507 struct commit_list
*to_merge
;
5508 const char *p1
, *p2
;
5509 struct object_id
*oid
;
5512 tail
= &commit_list_insert(commit
, tail
)->next
;
5513 oidset_insert(&interesting
, &commit
->object
.oid
);
5515 is_empty
= is_original_commit_empty(commit
);
5516 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5517 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5518 warning(_("skipped previously applied commit %s"),
5519 short_commit_name(commit
));
5523 if (is_empty
&& !keep_empty
)
5526 strbuf_reset(&oneline
);
5527 pretty_print_commit(pp
, commit
, &oneline
);
5529 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5531 /* non-merge commit: easy case */
5533 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5534 oid_to_hex(&commit
->object
.oid
),
5537 strbuf_addf(&buf
, " %c empty",
5540 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5541 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5542 oidmap_put(&commit2todo
, entry
);
5547 /* Create a label */
5548 strbuf_reset(&label
);
5549 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5550 (p1
= strchr(p1
, '\'')) &&
5551 (p2
= strchr(++p1
, '\'')))
5552 strbuf_add(&label
, p1
, p2
- p1
);
5553 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5555 (p1
= strstr(p1
, " from ")))
5556 strbuf_addstr(&label
, p1
+ strlen(" from "));
5558 strbuf_addbuf(&label
, &oneline
);
5561 strbuf_addf(&buf
, "%s -C %s",
5562 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5564 /* label the tips of merged branches */
5565 for (; to_merge
; to_merge
= to_merge
->next
) {
5566 oid
= &to_merge
->item
->object
.oid
;
5567 strbuf_addch(&buf
, ' ');
5569 if (!oidset_contains(&interesting
, oid
)) {
5570 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5575 tips_tail
= &commit_list_insert(to_merge
->item
,
5578 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5580 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5582 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5583 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5584 oidmap_put(&commit2todo
, entry
);
5587 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5588 _("use --reapply-cherry-picks to include skipped commits"));
5592 * - label branch points
5593 * - add HEAD to the branch tips
5595 for (iter
= commits
; iter
; iter
= iter
->next
) {
5596 struct commit_list
*parent
= iter
->item
->parents
;
5597 for (; parent
; parent
= parent
->next
) {
5598 struct object_id
*oid
= &parent
->item
->object
.oid
;
5599 if (!oidset_contains(&interesting
, oid
))
5601 if (oidset_insert(&child_seen
, oid
))
5602 label_oid(oid
, "branch-point", &state
);
5605 /* Add HEAD as implicit "tip of branch" */
5607 tips_tail
= &commit_list_insert(iter
->item
,
5612 * Third phase: output the todo list. This is a bit tricky, as we
5613 * want to avoid jumping back and forth between revisions. To
5614 * accomplish that goal, we walk backwards from the branch tips,
5615 * gathering commits not yet shown, reversing the list on the fly,
5616 * then outputting that list (labeling revisions as needed).
5618 strbuf_addf(out
, "%s onto\n", cmd_label
);
5619 for (iter
= tips
; iter
; iter
= iter
->next
) {
5620 struct commit_list
*list
= NULL
, *iter2
;
5622 commit
= iter
->item
;
5623 if (oidset_contains(&shown
, &commit
->object
.oid
))
5625 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5628 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5630 strbuf_addch(out
, '\n');
5632 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5633 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5634 commit_list_insert(commit
, &list
);
5635 if (!commit
->parents
) {
5639 commit
= commit
->parents
->item
;
5643 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5644 rebase_cousins
|| root_with_onto
?
5645 "onto" : "[new root]");
5647 const char *to
= NULL
;
5649 entry
= oidmap_get(&state
.commit2label
,
5650 &commit
->object
.oid
);
5653 else if (!rebase_cousins
)
5654 to
= label_oid(&commit
->object
.oid
, NULL
,
5657 if (!to
|| !strcmp(to
, "onto"))
5658 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5660 strbuf_reset(&oneline
);
5661 pretty_print_commit(pp
, commit
, &oneline
);
5662 strbuf_addf(out
, "%s %s # %s\n",
5663 cmd_reset
, to
, oneline
.buf
);
5667 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5668 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5669 entry
= oidmap_get(&commit2todo
, oid
);
5670 /* only show if not already upstream */
5672 strbuf_addf(out
, "%s\n", entry
->string
);
5673 entry
= oidmap_get(&state
.commit2label
, oid
);
5675 strbuf_addf(out
, "%s %s\n",
5676 cmd_label
, entry
->string
);
5677 oidset_insert(&shown
, oid
);
5680 free_commit_list(list
);
5683 free_commit_list(commits
);
5684 free_commit_list(tips
);
5686 strbuf_release(&label
);
5687 strbuf_release(&oneline
);
5688 strbuf_release(&buf
);
5690 oidmap_free(&commit2todo
, 1);
5691 oidmap_free(&state
.commit2label
, 1);
5692 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5693 strbuf_release(&state
.buf
);
5698 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5699 const char **argv
, unsigned flags
)
5701 char *format
= NULL
;
5702 struct pretty_print_context pp
= {0};
5703 struct rev_info revs
;
5704 struct commit
*commit
;
5705 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5706 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5707 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5708 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5709 int skipped_commit
= 0;
5712 repo_init_revisions(r
, &revs
, NULL
);
5713 revs
.verbose_header
= 1;
5715 revs
.max_parents
= 1;
5716 revs
.cherry_mark
= !reapply_cherry_picks
;
5719 revs
.right_only
= 1;
5720 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5721 revs
.topo_order
= 1;
5723 revs
.pretty_given
= 1;
5724 git_config_get_string("rebase.instructionFormat", &format
);
5725 if (!format
|| !*format
) {
5727 format
= xstrdup("%s");
5729 get_commit_format(format
, &revs
);
5731 pp
.fmt
= revs
.commit_format
;
5732 pp
.output_encoding
= get_log_output_encoding();
5734 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5735 ret
= error(_("make_script: unhandled options"));
5739 if (prepare_revision_walk(&revs
) < 0) {
5740 ret
= error(_("make_script: error preparing revisions"));
5744 if (rebase_merges
) {
5745 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5749 while ((commit
= get_revision(&revs
))) {
5750 int is_empty
= is_original_commit_empty(commit
);
5752 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5753 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5754 warning(_("skipped previously applied commit %s"),
5755 short_commit_name(commit
));
5759 if (is_empty
&& !keep_empty
)
5761 strbuf_addf(out
, "%s %s ", insn
,
5762 oid_to_hex(&commit
->object
.oid
));
5763 pretty_print_commit(&pp
, commit
, out
);
5765 strbuf_addf(out
, " %c empty", comment_line_char
);
5766 strbuf_addch(out
, '\n');
5769 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5770 _("use --reapply-cherry-picks to include skipped commits"));
5772 release_revisions(&revs
);
5777 * Add commands after pick and (series of) squash/fixup commands
5780 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5781 struct string_list
*commands
)
5783 struct strbuf
*buf
= &todo_list
->buf
;
5784 size_t base_offset
= buf
->len
;
5785 int i
, insert
, nr
= 0, alloc
= 0;
5786 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5788 CALLOC_ARRAY(base_items
, commands
->nr
);
5789 for (i
= 0; i
< commands
->nr
; i
++) {
5790 size_t command_len
= strlen(commands
->items
[i
].string
);
5792 strbuf_addstr(buf
, commands
->items
[i
].string
);
5793 strbuf_addch(buf
, '\n');
5795 base_items
[i
].command
= TODO_EXEC
;
5796 base_items
[i
].offset_in_buf
= base_offset
;
5797 base_items
[i
].arg_offset
= base_offset
;
5798 base_items
[i
].arg_len
= command_len
;
5800 base_offset
+= command_len
+ 1;
5804 * Insert <commands> after every pick. Here, fixup/squash chains
5805 * are considered part of the pick, so we insert the commands *after*
5806 * those chains if there are any.
5808 * As we insert the exec commands immediately after rearranging
5809 * any fixups and before the user edits the list, a fixup chain
5810 * can never contain comments (any comments are empty picks that
5811 * have been commented out because the user did not specify
5812 * --keep-empty). So, it is safe to insert an exec command
5813 * without looking at the command following a comment.
5816 for (i
= 0; i
< todo_list
->nr
; i
++) {
5817 enum todo_command command
= todo_list
->items
[i
].command
;
5818 if (insert
&& !is_fixup(command
)) {
5819 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5820 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5826 ALLOC_GROW(items
, nr
+ 1, alloc
);
5827 items
[nr
++] = todo_list
->items
[i
];
5829 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5833 /* insert or append final <commands> */
5835 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5836 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5841 FREE_AND_NULL(todo_list
->items
);
5842 todo_list
->items
= items
;
5844 todo_list
->alloc
= alloc
;
5847 static void todo_list_to_strbuf(struct repository
*r
, struct todo_list
*todo_list
,
5848 struct strbuf
*buf
, int num
, unsigned flags
)
5850 struct todo_item
*item
;
5851 int i
, max
= todo_list
->nr
;
5853 if (num
> 0 && num
< max
)
5856 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5859 /* if the item is not a command write it and continue */
5860 if (item
->command
>= TODO_COMMENT
) {
5861 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5862 todo_item_get_arg(todo_list
, item
));
5866 /* add command to the buffer */
5867 cmd
= command_to_char(item
->command
);
5868 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5869 strbuf_addch(buf
, cmd
);
5871 strbuf_addstr(buf
, command_to_string(item
->command
));
5875 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5876 short_commit_name(item
->commit
) :
5877 oid_to_hex(&item
->commit
->object
.oid
);
5879 if (item
->command
== TODO_FIXUP
) {
5880 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
5881 strbuf_addstr(buf
, " -c");
5882 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
5883 strbuf_addstr(buf
, " -C");
5887 if (item
->command
== TODO_MERGE
) {
5888 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5889 strbuf_addstr(buf
, " -c");
5891 strbuf_addstr(buf
, " -C");
5894 strbuf_addf(buf
, " %s", oid
);
5897 /* add all the rest */
5899 strbuf_addch(buf
, '\n');
5901 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5902 todo_item_get_arg(todo_list
, item
));
5906 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5907 const char *file
, const char *shortrevisions
,
5908 const char *shortonto
, int num
, unsigned flags
)
5911 struct strbuf buf
= STRBUF_INIT
;
5913 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5914 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5915 append_todo_help(count_commands(todo_list
),
5916 shortrevisions
, shortonto
, &buf
);
5918 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5919 strbuf_release(&buf
);
5924 /* skip picking commits whose parents are unchanged */
5925 static int skip_unnecessary_picks(struct repository
*r
,
5926 struct todo_list
*todo_list
,
5927 struct object_id
*base_oid
)
5929 struct object_id
*parent_oid
;
5932 for (i
= 0; i
< todo_list
->nr
; i
++) {
5933 struct todo_item
*item
= todo_list
->items
+ i
;
5935 if (item
->command
>= TODO_NOOP
)
5937 if (item
->command
!= TODO_PICK
)
5939 if (repo_parse_commit(r
, item
->commit
)) {
5940 return error(_("could not parse commit '%s'"),
5941 oid_to_hex(&item
->commit
->object
.oid
));
5943 if (!item
->commit
->parents
)
5944 break; /* root commit */
5945 if (item
->commit
->parents
->next
)
5946 break; /* merge commit */
5947 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
5948 if (!oideq(parent_oid
, base_oid
))
5950 oidcpy(base_oid
, &item
->commit
->object
.oid
);
5953 const char *done_path
= rebase_path_done();
5955 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
5956 error_errno(_("could not write to '%s'"), done_path
);
5960 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
5962 todo_list
->current
= 0;
5963 todo_list
->done_nr
+= i
;
5965 if (is_fixup(peek_command(todo_list
, 0)))
5966 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
5972 struct todo_add_branch_context
{
5973 struct todo_item
*items
;
5977 struct commit
*commit
;
5978 struct string_list refs_to_oids
;
5981 static int add_decorations_to_list(const struct commit
*commit
,
5982 struct todo_add_branch_context
*ctx
)
5984 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
5985 const char *head_ref
= resolve_ref_unsafe("HEAD",
5986 RESOLVE_REF_READING
,
5990 while (decoration
) {
5991 struct todo_item
*item
;
5993 size_t base_offset
= ctx
->buf
->len
;
5996 * If the branch is the current HEAD, then it will be
5997 * updated by the default rebase behavior.
5999 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6000 decoration
= decoration
->next
;
6004 ALLOC_GROW(ctx
->items
,
6007 item
= &ctx
->items
[ctx
->items_nr
];
6008 memset(item
, 0, sizeof(*item
));
6010 /* If the branch is checked out, then leave a comment instead. */
6011 if ((path
= branch_checked_out(decoration
->name
))) {
6012 item
->command
= TODO_COMMENT
;
6013 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6014 decoration
->name
, path
);
6016 struct string_list_item
*sti
;
6017 item
->command
= TODO_UPDATE_REF
;
6018 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6020 sti
= string_list_insert(&ctx
->refs_to_oids
,
6022 sti
->util
= init_update_ref_record(decoration
->name
);
6025 item
->offset_in_buf
= base_offset
;
6026 item
->arg_offset
= base_offset
;
6027 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6030 decoration
= decoration
->next
;
6037 * For each 'pick' command, find out if the commit has a decoration in
6038 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6040 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6043 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6044 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6045 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6046 struct decoration_filter decoration_filter
= {
6047 .include_ref_pattern
= &decorate_refs_include
,
6048 .exclude_ref_pattern
= &decorate_refs_exclude
,
6049 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6051 struct todo_add_branch_context ctx
= {
6052 .buf
= &todo_list
->buf
,
6053 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6056 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6057 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6059 string_list_append(&decorate_refs_include
, "refs/heads/");
6060 load_ref_decorations(&decoration_filter
, 0);
6062 for (i
= 0; i
< todo_list
->nr
; ) {
6063 struct todo_item
*item
= &todo_list
->items
[i
];
6065 /* insert ith item into new list */
6066 ALLOC_GROW(ctx
.items
,
6070 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6073 ctx
.commit
= item
->commit
;
6074 add_decorations_to_list(item
->commit
, &ctx
);
6078 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6080 string_list_clear(&ctx
.refs_to_oids
, 1);
6083 /* we failed, so clean up the new list. */
6088 free(todo_list
->items
);
6089 todo_list
->items
= ctx
.items
;
6090 todo_list
->nr
= ctx
.items_nr
;
6091 todo_list
->alloc
= ctx
.items_alloc
;
6096 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6097 const char *shortrevisions
, const char *onto_name
,
6098 struct commit
*onto
, const struct object_id
*orig_head
,
6099 struct string_list
*commands
, unsigned autosquash
,
6100 unsigned update_refs
,
6101 struct todo_list
*todo_list
)
6103 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6104 const char *todo_file
= rebase_path_todo();
6105 struct todo_list new_todo
= TODO_LIST_INIT
;
6106 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6107 struct object_id oid
= onto
->object
.oid
;
6110 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6113 if (buf
->len
== 0) {
6114 struct todo_item
*item
= append_new_todo(todo_list
);
6115 item
->command
= TODO_NOOP
;
6116 item
->commit
= NULL
;
6117 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6120 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6123 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6127 todo_list_add_exec_commands(todo_list
, commands
);
6129 if (count_commands(todo_list
) == 0) {
6130 apply_autostash(rebase_path_autostash());
6131 sequencer_remove_state(opts
);
6133 return error(_("nothing to do"));
6136 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6140 else if (res
== -2) {
6141 apply_autostash(rebase_path_autostash());
6142 sequencer_remove_state(opts
);
6145 } else if (res
== -3) {
6146 apply_autostash(rebase_path_autostash());
6147 sequencer_remove_state(opts
);
6148 todo_list_release(&new_todo
);
6150 return error(_("nothing to do"));
6151 } else if (res
== -4) {
6152 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6153 todo_list_release(&new_todo
);
6158 /* Expand the commit IDs */
6159 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6160 strbuf_swap(&new_todo
.buf
, &buf2
);
6161 strbuf_release(&buf2
);
6162 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6163 new_todo
.total_nr
= 0;
6164 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6165 BUG("invalid todo list after expanding IDs:\n%s",
6168 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6169 todo_list_release(&new_todo
);
6170 return error(_("could not skip unnecessary pick commands"));
6173 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6174 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6175 todo_list_release(&new_todo
);
6176 return error_errno(_("could not write '%s'"), todo_file
);
6181 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6184 if (require_clean_work_tree(r
, "rebase", "", 1, 1))
6187 todo_list_write_total_nr(&new_todo
);
6188 res
= pick_commits(r
, &new_todo
, opts
);
6191 todo_list_release(&new_todo
);
6196 struct subject2item_entry
{
6197 struct hashmap_entry entry
;
6199 char subject
[FLEX_ARRAY
];
6202 static int subject2item_cmp(const void *fndata UNUSED
,
6203 const struct hashmap_entry
*eptr
,
6204 const struct hashmap_entry
*entry_or_key
,
6207 const struct subject2item_entry
*a
, *b
;
6209 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6210 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6212 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6215 define_commit_slab(commit_todo_item
, struct todo_item
*);
6217 static int skip_fixupish(const char *subject
, const char **p
) {
6218 return skip_prefix(subject
, "fixup! ", p
) ||
6219 skip_prefix(subject
, "amend! ", p
) ||
6220 skip_prefix(subject
, "squash! ", p
);
6224 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6225 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6226 * after the former, and change "pick" to "fixup"/"squash".
6228 * Note that if the config has specified a custom instruction format, each log
6229 * message will have to be retrieved from the commit (as the oneline in the
6230 * script cannot be trusted) in order to normalize the autosquash arrangement.
6232 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6234 struct hashmap subject2item
;
6235 int rearranged
= 0, *next
, *tail
, i
, nr
= 0, alloc
= 0;
6237 struct commit_todo_item commit_todo
;
6238 struct todo_item
*items
= NULL
;
6240 init_commit_todo_item(&commit_todo
);
6242 * The hashmap maps onelines to the respective todo list index.
6244 * If any items need to be rearranged, the next[i] value will indicate
6245 * which item was moved directly after the i'th.
6247 * In that case, last[i] will indicate the index of the latest item to
6248 * be moved to appear after the i'th.
6250 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6251 ALLOC_ARRAY(next
, todo_list
->nr
);
6252 ALLOC_ARRAY(tail
, todo_list
->nr
);
6253 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6254 for (i
= 0; i
< todo_list
->nr
; i
++) {
6255 struct strbuf buf
= STRBUF_INIT
;
6256 struct todo_item
*item
= todo_list
->items
+ i
;
6257 const char *commit_buffer
, *subject
, *p
;
6260 struct subject2item_entry
*entry
;
6262 next
[i
] = tail
[i
] = -1;
6263 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6268 if (is_fixup(item
->command
)) {
6269 clear_commit_todo_item(&commit_todo
);
6270 return error(_("the script was already rearranged."));
6273 repo_parse_commit(the_repository
, item
->commit
);
6274 commit_buffer
= repo_logmsg_reencode(the_repository
,
6277 find_commit_subject(commit_buffer
, &subject
);
6278 format_subject(&buf
, subject
, " ");
6279 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6280 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6282 if (skip_fixupish(subject
, &p
)) {
6283 struct commit
*commit2
;
6288 if (!skip_fixupish(p
, &p
))
6292 entry
= hashmap_get_entry_from_hash(&subject2item
,
6294 struct subject2item_entry
,
6297 /* found by title */
6299 else if (!strchr(p
, ' ') &&
6301 lookup_commit_reference_by_name(p
)) &&
6302 *commit_todo_item_at(&commit_todo
, commit2
))
6303 /* found by commit name */
6304 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6307 /* copy can be a prefix of the commit subject */
6308 for (i2
= 0; i2
< i
; i2
++)
6310 starts_with(subjects
[i2
], p
))
6318 if (starts_with(subject
, "fixup!")) {
6319 todo_list
->items
[i
].command
= TODO_FIXUP
;
6320 } else if (starts_with(subject
, "amend!")) {
6321 todo_list
->items
[i
].command
= TODO_FIXUP
;
6322 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6324 todo_list
->items
[i
].command
= TODO_SQUASH
;
6330 next
[i
] = next
[tail
[i2
]];
6334 } else if (!hashmap_get_from_hash(&subject2item
,
6335 strhash(subject
), subject
)) {
6336 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6338 hashmap_entry_init(&entry
->entry
,
6339 strhash(entry
->subject
));
6340 hashmap_put(&subject2item
, &entry
->entry
);
6343 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6347 for (i
= 0; i
< todo_list
->nr
; i
++) {
6348 enum todo_command command
= todo_list
->items
[i
].command
;
6352 * Initially, all commands are 'pick's. If it is a
6353 * fixup or a squash now, we have rearranged it.
6355 if (is_fixup(command
))
6359 ALLOC_GROW(items
, nr
+ 1, alloc
);
6360 items
[nr
++] = todo_list
->items
[cur
];
6365 FREE_AND_NULL(todo_list
->items
);
6366 todo_list
->items
= items
;
6368 todo_list
->alloc
= alloc
;
6373 for (i
= 0; i
< todo_list
->nr
; i
++)
6376 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6378 clear_commit_todo_item(&commit_todo
);
6383 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6385 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6386 struct object_id cherry_pick_head
, rebase_head
;
6388 if (file_exists(git_path_seq_dir()))
6389 *whence
= FROM_CHERRY_PICK_MULTI
;
6390 if (file_exists(rebase_path()) &&
6391 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6392 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6393 oideq(&rebase_head
, &cherry_pick_head
))
6394 *whence
= FROM_REBASE_PICK
;
6396 *whence
= FROM_CHERRY_PICK_SINGLE
;
6404 int sequencer_get_update_refs_state(const char *wt_dir
,
6405 struct string_list
*refs
)
6409 struct strbuf ref
= STRBUF_INIT
;
6410 struct strbuf hash
= STRBUF_INIT
;
6411 struct update_ref_record
*rec
= NULL
;
6413 char *path
= rebase_path_update_refs(wt_dir
);
6415 fp
= fopen(path
, "r");
6419 while (strbuf_getline(&ref
, fp
) != EOF
) {
6420 struct string_list_item
*item
;
6422 CALLOC_ARRAY(rec
, 1);
6424 if (strbuf_getline(&hash
, fp
) == EOF
||
6425 get_oid_hex(hash
.buf
, &rec
->before
)) {
6426 warning(_("update-refs file at '%s' is invalid"),
6432 if (strbuf_getline(&hash
, fp
) == EOF
||
6433 get_oid_hex(hash
.buf
, &rec
->after
)) {
6434 warning(_("update-refs file at '%s' is invalid"),
6440 item
= string_list_insert(refs
, ref
.buf
);
6450 strbuf_release(&ref
);
6451 strbuf_release(&hash
);