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;
418 argv_array_init(&array);
419 argv_array_push(&array, "commit");
420 argv_array_push(&array, "-n");
422 argv_array_push(&array, "-q");
424 if (opts->gpg_sign) {
425 gpg_sign = xmalloc(3 + strlen(opts->gpg_sign));
426 sprintf(gpg_sign, "-S%s", opts->gpg_sign);
427 argv_array_push(&array, gpg_sign);
431 argv_array_push(&array, "-s");
433 argv_array_push(&array, "-F");
434 argv_array_push(&array, defmsg);
438 argv_array_push(&array, "--allow-empty");
440 if (opts->allow_empty_message)
441 argv_array_push(&array, "--allow-empty-message");
443 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
444 argv_array_clear(&array);
448 static int is_original_commit_empty(struct commit *commit)
450 const unsigned char *ptree_sha1;
452 if (parse_commit(commit))
453 return error(_("Could not parse commit %s\n"),
454 sha1_to_hex(commit->object.sha1));
455 if (commit->parents) {
456 struct commit *parent = commit->parents->item;
457 if (parse_commit(parent))
458 return error(_("Could not parse parent commit %s\n"),
459 sha1_to_hex(parent->object.sha1));
460 ptree_sha1 = parent->tree->object.sha1;
462 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
465 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
469 * Do we run "git commit" with "--allow-empty"?
471 static int allow_empty(struct replay_opts *opts, struct commit *commit)
473 int index_unchanged, empty_commit;
478 * (1) we do not allow empty at all and error out.
480 * (2) we allow ones that were initially empty, but
481 * forbid the ones that become empty;
485 if (!opts->allow_empty)
486 return 0; /* let "git commit" barf as necessary */
488 index_unchanged = is_index_unchanged();
489 if (index_unchanged < 0)
490 return index_unchanged;
491 if (!index_unchanged)
492 return 0; /* we do not have to say --allow-empty */
494 if (opts->keep_redundant_commits)
497 empty_commit = is_original_commit_empty(commit);
498 if (empty_commit < 0)
506 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
508 unsigned char head[20];
509 struct commit *base, *next, *parent;
510 const char *base_label, *next_label;
511 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
513 struct strbuf msgbuf = STRBUF_INIT;
514 int res, unborn = 0, allow;
516 if (opts->no_commit) {
518 * We do not intend to commit immediately. We just want to
519 * merge the differences in, so let's compute the tree
520 * that represents the "current" state for merge-recursive
523 if (write_cache_as_tree(head, 0, NULL))
524 die (_("Your index file is unmerged."));
526 unborn = get_sha1("HEAD", head);
528 hashcpy(head, EMPTY_TREE_SHA1_BIN);
529 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
530 return error_dirty_index(opts);
534 if (!commit->parents) {
537 else if (commit->parents->next) {
538 /* Reverting or cherry-picking a merge commit */
540 struct commit_list *p;
543 return error(_("Commit %s is a merge but no -m option was given."),
544 sha1_to_hex(commit->object.sha1));
546 for (cnt = 1, p = commit->parents;
547 cnt != opts->mainline && p;
550 if (cnt != opts->mainline || !p)
551 return error(_("Commit %s does not have parent %d"),
552 sha1_to_hex(commit->object.sha1), opts->mainline);
554 } else if (0 < opts->mainline)
555 return error(_("Mainline was specified but commit %s is not a merge."),
556 sha1_to_hex(commit->object.sha1));
558 parent = commit->parents->item;
560 if (opts->allow_ff &&
561 ((parent && !hashcmp(parent->object.sha1, head)) ||
562 (!parent && unborn)))
563 return fast_forward_to(commit->object.sha1, head, unborn, opts);
565 if (parent && parse_commit(parent) < 0)
566 /* TRANSLATORS: The first %s will be "revert" or
567 "cherry-pick", the second %s a SHA1 */
568 return error(_("%s: cannot parse parent commit %s"),
569 action_name(opts), sha1_to_hex(parent->object.sha1));
571 if (get_message(commit, &msg) != 0)
572 return error(_("Cannot get commit message for %s"),
573 sha1_to_hex(commit->object.sha1));
576 * "commit" is an existing commit. We would want to apply
577 * the difference it introduces since its first parent "prev"
578 * on top of the current HEAD if we are cherry-pick. Or the
579 * reverse of it if we are revert.
582 defmsg = git_pathdup("MERGE_MSG");
584 if (opts->action == REPLAY_REVERT) {
586 base_label = msg.label;
588 next_label = msg.parent_label;
589 strbuf_addstr(&msgbuf, "Revert \"");
590 strbuf_addstr(&msgbuf, msg.subject);
591 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
592 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
594 if (commit->parents && commit->parents->next) {
595 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
596 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
598 strbuf_addstr(&msgbuf, ".\n");
603 base_label = msg.parent_label;
605 next_label = msg.label;
608 * Append the commit log message to msgbuf; it starts
609 * after the tree, parent, author, committer
610 * information followed by "\n\n".
612 p = strstr(msg.message, "\n\n");
615 strbuf_addstr(&msgbuf, p);
618 if (opts->record_origin) {
619 if (!has_conforming_footer(&msgbuf, NULL, 0))
620 strbuf_addch(&msgbuf, '\n');
621 strbuf_addstr(&msgbuf, cherry_picked_prefix);
622 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
623 strbuf_addstr(&msgbuf, ")\n");
627 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
628 res = do_recursive_merge(base, next, base_label, next_label,
629 head, &msgbuf, opts);
630 write_message(&msgbuf, defmsg);
632 struct commit_list *common = NULL;
633 struct commit_list *remotes = NULL;
635 write_message(&msgbuf, defmsg);
637 commit_list_insert(base, &common);
638 commit_list_insert(next, &remotes);
639 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
640 common, sha1_to_hex(head), remotes);
641 free_commit_list(common);
642 free_commit_list(remotes);
646 * If the merge was clean or if it failed due to conflict, we write
647 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
648 * However, if the merge did not even start, then we don't want to
651 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
652 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
653 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
654 write_cherry_pick_head(commit, "REVERT_HEAD");
657 error(opts->action == REPLAY_REVERT
658 ? _("could not revert %s... %s")
659 : _("could not apply %s... %s"),
660 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
662 print_advice(res == 1, opts);
663 rerere(opts->allow_rerere_auto);
667 if (opts->skip_empty && is_index_unchanged() == 1) {
669 warning(_("skipping %s... %s"),
670 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
674 allow = allow_empty(opts, commit);
679 if (!opts->no_commit)
680 res = run_git_commit(defmsg, opts, allow);
682 if (!res && opts->action == REPLAY_PICK) {
683 unsigned char to[20];
685 if (read_ref("HEAD", to))
688 add_rewritten(&rewritten, commit->object.sha1, to);
697 static void prepare_revs(struct replay_opts *opts)
700 * picking (but not reverting) ranges (but not individual revisions)
701 * should be done in reverse
703 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
704 opts->revs->reverse ^= 1;
706 if (prepare_revision_walk(opts->revs))
707 die(_("revision walk setup failed"));
709 if (!opts->revs->commits && !opts->quiet)
710 error(_("empty commit set passed"));
713 static void read_and_refresh_cache(struct replay_opts *opts)
715 static struct lock_file index_lock;
716 int index_fd = hold_locked_index(&index_lock, 0);
717 if (read_index_preload(&the_index, NULL) < 0)
718 die(_("git %s: failed to read the index"), action_name(opts));
719 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
720 if (the_index.cache_changed) {
721 if (write_index(&the_index, index_fd) ||
722 commit_locked_index(&index_lock))
723 die(_("git %s: failed to refresh the index"), action_name(opts));
725 rollback_lock_file(&index_lock);
728 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
729 struct replay_opts *opts)
731 struct commit_list *cur = NULL;
732 const char *sha1_abbrev = NULL;
733 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
737 for (cur = todo_list; cur; cur = cur->next) {
738 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
739 subject_len = find_commit_subject(cur->item->buffer, &subject);
740 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
741 subject_len, subject);
746 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
748 unsigned char commit_sha1[20];
749 enum replay_action action;
750 char *end_of_object_name;
751 int saved, status, padding;
753 if (starts_with(bol, "pick")) {
754 action = REPLAY_PICK;
755 bol += strlen("pick");
756 } else if (starts_with(bol, "revert")) {
757 action = REPLAY_REVERT;
758 bol += strlen("revert");
762 /* Eat up extra spaces/ tabs before object name */
763 padding = strspn(bol, " \t");
768 end_of_object_name = bol + strcspn(bol, " \t\n");
769 saved = *end_of_object_name;
770 *end_of_object_name = '\0';
771 status = get_sha1(bol, commit_sha1);
772 *end_of_object_name = saved;
775 * Verify that the action matches up with the one in
776 * opts; we don't support arbitrary instructions
778 if (action != opts->action) {
779 const char *action_str;
780 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
781 error(_("Cannot %s during a %s"), action_str, action_name(opts));
788 return lookup_commit_reference(commit_sha1);
791 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
792 struct replay_opts *opts)
794 struct commit_list **next = todo_list;
795 struct commit *commit;
799 for (i = 1; *p; i++) {
800 char *eol = strchrnul(p, '\n');
801 commit = parse_insn_line(p, eol, opts);
803 return error(_("Could not parse line %d."), i);
804 next = commit_list_append(commit, next);
805 p = *eol ? eol + 1 : eol;
808 return error(_("No commits parsed."));
812 static void read_populate_todo(struct commit_list **todo_list,
813 struct replay_opts *opts)
815 const char *todo_file = git_path(SEQ_TODO_FILE);
816 struct strbuf buf = STRBUF_INIT;
819 fd = open(todo_file, O_RDONLY);
821 die_errno(_("Could not open %s"), todo_file);
822 if (strbuf_read(&buf, fd, 0) < 0) {
824 strbuf_release(&buf);
825 die(_("Could not read %s."), todo_file);
829 res = parse_insn_buffer(buf.buf, todo_list, opts);
830 strbuf_release(&buf);
832 die(_("Unusable instruction sheet: %s"), todo_file);
835 static int populate_opts_cb(const char *key, const char *value, void *data)
837 struct replay_opts *opts = data;
842 else if (!strcmp(key, "options.no-commit"))
843 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
844 else if (!strcmp(key, "options.edit"))
845 opts->edit = git_config_bool_or_int(key, value, &error_flag);
846 else if (!strcmp(key, "options.signoff"))
847 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
848 else if (!strcmp(key, "options.record-origin"))
849 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
850 else if (!strcmp(key, "options.allow-ff"))
851 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
852 else if (!strcmp(key, "options.mainline"))
853 opts->mainline = git_config_int(key, value);
854 else if (!strcmp(key, "options.strategy"))
855 git_config_string(&opts->strategy, key, value);
856 else if (!strcmp(key, "options.gpg-sign"))
857 git_config_string(&opts->gpg_sign, key, value);
858 else if (!strcmp(key, "options.strategy-option")) {
859 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
860 opts->xopts[opts->xopts_nr++] = xstrdup(value);
861 } else if (!strcmp(key, "options.allow-rerere-auto"))
862 opts->allow_rerere_auto = git_config_int(key, value);
863 else if (!strcmp(key, "options.action-name"))
864 git_config_string(&opts->action_name, key, value);
866 return error(_("Invalid key: %s"), key);
869 return error(_("Invalid value for %s: %s"), key, value);
874 static void read_populate_opts(struct replay_opts **opts_ptr)
876 const char *opts_file = git_path(SEQ_OPTS_FILE);
878 if (!file_exists(opts_file))
880 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
881 die(_("Malformed options sheet: %s"), opts_file);
884 static void walk_revs_populate_todo(struct commit_list **todo_list,
885 struct replay_opts *opts)
887 struct commit *commit;
888 struct commit_list **next;
893 while ((commit = get_revision(opts->revs)))
894 next = commit_list_append(commit, next);
897 static int create_seq_dir(void)
899 const char *seq_dir = git_path(SEQ_DIR);
901 if (file_exists(seq_dir)) {
902 error(_("a cherry-pick or revert is already in progress"));
903 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
906 else if (mkdir(seq_dir, 0777) < 0)
907 die_errno(_("Could not create sequencer directory %s"), seq_dir);
911 static void save_head(const char *head)
913 const char *head_file = git_path(SEQ_HEAD_FILE);
914 static struct lock_file head_lock;
915 struct strbuf buf = STRBUF_INIT;
918 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
919 strbuf_addf(&buf, "%s\n", head);
920 if (write_in_full(fd, buf.buf, buf.len) < 0)
921 die_errno(_("Could not write to %s"), head_file);
922 if (commit_lock_file(&head_lock) < 0)
923 die(_("Error wrapping up %s."), head_file);
926 static int reset_for_rollback(const unsigned char *sha1)
928 const char *argv[4]; /* reset --merge <arg> + NULL */
931 argv[2] = sha1_to_hex(sha1);
933 return run_command_v_opt(argv, RUN_GIT_CMD);
936 static int rollback_single_pick(void)
938 unsigned char head_sha1[20];
940 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
941 !file_exists(git_path("REVERT_HEAD")))
942 return error(_("no cherry-pick or revert in progress"));
943 if (read_ref_full("HEAD", head_sha1, 0, NULL))
944 return error(_("cannot resolve HEAD"));
945 if (is_null_sha1(head_sha1))
946 return error(_("cannot abort from a branch yet to be born"));
947 return reset_for_rollback(head_sha1);
950 static int sequencer_rollback(struct replay_opts *opts)
952 const char *filename;
954 unsigned char sha1[20];
955 struct strbuf buf = STRBUF_INIT;
956 struct string_list merge_rr = STRING_LIST_INIT_DUP;
958 if (setup_rerere(&merge_rr, 0) >= 0) {
959 rerere_clear(&merge_rr);
960 string_list_clear(&merge_rr, 1);
963 filename = git_path(SEQ_HEAD_FILE);
964 f = fopen(filename, "r");
965 if (!f && errno == ENOENT) {
967 * There is no multiple-cherry-pick in progress.
968 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
969 * a single-cherry-pick in progress, abort that.
971 return rollback_single_pick();
974 return error(_("cannot open %s: %s"), filename,
976 if (strbuf_getline(&buf, f, '\n')) {
977 error(_("cannot read %s: %s"), filename, ferror(f) ?
978 strerror(errno) : _("unexpected end of file"));
983 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
984 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
988 if (reset_for_rollback(sha1))
990 remove_sequencer_state();
991 strbuf_release(&buf);
994 strbuf_release(&buf);
998 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
1000 const char *todo_file = git_path(SEQ_TODO_FILE);
1001 static struct lock_file todo_lock;
1002 struct strbuf buf = STRBUF_INIT;
1005 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
1006 if (format_todo(&buf, todo_list, opts) < 0)
1007 die(_("Could not format %s."), todo_file);
1008 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1009 strbuf_release(&buf);
1010 die_errno(_("Could not write to %s"), todo_file);
1012 if (commit_lock_file(&todo_lock) < 0) {
1013 strbuf_release(&buf);
1014 die(_("Error wrapping up %s."), todo_file);
1016 strbuf_release(&buf);
1019 static void save_opts(struct replay_opts *opts)
1021 const char *opts_file = git_path(SEQ_OPTS_FILE);
1023 if (opts->no_commit)
1024 git_config_set_in_file(opts_file, "options.no-commit", "true");
1026 git_config_set_in_file(opts_file, "options.edit", "true");
1028 git_config_set_in_file(opts_file, "options.signoff", "true");
1029 if (opts->record_origin)
1030 git_config_set_in_file(opts_file, "options.record-origin", "true");
1032 git_config_set_in_file(opts_file, "options.allow-ff", "true");
1033 if (opts->mainline) {
1034 struct strbuf buf = STRBUF_INIT;
1035 strbuf_addf(&buf, "%d", opts->mainline);
1036 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
1037 strbuf_release(&buf);
1040 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
1042 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
1045 for (i = 0; i < opts->xopts_nr; i++)
1046 git_config_set_multivar_in_file(opts_file,
1047 "options.strategy-option",
1048 opts->xopts[i], "^$", 0);
1050 if (opts->allow_rerere_auto) {
1051 struct strbuf buf = STRBUF_INIT;
1052 strbuf_addf(&buf, "%d", opts->allow_rerere_auto);
1053 git_config_set_in_file(opts_file, "options.allow-rerere-auto", buf.buf);
1054 strbuf_release(&buf);
1056 if (opts->action_name)
1057 git_config_set_in_file(opts_file, "options.action-name", opts->action_name);
1060 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1062 struct commit_list *cur;
1065 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1067 assert(!(opts->signoff || opts->no_commit ||
1068 opts->record_origin || opts->edit));
1069 read_and_refresh_cache(opts);
1071 for (cur = todo_list; cur; cur = cur->next) {
1072 save_todo(cur, opts);
1073 res = do_pick_commit(cur->item, opts);
1075 if (opts->action == REPLAY_PICK)
1076 store_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1084 * Sequence of picks finished successfully; cleanup by
1085 * removing the .git/sequencer directory
1087 remove_sequencer_state();
1091 static int continue_single_pick(void)
1093 const char *argv[] = { "commit", NULL };
1095 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1096 !file_exists(git_path("REVERT_HEAD")))
1097 return error(_("no cherry-pick or revert in progress"));
1098 return run_command_v_opt(argv, RUN_GIT_CMD);
1101 static int sequencer_continue(struct replay_opts *opts, int skip)
1103 struct commit_list *todo_list = NULL;
1105 if (!file_exists(git_path(SEQ_TODO_FILE)))
1106 return continue_single_pick();
1107 read_populate_opts(&opts);
1108 read_populate_todo(&todo_list, opts);
1109 if (opts->action == REPLAY_PICK)
1110 load_rewritten(&rewritten, git_path(SEQ_REWR_FILE));
1112 /* Verify that the conflict has been resolved */
1113 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1114 file_exists(git_path("REVERT_HEAD"))) {
1115 int ret = continue_single_pick();
1119 if (index_differs_from("HEAD", 0))
1120 return error_dirty_index(opts);
1121 if (opts->action == REPLAY_PICK && !skip) {
1122 unsigned char to[20];
1123 if (!read_ref("HEAD", to))
1124 add_rewritten(&rewritten, todo_list->item->object.sha1, to);
1126 todo_list = todo_list->next;
1127 return pick_commits(todo_list, opts);
1130 static int sequencer_skip(struct replay_opts *opts)
1132 const char *argv[3]; /* reset --hard + NULL */
1133 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1136 if (setup_rerere(&merge_rr, 0) >= 0) {
1137 rerere_clear(&merge_rr);
1138 string_list_clear(&merge_rr, 1);
1144 ret = run_command_v_opt(argv, RUN_GIT_CMD);
1151 return sequencer_continue(opts, 1);
1154 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1157 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1158 ret = do_pick_commit(cmit, opts);
1165 int sequencer_pick_revisions(struct replay_opts *opts)
1167 struct commit_list *todo_list = NULL;
1168 unsigned char sha1[20];
1171 if (opts->subcommand == REPLAY_NONE)
1174 read_and_refresh_cache(opts);
1177 * Decide what to do depending on the arguments; a fresh
1178 * cherry-pick should be handled differently from an existing
1179 * one that is being continued
1181 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1182 remove_sequencer_state();
1185 if (opts->subcommand == REPLAY_ROLLBACK)
1186 return sequencer_rollback(opts);
1187 if (opts->subcommand == REPLAY_CONTINUE)
1188 return sequencer_continue(opts, 0);
1189 if (opts->subcommand == REPLAY_SKIP)
1190 return sequencer_skip(opts);
1192 for (i = 0; i < opts->revs->pending.nr; i++) {
1193 unsigned char sha1[20];
1194 const char *name = opts->revs->pending.objects[i].name;
1196 /* This happens when using --stdin. */
1200 if (!get_sha1(name, sha1)) {
1201 if (!lookup_commit_reference_gently(sha1, 1)) {
1202 enum object_type type = sha1_object_info(sha1, NULL);
1203 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1206 die(_("%s: bad revision"), name);
1210 * If we were called as "git cherry-pick <commit>", just
1211 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1212 * REVERT_HEAD, and don't touch the sequencer state.
1213 * This means it is possible to cherry-pick in the middle
1214 * of a cherry-pick sequence.
1216 if (opts->revs->cmdline.nr == 1 &&
1217 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1218 opts->revs->no_walk &&
1219 !opts->revs->cmdline.rev->flags) {
1220 struct commit *cmit;
1221 if (prepare_revision_walk(opts->revs))
1222 die(_("revision walk setup failed"));
1223 cmit = get_revision(opts->revs);
1224 if (!cmit || get_revision(opts->revs))
1225 die("BUG: expected exactly one commit from walk");
1226 return single_pick(cmit, opts);
1230 * Start a new cherry-pick/ revert sequence; but
1231 * first, make sure that an existing one isn't in
1235 walk_revs_populate_todo(&todo_list, opts);
1236 if (create_seq_dir() < 0)
1238 if (get_sha1("HEAD", sha1)) {
1239 if (opts->action == REPLAY_REVERT)
1240 return error(_("Can't revert as initial commit"));
1241 return error(_("Can't cherry-pick into empty head"));
1243 save_head(sha1_to_hex(sha1));
1245 return pick_commits(todo_list, opts);
1248 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1250 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1251 struct strbuf sob = STRBUF_INIT;
1254 strbuf_addstr(&sob, sign_off_header);
1255 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1256 getenv("GIT_COMMITTER_EMAIL")));
1257 strbuf_addch(&sob, '\n');
1260 * If the whole message buffer is equal to the sob, pretend that we
1261 * found a conforming footer with a matching sob
1263 if (msgbuf->len - ignore_footer == sob.len &&
1264 !strncmp(msgbuf->buf, sob.buf, sob.len))
1267 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1270 const char *append_newlines = NULL;
1271 size_t len = msgbuf->len - ignore_footer;
1275 * The buffer is completely empty. Leave foom for
1276 * the title and body to be filled in by the user.
1278 append_newlines = "\n\n";
1279 } else if (msgbuf->buf[len - 1] != '\n') {
1281 * Incomplete line. Complete the line and add a
1282 * blank one so that there is an empty line between
1283 * the message body and the sob.
1285 append_newlines = "\n\n";
1286 } else if (len == 1) {
1288 * Buffer contains a single newline. Add another
1289 * so that we leave room for the title and body.
1291 append_newlines = "\n";
1292 } else if (msgbuf->buf[len - 2] != '\n') {
1294 * Buffer ends with a single newline. Add another
1295 * so that there is an empty line between the message
1298 append_newlines = "\n";
1299 } /* else, the buffer already ends with two newlines. */
1301 if (append_newlines)
1302 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1303 append_newlines, strlen(append_newlines));
1306 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1307 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1310 strbuf_release(&sob);