sequencer: preserve commit messages
[git/mingw.git] / sequencer.c
blob8b735cdd04fceef13d85b3a5147616e18ca9307d
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(1); /* the callee should have complained already */
247 ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
248 0, NULL);
249 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
250 ret = write_ref_sha1(ref_lock, to, sb.buf);
251 strbuf_release(&sb);
252 return ret;
255 static int do_recursive_merge(struct commit *base, struct commit *next,
256 const char *base_label, const char *next_label,
257 unsigned char *head, struct strbuf *msgbuf,
258 struct replay_opts *opts)
260 struct merge_options o;
261 struct tree *result, *next_tree, *base_tree, *head_tree;
262 int clean, index_fd;
263 const char **xopt;
264 static struct lock_file index_lock;
266 index_fd = hold_locked_index(&index_lock, 1);
268 read_cache();
270 init_merge_options(&o);
271 o.ancestor = base ? base_label : "(empty tree)";
272 o.branch1 = "HEAD";
273 o.branch2 = next ? next_label : "(empty tree)";
275 head_tree = parse_tree_indirect(head);
276 next_tree = next ? next->tree : empty_tree();
277 base_tree = base ? base->tree : empty_tree();
279 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
280 parse_merge_opt(&o, *xopt);
282 clean = merge_trees(&o,
283 head_tree,
284 next_tree, base_tree, &result);
286 if (active_cache_changed &&
287 (write_cache(index_fd, active_cache, active_nr) ||
288 commit_locked_index(&index_lock)))
289 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
290 die(_("%s: Unable to write new index file"), action_name(opts));
291 rollback_lock_file(&index_lock);
293 if (opts->signoff)
294 append_signoff(msgbuf, 0, 0);
296 if (!clean) {
297 int i;
298 strbuf_addstr(msgbuf, "\nConflicts:\n");
299 for (i = 0; i < active_nr;) {
300 const struct cache_entry *ce = active_cache[i++];
301 if (ce_stage(ce)) {
302 strbuf_addch(msgbuf, '\t');
303 strbuf_addstr(msgbuf, ce->name);
304 strbuf_addch(msgbuf, '\n');
305 while (i < active_nr && !strcmp(ce->name,
306 active_cache[i]->name))
307 i++;
312 return !clean;
315 static int is_index_unchanged(void)
317 unsigned char head_sha1[20];
318 struct commit *head_commit;
320 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
321 return error(_("Could not resolve HEAD commit\n"));
323 head_commit = lookup_commit(head_sha1);
326 * If head_commit is NULL, check_commit, called from
327 * lookup_commit, would have indicated that head_commit is not
328 * a commit object already. parse_commit() will return failure
329 * without further complaints in such a case. Otherwise, if
330 * the commit is invalid, parse_commit() will complain. So
331 * there is nothing for us to say here. Just return failure.
333 if (parse_commit(head_commit))
334 return -1;
336 if (!active_cache_tree)
337 active_cache_tree = cache_tree();
339 if (!cache_tree_fully_valid(active_cache_tree))
340 if (cache_tree_update(active_cache_tree,
341 (const struct cache_entry * const *)active_cache,
342 active_nr, 0))
343 return error(_("Unable to update cache tree\n"));
345 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
349 * If we are cherry-pick, and if the merge did not result in
350 * hand-editing, we will hit this commit and inherit the original
351 * author date and name.
352 * If we are revert, or if our cherry-pick results in a hand merge,
353 * we had better say that the current user is responsible for that.
355 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
356 int allow_empty)
358 struct argv_array array;
359 int rc;
360 char *gpg_sign;
361 const char *value;
363 argv_array_init(&array);
364 argv_array_push(&array, "commit");
365 argv_array_push(&array, "-n");
367 if (opts->gpg_sign) {
368 gpg_sign = xmalloc(3 + strlen(opts->gpg_sign));
369 sprintf(gpg_sign, "-S%s", opts->gpg_sign);
370 argv_array_push(&array, gpg_sign);
371 free(gpg_sign);
373 if (opts->signoff)
374 argv_array_push(&array, "-s");
375 if (!opts->edit) {
376 argv_array_push(&array, "-F");
377 argv_array_push(&array, defmsg);
378 if (!opts->signoff &&
379 !opts->record_origin &&
380 git_config_get_value("commit.cleanup", &value))
381 argv_array_push(&array, "--cleanup=verbatim");
384 if (allow_empty)
385 argv_array_push(&array, "--allow-empty");
387 if (opts->allow_empty_message)
388 argv_array_push(&array, "--allow-empty-message");
390 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
391 argv_array_clear(&array);
392 return rc;
395 static int is_original_commit_empty(struct commit *commit)
397 const unsigned char *ptree_sha1;
399 if (parse_commit(commit))
400 return error(_("Could not parse commit %s\n"),
401 sha1_to_hex(commit->object.sha1));
402 if (commit->parents) {
403 struct commit *parent = commit->parents->item;
404 if (parse_commit(parent))
405 return error(_("Could not parse parent commit %s\n"),
406 sha1_to_hex(parent->object.sha1));
407 ptree_sha1 = parent->tree->object.sha1;
408 } else {
409 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
412 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
416 * Do we run "git commit" with "--allow-empty"?
418 static int allow_empty(struct replay_opts *opts, struct commit *commit)
420 int index_unchanged, empty_commit;
423 * Three cases:
425 * (1) we do not allow empty at all and error out.
427 * (2) we allow ones that were initially empty, but
428 * forbid the ones that become empty;
430 * (3) we allow both.
432 if (!opts->allow_empty)
433 return 0; /* let "git commit" barf as necessary */
435 index_unchanged = is_index_unchanged();
436 if (index_unchanged < 0)
437 return index_unchanged;
438 if (!index_unchanged)
439 return 0; /* we do not have to say --allow-empty */
441 if (opts->keep_redundant_commits)
442 return 1;
444 empty_commit = is_original_commit_empty(commit);
445 if (empty_commit < 0)
446 return empty_commit;
447 if (!empty_commit)
448 return 0;
449 else
450 return 1;
453 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
455 unsigned char head[20];
456 struct commit *base, *next, *parent;
457 const char *base_label, *next_label;
458 struct commit_message msg = { NULL, NULL, NULL, NULL };
459 char *defmsg = NULL;
460 struct strbuf msgbuf = STRBUF_INIT;
461 int res, unborn = 0, allow;
463 if (opts->no_commit) {
465 * We do not intend to commit immediately. We just want to
466 * merge the differences in, so let's compute the tree
467 * that represents the "current" state for merge-recursive
468 * to work on.
470 if (write_cache_as_tree(head, 0, NULL))
471 die (_("Your index file is unmerged."));
472 } else {
473 unborn = get_sha1("HEAD", head);
474 if (unborn)
475 hashcpy(head, EMPTY_TREE_SHA1_BIN);
476 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
477 return error_dirty_index(opts);
479 discard_cache();
481 if (!commit->parents) {
482 parent = NULL;
484 else if (commit->parents->next) {
485 /* Reverting or cherry-picking a merge commit */
486 int cnt;
487 struct commit_list *p;
489 if (!opts->mainline)
490 return error(_("Commit %s is a merge but no -m option was given."),
491 sha1_to_hex(commit->object.sha1));
493 for (cnt = 1, p = commit->parents;
494 cnt != opts->mainline && p;
495 cnt++)
496 p = p->next;
497 if (cnt != opts->mainline || !p)
498 return error(_("Commit %s does not have parent %d"),
499 sha1_to_hex(commit->object.sha1), opts->mainline);
500 parent = p->item;
501 } else if (0 < opts->mainline)
502 return error(_("Mainline was specified but commit %s is not a merge."),
503 sha1_to_hex(commit->object.sha1));
504 else
505 parent = commit->parents->item;
507 if (opts->allow_ff &&
508 ((parent && !hashcmp(parent->object.sha1, head)) ||
509 (!parent && unborn)))
510 return fast_forward_to(commit->object.sha1, head, unborn, opts);
512 if (parent && parse_commit(parent) < 0)
513 /* TRANSLATORS: The first %s will be "revert" or
514 "cherry-pick", the second %s a SHA1 */
515 return error(_("%s: cannot parse parent commit %s"),
516 action_name(opts), sha1_to_hex(parent->object.sha1));
518 if (get_message(commit, &msg) != 0)
519 return error(_("Cannot get commit message for %s"),
520 sha1_to_hex(commit->object.sha1));
523 * "commit" is an existing commit. We would want to apply
524 * the difference it introduces since its first parent "prev"
525 * on top of the current HEAD if we are cherry-pick. Or the
526 * reverse of it if we are revert.
529 defmsg = git_pathdup("MERGE_MSG");
531 if (opts->action == REPLAY_REVERT) {
532 base = commit;
533 base_label = msg.label;
534 next = parent;
535 next_label = msg.parent_label;
536 strbuf_addstr(&msgbuf, "Revert \"");
537 strbuf_addstr(&msgbuf, msg.subject);
538 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
539 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
541 if (commit->parents && commit->parents->next) {
542 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
543 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
545 strbuf_addstr(&msgbuf, ".\n");
546 } else {
547 const char *p;
549 base = parent;
550 base_label = msg.parent_label;
551 next = commit;
552 next_label = msg.label;
555 * Append the commit log message to msgbuf; it starts
556 * after the tree, parent, author, committer
557 * information followed by "\n\n".
559 p = strstr(msg.message, "\n\n");
560 if (p) {
561 p += 2;
562 strbuf_addstr(&msgbuf, p);
565 if (opts->record_origin) {
566 if (!has_conforming_footer(&msgbuf, NULL, 0))
567 strbuf_addch(&msgbuf, '\n');
568 strbuf_addstr(&msgbuf, cherry_picked_prefix);
569 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
570 strbuf_addstr(&msgbuf, ")\n");
574 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
575 res = do_recursive_merge(base, next, base_label, next_label,
576 head, &msgbuf, opts);
577 write_message(&msgbuf, defmsg);
578 } else {
579 struct commit_list *common = NULL;
580 struct commit_list *remotes = NULL;
582 write_message(&msgbuf, defmsg);
584 commit_list_insert(base, &common);
585 commit_list_insert(next, &remotes);
586 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
587 common, sha1_to_hex(head), remotes);
588 free_commit_list(common);
589 free_commit_list(remotes);
593 * If the merge was clean or if it failed due to conflict, we write
594 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
595 * However, if the merge did not even start, then we don't want to
596 * write it at all.
598 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
599 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
600 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
601 write_cherry_pick_head(commit, "REVERT_HEAD");
603 if (res) {
604 error(opts->action == REPLAY_REVERT
605 ? _("could not revert %s... %s")
606 : _("could not apply %s... %s"),
607 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
608 msg.subject);
609 print_advice(res == 1, opts);
610 rerere(opts->allow_rerere_auto);
611 goto leave;
614 allow = allow_empty(opts, commit);
615 if (allow < 0) {
616 res = allow;
617 goto leave;
619 if (!opts->no_commit)
620 res = run_git_commit(defmsg, opts, allow);
622 leave:
623 free_message(commit, &msg);
624 free(defmsg);
626 return res;
629 static void prepare_revs(struct replay_opts *opts)
632 * picking (but not reverting) ranges (but not individual revisions)
633 * should be done in reverse
635 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
636 opts->revs->reverse ^= 1;
638 if (prepare_revision_walk(opts->revs))
639 die(_("revision walk setup failed"));
641 if (!opts->revs->commits)
642 die(_("empty commit set passed"));
645 static void read_and_refresh_cache(struct replay_opts *opts)
647 static struct lock_file index_lock;
648 int index_fd = hold_locked_index(&index_lock, 0);
649 if (read_index_preload(&the_index, NULL) < 0)
650 die(_("git %s: failed to read the index"), action_name(opts));
651 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
652 if (the_index.cache_changed) {
653 if (write_index(&the_index, index_fd) ||
654 commit_locked_index(&index_lock))
655 die(_("git %s: failed to refresh the index"), action_name(opts));
657 rollback_lock_file(&index_lock);
660 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
661 struct replay_opts *opts)
663 struct commit_list *cur = NULL;
664 const char *sha1_abbrev = NULL;
665 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
666 const char *subject;
667 int subject_len;
669 for (cur = todo_list; cur; cur = cur->next) {
670 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
671 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
672 subject_len = find_commit_subject(commit_buffer, &subject);
673 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
674 subject_len, subject);
675 unuse_commit_buffer(cur->item, commit_buffer);
677 return 0;
680 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
682 unsigned char commit_sha1[20];
683 enum replay_action action;
684 char *end_of_object_name;
685 int saved, status, padding;
687 if (starts_with(bol, "pick")) {
688 action = REPLAY_PICK;
689 bol += strlen("pick");
690 } else if (starts_with(bol, "revert")) {
691 action = REPLAY_REVERT;
692 bol += strlen("revert");
693 } else
694 return NULL;
696 /* Eat up extra spaces/ tabs before object name */
697 padding = strspn(bol, " \t");
698 if (!padding)
699 return NULL;
700 bol += padding;
702 end_of_object_name = bol + strcspn(bol, " \t\n");
703 saved = *end_of_object_name;
704 *end_of_object_name = '\0';
705 status = get_sha1(bol, commit_sha1);
706 *end_of_object_name = saved;
709 * Verify that the action matches up with the one in
710 * opts; we don't support arbitrary instructions
712 if (action != opts->action) {
713 const char *action_str;
714 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
715 error(_("Cannot %s during a %s"), action_str, action_name(opts));
716 return NULL;
719 if (status < 0)
720 return NULL;
722 return lookup_commit_reference(commit_sha1);
725 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
726 struct replay_opts *opts)
728 struct commit_list **next = todo_list;
729 struct commit *commit;
730 char *p = buf;
731 int i;
733 for (i = 1; *p; i++) {
734 char *eol = strchrnul(p, '\n');
735 commit = parse_insn_line(p, eol, opts);
736 if (!commit)
737 return error(_("Could not parse line %d."), i);
738 next = commit_list_append(commit, next);
739 p = *eol ? eol + 1 : eol;
741 if (!*todo_list)
742 return error(_("No commits parsed."));
743 return 0;
746 static void read_populate_todo(struct commit_list **todo_list,
747 struct replay_opts *opts)
749 const char *todo_file = git_path(SEQ_TODO_FILE);
750 struct strbuf buf = STRBUF_INIT;
751 int fd, res;
753 fd = open(todo_file, O_RDONLY);
754 if (fd < 0)
755 die_errno(_("Could not open %s"), todo_file);
756 if (strbuf_read(&buf, fd, 0) < 0) {
757 close(fd);
758 strbuf_release(&buf);
759 die(_("Could not read %s."), todo_file);
761 close(fd);
763 res = parse_insn_buffer(buf.buf, todo_list, opts);
764 strbuf_release(&buf);
765 if (res)
766 die(_("Unusable instruction sheet: %s"), todo_file);
769 static int populate_opts_cb(const char *key, const char *value, void *data)
771 struct replay_opts *opts = data;
772 int error_flag = 1;
774 if (!value)
775 error_flag = 0;
776 else if (!strcmp(key, "options.no-commit"))
777 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
778 else if (!strcmp(key, "options.edit"))
779 opts->edit = git_config_bool_or_int(key, value, &error_flag);
780 else if (!strcmp(key, "options.signoff"))
781 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
782 else if (!strcmp(key, "options.record-origin"))
783 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
784 else if (!strcmp(key, "options.allow-ff"))
785 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
786 else if (!strcmp(key, "options.mainline"))
787 opts->mainline = git_config_int(key, value);
788 else if (!strcmp(key, "options.strategy"))
789 git_config_string(&opts->strategy, key, value);
790 else if (!strcmp(key, "options.gpg-sign"))
791 git_config_string(&opts->gpg_sign, key, value);
792 else if (!strcmp(key, "options.strategy-option")) {
793 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
794 opts->xopts[opts->xopts_nr++] = xstrdup(value);
795 } else
796 return error(_("Invalid key: %s"), key);
798 if (!error_flag)
799 return error(_("Invalid value for %s: %s"), key, value);
801 return 0;
804 static void read_populate_opts(struct replay_opts **opts_ptr)
806 const char *opts_file = git_path(SEQ_OPTS_FILE);
808 if (!file_exists(opts_file))
809 return;
810 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
811 die(_("Malformed options sheet: %s"), opts_file);
814 static void walk_revs_populate_todo(struct commit_list **todo_list,
815 struct replay_opts *opts)
817 struct commit *commit;
818 struct commit_list **next;
820 prepare_revs(opts);
822 next = todo_list;
823 while ((commit = get_revision(opts->revs)))
824 next = commit_list_append(commit, next);
827 static int create_seq_dir(void)
829 const char *seq_dir = git_path(SEQ_DIR);
831 if (file_exists(seq_dir)) {
832 error(_("a cherry-pick or revert is already in progress"));
833 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
834 return -1;
836 else if (mkdir(seq_dir, 0777) < 0)
837 die_errno(_("Could not create sequencer directory %s"), seq_dir);
838 return 0;
841 static void save_head(const char *head)
843 const char *head_file = git_path(SEQ_HEAD_FILE);
844 static struct lock_file head_lock;
845 struct strbuf buf = STRBUF_INIT;
846 int fd;
848 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
849 strbuf_addf(&buf, "%s\n", head);
850 if (write_in_full(fd, buf.buf, buf.len) < 0)
851 die_errno(_("Could not write to %s"), head_file);
852 if (commit_lock_file(&head_lock) < 0)
853 die(_("Error wrapping up %s."), head_file);
856 static int reset_for_rollback(const unsigned char *sha1)
858 const char *argv[4]; /* reset --merge <arg> + NULL */
859 argv[0] = "reset";
860 argv[1] = "--merge";
861 argv[2] = sha1_to_hex(sha1);
862 argv[3] = NULL;
863 return run_command_v_opt(argv, RUN_GIT_CMD);
866 static int rollback_single_pick(void)
868 unsigned char head_sha1[20];
870 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
871 !file_exists(git_path("REVERT_HEAD")))
872 return error(_("no cherry-pick or revert in progress"));
873 if (read_ref_full("HEAD", head_sha1, 0, NULL))
874 return error(_("cannot resolve HEAD"));
875 if (is_null_sha1(head_sha1))
876 return error(_("cannot abort from a branch yet to be born"));
877 return reset_for_rollback(head_sha1);
880 static int sequencer_rollback(struct replay_opts *opts)
882 const char *filename;
883 FILE *f;
884 unsigned char sha1[20];
885 struct strbuf buf = STRBUF_INIT;
887 filename = git_path(SEQ_HEAD_FILE);
888 f = fopen(filename, "r");
889 if (!f && errno == ENOENT) {
891 * There is no multiple-cherry-pick in progress.
892 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
893 * a single-cherry-pick in progress, abort that.
895 return rollback_single_pick();
897 if (!f)
898 return error(_("cannot open %s: %s"), filename,
899 strerror(errno));
900 if (strbuf_getline(&buf, f, '\n')) {
901 error(_("cannot read %s: %s"), filename, ferror(f) ?
902 strerror(errno) : _("unexpected end of file"));
903 fclose(f);
904 goto fail;
906 fclose(f);
907 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
908 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
909 filename);
910 goto fail;
912 if (reset_for_rollback(sha1))
913 goto fail;
914 remove_sequencer_state();
915 strbuf_release(&buf);
916 return 0;
917 fail:
918 strbuf_release(&buf);
919 return -1;
922 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
924 const char *todo_file = git_path(SEQ_TODO_FILE);
925 static struct lock_file todo_lock;
926 struct strbuf buf = STRBUF_INIT;
927 int fd;
929 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
930 if (format_todo(&buf, todo_list, opts) < 0)
931 die(_("Could not format %s."), todo_file);
932 if (write_in_full(fd, buf.buf, buf.len) < 0) {
933 strbuf_release(&buf);
934 die_errno(_("Could not write to %s"), todo_file);
936 if (commit_lock_file(&todo_lock) < 0) {
937 strbuf_release(&buf);
938 die(_("Error wrapping up %s."), todo_file);
940 strbuf_release(&buf);
943 static void save_opts(struct replay_opts *opts)
945 const char *opts_file = git_path(SEQ_OPTS_FILE);
947 if (opts->no_commit)
948 git_config_set_in_file(opts_file, "options.no-commit", "true");
949 if (opts->edit)
950 git_config_set_in_file(opts_file, "options.edit", "true");
951 if (opts->signoff)
952 git_config_set_in_file(opts_file, "options.signoff", "true");
953 if (opts->record_origin)
954 git_config_set_in_file(opts_file, "options.record-origin", "true");
955 if (opts->allow_ff)
956 git_config_set_in_file(opts_file, "options.allow-ff", "true");
957 if (opts->mainline) {
958 struct strbuf buf = STRBUF_INIT;
959 strbuf_addf(&buf, "%d", opts->mainline);
960 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
961 strbuf_release(&buf);
963 if (opts->strategy)
964 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
965 if (opts->gpg_sign)
966 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
967 if (opts->xopts) {
968 int i;
969 for (i = 0; i < opts->xopts_nr; i++)
970 git_config_set_multivar_in_file(opts_file,
971 "options.strategy-option",
972 opts->xopts[i], "^$", 0);
976 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
978 struct commit_list *cur;
979 int res;
981 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
982 if (opts->allow_ff)
983 assert(!(opts->signoff || opts->no_commit ||
984 opts->record_origin || opts->edit));
985 read_and_refresh_cache(opts);
987 for (cur = todo_list; cur; cur = cur->next) {
988 save_todo(cur, opts);
989 res = do_pick_commit(cur->item, opts);
990 if (res)
991 return res;
995 * Sequence of picks finished successfully; cleanup by
996 * removing the .git/sequencer directory
998 remove_sequencer_state();
999 return 0;
1002 static int continue_single_pick(void)
1004 const char *argv[] = { "commit", NULL };
1006 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1007 !file_exists(git_path("REVERT_HEAD")))
1008 return error(_("no cherry-pick or revert in progress"));
1009 return run_command_v_opt(argv, RUN_GIT_CMD);
1012 static int sequencer_continue(struct replay_opts *opts)
1014 struct commit_list *todo_list = NULL;
1016 if (!file_exists(git_path(SEQ_TODO_FILE)))
1017 return continue_single_pick();
1018 read_populate_opts(&opts);
1019 read_populate_todo(&todo_list, opts);
1021 /* Verify that the conflict has been resolved */
1022 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1023 file_exists(git_path("REVERT_HEAD"))) {
1024 int ret = continue_single_pick();
1025 if (ret)
1026 return ret;
1028 if (index_differs_from("HEAD", 0))
1029 return error_dirty_index(opts);
1030 todo_list = todo_list->next;
1031 return pick_commits(todo_list, opts);
1034 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1036 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1037 return do_pick_commit(cmit, opts);
1040 int sequencer_pick_revisions(struct replay_opts *opts)
1042 struct commit_list *todo_list = NULL;
1043 unsigned char sha1[20];
1044 int i;
1046 if (opts->subcommand == REPLAY_NONE)
1047 assert(opts->revs);
1049 read_and_refresh_cache(opts);
1052 * Decide what to do depending on the arguments; a fresh
1053 * cherry-pick should be handled differently from an existing
1054 * one that is being continued
1056 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1057 remove_sequencer_state();
1058 return 0;
1060 if (opts->subcommand == REPLAY_ROLLBACK)
1061 return sequencer_rollback(opts);
1062 if (opts->subcommand == REPLAY_CONTINUE)
1063 return sequencer_continue(opts);
1065 for (i = 0; i < opts->revs->pending.nr; i++) {
1066 unsigned char sha1[20];
1067 const char *name = opts->revs->pending.objects[i].name;
1069 /* This happens when using --stdin. */
1070 if (!strlen(name))
1071 continue;
1073 if (!get_sha1(name, sha1)) {
1074 if (!lookup_commit_reference_gently(sha1, 1)) {
1075 enum object_type type = sha1_object_info(sha1, NULL);
1076 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1078 } else
1079 die(_("%s: bad revision"), name);
1083 * If we were called as "git cherry-pick <commit>", just
1084 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1085 * REVERT_HEAD, and don't touch the sequencer state.
1086 * This means it is possible to cherry-pick in the middle
1087 * of a cherry-pick sequence.
1089 if (opts->revs->cmdline.nr == 1 &&
1090 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1091 opts->revs->no_walk &&
1092 !opts->revs->cmdline.rev->flags) {
1093 struct commit *cmit;
1094 if (prepare_revision_walk(opts->revs))
1095 die(_("revision walk setup failed"));
1096 cmit = get_revision(opts->revs);
1097 if (!cmit || get_revision(opts->revs))
1098 die("BUG: expected exactly one commit from walk");
1099 return single_pick(cmit, opts);
1103 * Start a new cherry-pick/ revert sequence; but
1104 * first, make sure that an existing one isn't in
1105 * progress
1108 walk_revs_populate_todo(&todo_list, opts);
1109 if (create_seq_dir() < 0)
1110 return -1;
1111 if (get_sha1("HEAD", sha1)) {
1112 if (opts->action == REPLAY_REVERT)
1113 return error(_("Can't revert as initial commit"));
1114 return error(_("Can't cherry-pick into empty head"));
1116 save_head(sha1_to_hex(sha1));
1117 save_opts(opts);
1118 return pick_commits(todo_list, opts);
1121 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1123 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1124 struct strbuf sob = STRBUF_INIT;
1125 int has_footer;
1127 strbuf_addstr(&sob, sign_off_header);
1128 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1129 getenv("GIT_COMMITTER_EMAIL")));
1130 strbuf_addch(&sob, '\n');
1133 * If the whole message buffer is equal to the sob, pretend that we
1134 * found a conforming footer with a matching sob
1136 if (msgbuf->len - ignore_footer == sob.len &&
1137 !strncmp(msgbuf->buf, sob.buf, sob.len))
1138 has_footer = 3;
1139 else
1140 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1142 if (!has_footer) {
1143 const char *append_newlines = NULL;
1144 size_t len = msgbuf->len - ignore_footer;
1146 if (!len) {
1148 * The buffer is completely empty. Leave foom for
1149 * the title and body to be filled in by the user.
1151 append_newlines = "\n\n";
1152 } else if (msgbuf->buf[len - 1] != '\n') {
1154 * Incomplete line. Complete the line and add a
1155 * blank one so that there is an empty line between
1156 * the message body and the sob.
1158 append_newlines = "\n\n";
1159 } else if (len == 1) {
1161 * Buffer contains a single newline. Add another
1162 * so that we leave room for the title and body.
1164 append_newlines = "\n";
1165 } else if (msgbuf->buf[len - 2] != '\n') {
1167 * Buffer ends with a single newline. Add another
1168 * so that there is an empty line between the message
1169 * body and the sob.
1171 append_newlines = "\n";
1172 } /* else, the buffer already ends with two newlines. */
1174 if (append_newlines)
1175 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1176 append_newlines, strlen(append_newlines));
1179 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1180 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1181 sob.buf, sob.len);
1183 strbuf_release(&sob);