5 #include "object-store.h"
10 #include "run-command.h"
13 #include "cache-tree.h"
17 #include "merge-recursive.h"
19 #include "argv-array.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"
35 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
37 const char sign_off_header
[] = "Signed-off-by: ";
38 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
40 GIT_PATH_FUNC(git_path_commit_editmsg
, "COMMIT_EDITMSG")
42 GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
44 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
45 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
46 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
47 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
49 static GIT_PATH_FUNC(rebase_path
, "rebase-merge")
51 * The file containing rebase commands, comments, and empty lines.
52 * This file is created by "git rebase -i" then edited by the user. As
53 * the lines are processed, they are removed from the front of this
54 * file and written to the tail of 'done'.
56 static GIT_PATH_FUNC(rebase_path_todo
, "rebase-merge/git-rebase-todo")
58 * The rebase command lines that have already been processed. A line
59 * is moved here when it is first handled, before any associated user
62 static GIT_PATH_FUNC(rebase_path_done
, "rebase-merge/done")
64 * The file to keep track of how many commands were already processed (e.g.
67 static GIT_PATH_FUNC(rebase_path_msgnum
, "rebase-merge/msgnum")
69 * The file to keep track of how many commands are to be processed in total
70 * (e.g. for the prompt).
72 static GIT_PATH_FUNC(rebase_path_msgtotal
, "rebase-merge/end")
74 * The commit message that is planned to be used for any changes that
75 * need to be committed following a user interaction.
77 static GIT_PATH_FUNC(rebase_path_message
, "rebase-merge/message")
79 * The file into which is accumulated the suggested commit message for
80 * squash/fixup commands. When the first of a series of squash/fixups
81 * is seen, the file is created and the commit message from the
82 * previous commit and from the first squash/fixup commit are written
83 * to it. The commit message for each subsequent squash/fixup commit
84 * is appended to the file as it is processed.
86 static GIT_PATH_FUNC(rebase_path_squash_msg
, "rebase-merge/message-squash")
88 * If the current series of squash/fixups has not yet included a squash
89 * command, then this file exists and holds the commit message of the
90 * original "pick" commit. (If the series ends without a "squash"
91 * command, then this can be used as the commit message of the combined
92 * commit without opening the editor.)
94 static GIT_PATH_FUNC(rebase_path_fixup_msg
, "rebase-merge/message-fixup")
96 * This file contains the list fixup/squash commands that have been
97 * accumulated into message-fixup or message-squash so far.
99 static GIT_PATH_FUNC(rebase_path_current_fixups
, "rebase-merge/current-fixups")
101 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
102 * GIT_AUTHOR_DATE that will be used for the commit that is currently
105 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
107 * When an "edit" rebase command is being processed, the SHA1 of the
108 * commit to be edited is recorded in this file. When "git rebase
109 * --continue" is executed, if there are any staged changes then they
110 * will be amended to the HEAD commit, but only provided the HEAD
111 * commit is still the commit to be edited. When any other rebase
112 * command is processed, this file is deleted.
114 static GIT_PATH_FUNC(rebase_path_amend
, "rebase-merge/amend")
116 * When we stop at a given patch via the "edit" command, this file contains
117 * the abbreviated commit name of the corresponding patch.
119 static GIT_PATH_FUNC(rebase_path_stopped_sha
, "rebase-merge/stopped-sha")
121 * For the post-rewrite hook, we make a list of rewritten commits and
122 * their new sha1s. The rewritten-pending list keeps the sha1s of
123 * commits that have been processed, but not committed yet,
124 * e.g. because they are waiting for a 'squash' command.
126 static GIT_PATH_FUNC(rebase_path_rewritten_list
, "rebase-merge/rewritten-list")
127 static GIT_PATH_FUNC(rebase_path_rewritten_pending
,
128 "rebase-merge/rewritten-pending")
131 * The path of the file containig the OID of the "squash onto" commit, i.e.
132 * the dummy commit used for `reset [new root]`.
134 static GIT_PATH_FUNC(rebase_path_squash_onto
, "rebase-merge/squash-onto")
137 * The path of the file listing refs that need to be deleted after the rebase
138 * finishes. This is used by the `label` command to record the need for cleanup.
140 static GIT_PATH_FUNC(rebase_path_refs_to_delete
, "rebase-merge/refs-to-delete")
143 * The following files are written by git-rebase just after parsing the
144 * command-line (and are only consumed, not modified, by the sequencer).
146 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
147 static GIT_PATH_FUNC(rebase_path_orig_head
, "rebase-merge/orig-head")
148 static GIT_PATH_FUNC(rebase_path_verbose
, "rebase-merge/verbose")
149 static GIT_PATH_FUNC(rebase_path_signoff
, "rebase-merge/signoff")
150 static GIT_PATH_FUNC(rebase_path_head_name
, "rebase-merge/head-name")
151 static GIT_PATH_FUNC(rebase_path_onto
, "rebase-merge/onto")
152 static GIT_PATH_FUNC(rebase_path_autostash
, "rebase-merge/autostash")
153 static GIT_PATH_FUNC(rebase_path_strategy
, "rebase-merge/strategy")
154 static GIT_PATH_FUNC(rebase_path_strategy_opts
, "rebase-merge/strategy_opts")
155 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate
, "rebase-merge/allow_rerere_autoupdate")
157 static int git_sequencer_config(const char *k
, const char *v
, void *cb
)
159 struct replay_opts
*opts
= cb
;
162 if (!strcmp(k
, "commit.cleanup")) {
165 status
= git_config_string(&s
, k
, v
);
169 if (!strcmp(s
, "verbatim"))
170 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
171 else if (!strcmp(s
, "whitespace"))
172 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
173 else if (!strcmp(s
, "strip"))
174 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_ALL
;
175 else if (!strcmp(s
, "scissors"))
176 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_SPACE
;
178 warning(_("invalid commit message cleanup mode '%s'"),
185 if (!strcmp(k
, "commit.gpgsign")) {
186 opts
->gpg_sign
= git_config_bool(k
, v
) ? xstrdup("") : NULL
;
190 status
= git_gpg_config(k
, v
, NULL
);
194 return git_diff_basic_config(k
, v
, NULL
);
197 void sequencer_init_config(struct replay_opts
*opts
)
199 opts
->default_msg_cleanup
= COMMIT_MSG_CLEANUP_NONE
;
200 git_config(git_sequencer_config
, opts
);
203 static inline int is_rebase_i(const struct replay_opts
*opts
)
205 return opts
->action
== REPLAY_INTERACTIVE_REBASE
;
208 static const char *get_dir(const struct replay_opts
*opts
)
210 if (is_rebase_i(opts
))
211 return rebase_path();
212 return git_path_seq_dir();
215 static const char *get_todo_path(const struct replay_opts
*opts
)
217 if (is_rebase_i(opts
))
218 return rebase_path_todo();
219 return git_path_todo_file();
223 * Returns 0 for non-conforming footer
224 * Returns 1 for conforming footer
225 * Returns 2 when sob exists within conforming footer
226 * Returns 3 when sob exists within conforming footer as last entry
228 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
229 size_t ignore_footer
)
231 struct process_trailer_options opts
= PROCESS_TRAILER_OPTIONS_INIT
;
232 struct trailer_info info
;
234 int found_sob
= 0, found_sob_last
= 0;
238 trailer_info_get(&info
, sb
->buf
, &opts
);
240 if (info
.trailer_start
== info
.trailer_end
)
243 for (i
= 0; i
< info
.trailer_nr
; i
++)
244 if (sob
&& !strncmp(info
.trailers
[i
], sob
->buf
, sob
->len
)) {
246 if (i
== info
.trailer_nr
- 1)
250 trailer_info_release(&info
);
259 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
261 static struct strbuf buf
= STRBUF_INIT
;
265 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
269 int sequencer_remove_state(struct replay_opts
*opts
)
271 struct strbuf buf
= STRBUF_INIT
;
274 if (is_rebase_i(opts
) &&
275 strbuf_read_file(&buf
, rebase_path_refs_to_delete(), 0) > 0) {
278 char *eol
= strchr(p
, '\n');
281 if (delete_ref("(rebase -i) cleanup", p
, NULL
, 0) < 0)
282 warning(_("could not delete '%s'"), p
);
289 free(opts
->gpg_sign
);
290 free(opts
->strategy
);
291 for (i
= 0; i
< opts
->xopts_nr
; i
++)
292 free(opts
->xopts
[i
]);
294 strbuf_release(&opts
->current_fixups
);
297 strbuf_addstr(&buf
, get_dir(opts
));
298 remove_dir_recursively(&buf
, 0);
299 strbuf_release(&buf
);
304 static const char *action_name(const struct replay_opts
*opts
)
306 switch (opts
->action
) {
310 return N_("cherry-pick");
311 case REPLAY_INTERACTIVE_REBASE
:
312 return N_("rebase -i");
314 die(_("unknown action: %d"), opts
->action
);
317 struct commit_message
{
324 static const char *short_commit_name(struct commit
*commit
)
326 return find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
);
329 static int get_message(struct commit
*commit
, struct commit_message
*out
)
331 const char *abbrev
, *subject
;
334 out
->message
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
335 abbrev
= short_commit_name(commit
);
337 subject_len
= find_commit_subject(out
->message
, &subject
);
339 out
->subject
= xmemdupz(subject
, subject_len
);
340 out
->label
= xstrfmt("%s... %s", abbrev
, out
->subject
);
341 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
346 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
348 free(msg
->parent_label
);
351 unuse_commit_buffer(commit
, msg
->message
);
354 static void print_advice(int show_hint
, struct replay_opts
*opts
)
356 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
359 fprintf(stderr
, "%s\n", msg
);
361 * A conflict has occurred but the porcelain
362 * (typically rebase --interactive) wants to take care
363 * of the commit itself so remove CHERRY_PICK_HEAD
365 unlink(git_path_cherry_pick_head(the_repository
));
371 advise(_("after resolving the conflicts, mark the corrected paths\n"
372 "with 'git add <paths>' or 'git rm <paths>'"));
374 advise(_("after resolving the conflicts, mark the corrected paths\n"
375 "with 'git add <paths>' or 'git rm <paths>'\n"
376 "and commit the result with 'git commit'"));
380 static int write_message(const void *buf
, size_t len
, const char *filename
,
383 struct lock_file msg_file
= LOCK_INIT
;
385 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
387 return error_errno(_("could not lock '%s'"), filename
);
388 if (write_in_full(msg_fd
, buf
, len
) < 0) {
389 error_errno(_("could not write to '%s'"), filename
);
390 rollback_lock_file(&msg_file
);
393 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
394 error_errno(_("could not write eol to '%s'"), filename
);
395 rollback_lock_file(&msg_file
);
398 if (commit_lock_file(&msg_file
) < 0)
399 return error(_("failed to finalize '%s'"), filename
);
405 * Reads a file that was presumably written by a shell script, i.e. with an
406 * end-of-line marker that needs to be stripped.
408 * Note that only the last end-of-line marker is stripped, consistent with the
409 * behavior of "$(cat path)" in a shell script.
411 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
413 static int read_oneliner(struct strbuf
*buf
,
414 const char *path
, int skip_if_empty
)
416 int orig_len
= buf
->len
;
418 if (!file_exists(path
))
421 if (strbuf_read_file(buf
, path
, 0) < 0) {
422 warning_errno(_("could not read '%s'"), path
);
426 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
427 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
429 buf
->buf
[buf
->len
] = '\0';
432 if (skip_if_empty
&& buf
->len
== orig_len
)
438 static struct tree
*empty_tree(void)
440 return lookup_tree(the_repository
, the_repository
->hash_algo
->empty_tree
);
443 static int error_dirty_index(struct replay_opts
*opts
)
445 if (read_cache_unmerged())
446 return error_resolve_conflict(_(action_name(opts
)));
448 error(_("your local changes would be overwritten by %s."),
449 _(action_name(opts
)));
451 if (advice_commit_before_merge
)
452 advise(_("commit your changes or stash them to proceed."));
456 static void update_abort_safety_file(void)
458 struct object_id head
;
460 /* Do nothing on a single-pick */
461 if (!file_exists(git_path_seq_dir()))
464 if (!get_oid("HEAD", &head
))
465 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
467 write_file(git_path_abort_safety_file(), "%s", "");
470 static int fast_forward_to(const struct object_id
*to
, const struct object_id
*from
,
471 int unborn
, struct replay_opts
*opts
)
473 struct ref_transaction
*transaction
;
474 struct strbuf sb
= STRBUF_INIT
;
475 struct strbuf err
= STRBUF_INIT
;
478 if (checkout_fast_forward(from
, to
, 1))
479 return -1; /* the callee should have complained already */
481 strbuf_addf(&sb
, _("%s: fast-forward"), _(action_name(opts
)));
483 transaction
= ref_transaction_begin(&err
);
485 ref_transaction_update(transaction
, "HEAD",
486 to
, unborn
&& !is_rebase_i(opts
) ?
489 ref_transaction_commit(transaction
, &err
)) {
490 ref_transaction_free(transaction
);
491 error("%s", err
.buf
);
493 strbuf_release(&err
);
498 strbuf_release(&err
);
499 ref_transaction_free(transaction
);
500 update_abort_safety_file();
504 void append_conflicts_hint(struct strbuf
*msgbuf
)
508 strbuf_addch(msgbuf
, '\n');
509 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
510 for (i
= 0; i
< active_nr
;) {
511 const struct cache_entry
*ce
= active_cache
[i
++];
513 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
514 while (i
< active_nr
&& !strcmp(ce
->name
,
515 active_cache
[i
]->name
))
521 static int do_recursive_merge(struct commit
*base
, struct commit
*next
,
522 const char *base_label
, const char *next_label
,
523 struct object_id
*head
, struct strbuf
*msgbuf
,
524 struct replay_opts
*opts
)
526 struct merge_options o
;
527 struct tree
*result
, *next_tree
, *base_tree
, *head_tree
;
530 struct lock_file index_lock
= LOCK_INIT
;
532 if (hold_locked_index(&index_lock
, LOCK_REPORT_ON_ERROR
) < 0)
537 init_merge_options(&o
);
538 o
.ancestor
= base
? base_label
: "(empty tree)";
540 o
.branch2
= next
? next_label
: "(empty tree)";
541 if (is_rebase_i(opts
))
543 o
.show_rename_progress
= 1;
545 head_tree
= parse_tree_indirect(head
);
546 next_tree
= next
? get_commit_tree(next
) : empty_tree();
547 base_tree
= base
? get_commit_tree(base
) : empty_tree();
549 for (xopt
= opts
->xopts
; xopt
!= opts
->xopts
+ opts
->xopts_nr
; xopt
++)
550 parse_merge_opt(&o
, *xopt
);
552 clean
= merge_trees(&o
,
554 next_tree
, base_tree
, &result
);
555 if (is_rebase_i(opts
) && clean
<= 0)
556 fputs(o
.obuf
.buf
, stdout
);
557 strbuf_release(&o
.obuf
);
558 diff_warn_rename_limit("merge.renamelimit", o
.needed_rename_limit
, 0);
560 rollback_lock_file(&index_lock
);
564 if (write_locked_index(&the_index
, &index_lock
,
565 COMMIT_LOCK
| SKIP_IF_UNCHANGED
))
567 * TRANSLATORS: %s will be "revert", "cherry-pick" or
570 return error(_("%s: Unable to write new index file"),
571 _(action_name(opts
)));
574 append_conflicts_hint(msgbuf
);
579 static struct object_id
*get_cache_tree_oid(void)
581 if (!active_cache_tree
)
582 active_cache_tree
= cache_tree();
584 if (!cache_tree_fully_valid(active_cache_tree
))
585 if (cache_tree_update(&the_index
, 0)) {
586 error(_("unable to update cache tree"));
590 return &active_cache_tree
->oid
;
593 static int is_index_unchanged(void)
595 struct object_id head_oid
, *cache_tree_oid
;
596 struct commit
*head_commit
;
598 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
599 return error(_("could not resolve HEAD commit"));
601 head_commit
= lookup_commit(the_repository
, &head_oid
);
604 * If head_commit is NULL, check_commit, called from
605 * lookup_commit, would have indicated that head_commit is not
606 * a commit object already. parse_commit() will return failure
607 * without further complaints in such a case. Otherwise, if
608 * the commit is invalid, parse_commit() will complain. So
609 * there is nothing for us to say here. Just return failure.
611 if (parse_commit(head_commit
))
614 if (!(cache_tree_oid
= get_cache_tree_oid()))
617 return oideq(cache_tree_oid
, get_commit_tree_oid(head_commit
));
620 static int write_author_script(const char *message
)
622 struct strbuf buf
= STRBUF_INIT
;
627 if (!*message
|| starts_with(message
, "\n")) {
629 /* Missing 'author' line? */
630 unlink(rebase_path_author_script());
632 } else if (skip_prefix(message
, "author ", &message
))
634 else if ((eol
= strchr(message
, '\n')))
639 strbuf_addstr(&buf
, "GIT_AUTHOR_NAME='");
640 while (*message
&& *message
!= '\n' && *message
!= '\r')
641 if (skip_prefix(message
, " <", &message
))
643 else if (*message
!= '\'')
644 strbuf_addch(&buf
, *(message
++));
646 strbuf_addf(&buf
, "'\\%c'", *(message
++));
647 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_EMAIL='");
648 while (*message
&& *message
!= '\n' && *message
!= '\r')
649 if (skip_prefix(message
, "> ", &message
))
651 else if (*message
!= '\'')
652 strbuf_addch(&buf
, *(message
++));
654 strbuf_addf(&buf
, "'\\%c'", *(message
++));
655 strbuf_addstr(&buf
, "'\nGIT_AUTHOR_DATE='@");
656 while (*message
&& *message
!= '\n' && *message
!= '\r')
657 if (*message
!= '\'')
658 strbuf_addch(&buf
, *(message
++));
660 strbuf_addf(&buf
, "'\\%c'", *(message
++));
661 strbuf_addch(&buf
, '\'');
662 res
= write_message(buf
.buf
, buf
.len
, rebase_path_author_script(), 1);
663 strbuf_release(&buf
);
669 * write_author_script() used to fail to terminate the last line with a "'" and
670 * also escaped "'" incorrectly as "'\\\\''" rather than "'\\''". We check for
671 * the terminating "'" on the last line to see how "'" has been escaped in case
672 * git was upgraded while rebase was stopped.
674 static int quoting_is_broken(const char *s
, size_t n
)
676 /* Skip any empty lines in case the file was hand edited */
677 while (n
> 0 && s
[--n
] == '\n')
679 if (n
> 0 && s
[n
] != '\'')
686 * Read a list of environment variable assignments (such as the author-script
687 * file) into an environment block. Returns -1 on error, 0 otherwise.
689 static int read_env_script(struct argv_array
*env
)
691 struct strbuf script
= STRBUF_INIT
;
692 int i
, count
= 0, sq_bug
;
696 if (strbuf_read_file(&script
, rebase_path_author_script(), 256) <= 0)
698 /* write_author_script() used to quote incorrectly */
699 sq_bug
= quoting_is_broken(script
.buf
, script
.len
);
700 for (p
= script
.buf
; *p
; p
++)
701 if (sq_bug
&& skip_prefix(p
, "'\\\\''", &p2
))
702 strbuf_splice(&script
, p
- script
.buf
, p2
- p
, "'", 1);
703 else if (skip_prefix(p
, "'\\''", &p2
))
704 strbuf_splice(&script
, p
- script
.buf
, p2
- p
, "'", 1);
706 strbuf_splice(&script
, p
-- - script
.buf
, 1, "", 0);
707 else if (*p
== '\n') {
712 for (i
= 0, p
= script
.buf
; i
< count
; i
++) {
713 argv_array_push(env
, p
);
720 static char *get_author(const char *message
)
725 a
= find_commit_header(message
, "author", &len
);
727 return xmemdupz(a
, len
);
732 /* Read author-script and return an ident line (author <email> timestamp) */
733 static const char *read_author_ident(struct strbuf
*buf
)
735 const char *keys
[] = {
736 "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
738 struct strbuf out
= STRBUF_INIT
;
743 if (strbuf_read_file(buf
, rebase_path_author_script(), 256) <= 0)
746 /* dequote values and construct ident line in-place */
747 for (in
= buf
->buf
; i
< 3 && in
- buf
->buf
< buf
->len
; i
++) {
748 if (!skip_prefix(in
, keys
[i
], (const char **)&in
)) {
749 warning(_("could not parse '%s' (looking for '%s')"),
750 rebase_path_author_script(), keys
[i
]);
754 eol
= strchrnul(in
, '\n');
756 if (!sq_dequote(in
)) {
757 warning(_("bad quoting on %s value in '%s'"),
758 keys
[i
], rebase_path_author_script());
766 warning(_("could not parse '%s' (looking for '%s')"),
767 rebase_path_author_script(), keys
[i
]);
771 /* validate date since fmt_ident() will die() on bad value */
772 if (parse_date(val
[2], &out
)){
773 warning(_("invalid date format '%s' in '%s'"),
774 val
[2], rebase_path_author_script());
775 strbuf_release(&out
);
780 strbuf_addstr(&out
, fmt_ident(val
[0], val
[1], val
[2], 0));
781 strbuf_swap(buf
, &out
);
782 strbuf_release(&out
);
786 static const char staged_changes_advice
[] =
787 N_("you have staged changes in your working tree\n"
788 "If these changes are meant to be squashed into the previous commit, run:\n"
790 " git commit --amend %s\n"
792 "If they are meant to go into a new commit, run:\n"
796 "In both cases, once you're done, continue with:\n"
798 " git rebase --continue\n");
800 #define ALLOW_EMPTY (1<<0)
801 #define EDIT_MSG (1<<1)
802 #define AMEND_MSG (1<<2)
803 #define CLEANUP_MSG (1<<3)
804 #define VERIFY_MSG (1<<4)
805 #define CREATE_ROOT_COMMIT (1<<5)
808 * If we are cherry-pick, and if the merge did not result in
809 * hand-editing, we will hit this commit and inherit the original
810 * author date and name.
812 * If we are revert, or if our cherry-pick results in a hand merge,
813 * we had better say that the current user is responsible for that.
815 * An exception is when run_git_commit() is called during an
816 * interactive rebase: in that case, we will want to retain the
819 static int run_git_commit(const char *defmsg
, struct replay_opts
*opts
,
822 struct child_process cmd
= CHILD_PROCESS_INIT
;
825 if ((flags
& CREATE_ROOT_COMMIT
) && !(flags
& AMEND_MSG
)) {
826 struct strbuf msg
= STRBUF_INIT
, script
= STRBUF_INIT
;
827 const char *author
= NULL
;
828 struct object_id root_commit
, *cache_tree_oid
;
831 if (is_rebase_i(opts
)) {
832 author
= read_author_ident(&script
);
834 strbuf_release(&script
);
840 BUG("root commit without message");
842 if (!(cache_tree_oid
= get_cache_tree_oid()))
846 res
= strbuf_read_file(&msg
, defmsg
, 0);
849 res
= error_errno(_("could not read '%s'"), defmsg
);
851 res
= commit_tree(msg
.buf
, msg
.len
, cache_tree_oid
,
852 NULL
, &root_commit
, author
,
855 strbuf_release(&msg
);
856 strbuf_release(&script
);
858 update_ref(NULL
, "CHERRY_PICK_HEAD", &root_commit
, NULL
,
859 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
);
860 res
= update_ref(NULL
, "HEAD", &root_commit
, NULL
, 0,
861 UPDATE_REFS_MSG_ON_ERR
);
863 return res
< 0 ? error(_("writing root commit")) : 0;
868 if (is_rebase_i(opts
)) {
869 if (!(flags
& EDIT_MSG
)) {
870 cmd
.stdout_to_stderr
= 1;
874 if (read_env_script(&cmd
.env_array
)) {
875 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
877 return error(_(staged_changes_advice
),
882 argv_array_push(&cmd
.args
, "commit");
884 if (!(flags
& VERIFY_MSG
))
885 argv_array_push(&cmd
.args
, "-n");
886 if ((flags
& AMEND_MSG
))
887 argv_array_push(&cmd
.args
, "--amend");
889 argv_array_pushf(&cmd
.args
, "-S%s", opts
->gpg_sign
);
891 argv_array_pushl(&cmd
.args
, "-F", defmsg
, NULL
);
892 else if (!(flags
& EDIT_MSG
))
893 argv_array_pushl(&cmd
.args
, "-C", "HEAD", NULL
);
894 if ((flags
& CLEANUP_MSG
))
895 argv_array_push(&cmd
.args
, "--cleanup=strip");
896 if ((flags
& EDIT_MSG
))
897 argv_array_push(&cmd
.args
, "-e");
898 else if (!(flags
& CLEANUP_MSG
) &&
899 !opts
->signoff
&& !opts
->record_origin
&&
900 git_config_get_value("commit.cleanup", &value
))
901 argv_array_push(&cmd
.args
, "--cleanup=verbatim");
903 if ((flags
& ALLOW_EMPTY
))
904 argv_array_push(&cmd
.args
, "--allow-empty");
906 if (!(flags
& EDIT_MSG
))
907 argv_array_push(&cmd
.args
, "--allow-empty-message");
910 /* hide stderr on success */
911 struct strbuf buf
= STRBUF_INIT
;
912 int rc
= pipe_command(&cmd
,
914 /* stdout is already redirected */
918 fputs(buf
.buf
, stderr
);
919 strbuf_release(&buf
);
923 return run_command(&cmd
);
926 static int rest_is_empty(const struct strbuf
*sb
, int start
)
931 /* Check if the rest is just whitespace and Signed-off-by's. */
932 for (i
= start
; i
< sb
->len
; i
++) {
933 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
939 if (strlen(sign_off_header
) <= eol
- i
&&
940 starts_with(sb
->buf
+ i
, sign_off_header
)) {
945 if (!isspace(sb
->buf
[i
++]))
953 * Find out if the message in the strbuf contains only whitespace and
954 * Signed-off-by lines.
956 int message_is_empty(const struct strbuf
*sb
,
957 enum commit_msg_cleanup_mode cleanup_mode
)
959 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
961 return rest_is_empty(sb
, 0);
965 * See if the user edited the message in the editor or left what
966 * was in the template intact
968 int template_untouched(const struct strbuf
*sb
, const char *template_file
,
969 enum commit_msg_cleanup_mode cleanup_mode
)
971 struct strbuf tmpl
= STRBUF_INIT
;
974 if (cleanup_mode
== COMMIT_MSG_CLEANUP_NONE
&& sb
->len
)
977 if (!template_file
|| strbuf_read_file(&tmpl
, template_file
, 0) <= 0)
980 strbuf_stripspace(&tmpl
, cleanup_mode
== COMMIT_MSG_CLEANUP_ALL
);
981 if (!skip_prefix(sb
->buf
, tmpl
.buf
, &start
))
983 strbuf_release(&tmpl
);
984 return rest_is_empty(sb
, start
- sb
->buf
);
987 int update_head_with_reflog(const struct commit
*old_head
,
988 const struct object_id
*new_head
,
989 const char *action
, const struct strbuf
*msg
,
992 struct ref_transaction
*transaction
;
993 struct strbuf sb
= STRBUF_INIT
;
998 strbuf_addstr(&sb
, action
);
999 strbuf_addstr(&sb
, ": ");
1002 nl
= strchr(msg
->buf
, '\n');
1004 strbuf_add(&sb
, msg
->buf
, nl
+ 1 - msg
->buf
);
1006 strbuf_addbuf(&sb
, msg
);
1007 strbuf_addch(&sb
, '\n');
1010 transaction
= ref_transaction_begin(err
);
1012 ref_transaction_update(transaction
, "HEAD", new_head
,
1013 old_head
? &old_head
->object
.oid
: &null_oid
,
1015 ref_transaction_commit(transaction
, err
)) {
1018 ref_transaction_free(transaction
);
1019 strbuf_release(&sb
);
1024 static int run_rewrite_hook(const struct object_id
*oldoid
,
1025 const struct object_id
*newoid
)
1027 struct child_process proc
= CHILD_PROCESS_INIT
;
1028 const char *argv
[3];
1030 struct strbuf sb
= STRBUF_INIT
;
1032 argv
[0] = find_hook("post-rewrite");
1041 proc
.stdout_to_stderr
= 1;
1043 code
= start_command(&proc
);
1046 strbuf_addf(&sb
, "%s %s\n", oid_to_hex(oldoid
), oid_to_hex(newoid
));
1047 sigchain_push(SIGPIPE
, SIG_IGN
);
1048 write_in_full(proc
.in
, sb
.buf
, sb
.len
);
1050 strbuf_release(&sb
);
1051 sigchain_pop(SIGPIPE
);
1052 return finish_command(&proc
);
1055 void commit_post_rewrite(const struct commit
*old_head
,
1056 const struct object_id
*new_head
)
1058 struct notes_rewrite_cfg
*cfg
;
1060 cfg
= init_copy_notes_for_rewrite("amend");
1062 /* we are amending, so old_head is not NULL */
1063 copy_note_for_rewrite(cfg
, &old_head
->object
.oid
, new_head
);
1064 finish_copy_notes_for_rewrite(cfg
, "Notes added by 'git commit --amend'");
1066 run_rewrite_hook(&old_head
->object
.oid
, new_head
);
1069 static int run_prepare_commit_msg_hook(struct strbuf
*msg
, const char *commit
)
1071 struct argv_array hook_env
= ARGV_ARRAY_INIT
;
1075 name
= git_path_commit_editmsg();
1076 if (write_message(msg
->buf
, msg
->len
, name
, 0))
1079 argv_array_pushf(&hook_env
, "GIT_INDEX_FILE=%s", get_index_file());
1080 argv_array_push(&hook_env
, "GIT_EDITOR=:");
1082 ret
= run_hook_le(hook_env
.argv
, "prepare-commit-msg", name
,
1083 "commit", commit
, NULL
);
1085 ret
= run_hook_le(hook_env
.argv
, "prepare-commit-msg", name
,
1088 ret
= error(_("'prepare-commit-msg' hook failed"));
1089 argv_array_clear(&hook_env
);
1094 static const char implicit_ident_advice_noconfig
[] =
1095 N_("Your name and email address were configured automatically based\n"
1096 "on your username and hostname. Please check that they are accurate.\n"
1097 "You can suppress this message by setting them explicitly. Run the\n"
1098 "following command and follow the instructions in your editor to edit\n"
1099 "your configuration file:\n"
1101 " git config --global --edit\n"
1103 "After doing this, you may fix the identity used for this commit with:\n"
1105 " git commit --amend --reset-author\n");
1107 static const char implicit_ident_advice_config
[] =
1108 N_("Your name and email address were configured automatically based\n"
1109 "on your username and hostname. Please check that they are accurate.\n"
1110 "You can suppress this message by setting them explicitly:\n"
1112 " git config --global user.name \"Your Name\"\n"
1113 " git config --global user.email you@example.com\n"
1115 "After doing this, you may fix the identity used for this commit with:\n"
1117 " git commit --amend --reset-author\n");
1119 static const char *implicit_ident_advice(void)
1121 char *user_config
= expand_user_path("~/.gitconfig", 0);
1122 char *xdg_config
= xdg_config_home("config");
1123 int config_exists
= file_exists(user_config
) || file_exists(xdg_config
);
1129 return _(implicit_ident_advice_config
);
1131 return _(implicit_ident_advice_noconfig
);
1135 void print_commit_summary(const char *prefix
, const struct object_id
*oid
,
1138 struct rev_info rev
;
1139 struct commit
*commit
;
1140 struct strbuf format
= STRBUF_INIT
;
1142 struct pretty_print_context pctx
= {0};
1143 struct strbuf author_ident
= STRBUF_INIT
;
1144 struct strbuf committer_ident
= STRBUF_INIT
;
1146 commit
= lookup_commit(the_repository
, oid
);
1148 die(_("couldn't look up newly created commit"));
1149 if (parse_commit(commit
))
1150 die(_("could not parse newly created commit"));
1152 strbuf_addstr(&format
, "format:%h] %s");
1154 format_commit_message(commit
, "%an <%ae>", &author_ident
, &pctx
);
1155 format_commit_message(commit
, "%cn <%ce>", &committer_ident
, &pctx
);
1156 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1157 strbuf_addstr(&format
, "\n Author: ");
1158 strbuf_addbuf_percentquote(&format
, &author_ident
);
1160 if (flags
& SUMMARY_SHOW_AUTHOR_DATE
) {
1161 struct strbuf date
= STRBUF_INIT
;
1163 format_commit_message(commit
, "%ad", &date
, &pctx
);
1164 strbuf_addstr(&format
, "\n Date: ");
1165 strbuf_addbuf_percentquote(&format
, &date
);
1166 strbuf_release(&date
);
1168 if (!committer_ident_sufficiently_given()) {
1169 strbuf_addstr(&format
, "\n Committer: ");
1170 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1171 if (advice_implicit_identity
) {
1172 strbuf_addch(&format
, '\n');
1173 strbuf_addstr(&format
, implicit_ident_advice());
1176 strbuf_release(&author_ident
);
1177 strbuf_release(&committer_ident
);
1179 init_revisions(&rev
, prefix
);
1180 setup_revisions(0, NULL
, &rev
, NULL
);
1183 rev
.diffopt
.output_format
=
1184 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1186 rev
.verbose_header
= 1;
1187 rev
.show_root_diff
= 1;
1188 get_commit_format(format
.buf
, &rev
);
1189 rev
.always_show_header
= 0;
1190 rev
.diffopt
.detect_rename
= DIFF_DETECT_RENAME
;
1191 rev
.diffopt
.break_opt
= 0;
1192 diff_setup_done(&rev
.diffopt
);
1194 head
= resolve_ref_unsafe("HEAD", 0, NULL
, NULL
);
1196 die_errno(_("unable to resolve HEAD after creating commit"));
1197 if (!strcmp(head
, "HEAD"))
1198 head
= _("detached HEAD");
1200 skip_prefix(head
, "refs/heads/", &head
);
1201 printf("[%s%s ", head
, (flags
& SUMMARY_INITIAL_COMMIT
) ?
1202 _(" (root-commit)") : "");
1204 if (!log_tree_commit(&rev
, commit
)) {
1205 rev
.always_show_header
= 1;
1206 rev
.use_terminator
= 1;
1207 log_tree_commit(&rev
, commit
);
1210 strbuf_release(&format
);
1213 static int parse_head(struct commit
**head
)
1215 struct commit
*current_head
;
1216 struct object_id oid
;
1218 if (get_oid("HEAD", &oid
)) {
1219 current_head
= NULL
;
1221 current_head
= lookup_commit_reference(the_repository
, &oid
);
1223 return error(_("could not parse HEAD"));
1224 if (!oideq(&oid
, ¤t_head
->object
.oid
)) {
1225 warning(_("HEAD %s is not a commit!"),
1228 if (parse_commit(current_head
))
1229 return error(_("could not parse HEAD commit"));
1231 *head
= current_head
;
1237 * Try to commit without forking 'git commit'. In some cases we need
1238 * to run 'git commit' to display an error message
1241 * -1 - error unable to commit
1243 * 1 - run 'git commit'
1245 static int try_to_commit(struct strbuf
*msg
, const char *author
,
1246 struct replay_opts
*opts
, unsigned int flags
,
1247 struct object_id
*oid
)
1249 struct object_id tree
;
1250 struct commit
*current_head
;
1251 struct commit_list
*parents
= NULL
;
1252 struct commit_extra_header
*extra
= NULL
;
1253 struct strbuf err
= STRBUF_INIT
;
1254 struct strbuf commit_msg
= STRBUF_INIT
;
1255 char *amend_author
= NULL
;
1256 const char *hook_commit
= NULL
;
1257 enum commit_msg_cleanup_mode cleanup
;
1260 if (parse_head(¤t_head
))
1263 if (flags
& AMEND_MSG
) {
1264 const char *exclude_gpgsig
[] = { "gpgsig", NULL
};
1265 const char *out_enc
= get_commit_output_encoding();
1266 const char *message
= logmsg_reencode(current_head
, NULL
,
1270 const char *orig_message
= NULL
;
1272 find_commit_subject(message
, &orig_message
);
1274 strbuf_addstr(msg
, orig_message
);
1275 hook_commit
= "HEAD";
1277 author
= amend_author
= get_author(message
);
1278 unuse_commit_buffer(current_head
, message
);
1280 res
= error(_("unable to parse commit author"));
1283 parents
= copy_commit_list(current_head
->parents
);
1284 extra
= read_commit_extra_headers(current_head
, exclude_gpgsig
);
1285 } else if (current_head
) {
1286 commit_list_insert(current_head
, &parents
);
1289 if (write_index_as_tree(&tree
, &the_index
, get_index_file(), 0, NULL
)) {
1290 res
= error(_("git write-tree failed to write a tree"));
1294 if (!(flags
& ALLOW_EMPTY
) && oideq(current_head
?
1295 get_commit_tree_oid(current_head
) :
1296 the_hash_algo
->empty_tree
, &tree
)) {
1297 res
= 1; /* run 'git commit' to display error message */
1301 if (find_hook("prepare-commit-msg")) {
1302 res
= run_prepare_commit_msg_hook(msg
, hook_commit
);
1305 if (strbuf_read_file(&commit_msg
, git_path_commit_editmsg(),
1307 res
= error_errno(_("unable to read commit message "
1309 git_path_commit_editmsg());
1315 cleanup
= (flags
& CLEANUP_MSG
) ? COMMIT_MSG_CLEANUP_ALL
:
1316 opts
->default_msg_cleanup
;
1318 if (cleanup
!= COMMIT_MSG_CLEANUP_NONE
)
1319 strbuf_stripspace(msg
, cleanup
== COMMIT_MSG_CLEANUP_ALL
);
1320 if ((flags
& EDIT_MSG
) && message_is_empty(msg
, cleanup
)) {
1321 res
= 1; /* run 'git commit' to display error message */
1327 if (commit_tree_extended(msg
->buf
, msg
->len
, &tree
, parents
,
1328 oid
, author
, opts
->gpg_sign
, extra
)) {
1329 res
= error(_("failed to write commit object"));
1333 if (update_head_with_reflog(current_head
, oid
,
1334 getenv("GIT_REFLOG_ACTION"), msg
, &err
)) {
1335 res
= error("%s", err
.buf
);
1339 if (flags
& AMEND_MSG
)
1340 commit_post_rewrite(current_head
, oid
);
1343 free_commit_extra_headers(extra
);
1344 strbuf_release(&err
);
1345 strbuf_release(&commit_msg
);
1351 static int do_commit(const char *msg_file
, const char *author
,
1352 struct replay_opts
*opts
, unsigned int flags
)
1356 if (!(flags
& EDIT_MSG
) && !(flags
& VERIFY_MSG
) &&
1357 !(flags
& CREATE_ROOT_COMMIT
)) {
1358 struct object_id oid
;
1359 struct strbuf sb
= STRBUF_INIT
;
1361 if (msg_file
&& strbuf_read_file(&sb
, msg_file
, 2048) < 0)
1362 return error_errno(_("unable to read commit message "
1366 res
= try_to_commit(msg_file
? &sb
: NULL
, author
, opts
, flags
,
1368 strbuf_release(&sb
);
1370 unlink(git_path_cherry_pick_head(the_repository
));
1371 unlink(git_path_merge_msg(the_repository
));
1372 if (!is_rebase_i(opts
))
1373 print_commit_summary(NULL
, &oid
,
1374 SUMMARY_SHOW_AUTHOR_DATE
);
1379 return run_git_commit(msg_file
, opts
, flags
);
1384 static int is_original_commit_empty(struct commit
*commit
)
1386 const struct object_id
*ptree_oid
;
1388 if (parse_commit(commit
))
1389 return error(_("could not parse commit %s"),
1390 oid_to_hex(&commit
->object
.oid
));
1391 if (commit
->parents
) {
1392 struct commit
*parent
= commit
->parents
->item
;
1393 if (parse_commit(parent
))
1394 return error(_("could not parse parent commit %s"),
1395 oid_to_hex(&parent
->object
.oid
));
1396 ptree_oid
= get_commit_tree_oid(parent
);
1398 ptree_oid
= the_hash_algo
->empty_tree
; /* commit is root */
1401 return oideq(ptree_oid
, get_commit_tree_oid(commit
));
1405 * Do we run "git commit" with "--allow-empty"?
1407 static int allow_empty(struct replay_opts
*opts
, struct commit
*commit
)
1409 int index_unchanged
, empty_commit
;
1414 * (1) we do not allow empty at all and error out.
1416 * (2) we allow ones that were initially empty, but
1417 * forbid the ones that become empty;
1419 * (3) we allow both.
1421 if (!opts
->allow_empty
)
1422 return 0; /* let "git commit" barf as necessary */
1424 index_unchanged
= is_index_unchanged();
1425 if (index_unchanged
< 0)
1426 return index_unchanged
;
1427 if (!index_unchanged
)
1428 return 0; /* we do not have to say --allow-empty */
1430 if (opts
->keep_redundant_commits
)
1433 empty_commit
= is_original_commit_empty(commit
);
1434 if (empty_commit
< 0)
1435 return empty_commit
;
1443 * Note that ordering matters in this enum. Not only must it match the mapping
1444 * below, it is also divided into several sections that matter. When adding
1445 * new commands, make sure you add it in the right section.
1448 /* commands that handle commits */
1455 /* commands that do something else than handling a single commit */
1460 /* commands that do nothing but are counted for reporting progress */
1463 /* comments (not counted for reporting progress) */
1470 } todo_command_info
[] = {
1486 static const char *command_to_string(const enum todo_command command
)
1488 if (command
< TODO_COMMENT
)
1489 return todo_command_info
[command
].str
;
1490 die(_("unknown command: %d"), command
);
1493 static char command_to_char(const enum todo_command command
)
1495 if (command
< TODO_COMMENT
&& todo_command_info
[command
].c
)
1496 return todo_command_info
[command
].c
;
1497 return comment_line_char
;
1500 static int is_noop(const enum todo_command command
)
1502 return TODO_NOOP
<= command
;
1505 static int is_fixup(enum todo_command command
)
1507 return command
== TODO_FIXUP
|| command
== TODO_SQUASH
;
1510 /* Does this command create a (non-merge) commit? */
1511 static int is_pick_or_similar(enum todo_command command
)
1526 static int update_squash_messages(enum todo_command command
,
1527 struct commit
*commit
, struct replay_opts
*opts
)
1529 struct strbuf buf
= STRBUF_INIT
;
1531 const char *message
, *body
;
1533 if (opts
->current_fixup_count
> 0) {
1534 struct strbuf header
= STRBUF_INIT
;
1537 if (strbuf_read_file(&buf
, rebase_path_squash_msg(), 9) <= 0)
1538 return error(_("could not read '%s'"),
1539 rebase_path_squash_msg());
1541 eol
= buf
.buf
[0] != comment_line_char
?
1542 buf
.buf
: strchrnul(buf
.buf
, '\n');
1544 strbuf_addf(&header
, "%c ", comment_line_char
);
1545 strbuf_addf(&header
, _("This is a combination of %d commits."),
1546 opts
->current_fixup_count
+ 2);
1547 strbuf_splice(&buf
, 0, eol
- buf
.buf
, header
.buf
, header
.len
);
1548 strbuf_release(&header
);
1550 struct object_id head
;
1551 struct commit
*head_commit
;
1552 const char *head_message
, *body
;
1554 if (get_oid("HEAD", &head
))
1555 return error(_("need a HEAD to fixup"));
1556 if (!(head_commit
= lookup_commit_reference(the_repository
, &head
)))
1557 return error(_("could not read HEAD"));
1558 if (!(head_message
= get_commit_buffer(head_commit
, NULL
)))
1559 return error(_("could not read HEAD's commit message"));
1561 find_commit_subject(head_message
, &body
);
1562 if (write_message(body
, strlen(body
),
1563 rebase_path_fixup_msg(), 0)) {
1564 unuse_commit_buffer(head_commit
, head_message
);
1565 return error(_("cannot write '%s'"),
1566 rebase_path_fixup_msg());
1569 strbuf_addf(&buf
, "%c ", comment_line_char
);
1570 strbuf_addf(&buf
, _("This is a combination of %d commits."), 2);
1571 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1572 strbuf_addstr(&buf
, _("This is the 1st commit message:"));
1573 strbuf_addstr(&buf
, "\n\n");
1574 strbuf_addstr(&buf
, body
);
1576 unuse_commit_buffer(head_commit
, head_message
);
1579 if (!(message
= get_commit_buffer(commit
, NULL
)))
1580 return error(_("could not read commit message of %s"),
1581 oid_to_hex(&commit
->object
.oid
));
1582 find_commit_subject(message
, &body
);
1584 if (command
== TODO_SQUASH
) {
1585 unlink(rebase_path_fixup_msg());
1586 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1587 strbuf_addf(&buf
, _("This is the commit message #%d:"),
1588 ++opts
->current_fixup_count
+ 1);
1589 strbuf_addstr(&buf
, "\n\n");
1590 strbuf_addstr(&buf
, body
);
1591 } else if (command
== TODO_FIXUP
) {
1592 strbuf_addf(&buf
, "\n%c ", comment_line_char
);
1593 strbuf_addf(&buf
, _("The commit message #%d will be skipped:"),
1594 ++opts
->current_fixup_count
+ 1);
1595 strbuf_addstr(&buf
, "\n\n");
1596 strbuf_add_commented_lines(&buf
, body
, strlen(body
));
1598 return error(_("unknown command: %d"), command
);
1599 unuse_commit_buffer(commit
, message
);
1601 res
= write_message(buf
.buf
, buf
.len
, rebase_path_squash_msg(), 0);
1602 strbuf_release(&buf
);
1605 strbuf_addf(&opts
->current_fixups
, "%s%s %s",
1606 opts
->current_fixups
.len
? "\n" : "",
1607 command_to_string(command
),
1608 oid_to_hex(&commit
->object
.oid
));
1609 res
= write_message(opts
->current_fixups
.buf
,
1610 opts
->current_fixups
.len
,
1611 rebase_path_current_fixups(), 0);
1617 static void flush_rewritten_pending(void) {
1618 struct strbuf buf
= STRBUF_INIT
;
1619 struct object_id newoid
;
1622 if (strbuf_read_file(&buf
, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ
+ 1) * 2) > 0 &&
1623 !get_oid("HEAD", &newoid
) &&
1624 (out
= fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1625 char *bol
= buf
.buf
, *eol
;
1628 eol
= strchrnul(bol
, '\n');
1629 fprintf(out
, "%.*s %s\n", (int)(eol
- bol
),
1630 bol
, oid_to_hex(&newoid
));
1636 unlink(rebase_path_rewritten_pending());
1638 strbuf_release(&buf
);
1641 static void record_in_rewritten(struct object_id
*oid
,
1642 enum todo_command next_command
) {
1643 FILE *out
= fopen_or_warn(rebase_path_rewritten_pending(), "a");
1648 fprintf(out
, "%s\n", oid_to_hex(oid
));
1651 if (!is_fixup(next_command
))
1652 flush_rewritten_pending();
1655 static int do_pick_commit(enum todo_command command
, struct commit
*commit
,
1656 struct replay_opts
*opts
, int final_fixup
)
1658 unsigned int flags
= opts
->edit
? EDIT_MSG
: 0;
1659 const char *msg_file
= opts
->edit
? NULL
: git_path_merge_msg(the_repository
);
1660 struct object_id head
;
1661 struct commit
*base
, *next
, *parent
;
1662 const char *base_label
, *next_label
;
1663 char *author
= NULL
;
1664 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
1665 struct strbuf msgbuf
= STRBUF_INIT
;
1666 int res
, unborn
= 0, allow
;
1668 if (opts
->no_commit
) {
1670 * We do not intend to commit immediately. We just want to
1671 * merge the differences in, so let's compute the tree
1672 * that represents the "current" state for merge-recursive
1675 if (write_index_as_tree(&head
, &the_index
, get_index_file(), 0, NULL
))
1676 return error(_("your index file is unmerged."));
1678 unborn
= get_oid("HEAD", &head
);
1679 /* Do we want to generate a root commit? */
1680 if (is_pick_or_similar(command
) && opts
->have_squash_onto
&&
1681 oideq(&head
, &opts
->squash_onto
)) {
1682 if (is_fixup(command
))
1683 return error(_("cannot fixup root commit"));
1684 flags
|= CREATE_ROOT_COMMIT
;
1687 oidcpy(&head
, the_hash_algo
->empty_tree
);
1688 if (index_differs_from(unborn
? empty_tree_oid_hex() : "HEAD",
1690 return error_dirty_index(opts
);
1694 if (!commit
->parents
)
1696 else if (commit
->parents
->next
) {
1697 /* Reverting or cherry-picking a merge commit */
1699 struct commit_list
*p
;
1701 if (!opts
->mainline
)
1702 return error(_("commit %s is a merge but no -m option was given."),
1703 oid_to_hex(&commit
->object
.oid
));
1705 for (cnt
= 1, p
= commit
->parents
;
1706 cnt
!= opts
->mainline
&& p
;
1709 if (cnt
!= opts
->mainline
|| !p
)
1710 return error(_("commit %s does not have parent %d"),
1711 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
1713 } else if (0 < opts
->mainline
)
1714 return error(_("mainline was specified but commit %s is not a merge."),
1715 oid_to_hex(&commit
->object
.oid
));
1717 parent
= commit
->parents
->item
;
1719 if (get_message(commit
, &msg
) != 0)
1720 return error(_("cannot get commit message for %s"),
1721 oid_to_hex(&commit
->object
.oid
));
1723 if (opts
->allow_ff
&& !is_fixup(command
) &&
1724 ((parent
&& oideq(&parent
->object
.oid
, &head
)) ||
1725 (!parent
&& unborn
))) {
1726 if (is_rebase_i(opts
))
1727 write_author_script(msg
.message
);
1728 res
= fast_forward_to(&commit
->object
.oid
, &head
, unborn
,
1730 if (res
|| command
!= TODO_REWORD
)
1732 flags
|= EDIT_MSG
| AMEND_MSG
| VERIFY_MSG
;
1734 goto fast_forward_edit
;
1736 if (parent
&& parse_commit(parent
) < 0)
1737 /* TRANSLATORS: The first %s will be a "todo" command like
1738 "revert" or "pick", the second %s a SHA1. */
1739 return error(_("%s: cannot parse parent commit %s"),
1740 command_to_string(command
),
1741 oid_to_hex(&parent
->object
.oid
));
1744 * "commit" is an existing commit. We would want to apply
1745 * the difference it introduces since its first parent "prev"
1746 * on top of the current HEAD if we are cherry-pick. Or the
1747 * reverse of it if we are revert.
1750 if (command
== TODO_REVERT
) {
1752 base_label
= msg
.label
;
1754 next_label
= msg
.parent_label
;
1755 strbuf_addstr(&msgbuf
, "Revert \"");
1756 strbuf_addstr(&msgbuf
, msg
.subject
);
1757 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
1758 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
1760 if (commit
->parents
&& commit
->parents
->next
) {
1761 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
1762 strbuf_addstr(&msgbuf
, oid_to_hex(&parent
->object
.oid
));
1764 strbuf_addstr(&msgbuf
, ".\n");
1769 base_label
= msg
.parent_label
;
1771 next_label
= msg
.label
;
1773 /* Append the commit log message to msgbuf. */
1774 if (find_commit_subject(msg
.message
, &p
))
1775 strbuf_addstr(&msgbuf
, p
);
1777 if (opts
->record_origin
) {
1778 strbuf_complete_line(&msgbuf
);
1779 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
1780 strbuf_addch(&msgbuf
, '\n');
1781 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
1782 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
1783 strbuf_addstr(&msgbuf
, ")\n");
1785 if (!is_fixup(command
))
1786 author
= get_author(msg
.message
);
1789 if (command
== TODO_REWORD
)
1790 flags
|= EDIT_MSG
| VERIFY_MSG
;
1791 else if (is_fixup(command
)) {
1792 if (update_squash_messages(command
, commit
, opts
))
1796 msg_file
= rebase_path_squash_msg();
1797 else if (file_exists(rebase_path_fixup_msg())) {
1798 flags
|= CLEANUP_MSG
;
1799 msg_file
= rebase_path_fixup_msg();
1801 const char *dest
= git_path_squash_msg(the_repository
);
1803 if (copy_file(dest
, rebase_path_squash_msg(), 0666))
1804 return error(_("could not rename '%s' to '%s'"),
1805 rebase_path_squash_msg(), dest
);
1806 unlink(git_path_merge_msg(the_repository
));
1812 if (opts
->signoff
&& !is_fixup(command
))
1813 append_signoff(&msgbuf
, 0, 0);
1815 if (is_rebase_i(opts
) && write_author_script(msg
.message
) < 0)
1817 else if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || command
== TODO_REVERT
) {
1818 res
= do_recursive_merge(base
, next
, base_label
, next_label
,
1819 &head
, &msgbuf
, opts
);
1823 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
1824 git_path_merge_msg(the_repository
), 0);
1826 struct commit_list
*common
= NULL
;
1827 struct commit_list
*remotes
= NULL
;
1829 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
1830 git_path_merge_msg(the_repository
), 0);
1832 commit_list_insert(base
, &common
);
1833 commit_list_insert(next
, &remotes
);
1834 res
|= try_merge_command(opts
->strategy
,
1835 opts
->xopts_nr
, (const char **)opts
->xopts
,
1836 common
, oid_to_hex(&head
), remotes
);
1837 free_commit_list(common
);
1838 free_commit_list(remotes
);
1840 strbuf_release(&msgbuf
);
1843 * If the merge was clean or if it failed due to conflict, we write
1844 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1845 * However, if the merge did not even start, then we don't want to
1848 if (command
== TODO_PICK
&& !opts
->no_commit
&& (res
== 0 || res
== 1) &&
1849 update_ref(NULL
, "CHERRY_PICK_HEAD", &commit
->object
.oid
, NULL
,
1850 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1852 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
1853 update_ref(NULL
, "REVERT_HEAD", &commit
->object
.oid
, NULL
,
1854 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
1858 error(command
== TODO_REVERT
1859 ? _("could not revert %s... %s")
1860 : _("could not apply %s... %s"),
1861 short_commit_name(commit
), msg
.subject
);
1862 print_advice(res
== 1, opts
);
1863 rerere(opts
->allow_rerere_auto
);
1867 allow
= allow_empty(opts
, commit
);
1872 flags
|= ALLOW_EMPTY
;
1873 if (!opts
->no_commit
) {
1875 if (author
|| command
== TODO_REVERT
|| (flags
& AMEND_MSG
))
1876 res
= do_commit(msg_file
, author
, opts
, flags
);
1878 res
= error(_("unable to parse commit author"));
1881 if (!res
&& final_fixup
) {
1882 unlink(rebase_path_fixup_msg());
1883 unlink(rebase_path_squash_msg());
1884 unlink(rebase_path_current_fixups());
1885 strbuf_reset(&opts
->current_fixups
);
1886 opts
->current_fixup_count
= 0;
1890 free_message(commit
, &msg
);
1892 update_abort_safety_file();
1897 static int prepare_revs(struct replay_opts
*opts
)
1900 * picking (but not reverting) ranges (but not individual revisions)
1901 * should be done in reverse
1903 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
1904 opts
->revs
->reverse
^= 1;
1906 if (prepare_revision_walk(opts
->revs
))
1907 return error(_("revision walk setup failed"));
1912 static int read_and_refresh_cache(struct replay_opts
*opts
)
1914 struct lock_file index_lock
= LOCK_INIT
;
1915 int index_fd
= hold_locked_index(&index_lock
, 0);
1916 if (read_index_preload(&the_index
, NULL
) < 0) {
1917 rollback_lock_file(&index_lock
);
1918 return error(_("git %s: failed to read the index"),
1919 _(action_name(opts
)));
1921 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
1922 if (index_fd
>= 0) {
1923 if (write_locked_index(&the_index
, &index_lock
,
1924 COMMIT_LOCK
| SKIP_IF_UNCHANGED
)) {
1925 return error(_("git %s: failed to refresh the index"),
1926 _(action_name(opts
)));
1932 enum todo_item_flags
{
1933 TODO_EDIT_MERGE_MSG
= 1
1937 enum todo_command command
;
1938 struct commit
*commit
;
1942 size_t offset_in_buf
;
1947 struct todo_item
*items
;
1948 int nr
, alloc
, current
;
1949 int done_nr
, total_nr
;
1950 struct stat_data stat
;
1953 #define TODO_LIST_INIT { STRBUF_INIT }
1955 static void todo_list_release(struct todo_list
*todo_list
)
1957 strbuf_release(&todo_list
->buf
);
1958 FREE_AND_NULL(todo_list
->items
);
1959 todo_list
->nr
= todo_list
->alloc
= 0;
1962 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
1964 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
1965 return todo_list
->items
+ todo_list
->nr
++;
1968 static int parse_insn_line(struct todo_item
*item
, const char *bol
, char *eol
)
1970 struct object_id commit_oid
;
1971 char *end_of_object_name
;
1972 int i
, saved
, status
, padding
;
1977 bol
+= strspn(bol
, " \t");
1979 if (bol
== eol
|| *bol
== '\r' || *bol
== comment_line_char
) {
1980 item
->command
= TODO_COMMENT
;
1981 item
->commit
= NULL
;
1983 item
->arg_len
= eol
- bol
;
1987 for (i
= 0; i
< TODO_COMMENT
; i
++)
1988 if (skip_prefix(bol
, todo_command_info
[i
].str
, &bol
)) {
1991 } else if (bol
[1] == ' ' && *bol
== todo_command_info
[i
].c
) {
1996 if (i
>= TODO_COMMENT
)
1999 /* Eat up extra spaces/ tabs before object name */
2000 padding
= strspn(bol
, " \t");
2003 if (item
->command
== TODO_NOOP
) {
2005 return error(_("%s does not accept arguments: '%s'"),
2006 command_to_string(item
->command
), bol
);
2007 item
->commit
= NULL
;
2009 item
->arg_len
= eol
- bol
;
2014 return error(_("missing arguments for %s"),
2015 command_to_string(item
->command
));
2017 if (item
->command
== TODO_EXEC
|| item
->command
== TODO_LABEL
||
2018 item
->command
== TODO_RESET
) {
2019 item
->commit
= NULL
;
2021 item
->arg_len
= (int)(eol
- bol
);
2025 if (item
->command
== TODO_MERGE
) {
2026 if (skip_prefix(bol
, "-C", &bol
))
2027 bol
+= strspn(bol
, " \t");
2028 else if (skip_prefix(bol
, "-c", &bol
)) {
2029 bol
+= strspn(bol
, " \t");
2030 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2032 item
->flags
|= TODO_EDIT_MERGE_MSG
;
2033 item
->commit
= NULL
;
2035 item
->arg_len
= (int)(eol
- bol
);
2040 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
2041 saved
= *end_of_object_name
;
2042 *end_of_object_name
= '\0';
2043 status
= get_oid(bol
, &commit_oid
);
2044 *end_of_object_name
= saved
;
2046 item
->arg
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
2047 item
->arg_len
= (int)(eol
- item
->arg
);
2052 item
->commit
= lookup_commit_reference(the_repository
, &commit_oid
);
2053 return !item
->commit
;
2056 static int parse_insn_buffer(char *buf
, struct todo_list
*todo_list
)
2058 struct todo_item
*item
;
2059 char *p
= buf
, *next_p
;
2060 int i
, res
= 0, fixup_okay
= file_exists(rebase_path_done());
2062 for (i
= 1; *p
; i
++, p
= next_p
) {
2063 char *eol
= strchrnul(p
, '\n');
2065 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
2067 if (p
!= eol
&& eol
[-1] == '\r')
2068 eol
--; /* strip Carriage Return */
2070 item
= append_new_todo(todo_list
);
2071 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
2072 if (parse_insn_line(item
, p
, eol
)) {
2073 res
= error(_("invalid line %d: %.*s"),
2074 i
, (int)(eol
- p
), p
);
2075 item
->command
= TODO_NOOP
;
2080 else if (is_fixup(item
->command
))
2081 return error(_("cannot '%s' without a previous commit"),
2082 command_to_string(item
->command
));
2083 else if (!is_noop(item
->command
))
2090 static int count_commands(struct todo_list
*todo_list
)
2094 for (i
= 0; i
< todo_list
->nr
; i
++)
2095 if (todo_list
->items
[i
].command
!= TODO_COMMENT
)
2101 static int get_item_line_offset(struct todo_list
*todo_list
, int index
)
2103 return index
< todo_list
->nr
?
2104 todo_list
->items
[index
].offset_in_buf
: todo_list
->buf
.len
;
2107 static const char *get_item_line(struct todo_list
*todo_list
, int index
)
2109 return todo_list
->buf
.buf
+ get_item_line_offset(todo_list
, index
);
2112 static int get_item_line_length(struct todo_list
*todo_list
, int index
)
2114 return get_item_line_offset(todo_list
, index
+ 1)
2115 - get_item_line_offset(todo_list
, index
);
2118 static ssize_t
strbuf_read_file_or_whine(struct strbuf
*sb
, const char *path
)
2123 fd
= open(path
, O_RDONLY
);
2125 return error_errno(_("could not open '%s'"), path
);
2126 len
= strbuf_read(sb
, fd
, 0);
2129 return error(_("could not read '%s'."), path
);
2133 static int read_populate_todo(struct todo_list
*todo_list
,
2134 struct replay_opts
*opts
)
2137 const char *todo_file
= get_todo_path(opts
);
2140 strbuf_reset(&todo_list
->buf
);
2141 if (strbuf_read_file_or_whine(&todo_list
->buf
, todo_file
) < 0)
2144 res
= stat(todo_file
, &st
);
2146 return error(_("could not stat '%s'"), todo_file
);
2147 fill_stat_data(&todo_list
->stat
, &st
);
2149 res
= parse_insn_buffer(todo_list
->buf
.buf
, todo_list
);
2151 if (is_rebase_i(opts
))
2152 return error(_("please fix this using "
2153 "'git rebase --edit-todo'."));
2154 return error(_("unusable instruction sheet: '%s'"), todo_file
);
2157 if (!todo_list
->nr
&&
2158 (!is_rebase_i(opts
) || !file_exists(rebase_path_done())))
2159 return error(_("no commits parsed."));
2161 if (!is_rebase_i(opts
)) {
2162 enum todo_command valid
=
2163 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
2166 for (i
= 0; i
< todo_list
->nr
; i
++)
2167 if (valid
== todo_list
->items
[i
].command
)
2169 else if (valid
== TODO_PICK
)
2170 return error(_("cannot cherry-pick during a revert."));
2172 return error(_("cannot revert during a cherry-pick."));
2175 if (is_rebase_i(opts
)) {
2176 struct todo_list done
= TODO_LIST_INIT
;
2177 FILE *f
= fopen_or_warn(rebase_path_msgtotal(), "w");
2179 if (strbuf_read_file(&done
.buf
, rebase_path_done(), 0) > 0 &&
2180 !parse_insn_buffer(done
.buf
.buf
, &done
))
2181 todo_list
->done_nr
= count_commands(&done
);
2183 todo_list
->done_nr
= 0;
2185 todo_list
->total_nr
= todo_list
->done_nr
2186 + count_commands(todo_list
);
2187 todo_list_release(&done
);
2190 fprintf(f
, "%d\n", todo_list
->total_nr
);
2198 static int git_config_string_dup(char **dest
,
2199 const char *var
, const char *value
)
2202 return config_error_nonbool(var
);
2204 *dest
= xstrdup(value
);
2208 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
2210 struct replay_opts
*opts
= data
;
2215 else if (!strcmp(key
, "options.no-commit"))
2216 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
2217 else if (!strcmp(key
, "options.edit"))
2218 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
2219 else if (!strcmp(key
, "options.signoff"))
2220 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
2221 else if (!strcmp(key
, "options.record-origin"))
2222 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
2223 else if (!strcmp(key
, "options.allow-ff"))
2224 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
2225 else if (!strcmp(key
, "options.mainline"))
2226 opts
->mainline
= git_config_int(key
, value
);
2227 else if (!strcmp(key
, "options.strategy"))
2228 git_config_string_dup(&opts
->strategy
, key
, value
);
2229 else if (!strcmp(key
, "options.gpg-sign"))
2230 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
2231 else if (!strcmp(key
, "options.strategy-option")) {
2232 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
2233 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(value
);
2234 } else if (!strcmp(key
, "options.allow-rerere-auto"))
2235 opts
->allow_rerere_auto
=
2236 git_config_bool_or_int(key
, value
, &error_flag
) ?
2237 RERERE_AUTOUPDATE
: RERERE_NOAUTOUPDATE
;
2239 return error(_("invalid key: %s"), key
);
2242 return error(_("invalid value for %s: %s"), key
, value
);
2247 static void read_strategy_opts(struct replay_opts
*opts
, struct strbuf
*buf
)
2250 char *strategy_opts_string
;
2253 if (!read_oneliner(buf
, rebase_path_strategy(), 0))
2255 opts
->strategy
= strbuf_detach(buf
, NULL
);
2256 if (!read_oneliner(buf
, rebase_path_strategy_opts(), 0))
2259 strategy_opts_string
= buf
->buf
;
2260 if (*strategy_opts_string
== ' ')
2261 strategy_opts_string
++;
2262 opts
->xopts_nr
= split_cmdline(strategy_opts_string
,
2263 (const char ***)&opts
->xopts
);
2264 for (i
= 0; i
< opts
->xopts_nr
; i
++) {
2265 const char *arg
= opts
->xopts
[i
];
2267 skip_prefix(arg
, "--", &arg
);
2268 opts
->xopts
[i
] = xstrdup(arg
);
2272 static int read_populate_opts(struct replay_opts
*opts
)
2274 if (is_rebase_i(opts
)) {
2275 struct strbuf buf
= STRBUF_INIT
;
2277 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(), 1)) {
2278 if (!starts_with(buf
.buf
, "-S"))
2281 free(opts
->gpg_sign
);
2282 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
2287 if (read_oneliner(&buf
, rebase_path_allow_rerere_autoupdate(), 1)) {
2288 if (!strcmp(buf
.buf
, "--rerere-autoupdate"))
2289 opts
->allow_rerere_auto
= RERERE_AUTOUPDATE
;
2290 else if (!strcmp(buf
.buf
, "--no-rerere-autoupdate"))
2291 opts
->allow_rerere_auto
= RERERE_NOAUTOUPDATE
;
2295 if (file_exists(rebase_path_verbose()))
2298 if (file_exists(rebase_path_signoff())) {
2303 read_strategy_opts(opts
, &buf
);
2304 strbuf_release(&buf
);
2306 if (read_oneliner(&opts
->current_fixups
,
2307 rebase_path_current_fixups(), 1)) {
2308 const char *p
= opts
->current_fixups
.buf
;
2309 opts
->current_fixup_count
= 1;
2310 while ((p
= strchr(p
, '\n'))) {
2311 opts
->current_fixup_count
++;
2316 if (read_oneliner(&buf
, rebase_path_squash_onto(), 0)) {
2317 if (get_oid_hex(buf
.buf
, &opts
->squash_onto
) < 0)
2318 return error(_("unusable squash-onto"));
2319 opts
->have_squash_onto
= 1;
2325 if (!file_exists(git_path_opts_file()))
2328 * The function git_parse_source(), called from git_config_from_file(),
2329 * may die() in case of a syntactically incorrect file. We do not care
2330 * about this case, though, because we wrote that file ourselves, so we
2331 * are pretty certain that it is syntactically correct.
2333 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
2334 return error(_("malformed options sheet: '%s'"),
2335 git_path_opts_file());
2339 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
2340 struct replay_opts
*opts
)
2342 enum todo_command command
= opts
->action
== REPLAY_PICK
?
2343 TODO_PICK
: TODO_REVERT
;
2344 const char *command_string
= todo_command_info
[command
].str
;
2345 struct commit
*commit
;
2347 if (prepare_revs(opts
))
2350 while ((commit
= get_revision(opts
->revs
))) {
2351 struct todo_item
*item
= append_new_todo(todo_list
);
2352 const char *commit_buffer
= get_commit_buffer(commit
, NULL
);
2353 const char *subject
;
2356 item
->command
= command
;
2357 item
->commit
= commit
;
2360 item
->offset_in_buf
= todo_list
->buf
.len
;
2361 subject_len
= find_commit_subject(commit_buffer
, &subject
);
2362 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
2363 short_commit_name(commit
), subject_len
, subject
);
2364 unuse_commit_buffer(commit
, commit_buffer
);
2368 return error(_("empty commit set passed"));
2373 static int create_seq_dir(void)
2375 if (file_exists(git_path_seq_dir())) {
2376 error(_("a cherry-pick or revert is already in progress"));
2377 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2379 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2380 return error_errno(_("could not create sequencer directory '%s'"),
2381 git_path_seq_dir());
2385 static int save_head(const char *head
)
2387 struct lock_file head_lock
= LOCK_INIT
;
2388 struct strbuf buf
= STRBUF_INIT
;
2392 fd
= hold_lock_file_for_update(&head_lock
, git_path_head_file(), 0);
2394 return error_errno(_("could not lock HEAD"));
2395 strbuf_addf(&buf
, "%s\n", head
);
2396 written
= write_in_full(fd
, buf
.buf
, buf
.len
);
2397 strbuf_release(&buf
);
2399 error_errno(_("could not write to '%s'"), git_path_head_file());
2400 rollback_lock_file(&head_lock
);
2403 if (commit_lock_file(&head_lock
) < 0)
2404 return error(_("failed to finalize '%s'"), git_path_head_file());
2408 static int rollback_is_safe(void)
2410 struct strbuf sb
= STRBUF_INIT
;
2411 struct object_id expected_head
, actual_head
;
2413 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
2415 if (get_oid_hex(sb
.buf
, &expected_head
)) {
2416 strbuf_release(&sb
);
2417 die(_("could not parse %s"), git_path_abort_safety_file());
2419 strbuf_release(&sb
);
2421 else if (errno
== ENOENT
)
2422 oidclr(&expected_head
);
2424 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2426 if (get_oid("HEAD", &actual_head
))
2427 oidclr(&actual_head
);
2429 return oideq(&actual_head
, &expected_head
);
2432 static int reset_for_rollback(const struct object_id
*oid
)
2434 const char *argv
[4]; /* reset --merge <arg> + NULL */
2437 argv
[1] = "--merge";
2438 argv
[2] = oid_to_hex(oid
);
2440 return run_command_v_opt(argv
, RUN_GIT_CMD
);
2443 static int rollback_single_pick(void)
2445 struct object_id head_oid
;
2447 if (!file_exists(git_path_cherry_pick_head(the_repository
)) &&
2448 !file_exists(git_path_revert_head(the_repository
)))
2449 return error(_("no cherry-pick or revert in progress"));
2450 if (read_ref_full("HEAD", 0, &head_oid
, NULL
))
2451 return error(_("cannot resolve HEAD"));
2452 if (is_null_oid(&head_oid
))
2453 return error(_("cannot abort from a branch yet to be born"));
2454 return reset_for_rollback(&head_oid
);
2457 int sequencer_rollback(struct replay_opts
*opts
)
2460 struct object_id oid
;
2461 struct strbuf buf
= STRBUF_INIT
;
2464 f
= fopen(git_path_head_file(), "r");
2465 if (!f
&& errno
== ENOENT
) {
2467 * There is no multiple-cherry-pick in progress.
2468 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2469 * a single-cherry-pick in progress, abort that.
2471 return rollback_single_pick();
2474 return error_errno(_("cannot open '%s'"), git_path_head_file());
2475 if (strbuf_getline_lf(&buf
, f
)) {
2476 error(_("cannot read '%s': %s"), git_path_head_file(),
2477 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
2482 if (parse_oid_hex(buf
.buf
, &oid
, &p
) || *p
!= '\0') {
2483 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2484 git_path_head_file());
2487 if (is_null_oid(&oid
)) {
2488 error(_("cannot abort from a branch yet to be born"));
2492 if (!rollback_is_safe()) {
2493 /* Do not error, just do not rollback */
2494 warning(_("You seem to have moved HEAD. "
2495 "Not rewinding, check your HEAD!"));
2497 if (reset_for_rollback(&oid
))
2499 strbuf_release(&buf
);
2500 return sequencer_remove_state(opts
);
2502 strbuf_release(&buf
);
2506 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
2508 struct lock_file todo_lock
= LOCK_INIT
;
2509 const char *todo_path
= get_todo_path(opts
);
2510 int next
= todo_list
->current
, offset
, fd
;
2513 * rebase -i writes "git-rebase-todo" without the currently executing
2514 * command, appending it to "done" instead.
2516 if (is_rebase_i(opts
))
2519 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
2521 return error_errno(_("could not lock '%s'"), todo_path
);
2522 offset
= get_item_line_offset(todo_list
, next
);
2523 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
2524 todo_list
->buf
.len
- offset
) < 0)
2525 return error_errno(_("could not write to '%s'"), todo_path
);
2526 if (commit_lock_file(&todo_lock
) < 0)
2527 return error(_("failed to finalize '%s'"), todo_path
);
2529 if (is_rebase_i(opts
) && next
> 0) {
2530 const char *done
= rebase_path_done();
2531 int fd
= open(done
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
2536 if (write_in_full(fd
, get_item_line(todo_list
, next
- 1),
2537 get_item_line_length(todo_list
, next
- 1))
2539 ret
= error_errno(_("could not write to '%s'"), done
);
2541 ret
= error_errno(_("failed to finalize '%s'"), done
);
2547 static int save_opts(struct replay_opts
*opts
)
2549 const char *opts_file
= git_path_opts_file();
2552 if (opts
->no_commit
)
2553 res
|= git_config_set_in_file_gently(opts_file
, "options.no-commit", "true");
2555 res
|= git_config_set_in_file_gently(opts_file
, "options.edit", "true");
2557 res
|= git_config_set_in_file_gently(opts_file
, "options.signoff", "true");
2558 if (opts
->record_origin
)
2559 res
|= git_config_set_in_file_gently(opts_file
, "options.record-origin", "true");
2561 res
|= git_config_set_in_file_gently(opts_file
, "options.allow-ff", "true");
2562 if (opts
->mainline
) {
2563 struct strbuf buf
= STRBUF_INIT
;
2564 strbuf_addf(&buf
, "%d", opts
->mainline
);
2565 res
|= git_config_set_in_file_gently(opts_file
, "options.mainline", buf
.buf
);
2566 strbuf_release(&buf
);
2569 res
|= git_config_set_in_file_gently(opts_file
, "options.strategy", opts
->strategy
);
2571 res
|= git_config_set_in_file_gently(opts_file
, "options.gpg-sign", opts
->gpg_sign
);
2574 for (i
= 0; i
< opts
->xopts_nr
; i
++)
2575 res
|= git_config_set_multivar_in_file_gently(opts_file
,
2576 "options.strategy-option",
2577 opts
->xopts
[i
], "^$", 0);
2579 if (opts
->allow_rerere_auto
)
2580 res
|= git_config_set_in_file_gently(opts_file
, "options.allow-rerere-auto",
2581 opts
->allow_rerere_auto
== RERERE_AUTOUPDATE
?
2586 static int make_patch(struct commit
*commit
, struct replay_opts
*opts
)
2588 struct strbuf buf
= STRBUF_INIT
;
2589 struct rev_info log_tree_opt
;
2590 const char *subject
, *p
;
2593 p
= short_commit_name(commit
);
2594 if (write_message(p
, strlen(p
), rebase_path_stopped_sha(), 1) < 0)
2596 if (update_ref("rebase", "REBASE_HEAD", &commit
->object
.oid
,
2597 NULL
, REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
))
2598 res
|= error(_("could not update %s"), "REBASE_HEAD");
2600 strbuf_addf(&buf
, "%s/patch", get_dir(opts
));
2601 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
2602 init_revisions(&log_tree_opt
, NULL
);
2603 log_tree_opt
.abbrev
= 0;
2604 log_tree_opt
.diff
= 1;
2605 log_tree_opt
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
2606 log_tree_opt
.disable_stdin
= 1;
2607 log_tree_opt
.no_commit_id
= 1;
2608 log_tree_opt
.diffopt
.file
= fopen(buf
.buf
, "w");
2609 log_tree_opt
.diffopt
.use_color
= GIT_COLOR_NEVER
;
2610 if (!log_tree_opt
.diffopt
.file
)
2611 res
|= error_errno(_("could not open '%s'"), buf
.buf
);
2613 res
|= log_tree_commit(&log_tree_opt
, commit
);
2614 fclose(log_tree_opt
.diffopt
.file
);
2618 strbuf_addf(&buf
, "%s/message", get_dir(opts
));
2619 if (!file_exists(buf
.buf
)) {
2620 const char *commit_buffer
= get_commit_buffer(commit
, NULL
);
2621 find_commit_subject(commit_buffer
, &subject
);
2622 res
|= write_message(subject
, strlen(subject
), buf
.buf
, 1);
2623 unuse_commit_buffer(commit
, commit_buffer
);
2625 strbuf_release(&buf
);
2630 static int intend_to_amend(void)
2632 struct object_id head
;
2635 if (get_oid("HEAD", &head
))
2636 return error(_("cannot read HEAD"));
2638 p
= oid_to_hex(&head
);
2639 return write_message(p
, strlen(p
), rebase_path_amend(), 1);
2642 static int error_with_patch(struct commit
*commit
,
2643 const char *subject
, int subject_len
,
2644 struct replay_opts
*opts
, int exit_code
, int to_amend
)
2647 if (make_patch(commit
, opts
))
2649 } else if (copy_file(rebase_path_message(),
2650 git_path_merge_msg(the_repository
), 0666))
2651 return error(_("unable to copy '%s' to '%s'"),
2652 git_path_merge_msg(the_repository
), rebase_path_message());
2655 if (intend_to_amend())
2659 _("You can amend the commit now, with\n"
2661 " git commit --amend %s\n"
2663 "Once you are satisfied with your changes, run\n"
2665 " git rebase --continue\n"),
2666 gpg_sign_opt_quoted(opts
));
2667 } else if (exit_code
) {
2669 fprintf_ln(stderr
, _("Could not apply %s... %.*s"),
2670 short_commit_name(commit
), subject_len
, subject
);
2673 * We don't have the hash of the parent so
2674 * just print the line from the todo file.
2676 fprintf_ln(stderr
, _("Could not merge %.*s"),
2677 subject_len
, subject
);
2683 static int error_failed_squash(struct commit
*commit
,
2684 struct replay_opts
*opts
, int subject_len
, const char *subject
)
2686 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2687 return error(_("could not copy '%s' to '%s'"),
2688 rebase_path_squash_msg(), rebase_path_message());
2689 unlink(git_path_merge_msg(the_repository
));
2690 if (copy_file(git_path_merge_msg(the_repository
), rebase_path_message(), 0666))
2691 return error(_("could not copy '%s' to '%s'"),
2692 rebase_path_message(),
2693 git_path_merge_msg(the_repository
));
2694 return error_with_patch(commit
, subject
, subject_len
, opts
, 1, 0);
2697 static int do_exec(const char *command_line
)
2699 struct argv_array child_env
= ARGV_ARRAY_INIT
;
2700 const char *child_argv
[] = { NULL
, NULL
};
2703 fprintf(stderr
, "Executing: %s\n", command_line
);
2704 child_argv
[0] = command_line
;
2705 argv_array_pushf(&child_env
, "GIT_DIR=%s", absolute_path(get_git_dir()));
2706 argv_array_pushf(&child_env
, "GIT_WORK_TREE=%s",
2707 absolute_path(get_git_work_tree()));
2708 status
= run_command_v_opt_cd_env(child_argv
, RUN_USING_SHELL
, NULL
,
2711 /* force re-reading of the cache */
2712 if (discard_cache() < 0 || read_cache() < 0)
2713 return error(_("could not read index"));
2715 dirty
= require_clean_work_tree("rebase", NULL
, 1, 1);
2718 warning(_("execution failed: %s\n%s"
2719 "You can fix the problem, and then run\n"
2721 " git rebase --continue\n"
2724 dirty
? N_("and made changes to the index and/or the "
2725 "working tree\n") : "");
2727 /* command not found */
2730 warning(_("execution succeeded: %s\nbut "
2731 "left changes to the index and/or the working tree\n"
2732 "Commit or stash your changes, and then run\n"
2734 " git rebase --continue\n"
2735 "\n"), command_line
);
2739 argv_array_clear(&child_env
);
2744 static int safe_append(const char *filename
, const char *fmt
, ...)
2747 struct lock_file lock
= LOCK_INIT
;
2748 int fd
= hold_lock_file_for_update(&lock
, filename
,
2749 LOCK_REPORT_ON_ERROR
);
2750 struct strbuf buf
= STRBUF_INIT
;
2755 if (strbuf_read_file(&buf
, filename
, 0) < 0 && errno
!= ENOENT
) {
2756 error_errno(_("could not read '%s'"), filename
);
2757 rollback_lock_file(&lock
);
2760 strbuf_complete(&buf
, '\n');
2762 strbuf_vaddf(&buf
, fmt
, ap
);
2765 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
2766 error_errno(_("could not write to '%s'"), filename
);
2767 strbuf_release(&buf
);
2768 rollback_lock_file(&lock
);
2771 if (commit_lock_file(&lock
) < 0) {
2772 strbuf_release(&buf
);
2773 rollback_lock_file(&lock
);
2774 return error(_("failed to finalize '%s'"), filename
);
2777 strbuf_release(&buf
);
2781 static int do_label(const char *name
, int len
)
2783 struct ref_store
*refs
= get_main_ref_store(the_repository
);
2784 struct ref_transaction
*transaction
;
2785 struct strbuf ref_name
= STRBUF_INIT
, err
= STRBUF_INIT
;
2786 struct strbuf msg
= STRBUF_INIT
;
2788 struct object_id head_oid
;
2790 if (len
== 1 && *name
== '#')
2791 return error(_("illegal label name: '%.*s'"), len
, name
);
2793 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
2794 strbuf_addf(&msg
, "rebase -i (label) '%.*s'", len
, name
);
2796 transaction
= ref_store_transaction_begin(refs
, &err
);
2798 error("%s", err
.buf
);
2800 } else if (get_oid("HEAD", &head_oid
)) {
2801 error(_("could not read HEAD"));
2803 } else if (ref_transaction_update(transaction
, ref_name
.buf
, &head_oid
,
2804 NULL
, 0, msg
.buf
, &err
) < 0 ||
2805 ref_transaction_commit(transaction
, &err
)) {
2806 error("%s", err
.buf
);
2809 ref_transaction_free(transaction
);
2810 strbuf_release(&err
);
2811 strbuf_release(&msg
);
2814 ret
= safe_append(rebase_path_refs_to_delete(),
2815 "%s\n", ref_name
.buf
);
2816 strbuf_release(&ref_name
);
2821 static const char *reflog_message(struct replay_opts
*opts
,
2822 const char *sub_action
, const char *fmt
, ...);
2824 static int do_reset(const char *name
, int len
, struct replay_opts
*opts
)
2826 struct strbuf ref_name
= STRBUF_INIT
;
2827 struct object_id oid
;
2828 struct lock_file lock
= LOCK_INIT
;
2829 struct tree_desc desc
;
2831 struct unpack_trees_options unpack_tree_opts
;
2834 if (hold_locked_index(&lock
, LOCK_REPORT_ON_ERROR
) < 0)
2837 if (len
== 10 && !strncmp("[new root]", name
, len
)) {
2838 if (!opts
->have_squash_onto
) {
2840 if (commit_tree("", 0, the_hash_algo
->empty_tree
,
2841 NULL
, &opts
->squash_onto
,
2843 return error(_("writing fake root commit"));
2844 opts
->have_squash_onto
= 1;
2845 hex
= oid_to_hex(&opts
->squash_onto
);
2846 if (write_message(hex
, strlen(hex
),
2847 rebase_path_squash_onto(), 0))
2848 return error(_("writing squash-onto"));
2850 oidcpy(&oid
, &opts
->squash_onto
);
2852 /* Determine the length of the label */
2853 for (i
= 0; i
< len
; i
++)
2854 if (isspace(name
[i
]))
2857 strbuf_addf(&ref_name
, "refs/rewritten/%.*s", len
, name
);
2858 if (get_oid(ref_name
.buf
, &oid
) &&
2859 get_oid(ref_name
.buf
+ strlen("refs/rewritten/"), &oid
)) {
2860 error(_("could not read '%s'"), ref_name
.buf
);
2861 rollback_lock_file(&lock
);
2862 strbuf_release(&ref_name
);
2867 memset(&unpack_tree_opts
, 0, sizeof(unpack_tree_opts
));
2868 setup_unpack_trees_porcelain(&unpack_tree_opts
, "reset");
2869 unpack_tree_opts
.head_idx
= 1;
2870 unpack_tree_opts
.src_index
= &the_index
;
2871 unpack_tree_opts
.dst_index
= &the_index
;
2872 unpack_tree_opts
.fn
= oneway_merge
;
2873 unpack_tree_opts
.merge
= 1;
2874 unpack_tree_opts
.update
= 1;
2876 if (read_cache_unmerged()) {
2877 rollback_lock_file(&lock
);
2878 strbuf_release(&ref_name
);
2879 return error_resolve_conflict(_(action_name(opts
)));
2882 if (!fill_tree_descriptor(&desc
, &oid
)) {
2883 error(_("failed to find tree of %s"), oid_to_hex(&oid
));
2884 rollback_lock_file(&lock
);
2885 free((void *)desc
.buffer
);
2886 strbuf_release(&ref_name
);
2890 if (unpack_trees(1, &desc
, &unpack_tree_opts
)) {
2891 rollback_lock_file(&lock
);
2892 free((void *)desc
.buffer
);
2893 strbuf_release(&ref_name
);
2897 tree
= parse_tree_indirect(&oid
);
2898 prime_cache_tree(&the_index
, tree
);
2900 if (write_locked_index(&the_index
, &lock
, COMMIT_LOCK
) < 0)
2901 ret
= error(_("could not write index"));
2902 free((void *)desc
.buffer
);
2905 ret
= update_ref(reflog_message(opts
, "reset", "'%.*s'",
2906 len
, name
), "HEAD", &oid
,
2907 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
2909 strbuf_release(&ref_name
);
2913 static struct commit
*lookup_label(const char *label
, int len
,
2916 struct commit
*commit
;
2919 strbuf_addf(buf
, "refs/rewritten/%.*s", len
, label
);
2920 commit
= lookup_commit_reference_by_name(buf
->buf
);
2922 /* fall back to non-rewritten ref or commit */
2923 strbuf_splice(buf
, 0, strlen("refs/rewritten/"), "", 0);
2924 commit
= lookup_commit_reference_by_name(buf
->buf
);
2928 error(_("could not resolve '%s'"), buf
->buf
);
2933 static int do_merge(struct commit
*commit
, const char *arg
, int arg_len
,
2934 int flags
, struct replay_opts
*opts
)
2936 int run_commit_flags
= (flags
& TODO_EDIT_MERGE_MSG
) ?
2937 EDIT_MSG
| VERIFY_MSG
: 0;
2938 struct strbuf ref_name
= STRBUF_INIT
;
2939 struct commit
*head_commit
, *merge_commit
, *i
;
2940 struct commit_list
*bases
, *j
, *reversed
= NULL
;
2941 struct commit_list
*to_merge
= NULL
, **tail
= &to_merge
;
2942 struct merge_options o
;
2943 int merge_arg_len
, oneline_offset
, can_fast_forward
, ret
, k
;
2944 static struct lock_file lock
;
2947 if (hold_locked_index(&lock
, LOCK_REPORT_ON_ERROR
) < 0) {
2952 head_commit
= lookup_commit_reference_by_name("HEAD");
2954 ret
= error(_("cannot merge without a current revision"));
2959 * For octopus merges, the arg starts with the list of revisions to be
2960 * merged. The list is optionally followed by '#' and the oneline.
2962 merge_arg_len
= oneline_offset
= arg_len
;
2963 for (p
= arg
; p
- arg
< arg_len
; p
+= strspn(p
, " \t\n")) {
2966 if (*p
== '#' && (!p
[1] || isspace(p
[1]))) {
2967 p
+= 1 + strspn(p
+ 1, " \t\n");
2968 oneline_offset
= p
- arg
;
2971 k
= strcspn(p
, " \t\n");
2974 merge_commit
= lookup_label(p
, k
, &ref_name
);
2975 if (!merge_commit
) {
2976 ret
= error(_("unable to parse '%.*s'"), k
, p
);
2979 tail
= &commit_list_insert(merge_commit
, tail
)->next
;
2981 merge_arg_len
= p
- arg
;
2985 ret
= error(_("nothing to merge: '%.*s'"), arg_len
, arg
);
2989 if (opts
->have_squash_onto
&&
2990 oideq(&head_commit
->object
.oid
, &opts
->squash_onto
)) {
2992 * When the user tells us to "merge" something into a
2993 * "[new root]", let's simply fast-forward to the merge head.
2995 rollback_lock_file(&lock
);
2997 ret
= error(_("octopus merge cannot be executed on "
2998 "top of a [new root]"));
3000 ret
= fast_forward_to(&to_merge
->item
->object
.oid
,
3001 &head_commit
->object
.oid
, 0,
3007 const char *message
= get_commit_buffer(commit
, NULL
);
3012 ret
= error(_("could not get commit message of '%s'"),
3013 oid_to_hex(&commit
->object
.oid
));
3016 write_author_script(message
);
3017 find_commit_subject(message
, &body
);
3019 ret
= write_message(body
, len
, git_path_merge_msg(the_repository
), 0);
3020 unuse_commit_buffer(commit
, message
);
3022 error_errno(_("could not write '%s'"),
3023 git_path_merge_msg(the_repository
));
3027 struct strbuf buf
= STRBUF_INIT
;
3030 strbuf_addf(&buf
, "author %s", git_author_info(0));
3031 write_author_script(buf
.buf
);
3034 if (oneline_offset
< arg_len
) {
3035 p
= arg
+ oneline_offset
;
3036 len
= arg_len
- oneline_offset
;
3038 strbuf_addf(&buf
, "Merge %s '%.*s'",
3039 to_merge
->next
? "branches" : "branch",
3040 merge_arg_len
, arg
);
3045 ret
= write_message(p
, len
, git_path_merge_msg(the_repository
), 0);
3046 strbuf_release(&buf
);
3048 error_errno(_("could not write '%s'"),
3049 git_path_merge_msg(the_repository
));
3055 * If HEAD is not identical to the first parent of the original merge
3056 * commit, we cannot fast-forward.
3058 can_fast_forward
= opts
->allow_ff
&& commit
&& commit
->parents
&&
3059 oideq(&commit
->parents
->item
->object
.oid
,
3060 &head_commit
->object
.oid
);
3063 * If any merge head is different from the original one, we cannot
3066 if (can_fast_forward
) {
3067 struct commit_list
*p
= commit
->parents
->next
;
3069 for (j
= to_merge
; j
&& p
; j
= j
->next
, p
= p
->next
)
3070 if (!oideq(&j
->item
->object
.oid
,
3071 &p
->item
->object
.oid
)) {
3072 can_fast_forward
= 0;
3076 * If the number of merge heads differs from the original merge
3077 * commit, we cannot fast-forward.
3080 can_fast_forward
= 0;
3083 if (can_fast_forward
) {
3084 rollback_lock_file(&lock
);
3085 ret
= fast_forward_to(&commit
->object
.oid
,
3086 &head_commit
->object
.oid
, 0, opts
);
3090 if (to_merge
->next
) {
3092 struct child_process cmd
= CHILD_PROCESS_INIT
;
3094 if (read_env_script(&cmd
.env_array
)) {
3095 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
3097 ret
= error(_(staged_changes_advice
), gpg_opt
, gpg_opt
);
3102 argv_array_push(&cmd
.args
, "merge");
3103 argv_array_push(&cmd
.args
, "-s");
3104 argv_array_push(&cmd
.args
, "octopus");
3105 argv_array_push(&cmd
.args
, "--no-edit");
3106 argv_array_push(&cmd
.args
, "--no-ff");
3107 argv_array_push(&cmd
.args
, "--no-log");
3108 argv_array_push(&cmd
.args
, "--no-stat");
3109 argv_array_push(&cmd
.args
, "-F");
3110 argv_array_push(&cmd
.args
, git_path_merge_msg(the_repository
));
3112 argv_array_push(&cmd
.args
, opts
->gpg_sign
);
3114 /* Add the tips to be merged */
3115 for (j
= to_merge
; j
; j
= j
->next
)
3116 argv_array_push(&cmd
.args
,
3117 oid_to_hex(&j
->item
->object
.oid
));
3119 strbuf_release(&ref_name
);
3120 unlink(git_path_cherry_pick_head(the_repository
));
3121 rollback_lock_file(&lock
);
3123 rollback_lock_file(&lock
);
3124 ret
= run_command(&cmd
);
3126 /* force re-reading of the cache */
3127 if (!ret
&& (discard_cache() < 0 || read_cache() < 0))
3128 ret
= error(_("could not read index"));
3132 merge_commit
= to_merge
->item
;
3133 write_message(oid_to_hex(&merge_commit
->object
.oid
), GIT_SHA1_HEXSZ
,
3134 git_path_merge_head(the_repository
), 0);
3135 write_message("no-ff", 5, git_path_merge_mode(the_repository
), 0);
3137 bases
= get_merge_bases(head_commit
, merge_commit
);
3138 if (bases
&& oideq(&merge_commit
->object
.oid
,
3139 &bases
->item
->object
.oid
)) {
3141 /* skip merging an ancestor of HEAD */
3145 for (j
= bases
; j
; j
= j
->next
)
3146 commit_list_insert(j
->item
, &reversed
);
3147 free_commit_list(bases
);
3150 init_merge_options(&o
);
3152 o
.branch2
= ref_name
.buf
;
3153 o
.buffer_output
= 2;
3155 ret
= merge_recursive(&o
, head_commit
, merge_commit
, reversed
, &i
);
3157 fputs(o
.obuf
.buf
, stdout
);
3158 strbuf_release(&o
.obuf
);
3160 error(_("could not even attempt to merge '%.*s'"),
3161 merge_arg_len
, arg
);
3165 * The return value of merge_recursive() is 1 on clean, and 0 on
3168 * Let's reverse that, so that do_merge() returns 0 upon success and
3169 * 1 upon failed merge (keeping the return value -1 for the cases where
3170 * we will want to reschedule the `merge` command).
3174 if (active_cache_changed
&&
3175 write_locked_index(&the_index
, &lock
, COMMIT_LOCK
)) {
3176 ret
= error(_("merge: Unable to write new index file"));
3180 rollback_lock_file(&lock
);
3182 rerere(opts
->allow_rerere_auto
);
3185 * In case of problems, we now want to return a positive
3186 * value (a negative one would indicate that the `merge`
3187 * command needs to be rescheduled).
3189 ret
= !!run_git_commit(git_path_merge_msg(the_repository
), opts
,
3193 strbuf_release(&ref_name
);
3194 rollback_lock_file(&lock
);
3195 free_commit_list(to_merge
);
3199 static int is_final_fixup(struct todo_list
*todo_list
)
3201 int i
= todo_list
->current
;
3203 if (!is_fixup(todo_list
->items
[i
].command
))
3206 while (++i
< todo_list
->nr
)
3207 if (is_fixup(todo_list
->items
[i
].command
))
3209 else if (!is_noop(todo_list
->items
[i
].command
))
3214 static enum todo_command
peek_command(struct todo_list
*todo_list
, int offset
)
3218 for (i
= todo_list
->current
+ offset
; i
< todo_list
->nr
; i
++)
3219 if (!is_noop(todo_list
->items
[i
].command
))
3220 return todo_list
->items
[i
].command
;
3225 static int apply_autostash(struct replay_opts
*opts
)
3227 struct strbuf stash_sha1
= STRBUF_INIT
;
3228 struct child_process child
= CHILD_PROCESS_INIT
;
3231 if (!read_oneliner(&stash_sha1
, rebase_path_autostash(), 1)) {
3232 strbuf_release(&stash_sha1
);
3235 strbuf_trim(&stash_sha1
);
3238 child
.no_stdout
= 1;
3239 child
.no_stderr
= 1;
3240 argv_array_push(&child
.args
, "stash");
3241 argv_array_push(&child
.args
, "apply");
3242 argv_array_push(&child
.args
, stash_sha1
.buf
);
3243 if (!run_command(&child
))
3244 fprintf(stderr
, _("Applied autostash.\n"));
3246 struct child_process store
= CHILD_PROCESS_INIT
;
3249 argv_array_push(&store
.args
, "stash");
3250 argv_array_push(&store
.args
, "store");
3251 argv_array_push(&store
.args
, "-m");
3252 argv_array_push(&store
.args
, "autostash");
3253 argv_array_push(&store
.args
, "-q");
3254 argv_array_push(&store
.args
, stash_sha1
.buf
);
3255 if (run_command(&store
))
3256 ret
= error(_("cannot store %s"), stash_sha1
.buf
);
3259 _("Applying autostash resulted in conflicts.\n"
3260 "Your changes are safe in the stash.\n"
3261 "You can run \"git stash pop\" or"
3262 " \"git stash drop\" at any time.\n"));
3265 strbuf_release(&stash_sha1
);
3269 static const char *reflog_message(struct replay_opts
*opts
,
3270 const char *sub_action
, const char *fmt
, ...)
3273 static struct strbuf buf
= STRBUF_INIT
;
3277 strbuf_addstr(&buf
, action_name(opts
));
3279 strbuf_addf(&buf
, " (%s)", sub_action
);
3281 strbuf_addstr(&buf
, ": ");
3282 strbuf_vaddf(&buf
, fmt
, ap
);
3289 static const char rescheduled_advice
[] =
3290 N_("Could not execute the todo command\n"
3294 "It has been rescheduled; To edit the command before continuing, please\n"
3295 "edit the todo list first:\n"
3297 " git rebase --edit-todo\n"
3298 " git rebase --continue\n");
3300 static int pick_commits(struct todo_list
*todo_list
, struct replay_opts
*opts
)
3302 int res
= 0, reschedule
= 0;
3304 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
3306 assert(!(opts
->signoff
|| opts
->no_commit
||
3307 opts
->record_origin
|| opts
->edit
));
3308 if (read_and_refresh_cache(opts
))
3311 while (todo_list
->current
< todo_list
->nr
) {
3312 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
3313 if (save_todo(todo_list
, opts
))
3315 if (is_rebase_i(opts
)) {
3316 if (item
->command
!= TODO_COMMENT
) {
3317 FILE *f
= fopen(rebase_path_msgnum(), "w");
3319 todo_list
->done_nr
++;
3322 fprintf(f
, "%d\n", todo_list
->done_nr
);
3325 fprintf(stderr
, "Rebasing (%d/%d)%s",
3327 todo_list
->total_nr
,
3328 opts
->verbose
? "\n" : "\r");
3330 unlink(rebase_path_message());
3331 unlink(rebase_path_author_script());
3332 unlink(rebase_path_stopped_sha());
3333 unlink(rebase_path_amend());
3334 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
3336 if (item
->command
<= TODO_SQUASH
) {
3337 if (is_rebase_i(opts
))
3338 setenv("GIT_REFLOG_ACTION", reflog_message(opts
,
3339 command_to_string(item
->command
), NULL
),
3341 res
= do_pick_commit(item
->command
, item
->commit
,
3342 opts
, is_final_fixup(todo_list
));
3343 if (is_rebase_i(opts
) && res
< 0) {
3345 advise(_(rescheduled_advice
),
3346 get_item_line_length(todo_list
,
3347 todo_list
->current
),
3348 get_item_line(todo_list
,
3349 todo_list
->current
));
3350 todo_list
->current
--;
3351 if (save_todo(todo_list
, opts
))
3354 if (item
->command
== TODO_EDIT
) {
3355 struct commit
*commit
= item
->commit
;
3358 _("Stopped at %s... %.*s\n"),
3359 short_commit_name(commit
),
3360 item
->arg_len
, item
->arg
);
3361 return error_with_patch(commit
,
3362 item
->arg
, item
->arg_len
, opts
, res
,
3365 if (is_rebase_i(opts
) && !res
)
3366 record_in_rewritten(&item
->commit
->object
.oid
,
3367 peek_command(todo_list
, 1));
3368 if (res
&& is_fixup(item
->command
)) {
3371 return error_failed_squash(item
->commit
, opts
,
3372 item
->arg_len
, item
->arg
);
3373 } else if (res
&& is_rebase_i(opts
) && item
->commit
) {
3375 struct object_id oid
;
3378 * If we are rewording and have either
3379 * fast-forwarded already, or are about to
3380 * create a new root commit, we want to amend,
3381 * otherwise we do not.
3383 if (item
->command
== TODO_REWORD
&&
3384 !get_oid("HEAD", &oid
) &&
3385 (oideq(&item
->commit
->object
.oid
, &oid
) ||
3386 (opts
->have_squash_onto
&&
3387 oideq(&opts
->squash_onto
, &oid
))))
3390 return res
| error_with_patch(item
->commit
,
3391 item
->arg
, item
->arg_len
, opts
,
3394 } else if (item
->command
== TODO_EXEC
) {
3395 char *end_of_arg
= (char *)(item
->arg
+ item
->arg_len
);
3396 int saved
= *end_of_arg
;
3400 res
= do_exec(item
->arg
);
3401 *end_of_arg
= saved
;
3403 /* Reread the todo file if it has changed. */
3405 ; /* fall through */
3406 else if (stat(get_todo_path(opts
), &st
))
3407 res
= error_errno(_("could not stat '%s'"),
3408 get_todo_path(opts
));
3409 else if (match_stat_data(&todo_list
->stat
, &st
)) {
3410 todo_list_release(todo_list
);
3411 if (read_populate_todo(todo_list
, opts
))
3412 res
= -1; /* message was printed */
3413 /* `current` will be incremented below */
3414 todo_list
->current
= -1;
3416 } else if (item
->command
== TODO_LABEL
) {
3417 if ((res
= do_label(item
->arg
, item
->arg_len
)))
3419 } else if (item
->command
== TODO_RESET
) {
3420 if ((res
= do_reset(item
->arg
, item
->arg_len
, opts
)))
3422 } else if (item
->command
== TODO_MERGE
) {
3423 if ((res
= do_merge(item
->commit
,
3424 item
->arg
, item
->arg_len
,
3425 item
->flags
, opts
)) < 0)
3427 else if (item
->commit
)
3428 record_in_rewritten(&item
->commit
->object
.oid
,
3429 peek_command(todo_list
, 1));
3431 /* failed with merge conflicts */
3432 return error_with_patch(item
->commit
,
3434 item
->arg_len
, opts
,
3436 } else if (!is_noop(item
->command
))
3437 return error(_("unknown command %d"), item
->command
);
3440 advise(_(rescheduled_advice
),
3441 get_item_line_length(todo_list
,
3442 todo_list
->current
),
3443 get_item_line(todo_list
, todo_list
->current
));
3444 todo_list
->current
--;
3445 if (save_todo(todo_list
, opts
))
3448 return error_with_patch(item
->commit
,
3450 item
->arg_len
, opts
,
3454 todo_list
->current
++;
3459 if (is_rebase_i(opts
)) {
3460 struct strbuf head_ref
= STRBUF_INIT
, buf
= STRBUF_INIT
;
3463 /* Stopped in the middle, as planned? */
3464 if (todo_list
->current
< todo_list
->nr
)
3467 if (read_oneliner(&head_ref
, rebase_path_head_name(), 0) &&
3468 starts_with(head_ref
.buf
, "refs/")) {
3470 struct object_id head
, orig
;
3473 if (get_oid("HEAD", &head
)) {
3474 res
= error(_("cannot read HEAD"));
3476 strbuf_release(&head_ref
);
3477 strbuf_release(&buf
);
3480 if (!read_oneliner(&buf
, rebase_path_orig_head(), 0) ||
3481 get_oid_hex(buf
.buf
, &orig
)) {
3482 res
= error(_("could not read orig-head"));
3483 goto cleanup_head_ref
;
3486 if (!read_oneliner(&buf
, rebase_path_onto(), 0)) {
3487 res
= error(_("could not read 'onto'"));
3488 goto cleanup_head_ref
;
3490 msg
= reflog_message(opts
, "finish", "%s onto %s",
3491 head_ref
.buf
, buf
.buf
);
3492 if (update_ref(msg
, head_ref
.buf
, &head
, &orig
,
3493 REF_NO_DEREF
, UPDATE_REFS_MSG_ON_ERR
)) {
3494 res
= error(_("could not update %s"),
3496 goto cleanup_head_ref
;
3498 msg
= reflog_message(opts
, "finish", "returning to %s",
3500 if (create_symref("HEAD", head_ref
.buf
, msg
)) {
3501 res
= error(_("could not update HEAD to %s"),
3503 goto cleanup_head_ref
;
3508 if (opts
->verbose
) {
3509 struct rev_info log_tree_opt
;
3510 struct object_id orig
, head
;
3512 memset(&log_tree_opt
, 0, sizeof(log_tree_opt
));
3513 init_revisions(&log_tree_opt
, NULL
);
3514 log_tree_opt
.diff
= 1;
3515 log_tree_opt
.diffopt
.output_format
=
3516 DIFF_FORMAT_DIFFSTAT
;
3517 log_tree_opt
.disable_stdin
= 1;
3519 if (read_oneliner(&buf
, rebase_path_orig_head(), 0) &&
3520 !get_oid(buf
.buf
, &orig
) &&
3521 !get_oid("HEAD", &head
)) {
3522 diff_tree_oid(&orig
, &head
, "",
3523 &log_tree_opt
.diffopt
);
3524 log_tree_diff_flush(&log_tree_opt
);
3527 flush_rewritten_pending();
3528 if (!stat(rebase_path_rewritten_list(), &st
) &&
3530 struct child_process child
= CHILD_PROCESS_INIT
;
3531 const char *post_rewrite_hook
=
3532 find_hook("post-rewrite");
3534 child
.in
= open(rebase_path_rewritten_list(), O_RDONLY
);
3536 argv_array_push(&child
.args
, "notes");
3537 argv_array_push(&child
.args
, "copy");
3538 argv_array_push(&child
.args
, "--for-rewrite=rebase");
3539 /* we don't care if this copying failed */
3540 run_command(&child
);
3542 if (post_rewrite_hook
) {
3543 struct child_process hook
= CHILD_PROCESS_INIT
;
3545 hook
.in
= open(rebase_path_rewritten_list(),
3547 hook
.stdout_to_stderr
= 1;
3548 argv_array_push(&hook
.args
, post_rewrite_hook
);
3549 argv_array_push(&hook
.args
, "rebase");
3550 /* we don't care if this hook failed */
3554 apply_autostash(opts
);
3556 fprintf(stderr
, "Successfully rebased and updated %s.\n",
3559 strbuf_release(&buf
);
3560 strbuf_release(&head_ref
);
3564 * Sequence of picks finished successfully; cleanup by
3565 * removing the .git/sequencer directory
3567 return sequencer_remove_state(opts
);
3570 static int continue_single_pick(void)
3572 const char *argv
[] = { "commit", NULL
};
3574 if (!file_exists(git_path_cherry_pick_head(the_repository
)) &&
3575 !file_exists(git_path_revert_head(the_repository
)))
3576 return error(_("no cherry-pick or revert in progress"));
3577 return run_command_v_opt(argv
, RUN_GIT_CMD
);
3580 static int commit_staged_changes(struct replay_opts
*opts
,
3581 struct todo_list
*todo_list
)
3583 unsigned int flags
= ALLOW_EMPTY
| EDIT_MSG
;
3584 unsigned int final_fixup
= 0, is_clean
;
3586 if (has_unstaged_changes(1))
3587 return error(_("cannot rebase: You have unstaged changes."));
3589 is_clean
= !has_uncommitted_changes(0);
3591 if (file_exists(rebase_path_amend())) {
3592 struct strbuf rev
= STRBUF_INIT
;
3593 struct object_id head
, to_amend
;
3595 if (get_oid("HEAD", &head
))
3596 return error(_("cannot amend non-existing commit"));
3597 if (!read_oneliner(&rev
, rebase_path_amend(), 0))
3598 return error(_("invalid file: '%s'"), rebase_path_amend());
3599 if (get_oid_hex(rev
.buf
, &to_amend
))
3600 return error(_("invalid contents: '%s'"),
3601 rebase_path_amend());
3602 if (!is_clean
&& !oideq(&head
, &to_amend
))
3603 return error(_("\nYou have uncommitted changes in your "
3604 "working tree. Please, commit them\n"
3605 "first and then run 'git rebase "
3606 "--continue' again."));
3608 * When skipping a failed fixup/squash, we need to edit the
3609 * commit message, the current fixup list and count, and if it
3610 * was the last fixup/squash in the chain, we need to clean up
3611 * the commit message and if there was a squash, let the user
3614 if (!is_clean
|| !opts
->current_fixup_count
)
3615 ; /* this is not the final fixup */
3616 else if (!oideq(&head
, &to_amend
) ||
3617 !file_exists(rebase_path_stopped_sha())) {
3618 /* was a final fixup or squash done manually? */
3619 if (!is_fixup(peek_command(todo_list
, 0))) {
3620 unlink(rebase_path_fixup_msg());
3621 unlink(rebase_path_squash_msg());
3622 unlink(rebase_path_current_fixups());
3623 strbuf_reset(&opts
->current_fixups
);
3624 opts
->current_fixup_count
= 0;
3627 /* we are in a fixup/squash chain */
3628 const char *p
= opts
->current_fixups
.buf
;
3629 int len
= opts
->current_fixups
.len
;
3631 opts
->current_fixup_count
--;
3633 BUG("Incorrect current_fixups:\n%s", p
);
3634 while (len
&& p
[len
- 1] != '\n')
3636 strbuf_setlen(&opts
->current_fixups
, len
);
3637 if (write_message(p
, len
, rebase_path_current_fixups(),
3639 return error(_("could not write file: '%s'"),
3640 rebase_path_current_fixups());
3643 * If a fixup/squash in a fixup/squash chain failed, the
3644 * commit message is already correct, no need to commit
3647 * Only if it is the final command in the fixup/squash
3648 * chain, and only if the chain is longer than a single
3649 * fixup/squash command (which was just skipped), do we
3650 * actually need to re-commit with a cleaned up commit
3653 if (opts
->current_fixup_count
> 0 &&
3654 !is_fixup(peek_command(todo_list
, 0))) {
3657 * If there was not a single "squash" in the
3658 * chain, we only need to clean up the commit
3659 * message, no need to bother the user with
3660 * opening the commit message in the editor.
3662 if (!starts_with(p
, "squash ") &&
3663 !strstr(p
, "\nsquash "))
3664 flags
= (flags
& ~EDIT_MSG
) | CLEANUP_MSG
;
3665 } else if (is_fixup(peek_command(todo_list
, 0))) {
3667 * We need to update the squash message to skip
3668 * the latest commit message.
3670 struct commit
*commit
;
3671 const char *path
= rebase_path_squash_msg();
3673 if (parse_head(&commit
) ||
3674 !(p
= get_commit_buffer(commit
, NULL
)) ||
3675 write_message(p
, strlen(p
), path
, 0)) {
3676 unuse_commit_buffer(commit
, p
);
3677 return error(_("could not write file: "
3680 unuse_commit_buffer(commit
, p
);
3684 strbuf_release(&rev
);
3689 const char *cherry_pick_head
= git_path_cherry_pick_head(the_repository
);
3691 if (file_exists(cherry_pick_head
) && unlink(cherry_pick_head
))
3692 return error(_("could not remove CHERRY_PICK_HEAD"));
3697 if (run_git_commit(final_fixup
? NULL
: rebase_path_message(),
3699 return error(_("could not commit staged changes."));
3700 unlink(rebase_path_amend());
3702 unlink(rebase_path_fixup_msg());
3703 unlink(rebase_path_squash_msg());
3705 if (opts
->current_fixup_count
> 0) {
3707 * Whether final fixup or not, we just cleaned up the commit
3710 unlink(rebase_path_current_fixups());
3711 strbuf_reset(&opts
->current_fixups
);
3712 opts
->current_fixup_count
= 0;
3717 int sequencer_continue(struct replay_opts
*opts
)
3719 struct todo_list todo_list
= TODO_LIST_INIT
;
3722 if (read_and_refresh_cache(opts
))
3725 if (read_populate_opts(opts
))
3727 if (is_rebase_i(opts
)) {
3728 if ((res
= read_populate_todo(&todo_list
, opts
)))
3729 goto release_todo_list
;
3730 if (commit_staged_changes(opts
, &todo_list
))
3732 } else if (!file_exists(get_todo_path(opts
)))
3733 return continue_single_pick();
3734 else if ((res
= read_populate_todo(&todo_list
, opts
)))
3735 goto release_todo_list
;
3737 if (!is_rebase_i(opts
)) {
3738 /* Verify that the conflict has been resolved */
3739 if (file_exists(git_path_cherry_pick_head(the_repository
)) ||
3740 file_exists(git_path_revert_head(the_repository
))) {
3741 res
= continue_single_pick();
3743 goto release_todo_list
;
3745 if (index_differs_from("HEAD", NULL
, 0)) {
3746 res
= error_dirty_index(opts
);
3747 goto release_todo_list
;
3749 todo_list
.current
++;
3750 } else if (file_exists(rebase_path_stopped_sha())) {
3751 struct strbuf buf
= STRBUF_INIT
;
3752 struct object_id oid
;
3754 if (read_oneliner(&buf
, rebase_path_stopped_sha(), 1) &&
3755 !get_oid_committish(buf
.buf
, &oid
))
3756 record_in_rewritten(&oid
, peek_command(&todo_list
, 0));
3757 strbuf_release(&buf
);
3760 res
= pick_commits(&todo_list
, opts
);
3762 todo_list_release(&todo_list
);
3766 static int single_pick(struct commit
*cmit
, struct replay_opts
*opts
)
3768 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
3769 return do_pick_commit(opts
->action
== REPLAY_PICK
?
3770 TODO_PICK
: TODO_REVERT
, cmit
, opts
, 0);
3773 int sequencer_pick_revisions(struct replay_opts
*opts
)
3775 struct todo_list todo_list
= TODO_LIST_INIT
;
3776 struct object_id oid
;
3780 if (read_and_refresh_cache(opts
))
3783 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
3784 struct object_id oid
;
3785 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
3787 /* This happens when using --stdin. */
3791 if (!get_oid(name
, &oid
)) {
3792 if (!lookup_commit_reference_gently(the_repository
, &oid
, 1)) {
3793 enum object_type type
= oid_object_info(the_repository
,
3796 return error(_("%s: can't cherry-pick a %s"),
3797 name
, type_name(type
));
3800 return error(_("%s: bad revision"), name
);
3804 * If we were called as "git cherry-pick <commit>", just
3805 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3806 * REVERT_HEAD, and don't touch the sequencer state.
3807 * This means it is possible to cherry-pick in the middle
3808 * of a cherry-pick sequence.
3810 if (opts
->revs
->cmdline
.nr
== 1 &&
3811 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
3812 opts
->revs
->no_walk
&&
3813 !opts
->revs
->cmdline
.rev
->flags
) {
3814 struct commit
*cmit
;
3815 if (prepare_revision_walk(opts
->revs
))
3816 return error(_("revision walk setup failed"));
3817 cmit
= get_revision(opts
->revs
);
3819 return error(_("empty commit set passed"));
3820 if (get_revision(opts
->revs
))
3821 BUG("unexpected extra commit from walk");
3822 return single_pick(cmit
, opts
);
3826 * Start a new cherry-pick/ revert sequence; but
3827 * first, make sure that an existing one isn't in
3831 if (walk_revs_populate_todo(&todo_list
, opts
) ||
3832 create_seq_dir() < 0)
3834 if (get_oid("HEAD", &oid
) && (opts
->action
== REPLAY_REVERT
))
3835 return error(_("can't revert as initial commit"));
3836 if (save_head(oid_to_hex(&oid
)))
3838 if (save_opts(opts
))
3840 update_abort_safety_file();
3841 res
= pick_commits(&todo_list
, opts
);
3842 todo_list_release(&todo_list
);
3846 void append_signoff(struct strbuf
*msgbuf
, size_t ignore_footer
, unsigned flag
)
3848 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
3849 struct strbuf sob
= STRBUF_INIT
;
3852 strbuf_addstr(&sob
, sign_off_header
);
3853 strbuf_addstr(&sob
, fmt_name(getenv("GIT_COMMITTER_NAME"),
3854 getenv("GIT_COMMITTER_EMAIL")));
3855 strbuf_addch(&sob
, '\n');
3858 strbuf_complete_line(msgbuf
);
3861 * If the whole message buffer is equal to the sob, pretend that we
3862 * found a conforming footer with a matching sob
3864 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
3865 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
3868 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
3871 const char *append_newlines
= NULL
;
3872 size_t len
= msgbuf
->len
- ignore_footer
;
3876 * The buffer is completely empty. Leave foom for
3877 * the title and body to be filled in by the user.
3879 append_newlines
= "\n\n";
3880 } else if (len
== 1) {
3882 * Buffer contains a single newline. Add another
3883 * so that we leave room for the title and body.
3885 append_newlines
= "\n";
3886 } else if (msgbuf
->buf
[len
- 2] != '\n') {
3888 * Buffer ends with a single newline. Add another
3889 * so that there is an empty line between the message
3892 append_newlines
= "\n";
3893 } /* else, the buffer already ends with two newlines. */
3895 if (append_newlines
)
3896 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
3897 append_newlines
, strlen(append_newlines
));
3900 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
3901 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
3904 strbuf_release(&sob
);
3907 struct labels_entry
{
3908 struct hashmap_entry entry
;
3909 char label
[FLEX_ARRAY
];
3912 static int labels_cmp(const void *fndata
, const struct labels_entry
*a
,
3913 const struct labels_entry
*b
, const void *key
)
3915 return key
? strcmp(a
->label
, key
) : strcmp(a
->label
, b
->label
);
3918 struct string_entry
{
3919 struct oidmap_entry entry
;
3920 char string
[FLEX_ARRAY
];
3923 struct label_state
{
3924 struct oidmap commit2label
;
3925 struct hashmap labels
;
3929 static const char *label_oid(struct object_id
*oid
, const char *label
,
3930 struct label_state
*state
)
3932 struct labels_entry
*labels_entry
;
3933 struct string_entry
*string_entry
;
3934 struct object_id dummy
;
3938 string_entry
= oidmap_get(&state
->commit2label
, oid
);
3940 return string_entry
->string
;
3943 * For "uninteresting" commits, i.e. commits that are not to be
3944 * rebased, and which can therefore not be labeled, we use a unique
3945 * abbreviation of the commit name. This is slightly more complicated
3946 * than calling find_unique_abbrev() because we also need to make
3947 * sure that the abbreviation does not conflict with any other
3950 * We disallow "interesting" commits to be labeled by a string that
3951 * is a valid full-length hash, to ensure that we always can find an
3952 * abbreviation for any uninteresting commit's names that does not
3953 * clash with any other label.
3958 strbuf_reset(&state
->buf
);
3959 strbuf_grow(&state
->buf
, GIT_SHA1_HEXSZ
);
3960 label
= p
= state
->buf
.buf
;
3962 find_unique_abbrev_r(p
, oid
, default_abbrev
);
3965 * We may need to extend the abbreviated hash so that there is
3966 * no conflicting label.
3968 if (hashmap_get_from_hash(&state
->labels
, strihash(p
), p
)) {
3969 size_t i
= strlen(p
) + 1;
3971 oid_to_hex_r(p
, oid
);
3972 for (; i
< GIT_SHA1_HEXSZ
; i
++) {
3975 if (!hashmap_get_from_hash(&state
->labels
,
3981 } else if (((len
= strlen(label
)) == the_hash_algo
->hexsz
&&
3982 !get_oid_hex(label
, &dummy
)) ||
3983 (len
== 1 && *label
== '#') ||
3984 hashmap_get_from_hash(&state
->labels
,
3985 strihash(label
), label
)) {
3987 * If the label already exists, or if the label is a valid full
3988 * OID, or the label is a '#' (which we use as a separator
3989 * between merge heads and oneline), we append a dash and a
3990 * number to make it unique.
3992 struct strbuf
*buf
= &state
->buf
;
3995 strbuf_add(buf
, label
, len
);
3997 for (i
= 2; ; i
++) {
3998 strbuf_setlen(buf
, len
);
3999 strbuf_addf(buf
, "-%d", i
);
4000 if (!hashmap_get_from_hash(&state
->labels
,
4009 FLEX_ALLOC_STR(labels_entry
, label
, label
);
4010 hashmap_entry_init(labels_entry
, strihash(label
));
4011 hashmap_add(&state
->labels
, labels_entry
);
4013 FLEX_ALLOC_STR(string_entry
, string
, label
);
4014 oidcpy(&string_entry
->entry
.oid
, oid
);
4015 oidmap_put(&state
->commit2label
, string_entry
);
4017 return string_entry
->string
;
4020 static int make_script_with_merges(struct pretty_print_context
*pp
,
4021 struct rev_info
*revs
, FILE *out
,
4024 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
4025 int rebase_cousins
= flags
& TODO_LIST_REBASE_COUSINS
;
4026 struct strbuf buf
= STRBUF_INIT
, oneline
= STRBUF_INIT
;
4027 struct strbuf label
= STRBUF_INIT
;
4028 struct commit_list
*commits
= NULL
, **tail
= &commits
, *iter
;
4029 struct commit_list
*tips
= NULL
, **tips_tail
= &tips
;
4030 struct commit
*commit
;
4031 struct oidmap commit2todo
= OIDMAP_INIT
;
4032 struct string_entry
*entry
;
4033 struct oidset interesting
= OIDSET_INIT
, child_seen
= OIDSET_INIT
,
4034 shown
= OIDSET_INIT
;
4035 struct label_state state
= { OIDMAP_INIT
, { NULL
}, STRBUF_INIT
};
4037 int abbr
= flags
& TODO_LIST_ABBREVIATE_CMDS
;
4038 const char *cmd_pick
= abbr
? "p" : "pick",
4039 *cmd_label
= abbr
? "l" : "label",
4040 *cmd_reset
= abbr
? "t" : "reset",
4041 *cmd_merge
= abbr
? "m" : "merge";
4043 oidmap_init(&commit2todo
, 0);
4044 oidmap_init(&state
.commit2label
, 0);
4045 hashmap_init(&state
.labels
, (hashmap_cmp_fn
) labels_cmp
, NULL
, 0);
4046 strbuf_init(&state
.buf
, 32);
4048 if (revs
->cmdline
.nr
&& (revs
->cmdline
.rev
[0].flags
& BOTTOM
)) {
4049 struct object_id
*oid
= &revs
->cmdline
.rev
[0].item
->oid
;
4050 FLEX_ALLOC_STR(entry
, string
, "onto");
4051 oidcpy(&entry
->entry
.oid
, oid
);
4052 oidmap_put(&state
.commit2label
, entry
);
4057 * - get onelines for all commits
4058 * - gather all branch tips (i.e. 2nd or later parents of merges)
4059 * - label all branch tips
4061 while ((commit
= get_revision(revs
))) {
4062 struct commit_list
*to_merge
;
4063 const char *p1
, *p2
;
4064 struct object_id
*oid
;
4067 tail
= &commit_list_insert(commit
, tail
)->next
;
4068 oidset_insert(&interesting
, &commit
->object
.oid
);
4070 is_empty
= is_original_commit_empty(commit
);
4071 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
))
4074 strbuf_reset(&oneline
);
4075 pretty_print_commit(pp
, commit
, &oneline
);
4077 to_merge
= commit
->parents
? commit
->parents
->next
: NULL
;
4079 /* non-merge commit: easy case */
4081 if (!keep_empty
&& is_empty
)
4082 strbuf_addf(&buf
, "%c ", comment_line_char
);
4083 strbuf_addf(&buf
, "%s %s %s", cmd_pick
,
4084 oid_to_hex(&commit
->object
.oid
),
4087 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
4088 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
4089 oidmap_put(&commit2todo
, entry
);
4094 /* Create a label */
4095 strbuf_reset(&label
);
4096 if (skip_prefix(oneline
.buf
, "Merge ", &p1
) &&
4097 (p1
= strchr(p1
, '\'')) &&
4098 (p2
= strchr(++p1
, '\'')))
4099 strbuf_add(&label
, p1
, p2
- p1
);
4100 else if (skip_prefix(oneline
.buf
, "Merge pull request ",
4102 (p1
= strstr(p1
, " from ")))
4103 strbuf_addstr(&label
, p1
+ strlen(" from "));
4105 strbuf_addbuf(&label
, &oneline
);
4107 for (p1
= label
.buf
; *p1
; p1
++)
4112 strbuf_addf(&buf
, "%s -C %s",
4113 cmd_merge
, oid_to_hex(&commit
->object
.oid
));
4115 /* label the tips of merged branches */
4116 for (; to_merge
; to_merge
= to_merge
->next
) {
4117 oid
= &to_merge
->item
->object
.oid
;
4118 strbuf_addch(&buf
, ' ');
4120 if (!oidset_contains(&interesting
, oid
)) {
4121 strbuf_addstr(&buf
, label_oid(oid
, NULL
,
4126 tips_tail
= &commit_list_insert(to_merge
->item
,
4129 strbuf_addstr(&buf
, label_oid(oid
, label
.buf
, &state
));
4131 strbuf_addf(&buf
, " # %s", oneline
.buf
);
4133 FLEX_ALLOC_STR(entry
, string
, buf
.buf
);
4134 oidcpy(&entry
->entry
.oid
, &commit
->object
.oid
);
4135 oidmap_put(&commit2todo
, entry
);
4140 * - label branch points
4141 * - add HEAD to the branch tips
4143 for (iter
= commits
; iter
; iter
= iter
->next
) {
4144 struct commit_list
*parent
= iter
->item
->parents
;
4145 for (; parent
; parent
= parent
->next
) {
4146 struct object_id
*oid
= &parent
->item
->object
.oid
;
4147 if (!oidset_contains(&interesting
, oid
))
4149 if (!oidset_contains(&child_seen
, oid
))
4150 oidset_insert(&child_seen
, oid
);
4152 label_oid(oid
, "branch-point", &state
);
4155 /* Add HEAD as implict "tip of branch" */
4157 tips_tail
= &commit_list_insert(iter
->item
,
4162 * Third phase: output the todo list. This is a bit tricky, as we
4163 * want to avoid jumping back and forth between revisions. To
4164 * accomplish that goal, we walk backwards from the branch tips,
4165 * gathering commits not yet shown, reversing the list on the fly,
4166 * then outputting that list (labeling revisions as needed).
4168 fprintf(out
, "%s onto\n", cmd_label
);
4169 for (iter
= tips
; iter
; iter
= iter
->next
) {
4170 struct commit_list
*list
= NULL
, *iter2
;
4172 commit
= iter
->item
;
4173 if (oidset_contains(&shown
, &commit
->object
.oid
))
4175 entry
= oidmap_get(&state
.commit2label
, &commit
->object
.oid
);
4178 fprintf(out
, "\n%c Branch %s\n", comment_line_char
, entry
->string
);
4182 while (oidset_contains(&interesting
, &commit
->object
.oid
) &&
4183 !oidset_contains(&shown
, &commit
->object
.oid
)) {
4184 commit_list_insert(commit
, &list
);
4185 if (!commit
->parents
) {
4189 commit
= commit
->parents
->item
;
4193 fprintf(out
, "%s %s\n", cmd_reset
,
4194 rebase_cousins
? "onto" : "[new root]");
4196 const char *to
= NULL
;
4198 entry
= oidmap_get(&state
.commit2label
,
4199 &commit
->object
.oid
);
4202 else if (!rebase_cousins
)
4203 to
= label_oid(&commit
->object
.oid
, NULL
,
4206 if (!to
|| !strcmp(to
, "onto"))
4207 fprintf(out
, "%s onto\n", cmd_reset
);
4209 strbuf_reset(&oneline
);
4210 pretty_print_commit(pp
, commit
, &oneline
);
4211 fprintf(out
, "%s %s # %s\n",
4212 cmd_reset
, to
, oneline
.buf
);
4216 for (iter2
= list
; iter2
; iter2
= iter2
->next
) {
4217 struct object_id
*oid
= &iter2
->item
->object
.oid
;
4218 entry
= oidmap_get(&commit2todo
, oid
);
4219 /* only show if not already upstream */
4221 fprintf(out
, "%s\n", entry
->string
);
4222 entry
= oidmap_get(&state
.commit2label
, oid
);
4224 fprintf(out
, "%s %s\n",
4225 cmd_label
, entry
->string
);
4226 oidset_insert(&shown
, oid
);
4229 free_commit_list(list
);
4232 free_commit_list(commits
);
4233 free_commit_list(tips
);
4235 strbuf_release(&label
);
4236 strbuf_release(&oneline
);
4237 strbuf_release(&buf
);
4239 oidmap_free(&commit2todo
, 1);
4240 oidmap_free(&state
.commit2label
, 1);
4241 hashmap_free(&state
.labels
, 1);
4242 strbuf_release(&state
.buf
);
4247 int sequencer_make_script(FILE *out
, int argc
, const char **argv
,
4250 char *format
= NULL
;
4251 struct pretty_print_context pp
= {0};
4252 struct strbuf buf
= STRBUF_INIT
;
4253 struct rev_info revs
;
4254 struct commit
*commit
;
4255 int keep_empty
= flags
& TODO_LIST_KEEP_EMPTY
;
4256 const char *insn
= flags
& TODO_LIST_ABBREVIATE_CMDS
? "p" : "pick";
4257 int rebase_merges
= flags
& TODO_LIST_REBASE_MERGES
;
4259 init_revisions(&revs
, NULL
);
4260 revs
.verbose_header
= 1;
4262 revs
.max_parents
= 1;
4263 revs
.cherry_mark
= 1;
4266 revs
.right_only
= 1;
4267 revs
.sort_order
= REV_SORT_IN_GRAPH_ORDER
;
4268 revs
.topo_order
= 1;
4270 revs
.pretty_given
= 1;
4271 git_config_get_string("rebase.instructionFormat", &format
);
4272 if (!format
|| !*format
) {
4274 format
= xstrdup("%s");
4276 get_commit_format(format
, &revs
);
4278 pp
.fmt
= revs
.commit_format
;
4279 pp
.output_encoding
= get_log_output_encoding();
4281 if (setup_revisions(argc
, argv
, &revs
, NULL
) > 1)
4282 return error(_("make_script: unhandled options"));
4284 if (prepare_revision_walk(&revs
) < 0)
4285 return error(_("make_script: error preparing revisions"));
4288 return make_script_with_merges(&pp
, &revs
, out
, flags
);
4290 while ((commit
= get_revision(&revs
))) {
4291 int is_empty
= is_original_commit_empty(commit
);
4293 if (!is_empty
&& (commit
->object
.flags
& PATCHSAME
))
4296 if (!keep_empty
&& is_empty
)
4297 strbuf_addf(&buf
, "%c ", comment_line_char
);
4298 strbuf_addf(&buf
, "%s %s ", insn
,
4299 oid_to_hex(&commit
->object
.oid
));
4300 pretty_print_commit(&pp
, commit
, &buf
);
4301 strbuf_addch(&buf
, '\n');
4302 fputs(buf
.buf
, out
);
4304 strbuf_release(&buf
);
4309 * Add commands after pick and (series of) squash/fixup commands
4312 int sequencer_add_exec_commands(const char *commands
)
4314 const char *todo_file
= rebase_path_todo();
4315 struct todo_list todo_list
= TODO_LIST_INIT
;
4316 struct strbuf
*buf
= &todo_list
.buf
;
4317 size_t offset
= 0, commands_len
= strlen(commands
);
4320 if (strbuf_read_file(&todo_list
.buf
, todo_file
, 0) < 0)
4321 return error(_("could not read '%s'."), todo_file
);
4323 if (parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
)) {
4324 todo_list_release(&todo_list
);
4325 return error(_("unusable todo list: '%s'"), todo_file
);
4329 * Insert <commands> after every pick. Here, fixup/squash chains
4330 * are considered part of the pick, so we insert the commands *after*
4331 * those chains if there are any.
4334 for (i
= 0; i
< todo_list
.nr
; i
++) {
4335 enum todo_command command
= todo_list
.items
[i
].command
;
4338 /* skip fixup/squash chains */
4339 if (command
== TODO_COMMENT
)
4341 else if (is_fixup(command
)) {
4346 todo_list
.items
[insert
].offset_in_buf
+
4347 offset
, commands
, commands_len
);
4348 offset
+= commands_len
;
4352 if (command
== TODO_PICK
|| command
== TODO_MERGE
)
4356 /* insert or append final <commands> */
4357 if (insert
>= 0 && insert
< todo_list
.nr
)
4358 strbuf_insert(buf
, todo_list
.items
[insert
].offset_in_buf
+
4359 offset
, commands
, commands_len
);
4360 else if (insert
>= 0 || !offset
)
4361 strbuf_add(buf
, commands
, commands_len
);
4363 i
= write_message(buf
->buf
, buf
->len
, todo_file
, 0);
4364 todo_list_release(&todo_list
);
4368 int transform_todos(unsigned flags
)
4370 const char *todo_file
= rebase_path_todo();
4371 struct todo_list todo_list
= TODO_LIST_INIT
;
4372 struct strbuf buf
= STRBUF_INIT
;
4373 struct todo_item
*item
;
4376 if (strbuf_read_file(&todo_list
.buf
, todo_file
, 0) < 0)
4377 return error(_("could not read '%s'."), todo_file
);
4379 if (parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
)) {
4380 todo_list_release(&todo_list
);
4381 return error(_("unusable todo list: '%s'"), todo_file
);
4384 for (item
= todo_list
.items
, i
= 0; i
< todo_list
.nr
; i
++, item
++) {
4385 /* if the item is not a command write it and continue */
4386 if (item
->command
>= TODO_COMMENT
) {
4387 strbuf_addf(&buf
, "%.*s\n", item
->arg_len
, item
->arg
);
4391 /* add command to the buffer */
4392 if (flags
& TODO_LIST_ABBREVIATE_CMDS
)
4393 strbuf_addch(&buf
, command_to_char(item
->command
));
4395 strbuf_addstr(&buf
, command_to_string(item
->command
));
4399 const char *oid
= flags
& TODO_LIST_SHORTEN_IDS
?
4400 short_commit_name(item
->commit
) :
4401 oid_to_hex(&item
->commit
->object
.oid
);
4403 if (item
->command
== TODO_MERGE
) {
4404 if (item
->flags
& TODO_EDIT_MERGE_MSG
)
4405 strbuf_addstr(&buf
, " -c");
4407 strbuf_addstr(&buf
, " -C");
4410 strbuf_addf(&buf
, " %s", oid
);
4413 /* add all the rest */
4415 strbuf_addch(&buf
, '\n');
4417 strbuf_addf(&buf
, " %.*s\n", item
->arg_len
, item
->arg
);
4420 i
= write_message(buf
.buf
, buf
.len
, todo_file
, 0);
4421 todo_list_release(&todo_list
);
4426 CHECK_IGNORE
= 0, CHECK_WARN
, CHECK_ERROR
4429 static enum check_level
get_missing_commit_check_level(void)
4433 if (git_config_get_value("rebase.missingcommitscheck", &value
) ||
4434 !strcasecmp("ignore", value
))
4435 return CHECK_IGNORE
;
4436 if (!strcasecmp("warn", value
))
4438 if (!strcasecmp("error", value
))
4440 warning(_("unrecognized setting %s for option "
4441 "rebase.missingCommitsCheck. Ignoring."), value
);
4442 return CHECK_IGNORE
;
4445 define_commit_slab(commit_seen
, unsigned char);
4447 * Check if the user dropped some commits by mistake
4448 * Behaviour determined by rebase.missingCommitsCheck.
4449 * Check if there is an unrecognized command or a
4450 * bad SHA-1 in a command.
4452 int check_todo_list(void)
4454 enum check_level check_level
= get_missing_commit_check_level();
4455 struct strbuf todo_file
= STRBUF_INIT
;
4456 struct todo_list todo_list
= TODO_LIST_INIT
;
4457 struct strbuf missing
= STRBUF_INIT
;
4458 int advise_to_edit_todo
= 0, res
= 0, i
;
4459 struct commit_seen commit_seen
;
4461 init_commit_seen(&commit_seen
);
4463 strbuf_addstr(&todo_file
, rebase_path_todo());
4464 if (strbuf_read_file_or_whine(&todo_list
.buf
, todo_file
.buf
) < 0) {
4468 advise_to_edit_todo
= res
=
4469 parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
);
4471 if (res
|| check_level
== CHECK_IGNORE
)
4474 /* Mark the commits in git-rebase-todo as seen */
4475 for (i
= 0; i
< todo_list
.nr
; i
++) {
4476 struct commit
*commit
= todo_list
.items
[i
].commit
;
4478 *commit_seen_at(&commit_seen
, commit
) = 1;
4481 todo_list_release(&todo_list
);
4482 strbuf_addstr(&todo_file
, ".backup");
4483 if (strbuf_read_file_or_whine(&todo_list
.buf
, todo_file
.buf
) < 0) {
4487 strbuf_release(&todo_file
);
4488 res
= !!parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
);
4490 /* Find commits in git-rebase-todo.backup yet unseen */
4491 for (i
= todo_list
.nr
- 1; i
>= 0; i
--) {
4492 struct todo_item
*item
= todo_list
.items
+ i
;
4493 struct commit
*commit
= item
->commit
;
4494 if (commit
&& !*commit_seen_at(&commit_seen
, commit
)) {
4495 strbuf_addf(&missing
, " - %s %.*s\n",
4496 short_commit_name(commit
),
4497 item
->arg_len
, item
->arg
);
4498 *commit_seen_at(&commit_seen
, commit
) = 1;
4502 /* Warn about missing commits */
4506 if (check_level
== CHECK_ERROR
)
4507 advise_to_edit_todo
= res
= 1;
4510 _("Warning: some commits may have been dropped accidentally.\n"
4511 "Dropped commits (newer to older):\n"));
4513 /* Make the list user-friendly and display */
4514 fputs(missing
.buf
, stderr
);
4515 strbuf_release(&missing
);
4517 fprintf(stderr
, _("To avoid this message, use \"drop\" to "
4518 "explicitly remove a commit.\n\n"
4519 "Use 'git config rebase.missingCommitsCheck' to change "
4520 "the level of warnings.\n"
4521 "The possible behaviours are: ignore, warn, error.\n\n"));
4524 clear_commit_seen(&commit_seen
);
4525 strbuf_release(&todo_file
);
4526 todo_list_release(&todo_list
);
4528 if (advise_to_edit_todo
)
4530 _("You can fix this with 'git rebase --edit-todo' "
4531 "and then run 'git rebase --continue'.\n"
4532 "Or you can abort the rebase with 'git rebase"
4538 static int rewrite_file(const char *path
, const char *buf
, size_t len
)
4541 int fd
= open(path
, O_WRONLY
| O_TRUNC
);
4543 return error_errno(_("could not open '%s' for writing"), path
);
4544 if (write_in_full(fd
, buf
, len
) < 0)
4545 rc
= error_errno(_("could not write to '%s'"), path
);
4546 if (close(fd
) && !rc
)
4547 rc
= error_errno(_("could not close '%s'"), path
);
4551 /* skip picking commits whose parents are unchanged */
4552 int skip_unnecessary_picks(void)
4554 const char *todo_file
= rebase_path_todo();
4555 struct strbuf buf
= STRBUF_INIT
;
4556 struct todo_list todo_list
= TODO_LIST_INIT
;
4557 struct object_id onto_oid
, *oid
= &onto_oid
, *parent_oid
;
4560 if (!read_oneliner(&buf
, rebase_path_onto(), 0))
4561 return error(_("could not read 'onto'"));
4562 if (get_oid(buf
.buf
, &onto_oid
)) {
4563 strbuf_release(&buf
);
4564 return error(_("need a HEAD to fixup"));
4566 strbuf_release(&buf
);
4568 if (strbuf_read_file_or_whine(&todo_list
.buf
, todo_file
) < 0)
4570 if (parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
) < 0) {
4571 todo_list_release(&todo_list
);
4575 for (i
= 0; i
< todo_list
.nr
; i
++) {
4576 struct todo_item
*item
= todo_list
.items
+ i
;
4578 if (item
->command
>= TODO_NOOP
)
4580 if (item
->command
!= TODO_PICK
)
4582 if (parse_commit(item
->commit
)) {
4583 todo_list_release(&todo_list
);
4584 return error(_("could not parse commit '%s'"),
4585 oid_to_hex(&item
->commit
->object
.oid
));
4587 if (!item
->commit
->parents
)
4588 break; /* root commit */
4589 if (item
->commit
->parents
->next
)
4590 break; /* merge commit */
4591 parent_oid
= &item
->commit
->parents
->item
->object
.oid
;
4592 if (!oideq(parent_oid
, oid
))
4594 oid
= &item
->commit
->object
.oid
;
4597 int offset
= get_item_line_offset(&todo_list
, i
);
4598 const char *done_path
= rebase_path_done();
4600 fd
= open(done_path
, O_CREAT
| O_WRONLY
| O_APPEND
, 0666);
4602 error_errno(_("could not open '%s' for writing"),
4604 todo_list_release(&todo_list
);
4607 if (write_in_full(fd
, todo_list
.buf
.buf
, offset
) < 0) {
4608 error_errno(_("could not write to '%s'"), done_path
);
4609 todo_list_release(&todo_list
);
4615 if (rewrite_file(rebase_path_todo(), todo_list
.buf
.buf
+ offset
,
4616 todo_list
.buf
.len
- offset
) < 0) {
4617 todo_list_release(&todo_list
);
4621 todo_list
.current
= i
;
4622 if (is_fixup(peek_command(&todo_list
, 0)))
4623 record_in_rewritten(oid
, peek_command(&todo_list
, 0));
4626 todo_list_release(&todo_list
);
4627 printf("%s\n", oid_to_hex(oid
));
4632 struct subject2item_entry
{
4633 struct hashmap_entry entry
;
4635 char subject
[FLEX_ARRAY
];
4638 static int subject2item_cmp(const void *fndata
,
4639 const struct subject2item_entry
*a
,
4640 const struct subject2item_entry
*b
, const void *key
)
4642 return key
? strcmp(a
->subject
, key
) : strcmp(a
->subject
, b
->subject
);
4645 define_commit_slab(commit_todo_item
, struct todo_item
*);
4648 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4649 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4650 * after the former, and change "pick" to "fixup"/"squash".
4652 * Note that if the config has specified a custom instruction format, each log
4653 * message will have to be retrieved from the commit (as the oneline in the
4654 * script cannot be trusted) in order to normalize the autosquash arrangement.
4656 int rearrange_squash(void)
4658 const char *todo_file
= rebase_path_todo();
4659 struct todo_list todo_list
= TODO_LIST_INIT
;
4660 struct hashmap subject2item
;
4661 int res
= 0, rearranged
= 0, *next
, *tail
, i
;
4663 struct commit_todo_item commit_todo
;
4665 if (strbuf_read_file_or_whine(&todo_list
.buf
, todo_file
) < 0)
4667 if (parse_insn_buffer(todo_list
.buf
.buf
, &todo_list
) < 0) {
4668 todo_list_release(&todo_list
);
4672 init_commit_todo_item(&commit_todo
);
4674 * The hashmap maps onelines to the respective todo list index.
4676 * If any items need to be rearranged, the next[i] value will indicate
4677 * which item was moved directly after the i'th.
4679 * In that case, last[i] will indicate the index of the latest item to
4680 * be moved to appear after the i'th.
4682 hashmap_init(&subject2item
, (hashmap_cmp_fn
) subject2item_cmp
,
4683 NULL
, todo_list
.nr
);
4684 ALLOC_ARRAY(next
, todo_list
.nr
);
4685 ALLOC_ARRAY(tail
, todo_list
.nr
);
4686 ALLOC_ARRAY(subjects
, todo_list
.nr
);
4687 for (i
= 0; i
< todo_list
.nr
; i
++) {
4688 struct strbuf buf
= STRBUF_INIT
;
4689 struct todo_item
*item
= todo_list
.items
+ i
;
4690 const char *commit_buffer
, *subject
, *p
;
4693 struct subject2item_entry
*entry
;
4695 next
[i
] = tail
[i
] = -1;
4696 if (!item
->commit
|| item
->command
== TODO_DROP
) {
4701 if (is_fixup(item
->command
)) {
4702 todo_list_release(&todo_list
);
4703 clear_commit_todo_item(&commit_todo
);
4704 return error(_("the script was already rearranged."));
4707 *commit_todo_item_at(&commit_todo
, item
->commit
) = item
;
4709 parse_commit(item
->commit
);
4710 commit_buffer
= get_commit_buffer(item
->commit
, NULL
);
4711 find_commit_subject(commit_buffer
, &subject
);
4712 format_subject(&buf
, subject
, " ");
4713 subject
= subjects
[i
] = strbuf_detach(&buf
, &subject_len
);
4714 unuse_commit_buffer(item
->commit
, commit_buffer
);
4715 if ((skip_prefix(subject
, "fixup! ", &p
) ||
4716 skip_prefix(subject
, "squash! ", &p
))) {
4717 struct commit
*commit2
;
4722 if (!skip_prefix(p
, "fixup! ", &p
) &&
4723 !skip_prefix(p
, "squash! ", &p
))
4727 if ((entry
= hashmap_get_from_hash(&subject2item
,
4729 /* found by title */
4731 else if (!strchr(p
, ' ') &&
4733 lookup_commit_reference_by_name(p
)) &&
4734 *commit_todo_item_at(&commit_todo
, commit2
))
4735 /* found by commit name */
4736 i2
= *commit_todo_item_at(&commit_todo
, commit2
)
4739 /* copy can be a prefix of the commit subject */
4740 for (i2
= 0; i2
< i
; i2
++)
4742 starts_with(subjects
[i2
], p
))
4750 todo_list
.items
[i
].command
=
4751 starts_with(subject
, "fixup!") ?
4752 TODO_FIXUP
: TODO_SQUASH
;
4758 } else if (!hashmap_get_from_hash(&subject2item
,
4759 strhash(subject
), subject
)) {
4760 FLEX_ALLOC_MEM(entry
, subject
, subject
, subject_len
);
4762 hashmap_entry_init(entry
, strhash(entry
->subject
));
4763 hashmap_put(&subject2item
, entry
);
4768 struct strbuf buf
= STRBUF_INIT
;
4770 for (i
= 0; i
< todo_list
.nr
; i
++) {
4771 enum todo_command command
= todo_list
.items
[i
].command
;
4775 * Initially, all commands are 'pick's. If it is a
4776 * fixup or a squash now, we have rearranged it.
4778 if (is_fixup(command
))
4783 get_item_line(&todo_list
, cur
);
4785 get_item_line(&todo_list
, cur
+ 1);
4787 /* replace 'pick', by 'fixup' or 'squash' */
4788 command
= todo_list
.items
[cur
].command
;
4789 if (is_fixup(command
)) {
4791 todo_command_info
[command
].str
);
4792 bol
+= strcspn(bol
, " \t");
4795 strbuf_add(&buf
, bol
, eol
- bol
);
4801 res
= rewrite_file(todo_file
, buf
.buf
, buf
.len
);
4802 strbuf_release(&buf
);
4807 for (i
= 0; i
< todo_list
.nr
; i
++)
4810 hashmap_free(&subject2item
, 1);
4811 todo_list_release(&todo_list
);
4813 clear_commit_todo_item(&commit_todo
);