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 ? N_("revert") : N_("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,
240 static struct lock_file msg_file;
242 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
244 return error_errno(_("could not lock '%s'"), filename);
245 if (write_in_full(msg_fd, buf, len) < 0) {
246 rollback_lock_file(&msg_file);
247 return error_errno(_("could not write to '%s'"), filename);
249 if (append_eol && write(msg_fd, "\n", 1) < 0) {
250 rollback_lock_file(&msg_file);
251 return error_errno(_("could not write eol to '%s'"), filename);
253 if (commit_lock_file(&msg_file) < 0) {
254 rollback_lock_file(&msg_file);
255 return error(_("failed to finalize '%s'."), filename);
262 * Reads a file that was presumably written by a shell script, i.e. with an
263 * end-of-line marker that needs to be stripped.
265 * Note that only the last end-of-line marker is stripped, consistent with the
266 * behavior of "$(cat path)" in a shell script.
268 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
270 static int read_oneliner(struct strbuf *buf,
271 const char *path, int skip_if_empty)
273 int orig_len = buf->len;
275 if (!file_exists(path))
278 if (strbuf_read_file(buf, path, 0) < 0) {
279 warning_errno(_("could not read '%s'"), path);
283 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
284 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
286 buf->buf[buf->len] = '\0';
289 if (skip_if_empty && buf->len == orig_len)
295 static struct tree *empty_tree(void)
297 return lookup_tree(EMPTY_TREE_SHA1_BIN);
300 static int error_dirty_index(struct replay_opts *opts)
302 if (read_cache_unmerged())
303 return error_resolve_conflict(_(action_name(opts)));
305 error(_("your local changes would be overwritten by %s."),
306 _(action_name(opts)));
308 if (advice_commit_before_merge)
309 advise(_("commit your changes or stash them to proceed."));
313 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
314 int unborn, struct replay_opts *opts)
316 struct ref_transaction *transaction;
317 struct strbuf sb = STRBUF_INIT;
318 struct strbuf err = STRBUF_INIT;
321 if (checkout_fast_forward(from, to, 1))
322 return -1; /* the callee should have complained already */
324 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
326 transaction = ref_transaction_begin(&err);
328 ref_transaction_update(transaction, "HEAD",
329 to, unborn ? null_sha1 : from,
331 ref_transaction_commit(transaction, &err)) {
332 ref_transaction_free(transaction);
333 error("%s", err.buf);
335 strbuf_release(&err);
340 strbuf_release(&err);
341 ref_transaction_free(transaction);
345 void append_conflicts_hint(struct strbuf *msgbuf)
349 strbuf_addch(msgbuf, '\n');
350 strbuf_commented_addf(msgbuf, "Conflicts:\n");
351 for (i = 0; i < active_nr;) {
352 const struct cache_entry *ce = active_cache[i++];
354 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
355 while (i < active_nr && !strcmp(ce->name,
356 active_cache[i]->name))
362 static int do_recursive_merge(struct commit *base, struct commit *next,
363 const char *base_label, const char *next_label,
364 unsigned char *head, struct strbuf *msgbuf,
365 struct replay_opts *opts)
367 struct merge_options o;
368 struct tree *result, *next_tree, *base_tree, *head_tree;
371 static struct lock_file index_lock;
373 hold_locked_index(&index_lock, 1);
377 init_merge_options(&o);
378 o.ancestor = base ? base_label : "(empty tree)";
380 o.branch2 = next ? next_label : "(empty tree)";
382 head_tree = parse_tree_indirect(head);
383 next_tree = next ? next->tree : empty_tree();
384 base_tree = base ? base->tree : empty_tree();
386 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
387 parse_merge_opt(&o, *xopt);
389 clean = merge_trees(&o,
391 next_tree, base_tree, &result);
392 strbuf_release(&o.obuf);
396 if (active_cache_changed &&
397 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
398 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
399 return error(_("%s: Unable to write new index file"),
400 _(action_name(opts)));
401 rollback_lock_file(&index_lock);
404 append_signoff(msgbuf, 0, 0);
407 append_conflicts_hint(msgbuf);
412 static int is_index_unchanged(void)
414 unsigned char head_sha1[20];
415 struct commit *head_commit;
417 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
418 return error(_("could not resolve HEAD commit\n"));
420 head_commit = lookup_commit(head_sha1);
423 * If head_commit is NULL, check_commit, called from
424 * lookup_commit, would have indicated that head_commit is not
425 * a commit object already. parse_commit() will return failure
426 * without further complaints in such a case. Otherwise, if
427 * the commit is invalid, parse_commit() will complain. So
428 * there is nothing for us to say here. Just return failure.
430 if (parse_commit(head_commit))
433 if (!active_cache_tree)
434 active_cache_tree = cache_tree();
436 if (!cache_tree_fully_valid(active_cache_tree))
437 if (cache_tree_update(&the_index, 0))
438 return error(_("unable to update cache tree\n"));
440 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
444 * Read the author-script file into an environment block, ready for use in
445 * run_command(), that can be free()d afterwards.
447 static char **read_author_script(void)
449 struct strbuf script = STRBUF_INIT;
454 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
457 for (p = script.buf; *p; p++)
458 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
459 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
461 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
462 else if (*p == '\n') {
467 env_size = (count + 1) * sizeof(*env);
468 strbuf_grow(&script, env_size);
469 memmove(script.buf + env_size, script.buf, script.len);
470 p = script.buf + env_size;
471 env = (char **)strbuf_detach(&script, NULL);
473 for (i = 0; i < count; i++) {
482 static const char staged_changes_advice[] =
483 N_("you have staged changes in your working tree\n"
484 "If these changes are meant to be squashed into the previous commit, run:\n"
486 " git commit --amend %s\n"
488 "If they are meant to go into a new commit, run:\n"
492 "In both cases, once you're done, continue with:\n"
494 " git rebase --continue\n");
497 * If we are cherry-pick, and if the merge did not result in
498 * hand-editing, we will hit this commit and inherit the original
499 * author date and name.
501 * If we are revert, or if our cherry-pick results in a hand merge,
502 * we had better say that the current user is responsible for that.
504 * An exception is when run_git_commit() is called during an
505 * interactive rebase: in that case, we will want to retain the
508 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
509 int allow_empty, int edit, int amend,
510 int cleanup_commit_message)
513 struct argv_array array;
517 if (is_rebase_i(opts)) {
518 env = read_author_script();
520 const char *gpg_opt = gpg_sign_opt_quoted(opts);
522 return error(_(staged_changes_advice),
527 argv_array_init(&array);
528 argv_array_push(&array, "commit");
529 argv_array_push(&array, "-n");
532 argv_array_push(&array, "--amend");
534 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
536 argv_array_push(&array, "-s");
538 argv_array_pushl(&array, "-F", defmsg, NULL);
539 if (cleanup_commit_message)
540 argv_array_push(&array, "--cleanup=strip");
542 argv_array_push(&array, "-e");
543 else if (!cleanup_commit_message &&
544 !opts->signoff && !opts->record_origin &&
545 git_config_get_value("commit.cleanup", &value))
546 argv_array_push(&array, "--cleanup=verbatim");
549 argv_array_push(&array, "--allow-empty");
551 if (opts->allow_empty_message)
552 argv_array_push(&array, "--allow-empty-message");
554 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
555 (const char *const *)env);
556 argv_array_clear(&array);
562 static int is_original_commit_empty(struct commit *commit)
564 const unsigned char *ptree_sha1;
566 if (parse_commit(commit))
567 return error(_("could not parse commit %s\n"),
568 oid_to_hex(&commit->object.oid));
569 if (commit->parents) {
570 struct commit *parent = commit->parents->item;
571 if (parse_commit(parent))
572 return error(_("could not parse parent commit %s\n"),
573 oid_to_hex(&parent->object.oid));
574 ptree_sha1 = parent->tree->object.oid.hash;
576 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
579 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
583 * Do we run "git commit" with "--allow-empty"?
585 static int allow_empty(struct replay_opts *opts, struct commit *commit)
587 int index_unchanged, empty_commit;
592 * (1) we do not allow empty at all and error out.
594 * (2) we allow ones that were initially empty, but
595 * forbid the ones that become empty;
599 if (!opts->allow_empty)
600 return 0; /* let "git commit" barf as necessary */
602 index_unchanged = is_index_unchanged();
603 if (index_unchanged < 0)
604 return index_unchanged;
605 if (!index_unchanged)
606 return 0; /* we do not have to say --allow-empty */
608 if (opts->keep_redundant_commits)
611 empty_commit = is_original_commit_empty(commit);
612 if (empty_commit < 0)
625 static const char *todo_command_strings[] = {
630 static const char *command_to_string(const enum todo_command command)
632 if ((size_t)command < ARRAY_SIZE(todo_command_strings))
633 return todo_command_strings[command];
634 die("Unknown command: %d", command);
638 static int do_pick_commit(enum todo_command command, struct commit *commit,
639 struct replay_opts *opts)
641 unsigned char head[20];
642 struct commit *base, *next, *parent;
643 const char *base_label, *next_label;
644 struct commit_message msg = { NULL, NULL, NULL, NULL };
645 struct strbuf msgbuf = STRBUF_INIT;
646 int res, unborn = 0, allow;
648 if (opts->no_commit) {
650 * We do not intend to commit immediately. We just want to
651 * merge the differences in, so let's compute the tree
652 * that represents the "current" state for merge-recursive
655 if (write_cache_as_tree(head, 0, NULL))
656 return error(_("your index file is unmerged."));
658 unborn = get_sha1("HEAD", head);
660 hashcpy(head, EMPTY_TREE_SHA1_BIN);
661 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
662 return error_dirty_index(opts);
666 if (!commit->parents) {
669 else if (commit->parents->next) {
670 /* Reverting or cherry-picking a merge commit */
672 struct commit_list *p;
675 return error(_("commit %s is a merge but no -m option was given."),
676 oid_to_hex(&commit->object.oid));
678 for (cnt = 1, p = commit->parents;
679 cnt != opts->mainline && p;
682 if (cnt != opts->mainline || !p)
683 return error(_("commit %s does not have parent %d"),
684 oid_to_hex(&commit->object.oid), opts->mainline);
686 } else if (0 < opts->mainline)
687 return error(_("mainline was specified but commit %s is not a merge."),
688 oid_to_hex(&commit->object.oid));
690 parent = commit->parents->item;
692 if (opts->allow_ff &&
693 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
694 (!parent && unborn)))
695 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
697 if (parent && parse_commit(parent) < 0)
698 /* TRANSLATORS: The first %s will be a "todo" command like
699 "revert" or "pick", the second %s a SHA1. */
700 return error(_("%s: cannot parse parent commit %s"),
701 command_to_string(command),
702 oid_to_hex(&parent->object.oid));
704 if (get_message(commit, &msg) != 0)
705 return error(_("cannot get commit message for %s"),
706 oid_to_hex(&commit->object.oid));
709 * "commit" is an existing commit. We would want to apply
710 * the difference it introduces since its first parent "prev"
711 * on top of the current HEAD if we are cherry-pick. Or the
712 * reverse of it if we are revert.
715 if (command == TODO_REVERT) {
717 base_label = msg.label;
719 next_label = msg.parent_label;
720 strbuf_addstr(&msgbuf, "Revert \"");
721 strbuf_addstr(&msgbuf, msg.subject);
722 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
723 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
725 if (commit->parents && commit->parents->next) {
726 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
727 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
729 strbuf_addstr(&msgbuf, ".\n");
734 base_label = msg.parent_label;
736 next_label = msg.label;
739 * Append the commit log message to msgbuf; it starts
740 * after the tree, parent, author, committer
741 * information followed by "\n\n".
743 p = strstr(msg.message, "\n\n");
745 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
747 if (opts->record_origin) {
748 if (!has_conforming_footer(&msgbuf, NULL, 0))
749 strbuf_addch(&msgbuf, '\n');
750 strbuf_addstr(&msgbuf, cherry_picked_prefix);
751 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
752 strbuf_addstr(&msgbuf, ")\n");
756 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
757 res = do_recursive_merge(base, next, base_label, next_label,
758 head, &msgbuf, opts);
761 res |= write_message(msgbuf.buf, msgbuf.len,
762 git_path_merge_msg(), 0);
764 struct commit_list *common = NULL;
765 struct commit_list *remotes = NULL;
767 res = write_message(msgbuf.buf, msgbuf.len,
768 git_path_merge_msg(), 0);
770 commit_list_insert(base, &common);
771 commit_list_insert(next, &remotes);
772 res |= try_merge_command(opts->strategy,
773 opts->xopts_nr, (const char **)opts->xopts,
774 common, sha1_to_hex(head), remotes);
775 free_commit_list(common);
776 free_commit_list(remotes);
778 strbuf_release(&msgbuf);
781 * If the merge was clean or if it failed due to conflict, we write
782 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
783 * However, if the merge did not even start, then we don't want to
786 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
787 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
788 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
790 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
791 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
792 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
796 error(command == TODO_REVERT
797 ? _("could not revert %s... %s")
798 : _("could not apply %s... %s"),
799 short_commit_name(commit), msg.subject);
800 print_advice(res == 1, opts);
801 rerere(opts->allow_rerere_auto);
805 allow = allow_empty(opts, commit);
810 if (!opts->no_commit)
811 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
812 opts, allow, opts->edit, 0, 0);
815 free_message(commit, &msg);
820 static int prepare_revs(struct replay_opts *opts)
823 * picking (but not reverting) ranges (but not individual revisions)
824 * should be done in reverse
826 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
827 opts->revs->reverse ^= 1;
829 if (prepare_revision_walk(opts->revs))
830 return error(_("revision walk setup failed"));
832 if (!opts->revs->commits)
833 return error(_("empty commit set passed"));
837 static int read_and_refresh_cache(struct replay_opts *opts)
839 static struct lock_file index_lock;
840 int index_fd = hold_locked_index(&index_lock, 0);
841 if (read_index_preload(&the_index, NULL) < 0) {
842 rollback_lock_file(&index_lock);
843 return error(_("git %s: failed to read the index"),
844 _(action_name(opts)));
846 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
847 if (the_index.cache_changed && index_fd >= 0) {
848 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
849 rollback_lock_file(&index_lock);
850 return error(_("git %s: failed to refresh the index"),
851 _(action_name(opts)));
854 rollback_lock_file(&index_lock);
859 enum todo_command command;
860 struct commit *commit;
863 size_t offset_in_buf;
868 struct todo_item *items;
869 int nr, alloc, current;
872 #define TODO_LIST_INIT { STRBUF_INIT }
874 static void todo_list_release(struct todo_list *todo_list)
876 strbuf_release(&todo_list->buf);
877 free(todo_list->items);
878 todo_list->items = NULL;
879 todo_list->nr = todo_list->alloc = 0;
882 static struct todo_item *append_new_todo(struct todo_list *todo_list)
884 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
885 return todo_list->items + todo_list->nr++;
888 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
890 unsigned char commit_sha1[20];
891 char *end_of_object_name;
892 int i, saved, status, padding;
895 bol += strspn(bol, " \t");
897 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
898 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
902 if (i >= ARRAY_SIZE(todo_command_strings))
905 /* Eat up extra spaces/ tabs before object name */
906 padding = strspn(bol, " \t");
911 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
912 saved = *end_of_object_name;
913 *end_of_object_name = '\0';
914 status = get_sha1(bol, commit_sha1);
915 *end_of_object_name = saved;
917 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
918 item->arg_len = (int)(eol - item->arg);
923 item->commit = lookup_commit_reference(commit_sha1);
924 return !item->commit;
927 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
929 struct todo_item *item;
930 char *p = buf, *next_p;
933 for (i = 1; *p; i++, p = next_p) {
934 char *eol = strchrnul(p, '\n');
936 next_p = *eol ? eol + 1 /* skip LF */ : eol;
938 if (p != eol && eol[-1] == '\r')
939 eol--; /* strip Carriage Return */
941 item = append_new_todo(todo_list);
942 item->offset_in_buf = p - todo_list->buf.buf;
943 if (parse_insn_line(item, p, eol)) {
944 res = error(_("invalid line %d: %.*s"),
945 i, (int)(eol - p), p);
950 return error(_("no commits parsed."));
954 static int read_populate_todo(struct todo_list *todo_list,
955 struct replay_opts *opts)
957 const char *todo_file = get_todo_path(opts);
960 strbuf_reset(&todo_list->buf);
961 fd = open(todo_file, O_RDONLY);
963 return error_errno(_("could not open '%s'"), todo_file);
964 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
966 return error(_("could not read '%s'."), todo_file);
970 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
972 return error(_("unusable instruction sheet: '%s'"), todo_file);
974 if (!is_rebase_i(opts)) {
975 enum todo_command valid =
976 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
979 for (i = 0; i < todo_list->nr; i++)
980 if (valid == todo_list->items[i].command)
982 else if (valid == TODO_PICK)
983 return error(_("cannot cherry-pick during a revert."));
985 return error(_("cannot revert during a cherry-pick."));
991 static int git_config_string_dup(char **dest,
992 const char *var, const char *value)
995 return config_error_nonbool(var);
997 *dest = xstrdup(value);
1001 static int populate_opts_cb(const char *key, const char *value, void *data)
1003 struct replay_opts *opts = data;
1008 else if (!strcmp(key, "options.no-commit"))
1009 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1010 else if (!strcmp(key, "options.edit"))
1011 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1012 else if (!strcmp(key, "options.signoff"))
1013 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1014 else if (!strcmp(key, "options.record-origin"))
1015 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1016 else if (!strcmp(key, "options.allow-ff"))
1017 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1018 else if (!strcmp(key, "options.mainline"))
1019 opts->mainline = git_config_int(key, value);
1020 else if (!strcmp(key, "options.strategy"))
1021 git_config_string_dup(&opts->strategy, key, value);
1022 else if (!strcmp(key, "options.gpg-sign"))
1023 git_config_string_dup(&opts->gpg_sign, key, value);
1024 else if (!strcmp(key, "options.strategy-option")) {
1025 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1026 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1028 return error(_("invalid key: %s"), key);
1031 return error(_("invalid value for %s: %s"), key, value);
1036 static int read_populate_opts(struct replay_opts *opts)
1038 if (is_rebase_i(opts)) {
1039 struct strbuf buf = STRBUF_INIT;
1041 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1042 if (!starts_with(buf.buf, "-S"))
1045 free(opts->gpg_sign);
1046 opts->gpg_sign = xstrdup(buf.buf + 2);
1049 strbuf_release(&buf);
1054 if (!file_exists(git_path_opts_file()))
1057 * The function git_parse_source(), called from git_config_from_file(),
1058 * may die() in case of a syntactically incorrect file. We do not care
1059 * about this case, though, because we wrote that file ourselves, so we
1060 * are pretty certain that it is syntactically correct.
1062 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1063 return error(_("malformed options sheet: '%s'"),
1064 git_path_opts_file());
1068 static int walk_revs_populate_todo(struct todo_list *todo_list,
1069 struct replay_opts *opts)
1071 enum todo_command command = opts->action == REPLAY_PICK ?
1072 TODO_PICK : TODO_REVERT;
1073 const char *command_string = todo_command_strings[command];
1074 struct commit *commit;
1076 if (prepare_revs(opts))
1079 while ((commit = get_revision(opts->revs))) {
1080 struct todo_item *item = append_new_todo(todo_list);
1081 const char *commit_buffer = get_commit_buffer(commit, NULL);
1082 const char *subject;
1085 item->command = command;
1086 item->commit = commit;
1089 item->offset_in_buf = todo_list->buf.len;
1090 subject_len = find_commit_subject(commit_buffer, &subject);
1091 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1092 short_commit_name(commit), subject_len, subject);
1093 unuse_commit_buffer(commit, commit_buffer);
1098 static int create_seq_dir(void)
1100 if (file_exists(git_path_seq_dir())) {
1101 error(_("a cherry-pick or revert is already in progress"));
1102 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1105 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1106 return error_errno(_("could not create sequencer directory '%s'"),
1107 git_path_seq_dir());
1111 static int save_head(const char *head)
1113 static struct lock_file head_lock;
1114 struct strbuf buf = STRBUF_INIT;
1117 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1119 rollback_lock_file(&head_lock);
1120 return error_errno(_("could not lock HEAD"));
1122 strbuf_addf(&buf, "%s\n", head);
1123 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1124 rollback_lock_file(&head_lock);
1125 return error_errno(_("could not write to '%s'"),
1126 git_path_head_file());
1128 if (commit_lock_file(&head_lock) < 0) {
1129 rollback_lock_file(&head_lock);
1130 return error(_("failed to finalize '%s'."), git_path_head_file());
1135 static int reset_for_rollback(const unsigned char *sha1)
1137 const char *argv[4]; /* reset --merge <arg> + NULL */
1139 argv[1] = "--merge";
1140 argv[2] = sha1_to_hex(sha1);
1142 return run_command_v_opt(argv, RUN_GIT_CMD);
1145 static int rollback_single_pick(void)
1147 unsigned char head_sha1[20];
1149 if (!file_exists(git_path_cherry_pick_head()) &&
1150 !file_exists(git_path_revert_head()))
1151 return error(_("no cherry-pick or revert in progress"));
1152 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1153 return error(_("cannot resolve HEAD"));
1154 if (is_null_sha1(head_sha1))
1155 return error(_("cannot abort from a branch yet to be born"));
1156 return reset_for_rollback(head_sha1);
1159 int sequencer_rollback(struct replay_opts *opts)
1162 unsigned char sha1[20];
1163 struct strbuf buf = STRBUF_INIT;
1165 f = fopen(git_path_head_file(), "r");
1166 if (!f && errno == ENOENT) {
1168 * There is no multiple-cherry-pick in progress.
1169 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1170 * a single-cherry-pick in progress, abort that.
1172 return rollback_single_pick();
1175 return error_errno(_("cannot open '%s'"), git_path_head_file());
1176 if (strbuf_getline_lf(&buf, f)) {
1177 error(_("cannot read '%s': %s"), git_path_head_file(),
1178 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1183 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1184 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1185 git_path_head_file());
1188 if (is_null_sha1(sha1)) {
1189 error(_("cannot abort from a branch yet to be born"));
1192 if (reset_for_rollback(sha1))
1194 strbuf_release(&buf);
1195 return sequencer_remove_state(opts);
1197 strbuf_release(&buf);
1201 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1203 static struct lock_file todo_lock;
1204 const char *todo_path = get_todo_path(opts);
1205 int next = todo_list->current, offset, fd;
1207 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1209 return error_errno(_("could not lock '%s'"), todo_path);
1210 offset = next < todo_list->nr ?
1211 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1212 if (write_in_full(fd, todo_list->buf.buf + offset,
1213 todo_list->buf.len - offset) < 0)
1214 return error_errno(_("could not write to '%s'"), todo_path);
1215 if (commit_lock_file(&todo_lock) < 0)
1216 return error(_("failed to finalize '%s'."), todo_path);
1220 static int save_opts(struct replay_opts *opts)
1222 const char *opts_file = git_path_opts_file();
1225 if (opts->no_commit)
1226 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1228 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1230 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1231 if (opts->record_origin)
1232 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1234 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1235 if (opts->mainline) {
1236 struct strbuf buf = STRBUF_INIT;
1237 strbuf_addf(&buf, "%d", opts->mainline);
1238 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1239 strbuf_release(&buf);
1242 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1244 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1247 for (i = 0; i < opts->xopts_nr; i++)
1248 res |= git_config_set_multivar_in_file_gently(opts_file,
1249 "options.strategy-option",
1250 opts->xopts[i], "^$", 0);
1255 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1259 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1261 assert(!(opts->signoff || opts->no_commit ||
1262 opts->record_origin || opts->edit));
1263 if (read_and_refresh_cache(opts))
1266 while (todo_list->current < todo_list->nr) {
1267 struct todo_item *item = todo_list->items + todo_list->current;
1268 if (save_todo(todo_list, opts))
1270 res = do_pick_commit(item->command, item->commit, opts);
1271 todo_list->current++;
1277 * Sequence of picks finished successfully; cleanup by
1278 * removing the .git/sequencer directory
1280 return sequencer_remove_state(opts);
1283 static int continue_single_pick(void)
1285 const char *argv[] = { "commit", NULL };
1287 if (!file_exists(git_path_cherry_pick_head()) &&
1288 !file_exists(git_path_revert_head()))
1289 return error(_("no cherry-pick or revert in progress"));
1290 return run_command_v_opt(argv, RUN_GIT_CMD);
1293 int sequencer_continue(struct replay_opts *opts)
1295 struct todo_list todo_list = TODO_LIST_INIT;
1298 if (read_and_refresh_cache(opts))
1301 if (!file_exists(get_todo_path(opts)))
1302 return continue_single_pick();
1303 if (read_populate_opts(opts))
1305 if ((res = read_populate_todo(&todo_list, opts)))
1306 goto release_todo_list;
1308 /* Verify that the conflict has been resolved */
1309 if (file_exists(git_path_cherry_pick_head()) ||
1310 file_exists(git_path_revert_head())) {
1311 res = continue_single_pick();
1313 goto release_todo_list;
1315 if (index_differs_from("HEAD", 0, 0)) {
1316 res = error_dirty_index(opts);
1317 goto release_todo_list;
1319 todo_list.current++;
1320 res = pick_commits(&todo_list, opts);
1322 todo_list_release(&todo_list);
1326 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1328 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1329 return do_pick_commit(opts->action == REPLAY_PICK ?
1330 TODO_PICK : TODO_REVERT, cmit, opts);
1333 int sequencer_pick_revisions(struct replay_opts *opts)
1335 struct todo_list todo_list = TODO_LIST_INIT;
1336 unsigned char sha1[20];
1340 if (read_and_refresh_cache(opts))
1343 for (i = 0; i < opts->revs->pending.nr; i++) {
1344 unsigned char sha1[20];
1345 const char *name = opts->revs->pending.objects[i].name;
1347 /* This happens when using --stdin. */
1351 if (!get_sha1(name, sha1)) {
1352 if (!lookup_commit_reference_gently(sha1, 1)) {
1353 enum object_type type = sha1_object_info(sha1, NULL);
1354 return error(_("%s: can't cherry-pick a %s"),
1355 name, typename(type));
1358 return error(_("%s: bad revision"), name);
1362 * If we were called as "git cherry-pick <commit>", just
1363 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1364 * REVERT_HEAD, and don't touch the sequencer state.
1365 * This means it is possible to cherry-pick in the middle
1366 * of a cherry-pick sequence.
1368 if (opts->revs->cmdline.nr == 1 &&
1369 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1370 opts->revs->no_walk &&
1371 !opts->revs->cmdline.rev->flags) {
1372 struct commit *cmit;
1373 if (prepare_revision_walk(opts->revs))
1374 return error(_("revision walk setup failed"));
1375 cmit = get_revision(opts->revs);
1376 if (!cmit || get_revision(opts->revs))
1377 return error("BUG: expected exactly one commit from walk");
1378 return single_pick(cmit, opts);
1382 * Start a new cherry-pick/ revert sequence; but
1383 * first, make sure that an existing one isn't in
1387 if (walk_revs_populate_todo(&todo_list, opts) ||
1388 create_seq_dir() < 0)
1390 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1391 return error(_("can't revert as initial commit"));
1392 if (save_head(sha1_to_hex(sha1)))
1394 if (save_opts(opts))
1396 res = pick_commits(&todo_list, opts);
1397 todo_list_release(&todo_list);
1401 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1403 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1404 struct strbuf sob = STRBUF_INIT;
1407 strbuf_addstr(&sob, sign_off_header);
1408 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1409 getenv("GIT_COMMITTER_EMAIL")));
1410 strbuf_addch(&sob, '\n');
1413 * If the whole message buffer is equal to the sob, pretend that we
1414 * found a conforming footer with a matching sob
1416 if (msgbuf->len - ignore_footer == sob.len &&
1417 !strncmp(msgbuf->buf, sob.buf, sob.len))
1420 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1423 const char *append_newlines = NULL;
1424 size_t len = msgbuf->len - ignore_footer;
1428 * The buffer is completely empty. Leave foom for
1429 * the title and body to be filled in by the user.
1431 append_newlines = "\n\n";
1432 } else if (msgbuf->buf[len - 1] != '\n') {
1434 * Incomplete line. Complete the line and add a
1435 * blank one so that there is an empty line between
1436 * the message body and the sob.
1438 append_newlines = "\n\n";
1439 } else if (len == 1) {
1441 * Buffer contains a single newline. Add another
1442 * so that we leave room for the title and body.
1444 append_newlines = "\n";
1445 } else if (msgbuf->buf[len - 2] != '\n') {
1447 * Buffer ends with a single newline. Add another
1448 * so that there is an empty line between the message
1451 append_newlines = "\n";
1452 } /* else, the buffer already ends with two newlines. */
1454 if (append_newlines)
1455 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1456 append_newlines, strlen(append_newlines));
1459 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1460 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1463 strbuf_release(&sob);