1 #include "git-compat-util.h"
6 #include "environment.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "object-store-ll.h"
17 #include "sequencer.h"
19 #include "run-command.h"
23 #include "cache-tree.h"
29 #include "merge-ort.h"
30 #include "merge-ort-wrappers.h"
32 #include "sparse-index.h"
37 #include "wt-status.h"
39 #include "notes-utils.h"
41 #include "unpack-trees.h"
45 #include "commit-slab.h"
47 #include "commit-reach.h"
48 #include "rebase-interactive.h"
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
59 * Add some margin to stay clear from reaching `NAME_MAX`.
61 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
63 static const char sign_off_header
[] = "Signed-off-by: ";
64 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
66 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
68 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
70 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
71 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
72 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
73 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
75 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
82 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
83 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
85 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
92 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
94 * The file to keep track of how many commands were already processed (e.g.
97 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
102 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
107 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
116 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
124 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
129 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
135 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
144 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
146 * When we stop at a given patch via the "edit" command, this file contains
147 * the commit object name of the corresponding patch.
149 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
151 * When we stop for the user to resolve conflicts this file contains
152 * the patch of the commit that is being picked.
154 static GIT_PATH_FUNC(rebase_path_patch
, "rebase-merge/patch")
156 * For the post-rewrite hook, we make a list of rewritten commits and
157 * their new sha1s. The rewritten-pending list keeps the sha1s of
158 * commits that have been processed, but not committed yet,
159 * e.g. because they are waiting for a 'squash' command.
161 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
162 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
163 "rebase-merge/rewritten-pending")
166 * The path of the file containing the OID of the "squash onto" commit, i.e.
167 * the dummy commit used for `reset [new root]`.
169 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
172 * The path of the file listing refs that need to be deleted after the rebase
173 * finishes. This is used by the `label` command to record the need for cleanup.
175 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
178 * The update-refs file stores a list of refs that will be updated at the end
179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
180 * update the OIDs for the refs in this file, but the refs are not updated
181 * until the end of the rebase sequence.
183 * rebase_path_update_refs() returns the path to this file for a given
184 * worktree directory. For the current worktree, pass the_repository->gitdir.
186 static char *rebase_path_update_refs(const char *wt_git_dir
)
188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
192 * The following files are written by git-rebase just after parsing the
195 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
196 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
197 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
198 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
199 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
200 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
201 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
202 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
203 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
204 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
205 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
206 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
207 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
208 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
209 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
210 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
211 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
214 * A 'struct update_refs_record' represents a value in the update-refs
215 * list. We use a string_list to map refs to these (before, after) pairs.
217 struct update_ref_record
{
218 struct object_id before
;
219 struct object_id after
;
222 static struct update_ref_record
*init_update_ref_record(const char *ref
)
224 struct update_ref_record
*rec
;
226 CALLOC_ARRAY(rec
, 1);
228 oidcpy(&rec
->before
, null_oid());
229 oidcpy(&rec
->after
, null_oid());
231 /* This may fail, but that's fine, we will keep the null OID. */
232 read_ref(ref
, &rec
->before
);
237 static int git_sequencer_config(const char *k
, const char *v
,
238 const struct config_context
*ctx
, void *cb
)
240 struct replay_opts
*opts
= cb
;
243 if (!strcmp(k
, "commit.cleanup")) {
246 status
= git_config_string(&s
, k
, v
);
250 if (!strcmp(s
, "verbatim")) {
251 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
252 opts
->explicit_cleanup
= 1;
253 } else if (!strcmp(s
, "whitespace")) {
254 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
255 opts
->explicit_cleanup
= 1;
256 } else if (!strcmp(s
, "strip")) {
257 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
258 opts
->explicit_cleanup
= 1;
259 } else if (!strcmp(s
, "scissors")) {
260 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
261 opts
->explicit_cleanup
= 1;
263 warning(_("invalid commit message cleanup mode '%s'"),
271 if (!strcmp(k
, "commit.gpgsign")) {
272 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
276 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
277 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
280 * pull.twohead is allowed to be multi-valued; we only
281 * care about the first value.
283 char *tmp
= strchr(opts
->default_strategy
, ' ');
290 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
291 opts
->commit_use_reference
= git_config_bool(k
, v
);
293 return git_diff_basic_config(k
, v
, ctx
, NULL
);
296 void sequencer_init_config(struct replay_opts
*opts
)
298 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
299 git_config(git_sequencer_config
, opts
);
302 static inline int is_rebase_i(const struct replay_opts
*opts
)
304 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
307 static const char *get_dir(const struct replay_opts
*opts
)
309 if (is_rebase_i(opts
))
310 return rebase_path();
311 return git_path_seq_dir();
314 static const char *get_todo_path(const struct replay_opts
*opts
)
316 if (is_rebase_i(opts
))
317 return rebase_path_todo();
318 return git_path_todo_file();
322 * Returns 0 for non-conforming footer
323 * Returns 1 for conforming footer
324 * Returns 2 when sob exists within conforming footer
325 * Returns 3 when sob exists within conforming footer as last entry
327 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
328 size_t ignore_footer
)
330 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
331 struct trailer_info info
;
333 int found_sob
= 0, found_sob_last
= 0;
339 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
340 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
343 trailer_info_get(&info
, sb
->buf
, &opts
);
346 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
348 if (info
.trailer_start
== info
.trailer_end
)
351 for (i
= 0; i
< info
.trailer_nr
; i
++)
352 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
354 if (i
== info
.trailer_nr
- 1)
358 trailer_info_release(&info
);
367 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
369 static struct strbuf buf
= STRBUF_INIT
;
373 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
377 void replay_opts_release(struct replay_opts
*opts
)
379 free(opts
->gpg_sign
);
380 free(opts
->reflog_action
);
381 free(opts
->default_strategy
);
382 free(opts
->strategy
);
383 strvec_clear (&opts
->xopts
);
384 strbuf_release(&opts
->current_fixups
);
386 release_revisions(opts
->revs
);
390 int sequencer_remove_state(struct replay_opts
*opts
)
392 struct strbuf buf
= STRBUF_INIT
;
395 if (is_rebase_i(opts
) &&
396 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
399 char *eol
= strchr(p
, '\n');
402 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
403 warning(_("could not delete '%s'"), p
);
413 strbuf_addstr(&buf
, get_dir(opts
));
414 if (remove_dir_recursively(&buf
, 0))
415 ret
= error(_("could not remove '%s'"), buf
.buf
);
416 strbuf_release(&buf
);
421 static const char *action_name(const struct replay_opts
*opts
)
423 switch (opts
->action
) {
427 return N_("cherry-pick");
428 case REPLAY_INTERACTIVE_REBASE
:
431 die(_("unknown action: %d"), opts
->action
);
434 struct commit_message
{
441 static const char *short_commit_name(struct commit
*commit
)
443 return repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
,
447 static int get_message(struct commit
*commit
, struct commit_message
*out
)
449 const char *abbrev
, *subject
;
452 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
453 get_commit_output_encoding());
454 abbrev
= short_commit_name(commit
);
456 subject_len
= find_commit_subject(out
->message
, &subject
);
458 out
->subject
= xmemdupz(subject
, subject_len
);
459 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
460 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
465 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
467 free(msg
->parent_label
);
470 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
473 static void print_advice(struct repository
*r
, int show_hint
,
474 struct replay_opts
*opts
)
476 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
481 * A conflict has occurred but the porcelain
482 * (typically rebase --interactive) wants to take care
483 * of the commit itself so remove CHERRY_PICK_HEAD
485 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
492 advise(_("after resolving the conflicts, mark the corrected paths\n"
493 "with 'git add <paths>' or 'git rm <paths>'"));
494 else if (opts
->action
== REPLAY_PICK
)
495 advise(_("After resolving the conflicts, mark them with\n"
496 "\"git add/rm <pathspec>\", then run\n"
497 "\"git cherry-pick --continue\".\n"
498 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
499 "To abort and get back to the state before \"git cherry-pick\",\n"
500 "run \"git cherry-pick --abort\"."));
501 else if (opts
->action
== REPLAY_REVERT
)
502 advise(_("After resolving the conflicts, mark them with\n"
503 "\"git add/rm <pathspec>\", then run\n"
504 "\"git revert --continue\".\n"
505 "You can instead skip this commit with \"git revert --skip\".\n"
506 "To abort and get back to the state before \"git revert\",\n"
507 "run \"git revert --abort\"."));
509 BUG("unexpected pick action in print_advice()");
513 static int write_message(const void *buf
, size_t len
, const char *filename
,
516 struct lock_file msg_file
= LOCK_INIT
;
518 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
520 return error_errno(_("could not lock '%s'"), filename
);
521 if (write_in_full(msg_fd
, buf
, len
) < 0) {
522 error_errno(_("could not write to '%s'"), filename
);
523 rollback_lock_file(&msg_file
);
526 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
527 error_errno(_("could not write eol to '%s'"), filename
);
528 rollback_lock_file(&msg_file
);
531 if (commit_lock_file(&msg_file
) < 0)
532 return error(_("failed to finalize '%s'"), filename
);
537 int read_oneliner(struct strbuf
*buf
,
538 const char *path
, unsigned flags
)
540 int orig_len
= buf
->len
;
542 if (strbuf_read_file(buf
, path
, 0) < 0) {
543 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
544 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
545 warning_errno(_("could not read '%s'"), path
);
549 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
550 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
552 buf
->buf
[buf
->len
] = '\0';
555 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
561 static struct tree
*empty_tree(struct repository
*r
)
563 return lookup_tree(r
, the_hash_algo
->empty_tree
);
566 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
568 if (repo_read_index_unmerged(repo
))
569 return error_resolve_conflict(action_name(opts
));
571 error(_("your local changes would be overwritten by %s."),
572 _(action_name(opts
)));
574 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
575 advise(_("commit your changes or stash them to proceed."));
579 static void update_abort_safety_file(void)
581 struct object_id head
;
583 /* Do nothing on a single-pick */
584 if (!file_exists(git_path_seq_dir()))
587 if (!repo_get_oid(the_repository
, "HEAD", &head
))
588 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
590 write_file(git_path_abort_safety_file(), "%s", "");
593 static int fast_forward_to(struct repository
*r
,
594 const struct object_id
*to
,
595 const struct object_id
*from
,
597 struct replay_opts
*opts
)
599 struct ref_transaction
*transaction
;
600 struct strbuf sb
= STRBUF_INIT
;
601 struct strbuf err
= STRBUF_INIT
;
604 if (checkout_fast_forward(r
, from
, to
, 1))
605 return -1; /* the callee should have complained already */
607 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
609 transaction
= ref_transaction_begin(&err
);
611 ref_transaction_update(transaction
, "HEAD",
612 to
, unborn
&& !is_rebase_i(opts
) ?
615 ref_transaction_commit(transaction
, &err
)) {
616 ref_transaction_free(transaction
);
617 error("%s", err
.buf
);
619 strbuf_release(&err
);
624 strbuf_release(&err
);
625 ref_transaction_free(transaction
);
626 update_abort_safety_file();
630 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
633 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
634 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
635 COMMIT_MSG_CLEANUP_SPACE
;
636 else if (!strcmp(cleanup_arg
, "verbatim"))
637 return COMMIT_MSG_CLEANUP_NONE
;
638 else if (!strcmp(cleanup_arg
, "whitespace"))
639 return COMMIT_MSG_CLEANUP_SPACE
;
640 else if (!strcmp(cleanup_arg
, "strip"))
641 return COMMIT_MSG_CLEANUP_ALL
;
642 else if (!strcmp(cleanup_arg
, "scissors"))
643 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
644 COMMIT_MSG_CLEANUP_SPACE
;
646 die(_("Invalid cleanup mode %s"), cleanup_arg
);
650 * NB using int rather than enum cleanup_mode to stop clang's
651 * -Wtautological-constant-out-of-range-compare complaining that the comparison
654 static const char *describe_cleanup_mode(int cleanup_mode
)
656 static const char *modes
[] = { "whitespace",
661 if (cleanup_mode
< ARRAY_SIZE(modes
))
662 return modes
[cleanup_mode
];
664 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
667 void append_conflicts_hint(struct index_state
*istate
,
668 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
672 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
673 strbuf_addch(msgbuf
, '\n');
674 wt_status_append_cut_line(msgbuf
);
675 strbuf_addch(msgbuf
, comment_line_char
);
678 strbuf_addch(msgbuf
, '\n');
679 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
680 for (i
= 0; i
< istate
->cache_nr
;) {
681 const struct cache_entry
*ce
= istate
->cache
[i
++];
683 strbuf_commented_addf(msgbuf
, comment_line_char
,
685 while (i
< istate
->cache_nr
&&
686 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
692 static int do_recursive_merge(struct repository
*r
,
693 struct commit
*base
, struct commit
*next
,
694 const char *base_label
, const char *next_label
,
695 struct object_id
*head
, struct strbuf
*msgbuf
,
696 struct replay_opts
*opts
)
698 struct merge_options o
;
699 struct merge_result result
;
700 struct tree
*next_tree
, *base_tree
, *head_tree
;
701 int clean
, show_output
;
703 struct lock_file index_lock
= LOCK_INIT
;
705 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
710 init_merge_options(&o
, r
);
711 o
.ancestor
= base
? base_label
: "(empty tree)";
713 o
.branch2
= next
? next_label
: "(empty tree)";
714 if (is_rebase_i(opts
))
716 o
.show_rename_progress
= 1;
718 head_tree
= parse_tree_indirect(head
);
719 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
720 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
722 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
723 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
725 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
726 memset(&result
, 0, sizeof(result
));
727 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
729 show_output
= !is_rebase_i(opts
) || !result
.clean
;
731 * TODO: merge_switch_to_result will update index/working tree;
732 * we only really want to do that if !result.clean || this is
733 * the final patch to be picked. But determining this is the
734 * final patch would take some work, and "head_tree" would need
735 * to be replace with the tree the index matched before we
736 * started doing any picks.
738 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
739 clean
= result
.clean
;
741 ensure_full_index(r
->index
);
742 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
743 if (is_rebase_i(opts
) && clean
<= 0)
744 fputs(o
.obuf
.buf
, stdout
);
745 strbuf_release(&o
.obuf
);
748 rollback_lock_file(&index_lock
);
752 if (write_locked_index(r
->index
, &index_lock
,
753 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
755 * TRANSLATORS: %s will be "revert", "cherry-pick" or
758 return error(_("%s: Unable to write new index file"),
759 _(action_name(opts
)));
762 append_conflicts_hint(r
->index
, msgbuf
,
763 opts
->default_msg_cleanup
);
768 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
770 if (!cache_tree_fully_valid(istate
->cache_tree
))
771 if (cache_tree_update(istate
, 0)) {
772 error(_("unable to update cache tree"));
776 return &istate
->cache_tree
->oid
;
779 static int is_index_unchanged(struct repository
*r
)
781 struct object_id head_oid
, *cache_tree_oid
;
782 struct commit
*head_commit
;
783 struct index_state
*istate
= r
->index
;
785 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
786 return error(_("could not resolve HEAD commit"));
788 head_commit
= lookup_commit(r
, &head_oid
);
791 * If head_commit is NULL, check_commit, called from
792 * lookup_commit, would have indicated that head_commit is not
793 * a commit object already. repo_parse_commit() will return failure
794 * without further complaints in such a case. Otherwise, if
795 * the commit is invalid, repo_parse_commit() will complain. So
796 * there is nothing for us to say here. Just return failure.
798 if (repo_parse_commit(r
, head_commit
))
801 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
804 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
807 static int write_author_script(const char *message
)
809 struct strbuf buf
= STRBUF_INIT
;
814 if (!*message
|| starts_with(message
, "\n")) {
816 /* Missing 'author' line? */
817 unlink(rebase_path_author_script());
819 } else if (skip_prefix(message
, "author ", &message
))
821 else if ((eol
= strchr(message
, '\n')))
826 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
827 while (*message
&& *message
!= '\n' && *message
!= '\r')
828 if (skip_prefix(message
, " <", &message
))
830 else if (*message
!= '\'')
831 strbuf_addch(&buf
, *(message
++));
833 strbuf_addf(&buf
, "'\\%c'", *(message
++));
834 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
835 while (*message
&& *message
!= '\n' && *message
!= '\r')
836 if (skip_prefix(message
, "> ", &message
))
838 else if (*message
!= '\'')
839 strbuf_addch(&buf
, *(message
++));
841 strbuf_addf(&buf
, "'\\%c'", *(message
++));
842 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
843 while (*message
&& *message
!= '\n' && *message
!= '\r')
844 if (*message
!= '\'')
845 strbuf_addch(&buf
, *(message
++));
847 strbuf_addf(&buf
, "'\\%c'", *(message
++));
848 strbuf_addch(&buf
, '\'');
849 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
850 strbuf_release(&buf
);
855 * Take a series of KEY='VALUE' lines where VALUE part is
856 * sq-quoted, and append <KEY, VALUE> at the end of the string list
858 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
861 struct string_list_item
*item
;
863 char *cp
= strchr(buf
, '=');
865 np
= strchrnul(buf
, '\n');
866 return error(_("no key present in '%.*s'"),
867 (int) (np
- buf
), buf
);
869 np
= strchrnul(cp
, '\n');
871 item
= string_list_append(list
, buf
);
873 buf
= np
+ (*np
== '\n');
877 return error(_("unable to dequote value of '%s'"),
879 item
->util
= xstrdup(cp
);
885 * Reads and parses the state directory's "author-script" file, and sets name,
886 * email and date accordingly.
887 * Returns 0 on success, -1 if the file could not be parsed.
889 * The author script is of the format:
891 * GIT_AUTHOR_NAME='$author_name'
892 * GIT_AUTHOR_EMAIL='$author_email'
893 * GIT_AUTHOR_DATE='$author_date'
895 * where $author_name, $author_email and $author_date are quoted. We are strict
896 * with our parsing, as the file was meant to be eval'd in the now-removed
897 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
898 * from what this function expects, it is better to bail out than to do
899 * something that the user does not expect.
901 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
904 struct strbuf buf
= STRBUF_INIT
;
905 struct string_list kv
= STRING_LIST_INIT_DUP
;
906 int retval
= -1; /* assume failure */
907 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
909 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
910 strbuf_release(&buf
);
911 if (errno
== ENOENT
&& allow_missing
)
914 return error_errno(_("could not open '%s' for reading"),
918 if (parse_key_value_squoted(buf
.buf
, &kv
))
921 for (i
= 0; i
< kv
.nr
; i
++) {
922 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
924 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
927 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
929 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
932 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
934 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
938 err
= error(_("unknown variable '%s'"),
943 error(_("missing 'GIT_AUTHOR_NAME'"));
945 error(_("missing 'GIT_AUTHOR_EMAIL'"));
947 error(_("missing 'GIT_AUTHOR_DATE'"));
948 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
950 *name
= kv
.items
[name_i
].util
;
951 *email
= kv
.items
[email_i
].util
;
952 *date
= kv
.items
[date_i
].util
;
955 string_list_clear(&kv
, !!retval
);
956 strbuf_release(&buf
);
961 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
962 * file with shell quoting into struct strvec. Returns -1 on
963 * error, 0 otherwise.
965 static int read_env_script(struct strvec
*env
)
967 char *name
, *email
, *date
;
969 if (read_author_script(rebase_path_author_script(),
970 &name
, &email
, &date
, 0))
973 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
974 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
975 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
983 static char *get_author(const char *message
)
988 a
= find_commit_header(message
, "author", &len
);
990 return xmemdupz(a
, len
);
995 static const char *author_date_from_env(const struct strvec
*env
)
1000 for (i
= 0; i
< env
->nr
; i
++)
1001 if (skip_prefix(env
->v
[i
],
1002 "GIT_AUTHOR_DATE=", &date
))
1005 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1006 * reading the script
1008 BUG("GIT_AUTHOR_DATE missing from author script");
1011 static const char staged_changes_advice
[] =
1012 N_("you have staged changes in your working tree\n"
1013 "If these changes are meant to be squashed into the previous commit, run:\n"
1015 " git commit --amend %s\n"
1017 "If they are meant to go into a new commit, run:\n"
1021 "In both cases, once you're done, continue with:\n"
1023 " git rebase --continue\n");
1025 #define ALLOW_EMPTY (1<<0)
1026 #define EDIT_MSG (1<<1)
1027 #define AMEND_MSG (1<<2)
1028 #define CLEANUP_MSG (1<<3)
1029 #define VERIFY_MSG (1<<4)
1030 #define CREATE_ROOT_COMMIT (1<<5)
1031 #define VERBATIM_MSG (1<<6)
1033 static int run_command_silent_on_success(struct child_process
*cmd
)
1035 struct strbuf buf
= STRBUF_INIT
;
1038 cmd
->stdout_to_stderr
= 1;
1039 rc
= pipe_command(cmd
,
1045 fputs(buf
.buf
, stderr
);
1046 strbuf_release(&buf
);
1051 * If we are cherry-pick, and if the merge did not result in
1052 * hand-editing, we will hit this commit and inherit the original
1053 * author date and name.
1055 * If we are revert, or if our cherry-pick results in a hand merge,
1056 * we had better say that the current user is responsible for that.
1058 * An exception is when run_git_commit() is called during an
1059 * interactive rebase: in that case, we will want to retain the
1062 static int run_git_commit(const char *defmsg
,
1063 struct replay_opts
*opts
,
1066 struct child_process cmd
= CHILD_PROCESS_INIT
;
1068 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1069 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1073 if (is_rebase_i(opts
) &&
1074 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1075 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1076 read_env_script(&cmd
.env
)) {
1077 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1079 return error(_(staged_changes_advice
),
1083 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1085 if (opts
->committer_date_is_author_date
)
1086 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1089 author_date_from_env(&cmd
.env
));
1090 if (opts
->ignore_date
)
1091 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1093 strvec_push(&cmd
.args
, "commit");
1095 if (!(flags
& VERIFY_MSG
))
1096 strvec_push(&cmd
.args
, "-n");
1097 if ((flags
& AMEND_MSG
))
1098 strvec_push(&cmd
.args
, "--amend");
1100 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1102 strvec_push(&cmd
.args
, "--no-gpg-sign");
1104 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1105 else if (!(flags
& EDIT_MSG
))
1106 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1107 if ((flags
& CLEANUP_MSG
))
1108 strvec_push(&cmd
.args
, "--cleanup=strip");
1109 if ((flags
& VERBATIM_MSG
))
1110 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1111 if ((flags
& EDIT_MSG
))
1112 strvec_push(&cmd
.args
, "-e");
1113 else if (!(flags
& CLEANUP_MSG
) &&
1114 !opts
->signoff
&& !opts
->record_origin
&&
1115 !opts
->explicit_cleanup
)
1116 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1118 if ((flags
& ALLOW_EMPTY
))
1119 strvec_push(&cmd
.args
, "--allow-empty");
1121 if (!(flags
& EDIT_MSG
))
1122 strvec_push(&cmd
.args
, "--allow-empty-message");
1124 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1125 return run_command_silent_on_success(&cmd
);
1127 return run_command(&cmd
);
1130 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1135 /* Check if the rest is just whitespace and Signed-off-by's. */
1136 for (i
= start
; i
< sb
->len
; i
++) {
1137 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1143 if (strlen(sign_off_header
) <= eol
- i
&&
1144 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1149 if (!isspace(sb
->buf
[i
++]))
1156 void cleanup_message(struct strbuf
*msgbuf
,
1157 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1159 if (verbose
|| /* Truncate the message just before the diff, if any. */
1160 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1161 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1162 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1163 strbuf_stripspace(msgbuf
,
1164 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1168 * Find out if the message in the strbuf contains only whitespace and
1169 * Signed-off-by lines.
1171 int message_is_empty(const struct strbuf
*sb
,
1172 enum commit_msg_cleanup_mode cleanup_mode
)
1174 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1176 return rest_is_empty(sb
, 0);
1180 * See if the user edited the message in the editor or left what
1181 * was in the template intact
1183 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1184 enum commit_msg_cleanup_mode cleanup_mode
)
1186 struct strbuf tmpl
= STRBUF_INIT
;
1189 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1192 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1195 strbuf_stripspace(&tmpl
,
1196 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1197 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1199 strbuf_release(&tmpl
);
1200 return rest_is_empty(sb
, start
- sb
->buf
);
1203 int update_head_with_reflog(const struct commit
*old_head
,
1204 const struct object_id
*new_head
,
1205 const char *action
, const struct strbuf
*msg
,
1208 struct ref_transaction
*transaction
;
1209 struct strbuf sb
= STRBUF_INIT
;
1214 strbuf_addstr(&sb
, action
);
1215 strbuf_addstr(&sb
, ": ");
1218 nl
= strchr(msg
->buf
, '\n');
1220 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1222 strbuf_addbuf(&sb
, msg
);
1223 strbuf_addch(&sb
, '\n');
1226 transaction
= ref_transaction_begin(err
);
1228 ref_transaction_update(transaction
, "HEAD", new_head
,
1229 old_head
? &old_head
->object
.oid
: null_oid(),
1231 ref_transaction_commit(transaction
, err
)) {
1234 ref_transaction_free(transaction
);
1235 strbuf_release(&sb
);
1240 static int run_rewrite_hook(const struct object_id
*oldoid
,
1241 const struct object_id
*newoid
)
1243 struct child_process proc
= CHILD_PROCESS_INIT
;
1245 struct strbuf sb
= STRBUF_INIT
;
1246 const char *hook_path
= find_hook("post-rewrite");
1251 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1253 proc
.stdout_to_stderr
= 1;
1254 proc
.trace2_hook_name
= "post-rewrite";
1256 code
= start_command(&proc
);
1259 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1260 sigchain_push(SIGPIPE
, SIG_IGN
);
1261 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1263 strbuf_release(&sb
);
1264 sigchain_pop(SIGPIPE
);
1265 return finish_command(&proc
);
1268 void commit_post_rewrite(struct repository
*r
,
1269 const struct commit
*old_head
,
1270 const struct object_id
*new_head
)
1272 struct notes_rewrite_cfg
*cfg
;
1274 cfg
= init_copy_notes_for_rewrite("amend");
1276 /* we are amending, so old_head is not NULL */
1277 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1278 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1280 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1283 static int run_prepare_commit_msg_hook(struct repository
*r
,
1288 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1290 name
= git_path_commit_editmsg();
1291 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1300 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1302 ret
= error(_("'prepare-commit-msg' hook failed"));
1307 static const char implicit_ident_advice_noconfig
[] =
1308 N_("Your name and email address were configured automatically based\n"
1309 "on your username and hostname. Please check that they are accurate.\n"
1310 "You can suppress this message by setting them explicitly. Run the\n"
1311 "following command and follow the instructions in your editor to edit\n"
1312 "your configuration file:\n"
1314 " git config --global --edit\n"
1316 "After doing this, you may fix the identity used for this commit with:\n"
1318 " git commit --amend --reset-author\n");
1320 static const char implicit_ident_advice_config
[] =
1321 N_("Your name and email address were configured automatically based\n"
1322 "on your username and hostname. Please check that they are accurate.\n"
1323 "You can suppress this message by setting them explicitly:\n"
1325 " git config --global user.name \"Your Name\"\n"
1326 " git config --global user.email you@example.com\n"
1328 "After doing this, you may fix the identity used for this commit with:\n"
1330 " git commit --amend --reset-author\n");
1332 static const char *implicit_ident_advice(void)
1334 char *user_config
= interpolate_path("~/.gitconfig", 0);
1335 char *xdg_config
= xdg_config_home("config");
1336 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1342 return _(implicit_ident_advice_config
);
1344 return _(implicit_ident_advice_noconfig
);
1348 void print_commit_summary(struct repository
*r
,
1350 const struct object_id
*oid
,
1353 struct rev_info rev
;
1354 struct commit
*commit
;
1355 struct strbuf format
= STRBUF_INIT
;
1357 struct pretty_print_context pctx
= {0};
1358 struct strbuf author_ident
= STRBUF_INIT
;
1359 struct strbuf committer_ident
= STRBUF_INIT
;
1360 struct ref_store
*refs
;
1362 commit
= lookup_commit(r
, oid
);
1364 die(_("couldn't look up newly created commit"));
1365 if (repo_parse_commit(r
, commit
))
1366 die(_("could not parse newly created commit"));
1368 strbuf_addstr(&format
, "format:%h] %s");
1370 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1372 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1374 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1375 strbuf_addstr(&format
, "\n Author: ");
1376 strbuf_addbuf_percentquote(&format
, &author_ident
);
1378 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1379 struct strbuf date
= STRBUF_INIT
;
1381 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1382 strbuf_addstr(&format
, "\n Date: ");
1383 strbuf_addbuf_percentquote(&format
, &date
);
1384 strbuf_release(&date
);
1386 if (!committer_ident_sufficiently_given()) {
1387 strbuf_addstr(&format
, "\n Committer: ");
1388 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1389 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1390 strbuf_addch(&format
, '\n');
1391 strbuf_addstr(&format
, implicit_ident_advice());
1394 strbuf_release(&author_ident
);
1395 strbuf_release(&committer_ident
);
1397 repo_init_revisions(r
, &rev
, prefix
);
1398 setup_revisions(0, NULL
, &rev
, NULL
);
1401 rev
.diffopt
.output_format
=
1402 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1404 rev
.verbose_header
= 1;
1405 rev
.show_root_diff
= 1;
1406 get_commit_format(format
.buf
, &rev
);
1407 rev
.always_show_header
= 0;
1408 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1409 diff_setup_done(&rev
.diffopt
);
1411 refs
= get_main_ref_store(r
);
1412 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1414 die(_("unable to resolve HEAD after creating commit"));
1415 if (!strcmp(head
, "HEAD"))
1416 head
= _("detached HEAD");
1418 skip_prefix(head
, "refs/heads/", &head
);
1419 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1420 _(" (root-commit)") : "");
1422 if (!log_tree_commit(&rev
, commit
)) {
1423 rev
.always_show_header
= 1;
1424 rev
.use_terminator
= 1;
1425 log_tree_commit(&rev
, commit
);
1428 release_revisions(&rev
);
1429 strbuf_release(&format
);
1432 static int parse_head(struct repository
*r
, struct commit
**head
)
1434 struct commit
*current_head
;
1435 struct object_id oid
;
1437 if (repo_get_oid(r
, "HEAD", &oid
)) {
1438 current_head
= NULL
;
1440 current_head
= lookup_commit_reference(r
, &oid
);
1442 return error(_("could not parse HEAD"));
1443 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1444 warning(_("HEAD %s is not a commit!"),
1447 if (repo_parse_commit(r
, current_head
))
1448 return error(_("could not parse HEAD commit"));
1450 *head
= current_head
;
1456 * Try to commit without forking 'git commit'. In some cases we need
1457 * to run 'git commit' to display an error message
1460 * -1 - error unable to commit
1462 * 1 - run 'git commit'
1464 static int try_to_commit(struct repository
*r
,
1465 struct strbuf
*msg
, const char *author
,
1466 struct replay_opts
*opts
, unsigned int flags
,
1467 struct object_id
*oid
)
1469 struct object_id tree
;
1470 struct commit
*current_head
= NULL
;
1471 struct commit_list
*parents
= NULL
;
1472 struct commit_extra_header
*extra
= NULL
;
1473 struct strbuf err
= STRBUF_INIT
;
1474 struct strbuf commit_msg
= STRBUF_INIT
;
1475 char *amend_author
= NULL
;
1476 const char *committer
= NULL
;
1477 const char *hook_commit
= NULL
;
1478 enum commit_msg_cleanup_mode cleanup
;
1481 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1482 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1484 if (parse_head(r
, ¤t_head
))
1487 if (flags
& AMEND_MSG
) {
1488 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1489 const char *out_enc
= get_commit_output_encoding();
1490 const char *message
= repo_logmsg_reencode(r
, current_head
,
1494 const char *orig_message
= NULL
;
1496 find_commit_subject(message
, &orig_message
);
1498 strbuf_addstr(msg
, orig_message
);
1499 hook_commit
= "HEAD";
1501 author
= amend_author
= get_author(message
);
1502 repo_unuse_commit_buffer(r
, current_head
,
1505 res
= error(_("unable to parse commit author"));
1508 parents
= copy_commit_list(current_head
->parents
);
1509 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1510 } else if (current_head
&&
1511 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1512 commit_list_insert(current_head
, &parents
);
1515 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1516 res
= error(_("git write-tree failed to write a tree"));
1520 if (!(flags
& ALLOW_EMPTY
)) {
1521 struct commit
*first_parent
= current_head
;
1523 if (flags
& AMEND_MSG
) {
1524 if (current_head
->parents
) {
1525 first_parent
= current_head
->parents
->item
;
1526 if (repo_parse_commit(r
, first_parent
)) {
1527 res
= error(_("could not parse HEAD commit"));
1531 first_parent
= NULL
;
1534 if (oideq(first_parent
1535 ? get_commit_tree_oid(first_parent
)
1536 : the_hash_algo
->empty_tree
,
1538 res
= 1; /* run 'git commit' to display error message */
1543 if (hook_exists("prepare-commit-msg")) {
1544 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1547 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1549 res
= error_errno(_("unable to read commit message "
1551 git_path_commit_editmsg());
1557 if (flags
& CLEANUP_MSG
)
1558 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1559 else if (flags
& VERBATIM_MSG
)
1560 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1561 else if ((opts
->signoff
|| opts
->record_origin
) &&
1562 !opts
->explicit_cleanup
)
1563 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1565 cleanup
= opts
->default_msg_cleanup
;
1567 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1568 strbuf_stripspace(msg
,
1569 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1570 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1571 res
= 1; /* run 'git commit' to display error message */
1575 if (opts
->committer_date_is_author_date
) {
1576 struct ident_split id
;
1577 struct strbuf date
= STRBUF_INIT
;
1579 if (!opts
->ignore_date
) {
1580 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1581 res
= error(_("invalid author identity '%s'"),
1585 if (!id
.date_begin
) {
1587 "corrupt author: missing date information"));
1590 strbuf_addf(&date
, "@%.*s %.*s",
1591 (int)(id
.date_end
- id
.date_begin
),
1593 (int)(id
.tz_end
- id
.tz_begin
),
1598 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1599 getenv("GIT_COMMITTER_EMAIL"),
1600 WANT_COMMITTER_IDENT
,
1601 opts
->ignore_date
? NULL
: date
.buf
,
1603 strbuf_release(&date
);
1608 if (opts
->ignore_date
) {
1609 struct ident_split id
;
1612 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1613 error(_("invalid author identity '%s'"), author
);
1616 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1617 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1618 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1624 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1625 author
, committer
, opts
->gpg_sign
, extra
)) {
1626 res
= error(_("failed to write commit object"));
1630 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1632 res
= error("%s", err
.buf
);
1636 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1637 if (flags
& AMEND_MSG
)
1638 commit_post_rewrite(r
, current_head
, oid
);
1641 free_commit_extra_headers(extra
);
1642 strbuf_release(&err
);
1643 strbuf_release(&commit_msg
);
1649 static int write_rebase_head(struct object_id
*oid
)
1651 if (update_ref("rebase", "REBASE_HEAD", oid
,
1652 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1653 return error(_("could not update %s"), "REBASE_HEAD");
1658 static int do_commit(struct repository
*r
,
1659 const char *msg_file
, const char *author
,
1660 struct replay_opts
*opts
, unsigned int flags
,
1661 struct object_id
*oid
)
1665 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1666 struct object_id oid
;
1667 struct strbuf sb
= STRBUF_INIT
;
1669 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1670 return error_errno(_("unable to read commit message "
1674 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1675 author
, opts
, flags
, &oid
);
1676 strbuf_release(&sb
);
1678 refs_delete_ref(get_main_ref_store(r
), "",
1679 "CHERRY_PICK_HEAD", NULL
, 0);
1680 unlink(git_path_merge_msg(r
));
1681 if (!is_rebase_i(opts
))
1682 print_commit_summary(r
, NULL
, &oid
,
1683 SUMMARY_SHOW_AUTHOR_DATE
);
1688 if (is_rebase_i(opts
) && oid
)
1689 if (write_rebase_head(oid
))
1691 return run_git_commit(msg_file
, opts
, flags
);
1697 static int is_original_commit_empty(struct commit
*commit
)
1699 const struct object_id
*ptree_oid
;
1701 if (repo_parse_commit(the_repository
, commit
))
1702 return error(_("could not parse commit %s"),
1703 oid_to_hex(&commit
->object
.oid
));
1704 if (commit
->parents
) {
1705 struct commit
*parent
= commit
->parents
->item
;
1706 if (repo_parse_commit(the_repository
, parent
))
1707 return error(_("could not parse parent commit %s"),
1708 oid_to_hex(&parent
->object
.oid
));
1709 ptree_oid
= get_commit_tree_oid(parent
);
1711 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1714 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1718 * Should empty commits be allowed? Return status:
1719 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1720 * 0: Halt on empty commit
1721 * 1: Allow empty commit
1722 * 2: Drop empty commit
1724 static int allow_empty(struct repository
*r
,
1725 struct replay_opts
*opts
,
1726 struct commit
*commit
)
1728 int index_unchanged
, originally_empty
;
1733 * (1) we do not allow empty at all and error out.
1735 * (2) we allow ones that were initially empty, and
1736 * just drop the ones that become empty
1738 * (3) we allow ones that were initially empty, but
1739 * halt for the ones that become empty;
1741 * (4) we allow both.
1743 if (!opts
->allow_empty
)
1744 return 0; /* let "git commit" barf as necessary */
1746 index_unchanged
= is_index_unchanged(r
);
1747 if (index_unchanged
< 0)
1748 return index_unchanged
;
1749 if (!index_unchanged
)
1750 return 0; /* we do not have to say --allow-empty */
1752 if (opts
->keep_redundant_commits
)
1755 originally_empty
= is_original_commit_empty(commit
);
1756 if (originally_empty
< 0)
1757 return originally_empty
;
1758 if (originally_empty
)
1760 else if (opts
->drop_redundant_commits
)
1769 } todo_command_info
[] = {
1770 [TODO_PICK
] = { 'p', "pick" },
1771 [TODO_REVERT
] = { 0, "revert" },
1772 [TODO_EDIT
] = { 'e', "edit" },
1773 [TODO_REWORD
] = { 'r', "reword" },
1774 [TODO_FIXUP
] = { 'f', "fixup" },
1775 [TODO_SQUASH
] = { 's', "squash" },
1776 [TODO_EXEC
] = { 'x', "exec" },
1777 [TODO_BREAK
] = { 'b', "break" },
1778 [TODO_LABEL
] = { 'l', "label" },
1779 [TODO_RESET
] = { 't', "reset" },
1780 [TODO_MERGE
] = { 'm', "merge" },
1781 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1782 [TODO_NOOP
] = { 0, "noop" },
1783 [TODO_DROP
] = { 'd', "drop" },
1784 [TODO_COMMENT
] = { 0, NULL
},
1787 static const char *command_to_string(const enum todo_command command
)
1789 if (command
< TODO_COMMENT
)
1790 return todo_command_info
[command
].str
;
1791 die(_("unknown command: %d"), command
);
1794 static char command_to_char(const enum todo_command command
)
1796 if (command
< TODO_COMMENT
)
1797 return todo_command_info
[command
].c
;
1798 return comment_line_char
;
1801 static int is_noop(const enum todo_command command
)
1803 return TODO_NOOP
<= command
;
1806 static int is_fixup(enum todo_command command
)
1808 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1811 /* Does this command create a (non-merge) commit? */
1812 static int is_pick_or_similar(enum todo_command command
)
1827 enum todo_item_flags
{
1828 TODO_EDIT_MERGE_MSG
= (1 << 0),
1829 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1830 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1833 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1834 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1835 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1836 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1837 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1839 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1841 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1842 (flag
& TODO_EDIT_FIXUP_MSG
));
1846 * Wrapper around strbuf_add_commented_lines() which avoids double
1847 * commenting commit subjects.
1849 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1851 const char *s
= str
;
1852 while (len
> 0 && s
[0] == comment_line_char
) {
1854 const char *n
= memchr(s
, '\n', len
);
1859 strbuf_add(buf
, s
, count
);
1863 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1866 /* Does the current fixup chain contain a squash command? */
1867 static int seen_squash(struct replay_opts
*opts
)
1869 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1870 strstr(opts
->current_fixups
.buf
, "\nsquash");
1873 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1875 strbuf_setlen(buf1
, 2);
1876 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1877 strbuf_addch(buf1
, '\n');
1878 strbuf_setlen(buf2
, 2);
1879 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1880 strbuf_addch(buf2
, '\n');
1884 * Comment out any un-commented commit messages, updating the message comments
1885 * to say they will be skipped but do not comment out the empty lines that
1886 * surround commit messages and their comments.
1888 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1890 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1891 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1892 const char *s
, *start
;
1894 size_t orig_msg_len
;
1897 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1898 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1899 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1903 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1905 * Copy the last message, preserving the blank line
1906 * preceding the current line
1908 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1909 copy_lines(msg
, start
, s
- start
- off
);
1911 strbuf_addch(msg
, '\n');
1913 * The next message needs to be commented out but the
1914 * message header is already commented out so just copy
1915 * it and the blank line that follows it.
1917 strbuf_addbuf(msg
, &buf2
);
1919 strbuf_addch(msg
, *next
++);
1921 copy_lines
= add_commented_lines
;
1922 update_comment_bufs(&buf1
, &buf2
, ++i
);
1923 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1924 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1925 copy_lines(msg
, start
, s
- start
- off
);
1928 copy_lines
= strbuf_add
;
1929 update_comment_bufs(&buf1
, &buf2
, ++i
);
1931 s
= strchr(s
, '\n');
1936 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1938 strbuf_release(&buf1
);
1939 strbuf_release(&buf2
);
1942 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1943 enum todo_command command
, struct replay_opts
*opts
,
1946 const char *fixup_msg
;
1947 size_t commented_len
= 0, fixup_off
;
1949 * amend is non-interactive and not normally used with fixup!
1950 * or squash! commits, so only comment out those subjects when
1951 * squashing commit messages.
1953 if (starts_with(body
, "amend!") ||
1954 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1955 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1956 commented_len
= commit_subject_length(body
);
1958 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1959 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1960 ++opts
->current_fixup_count
+ 1);
1961 strbuf_addstr(buf
, "\n\n");
1962 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1963 /* buf->buf may be reallocated so store an offset into the buffer */
1964 fixup_off
= buf
->len
;
1965 strbuf_addstr(buf
, body
+ commented_len
);
1967 /* fixup -C after squash behaves like squash */
1968 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1970 * We're replacing the commit message so we need to
1971 * append the Signed-off-by: trailer if the user
1972 * requested '--signoff'.
1975 append_signoff(buf
, 0, 0);
1977 if ((command
== TODO_FIXUP
) &&
1978 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1979 (file_exists(rebase_path_fixup_msg()) ||
1980 !file_exists(rebase_path_squash_msg()))) {
1981 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1982 if (write_message(fixup_msg
, strlen(fixup_msg
),
1983 rebase_path_fixup_msg(), 0) < 0)
1984 return error(_("cannot write '%s'"),
1985 rebase_path_fixup_msg());
1987 unlink(rebase_path_fixup_msg());
1990 unlink(rebase_path_fixup_msg());
1996 static int update_squash_messages(struct repository
*r
,
1997 enum todo_command command
,
1998 struct commit
*commit
,
1999 struct replay_opts
*opts
,
2002 struct strbuf buf
= STRBUF_INIT
;
2004 const char *message
, *body
;
2005 const char *encoding
= get_commit_output_encoding();
2007 if (opts
->current_fixup_count
> 0) {
2008 struct strbuf header
= STRBUF_INIT
;
2011 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2012 return error(_("could not read '%s'"),
2013 rebase_path_squash_msg());
2015 eol
= buf
.buf
[0] != comment_line_char
?
2016 buf
.buf
: strchrnul(buf
.buf
, '\n');
2018 strbuf_addf(&header
, "%c ", comment_line_char
);
2019 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2020 opts
->current_fixup_count
+ 2);
2021 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2022 strbuf_release(&header
);
2023 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2024 update_squash_message_for_fixup(&buf
);
2026 struct object_id head
;
2027 struct commit
*head_commit
;
2028 const char *head_message
, *body
;
2030 if (repo_get_oid(r
, "HEAD", &head
))
2031 return error(_("need a HEAD to fixup"));
2032 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2033 return error(_("could not read HEAD"));
2034 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2036 return error(_("could not read HEAD's commit message"));
2038 find_commit_subject(head_message
, &body
);
2039 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2040 rebase_path_fixup_msg(), 0) < 0) {
2041 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2042 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2044 strbuf_addf(&buf
, "%c ", comment_line_char
);
2045 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2046 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2047 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2048 _(skip_first_commit_msg_str
) :
2049 _(first_commit_msg_str
));
2050 strbuf_addstr(&buf
, "\n\n");
2051 if (is_fixup_flag(command
, flag
))
2052 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2055 strbuf_addstr(&buf
, body
);
2057 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2060 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2061 return error(_("could not read commit message of %s"),
2062 oid_to_hex(&commit
->object
.oid
));
2063 find_commit_subject(message
, &body
);
2065 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2066 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2067 } else if (command
== TODO_FIXUP
) {
2068 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2069 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2070 ++opts
->current_fixup_count
+ 1);
2071 strbuf_addstr(&buf
, "\n\n");
2072 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2075 return error(_("unknown command: %d"), command
);
2076 repo_unuse_commit_buffer(r
, commit
, message
);
2079 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2081 strbuf_release(&buf
);
2084 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2085 opts
->current_fixups
.len
? "\n" : "",
2086 command_to_string(command
),
2087 oid_to_hex(&commit
->object
.oid
));
2088 res
= write_message(opts
->current_fixups
.buf
,
2089 opts
->current_fixups
.len
,
2090 rebase_path_current_fixups(), 0);
2096 static void flush_rewritten_pending(void)
2098 struct strbuf buf
= STRBUF_INIT
;
2099 struct object_id newoid
;
2102 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2103 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2104 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2105 char *bol
= buf
.buf
, *eol
;
2108 eol
= strchrnul(bol
, '\n');
2109 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2110 bol
, oid_to_hex(&newoid
));
2116 unlink(rebase_path_rewritten_pending());
2118 strbuf_release(&buf
);
2121 static void record_in_rewritten(struct object_id
*oid
,
2122 enum todo_command next_command
)
2124 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2129 fprintf(out
, "%s\n", oid_to_hex(oid
));
2132 if (!is_fixup(next_command
))
2133 flush_rewritten_pending();
2136 static int should_edit(struct replay_opts
*opts
) {
2139 * Note that we only handle the case of non-conflicted
2140 * commits; continue_single_pick() handles the conflicted
2141 * commits itself instead of calling this function.
2143 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2147 static void refer_to_commit(struct replay_opts
*opts
,
2148 struct strbuf
*msgbuf
, struct commit
*commit
)
2150 if (opts
->commit_use_reference
) {
2151 struct pretty_print_context ctx
= {
2152 .abbrev
= DEFAULT_ABBREV
,
2153 .date_mode
.type
= DATE_SHORT
,
2155 repo_format_commit_message(the_repository
, commit
,
2156 "%h (%s, %ad)", msgbuf
, &ctx
);
2158 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2162 static int do_pick_commit(struct repository
*r
,
2163 struct todo_item
*item
,
2164 struct replay_opts
*opts
,
2165 int final_fixup
, int *check_todo
)
2167 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2168 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2169 struct object_id head
;
2170 struct commit
*base
, *next
, *parent
;
2171 const char *base_label
, *next_label
;
2172 char *author
= NULL
;
2173 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2174 struct strbuf msgbuf
= STRBUF_INIT
;
2175 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2176 enum todo_command command
= item
->command
;
2177 struct commit
*commit
= item
->commit
;
2179 if (opts
->no_commit
) {
2181 * We do not intend to commit immediately. We just want to
2182 * merge the differences in, so let's compute the tree
2183 * that represents the "current" state for the merge machinery
2186 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2187 return error(_("your index file is unmerged."));
2189 unborn
= repo_get_oid(r
, "HEAD", &head
);
2190 /* Do we want to generate a root commit? */
2191 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2192 oideq(&head
, &opts
->squash_onto
)) {
2193 if (is_fixup(command
))
2194 return error(_("cannot fixup root commit"));
2195 flags
|= CREATE_ROOT_COMMIT
;
2198 oidcpy(&head
, the_hash_algo
->empty_tree
);
2199 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2201 return error_dirty_index(r
, opts
);
2203 discard_index(r
->index
);
2205 if (!commit
->parents
)
2207 else if (commit
->parents
->next
) {
2208 /* Reverting or cherry-picking a merge commit */
2210 struct commit_list
*p
;
2212 if (!opts
->mainline
)
2213 return error(_("commit %s is a merge but no -m option was given."),
2214 oid_to_hex(&commit
->object
.oid
));
2216 for (cnt
= 1, p
= commit
->parents
;
2217 cnt
!= opts
->mainline
&& p
;
2220 if (cnt
!= opts
->mainline
|| !p
)
2221 return error(_("commit %s does not have parent %d"),
2222 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2224 } else if (1 < opts
->mainline
)
2226 * Non-first parent explicitly specified as mainline for
2229 return error(_("commit %s does not have parent %d"),
2230 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2232 parent
= commit
->parents
->item
;
2234 if (get_message(commit
, &msg
) != 0)
2235 return error(_("cannot get commit message for %s"),
2236 oid_to_hex(&commit
->object
.oid
));
2238 if (opts
->allow_ff
&& !is_fixup(command
) &&
2239 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2240 (!parent
&& unborn
))) {
2241 if (is_rebase_i(opts
))
2242 write_author_script(msg
.message
);
2243 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2245 if (res
|| command
!= TODO_REWORD
)
2249 goto fast_forward_edit
;
2251 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2252 /* TRANSLATORS: The first %s will be a "todo" command like
2253 "revert" or "pick", the second %s a SHA1. */
2254 return error(_("%s: cannot parse parent commit %s"),
2255 command_to_string(command
),
2256 oid_to_hex(&parent
->object
.oid
));
2259 * "commit" is an existing commit. We would want to apply
2260 * the difference it introduces since its first parent "prev"
2261 * on top of the current HEAD if we are cherry-pick. Or the
2262 * reverse of it if we are revert.
2265 if (command
== TODO_REVERT
) {
2267 base_label
= msg
.label
;
2269 next_label
= msg
.parent_label
;
2270 if (opts
->commit_use_reference
) {
2271 strbuf_addstr(&msgbuf
,
2272 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2274 strbuf_addstr(&msgbuf
, "Revert \"");
2275 strbuf_addstr(&msgbuf
, msg
.subject
);
2276 strbuf_addstr(&msgbuf
, "\"");
2278 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2279 refer_to_commit(opts
, &msgbuf
, commit
);
2281 if (commit
->parents
&& commit
->parents
->next
) {
2282 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2283 refer_to_commit(opts
, &msgbuf
, parent
);
2285 strbuf_addstr(&msgbuf
, ".\n");
2290 base_label
= msg
.parent_label
;
2292 next_label
= msg
.label
;
2294 /* Append the commit log message to msgbuf. */
2295 if (find_commit_subject(msg
.message
, &p
))
2296 strbuf_addstr(&msgbuf
, p
);
2298 if (opts
->record_origin
) {
2299 strbuf_complete_line(&msgbuf
);
2300 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2301 strbuf_addch(&msgbuf
, '\n');
2302 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2303 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2304 strbuf_addstr(&msgbuf
, ")\n");
2306 if (!is_fixup(command
))
2307 author
= get_author(msg
.message
);
2310 if (command
== TODO_REWORD
)
2312 else if (is_fixup(command
)) {
2313 if (update_squash_messages(r
, command
, commit
,
2314 opts
, item
->flags
)) {
2320 msg_file
= rebase_path_squash_msg();
2321 else if (file_exists(rebase_path_fixup_msg())) {
2322 flags
|= VERBATIM_MSG
;
2323 msg_file
= rebase_path_fixup_msg();
2325 const char *dest
= git_path_squash_msg(r
);
2327 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2328 res
= error(_("could not copy '%s' to '%s'"),
2329 rebase_path_squash_msg(), dest
);
2332 unlink(git_path_merge_msg(r
));
2338 if (opts
->signoff
&& !is_fixup(command
))
2339 append_signoff(&msgbuf
, 0, 0);
2341 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2343 else if (!opts
->strategy
||
2344 !strcmp(opts
->strategy
, "recursive") ||
2345 !strcmp(opts
->strategy
, "ort") ||
2346 command
== TODO_REVERT
) {
2347 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2348 &head
, &msgbuf
, opts
);
2352 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2353 git_path_merge_msg(r
), 0);
2355 struct commit_list
*common
= NULL
;
2356 struct commit_list
*remotes
= NULL
;
2358 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2359 git_path_merge_msg(r
), 0);
2361 commit_list_insert(base
, &common
);
2362 commit_list_insert(next
, &remotes
);
2363 res
|= try_merge_command(r
, opts
->strategy
,
2364 opts
->xopts
.nr
, opts
->xopts
.v
,
2365 common
, oid_to_hex(&head
), remotes
);
2366 free_commit_list(common
);
2367 free_commit_list(remotes
);
2371 * If the merge was clean or if it failed due to conflict, we write
2372 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2373 * However, if the merge did not even start, then we don't want to
2376 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2377 command
== TODO_EDIT
) && !opts
->no_commit
&&
2378 (res
== 0 || res
== 1) &&
2379 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2380 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2382 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2383 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2384 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2388 error(command
== TODO_REVERT
2389 ? _("could not revert %s... %s")
2390 : _("could not apply %s... %s"),
2391 short_commit_name(commit
), msg
.subject
);
2392 print_advice(r
, res
== 1, opts
);
2393 repo_rerere(r
, opts
->allow_rerere_auto
);
2398 allow
= allow_empty(r
, opts
, commit
);
2402 } else if (allow
== 1) {
2403 flags
|= ALLOW_EMPTY
;
2404 } else if (allow
== 2) {
2406 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2408 unlink(git_path_merge_msg(r
));
2409 unlink(git_path_auto_merge(r
));
2411 _("dropping %s %s -- patch contents already upstream\n"),
2412 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2413 } /* else allow == 0 and there's nothing special to do */
2414 if (!opts
->no_commit
&& !drop_commit
) {
2415 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2416 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2417 commit
? &commit
->object
.oid
: NULL
);
2419 res
= error(_("unable to parse commit author"));
2420 *check_todo
= !!(flags
& EDIT_MSG
);
2421 if (!res
&& reword
) {
2423 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2424 VERIFY_MSG
| AMEND_MSG
|
2425 (flags
& ALLOW_EMPTY
));
2431 if (!res
&& final_fixup
) {
2432 unlink(rebase_path_fixup_msg());
2433 unlink(rebase_path_squash_msg());
2434 unlink(rebase_path_current_fixups());
2435 strbuf_reset(&opts
->current_fixups
);
2436 opts
->current_fixup_count
= 0;
2440 free_message(commit
, &msg
);
2442 strbuf_release(&msgbuf
);
2443 update_abort_safety_file();
2448 static int prepare_revs(struct replay_opts
*opts
)
2451 * picking (but not reverting) ranges (but not individual revisions)
2452 * should be done in reverse
2454 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2455 opts
->revs
->reverse
^= 1;
2457 if (prepare_revision_walk(opts
->revs
))
2458 return error(_("revision walk setup failed"));
2463 static int read_and_refresh_cache(struct repository
*r
,
2464 struct replay_opts
*opts
)
2466 struct lock_file index_lock
= LOCK_INIT
;
2467 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2468 if (repo_read_index(r
) < 0) {
2469 rollback_lock_file(&index_lock
);
2470 return error(_("git %s: failed to read the index"),
2473 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2475 if (index_fd
>= 0) {
2476 if (write_locked_index(r
->index
, &index_lock
,
2477 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2478 return error(_("git %s: failed to refresh the index"),
2484 * If we are resolving merges in any way other than "ort", then
2485 * expand the sparse index.
2487 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2488 ensure_full_index(r
->index
);
2492 void todo_list_release(struct todo_list
*todo_list
)
2494 strbuf_release(&todo_list
->buf
);
2495 FREE_AND_NULL(todo_list
->items
);
2496 todo_list
->nr
= todo_list
->alloc
= 0;
2499 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2501 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2502 return todo_list
->items
+ todo_list
->nr
++;
2505 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2506 struct todo_item
*item
)
2508 return todo_list
->buf
.buf
+ item
->arg_offset
;
2511 static int is_command(enum todo_command command
, const char **bol
)
2513 const char *str
= todo_command_info
[command
].str
;
2514 const char nick
= todo_command_info
[command
].c
;
2515 const char *p
= *bol
;
2517 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2518 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2522 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2527 * '#' is not a valid label as the merge command uses it to
2528 * separate merge parents from the commit subject.
2530 if (!strcmp(arg
, "#") ||
2531 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2532 return error(_("'%s' is not a valid label"), arg
);
2535 case TODO_UPDATE_REF
:
2536 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2537 return error(_("'%s' is not a valid refname"), arg
);
2538 if (check_refname_format(arg
, 0))
2539 return error(_("update-ref requires a fully qualified "
2540 "refname e.g. refs/heads/%s"), arg
);
2544 BUG("unexpected todo_command");
2550 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2551 const char *buf
, const char *bol
, char *eol
)
2553 struct object_id commit_oid
;
2554 char *end_of_object_name
;
2555 int i
, saved
, status
, padding
;
2560 bol
+= strspn(bol
, " \t");
2562 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2563 item
->command
= TODO_COMMENT
;
2564 item
->commit
= NULL
;
2565 item
->arg_offset
= bol
- buf
;
2566 item
->arg_len
= eol
- bol
;
2570 for (i
= 0; i
< TODO_COMMENT
; i
++)
2571 if (is_command(i
, &bol
)) {
2575 if (i
>= TODO_COMMENT
)
2576 return error(_("invalid command '%.*s'"),
2577 (int)strcspn(bol
, " \t\r\n"), bol
);
2579 /* Eat up extra spaces/ tabs before object name */
2580 padding
= strspn(bol
, " \t");
2583 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2585 return error(_("%s does not accept arguments: '%s'"),
2586 command_to_string(item
->command
), bol
);
2587 item
->commit
= NULL
;
2588 item
->arg_offset
= bol
- buf
;
2589 item
->arg_len
= eol
- bol
;
2594 return error(_("missing arguments for %s"),
2595 command_to_string(item
->command
));
2597 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2598 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2601 item
->commit
= NULL
;
2602 item
->arg_offset
= bol
- buf
;
2603 item
->arg_len
= (int)(eol
- bol
);
2604 if (item
->command
== TODO_LABEL
||
2605 item
->command
== TODO_UPDATE_REF
) {
2608 ret
= check_label_or_ref_arg(item
->command
, bol
);
2614 if (item
->command
== TODO_FIXUP
) {
2615 if (skip_prefix(bol
, "-C", &bol
)) {
2616 bol
+= strspn(bol
, " \t");
2617 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2618 } else if (skip_prefix(bol
, "-c", &bol
)) {
2619 bol
+= strspn(bol
, " \t");
2620 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2624 if (item
->command
== TODO_MERGE
) {
2625 if (skip_prefix(bol
, "-C", &bol
))
2626 bol
+= strspn(bol
, " \t");
2627 else if (skip_prefix(bol
, "-c", &bol
)) {
2628 bol
+= strspn(bol
, " \t");
2629 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2631 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2632 item
->commit
= NULL
;
2633 item
->arg_offset
= bol
- buf
;
2634 item
->arg_len
= (int)(eol
- bol
);
2639 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2640 saved
= *end_of_object_name
;
2641 *end_of_object_name
= '\0';
2642 status
= repo_get_oid(r
, bol
, &commit_oid
);
2644 error(_("could not parse '%s'"), bol
); /* return later */
2645 *end_of_object_name
= saved
;
2647 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2648 item
->arg_offset
= bol
- buf
;
2649 item
->arg_len
= (int)(eol
- bol
);
2654 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2655 return item
->commit
? 0 : -1;
2658 int sequencer_get_last_command(struct repository
*r
, enum replay_action
*action
)
2660 const char *todo_file
, *bol
;
2661 struct strbuf buf
= STRBUF_INIT
;
2664 todo_file
= git_path_todo_file();
2665 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2666 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2669 return error_errno("unable to open '%s'", todo_file
);
2671 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2672 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2673 *action
= REPLAY_PICK
;
2674 else if (is_command(TODO_REVERT
, &bol
) &&
2675 (*bol
== ' ' || *bol
== '\t'))
2676 *action
= REPLAY_REVERT
;
2680 strbuf_release(&buf
);
2685 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2686 struct todo_list
*todo_list
)
2688 struct todo_item
*item
;
2689 char *p
= buf
, *next_p
;
2690 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2692 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2694 for (i
= 1; *p
; i
++, p
= next_p
) {
2695 char *eol
= strchrnul(p
, '\n');
2697 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2699 if (p
!= eol
&& eol
[-1] == '\r')
2700 eol
--; /* strip Carriage Return */
2702 item
= append_new_todo(todo_list
);
2703 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2704 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2705 res
= error(_("invalid line %d: %.*s"),
2706 i
, (int)(eol
- p
), p
);
2707 item
->command
= TODO_COMMENT
+ 1;
2708 item
->arg_offset
= p
- buf
;
2709 item
->arg_len
= (int)(eol
- p
);
2710 item
->commit
= NULL
;
2713 if (item
->command
!= TODO_COMMENT
)
2714 todo_list
->total_nr
++;
2718 else if (is_fixup(item
->command
))
2719 res
= error(_("cannot '%s' without a previous commit"),
2720 command_to_string(item
->command
));
2721 else if (!is_noop(item
->command
))
2728 static int count_commands(struct todo_list
*todo_list
)
2732 for (i
= 0; i
< todo_list
->nr
; i
++)
2733 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2739 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2741 return index
< todo_list
->nr
?
2742 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2745 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2747 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2750 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2752 return get_item_line_offset(todo_list
, index
+ 1)
2753 - get_item_line_offset(todo_list
, index
);
2756 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2761 fd
= open(path
, O_RDONLY
);
2763 return error_errno(_("could not open '%s'"), path
);
2764 len
= strbuf_read(sb
, fd
, 0);
2767 return error(_("could not read '%s'."), path
);
2771 static int have_finished_the_last_pick(void)
2773 struct strbuf buf
= STRBUF_INIT
;
2775 const char *todo_path
= git_path_todo_file();
2778 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2779 if (errno
== ENOENT
) {
2782 error_errno("unable to open '%s'", todo_path
);
2786 /* If there is only one line then we are done */
2787 eol
= strchr(buf
.buf
, '\n');
2788 if (!eol
|| !eol
[1])
2791 strbuf_release(&buf
);
2796 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2798 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2799 int need_cleanup
= 0;
2801 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2802 if (!refs_delete_ref(get_main_ref_store(r
), "",
2803 "CHERRY_PICK_HEAD", NULL
, 0) &&
2805 warning(_("cancelling a cherry picking in progress"));
2806 opts
.action
= REPLAY_PICK
;
2810 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2811 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2814 warning(_("cancelling a revert in progress"));
2815 opts
.action
= REPLAY_REVERT
;
2819 unlink(git_path_auto_merge(r
));
2824 if (!have_finished_the_last_pick())
2827 sequencer_remove_state(&opts
);
2830 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2832 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2835 fprintf(f
, "%d\n", todo_list
->total_nr
);
2840 static int read_populate_todo(struct repository
*r
,
2841 struct todo_list
*todo_list
,
2842 struct replay_opts
*opts
)
2844 const char *todo_file
= get_todo_path(opts
);
2847 strbuf_reset(&todo_list
->buf
);
2848 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2851 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2853 if (is_rebase_i(opts
))
2854 return error(_("please fix this using "
2855 "'git rebase --edit-todo'."));
2856 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2859 if (!todo_list
->nr
&&
2860 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2861 return error(_("no commits parsed."));
2863 if (!is_rebase_i(opts
)) {
2864 enum todo_command valid
=
2865 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2868 for (i
= 0; i
< todo_list
->nr
; i
++)
2869 if (valid
== todo_list
->items
[i
].command
)
2871 else if (valid
== TODO_PICK
)
2872 return error(_("cannot cherry-pick during a revert."));
2874 return error(_("cannot revert during a cherry-pick."));
2877 if (is_rebase_i(opts
)) {
2878 struct todo_list done
= TODO_LIST_INIT
;
2880 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2881 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2882 todo_list
->done_nr
= count_commands(&done
);
2884 todo_list
->done_nr
= 0;
2886 todo_list
->total_nr
= todo_list
->done_nr
2887 + count_commands(todo_list
);
2888 todo_list_release(&done
);
2890 todo_list_write_total_nr(todo_list
);
2896 static int git_config_string_dup(char **dest
,
2897 const char *var
, const char *value
)
2900 return config_error_nonbool(var
);
2902 *dest
= xstrdup(value
);
2906 static int populate_opts_cb(const char *key
, const char *value
,
2907 const struct config_context
*ctx
,
2910 struct replay_opts
*opts
= data
;
2915 else if (!strcmp(key
, "options.no-commit"))
2916 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2917 else if (!strcmp(key
, "options.edit"))
2918 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2919 else if (!strcmp(key
, "options.allow-empty"))
2921 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2922 else if (!strcmp(key
, "options.allow-empty-message"))
2923 opts
->allow_empty_message
=
2924 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2925 else if (!strcmp(key
, "options.keep-redundant-commits"))
2926 opts
->keep_redundant_commits
=
2927 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2928 else if (!strcmp(key
, "options.signoff"))
2929 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2930 else if (!strcmp(key
, "options.record-origin"))
2931 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2932 else if (!strcmp(key
, "options.allow-ff"))
2933 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2934 else if (!strcmp(key
, "options.mainline"))
2935 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2936 else if (!strcmp(key
, "options.strategy"))
2937 git_config_string_dup(&opts
->strategy
, key
, value
);
2938 else if (!strcmp(key
, "options.gpg-sign"))
2939 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2940 else if (!strcmp(key
, "options.strategy-option")) {
2941 strvec_push(&opts
->xopts
, value
);
2942 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2943 opts
->allow_rerere_auto
=
2944 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2945 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2946 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2947 opts
->explicit_cleanup
= 1;
2948 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2950 return error(_("invalid key: %s"), key
);
2953 return error(_("invalid value for '%s': '%s'"), key
, value
);
2958 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2963 char *strategy_opts_string
= raw_opts
;
2965 if (*strategy_opts_string
== ' ')
2966 strategy_opts_string
++;
2968 count
= split_cmdline(strategy_opts_string
, &argv
);
2970 BUG("could not split '%s': %s", strategy_opts_string
,
2971 split_cmdline_strerror(count
));
2972 for (i
= 0; i
< count
; i
++) {
2973 const char *arg
= argv
[i
];
2975 skip_prefix(arg
, "--", &arg
);
2976 strvec_push(&opts
->xopts
, arg
);
2981 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2984 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2986 opts
->strategy
= strbuf_detach(buf
, NULL
);
2987 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2990 parse_strategy_opts(opts
, buf
->buf
);
2993 static int read_populate_opts(struct replay_opts
*opts
)
2995 if (is_rebase_i(opts
)) {
2996 struct strbuf buf
= STRBUF_INIT
;
2999 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
3000 READ_ONELINER_SKIP_IF_EMPTY
)) {
3001 if (!starts_with(buf
.buf
, "-S"))
3004 free(opts
->gpg_sign
);
3005 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3010 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3011 READ_ONELINER_SKIP_IF_EMPTY
)) {
3012 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3013 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3014 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3015 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3019 if (file_exists(rebase_path_verbose()))
3022 if (file_exists(rebase_path_quiet()))
3025 if (file_exists(rebase_path_signoff())) {
3030 if (file_exists(rebase_path_cdate_is_adate())) {
3032 opts
->committer_date_is_author_date
= 1;
3035 if (file_exists(rebase_path_ignore_date())) {
3037 opts
->ignore_date
= 1;
3040 if (file_exists(rebase_path_reschedule_failed_exec()))
3041 opts
->reschedule_failed_exec
= 1;
3042 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3043 opts
->reschedule_failed_exec
= 0;
3045 if (file_exists(rebase_path_drop_redundant_commits()))
3046 opts
->drop_redundant_commits
= 1;
3048 if (file_exists(rebase_path_keep_redundant_commits()))
3049 opts
->keep_redundant_commits
= 1;
3051 read_strategy_opts(opts
, &buf
);
3054 if (read_oneliner(&opts
->current_fixups
,
3055 rebase_path_current_fixups(),
3056 READ_ONELINER_SKIP_IF_EMPTY
)) {
3057 const char *p
= opts
->current_fixups
.buf
;
3058 opts
->current_fixup_count
= 1;
3059 while ((p
= strchr(p
, '\n'))) {
3060 opts
->current_fixup_count
++;
3065 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3066 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3067 ret
= error(_("unusable squash-onto"));
3070 opts
->have_squash_onto
= 1;
3074 strbuf_release(&buf
);
3078 if (!file_exists(git_path_opts_file()))
3081 * The function git_parse_source(), called from git_config_from_file(),
3082 * may die() in case of a syntactically incorrect file. We do not care
3083 * about this case, though, because we wrote that file ourselves, so we
3084 * are pretty certain that it is syntactically correct.
3086 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3087 return error(_("malformed options sheet: '%s'"),
3088 git_path_opts_file());
3092 static void write_strategy_opts(struct replay_opts
*opts
)
3094 struct strbuf buf
= STRBUF_INIT
;
3097 * Quote strategy options so that they can be read correctly
3098 * by split_cmdline().
3100 quote_cmdline(&buf
, opts
->xopts
.v
);
3101 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3102 strbuf_release(&buf
);
3105 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3106 struct commit
*onto
, const struct object_id
*orig_head
)
3109 write_file(rebase_path_head_name(), "%s\n", head_name
);
3111 write_file(rebase_path_onto(), "%s\n",
3112 oid_to_hex(&onto
->object
.oid
));
3114 write_file(rebase_path_orig_head(), "%s\n",
3115 oid_to_hex(orig_head
));
3118 write_file(rebase_path_quiet(), "%s", "");
3120 write_file(rebase_path_verbose(), "%s", "");
3122 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3123 if (opts
->xopts
.nr
> 0)
3124 write_strategy_opts(opts
);
3126 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3127 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3128 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3129 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3132 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3134 write_file(rebase_path_signoff(), "--signoff\n");
3135 if (opts
->drop_redundant_commits
)
3136 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3137 if (opts
->keep_redundant_commits
)
3138 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3139 if (opts
->committer_date_is_author_date
)
3140 write_file(rebase_path_cdate_is_adate(), "%s", "");
3141 if (opts
->ignore_date
)
3142 write_file(rebase_path_ignore_date(), "%s", "");
3143 if (opts
->reschedule_failed_exec
)
3144 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3146 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3151 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3152 struct replay_opts
*opts
)
3154 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3155 TODO_PICK
: TODO_REVERT
;
3156 const char *command_string
= todo_command_info
[command
].str
;
3157 const char *encoding
;
3158 struct commit
*commit
;
3160 if (prepare_revs(opts
))
3163 encoding
= get_log_output_encoding();
3165 while ((commit
= get_revision(opts
->revs
))) {
3166 struct todo_item
*item
= append_new_todo(todo_list
);
3167 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3170 const char *subject
;
3173 item
->command
= command
;
3174 item
->commit
= commit
;
3175 item
->arg_offset
= 0;
3177 item
->offset_in_buf
= todo_list
->buf
.len
;
3178 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3179 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3180 short_commit_name(commit
), subject_len
, subject
);
3181 repo_unuse_commit_buffer(the_repository
, commit
,
3186 return error(_("empty commit set passed"));
3191 static int create_seq_dir(struct repository
*r
)
3193 enum replay_action action
;
3194 const char *in_progress_error
= NULL
;
3195 const char *in_progress_advice
= NULL
;
3196 unsigned int advise_skip
=
3197 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3198 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3200 if (!sequencer_get_last_command(r
, &action
)) {
3203 in_progress_error
= _("revert is already in progress");
3204 in_progress_advice
=
3205 _("try \"git revert (--continue | %s--abort | --quit)\"");
3208 in_progress_error
= _("cherry-pick is already in progress");
3209 in_progress_advice
=
3210 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3213 BUG("unexpected action in create_seq_dir");
3216 if (in_progress_error
) {
3217 error("%s", in_progress_error
);
3218 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3219 advise(in_progress_advice
,
3220 advise_skip
? "--skip | " : "");
3223 if (mkdir(git_path_seq_dir(), 0777) < 0)
3224 return error_errno(_("could not create sequencer directory '%s'"),
3225 git_path_seq_dir());
3230 static int save_head(const char *head
)
3232 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3235 static int rollback_is_safe(void)
3237 struct strbuf sb
= STRBUF_INIT
;
3238 struct object_id expected_head
, actual_head
;
3240 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3242 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3243 strbuf_release(&sb
);
3244 die(_("could not parse %s"), git_path_abort_safety_file());
3246 strbuf_release(&sb
);
3248 else if (errno
== ENOENT
)
3249 oidclr(&expected_head
);
3251 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3253 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3254 oidclr(&actual_head
);
3256 return oideq(&actual_head
, &expected_head
);
3259 static int reset_merge(const struct object_id
*oid
)
3261 struct child_process cmd
= CHILD_PROCESS_INIT
;
3264 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3266 if (!is_null_oid(oid
))
3267 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3269 return run_command(&cmd
);
3272 static int rollback_single_pick(struct repository
*r
)
3274 struct object_id head_oid
;
3276 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3277 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3278 return error(_("no cherry-pick or revert in progress"));
3279 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3280 return error(_("cannot resolve HEAD"));
3281 if (is_null_oid(&head_oid
))
3282 return error(_("cannot abort from a branch yet to be born"));
3283 return reset_merge(&head_oid
);
3286 static int skip_single_pick(void)
3288 struct object_id head
;
3290 if (read_ref_full("HEAD", 0, &head
, NULL
))
3291 return error(_("cannot resolve HEAD"));
3292 return reset_merge(&head
);
3295 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3298 struct object_id oid
;
3299 struct strbuf buf
= STRBUF_INIT
;
3302 f
= fopen(git_path_head_file(), "r");
3303 if (!f
&& errno
== ENOENT
) {
3305 * There is no multiple-cherry-pick in progress.
3306 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3307 * a single-cherry-pick in progress, abort that.
3309 return rollback_single_pick(r
);
3312 return error_errno(_("cannot open '%s'"), git_path_head_file());
3313 if (strbuf_getline_lf(&buf
, f
)) {
3314 error(_("cannot read '%s': %s"), git_path_head_file(),
3315 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3320 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3321 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3322 git_path_head_file());
3325 if (is_null_oid(&oid
)) {
3326 error(_("cannot abort from a branch yet to be born"));
3330 if (!rollback_is_safe()) {
3331 /* Do not error, just do not rollback */
3332 warning(_("You seem to have moved HEAD. "
3333 "Not rewinding, check your HEAD!"));
3335 if (reset_merge(&oid
))
3337 strbuf_release(&buf
);
3338 return sequencer_remove_state(opts
);
3340 strbuf_release(&buf
);
3344 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3346 enum replay_action action
= -1;
3347 sequencer_get_last_command(r
, &action
);
3350 * Check whether the subcommand requested to skip the commit is actually
3351 * in progress and that it's safe to skip the commit.
3353 * opts->action tells us which subcommand requested to skip the commit.
3354 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3355 * action is in progress and we can skip the commit.
3357 * Otherwise we check that the last instruction was related to the
3358 * particular subcommand we're trying to execute and barf if that's not
3361 * Finally we check that the rollback is "safe", i.e., has the HEAD
3362 * moved? In this case, it doesn't make sense to "reset the merge" and
3363 * "skip the commit" as the user already handled this by committing. But
3364 * we'd not want to barf here, instead give advice on how to proceed. We
3365 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3366 * it gets removed when the user commits, so if it still exists we're
3367 * sure the user can't have committed before.
3369 switch (opts
->action
) {
3371 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3372 if (action
!= REPLAY_REVERT
)
3373 return error(_("no revert in progress"));
3374 if (!rollback_is_safe())
3379 if (!refs_ref_exists(get_main_ref_store(r
),
3380 "CHERRY_PICK_HEAD")) {
3381 if (action
!= REPLAY_PICK
)
3382 return error(_("no cherry-pick in progress"));
3383 if (!rollback_is_safe())
3388 BUG("unexpected action in sequencer_skip");
3391 if (skip_single_pick())
3392 return error(_("failed to skip the commit"));
3393 if (!is_directory(git_path_seq_dir()))
3396 return sequencer_continue(r
, opts
);
3399 error(_("there is nothing to skip"));
3401 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3402 advise(_("have you committed already?\n"
3403 "try \"git %s --continue\""),
3404 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3409 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
,
3412 struct lock_file todo_lock
= LOCK_INIT
;
3413 const char *todo_path
= get_todo_path(opts
);
3414 int next
= todo_list
->current
, offset
, fd
;
3417 * rebase -i writes "git-rebase-todo" without the currently executing
3418 * command, appending it to "done" instead.
3420 if (is_rebase_i(opts
) && !reschedule
)
3423 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3425 return error_errno(_("could not lock '%s'"), todo_path
);
3426 offset
= get_item_line_offset(todo_list
, next
);
3427 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3428 todo_list
->buf
.len
- offset
) < 0)
3429 return error_errno(_("could not write to '%s'"), todo_path
);
3430 if (commit_lock_file(&todo_lock
) < 0)
3431 return error(_("failed to finalize '%s'"), todo_path
);
3433 if (is_rebase_i(opts
) && !reschedule
&& next
> 0) {
3434 const char *done
= rebase_path_done();
3435 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3440 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3441 get_item_line_length(todo_list
, next
- 1))
3443 ret
= error_errno(_("could not write to '%s'"), done
);
3445 ret
= error_errno(_("failed to finalize '%s'"), done
);
3451 static int save_opts(struct replay_opts
*opts
)
3453 const char *opts_file
= git_path_opts_file();
3456 if (opts
->no_commit
)
3457 res
|= git_config_set_in_file_gently(opts_file
,
3458 "options.no-commit", "true");
3459 if (opts
->edit
>= 0)
3460 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3461 opts
->edit
? "true" : "false");
3462 if (opts
->allow_empty
)
3463 res
|= git_config_set_in_file_gently(opts_file
,
3464 "options.allow-empty", "true");
3465 if (opts
->allow_empty_message
)
3466 res
|= git_config_set_in_file_gently(opts_file
,
3467 "options.allow-empty-message", "true");
3468 if (opts
->keep_redundant_commits
)
3469 res
|= git_config_set_in_file_gently(opts_file
,
3470 "options.keep-redundant-commits", "true");
3472 res
|= git_config_set_in_file_gently(opts_file
,
3473 "options.signoff", "true");
3474 if (opts
->record_origin
)
3475 res
|= git_config_set_in_file_gently(opts_file
,
3476 "options.record-origin", "true");
3478 res
|= git_config_set_in_file_gently(opts_file
,
3479 "options.allow-ff", "true");
3480 if (opts
->mainline
) {
3481 struct strbuf buf
= STRBUF_INIT
;
3482 strbuf_addf(&buf
, "%d", opts
->mainline
);
3483 res
|= git_config_set_in_file_gently(opts_file
,
3484 "options.mainline", buf
.buf
);
3485 strbuf_release(&buf
);
3488 res
|= git_config_set_in_file_gently(opts_file
,
3489 "options.strategy", opts
->strategy
);
3491 res
|= git_config_set_in_file_gently(opts_file
,
3492 "options.gpg-sign", opts
->gpg_sign
);
3493 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3494 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3495 "options.strategy-option",
3496 opts
->xopts
.v
[i
], "^$", 0);
3497 if (opts
->allow_rerere_auto
)
3498 res
|= git_config_set_in_file_gently(opts_file
,
3499 "options.allow-rerere-auto",
3500 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3503 if (opts
->explicit_cleanup
)
3504 res
|= git_config_set_in_file_gently(opts_file
,
3505 "options.default-msg-cleanup",
3506 describe_cleanup_mode(opts
->default_msg_cleanup
));
3510 static int make_patch(struct repository
*r
,
3511 struct commit
*commit
,
3512 struct replay_opts
*opts
)
3514 struct rev_info log_tree_opt
;
3515 const char *subject
;
3516 char hex
[GIT_MAX_HEXSZ
+ 1];
3519 if (!is_rebase_i(opts
))
3520 BUG("make_patch should only be called when rebasing");
3522 oid_to_hex_r(hex
, &commit
->object
.oid
);
3523 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3525 res
|= write_rebase_head(&commit
->object
.oid
);
3527 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3528 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3529 log_tree_opt
.abbrev
= 0;
3530 log_tree_opt
.diff
= 1;
3531 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3532 log_tree_opt
.disable_stdin
= 1;
3533 log_tree_opt
.no_commit_id
= 1;
3534 log_tree_opt
.diffopt
.file
= fopen(rebase_path_patch(), "w");
3535 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3536 if (!log_tree_opt
.diffopt
.file
)
3537 res
|= error_errno(_("could not open '%s'"),
3538 rebase_path_patch());
3540 res
|= log_tree_commit(&log_tree_opt
, commit
);
3541 fclose(log_tree_opt
.diffopt
.file
);
3544 if (!file_exists(rebase_path_message())) {
3545 const char *encoding
= get_commit_output_encoding();
3546 const char *commit_buffer
= repo_logmsg_reencode(r
,
3549 find_commit_subject(commit_buffer
, &subject
);
3550 res
|= write_message(subject
, strlen(subject
), rebase_path_message(), 1);
3551 repo_unuse_commit_buffer(r
, commit
,
3554 release_revisions(&log_tree_opt
);
3559 static int intend_to_amend(void)
3561 struct object_id head
;
3564 if (repo_get_oid(the_repository
, "HEAD", &head
))
3565 return error(_("cannot read HEAD"));
3567 p
= oid_to_hex(&head
);
3568 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3571 static int error_with_patch(struct repository
*r
,
3572 struct commit
*commit
,
3573 const char *subject
, int subject_len
,
3574 struct replay_opts
*opts
,
3575 int exit_code
, int to_amend
)
3578 if (make_patch(r
, commit
, opts
))
3580 } else if (copy_file(rebase_path_message(),
3581 git_path_merge_msg(r
), 0666))
3582 return error(_("unable to copy '%s' to '%s'"),
3583 git_path_merge_msg(r
), rebase_path_message());
3586 if (intend_to_amend())
3590 _("You can amend the commit now, with\n"
3592 " git commit --amend %s\n"
3594 "Once you are satisfied with your changes, run\n"
3596 " git rebase --continue\n"),
3597 gpg_sign_opt_quoted(opts
));
3598 } else if (exit_code
) {
3600 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3601 short_commit_name(commit
), subject_len
, subject
);
3604 * We don't have the hash of the parent so
3605 * just print the line from the todo file.
3607 fprintf_ln(stderr
, _("Could not merge %.*s"),
3608 subject_len
, subject
);
3614 static int error_failed_squash(struct repository
*r
,
3615 struct commit
*commit
,
3616 struct replay_opts
*opts
,
3618 const char *subject
)
3620 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3621 return error(_("could not copy '%s' to '%s'"),
3622 rebase_path_squash_msg(), rebase_path_message());
3623 unlink(git_path_merge_msg(r
));
3624 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3625 return error(_("could not copy '%s' to '%s'"),
3626 rebase_path_message(),
3627 git_path_merge_msg(r
));
3628 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3631 static int do_exec(struct repository
*r
, const char *command_line
)
3633 struct child_process cmd
= CHILD_PROCESS_INIT
;
3636 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3638 strvec_push(&cmd
.args
, command_line
);
3639 status
= run_command(&cmd
);
3641 /* force re-reading of the cache */
3642 discard_index(r
->index
);
3643 if (repo_read_index(r
) < 0)
3644 return error(_("could not read index"));
3646 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3649 warning(_("execution failed: %s\n%s"
3650 "You can fix the problem, and then run\n"
3652 " git rebase --continue\n"
3655 dirty
? _("and made changes to the index and/or the "
3656 "working tree.\n") : "");
3658 /* command not found */
3661 warning(_("execution succeeded: %s\nbut "
3662 "left changes to the index and/or the working tree.\n"
3663 "Commit or stash your changes, and then run\n"
3665 " git rebase --continue\n"
3666 "\n"), command_line
);
3673 __attribute__((format (printf
, 2, 3)))
3674 static int safe_append(const char *filename
, const char *fmt
, ...)
3677 struct lock_file lock
= LOCK_INIT
;
3678 int fd
= hold_lock_file_for_update(&lock
, filename
,
3679 LOCK_REPORT_ON_ERROR
);
3680 struct strbuf buf
= STRBUF_INIT
;
3685 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3686 error_errno(_("could not read '%s'"), filename
);
3687 rollback_lock_file(&lock
);
3690 strbuf_complete(&buf
, '\n');
3692 strbuf_vaddf(&buf
, fmt
, ap
);
3695 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3696 error_errno(_("could not write to '%s'"), filename
);
3697 strbuf_release(&buf
);
3698 rollback_lock_file(&lock
);
3701 if (commit_lock_file(&lock
) < 0) {
3702 strbuf_release(&buf
);
3703 return error(_("failed to finalize '%s'"), filename
);
3706 strbuf_release(&buf
);
3710 static int do_label(struct repository
*r
, const char *name
, int len
)
3712 struct ref_store
*refs
= get_main_ref_store(r
);
3713 struct ref_transaction
*transaction
;
3714 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3715 struct strbuf msg
= STRBUF_INIT
;
3717 struct object_id head_oid
;
3719 if (len
== 1 && *name
== '#')
3720 return error(_("illegal label name: '%.*s'"), len
, name
);
3722 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3723 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3725 transaction
= ref_store_transaction_begin(refs
, &err
);
3727 error("%s", err
.buf
);
3729 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3730 error(_("could not read HEAD"));
3732 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3733 NULL
, 0, msg
.buf
, &err
) < 0 ||
3734 ref_transaction_commit(transaction
, &err
)) {
3735 error("%s", err
.buf
);
3738 ref_transaction_free(transaction
);
3739 strbuf_release(&err
);
3740 strbuf_release(&msg
);
3743 ret
= safe_append(rebase_path_refs_to_delete(),
3744 "%s\n", ref_name
.buf
);
3745 strbuf_release(&ref_name
);
3750 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3752 if (!opts
->reflog_action
) {
3753 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3754 opts
->reflog_action
=
3755 xstrdup(opts
->reflog_action
? opts
->reflog_action
3756 : action_name(opts
));
3759 return opts
->reflog_action
;
3762 __attribute__((format (printf
, 3, 4)))
3763 static const char *reflog_message(struct replay_opts
*opts
,
3764 const char *sub_action
, const char *fmt
, ...)
3767 static struct strbuf buf
= STRBUF_INIT
;
3771 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3773 strbuf_addf(&buf
, " (%s)", sub_action
);
3775 strbuf_addstr(&buf
, ": ");
3776 strbuf_vaddf(&buf
, fmt
, ap
);
3783 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3784 int len
, struct strbuf
*buf
)
3786 struct commit
*commit
;
3787 struct object_id oid
;
3790 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3791 if (!read_ref(buf
->buf
, &oid
)) {
3792 commit
= lookup_commit_object(r
, &oid
);
3794 /* fall back to non-rewritten ref or commit */
3795 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3796 commit
= lookup_commit_reference_by_name(buf
->buf
);
3800 error(_("could not resolve '%s'"), buf
->buf
);
3805 static int do_reset(struct repository
*r
,
3806 const char *name
, int len
,
3807 struct replay_opts
*opts
)
3809 struct strbuf ref_name
= STRBUF_INIT
;
3810 struct object_id oid
;
3811 struct lock_file lock
= LOCK_INIT
;
3812 struct tree_desc desc
= { 0 };
3814 struct unpack_trees_options unpack_tree_opts
= { 0 };
3817 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3820 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3821 if (!opts
->have_squash_onto
) {
3823 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3824 NULL
, &opts
->squash_onto
,
3826 return error(_("writing fake root commit"));
3827 opts
->have_squash_onto
= 1;
3828 hex
= oid_to_hex(&opts
->squash_onto
);
3829 if (write_message(hex
, strlen(hex
),
3830 rebase_path_squash_onto(), 0))
3831 return error(_("writing squash-onto"));
3833 oidcpy(&oid
, &opts
->squash_onto
);
3836 struct commit
*commit
;
3838 /* Determine the length of the label */
3839 for (i
= 0; i
< len
; i
++)
3840 if (isspace(name
[i
]))
3844 commit
= lookup_label(r
, name
, len
, &ref_name
);
3849 oid
= commit
->object
.oid
;
3852 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3853 unpack_tree_opts
.head_idx
= 1;
3854 unpack_tree_opts
.src_index
= r
->index
;
3855 unpack_tree_opts
.dst_index
= r
->index
;
3856 unpack_tree_opts
.fn
= oneway_merge
;
3857 unpack_tree_opts
.merge
= 1;
3858 unpack_tree_opts
.update
= 1;
3859 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3860 unpack_tree_opts
.skip_cache_tree_update
= 1;
3861 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3863 if (repo_read_index_unmerged(r
)) {
3864 ret
= error_resolve_conflict(action_name(opts
));
3868 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3869 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3873 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3878 tree
= parse_tree_indirect(&oid
);
3879 prime_cache_tree(r
, r
->index
, tree
);
3881 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3882 ret
= error(_("could not write index"));
3885 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3886 len
, name
), "HEAD", &oid
,
3887 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3889 free((void *)desc
.buffer
);
3891 rollback_lock_file(&lock
);
3892 strbuf_release(&ref_name
);
3893 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3897 static int do_merge(struct repository
*r
,
3898 struct commit
*commit
,
3899 const char *arg
, int arg_len
,
3900 int flags
, int *check_todo
, struct replay_opts
*opts
)
3902 int run_commit_flags
= 0;
3903 struct strbuf ref_name
= STRBUF_INIT
;
3904 struct commit
*head_commit
, *merge_commit
, *i
;
3905 struct commit_list
*bases
, *j
;
3906 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3907 const char *strategy
= !opts
->xopts
.nr
&&
3909 !strcmp(opts
->strategy
, "recursive") ||
3910 !strcmp(opts
->strategy
, "ort")) ?
3911 NULL
: opts
->strategy
;
3912 struct merge_options o
;
3913 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3914 static struct lock_file lock
;
3917 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3922 head_commit
= lookup_commit_reference_by_name("HEAD");
3924 ret
= error(_("cannot merge without a current revision"));
3929 * For octopus merges, the arg starts with the list of revisions to be
3930 * merged. The list is optionally followed by '#' and the oneline.
3932 merge_arg_len
= oneline_offset
= arg_len
;
3933 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3936 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3937 p
+= 1 + strspn(p
+ 1, " \t\n");
3938 oneline_offset
= p
- arg
;
3941 k
= strcspn(p
, " \t\n");
3944 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3945 if (!merge_commit
) {
3946 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3949 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3951 merge_arg_len
= p
- arg
;
3955 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3959 if (opts
->have_squash_onto
&&
3960 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3962 * When the user tells us to "merge" something into a
3963 * "[new root]", let's simply fast-forward to the merge head.
3965 rollback_lock_file(&lock
);
3967 ret
= error(_("octopus merge cannot be executed on "
3968 "top of a [new root]"));
3970 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3971 &head_commit
->object
.oid
, 0,
3977 * If HEAD is not identical to the first parent of the original merge
3978 * commit, we cannot fast-forward.
3980 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3981 oideq(&commit
->parents
->item
->object
.oid
,
3982 &head_commit
->object
.oid
);
3985 * If any merge head is different from the original one, we cannot
3988 if (can_fast_forward
) {
3989 struct commit_list
*p
= commit
->parents
->next
;
3991 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
3992 if (!oideq(&j
->item
->object
.oid
,
3993 &p
->item
->object
.oid
)) {
3994 can_fast_forward
= 0;
3998 * If the number of merge heads differs from the original merge
3999 * commit, we cannot fast-forward.
4002 can_fast_forward
= 0;
4005 if (can_fast_forward
) {
4006 rollback_lock_file(&lock
);
4007 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4008 &head_commit
->object
.oid
, 0, opts
);
4009 if (flags
& TODO_EDIT_MERGE_MSG
)
4010 goto fast_forward_edit
;
4016 const char *encoding
= get_commit_output_encoding();
4017 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4023 ret
= error(_("could not get commit message of '%s'"),
4024 oid_to_hex(&commit
->object
.oid
));
4027 write_author_script(message
);
4028 find_commit_subject(message
, &body
);
4030 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4031 repo_unuse_commit_buffer(r
, commit
, message
);
4033 error_errno(_("could not write '%s'"),
4034 git_path_merge_msg(r
));
4038 struct strbuf buf
= STRBUF_INIT
;
4041 strbuf_addf(&buf
, "author %s", git_author_info(0));
4042 write_author_script(buf
.buf
);
4045 if (oneline_offset
< arg_len
) {
4046 p
= arg
+ oneline_offset
;
4047 len
= arg_len
- oneline_offset
;
4049 strbuf_addf(&buf
, "Merge %s '%.*s'",
4050 to_merge
->next
? "branches" : "branch",
4051 merge_arg_len
, arg
);
4056 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4057 strbuf_release(&buf
);
4059 error_errno(_("could not write '%s'"),
4060 git_path_merge_msg(r
));
4065 if (strategy
|| to_merge
->next
) {
4067 struct child_process cmd
= CHILD_PROCESS_INIT
;
4069 if (read_env_script(&cmd
.env
)) {
4070 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4072 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4076 if (opts
->committer_date_is_author_date
)
4077 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4080 author_date_from_env(&cmd
.env
));
4081 if (opts
->ignore_date
)
4082 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4085 strvec_push(&cmd
.args
, "merge");
4086 strvec_push(&cmd
.args
, "-s");
4088 strvec_push(&cmd
.args
, "octopus");
4090 strvec_push(&cmd
.args
, strategy
);
4091 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4092 strvec_pushf(&cmd
.args
,
4093 "-X%s", opts
->xopts
.v
[k
]);
4095 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4096 strvec_push(&cmd
.args
, "--no-edit");
4098 strvec_push(&cmd
.args
, "--edit");
4099 strvec_push(&cmd
.args
, "--no-ff");
4100 strvec_push(&cmd
.args
, "--no-log");
4101 strvec_push(&cmd
.args
, "--no-stat");
4102 strvec_push(&cmd
.args
, "-F");
4103 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4105 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4107 strvec_push(&cmd
.args
, "--no-gpg-sign");
4109 /* Add the tips to be merged */
4110 for (j
= to_merge
; j
; j
= j
->next
)
4111 strvec_push(&cmd
.args
,
4112 oid_to_hex(&j
->item
->object
.oid
));
4114 strbuf_release(&ref_name
);
4115 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4117 rollback_lock_file(&lock
);
4119 ret
= run_command(&cmd
);
4121 /* force re-reading of the cache */
4123 discard_index(r
->index
);
4124 if (repo_read_index(r
) < 0)
4125 ret
= error(_("could not read index"));
4130 merge_commit
= to_merge
->item
;
4131 bases
= repo_get_merge_bases(r
, head_commit
, merge_commit
);
4132 if (bases
&& oideq(&merge_commit
->object
.oid
,
4133 &bases
->item
->object
.oid
)) {
4135 /* skip merging an ancestor of HEAD */
4139 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4140 git_path_merge_head(r
), 0);
4141 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4143 bases
= reverse_commit_list(bases
);
4146 init_merge_options(&o
, r
);
4148 o
.branch2
= ref_name
.buf
;
4149 o
.buffer_output
= 2;
4151 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4153 * TODO: Should use merge_incore_recursive() and
4154 * merge_switch_to_result(), skipping the call to
4155 * merge_switch_to_result() when we don't actually need to
4156 * update the index and working copy immediately.
4158 ret
= merge_ort_recursive(&o
,
4159 head_commit
, merge_commit
, bases
,
4162 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4166 fputs(o
.obuf
.buf
, stdout
);
4167 strbuf_release(&o
.obuf
);
4169 error(_("could not even attempt to merge '%.*s'"),
4170 merge_arg_len
, arg
);
4171 unlink(git_path_merge_msg(r
));
4175 * The return value of merge_recursive() is 1 on clean, and 0 on
4178 * Let's reverse that, so that do_merge() returns 0 upon success and
4179 * 1 upon failed merge (keeping the return value -1 for the cases where
4180 * we will want to reschedule the `merge` command).
4184 if (r
->index
->cache_changed
&&
4185 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4186 ret
= error(_("merge: Unable to write new index file"));
4190 rollback_lock_file(&lock
);
4192 repo_rerere(r
, opts
->allow_rerere_auto
);
4195 * In case of problems, we now want to return a positive
4196 * value (a negative one would indicate that the `merge`
4197 * command needs to be rescheduled).
4199 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4202 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4205 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4206 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4211 strbuf_release(&ref_name
);
4212 rollback_lock_file(&lock
);
4213 free_commit_list(to_merge
);
4217 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4220 struct lock_file lock
= LOCK_INIT
;
4222 struct string_list_item
*item
;
4225 path
= rebase_path_update_refs(the_repository
->gitdir
);
4227 if (!refs_to_oids
->nr
) {
4228 if (unlink(path
) && errno
!= ENOENT
)
4229 result
= error_errno(_("could not unlink: %s"), path
);
4233 if (safe_create_leading_directories(path
)) {
4234 result
= error(_("unable to create leading directories of %s"),
4239 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4240 result
= error(_("another 'rebase' process appears to be running; "
4241 "'%s.lock' already exists"),
4246 fp
= fdopen_lock_file(&lock
, "w");
4248 result
= error_errno(_("could not open '%s' for writing"), path
);
4249 rollback_lock_file(&lock
);
4253 for_each_string_list_item(item
, refs_to_oids
) {
4254 struct update_ref_record
*rec
= item
->util
;
4255 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4256 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4259 result
= commit_lock_file(&lock
);
4267 * Parse the update-refs file for the current rebase, then remove the
4268 * refs that do not appear in the todo_list (and have not had updated
4269 * values stored) and add refs that are in the todo_list but not
4270 * represented in the update-refs file.
4272 * If there are changes to the update-refs list, then write the new state
4275 void todo_list_filter_update_refs(struct repository
*r
,
4276 struct todo_list
*todo_list
)
4280 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4282 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4285 * For each item in the update_refs list, if it has no updated
4286 * value and does not appear in the todo_list, then remove it
4287 * from the update_refs list.
4289 for (i
= 0; i
< update_refs
.nr
; i
++) {
4292 const char *ref
= update_refs
.items
[i
].string
;
4293 size_t reflen
= strlen(ref
);
4294 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4296 /* OID already stored as updated. */
4297 if (!is_null_oid(&rec
->after
))
4300 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4301 struct todo_item
*item
= &todo_list
->items
[j
];
4302 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4304 if (item
->command
!= TODO_UPDATE_REF
)
4307 if (item
->arg_len
!= reflen
||
4308 strncmp(arg
, ref
, reflen
))
4315 free(update_refs
.items
[i
].string
);
4316 free(update_refs
.items
[i
].util
);
4319 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4327 * For each todo_item, check if its ref is in the update_refs list.
4328 * If not, then add it as an un-updated ref.
4330 for (i
= 0; i
< todo_list
->nr
; i
++) {
4331 struct todo_item
*item
= &todo_list
->items
[i
];
4332 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4335 if (item
->command
!= TODO_UPDATE_REF
)
4338 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4339 const char *ref
= update_refs
.items
[j
].string
;
4341 found
= strlen(ref
) == item
->arg_len
&&
4342 !strncmp(ref
, arg
, item
->arg_len
);
4346 struct string_list_item
*inserted
;
4347 struct strbuf argref
= STRBUF_INIT
;
4349 strbuf_add(&argref
, arg
, item
->arg_len
);
4350 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4351 inserted
->util
= init_update_ref_record(argref
.buf
);
4352 strbuf_release(&argref
);
4358 write_update_refs_state(&update_refs
);
4359 string_list_clear(&update_refs
, 1);
4362 static int do_update_ref(struct repository
*r
, const char *refname
)
4364 struct string_list_item
*item
;
4365 struct string_list list
= STRING_LIST_INIT_DUP
;
4367 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4370 for_each_string_list_item(item
, &list
) {
4371 if (!strcmp(item
->string
, refname
)) {
4372 struct update_ref_record
*rec
= item
->util
;
4373 if (read_ref("HEAD", &rec
->after
))
4379 write_update_refs_state(&list
);
4380 string_list_clear(&list
, 1);
4384 static int do_update_refs(struct repository
*r
, int quiet
)
4387 struct string_list_item
*item
;
4388 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4389 struct ref_store
*refs
= get_main_ref_store(r
);
4390 struct strbuf update_msg
= STRBUF_INIT
;
4391 struct strbuf error_msg
= STRBUF_INIT
;
4393 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4396 for_each_string_list_item(item
, &refs_to_oids
) {
4397 struct update_ref_record
*rec
= item
->util
;
4400 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4402 &rec
->after
, &rec
->before
,
4403 0, UPDATE_REFS_MSG_ON_ERR
);
4410 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4412 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4416 (update_msg
.len
|| error_msg
.len
)) {
4418 _("Updated the following refs with %s:\n%s"),
4424 _("Failed to update the following refs with %s:\n%s"),
4429 string_list_clear(&refs_to_oids
, 1);
4430 strbuf_release(&update_msg
);
4431 strbuf_release(&error_msg
);
4435 static int is_final_fixup(struct todo_list
*todo_list
)
4437 int i
= todo_list
->current
;
4439 if (!is_fixup(todo_list
->items
[i
].command
))
4442 while (++i
< todo_list
->nr
)
4443 if (is_fixup(todo_list
->items
[i
].command
))
4445 else if (!is_noop(todo_list
->items
[i
].command
))
4450 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4454 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4455 if (!is_noop(todo_list
->items
[i
].command
))
4456 return todo_list
->items
[i
].command
;
4461 void create_autostash(struct repository
*r
, const char *path
)
4463 struct strbuf buf
= STRBUF_INIT
;
4464 struct lock_file lock_file
= LOCK_INIT
;
4467 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4468 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4470 repo_update_index_if_able(r
, &lock_file
);
4471 rollback_lock_file(&lock_file
);
4473 if (has_unstaged_changes(r
, 1) ||
4474 has_uncommitted_changes(r
, 1)) {
4475 struct child_process stash
= CHILD_PROCESS_INIT
;
4476 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4477 struct object_id oid
;
4479 strvec_pushl(&stash
.args
,
4480 "stash", "create", "autostash", NULL
);
4484 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4485 die(_("Cannot autostash"));
4486 strbuf_trim_trailing_newline(&buf
);
4487 if (repo_get_oid(r
, buf
.buf
, &oid
))
4488 die(_("Unexpected stash response: '%s'"),
4491 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4493 if (safe_create_leading_directories_const(path
))
4494 die(_("Could not create directory for '%s'"),
4496 write_file(path
, "%s", oid_to_hex(&oid
));
4497 printf(_("Created autostash: %s\n"), buf
.buf
);
4498 if (reset_head(r
, &ropts
) < 0)
4499 die(_("could not reset --hard"));
4500 discard_index(r
->index
);
4501 if (repo_read_index(r
) < 0)
4502 die(_("could not read index"));
4504 strbuf_release(&buf
);
4507 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4509 struct child_process child
= CHILD_PROCESS_INIT
;
4512 if (attempt_apply
) {
4514 child
.no_stdout
= 1;
4515 child
.no_stderr
= 1;
4516 strvec_push(&child
.args
, "stash");
4517 strvec_push(&child
.args
, "apply");
4518 strvec_push(&child
.args
, stash_oid
);
4519 ret
= run_command(&child
);
4522 if (attempt_apply
&& !ret
)
4523 fprintf(stderr
, _("Applied autostash.\n"));
4525 struct child_process store
= CHILD_PROCESS_INIT
;
4528 strvec_push(&store
.args
, "stash");
4529 strvec_push(&store
.args
, "store");
4530 strvec_push(&store
.args
, "-m");
4531 strvec_push(&store
.args
, "autostash");
4532 strvec_push(&store
.args
, "-q");
4533 strvec_push(&store
.args
, stash_oid
);
4534 if (run_command(&store
))
4535 ret
= error(_("cannot store %s"), stash_oid
);
4539 "Your changes are safe in the stash.\n"
4540 "You can run \"git stash pop\" or"
4541 " \"git stash drop\" at any time.\n"),
4543 _("Applying autostash resulted in conflicts.") :
4544 _("Autostash exists; creating a new stash entry."));
4550 static int apply_save_autostash(const char *path
, int attempt_apply
)
4552 struct strbuf stash_oid
= STRBUF_INIT
;
4555 if (!read_oneliner(&stash_oid
, path
,
4556 READ_ONELINER_SKIP_IF_EMPTY
)) {
4557 strbuf_release(&stash_oid
);
4560 strbuf_trim(&stash_oid
);
4562 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4565 strbuf_release(&stash_oid
);
4569 int save_autostash(const char *path
)
4571 return apply_save_autostash(path
, 0);
4574 int apply_autostash(const char *path
)
4576 return apply_save_autostash(path
, 1);
4579 int apply_autostash_oid(const char *stash_oid
)
4581 return apply_save_autostash_oid(stash_oid
, 1);
4584 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4585 const char *onto_name
, const struct object_id
*onto
,
4586 const struct object_id
*orig_head
)
4588 struct reset_head_opts ropts
= {
4590 .orig_head
= orig_head
,
4591 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4592 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4593 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4595 .default_reflog_action
= sequencer_reflog_action(opts
)
4597 if (reset_head(r
, &ropts
)) {
4598 apply_autostash(rebase_path_autostash());
4599 sequencer_remove_state(opts
);
4600 return error(_("could not detach HEAD"));
4606 static int stopped_at_head(struct repository
*r
)
4608 struct object_id head
;
4609 struct commit
*commit
;
4610 struct commit_message message
;
4612 if (repo_get_oid(r
, "HEAD", &head
) ||
4613 !(commit
= lookup_commit(r
, &head
)) ||
4614 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4615 fprintf(stderr
, _("Stopped at HEAD\n"));
4617 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4618 free_message(commit
, &message
);
4624 static int reread_todo_if_changed(struct repository
*r
,
4625 struct todo_list
*todo_list
,
4626 struct replay_opts
*opts
)
4629 struct strbuf buf
= STRBUF_INIT
;
4631 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4633 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4634 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4635 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4636 /* Reread the todo file if it has changed. */
4637 todo_list_release(todo_list
);
4638 if (read_populate_todo(r
, todo_list
, opts
))
4639 return -1; /* message was printed */
4640 /* `current` will be incremented on return */
4641 todo_list
->current
= -1;
4643 strbuf_release(&buf
);
4648 static const char rescheduled_advice
[] =
4649 N_("Could not execute the todo command\n"
4653 "It has been rescheduled; To edit the command before continuing, please\n"
4654 "edit the todo list first:\n"
4656 " git rebase --edit-todo\n"
4657 " git rebase --continue\n");
4659 static int pick_one_commit(struct repository
*r
,
4660 struct todo_list
*todo_list
,
4661 struct replay_opts
*opts
,
4662 int *check_todo
, int* reschedule
)
4665 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4666 const char *arg
= todo_item_get_arg(todo_list
, item
);
4667 if (is_rebase_i(opts
))
4668 opts
->reflog_message
= reflog_message(
4669 opts
, command_to_string(item
->command
), NULL
);
4671 res
= do_pick_commit(r
, item
, opts
, is_final_fixup(todo_list
),
4673 if (is_rebase_i(opts
) && res
< 0) {
4678 if (item
->command
== TODO_EDIT
) {
4679 struct commit
*commit
= item
->commit
;
4683 fprintf(stderr
, _("Stopped at %s... %.*s\n"),
4684 short_commit_name(commit
), item
->arg_len
, arg
);
4686 return error_with_patch(r
, commit
,
4687 arg
, item
->arg_len
, opts
, res
, !res
);
4689 if (is_rebase_i(opts
) && !res
)
4690 record_in_rewritten(&item
->commit
->object
.oid
,
4691 peek_command(todo_list
, 1));
4692 if (res
&& is_fixup(item
->command
)) {
4695 return error_failed_squash(r
, item
->commit
, opts
,
4696 item
->arg_len
, arg
);
4697 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4699 struct object_id oid
;
4702 * If we are rewording and have either
4703 * fast-forwarded already, or are about to
4704 * create a new root commit, we want to amend,
4705 * otherwise we do not.
4707 if (item
->command
== TODO_REWORD
&&
4708 !repo_get_oid(r
, "HEAD", &oid
) &&
4709 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4710 (opts
->have_squash_onto
&&
4711 oideq(&opts
->squash_onto
, &oid
))))
4714 return res
| error_with_patch(r
, item
->commit
,
4715 arg
, item
->arg_len
, opts
,
4721 static int pick_commits(struct repository
*r
,
4722 struct todo_list
*todo_list
,
4723 struct replay_opts
*opts
)
4725 int res
= 0, reschedule
= 0;
4727 opts
->reflog_message
= sequencer_reflog_action(opts
);
4729 assert(!(opts
->signoff
|| opts
->no_commit
||
4730 opts
->record_origin
|| should_edit(opts
) ||
4731 opts
->committer_date_is_author_date
||
4732 opts
->ignore_date
));
4733 if (read_and_refresh_cache(r
, opts
))
4736 unlink(rebase_path_message());
4737 unlink(rebase_path_stopped_sha());
4738 unlink(rebase_path_amend());
4739 unlink(rebase_path_patch());
4741 while (todo_list
->current
< todo_list
->nr
) {
4742 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4743 const char *arg
= todo_item_get_arg(todo_list
, item
);
4746 if (save_todo(todo_list
, opts
, reschedule
))
4748 if (is_rebase_i(opts
)) {
4749 if (item
->command
!= TODO_COMMENT
) {
4750 FILE *f
= fopen(rebase_path_msgnum(), "w");
4752 todo_list
->done_nr
++;
4755 fprintf(f
, "%d\n", todo_list
->done_nr
);
4759 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4761 todo_list
->total_nr
,
4762 opts
->verbose
? "\n" : "\r");
4764 unlink(rebase_path_author_script());
4765 unlink(git_path_merge_head(r
));
4766 unlink(git_path_auto_merge(r
));
4767 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
4769 if (item
->command
== TODO_BREAK
) {
4772 return stopped_at_head(r
);
4775 if (item
->command
<= TODO_SQUASH
) {
4776 res
= pick_one_commit(r
, todo_list
, opts
, &check_todo
,
4778 if (!res
&& item
->command
== TODO_EDIT
)
4780 } else if (item
->command
== TODO_EXEC
) {
4781 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4782 int saved
= *end_of_arg
;
4787 res
= do_exec(r
, arg
);
4788 *end_of_arg
= saved
;
4791 if (opts
->reschedule_failed_exec
)
4795 } else if (item
->command
== TODO_LABEL
) {
4796 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4798 } else if (item
->command
== TODO_RESET
) {
4799 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4801 } else if (item
->command
== TODO_MERGE
) {
4802 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4803 item
->flags
, &check_todo
, opts
)) < 0)
4805 else if (item
->commit
)
4806 record_in_rewritten(&item
->commit
->object
.oid
,
4807 peek_command(todo_list
, 1));
4809 /* failed with merge conflicts */
4810 return error_with_patch(r
, item
->commit
,
4813 } else if (item
->command
== TODO_UPDATE_REF
) {
4814 struct strbuf ref
= STRBUF_INIT
;
4815 strbuf_add(&ref
, arg
, item
->arg_len
);
4816 if ((res
= do_update_ref(r
, ref
.buf
)))
4818 strbuf_release(&ref
);
4819 } else if (!is_noop(item
->command
))
4820 return error(_("unknown command %d"), item
->command
);
4823 advise(_(rescheduled_advice
),
4824 get_item_line_length(todo_list
,
4825 todo_list
->current
),
4826 get_item_line(todo_list
, todo_list
->current
));
4827 if (save_todo(todo_list
, opts
, reschedule
))
4830 write_rebase_head(&item
->commit
->object
.oid
);
4831 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4832 reread_todo_if_changed(r
, todo_list
, opts
)) {
4839 todo_list
->current
++;
4842 if (is_rebase_i(opts
)) {
4843 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4846 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4847 starts_with(head_ref
.buf
, "refs/")) {
4849 struct object_id head
, orig
;
4852 if (repo_get_oid(r
, "HEAD", &head
)) {
4853 res
= error(_("cannot read HEAD"));
4855 strbuf_release(&head_ref
);
4856 strbuf_release(&buf
);
4859 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4860 get_oid_hex(buf
.buf
, &orig
)) {
4861 res
= error(_("could not read orig-head"));
4862 goto cleanup_head_ref
;
4865 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4866 res
= error(_("could not read 'onto'"));
4867 goto cleanup_head_ref
;
4869 msg
= reflog_message(opts
, "finish", "%s onto %s",
4870 head_ref
.buf
, buf
.buf
);
4871 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4872 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4873 res
= error(_("could not update %s"),
4875 goto cleanup_head_ref
;
4877 msg
= reflog_message(opts
, "finish", "returning to %s",
4879 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4880 res
= error(_("could not update HEAD to %s"),
4882 goto cleanup_head_ref
;
4887 if (opts
->verbose
) {
4888 struct rev_info log_tree_opt
;
4889 struct object_id orig
, head
;
4891 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4892 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4893 log_tree_opt
.diff
= 1;
4894 log_tree_opt
.diffopt
.output_format
=
4895 DIFF_FORMAT_DIFFSTAT
;
4896 log_tree_opt
.disable_stdin
= 1;
4898 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4899 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4900 !repo_get_oid(r
, "HEAD", &head
)) {
4901 diff_tree_oid(&orig
, &head
, "",
4902 &log_tree_opt
.diffopt
);
4903 log_tree_diff_flush(&log_tree_opt
);
4905 release_revisions(&log_tree_opt
);
4907 flush_rewritten_pending();
4908 if (!stat(rebase_path_rewritten_list(), &st
) &&
4910 struct child_process child
= CHILD_PROCESS_INIT
;
4911 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
4913 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4915 strvec_push(&child
.args
, "notes");
4916 strvec_push(&child
.args
, "copy");
4917 strvec_push(&child
.args
, "--for-rewrite=rebase");
4918 /* we don't care if this copying failed */
4919 run_command(&child
);
4921 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
4922 strvec_push(&hook_opt
.args
, "rebase");
4923 run_hooks_opt("post-rewrite", &hook_opt
);
4925 apply_autostash(rebase_path_autostash());
4931 _("Successfully rebased and updated %s.\n"),
4935 strbuf_release(&buf
);
4936 strbuf_release(&head_ref
);
4938 if (do_update_refs(r
, opts
->quiet
))
4943 * Sequence of picks finished successfully; cleanup by
4944 * removing the .git/sequencer directory
4946 return sequencer_remove_state(opts
);
4949 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
4951 struct child_process cmd
= CHILD_PROCESS_INIT
;
4953 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
4954 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
4955 return error(_("no cherry-pick or revert in progress"));
4958 strvec_push(&cmd
.args
, "commit");
4961 * continue_single_pick() handles the case of recovering from a
4962 * conflict. should_edit() doesn't handle that case; for a conflict,
4963 * we want to edit if the user asked for it, or if they didn't specify
4964 * and stdin is a tty.
4966 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
4968 * Include --cleanup=strip as well because we don't want the
4969 * "# Conflicts:" messages.
4971 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
4973 return run_command(&cmd
);
4976 static int commit_staged_changes(struct repository
*r
,
4977 struct replay_opts
*opts
,
4978 struct todo_list
*todo_list
)
4980 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
4981 unsigned int final_fixup
= 0, is_clean
;
4983 if (has_unstaged_changes(r
, 1))
4984 return error(_("cannot rebase: You have unstaged changes."));
4986 is_clean
= !has_uncommitted_changes(r
, 0);
4988 if (!is_clean
&& !file_exists(rebase_path_message())) {
4989 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4991 return error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4993 if (file_exists(rebase_path_amend())) {
4994 struct strbuf rev
= STRBUF_INIT
;
4995 struct object_id head
, to_amend
;
4997 if (repo_get_oid(r
, "HEAD", &head
))
4998 return error(_("cannot amend non-existing commit"));
4999 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
5000 return error(_("invalid file: '%s'"), rebase_path_amend());
5001 if (get_oid_hex(rev
.buf
, &to_amend
))
5002 return error(_("invalid contents: '%s'"),
5003 rebase_path_amend());
5004 if (!is_clean
&& !oideq(&head
, &to_amend
))
5005 return error(_("\nYou have uncommitted changes in your "
5006 "working tree. Please, commit them\n"
5007 "first and then run 'git rebase "
5008 "--continue' again."));
5010 * When skipping a failed fixup/squash, we need to edit the
5011 * commit message, the current fixup list and count, and if it
5012 * was the last fixup/squash in the chain, we need to clean up
5013 * the commit message and if there was a squash, let the user
5016 if (!is_clean
|| !opts
->current_fixup_count
)
5017 ; /* this is not the final fixup */
5018 else if (!oideq(&head
, &to_amend
) ||
5019 !file_exists(rebase_path_stopped_sha())) {
5020 /* was a final fixup or squash done manually? */
5021 if (!is_fixup(peek_command(todo_list
, 0))) {
5022 unlink(rebase_path_fixup_msg());
5023 unlink(rebase_path_squash_msg());
5024 unlink(rebase_path_current_fixups());
5025 strbuf_reset(&opts
->current_fixups
);
5026 opts
->current_fixup_count
= 0;
5029 /* we are in a fixup/squash chain */
5030 const char *p
= opts
->current_fixups
.buf
;
5031 int len
= opts
->current_fixups
.len
;
5033 opts
->current_fixup_count
--;
5035 BUG("Incorrect current_fixups:\n%s", p
);
5036 while (len
&& p
[len
- 1] != '\n')
5038 strbuf_setlen(&opts
->current_fixups
, len
);
5039 if (write_message(p
, len
, rebase_path_current_fixups(),
5041 return error(_("could not write file: '%s'"),
5042 rebase_path_current_fixups());
5045 * If a fixup/squash in a fixup/squash chain failed, the
5046 * commit message is already correct, no need to commit
5049 * Only if it is the final command in the fixup/squash
5050 * chain, and only if the chain is longer than a single
5051 * fixup/squash command (which was just skipped), do we
5052 * actually need to re-commit with a cleaned up commit
5055 if (opts
->current_fixup_count
> 0 &&
5056 !is_fixup(peek_command(todo_list
, 0))) {
5059 * If there was not a single "squash" in the
5060 * chain, we only need to clean up the commit
5061 * message, no need to bother the user with
5062 * opening the commit message in the editor.
5064 if (!starts_with(p
, "squash ") &&
5065 !strstr(p
, "\nsquash "))
5066 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5067 } else if (is_fixup(peek_command(todo_list
, 0))) {
5069 * We need to update the squash message to skip
5070 * the latest commit message.
5073 struct commit
*commit
;
5075 const char *path
= rebase_path_squash_msg();
5076 const char *encoding
= get_commit_output_encoding();
5078 if (parse_head(r
, &commit
))
5079 return error(_("could not parse HEAD"));
5081 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5083 res
= error(_("could not parse commit %s"),
5084 oid_to_hex(&commit
->object
.oid
));
5085 goto unuse_commit_buffer
;
5087 find_commit_subject(p
, &msg
);
5088 if (write_message(msg
, strlen(msg
), path
, 0)) {
5089 res
= error(_("could not write file: "
5091 goto unuse_commit_buffer
;
5093 unuse_commit_buffer
:
5094 repo_unuse_commit_buffer(r
, commit
, p
);
5100 strbuf_release(&rev
);
5105 if (refs_ref_exists(get_main_ref_store(r
),
5106 "CHERRY_PICK_HEAD") &&
5107 refs_delete_ref(get_main_ref_store(r
), "",
5108 "CHERRY_PICK_HEAD", NULL
, 0))
5109 return error(_("could not remove CHERRY_PICK_HEAD"));
5110 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5111 return error_errno(_("could not remove '%s'"),
5112 git_path_merge_msg(r
));
5117 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5119 return error(_("could not commit staged changes."));
5120 unlink(rebase_path_amend());
5121 unlink(git_path_merge_head(r
));
5122 unlink(git_path_auto_merge(r
));
5124 unlink(rebase_path_fixup_msg());
5125 unlink(rebase_path_squash_msg());
5127 if (opts
->current_fixup_count
> 0) {
5129 * Whether final fixup or not, we just cleaned up the commit
5132 unlink(rebase_path_current_fixups());
5133 strbuf_reset(&opts
->current_fixups
);
5134 opts
->current_fixup_count
= 0;
5139 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5141 struct todo_list todo_list
= TODO_LIST_INIT
;
5144 if (read_and_refresh_cache(r
, opts
))
5147 if (read_populate_opts(opts
))
5149 if (is_rebase_i(opts
)) {
5150 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5151 goto release_todo_list
;
5153 if (file_exists(rebase_path_dropped())) {
5154 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5155 goto release_todo_list
;
5157 unlink(rebase_path_dropped());
5160 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5161 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5163 goto release_todo_list
;
5165 } else if (!file_exists(get_todo_path(opts
)))
5166 return continue_single_pick(r
, opts
);
5167 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5168 goto release_todo_list
;
5170 if (!is_rebase_i(opts
)) {
5171 /* Verify that the conflict has been resolved */
5172 if (refs_ref_exists(get_main_ref_store(r
),
5173 "CHERRY_PICK_HEAD") ||
5174 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5175 res
= continue_single_pick(r
, opts
);
5177 goto release_todo_list
;
5179 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5180 res
= error_dirty_index(r
, opts
);
5181 goto release_todo_list
;
5183 todo_list
.current
++;
5184 } else if (file_exists(rebase_path_stopped_sha())) {
5185 struct strbuf buf
= STRBUF_INIT
;
5186 struct object_id oid
;
5188 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5189 READ_ONELINER_SKIP_IF_EMPTY
) &&
5190 !get_oid_hex(buf
.buf
, &oid
))
5191 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5192 strbuf_release(&buf
);
5195 res
= pick_commits(r
, &todo_list
, opts
);
5197 todo_list_release(&todo_list
);
5201 static int single_pick(struct repository
*r
,
5202 struct commit
*cmit
,
5203 struct replay_opts
*opts
)
5206 struct todo_item item
;
5208 item
.command
= opts
->action
== REPLAY_PICK
?
5209 TODO_PICK
: TODO_REVERT
;
5212 opts
->reflog_message
= sequencer_reflog_action(opts
);
5213 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5216 int sequencer_pick_revisions(struct repository
*r
,
5217 struct replay_opts
*opts
)
5219 struct todo_list todo_list
= TODO_LIST_INIT
;
5220 struct object_id oid
;
5224 if (read_and_refresh_cache(r
, opts
))
5227 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5228 struct object_id oid
;
5229 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5231 /* This happens when using --stdin. */
5235 if (!repo_get_oid(r
, name
, &oid
)) {
5236 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5237 enum object_type type
= oid_object_info(r
,
5240 return error(_("%s: can't cherry-pick a %s"),
5241 name
, type_name(type
));
5244 return error(_("%s: bad revision"), name
);
5248 * If we were called as "git cherry-pick <commit>", just
5249 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5250 * REVERT_HEAD, and don't touch the sequencer state.
5251 * This means it is possible to cherry-pick in the middle
5252 * of a cherry-pick sequence.
5254 if (opts
->revs
->cmdline
.nr
== 1 &&
5255 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5256 opts
->revs
->no_walk
&&
5257 !opts
->revs
->cmdline
.rev
->flags
) {
5258 struct commit
*cmit
;
5259 if (prepare_revision_walk(opts
->revs
))
5260 return error(_("revision walk setup failed"));
5261 cmit
= get_revision(opts
->revs
);
5263 return error(_("empty commit set passed"));
5264 if (get_revision(opts
->revs
))
5265 BUG("unexpected extra commit from walk");
5266 return single_pick(r
, cmit
, opts
);
5270 * Start a new cherry-pick/ revert sequence; but
5271 * first, make sure that an existing one isn't in
5275 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5276 create_seq_dir(r
) < 0)
5278 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5279 return error(_("can't revert as initial commit"));
5280 if (save_head(oid_to_hex(&oid
)))
5282 if (save_opts(opts
))
5284 update_abort_safety_file();
5285 res
= pick_commits(r
, &todo_list
, opts
);
5286 todo_list_release(&todo_list
);
5290 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5292 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5293 struct strbuf sob
= STRBUF_INIT
;
5296 strbuf_addstr(&sob
, sign_off_header
);
5297 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5298 strbuf_addch(&sob
, '\n');
5301 strbuf_complete_line(msgbuf
);
5304 * If the whole message buffer is equal to the sob, pretend that we
5305 * found a conforming footer with a matching sob
5307 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5308 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5311 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5314 const char *append_newlines
= NULL
;
5315 size_t len
= msgbuf
->len
- ignore_footer
;
5319 * The buffer is completely empty. Leave foom for
5320 * the title and body to be filled in by the user.
5322 append_newlines
= "\n\n";
5323 } else if (len
== 1) {
5325 * Buffer contains a single newline. Add another
5326 * so that we leave room for the title and body.
5328 append_newlines
= "\n";
5329 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5331 * Buffer ends with a single newline. Add another
5332 * so that there is an empty line between the message
5335 append_newlines
= "\n";
5336 } /* else, the buffer already ends with two newlines. */
5338 if (append_newlines
)
5339 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5340 append_newlines
, strlen(append_newlines
));
5343 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5344 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5347 strbuf_release(&sob
);
5350 struct labels_entry
{
5351 struct hashmap_entry entry
;
5352 char label
[FLEX_ARRAY
];
5355 static int labels_cmp(const void *fndata UNUSED
,
5356 const struct hashmap_entry
*eptr
,
5357 const struct hashmap_entry
*entry_or_key
, const void *key
)
5359 const struct labels_entry
*a
, *b
;
5361 a
= container_of(eptr
, const struct labels_entry
, entry
);
5362 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5364 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5367 struct string_entry
{
5368 struct oidmap_entry entry
;
5369 char string
[FLEX_ARRAY
];
5372 struct label_state
{
5373 struct oidmap commit2label
;
5374 struct hashmap labels
;
5376 int max_label_length
;
5379 static const char *label_oid(struct object_id
*oid
, const char *label
,
5380 struct label_state
*state
)
5382 struct labels_entry
*labels_entry
;
5383 struct string_entry
*string_entry
;
5384 struct object_id dummy
;
5387 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5389 return string_entry
->string
;
5392 * For "uninteresting" commits, i.e. commits that are not to be
5393 * rebased, and which can therefore not be labeled, we use a unique
5394 * abbreviation of the commit name. This is slightly more complicated
5395 * than calling repo_find_unique_abbrev() because we also need to make
5396 * sure that the abbreviation does not conflict with any other
5399 * We disallow "interesting" commits to be labeled by a string that
5400 * is a valid full-length hash, to ensure that we always can find an
5401 * abbreviation for any uninteresting commit's names that does not
5402 * clash with any other label.
5404 strbuf_reset(&state
->buf
);
5408 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5409 label
= p
= state
->buf
.buf
;
5411 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5415 * We may need to extend the abbreviated hash so that there is
5416 * no conflicting label.
5418 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5419 size_t i
= strlen(p
) + 1;
5421 oid_to_hex_r(p
, oid
);
5422 for (; i
< the_hash_algo
->hexsz
; i
++) {
5425 if (!hashmap_get_from_hash(&state
->labels
,
5432 struct strbuf
*buf
= &state
->buf
;
5433 int label_is_utf8
= 1; /* start with this assumption */
5434 size_t max_len
= buf
->len
+ state
->max_label_length
;
5437 * Sanitize labels by replacing non-alpha-numeric characters
5438 * (including white-space ones) by dashes, as they might be
5439 * illegal in file names (and hence in ref names).
5441 * Note that we retain non-ASCII UTF-8 characters (identified
5442 * via the most significant bit). They should be all acceptable
5445 * As we will use the labels as names of (loose) refs, it is
5446 * vital that the name not be longer than the maximum component
5447 * size of the file system (`NAME_MAX`). We are careful to
5448 * truncate the label accordingly, allowing for the `.lock`
5449 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5450 * truncating in the middle of a character).
5452 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5453 if (isalnum(*label
) ||
5454 (!label_is_utf8
&& (*label
& 0x80)))
5455 strbuf_addch(buf
, *label
);
5456 else if (*label
& 0x80) {
5457 const char *p
= label
;
5459 utf8_width(&p
, NULL
);
5461 if (buf
->len
+ (p
- label
) > max_len
)
5463 strbuf_add(buf
, label
, p
- label
);
5467 strbuf_addch(buf
, *label
);
5469 /* avoid leading dash and double-dashes */
5470 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5471 strbuf_addch(buf
, '-');
5473 strbuf_addstr(buf
, "rev-");
5474 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5478 if ((buf
->len
== the_hash_algo
->hexsz
&&
5479 !get_oid_hex(label
, &dummy
)) ||
5480 (buf
->len
== 1 && *label
== '#') ||
5481 hashmap_get_from_hash(&state
->labels
,
5482 strihash(label
), label
)) {
5484 * If the label already exists, or if the label is a
5485 * valid full OID, or the label is a '#' (which we use
5486 * as a separator between merge heads and oneline), we
5487 * append a dash and a number to make it unique.
5489 size_t len
= buf
->len
;
5491 for (i
= 2; ; i
++) {
5492 strbuf_setlen(buf
, len
);
5493 strbuf_addf(buf
, "-%d", i
);
5494 if (!hashmap_get_from_hash(&state
->labels
,
5504 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5505 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5506 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5508 FLEX_ALLOC_STR(string_entry
, string
, label
);
5509 oidcpy(&string_entry
->entry
.oid
, oid
);
5510 oidmap_put(&state
->commit2label
, string_entry
);
5512 return string_entry
->string
;
5515 static int make_script_with_merges(struct pretty_print_context
*pp
,
5516 struct rev_info
*revs
, struct strbuf
*out
,
5519 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5520 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5521 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5522 int skipped_commit
= 0;
5523 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5524 struct strbuf label
= STRBUF_INIT
;
5525 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5526 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5527 struct commit
*commit
;
5528 struct oidmap commit2todo
= OIDMAP_INIT
;
5529 struct string_entry
*entry
;
5530 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5531 shown
= OIDSET_INIT
;
5532 struct label_state state
=
5533 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5535 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5536 const char *cmd_pick
= abbr
? "p" : "pick",
5537 *cmd_label
= abbr
? "l" : "label",
5538 *cmd_reset
= abbr
? "t" : "reset",
5539 *cmd_merge
= abbr
? "m" : "merge";
5541 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5543 oidmap_init(&commit2todo
, 0);
5544 oidmap_init(&state
.commit2label
, 0);
5545 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5546 strbuf_init(&state
.buf
, 32);
5548 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5549 struct labels_entry
*onto_label_entry
;
5550 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5551 FLEX_ALLOC_STR(entry
, string
, "onto");
5552 oidcpy(&entry
->entry
.oid
, oid
);
5553 oidmap_put(&state
.commit2label
, entry
);
5555 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5556 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5557 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5562 * - get onelines for all commits
5563 * - gather all branch tips (i.e. 2nd or later parents of merges)
5564 * - label all branch tips
5566 while ((commit
= get_revision(revs
))) {
5567 struct commit_list
*to_merge
;
5568 const char *p1
, *p2
;
5569 struct object_id
*oid
;
5572 tail
= &commit_list_insert(commit
, tail
)->next
;
5573 oidset_insert(&interesting
, &commit
->object
.oid
);
5575 is_empty
= is_original_commit_empty(commit
);
5576 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5577 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5578 warning(_("skipped previously applied commit %s"),
5579 short_commit_name(commit
));
5583 if (is_empty
&& !keep_empty
)
5586 strbuf_reset(&oneline
);
5587 pretty_print_commit(pp
, commit
, &oneline
);
5589 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5591 /* non-merge commit: easy case */
5593 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5594 oid_to_hex(&commit
->object
.oid
),
5597 strbuf_addf(&buf
, " %c empty",
5600 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5601 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5602 oidmap_put(&commit2todo
, entry
);
5607 /* Create a label */
5608 strbuf_reset(&label
);
5609 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5610 (p1
= strchr(p1
, '\'')) &&
5611 (p2
= strchr(++p1
, '\'')))
5612 strbuf_add(&label
, p1
, p2
- p1
);
5613 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5615 (p1
= strstr(p1
, " from ")))
5616 strbuf_addstr(&label
, p1
+ strlen(" from "));
5618 strbuf_addbuf(&label
, &oneline
);
5621 strbuf_addf(&buf
, "%s -C %s",
5622 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5624 /* label the tips of merged branches */
5625 for (; to_merge
; to_merge
= to_merge
->next
) {
5626 oid
= &to_merge
->item
->object
.oid
;
5627 strbuf_addch(&buf
, ' ');
5629 if (!oidset_contains(&interesting
, oid
)) {
5630 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5635 tips_tail
= &commit_list_insert(to_merge
->item
,
5638 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5640 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5642 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5643 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5644 oidmap_put(&commit2todo
, entry
);
5647 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5648 _("use --reapply-cherry-picks to include skipped commits"));
5652 * - label branch points
5653 * - add HEAD to the branch tips
5655 for (iter
= commits
; iter
; iter
= iter
->next
) {
5656 struct commit_list
*parent
= iter
->item
->parents
;
5657 for (; parent
; parent
= parent
->next
) {
5658 struct object_id
*oid
= &parent
->item
->object
.oid
;
5659 if (!oidset_contains(&interesting
, oid
))
5661 if (oidset_insert(&child_seen
, oid
))
5662 label_oid(oid
, "branch-point", &state
);
5665 /* Add HEAD as implicit "tip of branch" */
5667 tips_tail
= &commit_list_insert(iter
->item
,
5672 * Third phase: output the todo list. This is a bit tricky, as we
5673 * want to avoid jumping back and forth between revisions. To
5674 * accomplish that goal, we walk backwards from the branch tips,
5675 * gathering commits not yet shown, reversing the list on the fly,
5676 * then outputting that list (labeling revisions as needed).
5678 strbuf_addf(out
, "%s onto\n", cmd_label
);
5679 for (iter
= tips
; iter
; iter
= iter
->next
) {
5680 struct commit_list
*list
= NULL
, *iter2
;
5682 commit
= iter
->item
;
5683 if (oidset_contains(&shown
, &commit
->object
.oid
))
5685 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5688 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5690 strbuf_addch(out
, '\n');
5692 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5693 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5694 commit_list_insert(commit
, &list
);
5695 if (!commit
->parents
) {
5699 commit
= commit
->parents
->item
;
5703 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5704 rebase_cousins
|| root_with_onto
?
5705 "onto" : "[new root]");
5707 const char *to
= NULL
;
5709 entry
= oidmap_get(&state
.commit2label
,
5710 &commit
->object
.oid
);
5713 else if (!rebase_cousins
)
5714 to
= label_oid(&commit
->object
.oid
, NULL
,
5717 if (!to
|| !strcmp(to
, "onto"))
5718 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5720 strbuf_reset(&oneline
);
5721 pretty_print_commit(pp
, commit
, &oneline
);
5722 strbuf_addf(out
, "%s %s # %s\n",
5723 cmd_reset
, to
, oneline
.buf
);
5727 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5728 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5729 entry
= oidmap_get(&commit2todo
, oid
);
5730 /* only show if not already upstream */
5732 strbuf_addf(out
, "%s\n", entry
->string
);
5733 entry
= oidmap_get(&state
.commit2label
, oid
);
5735 strbuf_addf(out
, "%s %s\n",
5736 cmd_label
, entry
->string
);
5737 oidset_insert(&shown
, oid
);
5740 free_commit_list(list
);
5743 free_commit_list(commits
);
5744 free_commit_list(tips
);
5746 strbuf_release(&label
);
5747 strbuf_release(&oneline
);
5748 strbuf_release(&buf
);
5750 oidmap_free(&commit2todo
, 1);
5751 oidmap_free(&state
.commit2label
, 1);
5752 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5753 strbuf_release(&state
.buf
);
5758 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5759 const char **argv
, unsigned flags
)
5761 char *format
= NULL
;
5762 struct pretty_print_context pp
= {0};
5763 struct rev_info revs
;
5764 struct commit
*commit
;
5765 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5766 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5767 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5768 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5769 int skipped_commit
= 0;
5772 repo_init_revisions(r
, &revs
, NULL
);
5773 revs
.verbose_header
= 1;
5775 revs
.max_parents
= 1;
5776 revs
.cherry_mark
= !reapply_cherry_picks
;
5779 revs
.right_only
= 1;
5780 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5781 revs
.topo_order
= 1;
5783 revs
.pretty_given
= 1;
5784 git_config_get_string("rebase.instructionFormat", &format
);
5785 if (!format
|| !*format
) {
5787 format
= xstrdup("%s");
5789 get_commit_format(format
, &revs
);
5791 pp
.fmt
= revs
.commit_format
;
5792 pp
.output_encoding
= get_log_output_encoding();
5794 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5795 ret
= error(_("make_script: unhandled options"));
5799 if (prepare_revision_walk(&revs
) < 0) {
5800 ret
= error(_("make_script: error preparing revisions"));
5804 if (rebase_merges
) {
5805 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5809 while ((commit
= get_revision(&revs
))) {
5810 int is_empty
= is_original_commit_empty(commit
);
5812 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5813 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5814 warning(_("skipped previously applied commit %s"),
5815 short_commit_name(commit
));
5819 if (is_empty
&& !keep_empty
)
5821 strbuf_addf(out
, "%s %s ", insn
,
5822 oid_to_hex(&commit
->object
.oid
));
5823 pretty_print_commit(&pp
, commit
, out
);
5825 strbuf_addf(out
, " %c empty", comment_line_char
);
5826 strbuf_addch(out
, '\n');
5829 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5830 _("use --reapply-cherry-picks to include skipped commits"));
5832 release_revisions(&revs
);
5837 * Add commands after pick and (series of) squash/fixup commands
5840 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5841 struct string_list
*commands
)
5843 struct strbuf
*buf
= &todo_list
->buf
;
5844 size_t base_offset
= buf
->len
;
5845 int i
, insert
, nr
= 0, alloc
= 0;
5846 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5848 CALLOC_ARRAY(base_items
, commands
->nr
);
5849 for (i
= 0; i
< commands
->nr
; i
++) {
5850 size_t command_len
= strlen(commands
->items
[i
].string
);
5852 strbuf_addstr(buf
, commands
->items
[i
].string
);
5853 strbuf_addch(buf
, '\n');
5855 base_items
[i
].command
= TODO_EXEC
;
5856 base_items
[i
].offset_in_buf
= base_offset
;
5857 base_items
[i
].arg_offset
= base_offset
;
5858 base_items
[i
].arg_len
= command_len
;
5860 base_offset
+= command_len
+ 1;
5864 * Insert <commands> after every pick. Here, fixup/squash chains
5865 * are considered part of the pick, so we insert the commands *after*
5866 * those chains if there are any.
5868 * As we insert the exec commands immediately after rearranging
5869 * any fixups and before the user edits the list, a fixup chain
5870 * can never contain comments (any comments are empty picks that
5871 * have been commented out because the user did not specify
5872 * --keep-empty). So, it is safe to insert an exec command
5873 * without looking at the command following a comment.
5876 for (i
= 0; i
< todo_list
->nr
; i
++) {
5877 enum todo_command command
= todo_list
->items
[i
].command
;
5878 if (insert
&& !is_fixup(command
)) {
5879 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5880 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5886 ALLOC_GROW(items
, nr
+ 1, alloc
);
5887 items
[nr
++] = todo_list
->items
[i
];
5889 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5893 /* insert or append final <commands> */
5895 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5896 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5901 FREE_AND_NULL(todo_list
->items
);
5902 todo_list
->items
= items
;
5904 todo_list
->alloc
= alloc
;
5907 static void todo_list_to_strbuf(struct repository
*r
, struct todo_list
*todo_list
,
5908 struct strbuf
*buf
, int num
, unsigned flags
)
5910 struct todo_item
*item
;
5911 int i
, max
= todo_list
->nr
;
5913 if (num
> 0 && num
< max
)
5916 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5919 /* if the item is not a command write it and continue */
5920 if (item
->command
>= TODO_COMMENT
) {
5921 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5922 todo_item_get_arg(todo_list
, item
));
5926 /* add command to the buffer */
5927 cmd
= command_to_char(item
->command
);
5928 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5929 strbuf_addch(buf
, cmd
);
5931 strbuf_addstr(buf
, command_to_string(item
->command
));
5935 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5936 short_commit_name(item
->commit
) :
5937 oid_to_hex(&item
->commit
->object
.oid
);
5939 if (item
->command
== TODO_FIXUP
) {
5940 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
5941 strbuf_addstr(buf
, " -c");
5942 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
5943 strbuf_addstr(buf
, " -C");
5947 if (item
->command
== TODO_MERGE
) {
5948 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5949 strbuf_addstr(buf
, " -c");
5951 strbuf_addstr(buf
, " -C");
5954 strbuf_addf(buf
, " %s", oid
);
5957 /* add all the rest */
5959 strbuf_addch(buf
, '\n');
5961 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5962 todo_item_get_arg(todo_list
, item
));
5966 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5967 const char *file
, const char *shortrevisions
,
5968 const char *shortonto
, int num
, unsigned flags
)
5971 struct strbuf buf
= STRBUF_INIT
;
5973 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5974 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5975 append_todo_help(count_commands(todo_list
),
5976 shortrevisions
, shortonto
, &buf
);
5978 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5979 strbuf_release(&buf
);
5984 /* skip picking commits whose parents are unchanged */
5985 static int skip_unnecessary_picks(struct repository
*r
,
5986 struct todo_list
*todo_list
,
5987 struct object_id
*base_oid
)
5989 struct object_id
*parent_oid
;
5992 for (i
= 0; i
< todo_list
->nr
; i
++) {
5993 struct todo_item
*item
= todo_list
->items
+ i
;
5995 if (item
->command
>= TODO_NOOP
)
5997 if (item
->command
!= TODO_PICK
)
5999 if (repo_parse_commit(r
, item
->commit
)) {
6000 return error(_("could not parse commit '%s'"),
6001 oid_to_hex(&item
->commit
->object
.oid
));
6003 if (!item
->commit
->parents
)
6004 break; /* root commit */
6005 if (item
->commit
->parents
->next
)
6006 break; /* merge commit */
6007 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
6008 if (!oideq(parent_oid
, base_oid
))
6010 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6013 const char *done_path
= rebase_path_done();
6015 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6016 error_errno(_("could not write to '%s'"), done_path
);
6020 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6022 todo_list
->current
= 0;
6023 todo_list
->done_nr
+= i
;
6025 if (is_fixup(peek_command(todo_list
, 0)))
6026 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6032 struct todo_add_branch_context
{
6033 struct todo_item
*items
;
6037 struct commit
*commit
;
6038 struct string_list refs_to_oids
;
6041 static int add_decorations_to_list(const struct commit
*commit
,
6042 struct todo_add_branch_context
*ctx
)
6044 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6045 const char *head_ref
= resolve_ref_unsafe("HEAD",
6046 RESOLVE_REF_READING
,
6050 while (decoration
) {
6051 struct todo_item
*item
;
6053 size_t base_offset
= ctx
->buf
->len
;
6056 * If the branch is the current HEAD, then it will be
6057 * updated by the default rebase behavior.
6059 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6060 decoration
= decoration
->next
;
6064 ALLOC_GROW(ctx
->items
,
6067 item
= &ctx
->items
[ctx
->items_nr
];
6068 memset(item
, 0, sizeof(*item
));
6070 /* If the branch is checked out, then leave a comment instead. */
6071 if ((path
= branch_checked_out(decoration
->name
))) {
6072 item
->command
= TODO_COMMENT
;
6073 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6074 decoration
->name
, path
);
6076 struct string_list_item
*sti
;
6077 item
->command
= TODO_UPDATE_REF
;
6078 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6080 sti
= string_list_insert(&ctx
->refs_to_oids
,
6082 sti
->util
= init_update_ref_record(decoration
->name
);
6085 item
->offset_in_buf
= base_offset
;
6086 item
->arg_offset
= base_offset
;
6087 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6090 decoration
= decoration
->next
;
6097 * For each 'pick' command, find out if the commit has a decoration in
6098 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6100 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6103 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6104 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6105 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6106 struct decoration_filter decoration_filter
= {
6107 .include_ref_pattern
= &decorate_refs_include
,
6108 .exclude_ref_pattern
= &decorate_refs_exclude
,
6109 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6111 struct todo_add_branch_context ctx
= {
6112 .buf
= &todo_list
->buf
,
6113 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6116 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6117 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6119 string_list_append(&decorate_refs_include
, "refs/heads/");
6120 load_ref_decorations(&decoration_filter
, 0);
6122 for (i
= 0; i
< todo_list
->nr
; ) {
6123 struct todo_item
*item
= &todo_list
->items
[i
];
6125 /* insert ith item into new list */
6126 ALLOC_GROW(ctx
.items
,
6130 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6133 ctx
.commit
= item
->commit
;
6134 add_decorations_to_list(item
->commit
, &ctx
);
6138 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6140 string_list_clear(&ctx
.refs_to_oids
, 1);
6143 /* we failed, so clean up the new list. */
6148 free(todo_list
->items
);
6149 todo_list
->items
= ctx
.items
;
6150 todo_list
->nr
= ctx
.items_nr
;
6151 todo_list
->alloc
= ctx
.items_alloc
;
6156 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6157 const char *shortrevisions
, const char *onto_name
,
6158 struct commit
*onto
, const struct object_id
*orig_head
,
6159 struct string_list
*commands
, unsigned autosquash
,
6160 unsigned update_refs
,
6161 struct todo_list
*todo_list
)
6163 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6164 const char *todo_file
= rebase_path_todo();
6165 struct todo_list new_todo
= TODO_LIST_INIT
;
6166 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6167 struct object_id oid
= onto
->object
.oid
;
6170 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6173 if (buf
->len
== 0) {
6174 struct todo_item
*item
= append_new_todo(todo_list
);
6175 item
->command
= TODO_NOOP
;
6176 item
->commit
= NULL
;
6177 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6180 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6183 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6187 todo_list_add_exec_commands(todo_list
, commands
);
6189 if (count_commands(todo_list
) == 0) {
6190 apply_autostash(rebase_path_autostash());
6191 sequencer_remove_state(opts
);
6193 return error(_("nothing to do"));
6196 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6200 else if (res
== -2) {
6201 apply_autostash(rebase_path_autostash());
6202 sequencer_remove_state(opts
);
6205 } else if (res
== -3) {
6206 apply_autostash(rebase_path_autostash());
6207 sequencer_remove_state(opts
);
6208 todo_list_release(&new_todo
);
6210 return error(_("nothing to do"));
6211 } else if (res
== -4) {
6212 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6213 todo_list_release(&new_todo
);
6218 /* Expand the commit IDs */
6219 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6220 strbuf_swap(&new_todo
.buf
, &buf2
);
6221 strbuf_release(&buf2
);
6222 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6223 new_todo
.total_nr
= 0;
6224 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6225 BUG("invalid todo list after expanding IDs:\n%s",
6228 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6229 todo_list_release(&new_todo
);
6230 return error(_("could not skip unnecessary pick commands"));
6233 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6234 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6235 todo_list_release(&new_todo
);
6236 return error_errno(_("could not write '%s'"), todo_file
);
6241 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6244 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6247 todo_list_write_total_nr(&new_todo
);
6248 res
= pick_commits(r
, &new_todo
, opts
);
6251 todo_list_release(&new_todo
);
6256 struct subject2item_entry
{
6257 struct hashmap_entry entry
;
6259 char subject
[FLEX_ARRAY
];
6262 static int subject2item_cmp(const void *fndata UNUSED
,
6263 const struct hashmap_entry
*eptr
,
6264 const struct hashmap_entry
*entry_or_key
,
6267 const struct subject2item_entry
*a
, *b
;
6269 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6270 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6272 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6275 define_commit_slab(commit_todo_item
, struct todo_item
*);
6277 static int skip_fixupish(const char *subject
, const char **p
) {
6278 return skip_prefix(subject
, "fixup! ", p
) ||
6279 skip_prefix(subject
, "amend! ", p
) ||
6280 skip_prefix(subject
, "squash! ", p
);
6284 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6285 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6286 * after the former, and change "pick" to "fixup"/"squash".
6288 * Note that if the config has specified a custom instruction format, each log
6289 * message will have to be retrieved from the commit (as the oneline in the
6290 * script cannot be trusted) in order to normalize the autosquash arrangement.
6292 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6294 struct hashmap subject2item
;
6295 int rearranged
= 0, *next
, *tail
, i
, nr
= 0, alloc
= 0;
6297 struct commit_todo_item commit_todo
;
6298 struct todo_item
*items
= NULL
;
6300 init_commit_todo_item(&commit_todo
);
6302 * The hashmap maps onelines to the respective todo list index.
6304 * If any items need to be rearranged, the next[i] value will indicate
6305 * which item was moved directly after the i'th.
6307 * In that case, last[i] will indicate the index of the latest item to
6308 * be moved to appear after the i'th.
6310 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6311 ALLOC_ARRAY(next
, todo_list
->nr
);
6312 ALLOC_ARRAY(tail
, todo_list
->nr
);
6313 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6314 for (i
= 0; i
< todo_list
->nr
; i
++) {
6315 struct strbuf buf
= STRBUF_INIT
;
6316 struct todo_item
*item
= todo_list
->items
+ i
;
6317 const char *commit_buffer
, *subject
, *p
;
6320 struct subject2item_entry
*entry
;
6322 next
[i
] = tail
[i
] = -1;
6323 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6328 if (is_fixup(item
->command
)) {
6329 clear_commit_todo_item(&commit_todo
);
6330 return error(_("the script was already rearranged."));
6333 repo_parse_commit(the_repository
, item
->commit
);
6334 commit_buffer
= repo_logmsg_reencode(the_repository
,
6337 find_commit_subject(commit_buffer
, &subject
);
6338 format_subject(&buf
, subject
, " ");
6339 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6340 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6342 if (skip_fixupish(subject
, &p
)) {
6343 struct commit
*commit2
;
6348 if (!skip_fixupish(p
, &p
))
6352 entry
= hashmap_get_entry_from_hash(&subject2item
,
6354 struct subject2item_entry
,
6357 /* found by title */
6359 else if (!strchr(p
, ' ') &&
6361 lookup_commit_reference_by_name(p
)) &&
6362 *commit_todo_item_at(&commit_todo
, commit2
))
6363 /* found by commit name */
6364 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6367 /* copy can be a prefix of the commit subject */
6368 for (i2
= 0; i2
< i
; i2
++)
6370 starts_with(subjects
[i2
], p
))
6378 if (starts_with(subject
, "fixup!")) {
6379 todo_list
->items
[i
].command
= TODO_FIXUP
;
6380 } else if (starts_with(subject
, "amend!")) {
6381 todo_list
->items
[i
].command
= TODO_FIXUP
;
6382 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6384 todo_list
->items
[i
].command
= TODO_SQUASH
;
6390 next
[i
] = next
[tail
[i2
]];
6394 } else if (!hashmap_get_from_hash(&subject2item
,
6395 strhash(subject
), subject
)) {
6396 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6398 hashmap_entry_init(&entry
->entry
,
6399 strhash(entry
->subject
));
6400 hashmap_put(&subject2item
, &entry
->entry
);
6403 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6407 for (i
= 0; i
< todo_list
->nr
; i
++) {
6408 enum todo_command command
= todo_list
->items
[i
].command
;
6412 * Initially, all commands are 'pick's. If it is a
6413 * fixup or a squash now, we have rearranged it.
6415 if (is_fixup(command
))
6419 ALLOC_GROW(items
, nr
+ 1, alloc
);
6420 items
[nr
++] = todo_list
->items
[cur
];
6425 FREE_AND_NULL(todo_list
->items
);
6426 todo_list
->items
= items
;
6428 todo_list
->alloc
= alloc
;
6433 for (i
= 0; i
< todo_list
->nr
; i
++)
6436 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6438 clear_commit_todo_item(&commit_todo
);
6443 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6445 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6446 struct object_id cherry_pick_head
, rebase_head
;
6448 if (file_exists(git_path_seq_dir()))
6449 *whence
= FROM_CHERRY_PICK_MULTI
;
6450 if (file_exists(rebase_path()) &&
6451 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6452 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6453 oideq(&rebase_head
, &cherry_pick_head
))
6454 *whence
= FROM_REBASE_PICK
;
6456 *whence
= FROM_CHERRY_PICK_SINGLE
;
6464 int sequencer_get_update_refs_state(const char *wt_dir
,
6465 struct string_list
*refs
)
6469 struct strbuf ref
= STRBUF_INIT
;
6470 struct strbuf hash
= STRBUF_INIT
;
6471 struct update_ref_record
*rec
= NULL
;
6473 char *path
= rebase_path_update_refs(wt_dir
);
6475 fp
= fopen(path
, "r");
6479 while (strbuf_getline(&ref
, fp
) != EOF
) {
6480 struct string_list_item
*item
;
6482 CALLOC_ARRAY(rec
, 1);
6484 if (strbuf_getline(&hash
, fp
) == EOF
||
6485 get_oid_hex(hash
.buf
, &rec
->before
)) {
6486 warning(_("update-refs file at '%s' is invalid"),
6492 if (strbuf_getline(&hash
, fp
) == EOF
||
6493 get_oid_hex(hash
.buf
, &rec
->after
)) {
6494 warning(_("update-refs file at '%s' is invalid"),
6500 item
= string_list_insert(refs
, ref
.buf
);
6510 strbuf_release(&ref
);
6511 strbuf_release(&hash
);