1 #include "git-compat-util.h"
6 #include "environment.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
17 #include "sequencer.h"
19 #include "run-command.h"
23 #include "cache-tree.h"
29 #include "merge-ort.h"
30 #include "merge-ort-wrappers.h"
32 #include "sparse-index.h"
37 #include "wt-status.h"
39 #include "notes-utils.h"
41 #include "unpack-trees.h"
45 #include "commit-slab.h"
47 #include "commit-reach.h"
48 #include "rebase-interactive.h"
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
59 * Add some margin to stay clear from reaching `NAME_MAX`.
61 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
63 static const char sign_off_header
[] = "Signed-off-by: ";
64 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
66 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
68 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
70 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
71 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
72 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
73 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
75 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
82 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
83 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
85 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
92 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
94 * The file to keep track of how many commands were already processed (e.g.
97 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
102 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
107 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
116 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
124 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
129 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
135 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
144 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
146 * When we stop at a given patch via the "edit" command, this file contains
147 * the commit object name of the corresponding patch.
149 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
151 * For the post-rewrite hook, we make a list of rewritten commits and
152 * their new sha1s. The rewritten-pending list keeps the sha1s of
153 * commits that have been processed, but not committed yet,
154 * e.g. because they are waiting for a 'squash' command.
156 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
157 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
158 "rebase-merge/rewritten-pending")
161 * The path of the file containing the OID of the "squash onto" commit, i.e.
162 * the dummy commit used for `reset [new root]`.
164 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
167 * The path of the file listing refs that need to be deleted after the rebase
168 * finishes. This is used by the `label` command to record the need for cleanup.
170 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
173 * The update-refs file stores a list of refs that will be updated at the end
174 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
175 * update the OIDs for the refs in this file, but the refs are not updated
176 * until the end of the rebase sequence.
178 * rebase_path_update_refs() returns the path to this file for a given
179 * worktree directory. For the current worktree, pass the_repository->gitdir.
181 static char *rebase_path_update_refs(const char *wt_git_dir
)
183 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
187 * The following files are written by git-rebase just after parsing the
190 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
191 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
192 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
193 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
194 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
195 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
196 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
197 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
198 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
199 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
200 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
201 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
202 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
203 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
204 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
205 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
206 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
209 * A 'struct update_refs_record' represents a value in the update-refs
210 * list. We use a string_list to map refs to these (before, after) pairs.
212 struct update_ref_record
{
213 struct object_id before
;
214 struct object_id after
;
217 static struct update_ref_record
*init_update_ref_record(const char *ref
)
219 struct update_ref_record
*rec
;
221 CALLOC_ARRAY(rec
, 1);
223 oidcpy(&rec
->before
, null_oid());
224 oidcpy(&rec
->after
, null_oid());
226 /* This may fail, but that's fine, we will keep the null OID. */
227 read_ref(ref
, &rec
->before
);
232 static int git_sequencer_config(const char *k
, const char *v
,
233 const struct config_context
*ctx
, void *cb
)
235 struct replay_opts
*opts
= cb
;
238 if (!strcmp(k
, "commit.cleanup")) {
241 status
= git_config_string(&s
, k
, v
);
245 if (!strcmp(s
, "verbatim")) {
246 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
247 opts
->explicit_cleanup
= 1;
248 } else if (!strcmp(s
, "whitespace")) {
249 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
250 opts
->explicit_cleanup
= 1;
251 } else if (!strcmp(s
, "strip")) {
252 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
253 opts
->explicit_cleanup
= 1;
254 } else if (!strcmp(s
, "scissors")) {
255 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
256 opts
->explicit_cleanup
= 1;
258 warning(_("invalid commit message cleanup mode '%s'"),
266 if (!strcmp(k
, "commit.gpgsign")) {
267 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
271 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
272 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
275 * pull.twohead is allowed to be multi-valued; we only
276 * care about the first value.
278 char *tmp
= strchr(opts
->default_strategy
, ' ');
285 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
286 opts
->commit_use_reference
= git_config_bool(k
, v
);
288 return git_diff_basic_config(k
, v
, ctx
, NULL
);
291 void sequencer_init_config(struct replay_opts
*opts
)
293 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
294 git_config(git_sequencer_config
, opts
);
297 static inline int is_rebase_i(const struct replay_opts
*opts
)
299 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
302 static const char *get_dir(const struct replay_opts
*opts
)
304 if (is_rebase_i(opts
))
305 return rebase_path();
306 return git_path_seq_dir();
309 static const char *get_todo_path(const struct replay_opts
*opts
)
311 if (is_rebase_i(opts
))
312 return rebase_path_todo();
313 return git_path_todo_file();
317 * Returns 0 for non-conforming footer
318 * Returns 1 for conforming footer
319 * Returns 2 when sob exists within conforming footer
320 * Returns 3 when sob exists within conforming footer as last entry
322 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
323 size_t ignore_footer
)
325 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
326 struct trailer_info info
;
328 int found_sob
= 0, found_sob_last
= 0;
334 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
335 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
338 trailer_info_get(&info
, sb
->buf
, &opts
);
341 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
343 if (info
.trailer_start
== info
.trailer_end
)
346 for (i
= 0; i
< info
.trailer_nr
; i
++)
347 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
349 if (i
== info
.trailer_nr
- 1)
353 trailer_info_release(&info
);
362 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
364 static struct strbuf buf
= STRBUF_INIT
;
368 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
372 void replay_opts_release(struct replay_opts
*opts
)
374 free(opts
->gpg_sign
);
375 free(opts
->reflog_action
);
376 free(opts
->default_strategy
);
377 free(opts
->strategy
);
378 strvec_clear (&opts
->xopts
);
379 strbuf_release(&opts
->current_fixups
);
381 release_revisions(opts
->revs
);
385 int sequencer_remove_state(struct replay_opts
*opts
)
387 struct strbuf buf
= STRBUF_INIT
;
390 if (is_rebase_i(opts
) &&
391 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
394 char *eol
= strchr(p
, '\n');
397 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
398 warning(_("could not delete '%s'"), p
);
408 strbuf_addstr(&buf
, get_dir(opts
));
409 if (remove_dir_recursively(&buf
, 0))
410 ret
= error(_("could not remove '%s'"), buf
.buf
);
411 strbuf_release(&buf
);
416 static const char *action_name(const struct replay_opts
*opts
)
418 switch (opts
->action
) {
422 return N_("cherry-pick");
423 case REPLAY_INTERACTIVE_REBASE
:
426 die(_("unknown action: %d"), opts
->action
);
429 struct commit_message
{
436 static const char *short_commit_name(struct repository
*r
, struct commit
*commit
)
438 return repo_find_unique_abbrev(r
, &commit
->object
.oid
, DEFAULT_ABBREV
);
441 static int get_message(struct commit
*commit
, struct commit_message
*out
)
443 const char *abbrev
, *subject
;
446 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
447 get_commit_output_encoding());
448 abbrev
= short_commit_name(the_repository
, commit
);
450 subject_len
= find_commit_subject(out
->message
, &subject
);
452 out
->subject
= xmemdupz(subject
, subject_len
);
453 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
454 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
459 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
461 free(msg
->parent_label
);
464 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
467 static void print_advice(struct repository
*r
, int show_hint
,
468 struct replay_opts
*opts
)
470 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
475 * A conflict has occurred but the porcelain
476 * (typically rebase --interactive) wants to take care
477 * of the commit itself so remove CHERRY_PICK_HEAD
479 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
486 advise(_("after resolving the conflicts, mark the corrected paths\n"
487 "with 'git add <paths>' or 'git rm <paths>'"));
488 else if (opts
->action
== REPLAY_PICK
)
489 advise(_("After resolving the conflicts, mark them with\n"
490 "\"git add/rm <pathspec>\", then run\n"
491 "\"git cherry-pick --continue\".\n"
492 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
493 "To abort and get back to the state before \"git cherry-pick\",\n"
494 "run \"git cherry-pick --abort\"."));
495 else if (opts
->action
== REPLAY_REVERT
)
496 advise(_("After resolving the conflicts, mark them with\n"
497 "\"git add/rm <pathspec>\", then run\n"
498 "\"git revert --continue\".\n"
499 "You can instead skip this commit with \"git revert --skip\".\n"
500 "To abort and get back to the state before \"git revert\",\n"
501 "run \"git revert --abort\"."));
503 BUG("unexpected pick action in print_advice()");
507 static int write_message(const void *buf
, size_t len
, const char *filename
,
510 struct lock_file msg_file
= LOCK_INIT
;
512 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
514 return error_errno(_("could not lock '%s'"), filename
);
515 if (write_in_full(msg_fd
, buf
, len
) < 0) {
516 error_errno(_("could not write to '%s'"), filename
);
517 rollback_lock_file(&msg_file
);
520 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
521 error_errno(_("could not write eol to '%s'"), filename
);
522 rollback_lock_file(&msg_file
);
525 if (commit_lock_file(&msg_file
) < 0)
526 return error(_("failed to finalize '%s'"), filename
);
531 int read_oneliner(struct strbuf
*buf
,
532 const char *path
, unsigned flags
)
534 int orig_len
= buf
->len
;
536 if (strbuf_read_file(buf
, path
, 0) < 0) {
537 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
538 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
539 warning_errno(_("could not read '%s'"), path
);
543 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
544 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
546 buf
->buf
[buf
->len
] = '\0';
549 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
555 static struct tree
*empty_tree(struct repository
*r
)
557 return lookup_tree(r
, the_hash_algo
->empty_tree
);
560 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
562 if (repo_read_index_unmerged(repo
))
563 return error_resolve_conflict(action_name(opts
));
565 error(_("your local changes would be overwritten by %s."),
566 _(action_name(opts
)));
568 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
569 advise(_("commit your changes or stash them to proceed."));
573 static void update_abort_safety_file(void)
575 struct object_id head
;
577 /* Do nothing on a single-pick */
578 if (!file_exists(git_path_seq_dir()))
581 if (!repo_get_oid(the_repository
, "HEAD", &head
))
582 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
584 write_file(git_path_abort_safety_file(), "%s", "");
587 static int fast_forward_to(struct repository
*r
,
588 const struct object_id
*to
,
589 const struct object_id
*from
,
591 struct replay_opts
*opts
)
593 struct ref_transaction
*transaction
;
594 struct strbuf sb
= STRBUF_INIT
;
595 struct strbuf err
= STRBUF_INIT
;
598 if (checkout_fast_forward(r
, from
, to
, 1))
599 return -1; /* the callee should have complained already */
601 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
603 transaction
= ref_transaction_begin(&err
);
605 ref_transaction_update(transaction
, "HEAD",
606 to
, unborn
&& !is_rebase_i(opts
) ?
609 ref_transaction_commit(transaction
, &err
)) {
610 ref_transaction_free(transaction
);
611 error("%s", err
.buf
);
613 strbuf_release(&err
);
618 strbuf_release(&err
);
619 ref_transaction_free(transaction
);
620 update_abort_safety_file();
624 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
627 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
628 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
629 COMMIT_MSG_CLEANUP_SPACE
;
630 else if (!strcmp(cleanup_arg
, "verbatim"))
631 return COMMIT_MSG_CLEANUP_NONE
;
632 else if (!strcmp(cleanup_arg
, "whitespace"))
633 return COMMIT_MSG_CLEANUP_SPACE
;
634 else if (!strcmp(cleanup_arg
, "strip"))
635 return COMMIT_MSG_CLEANUP_ALL
;
636 else if (!strcmp(cleanup_arg
, "scissors"))
637 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
638 COMMIT_MSG_CLEANUP_SPACE
;
640 die(_("Invalid cleanup mode %s"), cleanup_arg
);
644 * NB using int rather than enum cleanup_mode to stop clang's
645 * -Wtautological-constant-out-of-range-compare complaining that the comparison
648 static const char *describe_cleanup_mode(int cleanup_mode
)
650 static const char *modes
[] = { "whitespace",
655 if (cleanup_mode
< ARRAY_SIZE(modes
))
656 return modes
[cleanup_mode
];
658 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
661 void append_conflicts_hint(struct index_state
*istate
,
662 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
666 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
667 strbuf_addch(msgbuf
, '\n');
668 wt_status_append_cut_line(msgbuf
);
669 strbuf_addch(msgbuf
, comment_line_char
);
672 strbuf_addch(msgbuf
, '\n');
673 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
674 for (i
= 0; i
< istate
->cache_nr
;) {
675 const struct cache_entry
*ce
= istate
->cache
[i
++];
677 strbuf_commented_addf(msgbuf
, comment_line_char
,
679 while (i
< istate
->cache_nr
&&
680 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
686 static int do_recursive_merge(struct repository
*r
,
687 struct commit
*base
, struct commit
*next
,
688 const char *base_label
, const char *next_label
,
689 struct object_id
*head
, struct strbuf
*msgbuf
,
690 struct replay_opts
*opts
)
692 struct merge_options o
;
693 struct merge_result result
;
694 struct tree
*next_tree
, *base_tree
, *head_tree
;
695 int clean
, show_output
;
697 struct lock_file index_lock
= LOCK_INIT
;
699 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
704 init_merge_options(&o
, r
);
705 o
.ancestor
= base
? base_label
: "(empty tree)";
707 o
.branch2
= next
? next_label
: "(empty tree)";
708 if (is_rebase_i(opts
))
710 o
.show_rename_progress
= 1;
712 head_tree
= parse_tree_indirect(head
);
713 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
714 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
716 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
717 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
719 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
720 memset(&result
, 0, sizeof(result
));
721 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
723 show_output
= !is_rebase_i(opts
) || !result
.clean
;
725 * TODO: merge_switch_to_result will update index/working tree;
726 * we only really want to do that if !result.clean || this is
727 * the final patch to be picked. But determining this is the
728 * final patch would take some work, and "head_tree" would need
729 * to be replace with the tree the index matched before we
730 * started doing any picks.
732 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
733 clean
= result
.clean
;
735 ensure_full_index(r
->index
);
736 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
737 if (is_rebase_i(opts
) && clean
<= 0)
738 fputs(o
.obuf
.buf
, stdout
);
739 strbuf_release(&o
.obuf
);
742 rollback_lock_file(&index_lock
);
746 if (write_locked_index(r
->index
, &index_lock
,
747 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
749 * TRANSLATORS: %s will be "revert", "cherry-pick" or
752 return error(_("%s: Unable to write new index file"),
753 _(action_name(opts
)));
756 append_conflicts_hint(r
->index
, msgbuf
,
757 opts
->default_msg_cleanup
);
762 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
764 if (!cache_tree_fully_valid(istate
->cache_tree
))
765 if (cache_tree_update(istate
, 0)) {
766 error(_("unable to update cache tree"));
770 return &istate
->cache_tree
->oid
;
773 static int is_index_unchanged(struct repository
*r
)
775 struct object_id head_oid
, *cache_tree_oid
;
776 struct commit
*head_commit
;
777 struct index_state
*istate
= r
->index
;
779 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
780 return error(_("could not resolve HEAD commit"));
782 head_commit
= lookup_commit(r
, &head_oid
);
785 * If head_commit is NULL, check_commit, called from
786 * lookup_commit, would have indicated that head_commit is not
787 * a commit object already. repo_parse_commit() will return failure
788 * without further complaints in such a case. Otherwise, if
789 * the commit is invalid, repo_parse_commit() will complain. So
790 * there is nothing for us to say here. Just return failure.
792 if (repo_parse_commit(r
, head_commit
))
795 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
798 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
801 static int write_author_script(const char *message
)
803 struct strbuf buf
= STRBUF_INIT
;
808 if (!*message
|| starts_with(message
, "\n")) {
810 /* Missing 'author' line? */
811 unlink(rebase_path_author_script());
813 } else if (skip_prefix(message
, "author ", &message
))
815 else if ((eol
= strchr(message
, '\n')))
820 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
821 while (*message
&& *message
!= '\n' && *message
!= '\r')
822 if (skip_prefix(message
, " <", &message
))
824 else if (*message
!= '\'')
825 strbuf_addch(&buf
, *(message
++));
827 strbuf_addf(&buf
, "'\\%c'", *(message
++));
828 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
829 while (*message
&& *message
!= '\n' && *message
!= '\r')
830 if (skip_prefix(message
, "> ", &message
))
832 else if (*message
!= '\'')
833 strbuf_addch(&buf
, *(message
++));
835 strbuf_addf(&buf
, "'\\%c'", *(message
++));
836 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
837 while (*message
&& *message
!= '\n' && *message
!= '\r')
838 if (*message
!= '\'')
839 strbuf_addch(&buf
, *(message
++));
841 strbuf_addf(&buf
, "'\\%c'", *(message
++));
842 strbuf_addch(&buf
, '\'');
843 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
844 strbuf_release(&buf
);
849 * Take a series of KEY='VALUE' lines where VALUE part is
850 * sq-quoted, and append <KEY, VALUE> at the end of the string list
852 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
855 struct string_list_item
*item
;
857 char *cp
= strchr(buf
, '=');
859 np
= strchrnul(buf
, '\n');
860 return error(_("no key present in '%.*s'"),
861 (int) (np
- buf
), buf
);
863 np
= strchrnul(cp
, '\n');
865 item
= string_list_append(list
, buf
);
867 buf
= np
+ (*np
== '\n');
871 return error(_("unable to dequote value of '%s'"),
873 item
->util
= xstrdup(cp
);
879 * Reads and parses the state directory's "author-script" file, and sets name,
880 * email and date accordingly.
881 * Returns 0 on success, -1 if the file could not be parsed.
883 * The author script is of the format:
885 * GIT_AUTHOR_NAME='$author_name'
886 * GIT_AUTHOR_EMAIL='$author_email'
887 * GIT_AUTHOR_DATE='$author_date'
889 * where $author_name, $author_email and $author_date are quoted. We are strict
890 * with our parsing, as the file was meant to be eval'd in the now-removed
891 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
892 * from what this function expects, it is better to bail out than to do
893 * something that the user does not expect.
895 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
898 struct strbuf buf
= STRBUF_INIT
;
899 struct string_list kv
= STRING_LIST_INIT_DUP
;
900 int retval
= -1; /* assume failure */
901 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
903 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
904 strbuf_release(&buf
);
905 if (errno
== ENOENT
&& allow_missing
)
908 return error_errno(_("could not open '%s' for reading"),
912 if (parse_key_value_squoted(buf
.buf
, &kv
))
915 for (i
= 0; i
< kv
.nr
; i
++) {
916 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
918 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
921 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
923 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
926 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
928 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
932 err
= error(_("unknown variable '%s'"),
937 error(_("missing 'GIT_AUTHOR_NAME'"));
939 error(_("missing 'GIT_AUTHOR_EMAIL'"));
941 error(_("missing 'GIT_AUTHOR_DATE'"));
942 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
944 *name
= kv
.items
[name_i
].util
;
945 *email
= kv
.items
[email_i
].util
;
946 *date
= kv
.items
[date_i
].util
;
949 string_list_clear(&kv
, !!retval
);
950 strbuf_release(&buf
);
955 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
956 * file with shell quoting into struct strvec. Returns -1 on
957 * error, 0 otherwise.
959 static int read_env_script(struct strvec
*env
)
961 char *name
, *email
, *date
;
963 if (read_author_script(rebase_path_author_script(),
964 &name
, &email
, &date
, 0))
967 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
968 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
969 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
977 static char *get_author(const char *message
)
982 a
= find_commit_header(message
, "author", &len
);
984 return xmemdupz(a
, len
);
989 static const char *author_date_from_env(const struct strvec
*env
)
994 for (i
= 0; i
< env
->nr
; i
++)
995 if (skip_prefix(env
->v
[i
],
996 "GIT_AUTHOR_DATE=", &date
))
999 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1000 * reading the script
1002 BUG("GIT_AUTHOR_DATE missing from author script");
1005 static const char staged_changes_advice
[] =
1006 N_("you have staged changes in your working tree\n"
1007 "If these changes are meant to be squashed into the previous commit, run:\n"
1009 " git commit --amend %s\n"
1011 "If they are meant to go into a new commit, run:\n"
1015 "In both cases, once you're done, continue with:\n"
1017 " git rebase --continue\n");
1019 #define ALLOW_EMPTY (1<<0)
1020 #define EDIT_MSG (1<<1)
1021 #define AMEND_MSG (1<<2)
1022 #define CLEANUP_MSG (1<<3)
1023 #define VERIFY_MSG (1<<4)
1024 #define CREATE_ROOT_COMMIT (1<<5)
1025 #define VERBATIM_MSG (1<<6)
1027 static int run_command_silent_on_success(struct child_process
*cmd
)
1029 struct strbuf buf
= STRBUF_INIT
;
1032 cmd
->stdout_to_stderr
= 1;
1033 rc
= pipe_command(cmd
,
1039 fputs(buf
.buf
, stderr
);
1040 strbuf_release(&buf
);
1045 * If we are cherry-pick, and if the merge did not result in
1046 * hand-editing, we will hit this commit and inherit the original
1047 * author date and name.
1049 * If we are revert, or if our cherry-pick results in a hand merge,
1050 * we had better say that the current user is responsible for that.
1052 * An exception is when run_git_commit() is called during an
1053 * interactive rebase: in that case, we will want to retain the
1056 static int run_git_commit(const char *defmsg
,
1057 struct replay_opts
*opts
,
1060 struct child_process cmd
= CHILD_PROCESS_INIT
;
1062 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1063 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1067 if (is_rebase_i(opts
) &&
1068 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1069 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1070 read_env_script(&cmd
.env
)) {
1071 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1073 return error(_(staged_changes_advice
),
1077 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1079 if (opts
->committer_date_is_author_date
)
1080 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1083 author_date_from_env(&cmd
.env
));
1084 if (opts
->ignore_date
)
1085 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1087 strvec_push(&cmd
.args
, "commit");
1089 if (!(flags
& VERIFY_MSG
))
1090 strvec_push(&cmd
.args
, "-n");
1091 if ((flags
& AMEND_MSG
))
1092 strvec_push(&cmd
.args
, "--amend");
1094 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1096 strvec_push(&cmd
.args
, "--no-gpg-sign");
1098 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1099 else if (!(flags
& EDIT_MSG
))
1100 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1101 if ((flags
& CLEANUP_MSG
))
1102 strvec_push(&cmd
.args
, "--cleanup=strip");
1103 if ((flags
& VERBATIM_MSG
))
1104 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1105 if ((flags
& EDIT_MSG
))
1106 strvec_push(&cmd
.args
, "-e");
1107 else if (!(flags
& CLEANUP_MSG
) &&
1108 !opts
->signoff
&& !opts
->record_origin
&&
1109 !opts
->explicit_cleanup
)
1110 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1112 if ((flags
& ALLOW_EMPTY
))
1113 strvec_push(&cmd
.args
, "--allow-empty");
1115 if (!(flags
& EDIT_MSG
))
1116 strvec_push(&cmd
.args
, "--allow-empty-message");
1118 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1119 return run_command_silent_on_success(&cmd
);
1121 return run_command(&cmd
);
1124 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1129 /* Check if the rest is just whitespace and Signed-off-by's. */
1130 for (i
= start
; i
< sb
->len
; i
++) {
1131 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1137 if (strlen(sign_off_header
) <= eol
- i
&&
1138 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1143 if (!isspace(sb
->buf
[i
++]))
1150 void cleanup_message(struct strbuf
*msgbuf
,
1151 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1153 if (verbose
|| /* Truncate the message just before the diff, if any. */
1154 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1155 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1156 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1157 strbuf_stripspace(msgbuf
,
1158 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1162 * Find out if the message in the strbuf contains only whitespace and
1163 * Signed-off-by lines.
1165 int message_is_empty(const struct strbuf
*sb
,
1166 enum commit_msg_cleanup_mode cleanup_mode
)
1168 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1170 return rest_is_empty(sb
, 0);
1174 * See if the user edited the message in the editor or left what
1175 * was in the template intact
1177 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1178 enum commit_msg_cleanup_mode cleanup_mode
)
1180 struct strbuf tmpl
= STRBUF_INIT
;
1183 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1186 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1189 strbuf_stripspace(&tmpl
,
1190 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1191 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1193 strbuf_release(&tmpl
);
1194 return rest_is_empty(sb
, start
- sb
->buf
);
1197 int update_head_with_reflog(const struct commit
*old_head
,
1198 const struct object_id
*new_head
,
1199 const char *action
, const struct strbuf
*msg
,
1202 struct ref_transaction
*transaction
;
1203 struct strbuf sb
= STRBUF_INIT
;
1208 strbuf_addstr(&sb
, action
);
1209 strbuf_addstr(&sb
, ": ");
1212 nl
= strchr(msg
->buf
, '\n');
1214 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1216 strbuf_addbuf(&sb
, msg
);
1217 strbuf_addch(&sb
, '\n');
1220 transaction
= ref_transaction_begin(err
);
1222 ref_transaction_update(transaction
, "HEAD", new_head
,
1223 old_head
? &old_head
->object
.oid
: null_oid(),
1225 ref_transaction_commit(transaction
, err
)) {
1228 ref_transaction_free(transaction
);
1229 strbuf_release(&sb
);
1234 static int run_rewrite_hook(const struct object_id
*oldoid
,
1235 const struct object_id
*newoid
)
1237 struct child_process proc
= CHILD_PROCESS_INIT
;
1239 struct strbuf sb
= STRBUF_INIT
;
1240 const char *hook_path
= find_hook("post-rewrite");
1245 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1247 proc
.stdout_to_stderr
= 1;
1248 proc
.trace2_hook_name
= "post-rewrite";
1250 code
= start_command(&proc
);
1253 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1254 sigchain_push(SIGPIPE
, SIG_IGN
);
1255 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1257 strbuf_release(&sb
);
1258 sigchain_pop(SIGPIPE
);
1259 return finish_command(&proc
);
1262 void commit_post_rewrite(struct repository
*r
,
1263 const struct commit
*old_head
,
1264 const struct object_id
*new_head
)
1266 struct notes_rewrite_cfg
*cfg
;
1268 cfg
= init_copy_notes_for_rewrite("amend");
1270 /* we are amending, so old_head is not NULL */
1271 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1272 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1274 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1277 static int run_prepare_commit_msg_hook(struct repository
*r
,
1282 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1284 name
= git_path_commit_editmsg();
1285 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1294 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1296 ret
= error(_("'prepare-commit-msg' hook failed"));
1301 static const char implicit_ident_advice_noconfig
[] =
1302 N_("Your name and email address were configured automatically based\n"
1303 "on your username and hostname. Please check that they are accurate.\n"
1304 "You can suppress this message by setting them explicitly. Run the\n"
1305 "following command and follow the instructions in your editor to edit\n"
1306 "your configuration file:\n"
1308 " git config --global --edit\n"
1310 "After doing this, you may fix the identity used for this commit with:\n"
1312 " git commit --amend --reset-author\n");
1314 static const char implicit_ident_advice_config
[] =
1315 N_("Your name and email address were configured automatically based\n"
1316 "on your username and hostname. Please check that they are accurate.\n"
1317 "You can suppress this message by setting them explicitly:\n"
1319 " git config --global user.name \"Your Name\"\n"
1320 " git config --global user.email you@example.com\n"
1322 "After doing this, you may fix the identity used for this commit with:\n"
1324 " git commit --amend --reset-author\n");
1326 static const char *implicit_ident_advice(void)
1328 char *user_config
= interpolate_path("~/.gitconfig", 0);
1329 char *xdg_config
= xdg_config_home("config");
1330 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1336 return _(implicit_ident_advice_config
);
1338 return _(implicit_ident_advice_noconfig
);
1342 void print_commit_summary(struct repository
*r
,
1344 const struct object_id
*oid
,
1347 struct rev_info rev
;
1348 struct commit
*commit
;
1349 struct strbuf format
= STRBUF_INIT
;
1351 struct pretty_print_context pctx
= {0};
1352 struct strbuf author_ident
= STRBUF_INIT
;
1353 struct strbuf committer_ident
= STRBUF_INIT
;
1354 struct ref_store
*refs
;
1356 commit
= lookup_commit(r
, oid
);
1358 die(_("couldn't look up newly created commit"));
1359 if (repo_parse_commit(r
, commit
))
1360 die(_("could not parse newly created commit"));
1362 strbuf_addstr(&format
, "format:%h] %s");
1364 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1366 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1368 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1369 strbuf_addstr(&format
, "\n Author: ");
1370 strbuf_addbuf_percentquote(&format
, &author_ident
);
1372 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1373 struct strbuf date
= STRBUF_INIT
;
1375 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1376 strbuf_addstr(&format
, "\n Date: ");
1377 strbuf_addbuf_percentquote(&format
, &date
);
1378 strbuf_release(&date
);
1380 if (!committer_ident_sufficiently_given()) {
1381 strbuf_addstr(&format
, "\n Committer: ");
1382 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1383 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1384 strbuf_addch(&format
, '\n');
1385 strbuf_addstr(&format
, implicit_ident_advice());
1388 strbuf_release(&author_ident
);
1389 strbuf_release(&committer_ident
);
1391 repo_init_revisions(r
, &rev
, prefix
);
1392 setup_revisions(0, NULL
, &rev
, NULL
);
1395 rev
.diffopt
.output_format
=
1396 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1398 rev
.verbose_header
= 1;
1399 rev
.show_root_diff
= 1;
1400 get_commit_format(format
.buf
, &rev
);
1401 rev
.always_show_header
= 0;
1402 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1403 diff_setup_done(&rev
.diffopt
);
1405 refs
= get_main_ref_store(r
);
1406 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1408 die(_("unable to resolve HEAD after creating commit"));
1409 if (!strcmp(head
, "HEAD"))
1410 head
= _("detached HEAD");
1412 skip_prefix(head
, "refs/heads/", &head
);
1413 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1414 _(" (root-commit)") : "");
1416 if (!log_tree_commit(&rev
, commit
)) {
1417 rev
.always_show_header
= 1;
1418 rev
.use_terminator
= 1;
1419 log_tree_commit(&rev
, commit
);
1422 release_revisions(&rev
);
1423 strbuf_release(&format
);
1426 static int parse_head(struct repository
*r
, struct commit
**head
)
1428 struct commit
*current_head
;
1429 struct object_id oid
;
1431 if (repo_get_oid(r
, "HEAD", &oid
)) {
1432 current_head
= NULL
;
1434 current_head
= lookup_commit_reference(r
, &oid
);
1436 return error(_("could not parse HEAD"));
1437 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1438 warning(_("HEAD %s is not a commit!"),
1441 if (repo_parse_commit(r
, current_head
))
1442 return error(_("could not parse HEAD commit"));
1444 *head
= current_head
;
1450 * Try to commit without forking 'git commit'. In some cases we need
1451 * to run 'git commit' to display an error message
1454 * -1 - error unable to commit
1456 * 1 - run 'git commit'
1458 static int try_to_commit(struct repository
*r
,
1459 struct strbuf
*msg
, const char *author
,
1460 struct replay_opts
*opts
, unsigned int flags
,
1461 struct object_id
*oid
)
1463 struct object_id tree
;
1464 struct commit
*current_head
= NULL
;
1465 struct commit_list
*parents
= NULL
;
1466 struct commit_extra_header
*extra
= NULL
;
1467 struct strbuf err
= STRBUF_INIT
;
1468 struct strbuf commit_msg
= STRBUF_INIT
;
1469 char *amend_author
= NULL
;
1470 const char *committer
= NULL
;
1471 const char *hook_commit
= NULL
;
1472 enum commit_msg_cleanup_mode cleanup
;
1475 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1476 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1478 if (parse_head(r
, ¤t_head
))
1481 if (flags
& AMEND_MSG
) {
1482 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1483 const char *out_enc
= get_commit_output_encoding();
1484 const char *message
= repo_logmsg_reencode(r
, current_head
,
1488 const char *orig_message
= NULL
;
1490 find_commit_subject(message
, &orig_message
);
1492 strbuf_addstr(msg
, orig_message
);
1493 hook_commit
= "HEAD";
1495 author
= amend_author
= get_author(message
);
1496 repo_unuse_commit_buffer(r
, current_head
,
1499 res
= error(_("unable to parse commit author"));
1502 parents
= copy_commit_list(current_head
->parents
);
1503 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1504 } else if (current_head
&&
1505 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1506 commit_list_insert(current_head
, &parents
);
1509 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1510 res
= error(_("git write-tree failed to write a tree"));
1514 if (!(flags
& ALLOW_EMPTY
)) {
1515 struct commit
*first_parent
= current_head
;
1517 if (flags
& AMEND_MSG
) {
1518 if (current_head
->parents
) {
1519 first_parent
= current_head
->parents
->item
;
1520 if (repo_parse_commit(r
, first_parent
)) {
1521 res
= error(_("could not parse HEAD commit"));
1525 first_parent
= NULL
;
1528 if (oideq(first_parent
1529 ? get_commit_tree_oid(first_parent
)
1530 : the_hash_algo
->empty_tree
,
1532 res
= 1; /* run 'git commit' to display error message */
1537 if (hook_exists("prepare-commit-msg")) {
1538 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1541 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1543 res
= error_errno(_("unable to read commit message "
1545 git_path_commit_editmsg());
1551 if (flags
& CLEANUP_MSG
)
1552 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1553 else if (flags
& VERBATIM_MSG
)
1554 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1555 else if ((opts
->signoff
|| opts
->record_origin
) &&
1556 !opts
->explicit_cleanup
)
1557 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1559 cleanup
= opts
->default_msg_cleanup
;
1561 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1562 strbuf_stripspace(msg
,
1563 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1564 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1565 res
= 1; /* run 'git commit' to display error message */
1569 if (opts
->committer_date_is_author_date
) {
1570 struct ident_split id
;
1571 struct strbuf date
= STRBUF_INIT
;
1573 if (!opts
->ignore_date
) {
1574 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1575 res
= error(_("invalid author identity '%s'"),
1579 if (!id
.date_begin
) {
1581 "corrupt author: missing date information"));
1584 strbuf_addf(&date
, "@%.*s %.*s",
1585 (int)(id
.date_end
- id
.date_begin
),
1587 (int)(id
.tz_end
- id
.tz_begin
),
1592 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1593 getenv("GIT_COMMITTER_EMAIL"),
1594 WANT_COMMITTER_IDENT
,
1595 opts
->ignore_date
? NULL
: date
.buf
,
1597 strbuf_release(&date
);
1602 if (opts
->ignore_date
) {
1603 struct ident_split id
;
1606 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1607 error(_("invalid author identity '%s'"), author
);
1610 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1611 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1612 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1618 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1619 author
, committer
, opts
->gpg_sign
, extra
)) {
1620 res
= error(_("failed to write commit object"));
1624 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1626 res
= error("%s", err
.buf
);
1630 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1631 if (flags
& AMEND_MSG
)
1632 commit_post_rewrite(r
, current_head
, oid
);
1635 free_commit_extra_headers(extra
);
1636 strbuf_release(&err
);
1637 strbuf_release(&commit_msg
);
1643 static int write_rebase_head(struct object_id
*oid
)
1645 if (update_ref("rebase", "REBASE_HEAD", oid
,
1646 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1647 return error(_("could not update %s"), "REBASE_HEAD");
1652 static int do_commit(struct repository
*r
,
1653 const char *msg_file
, const char *author
,
1654 struct replay_opts
*opts
, unsigned int flags
,
1655 struct object_id
*oid
)
1659 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1660 struct object_id oid
;
1661 struct strbuf sb
= STRBUF_INIT
;
1663 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1664 return error_errno(_("unable to read commit message "
1668 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1669 author
, opts
, flags
, &oid
);
1670 strbuf_release(&sb
);
1672 refs_delete_ref(get_main_ref_store(r
), "",
1673 "CHERRY_PICK_HEAD", NULL
, 0);
1674 unlink(git_path_merge_msg(r
));
1675 if (!is_rebase_i(opts
))
1676 print_commit_summary(r
, NULL
, &oid
,
1677 SUMMARY_SHOW_AUTHOR_DATE
);
1682 if (is_rebase_i(opts
) && oid
)
1683 if (write_rebase_head(oid
))
1685 return run_git_commit(msg_file
, opts
, flags
);
1691 static int is_original_commit_empty(struct commit
*commit
)
1693 const struct object_id
*ptree_oid
;
1695 if (repo_parse_commit(the_repository
, commit
))
1696 return error(_("could not parse commit %s"),
1697 oid_to_hex(&commit
->object
.oid
));
1698 if (commit
->parents
) {
1699 struct commit
*parent
= commit
->parents
->item
;
1700 if (repo_parse_commit(the_repository
, parent
))
1701 return error(_("could not parse parent commit %s"),
1702 oid_to_hex(&parent
->object
.oid
));
1703 ptree_oid
= get_commit_tree_oid(parent
);
1705 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1708 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1712 * Should empty commits be allowed? Return status:
1713 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1714 * 0: Halt on empty commit
1715 * 1: Allow empty commit
1716 * 2: Drop empty commit
1718 static int allow_empty(struct repository
*r
,
1719 struct replay_opts
*opts
,
1720 struct commit
*commit
)
1722 int index_unchanged
, originally_empty
;
1727 * (1) we do not allow empty at all and error out.
1729 * (2) we allow ones that were initially empty, and
1730 * just drop the ones that become empty
1732 * (3) we allow ones that were initially empty, but
1733 * halt for the ones that become empty;
1735 * (4) we allow both.
1737 if (!opts
->allow_empty
)
1738 return 0; /* let "git commit" barf as necessary */
1740 index_unchanged
= is_index_unchanged(r
);
1741 if (index_unchanged
< 0)
1742 return index_unchanged
;
1743 if (!index_unchanged
)
1744 return 0; /* we do not have to say --allow-empty */
1746 if (opts
->keep_redundant_commits
)
1749 originally_empty
= is_original_commit_empty(commit
);
1750 if (originally_empty
< 0)
1751 return originally_empty
;
1752 if (originally_empty
)
1754 else if (opts
->drop_redundant_commits
)
1763 } todo_command_info
[] = {
1764 [TODO_PICK
] = { 'p', "pick" },
1765 [TODO_REVERT
] = { 0, "revert" },
1766 [TODO_EDIT
] = { 'e', "edit" },
1767 [TODO_REWORD
] = { 'r', "reword" },
1768 [TODO_FIXUP
] = { 'f', "fixup" },
1769 [TODO_SQUASH
] = { 's', "squash" },
1770 [TODO_EXEC
] = { 'x', "exec" },
1771 [TODO_BREAK
] = { 'b', "break" },
1772 [TODO_LABEL
] = { 'l', "label" },
1773 [TODO_RESET
] = { 't', "reset" },
1774 [TODO_MERGE
] = { 'm', "merge" },
1775 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1776 [TODO_NOOP
] = { 0, "noop" },
1777 [TODO_DROP
] = { 'd', "drop" },
1778 [TODO_COMMENT
] = { 0, NULL
},
1781 static const char *command_to_string(const enum todo_command command
)
1783 if (command
< TODO_COMMENT
)
1784 return todo_command_info
[command
].str
;
1785 die(_("unknown command: %d"), command
);
1788 static char command_to_char(const enum todo_command command
)
1790 if (command
< TODO_COMMENT
)
1791 return todo_command_info
[command
].c
;
1792 return comment_line_char
;
1795 static int is_noop(const enum todo_command command
)
1797 return TODO_NOOP
<= command
;
1800 static int is_fixup(enum todo_command command
)
1802 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1805 /* Does this command create a (non-merge) commit? */
1806 static int is_pick_or_similar(enum todo_command command
)
1821 enum todo_item_flags
{
1822 TODO_EDIT_MERGE_MSG
= (1 << 0),
1823 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1824 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1827 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1828 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1829 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1830 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1831 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1833 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1835 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1836 (flag
& TODO_EDIT_FIXUP_MSG
));
1840 * Wrapper around strbuf_add_commented_lines() which avoids double
1841 * commenting commit subjects.
1843 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1845 const char *s
= str
;
1846 while (len
> 0 && s
[0] == comment_line_char
) {
1848 const char *n
= memchr(s
, '\n', len
);
1853 strbuf_add(buf
, s
, count
);
1857 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1860 /* Does the current fixup chain contain a squash command? */
1861 static int seen_squash(struct replay_opts
*opts
)
1863 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1864 strstr(opts
->current_fixups
.buf
, "\nsquash");
1867 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1869 strbuf_setlen(buf1
, 2);
1870 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1871 strbuf_addch(buf1
, '\n');
1872 strbuf_setlen(buf2
, 2);
1873 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1874 strbuf_addch(buf2
, '\n');
1878 * Comment out any un-commented commit messages, updating the message comments
1879 * to say they will be skipped but do not comment out the empty lines that
1880 * surround commit messages and their comments.
1882 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1884 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1885 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1886 const char *s
, *start
;
1888 size_t orig_msg_len
;
1891 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1892 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1893 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1897 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1899 * Copy the last message, preserving the blank line
1900 * preceding the current line
1902 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1903 copy_lines(msg
, start
, s
- start
- off
);
1905 strbuf_addch(msg
, '\n');
1907 * The next message needs to be commented out but the
1908 * message header is already commented out so just copy
1909 * it and the blank line that follows it.
1911 strbuf_addbuf(msg
, &buf2
);
1913 strbuf_addch(msg
, *next
++);
1915 copy_lines
= add_commented_lines
;
1916 update_comment_bufs(&buf1
, &buf2
, ++i
);
1917 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1918 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1919 copy_lines(msg
, start
, s
- start
- off
);
1922 copy_lines
= strbuf_add
;
1923 update_comment_bufs(&buf1
, &buf2
, ++i
);
1925 s
= strchr(s
, '\n');
1930 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1932 strbuf_release(&buf1
);
1933 strbuf_release(&buf2
);
1936 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1937 enum todo_command command
, struct replay_opts
*opts
,
1940 const char *fixup_msg
;
1941 size_t commented_len
= 0, fixup_off
;
1943 * amend is non-interactive and not normally used with fixup!
1944 * or squash! commits, so only comment out those subjects when
1945 * squashing commit messages.
1947 if (starts_with(body
, "amend!") ||
1948 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1949 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1950 commented_len
= commit_subject_length(body
);
1952 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1953 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1954 ++opts
->current_fixup_count
+ 1);
1955 strbuf_addstr(buf
, "\n\n");
1956 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1957 /* buf->buf may be reallocated so store an offset into the buffer */
1958 fixup_off
= buf
->len
;
1959 strbuf_addstr(buf
, body
+ commented_len
);
1961 /* fixup -C after squash behaves like squash */
1962 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1964 * We're replacing the commit message so we need to
1965 * append the Signed-off-by: trailer if the user
1966 * requested '--signoff'.
1969 append_signoff(buf
, 0, 0);
1971 if ((command
== TODO_FIXUP
) &&
1972 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1973 (file_exists(rebase_path_fixup_msg()) ||
1974 !file_exists(rebase_path_squash_msg()))) {
1975 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1976 if (write_message(fixup_msg
, strlen(fixup_msg
),
1977 rebase_path_fixup_msg(), 0) < 0)
1978 return error(_("cannot write '%s'"),
1979 rebase_path_fixup_msg());
1981 unlink(rebase_path_fixup_msg());
1984 unlink(rebase_path_fixup_msg());
1990 static int update_squash_messages(struct repository
*r
,
1991 enum todo_command command
,
1992 struct commit
*commit
,
1993 struct replay_opts
*opts
,
1996 struct strbuf buf
= STRBUF_INIT
;
1998 const char *message
, *body
;
1999 const char *encoding
= get_commit_output_encoding();
2001 if (opts
->current_fixup_count
> 0) {
2002 struct strbuf header
= STRBUF_INIT
;
2005 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2006 return error(_("could not read '%s'"),
2007 rebase_path_squash_msg());
2009 eol
= buf
.buf
[0] != comment_line_char
?
2010 buf
.buf
: strchrnul(buf
.buf
, '\n');
2012 strbuf_addf(&header
, "%c ", comment_line_char
);
2013 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2014 opts
->current_fixup_count
+ 2);
2015 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2016 strbuf_release(&header
);
2017 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2018 update_squash_message_for_fixup(&buf
);
2020 struct object_id head
;
2021 struct commit
*head_commit
;
2022 const char *head_message
, *body
;
2024 if (repo_get_oid(r
, "HEAD", &head
))
2025 return error(_("need a HEAD to fixup"));
2026 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2027 return error(_("could not read HEAD"));
2028 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2030 return error(_("could not read HEAD's commit message"));
2032 find_commit_subject(head_message
, &body
);
2033 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2034 rebase_path_fixup_msg(), 0) < 0) {
2035 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2036 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2038 strbuf_addf(&buf
, "%c ", comment_line_char
);
2039 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2040 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2041 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2042 _(skip_first_commit_msg_str
) :
2043 _(first_commit_msg_str
));
2044 strbuf_addstr(&buf
, "\n\n");
2045 if (is_fixup_flag(command
, flag
))
2046 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2049 strbuf_addstr(&buf
, body
);
2051 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2054 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2055 return error(_("could not read commit message of %s"),
2056 oid_to_hex(&commit
->object
.oid
));
2057 find_commit_subject(message
, &body
);
2059 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2060 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2061 } else if (command
== TODO_FIXUP
) {
2062 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2063 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2064 ++opts
->current_fixup_count
+ 1);
2065 strbuf_addstr(&buf
, "\n\n");
2066 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2069 return error(_("unknown command: %d"), command
);
2070 repo_unuse_commit_buffer(r
, commit
, message
);
2073 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2075 strbuf_release(&buf
);
2078 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2079 opts
->current_fixups
.len
? "\n" : "",
2080 command_to_string(command
),
2081 oid_to_hex(&commit
->object
.oid
));
2082 res
= write_message(opts
->current_fixups
.buf
,
2083 opts
->current_fixups
.len
,
2084 rebase_path_current_fixups(), 0);
2090 static void flush_rewritten_pending(void)
2092 struct strbuf buf
= STRBUF_INIT
;
2093 struct object_id newoid
;
2096 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2097 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2098 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2099 char *bol
= buf
.buf
, *eol
;
2102 eol
= strchrnul(bol
, '\n');
2103 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2104 bol
, oid_to_hex(&newoid
));
2110 unlink(rebase_path_rewritten_pending());
2112 strbuf_release(&buf
);
2115 static void record_in_rewritten(struct object_id
*oid
,
2116 enum todo_command next_command
)
2118 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2123 fprintf(out
, "%s\n", oid_to_hex(oid
));
2126 if (!is_fixup(next_command
))
2127 flush_rewritten_pending();
2130 static int should_edit(struct replay_opts
*opts
) {
2133 * Note that we only handle the case of non-conflicted
2134 * commits; continue_single_pick() handles the conflicted
2135 * commits itself instead of calling this function.
2137 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2141 static void refer_to_commit(struct replay_opts
*opts
,
2142 struct strbuf
*msgbuf
, struct commit
*commit
)
2144 if (opts
->commit_use_reference
) {
2145 struct pretty_print_context ctx
= {
2146 .abbrev
= DEFAULT_ABBREV
,
2147 .date_mode
.type
= DATE_SHORT
,
2149 repo_format_commit_message(the_repository
, commit
,
2150 "%h (%s, %ad)", msgbuf
, &ctx
);
2152 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2156 static int do_pick_commit(struct repository
*r
,
2157 struct todo_item
*item
,
2158 struct replay_opts
*opts
,
2159 int final_fixup
, int *check_todo
)
2161 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2162 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2163 struct object_id head
;
2164 struct commit
*base
, *next
, *parent
;
2165 const char *base_label
, *next_label
;
2166 char *author
= NULL
;
2167 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2168 struct strbuf msgbuf
= STRBUF_INIT
;
2169 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2170 enum todo_command command
= item
->command
;
2171 struct commit
*commit
= item
->commit
;
2173 if (opts
->no_commit
) {
2175 * We do not intend to commit immediately. We just want to
2176 * merge the differences in, so let's compute the tree
2177 * that represents the "current" state for the merge machinery
2180 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2181 return error(_("your index file is unmerged."));
2183 unborn
= repo_get_oid(r
, "HEAD", &head
);
2184 /* Do we want to generate a root commit? */
2185 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2186 oideq(&head
, &opts
->squash_onto
)) {
2187 if (is_fixup(command
))
2188 return error(_("cannot fixup root commit"));
2189 flags
|= CREATE_ROOT_COMMIT
;
2192 oidcpy(&head
, the_hash_algo
->empty_tree
);
2193 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2195 return error_dirty_index(r
, opts
);
2197 discard_index(r
->index
);
2199 if (!commit
->parents
)
2201 else if (commit
->parents
->next
) {
2202 /* Reverting or cherry-picking a merge commit */
2204 struct commit_list
*p
;
2206 if (!opts
->mainline
)
2207 return error(_("commit %s is a merge but no -m option was given."),
2208 oid_to_hex(&commit
->object
.oid
));
2210 for (cnt
= 1, p
= commit
->parents
;
2211 cnt
!= opts
->mainline
&& p
;
2214 if (cnt
!= opts
->mainline
|| !p
)
2215 return error(_("commit %s does not have parent %d"),
2216 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2218 } else if (1 < opts
->mainline
)
2220 * Non-first parent explicitly specified as mainline for
2223 return error(_("commit %s does not have parent %d"),
2224 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2226 parent
= commit
->parents
->item
;
2228 if (get_message(commit
, &msg
) != 0)
2229 return error(_("cannot get commit message for %s"),
2230 oid_to_hex(&commit
->object
.oid
));
2232 if (opts
->allow_ff
&& !is_fixup(command
) &&
2233 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2234 (!parent
&& unborn
))) {
2235 if (is_rebase_i(opts
))
2236 write_author_script(msg
.message
);
2237 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2239 if (res
|| command
!= TODO_REWORD
)
2243 goto fast_forward_edit
;
2245 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2246 /* TRANSLATORS: The first %s will be a "todo" command like
2247 "revert" or "pick", the second %s a SHA1. */
2248 return error(_("%s: cannot parse parent commit %s"),
2249 command_to_string(command
),
2250 oid_to_hex(&parent
->object
.oid
));
2253 * "commit" is an existing commit. We would want to apply
2254 * the difference it introduces since its first parent "prev"
2255 * on top of the current HEAD if we are cherry-pick. Or the
2256 * reverse of it if we are revert.
2259 if (command
== TODO_REVERT
) {
2261 base_label
= msg
.label
;
2263 next_label
= msg
.parent_label
;
2264 if (opts
->commit_use_reference
) {
2265 strbuf_addstr(&msgbuf
,
2266 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2268 strbuf_addstr(&msgbuf
, "Revert \"");
2269 strbuf_addstr(&msgbuf
, msg
.subject
);
2270 strbuf_addstr(&msgbuf
, "\"");
2272 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2273 refer_to_commit(opts
, &msgbuf
, commit
);
2275 if (commit
->parents
&& commit
->parents
->next
) {
2276 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2277 refer_to_commit(opts
, &msgbuf
, parent
);
2279 strbuf_addstr(&msgbuf
, ".\n");
2284 base_label
= msg
.parent_label
;
2286 next_label
= msg
.label
;
2288 /* Append the commit log message to msgbuf. */
2289 if (find_commit_subject(msg
.message
, &p
))
2290 strbuf_addstr(&msgbuf
, p
);
2292 if (opts
->record_origin
) {
2293 strbuf_complete_line(&msgbuf
);
2294 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2295 strbuf_addch(&msgbuf
, '\n');
2296 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2297 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2298 strbuf_addstr(&msgbuf
, ")\n");
2300 if (!is_fixup(command
))
2301 author
= get_author(msg
.message
);
2304 if (command
== TODO_REWORD
)
2306 else if (is_fixup(command
)) {
2307 if (update_squash_messages(r
, command
, commit
,
2308 opts
, item
->flags
)) {
2314 msg_file
= rebase_path_squash_msg();
2315 else if (file_exists(rebase_path_fixup_msg())) {
2316 flags
|= VERBATIM_MSG
;
2317 msg_file
= rebase_path_fixup_msg();
2319 const char *dest
= git_path_squash_msg(r
);
2321 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2322 res
= error(_("could not copy '%s' to '%s'"),
2323 rebase_path_squash_msg(), dest
);
2326 unlink(git_path_merge_msg(r
));
2332 if (opts
->signoff
&& !is_fixup(command
))
2333 append_signoff(&msgbuf
, 0, 0);
2335 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2337 else if (!opts
->strategy
||
2338 !strcmp(opts
->strategy
, "recursive") ||
2339 !strcmp(opts
->strategy
, "ort") ||
2340 command
== TODO_REVERT
) {
2341 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2342 &head
, &msgbuf
, opts
);
2346 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2347 git_path_merge_msg(r
), 0);
2349 struct commit_list
*common
= NULL
;
2350 struct commit_list
*remotes
= NULL
;
2352 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2353 git_path_merge_msg(r
), 0);
2355 commit_list_insert(base
, &common
);
2356 commit_list_insert(next
, &remotes
);
2357 res
|= try_merge_command(r
, opts
->strategy
,
2358 opts
->xopts
.nr
, opts
->xopts
.v
,
2359 common
, oid_to_hex(&head
), remotes
);
2360 free_commit_list(common
);
2361 free_commit_list(remotes
);
2365 * If the merge was clean or if it failed due to conflict, we write
2366 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2367 * However, if the merge did not even start, then we don't want to
2370 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2371 command
== TODO_EDIT
) && !opts
->no_commit
&&
2372 (res
== 0 || res
== 1) &&
2373 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2374 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2376 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2377 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2378 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2382 error(command
== TODO_REVERT
2383 ? _("could not revert %s... %s")
2384 : _("could not apply %s... %s"),
2385 short_commit_name(r
, commit
), msg
.subject
);
2386 print_advice(r
, res
== 1, opts
);
2387 repo_rerere(r
, opts
->allow_rerere_auto
);
2392 allow
= allow_empty(r
, opts
, commit
);
2396 } else if (allow
== 1) {
2397 flags
|= ALLOW_EMPTY
;
2398 } else if (allow
== 2) {
2400 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2402 unlink(git_path_merge_msg(r
));
2403 unlink(git_path_auto_merge(r
));
2405 _("dropping %s %s -- patch contents already upstream\n"),
2406 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2407 } /* else allow == 0 and there's nothing special to do */
2408 if (!opts
->no_commit
&& !drop_commit
) {
2409 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2410 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2411 commit
? &commit
->object
.oid
: NULL
);
2413 res
= error(_("unable to parse commit author"));
2414 *check_todo
= !!(flags
& EDIT_MSG
);
2415 if (!res
&& reword
) {
2417 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2418 VERIFY_MSG
| AMEND_MSG
|
2419 (flags
& ALLOW_EMPTY
));
2425 if (!res
&& final_fixup
) {
2426 unlink(rebase_path_fixup_msg());
2427 unlink(rebase_path_squash_msg());
2428 unlink(rebase_path_current_fixups());
2429 strbuf_reset(&opts
->current_fixups
);
2430 opts
->current_fixup_count
= 0;
2434 free_message(commit
, &msg
);
2436 strbuf_release(&msgbuf
);
2437 update_abort_safety_file();
2442 static int prepare_revs(struct replay_opts
*opts
)
2445 * picking (but not reverting) ranges (but not individual revisions)
2446 * should be done in reverse
2448 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2449 opts
->revs
->reverse
^= 1;
2451 if (prepare_revision_walk(opts
->revs
))
2452 return error(_("revision walk setup failed"));
2457 static int read_and_refresh_cache(struct repository
*r
,
2458 struct replay_opts
*opts
)
2460 struct lock_file index_lock
= LOCK_INIT
;
2461 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2462 if (repo_read_index(r
) < 0) {
2463 rollback_lock_file(&index_lock
);
2464 return error(_("git %s: failed to read the index"),
2467 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2469 if (index_fd
>= 0) {
2470 if (write_locked_index(r
->index
, &index_lock
,
2471 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2472 return error(_("git %s: failed to refresh the index"),
2478 * If we are resolving merges in any way other than "ort", then
2479 * expand the sparse index.
2481 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2482 ensure_full_index(r
->index
);
2486 void todo_list_release(struct todo_list
*todo_list
)
2488 strbuf_release(&todo_list
->buf
);
2489 FREE_AND_NULL(todo_list
->items
);
2490 todo_list
->nr
= todo_list
->alloc
= 0;
2493 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2495 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2496 return todo_list
->items
+ todo_list
->nr
++;
2499 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2500 struct todo_item
*item
)
2502 return todo_list
->buf
.buf
+ item
->arg_offset
;
2505 static int is_command(enum todo_command command
, const char **bol
)
2507 const char *str
= todo_command_info
[command
].str
;
2508 const char nick
= todo_command_info
[command
].c
;
2509 const char *p
= *bol
;
2511 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2512 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2516 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2521 * '#' is not a valid label as the merge command uses it to
2522 * separate merge parents from the commit subject.
2524 if (!strcmp(arg
, "#") ||
2525 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2526 return error(_("'%s' is not a valid label"), arg
);
2529 case TODO_UPDATE_REF
:
2530 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2531 return error(_("'%s' is not a valid refname"), arg
);
2532 if (check_refname_format(arg
, 0))
2533 return error(_("update-ref requires a fully qualified "
2534 "refname e.g. refs/heads/%s"), arg
);
2538 BUG("unexpected todo_command");
2544 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2545 const char *buf
, const char *bol
, char *eol
)
2547 struct object_id commit_oid
;
2548 char *end_of_object_name
;
2549 int i
, saved
, status
, padding
;
2554 bol
+= strspn(bol
, " \t");
2556 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2557 item
->command
= TODO_COMMENT
;
2558 item
->commit
= NULL
;
2559 item
->arg_offset
= bol
- buf
;
2560 item
->arg_len
= eol
- bol
;
2564 for (i
= 0; i
< TODO_COMMENT
; i
++)
2565 if (is_command(i
, &bol
)) {
2569 if (i
>= TODO_COMMENT
)
2570 return error(_("invalid command '%.*s'"),
2571 (int)strcspn(bol
, " \t\r\n"), bol
);
2573 /* Eat up extra spaces/ tabs before object name */
2574 padding
= strspn(bol
, " \t");
2577 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2579 return error(_("%s does not accept arguments: '%s'"),
2580 command_to_string(item
->command
), bol
);
2581 item
->commit
= NULL
;
2582 item
->arg_offset
= bol
- buf
;
2583 item
->arg_len
= eol
- bol
;
2588 return error(_("missing arguments for %s"),
2589 command_to_string(item
->command
));
2591 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2592 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2595 item
->commit
= NULL
;
2596 item
->arg_offset
= bol
- buf
;
2597 item
->arg_len
= (int)(eol
- bol
);
2598 if (item
->command
== TODO_LABEL
||
2599 item
->command
== TODO_UPDATE_REF
) {
2602 ret
= check_label_or_ref_arg(item
->command
, bol
);
2608 if (item
->command
== TODO_FIXUP
) {
2609 if (skip_prefix(bol
, "-C", &bol
)) {
2610 bol
+= strspn(bol
, " \t");
2611 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2612 } else if (skip_prefix(bol
, "-c", &bol
)) {
2613 bol
+= strspn(bol
, " \t");
2614 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2618 if (item
->command
== TODO_MERGE
) {
2619 if (skip_prefix(bol
, "-C", &bol
))
2620 bol
+= strspn(bol
, " \t");
2621 else if (skip_prefix(bol
, "-c", &bol
)) {
2622 bol
+= strspn(bol
, " \t");
2623 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2625 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2626 item
->commit
= NULL
;
2627 item
->arg_offset
= bol
- buf
;
2628 item
->arg_len
= (int)(eol
- bol
);
2633 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2634 saved
= *end_of_object_name
;
2635 *end_of_object_name
= '\0';
2636 status
= repo_get_oid(r
, bol
, &commit_oid
);
2638 error(_("could not parse '%s'"), bol
); /* return later */
2639 *end_of_object_name
= saved
;
2641 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2642 item
->arg_offset
= bol
- buf
;
2643 item
->arg_len
= (int)(eol
- bol
);
2648 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2649 return item
->commit
? 0 : -1;
2652 int sequencer_get_last_command(struct repository
*r UNUSED
, enum replay_action
*action
)
2654 const char *todo_file
, *bol
;
2655 struct strbuf buf
= STRBUF_INIT
;
2658 todo_file
= git_path_todo_file();
2659 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2660 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2663 return error_errno("unable to open '%s'", todo_file
);
2665 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2666 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2667 *action
= REPLAY_PICK
;
2668 else if (is_command(TODO_REVERT
, &bol
) &&
2669 (*bol
== ' ' || *bol
== '\t'))
2670 *action
= REPLAY_REVERT
;
2674 strbuf_release(&buf
);
2679 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2680 struct todo_list
*todo_list
)
2682 struct todo_item
*item
;
2683 char *p
= buf
, *next_p
;
2684 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2686 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2688 for (i
= 1; *p
; i
++, p
= next_p
) {
2689 char *eol
= strchrnul(p
, '\n');
2691 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2693 if (p
!= eol
&& eol
[-1] == '\r')
2694 eol
--; /* strip Carriage Return */
2696 item
= append_new_todo(todo_list
);
2697 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2698 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2699 res
= error(_("invalid line %d: %.*s"),
2700 i
, (int)(eol
- p
), p
);
2701 item
->command
= TODO_COMMENT
+ 1;
2702 item
->arg_offset
= p
- buf
;
2703 item
->arg_len
= (int)(eol
- p
);
2704 item
->commit
= NULL
;
2707 if (item
->command
!= TODO_COMMENT
)
2708 todo_list
->total_nr
++;
2712 else if (is_fixup(item
->command
))
2713 res
= error(_("cannot '%s' without a previous commit"),
2714 command_to_string(item
->command
));
2715 else if (!is_noop(item
->command
))
2722 static int count_commands(struct todo_list
*todo_list
)
2726 for (i
= 0; i
< todo_list
->nr
; i
++)
2727 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2733 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2735 return index
< todo_list
->nr
?
2736 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2739 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2741 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2744 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2746 return get_item_line_offset(todo_list
, index
+ 1)
2747 - get_item_line_offset(todo_list
, index
);
2750 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2755 fd
= open(path
, O_RDONLY
);
2757 return error_errno(_("could not open '%s'"), path
);
2758 len
= strbuf_read(sb
, fd
, 0);
2761 return error(_("could not read '%s'."), path
);
2765 static int have_finished_the_last_pick(void)
2767 struct strbuf buf
= STRBUF_INIT
;
2769 const char *todo_path
= git_path_todo_file();
2772 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2773 if (errno
== ENOENT
) {
2776 error_errno("unable to open '%s'", todo_path
);
2780 /* If there is only one line then we are done */
2781 eol
= strchr(buf
.buf
, '\n');
2782 if (!eol
|| !eol
[1])
2785 strbuf_release(&buf
);
2790 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2792 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2793 int need_cleanup
= 0;
2795 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2796 if (!refs_delete_ref(get_main_ref_store(r
), "",
2797 "CHERRY_PICK_HEAD", NULL
, 0) &&
2799 warning(_("cancelling a cherry picking in progress"));
2800 opts
.action
= REPLAY_PICK
;
2804 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2805 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2808 warning(_("cancelling a revert in progress"));
2809 opts
.action
= REPLAY_REVERT
;
2813 unlink(git_path_auto_merge(r
));
2818 if (!have_finished_the_last_pick())
2821 sequencer_remove_state(&opts
);
2824 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2826 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2829 fprintf(f
, "%d\n", todo_list
->total_nr
);
2834 static int read_populate_todo(struct repository
*r
,
2835 struct todo_list
*todo_list
,
2836 struct replay_opts
*opts
)
2838 const char *todo_file
= get_todo_path(opts
);
2841 strbuf_reset(&todo_list
->buf
);
2842 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2845 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2847 if (is_rebase_i(opts
))
2848 return error(_("please fix this using "
2849 "'git rebase --edit-todo'."));
2850 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2853 if (!todo_list
->nr
&&
2854 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2855 return error(_("no commits parsed."));
2857 if (!is_rebase_i(opts
)) {
2858 enum todo_command valid
=
2859 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2862 for (i
= 0; i
< todo_list
->nr
; i
++)
2863 if (valid
== todo_list
->items
[i
].command
)
2865 else if (valid
== TODO_PICK
)
2866 return error(_("cannot cherry-pick during a revert."));
2868 return error(_("cannot revert during a cherry-pick."));
2871 if (is_rebase_i(opts
)) {
2872 struct todo_list done
= TODO_LIST_INIT
;
2874 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2875 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2876 todo_list
->done_nr
= count_commands(&done
);
2878 todo_list
->done_nr
= 0;
2880 todo_list
->total_nr
= todo_list
->done_nr
2881 + count_commands(todo_list
);
2882 todo_list_release(&done
);
2884 todo_list_write_total_nr(todo_list
);
2890 static int git_config_string_dup(char **dest
,
2891 const char *var
, const char *value
)
2894 return config_error_nonbool(var
);
2896 *dest
= xstrdup(value
);
2900 static int populate_opts_cb(const char *key
, const char *value
,
2901 const struct config_context
*ctx
,
2904 struct replay_opts
*opts
= data
;
2909 else if (!strcmp(key
, "options.no-commit"))
2910 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2911 else if (!strcmp(key
, "options.edit"))
2912 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2913 else if (!strcmp(key
, "options.allow-empty"))
2915 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2916 else if (!strcmp(key
, "options.allow-empty-message"))
2917 opts
->allow_empty_message
=
2918 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2919 else if (!strcmp(key
, "options.keep-redundant-commits"))
2920 opts
->keep_redundant_commits
=
2921 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2922 else if (!strcmp(key
, "options.signoff"))
2923 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2924 else if (!strcmp(key
, "options.record-origin"))
2925 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2926 else if (!strcmp(key
, "options.allow-ff"))
2927 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2928 else if (!strcmp(key
, "options.mainline"))
2929 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2930 else if (!strcmp(key
, "options.strategy"))
2931 git_config_string_dup(&opts
->strategy
, key
, value
);
2932 else if (!strcmp(key
, "options.gpg-sign"))
2933 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2934 else if (!strcmp(key
, "options.strategy-option")) {
2935 strvec_push(&opts
->xopts
, value
);
2936 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2937 opts
->allow_rerere_auto
=
2938 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2939 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2940 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2941 opts
->explicit_cleanup
= 1;
2942 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2944 return error(_("invalid key: %s"), key
);
2947 return error(_("invalid value for '%s': '%s'"), key
, value
);
2952 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2957 char *strategy_opts_string
= raw_opts
;
2959 if (*strategy_opts_string
== ' ')
2960 strategy_opts_string
++;
2962 count
= split_cmdline(strategy_opts_string
, &argv
);
2964 BUG("could not split '%s': %s", strategy_opts_string
,
2965 split_cmdline_strerror(count
));
2966 for (i
= 0; i
< count
; i
++) {
2967 const char *arg
= argv
[i
];
2969 skip_prefix(arg
, "--", &arg
);
2970 strvec_push(&opts
->xopts
, arg
);
2975 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2978 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2980 opts
->strategy
= strbuf_detach(buf
, NULL
);
2981 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2984 parse_strategy_opts(opts
, buf
->buf
);
2987 static int read_populate_opts(struct replay_opts
*opts
)
2989 if (is_rebase_i(opts
)) {
2990 struct strbuf buf
= STRBUF_INIT
;
2993 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
2994 READ_ONELINER_SKIP_IF_EMPTY
)) {
2995 if (!starts_with(buf
.buf
, "-S"))
2998 free(opts
->gpg_sign
);
2999 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3004 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3005 READ_ONELINER_SKIP_IF_EMPTY
)) {
3006 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3007 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3008 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3009 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3013 if (file_exists(rebase_path_verbose()))
3016 if (file_exists(rebase_path_quiet()))
3019 if (file_exists(rebase_path_signoff())) {
3024 if (file_exists(rebase_path_cdate_is_adate())) {
3026 opts
->committer_date_is_author_date
= 1;
3029 if (file_exists(rebase_path_ignore_date())) {
3031 opts
->ignore_date
= 1;
3034 if (file_exists(rebase_path_reschedule_failed_exec()))
3035 opts
->reschedule_failed_exec
= 1;
3036 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3037 opts
->reschedule_failed_exec
= 0;
3039 if (file_exists(rebase_path_drop_redundant_commits()))
3040 opts
->drop_redundant_commits
= 1;
3042 if (file_exists(rebase_path_keep_redundant_commits()))
3043 opts
->keep_redundant_commits
= 1;
3045 read_strategy_opts(opts
, &buf
);
3048 if (read_oneliner(&opts
->current_fixups
,
3049 rebase_path_current_fixups(),
3050 READ_ONELINER_SKIP_IF_EMPTY
)) {
3051 const char *p
= opts
->current_fixups
.buf
;
3052 opts
->current_fixup_count
= 1;
3053 while ((p
= strchr(p
, '\n'))) {
3054 opts
->current_fixup_count
++;
3059 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3060 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3061 ret
= error(_("unusable squash-onto"));
3064 opts
->have_squash_onto
= 1;
3068 strbuf_release(&buf
);
3072 if (!file_exists(git_path_opts_file()))
3075 * The function git_parse_source(), called from git_config_from_file(),
3076 * may die() in case of a syntactically incorrect file. We do not care
3077 * about this case, though, because we wrote that file ourselves, so we
3078 * are pretty certain that it is syntactically correct.
3080 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3081 return error(_("malformed options sheet: '%s'"),
3082 git_path_opts_file());
3086 static void write_strategy_opts(struct replay_opts
*opts
)
3088 struct strbuf buf
= STRBUF_INIT
;
3091 * Quote strategy options so that they can be read correctly
3092 * by split_cmdline().
3094 quote_cmdline(&buf
, opts
->xopts
.v
);
3095 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3096 strbuf_release(&buf
);
3099 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3100 struct commit
*onto
, const struct object_id
*orig_head
)
3103 write_file(rebase_path_head_name(), "%s\n", head_name
);
3105 write_file(rebase_path_onto(), "%s\n",
3106 oid_to_hex(&onto
->object
.oid
));
3108 write_file(rebase_path_orig_head(), "%s\n",
3109 oid_to_hex(orig_head
));
3112 write_file(rebase_path_quiet(), "%s", "");
3114 write_file(rebase_path_verbose(), "%s", "");
3116 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3117 if (opts
->xopts
.nr
> 0)
3118 write_strategy_opts(opts
);
3120 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3121 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3122 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3123 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3126 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3128 write_file(rebase_path_signoff(), "--signoff\n");
3129 if (opts
->drop_redundant_commits
)
3130 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3131 if (opts
->keep_redundant_commits
)
3132 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3133 if (opts
->committer_date_is_author_date
)
3134 write_file(rebase_path_cdate_is_adate(), "%s", "");
3135 if (opts
->ignore_date
)
3136 write_file(rebase_path_ignore_date(), "%s", "");
3137 if (opts
->reschedule_failed_exec
)
3138 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3140 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3145 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3146 struct replay_opts
*opts
)
3148 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3149 TODO_PICK
: TODO_REVERT
;
3150 const char *command_string
= todo_command_info
[command
].str
;
3151 const char *encoding
;
3152 struct commit
*commit
;
3154 if (prepare_revs(opts
))
3157 encoding
= get_log_output_encoding();
3159 while ((commit
= get_revision(opts
->revs
))) {
3160 struct todo_item
*item
= append_new_todo(todo_list
);
3161 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3164 const char *subject
;
3167 item
->command
= command
;
3168 item
->commit
= commit
;
3169 item
->arg_offset
= 0;
3171 item
->offset_in_buf
= todo_list
->buf
.len
;
3172 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3173 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3174 short_commit_name(the_repository
, commit
),
3175 subject_len
, subject
);
3176 repo_unuse_commit_buffer(the_repository
, commit
,
3181 return error(_("empty commit set passed"));
3186 static int create_seq_dir(struct repository
*r
)
3188 enum replay_action action
;
3189 const char *in_progress_error
= NULL
;
3190 const char *in_progress_advice
= NULL
;
3191 unsigned int advise_skip
=
3192 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3193 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3195 if (!sequencer_get_last_command(r
, &action
)) {
3198 in_progress_error
= _("revert is already in progress");
3199 in_progress_advice
=
3200 _("try \"git revert (--continue | %s--abort | --quit)\"");
3203 in_progress_error
= _("cherry-pick is already in progress");
3204 in_progress_advice
=
3205 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3208 BUG("unexpected action in create_seq_dir");
3211 if (in_progress_error
) {
3212 error("%s", in_progress_error
);
3213 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3214 advise(in_progress_advice
,
3215 advise_skip
? "--skip | " : "");
3218 if (mkdir(git_path_seq_dir(), 0777) < 0)
3219 return error_errno(_("could not create sequencer directory '%s'"),
3220 git_path_seq_dir());
3225 static int save_head(const char *head
)
3227 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3230 static int rollback_is_safe(void)
3232 struct strbuf sb
= STRBUF_INIT
;
3233 struct object_id expected_head
, actual_head
;
3235 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3237 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3238 strbuf_release(&sb
);
3239 die(_("could not parse %s"), git_path_abort_safety_file());
3241 strbuf_release(&sb
);
3243 else if (errno
== ENOENT
)
3244 oidclr(&expected_head
);
3246 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3248 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3249 oidclr(&actual_head
);
3251 return oideq(&actual_head
, &expected_head
);
3254 static int reset_merge(const struct object_id
*oid
)
3256 struct child_process cmd
= CHILD_PROCESS_INIT
;
3259 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3261 if (!is_null_oid(oid
))
3262 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3264 return run_command(&cmd
);
3267 static int rollback_single_pick(struct repository
*r
)
3269 struct object_id head_oid
;
3271 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3272 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3273 return error(_("no cherry-pick or revert in progress"));
3274 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3275 return error(_("cannot resolve HEAD"));
3276 if (is_null_oid(&head_oid
))
3277 return error(_("cannot abort from a branch yet to be born"));
3278 return reset_merge(&head_oid
);
3281 static int skip_single_pick(void)
3283 struct object_id head
;
3285 if (read_ref_full("HEAD", 0, &head
, NULL
))
3286 return error(_("cannot resolve HEAD"));
3287 return reset_merge(&head
);
3290 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3293 struct object_id oid
;
3294 struct strbuf buf
= STRBUF_INIT
;
3297 f
= fopen(git_path_head_file(), "r");
3298 if (!f
&& errno
== ENOENT
) {
3300 * There is no multiple-cherry-pick in progress.
3301 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3302 * a single-cherry-pick in progress, abort that.
3304 return rollback_single_pick(r
);
3307 return error_errno(_("cannot open '%s'"), git_path_head_file());
3308 if (strbuf_getline_lf(&buf
, f
)) {
3309 error(_("cannot read '%s': %s"), git_path_head_file(),
3310 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3315 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3316 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3317 git_path_head_file());
3320 if (is_null_oid(&oid
)) {
3321 error(_("cannot abort from a branch yet to be born"));
3325 if (!rollback_is_safe()) {
3326 /* Do not error, just do not rollback */
3327 warning(_("You seem to have moved HEAD. "
3328 "Not rewinding, check your HEAD!"));
3330 if (reset_merge(&oid
))
3332 strbuf_release(&buf
);
3333 return sequencer_remove_state(opts
);
3335 strbuf_release(&buf
);
3339 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3341 enum replay_action action
= -1;
3342 sequencer_get_last_command(r
, &action
);
3345 * Check whether the subcommand requested to skip the commit is actually
3346 * in progress and that it's safe to skip the commit.
3348 * opts->action tells us which subcommand requested to skip the commit.
3349 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3350 * action is in progress and we can skip the commit.
3352 * Otherwise we check that the last instruction was related to the
3353 * particular subcommand we're trying to execute and barf if that's not
3356 * Finally we check that the rollback is "safe", i.e., has the HEAD
3357 * moved? In this case, it doesn't make sense to "reset the merge" and
3358 * "skip the commit" as the user already handled this by committing. But
3359 * we'd not want to barf here, instead give advice on how to proceed. We
3360 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3361 * it gets removed when the user commits, so if it still exists we're
3362 * sure the user can't have committed before.
3364 switch (opts
->action
) {
3366 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3367 if (action
!= REPLAY_REVERT
)
3368 return error(_("no revert in progress"));
3369 if (!rollback_is_safe())
3374 if (!refs_ref_exists(get_main_ref_store(r
),
3375 "CHERRY_PICK_HEAD")) {
3376 if (action
!= REPLAY_PICK
)
3377 return error(_("no cherry-pick in progress"));
3378 if (!rollback_is_safe())
3383 BUG("unexpected action in sequencer_skip");
3386 if (skip_single_pick())
3387 return error(_("failed to skip the commit"));
3388 if (!is_directory(git_path_seq_dir()))
3391 return sequencer_continue(r
, opts
);
3394 error(_("there is nothing to skip"));
3396 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3397 advise(_("have you committed already?\n"
3398 "try \"git %s --continue\""),
3399 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3404 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
3406 struct lock_file todo_lock
= LOCK_INIT
;
3407 const char *todo_path
= get_todo_path(opts
);
3408 int next
= todo_list
->current
, offset
, fd
;
3411 * rebase -i writes "git-rebase-todo" without the currently executing
3412 * command, appending it to "done" instead.
3414 if (is_rebase_i(opts
))
3417 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3419 return error_errno(_("could not lock '%s'"), todo_path
);
3420 offset
= get_item_line_offset(todo_list
, next
);
3421 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3422 todo_list
->buf
.len
- offset
) < 0)
3423 return error_errno(_("could not write to '%s'"), todo_path
);
3424 if (commit_lock_file(&todo_lock
) < 0)
3425 return error(_("failed to finalize '%s'"), todo_path
);
3427 if (is_rebase_i(opts
) && next
> 0) {
3428 const char *done
= rebase_path_done();
3429 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3434 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3435 get_item_line_length(todo_list
, next
- 1))
3437 ret
= error_errno(_("could not write to '%s'"), done
);
3439 ret
= error_errno(_("failed to finalize '%s'"), done
);
3445 static int save_opts(struct replay_opts
*opts
)
3447 const char *opts_file
= git_path_opts_file();
3450 if (opts
->no_commit
)
3451 res
|= git_config_set_in_file_gently(opts_file
,
3452 "options.no-commit", "true");
3453 if (opts
->edit
>= 0)
3454 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3455 opts
->edit
? "true" : "false");
3456 if (opts
->allow_empty
)
3457 res
|= git_config_set_in_file_gently(opts_file
,
3458 "options.allow-empty", "true");
3459 if (opts
->allow_empty_message
)
3460 res
|= git_config_set_in_file_gently(opts_file
,
3461 "options.allow-empty-message", "true");
3462 if (opts
->keep_redundant_commits
)
3463 res
|= git_config_set_in_file_gently(opts_file
,
3464 "options.keep-redundant-commits", "true");
3466 res
|= git_config_set_in_file_gently(opts_file
,
3467 "options.signoff", "true");
3468 if (opts
->record_origin
)
3469 res
|= git_config_set_in_file_gently(opts_file
,
3470 "options.record-origin", "true");
3472 res
|= git_config_set_in_file_gently(opts_file
,
3473 "options.allow-ff", "true");
3474 if (opts
->mainline
) {
3475 struct strbuf buf
= STRBUF_INIT
;
3476 strbuf_addf(&buf
, "%d", opts
->mainline
);
3477 res
|= git_config_set_in_file_gently(opts_file
,
3478 "options.mainline", buf
.buf
);
3479 strbuf_release(&buf
);
3482 res
|= git_config_set_in_file_gently(opts_file
,
3483 "options.strategy", opts
->strategy
);
3485 res
|= git_config_set_in_file_gently(opts_file
,
3486 "options.gpg-sign", opts
->gpg_sign
);
3487 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3488 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3489 "options.strategy-option",
3490 opts
->xopts
.v
[i
], "^$", 0);
3491 if (opts
->allow_rerere_auto
)
3492 res
|= git_config_set_in_file_gently(opts_file
,
3493 "options.allow-rerere-auto",
3494 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3497 if (opts
->explicit_cleanup
)
3498 res
|= git_config_set_in_file_gently(opts_file
,
3499 "options.default-msg-cleanup",
3500 describe_cleanup_mode(opts
->default_msg_cleanup
));
3504 static int make_patch(struct repository
*r
,
3505 struct commit
*commit
,
3506 struct replay_opts
*opts
)
3508 struct strbuf buf
= STRBUF_INIT
;
3509 struct rev_info log_tree_opt
;
3510 const char *subject
;
3511 char hex
[GIT_MAX_HEXSZ
+ 1];
3514 oid_to_hex_r(hex
, &commit
->object
.oid
);
3515 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3517 res
|= write_rebase_head(&commit
->object
.oid
);
3519 strbuf_addf(&buf
, "%s/patch", get_dir(opts
));
3520 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3521 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3522 log_tree_opt
.abbrev
= 0;
3523 log_tree_opt
.diff
= 1;
3524 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3525 log_tree_opt
.disable_stdin
= 1;
3526 log_tree_opt
.no_commit_id
= 1;
3527 log_tree_opt
.diffopt
.file
= fopen(buf
.buf
, "w");
3528 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3529 if (!log_tree_opt
.diffopt
.file
)
3530 res
|= error_errno(_("could not open '%s'"), buf
.buf
);
3532 res
|= log_tree_commit(&log_tree_opt
, commit
);
3533 fclose(log_tree_opt
.diffopt
.file
);
3537 strbuf_addf(&buf
, "%s/message", get_dir(opts
));
3538 if (!file_exists(buf
.buf
)) {
3539 const char *encoding
= get_commit_output_encoding();
3540 const char *commit_buffer
= repo_logmsg_reencode(r
,
3543 find_commit_subject(commit_buffer
, &subject
);
3544 res
|= write_message(subject
, strlen(subject
), buf
.buf
, 1);
3545 repo_unuse_commit_buffer(r
, commit
,
3548 strbuf_release(&buf
);
3549 release_revisions(&log_tree_opt
);
3554 static int intend_to_amend(void)
3556 struct object_id head
;
3559 if (repo_get_oid(the_repository
, "HEAD", &head
))
3560 return error(_("cannot read HEAD"));
3562 p
= oid_to_hex(&head
);
3563 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3566 static int error_with_patch(struct repository
*r
,
3567 struct commit
*commit
,
3568 const char *subject
, int subject_len
,
3569 struct replay_opts
*opts
,
3570 int exit_code
, int to_amend
)
3573 if (make_patch(r
, commit
, opts
))
3575 } else if (copy_file(rebase_path_message(),
3576 git_path_merge_msg(r
), 0666))
3577 return error(_("unable to copy '%s' to '%s'"),
3578 git_path_merge_msg(r
), rebase_path_message());
3581 if (intend_to_amend())
3585 _("You can amend the commit now, with\n"
3587 " git commit --amend %s\n"
3589 "Once you are satisfied with your changes, run\n"
3591 " git rebase --continue\n"),
3592 gpg_sign_opt_quoted(opts
));
3593 } else if (exit_code
) {
3595 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3596 short_commit_name(r
, commit
), subject_len
, subject
);
3599 * We don't have the hash of the parent so
3600 * just print the line from the todo file.
3602 fprintf_ln(stderr
, _("Could not merge %.*s"),
3603 subject_len
, subject
);
3609 static int error_failed_squash(struct repository
*r
,
3610 struct commit
*commit
,
3611 struct replay_opts
*opts
,
3613 const char *subject
)
3615 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3616 return error(_("could not copy '%s' to '%s'"),
3617 rebase_path_squash_msg(), rebase_path_message());
3618 unlink(git_path_merge_msg(r
));
3619 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3620 return error(_("could not copy '%s' to '%s'"),
3621 rebase_path_message(),
3622 git_path_merge_msg(r
));
3623 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3626 static int do_exec(struct repository
*r
, const char *command_line
)
3628 struct child_process cmd
= CHILD_PROCESS_INIT
;
3631 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3633 strvec_push(&cmd
.args
, command_line
);
3634 status
= run_command(&cmd
);
3636 /* force re-reading of the cache */
3637 discard_index(r
->index
);
3638 if (repo_read_index(r
) < 0)
3639 return error(_("could not read index"));
3641 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3644 warning(_("execution failed: %s\n%s"
3645 "You can fix the problem, and then run\n"
3647 " git rebase --continue\n"
3650 dirty
? _("and made changes to the index and/or the "
3651 "working tree.\n") : "");
3653 /* command not found */
3656 warning(_("execution succeeded: %s\nbut "
3657 "left changes to the index and/or the working tree.\n"
3658 "Commit or stash your changes, and then run\n"
3660 " git rebase --continue\n"
3661 "\n"), command_line
);
3668 __attribute__((format (printf
, 2, 3)))
3669 static int safe_append(const char *filename
, const char *fmt
, ...)
3672 struct lock_file lock
= LOCK_INIT
;
3673 int fd
= hold_lock_file_for_update(&lock
, filename
,
3674 LOCK_REPORT_ON_ERROR
);
3675 struct strbuf buf
= STRBUF_INIT
;
3680 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3681 error_errno(_("could not read '%s'"), filename
);
3682 rollback_lock_file(&lock
);
3685 strbuf_complete(&buf
, '\n');
3687 strbuf_vaddf(&buf
, fmt
, ap
);
3690 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3691 error_errno(_("could not write to '%s'"), filename
);
3692 strbuf_release(&buf
);
3693 rollback_lock_file(&lock
);
3696 if (commit_lock_file(&lock
) < 0) {
3697 strbuf_release(&buf
);
3698 return error(_("failed to finalize '%s'"), filename
);
3701 strbuf_release(&buf
);
3705 static int do_label(struct repository
*r
, const char *name
, int len
)
3707 struct ref_store
*refs
= get_main_ref_store(r
);
3708 struct ref_transaction
*transaction
;
3709 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3710 struct strbuf msg
= STRBUF_INIT
;
3712 struct object_id head_oid
;
3714 if (len
== 1 && *name
== '#')
3715 return error(_("illegal label name: '%.*s'"), len
, name
);
3717 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3718 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3720 transaction
= ref_store_transaction_begin(refs
, &err
);
3722 error("%s", err
.buf
);
3724 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3725 error(_("could not read HEAD"));
3727 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3728 NULL
, 0, msg
.buf
, &err
) < 0 ||
3729 ref_transaction_commit(transaction
, &err
)) {
3730 error("%s", err
.buf
);
3733 ref_transaction_free(transaction
);
3734 strbuf_release(&err
);
3735 strbuf_release(&msg
);
3738 ret
= safe_append(rebase_path_refs_to_delete(),
3739 "%s\n", ref_name
.buf
);
3740 strbuf_release(&ref_name
);
3745 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3747 if (!opts
->reflog_action
) {
3748 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3749 opts
->reflog_action
=
3750 xstrdup(opts
->reflog_action
? opts
->reflog_action
3751 : action_name(opts
));
3754 return opts
->reflog_action
;
3757 __attribute__((format (printf
, 3, 4)))
3758 static const char *reflog_message(struct replay_opts
*opts
,
3759 const char *sub_action
, const char *fmt
, ...)
3762 static struct strbuf buf
= STRBUF_INIT
;
3766 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3768 strbuf_addf(&buf
, " (%s)", sub_action
);
3770 strbuf_addstr(&buf
, ": ");
3771 strbuf_vaddf(&buf
, fmt
, ap
);
3778 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3779 int len
, struct strbuf
*buf
)
3781 struct commit
*commit
;
3782 struct object_id oid
;
3785 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3786 if (!read_ref(buf
->buf
, &oid
)) {
3787 commit
= lookup_commit_object(r
, &oid
);
3789 /* fall back to non-rewritten ref or commit */
3790 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3791 commit
= lookup_commit_reference_by_name(buf
->buf
);
3795 error(_("could not resolve '%s'"), buf
->buf
);
3800 static int do_reset(struct repository
*r
,
3801 const char *name
, int len
,
3802 struct replay_opts
*opts
)
3804 struct strbuf ref_name
= STRBUF_INIT
;
3805 struct object_id oid
;
3806 struct lock_file lock
= LOCK_INIT
;
3807 struct tree_desc desc
= { 0 };
3809 struct unpack_trees_options unpack_tree_opts
= { 0 };
3812 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3815 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3816 if (!opts
->have_squash_onto
) {
3818 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3819 NULL
, &opts
->squash_onto
,
3821 return error(_("writing fake root commit"));
3822 opts
->have_squash_onto
= 1;
3823 hex
= oid_to_hex(&opts
->squash_onto
);
3824 if (write_message(hex
, strlen(hex
),
3825 rebase_path_squash_onto(), 0))
3826 return error(_("writing squash-onto"));
3828 oidcpy(&oid
, &opts
->squash_onto
);
3831 struct commit
*commit
;
3833 /* Determine the length of the label */
3834 for (i
= 0; i
< len
; i
++)
3835 if (isspace(name
[i
]))
3839 commit
= lookup_label(r
, name
, len
, &ref_name
);
3844 oid
= commit
->object
.oid
;
3847 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3848 unpack_tree_opts
.head_idx
= 1;
3849 unpack_tree_opts
.src_index
= r
->index
;
3850 unpack_tree_opts
.dst_index
= r
->index
;
3851 unpack_tree_opts
.fn
= oneway_merge
;
3852 unpack_tree_opts
.merge
= 1;
3853 unpack_tree_opts
.update
= 1;
3854 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3855 unpack_tree_opts
.skip_cache_tree_update
= 1;
3856 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3858 if (repo_read_index_unmerged(r
)) {
3859 ret
= error_resolve_conflict(action_name(opts
));
3863 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3864 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3868 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3873 tree
= parse_tree_indirect(&oid
);
3874 prime_cache_tree(r
, r
->index
, tree
);
3876 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3877 ret
= error(_("could not write index"));
3880 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3881 len
, name
), "HEAD", &oid
,
3882 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3884 free((void *)desc
.buffer
);
3886 rollback_lock_file(&lock
);
3887 strbuf_release(&ref_name
);
3888 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3892 static int do_merge(struct repository
*r
,
3893 struct commit
*commit
,
3894 const char *arg
, int arg_len
,
3895 int flags
, int *check_todo
, struct replay_opts
*opts
)
3897 int run_commit_flags
= 0;
3898 struct strbuf ref_name
= STRBUF_INIT
;
3899 struct commit
*head_commit
, *merge_commit
, *i
;
3900 struct commit_list
*bases
, *j
;
3901 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3902 const char *strategy
= !opts
->xopts
.nr
&&
3904 !strcmp(opts
->strategy
, "recursive") ||
3905 !strcmp(opts
->strategy
, "ort")) ?
3906 NULL
: opts
->strategy
;
3907 struct merge_options o
;
3908 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3909 static struct lock_file lock
;
3912 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3917 head_commit
= lookup_commit_reference_by_name("HEAD");
3919 ret
= error(_("cannot merge without a current revision"));
3924 * For octopus merges, the arg starts with the list of revisions to be
3925 * merged. The list is optionally followed by '#' and the oneline.
3927 merge_arg_len
= oneline_offset
= arg_len
;
3928 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3931 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3932 p
+= 1 + strspn(p
+ 1, " \t\n");
3933 oneline_offset
= p
- arg
;
3936 k
= strcspn(p
, " \t\n");
3939 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3940 if (!merge_commit
) {
3941 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3944 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3946 merge_arg_len
= p
- arg
;
3950 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3954 if (opts
->have_squash_onto
&&
3955 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3957 * When the user tells us to "merge" something into a
3958 * "[new root]", let's simply fast-forward to the merge head.
3960 rollback_lock_file(&lock
);
3962 ret
= error(_("octopus merge cannot be executed on "
3963 "top of a [new root]"));
3965 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3966 &head_commit
->object
.oid
, 0,
3972 * If HEAD is not identical to the first parent of the original merge
3973 * commit, we cannot fast-forward.
3975 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3976 oideq(&commit
->parents
->item
->object
.oid
,
3977 &head_commit
->object
.oid
);
3980 * If any merge head is different from the original one, we cannot
3983 if (can_fast_forward
) {
3984 struct commit_list
*p
= commit
->parents
->next
;
3986 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
3987 if (!oideq(&j
->item
->object
.oid
,
3988 &p
->item
->object
.oid
)) {
3989 can_fast_forward
= 0;
3993 * If the number of merge heads differs from the original merge
3994 * commit, we cannot fast-forward.
3997 can_fast_forward
= 0;
4000 if (can_fast_forward
) {
4001 rollback_lock_file(&lock
);
4002 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4003 &head_commit
->object
.oid
, 0, opts
);
4004 if (flags
& TODO_EDIT_MERGE_MSG
)
4005 goto fast_forward_edit
;
4011 const char *encoding
= get_commit_output_encoding();
4012 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4018 ret
= error(_("could not get commit message of '%s'"),
4019 oid_to_hex(&commit
->object
.oid
));
4022 write_author_script(message
);
4023 find_commit_subject(message
, &body
);
4025 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4026 repo_unuse_commit_buffer(r
, commit
, message
);
4028 error_errno(_("could not write '%s'"),
4029 git_path_merge_msg(r
));
4033 struct strbuf buf
= STRBUF_INIT
;
4036 strbuf_addf(&buf
, "author %s", git_author_info(0));
4037 write_author_script(buf
.buf
);
4040 if (oneline_offset
< arg_len
) {
4041 p
= arg
+ oneline_offset
;
4042 len
= arg_len
- oneline_offset
;
4044 strbuf_addf(&buf
, "Merge %s '%.*s'",
4045 to_merge
->next
? "branches" : "branch",
4046 merge_arg_len
, arg
);
4051 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4052 strbuf_release(&buf
);
4054 error_errno(_("could not write '%s'"),
4055 git_path_merge_msg(r
));
4060 if (strategy
|| to_merge
->next
) {
4062 struct child_process cmd
= CHILD_PROCESS_INIT
;
4064 if (read_env_script(&cmd
.env
)) {
4065 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4067 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4071 if (opts
->committer_date_is_author_date
)
4072 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4075 author_date_from_env(&cmd
.env
));
4076 if (opts
->ignore_date
)
4077 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4080 strvec_push(&cmd
.args
, "merge");
4081 strvec_push(&cmd
.args
, "-s");
4083 strvec_push(&cmd
.args
, "octopus");
4085 strvec_push(&cmd
.args
, strategy
);
4086 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4087 strvec_pushf(&cmd
.args
,
4088 "-X%s", opts
->xopts
.v
[k
]);
4090 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4091 strvec_push(&cmd
.args
, "--no-edit");
4093 strvec_push(&cmd
.args
, "--edit");
4094 strvec_push(&cmd
.args
, "--no-ff");
4095 strvec_push(&cmd
.args
, "--no-log");
4096 strvec_push(&cmd
.args
, "--no-stat");
4097 strvec_push(&cmd
.args
, "-F");
4098 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4100 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4102 strvec_push(&cmd
.args
, "--no-gpg-sign");
4104 /* Add the tips to be merged */
4105 for (j
= to_merge
; j
; j
= j
->next
)
4106 strvec_push(&cmd
.args
,
4107 oid_to_hex(&j
->item
->object
.oid
));
4109 strbuf_release(&ref_name
);
4110 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4112 rollback_lock_file(&lock
);
4114 ret
= run_command(&cmd
);
4116 /* force re-reading of the cache */
4118 discard_index(r
->index
);
4119 if (repo_read_index(r
) < 0)
4120 ret
= error(_("could not read index"));
4125 merge_commit
= to_merge
->item
;
4126 bases
= repo_get_merge_bases(r
, head_commit
, merge_commit
);
4127 if (bases
&& oideq(&merge_commit
->object
.oid
,
4128 &bases
->item
->object
.oid
)) {
4130 /* skip merging an ancestor of HEAD */
4134 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4135 git_path_merge_head(r
), 0);
4136 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4138 bases
= reverse_commit_list(bases
);
4141 init_merge_options(&o
, r
);
4143 o
.branch2
= ref_name
.buf
;
4144 o
.buffer_output
= 2;
4146 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4148 * TODO: Should use merge_incore_recursive() and
4149 * merge_switch_to_result(), skipping the call to
4150 * merge_switch_to_result() when we don't actually need to
4151 * update the index and working copy immediately.
4153 ret
= merge_ort_recursive(&o
,
4154 head_commit
, merge_commit
, bases
,
4157 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4161 fputs(o
.obuf
.buf
, stdout
);
4162 strbuf_release(&o
.obuf
);
4164 error(_("could not even attempt to merge '%.*s'"),
4165 merge_arg_len
, arg
);
4169 * The return value of merge_recursive() is 1 on clean, and 0 on
4172 * Let's reverse that, so that do_merge() returns 0 upon success and
4173 * 1 upon failed merge (keeping the return value -1 for the cases where
4174 * we will want to reschedule the `merge` command).
4178 if (r
->index
->cache_changed
&&
4179 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4180 ret
= error(_("merge: Unable to write new index file"));
4184 rollback_lock_file(&lock
);
4186 repo_rerere(r
, opts
->allow_rerere_auto
);
4189 * In case of problems, we now want to return a positive
4190 * value (a negative one would indicate that the `merge`
4191 * command needs to be rescheduled).
4193 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4196 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4199 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4200 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4205 strbuf_release(&ref_name
);
4206 rollback_lock_file(&lock
);
4207 free_commit_list(to_merge
);
4211 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4214 struct lock_file lock
= LOCK_INIT
;
4216 struct string_list_item
*item
;
4219 path
= rebase_path_update_refs(the_repository
->gitdir
);
4221 if (!refs_to_oids
->nr
) {
4222 if (unlink(path
) && errno
!= ENOENT
)
4223 result
= error_errno(_("could not unlink: %s"), path
);
4227 if (safe_create_leading_directories(path
)) {
4228 result
= error(_("unable to create leading directories of %s"),
4233 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4234 result
= error(_("another 'rebase' process appears to be running; "
4235 "'%s.lock' already exists"),
4240 fp
= fdopen_lock_file(&lock
, "w");
4242 result
= error_errno(_("could not open '%s' for writing"), path
);
4243 rollback_lock_file(&lock
);
4247 for_each_string_list_item(item
, refs_to_oids
) {
4248 struct update_ref_record
*rec
= item
->util
;
4249 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4250 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4253 result
= commit_lock_file(&lock
);
4261 * Parse the update-refs file for the current rebase, then remove the
4262 * refs that do not appear in the todo_list (and have not had updated
4263 * values stored) and add refs that are in the todo_list but not
4264 * represented in the update-refs file.
4266 * If there are changes to the update-refs list, then write the new state
4269 void todo_list_filter_update_refs(struct repository
*r
,
4270 struct todo_list
*todo_list
)
4274 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4276 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4279 * For each item in the update_refs list, if it has no updated
4280 * value and does not appear in the todo_list, then remove it
4281 * from the update_refs list.
4283 for (i
= 0; i
< update_refs
.nr
; i
++) {
4286 const char *ref
= update_refs
.items
[i
].string
;
4287 size_t reflen
= strlen(ref
);
4288 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4290 /* OID already stored as updated. */
4291 if (!is_null_oid(&rec
->after
))
4294 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4295 struct todo_item
*item
= &todo_list
->items
[j
];
4296 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4298 if (item
->command
!= TODO_UPDATE_REF
)
4301 if (item
->arg_len
!= reflen
||
4302 strncmp(arg
, ref
, reflen
))
4309 free(update_refs
.items
[i
].string
);
4310 free(update_refs
.items
[i
].util
);
4313 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4321 * For each todo_item, check if its ref is in the update_refs list.
4322 * If not, then add it as an un-updated ref.
4324 for (i
= 0; i
< todo_list
->nr
; i
++) {
4325 struct todo_item
*item
= &todo_list
->items
[i
];
4326 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4329 if (item
->command
!= TODO_UPDATE_REF
)
4332 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4333 const char *ref
= update_refs
.items
[j
].string
;
4335 found
= strlen(ref
) == item
->arg_len
&&
4336 !strncmp(ref
, arg
, item
->arg_len
);
4340 struct string_list_item
*inserted
;
4341 struct strbuf argref
= STRBUF_INIT
;
4343 strbuf_add(&argref
, arg
, item
->arg_len
);
4344 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4345 inserted
->util
= init_update_ref_record(argref
.buf
);
4346 strbuf_release(&argref
);
4352 write_update_refs_state(&update_refs
);
4353 string_list_clear(&update_refs
, 1);
4356 static int do_update_ref(struct repository
*r
, const char *refname
)
4358 struct string_list_item
*item
;
4359 struct string_list list
= STRING_LIST_INIT_DUP
;
4361 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4364 for_each_string_list_item(item
, &list
) {
4365 if (!strcmp(item
->string
, refname
)) {
4366 struct update_ref_record
*rec
= item
->util
;
4367 if (read_ref("HEAD", &rec
->after
))
4373 write_update_refs_state(&list
);
4374 string_list_clear(&list
, 1);
4378 static int do_update_refs(struct repository
*r
, int quiet
)
4381 struct string_list_item
*item
;
4382 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4383 struct ref_store
*refs
= get_main_ref_store(r
);
4384 struct strbuf update_msg
= STRBUF_INIT
;
4385 struct strbuf error_msg
= STRBUF_INIT
;
4387 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4390 for_each_string_list_item(item
, &refs_to_oids
) {
4391 struct update_ref_record
*rec
= item
->util
;
4394 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4396 &rec
->after
, &rec
->before
,
4397 0, UPDATE_REFS_MSG_ON_ERR
);
4404 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4406 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4410 (update_msg
.len
|| error_msg
.len
)) {
4412 _("Updated the following refs with %s:\n%s"),
4418 _("Failed to update the following refs with %s:\n%s"),
4423 string_list_clear(&refs_to_oids
, 1);
4424 strbuf_release(&update_msg
);
4425 strbuf_release(&error_msg
);
4429 static int is_final_fixup(struct todo_list
*todo_list
)
4431 int i
= todo_list
->current
;
4433 if (!is_fixup(todo_list
->items
[i
].command
))
4436 while (++i
< todo_list
->nr
)
4437 if (is_fixup(todo_list
->items
[i
].command
))
4439 else if (!is_noop(todo_list
->items
[i
].command
))
4444 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4448 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4449 if (!is_noop(todo_list
->items
[i
].command
))
4450 return todo_list
->items
[i
].command
;
4455 void create_autostash(struct repository
*r
, const char *path
)
4457 struct strbuf buf
= STRBUF_INIT
;
4458 struct lock_file lock_file
= LOCK_INIT
;
4461 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4462 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4464 repo_update_index_if_able(r
, &lock_file
);
4465 rollback_lock_file(&lock_file
);
4467 if (has_unstaged_changes(r
, 1) ||
4468 has_uncommitted_changes(r
, 1)) {
4469 struct child_process stash
= CHILD_PROCESS_INIT
;
4470 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4471 struct object_id oid
;
4473 strvec_pushl(&stash
.args
,
4474 "stash", "create", "autostash", NULL
);
4478 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4479 die(_("Cannot autostash"));
4480 strbuf_trim_trailing_newline(&buf
);
4481 if (repo_get_oid(r
, buf
.buf
, &oid
))
4482 die(_("Unexpected stash response: '%s'"),
4485 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4487 if (safe_create_leading_directories_const(path
))
4488 die(_("Could not create directory for '%s'"),
4490 write_file(path
, "%s", oid_to_hex(&oid
));
4491 printf(_("Created autostash: %s\n"), buf
.buf
);
4492 if (reset_head(r
, &ropts
) < 0)
4493 die(_("could not reset --hard"));
4494 discard_index(r
->index
);
4495 if (repo_read_index(r
) < 0)
4496 die(_("could not read index"));
4498 strbuf_release(&buf
);
4501 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4503 struct child_process child
= CHILD_PROCESS_INIT
;
4506 if (attempt_apply
) {
4508 child
.no_stdout
= 1;
4509 child
.no_stderr
= 1;
4510 strvec_push(&child
.args
, "stash");
4511 strvec_push(&child
.args
, "apply");
4512 strvec_push(&child
.args
, stash_oid
);
4513 ret
= run_command(&child
);
4516 if (attempt_apply
&& !ret
)
4517 fprintf(stderr
, _("Applied autostash.\n"));
4519 struct child_process store
= CHILD_PROCESS_INIT
;
4522 strvec_push(&store
.args
, "stash");
4523 strvec_push(&store
.args
, "store");
4524 strvec_push(&store
.args
, "-m");
4525 strvec_push(&store
.args
, "autostash");
4526 strvec_push(&store
.args
, "-q");
4527 strvec_push(&store
.args
, stash_oid
);
4528 if (run_command(&store
))
4529 ret
= error(_("cannot store %s"), stash_oid
);
4533 "Your changes are safe in the stash.\n"
4534 "You can run \"git stash pop\" or"
4535 " \"git stash drop\" at any time.\n"),
4537 _("Applying autostash resulted in conflicts.") :
4538 _("Autostash exists; creating a new stash entry."));
4544 static int apply_save_autostash(const char *path
, int attempt_apply
)
4546 struct strbuf stash_oid
= STRBUF_INIT
;
4549 if (!read_oneliner(&stash_oid
, path
,
4550 READ_ONELINER_SKIP_IF_EMPTY
)) {
4551 strbuf_release(&stash_oid
);
4554 strbuf_trim(&stash_oid
);
4556 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4559 strbuf_release(&stash_oid
);
4563 int save_autostash(const char *path
)
4565 return apply_save_autostash(path
, 0);
4568 int apply_autostash(const char *path
)
4570 return apply_save_autostash(path
, 1);
4573 int apply_autostash_oid(const char *stash_oid
)
4575 return apply_save_autostash_oid(stash_oid
, 1);
4578 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4579 const char *onto_name
, const struct object_id
*onto
,
4580 const struct object_id
*orig_head
)
4582 struct reset_head_opts ropts
= {
4584 .orig_head
= orig_head
,
4585 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4586 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4587 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4589 .default_reflog_action
= sequencer_reflog_action(opts
)
4591 if (reset_head(r
, &ropts
)) {
4592 apply_autostash(rebase_path_autostash());
4593 sequencer_remove_state(opts
);
4594 return error(_("could not detach HEAD"));
4600 static int stopped_at_head(struct repository
*r
)
4602 struct object_id head
;
4603 struct commit
*commit
;
4604 struct commit_message message
;
4606 if (repo_get_oid(r
, "HEAD", &head
) ||
4607 !(commit
= lookup_commit(r
, &head
)) ||
4608 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4609 fprintf(stderr
, _("Stopped at HEAD\n"));
4611 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4612 free_message(commit
, &message
);
4618 static int reread_todo_if_changed(struct repository
*r
,
4619 struct todo_list
*todo_list
,
4620 struct replay_opts
*opts
)
4623 struct strbuf buf
= STRBUF_INIT
;
4625 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4627 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4628 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4629 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4630 /* Reread the todo file if it has changed. */
4631 todo_list_release(todo_list
);
4632 if (read_populate_todo(r
, todo_list
, opts
))
4633 return -1; /* message was printed */
4634 /* `current` will be incremented on return */
4635 todo_list
->current
= -1;
4637 strbuf_release(&buf
);
4642 static const char rescheduled_advice
[] =
4643 N_("Could not execute the todo command\n"
4647 "It has been rescheduled; To edit the command before continuing, please\n"
4648 "edit the todo list first:\n"
4650 " git rebase --edit-todo\n"
4651 " git rebase --continue\n");
4653 static int pick_commits(struct repository
*r
,
4654 struct todo_list
*todo_list
,
4655 struct replay_opts
*opts
)
4657 int res
= 0, reschedule
= 0;
4659 opts
->reflog_message
= sequencer_reflog_action(opts
);
4661 assert(!(opts
->signoff
|| opts
->no_commit
||
4662 opts
->record_origin
|| should_edit(opts
) ||
4663 opts
->committer_date_is_author_date
||
4664 opts
->ignore_date
));
4665 if (read_and_refresh_cache(r
, opts
))
4668 while (todo_list
->current
< todo_list
->nr
) {
4669 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4670 const char *arg
= todo_item_get_arg(todo_list
, item
);
4673 if (save_todo(todo_list
, opts
))
4675 if (is_rebase_i(opts
)) {
4676 if (item
->command
!= TODO_COMMENT
) {
4677 FILE *f
= fopen(rebase_path_msgnum(), "w");
4679 todo_list
->done_nr
++;
4682 fprintf(f
, "%d\n", todo_list
->done_nr
);
4686 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4688 todo_list
->total_nr
,
4689 opts
->verbose
? "\n" : "\r");
4691 unlink(rebase_path_message());
4692 unlink(rebase_path_author_script());
4693 unlink(rebase_path_stopped_sha());
4694 unlink(rebase_path_amend());
4695 unlink(git_path_merge_head(r
));
4696 unlink(git_path_auto_merge(r
));
4697 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
4699 if (item
->command
== TODO_BREAK
) {
4702 return stopped_at_head(r
);
4705 if (item
->command
<= TODO_SQUASH
) {
4706 if (is_rebase_i(opts
))
4707 opts
->reflog_message
= reflog_message(opts
,
4708 command_to_string(item
->command
), NULL
);
4710 res
= do_pick_commit(r
, item
, opts
,
4711 is_final_fixup(todo_list
),
4713 if (is_rebase_i(opts
) && res
< 0) {
4715 advise(_(rescheduled_advice
),
4716 get_item_line_length(todo_list
,
4717 todo_list
->current
),
4718 get_item_line(todo_list
,
4719 todo_list
->current
));
4720 todo_list
->current
--;
4721 if (save_todo(todo_list
, opts
))
4724 if (item
->command
== TODO_EDIT
) {
4725 struct commit
*commit
= item
->commit
;
4730 _("Stopped at %s... %.*s\n"),
4731 short_commit_name(r
, commit
),
4732 item
->arg_len
, arg
);
4734 return error_with_patch(r
, commit
,
4735 arg
, item
->arg_len
, opts
, res
, !res
);
4737 if (is_rebase_i(opts
) && !res
)
4738 record_in_rewritten(&item
->commit
->object
.oid
,
4739 peek_command(todo_list
, 1));
4740 if (res
&& is_fixup(item
->command
)) {
4743 return error_failed_squash(r
, item
->commit
, opts
,
4744 item
->arg_len
, arg
);
4745 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4747 struct object_id oid
;
4750 * If we are rewording and have either
4751 * fast-forwarded already, or are about to
4752 * create a new root commit, we want to amend,
4753 * otherwise we do not.
4755 if (item
->command
== TODO_REWORD
&&
4756 !repo_get_oid(r
, "HEAD", &oid
) &&
4757 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4758 (opts
->have_squash_onto
&&
4759 oideq(&opts
->squash_onto
, &oid
))))
4762 return res
| error_with_patch(r
, item
->commit
,
4763 arg
, item
->arg_len
, opts
,
4766 } else if (item
->command
== TODO_EXEC
) {
4767 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4768 int saved
= *end_of_arg
;
4773 res
= do_exec(r
, arg
);
4774 *end_of_arg
= saved
;
4777 if (opts
->reschedule_failed_exec
)
4781 } else if (item
->command
== TODO_LABEL
) {
4782 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4784 } else if (item
->command
== TODO_RESET
) {
4785 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4787 } else if (item
->command
== TODO_MERGE
) {
4788 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4789 item
->flags
, &check_todo
, opts
)) < 0)
4791 else if (item
->commit
)
4792 record_in_rewritten(&item
->commit
->object
.oid
,
4793 peek_command(todo_list
, 1));
4795 /* failed with merge conflicts */
4796 return error_with_patch(r
, item
->commit
,
4799 } else if (item
->command
== TODO_UPDATE_REF
) {
4800 struct strbuf ref
= STRBUF_INIT
;
4801 strbuf_add(&ref
, arg
, item
->arg_len
);
4802 if ((res
= do_update_ref(r
, ref
.buf
)))
4804 strbuf_release(&ref
);
4805 } else if (!is_noop(item
->command
))
4806 return error(_("unknown command %d"), item
->command
);
4809 advise(_(rescheduled_advice
),
4810 get_item_line_length(todo_list
,
4811 todo_list
->current
),
4812 get_item_line(todo_list
, todo_list
->current
));
4813 todo_list
->current
--;
4814 if (save_todo(todo_list
, opts
))
4817 return error_with_patch(r
,
4821 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4822 reread_todo_if_changed(r
, todo_list
, opts
)) {
4826 todo_list
->current
++;
4831 if (is_rebase_i(opts
)) {
4832 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4835 /* Stopped in the middle, as planned? */
4836 if (todo_list
->current
< todo_list
->nr
)
4839 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4840 starts_with(head_ref
.buf
, "refs/")) {
4842 struct object_id head
, orig
;
4845 if (repo_get_oid(r
, "HEAD", &head
)) {
4846 res
= error(_("cannot read HEAD"));
4848 strbuf_release(&head_ref
);
4849 strbuf_release(&buf
);
4852 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4853 get_oid_hex(buf
.buf
, &orig
)) {
4854 res
= error(_("could not read orig-head"));
4855 goto cleanup_head_ref
;
4858 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4859 res
= error(_("could not read 'onto'"));
4860 goto cleanup_head_ref
;
4862 msg
= reflog_message(opts
, "finish", "%s onto %s",
4863 head_ref
.buf
, buf
.buf
);
4864 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4865 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4866 res
= error(_("could not update %s"),
4868 goto cleanup_head_ref
;
4870 msg
= reflog_message(opts
, "finish", "returning to %s",
4872 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4873 res
= error(_("could not update HEAD to %s"),
4875 goto cleanup_head_ref
;
4880 if (opts
->verbose
) {
4881 struct rev_info log_tree_opt
;
4882 struct object_id orig
, head
;
4884 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4885 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4886 log_tree_opt
.diff
= 1;
4887 log_tree_opt
.diffopt
.output_format
=
4888 DIFF_FORMAT_DIFFSTAT
;
4889 log_tree_opt
.disable_stdin
= 1;
4891 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4892 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4893 !repo_get_oid(r
, "HEAD", &head
)) {
4894 diff_tree_oid(&orig
, &head
, "",
4895 &log_tree_opt
.diffopt
);
4896 log_tree_diff_flush(&log_tree_opt
);
4898 release_revisions(&log_tree_opt
);
4900 flush_rewritten_pending();
4901 if (!stat(rebase_path_rewritten_list(), &st
) &&
4903 struct child_process child
= CHILD_PROCESS_INIT
;
4904 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4906 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4908 strvec_push(&child
.args
, "notes");
4909 strvec_push(&child
.args
, "copy");
4910 strvec_push(&child
.args
, "--for-rewrite=rebase");
4911 /* we don't care if this copying failed */
4912 run_command(&child
);
4914 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4915 strvec_push(&hook_opt
.args
, "rebase");
4916 run_hooks_opt("post-rewrite", &hook_opt
);
4918 apply_autostash(rebase_path_autostash());
4924 _("Successfully rebased and updated %s.\n"),
4928 strbuf_release(&buf
);
4929 strbuf_release(&head_ref
);
4931 if (do_update_refs(r
, opts
->quiet
))
4936 * Sequence of picks finished successfully; cleanup by
4937 * removing the .git/sequencer directory
4939 return sequencer_remove_state(opts
);
4942 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
4944 struct child_process cmd
= CHILD_PROCESS_INIT
;
4946 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
4947 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
4948 return error(_("no cherry-pick or revert in progress"));
4951 strvec_push(&cmd
.args
, "commit");
4954 * continue_single_pick() handles the case of recovering from a
4955 * conflict. should_edit() doesn't handle that case; for a conflict,
4956 * we want to edit if the user asked for it, or if they didn't specify
4957 * and stdin is a tty.
4959 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
4961 * Include --cleanup=strip as well because we don't want the
4962 * "# Conflicts:" messages.
4964 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
4966 return run_command(&cmd
);
4969 static int commit_staged_changes(struct repository
*r
,
4970 struct replay_opts
*opts
,
4971 struct todo_list
*todo_list
)
4973 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
4974 unsigned int final_fixup
= 0, is_clean
;
4976 if (has_unstaged_changes(r
, 1))
4977 return error(_("cannot rebase: You have unstaged changes."));
4979 is_clean
= !has_uncommitted_changes(r
, 0);
4981 if (file_exists(rebase_path_amend())) {
4982 struct strbuf rev
= STRBUF_INIT
;
4983 struct object_id head
, to_amend
;
4985 if (repo_get_oid(r
, "HEAD", &head
))
4986 return error(_("cannot amend non-existing commit"));
4987 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
4988 return error(_("invalid file: '%s'"), rebase_path_amend());
4989 if (get_oid_hex(rev
.buf
, &to_amend
))
4990 return error(_("invalid contents: '%s'"),
4991 rebase_path_amend());
4992 if (!is_clean
&& !oideq(&head
, &to_amend
))
4993 return error(_("\nYou have uncommitted changes in your "
4994 "working tree. Please, commit them\n"
4995 "first and then run 'git rebase "
4996 "--continue' again."));
4998 * When skipping a failed fixup/squash, we need to edit the
4999 * commit message, the current fixup list and count, and if it
5000 * was the last fixup/squash in the chain, we need to clean up
5001 * the commit message and if there was a squash, let the user
5004 if (!is_clean
|| !opts
->current_fixup_count
)
5005 ; /* this is not the final fixup */
5006 else if (!oideq(&head
, &to_amend
) ||
5007 !file_exists(rebase_path_stopped_sha())) {
5008 /* was a final fixup or squash done manually? */
5009 if (!is_fixup(peek_command(todo_list
, 0))) {
5010 unlink(rebase_path_fixup_msg());
5011 unlink(rebase_path_squash_msg());
5012 unlink(rebase_path_current_fixups());
5013 strbuf_reset(&opts
->current_fixups
);
5014 opts
->current_fixup_count
= 0;
5017 /* we are in a fixup/squash chain */
5018 const char *p
= opts
->current_fixups
.buf
;
5019 int len
= opts
->current_fixups
.len
;
5021 opts
->current_fixup_count
--;
5023 BUG("Incorrect current_fixups:\n%s", p
);
5024 while (len
&& p
[len
- 1] != '\n')
5026 strbuf_setlen(&opts
->current_fixups
, len
);
5027 if (write_message(p
, len
, rebase_path_current_fixups(),
5029 return error(_("could not write file: '%s'"),
5030 rebase_path_current_fixups());
5033 * If a fixup/squash in a fixup/squash chain failed, the
5034 * commit message is already correct, no need to commit
5037 * Only if it is the final command in the fixup/squash
5038 * chain, and only if the chain is longer than a single
5039 * fixup/squash command (which was just skipped), do we
5040 * actually need to re-commit with a cleaned up commit
5043 if (opts
->current_fixup_count
> 0 &&
5044 !is_fixup(peek_command(todo_list
, 0))) {
5047 * If there was not a single "squash" in the
5048 * chain, we only need to clean up the commit
5049 * message, no need to bother the user with
5050 * opening the commit message in the editor.
5052 if (!starts_with(p
, "squash ") &&
5053 !strstr(p
, "\nsquash "))
5054 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5055 } else if (is_fixup(peek_command(todo_list
, 0))) {
5057 * We need to update the squash message to skip
5058 * the latest commit message.
5061 struct commit
*commit
;
5063 const char *path
= rebase_path_squash_msg();
5064 const char *encoding
= get_commit_output_encoding();
5066 if (parse_head(r
, &commit
))
5067 return error(_("could not parse HEAD"));
5069 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5071 res
= error(_("could not parse commit %s"),
5072 oid_to_hex(&commit
->object
.oid
));
5073 goto unuse_commit_buffer
;
5075 find_commit_subject(p
, &msg
);
5076 if (write_message(msg
, strlen(msg
), path
, 0)) {
5077 res
= error(_("could not write file: "
5079 goto unuse_commit_buffer
;
5081 unuse_commit_buffer
:
5082 repo_unuse_commit_buffer(r
, commit
, p
);
5088 strbuf_release(&rev
);
5093 if (refs_ref_exists(get_main_ref_store(r
),
5094 "CHERRY_PICK_HEAD") &&
5095 refs_delete_ref(get_main_ref_store(r
), "",
5096 "CHERRY_PICK_HEAD", NULL
, 0))
5097 return error(_("could not remove CHERRY_PICK_HEAD"));
5098 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5099 return error_errno(_("could not remove '%s'"),
5100 git_path_merge_msg(r
));
5105 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5107 return error(_("could not commit staged changes."));
5108 unlink(rebase_path_amend());
5109 unlink(git_path_merge_head(r
));
5110 unlink(git_path_auto_merge(r
));
5112 unlink(rebase_path_fixup_msg());
5113 unlink(rebase_path_squash_msg());
5115 if (opts
->current_fixup_count
> 0) {
5117 * Whether final fixup or not, we just cleaned up the commit
5120 unlink(rebase_path_current_fixups());
5121 strbuf_reset(&opts
->current_fixups
);
5122 opts
->current_fixup_count
= 0;
5127 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5129 struct todo_list todo_list
= TODO_LIST_INIT
;
5132 if (read_and_refresh_cache(r
, opts
))
5135 if (read_populate_opts(opts
))
5137 if (is_rebase_i(opts
)) {
5138 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5139 goto release_todo_list
;
5141 if (file_exists(rebase_path_dropped())) {
5142 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5143 goto release_todo_list
;
5145 unlink(rebase_path_dropped());
5148 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5149 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5151 goto release_todo_list
;
5153 } else if (!file_exists(get_todo_path(opts
)))
5154 return continue_single_pick(r
, opts
);
5155 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5156 goto release_todo_list
;
5158 if (!is_rebase_i(opts
)) {
5159 /* Verify that the conflict has been resolved */
5160 if (refs_ref_exists(get_main_ref_store(r
),
5161 "CHERRY_PICK_HEAD") ||
5162 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5163 res
= continue_single_pick(r
, opts
);
5165 goto release_todo_list
;
5167 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5168 res
= error_dirty_index(r
, opts
);
5169 goto release_todo_list
;
5171 todo_list
.current
++;
5172 } else if (file_exists(rebase_path_stopped_sha())) {
5173 struct strbuf buf
= STRBUF_INIT
;
5174 struct object_id oid
;
5176 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5177 READ_ONELINER_SKIP_IF_EMPTY
) &&
5178 !get_oid_hex(buf
.buf
, &oid
))
5179 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5180 strbuf_release(&buf
);
5183 res
= pick_commits(r
, &todo_list
, opts
);
5185 todo_list_release(&todo_list
);
5189 static int single_pick(struct repository
*r
,
5190 struct commit
*cmit
,
5191 struct replay_opts
*opts
)
5194 struct todo_item item
;
5196 item
.command
= opts
->action
== REPLAY_PICK
?
5197 TODO_PICK
: TODO_REVERT
;
5200 opts
->reflog_message
= sequencer_reflog_action(opts
);
5201 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5204 int sequencer_pick_revisions(struct repository
*r
,
5205 struct replay_opts
*opts
)
5207 struct todo_list todo_list
= TODO_LIST_INIT
;
5208 struct object_id oid
;
5212 if (read_and_refresh_cache(r
, opts
))
5215 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5216 struct object_id oid
;
5217 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5219 /* This happens when using --stdin. */
5223 if (!repo_get_oid(r
, name
, &oid
)) {
5224 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5225 enum object_type type
= oid_object_info(r
,
5228 return error(_("%s: can't cherry-pick a %s"),
5229 name
, type_name(type
));
5232 return error(_("%s: bad revision"), name
);
5236 * If we were called as "git cherry-pick <commit>", just
5237 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5238 * REVERT_HEAD, and don't touch the sequencer state.
5239 * This means it is possible to cherry-pick in the middle
5240 * of a cherry-pick sequence.
5242 if (opts
->revs
->cmdline
.nr
== 1 &&
5243 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5244 opts
->revs
->no_walk
&&
5245 !opts
->revs
->cmdline
.rev
->flags
) {
5246 struct commit
*cmit
;
5247 if (prepare_revision_walk(opts
->revs
))
5248 return error(_("revision walk setup failed"));
5249 cmit
= get_revision(opts
->revs
);
5251 return error(_("empty commit set passed"));
5252 if (get_revision(opts
->revs
))
5253 BUG("unexpected extra commit from walk");
5254 return single_pick(r
, cmit
, opts
);
5258 * Start a new cherry-pick/ revert sequence; but
5259 * first, make sure that an existing one isn't in
5263 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5264 create_seq_dir(r
) < 0)
5266 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5267 return error(_("can't revert as initial commit"));
5268 if (save_head(oid_to_hex(&oid
)))
5270 if (save_opts(opts
))
5272 update_abort_safety_file();
5273 res
= pick_commits(r
, &todo_list
, opts
);
5274 todo_list_release(&todo_list
);
5278 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5280 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5281 struct strbuf sob
= STRBUF_INIT
;
5284 strbuf_addstr(&sob
, sign_off_header
);
5285 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5286 strbuf_addch(&sob
, '\n');
5289 strbuf_complete_line(msgbuf
);
5292 * If the whole message buffer is equal to the sob, pretend that we
5293 * found a conforming footer with a matching sob
5295 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5296 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5299 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5302 const char *append_newlines
= NULL
;
5303 size_t len
= msgbuf
->len
- ignore_footer
;
5307 * The buffer is completely empty. Leave foom for
5308 * the title and body to be filled in by the user.
5310 append_newlines
= "\n\n";
5311 } else if (len
== 1) {
5313 * Buffer contains a single newline. Add another
5314 * so that we leave room for the title and body.
5316 append_newlines
= "\n";
5317 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5319 * Buffer ends with a single newline. Add another
5320 * so that there is an empty line between the message
5323 append_newlines
= "\n";
5324 } /* else, the buffer already ends with two newlines. */
5326 if (append_newlines
)
5327 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5328 append_newlines
, strlen(append_newlines
));
5331 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5332 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5335 strbuf_release(&sob
);
5338 struct labels_entry
{
5339 struct hashmap_entry entry
;
5340 char label
[FLEX_ARRAY
];
5343 static int labels_cmp(const void *fndata UNUSED
,
5344 const struct hashmap_entry
*eptr
,
5345 const struct hashmap_entry
*entry_or_key
, const void *key
)
5347 const struct labels_entry
*a
, *b
;
5349 a
= container_of(eptr
, const struct labels_entry
, entry
);
5350 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5352 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5355 struct string_entry
{
5356 struct oidmap_entry entry
;
5357 char string
[FLEX_ARRAY
];
5360 struct label_state
{
5361 struct oidmap commit2label
;
5362 struct hashmap labels
;
5364 int max_label_length
;
5367 static const char *label_oid(struct object_id
*oid
, const char *label
,
5368 struct label_state
*state
)
5370 struct labels_entry
*labels_entry
;
5371 struct string_entry
*string_entry
;
5372 struct object_id dummy
;
5375 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5377 return string_entry
->string
;
5380 * For "uninteresting" commits, i.e. commits that are not to be
5381 * rebased, and which can therefore not be labeled, we use a unique
5382 * abbreviation of the commit name. This is slightly more complicated
5383 * than calling repo_find_unique_abbrev() because we also need to make
5384 * sure that the abbreviation does not conflict with any other
5387 * We disallow "interesting" commits to be labeled by a string that
5388 * is a valid full-length hash, to ensure that we always can find an
5389 * abbreviation for any uninteresting commit's names that does not
5390 * clash with any other label.
5392 strbuf_reset(&state
->buf
);
5396 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5397 label
= p
= state
->buf
.buf
;
5399 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5403 * We may need to extend the abbreviated hash so that there is
5404 * no conflicting label.
5406 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5407 size_t i
= strlen(p
) + 1;
5409 oid_to_hex_r(p
, oid
);
5410 for (; i
< the_hash_algo
->hexsz
; i
++) {
5413 if (!hashmap_get_from_hash(&state
->labels
,
5420 struct strbuf
*buf
= &state
->buf
;
5421 int label_is_utf8
= 1; /* start with this assumption */
5422 size_t max_len
= buf
->len
+ state
->max_label_length
;
5425 * Sanitize labels by replacing non-alpha-numeric characters
5426 * (including white-space ones) by dashes, as they might be
5427 * illegal in file names (and hence in ref names).
5429 * Note that we retain non-ASCII UTF-8 characters (identified
5430 * via the most significant bit). They should be all acceptable
5433 * As we will use the labels as names of (loose) refs, it is
5434 * vital that the name not be longer than the maximum component
5435 * size of the file system (`NAME_MAX`). We are careful to
5436 * truncate the label accordingly, allowing for the `.lock`
5437 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5438 * truncating in the middle of a character).
5440 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5441 if (isalnum(*label
) ||
5442 (!label_is_utf8
&& (*label
& 0x80)))
5443 strbuf_addch(buf
, *label
);
5444 else if (*label
& 0x80) {
5445 const char *p
= label
;
5447 utf8_width(&p
, NULL
);
5449 if (buf
->len
+ (p
- label
) > max_len
)
5451 strbuf_add(buf
, label
, p
- label
);
5455 strbuf_addch(buf
, *label
);
5457 /* avoid leading dash and double-dashes */
5458 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5459 strbuf_addch(buf
, '-');
5461 strbuf_addstr(buf
, "rev-");
5462 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5466 if ((buf
->len
== the_hash_algo
->hexsz
&&
5467 !get_oid_hex(label
, &dummy
)) ||
5468 (buf
->len
== 1 && *label
== '#') ||
5469 hashmap_get_from_hash(&state
->labels
,
5470 strihash(label
), label
)) {
5472 * If the label already exists, or if the label is a
5473 * valid full OID, or the label is a '#' (which we use
5474 * as a separator between merge heads and oneline), we
5475 * append a dash and a number to make it unique.
5477 size_t len
= buf
->len
;
5479 for (i
= 2; ; i
++) {
5480 strbuf_setlen(buf
, len
);
5481 strbuf_addf(buf
, "-%d", i
);
5482 if (!hashmap_get_from_hash(&state
->labels
,
5492 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5493 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5494 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5496 FLEX_ALLOC_STR(string_entry
, string
, label
);
5497 oidcpy(&string_entry
->entry
.oid
, oid
);
5498 oidmap_put(&state
->commit2label
, string_entry
);
5500 return string_entry
->string
;
5503 static int make_script_with_merges(struct pretty_print_context
*pp
,
5504 struct rev_info
*revs
, struct strbuf
*out
,
5507 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5508 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5509 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5510 int skipped_commit
= 0;
5511 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5512 struct strbuf label
= STRBUF_INIT
;
5513 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5514 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5515 struct commit
*commit
;
5516 struct oidmap commit2todo
= OIDMAP_INIT
;
5517 struct string_entry
*entry
;
5518 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5519 shown
= OIDSET_INIT
;
5520 struct label_state state
=
5521 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5523 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5524 const char *cmd_pick
= abbr
? "p" : "pick",
5525 *cmd_label
= abbr
? "l" : "label",
5526 *cmd_reset
= abbr
? "t" : "reset",
5527 *cmd_merge
= abbr
? "m" : "merge";
5529 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5531 oidmap_init(&commit2todo
, 0);
5532 oidmap_init(&state
.commit2label
, 0);
5533 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5534 strbuf_init(&state
.buf
, 32);
5536 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5537 struct labels_entry
*onto_label_entry
;
5538 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5539 FLEX_ALLOC_STR(entry
, string
, "onto");
5540 oidcpy(&entry
->entry
.oid
, oid
);
5541 oidmap_put(&state
.commit2label
, entry
);
5543 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5544 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5545 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5550 * - get onelines for all commits
5551 * - gather all branch tips (i.e. 2nd or later parents of merges)
5552 * - label all branch tips
5554 while ((commit
= get_revision(revs
))) {
5555 struct commit_list
*to_merge
;
5556 const char *p1
, *p2
;
5557 struct object_id
*oid
;
5560 tail
= &commit_list_insert(commit
, tail
)->next
;
5561 oidset_insert(&interesting
, &commit
->object
.oid
);
5563 is_empty
= is_original_commit_empty(commit
);
5564 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5565 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5566 warning(_("skipped previously applied commit %s"),
5567 short_commit_name(the_repository
, commit
));
5571 if (is_empty
&& !keep_empty
)
5574 strbuf_reset(&oneline
);
5575 pretty_print_commit(pp
, commit
, &oneline
);
5577 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5579 /* non-merge commit: easy case */
5581 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5582 oid_to_hex(&commit
->object
.oid
),
5585 strbuf_addf(&buf
, " %c empty",
5588 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5589 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5590 oidmap_put(&commit2todo
, entry
);
5595 /* Create a label */
5596 strbuf_reset(&label
);
5597 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5598 (p1
= strchr(p1
, '\'')) &&
5599 (p2
= strchr(++p1
, '\'')))
5600 strbuf_add(&label
, p1
, p2
- p1
);
5601 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5603 (p1
= strstr(p1
, " from ")))
5604 strbuf_addstr(&label
, p1
+ strlen(" from "));
5606 strbuf_addbuf(&label
, &oneline
);
5609 strbuf_addf(&buf
, "%s -C %s",
5610 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5612 /* label the tips of merged branches */
5613 for (; to_merge
; to_merge
= to_merge
->next
) {
5614 oid
= &to_merge
->item
->object
.oid
;
5615 strbuf_addch(&buf
, ' ');
5617 if (!oidset_contains(&interesting
, oid
)) {
5618 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5623 tips_tail
= &commit_list_insert(to_merge
->item
,
5626 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5628 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5630 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5631 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5632 oidmap_put(&commit2todo
, entry
);
5635 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5636 _("use --reapply-cherry-picks to include skipped commits"));
5640 * - label branch points
5641 * - add HEAD to the branch tips
5643 for (iter
= commits
; iter
; iter
= iter
->next
) {
5644 struct commit_list
*parent
= iter
->item
->parents
;
5645 for (; parent
; parent
= parent
->next
) {
5646 struct object_id
*oid
= &parent
->item
->object
.oid
;
5647 if (!oidset_contains(&interesting
, oid
))
5649 if (oidset_insert(&child_seen
, oid
))
5650 label_oid(oid
, "branch-point", &state
);
5653 /* Add HEAD as implicit "tip of branch" */
5655 tips_tail
= &commit_list_insert(iter
->item
,
5660 * Third phase: output the todo list. This is a bit tricky, as we
5661 * want to avoid jumping back and forth between revisions. To
5662 * accomplish that goal, we walk backwards from the branch tips,
5663 * gathering commits not yet shown, reversing the list on the fly,
5664 * then outputting that list (labeling revisions as needed).
5666 strbuf_addf(out
, "%s onto\n", cmd_label
);
5667 for (iter
= tips
; iter
; iter
= iter
->next
) {
5668 struct commit_list
*list
= NULL
, *iter2
;
5670 commit
= iter
->item
;
5671 if (oidset_contains(&shown
, &commit
->object
.oid
))
5673 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5676 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5678 strbuf_addch(out
, '\n');
5680 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5681 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5682 commit_list_insert(commit
, &list
);
5683 if (!commit
->parents
) {
5687 commit
= commit
->parents
->item
;
5691 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5692 rebase_cousins
|| root_with_onto
?
5693 "onto" : "[new root]");
5695 const char *to
= NULL
;
5697 entry
= oidmap_get(&state
.commit2label
,
5698 &commit
->object
.oid
);
5701 else if (!rebase_cousins
)
5702 to
= label_oid(&commit
->object
.oid
, NULL
,
5705 if (!to
|| !strcmp(to
, "onto"))
5706 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5708 strbuf_reset(&oneline
);
5709 pretty_print_commit(pp
, commit
, &oneline
);
5710 strbuf_addf(out
, "%s %s # %s\n",
5711 cmd_reset
, to
, oneline
.buf
);
5715 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5716 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5717 entry
= oidmap_get(&commit2todo
, oid
);
5718 /* only show if not already upstream */
5720 strbuf_addf(out
, "%s\n", entry
->string
);
5721 entry
= oidmap_get(&state
.commit2label
, oid
);
5723 strbuf_addf(out
, "%s %s\n",
5724 cmd_label
, entry
->string
);
5725 oidset_insert(&shown
, oid
);
5728 free_commit_list(list
);
5731 free_commit_list(commits
);
5732 free_commit_list(tips
);
5734 strbuf_release(&label
);
5735 strbuf_release(&oneline
);
5736 strbuf_release(&buf
);
5738 oidmap_free(&commit2todo
, 1);
5739 oidmap_free(&state
.commit2label
, 1);
5740 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5741 strbuf_release(&state
.buf
);
5746 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5747 const char **argv
, unsigned flags
)
5749 char *format
= NULL
;
5750 struct pretty_print_context pp
= {0};
5751 struct rev_info revs
;
5752 struct commit
*commit
;
5753 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5754 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5755 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5756 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5757 int skipped_commit
= 0;
5760 repo_init_revisions(r
, &revs
, NULL
);
5761 revs
.verbose_header
= 1;
5763 revs
.max_parents
= 1;
5764 revs
.cherry_mark
= !reapply_cherry_picks
;
5767 revs
.right_only
= 1;
5768 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5769 revs
.topo_order
= 1;
5771 revs
.pretty_given
= 1;
5772 git_config_get_string("rebase.instructionFormat", &format
);
5773 if (!format
|| !*format
) {
5775 format
= xstrdup("%s");
5777 get_commit_format(format
, &revs
);
5779 pp
.fmt
= revs
.commit_format
;
5780 pp
.output_encoding
= get_log_output_encoding();
5782 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5783 ret
= error(_("make_script: unhandled options"));
5787 if (prepare_revision_walk(&revs
) < 0) {
5788 ret
= error(_("make_script: error preparing revisions"));
5792 if (rebase_merges
) {
5793 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5797 while ((commit
= get_revision(&revs
))) {
5798 int is_empty
= is_original_commit_empty(commit
);
5800 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5801 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5802 warning(_("skipped previously applied commit %s"),
5803 short_commit_name(r
, commit
));
5807 if (is_empty
&& !keep_empty
)
5809 strbuf_addf(out
, "%s %s ", insn
,
5810 oid_to_hex(&commit
->object
.oid
));
5811 pretty_print_commit(&pp
, commit
, out
);
5813 strbuf_addf(out
, " %c empty", comment_line_char
);
5814 strbuf_addch(out
, '\n');
5817 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5818 _("use --reapply-cherry-picks to include skipped commits"));
5820 release_revisions(&revs
);
5825 * Add commands after pick and (series of) squash/fixup commands
5828 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5829 struct string_list
*commands
)
5831 struct strbuf
*buf
= &todo_list
->buf
;
5832 size_t base_offset
= buf
->len
;
5833 int i
, insert
, nr
= 0, alloc
= 0;
5834 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5836 CALLOC_ARRAY(base_items
, commands
->nr
);
5837 for (i
= 0; i
< commands
->nr
; i
++) {
5838 size_t command_len
= strlen(commands
->items
[i
].string
);
5840 strbuf_addstr(buf
, commands
->items
[i
].string
);
5841 strbuf_addch(buf
, '\n');
5843 base_items
[i
].command
= TODO_EXEC
;
5844 base_items
[i
].offset_in_buf
= base_offset
;
5845 base_items
[i
].arg_offset
= base_offset
;
5846 base_items
[i
].arg_len
= command_len
;
5848 base_offset
+= command_len
+ 1;
5852 * Insert <commands> after every pick. Here, fixup/squash chains
5853 * are considered part of the pick, so we insert the commands *after*
5854 * those chains if there are any.
5856 * As we insert the exec commands immediately after rearranging
5857 * any fixups and before the user edits the list, a fixup chain
5858 * can never contain comments (any comments are empty picks that
5859 * have been commented out because the user did not specify
5860 * --keep-empty). So, it is safe to insert an exec command
5861 * without looking at the command following a comment.
5864 for (i
= 0; i
< todo_list
->nr
; i
++) {
5865 enum todo_command command
= todo_list
->items
[i
].command
;
5866 if (insert
&& !is_fixup(command
)) {
5867 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5868 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5874 ALLOC_GROW(items
, nr
+ 1, alloc
);
5875 items
[nr
++] = todo_list
->items
[i
];
5877 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5881 /* insert or append final <commands> */
5883 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5884 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5889 FREE_AND_NULL(todo_list
->items
);
5890 todo_list
->items
= items
;
5892 todo_list
->alloc
= alloc
;
5895 static void todo_list_to_strbuf(struct repository
*r
,
5896 struct todo_list
*todo_list
,
5897 struct strbuf
*buf
, int num
, unsigned flags
)
5899 struct todo_item
*item
;
5900 int i
, max
= todo_list
->nr
;
5902 if (num
> 0 && num
< max
)
5905 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5908 /* if the item is not a command write it and continue */
5909 if (item
->command
>= TODO_COMMENT
) {
5910 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5911 todo_item_get_arg(todo_list
, item
));
5915 /* add command to the buffer */
5916 cmd
= command_to_char(item
->command
);
5917 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5918 strbuf_addch(buf
, cmd
);
5920 strbuf_addstr(buf
, command_to_string(item
->command
));
5924 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5925 short_commit_name(r
, item
->commit
) :
5926 oid_to_hex(&item
->commit
->object
.oid
);
5928 if (item
->command
== TODO_FIXUP
) {
5929 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
5930 strbuf_addstr(buf
, " -c");
5931 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
5932 strbuf_addstr(buf
, " -C");
5936 if (item
->command
== TODO_MERGE
) {
5937 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5938 strbuf_addstr(buf
, " -c");
5940 strbuf_addstr(buf
, " -C");
5943 strbuf_addf(buf
, " %s", oid
);
5946 /* add all the rest */
5948 strbuf_addch(buf
, '\n');
5950 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5951 todo_item_get_arg(todo_list
, item
));
5955 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5956 const char *file
, const char *shortrevisions
,
5957 const char *shortonto
, int num
, unsigned flags
)
5960 struct strbuf buf
= STRBUF_INIT
;
5962 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5963 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5964 append_todo_help(count_commands(todo_list
),
5965 shortrevisions
, shortonto
, &buf
);
5967 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5968 strbuf_release(&buf
);
5973 /* skip picking commits whose parents are unchanged */
5974 static int skip_unnecessary_picks(struct repository
*r
,
5975 struct todo_list
*todo_list
,
5976 struct object_id
*base_oid
)
5978 struct object_id
*parent_oid
;
5981 for (i
= 0; i
< todo_list
->nr
; i
++) {
5982 struct todo_item
*item
= todo_list
->items
+ i
;
5984 if (item
->command
>= TODO_NOOP
)
5986 if (item
->command
!= TODO_PICK
)
5988 if (repo_parse_commit(r
, item
->commit
)) {
5989 return error(_("could not parse commit '%s'"),
5990 oid_to_hex(&item
->commit
->object
.oid
));
5992 if (!item
->commit
->parents
)
5993 break; /* root commit */
5994 if (item
->commit
->parents
->next
)
5995 break; /* merge commit */
5996 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
5997 if (!oideq(parent_oid
, base_oid
))
5999 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6002 const char *done_path
= rebase_path_done();
6004 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6005 error_errno(_("could not write to '%s'"), done_path
);
6009 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6011 todo_list
->current
= 0;
6012 todo_list
->done_nr
+= i
;
6014 if (is_fixup(peek_command(todo_list
, 0)))
6015 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6021 struct todo_add_branch_context
{
6022 struct todo_item
*items
;
6026 struct commit
*commit
;
6027 struct string_list refs_to_oids
;
6030 static int add_decorations_to_list(const struct commit
*commit
,
6031 struct todo_add_branch_context
*ctx
)
6033 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6034 const char *head_ref
= resolve_ref_unsafe("HEAD",
6035 RESOLVE_REF_READING
,
6039 while (decoration
) {
6040 struct todo_item
*item
;
6042 size_t base_offset
= ctx
->buf
->len
;
6045 * If the branch is the current HEAD, then it will be
6046 * updated by the default rebase behavior.
6048 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6049 decoration
= decoration
->next
;
6053 ALLOC_GROW(ctx
->items
,
6056 item
= &ctx
->items
[ctx
->items_nr
];
6057 memset(item
, 0, sizeof(*item
));
6059 /* If the branch is checked out, then leave a comment instead. */
6060 if ((path
= branch_checked_out(decoration
->name
))) {
6061 item
->command
= TODO_COMMENT
;
6062 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6063 decoration
->name
, path
);
6065 struct string_list_item
*sti
;
6066 item
->command
= TODO_UPDATE_REF
;
6067 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6069 sti
= string_list_insert(&ctx
->refs_to_oids
,
6071 sti
->util
= init_update_ref_record(decoration
->name
);
6074 item
->offset_in_buf
= base_offset
;
6075 item
->arg_offset
= base_offset
;
6076 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6079 decoration
= decoration
->next
;
6086 * For each 'pick' command, find out if the commit has a decoration in
6087 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6089 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6092 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6093 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6094 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6095 struct decoration_filter decoration_filter
= {
6096 .include_ref_pattern
= &decorate_refs_include
,
6097 .exclude_ref_pattern
= &decorate_refs_exclude
,
6098 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6100 struct todo_add_branch_context ctx
= {
6101 .buf
= &todo_list
->buf
,
6102 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6105 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6106 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6108 string_list_append(&decorate_refs_include
, "refs/heads/");
6109 load_ref_decorations(&decoration_filter
, 0);
6111 for (i
= 0; i
< todo_list
->nr
; ) {
6112 struct todo_item
*item
= &todo_list
->items
[i
];
6114 /* insert ith item into new list */
6115 ALLOC_GROW(ctx
.items
,
6119 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6122 ctx
.commit
= item
->commit
;
6123 add_decorations_to_list(item
->commit
, &ctx
);
6127 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6129 string_list_clear(&ctx
.refs_to_oids
, 1);
6132 /* we failed, so clean up the new list. */
6137 free(todo_list
->items
);
6138 todo_list
->items
= ctx
.items
;
6139 todo_list
->nr
= ctx
.items_nr
;
6140 todo_list
->alloc
= ctx
.items_alloc
;
6145 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6146 const char *shortrevisions
, const char *onto_name
,
6147 struct commit
*onto
, const struct object_id
*orig_head
,
6148 struct string_list
*commands
, unsigned autosquash
,
6149 unsigned update_refs
,
6150 struct todo_list
*todo_list
)
6152 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6153 const char *todo_file
= rebase_path_todo();
6154 struct todo_list new_todo
= TODO_LIST_INIT
;
6155 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6156 struct object_id oid
= onto
->object
.oid
;
6159 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6162 if (buf
->len
== 0) {
6163 struct todo_item
*item
= append_new_todo(todo_list
);
6164 item
->command
= TODO_NOOP
;
6165 item
->commit
= NULL
;
6166 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6169 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6172 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6176 todo_list_add_exec_commands(todo_list
, commands
);
6178 if (count_commands(todo_list
) == 0) {
6179 apply_autostash(rebase_path_autostash());
6180 sequencer_remove_state(opts
);
6182 return error(_("nothing to do"));
6185 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6189 else if (res
== -2) {
6190 apply_autostash(rebase_path_autostash());
6191 sequencer_remove_state(opts
);
6194 } else if (res
== -3) {
6195 apply_autostash(rebase_path_autostash());
6196 sequencer_remove_state(opts
);
6197 todo_list_release(&new_todo
);
6199 return error(_("nothing to do"));
6200 } else if (res
== -4) {
6201 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6202 todo_list_release(&new_todo
);
6207 /* Expand the commit IDs */
6208 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6209 strbuf_swap(&new_todo
.buf
, &buf2
);
6210 strbuf_release(&buf2
);
6211 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6212 new_todo
.total_nr
= 0;
6213 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6214 BUG("invalid todo list after expanding IDs:\n%s",
6217 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6218 todo_list_release(&new_todo
);
6219 return error(_("could not skip unnecessary pick commands"));
6222 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6223 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6224 todo_list_release(&new_todo
);
6225 return error_errno(_("could not write '%s'"), todo_file
);
6230 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6233 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6236 todo_list_write_total_nr(&new_todo
);
6237 res
= pick_commits(r
, &new_todo
, opts
);
6240 todo_list_release(&new_todo
);
6245 struct subject2item_entry
{
6246 struct hashmap_entry entry
;
6248 char subject
[FLEX_ARRAY
];
6251 static int subject2item_cmp(const void *fndata UNUSED
,
6252 const struct hashmap_entry
*eptr
,
6253 const struct hashmap_entry
*entry_or_key
,
6256 const struct subject2item_entry
*a
, *b
;
6258 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6259 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6261 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6264 define_commit_slab(commit_todo_item
, struct todo_item
*);
6266 static int skip_fixupish(const char *subject
, const char **p
) {
6267 return skip_prefix(subject
, "fixup! ", p
) ||
6268 skip_prefix(subject
, "amend! ", p
) ||
6269 skip_prefix(subject
, "squash! ", p
);
6273 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6274 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6275 * after the former, and change "pick" to "fixup"/"squash".
6277 * Note that if the config has specified a custom instruction format, each log
6278 * message will have to be retrieved from the commit (as the oneline in the
6279 * script cannot be trusted) in order to normalize the autosquash arrangement.
6281 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6283 struct hashmap subject2item
;
6284 int rearranged
= 0, *next
, *tail
, i
, nr
= 0;
6286 struct commit_todo_item commit_todo
;
6287 struct todo_item
*items
= NULL
;
6289 init_commit_todo_item(&commit_todo
);
6291 * The hashmap maps onelines to the respective todo list index.
6293 * If any items need to be rearranged, the next[i] value will indicate
6294 * which item was moved directly after the i'th.
6296 * In that case, last[i] will indicate the index of the latest item to
6297 * be moved to appear after the i'th.
6299 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6300 ALLOC_ARRAY(next
, todo_list
->nr
);
6301 ALLOC_ARRAY(tail
, todo_list
->nr
);
6302 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6303 for (i
= 0; i
< todo_list
->nr
; i
++) {
6304 struct strbuf buf
= STRBUF_INIT
;
6305 struct todo_item
*item
= todo_list
->items
+ i
;
6306 const char *commit_buffer
, *subject
, *p
;
6309 struct subject2item_entry
*entry
;
6311 next
[i
] = tail
[i
] = -1;
6312 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6317 if (is_fixup(item
->command
)) {
6318 clear_commit_todo_item(&commit_todo
);
6319 return error(_("the script was already rearranged."));
6322 repo_parse_commit(the_repository
, item
->commit
);
6323 commit_buffer
= repo_logmsg_reencode(the_repository
,
6326 find_commit_subject(commit_buffer
, &subject
);
6327 format_subject(&buf
, subject
, " ");
6328 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6329 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6331 if (skip_fixupish(subject
, &p
)) {
6332 struct commit
*commit2
;
6337 if (!skip_fixupish(p
, &p
))
6341 entry
= hashmap_get_entry_from_hash(&subject2item
,
6343 struct subject2item_entry
,
6346 /* found by title */
6348 else if (!strchr(p
, ' ') &&
6350 lookup_commit_reference_by_name(p
)) &&
6351 *commit_todo_item_at(&commit_todo
, commit2
))
6352 /* found by commit name */
6353 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6356 /* copy can be a prefix of the commit subject */
6357 for (i2
= 0; i2
< i
; i2
++)
6359 starts_with(subjects
[i2
], p
))
6367 if (starts_with(subject
, "fixup!")) {
6368 todo_list
->items
[i
].command
= TODO_FIXUP
;
6369 } else if (starts_with(subject
, "amend!")) {
6370 todo_list
->items
[i
].command
= TODO_FIXUP
;
6371 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6373 todo_list
->items
[i
].command
= TODO_SQUASH
;
6379 next
[i
] = next
[tail
[i2
]];
6383 } else if (!hashmap_get_from_hash(&subject2item
,
6384 strhash(subject
), subject
)) {
6385 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6387 hashmap_entry_init(&entry
->entry
,
6388 strhash(entry
->subject
));
6389 hashmap_put(&subject2item
, &entry
->entry
);
6392 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6396 ALLOC_ARRAY(items
, todo_list
->nr
);
6398 for (i
= 0; i
< todo_list
->nr
; i
++) {
6399 enum todo_command command
= todo_list
->items
[i
].command
;
6403 * Initially, all commands are 'pick's. If it is a
6404 * fixup or a squash now, we have rearranged it.
6406 if (is_fixup(command
))
6410 items
[nr
++] = todo_list
->items
[cur
];
6415 assert(nr
== todo_list
->nr
);
6416 todo_list
->alloc
= nr
;
6417 FREE_AND_NULL(todo_list
->items
);
6418 todo_list
->items
= items
;
6423 for (i
= 0; i
< todo_list
->nr
; i
++)
6426 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6428 clear_commit_todo_item(&commit_todo
);
6433 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6435 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6436 struct object_id cherry_pick_head
, rebase_head
;
6438 if (file_exists(git_path_seq_dir()))
6439 *whence
= FROM_CHERRY_PICK_MULTI
;
6440 if (file_exists(rebase_path()) &&
6441 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6442 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6443 oideq(&rebase_head
, &cherry_pick_head
))
6444 *whence
= FROM_REBASE_PICK
;
6446 *whence
= FROM_CHERRY_PICK_SINGLE
;
6454 int sequencer_get_update_refs_state(const char *wt_dir
,
6455 struct string_list
*refs
)
6459 struct strbuf ref
= STRBUF_INIT
;
6460 struct strbuf hash
= STRBUF_INIT
;
6461 struct update_ref_record
*rec
= NULL
;
6463 char *path
= rebase_path_update_refs(wt_dir
);
6465 fp
= fopen(path
, "r");
6469 while (strbuf_getline(&ref
, fp
) != EOF
) {
6470 struct string_list_item
*item
;
6472 CALLOC_ARRAY(rec
, 1);
6474 if (strbuf_getline(&hash
, fp
) == EOF
||
6475 get_oid_hex(hash
.buf
, &rec
->before
)) {
6476 warning(_("update-refs file at '%s' is invalid"),
6482 if (strbuf_getline(&hash
, fp
) == EOF
||
6483 get_oid_hex(hash
.buf
, &rec
->after
)) {
6484 warning(_("update-refs file at '%s' is invalid"),
6490 item
= string_list_insert(refs
, ref
.buf
);
6500 strbuf_release(&ref
);
6501 strbuf_release(&hash
);