Merge branch 'sk/mingw-main'
[git.git] / sequencer.c
blobcdd30c07379621561edf7b7fb23c5607571edf4f
1 #include "cache.h"
2 #include "sequencer.h"
3 #include "dir.h"
4 #include "object.h"
5 #include "commit.h"
6 #include "tag.h"
7 #include "run-command.h"
8 #include "exec_cmd.h"
9 #include "utf8.h"
10 #include "cache-tree.h"
11 #include "diff.h"
12 #include "revision.h"
13 #include "rerere.h"
14 #include "merge-recursive.h"
15 #include "refs.h"
16 #include "argv-array.h"
18 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
20 const char sign_off_header[] = "Signed-off-by: ";
21 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
23 static int is_rfc2822_line(const char *buf, int len)
25 int i;
27 for (i = 0; i < len; i++) {
28 int ch = buf[i];
29 if (ch == ':')
30 return 1;
31 if (!isalnum(ch) && ch != '-')
32 break;
35 return 0;
38 static int is_cherry_picked_from_line(const char *buf, int len)
41 * We only care that it looks roughly like (cherry picked from ...)
43 return len > strlen(cherry_picked_prefix) + 1 &&
44 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
48 * Returns 0 for non-conforming footer
49 * Returns 1 for conforming footer
50 * Returns 2 when sob exists within conforming footer
51 * Returns 3 when sob exists within conforming footer as last entry
53 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
54 int ignore_footer)
56 char prev;
57 int i, k;
58 int len = sb->len - ignore_footer;
59 const char *buf = sb->buf;
60 int found_sob = 0;
62 /* footer must end with newline */
63 if (!len || buf[len - 1] != '\n')
64 return 0;
66 prev = '\0';
67 for (i = len - 1; i > 0; i--) {
68 char ch = buf[i];
69 if (prev == '\n' && ch == '\n') /* paragraph break */
70 break;
71 prev = ch;
74 /* require at least one blank line */
75 if (prev != '\n' || buf[i] != '\n')
76 return 0;
78 /* advance to start of last paragraph */
79 while (i < len - 1 && buf[i] == '\n')
80 i++;
82 for (; i < len; i = k) {
83 int found_rfc2822;
85 for (k = i; k < len && buf[k] != '\n'; k++)
86 ; /* do nothing */
87 k++;
89 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
90 if (found_rfc2822 && sob &&
91 !strncmp(buf + i, sob->buf, sob->len))
92 found_sob = k;
94 if (!(found_rfc2822 ||
95 is_cherry_picked_from_line(buf + i, k - i - 1)))
96 return 0;
98 if (found_sob == i)
99 return 3;
100 if (found_sob)
101 return 2;
102 return 1;
105 static void remove_sequencer_state(void)
107 struct strbuf seq_dir = STRBUF_INIT;
109 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
110 remove_dir_recursively(&seq_dir, 0);
111 strbuf_release(&seq_dir);
114 static const char *action_name(const struct replay_opts *opts)
116 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
119 struct commit_message {
120 char *parent_label;
121 const char *label;
122 const char *subject;
123 const char *message;
126 static int get_message(struct commit *commit, struct commit_message *out)
128 const char *abbrev, *subject;
129 int abbrev_len, subject_len;
130 char *q;
132 if (!git_commit_encoding)
133 git_commit_encoding = "UTF-8";
135 out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
136 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
137 abbrev_len = strlen(abbrev);
139 subject_len = find_commit_subject(out->message, &subject);
141 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
142 strlen("... ") + subject_len + 1);
143 q = out->parent_label;
144 q = mempcpy(q, "parent of ", strlen("parent of "));
145 out->label = q;
146 q = mempcpy(q, abbrev, abbrev_len);
147 q = mempcpy(q, "... ", strlen("... "));
148 out->subject = q;
149 q = mempcpy(q, subject, subject_len);
150 *q = '\0';
151 return 0;
154 static void free_message(struct commit *commit, struct commit_message *msg)
156 free(msg->parent_label);
157 unuse_commit_buffer(commit, msg->message);
160 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
162 const char *filename;
163 int fd;
164 struct strbuf buf = STRBUF_INIT;
166 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
168 filename = git_path("%s", pseudoref);
169 fd = open(filename, O_WRONLY | O_CREAT, 0666);
170 if (fd < 0)
171 die_errno(_("Could not open '%s' for writing"), filename);
172 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
173 die_errno(_("Could not write to '%s'"), filename);
174 strbuf_release(&buf);
177 static void print_advice(int show_hint, struct replay_opts *opts)
179 char *msg = getenv("GIT_CHERRY_PICK_HELP");
181 if (msg) {
182 fprintf(stderr, "%s\n", msg);
184 * A conflict has occurred but the porcelain
185 * (typically rebase --interactive) wants to take care
186 * of the commit itself so remove CHERRY_PICK_HEAD
188 unlink(git_path("CHERRY_PICK_HEAD"));
189 return;
192 if (show_hint) {
193 if (opts->no_commit)
194 advise(_("after resolving the conflicts, mark the corrected paths\n"
195 "with 'git add <paths>' or 'git rm <paths>'"));
196 else
197 advise(_("after resolving the conflicts, mark the corrected paths\n"
198 "with 'git add <paths>' or 'git rm <paths>'\n"
199 "and commit the result with 'git commit'"));
203 static void write_message(struct strbuf *msgbuf, const char *filename)
205 static struct lock_file msg_file;
207 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
208 LOCK_DIE_ON_ERROR);
209 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
210 die_errno(_("Could not write to %s"), filename);
211 strbuf_release(msgbuf);
212 if (commit_lock_file(&msg_file) < 0)
213 die(_("Error wrapping up %s"), filename);
216 static struct tree *empty_tree(void)
218 return lookup_tree(EMPTY_TREE_SHA1_BIN);
221 static int error_dirty_index(struct replay_opts *opts)
223 if (read_cache_unmerged())
224 return error_resolve_conflict(action_name(opts));
226 /* Different translation strings for cherry-pick and revert */
227 if (opts->action == REPLAY_PICK)
228 error(_("Your local changes would be overwritten by cherry-pick."));
229 else
230 error(_("Your local changes would be overwritten by revert."));
232 if (advice_commit_before_merge)
233 advise(_("Commit your changes or stash them to proceed."));
234 return -1;
237 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
238 int unborn, struct replay_opts *opts)
240 struct ref_lock *ref_lock;
241 struct strbuf sb = STRBUF_INIT;
242 int ret;
244 read_cache();
245 if (checkout_fast_forward(from, to, 1))
246 exit(128); /* the callee should have complained already */
247 ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
248 0, NULL);
249 if (!ref_lock)
250 return error(_("Failed to lock HEAD during fast_forward_to"));
252 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
253 ret = write_ref_sha1(ref_lock, to, sb.buf);
255 strbuf_release(&sb);
256 return ret;
259 static int do_recursive_merge(struct commit *base, struct commit *next,
260 const char *base_label, const char *next_label,
261 unsigned char *head, struct strbuf *msgbuf,
262 struct replay_opts *opts)
264 struct merge_options o;
265 struct tree *result, *next_tree, *base_tree, *head_tree;
266 int clean, index_fd;
267 const char **xopt;
268 static struct lock_file index_lock;
270 index_fd = hold_locked_index(&index_lock, 1);
272 read_cache();
274 init_merge_options(&o);
275 o.ancestor = base ? base_label : "(empty tree)";
276 o.branch1 = "HEAD";
277 o.branch2 = next ? next_label : "(empty tree)";
279 head_tree = parse_tree_indirect(head);
280 next_tree = next ? next->tree : empty_tree();
281 base_tree = base ? base->tree : empty_tree();
283 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
284 parse_merge_opt(&o, *xopt);
286 clean = merge_trees(&o,
287 head_tree,
288 next_tree, base_tree, &result);
290 if (active_cache_changed &&
291 (write_cache(index_fd, active_cache, active_nr) ||
292 commit_locked_index(&index_lock)))
293 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
294 die(_("%s: Unable to write new index file"), action_name(opts));
295 rollback_lock_file(&index_lock);
297 if (opts->signoff)
298 append_signoff(msgbuf, 0, 0);
300 if (!clean) {
301 int i;
302 strbuf_addstr(msgbuf, "\nConflicts:\n");
303 for (i = 0; i < active_nr;) {
304 const struct cache_entry *ce = active_cache[i++];
305 if (ce_stage(ce)) {
306 strbuf_addch(msgbuf, '\t');
307 strbuf_addstr(msgbuf, ce->name);
308 strbuf_addch(msgbuf, '\n');
309 while (i < active_nr && !strcmp(ce->name,
310 active_cache[i]->name))
311 i++;
316 return !clean;
319 static int is_index_unchanged(void)
321 unsigned char head_sha1[20];
322 struct commit *head_commit;
324 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
325 return error(_("Could not resolve HEAD commit\n"));
327 head_commit = lookup_commit(head_sha1);
330 * If head_commit is NULL, check_commit, called from
331 * lookup_commit, would have indicated that head_commit is not
332 * a commit object already. parse_commit() will return failure
333 * without further complaints in such a case. Otherwise, if
334 * the commit is invalid, parse_commit() will complain. So
335 * there is nothing for us to say here. Just return failure.
337 if (parse_commit(head_commit))
338 return -1;
340 if (!active_cache_tree)
341 active_cache_tree = cache_tree();
343 if (!cache_tree_fully_valid(active_cache_tree))
344 if (cache_tree_update(active_cache_tree,
345 (const struct cache_entry * const *)active_cache,
346 active_nr, 0))
347 return error(_("Unable to update cache tree\n"));
349 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
353 * If we are cherry-pick, and if the merge did not result in
354 * hand-editing, we will hit this commit and inherit the original
355 * author date and name.
356 * If we are revert, or if our cherry-pick results in a hand merge,
357 * we had better say that the current user is responsible for that.
359 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
360 int allow_empty)
362 struct argv_array array;
363 int rc;
365 argv_array_init(&array);
366 argv_array_push(&array, "commit");
367 argv_array_push(&array, "-n");
369 if (opts->gpg_sign)
370 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
371 if (opts->signoff)
372 argv_array_push(&array, "-s");
373 if (!opts->edit) {
374 argv_array_push(&array, "-F");
375 argv_array_push(&array, defmsg);
378 if (allow_empty)
379 argv_array_push(&array, "--allow-empty");
381 if (opts->allow_empty_message)
382 argv_array_push(&array, "--allow-empty-message");
384 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
385 argv_array_clear(&array);
386 return rc;
389 static int is_original_commit_empty(struct commit *commit)
391 const unsigned char *ptree_sha1;
393 if (parse_commit(commit))
394 return error(_("Could not parse commit %s\n"),
395 sha1_to_hex(commit->object.sha1));
396 if (commit->parents) {
397 struct commit *parent = commit->parents->item;
398 if (parse_commit(parent))
399 return error(_("Could not parse parent commit %s\n"),
400 sha1_to_hex(parent->object.sha1));
401 ptree_sha1 = parent->tree->object.sha1;
402 } else {
403 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
406 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
410 * Do we run "git commit" with "--allow-empty"?
412 static int allow_empty(struct replay_opts *opts, struct commit *commit)
414 int index_unchanged, empty_commit;
417 * Three cases:
419 * (1) we do not allow empty at all and error out.
421 * (2) we allow ones that were initially empty, but
422 * forbid the ones that become empty;
424 * (3) we allow both.
426 if (!opts->allow_empty)
427 return 0; /* let "git commit" barf as necessary */
429 index_unchanged = is_index_unchanged();
430 if (index_unchanged < 0)
431 return index_unchanged;
432 if (!index_unchanged)
433 return 0; /* we do not have to say --allow-empty */
435 if (opts->keep_redundant_commits)
436 return 1;
438 empty_commit = is_original_commit_empty(commit);
439 if (empty_commit < 0)
440 return empty_commit;
441 if (!empty_commit)
442 return 0;
443 else
444 return 1;
447 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
449 unsigned char head[20];
450 struct commit *base, *next, *parent;
451 const char *base_label, *next_label;
452 struct commit_message msg = { NULL, NULL, NULL, NULL };
453 char *defmsg = NULL;
454 struct strbuf msgbuf = STRBUF_INIT;
455 int res, unborn = 0, allow;
457 if (opts->no_commit) {
459 * We do not intend to commit immediately. We just want to
460 * merge the differences in, so let's compute the tree
461 * that represents the "current" state for merge-recursive
462 * to work on.
464 if (write_cache_as_tree(head, 0, NULL))
465 die (_("Your index file is unmerged."));
466 } else {
467 unborn = get_sha1("HEAD", head);
468 if (unborn)
469 hashcpy(head, EMPTY_TREE_SHA1_BIN);
470 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
471 return error_dirty_index(opts);
473 discard_cache();
475 if (!commit->parents) {
476 parent = NULL;
478 else if (commit->parents->next) {
479 /* Reverting or cherry-picking a merge commit */
480 int cnt;
481 struct commit_list *p;
483 if (!opts->mainline)
484 return error(_("Commit %s is a merge but no -m option was given."),
485 sha1_to_hex(commit->object.sha1));
487 for (cnt = 1, p = commit->parents;
488 cnt != opts->mainline && p;
489 cnt++)
490 p = p->next;
491 if (cnt != opts->mainline || !p)
492 return error(_("Commit %s does not have parent %d"),
493 sha1_to_hex(commit->object.sha1), opts->mainline);
494 parent = p->item;
495 } else if (0 < opts->mainline)
496 return error(_("Mainline was specified but commit %s is not a merge."),
497 sha1_to_hex(commit->object.sha1));
498 else
499 parent = commit->parents->item;
501 if (opts->allow_ff &&
502 ((parent && !hashcmp(parent->object.sha1, head)) ||
503 (!parent && unborn)))
504 return fast_forward_to(commit->object.sha1, head, unborn, opts);
506 if (parent && parse_commit(parent) < 0)
507 /* TRANSLATORS: The first %s will be "revert" or
508 "cherry-pick", the second %s a SHA1 */
509 return error(_("%s: cannot parse parent commit %s"),
510 action_name(opts), sha1_to_hex(parent->object.sha1));
512 if (get_message(commit, &msg) != 0)
513 return error(_("Cannot get commit message for %s"),
514 sha1_to_hex(commit->object.sha1));
517 * "commit" is an existing commit. We would want to apply
518 * the difference it introduces since its first parent "prev"
519 * on top of the current HEAD if we are cherry-pick. Or the
520 * reverse of it if we are revert.
523 defmsg = git_pathdup("MERGE_MSG");
525 if (opts->action == REPLAY_REVERT) {
526 base = commit;
527 base_label = msg.label;
528 next = parent;
529 next_label = msg.parent_label;
530 strbuf_addstr(&msgbuf, "Revert \"");
531 strbuf_addstr(&msgbuf, msg.subject);
532 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
533 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
535 if (commit->parents && commit->parents->next) {
536 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
537 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
539 strbuf_addstr(&msgbuf, ".\n");
540 } else {
541 const char *p;
543 base = parent;
544 base_label = msg.parent_label;
545 next = commit;
546 next_label = msg.label;
549 * Append the commit log message to msgbuf; it starts
550 * after the tree, parent, author, committer
551 * information followed by "\n\n".
553 p = strstr(msg.message, "\n\n");
554 if (p) {
555 p += 2;
556 strbuf_addstr(&msgbuf, p);
559 if (opts->record_origin) {
560 if (!has_conforming_footer(&msgbuf, NULL, 0))
561 strbuf_addch(&msgbuf, '\n');
562 strbuf_addstr(&msgbuf, cherry_picked_prefix);
563 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
564 strbuf_addstr(&msgbuf, ")\n");
568 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
569 res = do_recursive_merge(base, next, base_label, next_label,
570 head, &msgbuf, opts);
571 write_message(&msgbuf, defmsg);
572 } else {
573 struct commit_list *common = NULL;
574 struct commit_list *remotes = NULL;
576 write_message(&msgbuf, defmsg);
578 commit_list_insert(base, &common);
579 commit_list_insert(next, &remotes);
580 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
581 common, sha1_to_hex(head), remotes);
582 free_commit_list(common);
583 free_commit_list(remotes);
587 * If the merge was clean or if it failed due to conflict, we write
588 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
589 * However, if the merge did not even start, then we don't want to
590 * write it at all.
592 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
593 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
594 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
595 write_cherry_pick_head(commit, "REVERT_HEAD");
597 if (res) {
598 error(opts->action == REPLAY_REVERT
599 ? _("could not revert %s... %s")
600 : _("could not apply %s... %s"),
601 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
602 msg.subject);
603 print_advice(res == 1, opts);
604 rerere(opts->allow_rerere_auto);
605 goto leave;
608 allow = allow_empty(opts, commit);
609 if (allow < 0) {
610 res = allow;
611 goto leave;
613 if (!opts->no_commit)
614 res = run_git_commit(defmsg, opts, allow);
616 leave:
617 free_message(commit, &msg);
618 free(defmsg);
620 return res;
623 static void prepare_revs(struct replay_opts *opts)
626 * picking (but not reverting) ranges (but not individual revisions)
627 * should be done in reverse
629 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
630 opts->revs->reverse ^= 1;
632 if (prepare_revision_walk(opts->revs))
633 die(_("revision walk setup failed"));
635 if (!opts->revs->commits)
636 die(_("empty commit set passed"));
639 static void read_and_refresh_cache(struct replay_opts *opts)
641 static struct lock_file index_lock;
642 int index_fd = hold_locked_index(&index_lock, 0);
643 if (read_index_preload(&the_index, NULL) < 0)
644 die(_("git %s: failed to read the index"), action_name(opts));
645 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
646 if (the_index.cache_changed) {
647 if (write_index(&the_index, index_fd) ||
648 commit_locked_index(&index_lock))
649 die(_("git %s: failed to refresh the index"), action_name(opts));
651 rollback_lock_file(&index_lock);
654 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
655 struct replay_opts *opts)
657 struct commit_list *cur = NULL;
658 const char *sha1_abbrev = NULL;
659 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
660 const char *subject;
661 int subject_len;
663 for (cur = todo_list; cur; cur = cur->next) {
664 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
665 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
666 subject_len = find_commit_subject(commit_buffer, &subject);
667 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
668 subject_len, subject);
669 unuse_commit_buffer(cur->item, commit_buffer);
671 return 0;
674 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
676 unsigned char commit_sha1[20];
677 enum replay_action action;
678 char *end_of_object_name;
679 int saved, status, padding;
681 if (starts_with(bol, "pick")) {
682 action = REPLAY_PICK;
683 bol += strlen("pick");
684 } else if (starts_with(bol, "revert")) {
685 action = REPLAY_REVERT;
686 bol += strlen("revert");
687 } else
688 return NULL;
690 /* Eat up extra spaces/ tabs before object name */
691 padding = strspn(bol, " \t");
692 if (!padding)
693 return NULL;
694 bol += padding;
696 end_of_object_name = bol + strcspn(bol, " \t\n");
697 saved = *end_of_object_name;
698 *end_of_object_name = '\0';
699 status = get_sha1(bol, commit_sha1);
700 *end_of_object_name = saved;
703 * Verify that the action matches up with the one in
704 * opts; we don't support arbitrary instructions
706 if (action != opts->action) {
707 const char *action_str;
708 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
709 error(_("Cannot %s during a %s"), action_str, action_name(opts));
710 return NULL;
713 if (status < 0)
714 return NULL;
716 return lookup_commit_reference(commit_sha1);
719 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
720 struct replay_opts *opts)
722 struct commit_list **next = todo_list;
723 struct commit *commit;
724 char *p = buf;
725 int i;
727 for (i = 1; *p; i++) {
728 char *eol = strchrnul(p, '\n');
729 commit = parse_insn_line(p, eol, opts);
730 if (!commit)
731 return error(_("Could not parse line %d."), i);
732 next = commit_list_append(commit, next);
733 p = *eol ? eol + 1 : eol;
735 if (!*todo_list)
736 return error(_("No commits parsed."));
737 return 0;
740 static void read_populate_todo(struct commit_list **todo_list,
741 struct replay_opts *opts)
743 const char *todo_file = git_path(SEQ_TODO_FILE);
744 struct strbuf buf = STRBUF_INIT;
745 int fd, res;
747 fd = open(todo_file, O_RDONLY);
748 if (fd < 0)
749 die_errno(_("Could not open %s"), todo_file);
750 if (strbuf_read(&buf, fd, 0) < 0) {
751 close(fd);
752 strbuf_release(&buf);
753 die(_("Could not read %s."), todo_file);
755 close(fd);
757 res = parse_insn_buffer(buf.buf, todo_list, opts);
758 strbuf_release(&buf);
759 if (res)
760 die(_("Unusable instruction sheet: %s"), todo_file);
763 static int populate_opts_cb(const char *key, const char *value, void *data)
765 struct replay_opts *opts = data;
766 int error_flag = 1;
768 if (!value)
769 error_flag = 0;
770 else if (!strcmp(key, "options.no-commit"))
771 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
772 else if (!strcmp(key, "options.edit"))
773 opts->edit = git_config_bool_or_int(key, value, &error_flag);
774 else if (!strcmp(key, "options.signoff"))
775 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
776 else if (!strcmp(key, "options.record-origin"))
777 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
778 else if (!strcmp(key, "options.allow-ff"))
779 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
780 else if (!strcmp(key, "options.mainline"))
781 opts->mainline = git_config_int(key, value);
782 else if (!strcmp(key, "options.strategy"))
783 git_config_string(&opts->strategy, key, value);
784 else if (!strcmp(key, "options.gpg-sign"))
785 git_config_string(&opts->gpg_sign, key, value);
786 else if (!strcmp(key, "options.strategy-option")) {
787 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
788 opts->xopts[opts->xopts_nr++] = xstrdup(value);
789 } else
790 return error(_("Invalid key: %s"), key);
792 if (!error_flag)
793 return error(_("Invalid value for %s: %s"), key, value);
795 return 0;
798 static void read_populate_opts(struct replay_opts **opts_ptr)
800 const char *opts_file = git_path(SEQ_OPTS_FILE);
802 if (!file_exists(opts_file))
803 return;
804 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
805 die(_("Malformed options sheet: %s"), opts_file);
808 static void walk_revs_populate_todo(struct commit_list **todo_list,
809 struct replay_opts *opts)
811 struct commit *commit;
812 struct commit_list **next;
814 prepare_revs(opts);
816 next = todo_list;
817 while ((commit = get_revision(opts->revs)))
818 next = commit_list_append(commit, next);
821 static int create_seq_dir(void)
823 const char *seq_dir = git_path(SEQ_DIR);
825 if (file_exists(seq_dir)) {
826 error(_("a cherry-pick or revert is already in progress"));
827 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
828 return -1;
830 else if (mkdir(seq_dir, 0777) < 0)
831 die_errno(_("Could not create sequencer directory %s"), seq_dir);
832 return 0;
835 static void save_head(const char *head)
837 const char *head_file = git_path(SEQ_HEAD_FILE);
838 static struct lock_file head_lock;
839 struct strbuf buf = STRBUF_INIT;
840 int fd;
842 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
843 strbuf_addf(&buf, "%s\n", head);
844 if (write_in_full(fd, buf.buf, buf.len) < 0)
845 die_errno(_("Could not write to %s"), head_file);
846 if (commit_lock_file(&head_lock) < 0)
847 die(_("Error wrapping up %s."), head_file);
850 static int reset_for_rollback(const unsigned char *sha1)
852 const char *argv[4]; /* reset --merge <arg> + NULL */
853 argv[0] = "reset";
854 argv[1] = "--merge";
855 argv[2] = sha1_to_hex(sha1);
856 argv[3] = NULL;
857 return run_command_v_opt(argv, RUN_GIT_CMD);
860 static int rollback_single_pick(void)
862 unsigned char head_sha1[20];
864 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
865 !file_exists(git_path("REVERT_HEAD")))
866 return error(_("no cherry-pick or revert in progress"));
867 if (read_ref_full("HEAD", head_sha1, 0, NULL))
868 return error(_("cannot resolve HEAD"));
869 if (is_null_sha1(head_sha1))
870 return error(_("cannot abort from a branch yet to be born"));
871 return reset_for_rollback(head_sha1);
874 static int sequencer_rollback(struct replay_opts *opts)
876 const char *filename;
877 FILE *f;
878 unsigned char sha1[20];
879 struct strbuf buf = STRBUF_INIT;
881 filename = git_path(SEQ_HEAD_FILE);
882 f = fopen(filename, "r");
883 if (!f && errno == ENOENT) {
885 * There is no multiple-cherry-pick in progress.
886 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
887 * a single-cherry-pick in progress, abort that.
889 return rollback_single_pick();
891 if (!f)
892 return error(_("cannot open %s: %s"), filename,
893 strerror(errno));
894 if (strbuf_getline(&buf, f, '\n')) {
895 error(_("cannot read %s: %s"), filename, ferror(f) ?
896 strerror(errno) : _("unexpected end of file"));
897 fclose(f);
898 goto fail;
900 fclose(f);
901 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
902 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
903 filename);
904 goto fail;
906 if (reset_for_rollback(sha1))
907 goto fail;
908 remove_sequencer_state();
909 strbuf_release(&buf);
910 return 0;
911 fail:
912 strbuf_release(&buf);
913 return -1;
916 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
918 const char *todo_file = git_path(SEQ_TODO_FILE);
919 static struct lock_file todo_lock;
920 struct strbuf buf = STRBUF_INIT;
921 int fd;
923 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
924 if (format_todo(&buf, todo_list, opts) < 0)
925 die(_("Could not format %s."), todo_file);
926 if (write_in_full(fd, buf.buf, buf.len) < 0) {
927 strbuf_release(&buf);
928 die_errno(_("Could not write to %s"), todo_file);
930 if (commit_lock_file(&todo_lock) < 0) {
931 strbuf_release(&buf);
932 die(_("Error wrapping up %s."), todo_file);
934 strbuf_release(&buf);
937 static void save_opts(struct replay_opts *opts)
939 const char *opts_file = git_path(SEQ_OPTS_FILE);
941 if (opts->no_commit)
942 git_config_set_in_file(opts_file, "options.no-commit", "true");
943 if (opts->edit)
944 git_config_set_in_file(opts_file, "options.edit", "true");
945 if (opts->signoff)
946 git_config_set_in_file(opts_file, "options.signoff", "true");
947 if (opts->record_origin)
948 git_config_set_in_file(opts_file, "options.record-origin", "true");
949 if (opts->allow_ff)
950 git_config_set_in_file(opts_file, "options.allow-ff", "true");
951 if (opts->mainline) {
952 struct strbuf buf = STRBUF_INIT;
953 strbuf_addf(&buf, "%d", opts->mainline);
954 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
955 strbuf_release(&buf);
957 if (opts->strategy)
958 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
959 if (opts->gpg_sign)
960 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
961 if (opts->xopts) {
962 int i;
963 for (i = 0; i < opts->xopts_nr; i++)
964 git_config_set_multivar_in_file(opts_file,
965 "options.strategy-option",
966 opts->xopts[i], "^$", 0);
970 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
972 struct commit_list *cur;
973 int res;
975 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
976 if (opts->allow_ff)
977 assert(!(opts->signoff || opts->no_commit ||
978 opts->record_origin || opts->edit));
979 read_and_refresh_cache(opts);
981 for (cur = todo_list; cur; cur = cur->next) {
982 save_todo(cur, opts);
983 res = do_pick_commit(cur->item, opts);
984 if (res)
985 return res;
989 * Sequence of picks finished successfully; cleanup by
990 * removing the .git/sequencer directory
992 remove_sequencer_state();
993 return 0;
996 static int continue_single_pick(void)
998 const char *argv[] = { "commit", NULL };
1000 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1001 !file_exists(git_path("REVERT_HEAD")))
1002 return error(_("no cherry-pick or revert in progress"));
1003 return run_command_v_opt(argv, RUN_GIT_CMD);
1006 static int sequencer_continue(struct replay_opts *opts)
1008 struct commit_list *todo_list = NULL;
1010 if (!file_exists(git_path(SEQ_TODO_FILE)))
1011 return continue_single_pick();
1012 read_populate_opts(&opts);
1013 read_populate_todo(&todo_list, opts);
1015 /* Verify that the conflict has been resolved */
1016 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1017 file_exists(git_path("REVERT_HEAD"))) {
1018 int ret = continue_single_pick();
1019 if (ret)
1020 return ret;
1022 if (index_differs_from("HEAD", 0))
1023 return error_dirty_index(opts);
1024 todo_list = todo_list->next;
1025 return pick_commits(todo_list, opts);
1028 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1030 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1031 return do_pick_commit(cmit, opts);
1034 int sequencer_pick_revisions(struct replay_opts *opts)
1036 struct commit_list *todo_list = NULL;
1037 unsigned char sha1[20];
1038 int i;
1040 if (opts->subcommand == REPLAY_NONE)
1041 assert(opts->revs);
1043 read_and_refresh_cache(opts);
1046 * Decide what to do depending on the arguments; a fresh
1047 * cherry-pick should be handled differently from an existing
1048 * one that is being continued
1050 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1051 remove_sequencer_state();
1052 return 0;
1054 if (opts->subcommand == REPLAY_ROLLBACK)
1055 return sequencer_rollback(opts);
1056 if (opts->subcommand == REPLAY_CONTINUE)
1057 return sequencer_continue(opts);
1059 for (i = 0; i < opts->revs->pending.nr; i++) {
1060 unsigned char sha1[20];
1061 const char *name = opts->revs->pending.objects[i].name;
1063 /* This happens when using --stdin. */
1064 if (!strlen(name))
1065 continue;
1067 if (!get_sha1(name, sha1)) {
1068 if (!lookup_commit_reference_gently(sha1, 1)) {
1069 enum object_type type = sha1_object_info(sha1, NULL);
1070 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1072 } else
1073 die(_("%s: bad revision"), name);
1077 * If we were called as "git cherry-pick <commit>", just
1078 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1079 * REVERT_HEAD, and don't touch the sequencer state.
1080 * This means it is possible to cherry-pick in the middle
1081 * of a cherry-pick sequence.
1083 if (opts->revs->cmdline.nr == 1 &&
1084 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1085 opts->revs->no_walk &&
1086 !opts->revs->cmdline.rev->flags) {
1087 struct commit *cmit;
1088 if (prepare_revision_walk(opts->revs))
1089 die(_("revision walk setup failed"));
1090 cmit = get_revision(opts->revs);
1091 if (!cmit || get_revision(opts->revs))
1092 die("BUG: expected exactly one commit from walk");
1093 return single_pick(cmit, opts);
1097 * Start a new cherry-pick/ revert sequence; but
1098 * first, make sure that an existing one isn't in
1099 * progress
1102 walk_revs_populate_todo(&todo_list, opts);
1103 if (create_seq_dir() < 0)
1104 return -1;
1105 if (get_sha1("HEAD", sha1)) {
1106 if (opts->action == REPLAY_REVERT)
1107 return error(_("Can't revert as initial commit"));
1108 return error(_("Can't cherry-pick into empty head"));
1110 save_head(sha1_to_hex(sha1));
1111 save_opts(opts);
1112 return pick_commits(todo_list, opts);
1115 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1117 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1118 struct strbuf sob = STRBUF_INIT;
1119 int has_footer;
1121 strbuf_addstr(&sob, sign_off_header);
1122 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1123 getenv("GIT_COMMITTER_EMAIL")));
1124 strbuf_addch(&sob, '\n');
1127 * If the whole message buffer is equal to the sob, pretend that we
1128 * found a conforming footer with a matching sob
1130 if (msgbuf->len - ignore_footer == sob.len &&
1131 !strncmp(msgbuf->buf, sob.buf, sob.len))
1132 has_footer = 3;
1133 else
1134 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1136 if (!has_footer) {
1137 const char *append_newlines = NULL;
1138 size_t len = msgbuf->len - ignore_footer;
1140 if (!len) {
1142 * The buffer is completely empty. Leave foom for
1143 * the title and body to be filled in by the user.
1145 append_newlines = "\n\n";
1146 } else if (msgbuf->buf[len - 1] != '\n') {
1148 * Incomplete line. Complete the line and add a
1149 * blank one so that there is an empty line between
1150 * the message body and the sob.
1152 append_newlines = "\n\n";
1153 } else if (len == 1) {
1155 * Buffer contains a single newline. Add another
1156 * so that we leave room for the title and body.
1158 append_newlines = "\n";
1159 } else if (msgbuf->buf[len - 2] != '\n') {
1161 * Buffer ends with a single newline. Add another
1162 * so that there is an empty line between the message
1163 * body and the sob.
1165 append_newlines = "\n";
1166 } /* else, the buffer already ends with two newlines. */
1168 if (append_newlines)
1169 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1170 append_newlines, strlen(append_newlines));
1173 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1174 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1175 sob.buf, sob.len);
1177 strbuf_release(&sob);