5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-recursive.h"
23 #include "wt-status.h"
25 #include "notes-utils.h"
27 #include "unpack-trees.h"
31 #include "commit-slab.h"
33 #include "commit-reach.h"
34 #include "rebase-interactive.h"
37 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
39 static const char sign_off_header
[] = "Signed-off-by: ";
40 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
42 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
44 static GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
46 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
47 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
48 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
49 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
51 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
53 * The file containing rebase commands, comments, and empty lines.
54 * This file is created by "git rebase -i" then edited by the user. As
55 * the lines are processed, they are removed from the front of this
56 * file and written to the tail of 'done'.
58 GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
59 GIT_PATH_FUNC(rebase_path_todo_backup
, "rebase-merge/git-rebase-todo.backup")
61 GIT_PATH_FUNC(rebase_path_dropped
, "rebase-merge/dropped")
64 * The rebase command lines that have already been processed. A line
65 * is moved here when it is first handled, before any associated user
68 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
70 * The file to keep track of how many commands were already processed (e.g.
73 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
75 * The file to keep track of how many commands are to be processed in total
76 * (e.g. for the prompt).
78 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
80 * The commit message that is planned to be used for any changes that
81 * need to be committed following a user interaction.
83 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
85 * The file into which is accumulated the suggested commit message for
86 * squash/fixup commands. When the first of a series of squash/fixups
87 * is seen, the file is created and the commit message from the
88 * previous commit and from the first squash/fixup commit are written
89 * to it. The commit message for each subsequent squash/fixup commit
90 * is appended to the file as it is processed.
92 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
94 * If the current series of squash/fixups has not yet included a squash
95 * command, then this file exists and holds the commit message of the
96 * original "pick" commit. (If the series ends without a "squash"
97 * command, then this can be used as the commit message of the combined
98 * commit without opening the editor.)
100 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
102 * This file contains the list fixup/squash commands that have been
103 * accumulated into message-fixup or message-squash so far.
105 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
107 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
108 * GIT_AUTHOR_DATE that will be used for the commit that is currently
111 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
113 * When an "edit" rebase command is being processed, the SHA1 of the
114 * commit to be edited is recorded in this file. When "git rebase
115 * --continue" is executed, if there are any staged changes then they
116 * will be amended to the HEAD commit, but only provided the HEAD
117 * commit is still the commit to be edited. When any other rebase
118 * command is processed, this file is deleted.
120 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
122 * When we stop at a given patch via the "edit" command, this file contains
123 * the abbreviated commit name of the corresponding patch.
125 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
127 * For the post-rewrite hook, we make a list of rewritten commits and
128 * their new sha1s. The rewritten-pending list keeps the sha1s of
129 * commits that have been processed, but not committed yet,
130 * e.g. because they are waiting for a 'squash' command.
132 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
133 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
134 "rebase-merge/rewritten-pending")
137 * The path of the file containing the OID of the "squash onto" commit, i.e.
138 * the dummy commit used for `reset [new root]`.
140 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
143 * The path of the file listing refs that need to be deleted after the rebase
144 * finishes. This is used by the `label` command to record the need for cleanup.
146 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
149 * The following files are written by git-rebase just after parsing the
152 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
153 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
154 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
155 static GIT_PATH_FUNC(rebase_path_quiet
, "rebase-merge/quiet")
156 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
157 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
158 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
159 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
160 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
161 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
162 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
163 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec
, "rebase-merge/reschedule-failed-exec")
164 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits
, "rebase-merge/drop_redundant_commits")
165 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits
, "rebase-merge/keep_redundant_commits")
167 static int git_sequencer_config(const char *k
, const char *v
, void *cb
)
169 struct replay_opts
*opts
= cb
;
172 if (!strcmp(k
, "commit.cleanup")) {
175 status
= git_config_string(&s
, k
, v
);
179 if (!strcmp(s
, "verbatim")) {
180 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
181 opts
->explicit_cleanup
= 1;
182 } else if (!strcmp(s
, "whitespace")) {
183 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
184 opts
->explicit_cleanup
= 1;
185 } else if (!strcmp(s
, "strip")) {
186 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
187 opts
->explicit_cleanup
= 1;
188 } else if (!strcmp(s
, "scissors")) {
189 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SCISSORS
;
190 opts
->explicit_cleanup
= 1;
192 warning(_("invalid commit message cleanup mode '%s'"),
200 if (!strcmp(k
, "commit.gpgsign")) {
201 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
205 status
= git_gpg_config(k
, v
, NULL
);
209 return git_diff_basic_config(k
, v
, NULL
);
212 void sequencer_init_config(struct replay_opts
*opts
)
214 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
215 git_config(git_sequencer_config
, opts
);
218 static inline int is_rebase_i(const struct replay_opts
*opts
)
220 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
223 static const char *get_dir(const struct replay_opts
*opts
)
225 if (is_rebase_i(opts
))
226 return rebase_path();
227 return git_path_seq_dir();
230 static const char *get_todo_path(const struct replay_opts
*opts
)
232 if (is_rebase_i(opts
))
233 return rebase_path_todo();
234 return git_path_todo_file();
238 * Returns 0 for non-conforming footer
239 * Returns 1 for conforming footer
240 * Returns 2 when sob exists within conforming footer
241 * Returns 3 when sob exists within conforming footer as last entry
243 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
244 size_t ignore_footer
)
246 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
247 struct trailer_info info
;
249 int found_sob
= 0, found_sob_last
= 0;
253 trailer_info_get(&info
, sb
->buf
, &opts
);
255 if (info
.trailer_start
== info
.trailer_end
)
258 for (i
= 0; i
< info
.trailer_nr
; i
++)
259 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
261 if (i
== info
.trailer_nr
- 1)
265 trailer_info_release(&info
);
274 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
276 static struct strbuf buf
= STRBUF_INIT
;
280 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
284 int sequencer_remove_state(struct replay_opts
*opts
)
286 struct strbuf buf
= STRBUF_INIT
;
289 if (is_rebase_i(opts
) &&
290 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
293 char *eol
= strchr(p
, '\n');
296 if (delete_ref("(rebase) cleanup", p
, NULL
, 0) < 0) {
297 warning(_("could not delete '%s'"), p
);
306 free(opts
->gpg_sign
);
307 free(opts
->strategy
);
308 for (i
= 0; i
< opts
->xopts_nr
; i
++)
309 free(opts
->xopts
[i
]);
311 strbuf_release(&opts
->current_fixups
);
314 strbuf_addstr(&buf
, get_dir(opts
));
315 if (remove_dir_recursively(&buf
, 0))
316 ret
= error(_("could not remove '%s'"), buf
.buf
);
317 strbuf_release(&buf
);
322 static const char *action_name(const struct replay_opts
*opts
)
324 switch (opts
->action
) {
328 return N_("cherry-pick");
329 case REPLAY_INTERACTIVE_REBASE
:
332 die(_("unknown action: %d"), opts
->action
);
335 struct commit_message
{
342 static const char *short_commit_name(struct commit
*commit
)
344 return find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
);
347 static int get_message(struct commit
*commit
, struct commit_message
*out
)
349 const char *abbrev
, *subject
;
352 out
->message
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
353 abbrev
= short_commit_name(commit
);
355 subject_len
= find_commit_subject(out
->message
, &subject
);
357 out
->subject
= xmemdupz(subject
, subject_len
);
358 out
->label
= xstrfmt("%s... %s", abbrev
, out
->subject
);
359 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
364 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
366 free(msg
->parent_label
);
369 unuse_commit_buffer(commit
, msg
->message
);
372 static void print_advice(struct repository
*r
, int show_hint
,
373 struct replay_opts
*opts
)
375 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
378 fprintf(stderr
, "%s\n", msg
);
380 * A conflict has occurred but the porcelain
381 * (typically rebase --interactive) wants to take care
382 * of the commit itself so remove CHERRY_PICK_HEAD
384 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
391 advise(_("after resolving the conflicts, mark the corrected paths\n"
392 "with 'git add <paths>' or 'git rm <paths>'"));
394 advise(_("after resolving the conflicts, mark the corrected paths\n"
395 "with 'git add <paths>' or 'git rm <paths>'\n"
396 "and commit the result with 'git commit'"));
400 static int write_message(const void *buf
, size_t len
, const char *filename
,
403 struct lock_file msg_file
= LOCK_INIT
;
405 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
407 return error_errno(_("could not lock '%s'"), filename
);
408 if (write_in_full(msg_fd
, buf
, len
) < 0) {
409 error_errno(_("could not write to '%s'"), filename
);
410 rollback_lock_file(&msg_file
);
413 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
414 error_errno(_("could not write eol to '%s'"), filename
);
415 rollback_lock_file(&msg_file
);
418 if (commit_lock_file(&msg_file
) < 0)
419 return error(_("failed to finalize '%s'"), filename
);
424 int read_oneliner(struct strbuf
*buf
,
425 const char *path
, unsigned flags
)
427 int orig_len
= buf
->len
;
429 if (strbuf_read_file(buf
, path
, 0) < 0) {
430 if ((flags
& READ_ONELINER_WARN_MISSING
) ||
431 (errno
!= ENOENT
&& errno
!= ENOTDIR
))
432 warning_errno(_("could not read '%s'"), path
);
436 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
437 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
439 buf
->buf
[buf
->len
] = '\0';
442 if ((flags
& READ_ONELINER_SKIP_IF_EMPTY
) && buf
->len
== orig_len
)
448 static struct tree
*empty_tree(struct repository
*r
)
450 return lookup_tree(r
, the_hash_algo
->empty_tree
);
453 static int error_dirty_index(struct repository
*repo
, struct replay_opts
*opts
)
455 if (repo_read_index_unmerged(repo
))
456 return error_resolve_conflict(_(action_name(opts
)));
458 error(_("your local changes would be overwritten by %s."),
459 _(action_name(opts
)));
461 if (advice_commit_before_merge
)
462 advise(_("commit your changes or stash them to proceed."));
466 static void update_abort_safety_file(void)
468 struct object_id head
;
470 /* Do nothing on a single-pick */
471 if (!file_exists(git_path_seq_dir()))
474 if (!get_oid("HEAD", &head
))
475 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
477 write_file(git_path_abort_safety_file(), "%s", "");
480 static int fast_forward_to(struct repository
*r
,
481 const struct object_id
*to
,
482 const struct object_id
*from
,
484 struct replay_opts
*opts
)
486 struct ref_transaction
*transaction
;
487 struct strbuf sb
= STRBUF_INIT
;
488 struct strbuf err
= STRBUF_INIT
;
491 if (checkout_fast_forward(r
, from
, to
, 1))
492 return -1; /* the callee should have complained already */
494 strbuf_addf(&sb
, _("%s: fast-forward"), _(action_name(opts
)));
496 transaction
= ref_transaction_begin(&err
);
498 ref_transaction_update(transaction
, "HEAD",
499 to
, unborn
&& !is_rebase_i(opts
) ?
502 ref_transaction_commit(transaction
, &err
)) {
503 ref_transaction_free(transaction
);
504 error("%s", err
.buf
);
506 strbuf_release(&err
);
511 strbuf_release(&err
);
512 ref_transaction_free(transaction
);
513 update_abort_safety_file();
517 enum commit_msg_cleanup_mode
get_cleanup_mode(const char *cleanup_arg
,
520 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
521 return use_editor
? COMMIT_MSG_CLEANUP_ALL
:
522 COMMIT_MSG_CLEANUP_SPACE
;
523 else if (!strcmp(cleanup_arg
, "verbatim"))
524 return COMMIT_MSG_CLEANUP_NONE
;
525 else if (!strcmp(cleanup_arg
, "whitespace"))
526 return COMMIT_MSG_CLEANUP_SPACE
;
527 else if (!strcmp(cleanup_arg
, "strip"))
528 return COMMIT_MSG_CLEANUP_ALL
;
529 else if (!strcmp(cleanup_arg
, "scissors"))
530 return use_editor
? COMMIT_MSG_CLEANUP_SCISSORS
:
531 COMMIT_MSG_CLEANUP_SPACE
;
533 die(_("Invalid cleanup mode %s"), cleanup_arg
);
537 * NB using int rather than enum cleanup_mode to stop clang's
538 * -Wtautological-constant-out-of-range-compare complaining that the comparison
541 static const char *describe_cleanup_mode(int cleanup_mode
)
543 static const char *modes
[] = { "whitespace",
548 if (cleanup_mode
< ARRAY_SIZE(modes
))
549 return modes
[cleanup_mode
];
551 BUG("invalid cleanup_mode provided (%d)", cleanup_mode
);
554 void append_conflicts_hint(struct index_state
*istate
,
555 struct strbuf
*msgbuf
, enum commit_msg_cleanup_mode cleanup_mode
)
559 if (cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
) {
560 strbuf_addch(msgbuf
, '\n');
561 wt_status_append_cut_line(msgbuf
);
562 strbuf_addch(msgbuf
, comment_line_char
);
565 strbuf_addch(msgbuf
, '\n');
566 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
567 for (i
= 0; i
< istate
->cache_nr
;) {
568 const struct cache_entry
*ce
= istate
->cache
[i
++];
570 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
571 while (i
< istate
->cache_nr
&&
572 !strcmp(ce
->name
, istate
->cache
[i
]->name
))
578 static int do_recursive_merge(struct repository
*r
,
579 struct commit
*base
, struct commit
*next
,
580 const char *base_label
, const char *next_label
,
581 struct object_id
*head
, struct strbuf
*msgbuf
,
582 struct replay_opts
*opts
)
584 struct merge_options o
;
585 struct tree
*next_tree
, *base_tree
, *head_tree
;
588 struct lock_file index_lock
= LOCK_INIT
;
590 if (repo_hold_locked_index(r
, &index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
595 init_merge_options(&o
, r
);
596 o
.ancestor
= base
? base_label
: "(empty tree)";
598 o
.branch2
= next
? next_label
: "(empty tree)";
599 if (is_rebase_i(opts
))
601 o
.show_rename_progress
= 1;
603 head_tree
= parse_tree_indirect(head
);
604 next_tree
= next
? get_commit_tree(next
) : empty_tree(r
);
605 base_tree
= base
? get_commit_tree(base
) : empty_tree(r
);
607 for (i
= 0; i
< opts
->xopts_nr
; i
++)
608 parse_merge_opt(&o
, opts
->xopts
[i
]);
610 clean
= merge_trees(&o
,
612 next_tree
, base_tree
);
613 if (is_rebase_i(opts
) && clean
<= 0)
614 fputs(o
.obuf
.buf
, stdout
);
615 strbuf_release(&o
.obuf
);
617 rollback_lock_file(&index_lock
);
621 if (write_locked_index(r
->index
, &index_lock
,
622 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
624 * TRANSLATORS: %s will be "revert", "cherry-pick" or
627 return error(_("%s: Unable to write new index file"),
628 _(action_name(opts
)));
631 append_conflicts_hint(r
->index
, msgbuf
,
632 opts
->default_msg_cleanup
);
637 static struct object_id
*get_cache_tree_oid(struct index_state
*istate
)
639 if (!istate
->cache_tree
)
640 istate
->cache_tree
= cache_tree();
642 if (!cache_tree_fully_valid(istate
->cache_tree
))
643 if (cache_tree_update(istate
, 0)) {
644 error(_("unable to update cache tree"));
648 return &istate
->cache_tree
->oid
;
651 static int is_index_unchanged(struct repository
*r
)
653 struct object_id head_oid
, *cache_tree_oid
;
654 struct commit
*head_commit
;
655 struct index_state
*istate
= r
->index
;
657 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
658 return error(_("could not resolve HEAD commit"));
660 head_commit
= lookup_commit(r
, &head_oid
);
663 * If head_commit is NULL, check_commit, called from
664 * lookup_commit, would have indicated that head_commit is not
665 * a commit object already. parse_commit() will return failure
666 * without further complaints in such a case. Otherwise, if
667 * the commit is invalid, parse_commit() will complain. So
668 * there is nothing for us to say here. Just return failure.
670 if (parse_commit(head_commit
))
673 if (!(cache_tree_oid
= get_cache_tree_oid(istate
)))
676 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
679 static int write_author_script(const char *message
)
681 struct strbuf buf
= STRBUF_INIT
;
686 if (!*message
|| starts_with(message
, "\n")) {
688 /* Missing 'author' line? */
689 unlink(rebase_path_author_script());
691 } else if (skip_prefix(message
, "author ", &message
))
693 else if ((eol
= strchr(message
, '\n')))
698 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
699 while (*message
&& *message
!= '\n' && *message
!= '\r')
700 if (skip_prefix(message
, " <", &message
))
702 else if (*message
!= '\'')
703 strbuf_addch(&buf
, *(message
++));
705 strbuf_addf(&buf
, "'\\%c'", *(message
++));
706 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
707 while (*message
&& *message
!= '\n' && *message
!= '\r')
708 if (skip_prefix(message
, "> ", &message
))
710 else if (*message
!= '\'')
711 strbuf_addch(&buf
, *(message
++));
713 strbuf_addf(&buf
, "'\\%c'", *(message
++));
714 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
715 while (*message
&& *message
!= '\n' && *message
!= '\r')
716 if (*message
!= '\'')
717 strbuf_addch(&buf
, *(message
++));
719 strbuf_addf(&buf
, "'\\%c'", *(message
++));
720 strbuf_addch(&buf
, '\'');
721 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
722 strbuf_release(&buf
);
727 * Take a series of KEY='VALUE' lines where VALUE part is
728 * sq-quoted, and append <KEY, VALUE> at the end of the string list
730 static int parse_key_value_squoted(char *buf
, struct string_list
*list
)
733 struct string_list_item
*item
;
735 char *cp
= strchr(buf
, '=');
737 np
= strchrnul(buf
, '\n');
738 return error(_("no key present in '%.*s'"),
739 (int) (np
- buf
), buf
);
741 np
= strchrnul(cp
, '\n');
743 item
= string_list_append(list
, buf
);
745 buf
= np
+ (*np
== '\n');
749 return error(_("unable to dequote value of '%s'"),
751 item
->util
= xstrdup(cp
);
757 * Reads and parses the state directory's "author-script" file, and sets name,
758 * email and date accordingly.
759 * Returns 0 on success, -1 if the file could not be parsed.
761 * The author script is of the format:
763 * GIT_AUTHOR_NAME='$author_name'
764 * GIT_AUTHOR_EMAIL='$author_email'
765 * GIT_AUTHOR_DATE='$author_date'
767 * where $author_name, $author_email and $author_date are quoted. We are strict
768 * with our parsing, as the file was meant to be eval'd in the now-removed
769 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
770 * from what this function expects, it is better to bail out than to do
771 * something that the user does not expect.
773 int read_author_script(const char *path
, char **name
, char **email
, char **date
,
776 struct strbuf buf
= STRBUF_INIT
;
777 struct string_list kv
= STRING_LIST_INIT_DUP
;
778 int retval
= -1; /* assume failure */
779 int i
, name_i
= -2, email_i
= -2, date_i
= -2, err
= 0;
781 if (strbuf_read_file(&buf
, path
, 256) <= 0) {
782 strbuf_release(&buf
);
783 if (errno
== ENOENT
&& allow_missing
)
786 return error_errno(_("could not open '%s' for reading"),
790 if (parse_key_value_squoted(buf
.buf
, &kv
))
793 for (i
= 0; i
< kv
.nr
; i
++) {
794 if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_NAME")) {
796 name_i
= error(_("'GIT_AUTHOR_NAME' already given"));
799 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_EMAIL")) {
801 email_i
= error(_("'GIT_AUTHOR_EMAIL' already given"));
804 } else if (!strcmp(kv
.items
[i
].string
, "GIT_AUTHOR_DATE")) {
806 date_i
= error(_("'GIT_AUTHOR_DATE' already given"));
810 err
= error(_("unknown variable '%s'"),
815 error(_("missing 'GIT_AUTHOR_NAME'"));
817 error(_("missing 'GIT_AUTHOR_EMAIL'"));
819 error(_("missing 'GIT_AUTHOR_DATE'"));
820 if (date_i
< 0 || email_i
< 0 || date_i
< 0 || err
)
822 *name
= kv
.items
[name_i
].util
;
823 *email
= kv
.items
[email_i
].util
;
824 *date
= kv
.items
[date_i
].util
;
827 string_list_clear(&kv
, !!retval
);
828 strbuf_release(&buf
);
833 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
834 * file with shell quoting into struct strvec. Returns -1 on
835 * error, 0 otherwise.
837 static int read_env_script(struct strvec
*env
)
839 char *name
, *email
, *date
;
841 if (read_author_script(rebase_path_author_script(),
842 &name
, &email
, &date
, 0))
845 strvec_pushf(env
, "GIT_AUTHOR_NAME=%s", name
);
846 strvec_pushf(env
, "GIT_AUTHOR_EMAIL=%s", email
);
847 strvec_pushf(env
, "GIT_AUTHOR_DATE=%s", date
);
855 static char *get_author(const char *message
)
860 a
= find_commit_header(message
, "author", &len
);
862 return xmemdupz(a
, len
);
867 static const char staged_changes_advice
[] =
868 N_("you have staged changes in your working tree\n"
869 "If these changes are meant to be squashed into the previous commit, run:\n"
871 " git commit --amend %s\n"
873 "If they are meant to go into a new commit, run:\n"
877 "In both cases, once you're done, continue with:\n"
879 " git rebase --continue\n");
881 #define ALLOW_EMPTY (1<<0)
882 #define EDIT_MSG (1<<1)
883 #define AMEND_MSG (1<<2)
884 #define CLEANUP_MSG (1<<3)
885 #define VERIFY_MSG (1<<4)
886 #define CREATE_ROOT_COMMIT (1<<5)
888 static int run_command_silent_on_success(struct child_process
*cmd
)
890 struct strbuf buf
= STRBUF_INIT
;
893 cmd
->stdout_to_stderr
= 1;
894 rc
= pipe_command(cmd
,
900 fputs(buf
.buf
, stderr
);
901 strbuf_release(&buf
);
906 * If we are cherry-pick, and if the merge did not result in
907 * hand-editing, we will hit this commit and inherit the original
908 * author date and name.
910 * If we are revert, or if our cherry-pick results in a hand merge,
911 * we had better say that the current user is responsible for that.
913 * An exception is when run_git_commit() is called during an
914 * interactive rebase: in that case, we will want to retain the
917 static int run_git_commit(struct repository
*r
,
919 struct replay_opts
*opts
,
922 struct child_process cmd
= CHILD_PROCESS_INIT
;
926 if (is_rebase_i(opts
) && read_env_script(&cmd
.env_array
)) {
927 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
929 return error(_(staged_changes_advice
),
933 strvec_push(&cmd
.args
, "commit");
935 if (!(flags
& VERIFY_MSG
))
936 strvec_push(&cmd
.args
, "-n");
937 if ((flags
& AMEND_MSG
))
938 strvec_push(&cmd
.args
, "--amend");
940 strvec_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
942 strvec_push(&cmd
.args
, "--no-gpg-sign");
944 strvec_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
945 else if (!(flags
& EDIT_MSG
))
946 strvec_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
947 if ((flags
& CLEANUP_MSG
))
948 strvec_push(&cmd
.args
, "--cleanup=strip");
949 if ((flags
& EDIT_MSG
))
950 strvec_push(&cmd
.args
, "-e");
951 else if (!(flags
& CLEANUP_MSG
) &&
952 !opts
->signoff
&& !opts
->record_origin
&&
953 !opts
->explicit_cleanup
)
954 strvec_push(&cmd
.args
, "--cleanup=verbatim");
956 if ((flags
& ALLOW_EMPTY
))
957 strvec_push(&cmd
.args
, "--allow-empty");
959 if (!(flags
& EDIT_MSG
))
960 strvec_push(&cmd
.args
, "--allow-empty-message");
962 if (is_rebase_i(opts
) && !(flags
& EDIT_MSG
))
963 return run_command_silent_on_success(&cmd
);
965 return run_command(&cmd
);
968 static int rest_is_empty(const struct strbuf
*sb
, int start
)
973 /* Check if the rest is just whitespace and Signed-off-by's. */
974 for (i
= start
; i
< sb
->len
; i
++) {
975 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
981 if (strlen(sign_off_header
) <= eol
- i
&&
982 starts_with(sb
->buf
+ i
, sign_off_header
)) {
987 if (!isspace(sb
->buf
[i
++]))
994 void cleanup_message(struct strbuf
*msgbuf
,
995 enum commit_msg_cleanup_mode cleanup_mode
, int verbose
)
997 if (verbose
|| /* Truncate the message just before the diff, if any. */
998 cleanup_mode
== COMMIT_MSG_CLEANUP_SCISSORS
)
999 strbuf_setlen(msgbuf
, wt_status_locate_end(msgbuf
->buf
, msgbuf
->len
));
1000 if (cleanup_mode
!= COMMIT_MSG_CLEANUP_NONE
)
1001 strbuf_stripspace(msgbuf
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
1005 * Find out if the message in the strbuf contains only whitespace and
1006 * Signed-off-by lines.
1008 int message_is_empty(const struct strbuf
*sb
,
1009 enum commit_msg_cleanup_mode cleanup_mode
)
1011 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1013 return rest_is_empty(sb
, 0);
1017 * See if the user edited the message in the editor or left what
1018 * was in the template intact
1020 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
1021 enum commit_msg_cleanup_mode cleanup_mode
)
1023 struct strbuf tmpl
= STRBUF_INIT
;
1026 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
1029 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
1032 strbuf_stripspace(&tmpl
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
1033 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
1035 strbuf_release(&tmpl
);
1036 return rest_is_empty(sb
, start
- sb
->buf
);
1039 int update_head_with_reflog(const struct commit
*old_head
,
1040 const struct object_id
*new_head
,
1041 const char *action
, const struct strbuf
*msg
,
1044 struct ref_transaction
*transaction
;
1045 struct strbuf sb
= STRBUF_INIT
;
1050 strbuf_addstr(&sb
, action
);
1051 strbuf_addstr(&sb
, ": ");
1054 nl
= strchr(msg
->buf
, '\n');
1056 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1058 strbuf_addbuf(&sb
, msg
);
1059 strbuf_addch(&sb
, '\n');
1062 transaction
= ref_transaction_begin(err
);
1064 ref_transaction_update(transaction
, "HEAD", new_head
,
1065 old_head
? &old_head
->object
.oid
: &null_oid
,
1067 ref_transaction_commit(transaction
, err
)) {
1070 ref_transaction_free(transaction
);
1071 strbuf_release(&sb
);
1076 static int run_rewrite_hook(const struct object_id
*oldoid
,
1077 const struct object_id
*newoid
)
1079 struct child_process proc
= CHILD_PROCESS_INIT
;
1080 const char *argv
[3];
1082 struct strbuf sb
= STRBUF_INIT
;
1084 argv
[0] = find_hook("post-rewrite");
1093 proc
.stdout_to_stderr
= 1;
1094 proc
.trace2_hook_name
= "post-rewrite";
1096 code
= start_command(&proc
);
1099 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1100 sigchain_push(SIGPIPE
, SIG_IGN
);
1101 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1103 strbuf_release(&sb
);
1104 sigchain_pop(SIGPIPE
);
1105 return finish_command(&proc
);
1108 void commit_post_rewrite(struct repository
*r
,
1109 const struct commit
*old_head
,
1110 const struct object_id
*new_head
)
1112 struct notes_rewrite_cfg
*cfg
;
1114 cfg
= init_copy_notes_for_rewrite("amend");
1116 /* we are amending, so old_head is not NULL */
1117 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1118 finish_copy_notes_for_rewrite(r
, cfg
, "Notes added by 'git commit --amend'");
1120 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1123 static int run_prepare_commit_msg_hook(struct repository
*r
,
1128 const char *name
, *arg1
= NULL
, *arg2
= NULL
;
1130 name
= git_path_commit_editmsg();
1131 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1140 if (run_commit_hook(0, r
->index_file
, "prepare-commit-msg", name
,
1142 ret
= error(_("'prepare-commit-msg' hook failed"));
1147 static const char implicit_ident_advice_noconfig
[] =
1148 N_("Your name and email address were configured automatically based\n"
1149 "on your username and hostname. Please check that they are accurate.\n"
1150 "You can suppress this message by setting them explicitly. Run the\n"
1151 "following command and follow the instructions in your editor to edit\n"
1152 "your configuration file:\n"
1154 " git config --global --edit\n"
1156 "After doing this, you may fix the identity used for this commit with:\n"
1158 " git commit --amend --reset-author\n");
1160 static const char implicit_ident_advice_config
[] =
1161 N_("Your name and email address were configured automatically based\n"
1162 "on your username and hostname. Please check that they are accurate.\n"
1163 "You can suppress this message by setting them explicitly:\n"
1165 " git config --global user.name \"Your Name\"\n"
1166 " git config --global user.email you@example.com\n"
1168 "After doing this, you may fix the identity used for this commit with:\n"
1170 " git commit --amend --reset-author\n");
1172 static const char *implicit_ident_advice(void)
1174 char *user_config
= expand_user_path("~/.gitconfig", 0);
1175 char *xdg_config
= xdg_config_home("config");
1176 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1182 return _(implicit_ident_advice_config
);
1184 return _(implicit_ident_advice_noconfig
);
1188 void print_commit_summary(struct repository
*r
,
1190 const struct object_id
*oid
,
1193 struct rev_info rev
;
1194 struct commit
*commit
;
1195 struct strbuf format
= STRBUF_INIT
;
1197 struct pretty_print_context pctx
= {0};
1198 struct strbuf author_ident
= STRBUF_INIT
;
1199 struct strbuf committer_ident
= STRBUF_INIT
;
1201 commit
= lookup_commit(r
, oid
);
1203 die(_("couldn't look up newly created commit"));
1204 if (parse_commit(commit
))
1205 die(_("could not parse newly created commit"));
1207 strbuf_addstr(&format
, "format:%h] %s");
1209 format_commit_message(commit
, "%an <%ae>", &author_ident
, &pctx
);
1210 format_commit_message(commit
, "%cn <%ce>", &committer_ident
, &pctx
);
1211 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1212 strbuf_addstr(&format
, "\n Author: ");
1213 strbuf_addbuf_percentquote(&format
, &author_ident
);
1215 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1216 struct strbuf date
= STRBUF_INIT
;
1218 format_commit_message(commit
, "%ad", &date
, &pctx
);
1219 strbuf_addstr(&format
, "\n Date: ");
1220 strbuf_addbuf_percentquote(&format
, &date
);
1221 strbuf_release(&date
);
1223 if (!committer_ident_sufficiently_given()) {
1224 strbuf_addstr(&format
, "\n Committer: ");
1225 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1226 if (advice_implicit_identity
) {
1227 strbuf_addch(&format
, '\n');
1228 strbuf_addstr(&format
, implicit_ident_advice());
1231 strbuf_release(&author_ident
);
1232 strbuf_release(&committer_ident
);
1234 repo_init_revisions(r
, &rev
, prefix
);
1235 setup_revisions(0, NULL
, &rev
, NULL
);
1238 rev
.diffopt
.output_format
=
1239 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1241 rev
.verbose_header
= 1;
1242 rev
.show_root_diff
= 1;
1243 get_commit_format(format
.buf
, &rev
);
1244 rev
.always_show_header
= 0;
1245 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1246 rev
.diffopt
.break_opt
= 0;
1247 diff_setup_done(&rev
.diffopt
);
1249 head
= resolve_ref_unsafe("HEAD", 0, NULL
, NULL
);
1251 die_errno(_("unable to resolve HEAD after creating commit"));
1252 if (!strcmp(head
, "HEAD"))
1253 head
= _("detached HEAD");
1255 skip_prefix(head
, "refs/heads/", &head
);
1256 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1257 _(" (root-commit)") : "");
1259 if (!log_tree_commit(&rev
, commit
)) {
1260 rev
.always_show_header
= 1;
1261 rev
.use_terminator
= 1;
1262 log_tree_commit(&rev
, commit
);
1265 strbuf_release(&format
);
1268 static int parse_head(struct repository
*r
, struct commit
**head
)
1270 struct commit
*current_head
;
1271 struct object_id oid
;
1273 if (get_oid("HEAD", &oid
)) {
1274 current_head
= NULL
;
1276 current_head
= lookup_commit_reference(r
, &oid
);
1278 return error(_("could not parse HEAD"));
1279 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1280 warning(_("HEAD %s is not a commit!"),
1283 if (parse_commit(current_head
))
1284 return error(_("could not parse HEAD commit"));
1286 *head
= current_head
;
1292 * Try to commit without forking 'git commit'. In some cases we need
1293 * to run 'git commit' to display an error message
1296 * -1 - error unable to commit
1298 * 1 - run 'git commit'
1300 static int try_to_commit(struct repository
*r
,
1301 struct strbuf
*msg
, const char *author
,
1302 struct replay_opts
*opts
, unsigned int flags
,
1303 struct object_id
*oid
)
1305 struct object_id tree
;
1306 struct commit
*current_head
= NULL
;
1307 struct commit_list
*parents
= NULL
;
1308 struct commit_extra_header
*extra
= NULL
;
1309 struct strbuf err
= STRBUF_INIT
;
1310 struct strbuf commit_msg
= STRBUF_INIT
;
1311 char *amend_author
= NULL
;
1312 const char *hook_commit
= NULL
;
1313 enum commit_msg_cleanup_mode cleanup
;
1316 if (parse_head(r
, ¤t_head
))
1319 if (flags
& AMEND_MSG
) {
1320 const char *exclude_gpgsig
[] = { "gpgsig", "gpgsig-sha256", NULL
};
1321 const char *out_enc
= get_commit_output_encoding();
1322 const char *message
= logmsg_reencode(current_head
, NULL
,
1326 const char *orig_message
= NULL
;
1328 find_commit_subject(message
, &orig_message
);
1330 strbuf_addstr(msg
, orig_message
);
1331 hook_commit
= "HEAD";
1333 author
= amend_author
= get_author(message
);
1334 unuse_commit_buffer(current_head
, message
);
1336 res
= error(_("unable to parse commit author"));
1339 parents
= copy_commit_list(current_head
->parents
);
1340 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1341 } else if (current_head
&&
1342 (!(flags
& CREATE_ROOT_COMMIT
) || (flags
& AMEND_MSG
))) {
1343 commit_list_insert(current_head
, &parents
);
1346 if (write_index_as_tree(&tree
, r
->index
, r
->index_file
, 0, NULL
)) {
1347 res
= error(_("git write-tree failed to write a tree"));
1351 if (!(flags
& ALLOW_EMPTY
)) {
1352 struct commit
*first_parent
= current_head
;
1354 if (flags
& AMEND_MSG
) {
1355 if (current_head
->parents
) {
1356 first_parent
= current_head
->parents
->item
;
1357 if (repo_parse_commit(r
, first_parent
)) {
1358 res
= error(_("could not parse HEAD commit"));
1362 first_parent
= NULL
;
1365 if (oideq(first_parent
1366 ? get_commit_tree_oid(first_parent
)
1367 : the_hash_algo
->empty_tree
,
1369 res
= 1; /* run 'git commit' to display error message */
1374 if (find_hook("prepare-commit-msg")) {
1375 res
= run_prepare_commit_msg_hook(r
, msg
, hook_commit
);
1378 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1380 res
= error_errno(_("unable to read commit message "
1382 git_path_commit_editmsg());
1388 if (flags
& CLEANUP_MSG
)
1389 cleanup
= COMMIT_MSG_CLEANUP_ALL
;
1390 else if ((opts
->signoff
|| opts
->record_origin
) &&
1391 !opts
->explicit_cleanup
)
1392 cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
1394 cleanup
= opts
->default_msg_cleanup
;
1396 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1397 strbuf_stripspace(msg
, cleanup
== COMMIT_MSG_CLEANUP_ALL
);
1398 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1399 res
= 1; /* run 'git commit' to display error message */
1405 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
,
1406 oid
, author
, opts
->gpg_sign
, extra
)) {
1407 res
= error(_("failed to write commit object"));
1411 if (update_head_with_reflog(current_head
, oid
,
1412 getenv("GIT_REFLOG_ACTION"), msg
, &err
)) {
1413 res
= error("%s", err
.buf
);
1417 run_commit_hook(0, r
->index_file
, "post-commit", NULL
);
1418 if (flags
& AMEND_MSG
)
1419 commit_post_rewrite(r
, current_head
, oid
);
1422 free_commit_extra_headers(extra
);
1423 strbuf_release(&err
);
1424 strbuf_release(&commit_msg
);
1430 static int write_rebase_head(struct object_id
*oid
)
1432 if (update_ref("rebase", "REBASE_HEAD", oid
,
1433 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1434 return error(_("could not update %s"), "REBASE_HEAD");
1439 static int do_commit(struct repository
*r
,
1440 const char *msg_file
, const char *author
,
1441 struct replay_opts
*opts
, unsigned int flags
,
1442 struct object_id
*oid
)
1446 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
)) {
1447 struct object_id oid
;
1448 struct strbuf sb
= STRBUF_INIT
;
1450 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1451 return error_errno(_("unable to read commit message "
1455 res
= try_to_commit(r
, msg_file
? &sb
: NULL
,
1456 author
, opts
, flags
, &oid
);
1457 strbuf_release(&sb
);
1459 refs_delete_ref(get_main_ref_store(r
), "",
1460 "CHERRY_PICK_HEAD", NULL
, 0);
1461 unlink(git_path_merge_msg(r
));
1462 if (!is_rebase_i(opts
))
1463 print_commit_summary(r
, NULL
, &oid
,
1464 SUMMARY_SHOW_AUTHOR_DATE
);
1469 if (is_rebase_i(opts
) && oid
)
1470 if (write_rebase_head(oid
))
1472 return run_git_commit(r
, msg_file
, opts
, flags
);
1478 static int is_original_commit_empty(struct commit
*commit
)
1480 const struct object_id
*ptree_oid
;
1482 if (parse_commit(commit
))
1483 return error(_("could not parse commit %s"),
1484 oid_to_hex(&commit
->object
.oid
));
1485 if (commit
->parents
) {
1486 struct commit
*parent
= commit
->parents
->item
;
1487 if (parse_commit(parent
))
1488 return error(_("could not parse parent commit %s"),
1489 oid_to_hex(&parent
->object
.oid
));
1490 ptree_oid
= get_commit_tree_oid(parent
);
1492 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1495 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1499 * Should empty commits be allowed? Return status:
1500 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1501 * 0: Halt on empty commit
1502 * 1: Allow empty commit
1503 * 2: Drop empty commit
1505 static int allow_empty(struct repository
*r
,
1506 struct replay_opts
*opts
,
1507 struct commit
*commit
)
1509 int index_unchanged
, originally_empty
;
1514 * (1) we do not allow empty at all and error out.
1516 * (2) we allow ones that were initially empty, and
1517 * just drop the ones that become empty
1519 * (3) we allow ones that were initially empty, but
1520 * halt for the ones that become empty;
1522 * (4) we allow both.
1524 if (!opts
->allow_empty
)
1525 return 0; /* let "git commit" barf as necessary */
1527 index_unchanged
= is_index_unchanged(r
);
1528 if (index_unchanged
< 0)
1529 return index_unchanged
;
1530 if (!index_unchanged
)
1531 return 0; /* we do not have to say --allow-empty */
1533 if (opts
->keep_redundant_commits
)
1536 originally_empty
= is_original_commit_empty(commit
);
1537 if (originally_empty
< 0)
1538 return originally_empty
;
1539 if (originally_empty
)
1541 else if (opts
->drop_redundant_commits
)
1550 } todo_command_info
[] = {
1567 static const char *command_to_string(const enum todo_command command
)
1569 if (command
< TODO_COMMENT
)
1570 return todo_command_info
[command
].str
;
1571 die(_("unknown command: %d"), command
);
1574 static char command_to_char(const enum todo_command command
)
1576 if (command
< TODO_COMMENT
)
1577 return todo_command_info
[command
].c
;
1578 return comment_line_char
;
1581 static int is_noop(const enum todo_command command
)
1583 return TODO_NOOP
<= command
;
1586 static int is_fixup(enum todo_command command
)
1588 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1591 /* Does this command create a (non-merge) commit? */
1592 static int is_pick_or_similar(enum todo_command command
)
1607 static int update_squash_messages(struct repository
*r
,
1608 enum todo_command command
,
1609 struct commit
*commit
,
1610 struct replay_opts
*opts
)
1612 struct strbuf buf
= STRBUF_INIT
;
1614 const char *message
, *body
;
1615 const char *encoding
= get_commit_output_encoding();
1617 if (opts
->current_fixup_count
> 0) {
1618 struct strbuf header
= STRBUF_INIT
;
1621 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
1622 return error(_("could not read '%s'"),
1623 rebase_path_squash_msg());
1625 eol
= buf
.buf
[0] != comment_line_char
?
1626 buf
.buf
: strchrnul(buf
.buf
, '\n');
1628 strbuf_addf(&header
, "%c ", comment_line_char
);
1629 strbuf_addf(&header
, _("This is a combination of %d commits."),
1630 opts
->current_fixup_count
+ 2);
1631 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
1632 strbuf_release(&header
);
1634 struct object_id head
;
1635 struct commit
*head_commit
;
1636 const char *head_message
, *body
;
1638 if (get_oid("HEAD", &head
))
1639 return error(_("need a HEAD to fixup"));
1640 if (!(head_commit
= lookup_commit_reference(r
, &head
)))
1641 return error(_("could not read HEAD"));
1642 if (!(head_message
= logmsg_reencode(head_commit
, NULL
, encoding
)))
1643 return error(_("could not read HEAD's commit message"));
1645 find_commit_subject(head_message
, &body
);
1646 if (write_message(body
, strlen(body
),
1647 rebase_path_fixup_msg(), 0)) {
1648 unuse_commit_buffer(head_commit
, head_message
);
1649 return error(_("cannot write '%s'"),
1650 rebase_path_fixup_msg());
1653 strbuf_addf(&buf
, "%c ", comment_line_char
);
1654 strbuf_addf(&buf
, _("This is a combination of %d commits."), 2);
1655 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1656 strbuf_addstr(&buf
, _("This is the 1st commit message:"));
1657 strbuf_addstr(&buf
, "\n\n");
1658 strbuf_addstr(&buf
, body
);
1660 unuse_commit_buffer(head_commit
, head_message
);
1663 if (!(message
= logmsg_reencode(commit
, NULL
, encoding
)))
1664 return error(_("could not read commit message of %s"),
1665 oid_to_hex(&commit
->object
.oid
));
1666 find_commit_subject(message
, &body
);
1668 if (command
== TODO_SQUASH
) {
1669 unlink(rebase_path_fixup_msg());
1670 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1671 strbuf_addf(&buf
, _("This is the commit message #%d:"),
1672 ++opts
->current_fixup_count
+ 1);
1673 strbuf_addstr(&buf
, "\n\n");
1674 strbuf_addstr(&buf
, body
);
1675 } else if (command
== TODO_FIXUP
) {
1676 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1677 strbuf_addf(&buf
, _("The commit message #%d will be skipped:"),
1678 ++opts
->current_fixup_count
+ 1);
1679 strbuf_addstr(&buf
, "\n\n");
1680 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
1682 return error(_("unknown command: %d"), command
);
1683 unuse_commit_buffer(commit
, message
);
1685 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(), 0);
1686 strbuf_release(&buf
);
1689 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
1690 opts
->current_fixups
.len
? "\n" : "",
1691 command_to_string(command
),
1692 oid_to_hex(&commit
->object
.oid
));
1693 res
= write_message(opts
->current_fixups
.buf
,
1694 opts
->current_fixups
.len
,
1695 rebase_path_current_fixups(), 0);
1701 static void flush_rewritten_pending(void)
1703 struct strbuf buf
= STRBUF_INIT
;
1704 struct object_id newoid
;
1707 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
1708 !get_oid("HEAD", &newoid
) &&
1709 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1710 char *bol
= buf
.buf
, *eol
;
1713 eol
= strchrnul(bol
, '\n');
1714 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
1715 bol
, oid_to_hex(&newoid
));
1721 unlink(rebase_path_rewritten_pending());
1723 strbuf_release(&buf
);
1726 static void record_in_rewritten(struct object_id
*oid
,
1727 enum todo_command next_command
)
1729 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
1734 fprintf(out
, "%s\n", oid_to_hex(oid
));
1737 if (!is_fixup(next_command
))
1738 flush_rewritten_pending();
1741 static int do_pick_commit(struct repository
*r
,
1742 enum todo_command command
,
1743 struct commit
*commit
,
1744 struct replay_opts
*opts
,
1745 int final_fixup
, int *check_todo
)
1747 unsigned int flags
= opts
->edit
? EDIT_MSG
: 0;
1748 const char *msg_file
= opts
->edit
? NULL
: git_path_merge_msg(r
);
1749 struct object_id head
;
1750 struct commit
*base
, *next
, *parent
;
1751 const char *base_label
, *next_label
;
1752 char *author
= NULL
;
1753 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
1754 struct strbuf msgbuf
= STRBUF_INIT
;
1755 int res
, unborn
= 0, reword
= 0, allow
, drop_commit
;
1757 if (opts
->no_commit
) {
1759 * We do not intend to commit immediately. We just want to
1760 * merge the differences in, so let's compute the tree
1761 * that represents the "current" state for merge-recursive
1764 if (write_index_as_tree(&head
, r
->index
, r
->index_file
, 0, NULL
))
1765 return error(_("your index file is unmerged."));
1767 unborn
= get_oid("HEAD", &head
);
1768 /* Do we want to generate a root commit? */
1769 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
1770 oideq(&head
, &opts
->squash_onto
)) {
1771 if (is_fixup(command
))
1772 return error(_("cannot fixup root commit"));
1773 flags
|= CREATE_ROOT_COMMIT
;
1776 oidcpy(&head
, the_hash_algo
->empty_tree
);
1777 if (index_differs_from(r
, unborn
? empty_tree_oid_hex() : "HEAD",
1779 return error_dirty_index(r
, opts
);
1781 discard_index(r
->index
);
1783 if (!commit
->parents
)
1785 else if (commit
->parents
->next
) {
1786 /* Reverting or cherry-picking a merge commit */
1788 struct commit_list
*p
;
1790 if (!opts
->mainline
)
1791 return error(_("commit %s is a merge but no -m option was given."),
1792 oid_to_hex(&commit
->object
.oid
));
1794 for (cnt
= 1, p
= commit
->parents
;
1795 cnt
!= opts
->mainline
&& p
;
1798 if (cnt
!= opts
->mainline
|| !p
)
1799 return error(_("commit %s does not have parent %d"),
1800 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
1802 } else if (1 < opts
->mainline
)
1804 * Non-first parent explicitly specified as mainline for
1807 return error(_("commit %s does not have parent %d"),
1808 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
1810 parent
= commit
->parents
->item
;
1812 if (get_message(commit
, &msg
) != 0)
1813 return error(_("cannot get commit message for %s"),
1814 oid_to_hex(&commit
->object
.oid
));
1816 if (opts
->allow_ff
&& !is_fixup(command
) &&
1817 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
1818 (!parent
&& unborn
))) {
1819 if (is_rebase_i(opts
))
1820 write_author_script(msg
.message
);
1821 res
= fast_forward_to(r
, &commit
->object
.oid
, &head
, unborn
,
1823 if (res
|| command
!= TODO_REWORD
)
1827 goto fast_forward_edit
;
1829 if (parent
&& parse_commit(parent
) < 0)
1830 /* TRANSLATORS: The first %s will be a "todo" command like
1831 "revert" or "pick", the second %s a SHA1. */
1832 return error(_("%s: cannot parse parent commit %s"),
1833 command_to_string(command
),
1834 oid_to_hex(&parent
->object
.oid
));
1837 * "commit" is an existing commit. We would want to apply
1838 * the difference it introduces since its first parent "prev"
1839 * on top of the current HEAD if we are cherry-pick. Or the
1840 * reverse of it if we are revert.
1843 if (command
== TODO_REVERT
) {
1845 base_label
= msg
.label
;
1847 next_label
= msg
.parent_label
;
1848 strbuf_addstr(&msgbuf
, "Revert \"");
1849 strbuf_addstr(&msgbuf
, msg
.subject
);
1850 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
1851 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
1853 if (commit
->parents
&& commit
->parents
->next
) {
1854 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
1855 strbuf_addstr(&msgbuf
, oid_to_hex(&parent
->object
.oid
));
1857 strbuf_addstr(&msgbuf
, ".\n");
1862 base_label
= msg
.parent_label
;
1864 next_label
= msg
.label
;
1866 /* Append the commit log message to msgbuf. */
1867 if (find_commit_subject(msg
.message
, &p
))
1868 strbuf_addstr(&msgbuf
, p
);
1870 if (opts
->record_origin
) {
1871 strbuf_complete_line(&msgbuf
);
1872 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
1873 strbuf_addch(&msgbuf
, '\n');
1874 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
1875 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
1876 strbuf_addstr(&msgbuf
, ")\n");
1878 if (!is_fixup(command
))
1879 author
= get_author(msg
.message
);
1882 if (command
== TODO_REWORD
)
1884 else if (is_fixup(command
)) {
1885 if (update_squash_messages(r
, command
, commit
, opts
))
1889 msg_file
= rebase_path_squash_msg();
1890 else if (file_exists(rebase_path_fixup_msg())) {
1891 flags
|= CLEANUP_MSG
;
1892 msg_file
= rebase_path_fixup_msg();
1894 const char *dest
= git_path_squash_msg(r
);
1896 if (copy_file(dest
, rebase_path_squash_msg(), 0666))
1897 return error(_("could not rename '%s' to '%s'"),
1898 rebase_path_squash_msg(), dest
);
1899 unlink(git_path_merge_msg(r
));
1905 if (opts
->signoff
&& !is_fixup(command
))
1906 append_signoff(&msgbuf
, 0, 0);
1908 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
1910 else if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || command
== TODO_REVERT
) {
1911 res
= do_recursive_merge(r
, base
, next
, base_label
, next_label
,
1912 &head
, &msgbuf
, opts
);
1916 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
1917 git_path_merge_msg(r
), 0);
1919 struct commit_list
*common
= NULL
;
1920 struct commit_list
*remotes
= NULL
;
1922 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
1923 git_path_merge_msg(r
), 0);
1925 commit_list_insert(base
, &common
);
1926 commit_list_insert(next
, &remotes
);
1927 res
|= try_merge_command(r
, opts
->strategy
,
1928 opts
->xopts_nr
, (const char **)opts
->xopts
,
1929 common
, oid_to_hex(&head
), remotes
);
1930 free_commit_list(common
);
1931 free_commit_list(remotes
);
1933 strbuf_release(&msgbuf
);
1936 * If the merge was clean or if it failed due to conflict, we write
1937 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1938 * However, if the merge did not even start, then we don't want to
1941 if ((command
== TODO_PICK
|| command
== TODO_REWORD
||
1942 command
== TODO_EDIT
) && !opts
->no_commit
&&
1943 (res
== 0 || res
== 1) &&
1944 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
1945 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1947 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
1948 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
1949 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1953 error(command
== TODO_REVERT
1954 ? _("could not revert %s... %s")
1955 : _("could not apply %s... %s"),
1956 short_commit_name(commit
), msg
.subject
);
1957 print_advice(r
, res
== 1, opts
);
1958 repo_rerere(r
, opts
->allow_rerere_auto
);
1963 allow
= allow_empty(r
, opts
, commit
);
1967 } else if (allow
== 1) {
1968 flags
|= ALLOW_EMPTY
;
1969 } else if (allow
== 2) {
1971 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
1973 unlink(git_path_merge_msg(r
));
1975 _("dropping %s %s -- patch contents already upstream\n"),
1976 oid_to_hex(&commit
->object
.oid
), msg
.subject
);
1977 } /* else allow == 0 and there's nothing special to do */
1978 if (!opts
->no_commit
&& !drop_commit
) {
1979 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
1980 res
= do_commit(r
, msg_file
, author
, opts
, flags
,
1981 commit
? &commit
->object
.oid
: NULL
);
1983 res
= error(_("unable to parse commit author"));
1984 *check_todo
= !!(flags
& EDIT_MSG
);
1985 if (!res
&& reword
) {
1987 res
= run_git_commit(r
, NULL
, opts
, EDIT_MSG
|
1988 VERIFY_MSG
| AMEND_MSG
|
1989 (flags
& ALLOW_EMPTY
));
1995 if (!res
&& final_fixup
) {
1996 unlink(rebase_path_fixup_msg());
1997 unlink(rebase_path_squash_msg());
1998 unlink(rebase_path_current_fixups());
1999 strbuf_reset(&opts
->current_fixups
);
2000 opts
->current_fixup_count
= 0;
2004 free_message(commit
, &msg
);
2006 update_abort_safety_file();
2011 static int prepare_revs(struct replay_opts
*opts
)
2014 * picking (but not reverting) ranges (but not individual revisions)
2015 * should be done in reverse
2017 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
2018 opts
->revs
->reverse
^= 1;
2020 if (prepare_revision_walk(opts
->revs
))
2021 return error(_("revision walk setup failed"));
2026 static int read_and_refresh_cache(struct repository
*r
,
2027 struct replay_opts
*opts
)
2029 struct lock_file index_lock
= LOCK_INIT
;
2030 int index_fd
= repo_hold_locked_index(r
, &index_lock
, 0);
2031 if (repo_read_index(r
) < 0) {
2032 rollback_lock_file(&index_lock
);
2033 return error(_("git %s: failed to read the index"),
2034 _(action_name(opts
)));
2036 refresh_index(r
->index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
2037 if (index_fd
>= 0) {
2038 if (write_locked_index(r
->index
, &index_lock
,
2039 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
2040 return error(_("git %s: failed to refresh the index"),
2041 _(action_name(opts
)));
2047 enum todo_item_flags
{
2048 TODO_EDIT_MERGE_MSG
= 1
2051 void todo_list_release(struct todo_list
*todo_list
)
2053 strbuf_release(&todo_list
->buf
);
2054 FREE_AND_NULL(todo_list
->items
);
2055 todo_list
->nr
= todo_list
->alloc
= 0;
2058 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
2060 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
2061 todo_list
->total_nr
++;
2062 return todo_list
->items
+ todo_list
->nr
++;
2065 const char *todo_item_get_arg(struct todo_list
*todo_list
,
2066 struct todo_item
*item
)
2068 return todo_list
->buf
.buf
+ item
->arg_offset
;
2071 static int is_command(enum todo_command command
, const char **bol
)
2073 const char *str
= todo_command_info
[command
].str
;
2074 const char nick
= todo_command_info
[command
].c
;
2075 const char *p
= *bol
+ 1;
2077 return skip_prefix(*bol
, str
, bol
) ||
2078 ((nick
&& **bol
== nick
) &&
2079 (*p
== ' ' || *p
== '\t' || *p
== '\n' || *p
== '\r' || !*p
) &&
2083 static int parse_insn_line(struct repository
*r
, struct todo_item
*item
,
2084 const char *buf
, const char *bol
, char *eol
)
2086 struct object_id commit_oid
;
2087 char *end_of_object_name
;
2088 int i
, saved
, status
, padding
;
2093 bol
+= strspn(bol
, " \t");
2095 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
2096 item
->command
= TODO_COMMENT
;
2097 item
->commit
= NULL
;
2098 item
->arg_offset
= bol
- buf
;
2099 item
->arg_len
= eol
- bol
;
2103 for (i
= 0; i
< TODO_COMMENT
; i
++)
2104 if (is_command(i
, &bol
)) {
2108 if (i
>= TODO_COMMENT
)
2111 /* Eat up extra spaces/ tabs before object name */
2112 padding
= strspn(bol
, " \t");
2115 if (item
->command
== TODO_NOOP
|| item
->command
== TODO_BREAK
) {
2117 return error(_("%s does not accept arguments: '%s'"),
2118 command_to_string(item
->command
), bol
);
2119 item
->commit
= NULL
;
2120 item
->arg_offset
= bol
- buf
;
2121 item
->arg_len
= eol
- bol
;
2126 return error(_("missing arguments for %s"),
2127 command_to_string(item
->command
));
2129 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2130 item
->command
== TODO_RESET
) {
2131 item
->commit
= NULL
;
2132 item
->arg_offset
= bol
- buf
;
2133 item
->arg_len
= (int)(eol
- bol
);
2137 if (item
->command
== TODO_MERGE
) {
2138 if (skip_prefix(bol
, "-C", &bol
))
2139 bol
+= strspn(bol
, " \t");
2140 else if (skip_prefix(bol
, "-c", &bol
)) {
2141 bol
+= strspn(bol
, " \t");
2142 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2144 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2145 item
->commit
= NULL
;
2146 item
->arg_offset
= bol
- buf
;
2147 item
->arg_len
= (int)(eol
- bol
);
2152 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2153 saved
= *end_of_object_name
;
2154 *end_of_object_name
= '\0';
2155 status
= get_oid(bol
, &commit_oid
);
2157 error(_("could not parse '%s'"), bol
); /* return later */
2158 *end_of_object_name
= saved
;
2160 bol
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2161 item
->arg_offset
= bol
- buf
;
2162 item
->arg_len
= (int)(eol
- bol
);
2167 item
->commit
= lookup_commit_reference(r
, &commit_oid
);
2168 return item
->commit
? 0 : -1;
2171 int sequencer_get_last_command(struct repository
*r
, enum replay_action
*action
)
2173 const char *todo_file
, *bol
;
2174 struct strbuf buf
= STRBUF_INIT
;
2177 todo_file
= git_path_todo_file();
2178 if (strbuf_read_file(&buf
, todo_file
, 0) < 0) {
2179 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2182 return error_errno("unable to open '%s'", todo_file
);
2184 bol
= buf
.buf
+ strspn(buf
.buf
, " \t\r\n");
2185 if (is_command(TODO_PICK
, &bol
) && (*bol
== ' ' || *bol
== '\t'))
2186 *action
= REPLAY_PICK
;
2187 else if (is_command(TODO_REVERT
, &bol
) &&
2188 (*bol
== ' ' || *bol
== '\t'))
2189 *action
= REPLAY_REVERT
;
2193 strbuf_release(&buf
);
2198 int todo_list_parse_insn_buffer(struct repository
*r
, char *buf
,
2199 struct todo_list
*todo_list
)
2201 struct todo_item
*item
;
2202 char *p
= buf
, *next_p
;
2203 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2205 todo_list
->current
= todo_list
->nr
= 0;
2207 for (i
= 1; *p
; i
++, p
= next_p
) {
2208 char *eol
= strchrnul(p
, '\n');
2210 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2212 if (p
!= eol
&& eol
[-1] == '\r')
2213 eol
--; /* strip Carriage Return */
2215 item
= append_new_todo(todo_list
);
2216 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2217 if (parse_insn_line(r
, item
, buf
, p
, eol
)) {
2218 res
= error(_("invalid line %d: %.*s"),
2219 i
, (int)(eol
- p
), p
);
2220 item
->command
= TODO_COMMENT
+ 1;
2221 item
->arg_offset
= p
- buf
;
2222 item
->arg_len
= (int)(eol
- p
);
2223 item
->commit
= NULL
;
2228 else if (is_fixup(item
->command
))
2229 return error(_("cannot '%s' without a previous commit"),
2230 command_to_string(item
->command
));
2231 else if (!is_noop(item
->command
))
2238 static int count_commands(struct todo_list
*todo_list
)
2242 for (i
= 0; i
< todo_list
->nr
; i
++)
2243 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2249 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2251 return index
< todo_list
->nr
?
2252 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2255 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2257 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2260 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2262 return get_item_line_offset(todo_list
, index
+ 1)
2263 - get_item_line_offset(todo_list
, index
);
2266 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2271 fd
= open(path
, O_RDONLY
);
2273 return error_errno(_("could not open '%s'"), path
);
2274 len
= strbuf_read(sb
, fd
, 0);
2277 return error(_("could not read '%s'."), path
);
2281 static int have_finished_the_last_pick(void)
2283 struct strbuf buf
= STRBUF_INIT
;
2285 const char *todo_path
= git_path_todo_file();
2288 if (strbuf_read_file(&buf
, todo_path
, 0) < 0) {
2289 if (errno
== ENOENT
) {
2292 error_errno("unable to open '%s'", todo_path
);
2296 /* If there is only one line then we are done */
2297 eol
= strchr(buf
.buf
, '\n');
2298 if (!eol
|| !eol
[1])
2301 strbuf_release(&buf
);
2306 void sequencer_post_commit_cleanup(struct repository
*r
, int verbose
)
2308 struct replay_opts opts
= REPLAY_OPTS_INIT
;
2309 int need_cleanup
= 0;
2311 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
2312 if (!refs_delete_ref(get_main_ref_store(r
), "",
2313 "CHERRY_PICK_HEAD", NULL
, 0) &&
2315 warning(_("cancelling a cherry picking in progress"));
2316 opts
.action
= REPLAY_PICK
;
2320 if (file_exists(git_path_revert_head(r
))) {
2321 if (!unlink(git_path_revert_head(r
)) && verbose
)
2322 warning(_("cancelling a revert in progress"));
2323 opts
.action
= REPLAY_REVERT
;
2330 if (!have_finished_the_last_pick())
2333 sequencer_remove_state(&opts
);
2336 static void todo_list_write_total_nr(struct todo_list
*todo_list
)
2338 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2341 fprintf(f
, "%d\n", todo_list
->total_nr
);
2346 static int read_populate_todo(struct repository
*r
,
2347 struct todo_list
*todo_list
,
2348 struct replay_opts
*opts
)
2351 const char *todo_file
= get_todo_path(opts
);
2354 strbuf_reset(&todo_list
->buf
);
2355 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2358 res
= stat(todo_file
, &st
);
2360 return error(_("could not stat '%s'"), todo_file
);
2361 fill_stat_data(&todo_list
->stat
, &st
);
2363 res
= todo_list_parse_insn_buffer(r
, todo_list
->buf
.buf
, todo_list
);
2365 if (is_rebase_i(opts
))
2366 return error(_("please fix this using "
2367 "'git rebase --edit-todo'."));
2368 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2371 if (!todo_list
->nr
&&
2372 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2373 return error(_("no commits parsed."));
2375 if (!is_rebase_i(opts
)) {
2376 enum todo_command valid
=
2377 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2380 for (i
= 0; i
< todo_list
->nr
; i
++)
2381 if (valid
== todo_list
->items
[i
].command
)
2383 else if (valid
== TODO_PICK
)
2384 return error(_("cannot cherry-pick during a revert."));
2386 return error(_("cannot revert during a cherry-pick."));
2389 if (is_rebase_i(opts
)) {
2390 struct todo_list done
= TODO_LIST_INIT
;
2392 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2393 !todo_list_parse_insn_buffer(r
, done
.buf
.buf
, &done
))
2394 todo_list
->done_nr
= count_commands(&done
);
2396 todo_list
->done_nr
= 0;
2398 todo_list
->total_nr
= todo_list
->done_nr
2399 + count_commands(todo_list
);
2400 todo_list_release(&done
);
2402 todo_list_write_total_nr(todo_list
);
2408 static int git_config_string_dup(char **dest
,
2409 const char *var
, const char *value
)
2412 return config_error_nonbool(var
);
2414 *dest
= xstrdup(value
);
2418 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
2420 struct replay_opts
*opts
= data
;
2425 else if (!strcmp(key
, "options.no-commit"))
2426 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
2427 else if (!strcmp(key
, "options.edit"))
2428 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
2429 else if (!strcmp(key
, "options.allow-empty"))
2431 git_config_bool_or_int(key
, value
, &error_flag
);
2432 else if (!strcmp(key
, "options.allow-empty-message"))
2433 opts
->allow_empty_message
=
2434 git_config_bool_or_int(key
, value
, &error_flag
);
2435 else if (!strcmp(key
, "options.keep-redundant-commits"))
2436 opts
->keep_redundant_commits
=
2437 git_config_bool_or_int(key
, value
, &error_flag
);
2438 else if (!strcmp(key
, "options.signoff"))
2439 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
2440 else if (!strcmp(key
, "options.record-origin"))
2441 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
2442 else if (!strcmp(key
, "options.allow-ff"))
2443 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
2444 else if (!strcmp(key
, "options.mainline"))
2445 opts
->mainline
= git_config_int(key
, value
);
2446 else if (!strcmp(key
, "options.strategy"))
2447 git_config_string_dup(&opts
->strategy
, key
, value
);
2448 else if (!strcmp(key
, "options.gpg-sign"))
2449 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2450 else if (!strcmp(key
, "options.strategy-option")) {
2451 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
2452 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(value
);
2453 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2454 opts
->allow_rerere_auto
=
2455 git_config_bool_or_int(key
, value
, &error_flag
) ?
2456 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2457 else if (!strcmp(key
, "options.default-msg-cleanup")) {
2458 opts
->explicit_cleanup
= 1;
2459 opts
->default_msg_cleanup
= get_cleanup_mode(value
, 1);
2461 return error(_("invalid key: %s"), key
);
2464 return error(_("invalid value for %s: %s"), key
, value
);
2469 void parse_strategy_opts(struct replay_opts
*opts
, char *raw_opts
)
2472 char *strategy_opts_string
= raw_opts
;
2474 if (*strategy_opts_string
== ' ')
2475 strategy_opts_string
++;
2477 opts
->xopts_nr
= split_cmdline(strategy_opts_string
,
2478 (const char ***)&opts
->xopts
);
2479 for (i
= 0; i
< opts
->xopts_nr
; i
++) {
2480 const char *arg
= opts
->xopts
[i
];
2482 skip_prefix(arg
, "--", &arg
);
2483 opts
->xopts
[i
] = xstrdup(arg
);
2487 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2490 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2492 opts
->strategy
= strbuf_detach(buf
, NULL
);
2493 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2496 parse_strategy_opts(opts
, buf
->buf
);
2499 static int read_populate_opts(struct replay_opts
*opts
)
2501 if (is_rebase_i(opts
)) {
2502 struct strbuf buf
= STRBUF_INIT
;
2505 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(),
2506 READ_ONELINER_SKIP_IF_EMPTY
)) {
2507 if (!starts_with(buf
.buf
, "-S"))
2510 free(opts
->gpg_sign
);
2511 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
2516 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(),
2517 READ_ONELINER_SKIP_IF_EMPTY
)) {
2518 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
2519 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
2520 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
2521 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
2525 if (file_exists(rebase_path_verbose()))
2528 if (file_exists(rebase_path_quiet()))
2531 if (file_exists(rebase_path_signoff())) {
2536 if (file_exists(rebase_path_reschedule_failed_exec()))
2537 opts
->reschedule_failed_exec
= 1;
2539 if (file_exists(rebase_path_drop_redundant_commits()))
2540 opts
->drop_redundant_commits
= 1;
2542 if (file_exists(rebase_path_keep_redundant_commits()))
2543 opts
->keep_redundant_commits
= 1;
2545 read_strategy_opts(opts
, &buf
);
2548 if (read_oneliner(&opts
->current_fixups
,
2549 rebase_path_current_fixups(),
2550 READ_ONELINER_SKIP_IF_EMPTY
)) {
2551 const char *p
= opts
->current_fixups
.buf
;
2552 opts
->current_fixup_count
= 1;
2553 while ((p
= strchr(p
, '\n'))) {
2554 opts
->current_fixup_count
++;
2559 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
2560 if (get_oid_hex(buf
.buf
, &opts
->squash_onto
) < 0) {
2561 ret
= error(_("unusable squash-onto"));
2564 opts
->have_squash_onto
= 1;
2568 strbuf_release(&buf
);
2572 if (!file_exists(git_path_opts_file()))
2575 * The function git_parse_source(), called from git_config_from_file(),
2576 * may die() in case of a syntactically incorrect file. We do not care
2577 * about this case, though, because we wrote that file ourselves, so we
2578 * are pretty certain that it is syntactically correct.
2580 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
2581 return error(_("malformed options sheet: '%s'"),
2582 git_path_opts_file());
2586 static void write_strategy_opts(struct replay_opts
*opts
)
2589 struct strbuf buf
= STRBUF_INIT
;
2591 for (i
= 0; i
< opts
->xopts_nr
; ++i
)
2592 strbuf_addf(&buf
, " --%s", opts
->xopts
[i
]);
2594 write_file(rebase_path_strategy_opts(), "%s\n", buf
.buf
);
2595 strbuf_release(&buf
);
2598 int write_basic_state(struct replay_opts
*opts
, const char *head_name
,
2599 struct commit
*onto
, const char *orig_head
)
2602 write_file(rebase_path_head_name(), "%s\n", head_name
);
2604 write_file(rebase_path_onto(), "%s\n",
2605 oid_to_hex(&onto
->object
.oid
));
2607 write_file(rebase_path_orig_head(), "%s\n", orig_head
);
2610 write_file(rebase_path_quiet(), "%s", "");
2612 write_file(rebase_path_verbose(), "%s", "");
2614 write_file(rebase_path_strategy(), "%s\n", opts
->strategy
);
2615 if (opts
->xopts_nr
> 0)
2616 write_strategy_opts(opts
);
2618 if (opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
)
2619 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2620 else if (opts
->allow_rerere_auto
== RERERE_NOAUTOUPDATE
)
2621 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2624 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts
->gpg_sign
);
2626 write_file(rebase_path_signoff(), "--signoff\n");
2627 if (opts
->drop_redundant_commits
)
2628 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2629 if (opts
->keep_redundant_commits
)
2630 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2631 if (opts
->reschedule_failed_exec
)
2632 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2637 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
2638 struct replay_opts
*opts
)
2640 enum todo_command command
= opts
->action
== REPLAY_PICK
?
2641 TODO_PICK
: TODO_REVERT
;
2642 const char *command_string
= todo_command_info
[command
].str
;
2643 const char *encoding
;
2644 struct commit
*commit
;
2646 if (prepare_revs(opts
))
2649 encoding
= get_log_output_encoding();
2651 while ((commit
= get_revision(opts
->revs
))) {
2652 struct todo_item
*item
= append_new_todo(todo_list
);
2653 const char *commit_buffer
= logmsg_reencode(commit
, NULL
, encoding
);
2654 const char *subject
;
2657 item
->command
= command
;
2658 item
->commit
= commit
;
2659 item
->arg_offset
= 0;
2661 item
->offset_in_buf
= todo_list
->buf
.len
;
2662 subject_len
= find_commit_subject(commit_buffer
, &subject
);
2663 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
2664 short_commit_name(commit
), subject_len
, subject
);
2665 unuse_commit_buffer(commit
, commit_buffer
);
2669 return error(_("empty commit set passed"));
2674 static int create_seq_dir(struct repository
*r
)
2676 enum replay_action action
;
2677 const char *in_progress_error
= NULL
;
2678 const char *in_progress_advice
= NULL
;
2679 unsigned int advise_skip
=
2680 file_exists(git_path_revert_head(r
)) ||
2681 refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD");
2683 if (!sequencer_get_last_command(r
, &action
)) {
2686 in_progress_error
= _("revert is already in progress");
2687 in_progress_advice
=
2688 _("try \"git revert (--continue | %s--abort | --quit)\"");
2691 in_progress_error
= _("cherry-pick is already in progress");
2692 in_progress_advice
=
2693 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2696 BUG("unexpected action in create_seq_dir");
2699 if (in_progress_error
) {
2700 error("%s", in_progress_error
);
2701 if (advice_sequencer_in_use
)
2702 advise(in_progress_advice
,
2703 advise_skip
? "--skip | " : "");
2706 if (mkdir(git_path_seq_dir(), 0777) < 0)
2707 return error_errno(_("could not create sequencer directory '%s'"),
2708 git_path_seq_dir());
2713 static int save_head(const char *head
)
2715 struct lock_file head_lock
= LOCK_INIT
;
2716 struct strbuf buf
= STRBUF_INIT
;
2720 fd
= hold_lock_file_for_update(&head_lock
, git_path_head_file(), 0);
2722 return error_errno(_("could not lock HEAD"));
2723 strbuf_addf(&buf
, "%s\n", head
);
2724 written
= write_in_full(fd
, buf
.buf
, buf
.len
);
2725 strbuf_release(&buf
);
2727 error_errno(_("could not write to '%s'"), git_path_head_file());
2728 rollback_lock_file(&head_lock
);
2731 if (commit_lock_file(&head_lock
) < 0)
2732 return error(_("failed to finalize '%s'"), git_path_head_file());
2736 static int rollback_is_safe(void)
2738 struct strbuf sb
= STRBUF_INIT
;
2739 struct object_id expected_head
, actual_head
;
2741 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
2743 if (get_oid_hex(sb
.buf
, &expected_head
)) {
2744 strbuf_release(&sb
);
2745 die(_("could not parse %s"), git_path_abort_safety_file());
2747 strbuf_release(&sb
);
2749 else if (errno
== ENOENT
)
2750 oidclr(&expected_head
);
2752 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2754 if (get_oid("HEAD", &actual_head
))
2755 oidclr(&actual_head
);
2757 return oideq(&actual_head
, &expected_head
);
2760 static int reset_merge(const struct object_id
*oid
)
2763 struct strvec argv
= STRVEC_INIT
;
2765 strvec_pushl(&argv
, "reset", "--merge", NULL
);
2767 if (!is_null_oid(oid
))
2768 strvec_push(&argv
, oid_to_hex(oid
));
2770 ret
= run_command_v_opt(argv
.v
, RUN_GIT_CMD
);
2771 strvec_clear(&argv
);
2776 static int rollback_single_pick(struct repository
*r
)
2778 struct object_id head_oid
;
2780 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
2781 !file_exists(git_path_revert_head(r
)))
2782 return error(_("no cherry-pick or revert in progress"));
2783 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
2784 return error(_("cannot resolve HEAD"));
2785 if (is_null_oid(&head_oid
))
2786 return error(_("cannot abort from a branch yet to be born"));
2787 return reset_merge(&head_oid
);
2790 static int skip_single_pick(void)
2792 struct object_id head
;
2794 if (read_ref_full("HEAD", 0, &head
, NULL
))
2795 return error(_("cannot resolve HEAD"));
2796 return reset_merge(&head
);
2799 int sequencer_rollback(struct repository
*r
, struct replay_opts
*opts
)
2802 struct object_id oid
;
2803 struct strbuf buf
= STRBUF_INIT
;
2806 f
= fopen(git_path_head_file(), "r");
2807 if (!f
&& errno
== ENOENT
) {
2809 * There is no multiple-cherry-pick in progress.
2810 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2811 * a single-cherry-pick in progress, abort that.
2813 return rollback_single_pick(r
);
2816 return error_errno(_("cannot open '%s'"), git_path_head_file());
2817 if (strbuf_getline_lf(&buf
, f
)) {
2818 error(_("cannot read '%s': %s"), git_path_head_file(),
2819 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
2824 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
2825 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2826 git_path_head_file());
2829 if (is_null_oid(&oid
)) {
2830 error(_("cannot abort from a branch yet to be born"));
2834 if (!rollback_is_safe()) {
2835 /* Do not error, just do not rollback */
2836 warning(_("You seem to have moved HEAD. "
2837 "Not rewinding, check your HEAD!"));
2839 if (reset_merge(&oid
))
2841 strbuf_release(&buf
);
2842 return sequencer_remove_state(opts
);
2844 strbuf_release(&buf
);
2848 int sequencer_skip(struct repository
*r
, struct replay_opts
*opts
)
2850 enum replay_action action
= -1;
2851 sequencer_get_last_command(r
, &action
);
2854 * Check whether the subcommand requested to skip the commit is actually
2855 * in progress and that it's safe to skip the commit.
2857 * opts->action tells us which subcommand requested to skip the commit.
2858 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2859 * action is in progress and we can skip the commit.
2861 * Otherwise we check that the last instruction was related to the
2862 * particular subcommand we're trying to execute and barf if that's not
2865 * Finally we check that the rollback is "safe", i.e., has the HEAD
2866 * moved? In this case, it doesn't make sense to "reset the merge" and
2867 * "skip the commit" as the user already handled this by committing. But
2868 * we'd not want to barf here, instead give advice on how to proceed. We
2869 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2870 * it gets removed when the user commits, so if it still exists we're
2871 * sure the user can't have committed before.
2873 switch (opts
->action
) {
2875 if (!file_exists(git_path_revert_head(r
))) {
2876 if (action
!= REPLAY_REVERT
)
2877 return error(_("no revert in progress"));
2878 if (!rollback_is_safe())
2883 if (!refs_ref_exists(get_main_ref_store(r
),
2884 "CHERRY_PICK_HEAD")) {
2885 if (action
!= REPLAY_PICK
)
2886 return error(_("no cherry-pick in progress"));
2887 if (!rollback_is_safe())
2892 BUG("unexpected action in sequencer_skip");
2895 if (skip_single_pick())
2896 return error(_("failed to skip the commit"));
2897 if (!is_directory(git_path_seq_dir()))
2900 return sequencer_continue(r
, opts
);
2903 error(_("there is nothing to skip"));
2905 if (advice_resolve_conflict
) {
2906 advise(_("have you committed already?\n"
2907 "try \"git %s --continue\""),
2908 action
== REPLAY_REVERT
? "revert" : "cherry-pick");
2913 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
2915 struct lock_file todo_lock
= LOCK_INIT
;
2916 const char *todo_path
= get_todo_path(opts
);
2917 int next
= todo_list
->current
, offset
, fd
;
2920 * rebase -i writes "git-rebase-todo" without the currently executing
2921 * command, appending it to "done" instead.
2923 if (is_rebase_i(opts
))
2926 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
2928 return error_errno(_("could not lock '%s'"), todo_path
);
2929 offset
= get_item_line_offset(todo_list
, next
);
2930 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
2931 todo_list
->buf
.len
- offset
) < 0)
2932 return error_errno(_("could not write to '%s'"), todo_path
);
2933 if (commit_lock_file(&todo_lock
) < 0)
2934 return error(_("failed to finalize '%s'"), todo_path
);
2936 if (is_rebase_i(opts
) && next
> 0) {
2937 const char *done
= rebase_path_done();
2938 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
2943 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
2944 get_item_line_length(todo_list
, next
- 1))
2946 ret
= error_errno(_("could not write to '%s'"), done
);
2948 ret
= error_errno(_("failed to finalize '%s'"), done
);
2954 static int save_opts(struct replay_opts
*opts
)
2956 const char *opts_file
= git_path_opts_file();
2959 if (opts
->no_commit
)
2960 res
|= git_config_set_in_file_gently(opts_file
,
2961 "options.no-commit", "true");
2963 res
|= git_config_set_in_file_gently(opts_file
,
2964 "options.edit", "true");
2965 if (opts
->allow_empty
)
2966 res
|= git_config_set_in_file_gently(opts_file
,
2967 "options.allow-empty", "true");
2968 if (opts
->allow_empty_message
)
2969 res
|= git_config_set_in_file_gently(opts_file
,
2970 "options.allow-empty-message", "true");
2971 if (opts
->keep_redundant_commits
)
2972 res
|= git_config_set_in_file_gently(opts_file
,
2973 "options.keep-redundant-commits", "true");
2975 res
|= git_config_set_in_file_gently(opts_file
,
2976 "options.signoff", "true");
2977 if (opts
->record_origin
)
2978 res
|= git_config_set_in_file_gently(opts_file
,
2979 "options.record-origin", "true");
2981 res
|= git_config_set_in_file_gently(opts_file
,
2982 "options.allow-ff", "true");
2983 if (opts
->mainline
) {
2984 struct strbuf buf
= STRBUF_INIT
;
2985 strbuf_addf(&buf
, "%d", opts
->mainline
);
2986 res
|= git_config_set_in_file_gently(opts_file
,
2987 "options.mainline", buf
.buf
);
2988 strbuf_release(&buf
);
2991 res
|= git_config_set_in_file_gently(opts_file
,
2992 "options.strategy", opts
->strategy
);
2994 res
|= git_config_set_in_file_gently(opts_file
,
2995 "options.gpg-sign", opts
->gpg_sign
);
2998 for (i
= 0; i
< opts
->xopts_nr
; i
++)
2999 res
|= git_config_set_multivar_in_file_gently(opts_file
,
3000 "options.strategy-option",
3001 opts
->xopts
[i
], "^$", 0);
3003 if (opts
->allow_rerere_auto
)
3004 res
|= git_config_set_in_file_gently(opts_file
,
3005 "options.allow-rerere-auto",
3006 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
3009 if (opts
->explicit_cleanup
)
3010 res
|= git_config_set_in_file_gently(opts_file
,
3011 "options.default-msg-cleanup",
3012 describe_cleanup_mode(opts
->default_msg_cleanup
));
3016 static int make_patch(struct repository
*r
,
3017 struct commit
*commit
,
3018 struct replay_opts
*opts
)
3020 struct strbuf buf
= STRBUF_INIT
;
3021 struct rev_info log_tree_opt
;
3022 const char *subject
, *p
;
3025 p
= short_commit_name(commit
);
3026 if (write_message(p
, strlen(p
), rebase_path_stopped_sha(), 1) < 0)
3028 res
|= write_rebase_head(&commit
->object
.oid
);
3030 strbuf_addf(&buf
, "%s/patch", get_dir(opts
));
3031 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3032 repo_init_revisions(r
, &log_tree_opt
, NULL
);
3033 log_tree_opt
.abbrev
= 0;
3034 log_tree_opt
.diff
= 1;
3035 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
3036 log_tree_opt
.disable_stdin
= 1;
3037 log_tree_opt
.no_commit_id
= 1;
3038 log_tree_opt
.diffopt
.file
= fopen(buf
.buf
, "w");
3039 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
3040 if (!log_tree_opt
.diffopt
.file
)
3041 res
|= error_errno(_("could not open '%s'"), buf
.buf
);
3043 res
|= log_tree_commit(&log_tree_opt
, commit
);
3044 fclose(log_tree_opt
.diffopt
.file
);
3048 strbuf_addf(&buf
, "%s/message", get_dir(opts
));
3049 if (!file_exists(buf
.buf
)) {
3050 const char *encoding
= get_commit_output_encoding();
3051 const char *commit_buffer
= logmsg_reencode(commit
, NULL
, encoding
);
3052 find_commit_subject(commit_buffer
, &subject
);
3053 res
|= write_message(subject
, strlen(subject
), buf
.buf
, 1);
3054 unuse_commit_buffer(commit
, commit_buffer
);
3056 strbuf_release(&buf
);
3061 static int intend_to_amend(void)
3063 struct object_id head
;
3066 if (get_oid("HEAD", &head
))
3067 return error(_("cannot read HEAD"));
3069 p
= oid_to_hex(&head
);
3070 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
3073 static int error_with_patch(struct repository
*r
,
3074 struct commit
*commit
,
3075 const char *subject
, int subject_len
,
3076 struct replay_opts
*opts
,
3077 int exit_code
, int to_amend
)
3080 if (make_patch(r
, commit
, opts
))
3082 } else if (copy_file(rebase_path_message(),
3083 git_path_merge_msg(r
), 0666))
3084 return error(_("unable to copy '%s' to '%s'"),
3085 git_path_merge_msg(r
), rebase_path_message());
3088 if (intend_to_amend())
3092 _("You can amend the commit now, with\n"
3094 " git commit --amend %s\n"
3096 "Once you are satisfied with your changes, run\n"
3098 " git rebase --continue\n"),
3099 gpg_sign_opt_quoted(opts
));
3100 } else if (exit_code
) {
3102 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
3103 short_commit_name(commit
), subject_len
, subject
);
3106 * We don't have the hash of the parent so
3107 * just print the line from the todo file.
3109 fprintf_ln(stderr
, _("Could not merge %.*s"),
3110 subject_len
, subject
);
3116 static int error_failed_squash(struct repository
*r
,
3117 struct commit
*commit
,
3118 struct replay_opts
*opts
,
3120 const char *subject
)
3122 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3123 return error(_("could not copy '%s' to '%s'"),
3124 rebase_path_squash_msg(), rebase_path_message());
3125 unlink(git_path_merge_msg(r
));
3126 if (copy_file(git_path_merge_msg(r
), rebase_path_message(), 0666))
3127 return error(_("could not copy '%s' to '%s'"),
3128 rebase_path_message(),
3129 git_path_merge_msg(r
));
3130 return error_with_patch(r
, commit
, subject
, subject_len
, opts
, 1, 0);
3133 static int do_exec(struct repository
*r
, const char *command_line
)
3135 struct strvec child_env
= STRVEC_INIT
;
3136 const char *child_argv
[] = { NULL
, NULL
};
3139 fprintf(stderr
, _("Executing: %s\n"), command_line
);
3140 child_argv
[0] = command_line
;
3141 strvec_pushf(&child_env
, "GIT_DIR=%s", absolute_path(get_git_dir()));
3142 strvec_pushf(&child_env
, "GIT_WORK_TREE=%s",
3143 absolute_path(get_git_work_tree()));
3144 status
= run_command_v_opt_cd_env(child_argv
, RUN_USING_SHELL
, NULL
,
3147 /* force re-reading of the cache */
3148 if (discard_index(r
->index
) < 0 || repo_read_index(r
) < 0)
3149 return error(_("could not read index"));
3151 dirty
= require_clean_work_tree(r
, "rebase", NULL
, 1, 1);
3154 warning(_("execution failed: %s\n%s"
3155 "You can fix the problem, and then run\n"
3157 " git rebase --continue\n"
3160 dirty
? N_("and made changes to the index and/or the "
3161 "working tree\n") : "");
3163 /* command not found */
3166 warning(_("execution succeeded: %s\nbut "
3167 "left changes to the index and/or the working tree\n"
3168 "Commit or stash your changes, and then run\n"
3170 " git rebase --continue\n"
3171 "\n"), command_line
);
3175 strvec_clear(&child_env
);
3180 static int safe_append(const char *filename
, const char *fmt
, ...)
3183 struct lock_file lock
= LOCK_INIT
;
3184 int fd
= hold_lock_file_for_update(&lock
, filename
,
3185 LOCK_REPORT_ON_ERROR
);
3186 struct strbuf buf
= STRBUF_INIT
;
3191 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
3192 error_errno(_("could not read '%s'"), filename
);
3193 rollback_lock_file(&lock
);
3196 strbuf_complete(&buf
, '\n');
3198 strbuf_vaddf(&buf
, fmt
, ap
);
3201 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
3202 error_errno(_("could not write to '%s'"), filename
);
3203 strbuf_release(&buf
);
3204 rollback_lock_file(&lock
);
3207 if (commit_lock_file(&lock
) < 0) {
3208 strbuf_release(&buf
);
3209 rollback_lock_file(&lock
);
3210 return error(_("failed to finalize '%s'"), filename
);
3213 strbuf_release(&buf
);
3217 static int do_label(struct repository
*r
, const char *name
, int len
)
3219 struct ref_store
*refs
= get_main_ref_store(r
);
3220 struct ref_transaction
*transaction
;
3221 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
3222 struct strbuf msg
= STRBUF_INIT
;
3224 struct object_id head_oid
;
3226 if (len
== 1 && *name
== '#')
3227 return error(_("illegal label name: '%.*s'"), len
, name
);
3229 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3230 strbuf_addf(&msg
, "rebase (label) '%.*s'", len
, name
);
3232 transaction
= ref_store_transaction_begin(refs
, &err
);
3234 error("%s", err
.buf
);
3236 } else if (get_oid("HEAD", &head_oid
)) {
3237 error(_("could not read HEAD"));
3239 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
3240 NULL
, 0, msg
.buf
, &err
) < 0 ||
3241 ref_transaction_commit(transaction
, &err
)) {
3242 error("%s", err
.buf
);
3245 ref_transaction_free(transaction
);
3246 strbuf_release(&err
);
3247 strbuf_release(&msg
);
3250 ret
= safe_append(rebase_path_refs_to_delete(),
3251 "%s\n", ref_name
.buf
);
3252 strbuf_release(&ref_name
);
3257 static const char *reflog_message(struct replay_opts
*opts
,
3258 const char *sub_action
, const char *fmt
, ...);
3260 static int do_reset(struct repository
*r
,
3261 const char *name
, int len
,
3262 struct replay_opts
*opts
)
3264 struct strbuf ref_name
= STRBUF_INIT
;
3265 struct object_id oid
;
3266 struct lock_file lock
= LOCK_INIT
;
3267 struct tree_desc desc
;
3269 struct unpack_trees_options unpack_tree_opts
;
3272 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0)
3275 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
3276 if (!opts
->have_squash_onto
) {
3278 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
3279 NULL
, &opts
->squash_onto
,
3281 return error(_("writing fake root commit"));
3282 opts
->have_squash_onto
= 1;
3283 hex
= oid_to_hex(&opts
->squash_onto
);
3284 if (write_message(hex
, strlen(hex
),
3285 rebase_path_squash_onto(), 0))
3286 return error(_("writing squash-onto"));
3288 oidcpy(&oid
, &opts
->squash_onto
);
3292 /* Determine the length of the label */
3293 for (i
= 0; i
< len
; i
++)
3294 if (isspace(name
[i
]))
3298 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
3299 if (get_oid(ref_name
.buf
, &oid
) &&
3300 get_oid(ref_name
.buf
+ strlen("refs/rewritten/"), &oid
)) {
3301 error(_("could not read '%s'"), ref_name
.buf
);
3302 rollback_lock_file(&lock
);
3303 strbuf_release(&ref_name
);
3308 memset(&unpack_tree_opts
, 0, sizeof(unpack_tree_opts
));
3309 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
3310 unpack_tree_opts
.head_idx
= 1;
3311 unpack_tree_opts
.src_index
= r
->index
;
3312 unpack_tree_opts
.dst_index
= r
->index
;
3313 unpack_tree_opts
.fn
= oneway_merge
;
3314 unpack_tree_opts
.merge
= 1;
3315 unpack_tree_opts
.update
= 1;
3316 init_checkout_metadata(&unpack_tree_opts
.meta
, name
, &oid
, NULL
);
3318 if (repo_read_index_unmerged(r
)) {
3319 rollback_lock_file(&lock
);
3320 strbuf_release(&ref_name
);
3321 return error_resolve_conflict(_(action_name(opts
)));
3324 if (!fill_tree_descriptor(r
, &desc
, &oid
)) {
3325 error(_("failed to find tree of %s"), oid_to_hex(&oid
));
3326 rollback_lock_file(&lock
);
3327 free((void *)desc
.buffer
);
3328 strbuf_release(&ref_name
);
3332 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
3333 rollback_lock_file(&lock
);
3334 free((void *)desc
.buffer
);
3335 strbuf_release(&ref_name
);
3339 tree
= parse_tree_indirect(&oid
);
3340 prime_cache_tree(r
, r
->index
, tree
);
3342 if (write_locked_index(r
->index
, &lock
, COMMIT_LOCK
) < 0)
3343 ret
= error(_("could not write index"));
3344 free((void *)desc
.buffer
);
3347 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
3348 len
, name
), "HEAD", &oid
,
3349 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3351 strbuf_release(&ref_name
);
3355 static struct commit
*lookup_label(const char *label
, int len
,
3358 struct commit
*commit
;
3361 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
3362 commit
= lookup_commit_reference_by_name(buf
->buf
);
3364 /* fall back to non-rewritten ref or commit */
3365 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
3366 commit
= lookup_commit_reference_by_name(buf
->buf
);
3370 error(_("could not resolve '%s'"), buf
->buf
);
3375 static int do_merge(struct repository
*r
,
3376 struct commit
*commit
,
3377 const char *arg
, int arg_len
,
3378 int flags
, struct replay_opts
*opts
)
3380 int run_commit_flags
= (flags
& TODO_EDIT_MERGE_MSG
) ?
3381 EDIT_MSG
| VERIFY_MSG
: 0;
3382 struct strbuf ref_name
= STRBUF_INIT
;
3383 struct commit
*head_commit
, *merge_commit
, *i
;
3384 struct commit_list
*bases
, *j
, *reversed
= NULL
;
3385 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
3386 const char *strategy
= !opts
->xopts_nr
&&
3387 (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive")) ?
3388 NULL
: opts
->strategy
;
3389 struct merge_options o
;
3390 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
3391 static struct lock_file lock
;
3394 if (repo_hold_locked_index(r
, &lock
, LOCK_REPORT_ON_ERROR
) < 0) {
3399 head_commit
= lookup_commit_reference_by_name("HEAD");
3401 ret
= error(_("cannot merge without a current revision"));
3406 * For octopus merges, the arg starts with the list of revisions to be
3407 * merged. The list is optionally followed by '#' and the oneline.
3409 merge_arg_len
= oneline_offset
= arg_len
;
3410 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
3413 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
3414 p
+= 1 + strspn(p
+ 1, " \t\n");
3415 oneline_offset
= p
- arg
;
3418 k
= strcspn(p
, " \t\n");
3421 merge_commit
= lookup_label(p
, k
, &ref_name
);
3422 if (!merge_commit
) {
3423 ret
= error(_("unable to parse '%.*s'"), k
, p
);
3426 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
3428 merge_arg_len
= p
- arg
;
3432 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
3436 if (opts
->have_squash_onto
&&
3437 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
3439 * When the user tells us to "merge" something into a
3440 * "[new root]", let's simply fast-forward to the merge head.
3442 rollback_lock_file(&lock
);
3444 ret
= error(_("octopus merge cannot be executed on "
3445 "top of a [new root]"));
3447 ret
= fast_forward_to(r
, &to_merge
->item
->object
.oid
,
3448 &head_commit
->object
.oid
, 0,
3454 const char *encoding
= get_commit_output_encoding();
3455 const char *message
= logmsg_reencode(commit
, NULL
, encoding
);
3460 ret
= error(_("could not get commit message of '%s'"),
3461 oid_to_hex(&commit
->object
.oid
));
3464 write_author_script(message
);
3465 find_commit_subject(message
, &body
);
3467 ret
= write_message(body
, len
, git_path_merge_msg(r
), 0);
3468 unuse_commit_buffer(commit
, message
);
3470 error_errno(_("could not write '%s'"),
3471 git_path_merge_msg(r
));
3475 struct strbuf buf
= STRBUF_INIT
;
3478 strbuf_addf(&buf
, "author %s", git_author_info(0));
3479 write_author_script(buf
.buf
);
3482 if (oneline_offset
< arg_len
) {
3483 p
= arg
+ oneline_offset
;
3484 len
= arg_len
- oneline_offset
;
3486 strbuf_addf(&buf
, "Merge %s '%.*s'",
3487 to_merge
->next
? "branches" : "branch",
3488 merge_arg_len
, arg
);
3493 ret
= write_message(p
, len
, git_path_merge_msg(r
), 0);
3494 strbuf_release(&buf
);
3496 error_errno(_("could not write '%s'"),
3497 git_path_merge_msg(r
));
3503 * If HEAD is not identical to the first parent of the original merge
3504 * commit, we cannot fast-forward.
3506 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3507 oideq(&commit
->parents
->item
->object
.oid
,
3508 &head_commit
->object
.oid
);
3511 * If any merge head is different from the original one, we cannot
3514 if (can_fast_forward
) {
3515 struct commit_list
*p
= commit
->parents
->next
;
3517 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
3518 if (!oideq(&j
->item
->object
.oid
,
3519 &p
->item
->object
.oid
)) {
3520 can_fast_forward
= 0;
3524 * If the number of merge heads differs from the original merge
3525 * commit, we cannot fast-forward.
3528 can_fast_forward
= 0;
3531 if (can_fast_forward
) {
3532 rollback_lock_file(&lock
);
3533 ret
= fast_forward_to(r
, &commit
->object
.oid
,
3534 &head_commit
->object
.oid
, 0, opts
);
3535 if (flags
& TODO_EDIT_MERGE_MSG
) {
3536 run_commit_flags
|= AMEND_MSG
;
3537 goto fast_forward_edit
;
3542 if (strategy
|| to_merge
->next
) {
3544 struct child_process cmd
= CHILD_PROCESS_INIT
;
3546 if (read_env_script(&cmd
.env_array
)) {
3547 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
3549 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
3554 strvec_push(&cmd
.args
, "merge");
3555 strvec_push(&cmd
.args
, "-s");
3557 strvec_push(&cmd
.args
, "octopus");
3559 strvec_push(&cmd
.args
, strategy
);
3560 for (k
= 0; k
< opts
->xopts_nr
; k
++)
3561 strvec_pushf(&cmd
.args
,
3562 "-X%s", opts
->xopts
[k
]);
3564 strvec_push(&cmd
.args
, "--no-edit");
3565 strvec_push(&cmd
.args
, "--no-ff");
3566 strvec_push(&cmd
.args
, "--no-log");
3567 strvec_push(&cmd
.args
, "--no-stat");
3568 strvec_push(&cmd
.args
, "-F");
3569 strvec_push(&cmd
.args
, git_path_merge_msg(r
));
3571 strvec_push(&cmd
.args
, opts
->gpg_sign
);
3573 /* Add the tips to be merged */
3574 for (j
= to_merge
; j
; j
= j
->next
)
3575 strvec_push(&cmd
.args
,
3576 oid_to_hex(&j
->item
->object
.oid
));
3578 strbuf_release(&ref_name
);
3579 refs_delete_ref(get_main_ref_store(r
), "", "CHERRY_PICK_HEAD",
3581 rollback_lock_file(&lock
);
3583 rollback_lock_file(&lock
);
3584 ret
= run_command(&cmd
);
3586 /* force re-reading of the cache */
3587 if (!ret
&& (discard_index(r
->index
) < 0 ||
3588 repo_read_index(r
) < 0))
3589 ret
= error(_("could not read index"));
3593 merge_commit
= to_merge
->item
;
3594 bases
= get_merge_bases(head_commit
, merge_commit
);
3595 if (bases
&& oideq(&merge_commit
->object
.oid
,
3596 &bases
->item
->object
.oid
)) {
3598 /* skip merging an ancestor of HEAD */
3602 write_message(oid_to_hex(&merge_commit
->object
.oid
), the_hash_algo
->hexsz
,
3603 git_path_merge_head(r
), 0);
3604 write_message("no-ff", 5, git_path_merge_mode(r
), 0);
3606 for (j
= bases
; j
; j
= j
->next
)
3607 commit_list_insert(j
->item
, &reversed
);
3608 free_commit_list(bases
);
3611 init_merge_options(&o
, r
);
3613 o
.branch2
= ref_name
.buf
;
3614 o
.buffer_output
= 2;
3616 ret
= merge_recursive(&o
, head_commit
, merge_commit
, reversed
, &i
);
3618 fputs(o
.obuf
.buf
, stdout
);
3619 strbuf_release(&o
.obuf
);
3621 error(_("could not even attempt to merge '%.*s'"),
3622 merge_arg_len
, arg
);
3626 * The return value of merge_recursive() is 1 on clean, and 0 on
3629 * Let's reverse that, so that do_merge() returns 0 upon success and
3630 * 1 upon failed merge (keeping the return value -1 for the cases where
3631 * we will want to reschedule the `merge` command).
3635 if (r
->index
->cache_changed
&&
3636 write_locked_index(r
->index
, &lock
, COMMIT_LOCK
)) {
3637 ret
= error(_("merge: Unable to write new index file"));
3641 rollback_lock_file(&lock
);
3643 repo_rerere(r
, opts
->allow_rerere_auto
);
3646 * In case of problems, we now want to return a positive
3647 * value (a negative one would indicate that the `merge`
3648 * command needs to be rescheduled).
3651 ret
= !!run_git_commit(r
, git_path_merge_msg(r
), opts
,
3655 strbuf_release(&ref_name
);
3656 rollback_lock_file(&lock
);
3657 free_commit_list(to_merge
);
3661 static int is_final_fixup(struct todo_list
*todo_list
)
3663 int i
= todo_list
->current
;
3665 if (!is_fixup(todo_list
->items
[i
].command
))
3668 while (++i
< todo_list
->nr
)
3669 if (is_fixup(todo_list
->items
[i
].command
))
3671 else if (!is_noop(todo_list
->items
[i
].command
))
3676 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
3680 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
3681 if (!is_noop(todo_list
->items
[i
].command
))
3682 return todo_list
->items
[i
].command
;
3687 void create_autostash(struct repository
*r
, const char *path
,
3688 const char *default_reflog_action
)
3690 struct strbuf buf
= STRBUF_INIT
;
3691 struct lock_file lock_file
= LOCK_INIT
;
3694 fd
= repo_hold_locked_index(r
, &lock_file
, 0);
3695 refresh_index(r
->index
, REFRESH_QUIET
, NULL
, NULL
, NULL
);
3697 repo_update_index_if_able(r
, &lock_file
);
3698 rollback_lock_file(&lock_file
);
3700 if (has_unstaged_changes(r
, 1) ||
3701 has_uncommitted_changes(r
, 1)) {
3702 struct child_process stash
= CHILD_PROCESS_INIT
;
3703 struct object_id oid
;
3705 strvec_pushl(&stash
.args
,
3706 "stash", "create", "autostash", NULL
);
3710 if (capture_command(&stash
, &buf
, GIT_MAX_HEXSZ
))
3711 die(_("Cannot autostash"));
3712 strbuf_trim_trailing_newline(&buf
);
3713 if (get_oid(buf
.buf
, &oid
))
3714 die(_("Unexpected stash response: '%s'"),
3717 strbuf_add_unique_abbrev(&buf
, &oid
, DEFAULT_ABBREV
);
3719 if (safe_create_leading_directories_const(path
))
3720 die(_("Could not create directory for '%s'"),
3722 write_file(path
, "%s", oid_to_hex(&oid
));
3723 printf(_("Created autostash: %s\n"), buf
.buf
);
3724 if (reset_head(r
, NULL
, "reset --hard",
3725 NULL
, RESET_HEAD_HARD
, NULL
, NULL
,
3726 default_reflog_action
) < 0)
3727 die(_("could not reset --hard"));
3729 if (discard_index(r
->index
) < 0 ||
3730 repo_read_index(r
) < 0)
3731 die(_("could not read index"));
3733 strbuf_release(&buf
);
3736 static int apply_save_autostash_oid(const char *stash_oid
, int attempt_apply
)
3738 struct child_process child
= CHILD_PROCESS_INIT
;
3741 if (attempt_apply
) {
3743 child
.no_stdout
= 1;
3744 child
.no_stderr
= 1;
3745 strvec_push(&child
.args
, "stash");
3746 strvec_push(&child
.args
, "apply");
3747 strvec_push(&child
.args
, stash_oid
);
3748 ret
= run_command(&child
);
3751 if (attempt_apply
&& !ret
)
3752 fprintf(stderr
, _("Applied autostash.\n"));
3754 struct child_process store
= CHILD_PROCESS_INIT
;
3757 strvec_push(&store
.args
, "stash");
3758 strvec_push(&store
.args
, "store");
3759 strvec_push(&store
.args
, "-m");
3760 strvec_push(&store
.args
, "autostash");
3761 strvec_push(&store
.args
, "-q");
3762 strvec_push(&store
.args
, stash_oid
);
3763 if (run_command(&store
))
3764 ret
= error(_("cannot store %s"), stash_oid
);
3768 "Your changes are safe in the stash.\n"
3769 "You can run \"git stash pop\" or"
3770 " \"git stash drop\" at any time.\n"),
3772 _("Applying autostash resulted in conflicts.") :
3773 _("Autostash exists; creating a new stash entry."));
3779 static int apply_save_autostash(const char *path
, int attempt_apply
)
3781 struct strbuf stash_oid
= STRBUF_INIT
;
3784 if (!read_oneliner(&stash_oid
, path
,
3785 READ_ONELINER_SKIP_IF_EMPTY
)) {
3786 strbuf_release(&stash_oid
);
3789 strbuf_trim(&stash_oid
);
3791 ret
= apply_save_autostash_oid(stash_oid
.buf
, attempt_apply
);
3794 strbuf_release(&stash_oid
);
3798 int save_autostash(const char *path
)
3800 return apply_save_autostash(path
, 0);
3803 int apply_autostash(const char *path
)
3805 return apply_save_autostash(path
, 1);
3808 int apply_autostash_oid(const char *stash_oid
)
3810 return apply_save_autostash_oid(stash_oid
, 1);
3813 static const char *reflog_message(struct replay_opts
*opts
,
3814 const char *sub_action
, const char *fmt
, ...)
3817 static struct strbuf buf
= STRBUF_INIT
;
3818 char *reflog_action
= getenv(GIT_REFLOG_ACTION
);
3822 strbuf_addstr(&buf
, reflog_action
? reflog_action
: action_name(opts
));
3824 strbuf_addf(&buf
, " (%s)", sub_action
);
3826 strbuf_addstr(&buf
, ": ");
3827 strbuf_vaddf(&buf
, fmt
, ap
);
3834 static int run_git_checkout(struct repository
*r
, struct replay_opts
*opts
,
3835 const char *commit
, const char *action
)
3837 struct child_process cmd
= CHILD_PROCESS_INIT
;
3842 strvec_push(&cmd
.args
, "checkout");
3843 strvec_push(&cmd
.args
, commit
);
3844 strvec_pushf(&cmd
.env_array
, GIT_REFLOG_ACTION
"=%s", action
);
3847 ret
= run_command(&cmd
);
3849 ret
= run_command_silent_on_success(&cmd
);
3852 discard_index(r
->index
);
3857 static int checkout_onto(struct repository
*r
, struct replay_opts
*opts
,
3858 const char *onto_name
, const struct object_id
*onto
,
3859 const char *orig_head
)
3861 struct object_id oid
;
3862 const char *action
= reflog_message(opts
, "start", "checkout %s", onto_name
);
3864 if (get_oid(orig_head
, &oid
))
3865 return error(_("%s: not a valid OID"), orig_head
);
3867 if (run_git_checkout(r
, opts
, oid_to_hex(onto
), action
)) {
3868 apply_autostash(rebase_path_autostash());
3869 sequencer_remove_state(opts
);
3870 return error(_("could not detach HEAD"));
3873 return update_ref(NULL
, "ORIG_HEAD", &oid
, NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
3876 static int stopped_at_head(struct repository
*r
)
3878 struct object_id head
;
3879 struct commit
*commit
;
3880 struct commit_message message
;
3882 if (get_oid("HEAD", &head
) ||
3883 !(commit
= lookup_commit(r
, &head
)) ||
3884 parse_commit(commit
) || get_message(commit
, &message
))
3885 fprintf(stderr
, _("Stopped at HEAD\n"));
3887 fprintf(stderr
, _("Stopped at %s\n"), message
.label
);
3888 free_message(commit
, &message
);
3894 static const char rescheduled_advice
[] =
3895 N_("Could not execute the todo command\n"
3899 "It has been rescheduled; To edit the command before continuing, please\n"
3900 "edit the todo list first:\n"
3902 " git rebase --edit-todo\n"
3903 " git rebase --continue\n");
3905 static int pick_commits(struct repository
*r
,
3906 struct todo_list
*todo_list
,
3907 struct replay_opts
*opts
)
3909 int res
= 0, reschedule
= 0;
3910 char *prev_reflog_action
;
3912 /* Note that 0 for 3rd parameter of setenv means set only if not set */
3913 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
3914 prev_reflog_action
= xstrdup(getenv(GIT_REFLOG_ACTION
));
3916 assert(!(opts
->signoff
|| opts
->no_commit
||
3917 opts
->record_origin
|| opts
->edit
));
3918 if (read_and_refresh_cache(r
, opts
))
3921 while (todo_list
->current
< todo_list
->nr
) {
3922 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
3923 const char *arg
= todo_item_get_arg(todo_list
, item
);
3926 if (save_todo(todo_list
, opts
))
3928 if (is_rebase_i(opts
)) {
3929 if (item
->command
!= TODO_COMMENT
) {
3930 FILE *f
= fopen(rebase_path_msgnum(), "w");
3932 todo_list
->done_nr
++;
3935 fprintf(f
, "%d\n", todo_list
->done_nr
);
3939 fprintf(stderr
, _("Rebasing (%d/%d)%s"),
3941 todo_list
->total_nr
,
3942 opts
->verbose
? "\n" : "\r");
3944 unlink(rebase_path_message());
3945 unlink(rebase_path_author_script());
3946 unlink(rebase_path_stopped_sha());
3947 unlink(rebase_path_amend());
3948 unlink(git_path_merge_head(r
));
3949 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
3951 if (item
->command
== TODO_BREAK
) {
3954 return stopped_at_head(r
);
3957 if (item
->command
<= TODO_SQUASH
) {
3958 if (is_rebase_i(opts
))
3959 setenv(GIT_REFLOG_ACTION
, reflog_message(opts
,
3960 command_to_string(item
->command
), NULL
),
3962 res
= do_pick_commit(r
, item
->command
, item
->commit
,
3963 opts
, is_final_fixup(todo_list
),
3965 if (is_rebase_i(opts
))
3966 setenv(GIT_REFLOG_ACTION
, prev_reflog_action
, 1);
3967 if (is_rebase_i(opts
) && res
< 0) {
3969 advise(_(rescheduled_advice
),
3970 get_item_line_length(todo_list
,
3971 todo_list
->current
),
3972 get_item_line(todo_list
,
3973 todo_list
->current
));
3974 todo_list
->current
--;
3975 if (save_todo(todo_list
, opts
))
3978 if (item
->command
== TODO_EDIT
) {
3979 struct commit
*commit
= item
->commit
;
3984 _("Stopped at %s... %.*s\n"),
3985 short_commit_name(commit
),
3986 item
->arg_len
, arg
);
3988 return error_with_patch(r
, commit
,
3989 arg
, item
->arg_len
, opts
, res
, !res
);
3991 if (is_rebase_i(opts
) && !res
)
3992 record_in_rewritten(&item
->commit
->object
.oid
,
3993 peek_command(todo_list
, 1));
3994 if (res
&& is_fixup(item
->command
)) {
3997 return error_failed_squash(r
, item
->commit
, opts
,
3998 item
->arg_len
, arg
);
3999 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
4001 struct object_id oid
;
4004 * If we are rewording and have either
4005 * fast-forwarded already, or are about to
4006 * create a new root commit, we want to amend,
4007 * otherwise we do not.
4009 if (item
->command
== TODO_REWORD
&&
4010 !get_oid("HEAD", &oid
) &&
4011 (oideq(&item
->commit
->object
.oid
, &oid
) ||
4012 (opts
->have_squash_onto
&&
4013 oideq(&opts
->squash_onto
, &oid
))))
4016 return res
| error_with_patch(r
, item
->commit
,
4017 arg
, item
->arg_len
, opts
,
4020 } else if (item
->command
== TODO_EXEC
) {
4021 char *end_of_arg
= (char *)(arg
+ item
->arg_len
);
4022 int saved
= *end_of_arg
;
4027 res
= do_exec(r
, arg
);
4028 *end_of_arg
= saved
;
4031 if (opts
->reschedule_failed_exec
)
4035 } else if (item
->command
== TODO_LABEL
) {
4036 if ((res
= do_label(r
, arg
, item
->arg_len
)))
4038 } else if (item
->command
== TODO_RESET
) {
4039 if ((res
= do_reset(r
, arg
, item
->arg_len
, opts
)))
4041 } else if (item
->command
== TODO_MERGE
) {
4042 if ((res
= do_merge(r
, item
->commit
,
4044 item
->flags
, opts
)) < 0)
4046 else if (item
->commit
)
4047 record_in_rewritten(&item
->commit
->object
.oid
,
4048 peek_command(todo_list
, 1));
4050 /* failed with merge conflicts */
4051 return error_with_patch(r
, item
->commit
,
4054 } else if (!is_noop(item
->command
))
4055 return error(_("unknown command %d"), item
->command
);
4058 advise(_(rescheduled_advice
),
4059 get_item_line_length(todo_list
,
4060 todo_list
->current
),
4061 get_item_line(todo_list
, todo_list
->current
));
4062 todo_list
->current
--;
4063 if (save_todo(todo_list
, opts
))
4066 return error_with_patch(r
,
4070 } else if (is_rebase_i(opts
) && check_todo
&& !res
) {
4073 if (stat(get_todo_path(opts
), &st
)) {
4074 res
= error_errno(_("could not stat '%s'"),
4075 get_todo_path(opts
));
4076 } else if (match_stat_data(&todo_list
->stat
, &st
)) {
4077 /* Reread the todo file if it has changed. */
4078 todo_list_release(todo_list
);
4079 if (read_populate_todo(r
, todo_list
, opts
))
4080 res
= -1; /* message was printed */
4081 /* `current` will be incremented below */
4082 todo_list
->current
= -1;
4086 todo_list
->current
++;
4091 if (is_rebase_i(opts
)) {
4092 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
4095 /* Stopped in the middle, as planned? */
4096 if (todo_list
->current
< todo_list
->nr
)
4099 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
4100 starts_with(head_ref
.buf
, "refs/")) {
4102 struct object_id head
, orig
;
4105 if (get_oid("HEAD", &head
)) {
4106 res
= error(_("cannot read HEAD"));
4108 strbuf_release(&head_ref
);
4109 strbuf_release(&buf
);
4112 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
4113 get_oid_hex(buf
.buf
, &orig
)) {
4114 res
= error(_("could not read orig-head"));
4115 goto cleanup_head_ref
;
4118 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
4119 res
= error(_("could not read 'onto'"));
4120 goto cleanup_head_ref
;
4122 msg
= reflog_message(opts
, "finish", "%s onto %s",
4123 head_ref
.buf
, buf
.buf
);
4124 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
4125 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
4126 res
= error(_("could not update %s"),
4128 goto cleanup_head_ref
;
4130 msg
= reflog_message(opts
, "finish", "returning to %s",
4132 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
4133 res
= error(_("could not update HEAD to %s"),
4135 goto cleanup_head_ref
;
4140 if (opts
->verbose
) {
4141 struct rev_info log_tree_opt
;
4142 struct object_id orig
, head
;
4144 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
4145 repo_init_revisions(r
, &log_tree_opt
, NULL
);
4146 log_tree_opt
.diff
= 1;
4147 log_tree_opt
.diffopt
.output_format
=
4148 DIFF_FORMAT_DIFFSTAT
;
4149 log_tree_opt
.disable_stdin
= 1;
4151 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
4152 !get_oid(buf
.buf
, &orig
) &&
4153 !get_oid("HEAD", &head
)) {
4154 diff_tree_oid(&orig
, &head
, "",
4155 &log_tree_opt
.diffopt
);
4156 log_tree_diff_flush(&log_tree_opt
);
4159 flush_rewritten_pending();
4160 if (!stat(rebase_path_rewritten_list(), &st
) &&
4162 struct child_process child
= CHILD_PROCESS_INIT
;
4163 const char *post_rewrite_hook
=
4164 find_hook("post-rewrite");
4166 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
4168 strvec_push(&child
.args
, "notes");
4169 strvec_push(&child
.args
, "copy");
4170 strvec_push(&child
.args
, "--for-rewrite=rebase");
4171 /* we don't care if this copying failed */
4172 run_command(&child
);
4174 if (post_rewrite_hook
) {
4175 struct child_process hook
= CHILD_PROCESS_INIT
;
4177 hook
.in
= open(rebase_path_rewritten_list(),
4179 hook
.stdout_to_stderr
= 1;
4180 hook
.trace2_hook_name
= "post-rewrite";
4181 strvec_push(&hook
.args
, post_rewrite_hook
);
4182 strvec_push(&hook
.args
, "rebase");
4183 /* we don't care if this hook failed */
4187 apply_autostash(rebase_path_autostash());
4193 _("Successfully rebased and updated %s.\n"),
4197 strbuf_release(&buf
);
4198 strbuf_release(&head_ref
);
4202 * Sequence of picks finished successfully; cleanup by
4203 * removing the .git/sequencer directory
4205 return sequencer_remove_state(opts
);
4208 static int continue_single_pick(struct repository
*r
)
4210 const char *argv
[] = { "commit", NULL
};
4212 if (!refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD") &&
4213 !file_exists(git_path_revert_head(r
)))
4214 return error(_("no cherry-pick or revert in progress"));
4215 return run_command_v_opt(argv
, RUN_GIT_CMD
);
4218 static int commit_staged_changes(struct repository
*r
,
4219 struct replay_opts
*opts
,
4220 struct todo_list
*todo_list
)
4222 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
4223 unsigned int final_fixup
= 0, is_clean
;
4225 if (has_unstaged_changes(r
, 1))
4226 return error(_("cannot rebase: You have unstaged changes."));
4228 is_clean
= !has_uncommitted_changes(r
, 0);
4230 if (file_exists(rebase_path_amend())) {
4231 struct strbuf rev
= STRBUF_INIT
;
4232 struct object_id head
, to_amend
;
4234 if (get_oid("HEAD", &head
))
4235 return error(_("cannot amend non-existing commit"));
4236 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
4237 return error(_("invalid file: '%s'"), rebase_path_amend());
4238 if (get_oid_hex(rev
.buf
, &to_amend
))
4239 return error(_("invalid contents: '%s'"),
4240 rebase_path_amend());
4241 if (!is_clean
&& !oideq(&head
, &to_amend
))
4242 return error(_("\nYou have uncommitted changes in your "
4243 "working tree. Please, commit them\n"
4244 "first and then run 'git rebase "
4245 "--continue' again."));
4247 * When skipping a failed fixup/squash, we need to edit the
4248 * commit message, the current fixup list and count, and if it
4249 * was the last fixup/squash in the chain, we need to clean up
4250 * the commit message and if there was a squash, let the user
4253 if (!is_clean
|| !opts
->current_fixup_count
)
4254 ; /* this is not the final fixup */
4255 else if (!oideq(&head
, &to_amend
) ||
4256 !file_exists(rebase_path_stopped_sha())) {
4257 /* was a final fixup or squash done manually? */
4258 if (!is_fixup(peek_command(todo_list
, 0))) {
4259 unlink(rebase_path_fixup_msg());
4260 unlink(rebase_path_squash_msg());
4261 unlink(rebase_path_current_fixups());
4262 strbuf_reset(&opts
->current_fixups
);
4263 opts
->current_fixup_count
= 0;
4266 /* we are in a fixup/squash chain */
4267 const char *p
= opts
->current_fixups
.buf
;
4268 int len
= opts
->current_fixups
.len
;
4270 opts
->current_fixup_count
--;
4272 BUG("Incorrect current_fixups:\n%s", p
);
4273 while (len
&& p
[len
- 1] != '\n')
4275 strbuf_setlen(&opts
->current_fixups
, len
);
4276 if (write_message(p
, len
, rebase_path_current_fixups(),
4278 return error(_("could not write file: '%s'"),
4279 rebase_path_current_fixups());
4282 * If a fixup/squash in a fixup/squash chain failed, the
4283 * commit message is already correct, no need to commit
4286 * Only if it is the final command in the fixup/squash
4287 * chain, and only if the chain is longer than a single
4288 * fixup/squash command (which was just skipped), do we
4289 * actually need to re-commit with a cleaned up commit
4292 if (opts
->current_fixup_count
> 0 &&
4293 !is_fixup(peek_command(todo_list
, 0))) {
4296 * If there was not a single "squash" in the
4297 * chain, we only need to clean up the commit
4298 * message, no need to bother the user with
4299 * opening the commit message in the editor.
4301 if (!starts_with(p
, "squash ") &&
4302 !strstr(p
, "\nsquash "))
4303 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
4304 } else if (is_fixup(peek_command(todo_list
, 0))) {
4306 * We need to update the squash message to skip
4307 * the latest commit message.
4309 struct commit
*commit
;
4310 const char *path
= rebase_path_squash_msg();
4311 const char *encoding
= get_commit_output_encoding();
4313 if (parse_head(r
, &commit
) ||
4314 !(p
= logmsg_reencode(commit
, NULL
, encoding
)) ||
4315 write_message(p
, strlen(p
), path
, 0)) {
4316 unuse_commit_buffer(commit
, p
);
4317 return error(_("could not write file: "
4320 unuse_commit_buffer(commit
, p
);
4324 strbuf_release(&rev
);
4329 if (refs_ref_exists(get_main_ref_store(r
),
4330 "CHERRY_PICK_HEAD") &&
4331 refs_delete_ref(get_main_ref_store(r
), "",
4332 "CHERRY_PICK_HEAD", NULL
, 0))
4333 return error(_("could not remove CHERRY_PICK_HEAD"));
4338 if (run_git_commit(r
, final_fixup
? NULL
: rebase_path_message(),
4340 return error(_("could not commit staged changes."));
4341 unlink(rebase_path_amend());
4342 unlink(git_path_merge_head(r
));
4344 unlink(rebase_path_fixup_msg());
4345 unlink(rebase_path_squash_msg());
4347 if (opts
->current_fixup_count
> 0) {
4349 * Whether final fixup or not, we just cleaned up the commit
4352 unlink(rebase_path_current_fixups());
4353 strbuf_reset(&opts
->current_fixups
);
4354 opts
->current_fixup_count
= 0;
4359 int sequencer_continue(struct repository
*r
, struct replay_opts
*opts
)
4361 struct todo_list todo_list
= TODO_LIST_INIT
;
4364 if (read_and_refresh_cache(r
, opts
))
4367 if (read_populate_opts(opts
))
4369 if (is_rebase_i(opts
)) {
4370 if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
4371 goto release_todo_list
;
4373 if (file_exists(rebase_path_dropped())) {
4374 if ((res
= todo_list_check_against_backup(r
, &todo_list
)))
4375 goto release_todo_list
;
4377 unlink(rebase_path_dropped());
4380 if (commit_staged_changes(r
, opts
, &todo_list
)) {
4382 goto release_todo_list
;
4384 } else if (!file_exists(get_todo_path(opts
)))
4385 return continue_single_pick(r
);
4386 else if ((res
= read_populate_todo(r
, &todo_list
, opts
)))
4387 goto release_todo_list
;
4389 if (!is_rebase_i(opts
)) {
4390 /* Verify that the conflict has been resolved */
4391 if (refs_ref_exists(get_main_ref_store(r
),
4392 "CHERRY_PICK_HEAD") ||
4393 file_exists(git_path_revert_head(r
))) {
4394 res
= continue_single_pick(r
);
4396 goto release_todo_list
;
4398 if (index_differs_from(r
, "HEAD", NULL
, 0)) {
4399 res
= error_dirty_index(r
, opts
);
4400 goto release_todo_list
;
4402 todo_list
.current
++;
4403 } else if (file_exists(rebase_path_stopped_sha())) {
4404 struct strbuf buf
= STRBUF_INIT
;
4405 struct object_id oid
;
4407 if (read_oneliner(&buf
, rebase_path_stopped_sha(),
4408 READ_ONELINER_SKIP_IF_EMPTY
) &&
4409 !get_oid_committish(buf
.buf
, &oid
))
4410 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
4411 strbuf_release(&buf
);
4414 res
= pick_commits(r
, &todo_list
, opts
);
4416 todo_list_release(&todo_list
);
4420 static int single_pick(struct repository
*r
,
4421 struct commit
*cmit
,
4422 struct replay_opts
*opts
)
4426 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
4427 return do_pick_commit(r
, opts
->action
== REPLAY_PICK
?
4428 TODO_PICK
: TODO_REVERT
, cmit
, opts
, 0,
4432 int sequencer_pick_revisions(struct repository
*r
,
4433 struct replay_opts
*opts
)
4435 struct todo_list todo_list
= TODO_LIST_INIT
;
4436 struct object_id oid
;
4440 if (read_and_refresh_cache(r
, opts
))
4443 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
4444 struct object_id oid
;
4445 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
4447 /* This happens when using --stdin. */
4451 if (!get_oid(name
, &oid
)) {
4452 if (!lookup_commit_reference_gently(r
, &oid
, 1)) {
4453 enum object_type type
= oid_object_info(r
,
4456 return error(_("%s: can't cherry-pick a %s"),
4457 name
, type_name(type
));
4460 return error(_("%s: bad revision"), name
);
4464 * If we were called as "git cherry-pick <commit>", just
4465 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4466 * REVERT_HEAD, and don't touch the sequencer state.
4467 * This means it is possible to cherry-pick in the middle
4468 * of a cherry-pick sequence.
4470 if (opts
->revs
->cmdline
.nr
== 1 &&
4471 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
4472 opts
->revs
->no_walk
&&
4473 !opts
->revs
->cmdline
.rev
->flags
) {
4474 struct commit
*cmit
;
4475 if (prepare_revision_walk(opts
->revs
))
4476 return error(_("revision walk setup failed"));
4477 cmit
= get_revision(opts
->revs
);
4479 return error(_("empty commit set passed"));
4480 if (get_revision(opts
->revs
))
4481 BUG("unexpected extra commit from walk");
4482 return single_pick(r
, cmit
, opts
);
4486 * Start a new cherry-pick/ revert sequence; but
4487 * first, make sure that an existing one isn't in
4491 if (walk_revs_populate_todo(&todo_list
, opts
) ||
4492 create_seq_dir(r
) < 0)
4494 if (get_oid("HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
4495 return error(_("can't revert as initial commit"));
4496 if (save_head(oid_to_hex(&oid
)))
4498 if (save_opts(opts
))
4500 update_abort_safety_file();
4501 res
= pick_commits(r
, &todo_list
, opts
);
4502 todo_list_release(&todo_list
);
4506 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
4508 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
4509 struct strbuf sob
= STRBUF_INIT
;
4512 strbuf_addstr(&sob
, sign_off_header
);
4513 strbuf_addstr(&sob
, fmt_name(WANT_COMMITTER_IDENT
));
4514 strbuf_addch(&sob
, '\n');
4517 strbuf_complete_line(msgbuf
);
4520 * If the whole message buffer is equal to the sob, pretend that we
4521 * found a conforming footer with a matching sob
4523 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
4524 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
4527 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
4530 const char *append_newlines
= NULL
;
4531 size_t len
= msgbuf
->len
- ignore_footer
;
4535 * The buffer is completely empty. Leave foom for
4536 * the title and body to be filled in by the user.
4538 append_newlines
= "\n\n";
4539 } else if (len
== 1) {
4541 * Buffer contains a single newline. Add another
4542 * so that we leave room for the title and body.
4544 append_newlines
= "\n";
4545 } else if (msgbuf
->buf
[len
- 2] != '\n') {
4547 * Buffer ends with a single newline. Add another
4548 * so that there is an empty line between the message
4551 append_newlines
= "\n";
4552 } /* else, the buffer already ends with two newlines. */
4554 if (append_newlines
)
4555 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
4556 append_newlines
, strlen(append_newlines
));
4559 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
4560 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
4563 strbuf_release(&sob
);
4566 struct labels_entry
{
4567 struct hashmap_entry entry
;
4568 char label
[FLEX_ARRAY
];
4571 static int labels_cmp(const void *fndata
, const struct hashmap_entry
*eptr
,
4572 const struct hashmap_entry
*entry_or_key
, const void *key
)
4574 const struct labels_entry
*a
, *b
;
4576 a
= container_of(eptr
, const struct labels_entry
, entry
);
4577 b
= container_of(entry_or_key
, const struct labels_entry
, entry
);
4579 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
4582 struct string_entry
{
4583 struct oidmap_entry entry
;
4584 char string
[FLEX_ARRAY
];
4587 struct label_state
{
4588 struct oidmap commit2label
;
4589 struct hashmap labels
;
4593 static const char *label_oid(struct object_id
*oid
, const char *label
,
4594 struct label_state
*state
)
4596 struct labels_entry
*labels_entry
;
4597 struct string_entry
*string_entry
;
4598 struct object_id dummy
;
4601 string_entry
= oidmap_get(&state
->commit2label
, oid
);
4603 return string_entry
->string
;
4606 * For "uninteresting" commits, i.e. commits that are not to be
4607 * rebased, and which can therefore not be labeled, we use a unique
4608 * abbreviation of the commit name. This is slightly more complicated
4609 * than calling find_unique_abbrev() because we also need to make
4610 * sure that the abbreviation does not conflict with any other
4613 * We disallow "interesting" commits to be labeled by a string that
4614 * is a valid full-length hash, to ensure that we always can find an
4615 * abbreviation for any uninteresting commit's names that does not
4616 * clash with any other label.
4618 strbuf_reset(&state
->buf
);
4622 strbuf_grow(&state
->buf
, GIT_MAX_HEXSZ
);
4623 label
= p
= state
->buf
.buf
;
4625 find_unique_abbrev_r(p
, oid
, default_abbrev
);
4628 * We may need to extend the abbreviated hash so that there is
4629 * no conflicting label.
4631 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
4632 size_t i
= strlen(p
) + 1;
4634 oid_to_hex_r(p
, oid
);
4635 for (; i
< the_hash_algo
->hexsz
; i
++) {
4638 if (!hashmap_get_from_hash(&state
->labels
,
4645 struct strbuf
*buf
= &state
->buf
;
4648 * Sanitize labels by replacing non-alpha-numeric characters
4649 * (including white-space ones) by dashes, as they might be
4650 * illegal in file names (and hence in ref names).
4652 * Note that we retain non-ASCII UTF-8 characters (identified
4653 * via the most significant bit). They should be all acceptable
4654 * in file names. We do not validate the UTF-8 here, that's not
4655 * the job of this function.
4657 for (; *label
; label
++)
4658 if ((*label
& 0x80) || isalnum(*label
))
4659 strbuf_addch(buf
, *label
);
4660 /* avoid leading dash and double-dashes */
4661 else if (buf
->len
&& buf
->buf
[buf
->len
- 1] != '-')
4662 strbuf_addch(buf
, '-');
4664 strbuf_addstr(buf
, "rev-");
4665 strbuf_add_unique_abbrev(buf
, oid
, default_abbrev
);
4669 if ((buf
->len
== the_hash_algo
->hexsz
&&
4670 !get_oid_hex(label
, &dummy
)) ||
4671 (buf
->len
== 1 && *label
== '#') ||
4672 hashmap_get_from_hash(&state
->labels
,
4673 strihash(label
), label
)) {
4675 * If the label already exists, or if the label is a
4676 * valid full OID, or the label is a '#' (which we use
4677 * as a separator between merge heads and oneline), we
4678 * append a dash and a number to make it unique.
4680 size_t len
= buf
->len
;
4682 for (i
= 2; ; i
++) {
4683 strbuf_setlen(buf
, len
);
4684 strbuf_addf(buf
, "-%d", i
);
4685 if (!hashmap_get_from_hash(&state
->labels
,
4695 FLEX_ALLOC_STR(labels_entry
, label
, label
);
4696 hashmap_entry_init(&labels_entry
->entry
, strihash(label
));
4697 hashmap_add(&state
->labels
, &labels_entry
->entry
);
4699 FLEX_ALLOC_STR(string_entry
, string
, label
);
4700 oidcpy(&string_entry
->entry
.oid
, oid
);
4701 oidmap_put(&state
->commit2label
, string_entry
);
4703 return string_entry
->string
;
4706 static int make_script_with_merges(struct pretty_print_context
*pp
,
4707 struct rev_info
*revs
, struct strbuf
*out
,
4710 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
4711 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
4712 int root_with_onto
= flags
& TODO_LIST_ROOT_WITH_ONTO
;
4713 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
4714 struct strbuf label
= STRBUF_INIT
;
4715 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
4716 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
4717 struct commit
*commit
;
4718 struct oidmap commit2todo
= OIDMAP_INIT
;
4719 struct string_entry
*entry
;
4720 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
4721 shown
= OIDSET_INIT
;
4722 struct label_state state
= { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
};
4724 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
4725 const char *cmd_pick
= abbr
? "p" : "pick",
4726 *cmd_label
= abbr
? "l" : "label",
4727 *cmd_reset
= abbr
? "t" : "reset",
4728 *cmd_merge
= abbr
? "m" : "merge";
4730 oidmap_init(&commit2todo
, 0);
4731 oidmap_init(&state
.commit2label
, 0);
4732 hashmap_init(&state
.labels
, labels_cmp
, NULL
, 0);
4733 strbuf_init(&state
.buf
, 32);
4735 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
4736 struct labels_entry
*onto_label_entry
;
4737 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
4738 FLEX_ALLOC_STR(entry
, string
, "onto");
4739 oidcpy(&entry
->entry
.oid
, oid
);
4740 oidmap_put(&state
.commit2label
, entry
);
4742 FLEX_ALLOC_STR(onto_label_entry
, label
, "onto");
4743 hashmap_entry_init(&onto_label_entry
->entry
, strihash("onto"));
4744 hashmap_add(&state
.labels
, &onto_label_entry
->entry
);
4749 * - get onelines for all commits
4750 * - gather all branch tips (i.e. 2nd or later parents of merges)
4751 * - label all branch tips
4753 while ((commit
= get_revision(revs
))) {
4754 struct commit_list
*to_merge
;
4755 const char *p1
, *p2
;
4756 struct object_id
*oid
;
4759 tail
= &commit_list_insert(commit
, tail
)->next
;
4760 oidset_insert(&interesting
, &commit
->object
.oid
);
4762 is_empty
= is_original_commit_empty(commit
);
4763 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
))
4765 if (is_empty
&& !keep_empty
)
4768 strbuf_reset(&oneline
);
4769 pretty_print_commit(pp
, commit
, &oneline
);
4771 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
4773 /* non-merge commit: easy case */
4775 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
4776 oid_to_hex(&commit
->object
.oid
),
4779 strbuf_addf(&buf
, " %c empty",
4782 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
4783 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
4784 oidmap_put(&commit2todo
, entry
);
4789 /* Create a label */
4790 strbuf_reset(&label
);
4791 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
4792 (p1
= strchr(p1
, '\'')) &&
4793 (p2
= strchr(++p1
, '\'')))
4794 strbuf_add(&label
, p1
, p2
- p1
);
4795 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
4797 (p1
= strstr(p1
, " from ")))
4798 strbuf_addstr(&label
, p1
+ strlen(" from "));
4800 strbuf_addbuf(&label
, &oneline
);
4803 strbuf_addf(&buf
, "%s -C %s",
4804 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
4806 /* label the tips of merged branches */
4807 for (; to_merge
; to_merge
= to_merge
->next
) {
4808 oid
= &to_merge
->item
->object
.oid
;
4809 strbuf_addch(&buf
, ' ');
4811 if (!oidset_contains(&interesting
, oid
)) {
4812 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
4817 tips_tail
= &commit_list_insert(to_merge
->item
,
4820 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
4822 strbuf_addf(&buf
, " # %s", oneline
.buf
);
4824 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
4825 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
4826 oidmap_put(&commit2todo
, entry
);
4831 * - label branch points
4832 * - add HEAD to the branch tips
4834 for (iter
= commits
; iter
; iter
= iter
->next
) {
4835 struct commit_list
*parent
= iter
->item
->parents
;
4836 for (; parent
; parent
= parent
->next
) {
4837 struct object_id
*oid
= &parent
->item
->object
.oid
;
4838 if (!oidset_contains(&interesting
, oid
))
4840 if (oidset_insert(&child_seen
, oid
))
4841 label_oid(oid
, "branch-point", &state
);
4844 /* Add HEAD as implicit "tip of branch" */
4846 tips_tail
= &commit_list_insert(iter
->item
,
4851 * Third phase: output the todo list. This is a bit tricky, as we
4852 * want to avoid jumping back and forth between revisions. To
4853 * accomplish that goal, we walk backwards from the branch tips,
4854 * gathering commits not yet shown, reversing the list on the fly,
4855 * then outputting that list (labeling revisions as needed).
4857 strbuf_addf(out
, "%s onto\n", cmd_label
);
4858 for (iter
= tips
; iter
; iter
= iter
->next
) {
4859 struct commit_list
*list
= NULL
, *iter2
;
4861 commit
= iter
->item
;
4862 if (oidset_contains(&shown
, &commit
->object
.oid
))
4864 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
4867 strbuf_addf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
4869 strbuf_addch(out
, '\n');
4871 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
4872 !oidset_contains(&shown
, &commit
->object
.oid
)) {
4873 commit_list_insert(commit
, &list
);
4874 if (!commit
->parents
) {
4878 commit
= commit
->parents
->item
;
4882 strbuf_addf(out
, "%s %s\n", cmd_reset
,
4883 rebase_cousins
|| root_with_onto
?
4884 "onto" : "[new root]");
4886 const char *to
= NULL
;
4888 entry
= oidmap_get(&state
.commit2label
,
4889 &commit
->object
.oid
);
4892 else if (!rebase_cousins
)
4893 to
= label_oid(&commit
->object
.oid
, NULL
,
4896 if (!to
|| !strcmp(to
, "onto"))
4897 strbuf_addf(out
, "%s onto\n", cmd_reset
);
4899 strbuf_reset(&oneline
);
4900 pretty_print_commit(pp
, commit
, &oneline
);
4901 strbuf_addf(out
, "%s %s # %s\n",
4902 cmd_reset
, to
, oneline
.buf
);
4906 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
4907 struct object_id
*oid
= &iter2
->item
->object
.oid
;
4908 entry
= oidmap_get(&commit2todo
, oid
);
4909 /* only show if not already upstream */
4911 strbuf_addf(out
, "%s\n", entry
->string
);
4912 entry
= oidmap_get(&state
.commit2label
, oid
);
4914 strbuf_addf(out
, "%s %s\n",
4915 cmd_label
, entry
->string
);
4916 oidset_insert(&shown
, oid
);
4919 free_commit_list(list
);
4922 free_commit_list(commits
);
4923 free_commit_list(tips
);
4925 strbuf_release(&label
);
4926 strbuf_release(&oneline
);
4927 strbuf_release(&buf
);
4929 oidmap_free(&commit2todo
, 1);
4930 oidmap_free(&state
.commit2label
, 1);
4931 hashmap_free_entries(&state
.labels
, struct labels_entry
, entry
);
4932 strbuf_release(&state
.buf
);
4937 int sequencer_make_script(struct repository
*r
, struct strbuf
*out
, int argc
,
4938 const char **argv
, unsigned flags
)
4940 char *format
= NULL
;
4941 struct pretty_print_context pp
= {0};
4942 struct rev_info revs
;
4943 struct commit
*commit
;
4944 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
4945 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
4946 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
4947 int reapply_cherry_picks
= flags
& TODO_LIST_REAPPLY_CHERRY_PICKS
;
4949 repo_init_revisions(r
, &revs
, NULL
);
4950 revs
.verbose_header
= 1;
4952 revs
.max_parents
= 1;
4953 revs
.cherry_mark
= !reapply_cherry_picks
;
4956 revs
.right_only
= 1;
4957 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
4958 revs
.topo_order
= 1;
4960 revs
.pretty_given
= 1;
4961 git_config_get_string("rebase.instructionFormat", &format
);
4962 if (!format
|| !*format
) {
4964 format
= xstrdup("%s");
4966 get_commit_format(format
, &revs
);
4968 pp
.fmt
= revs
.commit_format
;
4969 pp
.output_encoding
= get_log_output_encoding();
4971 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1)
4972 return error(_("make_script: unhandled options"));
4974 if (prepare_revision_walk(&revs
) < 0)
4975 return error(_("make_script: error preparing revisions"));
4978 return make_script_with_merges(&pp
, &revs
, out
, flags
);
4980 while ((commit
= get_revision(&revs
))) {
4981 int is_empty
= is_original_commit_empty(commit
);
4983 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
))
4985 if (is_empty
&& !keep_empty
)
4987 strbuf_addf(out
, "%s %s ", insn
,
4988 oid_to_hex(&commit
->object
.oid
));
4989 pretty_print_commit(&pp
, commit
, out
);
4991 strbuf_addf(out
, " %c empty", comment_line_char
);
4992 strbuf_addch(out
, '\n');
4998 * Add commands after pick and (series of) squash/fixup commands
5001 void todo_list_add_exec_commands(struct todo_list
*todo_list
,
5002 struct string_list
*commands
)
5004 struct strbuf
*buf
= &todo_list
->buf
;
5005 size_t base_offset
= buf
->len
;
5006 int i
, insert
, nr
= 0, alloc
= 0;
5007 struct todo_item
*items
= NULL
, *base_items
= NULL
;
5009 base_items
= xcalloc(commands
->nr
, sizeof(struct todo_item
));
5010 for (i
= 0; i
< commands
->nr
; i
++) {
5011 size_t command_len
= strlen(commands
->items
[i
].string
);
5013 strbuf_addstr(buf
, commands
->items
[i
].string
);
5014 strbuf_addch(buf
, '\n');
5016 base_items
[i
].command
= TODO_EXEC
;
5017 base_items
[i
].offset_in_buf
= base_offset
;
5018 base_items
[i
].arg_offset
= base_offset
+ strlen("exec ");
5019 base_items
[i
].arg_len
= command_len
- strlen("exec ");
5021 base_offset
+= command_len
+ 1;
5025 * Insert <commands> after every pick. Here, fixup/squash chains
5026 * are considered part of the pick, so we insert the commands *after*
5027 * those chains if there are any.
5029 * As we insert the exec commands immediately after rearranging
5030 * any fixups and before the user edits the list, a fixup chain
5031 * can never contain comments (any comments are empty picks that
5032 * have been commented out because the user did not specify
5033 * --keep-empty). So, it is safe to insert an exec command
5034 * without looking at the command following a comment.
5037 for (i
= 0; i
< todo_list
->nr
; i
++) {
5038 enum todo_command command
= todo_list
->items
[i
].command
;
5039 if (insert
&& !is_fixup(command
)) {
5040 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5041 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5047 ALLOC_GROW(items
, nr
+ 1, alloc
);
5048 items
[nr
++] = todo_list
->items
[i
];
5050 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
5054 /* insert or append final <commands> */
5055 if (insert
|| nr
== todo_list
->nr
) {
5056 ALLOC_GROW(items
, nr
+ commands
->nr
, alloc
);
5057 COPY_ARRAY(items
+ nr
, base_items
, commands
->nr
);
5062 FREE_AND_NULL(todo_list
->items
);
5063 todo_list
->items
= items
;
5065 todo_list
->alloc
= alloc
;
5068 static void todo_list_to_strbuf(struct repository
*r
, struct todo_list
*todo_list
,
5069 struct strbuf
*buf
, int num
, unsigned flags
)
5071 struct todo_item
*item
;
5072 int i
, max
= todo_list
->nr
;
5074 if (num
> 0 && num
< max
)
5077 for (item
= todo_list
->items
, i
= 0; i
< max
; i
++, item
++) {
5080 /* if the item is not a command write it and continue */
5081 if (item
->command
>= TODO_COMMENT
) {
5082 strbuf_addf(buf
, "%.*s\n", item
->arg_len
,
5083 todo_item_get_arg(todo_list
, item
));
5087 /* add command to the buffer */
5088 cmd
= command_to_char(item
->command
);
5089 if ((flags
& TODO_LIST_ABBREVIATE_CMDS
) && cmd
)
5090 strbuf_addch(buf
, cmd
);
5092 strbuf_addstr(buf
, command_to_string(item
->command
));
5096 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
5097 short_commit_name(item
->commit
) :
5098 oid_to_hex(&item
->commit
->object
.oid
);
5100 if (item
->command
== TODO_MERGE
) {
5101 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
5102 strbuf_addstr(buf
, " -c");
5104 strbuf_addstr(buf
, " -C");
5107 strbuf_addf(buf
, " %s", oid
);
5110 /* add all the rest */
5112 strbuf_addch(buf
, '\n');
5114 strbuf_addf(buf
, " %.*s\n", item
->arg_len
,
5115 todo_item_get_arg(todo_list
, item
));
5119 int todo_list_write_to_file(struct repository
*r
, struct todo_list
*todo_list
,
5120 const char *file
, const char *shortrevisions
,
5121 const char *shortonto
, int num
, unsigned flags
)
5124 struct strbuf buf
= STRBUF_INIT
;
5126 todo_list_to_strbuf(r
, todo_list
, &buf
, num
, flags
);
5127 if (flags
& TODO_LIST_APPEND_TODO_HELP
)
5128 append_todo_help(count_commands(todo_list
),
5129 shortrevisions
, shortonto
, &buf
);
5131 res
= write_message(buf
.buf
, buf
.len
, file
, 0);
5132 strbuf_release(&buf
);
5137 /* skip picking commits whose parents are unchanged */
5138 static int skip_unnecessary_picks(struct repository
*r
,
5139 struct todo_list
*todo_list
,
5140 struct object_id
*base_oid
)
5142 struct object_id
*parent_oid
;
5145 for (i
= 0; i
< todo_list
->nr
; i
++) {
5146 struct todo_item
*item
= todo_list
->items
+ i
;
5148 if (item
->command
>= TODO_NOOP
)
5150 if (item
->command
!= TODO_PICK
)
5152 if (parse_commit(item
->commit
)) {
5153 return error(_("could not parse commit '%s'"),
5154 oid_to_hex(&item
->commit
->object
.oid
));
5156 if (!item
->commit
->parents
)
5157 break; /* root commit */
5158 if (item
->commit
->parents
->next
)
5159 break; /* merge commit */
5160 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
5161 if (!oideq(parent_oid
, base_oid
))
5163 oidcpy(base_oid
, &item
->commit
->object
.oid
);
5166 const char *done_path
= rebase_path_done();
5168 if (todo_list_write_to_file(r
, todo_list
, done_path
, NULL
, NULL
, i
, 0)) {
5169 error_errno(_("could not write to '%s'"), done_path
);
5173 MOVE_ARRAY(todo_list
->items
, todo_list
->items
+ i
, todo_list
->nr
- i
);
5175 todo_list
->current
= 0;
5176 todo_list
->done_nr
+= i
;
5178 if (is_fixup(peek_command(todo_list
, 0)))
5179 record_in_rewritten(base_oid
, peek_command(todo_list
, 0));
5185 int complete_action(struct repository
*r
, struct replay_opts
*opts
, unsigned flags
,
5186 const char *shortrevisions
, const char *onto_name
,
5187 struct commit
*onto
, const char *orig_head
,
5188 struct string_list
*commands
, unsigned autosquash
,
5189 struct todo_list
*todo_list
)
5191 const char *shortonto
, *todo_file
= rebase_path_todo();
5192 struct todo_list new_todo
= TODO_LIST_INIT
;
5193 struct strbuf
*buf
= &todo_list
->buf
, buf2
= STRBUF_INIT
;
5194 struct object_id oid
= onto
->object
.oid
;
5197 shortonto
= find_unique_abbrev(&oid
, DEFAULT_ABBREV
);
5199 if (buf
->len
== 0) {
5200 struct todo_item
*item
= append_new_todo(todo_list
);
5201 item
->command
= TODO_NOOP
;
5202 item
->commit
= NULL
;
5203 item
->arg_len
= item
->arg_offset
= item
->flags
= item
->offset_in_buf
= 0;
5206 if (autosquash
&& todo_list_rearrange_squash(todo_list
))
5210 todo_list_add_exec_commands(todo_list
, commands
);
5212 if (count_commands(todo_list
) == 0) {
5213 apply_autostash(rebase_path_autostash());
5214 sequencer_remove_state(opts
);
5216 return error(_("nothing to do"));
5219 res
= edit_todo_list(r
, todo_list
, &new_todo
, shortrevisions
,
5223 else if (res
== -2) {
5224 apply_autostash(rebase_path_autostash());
5225 sequencer_remove_state(opts
);
5228 } else if (res
== -3) {
5229 apply_autostash(rebase_path_autostash());
5230 sequencer_remove_state(opts
);
5231 todo_list_release(&new_todo
);
5233 return error(_("nothing to do"));
5234 } else if (res
== -4) {
5235 checkout_onto(r
, opts
, onto_name
, &onto
->object
.oid
, orig_head
);
5236 todo_list_release(&new_todo
);
5241 /* Expand the commit IDs */
5242 todo_list_to_strbuf(r
, &new_todo
, &buf2
, -1, 0);
5243 strbuf_swap(&new_todo
.buf
, &buf2
);
5244 strbuf_release(&buf2
);
5245 new_todo
.total_nr
-= new_todo
.nr
;
5246 if (todo_list_parse_insn_buffer(r
, new_todo
.buf
.buf
, &new_todo
) < 0)
5247 BUG("invalid todo list after expanding IDs:\n%s",
5250 if (opts
->allow_ff
&& skip_unnecessary_picks(r
, &new_todo
, &oid
)) {
5251 todo_list_release(&new_todo
);
5252 return error(_("could not skip unnecessary pick commands"));
5255 if (todo_list_write_to_file(r
, &new_todo
, todo_file
, NULL
, NULL
, -1,
5256 flags
& ~(TODO_LIST_SHORTEN_IDS
))) {
5257 todo_list_release(&new_todo
);
5258 return error_errno(_("could not write '%s'"), todo_file
);
5263 if (checkout_onto(r
, opts
, onto_name
, &oid
, orig_head
))
5266 if (require_clean_work_tree(r
, "rebase", "", 1, 1))
5269 todo_list_write_total_nr(&new_todo
);
5270 res
= pick_commits(r
, &new_todo
, opts
);
5273 todo_list_release(&new_todo
);
5278 struct subject2item_entry
{
5279 struct hashmap_entry entry
;
5281 char subject
[FLEX_ARRAY
];
5284 static int subject2item_cmp(const void *fndata
,
5285 const struct hashmap_entry
*eptr
,
5286 const struct hashmap_entry
*entry_or_key
,
5289 const struct subject2item_entry
*a
, *b
;
5291 a
= container_of(eptr
, const struct subject2item_entry
, entry
);
5292 b
= container_of(entry_or_key
, const struct subject2item_entry
, entry
);
5294 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
5297 define_commit_slab(commit_todo_item
, struct todo_item
*);
5300 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5301 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5302 * after the former, and change "pick" to "fixup"/"squash".
5304 * Note that if the config has specified a custom instruction format, each log
5305 * message will have to be retrieved from the commit (as the oneline in the
5306 * script cannot be trusted) in order to normalize the autosquash arrangement.
5308 int todo_list_rearrange_squash(struct todo_list
*todo_list
)
5310 struct hashmap subject2item
;
5311 int rearranged
= 0, *next
, *tail
, i
, nr
= 0, alloc
= 0;
5313 struct commit_todo_item commit_todo
;
5314 struct todo_item
*items
= NULL
;
5316 init_commit_todo_item(&commit_todo
);
5318 * The hashmap maps onelines to the respective todo list index.
5320 * If any items need to be rearranged, the next[i] value will indicate
5321 * which item was moved directly after the i'th.
5323 * In that case, last[i] will indicate the index of the latest item to
5324 * be moved to appear after the i'th.
5326 hashmap_init(&subject2item
, subject2item_cmp
, NULL
, todo_list
->nr
);
5327 ALLOC_ARRAY(next
, todo_list
->nr
);
5328 ALLOC_ARRAY(tail
, todo_list
->nr
);
5329 ALLOC_ARRAY(subjects
, todo_list
->nr
);
5330 for (i
= 0; i
< todo_list
->nr
; i
++) {
5331 struct strbuf buf
= STRBUF_INIT
;
5332 struct todo_item
*item
= todo_list
->items
+ i
;
5333 const char *commit_buffer
, *subject
, *p
;
5336 struct subject2item_entry
*entry
;
5338 next
[i
] = tail
[i
] = -1;
5339 if (!item
->commit
|| item
->command
== TODO_DROP
) {
5344 if (is_fixup(item
->command
)) {
5345 clear_commit_todo_item(&commit_todo
);
5346 return error(_("the script was already rearranged."));
5349 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
5351 parse_commit(item
->commit
);
5352 commit_buffer
= logmsg_reencode(item
->commit
, NULL
, "UTF-8");
5353 find_commit_subject(commit_buffer
, &subject
);
5354 format_subject(&buf
, subject
, " ");
5355 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
5356 unuse_commit_buffer(item
->commit
, commit_buffer
);
5357 if ((skip_prefix(subject
, "fixup! ", &p
) ||
5358 skip_prefix(subject
, "squash! ", &p
))) {
5359 struct commit
*commit2
;
5364 if (!skip_prefix(p
, "fixup! ", &p
) &&
5365 !skip_prefix(p
, "squash! ", &p
))
5369 entry
= hashmap_get_entry_from_hash(&subject2item
,
5371 struct subject2item_entry
,
5374 /* found by title */
5376 else if (!strchr(p
, ' ') &&
5378 lookup_commit_reference_by_name(p
)) &&
5379 *commit_todo_item_at(&commit_todo
, commit2
))
5380 /* found by commit name */
5381 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
5384 /* copy can be a prefix of the commit subject */
5385 for (i2
= 0; i2
< i
; i2
++)
5387 starts_with(subjects
[i2
], p
))
5395 todo_list
->items
[i
].command
=
5396 starts_with(subject
, "fixup!") ?
5397 TODO_FIXUP
: TODO_SQUASH
;
5402 next
[i
] = next
[tail
[i2
]];
5406 } else if (!hashmap_get_from_hash(&subject2item
,
5407 strhash(subject
), subject
)) {
5408 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
5410 hashmap_entry_init(&entry
->entry
,
5411 strhash(entry
->subject
));
5412 hashmap_put(&subject2item
, &entry
->entry
);
5417 for (i
= 0; i
< todo_list
->nr
; i
++) {
5418 enum todo_command command
= todo_list
->items
[i
].command
;
5422 * Initially, all commands are 'pick's. If it is a
5423 * fixup or a squash now, we have rearranged it.
5425 if (is_fixup(command
))
5429 ALLOC_GROW(items
, nr
+ 1, alloc
);
5430 items
[nr
++] = todo_list
->items
[cur
];
5435 FREE_AND_NULL(todo_list
->items
);
5436 todo_list
->items
= items
;
5438 todo_list
->alloc
= alloc
;
5443 for (i
= 0; i
< todo_list
->nr
; i
++)
5446 hashmap_free_entries(&subject2item
, struct subject2item_entry
, entry
);
5448 clear_commit_todo_item(&commit_todo
);
5453 int sequencer_determine_whence(struct repository
*r
, enum commit_whence
*whence
)
5455 if (refs_ref_exists(get_main_ref_store(r
), "CHERRY_PICK_HEAD")) {
5456 struct object_id cherry_pick_head
, rebase_head
;
5458 if (file_exists(git_path_seq_dir()))
5459 *whence
= FROM_CHERRY_PICK_MULTI
;
5460 if (file_exists(rebase_path()) &&
5461 !get_oid("REBASE_HEAD", &rebase_head
) &&
5462 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head
) &&
5463 oideq(&rebase_head
, &cherry_pick_head
))
5464 *whence
= FROM_REBASE_PICK
;
5466 *whence
= FROM_CHERRY_PICK_SINGLE
;