7 #include "run-command.h"
10 #include "cache-tree.h"
14 #include "merge-recursive.h"
16 #include "argv-array.h"
19 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
21 const char sign_off_header[] = "Signed-off-by: ";
22 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
23 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 static char *get_encoding(const char *message);
143 struct commit_message {
147 char *reencoded_message;
151 static int get_message(struct commit *commit, struct commit_message *out)
153 const char *encoding;
154 const char *abbrev, *subject;
155 int abbrev_len, subject_len;
160 encoding = get_encoding(commit->buffer);
163 if (!git_commit_encoding)
164 git_commit_encoding = "UTF-8";
166 out->reencoded_message = NULL;
167 out->message = commit->buffer;
168 if (same_encoding(encoding, git_commit_encoding))
169 out->reencoded_message = reencode_string(commit->buffer,
170 git_commit_encoding, encoding);
171 if (out->reencoded_message)
172 out->message = out->reencoded_message;
174 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
175 abbrev_len = strlen(abbrev);
177 subject_len = find_commit_subject(out->message, &subject);
179 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
180 strlen("... ") + subject_len + 1);
181 q = out->parent_label;
182 q = mempcpy(q, "parent of ", strlen("parent of "));
184 q = mempcpy(q, abbrev, abbrev_len);
185 q = mempcpy(q, "... ", strlen("... "));
187 q = mempcpy(q, subject, subject_len);
192 static void free_message(struct commit_message *msg)
194 free(msg->parent_label);
195 free(msg->reencoded_message);
198 static char *get_encoding(const char *message)
200 const char *p = message, *eol;
202 while (*p && *p != '\n') {
203 for (eol = p + 1; *eol && *eol != '\n'; eol++)
205 if (starts_with(p, "encoding ")) {
206 char *result = xmalloc(eol - 8 - p);
207 strlcpy(result, p + 9, eol - 8 - p);
217 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
219 const char *filename;
221 struct strbuf buf = STRBUF_INIT;
223 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
225 filename = git_path("%s", pseudoref);
226 fd = open(filename, O_WRONLY | O_CREAT, 0666);
228 die_errno(_("Could not open '%s' for writing"), filename);
229 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
230 die_errno(_("Could not write to '%s'"), filename);
231 strbuf_release(&buf);
234 static void print_advice(int show_hint, struct replay_opts *opts)
236 char *msg = getenv("GIT_CHERRY_PICK_HELP");
239 fprintf(stderr, "%s\n", msg);
241 * A conflict has occurred but the porcelain
242 * (typically rebase --interactive) wants to take care
243 * of the commit itself so remove CHERRY_PICK_HEAD
245 unlink(git_path("CHERRY_PICK_HEAD"));
251 advise(_("after resolving the conflicts, mark the corrected paths\n"
252 "with 'git add <paths>' or 'git rm <paths>'"));
254 advise(_("after resolving the conflicts, mark the corrected paths\n"
255 "with 'git add <paths>' or 'git rm <paths>'\n"
256 "and commit the result with 'git commit'"));
260 static void write_message(struct strbuf *msgbuf, const char *filename)
262 static struct lock_file msg_file;
264 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
266 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
267 die_errno(_("Could not write to %s"), filename);
268 strbuf_release(msgbuf);
269 if (commit_lock_file(&msg_file) < 0)
270 die(_("Error wrapping up %s"), filename);
273 static struct tree *empty_tree(void)
275 return lookup_tree(EMPTY_TREE_SHA1_BIN);
278 static int error_dirty_index(struct replay_opts *opts)
280 if (read_cache_unmerged())
281 return error_resolve_conflict(action_name(opts));
283 /* Different translation strings for cherry-pick and revert */
284 if (opts->action == REPLAY_PICK)
285 error(_("Your local changes would be overwritten by cherry-pick."));
287 error(_("Your local changes would be overwritten by revert."));
289 if (advice_commit_before_merge)
290 advise(_("Commit your changes or stash them to proceed."));
294 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
295 int unborn, struct replay_opts *opts)
297 struct ref_lock *ref_lock;
298 struct strbuf sb = STRBUF_INIT;
302 if (checkout_fast_forward(from, to, 1))
303 exit(1); /* the callee should have complained already */
304 ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
306 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
307 ret = write_ref_sha1(ref_lock, to, sb.buf);
312 static int do_recursive_merge(struct commit *base, struct commit *next,
313 const char *base_label, const char *next_label,
314 unsigned char *head, struct strbuf *msgbuf,
315 struct replay_opts *opts)
317 struct merge_options o;
318 struct tree *result, *next_tree, *base_tree, *head_tree;
321 static struct lock_file index_lock;
323 index_fd = hold_locked_index(&index_lock, 1);
327 init_merge_options(&o);
328 o.ancestor = base ? base_label : "(empty tree)";
330 o.branch2 = next ? next_label : "(empty tree)";
332 head_tree = parse_tree_indirect(head);
333 next_tree = next ? next->tree : empty_tree();
334 base_tree = base ? base->tree : empty_tree();
336 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
337 parse_merge_opt(&o, *xopt);
339 clean = merge_trees(&o,
341 next_tree, base_tree, &result);
343 if (active_cache_changed &&
344 (write_cache(index_fd, active_cache, active_nr) ||
345 commit_locked_index(&index_lock)))
346 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
347 die(_("%s: Unable to write new index file"), action_name(opts));
348 rollback_lock_file(&index_lock);
351 append_signoff(msgbuf, 0, 0);
355 strbuf_addstr(msgbuf, "\nConflicts:\n");
356 for (i = 0; i < active_nr;) {
357 const struct cache_entry *ce = active_cache[i++];
359 strbuf_addch(msgbuf, '\t');
360 strbuf_addstr(msgbuf, ce->name);
361 strbuf_addch(msgbuf, '\n');
362 while (i < active_nr && !strcmp(ce->name,
363 active_cache[i]->name))
372 static int is_index_unchanged(void)
374 unsigned char head_sha1[20];
375 struct commit *head_commit;
377 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
378 return error(_("Could not resolve HEAD commit\n"));
380 head_commit = lookup_commit(head_sha1);
383 * If head_commit is NULL, check_commit, called from
384 * lookup_commit, would have indicated that head_commit is not
385 * a commit object already. parse_commit() will return failure
386 * without further complaints in such a case. Otherwise, if
387 * the commit is invalid, parse_commit() will complain. So
388 * there is nothing for us to say here. Just return failure.
390 if (parse_commit(head_commit))
393 if (!active_cache_tree)
394 active_cache_tree = cache_tree();
396 if (!cache_tree_fully_valid(active_cache_tree))
397 if (cache_tree_update(active_cache_tree,
398 (const struct cache_entry * const *)active_cache,
400 return error(_("Unable to update cache tree\n"));
402 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
406 * If we are cherry-pick, and if the merge did not result in
407 * hand-editing, we will hit this commit and inherit the original
408 * author date and name.
409 * If we are revert, or if our cherry-pick results in a hand merge,
410 * we had better say that the current user is responsible for that.
412 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
415 struct argv_array array;
418 argv_array_init(&array);
419 argv_array_push(&array, "commit");
420 argv_array_push(&array, "-n");
422 argv_array_push(&array, "-q");
425 argv_array_push(&array, "-s");
427 argv_array_push(&array, "-F");
428 argv_array_push(&array, defmsg);
432 argv_array_push(&array, "--allow-empty");
434 if (opts->allow_empty_message)
435 argv_array_push(&array, "--allow-empty-message");
437 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
438 argv_array_clear(&array);
442 static int is_original_commit_empty(struct commit *commit)
444 const unsigned char *ptree_sha1;
446 if (parse_commit(commit))
447 return error(_("Could not parse commit %s\n"),
448 sha1_to_hex(commit->object.sha1));
449 if (commit->parents) {
450 struct commit *parent = commit->parents->item;
451 if (parse_commit(parent))
452 return error(_("Could not parse parent commit %s\n"),
453 sha1_to_hex(parent->object.sha1));
454 ptree_sha1 = parent->tree->object.sha1;
456 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
459 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
463 * Do we run "git commit" with "--allow-empty"?
465 static int allow_empty(struct replay_opts *opts, struct commit *commit)
467 int index_unchanged, empty_commit;
472 * (1) we do not allow empty at all and error out.
474 * (2) we allow ones that were initially empty, but
475 * forbid the ones that become empty;
479 if (!opts->allow_empty)
480 return 0; /* let "git commit" barf as necessary */
482 index_unchanged = is_index_unchanged();
483 if (index_unchanged < 0)
484 return index_unchanged;
485 if (!index_unchanged)
486 return 0; /* we do not have to say --allow-empty */
488 if (opts->keep_redundant_commits)
491 empty_commit = is_original_commit_empty(commit);
492 if (empty_commit < 0)
500 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
502 unsigned char head[20];
503 struct commit *base, *next, *parent;
504 const char *base_label, *next_label;
505 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
507 struct strbuf msgbuf = STRBUF_INIT;
508 int res, unborn = 0, allow;
510 if (opts->no_commit) {
512 * We do not intend to commit immediately. We just want to
513 * merge the differences in, so let's compute the tree
514 * that represents the "current" state for merge-recursive
517 if (write_cache_as_tree(head, 0, NULL))
518 die (_("Your index file is unmerged."));
520 unborn = get_sha1("HEAD", head);
522 hashcpy(head, EMPTY_TREE_SHA1_BIN);
523 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
524 return error_dirty_index(opts);
528 if (!commit->parents) {
531 else if (commit->parents->next) {
532 /* Reverting or cherry-picking a merge commit */
534 struct commit_list *p;
537 return error(_("Commit %s is a merge but no -m option was given."),
538 sha1_to_hex(commit->object.sha1));
540 for (cnt = 1, p = commit->parents;
541 cnt != opts->mainline && p;
544 if (cnt != opts->mainline || !p)
545 return error(_("Commit %s does not have parent %d"),
546 sha1_to_hex(commit->object.sha1), opts->mainline);
548 } else if (0 < opts->mainline)
549 return error(_("Mainline was specified but commit %s is not a merge."),
550 sha1_to_hex(commit->object.sha1));
552 parent = commit->parents->item;
554 if (opts->allow_ff &&
555 ((parent && !hashcmp(parent->object.sha1, head)) ||
556 (!parent && unborn)))
557 return fast_forward_to(commit->object.sha1, head, unborn, opts);
559 if (parent && parse_commit(parent) < 0)
560 /* TRANSLATORS: The first %s will be "revert" or
561 "cherry-pick", the second %s a SHA1 */
562 return error(_("%s: cannot parse parent commit %s"),
563 action_name(opts), sha1_to_hex(parent->object.sha1));
565 if (get_message(commit, &msg) != 0)
566 return error(_("Cannot get commit message for %s"),
567 sha1_to_hex(commit->object.sha1));
570 * "commit" is an existing commit. We would want to apply
571 * the difference it introduces since its first parent "prev"
572 * on top of the current HEAD if we are cherry-pick. Or the
573 * reverse of it if we are revert.
576 defmsg = git_pathdup("MERGE_MSG");
578 if (opts->action == REPLAY_REVERT) {
580 base_label = msg.label;
582 next_label = msg.parent_label;
583 strbuf_addstr(&msgbuf, "Revert \"");
584 strbuf_addstr(&msgbuf, msg.subject);
585 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
586 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
588 if (commit->parents && commit->parents->next) {
589 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
590 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
592 strbuf_addstr(&msgbuf, ".\n");
597 base_label = msg.parent_label;
599 next_label = msg.label;
602 * Append the commit log message to msgbuf; it starts
603 * after the tree, parent, author, committer
604 * information followed by "\n\n".
606 p = strstr(msg.message, "\n\n");
609 strbuf_addstr(&msgbuf, p);
612 if (opts->record_origin) {
613 if (!has_conforming_footer(&msgbuf, NULL, 0))
614 strbuf_addch(&msgbuf, '\n');
615 strbuf_addstr(&msgbuf, cherry_picked_prefix);
616 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
617 strbuf_addstr(&msgbuf, ")\n");
621 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
622 res = do_recursive_merge(base, next, base_label, next_label,
623 head, &msgbuf, opts);
624 write_message(&msgbuf, defmsg);
626 struct commit_list *common = NULL;
627 struct commit_list *remotes = NULL;
629 write_message(&msgbuf, defmsg);
631 commit_list_insert(base, &common);
632 commit_list_insert(next, &remotes);
633 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
634 common, sha1_to_hex(head), remotes);
635 free_commit_list(common);
636 free_commit_list(remotes);
640 * If the merge was clean or if it failed due to conflict, we write
641 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
642 * However, if the merge did not even start, then we don't want to
645 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
646 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
647 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
648 write_cherry_pick_head(commit, "REVERT_HEAD");
651 error(opts->action == REPLAY_REVERT
652 ? _("could not revert %s... %s")
653 : _("could not apply %s... %s"),
654 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
656 print_advice(res == 1, opts);
657 rerere(opts->allow_rerere_auto);
661 if (opts->skip_empty && is_index_unchanged() == 1) {
663 warning(_("skipping %s... %s"),
664 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
668 allow = allow_empty(opts, commit);
673 if (!opts->no_commit)
674 res = run_git_commit(defmsg, opts, allow);
676 if (!res && opts->action == REPLAY_PICK) {
677 unsigned char to[20];
679 if (read_ref("HEAD", to))
682 add_rewritten(&rewritten, commit->object.sha1, to);
691 static void prepare_revs(struct replay_opts *opts)
694 * picking (but not reverting) ranges (but not individual revisions)
695 * should be done in reverse
697 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
698 opts->revs->reverse ^= 1;
700 if (prepare_revision_walk(opts->revs))
701 die(_("revision walk setup failed"));
703 if (!opts->revs->commits && !opts->quiet)
704 error(_("empty commit set passed"));
707 static void read_and_refresh_cache(struct replay_opts *opts)
709 static struct lock_file index_lock;
710 int index_fd = hold_locked_index(&index_lock, 0);
711 if (read_index_preload(&the_index, NULL) < 0)
712 die(_("git %s: failed to read the index"), action_name(opts));
713 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
714 if (the_index.cache_changed) {
715 if (write_index(&the_index, index_fd) ||
716 commit_locked_index(&index_lock))
717 die(_("git %s: failed to refresh the index"), action_name(opts));
719 rollback_lock_file(&index_lock);
722 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
723 struct replay_opts *opts)
725 struct commit_list *cur = NULL;
726 const char *sha1_abbrev = NULL;
727 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
731 for (cur = todo_list; cur; cur = cur->next) {
732 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
733 subject_len = find_commit_subject(cur->item->buffer, &subject);
734 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
735 subject_len, subject);
740 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
742 unsigned char commit_sha1[20];
743 enum replay_action action;
744 char *end_of_object_name;
745 int saved, status, padding;
747 if (starts_with(bol, "pick")) {
748 action = REPLAY_PICK;
749 bol += strlen("pick");
750 } else if (starts_with(bol, "revert")) {
751 action = REPLAY_REVERT;
752 bol += strlen("revert");
756 /* Eat up extra spaces/ tabs before object name */
757 padding = strspn(bol, " \t");
762 end_of_object_name = bol + strcspn(bol, " \t\n");
763 saved = *end_of_object_name;
764 *end_of_object_name = '\0';
765 status = get_sha1(bol, commit_sha1);
766 *end_of_object_name = saved;
769 * Verify that the action matches up with the one in
770 * opts; we don't support arbitrary instructions
772 if (action != opts->action) {
773 const char *action_str;
774 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
775 error(_("Cannot %s during a %s"), action_str, action_name(opts));
782 return lookup_commit_reference(commit_sha1);
785 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
786 struct replay_opts *opts)
788 struct commit_list **next = todo_list;
789 struct commit *commit;
793 for (i = 1; *p; i++) {
794 char *eol = strchrnul(p, '\n');
795 commit = parse_insn_line(p, eol, opts);
797 return error(_("Could not parse line %d."), i);
798 next = commit_list_append(commit, next);
799 p = *eol ? eol + 1 : eol;
802 return error(_("No commits parsed."));
806 static void read_populate_todo(struct commit_list **todo_list,
807 struct replay_opts *opts)
809 const char *todo_file = git_path(SEQ_TODO_FILE);
810 struct strbuf buf = STRBUF_INIT;
813 fd = open(todo_file, O_RDONLY);
815 die_errno(_("Could not open %s"), todo_file);
816 if (strbuf_read(&buf, fd, 0) < 0) {
818 strbuf_release(&buf);
819 die(_("Could not read %s."), todo_file);
823 res = parse_insn_buffer(buf.buf, todo_list, opts);
824 strbuf_release(&buf);
826 die(_("Unusable instruction sheet: %s"), todo_file);
829 static int populate_opts_cb(const char *key, const char *value, void *data)
831 struct replay_opts *opts = data;
836 else if (!strcmp(key, "options.no-commit"))
837 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
838 else if (!strcmp(key, "options.edit"))
839 opts->edit = git_config_bool_or_int(key, value, &error_flag);
840 else if (!strcmp(key, "options.signoff"))
841 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
842 else if (!strcmp(key, "options.record-origin"))
843 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
844 else if (!strcmp(key, "options.allow-ff"))
845 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
846 else if (!strcmp(key, "options.mainline"))
847 opts->mainline = git_config_int(key, value);
848 else if (!strcmp(key, "options.strategy"))
849 git_config_string(&opts->strategy, key, value);
850 else if (!strcmp(key, "options.strategy-option")) {
851 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
852 opts->xopts[opts->xopts_nr++] = xstrdup(value);
853 } else if (!strcmp(key, "options.action-name"))
854 git_config_string(&opts->action_name, key, value);
855 else if (!strcmp(key, "options.allow-rerere-auto"))
856 opts->allow_rerere_auto = git_config_int(key, value);
858 return error(_("Invalid key: %s"), key);
861 return error(_("Invalid value for %s: %s"), key, value);
866 static void read_populate_opts(struct replay_opts **opts_ptr)
868 const char *opts_file = git_path(SEQ_OPTS_FILE);
870 if (!file_exists(opts_file))
872 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
873 die(_("Malformed options sheet: %s"), opts_file);
876 static void walk_revs_populate_todo(struct commit_list **todo_list,
877 struct replay_opts *opts)
879 struct commit *commit;
880 struct commit_list **next;
885 while ((commit = get_revision(opts->revs))) {
886 next = commit_list_append(commit, next);
891 static int create_seq_dir(void)
893 const char *seq_dir = git_path(SEQ_DIR);
895 if (file_exists(seq_dir)) {
896 error(_("a cherry-pick or revert is already in progress"));
897 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
900 else if (mkdir(seq_dir, 0777) < 0)
901 die_errno(_("Could not create sequencer directory %s"), seq_dir);
905 static void save_head(const char *head)
907 const char *head_file = git_path(SEQ_HEAD_FILE);
908 static struct lock_file head_lock;
909 struct strbuf buf = STRBUF_INIT;
912 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
913 strbuf_addf(&buf, "%s\n", head);
914 if (write_in_full(fd, buf.buf, buf.len) < 0)
915 die_errno(_("Could not write to %s"), head_file);
916 if (commit_lock_file(&head_lock) < 0)
917 die(_("Error wrapping up %s."), head_file);
920 static int reset_for_rollback(const unsigned char *sha1)
922 const char *argv[4]; /* reset --merge <arg> + NULL */
925 argv[2] = sha1_to_hex(sha1);
927 return run_command_v_opt(argv, RUN_GIT_CMD);
930 static int rollback_single_pick(void)
932 unsigned char head_sha1[20];
934 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
935 !file_exists(git_path("REVERT_HEAD")))
936 return error(_("no cherry-pick or revert in progress"));
937 if (read_ref_full("HEAD", head_sha1, 0, NULL))
938 return error(_("cannot resolve HEAD"));
939 if (is_null_sha1(head_sha1))
940 return error(_("cannot abort from a branch yet to be born"));
941 return reset_for_rollback(head_sha1);
944 static int sequencer_rollback(struct replay_opts *opts)
946 const char *filename;
948 unsigned char sha1[20];
949 struct strbuf buf = STRBUF_INIT;
951 filename = git_path(SEQ_HEAD_FILE);
952 f = fopen(filename, "r");
953 if (!f && errno == ENOENT) {
955 * There is no multiple-cherry-pick in progress.
956 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
957 * a single-cherry-pick in progress, abort that.
959 return rollback_single_pick();
962 return error(_("cannot open %s: %s"), filename,
964 if (strbuf_getline(&buf, f, '\n')) {
965 error(_("cannot read %s: %s"), filename, ferror(f) ?
966 strerror(errno) : _("unexpected end of file"));
971 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
972 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
976 if (reset_for_rollback(sha1))
978 remove_sequencer_state();
979 strbuf_release(&buf);
982 strbuf_release(&buf);
986 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
988 const char *todo_file = git_path(SEQ_TODO_FILE);
989 static struct lock_file todo_lock;
990 struct strbuf buf = STRBUF_INIT;
993 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
994 if (format_todo(&buf, todo_list, opts) < 0)
995 die(_("Could not format %s."), todo_file);
996 if (write_in_full(fd, buf.buf, buf.len) < 0) {
997 strbuf_release(&buf);
998 die_errno(_("Could not write to %s"), todo_file);
1000 if (commit_lock_file(&todo_lock) < 0) {
1001 strbuf_release(&buf);
1002 die(_("Error wrapping up %s."), todo_file);
1004 strbuf_release(&buf);
1007 static void save_opts(struct replay_opts *opts)
1009 const char *opts_file = git_path(SEQ_OPTS_FILE);
1011 if (opts->no_commit)
1012 git_config_set_in_file(opts_file, "options.no-commit", "true");
1014 git_config_set_in_file(opts_file, "options.edit", "true");
1016 git_config_set_in_file(opts_file, "options.signoff", "true");
1017 if (opts->record_origin)
1018 git_config_set_in_file(opts_file, "options.record-origin", "true");
1020 git_config_set_in_file(opts_file, "options.allow-ff", "true");
1021 if (opts->mainline) {
1022 struct strbuf buf = STRBUF_INIT;
1023 strbuf_addf(&buf, "%d", opts->mainline);
1024 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
1025 strbuf_release(&buf);
1028 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
1031 for (i = 0; i < opts->xopts_nr; i++)
1032 git_config_set_multivar_in_file(opts_file,
1033 "options.strategy-option",
1034 opts->xopts[i], "^$", 0);
1036 if (opts->action_name)
1037 git_config_set_in_file(opts_file, "options.action-name", opts->action_name);
1038 if (opts->allow_rerere_auto) {
1039 struct strbuf buf = STRBUF_INIT;
1040 strbuf_addf(&buf, "%d", opts->allow_rerere_auto);
1041 git_config_set_in_file(opts_file, "options.allow-rerere-auto", buf.buf);
1042 strbuf_release(&buf);
1046 static void save_info(int total, int step)
1049 f = fopen(git_path("sequencer/total"), "w");
1051 fprintf(f, "%i\n", total);
1054 f = fopen(git_path("sequencer/step"), "w");
1056 fprintf(f, "%i\n", step);
1061 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1063 struct commit_list *cur;
1066 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1068 assert(!(opts->signoff || opts->no_commit ||
1069 opts->record_origin || opts->edit));
1070 read_and_refresh_cache(opts);
1072 for (cur = todo_list; cur; cur = cur->next) {
1073 save_todo(cur, opts);
1074 res = do_pick_commit(cur->item, opts);
1076 if (opts->action == REPLAY_PICK) {
1077 store_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1078 save_info(total, rewritten.nr + 1);
1087 * Sequence of picks finished successfully; cleanup by
1088 * removing the .git/sequencer directory
1090 remove_sequencer_state();
1094 static int continue_single_pick(void)
1096 const char *argv[] = { "commit", NULL };
1098 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1099 !file_exists(git_path("REVERT_HEAD")))
1100 return error(_("no cherry-pick or revert in progress"));
1101 return run_command_v_opt(argv, RUN_GIT_CMD);
1104 static int sequencer_continue(struct replay_opts *opts, int skip)
1106 struct commit_list *todo_list = NULL;
1108 if (!file_exists(git_path(SEQ_TODO_FILE)))
1109 return continue_single_pick();
1110 read_populate_opts(&opts);
1111 read_populate_todo(&todo_list, opts);
1112 if (opts->action == REPLAY_PICK)
1113 load_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1115 /* Verify that the conflict has been resolved */
1116 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1117 file_exists(git_path("REVERT_HEAD"))) {
1118 int ret = continue_single_pick();
1122 if (index_differs_from("HEAD", 0))
1123 return error_dirty_index(opts);
1124 if (opts->action == REPLAY_PICK && !skip) {
1125 unsigned char to[20];
1126 if (!read_ref("HEAD", to))
1127 add_rewritten(&rewritten, todo_list->item->object.sha1, to);
1129 todo_list = todo_list->next;
1130 return pick_commits(todo_list, opts);
1133 static int sequencer_skip(struct replay_opts *opts)
1135 const char *argv[4]; /* reset --hard HEAD + NULL */
1136 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1139 if (setup_rerere(&merge_rr, 0) >= 0) {
1140 rerere_clear(&merge_rr);
1141 string_list_clear(&merge_rr, 1);
1148 ret = run_command_v_opt(argv, RUN_GIT_CMD);
1152 return sequencer_continue(opts, 1);
1155 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1158 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1159 ret = do_pick_commit(cmit, opts);
1166 int sequencer_pick_revisions(struct replay_opts *opts)
1168 struct commit_list *todo_list = NULL;
1169 unsigned char sha1[20];
1172 if (opts->subcommand == REPLAY_NONE)
1175 read_and_refresh_cache(opts);
1178 * Decide what to do depending on the arguments; a fresh
1179 * cherry-pick should be handled differently from an existing
1180 * one that is being continued
1182 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1183 remove_sequencer_state();
1186 if (opts->subcommand == REPLAY_ROLLBACK)
1187 return sequencer_rollback(opts);
1188 if (opts->subcommand == REPLAY_CONTINUE)
1189 return sequencer_continue(opts, 0);
1190 if (opts->subcommand == REPLAY_SKIP)
1191 return sequencer_skip(opts);
1193 for (i = 0; i < opts->revs->pending.nr; i++) {
1194 unsigned char sha1[20];
1195 const char *name = opts->revs->pending.objects[i].name;
1197 /* This happens when using --stdin. */
1201 if (!get_sha1(name, sha1)) {
1202 if (!lookup_commit_reference_gently(sha1, 1)) {
1203 enum object_type type = sha1_object_info(sha1, NULL);
1204 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1207 die(_("%s: bad revision"), name);
1211 * If we were called as "git cherry-pick <commit>", just
1212 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1213 * REVERT_HEAD, and don't touch the sequencer state.
1214 * This means it is possible to cherry-pick in the middle
1215 * of a cherry-pick sequence.
1217 if (opts->revs->cmdline.nr == 1 &&
1218 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1219 opts->revs->no_walk &&
1220 !opts->revs->cmdline.rev->flags) {
1221 struct commit *cmit;
1222 if (prepare_revision_walk(opts->revs))
1223 die(_("revision walk setup failed"));
1224 cmit = get_revision(opts->revs);
1225 if (!cmit || get_revision(opts->revs))
1226 die("BUG: expected exactly one commit from walk");
1227 return single_pick(cmit, opts);
1231 * Start a new cherry-pick/ revert sequence; but
1232 * first, make sure that an existing one isn't in
1236 walk_revs_populate_todo(&todo_list, opts);
1237 if (create_seq_dir() < 0)
1239 if (get_sha1("HEAD", sha1)) {
1240 if (opts->action == REPLAY_REVERT)
1241 return error(_("Can't revert as initial commit"));
1242 return error(_("Can't cherry-pick into empty head"));
1244 save_head(sha1_to_hex(sha1));
1246 return pick_commits(todo_list, opts);
1249 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1251 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1252 struct strbuf sob = STRBUF_INIT;
1255 strbuf_addstr(&sob, sign_off_header);
1256 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1257 getenv("GIT_COMMITTER_EMAIL")));
1258 strbuf_addch(&sob, '\n');
1261 * If the whole message buffer is equal to the sob, pretend that we
1262 * found a conforming footer with a matching sob
1264 if (msgbuf->len - ignore_footer == sob.len &&
1265 !strncmp(msgbuf->buf, sob.buf, sob.len))
1268 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1271 const char *append_newlines = NULL;
1272 size_t len = msgbuf->len - ignore_footer;
1276 * The buffer is completely empty. Leave foom for
1277 * the title and body to be filled in by the user.
1279 append_newlines = "\n\n";
1280 } else if (msgbuf->buf[len - 1] != '\n') {
1282 * Incomplete line. Complete the line and add a
1283 * blank one so that there is an empty line between
1284 * the message body and the sob.
1286 append_newlines = "\n\n";
1287 } else if (len == 1) {
1289 * Buffer contains a single newline. Add another
1290 * so that we leave room for the title and body.
1292 append_newlines = "\n";
1293 } else if (msgbuf->buf[len - 2] != '\n') {
1295 * Buffer ends with a single newline. Add another
1296 * so that there is an empty line between the message
1299 append_newlines = "\n";
1300 } /* else, the buffer already ends with two newlines. */
1302 if (append_newlines)
1303 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1304 append_newlines, strlen(append_newlines));
1307 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1308 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1311 strbuf_release(&sob);