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")
32 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
33 * GIT_AUTHOR_DATE that will be used for the commit that is currently
36 static GIT_PATH_FUNC(rebase_path_author_script
, "rebase-merge/author-script")
38 * The following files are written by git-rebase just after parsing the
39 * command-line (and are only consumed, not modified, by the sequencer).
41 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt
, "rebase-merge/gpg_sign_opt")
43 /* We will introduce the 'interactive rebase' mode later */
44 static inline int is_rebase_i(const struct replay_opts
*opts
)
49 static const char *get_dir(const struct replay_opts
*opts
)
51 return git_path_seq_dir();
54 static const char *get_todo_path(const struct replay_opts
*opts
)
56 return git_path_todo_file();
59 static int is_rfc2822_line(const char *buf
, int len
)
63 for (i
= 0; i
< len
; i
++) {
67 if (!isalnum(ch
) && ch
!= '-')
74 static int is_cherry_picked_from_line(const char *buf
, int len
)
77 * We only care that it looks roughly like (cherry picked from ...)
79 return len
> strlen(cherry_picked_prefix
) + 1 &&
80 starts_with(buf
, cherry_picked_prefix
) && buf
[len
- 1] == ')';
84 * Returns 0 for non-conforming footer
85 * Returns 1 for conforming footer
86 * Returns 2 when sob exists within conforming footer
87 * Returns 3 when sob exists within conforming footer as last entry
89 static int has_conforming_footer(struct strbuf
*sb
, struct strbuf
*sob
,
94 int len
= sb
->len
- ignore_footer
;
95 const char *buf
= sb
->buf
;
98 /* footer must end with newline */
99 if (!len
|| buf
[len
- 1] != '\n')
103 for (i
= len
- 1; i
> 0; i
--) {
105 if (prev
== '\n' && ch
== '\n') /* paragraph break */
110 /* require at least one blank line */
111 if (prev
!= '\n' || buf
[i
] != '\n')
114 /* advance to start of last paragraph */
115 while (i
< len
- 1 && buf
[i
] == '\n')
118 for (; i
< len
; i
= k
) {
121 for (k
= i
; k
< len
&& buf
[k
] != '\n'; k
++)
125 found_rfc2822
= is_rfc2822_line(buf
+ i
, k
- i
- 1);
126 if (found_rfc2822
&& sob
&&
127 !strncmp(buf
+ i
, sob
->buf
, sob
->len
))
130 if (!(found_rfc2822
||
131 is_cherry_picked_from_line(buf
+ i
, k
- i
- 1)))
141 static const char *gpg_sign_opt_quoted(struct replay_opts
*opts
)
143 static struct strbuf buf
= STRBUF_INIT
;
147 sq_quotef(&buf
, "-S%s", opts
->gpg_sign
);
151 int sequencer_remove_state(struct replay_opts
*opts
)
153 struct strbuf dir
= STRBUF_INIT
;
156 free(opts
->gpg_sign
);
157 free(opts
->strategy
);
158 for (i
= 0; i
< opts
->xopts_nr
; i
++)
159 free(opts
->xopts
[i
]);
162 strbuf_addf(&dir
, "%s", get_dir(opts
));
163 remove_dir_recursively(&dir
, 0);
164 strbuf_release(&dir
);
169 static const char *action_name(const struct replay_opts
*opts
)
171 return opts
->action
== REPLAY_REVERT
? "revert" : "cherry-pick";
174 struct commit_message
{
181 static const char *short_commit_name(struct commit
*commit
)
183 return find_unique_abbrev(commit
->object
.oid
.hash
, DEFAULT_ABBREV
);
186 static int get_message(struct commit
*commit
, struct commit_message
*out
)
188 const char *abbrev
, *subject
;
191 out
->message
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
192 abbrev
= short_commit_name(commit
);
194 subject_len
= find_commit_subject(out
->message
, &subject
);
196 out
->subject
= xmemdupz(subject
, subject_len
);
197 out
->label
= xstrfmt("%s... %s", abbrev
, out
->subject
);
198 out
->parent_label
= xstrfmt("parent of %s", out
->label
);
203 static void free_message(struct commit
*commit
, struct commit_message
*msg
)
205 free(msg
->parent_label
);
208 unuse_commit_buffer(commit
, msg
->message
);
211 static void print_advice(int show_hint
, struct replay_opts
*opts
)
213 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
216 fprintf(stderr
, "%s\n", msg
);
218 * A conflict has occurred but the porcelain
219 * (typically rebase --interactive) wants to take care
220 * of the commit itself so remove CHERRY_PICK_HEAD
222 unlink(git_path_cherry_pick_head());
228 advise(_("after resolving the conflicts, mark the corrected paths\n"
229 "with 'git add <paths>' or 'git rm <paths>'"));
231 advise(_("after resolving the conflicts, mark the corrected paths\n"
232 "with 'git add <paths>' or 'git rm <paths>'\n"
233 "and commit the result with 'git commit'"));
237 static int write_message(const void *buf
, size_t len
, const char *filename
)
239 static struct lock_file msg_file
;
241 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
, 0);
243 return error_errno(_("Could not lock '%s'"), filename
);
244 if (write_in_full(msg_fd
, buf
, len
) < 0) {
245 rollback_lock_file(&msg_file
);
246 return error_errno(_("Could not write to '%s'"), filename
);
248 if (commit_lock_file(&msg_file
) < 0) {
249 rollback_lock_file(&msg_file
);
250 return error(_("Error wrapping up %s."), filename
);
257 * Reads a file that was presumably written by a shell script, i.e. with an
258 * end-of-line marker that needs to be stripped.
260 * Note that only the last end-of-line marker is stripped, consistent with the
261 * behavior of "$(cat path)" in a shell script.
263 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
265 static int read_oneliner(struct strbuf
*buf
,
266 const char *path
, int skip_if_empty
)
268 int orig_len
= buf
->len
;
270 if (!file_exists(path
))
273 if (strbuf_read_file(buf
, path
, 0) < 0) {
274 warning_errno(_("could not read '%s'"), path
);
278 if (buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\n') {
279 if (--buf
->len
> orig_len
&& buf
->buf
[buf
->len
- 1] == '\r')
281 buf
->buf
[buf
->len
] = '\0';
284 if (skip_if_empty
&& buf
->len
== orig_len
)
290 static struct tree
*empty_tree(void)
292 return lookup_tree(EMPTY_TREE_SHA1_BIN
);
295 static int error_dirty_index(struct replay_opts
*opts
)
297 if (read_cache_unmerged())
298 return error_resolve_conflict(action_name(opts
));
300 error(_("Your local changes would be overwritten by %s."),
303 if (advice_commit_before_merge
)
304 advise(_("Commit your changes or stash them to proceed."));
308 static int fast_forward_to(const unsigned char *to
, const unsigned char *from
,
309 int unborn
, struct replay_opts
*opts
)
311 struct ref_transaction
*transaction
;
312 struct strbuf sb
= STRBUF_INIT
;
313 struct strbuf err
= STRBUF_INIT
;
316 if (checkout_fast_forward(from
, to
, 1))
317 return -1; /* the callee should have complained already */
319 strbuf_addf(&sb
, _("%s: fast-forward"), action_name(opts
));
321 transaction
= ref_transaction_begin(&err
);
323 ref_transaction_update(transaction
, "HEAD",
324 to
, unborn
? null_sha1
: from
,
326 ref_transaction_commit(transaction
, &err
)) {
327 ref_transaction_free(transaction
);
328 error("%s", err
.buf
);
330 strbuf_release(&err
);
335 strbuf_release(&err
);
336 ref_transaction_free(transaction
);
340 void append_conflicts_hint(struct strbuf
*msgbuf
)
344 strbuf_addch(msgbuf
, '\n');
345 strbuf_commented_addf(msgbuf
, "Conflicts:\n");
346 for (i
= 0; i
< active_nr
;) {
347 const struct cache_entry
*ce
= active_cache
[i
++];
349 strbuf_commented_addf(msgbuf
, "\t%s\n", ce
->name
);
350 while (i
< active_nr
&& !strcmp(ce
->name
,
351 active_cache
[i
]->name
))
357 static int do_recursive_merge(struct commit
*base
, struct commit
*next
,
358 const char *base_label
, const char *next_label
,
359 unsigned char *head
, struct strbuf
*msgbuf
,
360 struct replay_opts
*opts
)
362 struct merge_options o
;
363 struct tree
*result
, *next_tree
, *base_tree
, *head_tree
;
366 static struct lock_file index_lock
;
368 hold_locked_index(&index_lock
, 1);
372 init_merge_options(&o
);
373 o
.ancestor
= base
? base_label
: "(empty tree)";
375 o
.branch2
= next
? next_label
: "(empty tree)";
377 head_tree
= parse_tree_indirect(head
);
378 next_tree
= next
? next
->tree
: empty_tree();
379 base_tree
= base
? base
->tree
: empty_tree();
381 for (xopt
= opts
->xopts
; xopt
!= opts
->xopts
+ opts
->xopts_nr
; xopt
++)
382 parse_merge_opt(&o
, *xopt
);
384 clean
= merge_trees(&o
,
386 next_tree
, base_tree
, &result
);
387 strbuf_release(&o
.obuf
);
391 if (active_cache_changed
&&
392 write_locked_index(&the_index
, &index_lock
, COMMIT_LOCK
))
393 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
394 return error(_("%s: Unable to write new index file"),
396 rollback_lock_file(&index_lock
);
399 append_signoff(msgbuf
, 0, 0);
402 append_conflicts_hint(msgbuf
);
407 static int is_index_unchanged(void)
409 unsigned char head_sha1
[20];
410 struct commit
*head_commit
;
412 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, head_sha1
, NULL
))
413 return error(_("Could not resolve HEAD commit\n"));
415 head_commit
= lookup_commit(head_sha1
);
418 * If head_commit is NULL, check_commit, called from
419 * lookup_commit, would have indicated that head_commit is not
420 * a commit object already. parse_commit() will return failure
421 * without further complaints in such a case. Otherwise, if
422 * the commit is invalid, parse_commit() will complain. So
423 * there is nothing for us to say here. Just return failure.
425 if (parse_commit(head_commit
))
428 if (!active_cache_tree
)
429 active_cache_tree
= cache_tree();
431 if (!cache_tree_fully_valid(active_cache_tree
))
432 if (cache_tree_update(&the_index
, 0))
433 return error(_("Unable to update cache tree\n"));
435 return !hashcmp(active_cache_tree
->sha1
, head_commit
->tree
->object
.oid
.hash
);
439 * Read the author-script file into an environment block, ready for use in
440 * run_command(), that can be free()d afterwards.
442 static char **read_author_script(void)
444 struct strbuf script
= STRBUF_INIT
;
449 if (strbuf_read_file(&script
, rebase_path_author_script(), 256) <= 0)
452 for (p
= script
.buf
; *p
; p
++)
453 if (skip_prefix(p
, "'\\\\''", (const char **)&p2
))
454 strbuf_splice(&script
, p
- script
.buf
, p2
- p
, "'", 1);
456 strbuf_splice(&script
, p
-- - script
.buf
, 1, "", 0);
457 else if (*p
== '\n') {
462 env_size
= (count
+ 1) * sizeof(*env
);
463 strbuf_grow(&script
, env_size
);
464 memmove(script
.buf
+ env_size
, script
.buf
, script
.len
);
465 p
= script
.buf
+ env_size
;
466 env
= (char **)strbuf_detach(&script
, NULL
);
468 for (i
= 0; i
< count
; i
++) {
478 * If we are cherry-pick, and if the merge did not result in
479 * hand-editing, we will hit this commit and inherit the original
480 * author date and name.
482 * If we are revert, or if our cherry-pick results in a hand merge,
483 * we had better say that the current user is responsible for that.
485 * An exception is when run_git_commit() is called during an
486 * interactive rebase: in that case, we will want to retain the
489 static int run_git_commit(const char *defmsg
, struct replay_opts
*opts
,
490 int allow_empty
, int edit
, int amend
,
491 int cleanup_commit_message
)
494 struct argv_array array
;
498 if (is_rebase_i(opts
)) {
499 env
= read_author_script();
501 const char *gpg_opt
= gpg_sign_opt_quoted(opts
);
503 return error("You have staged changes in your working "
504 "tree. If these changes are meant to be\n"
505 "squashed into the previous commit, run:\n\n"
506 " git commit --amend %s\n\n"
507 "If they are meant to go into a new commit, "
510 "In both cases, once you're done, continue "
512 " git rebase --continue\n", gpg_opt
, gpg_opt
);
516 argv_array_init(&array
);
517 argv_array_push(&array
, "commit");
518 argv_array_push(&array
, "-n");
521 argv_array_push(&array
, "--amend");
523 argv_array_pushf(&array
, "-S%s", opts
->gpg_sign
);
525 argv_array_push(&array
, "-s");
527 argv_array_pushl(&array
, "-F", defmsg
, NULL
);
528 if (cleanup_commit_message
)
529 argv_array_push(&array
, "--cleanup=strip");
531 argv_array_push(&array
, "-e");
532 else if (!cleanup_commit_message
&&
533 !opts
->signoff
&& !opts
->record_origin
&&
534 git_config_get_value("commit.cleanup", &value
))
535 argv_array_push(&array
, "--cleanup=verbatim");
538 argv_array_push(&array
, "--allow-empty");
540 if (opts
->allow_empty_message
)
541 argv_array_push(&array
, "--allow-empty-message");
543 rc
= run_command_v_opt_cd_env(array
.argv
, RUN_GIT_CMD
, NULL
,
544 (const char *const *)env
);
545 argv_array_clear(&array
);
551 static int is_original_commit_empty(struct commit
*commit
)
553 const unsigned char *ptree_sha1
;
555 if (parse_commit(commit
))
556 return error(_("Could not parse commit %s\n"),
557 oid_to_hex(&commit
->object
.oid
));
558 if (commit
->parents
) {
559 struct commit
*parent
= commit
->parents
->item
;
560 if (parse_commit(parent
))
561 return error(_("Could not parse parent commit %s\n"),
562 oid_to_hex(&parent
->object
.oid
));
563 ptree_sha1
= parent
->tree
->object
.oid
.hash
;
565 ptree_sha1
= EMPTY_TREE_SHA1_BIN
; /* commit is root */
568 return !hashcmp(ptree_sha1
, commit
->tree
->object
.oid
.hash
);
572 * Do we run "git commit" with "--allow-empty"?
574 static int allow_empty(struct replay_opts
*opts
, struct commit
*commit
)
576 int index_unchanged
, empty_commit
;
581 * (1) we do not allow empty at all and error out.
583 * (2) we allow ones that were initially empty, but
584 * forbid the ones that become empty;
588 if (!opts
->allow_empty
)
589 return 0; /* let "git commit" barf as necessary */
591 index_unchanged
= is_index_unchanged();
592 if (index_unchanged
< 0)
593 return index_unchanged
;
594 if (!index_unchanged
)
595 return 0; /* we do not have to say --allow-empty */
597 if (opts
->keep_redundant_commits
)
600 empty_commit
= is_original_commit_empty(commit
);
601 if (empty_commit
< 0)
614 static const char *todo_command_strings
[] = {
619 static const char *command_to_string(const enum todo_command command
)
621 if (command
< ARRAY_SIZE(todo_command_strings
))
622 return todo_command_strings
[command
];
623 die("Unknown command: %d", command
);
627 static int do_pick_commit(enum todo_command command
, struct commit
*commit
,
628 struct replay_opts
*opts
)
630 unsigned char head
[20];
631 struct commit
*base
, *next
, *parent
;
632 const char *base_label
, *next_label
;
633 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
};
634 struct strbuf msgbuf
= STRBUF_INIT
;
635 int res
, unborn
= 0, allow
;
637 if (opts
->no_commit
) {
639 * We do not intend to commit immediately. We just want to
640 * merge the differences in, so let's compute the tree
641 * that represents the "current" state for merge-recursive
644 if (write_cache_as_tree(head
, 0, NULL
))
645 return error(_("Your index file is unmerged."));
647 unborn
= get_sha1("HEAD", head
);
649 hashcpy(head
, EMPTY_TREE_SHA1_BIN
);
650 if (index_differs_from(unborn
? EMPTY_TREE_SHA1_HEX
: "HEAD", 0))
651 return error_dirty_index(opts
);
655 if (!commit
->parents
) {
658 else if (commit
->parents
->next
) {
659 /* Reverting or cherry-picking a merge commit */
661 struct commit_list
*p
;
664 return error(_("Commit %s is a merge but no -m option was given."),
665 oid_to_hex(&commit
->object
.oid
));
667 for (cnt
= 1, p
= commit
->parents
;
668 cnt
!= opts
->mainline
&& p
;
671 if (cnt
!= opts
->mainline
|| !p
)
672 return error(_("Commit %s does not have parent %d"),
673 oid_to_hex(&commit
->object
.oid
), opts
->mainline
);
675 } else if (0 < opts
->mainline
)
676 return error(_("Mainline was specified but commit %s is not a merge."),
677 oid_to_hex(&commit
->object
.oid
));
679 parent
= commit
->parents
->item
;
681 if (opts
->allow_ff
&&
682 ((parent
&& !hashcmp(parent
->object
.oid
.hash
, head
)) ||
683 (!parent
&& unborn
)))
684 return fast_forward_to(commit
->object
.oid
.hash
, head
, unborn
, opts
);
686 if (parent
&& parse_commit(parent
) < 0)
687 /* TRANSLATORS: The first %s will be a "todo" command like
688 "revert" or "pick", the second %s a SHA1. */
689 return error(_("%s: cannot parse parent commit %s"),
690 command_to_string(command
),
691 oid_to_hex(&parent
->object
.oid
));
693 if (get_message(commit
, &msg
) != 0)
694 return error(_("Cannot get commit message for %s"),
695 oid_to_hex(&commit
->object
.oid
));
698 * "commit" is an existing commit. We would want to apply
699 * the difference it introduces since its first parent "prev"
700 * on top of the current HEAD if we are cherry-pick. Or the
701 * reverse of it if we are revert.
704 if (command
== TODO_REVERT
) {
706 base_label
= msg
.label
;
708 next_label
= msg
.parent_label
;
709 strbuf_addstr(&msgbuf
, "Revert \"");
710 strbuf_addstr(&msgbuf
, msg
.subject
);
711 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
712 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
714 if (commit
->parents
&& commit
->parents
->next
) {
715 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
716 strbuf_addstr(&msgbuf
, oid_to_hex(&parent
->object
.oid
));
718 strbuf_addstr(&msgbuf
, ".\n");
723 base_label
= msg
.parent_label
;
725 next_label
= msg
.label
;
728 * Append the commit log message to msgbuf; it starts
729 * after the tree, parent, author, committer
730 * information followed by "\n\n".
732 p
= strstr(msg
.message
, "\n\n");
734 strbuf_addstr(&msgbuf
, skip_blank_lines(p
+ 2));
736 if (opts
->record_origin
) {
737 if (!has_conforming_footer(&msgbuf
, NULL
, 0))
738 strbuf_addch(&msgbuf
, '\n');
739 strbuf_addstr(&msgbuf
, cherry_picked_prefix
);
740 strbuf_addstr(&msgbuf
, oid_to_hex(&commit
->object
.oid
));
741 strbuf_addstr(&msgbuf
, ")\n");
745 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || command
== TODO_REVERT
) {
746 res
= do_recursive_merge(base
, next
, base_label
, next_label
,
747 head
, &msgbuf
, opts
);
750 res
|= write_message(msgbuf
.buf
, msgbuf
.len
,
751 git_path_merge_msg());
753 struct commit_list
*common
= NULL
;
754 struct commit_list
*remotes
= NULL
;
756 res
= write_message(msgbuf
.buf
, msgbuf
.len
,
757 git_path_merge_msg());
759 commit_list_insert(base
, &common
);
760 commit_list_insert(next
, &remotes
);
761 res
|= try_merge_command(opts
->strategy
,
762 opts
->xopts_nr
, (const char **)opts
->xopts
,
763 common
, sha1_to_hex(head
), remotes
);
764 free_commit_list(common
);
765 free_commit_list(remotes
);
767 strbuf_release(&msgbuf
);
770 * If the merge was clean or if it failed due to conflict, we write
771 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
772 * However, if the merge did not even start, then we don't want to
775 if (command
== TODO_PICK
&& !opts
->no_commit
&& (res
== 0 || res
== 1) &&
776 update_ref(NULL
, "CHERRY_PICK_HEAD", commit
->object
.oid
.hash
, NULL
,
777 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
))
779 if (command
== TODO_REVERT
&& ((opts
->no_commit
&& res
== 0) || res
== 1) &&
780 update_ref(NULL
, "REVERT_HEAD", commit
->object
.oid
.hash
, NULL
,
781 REF_NODEREF
, UPDATE_REFS_MSG_ON_ERR
))
785 error(command
== TODO_REVERT
786 ? _("could not revert %s... %s")
787 : _("could not apply %s... %s"),
788 short_commit_name(commit
), msg
.subject
);
789 print_advice(res
== 1, opts
);
790 rerere(opts
->allow_rerere_auto
);
794 allow
= allow_empty(opts
, commit
);
799 if (!opts
->no_commit
)
800 res
= run_git_commit(opts
->edit
? NULL
: git_path_merge_msg(),
801 opts
, allow
, opts
->edit
, 0, 0);
804 free_message(commit
, &msg
);
809 static int prepare_revs(struct replay_opts
*opts
)
812 * picking (but not reverting) ranges (but not individual revisions)
813 * should be done in reverse
815 if (opts
->action
== REPLAY_PICK
&& !opts
->revs
->no_walk
)
816 opts
->revs
->reverse
^= 1;
818 if (prepare_revision_walk(opts
->revs
))
819 return error(_("revision walk setup failed"));
821 if (!opts
->revs
->commits
)
822 return error(_("empty commit set passed"));
826 static int read_and_refresh_cache(struct replay_opts
*opts
)
828 static struct lock_file index_lock
;
829 int index_fd
= hold_locked_index(&index_lock
, 0);
830 if (read_index_preload(&the_index
, NULL
) < 0) {
831 rollback_lock_file(&index_lock
);
832 return error(_("git %s: failed to read the index"),
835 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
836 if (the_index
.cache_changed
&& index_fd
>= 0) {
837 if (write_locked_index(&the_index
, &index_lock
, COMMIT_LOCK
)) {
838 rollback_lock_file(&index_lock
);
839 return error(_("git %s: failed to refresh the index"),
843 rollback_lock_file(&index_lock
);
848 enum todo_command command
;
849 struct commit
*commit
;
852 size_t offset_in_buf
;
857 struct todo_item
*items
;
858 int nr
, alloc
, current
;
861 #define TODO_LIST_INIT { STRBUF_INIT }
863 static void todo_list_release(struct todo_list
*todo_list
)
865 strbuf_release(&todo_list
->buf
);
866 free(todo_list
->items
);
867 todo_list
->items
= NULL
;
868 todo_list
->nr
= todo_list
->alloc
= 0;
871 static struct todo_item
*append_new_todo(struct todo_list
*todo_list
)
873 ALLOC_GROW(todo_list
->items
, todo_list
->nr
+ 1, todo_list
->alloc
);
874 return todo_list
->items
+ todo_list
->nr
++;
877 static int parse_insn_line(struct todo_item
*item
, const char *bol
, char *eol
)
879 unsigned char commit_sha1
[20];
880 char *end_of_object_name
;
881 int i
, saved
, status
, padding
;
884 bol
+= strspn(bol
, " \t");
886 for (i
= 0; i
< ARRAY_SIZE(todo_command_strings
); i
++)
887 if (skip_prefix(bol
, todo_command_strings
[i
], &bol
)) {
891 if (i
>= ARRAY_SIZE(todo_command_strings
))
894 /* Eat up extra spaces/ tabs before object name */
895 padding
= strspn(bol
, " \t");
900 end_of_object_name
= (char *) bol
+ strcspn(bol
, " \t\n");
901 saved
= *end_of_object_name
;
902 *end_of_object_name
= '\0';
903 status
= get_sha1(bol
, commit_sha1
);
904 *end_of_object_name
= saved
;
906 item
->arg
= end_of_object_name
+ strspn(end_of_object_name
, " \t");
907 item
->arg_len
= (int)(eol
- item
->arg
);
912 item
->commit
= lookup_commit_reference(commit_sha1
);
913 return !item
->commit
;
916 static int parse_insn_buffer(char *buf
, struct todo_list
*todo_list
)
918 struct todo_item
*item
;
919 char *p
= buf
, *next_p
;
922 for (i
= 1; *p
; i
++, p
= next_p
) {
923 char *eol
= strchrnul(p
, '\n');
925 next_p
= *eol
? eol
+ 1 /* skip LF */ : eol
;
927 if (p
!= eol
&& eol
[-1] == '\r')
928 eol
--; /* strip Carriage Return */
930 item
= append_new_todo(todo_list
);
931 item
->offset_in_buf
= p
- todo_list
->buf
.buf
;
932 if (parse_insn_line(item
, p
, eol
)) {
933 res
= error(_("Invalid line %d: %.*s"),
934 i
, (int)(eol
- p
), p
);
939 return error(_("No commits parsed."));
943 static int read_populate_todo(struct todo_list
*todo_list
,
944 struct replay_opts
*opts
)
946 const char *todo_file
= get_todo_path(opts
);
949 strbuf_reset(&todo_list
->buf
);
950 fd
= open(todo_file
, O_RDONLY
);
952 return error_errno(_("Could not open %s"), todo_file
);
953 if (strbuf_read(&todo_list
->buf
, fd
, 0) < 0) {
955 return error(_("Could not read %s."), todo_file
);
959 res
= parse_insn_buffer(todo_list
->buf
.buf
, todo_list
);
961 enum todo_command valid
=
962 opts
->action
== REPLAY_PICK
? TODO_PICK
: TODO_REVERT
;
965 for (i
= 0; i
< todo_list
->nr
; i
++)
966 if (valid
== todo_list
->items
[i
].command
)
968 else if (valid
== TODO_PICK
)
969 return error(_("Cannot cherry-pick during a revert."));
971 return error(_("Cannot revert during a cherry-pick."));
975 return error(_("Unusable instruction sheet: %s"), todo_file
);
979 static int git_config_string_dup(char **dest
,
980 const char *var
, const char *value
)
983 return config_error_nonbool(var
);
985 *dest
= xstrdup(value
);
989 static int populate_opts_cb(const char *key
, const char *value
, void *data
)
991 struct replay_opts
*opts
= data
;
996 else if (!strcmp(key
, "options.no-commit"))
997 opts
->no_commit
= git_config_bool_or_int(key
, value
, &error_flag
);
998 else if (!strcmp(key
, "options.edit"))
999 opts
->edit
= git_config_bool_or_int(key
, value
, &error_flag
);
1000 else if (!strcmp(key
, "options.signoff"))
1001 opts
->signoff
= git_config_bool_or_int(key
, value
, &error_flag
);
1002 else if (!strcmp(key
, "options.record-origin"))
1003 opts
->record_origin
= git_config_bool_or_int(key
, value
, &error_flag
);
1004 else if (!strcmp(key
, "options.allow-ff"))
1005 opts
->allow_ff
= git_config_bool_or_int(key
, value
, &error_flag
);
1006 else if (!strcmp(key
, "options.mainline"))
1007 opts
->mainline
= git_config_int(key
, value
);
1008 else if (!strcmp(key
, "options.strategy"))
1009 git_config_string_dup(&opts
->strategy
, key
, value
);
1010 else if (!strcmp(key
, "options.gpg-sign"))
1011 git_config_string_dup(&opts
->gpg_sign
, key
, value
);
1012 else if (!strcmp(key
, "options.strategy-option")) {
1013 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
1014 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(value
);
1016 return error(_("Invalid key: %s"), key
);
1019 return error(_("Invalid value for %s: %s"), key
, value
);
1024 static int read_populate_opts(struct replay_opts
*opts
)
1026 if (is_rebase_i(opts
)) {
1027 struct strbuf buf
= STRBUF_INIT
;
1029 if (read_oneliner(&buf
, rebase_path_gpg_sign_opt(), 1)) {
1030 if (!starts_with(buf
.buf
, "-S"))
1033 free(opts
->gpg_sign
);
1034 opts
->gpg_sign
= xstrdup(buf
.buf
+ 2);
1037 strbuf_release(&buf
);
1042 if (!file_exists(git_path_opts_file()))
1045 * The function git_parse_source(), called from git_config_from_file(),
1046 * may die() in case of a syntactically incorrect file. We do not care
1047 * about this case, though, because we wrote that file ourselves, so we
1048 * are pretty certain that it is syntactically correct.
1050 if (git_config_from_file(populate_opts_cb
, git_path_opts_file(), opts
) < 0)
1051 return error(_("Malformed options sheet: %s"),
1052 git_path_opts_file());
1056 static int walk_revs_populate_todo(struct todo_list
*todo_list
,
1057 struct replay_opts
*opts
)
1059 enum todo_command command
= opts
->action
== REPLAY_PICK
?
1060 TODO_PICK
: TODO_REVERT
;
1061 const char *command_string
= todo_command_strings
[command
];
1062 struct commit
*commit
;
1064 if (prepare_revs(opts
))
1067 while ((commit
= get_revision(opts
->revs
))) {
1068 struct todo_item
*item
= append_new_todo(todo_list
);
1069 const char *commit_buffer
= get_commit_buffer(commit
, NULL
);
1070 const char *subject
;
1073 item
->command
= command
;
1074 item
->commit
= commit
;
1077 item
->offset_in_buf
= todo_list
->buf
.len
;
1078 subject_len
= find_commit_subject(commit_buffer
, &subject
);
1079 strbuf_addf(&todo_list
->buf
, "%s %s %.*s\n", command_string
,
1080 short_commit_name(commit
), subject_len
, subject
);
1081 unuse_commit_buffer(commit
, commit_buffer
);
1086 static int create_seq_dir(void)
1088 if (file_exists(git_path_seq_dir())) {
1089 error(_("a cherry-pick or revert is already in progress"));
1090 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1093 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1094 return error_errno(_("Could not create sequencer directory %s"),
1095 git_path_seq_dir());
1099 static int save_head(const char *head
)
1101 static struct lock_file head_lock
;
1102 struct strbuf buf
= STRBUF_INIT
;
1105 fd
= hold_lock_file_for_update(&head_lock
, git_path_head_file(), 0);
1107 rollback_lock_file(&head_lock
);
1108 return error_errno(_("Could not lock HEAD"));
1110 strbuf_addf(&buf
, "%s\n", head
);
1111 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
1112 rollback_lock_file(&head_lock
);
1113 return error_errno(_("Could not write to %s"),
1114 git_path_head_file());
1116 if (commit_lock_file(&head_lock
) < 0) {
1117 rollback_lock_file(&head_lock
);
1118 return error(_("Error wrapping up %s."), git_path_head_file());
1123 static int reset_for_rollback(const unsigned char *sha1
)
1125 const char *argv
[4]; /* reset --merge <arg> + NULL */
1127 argv
[1] = "--merge";
1128 argv
[2] = sha1_to_hex(sha1
);
1130 return run_command_v_opt(argv
, RUN_GIT_CMD
);
1133 static int rollback_single_pick(void)
1135 unsigned char head_sha1
[20];
1137 if (!file_exists(git_path_cherry_pick_head()) &&
1138 !file_exists(git_path_revert_head()))
1139 return error(_("no cherry-pick or revert in progress"));
1140 if (read_ref_full("HEAD", 0, head_sha1
, NULL
))
1141 return error(_("cannot resolve HEAD"));
1142 if (is_null_sha1(head_sha1
))
1143 return error(_("cannot abort from a branch yet to be born"));
1144 return reset_for_rollback(head_sha1
);
1147 int sequencer_rollback(struct replay_opts
*opts
)
1150 unsigned char sha1
[20];
1151 struct strbuf buf
= STRBUF_INIT
;
1153 f
= fopen(git_path_head_file(), "r");
1154 if (!f
&& errno
== ENOENT
) {
1156 * There is no multiple-cherry-pick in progress.
1157 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1158 * a single-cherry-pick in progress, abort that.
1160 return rollback_single_pick();
1163 return error_errno(_("cannot open %s"), git_path_head_file());
1164 if (strbuf_getline_lf(&buf
, f
)) {
1165 error(_("cannot read %s: %s"), git_path_head_file(),
1166 ferror(f
) ? strerror(errno
) : _("unexpected end of file"));
1171 if (get_sha1_hex(buf
.buf
, sha1
) || buf
.buf
[40] != '\0') {
1172 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1173 git_path_head_file());
1176 if (is_null_sha1(sha1
)) {
1177 error(_("cannot abort from a branch yet to be born"));
1180 if (reset_for_rollback(sha1
))
1182 strbuf_release(&buf
);
1183 return sequencer_remove_state(opts
);
1185 strbuf_release(&buf
);
1189 static int save_todo(struct todo_list
*todo_list
, struct replay_opts
*opts
)
1191 static struct lock_file todo_lock
;
1192 const char *todo_path
= get_todo_path(opts
);
1193 int next
= todo_list
->current
, offset
, fd
;
1195 fd
= hold_lock_file_for_update(&todo_lock
, todo_path
, 0);
1197 return error_errno(_("Could not lock '%s'"), todo_path
);
1198 offset
= next
< todo_list
->nr
?
1199 todo_list
->items
[next
].offset_in_buf
: todo_list
->buf
.len
;
1200 if (write_in_full(fd
, todo_list
->buf
.buf
+ offset
,
1201 todo_list
->buf
.len
- offset
) < 0)
1202 return error_errno(_("Could not write to '%s'"), todo_path
);
1203 if (commit_lock_file(&todo_lock
) < 0)
1204 return error(_("Error wrapping up %s."), todo_path
);
1208 static int save_opts(struct replay_opts
*opts
)
1210 const char *opts_file
= git_path_opts_file();
1213 if (opts
->no_commit
)
1214 res
|= git_config_set_in_file_gently(opts_file
, "options.no-commit", "true");
1216 res
|= git_config_set_in_file_gently(opts_file
, "options.edit", "true");
1218 res
|= git_config_set_in_file_gently(opts_file
, "options.signoff", "true");
1219 if (opts
->record_origin
)
1220 res
|= git_config_set_in_file_gently(opts_file
, "options.record-origin", "true");
1222 res
|= git_config_set_in_file_gently(opts_file
, "options.allow-ff", "true");
1223 if (opts
->mainline
) {
1224 struct strbuf buf
= STRBUF_INIT
;
1225 strbuf_addf(&buf
, "%d", opts
->mainline
);
1226 res
|= git_config_set_in_file_gently(opts_file
, "options.mainline", buf
.buf
);
1227 strbuf_release(&buf
);
1230 res
|= git_config_set_in_file_gently(opts_file
, "options.strategy", opts
->strategy
);
1232 res
|= git_config_set_in_file_gently(opts_file
, "options.gpg-sign", opts
->gpg_sign
);
1235 for (i
= 0; i
< opts
->xopts_nr
; i
++)
1236 res
|= git_config_set_multivar_in_file_gently(opts_file
,
1237 "options.strategy-option",
1238 opts
->xopts
[i
], "^$", 0);
1243 static int pick_commits(struct todo_list
*todo_list
, struct replay_opts
*opts
)
1247 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
1249 assert(!(opts
->signoff
|| opts
->no_commit
||
1250 opts
->record_origin
|| opts
->edit
));
1251 if (read_and_refresh_cache(opts
))
1254 while (todo_list
->current
< todo_list
->nr
) {
1255 struct todo_item
*item
= todo_list
->items
+ todo_list
->current
;
1256 if (save_todo(todo_list
, opts
))
1258 res
= do_pick_commit(item
->command
, item
->commit
, opts
);
1259 todo_list
->current
++;
1265 * Sequence of picks finished successfully; cleanup by
1266 * removing the .git/sequencer directory
1268 return sequencer_remove_state(opts
);
1271 static int continue_single_pick(void)
1273 const char *argv
[] = { "commit", NULL
};
1275 if (!file_exists(git_path_cherry_pick_head()) &&
1276 !file_exists(git_path_revert_head()))
1277 return error(_("no cherry-pick or revert in progress"));
1278 return run_command_v_opt(argv
, RUN_GIT_CMD
);
1281 int sequencer_continue(struct replay_opts
*opts
)
1283 struct todo_list todo_list
= TODO_LIST_INIT
;
1286 if (read_and_refresh_cache(opts
))
1289 if (!file_exists(get_todo_path(opts
)))
1290 return continue_single_pick();
1291 if (read_populate_opts(opts
))
1293 if ((res
= read_populate_todo(&todo_list
, opts
)))
1294 goto release_todo_list
;
1296 /* Verify that the conflict has been resolved */
1297 if (file_exists(git_path_cherry_pick_head()) ||
1298 file_exists(git_path_revert_head())) {
1299 res
= continue_single_pick();
1301 goto release_todo_list
;
1303 if (index_differs_from("HEAD", 0)) {
1304 res
= error_dirty_index(opts
);
1305 goto release_todo_list
;
1307 todo_list
.current
++;
1308 res
= pick_commits(&todo_list
, opts
);
1310 todo_list_release(&todo_list
);
1314 static int single_pick(struct commit
*cmit
, struct replay_opts
*opts
)
1316 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
1317 return do_pick_commit(opts
->action
== REPLAY_PICK
?
1318 TODO_PICK
: TODO_REVERT
, cmit
, opts
);
1321 int sequencer_pick_revisions(struct replay_opts
*opts
)
1323 struct todo_list todo_list
= TODO_LIST_INIT
;
1324 unsigned char sha1
[20];
1328 if (read_and_refresh_cache(opts
))
1331 for (i
= 0; i
< opts
->revs
->pending
.nr
; i
++) {
1332 unsigned char sha1
[20];
1333 const char *name
= opts
->revs
->pending
.objects
[i
].name
;
1335 /* This happens when using --stdin. */
1339 if (!get_sha1(name
, sha1
)) {
1340 if (!lookup_commit_reference_gently(sha1
, 1)) {
1341 enum object_type type
= sha1_object_info(sha1
, NULL
);
1342 return error(_("%s: can't cherry-pick a %s"),
1343 name
, typename(type
));
1346 return error(_("%s: bad revision"), name
);
1350 * If we were called as "git cherry-pick <commit>", just
1351 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1352 * REVERT_HEAD, and don't touch the sequencer state.
1353 * This means it is possible to cherry-pick in the middle
1354 * of a cherry-pick sequence.
1356 if (opts
->revs
->cmdline
.nr
== 1 &&
1357 opts
->revs
->cmdline
.rev
->whence
== REV_CMD_REV
&&
1358 opts
->revs
->no_walk
&&
1359 !opts
->revs
->cmdline
.rev
->flags
) {
1360 struct commit
*cmit
;
1361 if (prepare_revision_walk(opts
->revs
))
1362 return error(_("revision walk setup failed"));
1363 cmit
= get_revision(opts
->revs
);
1364 if (!cmit
|| get_revision(opts
->revs
))
1365 return error("BUG: expected exactly one commit from walk");
1366 return single_pick(cmit
, opts
);
1370 * Start a new cherry-pick/ revert sequence; but
1371 * first, make sure that an existing one isn't in
1375 if (walk_revs_populate_todo(&todo_list
, opts
) ||
1376 create_seq_dir() < 0)
1378 if (get_sha1("HEAD", sha1
) && (opts
->action
== REPLAY_REVERT
))
1379 return error(_("Can't revert as initial commit"));
1380 if (save_head(sha1_to_hex(sha1
)))
1382 if (save_opts(opts
))
1384 res
= pick_commits(&todo_list
, opts
);
1385 todo_list_release(&todo_list
);
1389 void append_signoff(struct strbuf
*msgbuf
, int ignore_footer
, unsigned flag
)
1391 unsigned no_dup_sob
= flag
& APPEND_SIGNOFF_DEDUP
;
1392 struct strbuf sob
= STRBUF_INIT
;
1395 strbuf_addstr(&sob
, sign_off_header
);
1396 strbuf_addstr(&sob
, fmt_name(getenv("GIT_COMMITTER_NAME"),
1397 getenv("GIT_COMMITTER_EMAIL")));
1398 strbuf_addch(&sob
, '\n');
1401 * If the whole message buffer is equal to the sob, pretend that we
1402 * found a conforming footer with a matching sob
1404 if (msgbuf
->len
- ignore_footer
== sob
.len
&&
1405 !strncmp(msgbuf
->buf
, sob
.buf
, sob
.len
))
1408 has_footer
= has_conforming_footer(msgbuf
, &sob
, ignore_footer
);
1411 const char *append_newlines
= NULL
;
1412 size_t len
= msgbuf
->len
- ignore_footer
;
1416 * The buffer is completely empty. Leave foom for
1417 * the title and body to be filled in by the user.
1419 append_newlines
= "\n\n";
1420 } else if (msgbuf
->buf
[len
- 1] != '\n') {
1422 * Incomplete line. Complete the line and add a
1423 * blank one so that there is an empty line between
1424 * the message body and the sob.
1426 append_newlines
= "\n\n";
1427 } else if (len
== 1) {
1429 * Buffer contains a single newline. Add another
1430 * so that we leave room for the title and body.
1432 append_newlines
= "\n";
1433 } else if (msgbuf
->buf
[len
- 2] != '\n') {
1435 * Buffer ends with a single newline. Add another
1436 * so that there is an empty line between the message
1439 append_newlines
= "\n";
1440 } /* else, the buffer already ends with two newlines. */
1442 if (append_newlines
)
1443 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
1444 append_newlines
, strlen(append_newlines
));
1447 if (has_footer
!= 3 && (!no_dup_sob
|| has_footer
!= 2))
1448 strbuf_splice(msgbuf
, msgbuf
->len
- ignore_footer
, 0,
1451 strbuf_release(&sob
);