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 void finish(struct replay_opts *opts)
29 struct strbuf msg = STRBUF_INIT;
31 if (opts->action != REPLAY_PICK)
34 name = opts->action_name ? opts->action_name : "cherry-pick";
39 strbuf_addf(&msg, "Notes added by 'git %s'", name);
40 copy_rewrite_notes(&rewritten, name, msg.buf);
41 run_rewrite_hook(&rewritten, name);
45 static int is_rfc2822_line(const char *buf, int len)
49 for (i = 0; i < len; i++) {
53 if (!isalnum(ch) && ch != '-')
60 static int is_cherry_picked_from_line(const char *buf, int len)
63 * We only care that it looks roughly like (cherry picked from ...)
65 return len > strlen(cherry_picked_prefix) + 1 &&
66 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
70 * Returns 0 for non-conforming footer
71 * Returns 1 for conforming footer
72 * Returns 2 when sob exists within conforming footer
73 * Returns 3 when sob exists within conforming footer as last entry
75 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
80 int len = sb->len - ignore_footer;
81 const char *buf = sb->buf;
84 /* footer must end with newline */
85 if (!len || buf[len - 1] != '\n')
89 for (i = len - 1; i > 0; i--) {
91 if (prev == '\n' && ch == '\n') /* paragraph break */
96 /* require at least one blank line */
97 if (prev != '\n' || buf[i] != '\n')
100 /* advance to start of last paragraph */
101 while (i < len - 1 && buf[i] == '\n')
104 for (; i < len; i = k) {
107 for (k = i; k < len && buf[k] != '\n'; k++)
111 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
112 if (found_rfc2822 && sob &&
113 !strncmp(buf + i, sob->buf, sob->len))
116 if (!(found_rfc2822 ||
117 is_cherry_picked_from_line(buf + i, k - i - 1)))
127 static void remove_sequencer_state(void)
129 struct strbuf seq_dir = STRBUF_INIT;
131 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
132 remove_dir_recursively(&seq_dir, 0);
133 strbuf_release(&seq_dir);
136 static const char *action_name(const struct replay_opts *opts)
138 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
141 struct commit_message {
148 static int get_message(struct commit *commit, struct commit_message *out)
150 const char *abbrev, *subject;
151 int abbrev_len, subject_len;
154 if (!git_commit_encoding)
155 git_commit_encoding = "UTF-8";
157 out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
158 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
159 abbrev_len = strlen(abbrev);
161 subject_len = find_commit_subject(out->message, &subject);
163 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
164 strlen("... ") + subject_len + 1);
165 q = out->parent_label;
166 q = mempcpy(q, "parent of ", strlen("parent of "));
168 q = mempcpy(q, abbrev, abbrev_len);
169 q = mempcpy(q, "... ", strlen("... "));
171 q = mempcpy(q, subject, subject_len);
176 static void free_message(struct commit *commit, struct commit_message *msg)
178 free(msg->parent_label);
179 unuse_commit_buffer(commit, msg->message);
182 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
184 const char *filename;
186 struct strbuf buf = STRBUF_INIT;
188 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
190 filename = git_path("%s", pseudoref);
191 fd = open(filename, O_WRONLY | O_CREAT, 0666);
193 die_errno(_("Could not open '%s' for writing"), filename);
194 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
195 die_errno(_("Could not write to '%s'"), filename);
196 strbuf_release(&buf);
199 static void print_advice(int show_hint, struct replay_opts *opts)
201 char *msg = getenv("GIT_CHERRY_PICK_HELP");
204 fprintf(stderr, "%s\n", msg);
206 * A conflict has occurred but the porcelain
207 * (typically rebase --interactive) wants to take care
208 * of the commit itself so remove CHERRY_PICK_HEAD
210 unlink(git_path("CHERRY_PICK_HEAD"));
216 advise(_("after resolving the conflicts, mark the corrected paths\n"
217 "with 'git add <paths>' or 'git rm <paths>'"));
219 advise(_("after resolving the conflicts, mark the corrected paths\n"
220 "with 'git add <paths>' or 'git rm <paths>'\n"
221 "and commit the result with 'git commit'"));
225 static void write_message(struct strbuf *msgbuf, const char *filename)
227 static struct lock_file msg_file;
229 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
231 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
232 die_errno(_("Could not write to %s"), filename);
233 strbuf_release(msgbuf);
234 if (commit_lock_file(&msg_file) < 0)
235 die(_("Error wrapping up %s"), filename);
238 static struct tree *empty_tree(void)
240 return lookup_tree(EMPTY_TREE_SHA1_BIN);
243 static int error_dirty_index(struct replay_opts *opts)
245 if (read_cache_unmerged())
246 return error_resolve_conflict(action_name(opts));
248 /* Different translation strings for cherry-pick and revert */
249 if (opts->action == REPLAY_PICK)
250 error(_("Your local changes would be overwritten by cherry-pick."));
252 error(_("Your local changes would be overwritten by revert."));
254 if (advice_commit_before_merge)
255 advise(_("Commit your changes or stash them to proceed."));
259 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
260 int unborn, struct replay_opts *opts)
262 struct ref_transaction *transaction;
263 struct strbuf sb = STRBUF_INIT;
264 struct strbuf err = STRBUF_INIT;
267 if (checkout_fast_forward(from, to, 1))
268 exit(128); /* the callee should have complained already */
270 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
272 transaction = ref_transaction_begin(&err);
274 ref_transaction_update(transaction, "HEAD",
275 to, unborn ? null_sha1 : from,
276 0, 1, sb.buf, &err) ||
277 ref_transaction_commit(transaction, &err)) {
278 ref_transaction_free(transaction);
279 error("%s", err.buf);
281 strbuf_release(&err);
286 strbuf_release(&err);
287 ref_transaction_free(transaction);
291 void append_conflicts_hint(struct strbuf *msgbuf)
295 strbuf_addch(msgbuf, '\n');
296 strbuf_commented_addf(msgbuf, "Conflicts:\n");
297 for (i = 0; i < active_nr;) {
298 const struct cache_entry *ce = active_cache[i++];
300 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
301 while (i < active_nr && !strcmp(ce->name,
302 active_cache[i]->name))
308 static int do_recursive_merge(struct commit *base, struct commit *next,
309 const char *base_label, const char *next_label,
310 unsigned char *head, struct strbuf *msgbuf,
311 struct replay_opts *opts)
313 struct merge_options o;
314 struct tree *result, *next_tree, *base_tree, *head_tree;
317 static struct lock_file index_lock;
319 hold_locked_index(&index_lock, 1);
323 init_merge_options(&o);
324 o.ancestor = base ? base_label : "(empty tree)";
326 o.branch2 = next ? next_label : "(empty tree)";
328 head_tree = parse_tree_indirect(head);
329 next_tree = next ? next->tree : empty_tree();
330 base_tree = base ? base->tree : empty_tree();
332 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
333 parse_merge_opt(&o, *xopt);
335 clean = merge_trees(&o,
337 next_tree, base_tree, &result);
339 if (active_cache_changed &&
340 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
341 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
342 die(_("%s: Unable to write new index file"), action_name(opts));
343 rollback_lock_file(&index_lock);
346 append_signoff(msgbuf, 0, 0);
349 append_conflicts_hint(msgbuf);
354 static int is_index_unchanged(void)
356 unsigned char head_sha1[20];
357 struct commit *head_commit;
359 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
360 return error(_("Could not resolve HEAD commit\n"));
362 head_commit = lookup_commit(head_sha1);
365 * If head_commit is NULL, check_commit, called from
366 * lookup_commit, would have indicated that head_commit is not
367 * a commit object already. parse_commit() will return failure
368 * without further complaints in such a case. Otherwise, if
369 * the commit is invalid, parse_commit() will complain. So
370 * there is nothing for us to say here. Just return failure.
372 if (parse_commit(head_commit))
375 if (!active_cache_tree)
376 active_cache_tree = cache_tree();
378 if (!cache_tree_fully_valid(active_cache_tree))
379 if (cache_tree_update(&the_index, 0))
380 return error(_("Unable to update cache tree\n"));
382 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
386 * If we are cherry-pick, and if the merge did not result in
387 * hand-editing, we will hit this commit and inherit the original
388 * author date and name.
389 * If we are revert, or if our cherry-pick results in a hand merge,
390 * we had better say that the current user is responsible for that.
392 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
395 struct argv_array array;
398 argv_array_init(&array);
399 argv_array_push(&array, "commit");
400 argv_array_push(&array, "-n");
402 argv_array_push(&array, "-q");
405 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
407 argv_array_push(&array, "-s");
409 argv_array_push(&array, "-F");
410 argv_array_push(&array, defmsg);
414 argv_array_push(&array, "--allow-empty");
416 if (opts->allow_empty_message)
417 argv_array_push(&array, "--allow-empty-message");
419 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
420 argv_array_clear(&array);
424 static int is_original_commit_empty(struct commit *commit)
426 const unsigned char *ptree_sha1;
428 if (parse_commit(commit))
429 return error(_("Could not parse commit %s\n"),
430 sha1_to_hex(commit->object.sha1));
431 if (commit->parents) {
432 struct commit *parent = commit->parents->item;
433 if (parse_commit(parent))
434 return error(_("Could not parse parent commit %s\n"),
435 sha1_to_hex(parent->object.sha1));
436 ptree_sha1 = parent->tree->object.sha1;
438 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
441 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
445 * Do we run "git commit" with "--allow-empty"?
447 static int allow_empty(struct replay_opts *opts, struct commit *commit)
449 int index_unchanged, empty_commit;
454 * (1) we do not allow empty at all and error out.
456 * (2) we allow ones that were initially empty, but
457 * forbid the ones that become empty;
461 if (!opts->allow_empty)
462 return 0; /* let "git commit" barf as necessary */
464 index_unchanged = is_index_unchanged();
465 if (index_unchanged < 0)
466 return index_unchanged;
467 if (!index_unchanged)
468 return 0; /* we do not have to say --allow-empty */
470 if (opts->keep_redundant_commits)
473 empty_commit = is_original_commit_empty(commit);
474 if (empty_commit < 0)
482 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
484 unsigned char head[20];
485 struct commit *base, *next, *parent;
486 const char *base_label, *next_label;
487 struct commit_message msg = { NULL, NULL, NULL, NULL };
489 struct strbuf msgbuf = STRBUF_INIT;
490 int res, unborn = 0, allow;
492 if (opts->no_commit) {
494 * We do not intend to commit immediately. We just want to
495 * merge the differences in, so let's compute the tree
496 * that represents the "current" state for merge-recursive
499 if (write_cache_as_tree(head, 0, NULL))
500 die (_("Your index file is unmerged."));
502 unborn = get_sha1("HEAD", head);
504 hashcpy(head, EMPTY_TREE_SHA1_BIN);
505 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
506 return error_dirty_index(opts);
510 if (!commit->parents) {
513 else if (commit->parents->next) {
514 /* Reverting or cherry-picking a merge commit */
516 struct commit_list *p;
519 return error(_("Commit %s is a merge but no -m option was given."),
520 sha1_to_hex(commit->object.sha1));
522 for (cnt = 1, p = commit->parents;
523 cnt != opts->mainline && p;
526 if (cnt != opts->mainline || !p)
527 return error(_("Commit %s does not have parent %d"),
528 sha1_to_hex(commit->object.sha1), opts->mainline);
530 } else if (0 < opts->mainline)
531 return error(_("Mainline was specified but commit %s is not a merge."),
532 sha1_to_hex(commit->object.sha1));
534 parent = commit->parents->item;
536 if (opts->allow_ff &&
537 ((parent && !hashcmp(parent->object.sha1, head)) ||
538 (!parent && unborn)))
539 return fast_forward_to(commit->object.sha1, head, unborn, opts);
541 if (parent && parse_commit(parent) < 0)
542 /* TRANSLATORS: The first %s will be "revert" or
543 "cherry-pick", the second %s a SHA1 */
544 return error(_("%s: cannot parse parent commit %s"),
545 action_name(opts), sha1_to_hex(parent->object.sha1));
547 if (get_message(commit, &msg) != 0)
548 return error(_("Cannot get commit message for %s"),
549 sha1_to_hex(commit->object.sha1));
552 * "commit" is an existing commit. We would want to apply
553 * the difference it introduces since its first parent "prev"
554 * on top of the current HEAD if we are cherry-pick. Or the
555 * reverse of it if we are revert.
558 defmsg = git_pathdup("MERGE_MSG");
560 if (opts->action == REPLAY_REVERT) {
562 base_label = msg.label;
564 next_label = msg.parent_label;
565 strbuf_addstr(&msgbuf, "Revert \"");
566 strbuf_addstr(&msgbuf, msg.subject);
567 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
568 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
570 if (commit->parents && commit->parents->next) {
571 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
572 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
574 strbuf_addstr(&msgbuf, ".\n");
579 base_label = msg.parent_label;
581 next_label = msg.label;
584 * Append the commit log message to msgbuf; it starts
585 * after the tree, parent, author, committer
586 * information followed by "\n\n".
588 p = strstr(msg.message, "\n\n");
591 strbuf_addstr(&msgbuf, p);
594 if (opts->record_origin) {
595 if (!has_conforming_footer(&msgbuf, NULL, 0))
596 strbuf_addch(&msgbuf, '\n');
597 strbuf_addstr(&msgbuf, cherry_picked_prefix);
598 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
599 strbuf_addstr(&msgbuf, ")\n");
603 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
604 res = do_recursive_merge(base, next, base_label, next_label,
605 head, &msgbuf, opts);
606 write_message(&msgbuf, defmsg);
608 struct commit_list *common = NULL;
609 struct commit_list *remotes = NULL;
611 write_message(&msgbuf, defmsg);
613 commit_list_insert(base, &common);
614 commit_list_insert(next, &remotes);
615 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
616 common, sha1_to_hex(head), remotes);
617 free_commit_list(common);
618 free_commit_list(remotes);
622 * If the merge was clean or if it failed due to conflict, we write
623 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
624 * However, if the merge did not even start, then we don't want to
627 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
628 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
629 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
630 write_cherry_pick_head(commit, "REVERT_HEAD");
633 error(opts->action == REPLAY_REVERT
634 ? _("could not revert %s... %s")
635 : _("could not apply %s... %s"),
636 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
638 print_advice(res == 1, opts);
639 rerere(opts->allow_rerere_auto);
643 if (opts->skip_empty && is_index_unchanged() == 1) {
645 warning(_("skipping %s... %s"),
646 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
650 allow = allow_empty(opts, commit);
655 if (!opts->no_commit)
656 res = run_git_commit(defmsg, opts, allow);
658 if (!res && opts->action == REPLAY_PICK) {
659 unsigned char to[20];
661 if (read_ref("HEAD", to))
664 add_rewritten(&rewritten, commit->object.sha1, to);
667 free_message(commit, &msg);
673 static void prepare_revs(struct replay_opts *opts)
676 * picking (but not reverting) ranges (but not individual revisions)
677 * should be done in reverse
679 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
680 opts->revs->reverse ^= 1;
682 if (prepare_revision_walk(opts->revs))
683 die(_("revision walk setup failed"));
685 if (!opts->revs->commits && !opts->quiet)
686 error(_("empty commit set passed"));
689 static void read_and_refresh_cache(struct replay_opts *opts)
691 static struct lock_file index_lock;
692 int index_fd = hold_locked_index(&index_lock, 0);
693 if (read_index_preload(&the_index, NULL) < 0)
694 die(_("git %s: failed to read the index"), action_name(opts));
695 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
696 if (the_index.cache_changed && index_fd >= 0) {
697 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
698 die(_("git %s: failed to refresh the index"), action_name(opts));
700 rollback_lock_file(&index_lock);
703 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
704 struct replay_opts *opts)
706 struct commit_list *cur = NULL;
707 const char *sha1_abbrev = NULL;
708 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
712 for (cur = todo_list; cur; cur = cur->next) {
713 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
714 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
715 subject_len = find_commit_subject(commit_buffer, &subject);
716 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
717 subject_len, subject);
718 unuse_commit_buffer(cur->item, commit_buffer);
723 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
725 unsigned char commit_sha1[20];
726 enum replay_action action;
727 char *end_of_object_name;
728 int saved, status, padding;
730 if (starts_with(bol, "pick")) {
731 action = REPLAY_PICK;
732 bol += strlen("pick");
733 } else if (starts_with(bol, "revert")) {
734 action = REPLAY_REVERT;
735 bol += strlen("revert");
739 /* Eat up extra spaces/ tabs before object name */
740 padding = strspn(bol, " \t");
745 end_of_object_name = bol + strcspn(bol, " \t\n");
746 saved = *end_of_object_name;
747 *end_of_object_name = '\0';
748 status = get_sha1(bol, commit_sha1);
749 *end_of_object_name = saved;
752 * Verify that the action matches up with the one in
753 * opts; we don't support arbitrary instructions
755 if (action != opts->action) {
756 const char *action_str;
757 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
758 error(_("Cannot %s during a %s"), action_str, action_name(opts));
765 return lookup_commit_reference(commit_sha1);
768 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
769 struct replay_opts *opts)
771 struct commit_list **next = todo_list;
772 struct commit *commit;
776 for (i = 1; *p; i++) {
777 char *eol = strchrnul(p, '\n');
778 commit = parse_insn_line(p, eol, opts);
780 return error(_("Could not parse line %d."), i);
781 next = commit_list_append(commit, next);
782 p = *eol ? eol + 1 : eol;
785 return error(_("No commits parsed."));
789 static void read_populate_todo(struct commit_list **todo_list,
790 struct replay_opts *opts)
792 const char *todo_file = git_path(SEQ_TODO_FILE);
793 struct strbuf buf = STRBUF_INIT;
796 fd = open(todo_file, O_RDONLY);
798 die_errno(_("Could not open %s"), todo_file);
799 if (strbuf_read(&buf, fd, 0) < 0) {
801 strbuf_release(&buf);
802 die(_("Could not read %s."), todo_file);
806 res = parse_insn_buffer(buf.buf, todo_list, opts);
807 strbuf_release(&buf);
809 die(_("Unusable instruction sheet: %s"), todo_file);
812 static int populate_opts_cb(const char *key, const char *value, void *data)
814 struct replay_opts *opts = data;
819 else if (!strcmp(key, "options.no-commit"))
820 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
821 else if (!strcmp(key, "options.edit"))
822 opts->edit = git_config_bool_or_int(key, value, &error_flag);
823 else if (!strcmp(key, "options.signoff"))
824 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
825 else if (!strcmp(key, "options.record-origin"))
826 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
827 else if (!strcmp(key, "options.allow-ff"))
828 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
829 else if (!strcmp(key, "options.mainline"))
830 opts->mainline = git_config_int(key, value);
831 else if (!strcmp(key, "options.strategy"))
832 git_config_string(&opts->strategy, key, value);
833 else if (!strcmp(key, "options.gpg-sign"))
834 git_config_string(&opts->gpg_sign, key, value);
835 else if (!strcmp(key, "options.strategy-option")) {
836 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
837 opts->xopts[opts->xopts_nr++] = xstrdup(value);
838 } else if (!strcmp(key, "options.allow-rerere-auto"))
839 opts->allow_rerere_auto = git_config_int(key, value);
840 else if (!strcmp(key, "options.action-name"))
841 git_config_string(&opts->action_name, key, value);
843 return error(_("Invalid key: %s"), key);
846 return error(_("Invalid value for %s: %s"), key, value);
851 static void read_populate_opts(struct replay_opts **opts_ptr)
853 const char *opts_file = git_path(SEQ_OPTS_FILE);
855 if (!file_exists(opts_file))
857 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
858 die(_("Malformed options sheet: %s"), opts_file);
861 static void walk_revs_populate_todo(struct commit_list **todo_list,
862 struct replay_opts *opts)
864 struct commit *commit;
865 struct commit_list **next;
870 while ((commit = get_revision(opts->revs)))
871 next = commit_list_append(commit, next);
874 static int create_seq_dir(void)
876 const char *seq_dir = git_path(SEQ_DIR);
878 if (file_exists(seq_dir)) {
879 error(_("a cherry-pick or revert is already in progress"));
880 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
883 else if (mkdir(seq_dir, 0777) < 0)
884 die_errno(_("Could not create sequencer directory %s"), seq_dir);
888 static void save_head(const char *head)
890 const char *head_file = git_path(SEQ_HEAD_FILE);
891 static struct lock_file head_lock;
892 struct strbuf buf = STRBUF_INIT;
895 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
896 strbuf_addf(&buf, "%s\n", head);
897 if (write_in_full(fd, buf.buf, buf.len) < 0)
898 die_errno(_("Could not write to %s"), head_file);
899 if (commit_lock_file(&head_lock) < 0)
900 die(_("Error wrapping up %s."), head_file);
903 static int reset_for_rollback(const unsigned char *sha1)
905 const char *argv[4]; /* reset --merge <arg> + NULL */
908 argv[2] = sha1_to_hex(sha1);
910 return run_command_v_opt(argv, RUN_GIT_CMD);
913 static int rollback_single_pick(void)
915 unsigned char head_sha1[20];
917 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
918 !file_exists(git_path("REVERT_HEAD")))
919 return error(_("no cherry-pick or revert in progress"));
920 if (read_ref_full("HEAD", 0, head_sha1, NULL))
921 return error(_("cannot resolve HEAD"));
922 if (is_null_sha1(head_sha1))
923 return error(_("cannot abort from a branch yet to be born"));
924 return reset_for_rollback(head_sha1);
927 static int sequencer_rollback(struct replay_opts *opts)
929 const char *filename;
931 unsigned char sha1[20];
932 struct strbuf buf = STRBUF_INIT;
933 struct string_list merge_rr = STRING_LIST_INIT_DUP;
935 if (setup_rerere(&merge_rr, 0) >= 0) {
936 rerere_clear(&merge_rr);
937 string_list_clear(&merge_rr, 1);
940 filename = git_path(SEQ_HEAD_FILE);
941 f = fopen(filename, "r");
942 if (!f && errno == ENOENT) {
944 * There is no multiple-cherry-pick in progress.
945 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
946 * a single-cherry-pick in progress, abort that.
948 return rollback_single_pick();
951 return error(_("cannot open %s: %s"), filename,
953 if (strbuf_getline(&buf, f, '\n')) {
954 error(_("cannot read %s: %s"), filename, ferror(f) ?
955 strerror(errno) : _("unexpected end of file"));
960 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
961 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
965 if (reset_for_rollback(sha1))
967 remove_sequencer_state();
968 strbuf_release(&buf);
971 strbuf_release(&buf);
975 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
977 const char *todo_file = git_path(SEQ_TODO_FILE);
978 static struct lock_file todo_lock;
979 struct strbuf buf = STRBUF_INIT;
982 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
983 if (format_todo(&buf, todo_list, opts) < 0)
984 die(_("Could not format %s."), todo_file);
985 if (write_in_full(fd, buf.buf, buf.len) < 0) {
986 strbuf_release(&buf);
987 die_errno(_("Could not write to %s"), todo_file);
989 if (commit_lock_file(&todo_lock) < 0) {
990 strbuf_release(&buf);
991 die(_("Error wrapping up %s."), todo_file);
993 strbuf_release(&buf);
996 static void save_opts(struct replay_opts *opts)
998 const char *opts_file = git_path(SEQ_OPTS_FILE);
1000 if (opts->no_commit)
1001 git_config_set_in_file(opts_file, "options.no-commit", "true");
1003 git_config_set_in_file(opts_file, "options.edit", "true");
1005 git_config_set_in_file(opts_file, "options.signoff", "true");
1006 if (opts->record_origin)
1007 git_config_set_in_file(opts_file, "options.record-origin", "true");
1009 git_config_set_in_file(opts_file, "options.allow-ff", "true");
1010 if (opts->mainline) {
1011 struct strbuf buf = STRBUF_INIT;
1012 strbuf_addf(&buf, "%d", opts->mainline);
1013 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
1014 strbuf_release(&buf);
1017 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
1019 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
1022 for (i = 0; i < opts->xopts_nr; i++)
1023 git_config_set_multivar_in_file(opts_file,
1024 "options.strategy-option",
1025 opts->xopts[i], "^$", 0);
1027 if (opts->allow_rerere_auto) {
1028 struct strbuf buf = STRBUF_INIT;
1029 strbuf_addf(&buf, "%d", opts->allow_rerere_auto);
1030 git_config_set_in_file(opts_file, "options.allow-rerere-auto", buf.buf);
1031 strbuf_release(&buf);
1033 if (opts->action_name)
1034 git_config_set_in_file(opts_file, "options.action-name", opts->action_name);
1037 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1039 struct commit_list *cur;
1042 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1044 assert(!(opts->signoff || opts->no_commit ||
1045 opts->record_origin || opts->edit));
1046 read_and_refresh_cache(opts);
1048 for (cur = todo_list; cur; cur = cur->next) {
1049 save_todo(cur, opts);
1050 res = do_pick_commit(cur->item, opts);
1052 if (opts->action == REPLAY_PICK)
1053 store_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1061 * Sequence of picks finished successfully; cleanup by
1062 * removing the .git/sequencer directory
1064 remove_sequencer_state();
1068 static int continue_single_pick(void)
1070 const char *argv[] = { "commit", NULL };
1072 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1073 !file_exists(git_path("REVERT_HEAD")))
1074 return error(_("no cherry-pick or revert in progress"));
1075 return run_command_v_opt(argv, RUN_GIT_CMD);
1078 static int sequencer_continue(struct replay_opts *opts, int skip)
1080 struct commit_list *todo_list = NULL;
1082 if (!file_exists(git_path(SEQ_TODO_FILE)))
1083 return continue_single_pick();
1084 read_populate_opts(&opts);
1085 read_populate_todo(&todo_list, opts);
1086 if (opts->action == REPLAY_PICK)
1087 load_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1089 /* Verify that the conflict has been resolved */
1090 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1091 file_exists(git_path("REVERT_HEAD"))) {
1092 int ret = continue_single_pick();
1096 if (index_differs_from("HEAD", 0))
1097 return error_dirty_index(opts);
1098 if (opts->action == REPLAY_PICK && !skip) {
1099 unsigned char to[20];
1100 if (!read_ref("HEAD", to))
1101 add_rewritten(&rewritten, todo_list->item->object.sha1, to);
1103 todo_list = todo_list->next;
1104 return pick_commits(todo_list, opts);
1107 static int sequencer_skip(struct replay_opts *opts)
1109 const char *argv[3]; /* reset --hard + NULL */
1110 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1113 if (setup_rerere(&merge_rr, 0) >= 0) {
1114 rerere_clear(&merge_rr);
1115 string_list_clear(&merge_rr, 1);
1121 ret = run_command_v_opt(argv, RUN_GIT_CMD);
1128 return sequencer_continue(opts, 1);
1131 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1134 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1135 ret = do_pick_commit(cmit, opts);
1142 int sequencer_pick_revisions(struct replay_opts *opts)
1144 struct commit_list *todo_list = NULL;
1145 unsigned char sha1[20];
1148 if (opts->subcommand == REPLAY_NONE)
1151 read_and_refresh_cache(opts);
1154 * Decide what to do depending on the arguments; a fresh
1155 * cherry-pick should be handled differently from an existing
1156 * one that is being continued
1158 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1159 remove_sequencer_state();
1162 if (opts->subcommand == REPLAY_ROLLBACK)
1163 return sequencer_rollback(opts);
1164 if (opts->subcommand == REPLAY_CONTINUE)
1165 return sequencer_continue(opts, 0);
1166 if (opts->subcommand == REPLAY_SKIP)
1167 return sequencer_skip(opts);
1169 for (i = 0; i < opts->revs->pending.nr; i++) {
1170 unsigned char sha1[20];
1171 const char *name = opts->revs->pending.objects[i].name;
1173 /* This happens when using --stdin. */
1177 if (!get_sha1(name, sha1)) {
1178 if (!lookup_commit_reference_gently(sha1, 1)) {
1179 enum object_type type = sha1_object_info(sha1, NULL);
1180 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1183 die(_("%s: bad revision"), name);
1187 * If we were called as "git cherry-pick <commit>", just
1188 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1189 * REVERT_HEAD, and don't touch the sequencer state.
1190 * This means it is possible to cherry-pick in the middle
1191 * of a cherry-pick sequence.
1193 if (opts->revs->cmdline.nr == 1 &&
1194 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1195 opts->revs->no_walk &&
1196 !opts->revs->cmdline.rev->flags) {
1197 struct commit *cmit;
1198 if (prepare_revision_walk(opts->revs))
1199 die(_("revision walk setup failed"));
1200 cmit = get_revision(opts->revs);
1201 if (!cmit || get_revision(opts->revs))
1202 die("BUG: expected exactly one commit from walk");
1203 return single_pick(cmit, opts);
1207 * Start a new cherry-pick/ revert sequence; but
1208 * first, make sure that an existing one isn't in
1212 walk_revs_populate_todo(&todo_list, opts);
1213 if (create_seq_dir() < 0)
1215 if (get_sha1("HEAD", sha1)) {
1216 if (opts->action == REPLAY_REVERT)
1217 return error(_("Can't revert as initial commit"));
1218 return error(_("Can't cherry-pick into empty head"));
1220 save_head(sha1_to_hex(sha1));
1222 return pick_commits(todo_list, opts);
1225 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1227 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1228 struct strbuf sob = STRBUF_INIT;
1231 strbuf_addstr(&sob, sign_off_header);
1232 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1233 getenv("GIT_COMMITTER_EMAIL")));
1234 strbuf_addch(&sob, '\n');
1237 * If the whole message buffer is equal to the sob, pretend that we
1238 * found a conforming footer with a matching sob
1240 if (msgbuf->len - ignore_footer == sob.len &&
1241 !strncmp(msgbuf->buf, sob.buf, sob.len))
1244 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1247 const char *append_newlines = NULL;
1248 size_t len = msgbuf->len - ignore_footer;
1252 * The buffer is completely empty. Leave foom for
1253 * the title and body to be filled in by the user.
1255 append_newlines = "\n\n";
1256 } else if (msgbuf->buf[len - 1] != '\n') {
1258 * Incomplete line. Complete the line and add a
1259 * blank one so that there is an empty line between
1260 * the message body and the sob.
1262 append_newlines = "\n\n";
1263 } else if (len == 1) {
1265 * Buffer contains a single newline. Add another
1266 * so that we leave room for the title and body.
1268 append_newlines = "\n";
1269 } else if (msgbuf->buf[len - 2] != '\n') {
1271 * Buffer ends with a single newline. Add another
1272 * so that there is an empty line between the message
1275 append_newlines = "\n";
1276 } /* else, the buffer already ends with two newlines. */
1278 if (append_newlines)
1279 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1280 append_newlines, strlen(append_newlines));
1283 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1284 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1287 strbuf_release(&sob);