9 #include "run-command.h"
12 #include "cache-tree.h"
16 #include "merge-recursive.h"
18 #include "argv-array.h"
22 #include "wt-status.h"
24 #include "notes-utils.h"
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
29 const char sign_off_header
[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
32 GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
34 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
35 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
36 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
37 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
39 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
41 * The file containing rebase commands, comments, and empty lines.
42 * This file is created by "git rebase -i" then edited by the user. As
43 * the lines are processed, they are removed from the front of this
44 * file and written to the tail of 'done'.
46 static GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
48 * The rebase command lines that have already been processed. A line
49 * is moved here when it is first handled, before any associated user
52 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
54 * The file to keep track of how many commands were already processed (e.g.
57 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum");
59 * The file to keep track of how many commands are to be processed in total
60 * (e.g. for the prompt).
62 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end");
64 * The commit message that is planned to be used for any changes that
65 * need to be committed following a user interaction.
67 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
69 * The file into which is accumulated the suggested commit message for
70 * squash/fixup commands. When the first of a series of squash/fixups
71 * is seen, the file is created and the commit message from the
72 * previous commit and from the first squash/fixup commit are written
73 * to it. The commit message for each subsequent squash/fixup commit
74 * is appended to the file as it is processed.
76 * The first line of the file is of the form
77 * # This is a combination of $count commits.
78 * where $count is the number of commits whose messages have been
79 * written to the file so far (including the initial "pick" commit).
80 * Each time that a commit message is processed, this line is read and
81 * updated. It is deleted just before the combined commit is made.
83 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
85 * If the current series of squash/fixups has not yet included a squash
86 * command, then this file exists and holds the commit message of the
87 * original "pick" commit. (If the series ends without a "squash"
88 * command, then this can be used as the commit message of the combined
89 * commit without opening the editor.)
91 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
93 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
94 * GIT_AUTHOR_DATE that will be used for the commit that is currently
97 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
99 * When an "edit" rebase command is being processed, the SHA1 of the
100 * commit to be edited is recorded in this file. When "git rebase
101 * --continue" is executed, if there are any staged changes then they
102 * will be amended to the HEAD commit, but only provided the HEAD
103 * commit is still the commit to be edited. When any other rebase
104 * command is processed, this file is deleted.
106 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
108 * When we stop at a given patch via the "edit" command, this file contains
109 * the abbreviated commit name of the corresponding patch.
111 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
113 * For the post-rewrite hook, we make a list of rewritten commits and
114 * their new sha1s. The rewritten-pending list keeps the sha1s of
115 * commits that have been processed, but not committed yet,
116 * e.g. because they are waiting for a 'squash' command.
118 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
119 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
120 "rebase-merge/rewritten-pending")
122 * The following files are written by git-rebase just after parsing the
123 * command-line (and are only consumed, not modified, by the sequencer).
125 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
126 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
127 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
128 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
129 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
130 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
131 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
132 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
133 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
135 static inline int is_rebase_i(const struct replay_opts
*opts
)
137 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
140 static const char *get_dir(const struct replay_opts
*opts
)
142 if (is_rebase_i(opts
))
143 return rebase_path();
144 return git_path_seq_dir();
147 static const char *get_todo_path(const struct replay_opts
*opts
)
149 if (is_rebase_i(opts
))
150 return rebase_path_todo();
151 return git_path_todo_file();
155 * Returns 0 for non-conforming footer
156 * Returns 1 for conforming footer
157 * Returns 2 when sob exists within conforming footer
158 * Returns 3 when sob exists within conforming footer as last entry
160 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
163 struct trailer_info info
;
165 int found_sob
= 0, found_sob_last
= 0;
167 trailer_info_get(&info
, sb
->buf
);
169 if (info
.trailer_start
== info
.trailer_end
)
172 for (i
= 0; i
< info
.trailer_nr
; i
++)
173 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
175 if (i
== info
.trailer_nr
- 1)
179 trailer_info_release(&info
);
188 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
190 static struct strbuf buf
= STRBUF_INIT
;
194 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
198 int sequencer_remove_state(struct replay_opts
*opts
)
200 struct strbuf dir
= STRBUF_INIT
;
203 free(opts
->gpg_sign
);
204 free(opts
->strategy
);
205 for (i
= 0; i
< opts
->xopts_nr
; i
++)
206 free(opts
->xopts
[i
]);
209 strbuf_addstr(&dir
, get_dir(opts
));
210 remove_dir_recursively(&dir
, 0);
211 strbuf_release(&dir
);
216 static const char *action_name(const struct replay_opts
*opts
)
218 switch (opts
->action
) {
222 return N_("cherry-pick");
223 case REPLAY_INTERACTIVE_REBASE
:
224 return N_("rebase -i");
226 die(_("Unknown action: %d"), opts
->action
);
229 struct commit_message
{
236 static const char *short_commit_name(struct commit
*commit
)
238 return find_unique_abbrev(commit
->object
.oid
.hash
, DEFAULT_ABBREV
);
241 static int get_message(struct commit
*commit
, struct commit_message
*out
)
243 const char *abbrev
, *subject
;
246 out
->message
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
247 abbrev
= short_commit_name(commit
);
249 subject_len
= find_commit_subject(out
->message
, &subject
);
251 out
->subject
= xmemdupz(subject
, subject_len
);
252 out
->label
= xstrfmt("%s... %s", abbrev
, out
->subject
);
253 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
258 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
260 free(msg
->parent_label
);
263 unuse_commit_buffer(commit
, msg
->message
);
266 static void print_advice(int show_hint
, struct replay_opts
*opts
)
268 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
271 fprintf(stderr
, "%s\n", msg
);
273 * A conflict has occurred but the porcelain
274 * (typically rebase --interactive) wants to take care
275 * of the commit itself so remove CHERRY_PICK_HEAD
277 unlink(git_path_cherry_pick_head());
283 advise(_("after resolving the conflicts, mark the corrected paths\n"
284 "with 'git add <paths>' or 'git rm <paths>'"));
286 advise(_("after resolving the conflicts, mark the corrected paths\n"
287 "with 'git add <paths>' or 'git rm <paths>'\n"
288 "and commit the result with 'git commit'"));
292 static int write_message(const void *buf
, size_t len
, const char *filename
,
295 static struct lock_file msg_file
;
297 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
299 return error_errno(_("could not lock '%s'"), filename
);
300 if (write_in_full(msg_fd
, buf
, len
) < 0) {
301 rollback_lock_file(&msg_file
);
302 return error_errno(_("could not write to '%s'"), filename
);
304 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
305 rollback_lock_file(&msg_file
);
306 return error_errno(_("could not write eol to '%s'"), filename
);
308 if (commit_lock_file(&msg_file
) < 0) {
309 rollback_lock_file(&msg_file
);
310 return error(_("failed to finalize '%s'."), filename
);
317 * Reads a file that was presumably written by a shell script, i.e. with an
318 * end-of-line marker that needs to be stripped.
320 * Note that only the last end-of-line marker is stripped, consistent with the
321 * behavior of "$(cat path)" in a shell script.
323 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
325 static int read_oneliner(struct strbuf
*buf
,
326 const char *path
, int skip_if_empty
)
328 int orig_len
= buf
->len
;
330 if (!file_exists(path
))
333 if (strbuf_read_file(buf
, path
, 0) < 0) {
334 warning_errno(_("could not read '%s'"), path
);
338 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
339 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
341 buf
->buf
[buf
->len
] = '\0';
344 if (skip_if_empty
&& buf
->len
== orig_len
)
350 static struct tree
*empty_tree(void)
352 return lookup_tree(&empty_tree_oid
);
355 static int error_dirty_index(struct replay_opts
*opts
)
357 if (read_cache_unmerged())
358 return error_resolve_conflict(_(action_name(opts
)));
360 error(_("your local changes would be overwritten by %s."),
361 _(action_name(opts
)));
363 if (advice_commit_before_merge
)
364 advise(_("commit your changes or stash them to proceed."));
368 static void update_abort_safety_file(void)
370 struct object_id head
;
372 /* Do nothing on a single-pick */
373 if (!file_exists(git_path_seq_dir()))
376 if (!get_oid("HEAD", &head
))
377 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
379 write_file(git_path_abort_safety_file(), "%s", "");
382 static int fast_forward_to(const struct object_id
*to
, const struct object_id
*from
,
383 int unborn
, struct replay_opts
*opts
)
385 struct ref_transaction
*transaction
;
386 struct strbuf sb
= STRBUF_INIT
;
387 struct strbuf err
= STRBUF_INIT
;
390 if (checkout_fast_forward(from
, to
, 1))
391 return -1; /* the callee should have complained already */
393 strbuf_addf(&sb
, _("%s: fast-forward"), _(action_name(opts
)));
395 transaction
= ref_transaction_begin(&err
);
397 ref_transaction_update(transaction
, "HEAD",
398 to
, unborn
? &null_oid
: from
,
400 ref_transaction_commit(transaction
, &err
)) {
401 ref_transaction_free(transaction
);
402 error("%s", err
.buf
);
404 strbuf_release(&err
);
409 strbuf_release(&err
);
410 ref_transaction_free(transaction
);
411 update_abort_safety_file();
415 void append_conflicts_hint(struct strbuf
*msgbuf
)
419 strbuf_addch(msgbuf
, '\n');
420 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
421 for (i
= 0; i
< active_nr
;) {
422 const struct cache_entry
*ce
= active_cache
[i
++];
424 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
425 while (i
< active_nr
&& !strcmp(ce
->name
,
426 active_cache
[i
]->name
))
432 static int do_recursive_merge(struct commit
*base
, struct commit
*next
,
433 const char *base_label
, const char *next_label
,
434 struct object_id
*head
, struct strbuf
*msgbuf
,
435 struct replay_opts
*opts
)
437 struct merge_options o
;
438 struct tree
*result
, *next_tree
, *base_tree
, *head_tree
;
441 static struct lock_file index_lock
;
443 hold_locked_index(&index_lock
, LOCK_DIE_ON_ERROR
);
447 init_merge_options(&o
);
448 o
.ancestor
= base
? base_label
: "(empty tree)";
450 o
.branch2
= next
? next_label
: "(empty tree)";
451 if (is_rebase_i(opts
))
454 head_tree
= parse_tree_indirect(head
);
455 next_tree
= next
? next
->tree
: empty_tree();
456 base_tree
= base
? base
->tree
: empty_tree();
458 for (xopt
= opts
->xopts
; xopt
!= opts
->xopts
+ opts
->xopts_nr
; xopt
++)
459 parse_merge_opt(&o
, *xopt
);
461 clean
= merge_trees(&o
,
463 next_tree
, base_tree
, &result
);
464 if (is_rebase_i(opts
) && clean
<= 0)
465 fputs(o
.obuf
.buf
, stdout
);
466 strbuf_release(&o
.obuf
);
470 if (active_cache_changed
&&
471 write_locked_index(&the_index
, &index_lock
, COMMIT_LOCK
))
473 * TRANSLATORS: %s will be "revert", "cherry-pick" or
476 return error(_("%s: Unable to write new index file"),
477 _(action_name(opts
)));
478 rollback_lock_file(&index_lock
);
481 append_signoff(msgbuf
, 0, 0);
484 append_conflicts_hint(msgbuf
);
489 static int is_index_unchanged(void)
491 struct object_id head_oid
;
492 struct commit
*head_commit
;
494 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
495 return error(_("could not resolve HEAD commit\n"));
497 head_commit
= lookup_commit(&head_oid
);
500 * If head_commit is NULL, check_commit, called from
501 * lookup_commit, would have indicated that head_commit is not
502 * a commit object already. parse_commit() will return failure
503 * without further complaints in such a case. Otherwise, if
504 * the commit is invalid, parse_commit() will complain. So
505 * there is nothing for us to say here. Just return failure.
507 if (parse_commit(head_commit
))
510 if (!active_cache_tree
)
511 active_cache_tree
= cache_tree();
513 if (!cache_tree_fully_valid(active_cache_tree
))
514 if (cache_tree_update(&the_index
, 0))
515 return error(_("unable to update cache tree\n"));
517 return !oidcmp(&active_cache_tree
->oid
,
518 &head_commit
->tree
->object
.oid
);
521 static int write_author_script(const char *message
)
523 struct strbuf buf
= STRBUF_INIT
;
528 if (!*message
|| starts_with(message
, "\n")) {
530 /* Missing 'author' line? */
531 unlink(rebase_path_author_script());
533 } else if (skip_prefix(message
, "author ", &message
))
535 else if ((eol
= strchr(message
, '\n')))
540 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
541 while (*message
&& *message
!= '\n' && *message
!= '\r')
542 if (skip_prefix(message
, " <", &message
))
544 else if (*message
!= '\'')
545 strbuf_addch(&buf
, *(message
++));
547 strbuf_addf(&buf
, "'\\\\%c'", *(message
++));
548 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
549 while (*message
&& *message
!= '\n' && *message
!= '\r')
550 if (skip_prefix(message
, "> ", &message
))
552 else if (*message
!= '\'')
553 strbuf_addch(&buf
, *(message
++));
555 strbuf_addf(&buf
, "'\\\\%c'", *(message
++));
556 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
557 while (*message
&& *message
!= '\n' && *message
!= '\r')
558 if (*message
!= '\'')
559 strbuf_addch(&buf
, *(message
++));
561 strbuf_addf(&buf
, "'\\\\%c'", *(message
++));
562 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
563 strbuf_release(&buf
);
568 * Read a list of environment variable assignments (such as the author-script
569 * file) into an environment block. Returns -1 on error, 0 otherwise.
571 static int read_env_script(struct argv_array
*env
)
573 struct strbuf script
= STRBUF_INIT
;
577 if (strbuf_read_file(&script
, rebase_path_author_script(), 256) <= 0)
580 for (p
= script
.buf
; *p
; p
++)
581 if (skip_prefix(p
, "'\\\\''", (const char **)&p2
))
582 strbuf_splice(&script
, p
- script
.buf
, p2
- p
, "'", 1);
584 strbuf_splice(&script
, p
-- - script
.buf
, 1, "", 0);
585 else if (*p
== '\n') {
590 for (i
= 0, p
= script
.buf
; i
< count
; i
++) {
591 argv_array_push(env
, p
);
598 static const char staged_changes_advice
[] =
599 N_("you have staged changes in your working tree\n"
600 "If these changes are meant to be squashed into the previous commit, run:\n"
602 " git commit --amend %s\n"
604 "If they are meant to go into a new commit, run:\n"
608 "In both cases, once you're done, continue with:\n"
610 " git rebase --continue\n");
612 #define ALLOW_EMPTY (1<<0)
613 #define EDIT_MSG (1<<1)
614 #define AMEND_MSG (1<<2)
615 #define CLEANUP_MSG (1<<3)
616 #define VERIFY_MSG (1<<4)
619 * If we are cherry-pick, and if the merge did not result in
620 * hand-editing, we will hit this commit and inherit the original
621 * author date and name.
623 * If we are revert, or if our cherry-pick results in a hand merge,
624 * we had better say that the current user is responsible for that.
626 * An exception is when run_git_commit() is called during an
627 * interactive rebase: in that case, we will want to retain the
630 static int run_git_commit(const char *defmsg
, struct replay_opts
*opts
,
633 struct child_process cmd
= CHILD_PROCESS_INIT
;
638 if (is_rebase_i(opts
)) {
639 if (!(flags
& EDIT_MSG
)) {
640 cmd
.stdout_to_stderr
= 1;
644 if (read_env_script(&cmd
.env_array
)) {
645 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
647 return error(_(staged_changes_advice
),
652 argv_array_push(&cmd
.args
, "commit");
654 if (!(flags
& VERIFY_MSG
))
655 argv_array_push(&cmd
.args
, "-n");
656 if ((flags
& AMEND_MSG
))
657 argv_array_push(&cmd
.args
, "--amend");
659 argv_array_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
661 argv_array_push(&cmd
.args
, "-s");
663 argv_array_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
664 if ((flags
& CLEANUP_MSG
))
665 argv_array_push(&cmd
.args
, "--cleanup=strip");
666 if ((flags
& EDIT_MSG
))
667 argv_array_push(&cmd
.args
, "-e");
668 else if (!(flags
& CLEANUP_MSG
) &&
669 !opts
->signoff
&& !opts
->record_origin
&&
670 git_config_get_value("commit.cleanup", &value
))
671 argv_array_push(&cmd
.args
, "--cleanup=verbatim");
673 if ((flags
& ALLOW_EMPTY
))
674 argv_array_push(&cmd
.args
, "--allow-empty");
676 if (opts
->allow_empty_message
)
677 argv_array_push(&cmd
.args
, "--allow-empty-message");
680 /* hide stderr on success */
681 struct strbuf buf
= STRBUF_INIT
;
682 int rc
= pipe_command(&cmd
,
684 /* stdout is already redirected */
688 fputs(buf
.buf
, stderr
);
689 strbuf_release(&buf
);
693 return run_command(&cmd
);
696 static int rest_is_empty(const struct strbuf
*sb
, int start
)
701 /* Check if the rest is just whitespace and Signed-off-by's. */
702 for (i
= start
; i
< sb
->len
; i
++) {
703 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
709 if (strlen(sign_off_header
) <= eol
- i
&&
710 starts_with(sb
->buf
+ i
, sign_off_header
)) {
715 if (!isspace(sb
->buf
[i
++]))
723 * Find out if the message in the strbuf contains only whitespace and
724 * Signed-off-by lines.
726 int message_is_empty(const struct strbuf
*sb
,
727 enum commit_msg_cleanup_mode cleanup_mode
)
729 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
731 return rest_is_empty(sb
, 0);
735 * See if the user edited the message in the editor or left what
736 * was in the template intact
738 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
739 enum commit_msg_cleanup_mode cleanup_mode
)
741 struct strbuf tmpl
= STRBUF_INIT
;
744 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
747 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
750 strbuf_stripspace(&tmpl
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
751 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
753 strbuf_release(&tmpl
);
754 return rest_is_empty(sb
, start
- sb
->buf
);
757 int update_head_with_reflog(const struct commit
*old_head
,
758 const struct object_id
*new_head
,
759 const char *action
, const struct strbuf
*msg
,
762 struct ref_transaction
*transaction
;
763 struct strbuf sb
= STRBUF_INIT
;
768 strbuf_addstr(&sb
, action
);
769 strbuf_addstr(&sb
, ": ");
772 nl
= strchr(msg
->buf
, '\n');
774 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
776 strbuf_addbuf(&sb
, msg
);
777 strbuf_addch(&sb
, '\n');
780 transaction
= ref_transaction_begin(err
);
782 ref_transaction_update(transaction
, "HEAD", new_head
,
783 old_head
? &old_head
->object
.oid
: &null_oid
,
785 ref_transaction_commit(transaction
, err
)) {
788 ref_transaction_free(transaction
);
794 static int run_rewrite_hook(const struct object_id
*oldoid
,
795 const struct object_id
*newoid
)
797 struct child_process proc
= CHILD_PROCESS_INIT
;
800 struct strbuf sb
= STRBUF_INIT
;
802 argv
[0] = find_hook("post-rewrite");
811 proc
.stdout_to_stderr
= 1;
813 code
= start_command(&proc
);
816 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
817 sigchain_push(SIGPIPE
, SIG_IGN
);
818 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
821 sigchain_pop(SIGPIPE
);
822 return finish_command(&proc
);
825 void commit_post_rewrite(const struct commit
*old_head
,
826 const struct object_id
*new_head
)
828 struct notes_rewrite_cfg
*cfg
;
830 cfg
= init_copy_notes_for_rewrite("amend");
832 /* we are amending, so old_head is not NULL */
833 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
834 finish_copy_notes_for_rewrite(cfg
, "Notes added by 'git commit --amend'");
836 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
839 static const char implicit_ident_advice_noconfig
[] =
840 N_("Your name and email address were configured automatically based\n"
841 "on your username and hostname. Please check that they are accurate.\n"
842 "You can suppress this message by setting them explicitly. Run the\n"
843 "following command and follow the instructions in your editor to edit\n"
844 "your configuration file:\n"
846 " git config --global --edit\n"
848 "After doing this, you may fix the identity used for this commit with:\n"
850 " git commit --amend --reset-author\n");
852 static const char implicit_ident_advice_config
[] =
853 N_("Your name and email address were configured automatically based\n"
854 "on your username and hostname. Please check that they are accurate.\n"
855 "You can suppress this message by setting them explicitly:\n"
857 " git config --global user.name \"Your Name\"\n"
858 " git config --global user.email you@example.com\n"
860 "After doing this, you may fix the identity used for this commit with:\n"
862 " git commit --amend --reset-author\n");
864 static const char *implicit_ident_advice(void)
866 char *user_config
= expand_user_path("~/.gitconfig", 0);
867 char *xdg_config
= xdg_config_home("config");
868 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
874 return _(implicit_ident_advice_config
);
876 return _(implicit_ident_advice_noconfig
);
880 void print_commit_summary(const char *prefix
, const struct object_id
*oid
,
884 struct commit
*commit
;
885 struct strbuf format
= STRBUF_INIT
;
887 struct pretty_print_context pctx
= {0};
888 struct strbuf author_ident
= STRBUF_INIT
;
889 struct strbuf committer_ident
= STRBUF_INIT
;
891 commit
= lookup_commit(oid
);
893 die(_("couldn't look up newly created commit"));
894 if (parse_commit(commit
))
895 die(_("could not parse newly created commit"));
897 strbuf_addstr(&format
, "format:%h] %s");
899 format_commit_message(commit
, "%an <%ae>", &author_ident
, &pctx
);
900 format_commit_message(commit
, "%cn <%ce>", &committer_ident
, &pctx
);
901 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
902 strbuf_addstr(&format
, "\n Author: ");
903 strbuf_addbuf_percentquote(&format
, &author_ident
);
905 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
906 struct strbuf date
= STRBUF_INIT
;
908 format_commit_message(commit
, "%ad", &date
, &pctx
);
909 strbuf_addstr(&format
, "\n Date: ");
910 strbuf_addbuf_percentquote(&format
, &date
);
911 strbuf_release(&date
);
913 if (!committer_ident_sufficiently_given()) {
914 strbuf_addstr(&format
, "\n Committer: ");
915 strbuf_addbuf_percentquote(&format
, &committer_ident
);
916 if (advice_implicit_identity
) {
917 strbuf_addch(&format
, '\n');
918 strbuf_addstr(&format
, implicit_ident_advice());
921 strbuf_release(&author_ident
);
922 strbuf_release(&committer_ident
);
924 init_revisions(&rev
, prefix
);
925 setup_revisions(0, NULL
, &rev
, NULL
);
928 rev
.diffopt
.output_format
=
929 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
931 rev
.verbose_header
= 1;
932 rev
.show_root_diff
= 1;
933 get_commit_format(format
.buf
, &rev
);
934 rev
.always_show_header
= 0;
935 rev
.diffopt
.detect_rename
= 1;
936 rev
.diffopt
.break_opt
= 0;
937 diff_setup_done(&rev
.diffopt
);
939 head
= resolve_ref_unsafe("HEAD", 0, NULL
, NULL
);
941 die_errno(_("unable to resolve HEAD after creating commit"));
942 if (!strcmp(head
, "HEAD"))
943 head
= _("detached HEAD");
945 skip_prefix(head
, "refs/heads/", &head
);
946 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
947 _(" (root-commit)") : "");
949 if (!log_tree_commit(&rev
, commit
)) {
950 rev
.always_show_header
= 1;
951 rev
.use_terminator
= 1;
952 log_tree_commit(&rev
, commit
);
955 strbuf_release(&format
);
958 static int is_original_commit_empty(struct commit
*commit
)
960 const struct object_id
*ptree_oid
;
962 if (parse_commit(commit
))
963 return error(_("could not parse commit %s\n"),
964 oid_to_hex(&commit
->object
.oid
));
965 if (commit
->parents
) {
966 struct commit
*parent
= commit
->parents
->item
;
967 if (parse_commit(parent
))
968 return error(_("could not parse parent commit %s\n"),
969 oid_to_hex(&parent
->object
.oid
));
970 ptree_oid
= &parent
->tree
->object
.oid
;
972 ptree_oid
= &empty_tree_oid
; /* commit is root */
975 return !oidcmp(ptree_oid
, &commit
->tree
->object
.oid
);
979 * Do we run "git commit" with "--allow-empty"?
981 static int allow_empty(struct replay_opts
*opts
, struct commit
*commit
)
983 int index_unchanged
, empty_commit
;
988 * (1) we do not allow empty at all and error out.
990 * (2) we allow ones that were initially empty, but
991 * forbid the ones that become empty;
995 if (!opts
->allow_empty
)
996 return 0; /* let "git commit" barf as necessary */
998 index_unchanged
= is_index_unchanged();
999 if (index_unchanged
< 0)
1000 return index_unchanged
;
1001 if (!index_unchanged
)
1002 return 0; /* we do not have to say --allow-empty */
1004 if (opts
->keep_redundant_commits
)
1007 empty_commit
= is_original_commit_empty(commit
);
1008 if (empty_commit
< 0)
1009 return empty_commit
;
1017 * Note that ordering matters in this enum. Not only must it match the mapping
1018 * below, it is also divided into several sections that matter. When adding
1019 * new commands, make sure you add it in the right section.
1022 /* commands that handle commits */
1029 /* commands that do something else than handling a single commit */
1031 /* commands that do nothing but are counted for reporting progress */
1034 /* comments (not counted for reporting progress) */
1041 } todo_command_info
[] = {
1054 static const char *command_to_string(const enum todo_command command
)
1056 if (command
< TODO_COMMENT
)
1057 return todo_command_info
[command
].str
;
1058 die("Unknown command: %d", command
);
1061 static int is_noop(const enum todo_command command
)
1063 return TODO_NOOP
<= command
;
1066 static int is_fixup(enum todo_command command
)
1068 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1071 static int update_squash_messages(enum todo_command command
,
1072 struct commit
*commit
, struct replay_opts
*opts
)
1074 struct strbuf buf
= STRBUF_INIT
;
1076 const char *message
, *body
;
1078 if (file_exists(rebase_path_squash_msg())) {
1079 struct strbuf header
= STRBUF_INIT
;
1082 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 2048) <= 0)
1083 return error(_("could not read '%s'"),
1084 rebase_path_squash_msg());
1087 eol
= strchrnul(buf
.buf
, '\n');
1088 if (buf
.buf
[0] != comment_line_char
||
1089 (p
+= strcspn(p
, "0123456789\n")) == eol
)
1090 return error(_("unexpected 1st line of squash message:"
1092 (int)(eol
- buf
.buf
), buf
.buf
);
1093 count
= strtol(p
, NULL
, 10);
1096 return error(_("invalid 1st line of squash message:\n"
1098 (int)(eol
- buf
.buf
), buf
.buf
);
1100 strbuf_addf(&header
, "%c ", comment_line_char
);
1101 strbuf_addf(&header
,
1102 _("This is a combination of %d commits."), ++count
);
1103 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
1104 strbuf_release(&header
);
1106 struct object_id head
;
1107 struct commit
*head_commit
;
1108 const char *head_message
, *body
;
1110 if (get_oid("HEAD", &head
))
1111 return error(_("need a HEAD to fixup"));
1112 if (!(head_commit
= lookup_commit_reference(&head
)))
1113 return error(_("could not read HEAD"));
1114 if (!(head_message
= get_commit_buffer(head_commit
, NULL
)))
1115 return error(_("could not read HEAD's commit message"));
1117 find_commit_subject(head_message
, &body
);
1118 if (write_message(body
, strlen(body
),
1119 rebase_path_fixup_msg(), 0)) {
1120 unuse_commit_buffer(head_commit
, head_message
);
1121 return error(_("cannot write '%s'"),
1122 rebase_path_fixup_msg());
1126 strbuf_addf(&buf
, "%c ", comment_line_char
);
1127 strbuf_addf(&buf
, _("This is a combination of %d commits."),
1129 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1130 strbuf_addstr(&buf
, _("This is the 1st commit message:"));
1131 strbuf_addstr(&buf
, "\n\n");
1132 strbuf_addstr(&buf
, body
);
1134 unuse_commit_buffer(head_commit
, head_message
);
1137 if (!(message
= get_commit_buffer(commit
, NULL
)))
1138 return error(_("could not read commit message of %s"),
1139 oid_to_hex(&commit
->object
.oid
));
1140 find_commit_subject(message
, &body
);
1142 if (command
== TODO_SQUASH
) {
1143 unlink(rebase_path_fixup_msg());
1144 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1145 strbuf_addf(&buf
, _("This is the commit message #%d:"), count
);
1146 strbuf_addstr(&buf
, "\n\n");
1147 strbuf_addstr(&buf
, body
);
1148 } else if (command
== TODO_FIXUP
) {
1149 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1150 strbuf_addf(&buf
, _("The commit message #%d will be skipped:"),
1152 strbuf_addstr(&buf
, "\n\n");
1153 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
1155 return error(_("unknown command: %d"), command
);
1156 unuse_commit_buffer(commit
, message
);
1158 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(), 0);
1159 strbuf_release(&buf
);
1163 static void flush_rewritten_pending(void) {
1164 struct strbuf buf
= STRBUF_INIT
;
1165 struct object_id newoid
;
1168 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
1169 !get_oid("HEAD", &newoid
) &&
1170 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1171 char *bol
= buf
.buf
, *eol
;
1174 eol
= strchrnul(bol
, '\n');
1175 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
1176 bol
, oid_to_hex(&newoid
));
1182 unlink(rebase_path_rewritten_pending());
1184 strbuf_release(&buf
);
1187 static void record_in_rewritten(struct object_id
*oid
,
1188 enum todo_command next_command
) {
1189 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
1194 fprintf(out
, "%s\n", oid_to_hex(oid
));
1197 if (!is_fixup(next_command
))
1198 flush_rewritten_pending();
1201 static int do_pick_commit(enum todo_command command
, struct commit
*commit
,
1202 struct replay_opts
*opts
, int final_fixup
)
1204 unsigned int flags
= opts
->edit
? EDIT_MSG
: 0;
1205 const char *msg_file
= opts
->edit
? NULL
: git_path_merge_msg();
1206 struct object_id head
;
1207 struct commit
*base
, *next
, *parent
;
1208 const char *base_label
, *next_label
;
1209 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
1210 struct strbuf msgbuf
= STRBUF_INIT
;
1211 int res
, unborn
= 0, allow
;
1213 if (opts
->no_commit
) {
1215 * We do not intend to commit immediately. We just want to
1216 * merge the differences in, so let's compute the tree
1217 * that represents the "current" state for merge-recursive
1220 if (write_cache_as_tree(head
.hash
, 0, NULL
))
1221 return error(_("your index file is unmerged."));
1223 unborn
= get_oid("HEAD", &head
);
1225 oidcpy(&head
, &empty_tree_oid
);
1226 if (index_differs_from(unborn
? EMPTY_TREE_SHA1_HEX
: "HEAD",
1228 return error_dirty_index(opts
);
1232 if (!commit
->parents
)
1234 else if (commit
->parents
->next
) {
1235 /* Reverting or cherry-picking a merge commit */
1237 struct commit_list
*p
;
1239 if (!opts
->mainline
)
1240 return error(_("commit %s is a merge but no -m option was given."),
1241 oid_to_hex(&commit
->object
.oid
));
1243 for (cnt
= 1, p
= commit
->parents
;
1244 cnt
!= opts
->mainline
&& p
;
1247 if (cnt
!= opts
->mainline
|| !p
)
1248 return error(_("commit %s does not have parent %d"),
1249 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
1251 } else if (0 < opts
->mainline
)
1252 return error(_("mainline was specified but commit %s is not a merge."),
1253 oid_to_hex(&commit
->object
.oid
));
1255 parent
= commit
->parents
->item
;
1257 if (get_message(commit
, &msg
) != 0)
1258 return error(_("cannot get commit message for %s"),
1259 oid_to_hex(&commit
->object
.oid
));
1261 if (opts
->allow_ff
&& !is_fixup(command
) &&
1262 ((parent
&& !oidcmp(&parent
->object
.oid
, &head
)) ||
1263 (!parent
&& unborn
))) {
1264 if (is_rebase_i(opts
))
1265 write_author_script(msg
.message
);
1266 res
= fast_forward_to(&commit
->object
.oid
, &head
, unborn
,
1268 if (res
|| command
!= TODO_REWORD
)
1270 flags
|= EDIT_MSG
| AMEND_MSG
;
1271 if (command
== TODO_REWORD
)
1272 flags
|= VERIFY_MSG
;
1274 goto fast_forward_edit
;
1276 if (parent
&& parse_commit(parent
) < 0)
1277 /* TRANSLATORS: The first %s will be a "todo" command like
1278 "revert" or "pick", the second %s a SHA1. */
1279 return error(_("%s: cannot parse parent commit %s"),
1280 command_to_string(command
),
1281 oid_to_hex(&parent
->object
.oid
));
1284 * "commit" is an existing commit. We would want to apply
1285 * the difference it introduces since its first parent "prev"
1286 * on top of the current HEAD if we are cherry-pick. Or the
1287 * reverse of it if we are revert.
1290 if (command
== TODO_REVERT
) {
1292 base_label
= msg
.label
;
1294 next_label
= msg
.parent_label
;
1295 strbuf_addstr(&msgbuf
, "Revert \"");
1296 strbuf_addstr(&msgbuf
, msg
.subject
);
1297 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
1298 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
1300 if (commit
->parents
&& commit
->parents
->next
) {
1301 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
1302 strbuf_addstr(&msgbuf
, oid_to_hex(&parent
->object
.oid
));
1304 strbuf_addstr(&msgbuf
, ".\n");
1309 base_label
= msg
.parent_label
;
1311 next_label
= msg
.label
;
1313 /* Append the commit log message to msgbuf. */
1314 if (find_commit_subject(msg
.message
, &p
))
1315 strbuf_addstr(&msgbuf
, p
);
1317 if (opts
->record_origin
) {
1318 strbuf_complete_line(&msgbuf
);
1319 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
1320 strbuf_addch(&msgbuf
, '\n');
1321 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
1322 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
1323 strbuf_addstr(&msgbuf
, ")\n");
1327 if (command
== TODO_REWORD
)
1328 flags
|= EDIT_MSG
| VERIFY_MSG
;
1329 else if (is_fixup(command
)) {
1330 if (update_squash_messages(command
, commit
, opts
))
1334 msg_file
= rebase_path_squash_msg();
1335 else if (file_exists(rebase_path_fixup_msg())) {
1336 flags
|= CLEANUP_MSG
;
1337 msg_file
= rebase_path_fixup_msg();
1339 const char *dest
= git_path_squash_msg();
1341 if (copy_file(dest
, rebase_path_squash_msg(), 0666))
1342 return error(_("could not rename '%s' to '%s'"),
1343 rebase_path_squash_msg(), dest
);
1344 unlink(git_path_merge_msg());
1350 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
1352 else if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || command
== TODO_REVERT
) {
1353 res
= do_recursive_merge(base
, next
, base_label
, next_label
,
1354 &head
, &msgbuf
, opts
);
1357 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
1358 git_path_merge_msg(), 0);
1360 struct commit_list
*common
= NULL
;
1361 struct commit_list
*remotes
= NULL
;
1363 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
1364 git_path_merge_msg(), 0);
1366 commit_list_insert(base
, &common
);
1367 commit_list_insert(next
, &remotes
);
1368 res
|= try_merge_command(opts
->strategy
,
1369 opts
->xopts_nr
, (const char **)opts
->xopts
,
1370 common
, oid_to_hex(&head
), remotes
);
1371 free_commit_list(common
);
1372 free_commit_list(remotes
);
1374 strbuf_release(&msgbuf
);
1377 * If the merge was clean or if it failed due to conflict, we write
1378 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1379 * However, if the merge did not even start, then we don't want to
1382 if (command
== TODO_PICK
&& !opts
->no_commit
&& (res
== 0 || res
== 1) &&
1383 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
1384 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
))
1386 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
1387 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
1388 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
))
1392 error(command
== TODO_REVERT
1393 ? _("could not revert %s... %s")
1394 : _("could not apply %s... %s"),
1395 short_commit_name(commit
), msg
.subject
);
1396 print_advice(res
== 1, opts
);
1397 rerere(opts
->allow_rerere_auto
);
1401 allow
= allow_empty(opts
, commit
);
1406 flags
|= ALLOW_EMPTY
;
1407 if (!opts
->no_commit
)
1409 res
= run_git_commit(msg_file
, opts
, flags
);
1411 if (!res
&& final_fixup
) {
1412 unlink(rebase_path_fixup_msg());
1413 unlink(rebase_path_squash_msg());
1417 free_message(commit
, &msg
);
1418 update_abort_safety_file();
1423 static int prepare_revs(struct replay_opts
*opts
)
1426 * picking (but not reverting) ranges (but not individual revisions)
1427 * should be done in reverse
1429 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
1430 opts
->revs
->reverse
^= 1;
1432 if (prepare_revision_walk(opts
->revs
))
1433 return error(_("revision walk setup failed"));
1435 if (!opts
->revs
->commits
)
1436 return error(_("empty commit set passed"));
1440 static int read_and_refresh_cache(struct replay_opts
*opts
)
1442 static struct lock_file index_lock
;
1443 int index_fd
= hold_locked_index(&index_lock
, 0);
1444 if (read_index_preload(&the_index
, NULL
) < 0) {
1445 rollback_lock_file(&index_lock
);
1446 return error(_("git %s: failed to read the index"),
1447 _(action_name(opts
)));
1449 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
1450 if (the_index
.cache_changed
&& index_fd
>= 0) {
1451 if (write_locked_index(&the_index
, &index_lock
, COMMIT_LOCK
)) {
1452 return error(_("git %s: failed to refresh the index"),
1453 _(action_name(opts
)));
1456 rollback_lock_file(&index_lock
);
1461 enum todo_command command
;
1462 struct commit
*commit
;
1465 size_t offset_in_buf
;
1470 struct todo_item
*items
;
1471 int nr
, alloc
, current
;
1472 int done_nr
, total_nr
;
1473 struct stat_data stat
;
1476 #define TODO_LIST_INIT { STRBUF_INIT }
1478 static void todo_list_release(struct todo_list
*todo_list
)
1480 strbuf_release(&todo_list
->buf
);
1481 FREE_AND_NULL(todo_list
->items
);
1482 todo_list
->nr
= todo_list
->alloc
= 0;
1485 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
1487 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
1488 return todo_list
->items
+ todo_list
->nr
++;
1491 static int parse_insn_line(struct todo_item
*item
, const char *bol
, char *eol
)
1493 struct object_id commit_oid
;
1494 char *end_of_object_name
;
1495 int i
, saved
, status
, padding
;
1498 bol
+= strspn(bol
, " \t");
1500 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
1501 item
->command
= TODO_COMMENT
;
1502 item
->commit
= NULL
;
1504 item
->arg_len
= eol
- bol
;
1508 for (i
= 0; i
< TODO_COMMENT
; i
++)
1509 if (skip_prefix(bol
, todo_command_info
[i
].str
, &bol
)) {
1512 } else if (bol
[1] == ' ' && *bol
== todo_command_info
[i
].c
) {
1517 if (i
>= TODO_COMMENT
)
1520 if (item
->command
== TODO_NOOP
) {
1521 item
->commit
= NULL
;
1523 item
->arg_len
= eol
- bol
;
1527 /* Eat up extra spaces/ tabs before object name */
1528 padding
= strspn(bol
, " \t");
1533 if (item
->command
== TODO_EXEC
) {
1535 item
->arg_len
= (int)(eol
- bol
);
1539 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
1540 saved
= *end_of_object_name
;
1541 *end_of_object_name
= '\0';
1542 status
= get_oid(bol
, &commit_oid
);
1543 *end_of_object_name
= saved
;
1545 item
->arg
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
1546 item
->arg_len
= (int)(eol
- item
->arg
);
1551 item
->commit
= lookup_commit_reference(&commit_oid
);
1552 return !item
->commit
;
1555 static int parse_insn_buffer(char *buf
, struct todo_list
*todo_list
)
1557 struct todo_item
*item
;
1558 char *p
= buf
, *next_p
;
1559 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
1561 for (i
= 1; *p
; i
++, p
= next_p
) {
1562 char *eol
= strchrnul(p
, '\n');
1564 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
1566 if (p
!= eol
&& eol
[-1] == '\r')
1567 eol
--; /* strip Carriage Return */
1569 item
= append_new_todo(todo_list
);
1570 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
1571 if (parse_insn_line(item
, p
, eol
)) {
1572 res
= error(_("invalid line %d: %.*s"),
1573 i
, (int)(eol
- p
), p
);
1574 item
->command
= TODO_NOOP
;
1579 else if (is_fixup(item
->command
))
1580 return error(_("cannot '%s' without a previous commit"),
1581 command_to_string(item
->command
));
1582 else if (!is_noop(item
->command
))
1589 static int count_commands(struct todo_list
*todo_list
)
1593 for (i
= 0; i
< todo_list
->nr
; i
++)
1594 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
1600 static int read_populate_todo(struct todo_list
*todo_list
,
1601 struct replay_opts
*opts
)
1604 const char *todo_file
= get_todo_path(opts
);
1607 strbuf_reset(&todo_list
->buf
);
1608 fd
= open(todo_file
, O_RDONLY
);
1610 return error_errno(_("could not open '%s'"), todo_file
);
1611 if (strbuf_read(&todo_list
->buf
, fd
, 0) < 0) {
1613 return error(_("could not read '%s'."), todo_file
);
1617 res
= stat(todo_file
, &st
);
1619 return error(_("could not stat '%s'"), todo_file
);
1620 fill_stat_data(&todo_list
->stat
, &st
);
1622 res
= parse_insn_buffer(todo_list
->buf
.buf
, todo_list
);
1624 if (is_rebase_i(opts
))
1625 return error(_("please fix this using "
1626 "'git rebase --edit-todo'."));
1627 return error(_("unusable instruction sheet: '%s'"), todo_file
);
1630 if (!todo_list
->nr
&&
1631 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
1632 return error(_("no commits parsed."));
1634 if (!is_rebase_i(opts
)) {
1635 enum todo_command valid
=
1636 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
1639 for (i
= 0; i
< todo_list
->nr
; i
++)
1640 if (valid
== todo_list
->items
[i
].command
)
1642 else if (valid
== TODO_PICK
)
1643 return error(_("cannot cherry-pick during a revert."));
1645 return error(_("cannot revert during a cherry-pick."));
1648 if (is_rebase_i(opts
)) {
1649 struct todo_list done
= TODO_LIST_INIT
;
1650 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
1652 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
1653 !parse_insn_buffer(done
.buf
.buf
, &done
))
1654 todo_list
->done_nr
= count_commands(&done
);
1656 todo_list
->done_nr
= 0;
1658 todo_list
->total_nr
= todo_list
->done_nr
1659 + count_commands(todo_list
);
1660 todo_list_release(&done
);
1663 fprintf(f
, "%d\n", todo_list
->total_nr
);
1671 static int git_config_string_dup(char **dest
,
1672 const char *var
, const char *value
)
1675 return config_error_nonbool(var
);
1677 *dest
= xstrdup(value
);
1681 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
1683 struct replay_opts
*opts
= data
;
1688 else if (!strcmp(key
, "options.no-commit"))
1689 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
1690 else if (!strcmp(key
, "options.edit"))
1691 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
1692 else if (!strcmp(key
, "options.signoff"))
1693 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
1694 else if (!strcmp(key
, "options.record-origin"))
1695 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
1696 else if (!strcmp(key
, "options.allow-ff"))
1697 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
1698 else if (!strcmp(key
, "options.mainline"))
1699 opts
->mainline
= git_config_int(key
, value
);
1700 else if (!strcmp(key
, "options.strategy"))
1701 git_config_string_dup(&opts
->strategy
, key
, value
);
1702 else if (!strcmp(key
, "options.gpg-sign"))
1703 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
1704 else if (!strcmp(key
, "options.strategy-option")) {
1705 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
1706 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(value
);
1707 } else if (!strcmp(key
, "options.allow-rerere-auto"))
1708 opts
->allow_rerere_auto
=
1709 git_config_bool_or_int(key
, value
, &error_flag
) ?
1710 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
1712 return error(_("invalid key: %s"), key
);
1715 return error(_("invalid value for %s: %s"), key
, value
);
1720 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
1725 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
1727 opts
->strategy
= strbuf_detach(buf
, NULL
);
1728 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
1731 opts
->xopts_nr
= split_cmdline(buf
->buf
, (const char ***)&opts
->xopts
);
1732 for (i
= 0; i
< opts
->xopts_nr
; i
++) {
1733 const char *arg
= opts
->xopts
[i
];
1735 skip_prefix(arg
, "--", &arg
);
1736 opts
->xopts
[i
] = xstrdup(arg
);
1740 static int read_populate_opts(struct replay_opts
*opts
)
1742 if (is_rebase_i(opts
)) {
1743 struct strbuf buf
= STRBUF_INIT
;
1745 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(), 1)) {
1746 if (!starts_with(buf
.buf
, "-S"))
1749 free(opts
->gpg_sign
);
1750 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
1755 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(), 1)) {
1756 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
1757 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
1758 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
1759 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
1763 if (file_exists(rebase_path_verbose()))
1766 read_strategy_opts(opts
, &buf
);
1767 strbuf_release(&buf
);
1772 if (!file_exists(git_path_opts_file()))
1775 * The function git_parse_source(), called from git_config_from_file(),
1776 * may die() in case of a syntactically incorrect file. We do not care
1777 * about this case, though, because we wrote that file ourselves, so we
1778 * are pretty certain that it is syntactically correct.
1780 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
1781 return error(_("malformed options sheet: '%s'"),
1782 git_path_opts_file());
1786 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
1787 struct replay_opts
*opts
)
1789 enum todo_command command
= opts
->action
== REPLAY_PICK
?
1790 TODO_PICK
: TODO_REVERT
;
1791 const char *command_string
= todo_command_info
[command
].str
;
1792 struct commit
*commit
;
1794 if (prepare_revs(opts
))
1797 while ((commit
= get_revision(opts
->revs
))) {
1798 struct todo_item
*item
= append_new_todo(todo_list
);
1799 const char *commit_buffer
= get_commit_buffer(commit
, NULL
);
1800 const char *subject
;
1803 item
->command
= command
;
1804 item
->commit
= commit
;
1807 item
->offset_in_buf
= todo_list
->buf
.len
;
1808 subject_len
= find_commit_subject(commit_buffer
, &subject
);
1809 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
1810 short_commit_name(commit
), subject_len
, subject
);
1811 unuse_commit_buffer(commit
, commit_buffer
);
1816 static int create_seq_dir(void)
1818 if (file_exists(git_path_seq_dir())) {
1819 error(_("a cherry-pick or revert is already in progress"));
1820 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1822 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1823 return error_errno(_("could not create sequencer directory '%s'"),
1824 git_path_seq_dir());
1828 static int save_head(const char *head
)
1830 static struct lock_file head_lock
;
1831 struct strbuf buf
= STRBUF_INIT
;
1835 fd
= hold_lock_file_for_update(&head_lock
, git_path_head_file(), 0);
1837 rollback_lock_file(&head_lock
);
1838 return error_errno(_("could not lock HEAD"));
1840 strbuf_addf(&buf
, "%s\n", head
);
1841 written
= write_in_full(fd
, buf
.buf
, buf
.len
);
1842 strbuf_release(&buf
);
1844 rollback_lock_file(&head_lock
);
1845 return error_errno(_("could not write to '%s'"),
1846 git_path_head_file());
1848 if (commit_lock_file(&head_lock
) < 0) {
1849 rollback_lock_file(&head_lock
);
1850 return error(_("failed to finalize '%s'."), git_path_head_file());
1855 static int rollback_is_safe(void)
1857 struct strbuf sb
= STRBUF_INIT
;
1858 struct object_id expected_head
, actual_head
;
1860 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
1862 if (get_oid_hex(sb
.buf
, &expected_head
)) {
1863 strbuf_release(&sb
);
1864 die(_("could not parse %s"), git_path_abort_safety_file());
1866 strbuf_release(&sb
);
1868 else if (errno
== ENOENT
)
1869 oidclr(&expected_head
);
1871 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1873 if (get_oid("HEAD", &actual_head
))
1874 oidclr(&actual_head
);
1876 return !oidcmp(&actual_head
, &expected_head
);
1879 static int reset_for_rollback(const struct object_id
*oid
)
1881 const char *argv
[4]; /* reset --merge <arg> + NULL */
1884 argv
[1] = "--merge";
1885 argv
[2] = oid_to_hex(oid
);
1887 return run_command_v_opt(argv
, RUN_GIT_CMD
);
1890 static int rollback_single_pick(void)
1892 struct object_id head_oid
;
1894 if (!file_exists(git_path_cherry_pick_head()) &&
1895 !file_exists(git_path_revert_head()))
1896 return error(_("no cherry-pick or revert in progress"));
1897 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
1898 return error(_("cannot resolve HEAD"));
1899 if (is_null_oid(&head_oid
))
1900 return error(_("cannot abort from a branch yet to be born"));
1901 return reset_for_rollback(&head_oid
);
1904 int sequencer_rollback(struct replay_opts
*opts
)
1907 struct object_id oid
;
1908 struct strbuf buf
= STRBUF_INIT
;
1911 f
= fopen(git_path_head_file(), "r");
1912 if (!f
&& errno
== ENOENT
) {
1914 * There is no multiple-cherry-pick in progress.
1915 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1916 * a single-cherry-pick in progress, abort that.
1918 return rollback_single_pick();
1921 return error_errno(_("cannot open '%s'"), git_path_head_file());
1922 if (strbuf_getline_lf(&buf
, f
)) {
1923 error(_("cannot read '%s': %s"), git_path_head_file(),
1924 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
1929 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
1930 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1931 git_path_head_file());
1934 if (is_null_oid(&oid
)) {
1935 error(_("cannot abort from a branch yet to be born"));
1939 if (!rollback_is_safe()) {
1940 /* Do not error, just do not rollback */
1941 warning(_("You seem to have moved HEAD. "
1942 "Not rewinding, check your HEAD!"));
1944 if (reset_for_rollback(&oid
))
1946 strbuf_release(&buf
);
1947 return sequencer_remove_state(opts
);
1949 strbuf_release(&buf
);
1953 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
1955 static struct lock_file todo_lock
;
1956 const char *todo_path
= get_todo_path(opts
);
1957 int next
= todo_list
->current
, offset
, fd
;
1960 * rebase -i writes "git-rebase-todo" without the currently executing
1961 * command, appending it to "done" instead.
1963 if (is_rebase_i(opts
))
1966 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
1968 return error_errno(_("could not lock '%s'"), todo_path
);
1969 offset
= next
< todo_list
->nr
?
1970 todo_list
->items
[next
].offset_in_buf
: todo_list
->buf
.len
;
1971 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
1972 todo_list
->buf
.len
- offset
) < 0)
1973 return error_errno(_("could not write to '%s'"), todo_path
);
1974 if (commit_lock_file(&todo_lock
) < 0)
1975 return error(_("failed to finalize '%s'."), todo_path
);
1977 if (is_rebase_i(opts
)) {
1978 const char *done_path
= rebase_path_done();
1979 int fd
= open(done_path
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
1980 int prev_offset
= !next
? 0 :
1981 todo_list
->items
[next
- 1].offset_in_buf
;
1983 if (fd
>= 0 && offset
> prev_offset
&&
1984 write_in_full(fd
, todo_list
->buf
.buf
+ prev_offset
,
1985 offset
- prev_offset
) < 0) {
1987 return error_errno(_("could not write to '%s'"),
1996 static int save_opts(struct replay_opts
*opts
)
1998 const char *opts_file
= git_path_opts_file();
2001 if (opts
->no_commit
)
2002 res
|= git_config_set_in_file_gently(opts_file
, "options.no-commit", "true");
2004 res
|= git_config_set_in_file_gently(opts_file
, "options.edit", "true");
2006 res
|= git_config_set_in_file_gently(opts_file
, "options.signoff", "true");
2007 if (opts
->record_origin
)
2008 res
|= git_config_set_in_file_gently(opts_file
, "options.record-origin", "true");
2010 res
|= git_config_set_in_file_gently(opts_file
, "options.allow-ff", "true");
2011 if (opts
->mainline
) {
2012 struct strbuf buf
= STRBUF_INIT
;
2013 strbuf_addf(&buf
, "%d", opts
->mainline
);
2014 res
|= git_config_set_in_file_gently(opts_file
, "options.mainline", buf
.buf
);
2015 strbuf_release(&buf
);
2018 res
|= git_config_set_in_file_gently(opts_file
, "options.strategy", opts
->strategy
);
2020 res
|= git_config_set_in_file_gently(opts_file
, "options.gpg-sign", opts
->gpg_sign
);
2023 for (i
= 0; i
< opts
->xopts_nr
; i
++)
2024 res
|= git_config_set_multivar_in_file_gently(opts_file
,
2025 "options.strategy-option",
2026 opts
->xopts
[i
], "^$", 0);
2028 if (opts
->allow_rerere_auto
)
2029 res
|= git_config_set_in_file_gently(opts_file
, "options.allow-rerere-auto",
2030 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
2035 static int make_patch(struct commit
*commit
, struct replay_opts
*opts
)
2037 struct strbuf buf
= STRBUF_INIT
;
2038 struct rev_info log_tree_opt
;
2039 const char *subject
, *p
;
2042 p
= short_commit_name(commit
);
2043 if (write_message(p
, strlen(p
), rebase_path_stopped_sha(), 1) < 0)
2046 strbuf_addf(&buf
, "%s/patch", get_dir(opts
));
2047 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
2048 init_revisions(&log_tree_opt
, NULL
);
2049 log_tree_opt
.abbrev
= 0;
2050 log_tree_opt
.diff
= 1;
2051 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
2052 log_tree_opt
.disable_stdin
= 1;
2053 log_tree_opt
.no_commit_id
= 1;
2054 log_tree_opt
.diffopt
.file
= fopen(buf
.buf
, "w");
2055 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
2056 if (!log_tree_opt
.diffopt
.file
)
2057 res
|= error_errno(_("could not open '%s'"), buf
.buf
);
2059 res
|= log_tree_commit(&log_tree_opt
, commit
);
2060 fclose(log_tree_opt
.diffopt
.file
);
2064 strbuf_addf(&buf
, "%s/message", get_dir(opts
));
2065 if (!file_exists(buf
.buf
)) {
2066 const char *commit_buffer
= get_commit_buffer(commit
, NULL
);
2067 find_commit_subject(commit_buffer
, &subject
);
2068 res
|= write_message(subject
, strlen(subject
), buf
.buf
, 1);
2069 unuse_commit_buffer(commit
, commit_buffer
);
2071 strbuf_release(&buf
);
2076 static int intend_to_amend(void)
2078 struct object_id head
;
2081 if (get_oid("HEAD", &head
))
2082 return error(_("cannot read HEAD"));
2084 p
= oid_to_hex(&head
);
2085 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
2088 static int error_with_patch(struct commit
*commit
,
2089 const char *subject
, int subject_len
,
2090 struct replay_opts
*opts
, int exit_code
, int to_amend
)
2092 if (make_patch(commit
, opts
))
2096 if (intend_to_amend())
2099 fprintf(stderr
, "You can amend the commit now, with\n"
2101 " git commit --amend %s\n"
2103 "Once you are satisfied with your changes, run\n"
2105 " git rebase --continue\n", gpg_sign_opt_quoted(opts
));
2106 } else if (exit_code
)
2107 fprintf(stderr
, "Could not apply %s... %.*s\n",
2108 short_commit_name(commit
), subject_len
, subject
);
2113 static int error_failed_squash(struct commit
*commit
,
2114 struct replay_opts
*opts
, int subject_len
, const char *subject
)
2116 if (rename(rebase_path_squash_msg(), rebase_path_message()))
2117 return error(_("could not rename '%s' to '%s'"),
2118 rebase_path_squash_msg(), rebase_path_message());
2119 unlink(rebase_path_fixup_msg());
2120 unlink(git_path_merge_msg());
2121 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2122 return error(_("could not copy '%s' to '%s'"),
2123 rebase_path_message(), git_path_merge_msg());
2124 return error_with_patch(commit
, subject
, subject_len
, opts
, 1, 0);
2127 static int do_exec(const char *command_line
)
2129 struct argv_array child_env
= ARGV_ARRAY_INIT
;
2130 const char *child_argv
[] = { NULL
, NULL
};
2133 fprintf(stderr
, "Executing: %s\n", command_line
);
2134 child_argv
[0] = command_line
;
2135 argv_array_pushf(&child_env
, "GIT_DIR=%s", absolute_path(get_git_dir()));
2136 status
= run_command_v_opt_cd_env(child_argv
, RUN_USING_SHELL
, NULL
,
2139 /* force re-reading of the cache */
2140 if (discard_cache() < 0 || read_cache() < 0)
2141 return error(_("could not read index"));
2143 dirty
= require_clean_work_tree("rebase", NULL
, 1, 1);
2146 warning(_("execution failed: %s\n%s"
2147 "You can fix the problem, and then run\n"
2149 " git rebase --continue\n"
2152 dirty
? N_("and made changes to the index and/or the "
2153 "working tree\n") : "");
2155 /* command not found */
2158 warning(_("execution succeeded: %s\nbut "
2159 "left changes to the index and/or the working tree\n"
2160 "Commit or stash your changes, and then run\n"
2162 " git rebase --continue\n"
2163 "\n"), command_line
);
2167 argv_array_clear(&child_env
);
2172 static int is_final_fixup(struct todo_list
*todo_list
)
2174 int i
= todo_list
->current
;
2176 if (!is_fixup(todo_list
->items
[i
].command
))
2179 while (++i
< todo_list
->nr
)
2180 if (is_fixup(todo_list
->items
[i
].command
))
2182 else if (!is_noop(todo_list
->items
[i
].command
))
2187 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
2191 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
2192 if (!is_noop(todo_list
->items
[i
].command
))
2193 return todo_list
->items
[i
].command
;
2198 static int apply_autostash(struct replay_opts
*opts
)
2200 struct strbuf stash_sha1
= STRBUF_INIT
;
2201 struct child_process child
= CHILD_PROCESS_INIT
;
2204 if (!read_oneliner(&stash_sha1
, rebase_path_autostash(), 1)) {
2205 strbuf_release(&stash_sha1
);
2208 strbuf_trim(&stash_sha1
);
2211 child
.no_stdout
= 1;
2212 child
.no_stderr
= 1;
2213 argv_array_push(&child
.args
, "stash");
2214 argv_array_push(&child
.args
, "apply");
2215 argv_array_push(&child
.args
, stash_sha1
.buf
);
2216 if (!run_command(&child
))
2217 fprintf(stderr
, _("Applied autostash.\n"));
2219 struct child_process store
= CHILD_PROCESS_INIT
;
2222 argv_array_push(&store
.args
, "stash");
2223 argv_array_push(&store
.args
, "store");
2224 argv_array_push(&store
.args
, "-m");
2225 argv_array_push(&store
.args
, "autostash");
2226 argv_array_push(&store
.args
, "-q");
2227 argv_array_push(&store
.args
, stash_sha1
.buf
);
2228 if (run_command(&store
))
2229 ret
= error(_("cannot store %s"), stash_sha1
.buf
);
2232 _("Applying autostash resulted in conflicts.\n"
2233 "Your changes are safe in the stash.\n"
2234 "You can run \"git stash pop\" or"
2235 " \"git stash drop\" at any time.\n"));
2238 strbuf_release(&stash_sha1
);
2242 static const char *reflog_message(struct replay_opts
*opts
,
2243 const char *sub_action
, const char *fmt
, ...)
2246 static struct strbuf buf
= STRBUF_INIT
;
2250 strbuf_addstr(&buf
, action_name(opts
));
2252 strbuf_addf(&buf
, " (%s)", sub_action
);
2254 strbuf_addstr(&buf
, ": ");
2255 strbuf_vaddf(&buf
, fmt
, ap
);
2262 static int pick_commits(struct todo_list
*todo_list
, struct replay_opts
*opts
)
2266 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
2268 assert(!(opts
->signoff
|| opts
->no_commit
||
2269 opts
->record_origin
|| opts
->edit
));
2270 if (read_and_refresh_cache(opts
))
2273 while (todo_list
->current
< todo_list
->nr
) {
2274 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
2275 if (save_todo(todo_list
, opts
))
2277 if (is_rebase_i(opts
)) {
2278 if (item
->command
!= TODO_COMMENT
) {
2279 FILE *f
= fopen(rebase_path_msgnum(), "w");
2281 todo_list
->done_nr
++;
2284 fprintf(f
, "%d\n", todo_list
->done_nr
);
2287 fprintf(stderr
, "Rebasing (%d/%d)%s",
2289 todo_list
->total_nr
,
2290 opts
->verbose
? "\n" : "\r");
2292 unlink(rebase_path_message());
2293 unlink(rebase_path_author_script());
2294 unlink(rebase_path_stopped_sha());
2295 unlink(rebase_path_amend());
2297 if (item
->command
<= TODO_SQUASH
) {
2298 if (is_rebase_i(opts
))
2299 setenv("GIT_REFLOG_ACTION", reflog_message(opts
,
2300 command_to_string(item
->command
), NULL
),
2302 res
= do_pick_commit(item
->command
, item
->commit
,
2303 opts
, is_final_fixup(todo_list
));
2304 if (is_rebase_i(opts
) && res
< 0) {
2306 todo_list
->current
--;
2307 if (save_todo(todo_list
, opts
))
2310 if (item
->command
== TODO_EDIT
) {
2311 struct commit
*commit
= item
->commit
;
2314 _("Stopped at %s... %.*s\n"),
2315 short_commit_name(commit
),
2316 item
->arg_len
, item
->arg
);
2317 return error_with_patch(commit
,
2318 item
->arg
, item
->arg_len
, opts
, res
,
2321 if (is_rebase_i(opts
) && !res
)
2322 record_in_rewritten(&item
->commit
->object
.oid
,
2323 peek_command(todo_list
, 1));
2324 if (res
&& is_fixup(item
->command
)) {
2327 return error_failed_squash(item
->commit
, opts
,
2328 item
->arg_len
, item
->arg
);
2329 } else if (res
&& is_rebase_i(opts
))
2330 return res
| error_with_patch(item
->commit
,
2331 item
->arg
, item
->arg_len
, opts
, res
,
2332 item
->command
== TODO_REWORD
);
2333 } else if (item
->command
== TODO_EXEC
) {
2334 char *end_of_arg
= (char *)(item
->arg
+ item
->arg_len
);
2335 int saved
= *end_of_arg
;
2339 res
= do_exec(item
->arg
);
2340 *end_of_arg
= saved
;
2342 /* Reread the todo file if it has changed. */
2344 ; /* fall through */
2345 else if (stat(get_todo_path(opts
), &st
))
2346 res
= error_errno(_("could not stat '%s'"),
2347 get_todo_path(opts
));
2348 else if (match_stat_data(&todo_list
->stat
, &st
)) {
2349 todo_list_release(todo_list
);
2350 if (read_populate_todo(todo_list
, opts
))
2351 res
= -1; /* message was printed */
2352 /* `current` will be incremented below */
2353 todo_list
->current
= -1;
2355 } else if (!is_noop(item
->command
))
2356 return error(_("unknown command %d"), item
->command
);
2358 todo_list
->current
++;
2363 if (is_rebase_i(opts
)) {
2364 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
2367 /* Stopped in the middle, as planned? */
2368 if (todo_list
->current
< todo_list
->nr
)
2371 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
2372 starts_with(head_ref
.buf
, "refs/")) {
2374 struct object_id head
, orig
;
2377 if (get_oid("HEAD", &head
)) {
2378 res
= error(_("cannot read HEAD"));
2380 strbuf_release(&head_ref
);
2381 strbuf_release(&buf
);
2384 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
2385 get_oid_hex(buf
.buf
, &orig
)) {
2386 res
= error(_("could not read orig-head"));
2387 goto cleanup_head_ref
;
2390 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
2391 res
= error(_("could not read 'onto'"));
2392 goto cleanup_head_ref
;
2394 msg
= reflog_message(opts
, "finish", "%s onto %s",
2395 head_ref
.buf
, buf
.buf
);
2396 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
2397 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
2398 res
= error(_("could not update %s"),
2400 goto cleanup_head_ref
;
2402 msg
= reflog_message(opts
, "finish", "returning to %s",
2404 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
2405 res
= error(_("could not update HEAD to %s"),
2407 goto cleanup_head_ref
;
2412 if (opts
->verbose
) {
2413 struct rev_info log_tree_opt
;
2414 struct object_id orig
, head
;
2416 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
2417 init_revisions(&log_tree_opt
, NULL
);
2418 log_tree_opt
.diff
= 1;
2419 log_tree_opt
.diffopt
.output_format
=
2420 DIFF_FORMAT_DIFFSTAT
;
2421 log_tree_opt
.disable_stdin
= 1;
2423 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
2424 !get_oid(buf
.buf
, &orig
) &&
2425 !get_oid("HEAD", &head
)) {
2426 diff_tree_oid(&orig
, &head
, "",
2427 &log_tree_opt
.diffopt
);
2428 log_tree_diff_flush(&log_tree_opt
);
2431 flush_rewritten_pending();
2432 if (!stat(rebase_path_rewritten_list(), &st
) &&
2434 struct child_process child
= CHILD_PROCESS_INIT
;
2435 const char *post_rewrite_hook
=
2436 find_hook("post-rewrite");
2438 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
2440 argv_array_push(&child
.args
, "notes");
2441 argv_array_push(&child
.args
, "copy");
2442 argv_array_push(&child
.args
, "--for-rewrite=rebase");
2443 /* we don't care if this copying failed */
2444 run_command(&child
);
2446 if (post_rewrite_hook
) {
2447 struct child_process hook
= CHILD_PROCESS_INIT
;
2449 hook
.in
= open(rebase_path_rewritten_list(),
2451 hook
.stdout_to_stderr
= 1;
2452 argv_array_push(&hook
.args
, post_rewrite_hook
);
2453 argv_array_push(&hook
.args
, "rebase");
2454 /* we don't care if this hook failed */
2458 apply_autostash(opts
);
2460 fprintf(stderr
, "Successfully rebased and updated %s.\n",
2463 strbuf_release(&buf
);
2464 strbuf_release(&head_ref
);
2468 * Sequence of picks finished successfully; cleanup by
2469 * removing the .git/sequencer directory
2471 return sequencer_remove_state(opts
);
2474 static int continue_single_pick(void)
2476 const char *argv
[] = { "commit", NULL
};
2478 if (!file_exists(git_path_cherry_pick_head()) &&
2479 !file_exists(git_path_revert_head()))
2480 return error(_("no cherry-pick or revert in progress"));
2481 return run_command_v_opt(argv
, RUN_GIT_CMD
);
2484 static int commit_staged_changes(struct replay_opts
*opts
)
2486 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
2488 if (has_unstaged_changes(1))
2489 return error(_("cannot rebase: You have unstaged changes."));
2490 if (!has_uncommitted_changes(0)) {
2491 const char *cherry_pick_head
= git_path_cherry_pick_head();
2493 if (file_exists(cherry_pick_head
) && unlink(cherry_pick_head
))
2494 return error(_("could not remove CHERRY_PICK_HEAD"));
2498 if (file_exists(rebase_path_amend())) {
2499 struct strbuf rev
= STRBUF_INIT
;
2500 struct object_id head
, to_amend
;
2502 if (get_oid("HEAD", &head
))
2503 return error(_("cannot amend non-existing commit"));
2504 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
2505 return error(_("invalid file: '%s'"), rebase_path_amend());
2506 if (get_oid_hex(rev
.buf
, &to_amend
))
2507 return error(_("invalid contents: '%s'"),
2508 rebase_path_amend());
2509 if (oidcmp(&head
, &to_amend
))
2510 return error(_("\nYou have uncommitted changes in your "
2511 "working tree. Please, commit them\n"
2512 "first and then run 'git rebase "
2513 "--continue' again."));
2515 strbuf_release(&rev
);
2519 if (run_git_commit(rebase_path_message(), opts
, flags
))
2520 return error(_("could not commit staged changes."));
2521 unlink(rebase_path_amend());
2525 int sequencer_continue(struct replay_opts
*opts
)
2527 struct todo_list todo_list
= TODO_LIST_INIT
;
2530 if (read_and_refresh_cache(opts
))
2533 if (is_rebase_i(opts
)) {
2534 if (commit_staged_changes(opts
))
2536 } else if (!file_exists(get_todo_path(opts
)))
2537 return continue_single_pick();
2538 if (read_populate_opts(opts
))
2540 if ((res
= read_populate_todo(&todo_list
, opts
)))
2541 goto release_todo_list
;
2543 if (!is_rebase_i(opts
)) {
2544 /* Verify that the conflict has been resolved */
2545 if (file_exists(git_path_cherry_pick_head()) ||
2546 file_exists(git_path_revert_head())) {
2547 res
= continue_single_pick();
2549 goto release_todo_list
;
2551 if (index_differs_from("HEAD", NULL
, 0)) {
2552 res
= error_dirty_index(opts
);
2553 goto release_todo_list
;
2555 todo_list
.current
++;
2556 } else if (file_exists(rebase_path_stopped_sha())) {
2557 struct strbuf buf
= STRBUF_INIT
;
2558 struct object_id oid
;
2560 if (read_oneliner(&buf
, rebase_path_stopped_sha(), 1) &&
2561 !get_oid_committish(buf
.buf
, &oid
))
2562 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
2563 strbuf_release(&buf
);
2566 res
= pick_commits(&todo_list
, opts
);
2568 todo_list_release(&todo_list
);
2572 static int single_pick(struct commit
*cmit
, struct replay_opts
*opts
)
2574 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
2575 return do_pick_commit(opts
->action
== REPLAY_PICK
?
2576 TODO_PICK
: TODO_REVERT
, cmit
, opts
, 0);
2579 int sequencer_pick_revisions(struct replay_opts
*opts
)
2581 struct todo_list todo_list
= TODO_LIST_INIT
;
2582 struct object_id oid
;
2586 if (read_and_refresh_cache(opts
))
2589 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
2590 struct object_id oid
;
2591 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
2593 /* This happens when using --stdin. */
2597 if (!get_oid(name
, &oid
)) {
2598 if (!lookup_commit_reference_gently(&oid
, 1)) {
2599 enum object_type type
= sha1_object_info(oid
.hash
, NULL
);
2600 return error(_("%s: can't cherry-pick a %s"),
2601 name
, typename(type
));
2604 return error(_("%s: bad revision"), name
);
2608 * If we were called as "git cherry-pick <commit>", just
2609 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2610 * REVERT_HEAD, and don't touch the sequencer state.
2611 * This means it is possible to cherry-pick in the middle
2612 * of a cherry-pick sequence.
2614 if (opts
->revs
->cmdline
.nr
== 1 &&
2615 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
2616 opts
->revs
->no_walk
&&
2617 !opts
->revs
->cmdline
.rev
->flags
) {
2618 struct commit
*cmit
;
2619 if (prepare_revision_walk(opts
->revs
))
2620 return error(_("revision walk setup failed"));
2621 cmit
= get_revision(opts
->revs
);
2622 if (!cmit
|| get_revision(opts
->revs
))
2623 return error("BUG: expected exactly one commit from walk");
2624 return single_pick(cmit
, opts
);
2628 * Start a new cherry-pick/ revert sequence; but
2629 * first, make sure that an existing one isn't in
2633 if (walk_revs_populate_todo(&todo_list
, opts
) ||
2634 create_seq_dir() < 0)
2636 if (get_oid("HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
2637 return error(_("can't revert as initial commit"));
2638 if (save_head(oid_to_hex(&oid
)))
2640 if (save_opts(opts
))
2642 update_abort_safety_file();
2643 res
= pick_commits(&todo_list
, opts
);
2644 todo_list_release(&todo_list
);
2648 void append_signoff(struct strbuf
*msgbuf
, int ignore_footer
, unsigned flag
)
2650 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
2651 struct strbuf sob
= STRBUF_INIT
;
2654 strbuf_addstr(&sob
, sign_off_header
);
2655 strbuf_addstr(&sob
, fmt_name(getenv("GIT_COMMITTER_NAME"),
2656 getenv("GIT_COMMITTER_EMAIL")));
2657 strbuf_addch(&sob
, '\n');
2660 strbuf_complete_line(msgbuf
);
2663 * If the whole message buffer is equal to the sob, pretend that we
2664 * found a conforming footer with a matching sob
2666 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
2667 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
2670 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
2673 const char *append_newlines
= NULL
;
2674 size_t len
= msgbuf
->len
- ignore_footer
;
2678 * The buffer is completely empty. Leave foom for
2679 * the title and body to be filled in by the user.
2681 append_newlines
= "\n\n";
2682 } else if (len
== 1) {
2684 * Buffer contains a single newline. Add another
2685 * so that we leave room for the title and body.
2687 append_newlines
= "\n";
2688 } else if (msgbuf
->buf
[len
- 2] != '\n') {
2690 * Buffer ends with a single newline. Add another
2691 * so that there is an empty line between the message
2694 append_newlines
= "\n";
2695 } /* else, the buffer already ends with two newlines. */
2697 if (append_newlines
)
2698 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
2699 append_newlines
, strlen(append_newlines
));
2702 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
2703 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
2706 strbuf_release(&sob
);
2709 int sequencer_make_script(int keep_empty
, FILE *out
,
2710 int argc
, const char **argv
)
2712 char *format
= NULL
;
2713 struct pretty_print_context pp
= {0};
2714 struct strbuf buf
= STRBUF_INIT
;
2715 struct rev_info revs
;
2716 struct commit
*commit
;
2718 init_revisions(&revs
, NULL
);
2719 revs
.verbose_header
= 1;
2720 revs
.max_parents
= 1;
2721 revs
.cherry_pick
= 1;
2724 revs
.right_only
= 1;
2725 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
2726 revs
.topo_order
= 1;
2728 revs
.pretty_given
= 1;
2729 git_config_get_string("rebase.instructionFormat", &format
);
2730 if (!format
|| !*format
) {
2732 format
= xstrdup("%s");
2734 get_commit_format(format
, &revs
);
2736 pp
.fmt
= revs
.commit_format
;
2737 pp
.output_encoding
= get_log_output_encoding();
2739 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1)
2740 return error(_("make_script: unhandled options"));
2742 if (prepare_revision_walk(&revs
) < 0)
2743 return error(_("make_script: error preparing revisions"));
2745 while ((commit
= get_revision(&revs
))) {
2747 if (!keep_empty
&& is_original_commit_empty(commit
))
2748 strbuf_addf(&buf
, "%c ", comment_line_char
);
2749 strbuf_addf(&buf
, "pick %s ", oid_to_hex(&commit
->object
.oid
));
2750 pretty_print_commit(&pp
, commit
, &buf
);
2751 strbuf_addch(&buf
, '\n');
2752 fputs(buf
.buf
, out
);
2754 strbuf_release(&buf
);
2759 int transform_todo_ids(int shorten_ids
)
2761 const char *todo_file
= rebase_path_todo();
2762 struct todo_list todo_list
= TODO_LIST_INIT
;
2766 strbuf_reset(&todo_list
.buf
);
2767 fd
= open(todo_file
, O_RDONLY
);
2769 return error_errno(_("could not open '%s'"), todo_file
);
2770 if (strbuf_read(&todo_list
.buf
, fd
, 0) < 0) {
2772 return error(_("could not read '%s'."), todo_file
);
2776 res
= parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
);
2778 todo_list_release(&todo_list
);
2779 return error(_("unusable todo list: '%s'"), todo_file
);
2782 out
= fopen(todo_file
, "w");
2784 todo_list_release(&todo_list
);
2785 return error(_("unable to open '%s' for writing"), todo_file
);
2787 for (i
= 0; i
< todo_list
.nr
; i
++) {
2788 struct todo_item
*item
= todo_list
.items
+ i
;
2789 int bol
= item
->offset_in_buf
;
2790 const char *p
= todo_list
.buf
.buf
+ bol
;
2791 int eol
= i
+ 1 < todo_list
.nr
?
2792 todo_list
.items
[i
+ 1].offset_in_buf
:
2795 if (item
->command
>= TODO_EXEC
&& item
->command
!= TODO_DROP
)
2796 fwrite(p
, eol
- bol
, 1, out
);
2798 const char *id
= shorten_ids
?
2799 short_commit_name(item
->commit
) :
2800 oid_to_hex(&item
->commit
->object
.oid
);
2803 p
+= strspn(p
, " \t"); /* left-trim command */
2804 len
= strcspn(p
, " \t"); /* length of command */
2806 fprintf(out
, "%.*s %s %.*s\n",
2807 len
, p
, id
, item
->arg_len
, item
->arg
);
2811 todo_list_release(&todo_list
);
2816 CHECK_IGNORE
= 0, CHECK_WARN
, CHECK_ERROR
2819 static enum check_level
get_missing_commit_check_level(void)
2823 if (git_config_get_value("rebase.missingcommitscheck", &value
) ||
2824 !strcasecmp("ignore", value
))
2825 return CHECK_IGNORE
;
2826 if (!strcasecmp("warn", value
))
2828 if (!strcasecmp("error", value
))
2830 warning(_("unrecognized setting %s for option "
2831 "rebase.missingCommitsCheck. Ignoring."), value
);
2832 return CHECK_IGNORE
;
2836 * Check if the user dropped some commits by mistake
2837 * Behaviour determined by rebase.missingCommitsCheck.
2838 * Check if there is an unrecognized command or a
2839 * bad SHA-1 in a command.
2841 int check_todo_list(void)
2843 enum check_level check_level
= get_missing_commit_check_level();
2844 struct strbuf todo_file
= STRBUF_INIT
;
2845 struct todo_list todo_list
= TODO_LIST_INIT
;
2846 struct strbuf missing
= STRBUF_INIT
;
2847 int advise_to_edit_todo
= 0, res
= 0, fd
, i
;
2849 strbuf_addstr(&todo_file
, rebase_path_todo());
2850 fd
= open(todo_file
.buf
, O_RDONLY
);
2852 res
= error_errno(_("could not open '%s'"), todo_file
.buf
);
2855 if (strbuf_read(&todo_list
.buf
, fd
, 0) < 0) {
2857 res
= error(_("could not read '%s'."), todo_file
.buf
);
2861 advise_to_edit_todo
= res
=
2862 parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
);
2864 if (res
|| check_level
== CHECK_IGNORE
)
2867 /* Mark the commits in git-rebase-todo as seen */
2868 for (i
= 0; i
< todo_list
.nr
; i
++) {
2869 struct commit
*commit
= todo_list
.items
[i
].commit
;
2871 commit
->util
= (void *)1;
2874 todo_list_release(&todo_list
);
2875 strbuf_addstr(&todo_file
, ".backup");
2876 fd
= open(todo_file
.buf
, O_RDONLY
);
2878 res
= error_errno(_("could not open '%s'"), todo_file
.buf
);
2881 if (strbuf_read(&todo_list
.buf
, fd
, 0) < 0) {
2883 res
= error(_("could not read '%s'."), todo_file
.buf
);
2887 strbuf_release(&todo_file
);
2888 res
= !!parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
);
2890 /* Find commits in git-rebase-todo.backup yet unseen */
2891 for (i
= todo_list
.nr
- 1; i
>= 0; i
--) {
2892 struct todo_item
*item
= todo_list
.items
+ i
;
2893 struct commit
*commit
= item
->commit
;
2894 if (commit
&& !commit
->util
) {
2895 strbuf_addf(&missing
, " - %s %.*s\n",
2896 short_commit_name(commit
),
2897 item
->arg_len
, item
->arg
);
2898 commit
->util
= (void *)1;
2902 /* Warn about missing commits */
2906 if (check_level
== CHECK_ERROR
)
2907 advise_to_edit_todo
= res
= 1;
2910 _("Warning: some commits may have been dropped accidentally.\n"
2911 "Dropped commits (newer to older):\n"));
2913 /* Make the list user-friendly and display */
2914 fputs(missing
.buf
, stderr
);
2915 strbuf_release(&missing
);
2917 fprintf(stderr
, _("To avoid this message, use \"drop\" to "
2918 "explicitly remove a commit.\n\n"
2919 "Use 'git config rebase.missingCommitsCheck' to change "
2920 "the level of warnings.\n"
2921 "The possible behaviours are: ignore, warn, error.\n\n"));
2924 strbuf_release(&todo_file
);
2925 todo_list_release(&todo_list
);
2927 if (advise_to_edit_todo
)
2929 _("You can fix this with 'git rebase --edit-todo' "
2930 "and then run 'git rebase --continue'.\n"
2931 "Or you can abort the rebase with 'git rebase"
2937 /* skip picking commits whose parents are unchanged */
2938 int skip_unnecessary_picks(void)
2940 const char *todo_file
= rebase_path_todo();
2941 struct strbuf buf
= STRBUF_INIT
;
2942 struct todo_list todo_list
= TODO_LIST_INIT
;
2943 struct object_id onto_oid
, *oid
= &onto_oid
, *parent_oid
;
2946 if (!read_oneliner(&buf
, rebase_path_onto(), 0))
2947 return error(_("could not read 'onto'"));
2948 if (get_oid(buf
.buf
, &onto_oid
)) {
2949 strbuf_release(&buf
);
2950 return error(_("need a HEAD to fixup"));
2952 strbuf_release(&buf
);
2954 fd
= open(todo_file
, O_RDONLY
);
2956 return error_errno(_("could not open '%s'"), todo_file
);
2958 if (strbuf_read(&todo_list
.buf
, fd
, 0) < 0) {
2960 return error(_("could not read '%s'."), todo_file
);
2963 if (parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
) < 0) {
2964 todo_list_release(&todo_list
);
2968 for (i
= 0; i
< todo_list
.nr
; i
++) {
2969 struct todo_item
*item
= todo_list
.items
+ i
;
2971 if (item
->command
>= TODO_NOOP
)
2973 if (item
->command
!= TODO_PICK
)
2975 if (parse_commit(item
->commit
)) {
2976 todo_list_release(&todo_list
);
2977 return error(_("could not parse commit '%s'"),
2978 oid_to_hex(&item
->commit
->object
.oid
));
2980 if (!item
->commit
->parents
)
2981 break; /* root commit */
2982 if (item
->commit
->parents
->next
)
2983 break; /* merge commit */
2984 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
2985 if (hashcmp(parent_oid
->hash
, oid
->hash
))
2987 oid
= &item
->commit
->object
.oid
;
2990 int offset
= i
< todo_list
.nr
?
2991 todo_list
.items
[i
].offset_in_buf
: todo_list
.buf
.len
;
2992 const char *done_path
= rebase_path_done();
2994 fd
= open(done_path
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
2996 error_errno(_("could not open '%s' for writing"),
2998 todo_list_release(&todo_list
);
3001 if (write_in_full(fd
, todo_list
.buf
.buf
, offset
) < 0) {
3002 error_errno(_("could not write to '%s'"), done_path
);
3003 todo_list_release(&todo_list
);
3009 fd
= open(rebase_path_todo(), O_WRONLY
, 0666);
3011 error_errno(_("could not open '%s' for writing"),
3012 rebase_path_todo());
3013 todo_list_release(&todo_list
);
3016 if (write_in_full(fd
, todo_list
.buf
.buf
+ offset
,
3017 todo_list
.buf
.len
- offset
) < 0) {
3018 error_errno(_("could not write to '%s'"),
3019 rebase_path_todo());
3021 todo_list_release(&todo_list
);
3024 if (ftruncate(fd
, todo_list
.buf
.len
- offset
) < 0) {
3025 error_errno(_("could not truncate '%s'"),
3026 rebase_path_todo());
3027 todo_list_release(&todo_list
);
3033 todo_list
.current
= i
;
3034 if (is_fixup(peek_command(&todo_list
, 0)))
3035 record_in_rewritten(oid
, peek_command(&todo_list
, 0));
3038 todo_list_release(&todo_list
);
3039 printf("%s\n", oid_to_hex(oid
));
3044 struct subject2item_entry
{
3045 struct hashmap_entry entry
;
3047 char subject
[FLEX_ARRAY
];
3050 static int subject2item_cmp(const void *fndata
,
3051 const struct subject2item_entry
*a
,
3052 const struct subject2item_entry
*b
, const void *key
)
3054 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
3058 * Rearrange the todo list that has both "pick commit-id msg" and "pick
3059 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3060 * after the former, and change "pick" to "fixup"/"squash".
3062 * Note that if the config has specified a custom instruction format, each log
3063 * message will have to be retrieved from the commit (as the oneline in the
3064 * script cannot be trusted) in order to normalize the autosquash arrangement.
3066 int rearrange_squash(void)
3068 const char *todo_file
= rebase_path_todo();
3069 struct todo_list todo_list
= TODO_LIST_INIT
;
3070 struct hashmap subject2item
;
3071 int res
= 0, rearranged
= 0, *next
, *tail
, fd
, i
;
3074 fd
= open(todo_file
, O_RDONLY
);
3076 return error_errno(_("could not open '%s'"), todo_file
);
3077 if (strbuf_read(&todo_list
.buf
, fd
, 0) < 0) {
3079 return error(_("could not read '%s'."), todo_file
);
3082 if (parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
) < 0) {
3083 todo_list_release(&todo_list
);
3088 * The hashmap maps onelines to the respective todo list index.
3090 * If any items need to be rearranged, the next[i] value will indicate
3091 * which item was moved directly after the i'th.
3093 * In that case, last[i] will indicate the index of the latest item to
3094 * be moved to appear after the i'th.
3096 hashmap_init(&subject2item
, (hashmap_cmp_fn
) subject2item_cmp
,
3097 NULL
, todo_list
.nr
);
3098 ALLOC_ARRAY(next
, todo_list
.nr
);
3099 ALLOC_ARRAY(tail
, todo_list
.nr
);
3100 ALLOC_ARRAY(subjects
, todo_list
.nr
);
3101 for (i
= 0; i
< todo_list
.nr
; i
++) {
3102 struct strbuf buf
= STRBUF_INIT
;
3103 struct todo_item
*item
= todo_list
.items
+ i
;
3104 const char *commit_buffer
, *subject
, *p
;
3107 struct subject2item_entry
*entry
;
3109 next
[i
] = tail
[i
] = -1;
3110 if (item
->command
>= TODO_EXEC
) {
3115 if (is_fixup(item
->command
)) {
3116 todo_list_release(&todo_list
);
3117 return error(_("the script was already rearranged."));
3120 item
->commit
->util
= item
;
3122 parse_commit(item
->commit
);
3123 commit_buffer
= get_commit_buffer(item
->commit
, NULL
);
3124 find_commit_subject(commit_buffer
, &subject
);
3125 format_subject(&buf
, subject
, " ");
3126 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
3127 unuse_commit_buffer(item
->commit
, commit_buffer
);
3128 if ((skip_prefix(subject
, "fixup! ", &p
) ||
3129 skip_prefix(subject
, "squash! ", &p
))) {
3130 struct commit
*commit2
;
3135 if (!skip_prefix(p
, "fixup! ", &p
) &&
3136 !skip_prefix(p
, "squash! ", &p
))
3140 if ((entry
= hashmap_get_from_hash(&subject2item
,
3142 /* found by title */
3144 else if (!strchr(p
, ' ') &&
3146 lookup_commit_reference_by_name(p
)) &&
3148 /* found by commit name */
3149 i2
= (struct todo_item
*)commit2
->util
3152 /* copy can be a prefix of the commit subject */
3153 for (i2
= 0; i2
< i
; i2
++)
3155 starts_with(subjects
[i2
], p
))
3163 todo_list
.items
[i
].command
=
3164 starts_with(subject
, "fixup!") ?
3165 TODO_FIXUP
: TODO_SQUASH
;
3171 } else if (!hashmap_get_from_hash(&subject2item
,
3172 strhash(subject
), subject
)) {
3173 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
3175 hashmap_entry_init(entry
, strhash(entry
->subject
));
3176 hashmap_put(&subject2item
, entry
);
3181 struct strbuf buf
= STRBUF_INIT
;
3183 for (i
= 0; i
< todo_list
.nr
; i
++) {
3184 enum todo_command command
= todo_list
.items
[i
].command
;
3188 * Initially, all commands are 'pick's. If it is a
3189 * fixup or a squash now, we have rearranged it.
3191 if (is_fixup(command
))
3195 int offset
= todo_list
.items
[cur
].offset_in_buf
;
3196 int end_offset
= cur
+ 1 < todo_list
.nr
?
3197 todo_list
.items
[cur
+ 1].offset_in_buf
:
3199 char *bol
= todo_list
.buf
.buf
+ offset
;
3200 char *eol
= todo_list
.buf
.buf
+ end_offset
;
3202 /* replace 'pick', by 'fixup' or 'squash' */
3203 command
= todo_list
.items
[cur
].command
;
3204 if (is_fixup(command
)) {
3206 todo_command_info
[command
].str
);
3207 bol
+= strcspn(bol
, " \t");
3210 strbuf_add(&buf
, bol
, eol
- bol
);
3216 fd
= open(todo_file
, O_WRONLY
);
3218 res
= error_errno(_("could not open '%s'"), todo_file
);
3219 else if (write(fd
, buf
.buf
, buf
.len
) < 0)
3220 res
= error_errno(_("could not write to '%s'"), todo_file
);
3221 else if (ftruncate(fd
, buf
.len
) < 0)
3222 res
= error_errno(_("could not truncate '%s'"),
3225 strbuf_release(&buf
);
3230 for (i
= 0; i
< todo_list
.nr
; i
++)
3233 hashmap_free(&subject2item
, 1);
3234 todo_list_release(&todo_list
);