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"
18 #include "run-command.h"
21 #include "cache-tree.h"
27 #include "merge-ort.h"
28 #include "merge-ort-wrappers.h"
30 #include "sparse-index.h"
35 #include "wt-status.h"
37 #include "notes-utils.h"
39 #include "unpack-trees.h"
42 #include "commit-slab.h"
44 #include "commit-reach.h"
45 #include "rebase-interactive.h"
49 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52 * To accommodate common filesystem limitations, where the loose refs' file
53 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
54 * --rebase-merges` need to be truncated if the corresponding commit subjects
56 * Add some margin to stay clear from reaching `NAME_MAX`.
58 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
60 static const char sign_off_header
[] = "Signed-off-by: ";
61 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
63 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
65 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
67 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
68 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
69 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
70 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
72 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
74 * The file containing rebase commands, comments, and empty lines.
75 * This file is created by "git rebase -i" then edited by the user. As
76 * the lines are processed, they are removed from the front of this
77 * file and written to the tail of 'done'.
79 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
80 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
82 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
85 * The rebase command lines that have already been processed. A line
86 * is moved here when it is first handled, before any associated user
89 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
91 * The file to keep track of how many commands were already processed (e.g.
94 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
96 * The file to keep track of how many commands are to be processed in total
97 * (e.g. for the prompt).
99 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
101 * The commit message that is planned to be used for any changes that
102 * need to be committed following a user interaction.
104 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
106 * The file into which is accumulated the suggested commit message for
107 * squash/fixup commands. When the first of a series of squash/fixups
108 * is seen, the file is created and the commit message from the
109 * previous commit and from the first squash/fixup commit are written
110 * to it. The commit message for each subsequent squash/fixup commit
111 * is appended to the file as it is processed.
113 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
115 * If the current series of squash/fixups has not yet included a squash
116 * command, then this file exists and holds the commit message of the
117 * original "pick" commit. (If the series ends without a "squash"
118 * command, then this can be used as the commit message of the combined
119 * commit without opening the editor.)
121 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
123 * This file contains the list fixup/squash commands that have been
124 * accumulated into message-fixup or message-squash so far.
126 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
128 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
129 * GIT_AUTHOR_DATE that will be used for the commit that is currently
132 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
134 * When an "edit" rebase command is being processed, the SHA1 of the
135 * commit to be edited is recorded in this file. When "git rebase
136 * --continue" is executed, if there are any staged changes then they
137 * will be amended to the HEAD commit, but only provided the HEAD
138 * commit is still the commit to be edited. When any other rebase
139 * command is processed, this file is deleted.
141 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
143 * When we stop at a given patch via the "edit" command, this file contains
144 * the commit object name of the corresponding patch.
146 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
148 * When we stop for the user to resolve conflicts this file contains
149 * the patch of the commit that is being picked.
151 static GIT_PATH_FUNC(rebase_path_patch
, "rebase-merge/patch")
153 * For the post-rewrite hook, we make a list of rewritten commits and
154 * their new sha1s. The rewritten-pending list keeps the sha1s of
155 * commits that have been processed, but not committed yet,
156 * e.g. because they are waiting for a 'squash' command.
158 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
159 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
160 "rebase-merge/rewritten-pending")
163 * The path of the file containing the OID of the "squash onto" commit, i.e.
164 * the dummy commit used for `reset [new root]`.
166 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
169 * The path of the file listing refs that need to be deleted after the rebase
170 * finishes. This is used by the `label` command to record the need for cleanup.
172 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
175 * The update-refs file stores a list of refs that will be updated at the end
176 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
177 * update the OIDs for the refs in this file, but the refs are not updated
178 * until the end of the rebase sequence.
180 * rebase_path_update_refs() returns the path to this file for a given
181 * worktree directory. For the current worktree, pass the_repository->gitdir.
183 static char *rebase_path_update_refs(const char *wt_git_dir
)
185 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir
);
189 * The following files are written by git-rebase just after parsing the
192 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
193 static GIT_PATH_FUNC(rebase_path_cdate_is_adate
, "rebase-merge/cdate_is_adate")
194 static GIT_PATH_FUNC(rebase_path_ignore_date
, "rebase-merge/ignore_date")
195 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
196 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
197 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
198 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
199 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
200 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
201 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
202 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
203 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
204 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
205 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
206 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec
, "rebase-merge/no-reschedule-failed-exec")
207 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
208 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
211 * A 'struct update_refs_record' represents a value in the update-refs
212 * list. We use a string_list to map refs to these (before, after) pairs.
214 struct update_ref_record
{
215 struct object_id before
;
216 struct object_id after
;
219 static struct update_ref_record
*init_update_ref_record(const char *ref
)
221 struct update_ref_record
*rec
;
223 CALLOC_ARRAY(rec
, 1);
225 oidcpy(&rec
->before
, null_oid());
226 oidcpy(&rec
->after
, null_oid());
228 /* This may fail, but that's fine, we will keep the null OID. */
229 read_ref(ref
, &rec
->before
);
234 static int git_sequencer_config(const char *k
, const char *v
,
235 const struct config_context
*ctx
, void *cb
)
237 struct replay_opts
*opts
= cb
;
239 if (!strcmp(k
, "commit.cleanup")) {
241 return config_error_nonbool(k
);
243 if (!strcmp(v
, "verbatim")) {
244 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
245 opts
->explicit_cleanup
= 1;
246 } else if (!strcmp(v
, "whitespace")) {
247 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
248 opts
->explicit_cleanup
= 1;
249 } else if (!strcmp(v
, "strip")) {
250 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
251 opts
->explicit_cleanup
= 1;
252 } else if (!strcmp(v
, "scissors")) {
253 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
254 opts
->explicit_cleanup
= 1;
256 warning(_("invalid commit message cleanup mode '%s'"),
263 if (!strcmp(k
, "commit.gpgsign")) {
264 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
268 if (!opts
->default_strategy
&& !strcmp(k
, "pull.twohead")) {
269 int ret
= git_config_string((const char**)&opts
->default_strategy
, k
, v
);
272 * pull.twohead is allowed to be multi-valued; we only
273 * care about the first value.
275 char *tmp
= strchr(opts
->default_strategy
, ' ');
282 if (opts
->action
== REPLAY_REVERT
&& !strcmp(k
, "revert.reference"))
283 opts
->commit_use_reference
= git_config_bool(k
, v
);
285 return git_diff_basic_config(k
, v
, ctx
, NULL
);
288 void sequencer_init_config(struct replay_opts
*opts
)
290 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
291 git_config(git_sequencer_config
, opts
);
294 static inline int is_rebase_i(const struct replay_opts
*opts
)
296 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
299 static const char *get_dir(const struct replay_opts
*opts
)
301 if (is_rebase_i(opts
))
302 return rebase_path();
303 return git_path_seq_dir();
306 static const char *get_todo_path(const struct replay_opts
*opts
)
308 if (is_rebase_i(opts
))
309 return rebase_path_todo();
310 return git_path_todo_file();
314 * Returns 0 for non-conforming footer
315 * Returns 1 for conforming footer
316 * Returns 2 when sob exists within conforming footer
317 * Returns 3 when sob exists within conforming footer as last entry
319 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
320 size_t ignore_footer
)
322 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
323 struct trailer_info info
;
325 int found_sob
= 0, found_sob_last
= 0;
331 saved_char
= sb
->buf
[sb
->len
- ignore_footer
];
332 sb
->buf
[sb
->len
- ignore_footer
] = '\0';
335 trailer_info_get(&opts
, sb
->buf
, &info
);
338 sb
->buf
[sb
->len
- ignore_footer
] = saved_char
;
340 if (info
.trailer_block_start
== info
.trailer_block_end
)
343 for (i
= 0; i
< info
.trailer_nr
; i
++)
344 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
346 if (i
== info
.trailer_nr
- 1)
350 trailer_info_release(&info
);
359 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
361 static struct strbuf buf
= STRBUF_INIT
;
365 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
369 void replay_opts_release(struct replay_opts
*opts
)
371 free(opts
->gpg_sign
);
372 free(opts
->reflog_action
);
373 free(opts
->default_strategy
);
374 free(opts
->strategy
);
375 strvec_clear (&opts
->xopts
);
376 strbuf_release(&opts
->current_fixups
);
378 release_revisions(opts
->revs
);
382 int sequencer_remove_state(struct replay_opts
*opts
)
384 struct strbuf buf
= STRBUF_INIT
;
387 if (is_rebase_i(opts
) &&
388 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
391 char *eol
= strchr(p
, '\n');
394 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
395 warning(_("could not delete '%s'"), p
);
405 strbuf_addstr(&buf
, get_dir(opts
));
406 if (remove_dir_recursively(&buf
, 0))
407 ret
= error(_("could not remove '%s'"), buf
.buf
);
408 strbuf_release(&buf
);
413 static const char *action_name(const struct replay_opts
*opts
)
415 switch (opts
->action
) {
419 return N_("cherry-pick");
420 case REPLAY_INTERACTIVE_REBASE
:
423 die(_("unknown action: %d"), opts
->action
);
426 struct commit_message
{
433 static const char *short_commit_name(struct repository
*r
, struct commit
*commit
)
435 return repo_find_unique_abbrev(r
, &commit
->object
.oid
, DEFAULT_ABBREV
);
438 static int get_message(struct commit
*commit
, struct commit_message
*out
)
440 const char *abbrev
, *subject
;
443 out
->message
= repo_logmsg_reencode(the_repository
, commit
, NULL
,
444 get_commit_output_encoding());
445 abbrev
= short_commit_name(the_repository
, commit
);
447 subject_len
= find_commit_subject(out
->message
, &subject
);
449 out
->subject
= xmemdupz(subject
, subject_len
);
450 out
->label
= xstrfmt("%s (%s)", abbrev
, out
->subject
);
451 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
456 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
458 free(msg
->parent_label
);
461 repo_unuse_commit_buffer(the_repository
, commit
, msg
->message
);
464 const char *rebase_resolvemsg
=
465 N_("Resolve all conflicts manually, mark them as resolved with\n"
466 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
467 "You can instead skip this commit: run \"git rebase --skip\".\n"
468 "To abort and get back to the state before \"git rebase\", run "
469 "\"git rebase --abort\".");
471 static void print_advice(struct repository
*r
, int show_hint
,
472 struct replay_opts
*opts
)
476 if (is_rebase_i(opts
))
477 msg
= rebase_resolvemsg
;
479 msg
= getenv("GIT_CHERRY_PICK_HELP");
482 advise_if_enabled(ADVICE_MERGE_CONFLICT
, "%s", msg
);
484 * A conflict has occurred but the porcelain
485 * (typically rebase --interactive) wants to take care
486 * of the commit itself so remove CHERRY_PICK_HEAD
488 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
495 advise_if_enabled(ADVICE_MERGE_CONFLICT
,
496 _("after resolving the conflicts, mark the corrected paths\n"
497 "with 'git add <paths>' or 'git rm <paths>'"));
498 else if (opts
->action
== REPLAY_PICK
)
499 advise_if_enabled(ADVICE_MERGE_CONFLICT
,
500 _("After resolving the conflicts, mark them with\n"
501 "\"git add/rm <pathspec>\", then run\n"
502 "\"git cherry-pick --continue\".\n"
503 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
504 "To abort and get back to the state before \"git cherry-pick\",\n"
505 "run \"git cherry-pick --abort\"."));
506 else if (opts
->action
== REPLAY_REVERT
)
507 advise_if_enabled(ADVICE_MERGE_CONFLICT
,
508 _("After resolving the conflicts, mark them with\n"
509 "\"git add/rm <pathspec>\", then run\n"
510 "\"git revert --continue\".\n"
511 "You can instead skip this commit with \"git revert --skip\".\n"
512 "To abort and get back to the state before \"git revert\",\n"
513 "run \"git revert --abort\"."));
515 BUG("unexpected pick action in print_advice()");
519 static int write_message(const void *buf
, size_t len
, const char *filename
,
522 struct lock_file msg_file
= LOCK_INIT
;
524 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
526 return error_errno(_("could not lock '%s'"), filename
);
527 if (write_in_full(msg_fd
, buf
, len
) < 0) {
528 error_errno(_("could not write to '%s'"), filename
);
529 rollback_lock_file(&msg_file
);
532 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
533 error_errno(_("could not write eol to '%s'"), filename
);
534 rollback_lock_file(&msg_file
);
537 if (commit_lock_file(&msg_file
) < 0)
538 return error(_("failed to finalize '%s'"), filename
);
543 int read_oneliner(struct strbuf
*buf
,
544 const char *path
, unsigned flags
)
546 int orig_len
= buf
->len
;
548 if (strbuf_read_file(buf
, path
, 0) < 0) {
549 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
550 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
551 warning_errno(_("could not read '%s'"), path
);
555 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
556 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
558 buf
->buf
[buf
->len
] = '\0';
561 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
567 static struct tree
*empty_tree(struct repository
*r
)
569 return lookup_tree(r
, the_hash_algo
->empty_tree
);
572 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
574 if (repo_read_index_unmerged(repo
))
575 return error_resolve_conflict(action_name(opts
));
577 error(_("your local changes would be overwritten by %s."),
578 _(action_name(opts
)));
580 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE
))
581 advise(_("commit your changes or stash them to proceed."));
585 static void update_abort_safety_file(void)
587 struct object_id head
;
589 /* Do nothing on a single-pick */
590 if (!file_exists(git_path_seq_dir()))
593 if (!repo_get_oid(the_repository
, "HEAD", &head
))
594 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
596 write_file(git_path_abort_safety_file(), "%s", "");
599 static int fast_forward_to(struct repository
*r
,
600 const struct object_id
*to
,
601 const struct object_id
*from
,
603 struct replay_opts
*opts
)
605 struct ref_transaction
*transaction
;
606 struct strbuf sb
= STRBUF_INIT
;
607 struct strbuf err
= STRBUF_INIT
;
610 if (checkout_fast_forward(r
, from
, to
, 1))
611 return -1; /* the callee should have complained already */
613 strbuf_addf(&sb
, "%s: fast-forward", action_name(opts
));
615 transaction
= ref_transaction_begin(&err
);
617 ref_transaction_update(transaction
, "HEAD",
618 to
, unborn
&& !is_rebase_i(opts
) ?
621 ref_transaction_commit(transaction
, &err
)) {
622 ref_transaction_free(transaction
);
623 error("%s", err
.buf
);
625 strbuf_release(&err
);
630 strbuf_release(&err
);
631 ref_transaction_free(transaction
);
632 update_abort_safety_file();
636 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
639 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
640 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
641 COMMIT_MSG_CLEANUP_SPACE
;
642 else if (!strcmp(cleanup_arg
, "verbatim"))
643 return COMMIT_MSG_CLEANUP_NONE
;
644 else if (!strcmp(cleanup_arg
, "whitespace"))
645 return COMMIT_MSG_CLEANUP_SPACE
;
646 else if (!strcmp(cleanup_arg
, "strip"))
647 return COMMIT_MSG_CLEANUP_ALL
;
648 else if (!strcmp(cleanup_arg
, "scissors"))
649 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
650 COMMIT_MSG_CLEANUP_SPACE
;
652 die(_("Invalid cleanup mode %s"), cleanup_arg
);
656 * NB using int rather than enum cleanup_mode to stop clang's
657 * -Wtautological-constant-out-of-range-compare complaining that the comparison
660 static const char *describe_cleanup_mode(int cleanup_mode
)
662 static const char *modes
[] = { "whitespace",
667 if (cleanup_mode
< ARRAY_SIZE(modes
))
668 return modes
[cleanup_mode
];
670 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
673 void append_conflicts_hint(struct index_state
*istate
,
674 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
678 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
679 strbuf_addch(msgbuf
, '\n');
680 wt_status_append_cut_line(msgbuf
);
681 strbuf_addch(msgbuf
, comment_line_char
);
684 strbuf_addch(msgbuf
, '\n');
685 strbuf_commented_addf(msgbuf
, comment_line_char
, "Conflicts:\n");
686 for (i
= 0; i
< istate
->cache_nr
;) {
687 const struct cache_entry
*ce
= istate
->cache
[i
++];
689 strbuf_commented_addf(msgbuf
, comment_line_char
,
691 while (i
< istate
->cache_nr
&&
692 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
698 static int do_recursive_merge(struct repository
*r
,
699 struct commit
*base
, struct commit
*next
,
700 const char *base_label
, const char *next_label
,
701 struct object_id
*head
, struct strbuf
*msgbuf
,
702 struct replay_opts
*opts
)
704 struct merge_options o
;
705 struct merge_result result
;
706 struct tree
*next_tree
, *base_tree
, *head_tree
;
707 int clean
, show_output
;
709 struct lock_file index_lock
= LOCK_INIT
;
711 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
716 init_merge_options(&o
, r
);
717 o
.ancestor
= base
? base_label
: "(empty tree)";
719 o
.branch2
= next
? next_label
: "(empty tree)";
720 if (is_rebase_i(opts
))
722 o
.show_rename_progress
= 1;
724 head_tree
= parse_tree_indirect(head
);
726 return error(_("unable to read tree (%s)"), oid_to_hex(head
));
727 next_tree
= next
? repo_get_commit_tree(r
, next
) : empty_tree(r
);
728 base_tree
= base
? repo_get_commit_tree(r
, base
) : empty_tree(r
);
730 for (i
= 0; i
< opts
->xopts
.nr
; i
++)
731 parse_merge_opt(&o
, opts
->xopts
.v
[i
]);
733 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
734 memset(&result
, 0, sizeof(result
));
735 merge_incore_nonrecursive(&o
, base_tree
, head_tree
, next_tree
,
737 show_output
= !is_rebase_i(opts
) || !result
.clean
;
739 * TODO: merge_switch_to_result will update index/working tree;
740 * we only really want to do that if !result.clean || this is
741 * the final patch to be picked. But determining this is the
742 * final patch would take some work, and "head_tree" would need
743 * to be replace with the tree the index matched before we
744 * started doing any picks.
746 merge_switch_to_result(&o
, head_tree
, &result
, 1, show_output
);
747 clean
= result
.clean
;
749 ensure_full_index(r
->index
);
750 clean
= merge_trees(&o
, head_tree
, next_tree
, base_tree
);
751 if (is_rebase_i(opts
) && clean
<= 0)
752 fputs(o
.obuf
.buf
, stdout
);
753 strbuf_release(&o
.obuf
);
756 rollback_lock_file(&index_lock
);
760 if (write_locked_index(r
->index
, &index_lock
,
761 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
763 * TRANSLATORS: %s will be "revert", "cherry-pick" or
766 return error(_("%s: Unable to write new index file"),
767 _(action_name(opts
)));
770 append_conflicts_hint(r
->index
, msgbuf
,
771 opts
->default_msg_cleanup
);
776 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
778 if (!cache_tree_fully_valid(istate
->cache_tree
))
779 if (cache_tree_update(istate
, 0)) {
780 error(_("unable to update cache tree"));
784 return &istate
->cache_tree
->oid
;
787 static int is_index_unchanged(struct repository
*r
)
789 struct object_id head_oid
, *cache_tree_oid
;
790 struct commit
*head_commit
;
791 struct index_state
*istate
= r
->index
;
793 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
794 return error(_("could not resolve HEAD commit"));
796 head_commit
= lookup_commit(r
, &head_oid
);
799 * If head_commit is NULL, check_commit, called from
800 * lookup_commit, would have indicated that head_commit is not
801 * a commit object already. repo_parse_commit() will return failure
802 * without further complaints in such a case. Otherwise, if
803 * the commit is invalid, repo_parse_commit() will complain. So
804 * there is nothing for us to say here. Just return failure.
806 if (repo_parse_commit(r
, head_commit
))
809 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
812 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
815 static int write_author_script(const char *message
)
817 struct strbuf buf
= STRBUF_INIT
;
822 if (!*message
|| starts_with(message
, "\n")) {
824 /* Missing 'author' line? */
825 unlink(rebase_path_author_script());
827 } else if (skip_prefix(message
, "author ", &message
))
829 else if ((eol
= strchr(message
, '\n')))
834 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
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_EMAIL='");
843 while (*message
&& *message
!= '\n' && *message
!= '\r')
844 if (skip_prefix(message
, "> ", &message
))
846 else if (*message
!= '\'')
847 strbuf_addch(&buf
, *(message
++));
849 strbuf_addf(&buf
, "'\\%c'", *(message
++));
850 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
851 while (*message
&& *message
!= '\n' && *message
!= '\r')
852 if (*message
!= '\'')
853 strbuf_addch(&buf
, *(message
++));
855 strbuf_addf(&buf
, "'\\%c'", *(message
++));
856 strbuf_addch(&buf
, '\'');
857 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
858 strbuf_release(&buf
);
863 * Take a series of KEY='VALUE' lines where VALUE part is
864 * sq-quoted, and append <KEY, VALUE> at the end of the string list
866 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
869 struct string_list_item
*item
;
871 char *cp
= strchr(buf
, '=');
873 np
= strchrnul(buf
, '\n');
874 return error(_("no key present in '%.*s'"),
875 (int) (np
- buf
), buf
);
877 np
= strchrnul(cp
, '\n');
879 item
= string_list_append(list
, buf
);
881 buf
= np
+ (*np
== '\n');
885 return error(_("unable to dequote value of '%s'"),
887 item
->util
= xstrdup(cp
);
893 * Reads and parses the state directory's "author-script" file, and sets name,
894 * email and date accordingly.
895 * Returns 0 on success, -1 if the file could not be parsed.
897 * The author script is of the format:
899 * GIT_AUTHOR_NAME='$author_name'
900 * GIT_AUTHOR_EMAIL='$author_email'
901 * GIT_AUTHOR_DATE='$author_date'
903 * where $author_name, $author_email and $author_date are quoted. We are strict
904 * with our parsing, as the file was meant to be eval'd in the now-removed
905 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
906 * from what this function expects, it is better to bail out than to do
907 * something that the user does not expect.
909 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
912 struct strbuf buf
= STRBUF_INIT
;
913 struct string_list kv
= STRING_LIST_INIT_DUP
;
914 int retval
= -1; /* assume failure */
915 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
917 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
918 strbuf_release(&buf
);
919 if (errno
== ENOENT
&& allow_missing
)
922 return error_errno(_("could not open '%s' for reading"),
926 if (parse_key_value_squoted(buf
.buf
, &kv
))
929 for (i
= 0; i
< kv
.nr
; i
++) {
930 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
932 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
935 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
937 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
940 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
942 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
946 err
= error(_("unknown variable '%s'"),
951 error(_("missing 'GIT_AUTHOR_NAME'"));
953 error(_("missing 'GIT_AUTHOR_EMAIL'"));
955 error(_("missing 'GIT_AUTHOR_DATE'"));
956 if (name_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
958 *name
= kv
.items
[name_i
].util
;
959 *email
= kv
.items
[email_i
].util
;
960 *date
= kv
.items
[date_i
].util
;
963 string_list_clear(&kv
, !!retval
);
964 strbuf_release(&buf
);
969 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
970 * file with shell quoting into struct strvec. Returns -1 on
971 * error, 0 otherwise.
973 static int read_env_script(struct strvec
*env
)
975 char *name
, *email
, *date
;
977 if (read_author_script(rebase_path_author_script(),
978 &name
, &email
, &date
, 0))
981 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
982 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
983 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
991 static char *get_author(const char *message
)
996 a
= find_commit_header(message
, "author", &len
);
998 return xmemdupz(a
, len
);
1003 static const char *author_date_from_env(const struct strvec
*env
)
1008 for (i
= 0; i
< env
->nr
; i
++)
1009 if (skip_prefix(env
->v
[i
],
1010 "GIT_AUTHOR_DATE=", &date
))
1013 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1014 * reading the script
1016 BUG("GIT_AUTHOR_DATE missing from author script");
1019 static const char staged_changes_advice
[] =
1020 N_("you have staged changes in your working tree\n"
1021 "If these changes are meant to be squashed into the previous commit, run:\n"
1023 " git commit --amend %s\n"
1025 "If they are meant to go into a new commit, run:\n"
1029 "In both cases, once you're done, continue with:\n"
1031 " git rebase --continue\n");
1033 #define ALLOW_EMPTY (1<<0)
1034 #define EDIT_MSG (1<<1)
1035 #define AMEND_MSG (1<<2)
1036 #define CLEANUP_MSG (1<<3)
1037 #define VERIFY_MSG (1<<4)
1038 #define CREATE_ROOT_COMMIT (1<<5)
1039 #define VERBATIM_MSG (1<<6)
1041 static int run_command_silent_on_success(struct child_process
*cmd
)
1043 struct strbuf buf
= STRBUF_INIT
;
1046 cmd
->stdout_to_stderr
= 1;
1047 rc
= pipe_command(cmd
,
1053 fputs(buf
.buf
, stderr
);
1054 strbuf_release(&buf
);
1059 * If we are cherry-pick, and if the merge did not result in
1060 * hand-editing, we will hit this commit and inherit the original
1061 * author date and name.
1063 * If we are revert, or if our cherry-pick results in a hand merge,
1064 * we had better say that the current user is responsible for that.
1066 * An exception is when run_git_commit() is called during an
1067 * interactive rebase: in that case, we will want to retain the
1070 static int run_git_commit(const char *defmsg
,
1071 struct replay_opts
*opts
,
1074 struct child_process cmd
= CHILD_PROCESS_INIT
;
1076 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1077 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1081 if (is_rebase_i(opts
) &&
1082 ((opts
->committer_date_is_author_date
&& !opts
->ignore_date
) ||
1083 !(!defmsg
&& (flags
& AMEND_MSG
))) &&
1084 read_env_script(&cmd
.env
)) {
1085 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
1087 return error(_(staged_changes_advice
),
1091 strvec_pushf(&cmd
.env
, GIT_REFLOG_ACTION
"=%s", opts
->reflog_message
);
1093 if (opts
->committer_date_is_author_date
)
1094 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
1097 author_date_from_env(&cmd
.env
));
1098 if (opts
->ignore_date
)
1099 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
1101 strvec_push(&cmd
.args
, "commit");
1103 if (!(flags
& VERIFY_MSG
))
1104 strvec_push(&cmd
.args
, "-n");
1105 if ((flags
& AMEND_MSG
))
1106 strvec_push(&cmd
.args
, "--amend");
1108 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
1110 strvec_push(&cmd
.args
, "--no-gpg-sign");
1112 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
1113 else if (!(flags
& EDIT_MSG
))
1114 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
1115 if ((flags
& CLEANUP_MSG
))
1116 strvec_push(&cmd
.args
, "--cleanup=strip");
1117 if ((flags
& VERBATIM_MSG
))
1118 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1119 if ((flags
& EDIT_MSG
))
1120 strvec_push(&cmd
.args
, "-e");
1121 else if (!(flags
& CLEANUP_MSG
) &&
1122 !opts
->signoff
&& !opts
->record_origin
&&
1123 !opts
->explicit_cleanup
)
1124 strvec_push(&cmd
.args
, "--cleanup=verbatim");
1126 if ((flags
& ALLOW_EMPTY
))
1127 strvec_push(&cmd
.args
, "--allow-empty");
1129 if (!(flags
& EDIT_MSG
))
1130 strvec_push(&cmd
.args
, "--allow-empty-message");
1132 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
1133 return run_command_silent_on_success(&cmd
);
1135 return run_command(&cmd
);
1138 static int rest_is_empty(const struct strbuf
*sb
, int start
)
1143 /* Check if the rest is just whitespace and Signed-off-by's. */
1144 for (i
= start
; i
< sb
->len
; i
++) {
1145 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
1151 if (strlen(sign_off_header
) <= eol
- i
&&
1152 starts_with(sb
->buf
+ i
, sign_off_header
)) {
1157 if (!isspace(sb
->buf
[i
++]))
1164 void cleanup_message(struct strbuf
*msgbuf
,
1165 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
1167 if (verbose
|| /* Truncate the message just before the diff, if any. */
1168 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
1169 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1170 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1171 strbuf_stripspace(msgbuf
,
1172 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1176 * Find out if the message in the strbuf contains only whitespace and
1177 * Signed-off-by lines.
1179 int message_is_empty(const struct strbuf
*sb
,
1180 enum commit_msg_cleanup_mode cleanup_mode
)
1182 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1184 return rest_is_empty(sb
, 0);
1188 * See if the user edited the message in the editor or left what
1189 * was in the template intact
1191 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1192 enum commit_msg_cleanup_mode cleanup_mode
)
1194 struct strbuf tmpl
= STRBUF_INIT
;
1197 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1200 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1203 strbuf_stripspace(&tmpl
,
1204 cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1205 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1207 strbuf_release(&tmpl
);
1208 return rest_is_empty(sb
, start
- sb
->buf
);
1211 int update_head_with_reflog(const struct commit
*old_head
,
1212 const struct object_id
*new_head
,
1213 const char *action
, const struct strbuf
*msg
,
1216 struct ref_transaction
*transaction
;
1217 struct strbuf sb
= STRBUF_INIT
;
1222 strbuf_addstr(&sb
, action
);
1223 strbuf_addstr(&sb
, ": ");
1226 nl
= strchr(msg
->buf
, '\n');
1228 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1230 strbuf_addbuf(&sb
, msg
);
1231 strbuf_addch(&sb
, '\n');
1234 transaction
= ref_transaction_begin(err
);
1236 ref_transaction_update(transaction
, "HEAD", new_head
,
1237 old_head
? &old_head
->object
.oid
: null_oid(),
1239 ref_transaction_commit(transaction
, err
)) {
1242 ref_transaction_free(transaction
);
1243 strbuf_release(&sb
);
1248 static int run_rewrite_hook(const struct object_id
*oldoid
,
1249 const struct object_id
*newoid
)
1251 struct child_process proc
= CHILD_PROCESS_INIT
;
1253 struct strbuf sb
= STRBUF_INIT
;
1254 const char *hook_path
= find_hook("post-rewrite");
1259 strvec_pushl(&proc
.args
, hook_path
, "amend", NULL
);
1261 proc
.stdout_to_stderr
= 1;
1262 proc
.trace2_hook_name
= "post-rewrite";
1264 code
= start_command(&proc
);
1267 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1268 sigchain_push(SIGPIPE
, SIG_IGN
);
1269 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1271 strbuf_release(&sb
);
1272 sigchain_pop(SIGPIPE
);
1273 return finish_command(&proc
);
1276 void commit_post_rewrite(struct repository
*r
,
1277 const struct commit
*old_head
,
1278 const struct object_id
*new_head
)
1280 struct notes_rewrite_cfg
*cfg
;
1282 cfg
= init_copy_notes_for_rewrite("amend");
1284 /* we are amending, so old_head is not NULL */
1285 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1286 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1288 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1291 static int run_prepare_commit_msg_hook(struct repository
*r
,
1296 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1298 name
= git_path_commit_editmsg();
1299 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1308 if (run_commit_hook(0, r
->index_file
, NULL
, "prepare-commit-msg", name
,
1310 ret
= error(_("'prepare-commit-msg' hook failed"));
1315 static const char implicit_ident_advice_noconfig
[] =
1316 N_("Your name and email address were configured automatically based\n"
1317 "on your username and hostname. Please check that they are accurate.\n"
1318 "You can suppress this message by setting them explicitly. Run the\n"
1319 "following command and follow the instructions in your editor to edit\n"
1320 "your configuration file:\n"
1322 " git config --global --edit\n"
1324 "After doing this, you may fix the identity used for this commit with:\n"
1326 " git commit --amend --reset-author\n");
1328 static const char implicit_ident_advice_config
[] =
1329 N_("Your name and email address were configured automatically based\n"
1330 "on your username and hostname. Please check that they are accurate.\n"
1331 "You can suppress this message by setting them explicitly:\n"
1333 " git config --global user.name \"Your Name\"\n"
1334 " git config --global user.email you@example.com\n"
1336 "After doing this, you may fix the identity used for this commit with:\n"
1338 " git commit --amend --reset-author\n");
1340 static const char *implicit_ident_advice(void)
1342 char *user_config
= interpolate_path("~/.gitconfig", 0);
1343 char *xdg_config
= xdg_config_home("config");
1344 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1350 return _(implicit_ident_advice_config
);
1352 return _(implicit_ident_advice_noconfig
);
1356 void print_commit_summary(struct repository
*r
,
1358 const struct object_id
*oid
,
1361 struct rev_info rev
;
1362 struct commit
*commit
;
1363 struct strbuf format
= STRBUF_INIT
;
1365 struct pretty_print_context pctx
= {0};
1366 struct strbuf author_ident
= STRBUF_INIT
;
1367 struct strbuf committer_ident
= STRBUF_INIT
;
1368 struct ref_store
*refs
;
1370 commit
= lookup_commit(r
, oid
);
1372 die(_("couldn't look up newly created commit"));
1373 if (repo_parse_commit(r
, commit
))
1374 die(_("could not parse newly created commit"));
1376 strbuf_addstr(&format
, "format:%h] %s");
1378 repo_format_commit_message(r
, commit
, "%an <%ae>", &author_ident
,
1380 repo_format_commit_message(r
, commit
, "%cn <%ce>", &committer_ident
,
1382 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1383 strbuf_addstr(&format
, "\n Author: ");
1384 strbuf_addbuf_percentquote(&format
, &author_ident
);
1386 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1387 struct strbuf date
= STRBUF_INIT
;
1389 repo_format_commit_message(r
, commit
, "%ad", &date
, &pctx
);
1390 strbuf_addstr(&format
, "\n Date: ");
1391 strbuf_addbuf_percentquote(&format
, &date
);
1392 strbuf_release(&date
);
1394 if (!committer_ident_sufficiently_given()) {
1395 strbuf_addstr(&format
, "\n Committer: ");
1396 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1397 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY
)) {
1398 strbuf_addch(&format
, '\n');
1399 strbuf_addstr(&format
, implicit_ident_advice());
1402 strbuf_release(&author_ident
);
1403 strbuf_release(&committer_ident
);
1405 repo_init_revisions(r
, &rev
, prefix
);
1406 setup_revisions(0, NULL
, &rev
, NULL
);
1409 rev
.diffopt
.output_format
=
1410 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1412 rev
.verbose_header
= 1;
1413 rev
.show_root_diff
= 1;
1414 get_commit_format(format
.buf
, &rev
);
1415 rev
.always_show_header
= 0;
1416 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1417 diff_setup_done(&rev
.diffopt
);
1419 refs
= get_main_ref_store(r
);
1420 head
= refs_resolve_ref_unsafe(refs
, "HEAD", 0, NULL
, NULL
);
1422 die(_("unable to resolve HEAD after creating commit"));
1423 if (!strcmp(head
, "HEAD"))
1424 head
= _("detached HEAD");
1426 skip_prefix(head
, "refs/heads/", &head
);
1427 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1428 _(" (root-commit)") : "");
1430 if (!log_tree_commit(&rev
, commit
)) {
1431 rev
.always_show_header
= 1;
1432 rev
.use_terminator
= 1;
1433 log_tree_commit(&rev
, commit
);
1436 release_revisions(&rev
);
1437 strbuf_release(&format
);
1440 static int parse_head(struct repository
*r
, struct commit
**head
)
1442 struct commit
*current_head
;
1443 struct object_id oid
;
1445 if (repo_get_oid(r
, "HEAD", &oid
)) {
1446 current_head
= NULL
;
1448 current_head
= lookup_commit_reference(r
, &oid
);
1450 return error(_("could not parse HEAD"));
1451 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1452 warning(_("HEAD %s is not a commit!"),
1455 if (repo_parse_commit(r
, current_head
))
1456 return error(_("could not parse HEAD commit"));
1458 *head
= current_head
;
1464 * Try to commit without forking 'git commit'. In some cases we need
1465 * to run 'git commit' to display an error message
1468 * -1 - error unable to commit
1470 * 1 - run 'git commit'
1472 static int try_to_commit(struct repository
*r
,
1473 struct strbuf
*msg
, const char *author
,
1474 struct replay_opts
*opts
, unsigned int flags
,
1475 struct object_id
*oid
)
1477 struct object_id tree
;
1478 struct commit
*current_head
= NULL
;
1479 struct commit_list
*parents
= NULL
;
1480 struct commit_extra_header
*extra
= NULL
;
1481 struct strbuf err
= STRBUF_INIT
;
1482 struct strbuf commit_msg
= STRBUF_INIT
;
1483 char *amend_author
= NULL
;
1484 const char *committer
= NULL
;
1485 const char *hook_commit
= NULL
;
1486 enum commit_msg_cleanup_mode cleanup
;
1489 if ((flags
& CLEANUP_MSG
) && (flags
& VERBATIM_MSG
))
1490 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1492 if (parse_head(r
, ¤t_head
))
1495 if (flags
& AMEND_MSG
) {
1496 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1497 const char *out_enc
= get_commit_output_encoding();
1498 const char *message
= repo_logmsg_reencode(r
, current_head
,
1502 const char *orig_message
= NULL
;
1504 find_commit_subject(message
, &orig_message
);
1506 strbuf_addstr(msg
, orig_message
);
1507 hook_commit
= "HEAD";
1509 author
= amend_author
= get_author(message
);
1510 repo_unuse_commit_buffer(r
, current_head
,
1513 res
= error(_("unable to parse commit author"));
1516 parents
= copy_commit_list(current_head
->parents
);
1517 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1518 } else if (current_head
&&
1519 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1520 commit_list_insert(current_head
, &parents
);
1523 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1524 res
= error(_("git write-tree failed to write a tree"));
1528 if (!(flags
& ALLOW_EMPTY
)) {
1529 struct commit
*first_parent
= current_head
;
1531 if (flags
& AMEND_MSG
) {
1532 if (current_head
->parents
) {
1533 first_parent
= current_head
->parents
->item
;
1534 if (repo_parse_commit(r
, first_parent
)) {
1535 res
= error(_("could not parse HEAD commit"));
1539 first_parent
= NULL
;
1542 if (oideq(first_parent
1543 ? get_commit_tree_oid(first_parent
)
1544 : the_hash_algo
->empty_tree
,
1546 res
= 1; /* run 'git commit' to display error message */
1551 if (hook_exists("prepare-commit-msg")) {
1552 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1555 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1557 res
= error_errno(_("unable to read commit message "
1559 git_path_commit_editmsg());
1565 if (flags
& CLEANUP_MSG
)
1566 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1567 else if (flags
& VERBATIM_MSG
)
1568 cleanup
= COMMIT_MSG_CLEANUP_NONE
;
1569 else if ((opts
->signoff
|| opts
->record_origin
) &&
1570 !opts
->explicit_cleanup
)
1571 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1573 cleanup
= opts
->default_msg_cleanup
;
1575 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1576 strbuf_stripspace(msg
,
1577 cleanup
== COMMIT_MSG_CLEANUP_ALL
? comment_line_char
: '\0');
1578 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1579 res
= 1; /* run 'git commit' to display error message */
1583 if (opts
->committer_date_is_author_date
) {
1584 struct ident_split id
;
1585 struct strbuf date
= STRBUF_INIT
;
1587 if (!opts
->ignore_date
) {
1588 if (split_ident_line(&id
, author
, (int)strlen(author
)) < 0) {
1589 res
= error(_("invalid author identity '%s'"),
1593 if (!id
.date_begin
) {
1595 "corrupt author: missing date information"));
1598 strbuf_addf(&date
, "@%.*s %.*s",
1599 (int)(id
.date_end
- id
.date_begin
),
1601 (int)(id
.tz_end
- id
.tz_begin
),
1606 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1607 getenv("GIT_COMMITTER_EMAIL"),
1608 WANT_COMMITTER_IDENT
,
1609 opts
->ignore_date
? NULL
: date
.buf
,
1611 strbuf_release(&date
);
1616 if (opts
->ignore_date
) {
1617 struct ident_split id
;
1620 if (split_ident_line(&id
, author
, strlen(author
)) < 0) {
1621 error(_("invalid author identity '%s'"), author
);
1624 name
= xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1625 email
= xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1626 author
= fmt_ident(name
, email
, WANT_AUTHOR_IDENT
, NULL
,
1632 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
, oid
,
1633 author
, committer
, opts
->gpg_sign
, extra
)) {
1634 res
= error(_("failed to write commit object"));
1638 if (update_head_with_reflog(current_head
, oid
, opts
->reflog_message
,
1640 res
= error("%s", err
.buf
);
1644 run_commit_hook(0, r
->index_file
, NULL
, "post-commit", NULL
);
1645 if (flags
& AMEND_MSG
)
1646 commit_post_rewrite(r
, current_head
, oid
);
1649 free_commit_extra_headers(extra
);
1650 strbuf_release(&err
);
1651 strbuf_release(&commit_msg
);
1657 static int write_rebase_head(struct object_id
*oid
)
1659 if (update_ref("rebase", "REBASE_HEAD", oid
,
1660 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1661 return error(_("could not update %s"), "REBASE_HEAD");
1666 static int do_commit(struct repository
*r
,
1667 const char *msg_file
, const char *author
,
1668 struct replay_opts
*opts
, unsigned int flags
,
1669 struct object_id
*oid
)
1673 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1674 struct object_id oid
;
1675 struct strbuf sb
= STRBUF_INIT
;
1677 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1678 return error_errno(_("unable to read commit message "
1682 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1683 author
, opts
, flags
, &oid
);
1684 strbuf_release(&sb
);
1686 refs_delete_ref(get_main_ref_store(r
), "",
1687 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
);
1688 unlink(git_path_merge_msg(r
));
1689 if (!is_rebase_i(opts
))
1690 print_commit_summary(r
, NULL
, &oid
,
1691 SUMMARY_SHOW_AUTHOR_DATE
);
1696 if (is_rebase_i(opts
) && oid
)
1697 if (write_rebase_head(oid
))
1699 return run_git_commit(msg_file
, opts
, flags
);
1705 static int is_original_commit_empty(struct commit
*commit
)
1707 const struct object_id
*ptree_oid
;
1709 if (repo_parse_commit(the_repository
, commit
))
1710 return error(_("could not parse commit %s"),
1711 oid_to_hex(&commit
->object
.oid
));
1712 if (commit
->parents
) {
1713 struct commit
*parent
= commit
->parents
->item
;
1714 if (repo_parse_commit(the_repository
, parent
))
1715 return error(_("could not parse parent commit %s"),
1716 oid_to_hex(&parent
->object
.oid
));
1717 ptree_oid
= get_commit_tree_oid(parent
);
1719 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1722 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1726 * Should empty commits be allowed? Return status:
1727 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1728 * 0: Halt on empty commit
1729 * 1: Allow empty commit
1730 * 2: Drop empty commit
1732 static int allow_empty(struct repository
*r
,
1733 struct replay_opts
*opts
,
1734 struct commit
*commit
)
1736 int index_unchanged
, originally_empty
;
1741 * (1) we do not allow empty at all and error out.
1743 * (2) we allow ones that were initially empty, and
1744 * just drop the ones that become empty
1746 * (3) we allow ones that were initially empty, but
1747 * halt for the ones that become empty;
1749 * (4) we allow both.
1751 if (!opts
->allow_empty
)
1752 return 0; /* let "git commit" barf as necessary */
1754 index_unchanged
= is_index_unchanged(r
);
1755 if (index_unchanged
< 0)
1756 return index_unchanged
;
1757 if (!index_unchanged
)
1758 return 0; /* we do not have to say --allow-empty */
1760 if (opts
->keep_redundant_commits
)
1763 originally_empty
= is_original_commit_empty(commit
);
1764 if (originally_empty
< 0)
1765 return originally_empty
;
1766 if (originally_empty
)
1768 else if (opts
->drop_redundant_commits
)
1777 } todo_command_info
[] = {
1778 [TODO_PICK
] = { 'p', "pick" },
1779 [TODO_REVERT
] = { 0, "revert" },
1780 [TODO_EDIT
] = { 'e', "edit" },
1781 [TODO_REWORD
] = { 'r', "reword" },
1782 [TODO_FIXUP
] = { 'f', "fixup" },
1783 [TODO_SQUASH
] = { 's', "squash" },
1784 [TODO_EXEC
] = { 'x', "exec" },
1785 [TODO_BREAK
] = { 'b', "break" },
1786 [TODO_LABEL
] = { 'l', "label" },
1787 [TODO_RESET
] = { 't', "reset" },
1788 [TODO_MERGE
] = { 'm', "merge" },
1789 [TODO_UPDATE_REF
] = { 'u', "update-ref" },
1790 [TODO_NOOP
] = { 0, "noop" },
1791 [TODO_DROP
] = { 'd', "drop" },
1792 [TODO_COMMENT
] = { 0, NULL
},
1795 static const char *command_to_string(const enum todo_command command
)
1797 if (command
< TODO_COMMENT
)
1798 return todo_command_info
[command
].str
;
1799 die(_("unknown command: %d"), command
);
1802 static char command_to_char(const enum todo_command command
)
1804 if (command
< TODO_COMMENT
)
1805 return todo_command_info
[command
].c
;
1806 return comment_line_char
;
1809 static int is_noop(const enum todo_command command
)
1811 return TODO_NOOP
<= command
;
1814 static int is_fixup(enum todo_command command
)
1816 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1819 /* Does this command create a (non-merge) commit? */
1820 static int is_pick_or_similar(enum todo_command command
)
1835 enum todo_item_flags
{
1836 TODO_EDIT_MERGE_MSG
= (1 << 0),
1837 TODO_REPLACE_FIXUP_MSG
= (1 << 1),
1838 TODO_EDIT_FIXUP_MSG
= (1 << 2),
1841 static const char first_commit_msg_str
[] = N_("This is the 1st commit message:");
1842 static const char nth_commit_msg_fmt
[] = N_("This is the commit message #%d:");
1843 static const char skip_first_commit_msg_str
[] = N_("The 1st commit message will be skipped:");
1844 static const char skip_nth_commit_msg_fmt
[] = N_("The commit message #%d will be skipped:");
1845 static const char combined_commit_msg_fmt
[] = N_("This is a combination of %d commits.");
1847 static int is_fixup_flag(enum todo_command command
, unsigned flag
)
1849 return command
== TODO_FIXUP
&& ((flag
& TODO_REPLACE_FIXUP_MSG
) ||
1850 (flag
& TODO_EDIT_FIXUP_MSG
));
1854 * Wrapper around strbuf_add_commented_lines() which avoids double
1855 * commenting commit subjects.
1857 static void add_commented_lines(struct strbuf
*buf
, const void *str
, size_t len
)
1859 const char *s
= str
;
1860 while (len
> 0 && s
[0] == comment_line_char
) {
1862 const char *n
= memchr(s
, '\n', len
);
1867 strbuf_add(buf
, s
, count
);
1871 strbuf_add_commented_lines(buf
, s
, len
, comment_line_char
);
1874 /* Does the current fixup chain contain a squash command? */
1875 static int seen_squash(struct replay_opts
*opts
)
1877 return starts_with(opts
->current_fixups
.buf
, "squash") ||
1878 strstr(opts
->current_fixups
.buf
, "\nsquash");
1881 static void update_comment_bufs(struct strbuf
*buf1
, struct strbuf
*buf2
, int n
)
1883 strbuf_setlen(buf1
, 2);
1884 strbuf_addf(buf1
, _(nth_commit_msg_fmt
), n
);
1885 strbuf_addch(buf1
, '\n');
1886 strbuf_setlen(buf2
, 2);
1887 strbuf_addf(buf2
, _(skip_nth_commit_msg_fmt
), n
);
1888 strbuf_addch(buf2
, '\n');
1892 * Comment out any un-commented commit messages, updating the message comments
1893 * to say they will be skipped but do not comment out the empty lines that
1894 * surround commit messages and their comments.
1896 static void update_squash_message_for_fixup(struct strbuf
*msg
)
1898 void (*copy_lines
)(struct strbuf
*, const void *, size_t) = strbuf_add
;
1899 struct strbuf buf1
= STRBUF_INIT
, buf2
= STRBUF_INIT
;
1900 const char *s
, *start
;
1902 size_t orig_msg_len
;
1905 strbuf_addf(&buf1
, "# %s\n", _(first_commit_msg_str
));
1906 strbuf_addf(&buf2
, "# %s\n", _(skip_first_commit_msg_str
));
1907 s
= start
= orig_msg
= strbuf_detach(msg
, &orig_msg_len
);
1911 if (skip_prefix(s
, buf1
.buf
, &next
)) {
1913 * Copy the last message, preserving the blank line
1914 * preceding the current line
1916 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1917 copy_lines(msg
, start
, s
- start
- off
);
1919 strbuf_addch(msg
, '\n');
1921 * The next message needs to be commented out but the
1922 * message header is already commented out so just copy
1923 * it and the blank line that follows it.
1925 strbuf_addbuf(msg
, &buf2
);
1927 strbuf_addch(msg
, *next
++);
1929 copy_lines
= add_commented_lines
;
1930 update_comment_bufs(&buf1
, &buf2
, ++i
);
1931 } else if (skip_prefix(s
, buf2
.buf
, &next
)) {
1932 off
= (s
> start
+ 1 && s
[-2] == '\n') ? 1 : 0;
1933 copy_lines(msg
, start
, s
- start
- off
);
1936 copy_lines
= strbuf_add
;
1937 update_comment_bufs(&buf1
, &buf2
, ++i
);
1939 s
= strchr(s
, '\n');
1944 copy_lines(msg
, start
, orig_msg_len
- (start
- orig_msg
));
1946 strbuf_release(&buf1
);
1947 strbuf_release(&buf2
);
1950 static int append_squash_message(struct strbuf
*buf
, const char *body
,
1951 enum todo_command command
, struct replay_opts
*opts
,
1954 const char *fixup_msg
;
1955 size_t commented_len
= 0, fixup_off
;
1957 * amend is non-interactive and not normally used with fixup!
1958 * or squash! commits, so only comment out those subjects when
1959 * squashing commit messages.
1961 if (starts_with(body
, "amend!") ||
1962 ((command
== TODO_SQUASH
|| seen_squash(opts
)) &&
1963 (starts_with(body
, "squash!") || starts_with(body
, "fixup!"))))
1964 commented_len
= commit_subject_length(body
);
1966 strbuf_addf(buf
, "\n%c ", comment_line_char
);
1967 strbuf_addf(buf
, _(nth_commit_msg_fmt
),
1968 ++opts
->current_fixup_count
+ 1);
1969 strbuf_addstr(buf
, "\n\n");
1970 strbuf_add_commented_lines(buf
, body
, commented_len
, comment_line_char
);
1971 /* buf->buf may be reallocated so store an offset into the buffer */
1972 fixup_off
= buf
->len
;
1973 strbuf_addstr(buf
, body
+ commented_len
);
1975 /* fixup -C after squash behaves like squash */
1976 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
)) {
1978 * We're replacing the commit message so we need to
1979 * append the Signed-off-by: trailer if the user
1980 * requested '--signoff'.
1983 append_signoff(buf
, 0, 0);
1985 if ((command
== TODO_FIXUP
) &&
1986 (flag
& TODO_REPLACE_FIXUP_MSG
) &&
1987 (file_exists(rebase_path_fixup_msg()) ||
1988 !file_exists(rebase_path_squash_msg()))) {
1989 fixup_msg
= skip_blank_lines(buf
->buf
+ fixup_off
);
1990 if (write_message(fixup_msg
, strlen(fixup_msg
),
1991 rebase_path_fixup_msg(), 0) < 0)
1992 return error(_("cannot write '%s'"),
1993 rebase_path_fixup_msg());
1995 unlink(rebase_path_fixup_msg());
1998 unlink(rebase_path_fixup_msg());
2004 static int update_squash_messages(struct repository
*r
,
2005 enum todo_command command
,
2006 struct commit
*commit
,
2007 struct replay_opts
*opts
,
2010 struct strbuf buf
= STRBUF_INIT
;
2012 const char *message
, *body
;
2013 const char *encoding
= get_commit_output_encoding();
2015 if (opts
->current_fixup_count
> 0) {
2016 struct strbuf header
= STRBUF_INIT
;
2019 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
2020 return error(_("could not read '%s'"),
2021 rebase_path_squash_msg());
2023 eol
= buf
.buf
[0] != comment_line_char
?
2024 buf
.buf
: strchrnul(buf
.buf
, '\n');
2026 strbuf_addf(&header
, "%c ", comment_line_char
);
2027 strbuf_addf(&header
, _(combined_commit_msg_fmt
),
2028 opts
->current_fixup_count
+ 2);
2029 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
2030 strbuf_release(&header
);
2031 if (is_fixup_flag(command
, flag
) && !seen_squash(opts
))
2032 update_squash_message_for_fixup(&buf
);
2034 struct object_id head
;
2035 struct commit
*head_commit
;
2036 const char *head_message
, *body
;
2038 if (repo_get_oid(r
, "HEAD", &head
))
2039 return error(_("need a HEAD to fixup"));
2040 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
2041 return error(_("could not read HEAD"));
2042 if (!(head_message
= repo_logmsg_reencode(r
, head_commit
, NULL
,
2044 return error(_("could not read HEAD's commit message"));
2046 find_commit_subject(head_message
, &body
);
2047 if (command
== TODO_FIXUP
&& !flag
&& write_message(body
, strlen(body
),
2048 rebase_path_fixup_msg(), 0) < 0) {
2049 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2050 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2052 strbuf_addf(&buf
, "%c ", comment_line_char
);
2053 strbuf_addf(&buf
, _(combined_commit_msg_fmt
), 2);
2054 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2055 strbuf_addstr(&buf
, is_fixup_flag(command
, flag
) ?
2056 _(skip_first_commit_msg_str
) :
2057 _(first_commit_msg_str
));
2058 strbuf_addstr(&buf
, "\n\n");
2059 if (is_fixup_flag(command
, flag
))
2060 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2063 strbuf_addstr(&buf
, body
);
2065 repo_unuse_commit_buffer(r
, head_commit
, head_message
);
2068 if (!(message
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
)))
2069 return error(_("could not read commit message of %s"),
2070 oid_to_hex(&commit
->object
.oid
));
2071 find_commit_subject(message
, &body
);
2073 if (command
== TODO_SQUASH
|| is_fixup_flag(command
, flag
)) {
2074 res
= append_squash_message(&buf
, body
, command
, opts
, flag
);
2075 } else if (command
== TODO_FIXUP
) {
2076 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
2077 strbuf_addf(&buf
, _(skip_nth_commit_msg_fmt
),
2078 ++opts
->current_fixup_count
+ 1);
2079 strbuf_addstr(&buf
, "\n\n");
2080 strbuf_add_commented_lines(&buf
, body
, strlen(body
),
2083 return error(_("unknown command: %d"), command
);
2084 repo_unuse_commit_buffer(r
, commit
, message
);
2087 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(),
2089 strbuf_release(&buf
);
2092 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
2093 opts
->current_fixups
.len
? "\n" : "",
2094 command_to_string(command
),
2095 oid_to_hex(&commit
->object
.oid
));
2096 res
= write_message(opts
->current_fixups
.buf
,
2097 opts
->current_fixups
.len
,
2098 rebase_path_current_fixups(), 0);
2104 static void flush_rewritten_pending(void)
2106 struct strbuf buf
= STRBUF_INIT
;
2107 struct object_id newoid
;
2110 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
2111 !repo_get_oid(the_repository
, "HEAD", &newoid
) &&
2112 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2113 char *bol
= buf
.buf
, *eol
;
2116 eol
= strchrnul(bol
, '\n');
2117 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
2118 bol
, oid_to_hex(&newoid
));
2124 unlink(rebase_path_rewritten_pending());
2126 strbuf_release(&buf
);
2129 static void record_in_rewritten(struct object_id
*oid
,
2130 enum todo_command next_command
)
2132 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
2137 fprintf(out
, "%s\n", oid_to_hex(oid
));
2140 if (!is_fixup(next_command
))
2141 flush_rewritten_pending();
2144 static int should_edit(struct replay_opts
*opts
) {
2147 * Note that we only handle the case of non-conflicted
2148 * commits; continue_single_pick() handles the conflicted
2149 * commits itself instead of calling this function.
2151 return (opts
->action
== REPLAY_REVERT
&& isatty(0)) ? 1 : 0;
2155 static void refer_to_commit(struct replay_opts
*opts
,
2156 struct strbuf
*msgbuf
, struct commit
*commit
)
2158 if (opts
->commit_use_reference
) {
2159 struct pretty_print_context ctx
= {
2160 .abbrev
= DEFAULT_ABBREV
,
2161 .date_mode
.type
= DATE_SHORT
,
2163 repo_format_commit_message(the_repository
, commit
,
2164 "%h (%s, %ad)", msgbuf
, &ctx
);
2166 strbuf_addstr(msgbuf
, oid_to_hex(&commit
->object
.oid
));
2170 static int do_pick_commit(struct repository
*r
,
2171 struct todo_item
*item
,
2172 struct replay_opts
*opts
,
2173 int final_fixup
, int *check_todo
)
2175 unsigned int flags
= should_edit(opts
) ? EDIT_MSG
: 0;
2176 const char *msg_file
= should_edit(opts
) ? NULL
: git_path_merge_msg(r
);
2177 struct object_id head
;
2178 struct commit
*base
, *next
, *parent
;
2179 const char *base_label
, *next_label
;
2180 char *author
= NULL
;
2181 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
2182 struct strbuf msgbuf
= STRBUF_INIT
;
2183 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
2184 enum todo_command command
= item
->command
;
2185 struct commit
*commit
= item
->commit
;
2187 if (opts
->no_commit
) {
2189 * We do not intend to commit immediately. We just want to
2190 * merge the differences in, so let's compute the tree
2191 * that represents the "current" state for the merge machinery
2194 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
2195 return error(_("your index file is unmerged."));
2197 unborn
= repo_get_oid(r
, "HEAD", &head
);
2198 /* Do we want to generate a root commit? */
2199 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
2200 oideq(&head
, &opts
->squash_onto
)) {
2201 if (is_fixup(command
))
2202 return error(_("cannot fixup root commit"));
2203 flags
|= CREATE_ROOT_COMMIT
;
2206 oidcpy(&head
, the_hash_algo
->empty_tree
);
2207 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
2209 return error_dirty_index(r
, opts
);
2211 discard_index(r
->index
);
2213 if (!commit
->parents
)
2215 else if (commit
->parents
->next
) {
2216 /* Reverting or cherry-picking a merge commit */
2218 struct commit_list
*p
;
2220 if (!opts
->mainline
)
2221 return error(_("commit %s is a merge but no -m option was given."),
2222 oid_to_hex(&commit
->object
.oid
));
2224 for (cnt
= 1, p
= commit
->parents
;
2225 cnt
!= opts
->mainline
&& p
;
2228 if (cnt
!= opts
->mainline
|| !p
)
2229 return error(_("commit %s does not have parent %d"),
2230 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2232 } else if (1 < opts
->mainline
)
2234 * Non-first parent explicitly specified as mainline for
2237 return error(_("commit %s does not have parent %d"),
2238 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
2240 parent
= commit
->parents
->item
;
2242 if (get_message(commit
, &msg
) != 0)
2243 return error(_("cannot get commit message for %s"),
2244 oid_to_hex(&commit
->object
.oid
));
2246 if (opts
->allow_ff
&& !is_fixup(command
) &&
2247 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
2248 (!parent
&& unborn
))) {
2249 if (is_rebase_i(opts
))
2250 write_author_script(msg
.message
);
2251 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
2253 if (res
|| command
!= TODO_REWORD
)
2257 goto fast_forward_edit
;
2259 if (parent
&& repo_parse_commit(r
, parent
) < 0)
2260 /* TRANSLATORS: The first %s will be a "todo" command like
2261 "revert" or "pick", the second %s a SHA1. */
2262 return error(_("%s: cannot parse parent commit %s"),
2263 command_to_string(command
),
2264 oid_to_hex(&parent
->object
.oid
));
2267 * "commit" is an existing commit. We would want to apply
2268 * the difference it introduces since its first parent "prev"
2269 * on top of the current HEAD if we are cherry-pick. Or the
2270 * reverse of it if we are revert.
2273 if (command
== TODO_REVERT
) {
2274 const char *orig_subject
;
2277 base_label
= msg
.label
;
2279 next_label
= msg
.parent_label
;
2280 if (opts
->commit_use_reference
) {
2281 strbuf_addstr(&msgbuf
,
2282 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2283 } else if (skip_prefix(msg
.subject
, "Revert \"", &orig_subject
) &&
2285 * We don't touch pre-existing repeated reverts, because
2286 * theoretically these can be nested arbitrarily deeply,
2287 * thus requiring excessive complexity to deal with.
2289 !starts_with(orig_subject
, "Revert \"")) {
2290 strbuf_addstr(&msgbuf
, "Reapply \"");
2291 strbuf_addstr(&msgbuf
, orig_subject
);
2293 strbuf_addstr(&msgbuf
, "Revert \"");
2294 strbuf_addstr(&msgbuf
, msg
.subject
);
2295 strbuf_addstr(&msgbuf
, "\"");
2297 strbuf_addstr(&msgbuf
, "\n\nThis reverts commit ");
2298 refer_to_commit(opts
, &msgbuf
, commit
);
2300 if (commit
->parents
&& commit
->parents
->next
) {
2301 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
2302 refer_to_commit(opts
, &msgbuf
, parent
);
2304 strbuf_addstr(&msgbuf
, ".\n");
2309 base_label
= msg
.parent_label
;
2311 next_label
= msg
.label
;
2313 /* Append the commit log message to msgbuf. */
2314 if (find_commit_subject(msg
.message
, &p
))
2315 strbuf_addstr(&msgbuf
, p
);
2317 if (opts
->record_origin
) {
2318 strbuf_complete_line(&msgbuf
);
2319 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
2320 strbuf_addch(&msgbuf
, '\n');
2321 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
2322 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
2323 strbuf_addstr(&msgbuf
, ")\n");
2325 if (!is_fixup(command
))
2326 author
= get_author(msg
.message
);
2329 if (command
== TODO_REWORD
)
2331 else if (is_fixup(command
)) {
2332 if (update_squash_messages(r
, command
, commit
,
2333 opts
, item
->flags
)) {
2339 msg_file
= rebase_path_squash_msg();
2340 else if (file_exists(rebase_path_fixup_msg())) {
2341 flags
|= VERBATIM_MSG
;
2342 msg_file
= rebase_path_fixup_msg();
2344 const char *dest
= git_path_squash_msg(r
);
2346 if (copy_file(dest
, rebase_path_squash_msg(), 0666)) {
2347 res
= error(_("could not copy '%s' to '%s'"),
2348 rebase_path_squash_msg(), dest
);
2351 unlink(git_path_merge_msg(r
));
2357 if (opts
->signoff
&& !is_fixup(command
))
2358 append_signoff(&msgbuf
, 0, 0);
2360 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
2362 else if (!opts
->strategy
||
2363 !strcmp(opts
->strategy
, "recursive") ||
2364 !strcmp(opts
->strategy
, "ort") ||
2365 command
== TODO_REVERT
) {
2366 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
2367 &head
, &msgbuf
, opts
);
2371 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
2372 git_path_merge_msg(r
), 0);
2374 struct commit_list
*common
= NULL
;
2375 struct commit_list
*remotes
= NULL
;
2377 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
2378 git_path_merge_msg(r
), 0);
2380 commit_list_insert(base
, &common
);
2381 commit_list_insert(next
, &remotes
);
2382 res
|= try_merge_command(r
, opts
->strategy
,
2383 opts
->xopts
.nr
, opts
->xopts
.v
,
2384 common
, oid_to_hex(&head
), remotes
);
2385 free_commit_list(common
);
2386 free_commit_list(remotes
);
2390 * If the merge was clean or if it failed due to conflict, we write
2391 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2392 * However, if the merge did not even start, then we don't want to
2395 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
2396 command
== TODO_EDIT
) && !opts
->no_commit
&&
2397 (res
== 0 || res
== 1) &&
2398 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
2399 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2401 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
2402 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
2403 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2407 error(command
== TODO_REVERT
2408 ? _("could not revert %s... %s")
2409 : _("could not apply %s... %s"),
2410 short_commit_name(r
, commit
), msg
.subject
);
2411 print_advice(r
, res
== 1, opts
);
2412 repo_rerere(r
, opts
->allow_rerere_auto
);
2417 allow
= allow_empty(r
, opts
, commit
);
2421 } else if (allow
== 1) {
2422 flags
|= ALLOW_EMPTY
;
2423 } else if (allow
== 2) {
2425 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
2426 NULL
, REF_NO_DEREF
);
2427 unlink(git_path_merge_msg(r
));
2428 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2429 NULL
, REF_NO_DEREF
);
2431 _("dropping %s %s -- patch contents already upstream\n"),
2432 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
2433 } /* else allow == 0 and there's nothing special to do */
2434 if (!opts
->no_commit
&& !drop_commit
) {
2435 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
2436 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
2437 commit
? &commit
->object
.oid
: NULL
);
2439 res
= error(_("unable to parse commit author"));
2440 *check_todo
= !!(flags
& EDIT_MSG
);
2441 if (!res
&& reword
) {
2443 res
= run_git_commit(NULL
, opts
, EDIT_MSG
|
2444 VERIFY_MSG
| AMEND_MSG
|
2445 (flags
& ALLOW_EMPTY
));
2451 if (!res
&& final_fixup
) {
2452 unlink(rebase_path_fixup_msg());
2453 unlink(rebase_path_squash_msg());
2454 unlink(rebase_path_current_fixups());
2455 strbuf_reset(&opts
->current_fixups
);
2456 opts
->current_fixup_count
= 0;
2460 free_message(commit
, &msg
);
2462 strbuf_release(&msgbuf
);
2463 update_abort_safety_file();
2468 static int prepare_revs(struct replay_opts
*opts
)
2471 * picking (but not reverting) ranges (but not individual revisions)
2472 * should be done in reverse
2474 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2475 opts
->revs
->reverse
^= 1;
2477 if (prepare_revision_walk(opts
->revs
))
2478 return error(_("revision walk setup failed"));
2483 static int read_and_refresh_cache(struct repository
*r
,
2484 struct replay_opts
*opts
)
2486 struct lock_file index_lock
= LOCK_INIT
;
2487 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2488 if (repo_read_index(r
) < 0) {
2489 rollback_lock_file(&index_lock
);
2490 return error(_("git %s: failed to read the index"),
2493 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2495 if (index_fd
>= 0) {
2496 if (write_locked_index(r
->index
, &index_lock
,
2497 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2498 return error(_("git %s: failed to refresh the index"),
2504 * If we are resolving merges in any way other than "ort", then
2505 * expand the sparse index.
2507 if (opts
->strategy
&& strcmp(opts
->strategy
, "ort"))
2508 ensure_full_index(r
->index
);
2512 void todo_list_release(struct todo_list
*todo_list
)
2514 strbuf_release(&todo_list
->buf
);
2515 FREE_AND_NULL(todo_list
->items
);
2516 todo_list
->nr
= todo_list
->alloc
= 0;
2519 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2521 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2522 return todo_list
->items
+ todo_list
->nr
++;
2525 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2526 struct todo_item
*item
)
2528 return todo_list
->buf
.buf
+ item
->arg_offset
;
2531 static int is_command(enum todo_command command
, const char **bol
)
2533 const char *str
= todo_command_info
[command
].str
;
2534 const char nick
= todo_command_info
[command
].c
;
2535 const char *p
= *bol
;
2537 return (skip_prefix(p
, str
, &p
) || (nick
&& *p
++ == nick
)) &&
2538 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2542 static int check_label_or_ref_arg(enum todo_command command
, const char *arg
)
2547 * '#' is not a valid label as the merge command uses it to
2548 * separate merge parents from the commit subject.
2550 if (!strcmp(arg
, "#") ||
2551 check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2552 return error(_("'%s' is not a valid label"), arg
);
2555 case TODO_UPDATE_REF
:
2556 if (check_refname_format(arg
, REFNAME_ALLOW_ONELEVEL
))
2557 return error(_("'%s' is not a valid refname"), arg
);
2558 if (check_refname_format(arg
, 0))
2559 return error(_("update-ref requires a fully qualified "
2560 "refname e.g. refs/heads/%s"), arg
);
2564 BUG("unexpected todo_command");
2570 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2571 const char *buf
, const char *bol
, char *eol
)
2573 struct object_id commit_oid
;
2574 char *end_of_object_name
;
2575 int i
, saved
, status
, padding
;
2580 bol
+= strspn(bol
, " \t");
2582 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2583 item
->command
= TODO_COMMENT
;
2584 item
->commit
= NULL
;
2585 item
->arg_offset
= bol
- buf
;
2586 item
->arg_len
= eol
- bol
;
2590 for (i
= 0; i
< TODO_COMMENT
; i
++)
2591 if (is_command(i
, &bol
)) {
2595 if (i
>= TODO_COMMENT
)
2596 return error(_("invalid command '%.*s'"),
2597 (int)strcspn(bol
, " \t\r\n"), bol
);
2599 /* Eat up extra spaces/ tabs before object name */
2600 padding
= strspn(bol
, " \t");
2603 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2605 return error(_("%s does not accept arguments: '%s'"),
2606 command_to_string(item
->command
), bol
);
2607 item
->commit
= NULL
;
2608 item
->arg_offset
= bol
- buf
;
2609 item
->arg_len
= eol
- bol
;
2614 return error(_("missing arguments for %s"),
2615 command_to_string(item
->command
));
2617 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2618 item
->command
== TODO_RESET
|| item
->command
== TODO_UPDATE_REF
) {
2621 item
->commit
= NULL
;
2622 item
->arg_offset
= bol
- buf
;
2623 item
->arg_len
= (int)(eol
- bol
);
2624 if (item
->command
== TODO_LABEL
||
2625 item
->command
== TODO_UPDATE_REF
) {
2628 ret
= check_label_or_ref_arg(item
->command
, bol
);
2634 if (item
->command
== TODO_FIXUP
) {
2635 if (skip_prefix(bol
, "-C", &bol
)) {
2636 bol
+= strspn(bol
, " \t");
2637 item
->flags
|= TODO_REPLACE_FIXUP_MSG
;
2638 } else if (skip_prefix(bol
, "-c", &bol
)) {
2639 bol
+= strspn(bol
, " \t");
2640 item
->flags
|= TODO_EDIT_FIXUP_MSG
;
2644 if (item
->command
== TODO_MERGE
) {
2645 if (skip_prefix(bol
, "-C", &bol
))
2646 bol
+= strspn(bol
, " \t");
2647 else if (skip_prefix(bol
, "-c", &bol
)) {
2648 bol
+= strspn(bol
, " \t");
2649 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2651 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2652 item
->commit
= NULL
;
2653 item
->arg_offset
= bol
- buf
;
2654 item
->arg_len
= (int)(eol
- bol
);
2659 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2660 saved
= *end_of_object_name
;
2661 *end_of_object_name
= '\0';
2662 status
= repo_get_oid(r
, bol
, &commit_oid
);
2664 error(_("could not parse '%s'"), bol
); /* return later */
2665 *end_of_object_name
= saved
;
2667 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2668 item
->arg_offset
= bol
- buf
;
2669 item
->arg_len
= (int)(eol
- bol
);
2674 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2675 return item
->commit
? 0 : -1;
2678 int sequencer_get_last_command(struct repository
*r UNUSED
, enum replay_action
*action
)
2680 const char *todo_file
, *bol
;
2681 struct strbuf buf
= STRBUF_INIT
;
2684 todo_file
= git_path_todo_file();
2685 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2686 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2689 return error_errno("unable to open '%s'", todo_file
);
2691 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2692 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2693 *action
= REPLAY_PICK
;
2694 else if (is_command(TODO_REVERT
, &bol
) &&
2695 (*bol
== ' ' || *bol
== '\t'))
2696 *action
= REPLAY_REVERT
;
2700 strbuf_release(&buf
);
2705 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2706 struct todo_list
*todo_list
)
2708 struct todo_item
*item
;
2709 char *p
= buf
, *next_p
;
2710 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2712 todo_list
->current
= todo_list
->nr
= todo_list
->total_nr
= 0;
2714 for (i
= 1; *p
; i
++, p
= next_p
) {
2715 char *eol
= strchrnul(p
, '\n');
2717 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2719 if (p
!= eol
&& eol
[-1] == '\r')
2720 eol
--; /* strip Carriage Return */
2722 item
= append_new_todo(todo_list
);
2723 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2724 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2725 res
= error(_("invalid line %d: %.*s"),
2726 i
, (int)(eol
- p
), p
);
2727 item
->command
= TODO_COMMENT
+ 1;
2728 item
->arg_offset
= p
- buf
;
2729 item
->arg_len
= (int)(eol
- p
);
2730 item
->commit
= NULL
;
2733 if (item
->command
!= TODO_COMMENT
)
2734 todo_list
->total_nr
++;
2738 else if (is_fixup(item
->command
))
2739 res
= error(_("cannot '%s' without a previous commit"),
2740 command_to_string(item
->command
));
2741 else if (!is_noop(item
->command
))
2748 static int count_commands(struct todo_list
*todo_list
)
2752 for (i
= 0; i
< todo_list
->nr
; i
++)
2753 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2759 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2761 return index
< todo_list
->nr
?
2762 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2765 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2767 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2770 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2772 return get_item_line_offset(todo_list
, index
+ 1)
2773 - get_item_line_offset(todo_list
, index
);
2776 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2781 fd
= open(path
, O_RDONLY
);
2783 return error_errno(_("could not open '%s'"), path
);
2784 len
= strbuf_read(sb
, fd
, 0);
2787 return error(_("could not read '%s'."), path
);
2791 static int have_finished_the_last_pick(void)
2793 struct strbuf buf
= STRBUF_INIT
;
2795 const char *todo_path
= git_path_todo_file();
2798 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2799 if (errno
== ENOENT
) {
2802 error_errno("unable to open '%s'", todo_path
);
2806 /* If there is only one line then we are done */
2807 eol
= strchr(buf
.buf
, '\n');
2808 if (!eol
|| !eol
[1])
2811 strbuf_release(&buf
);
2816 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2818 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2819 int need_cleanup
= 0;
2821 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2822 if (!refs_delete_ref(get_main_ref_store(r
), "",
2823 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
) &&
2825 warning(_("cancelling a cherry picking in progress"));
2826 opts
.action
= REPLAY_PICK
;
2830 if (refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
2831 if (!refs_delete_ref(get_main_ref_store(r
), "", "REVERT_HEAD",
2832 NULL
, REF_NO_DEREF
) &&
2834 warning(_("cancelling a revert in progress"));
2835 opts
.action
= REPLAY_REVERT
;
2839 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
2840 NULL
, REF_NO_DEREF
);
2845 if (!have_finished_the_last_pick())
2848 sequencer_remove_state(&opts
);
2851 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2853 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2856 fprintf(f
, "%d\n", todo_list
->total_nr
);
2861 static int read_populate_todo(struct repository
*r
,
2862 struct todo_list
*todo_list
,
2863 struct replay_opts
*opts
)
2865 const char *todo_file
= get_todo_path(opts
);
2868 strbuf_reset(&todo_list
->buf
);
2869 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2872 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2874 if (is_rebase_i(opts
))
2875 return error(_("please fix this using "
2876 "'git rebase --edit-todo'."));
2877 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2880 if (!todo_list
->nr
&&
2881 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2882 return error(_("no commits parsed."));
2884 if (!is_rebase_i(opts
)) {
2885 enum todo_command valid
=
2886 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2889 for (i
= 0; i
< todo_list
->nr
; i
++)
2890 if (valid
== todo_list
->items
[i
].command
)
2892 else if (valid
== TODO_PICK
)
2893 return error(_("cannot cherry-pick during a revert."));
2895 return error(_("cannot revert during a cherry-pick."));
2898 if (is_rebase_i(opts
)) {
2899 struct todo_list done
= TODO_LIST_INIT
;
2901 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2902 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2903 todo_list
->done_nr
= count_commands(&done
);
2905 todo_list
->done_nr
= 0;
2907 todo_list
->total_nr
= todo_list
->done_nr
2908 + count_commands(todo_list
);
2909 todo_list_release(&done
);
2911 todo_list_write_total_nr(todo_list
);
2917 static int git_config_string_dup(char **dest
,
2918 const char *var
, const char *value
)
2921 return config_error_nonbool(var
);
2923 *dest
= xstrdup(value
);
2927 static int populate_opts_cb(const char *key
, const char *value
,
2928 const struct config_context
*ctx
,
2931 struct replay_opts
*opts
= data
;
2936 else if (!strcmp(key
, "options.no-commit"))
2937 opts
->no_commit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2938 else if (!strcmp(key
, "options.edit"))
2939 opts
->edit
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2940 else if (!strcmp(key
, "options.allow-empty"))
2942 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2943 else if (!strcmp(key
, "options.allow-empty-message"))
2944 opts
->allow_empty_message
=
2945 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2946 else if (!strcmp(key
, "options.keep-redundant-commits"))
2947 opts
->keep_redundant_commits
=
2948 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2949 else if (!strcmp(key
, "options.signoff"))
2950 opts
->signoff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2951 else if (!strcmp(key
, "options.record-origin"))
2952 opts
->record_origin
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2953 else if (!strcmp(key
, "options.allow-ff"))
2954 opts
->allow_ff
= git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
);
2955 else if (!strcmp(key
, "options.mainline"))
2956 opts
->mainline
= git_config_int(key
, value
, ctx
->kvi
);
2957 else if (!strcmp(key
, "options.strategy"))
2958 git_config_string_dup(&opts
->strategy
, key
, value
);
2959 else if (!strcmp(key
, "options.gpg-sign"))
2960 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2961 else if (!strcmp(key
, "options.strategy-option")) {
2962 strvec_push(&opts
->xopts
, value
);
2963 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2964 opts
->allow_rerere_auto
=
2965 git_config_bool_or_int(key
, value
, ctx
->kvi
, &error_flag
) ?
2966 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2967 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2968 opts
->explicit_cleanup
= 1;
2969 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2971 return error(_("invalid key: %s"), key
);
2974 return error(_("invalid value for '%s': '%s'"), key
, value
);
2979 static void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2984 char *strategy_opts_string
= raw_opts
;
2986 if (*strategy_opts_string
== ' ')
2987 strategy_opts_string
++;
2989 count
= split_cmdline(strategy_opts_string
, &argv
);
2991 BUG("could not split '%s': %s", strategy_opts_string
,
2992 split_cmdline_strerror(count
));
2993 for (i
= 0; i
< count
; i
++) {
2994 const char *arg
= argv
[i
];
2996 skip_prefix(arg
, "--", &arg
);
2997 strvec_push(&opts
->xopts
, arg
);
3002 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
3005 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
3007 opts
->strategy
= strbuf_detach(buf
, NULL
);
3008 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
3011 parse_strategy_opts(opts
, buf
->buf
);
3014 static int read_populate_opts(struct replay_opts
*opts
)
3016 if (is_rebase_i(opts
)) {
3017 struct strbuf buf
= STRBUF_INIT
;
3020 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
3021 READ_ONELINER_SKIP_IF_EMPTY
)) {
3022 if (!starts_with(buf
.buf
, "-S"))
3025 free(opts
->gpg_sign
);
3026 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
3031 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
3032 READ_ONELINER_SKIP_IF_EMPTY
)) {
3033 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
3034 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
3035 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
3036 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
3040 if (file_exists(rebase_path_verbose()))
3043 if (file_exists(rebase_path_quiet()))
3046 if (file_exists(rebase_path_signoff())) {
3051 if (file_exists(rebase_path_cdate_is_adate())) {
3053 opts
->committer_date_is_author_date
= 1;
3056 if (file_exists(rebase_path_ignore_date())) {
3058 opts
->ignore_date
= 1;
3061 if (file_exists(rebase_path_reschedule_failed_exec()))
3062 opts
->reschedule_failed_exec
= 1;
3063 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3064 opts
->reschedule_failed_exec
= 0;
3066 if (file_exists(rebase_path_drop_redundant_commits()))
3067 opts
->drop_redundant_commits
= 1;
3069 if (file_exists(rebase_path_keep_redundant_commits()))
3070 opts
->keep_redundant_commits
= 1;
3072 read_strategy_opts(opts
, &buf
);
3075 if (read_oneliner(&opts
->current_fixups
,
3076 rebase_path_current_fixups(),
3077 READ_ONELINER_SKIP_IF_EMPTY
)) {
3078 const char *p
= opts
->current_fixups
.buf
;
3079 opts
->current_fixup_count
= 1;
3080 while ((p
= strchr(p
, '\n'))) {
3081 opts
->current_fixup_count
++;
3086 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
3087 if (repo_get_oid_committish(the_repository
, buf
.buf
, &opts
->squash_onto
) < 0) {
3088 ret
= error(_("unusable squash-onto"));
3091 opts
->have_squash_onto
= 1;
3095 strbuf_release(&buf
);
3099 if (!file_exists(git_path_opts_file()))
3102 * The function git_parse_source(), called from git_config_from_file(),
3103 * may die() in case of a syntactically incorrect file. We do not care
3104 * about this case, though, because we wrote that file ourselves, so we
3105 * are pretty certain that it is syntactically correct.
3107 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
3108 return error(_("malformed options sheet: '%s'"),
3109 git_path_opts_file());
3113 static void write_strategy_opts(struct replay_opts
*opts
)
3115 struct strbuf buf
= STRBUF_INIT
;
3118 * Quote strategy options so that they can be read correctly
3119 * by split_cmdline().
3121 quote_cmdline(&buf
, opts
->xopts
.v
);
3122 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
3123 strbuf_release(&buf
);
3126 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
3127 struct commit
*onto
, const struct object_id
*orig_head
)
3130 write_file(rebase_path_head_name(), "%s\n", head_name
);
3132 write_file(rebase_path_onto(), "%s\n",
3133 oid_to_hex(&onto
->object
.oid
));
3135 write_file(rebase_path_orig_head(), "%s\n",
3136 oid_to_hex(orig_head
));
3139 write_file(rebase_path_quiet(), "%s", "");
3141 write_file(rebase_path_verbose(), "%s", "");
3143 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
3144 if (opts
->xopts
.nr
> 0)
3145 write_strategy_opts(opts
);
3147 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
3148 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3149 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
3150 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3153 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
3155 write_file(rebase_path_signoff(), "--signoff\n");
3156 if (opts
->drop_redundant_commits
)
3157 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3158 if (opts
->keep_redundant_commits
)
3159 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3160 if (opts
->committer_date_is_author_date
)
3161 write_file(rebase_path_cdate_is_adate(), "%s", "");
3162 if (opts
->ignore_date
)
3163 write_file(rebase_path_ignore_date(), "%s", "");
3164 if (opts
->reschedule_failed_exec
)
3165 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3167 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3172 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
3173 struct replay_opts
*opts
)
3175 enum todo_command command
= opts
->action
== REPLAY_PICK
?
3176 TODO_PICK
: TODO_REVERT
;
3177 const char *command_string
= todo_command_info
[command
].str
;
3178 const char *encoding
;
3179 struct commit
*commit
;
3181 if (prepare_revs(opts
))
3184 encoding
= get_log_output_encoding();
3186 while ((commit
= get_revision(opts
->revs
))) {
3187 struct todo_item
*item
= append_new_todo(todo_list
);
3188 const char *commit_buffer
= repo_logmsg_reencode(the_repository
,
3191 const char *subject
;
3194 item
->command
= command
;
3195 item
->commit
= commit
;
3196 item
->arg_offset
= 0;
3198 item
->offset_in_buf
= todo_list
->buf
.len
;
3199 subject_len
= find_commit_subject(commit_buffer
, &subject
);
3200 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
3201 short_commit_name(the_repository
, commit
),
3202 subject_len
, subject
);
3203 repo_unuse_commit_buffer(the_repository
, commit
,
3208 return error(_("empty commit set passed"));
3213 static int create_seq_dir(struct repository
*r
)
3215 enum replay_action action
;
3216 const char *in_progress_error
= NULL
;
3217 const char *in_progress_advice
= NULL
;
3218 unsigned int advise_skip
=
3219 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD") ||
3220 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
3222 if (!sequencer_get_last_command(r
, &action
)) {
3225 in_progress_error
= _("revert is already in progress");
3226 in_progress_advice
=
3227 _("try \"git revert (--continue | %s--abort | --quit)\"");
3230 in_progress_error
= _("cherry-pick is already in progress");
3231 in_progress_advice
=
3232 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3235 BUG("unexpected action in create_seq_dir");
3238 if (in_progress_error
) {
3239 error("%s", in_progress_error
);
3240 if (advice_enabled(ADVICE_SEQUENCER_IN_USE
))
3241 advise(in_progress_advice
,
3242 advise_skip
? "--skip | " : "");
3245 if (mkdir(git_path_seq_dir(), 0777) < 0)
3246 return error_errno(_("could not create sequencer directory '%s'"),
3247 git_path_seq_dir());
3252 static int save_head(const char *head
)
3254 return write_message(head
, strlen(head
), git_path_head_file(), 1);
3257 static int rollback_is_safe(void)
3259 struct strbuf sb
= STRBUF_INIT
;
3260 struct object_id expected_head
, actual_head
;
3262 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
3264 if (get_oid_hex(sb
.buf
, &expected_head
)) {
3265 strbuf_release(&sb
);
3266 die(_("could not parse %s"), git_path_abort_safety_file());
3268 strbuf_release(&sb
);
3270 else if (errno
== ENOENT
)
3271 oidclr(&expected_head
);
3273 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3275 if (repo_get_oid(the_repository
, "HEAD", &actual_head
))
3276 oidclr(&actual_head
);
3278 return oideq(&actual_head
, &expected_head
);
3281 static int reset_merge(const struct object_id
*oid
)
3283 struct child_process cmd
= CHILD_PROCESS_INIT
;
3286 strvec_pushl(&cmd
.args
, "reset", "--merge", NULL
);
3288 if (!is_null_oid(oid
))
3289 strvec_push(&cmd
.args
, oid_to_hex(oid
));
3291 return run_command(&cmd
);
3294 static int rollback_single_pick(struct repository
*r
)
3296 struct object_id head_oid
;
3298 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
3299 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
3300 return error(_("no cherry-pick or revert in progress"));
3301 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
3302 return error(_("cannot resolve HEAD"));
3303 if (is_null_oid(&head_oid
))
3304 return error(_("cannot abort from a branch yet to be born"));
3305 return reset_merge(&head_oid
);
3308 static int skip_single_pick(void)
3310 struct object_id head
;
3312 if (read_ref_full("HEAD", 0, &head
, NULL
))
3313 return error(_("cannot resolve HEAD"));
3314 return reset_merge(&head
);
3317 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
3320 struct object_id oid
;
3321 struct strbuf buf
= STRBUF_INIT
;
3324 f
= fopen(git_path_head_file(), "r");
3325 if (!f
&& errno
== ENOENT
) {
3327 * There is no multiple-cherry-pick in progress.
3328 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3329 * a single-cherry-pick in progress, abort that.
3331 return rollback_single_pick(r
);
3334 return error_errno(_("cannot open '%s'"), git_path_head_file());
3335 if (strbuf_getline_lf(&buf
, f
)) {
3336 error(_("cannot read '%s': %s"), git_path_head_file(),
3337 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
3342 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
3343 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3344 git_path_head_file());
3347 if (is_null_oid(&oid
)) {
3348 error(_("cannot abort from a branch yet to be born"));
3352 if (!rollback_is_safe()) {
3353 /* Do not error, just do not rollback */
3354 warning(_("You seem to have moved HEAD. "
3355 "Not rewinding, check your HEAD!"));
3357 if (reset_merge(&oid
))
3359 strbuf_release(&buf
);
3360 return sequencer_remove_state(opts
);
3362 strbuf_release(&buf
);
3366 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
3368 enum replay_action action
= -1;
3369 sequencer_get_last_command(r
, &action
);
3372 * Check whether the subcommand requested to skip the commit is actually
3373 * in progress and that it's safe to skip the commit.
3375 * opts->action tells us which subcommand requested to skip the commit.
3376 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3377 * action is in progress and we can skip the commit.
3379 * Otherwise we check that the last instruction was related to the
3380 * particular subcommand we're trying to execute and barf if that's not
3383 * Finally we check that the rollback is "safe", i.e., has the HEAD
3384 * moved? In this case, it doesn't make sense to "reset the merge" and
3385 * "skip the commit" as the user already handled this by committing. But
3386 * we'd not want to barf here, instead give advice on how to proceed. We
3387 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3388 * it gets removed when the user commits, so if it still exists we're
3389 * sure the user can't have committed before.
3391 switch (opts
->action
) {
3393 if (!refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
3394 if (action
!= REPLAY_REVERT
)
3395 return error(_("no revert in progress"));
3396 if (!rollback_is_safe())
3401 if (!refs_ref_exists(get_main_ref_store(r
),
3402 "CHERRY_PICK_HEAD")) {
3403 if (action
!= REPLAY_PICK
)
3404 return error(_("no cherry-pick in progress"));
3405 if (!rollback_is_safe())
3410 BUG("unexpected action in sequencer_skip");
3413 if (skip_single_pick())
3414 return error(_("failed to skip the commit"));
3415 if (!is_directory(git_path_seq_dir()))
3418 return sequencer_continue(r
, opts
);
3421 error(_("there is nothing to skip"));
3423 if (advice_enabled(ADVICE_RESOLVE_CONFLICT
)) {
3424 advise(_("have you committed already?\n"
3425 "try \"git %s --continue\""),
3426 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
3431 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
,
3434 struct lock_file todo_lock
= LOCK_INIT
;
3435 const char *todo_path
= get_todo_path(opts
);
3436 int next
= todo_list
->current
, offset
, fd
;
3439 * rebase -i writes "git-rebase-todo" without the currently executing
3440 * command, appending it to "done" instead.
3442 if (is_rebase_i(opts
) && !reschedule
)
3445 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
3447 return error_errno(_("could not lock '%s'"), todo_path
);
3448 offset
= get_item_line_offset(todo_list
, next
);
3449 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
3450 todo_list
->buf
.len
- offset
) < 0)
3451 return error_errno(_("could not write to '%s'"), todo_path
);
3452 if (commit_lock_file(&todo_lock
) < 0)
3453 return error(_("failed to finalize '%s'"), todo_path
);
3455 if (is_rebase_i(opts
) && !reschedule
&& next
> 0) {
3456 const char *done
= rebase_path_done();
3457 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
3462 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
3463 get_item_line_length(todo_list
, next
- 1))
3465 ret
= error_errno(_("could not write to '%s'"), done
);
3467 ret
= error_errno(_("failed to finalize '%s'"), done
);
3473 static int save_opts(struct replay_opts
*opts
)
3475 const char *opts_file
= git_path_opts_file();
3478 if (opts
->no_commit
)
3479 res
|= git_config_set_in_file_gently(opts_file
,
3480 "options.no-commit", "true");
3481 if (opts
->edit
>= 0)
3482 res
|= git_config_set_in_file_gently(opts_file
, "options.edit",
3483 opts
->edit
? "true" : "false");
3484 if (opts
->allow_empty
)
3485 res
|= git_config_set_in_file_gently(opts_file
,
3486 "options.allow-empty", "true");
3487 if (opts
->allow_empty_message
)
3488 res
|= git_config_set_in_file_gently(opts_file
,
3489 "options.allow-empty-message", "true");
3490 if (opts
->keep_redundant_commits
)
3491 res
|= git_config_set_in_file_gently(opts_file
,
3492 "options.keep-redundant-commits", "true");
3494 res
|= git_config_set_in_file_gently(opts_file
,
3495 "options.signoff", "true");
3496 if (opts
->record_origin
)
3497 res
|= git_config_set_in_file_gently(opts_file
,
3498 "options.record-origin", "true");
3500 res
|= git_config_set_in_file_gently(opts_file
,
3501 "options.allow-ff", "true");
3502 if (opts
->mainline
) {
3503 struct strbuf buf
= STRBUF_INIT
;
3504 strbuf_addf(&buf
, "%d", opts
->mainline
);
3505 res
|= git_config_set_in_file_gently(opts_file
,
3506 "options.mainline", buf
.buf
);
3507 strbuf_release(&buf
);
3510 res
|= git_config_set_in_file_gently(opts_file
,
3511 "options.strategy", opts
->strategy
);
3513 res
|= git_config_set_in_file_gently(opts_file
,
3514 "options.gpg-sign", opts
->gpg_sign
);
3515 for (size_t i
= 0; i
< opts
->xopts
.nr
; i
++)
3516 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3517 "options.strategy-option",
3518 opts
->xopts
.v
[i
], "^$", 0);
3519 if (opts
->allow_rerere_auto
)
3520 res
|= git_config_set_in_file_gently(opts_file
,
3521 "options.allow-rerere-auto",
3522 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3525 if (opts
->explicit_cleanup
)
3526 res
|= git_config_set_in_file_gently(opts_file
,
3527 "options.default-msg-cleanup",
3528 describe_cleanup_mode(opts
->default_msg_cleanup
));
3532 static int make_patch(struct repository
*r
,
3533 struct commit
*commit
,
3534 struct replay_opts
*opts
)
3536 struct rev_info log_tree_opt
;
3537 const char *subject
;
3538 char hex
[GIT_MAX_HEXSZ
+ 1];
3541 if (!is_rebase_i(opts
))
3542 BUG("make_patch should only be called when rebasing");
3544 oid_to_hex_r(hex
, &commit
->object
.oid
);
3545 if (write_message(hex
, strlen(hex
), rebase_path_stopped_sha(), 1) < 0)
3547 res
|= write_rebase_head(&commit
->object
.oid
);
3549 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3550 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3551 log_tree_opt
.abbrev
= 0;
3552 log_tree_opt
.diff
= 1;
3553 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3554 log_tree_opt
.disable_stdin
= 1;
3555 log_tree_opt
.no_commit_id
= 1;
3556 log_tree_opt
.diffopt
.file
= fopen(rebase_path_patch(), "w");
3557 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3558 if (!log_tree_opt
.diffopt
.file
)
3559 res
|= error_errno(_("could not open '%s'"),
3560 rebase_path_patch());
3562 res
|= log_tree_commit(&log_tree_opt
, commit
);
3563 fclose(log_tree_opt
.diffopt
.file
);
3566 if (!file_exists(rebase_path_message())) {
3567 const char *encoding
= get_commit_output_encoding();
3568 const char *commit_buffer
= repo_logmsg_reencode(r
,
3571 find_commit_subject(commit_buffer
, &subject
);
3572 res
|= write_message(subject
, strlen(subject
), rebase_path_message(), 1);
3573 repo_unuse_commit_buffer(r
, commit
,
3576 release_revisions(&log_tree_opt
);
3581 static int intend_to_amend(void)
3583 struct object_id head
;
3586 if (repo_get_oid(the_repository
, "HEAD", &head
))
3587 return error(_("cannot read HEAD"));
3589 p
= oid_to_hex(&head
);
3590 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3593 static int error_with_patch(struct repository
*r
,
3594 struct commit
*commit
,
3595 const char *subject
, int subject_len
,
3596 struct replay_opts
*opts
,
3597 int exit_code
, int to_amend
)
3600 if (make_patch(r
, commit
, opts
))
3602 } else if (copy_file(rebase_path_message(),
3603 git_path_merge_msg(r
), 0666))
3604 return error(_("unable to copy '%s' to '%s'"),
3605 git_path_merge_msg(r
), rebase_path_message());
3608 if (intend_to_amend())
3612 _("You can amend the commit now, with\n"
3614 " git commit --amend %s\n"
3616 "Once you are satisfied with your changes, run\n"
3618 " git rebase --continue\n"),
3619 gpg_sign_opt_quoted(opts
));
3620 } else if (exit_code
) {
3622 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3623 short_commit_name(r
, commit
), subject_len
, subject
);
3626 * We don't have the hash of the parent so
3627 * just print the line from the todo file.
3629 fprintf_ln(stderr
, _("Could not merge %.*s"),
3630 subject_len
, subject
);
3636 static int error_failed_squash(struct repository
*r
,
3637 struct commit
*commit
,
3638 struct replay_opts
*opts
,
3640 const char *subject
)
3642 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3643 return error(_("could not copy '%s' to '%s'"),
3644 rebase_path_squash_msg(), rebase_path_message());
3645 unlink(git_path_merge_msg(r
));
3646 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3647 return error(_("could not copy '%s' to '%s'"),
3648 rebase_path_message(),
3649 git_path_merge_msg(r
));
3650 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3653 static int do_exec(struct repository
*r
, const char *command_line
)
3655 struct child_process cmd
= CHILD_PROCESS_INIT
;
3658 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3660 strvec_push(&cmd
.args
, command_line
);
3661 strvec_push(&cmd
.env
, "GIT_CHERRY_PICK_HELP");
3662 status
= run_command(&cmd
);
3664 /* force re-reading of the cache */
3665 discard_index(r
->index
);
3666 if (repo_read_index(r
) < 0)
3667 return error(_("could not read index"));
3669 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3672 warning(_("execution failed: %s\n%s"
3673 "You can fix the problem, and then run\n"
3675 " git rebase --continue\n"
3678 dirty
? _("and made changes to the index and/or the "
3679 "working tree.\n") : "");
3681 /* command not found */
3684 warning(_("execution succeeded: %s\nbut "
3685 "left changes to the index and/or the working tree.\n"
3686 "Commit or stash your changes, and then run\n"
3688 " git rebase --continue\n"
3689 "\n"), command_line
);
3696 __attribute__((format (printf
, 2, 3)))
3697 static int safe_append(const char *filename
, const char *fmt
, ...)
3700 struct lock_file lock
= LOCK_INIT
;
3701 int fd
= hold_lock_file_for_update(&lock
, filename
,
3702 LOCK_REPORT_ON_ERROR
);
3703 struct strbuf buf
= STRBUF_INIT
;
3708 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3709 error_errno(_("could not read '%s'"), filename
);
3710 rollback_lock_file(&lock
);
3713 strbuf_complete(&buf
, '\n');
3715 strbuf_vaddf(&buf
, fmt
, ap
);
3718 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3719 error_errno(_("could not write to '%s'"), filename
);
3720 strbuf_release(&buf
);
3721 rollback_lock_file(&lock
);
3724 if (commit_lock_file(&lock
) < 0) {
3725 strbuf_release(&buf
);
3726 return error(_("failed to finalize '%s'"), filename
);
3729 strbuf_release(&buf
);
3733 static int do_label(struct repository
*r
, const char *name
, int len
)
3735 struct ref_store
*refs
= get_main_ref_store(r
);
3736 struct ref_transaction
*transaction
;
3737 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3738 struct strbuf msg
= STRBUF_INIT
;
3740 struct object_id head_oid
;
3742 if (len
== 1 && *name
== '#')
3743 return error(_("illegal label name: '%.*s'"), len
, name
);
3745 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3746 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3748 transaction
= ref_store_transaction_begin(refs
, &err
);
3750 error("%s", err
.buf
);
3752 } else if (repo_get_oid(r
, "HEAD", &head_oid
)) {
3753 error(_("could not read HEAD"));
3755 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3756 NULL
, 0, msg
.buf
, &err
) < 0 ||
3757 ref_transaction_commit(transaction
, &err
)) {
3758 error("%s", err
.buf
);
3761 ref_transaction_free(transaction
);
3762 strbuf_release(&err
);
3763 strbuf_release(&msg
);
3766 ret
= safe_append(rebase_path_refs_to_delete(),
3767 "%s\n", ref_name
.buf
);
3768 strbuf_release(&ref_name
);
3773 static const char *sequencer_reflog_action(struct replay_opts
*opts
)
3775 if (!opts
->reflog_action
) {
3776 opts
->reflog_action
= getenv(GIT_REFLOG_ACTION
);
3777 opts
->reflog_action
=
3778 xstrdup(opts
->reflog_action
? opts
->reflog_action
3779 : action_name(opts
));
3782 return opts
->reflog_action
;
3785 __attribute__((format (printf
, 3, 4)))
3786 static const char *reflog_message(struct replay_opts
*opts
,
3787 const char *sub_action
, const char *fmt
, ...)
3790 static struct strbuf buf
= STRBUF_INIT
;
3794 strbuf_addstr(&buf
, sequencer_reflog_action(opts
));
3796 strbuf_addf(&buf
, " (%s)", sub_action
);
3798 strbuf_addstr(&buf
, ": ");
3799 strbuf_vaddf(&buf
, fmt
, ap
);
3806 static struct commit
*lookup_label(struct repository
*r
, const char *label
,
3807 int len
, struct strbuf
*buf
)
3809 struct commit
*commit
;
3810 struct object_id oid
;
3813 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3814 if (!read_ref(buf
->buf
, &oid
)) {
3815 commit
= lookup_commit_object(r
, &oid
);
3817 /* fall back to non-rewritten ref or commit */
3818 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3819 commit
= lookup_commit_reference_by_name(buf
->buf
);
3823 error(_("could not resolve '%s'"), buf
->buf
);
3828 static int do_reset(struct repository
*r
,
3829 const char *name
, int len
,
3830 struct replay_opts
*opts
)
3832 struct strbuf ref_name
= STRBUF_INIT
;
3833 struct object_id oid
;
3834 struct lock_file lock
= LOCK_INIT
;
3835 struct tree_desc desc
= { 0 };
3837 struct unpack_trees_options unpack_tree_opts
= { 0 };
3840 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3843 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3844 if (!opts
->have_squash_onto
) {
3846 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3847 NULL
, &opts
->squash_onto
,
3849 return error(_("writing fake root commit"));
3850 opts
->have_squash_onto
= 1;
3851 hex
= oid_to_hex(&opts
->squash_onto
);
3852 if (write_message(hex
, strlen(hex
),
3853 rebase_path_squash_onto(), 0))
3854 return error(_("writing squash-onto"));
3856 oidcpy(&oid
, &opts
->squash_onto
);
3859 struct commit
*commit
;
3861 /* Determine the length of the label */
3862 for (i
= 0; i
< len
; i
++)
3863 if (isspace(name
[i
]))
3867 commit
= lookup_label(r
, name
, len
, &ref_name
);
3872 oid
= commit
->object
.oid
;
3875 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3876 unpack_tree_opts
.head_idx
= 1;
3877 unpack_tree_opts
.src_index
= r
->index
;
3878 unpack_tree_opts
.dst_index
= r
->index
;
3879 unpack_tree_opts
.fn
= oneway_merge
;
3880 unpack_tree_opts
.merge
= 1;
3881 unpack_tree_opts
.update
= 1;
3882 unpack_tree_opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
3883 unpack_tree_opts
.skip_cache_tree_update
= 1;
3884 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3886 if (repo_read_index_unmerged(r
)) {
3887 ret
= error_resolve_conflict(action_name(opts
));
3891 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3892 ret
= error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3896 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3901 tree
= parse_tree_indirect(&oid
);
3903 return error(_("unable to read tree (%s)"), oid_to_hex(&oid
));
3904 prime_cache_tree(r
, r
->index
, tree
);
3906 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3907 ret
= error(_("could not write index"));
3910 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3911 len
, name
), "HEAD", &oid
,
3912 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3914 free((void *)desc
.buffer
);
3916 rollback_lock_file(&lock
);
3917 strbuf_release(&ref_name
);
3918 clear_unpack_trees_porcelain(&unpack_tree_opts
);
3922 static int do_merge(struct repository
*r
,
3923 struct commit
*commit
,
3924 const char *arg
, int arg_len
,
3925 int flags
, int *check_todo
, struct replay_opts
*opts
)
3927 int run_commit_flags
= 0;
3928 struct strbuf ref_name
= STRBUF_INIT
;
3929 struct commit
*head_commit
, *merge_commit
, *i
;
3930 struct commit_list
*bases
= NULL
, *j
;
3931 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3932 const char *strategy
= !opts
->xopts
.nr
&&
3934 !strcmp(opts
->strategy
, "recursive") ||
3935 !strcmp(opts
->strategy
, "ort")) ?
3936 NULL
: opts
->strategy
;
3937 struct merge_options o
;
3938 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3939 static struct lock_file lock
;
3942 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3947 head_commit
= lookup_commit_reference_by_name("HEAD");
3949 ret
= error(_("cannot merge without a current revision"));
3954 * For octopus merges, the arg starts with the list of revisions to be
3955 * merged. The list is optionally followed by '#' and the oneline.
3957 merge_arg_len
= oneline_offset
= arg_len
;
3958 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3961 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3962 p
+= 1 + strspn(p
+ 1, " \t\n");
3963 oneline_offset
= p
- arg
;
3966 k
= strcspn(p
, " \t\n");
3969 merge_commit
= lookup_label(r
, p
, k
, &ref_name
);
3970 if (!merge_commit
) {
3971 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3974 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3976 merge_arg_len
= p
- arg
;
3980 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3984 if (opts
->have_squash_onto
&&
3985 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3987 * When the user tells us to "merge" something into a
3988 * "[new root]", let's simply fast-forward to the merge head.
3990 rollback_lock_file(&lock
);
3992 ret
= error(_("octopus merge cannot be executed on "
3993 "top of a [new root]"));
3995 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3996 &head_commit
->object
.oid
, 0,
4002 * If HEAD is not identical to the first parent of the original merge
4003 * commit, we cannot fast-forward.
4005 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
4006 oideq(&commit
->parents
->item
->object
.oid
,
4007 &head_commit
->object
.oid
);
4010 * If any merge head is different from the original one, we cannot
4013 if (can_fast_forward
) {
4014 struct commit_list
*p
= commit
->parents
->next
;
4016 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
4017 if (!oideq(&j
->item
->object
.oid
,
4018 &p
->item
->object
.oid
)) {
4019 can_fast_forward
= 0;
4023 * If the number of merge heads differs from the original merge
4024 * commit, we cannot fast-forward.
4027 can_fast_forward
= 0;
4030 if (can_fast_forward
) {
4031 rollback_lock_file(&lock
);
4032 ret
= fast_forward_to(r
, &commit
->object
.oid
,
4033 &head_commit
->object
.oid
, 0, opts
);
4034 if (flags
& TODO_EDIT_MERGE_MSG
)
4035 goto fast_forward_edit
;
4041 const char *encoding
= get_commit_output_encoding();
4042 const char *message
= repo_logmsg_reencode(r
, commit
, NULL
,
4048 ret
= error(_("could not get commit message of '%s'"),
4049 oid_to_hex(&commit
->object
.oid
));
4052 write_author_script(message
);
4053 find_commit_subject(message
, &body
);
4055 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
4056 repo_unuse_commit_buffer(r
, commit
, message
);
4058 error_errno(_("could not write '%s'"),
4059 git_path_merge_msg(r
));
4063 struct strbuf buf
= STRBUF_INIT
;
4066 strbuf_addf(&buf
, "author %s", git_author_info(0));
4067 write_author_script(buf
.buf
);
4070 if (oneline_offset
< arg_len
) {
4071 p
= arg
+ oneline_offset
;
4072 len
= arg_len
- oneline_offset
;
4074 strbuf_addf(&buf
, "Merge %s '%.*s'",
4075 to_merge
->next
? "branches" : "branch",
4076 merge_arg_len
, arg
);
4081 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
4082 strbuf_release(&buf
);
4084 error_errno(_("could not write '%s'"),
4085 git_path_merge_msg(r
));
4090 if (strategy
|| to_merge
->next
) {
4092 struct child_process cmd
= CHILD_PROCESS_INIT
;
4094 if (read_env_script(&cmd
.env
)) {
4095 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
4097 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
4101 if (opts
->committer_date_is_author_date
)
4102 strvec_pushf(&cmd
.env
, "GIT_COMMITTER_DATE=%s",
4105 author_date_from_env(&cmd
.env
));
4106 if (opts
->ignore_date
)
4107 strvec_push(&cmd
.env
, "GIT_AUTHOR_DATE=");
4110 strvec_push(&cmd
.args
, "merge");
4111 strvec_push(&cmd
.args
, "-s");
4113 strvec_push(&cmd
.args
, "octopus");
4115 strvec_push(&cmd
.args
, strategy
);
4116 for (k
= 0; k
< opts
->xopts
.nr
; k
++)
4117 strvec_pushf(&cmd
.args
,
4118 "-X%s", opts
->xopts
.v
[k
]);
4120 if (!(flags
& TODO_EDIT_MERGE_MSG
))
4121 strvec_push(&cmd
.args
, "--no-edit");
4123 strvec_push(&cmd
.args
, "--edit");
4124 strvec_push(&cmd
.args
, "--no-ff");
4125 strvec_push(&cmd
.args
, "--no-log");
4126 strvec_push(&cmd
.args
, "--no-stat");
4127 strvec_push(&cmd
.args
, "-F");
4128 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
4130 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
4132 strvec_push(&cmd
.args
, "--no-gpg-sign");
4134 /* Add the tips to be merged */
4135 for (j
= to_merge
; j
; j
= j
->next
)
4136 strvec_push(&cmd
.args
,
4137 oid_to_hex(&j
->item
->object
.oid
));
4139 strbuf_release(&ref_name
);
4140 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
4141 NULL
, REF_NO_DEREF
);
4142 rollback_lock_file(&lock
);
4144 ret
= run_command(&cmd
);
4146 /* force re-reading of the cache */
4148 discard_index(r
->index
);
4149 if (repo_read_index(r
) < 0)
4150 ret
= error(_("could not read index"));
4155 merge_commit
= to_merge
->item
;
4156 if (repo_get_merge_bases(r
, head_commit
, merge_commit
, &bases
) < 0) {
4161 if (bases
&& oideq(&merge_commit
->object
.oid
,
4162 &bases
->item
->object
.oid
)) {
4164 /* skip merging an ancestor of HEAD */
4168 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
4169 git_path_merge_head(r
), 0);
4170 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
4172 bases
= reverse_commit_list(bases
);
4175 init_merge_options(&o
, r
);
4177 o
.branch2
= ref_name
.buf
;
4178 o
.buffer_output
= 2;
4180 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "ort")) {
4182 * TODO: Should use merge_incore_recursive() and
4183 * merge_switch_to_result(), skipping the call to
4184 * merge_switch_to_result() when we don't actually need to
4185 * update the index and working copy immediately.
4187 ret
= merge_ort_recursive(&o
,
4188 head_commit
, merge_commit
, bases
,
4191 ret
= merge_recursive(&o
, head_commit
, merge_commit
, bases
,
4195 fputs(o
.obuf
.buf
, stdout
);
4196 strbuf_release(&o
.obuf
);
4198 error(_("could not even attempt to merge '%.*s'"),
4199 merge_arg_len
, arg
);
4200 unlink(git_path_merge_msg(r
));
4204 * The return value of merge_recursive() is 1 on clean, and 0 on
4207 * Let's reverse that, so that do_merge() returns 0 upon success and
4208 * 1 upon failed merge (keeping the return value -1 for the cases where
4209 * we will want to reschedule the `merge` command).
4213 if (r
->index
->cache_changed
&&
4214 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
4215 ret
= error(_("merge: Unable to write new index file"));
4219 rollback_lock_file(&lock
);
4221 repo_rerere(r
, opts
->allow_rerere_auto
);
4224 * In case of problems, we now want to return a positive
4225 * value (a negative one would indicate that the `merge`
4226 * command needs to be rescheduled).
4228 ret
= !!run_git_commit(git_path_merge_msg(r
), opts
,
4231 if (!ret
&& flags
& TODO_EDIT_MERGE_MSG
) {
4234 run_commit_flags
|= AMEND_MSG
| EDIT_MSG
| VERIFY_MSG
;
4235 ret
= !!run_git_commit(NULL
, opts
, run_commit_flags
);
4240 strbuf_release(&ref_name
);
4241 rollback_lock_file(&lock
);
4242 free_commit_list(to_merge
);
4246 static int write_update_refs_state(struct string_list
*refs_to_oids
)
4249 struct lock_file lock
= LOCK_INIT
;
4251 struct string_list_item
*item
;
4254 path
= rebase_path_update_refs(the_repository
->gitdir
);
4256 if (!refs_to_oids
->nr
) {
4257 if (unlink(path
) && errno
!= ENOENT
)
4258 result
= error_errno(_("could not unlink: %s"), path
);
4262 if (safe_create_leading_directories(path
)) {
4263 result
= error(_("unable to create leading directories of %s"),
4268 if (hold_lock_file_for_update(&lock
, path
, 0) < 0) {
4269 result
= error(_("another 'rebase' process appears to be running; "
4270 "'%s.lock' already exists"),
4275 fp
= fdopen_lock_file(&lock
, "w");
4277 result
= error_errno(_("could not open '%s' for writing"), path
);
4278 rollback_lock_file(&lock
);
4282 for_each_string_list_item(item
, refs_to_oids
) {
4283 struct update_ref_record
*rec
= item
->util
;
4284 fprintf(fp
, "%s\n%s\n%s\n", item
->string
,
4285 oid_to_hex(&rec
->before
), oid_to_hex(&rec
->after
));
4288 result
= commit_lock_file(&lock
);
4296 * Parse the update-refs file for the current rebase, then remove the
4297 * refs that do not appear in the todo_list (and have not had updated
4298 * values stored) and add refs that are in the todo_list but not
4299 * represented in the update-refs file.
4301 * If there are changes to the update-refs list, then write the new state
4304 void todo_list_filter_update_refs(struct repository
*r
,
4305 struct todo_list
*todo_list
)
4309 struct string_list update_refs
= STRING_LIST_INIT_DUP
;
4311 sequencer_get_update_refs_state(r
->gitdir
, &update_refs
);
4314 * For each item in the update_refs list, if it has no updated
4315 * value and does not appear in the todo_list, then remove it
4316 * from the update_refs list.
4318 for (i
= 0; i
< update_refs
.nr
; i
++) {
4321 const char *ref
= update_refs
.items
[i
].string
;
4322 size_t reflen
= strlen(ref
);
4323 struct update_ref_record
*rec
= update_refs
.items
[i
].util
;
4325 /* OID already stored as updated. */
4326 if (!is_null_oid(&rec
->after
))
4329 for (j
= 0; !found
&& j
< todo_list
->nr
; j
++) {
4330 struct todo_item
*item
= &todo_list
->items
[j
];
4331 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4333 if (item
->command
!= TODO_UPDATE_REF
)
4336 if (item
->arg_len
!= reflen
||
4337 strncmp(arg
, ref
, reflen
))
4344 free(update_refs
.items
[i
].string
);
4345 free(update_refs
.items
[i
].util
);
4348 MOVE_ARRAY(update_refs
.items
+ i
, update_refs
.items
+ i
+ 1, update_refs
.nr
- i
);
4356 * For each todo_item, check if its ref is in the update_refs list.
4357 * If not, then add it as an un-updated ref.
4359 for (i
= 0; i
< todo_list
->nr
; i
++) {
4360 struct todo_item
*item
= &todo_list
->items
[i
];
4361 const char *arg
= todo_list
->buf
.buf
+ item
->arg_offset
;
4364 if (item
->command
!= TODO_UPDATE_REF
)
4367 for (j
= 0; !found
&& j
< update_refs
.nr
; j
++) {
4368 const char *ref
= update_refs
.items
[j
].string
;
4370 found
= strlen(ref
) == item
->arg_len
&&
4371 !strncmp(ref
, arg
, item
->arg_len
);
4375 struct string_list_item
*inserted
;
4376 struct strbuf argref
= STRBUF_INIT
;
4378 strbuf_add(&argref
, arg
, item
->arg_len
);
4379 inserted
= string_list_insert(&update_refs
, argref
.buf
);
4380 inserted
->util
= init_update_ref_record(argref
.buf
);
4381 strbuf_release(&argref
);
4387 write_update_refs_state(&update_refs
);
4388 string_list_clear(&update_refs
, 1);
4391 static int do_update_ref(struct repository
*r
, const char *refname
)
4393 struct string_list_item
*item
;
4394 struct string_list list
= STRING_LIST_INIT_DUP
;
4396 if (sequencer_get_update_refs_state(r
->gitdir
, &list
))
4399 for_each_string_list_item(item
, &list
) {
4400 if (!strcmp(item
->string
, refname
)) {
4401 struct update_ref_record
*rec
= item
->util
;
4402 if (read_ref("HEAD", &rec
->after
))
4408 write_update_refs_state(&list
);
4409 string_list_clear(&list
, 1);
4413 static int do_update_refs(struct repository
*r
, int quiet
)
4416 struct string_list_item
*item
;
4417 struct string_list refs_to_oids
= STRING_LIST_INIT_DUP
;
4418 struct ref_store
*refs
= get_main_ref_store(r
);
4419 struct strbuf update_msg
= STRBUF_INIT
;
4420 struct strbuf error_msg
= STRBUF_INIT
;
4422 if ((res
= sequencer_get_update_refs_state(r
->gitdir
, &refs_to_oids
)))
4425 for_each_string_list_item(item
, &refs_to_oids
) {
4426 struct update_ref_record
*rec
= item
->util
;
4429 loop_res
= refs_update_ref(refs
, "rewritten during rebase",
4431 &rec
->after
, &rec
->before
,
4432 0, UPDATE_REFS_MSG_ON_ERR
);
4439 strbuf_addf(&error_msg
, "\t%s\n", item
->string
);
4441 strbuf_addf(&update_msg
, "\t%s\n", item
->string
);
4445 (update_msg
.len
|| error_msg
.len
)) {
4447 _("Updated the following refs with %s:\n%s"),
4453 _("Failed to update the following refs with %s:\n%s"),
4458 string_list_clear(&refs_to_oids
, 1);
4459 strbuf_release(&update_msg
);
4460 strbuf_release(&error_msg
);
4464 static int is_final_fixup(struct todo_list
*todo_list
)
4466 int i
= todo_list
->current
;
4468 if (!is_fixup(todo_list
->items
[i
].command
))
4471 while (++i
< todo_list
->nr
)
4472 if (is_fixup(todo_list
->items
[i
].command
))
4474 else if (!is_noop(todo_list
->items
[i
].command
))
4479 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
4483 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
4484 if (!is_noop(todo_list
->items
[i
].command
))
4485 return todo_list
->items
[i
].command
;
4490 static void create_autostash_internal(struct repository
*r
,
4492 const char *refname
)
4494 struct strbuf buf
= STRBUF_INIT
;
4495 struct lock_file lock_file
= LOCK_INIT
;
4498 if (path
&& refname
)
4499 BUG("can only pass path or refname");
4501 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
4502 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
4504 repo_update_index_if_able(r
, &lock_file
);
4505 rollback_lock_file(&lock_file
);
4507 if (has_unstaged_changes(r
, 1) ||
4508 has_uncommitted_changes(r
, 1)) {
4509 struct child_process stash
= CHILD_PROCESS_INIT
;
4510 struct reset_head_opts ropts
= { .flags
= RESET_HEAD_HARD
};
4511 struct object_id oid
;
4513 strvec_pushl(&stash
.args
,
4514 "stash", "create", "autostash", NULL
);
4518 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
4519 die(_("Cannot autostash"));
4520 strbuf_trim_trailing_newline(&buf
);
4521 if (repo_get_oid(r
, buf
.buf
, &oid
))
4522 die(_("Unexpected stash response: '%s'"),
4525 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
4528 if (safe_create_leading_directories_const(path
))
4529 die(_("Could not create directory for '%s'"),
4531 write_file(path
, "%s", oid_to_hex(&oid
));
4533 refs_update_ref(get_main_ref_store(r
), "", refname
,
4534 &oid
, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR
);
4537 printf(_("Created autostash: %s\n"), buf
.buf
);
4538 if (reset_head(r
, &ropts
) < 0)
4539 die(_("could not reset --hard"));
4540 discard_index(r
->index
);
4541 if (repo_read_index(r
) < 0)
4542 die(_("could not read index"));
4544 strbuf_release(&buf
);
4547 void create_autostash(struct repository
*r
, const char *path
)
4549 create_autostash_internal(r
, path
, NULL
);
4552 void create_autostash_ref(struct repository
*r
, const char *refname
)
4554 create_autostash_internal(r
, NULL
, refname
);
4557 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
4559 struct child_process child
= CHILD_PROCESS_INIT
;
4562 if (attempt_apply
) {
4564 child
.no_stdout
= 1;
4565 child
.no_stderr
= 1;
4566 strvec_push(&child
.args
, "stash");
4567 strvec_push(&child
.args
, "apply");
4568 strvec_push(&child
.args
, stash_oid
);
4569 ret
= run_command(&child
);
4572 if (attempt_apply
&& !ret
)
4573 fprintf(stderr
, _("Applied autostash.\n"));
4575 struct child_process store
= CHILD_PROCESS_INIT
;
4578 strvec_push(&store
.args
, "stash");
4579 strvec_push(&store
.args
, "store");
4580 strvec_push(&store
.args
, "-m");
4581 strvec_push(&store
.args
, "autostash");
4582 strvec_push(&store
.args
, "-q");
4583 strvec_push(&store
.args
, stash_oid
);
4584 if (run_command(&store
))
4585 ret
= error(_("cannot store %s"), stash_oid
);
4589 "Your changes are safe in the stash.\n"
4590 "You can run \"git stash pop\" or"
4591 " \"git stash drop\" at any time.\n"),
4593 _("Applying autostash resulted in conflicts.") :
4594 _("Autostash exists; creating a new stash entry."));
4600 static int apply_save_autostash(const char *path
, int attempt_apply
)
4602 struct strbuf stash_oid
= STRBUF_INIT
;
4605 if (!read_oneliner(&stash_oid
, path
,
4606 READ_ONELINER_SKIP_IF_EMPTY
)) {
4607 strbuf_release(&stash_oid
);
4610 strbuf_trim(&stash_oid
);
4612 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
4615 strbuf_release(&stash_oid
);
4619 int save_autostash(const char *path
)
4621 return apply_save_autostash(path
, 0);
4624 int apply_autostash(const char *path
)
4626 return apply_save_autostash(path
, 1);
4629 int apply_autostash_oid(const char *stash_oid
)
4631 return apply_save_autostash_oid(stash_oid
, 1);
4634 static int apply_save_autostash_ref(struct repository
*r
, const char *refname
,
4637 struct object_id stash_oid
;
4638 char stash_oid_hex
[GIT_MAX_HEXSZ
+ 1];
4641 if (!refs_ref_exists(get_main_ref_store(r
), refname
))
4644 if (!refs_resolve_ref_unsafe(get_main_ref_store(r
), refname
,
4645 RESOLVE_REF_READING
, &stash_oid
, &flag
))
4647 if (flag
& REF_ISSYMREF
)
4648 return error(_("autostash reference is a symref"));
4650 oid_to_hex_r(stash_oid_hex
, &stash_oid
);
4651 ret
= apply_save_autostash_oid(stash_oid_hex
, attempt_apply
);
4653 refs_delete_ref(get_main_ref_store(r
), "", refname
,
4654 &stash_oid
, REF_NO_DEREF
);
4659 int save_autostash_ref(struct repository
*r
, const char *refname
)
4661 return apply_save_autostash_ref(r
, refname
, 0);
4664 int apply_autostash_ref(struct repository
*r
, const char *refname
)
4666 return apply_save_autostash_ref(r
, refname
, 1);
4669 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
4670 const char *onto_name
, const struct object_id
*onto
,
4671 const struct object_id
*orig_head
)
4673 struct reset_head_opts ropts
= {
4675 .orig_head
= orig_head
,
4676 .flags
= RESET_HEAD_DETACH
| RESET_ORIG_HEAD
|
4677 RESET_HEAD_RUN_POST_CHECKOUT_HOOK
,
4678 .head_msg
= reflog_message(opts
, "start", "checkout %s",
4680 .default_reflog_action
= sequencer_reflog_action(opts
)
4682 if (reset_head(r
, &ropts
)) {
4683 apply_autostash(rebase_path_autostash());
4684 sequencer_remove_state(opts
);
4685 return error(_("could not detach HEAD"));
4691 static int stopped_at_head(struct repository
*r
)
4693 struct object_id head
;
4694 struct commit
*commit
;
4695 struct commit_message message
;
4697 if (repo_get_oid(r
, "HEAD", &head
) ||
4698 !(commit
= lookup_commit(r
, &head
)) ||
4699 repo_parse_commit(r
, commit
) || get_message(commit
, &message
))
4700 fprintf(stderr
, _("Stopped at HEAD\n"));
4702 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
4703 free_message(commit
, &message
);
4709 static int reread_todo_if_changed(struct repository
*r
,
4710 struct todo_list
*todo_list
,
4711 struct replay_opts
*opts
)
4714 struct strbuf buf
= STRBUF_INIT
;
4716 if (strbuf_read_file_or_whine(&buf
, get_todo_path(opts
)) < 0)
4718 offset
= get_item_line_offset(todo_list
, todo_list
->current
+ 1);
4719 if (buf
.len
!= todo_list
->buf
.len
- offset
||
4720 memcmp(buf
.buf
, todo_list
->buf
.buf
+ offset
, buf
.len
)) {
4721 /* Reread the todo file if it has changed. */
4722 todo_list_release(todo_list
);
4723 if (read_populate_todo(r
, todo_list
, opts
))
4724 return -1; /* message was printed */
4725 /* `current` will be incremented on return */
4726 todo_list
->current
= -1;
4728 strbuf_release(&buf
);
4733 static const char rescheduled_advice
[] =
4734 N_("Could not execute the todo command\n"
4738 "It has been rescheduled; To edit the command before continuing, please\n"
4739 "edit the todo list first:\n"
4741 " git rebase --edit-todo\n"
4742 " git rebase --continue\n");
4744 static int pick_one_commit(struct repository
*r
,
4745 struct todo_list
*todo_list
,
4746 struct replay_opts
*opts
,
4747 int *check_todo
, int* reschedule
)
4750 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4751 const char *arg
= todo_item_get_arg(todo_list
, item
);
4752 if (is_rebase_i(opts
))
4753 opts
->reflog_message
= reflog_message(
4754 opts
, command_to_string(item
->command
), NULL
);
4756 res
= do_pick_commit(r
, item
, opts
, is_final_fixup(todo_list
),
4758 if (is_rebase_i(opts
) && res
< 0) {
4763 if (item
->command
== TODO_EDIT
) {
4764 struct commit
*commit
= item
->commit
;
4768 fprintf(stderr
, _("Stopped at %s... %.*s\n"),
4769 short_commit_name(r
, commit
), item
->arg_len
, arg
);
4771 return error_with_patch(r
, commit
,
4772 arg
, item
->arg_len
, opts
, res
, !res
);
4774 if (is_rebase_i(opts
) && !res
)
4775 record_in_rewritten(&item
->commit
->object
.oid
,
4776 peek_command(todo_list
, 1));
4777 if (res
&& is_fixup(item
->command
)) {
4780 return error_failed_squash(r
, item
->commit
, opts
,
4781 item
->arg_len
, arg
);
4782 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4784 struct object_id oid
;
4787 * If we are rewording and have either
4788 * fast-forwarded already, or are about to
4789 * create a new root commit, we want to amend,
4790 * otherwise we do not.
4792 if (item
->command
== TODO_REWORD
&&
4793 !repo_get_oid(r
, "HEAD", &oid
) &&
4794 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4795 (opts
->have_squash_onto
&&
4796 oideq(&opts
->squash_onto
, &oid
))))
4799 return res
| error_with_patch(r
, item
->commit
,
4800 arg
, item
->arg_len
, opts
,
4806 static int pick_commits(struct repository
*r
,
4807 struct todo_list
*todo_list
,
4808 struct replay_opts
*opts
)
4810 int res
= 0, reschedule
= 0;
4812 opts
->reflog_message
= sequencer_reflog_action(opts
);
4814 assert(!(opts
->signoff
|| opts
->no_commit
||
4815 opts
->record_origin
|| should_edit(opts
) ||
4816 opts
->committer_date_is_author_date
||
4817 opts
->ignore_date
));
4818 if (read_and_refresh_cache(r
, opts
))
4821 unlink(rebase_path_message());
4822 unlink(rebase_path_stopped_sha());
4823 unlink(rebase_path_amend());
4824 unlink(rebase_path_patch());
4826 while (todo_list
->current
< todo_list
->nr
) {
4827 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
4828 const char *arg
= todo_item_get_arg(todo_list
, item
);
4831 if (save_todo(todo_list
, opts
, reschedule
))
4833 if (is_rebase_i(opts
)) {
4834 if (item
->command
!= TODO_COMMENT
) {
4835 FILE *f
= fopen(rebase_path_msgnum(), "w");
4837 todo_list
->done_nr
++;
4840 fprintf(f
, "%d\n", todo_list
->done_nr
);
4844 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
4846 todo_list
->total_nr
,
4847 opts
->verbose
? "\n" : "\r");
4849 unlink(rebase_path_author_script());
4850 unlink(git_path_merge_head(r
));
4851 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
4852 NULL
, REF_NO_DEREF
);
4853 refs_delete_ref(get_main_ref_store(r
), "", "REBASE_HEAD",
4854 NULL
, REF_NO_DEREF
);
4856 if (item
->command
== TODO_BREAK
) {
4859 return stopped_at_head(r
);
4862 if (item
->command
<= TODO_SQUASH
) {
4863 res
= pick_one_commit(r
, todo_list
, opts
, &check_todo
,
4865 if (!res
&& item
->command
== TODO_EDIT
)
4867 } else if (item
->command
== TODO_EXEC
) {
4868 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4869 int saved
= *end_of_arg
;
4874 res
= do_exec(r
, arg
);
4875 *end_of_arg
= saved
;
4878 if (opts
->reschedule_failed_exec
)
4882 } else if (item
->command
== TODO_LABEL
) {
4883 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4885 } else if (item
->command
== TODO_RESET
) {
4886 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4888 } else if (item
->command
== TODO_MERGE
) {
4889 if ((res
= do_merge(r
, item
->commit
, arg
, item
->arg_len
,
4890 item
->flags
, &check_todo
, opts
)) < 0)
4892 else if (item
->commit
)
4893 record_in_rewritten(&item
->commit
->object
.oid
,
4894 peek_command(todo_list
, 1));
4896 /* failed with merge conflicts */
4897 return error_with_patch(r
, item
->commit
,
4900 } else if (item
->command
== TODO_UPDATE_REF
) {
4901 struct strbuf ref
= STRBUF_INIT
;
4902 strbuf_add(&ref
, arg
, item
->arg_len
);
4903 if ((res
= do_update_ref(r
, ref
.buf
)))
4905 strbuf_release(&ref
);
4906 } else if (!is_noop(item
->command
))
4907 return error(_("unknown command %d"), item
->command
);
4910 advise(_(rescheduled_advice
),
4911 get_item_line_length(todo_list
,
4912 todo_list
->current
),
4913 get_item_line(todo_list
, todo_list
->current
));
4914 if (save_todo(todo_list
, opts
, reschedule
))
4917 write_rebase_head(&item
->commit
->object
.oid
);
4918 } else if (is_rebase_i(opts
) && check_todo
&& !res
&&
4919 reread_todo_if_changed(r
, todo_list
, opts
)) {
4926 todo_list
->current
++;
4929 if (is_rebase_i(opts
)) {
4930 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4933 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4934 starts_with(head_ref
.buf
, "refs/")) {
4936 struct object_id head
, orig
;
4939 if (repo_get_oid(r
, "HEAD", &head
)) {
4940 res
= error(_("cannot read HEAD"));
4942 strbuf_release(&head_ref
);
4943 strbuf_release(&buf
);
4946 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4947 get_oid_hex(buf
.buf
, &orig
)) {
4948 res
= error(_("could not read orig-head"));
4949 goto cleanup_head_ref
;
4952 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4953 res
= error(_("could not read 'onto'"));
4954 goto cleanup_head_ref
;
4956 msg
= reflog_message(opts
, "finish", "%s onto %s",
4957 head_ref
.buf
, buf
.buf
);
4958 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4959 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4960 res
= error(_("could not update %s"),
4962 goto cleanup_head_ref
;
4964 msg
= reflog_message(opts
, "finish", "returning to %s",
4966 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4967 res
= error(_("could not update HEAD to %s"),
4969 goto cleanup_head_ref
;
4974 if (opts
->verbose
) {
4975 struct rev_info log_tree_opt
;
4976 struct object_id orig
, head
;
4978 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4979 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4980 log_tree_opt
.diff
= 1;
4981 log_tree_opt
.diffopt
.output_format
=
4982 DIFF_FORMAT_DIFFSTAT
;
4983 log_tree_opt
.disable_stdin
= 1;
4985 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4986 !repo_get_oid(r
, buf
.buf
, &orig
) &&
4987 !repo_get_oid(r
, "HEAD", &head
)) {
4988 diff_tree_oid(&orig
, &head
, "",
4989 &log_tree_opt
.diffopt
);
4990 log_tree_diff_flush(&log_tree_opt
);
4992 release_revisions(&log_tree_opt
);
4994 flush_rewritten_pending();
4995 if (!stat(rebase_path_rewritten_list(), &st
) &&
4997 struct child_process child
= CHILD_PROCESS_INIT
;
4998 struct run_hooks_opt hook_opt
= RUN_HOOKS_OPT_INIT
;
5000 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
5002 strvec_push(&child
.args
, "notes");
5003 strvec_push(&child
.args
, "copy");
5004 strvec_push(&child
.args
, "--for-rewrite=rebase");
5005 /* we don't care if this copying failed */
5006 run_command(&child
);
5008 hook_opt
.path_to_stdin
= rebase_path_rewritten_list();
5009 strvec_push(&hook_opt
.args
, "rebase");
5010 run_hooks_opt("post-rewrite", &hook_opt
);
5012 apply_autostash(rebase_path_autostash());
5018 _("Successfully rebased and updated %s.\n"),
5022 strbuf_release(&buf
);
5023 strbuf_release(&head_ref
);
5025 if (do_update_refs(r
, opts
->quiet
))
5030 * Sequence of picks finished successfully; cleanup by
5031 * removing the .git/sequencer directory
5033 return sequencer_remove_state(opts
);
5036 static int continue_single_pick(struct repository
*r
, struct replay_opts
*opts
)
5038 struct child_process cmd
= CHILD_PROCESS_INIT
;
5040 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
5041 !refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD"))
5042 return error(_("no cherry-pick or revert in progress"));
5045 strvec_push(&cmd
.args
, "commit");
5048 * continue_single_pick() handles the case of recovering from a
5049 * conflict. should_edit() doesn't handle that case; for a conflict,
5050 * we want to edit if the user asked for it, or if they didn't specify
5051 * and stdin is a tty.
5053 if (!opts
->edit
|| (opts
->edit
< 0 && !isatty(0)))
5055 * Include --cleanup=strip as well because we don't want the
5056 * "# Conflicts:" messages.
5058 strvec_pushl(&cmd
.args
, "--no-edit", "--cleanup=strip", NULL
);
5060 return run_command(&cmd
);
5063 static int commit_staged_changes(struct repository
*r
,
5064 struct replay_opts
*opts
,
5065 struct todo_list
*todo_list
)
5067 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
5068 unsigned int final_fixup
= 0, is_clean
;
5070 if (has_unstaged_changes(r
, 1))
5071 return error(_("cannot rebase: You have unstaged changes."));
5073 is_clean
= !has_uncommitted_changes(r
, 0);
5075 if (!is_clean
&& !file_exists(rebase_path_message())) {
5076 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
5078 return error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
5080 if (file_exists(rebase_path_amend())) {
5081 struct strbuf rev
= STRBUF_INIT
;
5082 struct object_id head
, to_amend
;
5084 if (repo_get_oid(r
, "HEAD", &head
))
5085 return error(_("cannot amend non-existing commit"));
5086 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
5087 return error(_("invalid file: '%s'"), rebase_path_amend());
5088 if (get_oid_hex(rev
.buf
, &to_amend
))
5089 return error(_("invalid contents: '%s'"),
5090 rebase_path_amend());
5091 if (!is_clean
&& !oideq(&head
, &to_amend
))
5092 return error(_("\nYou have uncommitted changes in your "
5093 "working tree. Please, commit them\n"
5094 "first and then run 'git rebase "
5095 "--continue' again."));
5097 * When skipping a failed fixup/squash, we need to edit the
5098 * commit message, the current fixup list and count, and if it
5099 * was the last fixup/squash in the chain, we need to clean up
5100 * the commit message and if there was a squash, let the user
5103 if (!is_clean
|| !opts
->current_fixup_count
)
5104 ; /* this is not the final fixup */
5105 else if (!oideq(&head
, &to_amend
) ||
5106 !file_exists(rebase_path_stopped_sha())) {
5107 /* was a final fixup or squash done manually? */
5108 if (!is_fixup(peek_command(todo_list
, 0))) {
5109 unlink(rebase_path_fixup_msg());
5110 unlink(rebase_path_squash_msg());
5111 unlink(rebase_path_current_fixups());
5112 strbuf_reset(&opts
->current_fixups
);
5113 opts
->current_fixup_count
= 0;
5116 /* we are in a fixup/squash chain */
5117 const char *p
= opts
->current_fixups
.buf
;
5118 int len
= opts
->current_fixups
.len
;
5120 opts
->current_fixup_count
--;
5122 BUG("Incorrect current_fixups:\n%s", p
);
5123 while (len
&& p
[len
- 1] != '\n')
5125 strbuf_setlen(&opts
->current_fixups
, len
);
5126 if (write_message(p
, len
, rebase_path_current_fixups(),
5128 return error(_("could not write file: '%s'"),
5129 rebase_path_current_fixups());
5132 * If a fixup/squash in a fixup/squash chain failed, the
5133 * commit message is already correct, no need to commit
5136 * Only if it is the final command in the fixup/squash
5137 * chain, and only if the chain is longer than a single
5138 * fixup/squash command (which was just skipped), do we
5139 * actually need to re-commit with a cleaned up commit
5142 if (opts
->current_fixup_count
> 0 &&
5143 !is_fixup(peek_command(todo_list
, 0))) {
5146 * If there was not a single "squash" in the
5147 * chain, we only need to clean up the commit
5148 * message, no need to bother the user with
5149 * opening the commit message in the editor.
5151 if (!starts_with(p
, "squash ") &&
5152 !strstr(p
, "\nsquash "))
5153 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
5154 } else if (is_fixup(peek_command(todo_list
, 0))) {
5156 * We need to update the squash message to skip
5157 * the latest commit message.
5160 struct commit
*commit
;
5162 const char *path
= rebase_path_squash_msg();
5163 const char *encoding
= get_commit_output_encoding();
5165 if (parse_head(r
, &commit
))
5166 return error(_("could not parse HEAD"));
5168 p
= repo_logmsg_reencode(r
, commit
, NULL
, encoding
);
5170 res
= error(_("could not parse commit %s"),
5171 oid_to_hex(&commit
->object
.oid
));
5172 goto unuse_commit_buffer
;
5174 find_commit_subject(p
, &msg
);
5175 if (write_message(msg
, strlen(msg
), path
, 0)) {
5176 res
= error(_("could not write file: "
5178 goto unuse_commit_buffer
;
5180 unuse_commit_buffer
:
5181 repo_unuse_commit_buffer(r
, commit
, p
);
5187 strbuf_release(&rev
);
5192 if (refs_ref_exists(get_main_ref_store(r
),
5193 "CHERRY_PICK_HEAD") &&
5194 refs_delete_ref(get_main_ref_store(r
), "",
5195 "CHERRY_PICK_HEAD", NULL
, REF_NO_DEREF
))
5196 return error(_("could not remove CHERRY_PICK_HEAD"));
5197 if (unlink(git_path_merge_msg(r
)) && errno
!= ENOENT
)
5198 return error_errno(_("could not remove '%s'"),
5199 git_path_merge_msg(r
));
5204 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
5206 return error(_("could not commit staged changes."));
5207 unlink(rebase_path_amend());
5208 unlink(git_path_merge_head(r
));
5209 refs_delete_ref(get_main_ref_store(r
), "", "AUTO_MERGE",
5210 NULL
, REF_NO_DEREF
);
5212 unlink(rebase_path_fixup_msg());
5213 unlink(rebase_path_squash_msg());
5215 if (opts
->current_fixup_count
> 0) {
5217 * Whether final fixup or not, we just cleaned up the commit
5220 unlink(rebase_path_current_fixups());
5221 strbuf_reset(&opts
->current_fixups
);
5222 opts
->current_fixup_count
= 0;
5227 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
5229 struct todo_list todo_list
= TODO_LIST_INIT
;
5232 if (read_and_refresh_cache(r
, opts
))
5235 if (read_populate_opts(opts
))
5237 if (is_rebase_i(opts
)) {
5238 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5239 goto release_todo_list
;
5241 if (file_exists(rebase_path_dropped())) {
5242 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
5243 goto release_todo_list
;
5245 unlink(rebase_path_dropped());
5248 opts
->reflog_message
= reflog_message(opts
, "continue", NULL
);
5249 if (commit_staged_changes(r
, opts
, &todo_list
)) {
5251 goto release_todo_list
;
5253 } else if (!file_exists(get_todo_path(opts
)))
5254 return continue_single_pick(r
, opts
);
5255 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
5256 goto release_todo_list
;
5258 if (!is_rebase_i(opts
)) {
5259 /* Verify that the conflict has been resolved */
5260 if (refs_ref_exists(get_main_ref_store(r
),
5261 "CHERRY_PICK_HEAD") ||
5262 refs_ref_exists(get_main_ref_store(r
), "REVERT_HEAD")) {
5263 res
= continue_single_pick(r
, opts
);
5265 goto release_todo_list
;
5267 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
5268 res
= error_dirty_index(r
, opts
);
5269 goto release_todo_list
;
5271 todo_list
.current
++;
5272 } else if (file_exists(rebase_path_stopped_sha())) {
5273 struct strbuf buf
= STRBUF_INIT
;
5274 struct object_id oid
;
5276 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
5277 READ_ONELINER_SKIP_IF_EMPTY
) &&
5278 !get_oid_hex(buf
.buf
, &oid
))
5279 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
5280 strbuf_release(&buf
);
5283 res
= pick_commits(r
, &todo_list
, opts
);
5285 todo_list_release(&todo_list
);
5289 static int single_pick(struct repository
*r
,
5290 struct commit
*cmit
,
5291 struct replay_opts
*opts
)
5294 struct todo_item item
;
5296 item
.command
= opts
->action
== REPLAY_PICK
?
5297 TODO_PICK
: TODO_REVERT
;
5300 opts
->reflog_message
= sequencer_reflog_action(opts
);
5301 return do_pick_commit(r
, &item
, opts
, 0, &check_todo
);
5304 int sequencer_pick_revisions(struct repository
*r
,
5305 struct replay_opts
*opts
)
5307 struct todo_list todo_list
= TODO_LIST_INIT
;
5308 struct object_id oid
;
5312 if (read_and_refresh_cache(r
, opts
))
5315 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
5316 struct object_id oid
;
5317 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
5319 /* This happens when using --stdin. */
5323 if (!repo_get_oid(r
, name
, &oid
)) {
5324 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
5325 enum object_type type
= oid_object_info(r
,
5328 return error(_("%s: can't cherry-pick a %s"),
5329 name
, type_name(type
));
5332 return error(_("%s: bad revision"), name
);
5336 * If we were called as "git cherry-pick <commit>", just
5337 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5338 * REVERT_HEAD, and don't touch the sequencer state.
5339 * This means it is possible to cherry-pick in the middle
5340 * of a cherry-pick sequence.
5342 if (opts
->revs
->cmdline
.nr
== 1 &&
5343 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
5344 opts
->revs
->no_walk
&&
5345 !opts
->revs
->cmdline
.rev
->flags
) {
5346 struct commit
*cmit
;
5347 if (prepare_revision_walk(opts
->revs
))
5348 return error(_("revision walk setup failed"));
5349 cmit
= get_revision(opts
->revs
);
5351 return error(_("empty commit set passed"));
5352 if (get_revision(opts
->revs
))
5353 BUG("unexpected extra commit from walk");
5354 return single_pick(r
, cmit
, opts
);
5358 * Start a new cherry-pick/ revert sequence; but
5359 * first, make sure that an existing one isn't in
5363 if (walk_revs_populate_todo(&todo_list
, opts
) ||
5364 create_seq_dir(r
) < 0)
5366 if (repo_get_oid(r
, "HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
5367 return error(_("can't revert as initial commit"));
5368 if (save_head(oid_to_hex(&oid
)))
5370 if (save_opts(opts
))
5372 update_abort_safety_file();
5373 res
= pick_commits(r
, &todo_list
, opts
);
5374 todo_list_release(&todo_list
);
5378 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
5380 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
5381 struct strbuf sob
= STRBUF_INIT
;
5384 strbuf_addstr(&sob
, sign_off_header
);
5385 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
5386 strbuf_addch(&sob
, '\n');
5389 strbuf_complete_line(msgbuf
);
5392 * If the whole message buffer is equal to the sob, pretend that we
5393 * found a conforming footer with a matching sob
5395 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
5396 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
5399 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
5402 const char *append_newlines
= NULL
;
5403 size_t len
= msgbuf
->len
- ignore_footer
;
5407 * The buffer is completely empty. Leave foom for
5408 * the title and body to be filled in by the user.
5410 append_newlines
= "\n\n";
5411 } else if (len
== 1) {
5413 * Buffer contains a single newline. Add another
5414 * so that we leave room for the title and body.
5416 append_newlines
= "\n";
5417 } else if (msgbuf
->buf
[len
- 2] != '\n') {
5419 * Buffer ends with a single newline. Add another
5420 * so that there is an empty line between the message
5423 append_newlines
= "\n";
5424 } /* else, the buffer already ends with two newlines. */
5426 if (append_newlines
)
5427 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5428 append_newlines
, strlen(append_newlines
));
5431 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
5432 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
5435 strbuf_release(&sob
);
5438 struct labels_entry
{
5439 struct hashmap_entry entry
;
5440 char label
[FLEX_ARRAY
];
5443 static int labels_cmp(const void *fndata UNUSED
,
5444 const struct hashmap_entry
*eptr
,
5445 const struct hashmap_entry
*entry_or_key
, const void *key
)
5447 const struct labels_entry
*a
, *b
;
5449 a
= container_of(eptr
, const struct labels_entry
, entry
);
5450 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
5452 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
5455 struct string_entry
{
5456 struct oidmap_entry entry
;
5457 char string
[FLEX_ARRAY
];
5460 struct label_state
{
5461 struct oidmap commit2label
;
5462 struct hashmap labels
;
5464 int max_label_length
;
5467 static const char *label_oid(struct object_id
*oid
, const char *label
,
5468 struct label_state
*state
)
5470 struct labels_entry
*labels_entry
;
5471 struct string_entry
*string_entry
;
5472 struct object_id dummy
;
5475 string_entry
= oidmap_get(&state
->commit2label
, oid
);
5477 return string_entry
->string
;
5480 * For "uninteresting" commits, i.e. commits that are not to be
5481 * rebased, and which can therefore not be labeled, we use a unique
5482 * abbreviation of the commit name. This is slightly more complicated
5483 * than calling repo_find_unique_abbrev() because we also need to make
5484 * sure that the abbreviation does not conflict with any other
5487 * We disallow "interesting" commits to be labeled by a string that
5488 * is a valid full-length hash, to ensure that we always can find an
5489 * abbreviation for any uninteresting commit's names that does not
5490 * clash with any other label.
5492 strbuf_reset(&state
->buf
);
5496 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
5497 label
= p
= state
->buf
.buf
;
5499 repo_find_unique_abbrev_r(the_repository
, p
, oid
,
5503 * We may need to extend the abbreviated hash so that there is
5504 * no conflicting label.
5506 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
5507 size_t i
= strlen(p
) + 1;
5509 oid_to_hex_r(p
, oid
);
5510 for (; i
< the_hash_algo
->hexsz
; i
++) {
5513 if (!hashmap_get_from_hash(&state
->labels
,
5520 struct strbuf
*buf
= &state
->buf
;
5521 int label_is_utf8
= 1; /* start with this assumption */
5522 size_t max_len
= buf
->len
+ state
->max_label_length
;
5525 * Sanitize labels by replacing non-alpha-numeric characters
5526 * (including white-space ones) by dashes, as they might be
5527 * illegal in file names (and hence in ref names).
5529 * Note that we retain non-ASCII UTF-8 characters (identified
5530 * via the most significant bit). They should be all acceptable
5533 * As we will use the labels as names of (loose) refs, it is
5534 * vital that the name not be longer than the maximum component
5535 * size of the file system (`NAME_MAX`). We are careful to
5536 * truncate the label accordingly, allowing for the `.lock`
5537 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5538 * truncating in the middle of a character).
5540 for (; *label
&& buf
->len
+ 1 < max_len
; label
++)
5541 if (isalnum(*label
) ||
5542 (!label_is_utf8
&& (*label
& 0x80)))
5543 strbuf_addch(buf
, *label
);
5544 else if (*label
& 0x80) {
5545 const char *p
= label
;
5547 utf8_width(&p
, NULL
);
5549 if (buf
->len
+ (p
- label
) > max_len
)
5551 strbuf_add(buf
, label
, p
- label
);
5555 strbuf_addch(buf
, *label
);
5557 /* avoid leading dash and double-dashes */
5558 } else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
5559 strbuf_addch(buf
, '-');
5561 strbuf_addstr(buf
, "rev-");
5562 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
5566 if ((buf
->len
== the_hash_algo
->hexsz
&&
5567 !get_oid_hex(label
, &dummy
)) ||
5568 (buf
->len
== 1 && *label
== '#') ||
5569 hashmap_get_from_hash(&state
->labels
,
5570 strihash(label
), label
)) {
5572 * If the label already exists, or if the label is a
5573 * valid full OID, or the label is a '#' (which we use
5574 * as a separator between merge heads and oneline), we
5575 * append a dash and a number to make it unique.
5577 size_t len
= buf
->len
;
5579 for (i
= 2; ; i
++) {
5580 strbuf_setlen(buf
, len
);
5581 strbuf_addf(buf
, "-%d", i
);
5582 if (!hashmap_get_from_hash(&state
->labels
,
5592 FLEX_ALLOC_STR(labels_entry
, label
, label
);
5593 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
5594 hashmap_add(&state
->labels
, &labels_entry
->entry
);
5596 FLEX_ALLOC_STR(string_entry
, string
, label
);
5597 oidcpy(&string_entry
->entry
.oid
, oid
);
5598 oidmap_put(&state
->commit2label
, string_entry
);
5600 return string_entry
->string
;
5603 static int make_script_with_merges(struct pretty_print_context
*pp
,
5604 struct rev_info
*revs
, struct strbuf
*out
,
5607 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5608 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
5609 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
5610 int skipped_commit
= 0;
5611 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
5612 struct strbuf label
= STRBUF_INIT
;
5613 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
5614 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
5615 struct commit
*commit
;
5616 struct oidmap commit2todo
= OIDMAP_INIT
;
5617 struct string_entry
*entry
;
5618 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
5619 shown
= OIDSET_INIT
;
5620 struct label_state state
=
5621 { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
, GIT_MAX_LABEL_LENGTH
};
5623 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
5624 const char *cmd_pick
= abbr
? "p" : "pick",
5625 *cmd_label
= abbr
? "l" : "label",
5626 *cmd_reset
= abbr
? "t" : "reset",
5627 *cmd_merge
= abbr
? "m" : "merge";
5629 git_config_get_int("rebase.maxlabellength", &state
.max_label_length
);
5631 oidmap_init(&commit2todo
, 0);
5632 oidmap_init(&state
.commit2label
, 0);
5633 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
5634 strbuf_init(&state
.buf
, 32);
5636 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
5637 struct labels_entry
*onto_label_entry
;
5638 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
5639 FLEX_ALLOC_STR(entry
, string
, "onto");
5640 oidcpy(&entry
->entry
.oid
, oid
);
5641 oidmap_put(&state
.commit2label
, entry
);
5643 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
5644 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
5645 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
5650 * - get onelines for all commits
5651 * - gather all branch tips (i.e. 2nd or later parents of merges)
5652 * - label all branch tips
5654 while ((commit
= get_revision(revs
))) {
5655 struct commit_list
*to_merge
;
5656 const char *p1
, *p2
;
5657 struct object_id
*oid
;
5660 tail
= &commit_list_insert(commit
, tail
)->next
;
5661 oidset_insert(&interesting
, &commit
->object
.oid
);
5663 is_empty
= is_original_commit_empty(commit
);
5664 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5665 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5666 warning(_("skipped previously applied commit %s"),
5667 short_commit_name(the_repository
, commit
));
5671 if (is_empty
&& !keep_empty
)
5674 strbuf_reset(&oneline
);
5675 pretty_print_commit(pp
, commit
, &oneline
);
5677 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
5679 /* non-merge commit: easy case */
5681 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
5682 oid_to_hex(&commit
->object
.oid
),
5685 strbuf_addf(&buf
, " %c empty",
5688 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5689 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5690 oidmap_put(&commit2todo
, entry
);
5695 /* Create a label */
5696 strbuf_reset(&label
);
5697 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
5698 (p1
= strchr(p1
, '\'')) &&
5699 (p2
= strchr(++p1
, '\'')))
5700 strbuf_add(&label
, p1
, p2
- p1
);
5701 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
5703 (p1
= strstr(p1
, " from ")))
5704 strbuf_addstr(&label
, p1
+ strlen(" from "));
5706 strbuf_addbuf(&label
, &oneline
);
5709 strbuf_addf(&buf
, "%s -C %s",
5710 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
5712 /* label the tips of merged branches */
5713 for (; to_merge
; to_merge
= to_merge
->next
) {
5714 oid
= &to_merge
->item
->object
.oid
;
5715 strbuf_addch(&buf
, ' ');
5717 if (!oidset_contains(&interesting
, oid
)) {
5718 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
5723 tips_tail
= &commit_list_insert(to_merge
->item
,
5726 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
5728 strbuf_addf(&buf
, " # %s", oneline
.buf
);
5730 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
5731 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
5732 oidmap_put(&commit2todo
, entry
);
5735 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5736 _("use --reapply-cherry-picks to include skipped commits"));
5740 * - label branch points
5741 * - add HEAD to the branch tips
5743 for (iter
= commits
; iter
; iter
= iter
->next
) {
5744 struct commit_list
*parent
= iter
->item
->parents
;
5745 for (; parent
; parent
= parent
->next
) {
5746 struct object_id
*oid
= &parent
->item
->object
.oid
;
5747 if (!oidset_contains(&interesting
, oid
))
5749 if (oidset_insert(&child_seen
, oid
))
5750 label_oid(oid
, "branch-point", &state
);
5753 /* Add HEAD as implicit "tip of branch" */
5755 tips_tail
= &commit_list_insert(iter
->item
,
5760 * Third phase: output the todo list. This is a bit tricky, as we
5761 * want to avoid jumping back and forth between revisions. To
5762 * accomplish that goal, we walk backwards from the branch tips,
5763 * gathering commits not yet shown, reversing the list on the fly,
5764 * then outputting that list (labeling revisions as needed).
5766 strbuf_addf(out
, "%s onto\n", cmd_label
);
5767 for (iter
= tips
; iter
; iter
= iter
->next
) {
5768 struct commit_list
*list
= NULL
, *iter2
;
5770 commit
= iter
->item
;
5771 if (oidset_contains(&shown
, &commit
->object
.oid
))
5773 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
5776 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
5778 strbuf_addch(out
, '\n');
5780 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
5781 !oidset_contains(&shown
, &commit
->object
.oid
)) {
5782 commit_list_insert(commit
, &list
);
5783 if (!commit
->parents
) {
5787 commit
= commit
->parents
->item
;
5791 strbuf_addf(out
, "%s %s\n", cmd_reset
,
5792 rebase_cousins
|| root_with_onto
?
5793 "onto" : "[new root]");
5795 const char *to
= NULL
;
5797 entry
= oidmap_get(&state
.commit2label
,
5798 &commit
->object
.oid
);
5801 else if (!rebase_cousins
)
5802 to
= label_oid(&commit
->object
.oid
, NULL
,
5805 if (!to
|| !strcmp(to
, "onto"))
5806 strbuf_addf(out
, "%s onto\n", cmd_reset
);
5808 strbuf_reset(&oneline
);
5809 pretty_print_commit(pp
, commit
, &oneline
);
5810 strbuf_addf(out
, "%s %s # %s\n",
5811 cmd_reset
, to
, oneline
.buf
);
5815 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
5816 struct object_id
*oid
= &iter2
->item
->object
.oid
;
5817 entry
= oidmap_get(&commit2todo
, oid
);
5818 /* only show if not already upstream */
5820 strbuf_addf(out
, "%s\n", entry
->string
);
5821 entry
= oidmap_get(&state
.commit2label
, oid
);
5823 strbuf_addf(out
, "%s %s\n",
5824 cmd_label
, entry
->string
);
5825 oidset_insert(&shown
, oid
);
5828 free_commit_list(list
);
5831 free_commit_list(commits
);
5832 free_commit_list(tips
);
5834 strbuf_release(&label
);
5835 strbuf_release(&oneline
);
5836 strbuf_release(&buf
);
5838 oidmap_free(&commit2todo
, 1);
5839 oidmap_free(&state
.commit2label
, 1);
5840 hashmap_clear_and_free(&state
.labels
, struct labels_entry
, entry
);
5841 strbuf_release(&state
.buf
);
5846 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
5847 const char **argv
, unsigned flags
)
5849 char *format
= NULL
;
5850 struct pretty_print_context pp
= {0};
5851 struct rev_info revs
;
5852 struct commit
*commit
;
5853 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
5854 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
5855 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
5856 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
5857 int skipped_commit
= 0;
5860 repo_init_revisions(r
, &revs
, NULL
);
5861 revs
.verbose_header
= 1;
5863 revs
.max_parents
= 1;
5864 revs
.cherry_mark
= !reapply_cherry_picks
;
5867 revs
.right_only
= 1;
5868 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
5869 revs
.topo_order
= 1;
5871 revs
.pretty_given
= 1;
5872 git_config_get_string("rebase.instructionFormat", &format
);
5873 if (!format
|| !*format
) {
5875 format
= xstrdup("%s");
5877 get_commit_format(format
, &revs
);
5879 pp
.fmt
= revs
.commit_format
;
5880 pp
.output_encoding
= get_log_output_encoding();
5882 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1) {
5883 ret
= error(_("make_script: unhandled options"));
5887 if (prepare_revision_walk(&revs
) < 0) {
5888 ret
= error(_("make_script: error preparing revisions"));
5892 if (rebase_merges
) {
5893 ret
= make_script_with_merges(&pp
, &revs
, out
, flags
);
5897 while ((commit
= get_revision(&revs
))) {
5898 int is_empty
= is_original_commit_empty(commit
);
5900 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
)) {
5901 if (flags
& TODO_LIST_WARN_SKIPPED_CHERRY_PICKS
)
5902 warning(_("skipped previously applied commit %s"),
5903 short_commit_name(r
, commit
));
5907 if (is_empty
&& !keep_empty
)
5909 strbuf_addf(out
, "%s %s ", insn
,
5910 oid_to_hex(&commit
->object
.oid
));
5911 pretty_print_commit(&pp
, commit
, out
);
5913 strbuf_addf(out
, " %c empty", comment_line_char
);
5914 strbuf_addch(out
, '\n');
5917 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS
,
5918 _("use --reapply-cherry-picks to include skipped commits"));
5920 release_revisions(&revs
);
5925 * Add commands after pick and (series of) squash/fixup commands
5928 static void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5929 struct string_list
*commands
)
5931 struct strbuf
*buf
= &todo_list
->buf
;
5932 size_t base_offset
= buf
->len
;
5933 int i
, insert
, nr
= 0, alloc
= 0;
5934 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5936 CALLOC_ARRAY(base_items
, commands
->nr
);
5937 for (i
= 0; i
< commands
->nr
; i
++) {
5938 size_t command_len
= strlen(commands
->items
[i
].string
);
5940 strbuf_addstr(buf
, commands
->items
[i
].string
);
5941 strbuf_addch(buf
, '\n');
5943 base_items
[i
].command
= TODO_EXEC
;
5944 base_items
[i
].offset_in_buf
= base_offset
;
5945 base_items
[i
].arg_offset
= base_offset
;
5946 base_items
[i
].arg_len
= command_len
;
5948 base_offset
+= command_len
+ 1;
5952 * Insert <commands> after every pick. Here, fixup/squash chains
5953 * are considered part of the pick, so we insert the commands *after*
5954 * those chains if there are any.
5956 * As we insert the exec commands immediately after rearranging
5957 * any fixups and before the user edits the list, a fixup chain
5958 * can never contain comments (any comments are empty picks that
5959 * have been commented out because the user did not specify
5960 * --keep-empty). So, it is safe to insert an exec command
5961 * without looking at the command following a comment.
5964 for (i
= 0; i
< todo_list
->nr
; i
++) {
5965 enum todo_command command
= todo_list
->items
[i
].command
;
5966 if (insert
&& !is_fixup(command
)) {
5967 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5968 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5974 ALLOC_GROW(items
, nr
+ 1, alloc
);
5975 items
[nr
++] = todo_list
->items
[i
];
5977 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5981 /* insert or append final <commands> */
5983 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5984 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5989 FREE_AND_NULL(todo_list
->items
);
5990 todo_list
->items
= items
;
5992 todo_list
->alloc
= alloc
;
5995 static void todo_list_to_strbuf(struct repository
*r
,
5996 struct todo_list
*todo_list
,
5997 struct strbuf
*buf
, int num
, unsigned flags
)
5999 struct todo_item
*item
;
6000 int i
, max
= todo_list
->nr
;
6002 if (num
> 0 && num
< max
)
6005 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
6008 /* if the item is not a command write it and continue */
6009 if (item
->command
>= TODO_COMMENT
) {
6010 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
6011 todo_item_get_arg(todo_list
, item
));
6015 /* add command to the buffer */
6016 cmd
= command_to_char(item
->command
);
6017 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
6018 strbuf_addch(buf
, cmd
);
6020 strbuf_addstr(buf
, command_to_string(item
->command
));
6024 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
6025 short_commit_name(r
, item
->commit
) :
6026 oid_to_hex(&item
->commit
->object
.oid
);
6028 if (item
->command
== TODO_FIXUP
) {
6029 if (item
->flags
& TODO_EDIT_FIXUP_MSG
)
6030 strbuf_addstr(buf
, " -c");
6031 else if (item
->flags
& TODO_REPLACE_FIXUP_MSG
) {
6032 strbuf_addstr(buf
, " -C");
6036 if (item
->command
== TODO_MERGE
) {
6037 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
6038 strbuf_addstr(buf
, " -c");
6040 strbuf_addstr(buf
, " -C");
6043 strbuf_addf(buf
, " %s", oid
);
6046 /* add all the rest */
6048 strbuf_addch(buf
, '\n');
6050 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
6051 todo_item_get_arg(todo_list
, item
));
6055 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
6056 const char *file
, const char *shortrevisions
,
6057 const char *shortonto
, int num
, unsigned flags
)
6060 struct strbuf buf
= STRBUF_INIT
;
6062 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
6063 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
6064 append_todo_help(count_commands(todo_list
),
6065 shortrevisions
, shortonto
, &buf
);
6067 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
6068 strbuf_release(&buf
);
6073 /* skip picking commits whose parents are unchanged */
6074 static int skip_unnecessary_picks(struct repository
*r
,
6075 struct todo_list
*todo_list
,
6076 struct object_id
*base_oid
)
6078 struct object_id
*parent_oid
;
6081 for (i
= 0; i
< todo_list
->nr
; i
++) {
6082 struct todo_item
*item
= todo_list
->items
+ i
;
6084 if (item
->command
>= TODO_NOOP
)
6086 if (item
->command
!= TODO_PICK
)
6088 if (repo_parse_commit(r
, item
->commit
)) {
6089 return error(_("could not parse commit '%s'"),
6090 oid_to_hex(&item
->commit
->object
.oid
));
6092 if (!item
->commit
->parents
)
6093 break; /* root commit */
6094 if (item
->commit
->parents
->next
)
6095 break; /* merge commit */
6096 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
6097 if (!oideq(parent_oid
, base_oid
))
6099 oidcpy(base_oid
, &item
->commit
->object
.oid
);
6102 const char *done_path
= rebase_path_done();
6104 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
6105 error_errno(_("could not write to '%s'"), done_path
);
6109 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
6111 todo_list
->current
= 0;
6112 todo_list
->done_nr
+= i
;
6114 if (is_fixup(peek_command(todo_list
, 0)))
6115 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
6121 struct todo_add_branch_context
{
6122 struct todo_item
*items
;
6126 struct commit
*commit
;
6127 struct string_list refs_to_oids
;
6130 static int add_decorations_to_list(const struct commit
*commit
,
6131 struct todo_add_branch_context
*ctx
)
6133 const struct name_decoration
*decoration
= get_name_decoration(&commit
->object
);
6134 const char *head_ref
= resolve_ref_unsafe("HEAD",
6135 RESOLVE_REF_READING
,
6139 while (decoration
) {
6140 struct todo_item
*item
;
6142 size_t base_offset
= ctx
->buf
->len
;
6145 * If the branch is the current HEAD, then it will be
6146 * updated by the default rebase behavior.
6148 if (head_ref
&& !strcmp(head_ref
, decoration
->name
)) {
6149 decoration
= decoration
->next
;
6153 ALLOC_GROW(ctx
->items
,
6156 item
= &ctx
->items
[ctx
->items_nr
];
6157 memset(item
, 0, sizeof(*item
));
6159 /* If the branch is checked out, then leave a comment instead. */
6160 if ((path
= branch_checked_out(decoration
->name
))) {
6161 item
->command
= TODO_COMMENT
;
6162 strbuf_addf(ctx
->buf
, "# Ref %s checked out at '%s'\n",
6163 decoration
->name
, path
);
6165 struct string_list_item
*sti
;
6166 item
->command
= TODO_UPDATE_REF
;
6167 strbuf_addf(ctx
->buf
, "%s\n", decoration
->name
);
6169 sti
= string_list_insert(&ctx
->refs_to_oids
,
6171 sti
->util
= init_update_ref_record(decoration
->name
);
6174 item
->offset_in_buf
= base_offset
;
6175 item
->arg_offset
= base_offset
;
6176 item
->arg_len
= ctx
->buf
->len
- base_offset
;
6179 decoration
= decoration
->next
;
6186 * For each 'pick' command, find out if the commit has a decoration in
6187 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6189 static int todo_list_add_update_ref_commands(struct todo_list
*todo_list
)
6192 static struct string_list decorate_refs_exclude
= STRING_LIST_INIT_NODUP
;
6193 static struct string_list decorate_refs_exclude_config
= STRING_LIST_INIT_NODUP
;
6194 static struct string_list decorate_refs_include
= STRING_LIST_INIT_NODUP
;
6195 struct decoration_filter decoration_filter
= {
6196 .include_ref_pattern
= &decorate_refs_include
,
6197 .exclude_ref_pattern
= &decorate_refs_exclude
,
6198 .exclude_ref_config_pattern
= &decorate_refs_exclude_config
,
6200 struct todo_add_branch_context ctx
= {
6201 .buf
= &todo_list
->buf
,
6202 .refs_to_oids
= STRING_LIST_INIT_DUP
,
6205 ctx
.items_alloc
= 2 * todo_list
->nr
+ 1;
6206 ALLOC_ARRAY(ctx
.items
, ctx
.items_alloc
);
6208 string_list_append(&decorate_refs_include
, "refs/heads/");
6209 load_ref_decorations(&decoration_filter
, 0);
6211 for (i
= 0; i
< todo_list
->nr
; ) {
6212 struct todo_item
*item
= &todo_list
->items
[i
];
6214 /* insert ith item into new list */
6215 ALLOC_GROW(ctx
.items
,
6219 ctx
.items
[ctx
.items_nr
++] = todo_list
->items
[i
++];
6222 ctx
.commit
= item
->commit
;
6223 add_decorations_to_list(item
->commit
, &ctx
);
6227 res
= write_update_refs_state(&ctx
.refs_to_oids
);
6229 string_list_clear(&ctx
.refs_to_oids
, 1);
6232 /* we failed, so clean up the new list. */
6237 free(todo_list
->items
);
6238 todo_list
->items
= ctx
.items
;
6239 todo_list
->nr
= ctx
.items_nr
;
6240 todo_list
->alloc
= ctx
.items_alloc
;
6245 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
6246 const char *shortrevisions
, const char *onto_name
,
6247 struct commit
*onto
, const struct object_id
*orig_head
,
6248 struct string_list
*commands
, unsigned autosquash
,
6249 unsigned update_refs
,
6250 struct todo_list
*todo_list
)
6252 char shortonto
[GIT_MAX_HEXSZ
+ 1];
6253 const char *todo_file
= rebase_path_todo();
6254 struct todo_list new_todo
= TODO_LIST_INIT
;
6255 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
6256 struct object_id oid
= onto
->object
.oid
;
6259 repo_find_unique_abbrev_r(r
, shortonto
, &oid
,
6262 if (buf
->len
== 0) {
6263 struct todo_item
*item
= append_new_todo(todo_list
);
6264 item
->command
= TODO_NOOP
;
6265 item
->commit
= NULL
;
6266 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
6269 if (update_refs
&& todo_list_add_update_ref_commands(todo_list
))
6272 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
6276 todo_list_add_exec_commands(todo_list
, commands
);
6278 if (count_commands(todo_list
) == 0) {
6279 apply_autostash(rebase_path_autostash());
6280 sequencer_remove_state(opts
);
6282 return error(_("nothing to do"));
6285 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
6289 else if (res
== -2) {
6290 apply_autostash(rebase_path_autostash());
6291 sequencer_remove_state(opts
);
6294 } else if (res
== -3) {
6295 apply_autostash(rebase_path_autostash());
6296 sequencer_remove_state(opts
);
6297 todo_list_release(&new_todo
);
6299 return error(_("nothing to do"));
6300 } else if (res
== -4) {
6301 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
6302 todo_list_release(&new_todo
);
6307 /* Expand the commit IDs */
6308 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
6309 strbuf_swap(&new_todo
.buf
, &buf2
);
6310 strbuf_release(&buf2
);
6311 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6312 new_todo
.total_nr
= 0;
6313 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
6314 BUG("invalid todo list after expanding IDs:\n%s",
6317 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
6318 todo_list_release(&new_todo
);
6319 return error(_("could not skip unnecessary pick commands"));
6322 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
6323 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
6324 todo_list_release(&new_todo
);
6325 return error_errno(_("could not write '%s'"), todo_file
);
6330 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
6333 if (require_clean_work_tree(r
, "rebase", NULL
, 1, 1))
6336 todo_list_write_total_nr(&new_todo
);
6337 res
= pick_commits(r
, &new_todo
, opts
);
6340 todo_list_release(&new_todo
);
6345 struct subject2item_entry
{
6346 struct hashmap_entry entry
;
6348 char subject
[FLEX_ARRAY
];
6351 static int subject2item_cmp(const void *fndata UNUSED
,
6352 const struct hashmap_entry
*eptr
,
6353 const struct hashmap_entry
*entry_or_key
,
6356 const struct subject2item_entry
*a
, *b
;
6358 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
6359 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
6361 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
6364 define_commit_slab(commit_todo_item
, struct todo_item
*);
6366 static int skip_fixupish(const char *subject
, const char **p
) {
6367 return skip_prefix(subject
, "fixup! ", p
) ||
6368 skip_prefix(subject
, "amend! ", p
) ||
6369 skip_prefix(subject
, "squash! ", p
);
6373 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6374 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6375 * after the former, and change "pick" to "fixup"/"squash".
6377 * Note that if the config has specified a custom instruction format, each log
6378 * message will have to be retrieved from the commit (as the oneline in the
6379 * script cannot be trusted) in order to normalize the autosquash arrangement.
6381 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
6383 struct hashmap subject2item
;
6384 int rearranged
= 0, *next
, *tail
, i
, nr
= 0;
6386 struct commit_todo_item commit_todo
;
6387 struct todo_item
*items
= NULL
;
6389 init_commit_todo_item(&commit_todo
);
6391 * The hashmap maps onelines to the respective todo list index.
6393 * If any items need to be rearranged, the next[i] value will indicate
6394 * which item was moved directly after the i'th.
6396 * In that case, last[i] will indicate the index of the latest item to
6397 * be moved to appear after the i'th.
6399 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
6400 ALLOC_ARRAY(next
, todo_list
->nr
);
6401 ALLOC_ARRAY(tail
, todo_list
->nr
);
6402 ALLOC_ARRAY(subjects
, todo_list
->nr
);
6403 for (i
= 0; i
< todo_list
->nr
; i
++) {
6404 struct strbuf buf
= STRBUF_INIT
;
6405 struct todo_item
*item
= todo_list
->items
+ i
;
6406 const char *commit_buffer
, *subject
, *p
;
6409 struct subject2item_entry
*entry
;
6411 next
[i
] = tail
[i
] = -1;
6412 if (!item
->commit
|| item
->command
== TODO_DROP
) {
6417 if (is_fixup(item
->command
)) {
6418 clear_commit_todo_item(&commit_todo
);
6419 return error(_("the script was already rearranged."));
6422 repo_parse_commit(the_repository
, item
->commit
);
6423 commit_buffer
= repo_logmsg_reencode(the_repository
,
6426 find_commit_subject(commit_buffer
, &subject
);
6427 format_subject(&buf
, subject
, " ");
6428 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
6429 repo_unuse_commit_buffer(the_repository
, item
->commit
,
6431 if (skip_fixupish(subject
, &p
)) {
6432 struct commit
*commit2
;
6437 if (!skip_fixupish(p
, &p
))
6441 entry
= hashmap_get_entry_from_hash(&subject2item
,
6443 struct subject2item_entry
,
6446 /* found by title */
6448 else if (!strchr(p
, ' ') &&
6450 lookup_commit_reference_by_name(p
)) &&
6451 *commit_todo_item_at(&commit_todo
, commit2
))
6452 /* found by commit name */
6453 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
6456 /* copy can be a prefix of the commit subject */
6457 for (i2
= 0; i2
< i
; i2
++)
6459 starts_with(subjects
[i2
], p
))
6467 if (starts_with(subject
, "fixup!")) {
6468 todo_list
->items
[i
].command
= TODO_FIXUP
;
6469 } else if (starts_with(subject
, "amend!")) {
6470 todo_list
->items
[i
].command
= TODO_FIXUP
;
6471 todo_list
->items
[i
].flags
= TODO_REPLACE_FIXUP_MSG
;
6473 todo_list
->items
[i
].command
= TODO_SQUASH
;
6479 next
[i
] = next
[tail
[i2
]];
6483 } else if (!hashmap_get_from_hash(&subject2item
,
6484 strhash(subject
), subject
)) {
6485 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
6487 hashmap_entry_init(&entry
->entry
,
6488 strhash(entry
->subject
));
6489 hashmap_put(&subject2item
, &entry
->entry
);
6492 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
6496 ALLOC_ARRAY(items
, todo_list
->nr
);
6498 for (i
= 0; i
< todo_list
->nr
; i
++) {
6499 enum todo_command command
= todo_list
->items
[i
].command
;
6503 * Initially, all commands are 'pick's. If it is a
6504 * fixup or a squash now, we have rearranged it.
6506 if (is_fixup(command
))
6510 items
[nr
++] = todo_list
->items
[cur
];
6515 assert(nr
== todo_list
->nr
);
6516 todo_list
->alloc
= nr
;
6517 FREE_AND_NULL(todo_list
->items
);
6518 todo_list
->items
= items
;
6523 for (i
= 0; i
< todo_list
->nr
; i
++)
6526 hashmap_clear_and_free(&subject2item
, struct subject2item_entry
, entry
);
6528 clear_commit_todo_item(&commit_todo
);
6533 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
6535 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
6536 struct object_id cherry_pick_head
, rebase_head
;
6538 if (file_exists(git_path_seq_dir()))
6539 *whence
= FROM_CHERRY_PICK_MULTI
;
6540 if (file_exists(rebase_path()) &&
6541 !repo_get_oid(r
, "REBASE_HEAD", &rebase_head
) &&
6542 !repo_get_oid(r
, "CHERRY_PICK_HEAD", &cherry_pick_head
) &&
6543 oideq(&rebase_head
, &cherry_pick_head
))
6544 *whence
= FROM_REBASE_PICK
;
6546 *whence
= FROM_CHERRY_PICK_SINGLE
;
6554 int sequencer_get_update_refs_state(const char *wt_dir
,
6555 struct string_list
*refs
)
6559 struct strbuf ref
= STRBUF_INIT
;
6560 struct strbuf hash
= STRBUF_INIT
;
6561 struct update_ref_record
*rec
= NULL
;
6563 char *path
= rebase_path_update_refs(wt_dir
);
6565 fp
= fopen(path
, "r");
6569 while (strbuf_getline(&ref
, fp
) != EOF
) {
6570 struct string_list_item
*item
;
6572 CALLOC_ARRAY(rec
, 1);
6574 if (strbuf_getline(&hash
, fp
) == EOF
||
6575 get_oid_hex(hash
.buf
, &rec
->before
)) {
6576 warning(_("update-refs file at '%s' is invalid"),
6582 if (strbuf_getline(&hash
, fp
) == EOF
||
6583 get_oid_hex(hash
.buf
, &rec
->after
)) {
6584 warning(_("update-refs file at '%s' is invalid"),
6590 item
= string_list_insert(refs
, ref
.buf
);
6600 strbuf_release(&ref
);
6601 strbuf_release(&hash
);