8 #include "run-command.h"
11 #include "cache-tree.h"
15 #include "merge-recursive.h"
17 #include "argv-array.h"
20 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
22 const char sign_off_header
[] = "Signed-off-by: ";
23 static const char cherry_picked_prefix
[] = "(cherry picked from commit ";
25 GIT_PATH_FUNC(git_path_seq_dir
, "sequencer")
27 static GIT_PATH_FUNC(git_path_todo_file
, "sequencer/todo")
28 static GIT_PATH_FUNC(git_path_opts_file
, "sequencer/opts")
29 static GIT_PATH_FUNC(git_path_head_file
, "sequencer/head")
30 static GIT_PATH_FUNC(git_path_abort_safety_file
, "sequencer/abort-safety")
33 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
34 * GIT_AUTHOR_DATE that will be used for the commit that is currently
37 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
39 * The following files are written by git-rebase just after parsing the
40 * command-line (and are only consumed, not modified, by the sequencer).
42 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
44 /* We will introduce the 'interactive rebase' mode later */
45 static inline int is_rebase_i(const struct replay_opts
*opts
)
50 static const char *get_dir(const struct replay_opts
*opts
)
52 return git_path_seq_dir();
55 static const char *get_todo_path(const struct replay_opts
*opts
)
57 return git_path_todo_file();
60 static int is_rfc2822_line(const char *buf
, int len
)
64 for (i
= 0; i
< len
; i
++) {
68 if (!isalnum(ch
) && ch
!= '-')
75 static int is_cherry_picked_from_line(const char *buf
, int len
)
78 * We only care that it looks roughly like (cherry picked from ...)
80 return len
> strlen(cherry_picked_prefix
) + 1 &&
81 starts_with(buf
, cherry_picked_prefix
) && buf
[len
- 1] == ')';
85 * Returns 0 for non-conforming footer
86 * Returns 1 for conforming footer
87 * Returns 2 when sob exists within conforming footer
88 * Returns 3 when sob exists within conforming footer as last entry
90 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
95 int len
= sb
->len
- ignore_footer
;
96 const char *buf
= sb
->buf
;
99 /* footer must end with newline */
100 if (!len
|| buf
[len
- 1] != '\n')
104 for (i
= len
- 1; i
> 0; i
--) {
106 if (prev
== '\n' && ch
== '\n') /* paragraph break */
111 /* require at least one blank line */
112 if (prev
!= '\n' || buf
[i
] != '\n')
115 /* advance to start of last paragraph */
116 while (i
< len
- 1 && buf
[i
] == '\n')
119 for (; i
< len
; i
= k
) {
122 for (k
= i
; k
< len
&& buf
[k
] != '\n'; k
++)
126 found_rfc2822
= is_rfc2822_line(buf
+ i
, k
- i
- 1);
127 if (found_rfc2822
&& sob
&&
128 !strncmp(buf
+ i
, sob
->buf
, sob
->len
))
131 if (!(found_rfc2822
||
132 is_cherry_picked_from_line(buf
+ i
, k
- i
- 1)))
142 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
144 static struct strbuf buf
= STRBUF_INIT
;
148 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
152 int sequencer_remove_state(struct replay_opts
*opts
)
154 struct strbuf dir
= STRBUF_INIT
;
157 free(opts
->gpg_sign
);
158 free(opts
->strategy
);
159 for (i
= 0; i
< opts
->xopts_nr
; i
++)
160 free(opts
->xopts
[i
]);
163 strbuf_addf(&dir
, "%s", get_dir(opts
));
164 remove_dir_recursively(&dir
, 0);
165 strbuf_release(&dir
);
170 static const char *action_name(const struct replay_opts
*opts
)
172 return opts
->action
== REPLAY_REVERT
? N_("revert") : N_("cherry-pick");
175 struct commit_message
{
182 static const char *short_commit_name(struct commit
*commit
)
184 return find_unique_abbrev(commit
->object
.oid
.hash
, DEFAULT_ABBREV
);
187 static int get_message(struct commit
*commit
, struct commit_message
*out
)
189 const char *abbrev
, *subject
;
192 out
->message
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
193 abbrev
= short_commit_name(commit
);
195 subject_len
= find_commit_subject(out
->message
, &subject
);
197 out
->subject
= xmemdupz(subject
, subject_len
);
198 out
->label
= xstrfmt("%s... %s", abbrev
, out
->subject
);
199 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
204 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
206 free(msg
->parent_label
);
209 unuse_commit_buffer(commit
, msg
->message
);
212 static void print_advice(int show_hint
, struct replay_opts
*opts
)
214 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
217 fprintf(stderr
, "%s\n", msg
);
219 * A conflict has occurred but the porcelain
220 * (typically rebase --interactive) wants to take care
221 * of the commit itself so remove CHERRY_PICK_HEAD
223 unlink(git_path_cherry_pick_head());
229 advise(_("after resolving the conflicts, mark the corrected paths\n"
230 "with 'git add <paths>' or 'git rm <paths>'"));
232 advise(_("after resolving the conflicts, mark the corrected paths\n"
233 "with 'git add <paths>' or 'git rm <paths>'\n"
234 "and commit the result with 'git commit'"));
238 static int write_message(const void *buf
, size_t len
, const char *filename
,
241 static struct lock_file msg_file
;
243 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
245 return error_errno(_("could not lock '%s'"), filename
);
246 if (write_in_full(msg_fd
, buf
, len
) < 0) {
247 rollback_lock_file(&msg_file
);
248 return error_errno(_("could not write to '%s'"), filename
);
250 if (append_eol
&& write(msg_fd
, "\n", 1) < 0) {
251 rollback_lock_file(&msg_file
);
252 return error_errno(_("could not write eol to '%s'"), filename
);
254 if (commit_lock_file(&msg_file
) < 0) {
255 rollback_lock_file(&msg_file
);
256 return error(_("failed to finalize '%s'."), filename
);
263 * Reads a file that was presumably written by a shell script, i.e. with an
264 * end-of-line marker that needs to be stripped.
266 * Note that only the last end-of-line marker is stripped, consistent with the
267 * behavior of "$(cat path)" in a shell script.
269 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
271 static int read_oneliner(struct strbuf
*buf
,
272 const char *path
, int skip_if_empty
)
274 int orig_len
= buf
->len
;
276 if (!file_exists(path
))
279 if (strbuf_read_file(buf
, path
, 0) < 0) {
280 warning_errno(_("could not read '%s'"), path
);
284 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
285 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
287 buf
->buf
[buf
->len
] = '\0';
290 if (skip_if_empty
&& buf
->len
== orig_len
)
296 static struct tree
*empty_tree(void)
298 return lookup_tree(EMPTY_TREE_SHA1_BIN
);
301 static int error_dirty_index(struct replay_opts
*opts
)
303 if (read_cache_unmerged())
304 return error_resolve_conflict(_(action_name(opts
)));
306 error(_("your local changes would be overwritten by %s."),
307 _(action_name(opts
)));
309 if (advice_commit_before_merge
)
310 advise(_("commit your changes or stash them to proceed."));
314 static void update_abort_safety_file(void)
316 struct object_id head
;
318 /* Do nothing on a single-pick */
319 if (!file_exists(git_path_seq_dir()))
322 if (!get_oid("HEAD", &head
))
323 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head
));
325 write_file(git_path_abort_safety_file(), "%s", "");
328 static int fast_forward_to(const unsigned char *to
, const unsigned char *from
,
329 int unborn
, struct replay_opts
*opts
)
331 struct ref_transaction
*transaction
;
332 struct strbuf sb
= STRBUF_INIT
;
333 struct strbuf err
= STRBUF_INIT
;
336 if (checkout_fast_forward(from
, to
, 1))
337 return -1; /* the callee should have complained already */
339 strbuf_addf(&sb
, _("%s: fast-forward"), _(action_name(opts
)));
341 transaction
= ref_transaction_begin(&err
);
343 ref_transaction_update(transaction
, "HEAD",
344 to
, unborn
? null_sha1
: from
,
346 ref_transaction_commit(transaction
, &err
)) {
347 ref_transaction_free(transaction
);
348 error("%s", err
.buf
);
350 strbuf_release(&err
);
355 strbuf_release(&err
);
356 ref_transaction_free(transaction
);
357 update_abort_safety_file();
361 void append_conflicts_hint(struct strbuf
*msgbuf
)
365 strbuf_addch(msgbuf
, '\n');
366 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
367 for (i
= 0; i
< active_nr
;) {
368 const struct cache_entry
*ce
= active_cache
[i
++];
370 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
371 while (i
< active_nr
&& !strcmp(ce
->name
,
372 active_cache
[i
]->name
))
378 static int do_recursive_merge(struct commit
*base
, struct commit
*next
,
379 const char *base_label
, const char *next_label
,
380 unsigned char *head
, struct strbuf
*msgbuf
,
381 struct replay_opts
*opts
)
383 struct merge_options o
;
384 struct tree
*result
, *next_tree
, *base_tree
, *head_tree
;
387 static struct lock_file index_lock
;
389 hold_locked_index(&index_lock
, 1);
393 init_merge_options(&o
);
394 o
.ancestor
= base
? base_label
: "(empty tree)";
396 o
.branch2
= next
? next_label
: "(empty tree)";
398 head_tree
= parse_tree_indirect(head
);
399 next_tree
= next
? next
->tree
: empty_tree();
400 base_tree
= base
? base
->tree
: empty_tree();
402 for (xopt
= opts
->xopts
; xopt
!= opts
->xopts
+ opts
->xopts_nr
; xopt
++)
403 parse_merge_opt(&o
, *xopt
);
405 clean
= merge_trees(&o
,
407 next_tree
, base_tree
, &result
);
408 strbuf_release(&o
.obuf
);
412 if (active_cache_changed
&&
413 write_locked_index(&the_index
, &index_lock
, COMMIT_LOCK
))
414 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
415 return error(_("%s: Unable to write new index file"),
416 _(action_name(opts
)));
417 rollback_lock_file(&index_lock
);
420 append_signoff(msgbuf
, 0, 0);
423 append_conflicts_hint(msgbuf
);
428 static int is_index_unchanged(void)
430 unsigned char head_sha1
[20];
431 struct commit
*head_commit
;
433 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, head_sha1
, NULL
))
434 return error(_("could not resolve HEAD commit\n"));
436 head_commit
= lookup_commit(head_sha1
);
439 * If head_commit is NULL, check_commit, called from
440 * lookup_commit, would have indicated that head_commit is not
441 * a commit object already. parse_commit() will return failure
442 * without further complaints in such a case. Otherwise, if
443 * the commit is invalid, parse_commit() will complain. So
444 * there is nothing for us to say here. Just return failure.
446 if (parse_commit(head_commit
))
449 if (!active_cache_tree
)
450 active_cache_tree
= cache_tree();
452 if (!cache_tree_fully_valid(active_cache_tree
))
453 if (cache_tree_update(&the_index
, 0))
454 return error(_("unable to update cache tree\n"));
456 return !hashcmp(active_cache_tree
->sha1
, head_commit
->tree
->object
.oid
.hash
);
460 * Read the author-script file into an environment block, ready for use in
461 * run_command(), that can be free()d afterwards.
463 static char **read_author_script(void)
465 struct strbuf script
= STRBUF_INIT
;
470 if (strbuf_read_file(&script
, rebase_path_author_script(), 256) <= 0)
473 for (p
= script
.buf
; *p
; p
++)
474 if (skip_prefix(p
, "'\\\\''", (const char **)&p2
))
475 strbuf_splice(&script
, p
- script
.buf
, p2
- p
, "'", 1);
477 strbuf_splice(&script
, p
-- - script
.buf
, 1, "", 0);
478 else if (*p
== '\n') {
483 env_size
= (count
+ 1) * sizeof(*env
);
484 strbuf_grow(&script
, env_size
);
485 memmove(script
.buf
+ env_size
, script
.buf
, script
.len
);
486 p
= script
.buf
+ env_size
;
487 env
= (char **)strbuf_detach(&script
, NULL
);
489 for (i
= 0; i
< count
; i
++) {
498 static const char staged_changes_advice
[] =
499 N_("you have staged changes in your working tree\n"
500 "If these changes are meant to be squashed into the previous commit, run:\n"
502 " git commit --amend %s\n"
504 "If they are meant to go into a new commit, run:\n"
508 "In both cases, once you're done, continue with:\n"
510 " git rebase --continue\n");
513 * If we are cherry-pick, and if the merge did not result in
514 * hand-editing, we will hit this commit and inherit the original
515 * author date and name.
517 * If we are revert, or if our cherry-pick results in a hand merge,
518 * we had better say that the current user is responsible for that.
520 * An exception is when run_git_commit() is called during an
521 * interactive rebase: in that case, we will want to retain the
524 static int run_git_commit(const char *defmsg
, struct replay_opts
*opts
,
525 int allow_empty
, int edit
, int amend
,
526 int cleanup_commit_message
)
529 struct argv_array array
;
533 if (is_rebase_i(opts
)) {
534 env
= read_author_script();
536 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
538 return error(_(staged_changes_advice
),
543 argv_array_init(&array
);
544 argv_array_push(&array
, "commit");
545 argv_array_push(&array
, "-n");
548 argv_array_push(&array
, "--amend");
550 argv_array_pushf(&array
, "-S%s", opts
->gpg_sign
);
552 argv_array_push(&array
, "-s");
554 argv_array_pushl(&array
, "-F", defmsg
, NULL
);
555 if (cleanup_commit_message
)
556 argv_array_push(&array
, "--cleanup=strip");
558 argv_array_push(&array
, "-e");
559 else if (!cleanup_commit_message
&&
560 !opts
->signoff
&& !opts
->record_origin
&&
561 git_config_get_value("commit.cleanup", &value
))
562 argv_array_push(&array
, "--cleanup=verbatim");
565 argv_array_push(&array
, "--allow-empty");
567 if (opts
->allow_empty_message
)
568 argv_array_push(&array
, "--allow-empty-message");
570 rc
= run_command_v_opt_cd_env(array
.argv
, RUN_GIT_CMD
, NULL
,
571 (const char *const *)env
);
572 argv_array_clear(&array
);
578 static int is_original_commit_empty(struct commit
*commit
)
580 const unsigned char *ptree_sha1
;
582 if (parse_commit(commit
))
583 return error(_("could not parse commit %s\n"),
584 oid_to_hex(&commit
->object
.oid
));
585 if (commit
->parents
) {
586 struct commit
*parent
= commit
->parents
->item
;
587 if (parse_commit(parent
))
588 return error(_("could not parse parent commit %s\n"),
589 oid_to_hex(&parent
->object
.oid
));
590 ptree_sha1
= parent
->tree
->object
.oid
.hash
;
592 ptree_sha1
= EMPTY_TREE_SHA1_BIN
; /* commit is root */
595 return !hashcmp(ptree_sha1
, commit
->tree
->object
.oid
.hash
);
599 * Do we run "git commit" with "--allow-empty"?
601 static int allow_empty(struct replay_opts
*opts
, struct commit
*commit
)
603 int index_unchanged
, empty_commit
;
608 * (1) we do not allow empty at all and error out.
610 * (2) we allow ones that were initially empty, but
611 * forbid the ones that become empty;
615 if (!opts
->allow_empty
)
616 return 0; /* let "git commit" barf as necessary */
618 index_unchanged
= is_index_unchanged();
619 if (index_unchanged
< 0)
620 return index_unchanged
;
621 if (!index_unchanged
)
622 return 0; /* we do not have to say --allow-empty */
624 if (opts
->keep_redundant_commits
)
627 empty_commit
= is_original_commit_empty(commit
);
628 if (empty_commit
< 0)
641 static const char *todo_command_strings
[] = {
646 static const char *command_to_string(const enum todo_command command
)
648 if ((size_t)command
< ARRAY_SIZE(todo_command_strings
))
649 return todo_command_strings
[command
];
650 die("Unknown command: %d", command
);
654 static int do_pick_commit(enum todo_command command
, struct commit
*commit
,
655 struct replay_opts
*opts
)
657 unsigned char head
[20];
658 struct commit
*base
, *next
, *parent
;
659 const char *base_label
, *next_label
;
660 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
661 struct strbuf msgbuf
= STRBUF_INIT
;
662 int res
, unborn
= 0, allow
;
664 if (opts
->no_commit
) {
666 * We do not intend to commit immediately. We just want to
667 * merge the differences in, so let's compute the tree
668 * that represents the "current" state for merge-recursive
671 if (write_cache_as_tree(head
, 0, NULL
))
672 return error(_("your index file is unmerged."));
674 unborn
= get_sha1("HEAD", head
);
676 hashcpy(head
, EMPTY_TREE_SHA1_BIN
);
677 if (index_differs_from(unborn
? EMPTY_TREE_SHA1_HEX
: "HEAD", 0, 0))
678 return error_dirty_index(opts
);
682 if (!commit
->parents
) {
685 else if (commit
->parents
->next
) {
686 /* Reverting or cherry-picking a merge commit */
688 struct commit_list
*p
;
691 return error(_("commit %s is a merge but no -m option was given."),
692 oid_to_hex(&commit
->object
.oid
));
694 for (cnt
= 1, p
= commit
->parents
;
695 cnt
!= opts
->mainline
&& p
;
698 if (cnt
!= opts
->mainline
|| !p
)
699 return error(_("commit %s does not have parent %d"),
700 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
702 } else if (0 < opts
->mainline
)
703 return error(_("mainline was specified but commit %s is not a merge."),
704 oid_to_hex(&commit
->object
.oid
));
706 parent
= commit
->parents
->item
;
708 if (opts
->allow_ff
&&
709 ((parent
&& !hashcmp(parent
->object
.oid
.hash
, head
)) ||
710 (!parent
&& unborn
)))
711 return fast_forward_to(commit
->object
.oid
.hash
, head
, unborn
, opts
);
713 if (parent
&& parse_commit(parent
) < 0)
714 /* TRANSLATORS: The first %s will be a "todo" command like
715 "revert" or "pick", the second %s a SHA1. */
716 return error(_("%s: cannot parse parent commit %s"),
717 command_to_string(command
),
718 oid_to_hex(&parent
->object
.oid
));
720 if (get_message(commit
, &msg
) != 0)
721 return error(_("cannot get commit message for %s"),
722 oid_to_hex(&commit
->object
.oid
));
725 * "commit" is an existing commit. We would want to apply
726 * the difference it introduces since its first parent "prev"
727 * on top of the current HEAD if we are cherry-pick. Or the
728 * reverse of it if we are revert.
731 if (command
== TODO_REVERT
) {
733 base_label
= msg
.label
;
735 next_label
= msg
.parent_label
;
736 strbuf_addstr(&msgbuf
, "Revert \"");
737 strbuf_addstr(&msgbuf
, msg
.subject
);
738 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
739 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
741 if (commit
->parents
&& commit
->parents
->next
) {
742 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
743 strbuf_addstr(&msgbuf
, oid_to_hex(&parent
->object
.oid
));
745 strbuf_addstr(&msgbuf
, ".\n");
750 base_label
= msg
.parent_label
;
752 next_label
= msg
.label
;
755 * Append the commit log message to msgbuf; it starts
756 * after the tree, parent, author, committer
757 * information followed by "\n\n".
759 p
= strstr(msg
.message
, "\n\n");
761 strbuf_addstr(&msgbuf
, skip_blank_lines(p
+ 2));
763 if (opts
->record_origin
) {
764 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
765 strbuf_addch(&msgbuf
, '\n');
766 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
767 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
768 strbuf_addstr(&msgbuf
, ")\n");
772 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || command
== TODO_REVERT
) {
773 res
= do_recursive_merge(base
, next
, base_label
, next_label
,
774 head
, &msgbuf
, opts
);
777 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
778 git_path_merge_msg(), 0);
780 struct commit_list
*common
= NULL
;
781 struct commit_list
*remotes
= NULL
;
783 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
784 git_path_merge_msg(), 0);
786 commit_list_insert(base
, &common
);
787 commit_list_insert(next
, &remotes
);
788 res
|= try_merge_command(opts
->strategy
,
789 opts
->xopts_nr
, (const char **)opts
->xopts
,
790 common
, sha1_to_hex(head
), remotes
);
791 free_commit_list(common
);
792 free_commit_list(remotes
);
794 strbuf_release(&msgbuf
);
797 * If the merge was clean or if it failed due to conflict, we write
798 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
799 * However, if the merge did not even start, then we don't want to
802 if (command
== TODO_PICK
&& !opts
->no_commit
&& (res
== 0 || res
== 1) &&
803 update_ref(NULL
, "CHERRY_PICK_HEAD", commit
->object
.oid
.hash
, NULL
,
804 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
))
806 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
807 update_ref(NULL
, "REVERT_HEAD", commit
->object
.oid
.hash
, NULL
,
808 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
))
812 error(command
== TODO_REVERT
813 ? _("could not revert %s... %s")
814 : _("could not apply %s... %s"),
815 short_commit_name(commit
), msg
.subject
);
816 print_advice(res
== 1, opts
);
817 rerere(opts
->allow_rerere_auto
);
821 allow
= allow_empty(opts
, commit
);
826 if (!opts
->no_commit
)
827 res
= run_git_commit(opts
->edit
? NULL
: git_path_merge_msg(),
828 opts
, allow
, opts
->edit
, 0, 0);
831 free_message(commit
, &msg
);
832 update_abort_safety_file();
837 static int prepare_revs(struct replay_opts
*opts
)
840 * picking (but not reverting) ranges (but not individual revisions)
841 * should be done in reverse
843 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
844 opts
->revs
->reverse
^= 1;
846 if (prepare_revision_walk(opts
->revs
))
847 return error(_("revision walk setup failed"));
849 if (!opts
->revs
->commits
)
850 return error(_("empty commit set passed"));
854 static int read_and_refresh_cache(struct replay_opts
*opts
)
856 static struct lock_file index_lock
;
857 int index_fd
= hold_locked_index(&index_lock
, 0);
858 if (read_index_preload(&the_index
, NULL
) < 0) {
859 rollback_lock_file(&index_lock
);
860 return error(_("git %s: failed to read the index"),
861 _(action_name(opts
)));
863 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
864 if (the_index
.cache_changed
&& index_fd
>= 0) {
865 if (write_locked_index(&the_index
, &index_lock
, COMMIT_LOCK
)) {
866 rollback_lock_file(&index_lock
);
867 return error(_("git %s: failed to refresh the index"),
868 _(action_name(opts
)));
871 rollback_lock_file(&index_lock
);
876 enum todo_command command
;
877 struct commit
*commit
;
880 size_t offset_in_buf
;
885 struct todo_item
*items
;
886 int nr
, alloc
, current
;
889 #define TODO_LIST_INIT { STRBUF_INIT }
891 static void todo_list_release(struct todo_list
*todo_list
)
893 strbuf_release(&todo_list
->buf
);
894 free(todo_list
->items
);
895 todo_list
->items
= NULL
;
896 todo_list
->nr
= todo_list
->alloc
= 0;
899 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
901 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
902 return todo_list
->items
+ todo_list
->nr
++;
905 static int parse_insn_line(struct todo_item
*item
, const char *bol
, char *eol
)
907 unsigned char commit_sha1
[20];
908 char *end_of_object_name
;
909 int i
, saved
, status
, padding
;
912 bol
+= strspn(bol
, " \t");
914 for (i
= 0; i
< ARRAY_SIZE(todo_command_strings
); i
++)
915 if (skip_prefix(bol
, todo_command_strings
[i
], &bol
)) {
919 if (i
>= ARRAY_SIZE(todo_command_strings
))
922 /* Eat up extra spaces/ tabs before object name */
923 padding
= strspn(bol
, " \t");
928 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
929 saved
= *end_of_object_name
;
930 *end_of_object_name
= '\0';
931 status
= get_sha1(bol
, commit_sha1
);
932 *end_of_object_name
= saved
;
934 item
->arg
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
935 item
->arg_len
= (int)(eol
- item
->arg
);
940 item
->commit
= lookup_commit_reference(commit_sha1
);
941 return !item
->commit
;
944 static int parse_insn_buffer(char *buf
, struct todo_list
*todo_list
)
946 struct todo_item
*item
;
947 char *p
= buf
, *next_p
;
950 for (i
= 1; *p
; i
++, p
= next_p
) {
951 char *eol
= strchrnul(p
, '\n');
953 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
955 if (p
!= eol
&& eol
[-1] == '\r')
956 eol
--; /* strip Carriage Return */
958 item
= append_new_todo(todo_list
);
959 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
960 if (parse_insn_line(item
, p
, eol
)) {
961 res
= error(_("invalid line %d: %.*s"),
962 i
, (int)(eol
- p
), p
);
967 return error(_("no commits parsed."));
971 static int read_populate_todo(struct todo_list
*todo_list
,
972 struct replay_opts
*opts
)
974 const char *todo_file
= get_todo_path(opts
);
977 strbuf_reset(&todo_list
->buf
);
978 fd
= open(todo_file
, O_RDONLY
);
980 return error_errno(_("could not open '%s'"), todo_file
);
981 if (strbuf_read(&todo_list
->buf
, fd
, 0) < 0) {
983 return error(_("could not read '%s'."), todo_file
);
987 res
= parse_insn_buffer(todo_list
->buf
.buf
, todo_list
);
989 return error(_("unusable instruction sheet: '%s'"), todo_file
);
991 if (!is_rebase_i(opts
)) {
992 enum todo_command valid
=
993 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
996 for (i
= 0; i
< todo_list
->nr
; i
++)
997 if (valid
== todo_list
->items
[i
].command
)
999 else if (valid
== TODO_PICK
)
1000 return error(_("cannot cherry-pick during a revert."));
1002 return error(_("cannot revert during a cherry-pick."));
1008 static int git_config_string_dup(char **dest
,
1009 const char *var
, const char *value
)
1012 return config_error_nonbool(var
);
1014 *dest
= xstrdup(value
);
1018 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
1020 struct replay_opts
*opts
= data
;
1025 else if (!strcmp(key
, "options.no-commit"))
1026 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
1027 else if (!strcmp(key
, "options.edit"))
1028 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
1029 else if (!strcmp(key
, "options.signoff"))
1030 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
1031 else if (!strcmp(key
, "options.record-origin"))
1032 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
1033 else if (!strcmp(key
, "options.allow-ff"))
1034 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
1035 else if (!strcmp(key
, "options.mainline"))
1036 opts
->mainline
= git_config_int(key
, value
);
1037 else if (!strcmp(key
, "options.strategy"))
1038 git_config_string_dup(&opts
->strategy
, key
, value
);
1039 else if (!strcmp(key
, "options.gpg-sign"))
1040 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
1041 else if (!strcmp(key
, "options.strategy-option")) {
1042 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
1043 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(value
);
1045 return error(_("invalid key: %s"), key
);
1048 return error(_("invalid value for %s: %s"), key
, value
);
1053 static int read_populate_opts(struct replay_opts
*opts
)
1055 if (is_rebase_i(opts
)) {
1056 struct strbuf buf
= STRBUF_INIT
;
1058 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(), 1)) {
1059 if (!starts_with(buf
.buf
, "-S"))
1062 free(opts
->gpg_sign
);
1063 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
1066 strbuf_release(&buf
);
1071 if (!file_exists(git_path_opts_file()))
1074 * The function git_parse_source(), called from git_config_from_file(),
1075 * may die() in case of a syntactically incorrect file. We do not care
1076 * about this case, though, because we wrote that file ourselves, so we
1077 * are pretty certain that it is syntactically correct.
1079 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
1080 return error(_("malformed options sheet: '%s'"),
1081 git_path_opts_file());
1085 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
1086 struct replay_opts
*opts
)
1088 enum todo_command command
= opts
->action
== REPLAY_PICK
?
1089 TODO_PICK
: TODO_REVERT
;
1090 const char *command_string
= todo_command_strings
[command
];
1091 struct commit
*commit
;
1093 if (prepare_revs(opts
))
1096 while ((commit
= get_revision(opts
->revs
))) {
1097 struct todo_item
*item
= append_new_todo(todo_list
);
1098 const char *commit_buffer
= get_commit_buffer(commit
, NULL
);
1099 const char *subject
;
1102 item
->command
= command
;
1103 item
->commit
= commit
;
1106 item
->offset_in_buf
= todo_list
->buf
.len
;
1107 subject_len
= find_commit_subject(commit_buffer
, &subject
);
1108 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
1109 short_commit_name(commit
), subject_len
, subject
);
1110 unuse_commit_buffer(commit
, commit_buffer
);
1115 static int create_seq_dir(void)
1117 if (file_exists(git_path_seq_dir())) {
1118 error(_("a cherry-pick or revert is already in progress"));
1119 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1122 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1123 return error_errno(_("could not create sequencer directory '%s'"),
1124 git_path_seq_dir());
1128 static int save_head(const char *head
)
1130 static struct lock_file head_lock
;
1131 struct strbuf buf
= STRBUF_INIT
;
1134 fd
= hold_lock_file_for_update(&head_lock
, git_path_head_file(), 0);
1136 rollback_lock_file(&head_lock
);
1137 return error_errno(_("could not lock HEAD"));
1139 strbuf_addf(&buf
, "%s\n", head
);
1140 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
1141 rollback_lock_file(&head_lock
);
1142 return error_errno(_("could not write to '%s'"),
1143 git_path_head_file());
1145 if (commit_lock_file(&head_lock
) < 0) {
1146 rollback_lock_file(&head_lock
);
1147 return error(_("failed to finalize '%s'."), git_path_head_file());
1152 static int rollback_is_safe(void)
1154 struct strbuf sb
= STRBUF_INIT
;
1155 struct object_id expected_head
, actual_head
;
1157 if (strbuf_read_file(&sb
, git_path_abort_safety_file(), 0) >= 0) {
1159 if (get_oid_hex(sb
.buf
, &expected_head
)) {
1160 strbuf_release(&sb
);
1161 die(_("could not parse %s"), git_path_abort_safety_file());
1163 strbuf_release(&sb
);
1165 else if (errno
== ENOENT
)
1166 oidclr(&expected_head
);
1168 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1170 if (get_oid("HEAD", &actual_head
))
1171 oidclr(&actual_head
);
1173 return !oidcmp(&actual_head
, &expected_head
);
1176 static int reset_for_rollback(const unsigned char *sha1
)
1178 const char *argv
[4]; /* reset --merge <arg> + NULL */
1181 argv
[1] = "--merge";
1182 argv
[2] = sha1_to_hex(sha1
);
1184 return run_command_v_opt(argv
, RUN_GIT_CMD
);
1187 static int rollback_single_pick(void)
1189 unsigned char head_sha1
[20];
1191 if (!file_exists(git_path_cherry_pick_head()) &&
1192 !file_exists(git_path_revert_head()))
1193 return error(_("no cherry-pick or revert in progress"));
1194 if (read_ref_full("HEAD", 0, head_sha1
, NULL
))
1195 return error(_("cannot resolve HEAD"));
1196 if (is_null_sha1(head_sha1
))
1197 return error(_("cannot abort from a branch yet to be born"));
1198 return reset_for_rollback(head_sha1
);
1201 int sequencer_rollback(struct replay_opts
*opts
)
1204 unsigned char sha1
[20];
1205 struct strbuf buf
= STRBUF_INIT
;
1207 f
= fopen(git_path_head_file(), "r");
1208 if (!f
&& errno
== ENOENT
) {
1210 * There is no multiple-cherry-pick in progress.
1211 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1212 * a single-cherry-pick in progress, abort that.
1214 return rollback_single_pick();
1217 return error_errno(_("cannot open '%s'"), git_path_head_file());
1218 if (strbuf_getline_lf(&buf
, f
)) {
1219 error(_("cannot read '%s': %s"), git_path_head_file(),
1220 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
1225 if (get_sha1_hex(buf
.buf
, sha1
) || buf
.buf
[40] != '\0') {
1226 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1227 git_path_head_file());
1230 if (is_null_sha1(sha1
)) {
1231 error(_("cannot abort from a branch yet to be born"));
1235 if (!rollback_is_safe()) {
1236 /* Do not error, just do not rollback */
1237 warning(_("You seem to have moved HEAD. "
1238 "Not rewinding, check your HEAD!"));
1240 if (reset_for_rollback(sha1
))
1242 strbuf_release(&buf
);
1243 return sequencer_remove_state(opts
);
1245 strbuf_release(&buf
);
1249 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
1251 static struct lock_file todo_lock
;
1252 const char *todo_path
= get_todo_path(opts
);
1253 int next
= todo_list
->current
, offset
, fd
;
1255 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
1257 return error_errno(_("could not lock '%s'"), todo_path
);
1258 offset
= next
< todo_list
->nr
?
1259 todo_list
->items
[next
].offset_in_buf
: todo_list
->buf
.len
;
1260 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
1261 todo_list
->buf
.len
- offset
) < 0)
1262 return error_errno(_("could not write to '%s'"), todo_path
);
1263 if (commit_lock_file(&todo_lock
) < 0)
1264 return error(_("failed to finalize '%s'."), todo_path
);
1268 static int save_opts(struct replay_opts
*opts
)
1270 const char *opts_file
= git_path_opts_file();
1273 if (opts
->no_commit
)
1274 res
|= git_config_set_in_file_gently(opts_file
, "options.no-commit", "true");
1276 res
|= git_config_set_in_file_gently(opts_file
, "options.edit", "true");
1278 res
|= git_config_set_in_file_gently(opts_file
, "options.signoff", "true");
1279 if (opts
->record_origin
)
1280 res
|= git_config_set_in_file_gently(opts_file
, "options.record-origin", "true");
1282 res
|= git_config_set_in_file_gently(opts_file
, "options.allow-ff", "true");
1283 if (opts
->mainline
) {
1284 struct strbuf buf
= STRBUF_INIT
;
1285 strbuf_addf(&buf
, "%d", opts
->mainline
);
1286 res
|= git_config_set_in_file_gently(opts_file
, "options.mainline", buf
.buf
);
1287 strbuf_release(&buf
);
1290 res
|= git_config_set_in_file_gently(opts_file
, "options.strategy", opts
->strategy
);
1292 res
|= git_config_set_in_file_gently(opts_file
, "options.gpg-sign", opts
->gpg_sign
);
1295 for (i
= 0; i
< opts
->xopts_nr
; i
++)
1296 res
|= git_config_set_multivar_in_file_gently(opts_file
,
1297 "options.strategy-option",
1298 opts
->xopts
[i
], "^$", 0);
1303 static int pick_commits(struct todo_list
*todo_list
, struct replay_opts
*opts
)
1307 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
1309 assert(!(opts
->signoff
|| opts
->no_commit
||
1310 opts
->record_origin
|| opts
->edit
));
1311 if (read_and_refresh_cache(opts
))
1314 while (todo_list
->current
< todo_list
->nr
) {
1315 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
1316 if (save_todo(todo_list
, opts
))
1318 res
= do_pick_commit(item
->command
, item
->commit
, opts
);
1319 todo_list
->current
++;
1325 * Sequence of picks finished successfully; cleanup by
1326 * removing the .git/sequencer directory
1328 return sequencer_remove_state(opts
);
1331 static int continue_single_pick(void)
1333 const char *argv
[] = { "commit", NULL
};
1335 if (!file_exists(git_path_cherry_pick_head()) &&
1336 !file_exists(git_path_revert_head()))
1337 return error(_("no cherry-pick or revert in progress"));
1338 return run_command_v_opt(argv
, RUN_GIT_CMD
);
1341 int sequencer_continue(struct replay_opts
*opts
)
1343 struct todo_list todo_list
= TODO_LIST_INIT
;
1346 if (read_and_refresh_cache(opts
))
1349 if (!file_exists(get_todo_path(opts
)))
1350 return continue_single_pick();
1351 if (read_populate_opts(opts
))
1353 if ((res
= read_populate_todo(&todo_list
, opts
)))
1354 goto release_todo_list
;
1356 /* Verify that the conflict has been resolved */
1357 if (file_exists(git_path_cherry_pick_head()) ||
1358 file_exists(git_path_revert_head())) {
1359 res
= continue_single_pick();
1361 goto release_todo_list
;
1363 if (index_differs_from("HEAD", 0, 0)) {
1364 res
= error_dirty_index(opts
);
1365 goto release_todo_list
;
1367 todo_list
.current
++;
1368 res
= pick_commits(&todo_list
, opts
);
1370 todo_list_release(&todo_list
);
1374 static int single_pick(struct commit
*cmit
, struct replay_opts
*opts
)
1376 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
1377 return do_pick_commit(opts
->action
== REPLAY_PICK
?
1378 TODO_PICK
: TODO_REVERT
, cmit
, opts
);
1381 int sequencer_pick_revisions(struct replay_opts
*opts
)
1383 struct todo_list todo_list
= TODO_LIST_INIT
;
1384 unsigned char sha1
[20];
1388 if (read_and_refresh_cache(opts
))
1391 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
1392 unsigned char sha1
[20];
1393 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
1395 /* This happens when using --stdin. */
1399 if (!get_sha1(name
, sha1
)) {
1400 if (!lookup_commit_reference_gently(sha1
, 1)) {
1401 enum object_type type
= sha1_object_info(sha1
, NULL
);
1402 return error(_("%s: can't cherry-pick a %s"),
1403 name
, typename(type
));
1406 return error(_("%s: bad revision"), name
);
1410 * If we were called as "git cherry-pick <commit>", just
1411 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1412 * REVERT_HEAD, and don't touch the sequencer state.
1413 * This means it is possible to cherry-pick in the middle
1414 * of a cherry-pick sequence.
1416 if (opts
->revs
->cmdline
.nr
== 1 &&
1417 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
1418 opts
->revs
->no_walk
&&
1419 !opts
->revs
->cmdline
.rev
->flags
) {
1420 struct commit
*cmit
;
1421 if (prepare_revision_walk(opts
->revs
))
1422 return error(_("revision walk setup failed"));
1423 cmit
= get_revision(opts
->revs
);
1424 if (!cmit
|| get_revision(opts
->revs
))
1425 return error("BUG: expected exactly one commit from walk");
1426 return single_pick(cmit
, opts
);
1430 * Start a new cherry-pick/ revert sequence; but
1431 * first, make sure that an existing one isn't in
1435 if (walk_revs_populate_todo(&todo_list
, opts
) ||
1436 create_seq_dir() < 0)
1438 if (get_sha1("HEAD", sha1
) && (opts
->action
== REPLAY_REVERT
))
1439 return error(_("can't revert as initial commit"));
1440 if (save_head(sha1_to_hex(sha1
)))
1442 if (save_opts(opts
))
1444 update_abort_safety_file();
1445 res
= pick_commits(&todo_list
, opts
);
1446 todo_list_release(&todo_list
);
1450 void append_signoff(struct strbuf
*msgbuf
, int ignore_footer
, unsigned flag
)
1452 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
1453 struct strbuf sob
= STRBUF_INIT
;
1456 strbuf_addstr(&sob
, sign_off_header
);
1457 strbuf_addstr(&sob
, fmt_name(getenv("GIT_COMMITTER_NAME"),
1458 getenv("GIT_COMMITTER_EMAIL")));
1459 strbuf_addch(&sob
, '\n');
1462 * If the whole message buffer is equal to the sob, pretend that we
1463 * found a conforming footer with a matching sob
1465 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
1466 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
1469 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
1472 const char *append_newlines
= NULL
;
1473 size_t len
= msgbuf
->len
- ignore_footer
;
1477 * The buffer is completely empty. Leave foom for
1478 * the title and body to be filled in by the user.
1480 append_newlines
= "\n\n";
1481 } else if (msgbuf
->buf
[len
- 1] != '\n') {
1483 * Incomplete line. Complete the line and add a
1484 * blank one so that there is an empty line between
1485 * the message body and the sob.
1487 append_newlines
= "\n\n";
1488 } else if (len
== 1) {
1490 * Buffer contains a single newline. Add another
1491 * so that we leave room for the title and body.
1493 append_newlines
= "\n";
1494 } else if (msgbuf
->buf
[len
- 2] != '\n') {
1496 * Buffer ends with a single newline. Add another
1497 * so that there is an empty line between the message
1500 append_newlines
= "\n";
1501 } /* else, the buffer already ends with two newlines. */
1503 if (append_newlines
)
1504 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
1505 append_newlines
, strlen(append_newlines
));
1508 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
1509 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
1512 strbuf_release(&sob
);