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;
25 static void finish(struct replay_opts *opts)
28 struct strbuf msg = STRBUF_INIT;
30 if (opts->action != REPLAY_PICK)
33 name = opts->action_name ? opts->action_name : "cherry-pick";
38 strbuf_addf(&msg, "Notes added by 'git %s'", name);
39 copy_rewrite_notes(&rewritten, name, msg.buf);
40 run_rewrite_hook(&rewritten, name);
44 static int is_rfc2822_line(const char *buf, int len)
48 for (i = 0; i < len; i++) {
52 if (!isalnum(ch) && ch != '-')
59 static int is_cherry_picked_from_line(const char *buf, int len)
62 * We only care that it looks roughly like (cherry picked from ...)
64 return len > strlen(cherry_picked_prefix) + 1 &&
65 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
69 * Returns 0 for non-conforming footer
70 * Returns 1 for conforming footer
71 * Returns 2 when sob exists within conforming footer
72 * Returns 3 when sob exists within conforming footer as last entry
74 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
79 int len = sb->len - ignore_footer;
80 const char *buf = sb->buf;
83 /* footer must end with newline */
84 if (!len || buf[len - 1] != '\n')
88 for (i = len - 1; i > 0; i--) {
90 if (prev == '\n' && ch == '\n') /* paragraph break */
95 /* require at least one blank line */
96 if (prev != '\n' || buf[i] != '\n')
99 /* advance to start of last paragraph */
100 while (i < len - 1 && buf[i] == '\n')
103 for (; i < len; i = k) {
106 for (k = i; k < len && buf[k] != '\n'; k++)
110 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
111 if (found_rfc2822 && sob &&
112 !strncmp(buf + i, sob->buf, sob->len))
115 if (!(found_rfc2822 ||
116 is_cherry_picked_from_line(buf + i, k - i - 1)))
126 static void remove_sequencer_state(void)
128 struct strbuf seq_dir = STRBUF_INIT;
130 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
131 remove_dir_recursively(&seq_dir, 0);
132 strbuf_release(&seq_dir);
135 static const char *action_name(const struct replay_opts *opts)
137 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
140 static char *get_encoding(const char *message);
142 struct commit_message {
146 char *reencoded_message;
150 static int get_message(struct commit *commit, struct commit_message *out)
152 const char *encoding;
153 const char *abbrev, *subject;
154 int abbrev_len, subject_len;
159 encoding = get_encoding(commit->buffer);
162 if (!git_commit_encoding)
163 git_commit_encoding = "UTF-8";
165 out->reencoded_message = NULL;
166 out->message = commit->buffer;
167 if (same_encoding(encoding, git_commit_encoding))
168 out->reencoded_message = reencode_string(commit->buffer,
169 git_commit_encoding, encoding);
170 if (out->reencoded_message)
171 out->message = out->reencoded_message;
173 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
174 abbrev_len = strlen(abbrev);
176 subject_len = find_commit_subject(out->message, &subject);
178 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
179 strlen("... ") + subject_len + 1);
180 q = out->parent_label;
181 q = mempcpy(q, "parent of ", strlen("parent of "));
183 q = mempcpy(q, abbrev, abbrev_len);
184 q = mempcpy(q, "... ", strlen("... "));
186 q = mempcpy(q, subject, subject_len);
191 static void free_message(struct commit_message *msg)
193 free(msg->parent_label);
194 free(msg->reencoded_message);
197 static char *get_encoding(const char *message)
199 const char *p = message, *eol;
201 while (*p && *p != '\n') {
202 for (eol = p + 1; *eol && *eol != '\n'; eol++)
204 if (starts_with(p, "encoding ")) {
205 char *result = xmalloc(eol - 8 - p);
206 strlcpy(result, p + 9, eol - 8 - p);
216 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
218 const char *filename;
220 struct strbuf buf = STRBUF_INIT;
222 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
224 filename = git_path("%s", pseudoref);
225 fd = open(filename, O_WRONLY | O_CREAT, 0666);
227 die_errno(_("Could not open '%s' for writing"), filename);
228 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
229 die_errno(_("Could not write to '%s'"), filename);
230 strbuf_release(&buf);
233 static void print_advice(int show_hint, struct replay_opts *opts)
235 char *msg = getenv("GIT_CHERRY_PICK_HELP");
238 fprintf(stderr, "%s\n", msg);
240 * A conflict has occurred but the porcelain
241 * (typically rebase --interactive) wants to take care
242 * of the commit itself so remove CHERRY_PICK_HEAD
244 unlink(git_path("CHERRY_PICK_HEAD"));
250 advise(_("after resolving the conflicts, mark the corrected paths\n"
251 "with 'git add <paths>' or 'git rm <paths>'"));
253 advise(_("after resolving the conflicts, mark the corrected paths\n"
254 "with 'git add <paths>' or 'git rm <paths>'\n"
255 "and commit the result with 'git commit'"));
259 static void write_message(struct strbuf *msgbuf, const char *filename)
261 static struct lock_file msg_file;
263 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
265 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
266 die_errno(_("Could not write to %s"), filename);
267 strbuf_release(msgbuf);
268 if (commit_lock_file(&msg_file) < 0)
269 die(_("Error wrapping up %s"), filename);
272 static struct tree *empty_tree(void)
274 return lookup_tree(EMPTY_TREE_SHA1_BIN);
277 static int error_dirty_index(struct replay_opts *opts)
279 if (read_cache_unmerged())
280 return error_resolve_conflict(action_name(opts));
282 /* Different translation strings for cherry-pick and revert */
283 if (opts->action == REPLAY_PICK)
284 error(_("Your local changes would be overwritten by cherry-pick."));
286 error(_("Your local changes would be overwritten by revert."));
288 if (advice_commit_before_merge)
289 advise(_("Commit your changes or stash them to proceed."));
293 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
294 int unborn, struct replay_opts *opts)
296 struct ref_lock *ref_lock;
297 struct strbuf sb = STRBUF_INIT;
301 if (checkout_fast_forward(from, to, 1))
302 exit(1); /* the callee should have complained already */
303 ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
305 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
306 ret = write_ref_sha1(ref_lock, to, sb.buf);
311 static int do_recursive_merge(struct commit *base, struct commit *next,
312 const char *base_label, const char *next_label,
313 unsigned char *head, struct strbuf *msgbuf,
314 struct replay_opts *opts)
316 struct merge_options o;
317 struct tree *result, *next_tree, *base_tree, *head_tree;
320 static struct lock_file index_lock;
322 index_fd = hold_locked_index(&index_lock, 1);
326 init_merge_options(&o);
327 o.ancestor = base ? base_label : "(empty tree)";
329 o.branch2 = next ? next_label : "(empty tree)";
331 head_tree = parse_tree_indirect(head);
332 next_tree = next ? next->tree : empty_tree();
333 base_tree = base ? base->tree : empty_tree();
335 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
336 parse_merge_opt(&o, *xopt);
338 clean = merge_trees(&o,
340 next_tree, base_tree, &result);
342 if (active_cache_changed &&
343 (write_cache(index_fd, active_cache, active_nr) ||
344 commit_locked_index(&index_lock)))
345 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
346 die(_("%s: Unable to write new index file"), action_name(opts));
347 rollback_lock_file(&index_lock);
350 append_signoff(msgbuf, 0, 0);
354 strbuf_addstr(msgbuf, "\nConflicts:\n");
355 for (i = 0; i < active_nr;) {
356 const struct cache_entry *ce = active_cache[i++];
358 strbuf_addch(msgbuf, '\t');
359 strbuf_addstr(msgbuf, ce->name);
360 strbuf_addch(msgbuf, '\n');
361 while (i < active_nr && !strcmp(ce->name,
362 active_cache[i]->name))
371 static int is_index_unchanged(void)
373 unsigned char head_sha1[20];
374 struct commit *head_commit;
376 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
377 return error(_("Could not resolve HEAD commit\n"));
379 head_commit = lookup_commit(head_sha1);
382 * If head_commit is NULL, check_commit, called from
383 * lookup_commit, would have indicated that head_commit is not
384 * a commit object already. parse_commit() will return failure
385 * without further complaints in such a case. Otherwise, if
386 * the commit is invalid, parse_commit() will complain. So
387 * there is nothing for us to say here. Just return failure.
389 if (parse_commit(head_commit))
392 if (!active_cache_tree)
393 active_cache_tree = cache_tree();
395 if (!cache_tree_fully_valid(active_cache_tree))
396 if (cache_tree_update(active_cache_tree,
397 (const struct cache_entry * const *)active_cache,
399 return error(_("Unable to update cache tree\n"));
401 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
405 * If we are cherry-pick, and if the merge did not result in
406 * hand-editing, we will hit this commit and inherit the original
407 * author date and name.
408 * If we are revert, or if our cherry-pick results in a hand merge,
409 * we had better say that the current user is responsible for that.
411 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
414 struct argv_array array;
417 argv_array_init(&array);
418 argv_array_push(&array, "commit");
419 argv_array_push(&array, "-n");
421 argv_array_push(&array, "-q");
424 argv_array_push(&array, "-s");
426 argv_array_push(&array, "-F");
427 argv_array_push(&array, defmsg);
431 argv_array_push(&array, "--allow-empty");
433 if (opts->allow_empty_message)
434 argv_array_push(&array, "--allow-empty-message");
436 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
437 argv_array_clear(&array);
441 static int is_original_commit_empty(struct commit *commit)
443 const unsigned char *ptree_sha1;
445 if (parse_commit(commit))
446 return error(_("Could not parse commit %s\n"),
447 sha1_to_hex(commit->object.sha1));
448 if (commit->parents) {
449 struct commit *parent = commit->parents->item;
450 if (parse_commit(parent))
451 return error(_("Could not parse parent commit %s\n"),
452 sha1_to_hex(parent->object.sha1));
453 ptree_sha1 = parent->tree->object.sha1;
455 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
458 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
462 * Do we run "git commit" with "--allow-empty"?
464 static int allow_empty(struct replay_opts *opts, struct commit *commit)
466 int index_unchanged, empty_commit;
471 * (1) we do not allow empty at all and error out.
473 * (2) we allow ones that were initially empty, but
474 * forbid the ones that become empty;
478 if (!opts->allow_empty)
479 return 0; /* let "git commit" barf as necessary */
481 index_unchanged = is_index_unchanged();
482 if (index_unchanged < 0)
483 return index_unchanged;
484 if (!index_unchanged)
485 return 0; /* we do not have to say --allow-empty */
487 if (opts->keep_redundant_commits)
490 empty_commit = is_original_commit_empty(commit);
491 if (empty_commit < 0)
499 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
501 unsigned char head[20];
502 struct commit *base, *next, *parent;
503 const char *base_label, *next_label;
504 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
506 struct strbuf msgbuf = STRBUF_INIT;
507 int res, unborn = 0, allow;
509 if (opts->no_commit) {
511 * We do not intend to commit immediately. We just want to
512 * merge the differences in, so let's compute the tree
513 * that represents the "current" state for merge-recursive
516 if (write_cache_as_tree(head, 0, NULL))
517 die (_("Your index file is unmerged."));
519 unborn = get_sha1("HEAD", head);
521 hashcpy(head, EMPTY_TREE_SHA1_BIN);
522 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
523 return error_dirty_index(opts);
527 if (!commit->parents) {
530 else if (commit->parents->next) {
531 /* Reverting or cherry-picking a merge commit */
533 struct commit_list *p;
536 return error(_("Commit %s is a merge but no -m option was given."),
537 sha1_to_hex(commit->object.sha1));
539 for (cnt = 1, p = commit->parents;
540 cnt != opts->mainline && p;
543 if (cnt != opts->mainline || !p)
544 return error(_("Commit %s does not have parent %d"),
545 sha1_to_hex(commit->object.sha1), opts->mainline);
547 } else if (0 < opts->mainline)
548 return error(_("Mainline was specified but commit %s is not a merge."),
549 sha1_to_hex(commit->object.sha1));
551 parent = commit->parents->item;
553 if (opts->allow_ff &&
554 ((parent && !hashcmp(parent->object.sha1, head)) ||
555 (!parent && unborn)))
556 return fast_forward_to(commit->object.sha1, head, unborn, opts);
558 if (parent && parse_commit(parent) < 0)
559 /* TRANSLATORS: The first %s will be "revert" or
560 "cherry-pick", the second %s a SHA1 */
561 return error(_("%s: cannot parse parent commit %s"),
562 action_name(opts), sha1_to_hex(parent->object.sha1));
564 if (get_message(commit, &msg) != 0)
565 return error(_("Cannot get commit message for %s"),
566 sha1_to_hex(commit->object.sha1));
569 * "commit" is an existing commit. We would want to apply
570 * the difference it introduces since its first parent "prev"
571 * on top of the current HEAD if we are cherry-pick. Or the
572 * reverse of it if we are revert.
575 defmsg = git_pathdup("MERGE_MSG");
577 if (opts->action == REPLAY_REVERT) {
579 base_label = msg.label;
581 next_label = msg.parent_label;
582 strbuf_addstr(&msgbuf, "Revert \"");
583 strbuf_addstr(&msgbuf, msg.subject);
584 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
585 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
587 if (commit->parents && commit->parents->next) {
588 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
589 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
591 strbuf_addstr(&msgbuf, ".\n");
596 base_label = msg.parent_label;
598 next_label = msg.label;
601 * Append the commit log message to msgbuf; it starts
602 * after the tree, parent, author, committer
603 * information followed by "\n\n".
605 p = strstr(msg.message, "\n\n");
608 strbuf_addstr(&msgbuf, p);
611 if (opts->record_origin) {
612 if (!has_conforming_footer(&msgbuf, NULL, 0))
613 strbuf_addch(&msgbuf, '\n');
614 strbuf_addstr(&msgbuf, cherry_picked_prefix);
615 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
616 strbuf_addstr(&msgbuf, ")\n");
620 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
621 res = do_recursive_merge(base, next, base_label, next_label,
622 head, &msgbuf, opts);
623 write_message(&msgbuf, defmsg);
625 struct commit_list *common = NULL;
626 struct commit_list *remotes = NULL;
628 write_message(&msgbuf, defmsg);
630 commit_list_insert(base, &common);
631 commit_list_insert(next, &remotes);
632 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
633 common, sha1_to_hex(head), remotes);
634 free_commit_list(common);
635 free_commit_list(remotes);
639 * If the merge was clean or if it failed due to conflict, we write
640 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
641 * However, if the merge did not even start, then we don't want to
644 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
645 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
646 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
647 write_cherry_pick_head(commit, "REVERT_HEAD");
650 error(opts->action == REPLAY_REVERT
651 ? _("could not revert %s... %s")
652 : _("could not apply %s... %s"),
653 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
655 print_advice(res == 1, opts);
656 rerere(opts->allow_rerere_auto);
660 if (opts->skip_empty && is_index_unchanged() == 1) {
662 warning(_("skipping %s... %s"),
663 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
667 allow = allow_empty(opts, commit);
672 if (!opts->no_commit)
673 res = run_git_commit(defmsg, opts, allow);
675 if (!res && opts->action == REPLAY_PICK) {
676 unsigned char to[20];
678 if (read_ref("HEAD", to))
681 add_rewritten(&rewritten, commit->object.sha1, to);
690 static void prepare_revs(struct replay_opts *opts)
693 * picking (but not reverting) ranges (but not individual revisions)
694 * should be done in reverse
696 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
697 opts->revs->reverse ^= 1;
699 if (prepare_revision_walk(opts->revs))
700 die(_("revision walk setup failed"));
702 if (!opts->revs->commits && !opts->quiet)
703 error(_("empty commit set passed"));
706 static void read_and_refresh_cache(struct replay_opts *opts)
708 static struct lock_file index_lock;
709 int index_fd = hold_locked_index(&index_lock, 0);
710 if (read_index_preload(&the_index, NULL) < 0)
711 die(_("git %s: failed to read the index"), action_name(opts));
712 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
713 if (the_index.cache_changed) {
714 if (write_index(&the_index, index_fd) ||
715 commit_locked_index(&index_lock))
716 die(_("git %s: failed to refresh the index"), action_name(opts));
718 rollback_lock_file(&index_lock);
721 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
722 struct replay_opts *opts)
724 struct commit_list *cur = NULL;
725 const char *sha1_abbrev = NULL;
726 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
730 for (cur = todo_list; cur; cur = cur->next) {
731 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
732 subject_len = find_commit_subject(cur->item->buffer, &subject);
733 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
734 subject_len, subject);
739 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
741 unsigned char commit_sha1[20];
742 enum replay_action action;
743 char *end_of_object_name;
744 int saved, status, padding;
746 if (starts_with(bol, "pick")) {
747 action = REPLAY_PICK;
748 bol += strlen("pick");
749 } else if (starts_with(bol, "revert")) {
750 action = REPLAY_REVERT;
751 bol += strlen("revert");
755 /* Eat up extra spaces/ tabs before object name */
756 padding = strspn(bol, " \t");
761 end_of_object_name = bol + strcspn(bol, " \t\n");
762 saved = *end_of_object_name;
763 *end_of_object_name = '\0';
764 status = get_sha1(bol, commit_sha1);
765 *end_of_object_name = saved;
768 * Verify that the action matches up with the one in
769 * opts; we don't support arbitrary instructions
771 if (action != opts->action) {
772 const char *action_str;
773 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
774 error(_("Cannot %s during a %s"), action_str, action_name(opts));
781 return lookup_commit_reference(commit_sha1);
784 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
785 struct replay_opts *opts)
787 struct commit_list **next = todo_list;
788 struct commit *commit;
792 for (i = 1; *p; i++) {
793 char *eol = strchrnul(p, '\n');
794 commit = parse_insn_line(p, eol, opts);
796 return error(_("Could not parse line %d."), i);
797 next = commit_list_append(commit, next);
798 p = *eol ? eol + 1 : eol;
801 return error(_("No commits parsed."));
805 static void read_populate_todo(struct commit_list **todo_list,
806 struct replay_opts *opts)
808 const char *todo_file = git_path(SEQ_TODO_FILE);
809 struct strbuf buf = STRBUF_INIT;
812 fd = open(todo_file, O_RDONLY);
814 die_errno(_("Could not open %s"), todo_file);
815 if (strbuf_read(&buf, fd, 0) < 0) {
817 strbuf_release(&buf);
818 die(_("Could not read %s."), todo_file);
822 res = parse_insn_buffer(buf.buf, todo_list, opts);
823 strbuf_release(&buf);
825 die(_("Unusable instruction sheet: %s"), todo_file);
828 static int populate_opts_cb(const char *key, const char *value, void *data)
830 struct replay_opts *opts = data;
835 else if (!strcmp(key, "options.no-commit"))
836 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
837 else if (!strcmp(key, "options.edit"))
838 opts->edit = git_config_bool_or_int(key, value, &error_flag);
839 else if (!strcmp(key, "options.signoff"))
840 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
841 else if (!strcmp(key, "options.record-origin"))
842 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
843 else if (!strcmp(key, "options.allow-ff"))
844 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
845 else if (!strcmp(key, "options.mainline"))
846 opts->mainline = git_config_int(key, value);
847 else if (!strcmp(key, "options.strategy"))
848 git_config_string(&opts->strategy, key, value);
849 else if (!strcmp(key, "options.strategy-option")) {
850 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
851 opts->xopts[opts->xopts_nr++] = xstrdup(value);
852 } else if (!strcmp(key, "options.action-name"))
853 git_config_string(&opts->action_name, key, value);
854 else if (!strcmp(key, "options.allow-rerere-auto"))
855 opts->allow_rerere_auto = git_config_int(key, value);
857 return error(_("Invalid key: %s"), key);
860 return error(_("Invalid value for %s: %s"), key, value);
865 static void read_populate_opts(struct replay_opts **opts_ptr)
867 const char *opts_file = git_path(SEQ_OPTS_FILE);
869 if (!file_exists(opts_file))
871 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
872 die(_("Malformed options sheet: %s"), opts_file);
875 static void walk_revs_populate_todo(struct commit_list **todo_list,
876 struct replay_opts *opts)
878 struct commit *commit;
879 struct commit_list **next;
884 while ((commit = get_revision(opts->revs)))
885 next = commit_list_append(commit, next);
888 static int create_seq_dir(void)
890 const char *seq_dir = git_path(SEQ_DIR);
892 if (file_exists(seq_dir)) {
893 error(_("a cherry-pick or revert is already in progress"));
894 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
897 else if (mkdir(seq_dir, 0777) < 0)
898 die_errno(_("Could not create sequencer directory %s"), seq_dir);
902 static void save_head(const char *head)
904 const char *head_file = git_path(SEQ_HEAD_FILE);
905 static struct lock_file head_lock;
906 struct strbuf buf = STRBUF_INIT;
909 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
910 strbuf_addf(&buf, "%s\n", head);
911 if (write_in_full(fd, buf.buf, buf.len) < 0)
912 die_errno(_("Could not write to %s"), head_file);
913 if (commit_lock_file(&head_lock) < 0)
914 die(_("Error wrapping up %s."), head_file);
917 static int reset_for_rollback(const unsigned char *sha1)
919 const char *argv[4]; /* reset --merge <arg> + NULL */
922 argv[2] = sha1_to_hex(sha1);
924 return run_command_v_opt(argv, RUN_GIT_CMD);
927 static int rollback_single_pick(void)
929 unsigned char head_sha1[20];
931 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
932 !file_exists(git_path("REVERT_HEAD")))
933 return error(_("no cherry-pick or revert in progress"));
934 if (read_ref_full("HEAD", head_sha1, 0, NULL))
935 return error(_("cannot resolve HEAD"));
936 if (is_null_sha1(head_sha1))
937 return error(_("cannot abort from a branch yet to be born"));
938 return reset_for_rollback(head_sha1);
941 static int sequencer_rollback(struct replay_opts *opts)
943 const char *filename;
945 unsigned char sha1[20];
946 struct strbuf buf = STRBUF_INIT;
948 filename = git_path(SEQ_HEAD_FILE);
949 f = fopen(filename, "r");
950 if (!f && errno == ENOENT) {
952 * There is no multiple-cherry-pick in progress.
953 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
954 * a single-cherry-pick in progress, abort that.
956 return rollback_single_pick();
959 return error(_("cannot open %s: %s"), filename,
961 if (strbuf_getline(&buf, f, '\n')) {
962 error(_("cannot read %s: %s"), filename, ferror(f) ?
963 strerror(errno) : _("unexpected end of file"));
968 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
969 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
973 if (reset_for_rollback(sha1))
975 remove_sequencer_state();
976 strbuf_release(&buf);
979 strbuf_release(&buf);
983 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
985 const char *todo_file = git_path(SEQ_TODO_FILE);
986 static struct lock_file todo_lock;
987 struct strbuf buf = STRBUF_INIT;
990 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
991 if (format_todo(&buf, todo_list, opts) < 0)
992 die(_("Could not format %s."), todo_file);
993 if (write_in_full(fd, buf.buf, buf.len) < 0) {
994 strbuf_release(&buf);
995 die_errno(_("Could not write to %s"), todo_file);
997 if (commit_lock_file(&todo_lock) < 0) {
998 strbuf_release(&buf);
999 die(_("Error wrapping up %s."), todo_file);
1001 strbuf_release(&buf);
1004 static void save_opts(struct replay_opts *opts)
1006 const char *opts_file = git_path(SEQ_OPTS_FILE);
1008 if (opts->no_commit)
1009 git_config_set_in_file(opts_file, "options.no-commit", "true");
1011 git_config_set_in_file(opts_file, "options.edit", "true");
1013 git_config_set_in_file(opts_file, "options.signoff", "true");
1014 if (opts->record_origin)
1015 git_config_set_in_file(opts_file, "options.record-origin", "true");
1017 git_config_set_in_file(opts_file, "options.allow-ff", "true");
1018 if (opts->mainline) {
1019 struct strbuf buf = STRBUF_INIT;
1020 strbuf_addf(&buf, "%d", opts->mainline);
1021 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
1022 strbuf_release(&buf);
1025 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
1028 for (i = 0; i < opts->xopts_nr; i++)
1029 git_config_set_multivar_in_file(opts_file,
1030 "options.strategy-option",
1031 opts->xopts[i], "^$", 0);
1033 if (opts->action_name)
1034 git_config_set_in_file(opts_file, "options.action-name", opts->action_name);
1035 if (opts->allow_rerere_auto) {
1036 struct strbuf buf = STRBUF_INIT;
1037 strbuf_addf(&buf, "%d", opts->allow_rerere_auto);
1038 git_config_set_in_file(opts_file, "options.allow-rerere-auto", buf.buf);
1039 strbuf_release(&buf);
1043 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1045 struct commit_list *cur;
1048 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1050 assert(!(opts->signoff || opts->no_commit ||
1051 opts->record_origin || opts->edit));
1052 read_and_refresh_cache(opts);
1054 for (cur = todo_list; cur; cur = cur->next) {
1055 save_todo(cur, opts);
1056 res = do_pick_commit(cur->item, opts);
1058 if (opts->action == REPLAY_PICK)
1059 store_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1067 * Sequence of picks finished successfully; cleanup by
1068 * removing the .git/sequencer directory
1070 remove_sequencer_state();
1074 static int continue_single_pick(void)
1076 const char *argv[] = { "commit", NULL };
1078 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1079 !file_exists(git_path("REVERT_HEAD")))
1080 return error(_("no cherry-pick or revert in progress"));
1081 return run_command_v_opt(argv, RUN_GIT_CMD);
1084 static int sequencer_continue(struct replay_opts *opts, int skip)
1086 struct commit_list *todo_list = NULL;
1088 if (!file_exists(git_path(SEQ_TODO_FILE)))
1089 return continue_single_pick();
1090 read_populate_opts(&opts);
1091 read_populate_todo(&todo_list, opts);
1092 if (opts->action == REPLAY_PICK)
1093 load_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1095 /* Verify that the conflict has been resolved */
1096 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1097 file_exists(git_path("REVERT_HEAD"))) {
1098 int ret = continue_single_pick();
1102 if (index_differs_from("HEAD", 0))
1103 return error_dirty_index(opts);
1104 if (opts->action == REPLAY_PICK && !skip) {
1105 unsigned char to[20];
1106 if (!read_ref("HEAD", to))
1107 add_rewritten(&rewritten, todo_list->item->object.sha1, to);
1109 todo_list = todo_list->next;
1110 return pick_commits(todo_list, opts);
1113 static int sequencer_skip(struct replay_opts *opts)
1115 const char *argv[4]; /* reset --hard HEAD + NULL */
1116 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1119 if (setup_rerere(&merge_rr, 0) >= 0) {
1120 rerere_clear(&merge_rr);
1121 string_list_clear(&merge_rr, 1);
1128 ret = run_command_v_opt(argv, RUN_GIT_CMD);
1132 return sequencer_continue(opts, 1);
1135 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1138 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1139 ret = do_pick_commit(cmit, opts);
1146 int sequencer_pick_revisions(struct replay_opts *opts)
1148 struct commit_list *todo_list = NULL;
1149 unsigned char sha1[20];
1152 if (opts->subcommand == REPLAY_NONE)
1155 read_and_refresh_cache(opts);
1158 * Decide what to do depending on the arguments; a fresh
1159 * cherry-pick should be handled differently from an existing
1160 * one that is being continued
1162 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1163 remove_sequencer_state();
1166 if (opts->subcommand == REPLAY_ROLLBACK)
1167 return sequencer_rollback(opts);
1168 if (opts->subcommand == REPLAY_CONTINUE)
1169 return sequencer_continue(opts, 0);
1170 if (opts->subcommand == REPLAY_SKIP)
1171 return sequencer_skip(opts);
1173 for (i = 0; i < opts->revs->pending.nr; i++) {
1174 unsigned char sha1[20];
1175 const char *name = opts->revs->pending.objects[i].name;
1177 /* This happens when using --stdin. */
1181 if (!get_sha1(name, sha1)) {
1182 if (!lookup_commit_reference_gently(sha1, 1)) {
1183 enum object_type type = sha1_object_info(sha1, NULL);
1184 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1187 die(_("%s: bad revision"), name);
1191 * If we were called as "git cherry-pick <commit>", just
1192 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1193 * REVERT_HEAD, and don't touch the sequencer state.
1194 * This means it is possible to cherry-pick in the middle
1195 * of a cherry-pick sequence.
1197 if (opts->revs->cmdline.nr == 1 &&
1198 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1199 opts->revs->no_walk &&
1200 !opts->revs->cmdline.rev->flags) {
1201 struct commit *cmit;
1202 if (prepare_revision_walk(opts->revs))
1203 die(_("revision walk setup failed"));
1204 cmit = get_revision(opts->revs);
1205 if (!cmit || get_revision(opts->revs))
1206 die("BUG: expected exactly one commit from walk");
1207 return single_pick(cmit, opts);
1211 * Start a new cherry-pick/ revert sequence; but
1212 * first, make sure that an existing one isn't in
1216 walk_revs_populate_todo(&todo_list, opts);
1217 if (create_seq_dir() < 0)
1219 if (get_sha1("HEAD", sha1)) {
1220 if (opts->action == REPLAY_REVERT)
1221 return error(_("Can't revert as initial commit"));
1222 return error(_("Can't cherry-pick into empty head"));
1224 save_head(sha1_to_hex(sha1));
1226 return pick_commits(todo_list, opts);
1229 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1231 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1232 struct strbuf sob = STRBUF_INIT;
1235 strbuf_addstr(&sob, sign_off_header);
1236 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1237 getenv("GIT_COMMITTER_EMAIL")));
1238 strbuf_addch(&sob, '\n');
1241 * If the whole message buffer is equal to the sob, pretend that we
1242 * found a conforming footer with a matching sob
1244 if (msgbuf->len - ignore_footer == sob.len &&
1245 !strncmp(msgbuf->buf, sob.buf, sob.len))
1248 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1251 const char *append_newlines = NULL;
1252 size_t len = msgbuf->len - ignore_footer;
1256 * The buffer is completely empty. Leave foom for
1257 * the title and body to be filled in by the user.
1259 append_newlines = "\n\n";
1260 } else if (msgbuf->buf[len - 1] != '\n') {
1262 * Incomplete line. Complete the line and add a
1263 * blank one so that there is an empty line between
1264 * the message body and the sob.
1266 append_newlines = "\n\n";
1267 } else if (len == 1) {
1269 * Buffer contains a single newline. Add another
1270 * so that we leave room for the title and body.
1272 append_newlines = "\n";
1273 } else if (msgbuf->buf[len - 2] != '\n') {
1275 * Buffer ends with a single newline. Add another
1276 * so that there is an empty line between the message
1279 append_newlines = "\n";
1280 } /* else, the buffer already ends with two newlines. */
1282 if (append_newlines)
1283 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1284 append_newlines, strlen(append_newlines));
1287 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1288 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1291 strbuf_release(&sob);