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 ";
24 static struct rewritten rewritten;
26 static GIT_PATH_FUNC(git_path_todo_file, SEQ_TODO_FILE)
27 static GIT_PATH_FUNC(git_path_opts_file, SEQ_OPTS_FILE)
28 static GIT_PATH_FUNC(git_path_seq_dir, SEQ_DIR)
29 static GIT_PATH_FUNC(git_path_head_file, SEQ_HEAD_FILE)
31 static void finish(struct replay_opts *opts)
34 struct strbuf msg = STRBUF_INIT;
36 if (opts->action != REPLAY_PICK)
39 name = opts->action_name ? opts->action_name : "cherry-pick";
44 strbuf_addf(&msg, "Notes added by 'git %s'", name);
45 copy_rewrite_notes(&rewritten, name, msg.buf);
46 run_rewrite_hook(&rewritten, name);
50 static int is_rfc2822_line(const char *buf, int len)
54 for (i = 0; i < len; i++) {
58 if (!isalnum(ch) && ch != '-')
65 static int is_cherry_picked_from_line(const char *buf, int len)
68 * We only care that it looks roughly like (cherry picked from ...)
70 return len > strlen(cherry_picked_prefix) + 1 &&
71 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
75 * Returns 0 for non-conforming footer
76 * Returns 1 for conforming footer
77 * Returns 2 when sob exists within conforming footer
78 * Returns 3 when sob exists within conforming footer as last entry
80 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
85 int len = sb->len - ignore_footer;
86 const char *buf = sb->buf;
89 /* footer must end with newline */
90 if (!len || buf[len - 1] != '\n')
94 for (i = len - 1; i > 0; i--) {
96 if (prev == '\n' && ch == '\n') /* paragraph break */
101 /* require at least one blank line */
102 if (prev != '\n' || buf[i] != '\n')
105 /* advance to start of last paragraph */
106 while (i < len - 1 && buf[i] == '\n')
109 for (; i < len; i = k) {
112 for (k = i; k < len && buf[k] != '\n'; k++)
116 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
117 if (found_rfc2822 && sob &&
118 !strncmp(buf + i, sob->buf, sob->len))
121 if (!(found_rfc2822 ||
122 is_cherry_picked_from_line(buf + i, k - i - 1)))
132 static void remove_sequencer_state(void)
134 struct strbuf seq_dir = STRBUF_INIT;
136 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
137 remove_dir_recursively(&seq_dir, 0);
138 strbuf_release(&seq_dir);
141 static const char *action_name(const struct replay_opts *opts)
143 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
146 struct commit_message {
153 static int get_message(struct commit *commit, struct commit_message *out)
155 const char *abbrev, *subject;
158 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
159 abbrev = find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
161 subject_len = find_commit_subject(out->message, &subject);
163 out->subject = xmemdupz(subject, subject_len);
164 out->label = xstrfmt("%s... %s", abbrev, out->subject);
165 out->parent_label = xstrfmt("parent of %s", out->label);
170 static void free_message(struct commit *commit, struct commit_message *msg)
172 free(msg->parent_label);
175 unuse_commit_buffer(commit, msg->message);
178 static void print_advice(int show_hint, struct replay_opts *opts)
180 char *msg = getenv("GIT_CHERRY_PICK_HELP");
183 fprintf(stderr, "%s\n", msg);
185 * A conflict has occurred but the porcelain
186 * (typically rebase --interactive) wants to take care
187 * of the commit itself so remove CHERRY_PICK_HEAD
189 unlink(git_path_cherry_pick_head());
195 advise(_("after resolving the conflicts, mark the corrected paths\n"
196 "with 'git add <paths>' or 'git rm <paths>'"));
198 advise(_("after resolving the conflicts, mark the corrected paths\n"
199 "with 'git add <paths>' or 'git rm <paths>'\n"
200 "and commit the result with 'git commit'"));
204 static void write_message(struct strbuf *msgbuf, const char *filename)
206 static struct lock_file msg_file;
208 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
210 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
211 die_errno(_("Could not write to %s"), filename);
212 strbuf_release(msgbuf);
213 if (commit_lock_file(&msg_file) < 0)
214 die(_("Error wrapping up %s"), filename);
217 static struct tree *empty_tree(void)
219 return lookup_tree(EMPTY_TREE_SHA1_BIN);
222 static int error_dirty_index(struct replay_opts *opts)
224 if (read_cache_unmerged())
225 return error_resolve_conflict(action_name(opts));
227 /* Different translation strings for cherry-pick and revert */
228 if (opts->action == REPLAY_PICK)
229 error(_("Your local changes would be overwritten by cherry-pick."));
231 error(_("Your local changes would be overwritten by revert."));
233 if (advice_commit_before_merge)
234 advise(_("Commit your changes or stash them to proceed."));
238 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
239 int unborn, struct replay_opts *opts)
241 struct ref_transaction *transaction;
242 struct strbuf sb = STRBUF_INIT;
243 struct strbuf err = STRBUF_INIT;
246 if (checkout_fast_forward(from, to, 1))
247 exit(128); /* the callee should have complained already */
249 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
251 transaction = ref_transaction_begin(&err);
253 ref_transaction_update(transaction, "HEAD",
254 to, unborn ? null_sha1 : from,
256 ref_transaction_commit(transaction, &err)) {
257 ref_transaction_free(transaction);
258 error("%s", err.buf);
260 strbuf_release(&err);
265 strbuf_release(&err);
266 ref_transaction_free(transaction);
270 void append_conflicts_hint(struct strbuf *msgbuf)
274 strbuf_addch(msgbuf, '\n');
275 strbuf_commented_addf(msgbuf, "Conflicts:\n");
276 for (i = 0; i < active_nr;) {
277 const struct cache_entry *ce = active_cache[i++];
279 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
280 while (i < active_nr && !strcmp(ce->name,
281 active_cache[i]->name))
287 static int do_recursive_merge(struct commit *base, struct commit *next,
288 const char *base_label, const char *next_label,
289 unsigned char *head, struct strbuf *msgbuf,
290 struct replay_opts *opts)
292 struct merge_options o;
293 struct tree *result, *next_tree, *base_tree, *head_tree;
296 static struct lock_file index_lock;
298 hold_locked_index(&index_lock, 1);
302 init_merge_options(&o);
303 o.ancestor = base ? base_label : "(empty tree)";
305 o.branch2 = next ? next_label : "(empty tree)";
307 head_tree = parse_tree_indirect(head);
308 next_tree = next ? next->tree : empty_tree();
309 base_tree = base ? base->tree : empty_tree();
311 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
312 parse_merge_opt(&o, *xopt);
314 clean = merge_trees(&o,
316 next_tree, base_tree, &result);
318 if (active_cache_changed &&
319 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
320 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
321 die(_("%s: Unable to write new index file"), action_name(opts));
322 rollback_lock_file(&index_lock);
325 append_signoff(msgbuf, 0, 0);
328 append_conflicts_hint(msgbuf);
333 static int is_index_unchanged(void)
335 unsigned char head_sha1[20];
336 struct commit *head_commit;
338 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
339 return error(_("Could not resolve HEAD commit\n"));
341 head_commit = lookup_commit(head_sha1);
344 * If head_commit is NULL, check_commit, called from
345 * lookup_commit, would have indicated that head_commit is not
346 * a commit object already. parse_commit() will return failure
347 * without further complaints in such a case. Otherwise, if
348 * the commit is invalid, parse_commit() will complain. So
349 * there is nothing for us to say here. Just return failure.
351 if (parse_commit(head_commit))
354 if (!active_cache_tree)
355 active_cache_tree = cache_tree();
357 if (!cache_tree_fully_valid(active_cache_tree))
358 if (cache_tree_update(&the_index, 0))
359 return error(_("Unable to update cache tree\n"));
361 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
365 * If we are cherry-pick, and if the merge did not result in
366 * hand-editing, we will hit this commit and inherit the original
367 * author date and name.
368 * If we are revert, or if our cherry-pick results in a hand merge,
369 * we had better say that the current user is responsible for that.
371 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
374 struct argv_array array;
378 argv_array_init(&array);
379 argv_array_push(&array, "commit");
380 argv_array_push(&array, "-n");
382 argv_array_push(&array, "-q");
385 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
387 argv_array_push(&array, "-s");
389 argv_array_push(&array, "-F");
390 argv_array_push(&array, defmsg);
391 if (!opts->signoff &&
392 !opts->record_origin &&
393 git_config_get_value("commit.cleanup", &value))
394 argv_array_push(&array, "--cleanup=verbatim");
398 argv_array_push(&array, "--allow-empty");
400 if (opts->allow_empty_message)
401 argv_array_push(&array, "--allow-empty-message");
403 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
404 argv_array_clear(&array);
408 static int is_original_commit_empty(struct commit *commit)
410 const unsigned char *ptree_sha1;
412 if (parse_commit(commit))
413 return error(_("Could not parse commit %s\n"),
414 oid_to_hex(&commit->object.oid));
415 if (commit->parents) {
416 struct commit *parent = commit->parents->item;
417 if (parse_commit(parent))
418 return error(_("Could not parse parent commit %s\n"),
419 oid_to_hex(&parent->object.oid));
420 ptree_sha1 = parent->tree->object.oid.hash;
422 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
425 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
429 * Do we run "git commit" with "--allow-empty"?
431 static int allow_empty(struct replay_opts *opts, struct commit *commit)
433 int index_unchanged, empty_commit;
438 * (1) we do not allow empty at all and error out.
440 * (2) we allow ones that were initially empty, but
441 * forbid the ones that become empty;
445 if (!opts->allow_empty)
446 return 0; /* let "git commit" barf as necessary */
448 index_unchanged = is_index_unchanged();
449 if (index_unchanged < 0)
450 return index_unchanged;
451 if (!index_unchanged)
452 return 0; /* we do not have to say --allow-empty */
454 if (opts->keep_redundant_commits)
457 empty_commit = is_original_commit_empty(commit);
458 if (empty_commit < 0)
466 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
468 unsigned char head[20];
469 struct commit *base, *next, *parent;
470 const char *base_label, *next_label;
471 struct commit_message msg = { NULL, NULL, NULL, NULL };
472 struct strbuf msgbuf = STRBUF_INIT;
473 int res, unborn = 0, allow;
475 if (opts->no_commit) {
477 * We do not intend to commit immediately. We just want to
478 * merge the differences in, so let's compute the tree
479 * that represents the "current" state for merge-recursive
482 if (write_cache_as_tree(head, 0, NULL))
483 die (_("Your index file is unmerged."));
485 unborn = get_sha1("HEAD", head);
487 hashcpy(head, EMPTY_TREE_SHA1_BIN);
488 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
489 return error_dirty_index(opts);
493 if (!commit->parents) {
496 else if (commit->parents->next) {
497 /* Reverting or cherry-picking a merge commit */
499 struct commit_list *p;
502 return error(_("Commit %s is a merge but no -m option was given."),
503 oid_to_hex(&commit->object.oid));
505 for (cnt = 1, p = commit->parents;
506 cnt != opts->mainline && p;
509 if (cnt != opts->mainline || !p)
510 return error(_("Commit %s does not have parent %d"),
511 oid_to_hex(&commit->object.oid), opts->mainline);
513 } else if (0 < opts->mainline)
514 return error(_("Mainline was specified but commit %s is not a merge."),
515 oid_to_hex(&commit->object.oid));
517 parent = commit->parents->item;
519 if (opts->allow_ff &&
520 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
521 (!parent && unborn)))
522 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
524 if (parent && parse_commit(parent) < 0)
525 /* TRANSLATORS: The first %s will be "revert" or
526 "cherry-pick", the second %s a SHA1 */
527 return error(_("%s: cannot parse parent commit %s"),
528 action_name(opts), oid_to_hex(&parent->object.oid));
530 if (get_message(commit, &msg) != 0)
531 return error(_("Cannot get commit message for %s"),
532 oid_to_hex(&commit->object.oid));
535 * "commit" is an existing commit. We would want to apply
536 * the difference it introduces since its first parent "prev"
537 * on top of the current HEAD if we are cherry-pick. Or the
538 * reverse of it if we are revert.
541 if (opts->action == REPLAY_REVERT) {
543 base_label = msg.label;
545 next_label = msg.parent_label;
546 strbuf_addstr(&msgbuf, "Revert \"");
547 strbuf_addstr(&msgbuf, msg.subject);
548 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
549 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
551 if (commit->parents && commit->parents->next) {
552 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
553 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
555 strbuf_addstr(&msgbuf, ".\n");
560 base_label = msg.parent_label;
562 next_label = msg.label;
565 * Append the commit log message to msgbuf; it starts
566 * after the tree, parent, author, committer
567 * information followed by "\n\n".
569 p = strstr(msg.message, "\n\n");
572 strbuf_addstr(&msgbuf, p);
575 if (opts->record_origin) {
576 if (!has_conforming_footer(&msgbuf, NULL, 0))
577 strbuf_addch(&msgbuf, '\n');
578 strbuf_addstr(&msgbuf, cherry_picked_prefix);
579 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
580 strbuf_addstr(&msgbuf, ")\n");
584 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
585 res = do_recursive_merge(base, next, base_label, next_label,
586 head, &msgbuf, opts);
587 write_message(&msgbuf, git_path_merge_msg());
589 struct commit_list *common = NULL;
590 struct commit_list *remotes = NULL;
592 write_message(&msgbuf, git_path_merge_msg());
594 commit_list_insert(base, &common);
595 commit_list_insert(next, &remotes);
596 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
597 common, sha1_to_hex(head), remotes);
598 free_commit_list(common);
599 free_commit_list(remotes);
603 * If the merge was clean or if it failed due to conflict, we write
604 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
605 * However, if the merge did not even start, then we don't want to
608 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
609 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
610 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
611 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
612 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
613 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
616 error(opts->action == REPLAY_REVERT
617 ? _("could not revert %s... %s")
618 : _("could not apply %s... %s"),
619 find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV),
621 print_advice(res == 1, opts);
622 rerere(opts->allow_rerere_auto);
626 if (opts->skip_empty && is_index_unchanged() == 1) {
628 warning(_("skipping %s... %s"),
629 find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV),
633 allow = allow_empty(opts, commit);
638 if (!opts->no_commit)
639 res = run_git_commit(git_path_merge_msg(), opts, allow);
641 if (!res && opts->action == REPLAY_PICK) {
642 unsigned char to[20];
644 if (read_ref("HEAD", to))
647 add_rewritten(&rewritten, commit->object.oid.hash, to);
650 free_message(commit, &msg);
655 static void prepare_revs(struct replay_opts *opts)
658 * picking (but not reverting) ranges (but not individual revisions)
659 * should be done in reverse
661 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
662 opts->revs->reverse ^= 1;
664 if (prepare_revision_walk(opts->revs))
665 die(_("revision walk setup failed"));
667 if (!opts->revs->commits && !opts->quiet)
668 error(_("empty commit set passed"));
671 static void read_and_refresh_cache(struct replay_opts *opts)
673 static struct lock_file index_lock;
674 int index_fd = hold_locked_index(&index_lock, 0);
675 if (read_index_preload(&the_index, NULL) < 0)
676 die(_("git %s: failed to read the index"), action_name(opts));
677 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
678 if (the_index.cache_changed && index_fd >= 0) {
679 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
680 die(_("git %s: failed to refresh the index"), action_name(opts));
682 rollback_lock_file(&index_lock);
685 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
686 struct replay_opts *opts)
688 struct commit_list *cur = NULL;
689 const char *sha1_abbrev = NULL;
690 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
694 for (cur = todo_list; cur; cur = cur->next) {
695 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
696 sha1_abbrev = find_unique_abbrev(cur->item->object.oid.hash, DEFAULT_ABBREV);
697 subject_len = find_commit_subject(commit_buffer, &subject);
698 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
699 subject_len, subject);
700 unuse_commit_buffer(cur->item, commit_buffer);
705 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
707 unsigned char commit_sha1[20];
708 enum replay_action action;
709 char *end_of_object_name;
710 int saved, status, padding;
712 if (starts_with(bol, "pick")) {
713 action = REPLAY_PICK;
714 bol += strlen("pick");
715 } else if (starts_with(bol, "revert")) {
716 action = REPLAY_REVERT;
717 bol += strlen("revert");
721 /* Eat up extra spaces/ tabs before object name */
722 padding = strspn(bol, " \t");
727 end_of_object_name = bol + strcspn(bol, " \t\n");
728 saved = *end_of_object_name;
729 *end_of_object_name = '\0';
730 status = get_sha1(bol, commit_sha1);
731 *end_of_object_name = saved;
734 * Verify that the action matches up with the one in
735 * opts; we don't support arbitrary instructions
737 if (action != opts->action) {
738 const char *action_str;
739 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
740 error(_("Cannot %s during a %s"), action_str, action_name(opts));
747 return lookup_commit_reference(commit_sha1);
750 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
751 struct replay_opts *opts)
753 struct commit_list **next = todo_list;
754 struct commit *commit;
758 for (i = 1; *p; i++) {
759 char *eol = strchrnul(p, '\n');
760 commit = parse_insn_line(p, eol, opts);
762 return error(_("Could not parse line %d."), i);
763 next = commit_list_append(commit, next);
764 p = *eol ? eol + 1 : eol;
767 return error(_("No commits parsed."));
771 static void read_populate_todo(struct commit_list **todo_list,
772 struct replay_opts *opts)
774 struct strbuf buf = STRBUF_INIT;
777 fd = open(git_path_todo_file(), O_RDONLY);
779 die_errno(_("Could not open %s"), git_path_todo_file());
780 if (strbuf_read(&buf, fd, 0) < 0) {
782 strbuf_release(&buf);
783 die(_("Could not read %s."), git_path_todo_file());
787 res = parse_insn_buffer(buf.buf, todo_list, opts);
788 strbuf_release(&buf);
790 die(_("Unusable instruction sheet: %s"), git_path_todo_file());
793 static int populate_opts_cb(const char *key, const char *value, void *data)
795 struct replay_opts *opts = data;
800 else if (!strcmp(key, "options.no-commit"))
801 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
802 else if (!strcmp(key, "options.edit"))
803 opts->edit = git_config_bool_or_int(key, value, &error_flag);
804 else if (!strcmp(key, "options.signoff"))
805 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
806 else if (!strcmp(key, "options.record-origin"))
807 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
808 else if (!strcmp(key, "options.allow-ff"))
809 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
810 else if (!strcmp(key, "options.mainline"))
811 opts->mainline = git_config_int(key, value);
812 else if (!strcmp(key, "options.strategy"))
813 git_config_string(&opts->strategy, key, value);
814 else if (!strcmp(key, "options.gpg-sign"))
815 git_config_string(&opts->gpg_sign, key, value);
816 else if (!strcmp(key, "options.strategy-option")) {
817 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
818 opts->xopts[opts->xopts_nr++] = xstrdup(value);
819 } else if (!strcmp(key, "options.allow-rerere-auto"))
820 opts->allow_rerere_auto = git_config_int(key, value);
821 else if (!strcmp(key, "options.action-name"))
822 git_config_string(&opts->action_name, key, value);
824 return error(_("Invalid key: %s"), key);
827 return error(_("Invalid value for %s: %s"), key, value);
832 static void read_populate_opts(struct replay_opts **opts_ptr)
834 if (!file_exists(git_path_opts_file()))
836 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), *opts_ptr) < 0)
837 die(_("Malformed options sheet: %s"), git_path_opts_file());
840 static void walk_revs_populate_todo(struct commit_list **todo_list,
841 struct replay_opts *opts)
843 struct commit *commit;
844 struct commit_list **next;
849 while ((commit = get_revision(opts->revs)))
850 next = commit_list_append(commit, next);
853 static int create_seq_dir(void)
855 if (file_exists(git_path_seq_dir())) {
856 error(_("a cherry-pick or revert is already in progress"));
857 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
860 else if (mkdir(git_path_seq_dir(), 0777) < 0)
861 die_errno(_("Could not create sequencer directory %s"),
866 static void save_head(const char *head)
868 static struct lock_file head_lock;
869 struct strbuf buf = STRBUF_INIT;
872 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), LOCK_DIE_ON_ERROR);
873 strbuf_addf(&buf, "%s\n", head);
874 if (write_in_full(fd, buf.buf, buf.len) < 0)
875 die_errno(_("Could not write to %s"), git_path_head_file());
876 if (commit_lock_file(&head_lock) < 0)
877 die(_("Error wrapping up %s."), git_path_head_file());
880 static int reset_for_rollback(const unsigned char *sha1)
882 const char *argv[4]; /* reset --merge <arg> + NULL */
885 argv[2] = sha1_to_hex(sha1);
887 return run_command_v_opt(argv, RUN_GIT_CMD);
890 static int rollback_single_pick(void)
892 unsigned char head_sha1[20];
894 if (!file_exists(git_path_cherry_pick_head()) &&
895 !file_exists(git_path_revert_head()))
896 return error(_("no cherry-pick or revert in progress"));
897 if (read_ref_full("HEAD", 0, head_sha1, NULL))
898 return error(_("cannot resolve HEAD"));
899 if (is_null_sha1(head_sha1))
900 return error(_("cannot abort from a branch yet to be born"));
901 return reset_for_rollback(head_sha1);
904 static int sequencer_rollback(struct replay_opts *opts)
907 unsigned char sha1[20];
908 struct strbuf buf = STRBUF_INIT;
909 struct string_list merge_rr = STRING_LIST_INIT_DUP;
911 if (setup_rerere(&merge_rr, 0) >= 0) {
912 rerere_clear(&merge_rr);
913 string_list_clear(&merge_rr, 1);
916 f = fopen(git_path_head_file(), "r");
917 if (!f && errno == ENOENT) {
919 * There is no multiple-cherry-pick in progress.
920 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
921 * a single-cherry-pick in progress, abort that.
923 return rollback_single_pick();
926 return error(_("cannot open %s: %s"), git_path_head_file(),
928 if (strbuf_getline_lf(&buf, f)) {
929 error(_("cannot read %s: %s"), git_path_head_file(),
930 ferror(f) ? strerror(errno) : _("unexpected end of file"));
935 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
936 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
937 git_path_head_file());
940 if (reset_for_rollback(sha1))
942 remove_sequencer_state();
943 strbuf_release(&buf);
946 strbuf_release(&buf);
950 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
952 static struct lock_file todo_lock;
953 struct strbuf buf = STRBUF_INIT;
956 fd = hold_lock_file_for_update(&todo_lock, git_path_todo_file(), LOCK_DIE_ON_ERROR);
957 if (format_todo(&buf, todo_list, opts) < 0)
958 die(_("Could not format %s."), git_path_todo_file());
959 if (write_in_full(fd, buf.buf, buf.len) < 0) {
960 strbuf_release(&buf);
961 die_errno(_("Could not write to %s"), git_path_todo_file());
963 if (commit_lock_file(&todo_lock) < 0) {
964 strbuf_release(&buf);
965 die(_("Error wrapping up %s."), git_path_todo_file());
967 strbuf_release(&buf);
970 static void save_opts(struct replay_opts *opts)
972 const char *opts_file = git_path_opts_file();
975 git_config_set_in_file(opts_file, "options.no-commit", "true");
977 git_config_set_in_file(opts_file, "options.edit", "true");
979 git_config_set_in_file(opts_file, "options.signoff", "true");
980 if (opts->record_origin)
981 git_config_set_in_file(opts_file, "options.record-origin", "true");
983 git_config_set_in_file(opts_file, "options.allow-ff", "true");
984 if (opts->mainline) {
985 struct strbuf buf = STRBUF_INIT;
986 strbuf_addf(&buf, "%d", opts->mainline);
987 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
988 strbuf_release(&buf);
991 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
993 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
996 for (i = 0; i < opts->xopts_nr; i++)
997 git_config_set_multivar_in_file(opts_file,
998 "options.strategy-option",
999 opts->xopts[i], "^$", 0);
1001 if (opts->allow_rerere_auto) {
1002 struct strbuf buf = STRBUF_INIT;
1003 strbuf_addf(&buf, "%d", opts->allow_rerere_auto);
1004 git_config_set_in_file(opts_file, "options.allow-rerere-auto", buf.buf);
1005 strbuf_release(&buf);
1007 if (opts->action_name)
1008 git_config_set_in_file(opts_file, "options.action-name", opts->action_name);
1011 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1013 struct commit_list *cur;
1016 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1018 assert(!(opts->signoff || opts->no_commit ||
1019 opts->record_origin || opts->edit));
1020 read_and_refresh_cache(opts);
1022 for (cur = todo_list; cur; cur = cur->next) {
1023 save_todo(cur, opts);
1024 res = do_pick_commit(cur->item, opts);
1026 if (opts->action == REPLAY_PICK)
1027 store_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1035 * Sequence of picks finished successfully; cleanup by
1036 * removing the .git/sequencer directory
1038 remove_sequencer_state();
1042 static int continue_single_pick(void)
1044 const char *argv[] = { "commit", NULL };
1046 if (!file_exists(git_path_cherry_pick_head()) &&
1047 !file_exists(git_path_revert_head()))
1048 return error(_("no cherry-pick or revert in progress"));
1049 return run_command_v_opt(argv, RUN_GIT_CMD);
1052 static int sequencer_continue(struct replay_opts *opts, int skip)
1054 struct commit_list *todo_list = NULL;
1056 if (!file_exists(git_path_todo_file()))
1057 return continue_single_pick();
1058 read_populate_opts(&opts);
1059 read_populate_todo(&todo_list, opts);
1060 if (opts->action == REPLAY_PICK)
1061 load_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1063 /* Verify that the conflict has been resolved */
1064 if (file_exists(git_path_cherry_pick_head()) ||
1065 file_exists(git_path_revert_head())) {
1066 int ret = continue_single_pick();
1070 if (index_differs_from("HEAD", 0))
1071 return error_dirty_index(opts);
1072 if (opts->action == REPLAY_PICK && !skip) {
1073 unsigned char to[20];
1074 if (!read_ref("HEAD", to))
1075 add_rewritten(&rewritten, todo_list->item->object.oid.hash, to);
1077 todo_list = todo_list->next;
1078 return pick_commits(todo_list, opts);
1081 static int sequencer_skip(struct replay_opts *opts)
1083 const char *argv[3]; /* reset --hard + NULL */
1084 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1087 if (setup_rerere(&merge_rr, 0) >= 0) {
1088 rerere_clear(&merge_rr);
1089 string_list_clear(&merge_rr, 1);
1095 ret = run_command_v_opt(argv, RUN_GIT_CMD);
1102 return sequencer_continue(opts, 1);
1105 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1108 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1109 ret = do_pick_commit(cmit, opts);
1116 int sequencer_pick_revisions(struct replay_opts *opts)
1118 struct commit_list *todo_list = NULL;
1119 unsigned char sha1[20];
1122 if (opts->subcommand == REPLAY_NONE)
1125 read_and_refresh_cache(opts);
1128 * Decide what to do depending on the arguments; a fresh
1129 * cherry-pick should be handled differently from an existing
1130 * one that is being continued
1132 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1133 remove_sequencer_state();
1136 if (opts->subcommand == REPLAY_ROLLBACK)
1137 return sequencer_rollback(opts);
1138 if (opts->subcommand == REPLAY_CONTINUE)
1139 return sequencer_continue(opts, 0);
1140 if (opts->subcommand == REPLAY_SKIP)
1141 return sequencer_skip(opts);
1143 for (i = 0; i < opts->revs->pending.nr; i++) {
1144 unsigned char sha1[20];
1145 const char *name = opts->revs->pending.objects[i].name;
1147 /* This happens when using --stdin. */
1151 if (!get_sha1(name, sha1)) {
1152 if (!lookup_commit_reference_gently(sha1, 1)) {
1153 enum object_type type = sha1_object_info(sha1, NULL);
1154 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1157 die(_("%s: bad revision"), name);
1161 * If we were called as "git cherry-pick <commit>", just
1162 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1163 * REVERT_HEAD, and don't touch the sequencer state.
1164 * This means it is possible to cherry-pick in the middle
1165 * of a cherry-pick sequence.
1167 if (opts->revs->cmdline.nr == 1 &&
1168 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1169 opts->revs->no_walk &&
1170 !opts->revs->cmdline.rev->flags) {
1171 struct commit *cmit;
1172 if (prepare_revision_walk(opts->revs))
1173 die(_("revision walk setup failed"));
1174 cmit = get_revision(opts->revs);
1175 if (!cmit || get_revision(opts->revs))
1176 die("BUG: expected exactly one commit from walk");
1177 return single_pick(cmit, opts);
1181 * Start a new cherry-pick/ revert sequence; but
1182 * first, make sure that an existing one isn't in
1186 walk_revs_populate_todo(&todo_list, opts);
1187 if (create_seq_dir() < 0)
1189 if (get_sha1("HEAD", sha1)) {
1190 if (opts->action == REPLAY_REVERT)
1191 return error(_("Can't revert as initial commit"));
1192 return error(_("Can't cherry-pick into empty head"));
1194 save_head(sha1_to_hex(sha1));
1196 return pick_commits(todo_list, opts);
1199 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1201 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1202 struct strbuf sob = STRBUF_INIT;
1205 strbuf_addstr(&sob, sign_off_header);
1206 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1207 getenv("GIT_COMMITTER_EMAIL")));
1208 strbuf_addch(&sob, '\n');
1211 * If the whole message buffer is equal to the sob, pretend that we
1212 * found a conforming footer with a matching sob
1214 if (msgbuf->len - ignore_footer == sob.len &&
1215 !strncmp(msgbuf->buf, sob.buf, sob.len))
1218 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1221 const char *append_newlines = NULL;
1222 size_t len = msgbuf->len - ignore_footer;
1226 * The buffer is completely empty. Leave foom for
1227 * the title and body to be filled in by the user.
1229 append_newlines = "\n\n";
1230 } else if (msgbuf->buf[len - 1] != '\n') {
1232 * Incomplete line. Complete the line and add a
1233 * blank one so that there is an empty line between
1234 * the message body and the sob.
1236 append_newlines = "\n\n";
1237 } else if (len == 1) {
1239 * Buffer contains a single newline. Add another
1240 * so that we leave room for the title and body.
1242 append_newlines = "\n";
1243 } else if (msgbuf->buf[len - 2] != '\n') {
1245 * Buffer ends with a single newline. Add another
1246 * so that there is an empty line between the message
1249 append_newlines = "\n";
1250 } /* else, the buffer already ends with two newlines. */
1252 if (append_newlines)
1253 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1254 append_newlines, strlen(append_newlines));
1257 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1258 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1261 strbuf_release(&sob);