Merge branch 'rs/ref-transaction-1' into jch
[git/jrn.git] / sequencer.c
bloba888cf30c4de71585f030da68f2ec29af774df6c
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_transaction *transaction;
241 struct strbuf sb = STRBUF_INIT;
242 struct strbuf err = STRBUF_INIT;
244 read_cache();
245 if (checkout_fast_forward(from, to, 1))
246 exit(128); /* the callee should have complained already */
248 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
250 transaction = ref_transaction_begin(&err);
251 if (!transaction ||
252 ref_transaction_update(transaction, "HEAD",
253 to, unborn ? null_sha1 : from,
254 0, 1, &err) ||
255 ref_transaction_commit(transaction, sb.buf, &err)) {
256 ref_transaction_free(transaction);
257 error("%s", err.buf);
258 strbuf_release(&sb);
259 strbuf_release(&err);
260 return -1;
263 strbuf_release(&sb);
264 ref_transaction_free(transaction);
265 return 0;
268 static int do_recursive_merge(struct commit *base, struct commit *next,
269 const char *base_label, const char *next_label,
270 unsigned char *head, struct strbuf *msgbuf,
271 struct replay_opts *opts)
273 struct merge_options o;
274 struct tree *result, *next_tree, *base_tree, *head_tree;
275 int clean;
276 const char **xopt;
277 static struct lock_file index_lock;
279 hold_locked_index(&index_lock, 1);
281 read_cache();
283 init_merge_options(&o);
284 o.ancestor = base ? base_label : "(empty tree)";
285 o.branch1 = "HEAD";
286 o.branch2 = next ? next_label : "(empty tree)";
288 head_tree = parse_tree_indirect(head);
289 next_tree = next ? next->tree : empty_tree();
290 base_tree = base ? base->tree : empty_tree();
292 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
293 parse_merge_opt(&o, *xopt);
295 clean = merge_trees(&o,
296 head_tree,
297 next_tree, base_tree, &result);
299 if (active_cache_changed &&
300 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
301 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
302 die(_("%s: Unable to write new index file"), action_name(opts));
303 rollback_lock_file(&index_lock);
305 if (opts->signoff)
306 append_signoff(msgbuf, 0, 0);
308 if (!clean) {
309 int i;
310 strbuf_addstr(msgbuf, "\nConflicts:\n");
311 for (i = 0; i < active_nr;) {
312 const struct cache_entry *ce = active_cache[i++];
313 if (ce_stage(ce)) {
314 strbuf_addch(msgbuf, '\t');
315 strbuf_addstr(msgbuf, ce->name);
316 strbuf_addch(msgbuf, '\n');
317 while (i < active_nr && !strcmp(ce->name,
318 active_cache[i]->name))
319 i++;
324 return !clean;
327 static int is_index_unchanged(void)
329 unsigned char head_sha1[20];
330 struct commit *head_commit;
332 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
333 return error(_("Could not resolve HEAD commit\n"));
335 head_commit = lookup_commit(head_sha1);
338 * If head_commit is NULL, check_commit, called from
339 * lookup_commit, would have indicated that head_commit is not
340 * a commit object already. parse_commit() will return failure
341 * without further complaints in such a case. Otherwise, if
342 * the commit is invalid, parse_commit() will complain. So
343 * there is nothing for us to say here. Just return failure.
345 if (parse_commit(head_commit))
346 return -1;
348 if (!active_cache_tree)
349 active_cache_tree = cache_tree();
351 if (!cache_tree_fully_valid(active_cache_tree))
352 if (cache_tree_update(&the_index, 0))
353 return error(_("Unable to update cache tree\n"));
355 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
359 * If we are cherry-pick, and if the merge did not result in
360 * hand-editing, we will hit this commit and inherit the original
361 * author date and name.
362 * If we are revert, or if our cherry-pick results in a hand merge,
363 * we had better say that the current user is responsible for that.
365 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
366 int allow_empty)
368 struct argv_array array;
369 int rc;
371 argv_array_init(&array);
372 argv_array_push(&array, "commit");
373 argv_array_push(&array, "-n");
375 if (opts->gpg_sign)
376 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
377 if (opts->signoff)
378 argv_array_push(&array, "-s");
379 if (!opts->edit) {
380 argv_array_push(&array, "-F");
381 argv_array_push(&array, defmsg);
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 && index_fd >= 0) {
653 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
654 die(_("git %s: failed to refresh the index"), action_name(opts));
656 rollback_lock_file(&index_lock);
659 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
660 struct replay_opts *opts)
662 struct commit_list *cur = NULL;
663 const char *sha1_abbrev = NULL;
664 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
665 const char *subject;
666 int subject_len;
668 for (cur = todo_list; cur; cur = cur->next) {
669 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
670 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
671 subject_len = find_commit_subject(commit_buffer, &subject);
672 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
673 subject_len, subject);
674 unuse_commit_buffer(cur->item, commit_buffer);
676 return 0;
679 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
681 unsigned char commit_sha1[20];
682 enum replay_action action;
683 char *end_of_object_name;
684 int saved, status, padding;
686 if (starts_with(bol, "pick")) {
687 action = REPLAY_PICK;
688 bol += strlen("pick");
689 } else if (starts_with(bol, "revert")) {
690 action = REPLAY_REVERT;
691 bol += strlen("revert");
692 } else
693 return NULL;
695 /* Eat up extra spaces/ tabs before object name */
696 padding = strspn(bol, " \t");
697 if (!padding)
698 return NULL;
699 bol += padding;
701 end_of_object_name = bol + strcspn(bol, " \t\n");
702 saved = *end_of_object_name;
703 *end_of_object_name = '\0';
704 status = get_sha1(bol, commit_sha1);
705 *end_of_object_name = saved;
708 * Verify that the action matches up with the one in
709 * opts; we don't support arbitrary instructions
711 if (action != opts->action) {
712 const char *action_str;
713 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
714 error(_("Cannot %s during a %s"), action_str, action_name(opts));
715 return NULL;
718 if (status < 0)
719 return NULL;
721 return lookup_commit_reference(commit_sha1);
724 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
725 struct replay_opts *opts)
727 struct commit_list **next = todo_list;
728 struct commit *commit;
729 char *p = buf;
730 int i;
732 for (i = 1; *p; i++) {
733 char *eol = strchrnul(p, '\n');
734 commit = parse_insn_line(p, eol, opts);
735 if (!commit)
736 return error(_("Could not parse line %d."), i);
737 next = commit_list_append(commit, next);
738 p = *eol ? eol + 1 : eol;
740 if (!*todo_list)
741 return error(_("No commits parsed."));
742 return 0;
745 static void read_populate_todo(struct commit_list **todo_list,
746 struct replay_opts *opts)
748 const char *todo_file = git_path(SEQ_TODO_FILE);
749 struct strbuf buf = STRBUF_INIT;
750 int fd, res;
752 fd = open(todo_file, O_RDONLY);
753 if (fd < 0)
754 die_errno(_("Could not open %s"), todo_file);
755 if (strbuf_read(&buf, fd, 0) < 0) {
756 close(fd);
757 strbuf_release(&buf);
758 die(_("Could not read %s."), todo_file);
760 close(fd);
762 res = parse_insn_buffer(buf.buf, todo_list, opts);
763 strbuf_release(&buf);
764 if (res)
765 die(_("Unusable instruction sheet: %s"), todo_file);
768 static int populate_opts_cb(const char *key, const char *value, void *data)
770 struct replay_opts *opts = data;
771 int error_flag = 1;
773 if (!value)
774 error_flag = 0;
775 else if (!strcmp(key, "options.no-commit"))
776 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
777 else if (!strcmp(key, "options.edit"))
778 opts->edit = git_config_bool_or_int(key, value, &error_flag);
779 else if (!strcmp(key, "options.signoff"))
780 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
781 else if (!strcmp(key, "options.record-origin"))
782 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
783 else if (!strcmp(key, "options.allow-ff"))
784 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
785 else if (!strcmp(key, "options.mainline"))
786 opts->mainline = git_config_int(key, value);
787 else if (!strcmp(key, "options.strategy"))
788 git_config_string(&opts->strategy, key, value);
789 else if (!strcmp(key, "options.gpg-sign"))
790 git_config_string(&opts->gpg_sign, key, value);
791 else if (!strcmp(key, "options.strategy-option")) {
792 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
793 opts->xopts[opts->xopts_nr++] = xstrdup(value);
794 } else
795 return error(_("Invalid key: %s"), key);
797 if (!error_flag)
798 return error(_("Invalid value for %s: %s"), key, value);
800 return 0;
803 static void read_populate_opts(struct replay_opts **opts_ptr)
805 const char *opts_file = git_path(SEQ_OPTS_FILE);
807 if (!file_exists(opts_file))
808 return;
809 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
810 die(_("Malformed options sheet: %s"), opts_file);
813 static void walk_revs_populate_todo(struct commit_list **todo_list,
814 struct replay_opts *opts)
816 struct commit *commit;
817 struct commit_list **next;
819 prepare_revs(opts);
821 next = todo_list;
822 while ((commit = get_revision(opts->revs)))
823 next = commit_list_append(commit, next);
826 static int create_seq_dir(void)
828 const char *seq_dir = git_path(SEQ_DIR);
830 if (file_exists(seq_dir)) {
831 error(_("a cherry-pick or revert is already in progress"));
832 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
833 return -1;
835 else if (mkdir(seq_dir, 0777) < 0)
836 die_errno(_("Could not create sequencer directory %s"), seq_dir);
837 return 0;
840 static void save_head(const char *head)
842 const char *head_file = git_path(SEQ_HEAD_FILE);
843 static struct lock_file head_lock;
844 struct strbuf buf = STRBUF_INIT;
845 int fd;
847 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
848 strbuf_addf(&buf, "%s\n", head);
849 if (write_in_full(fd, buf.buf, buf.len) < 0)
850 die_errno(_("Could not write to %s"), head_file);
851 if (commit_lock_file(&head_lock) < 0)
852 die(_("Error wrapping up %s."), head_file);
855 static int reset_for_rollback(const unsigned char *sha1)
857 const char *argv[4]; /* reset --merge <arg> + NULL */
858 argv[0] = "reset";
859 argv[1] = "--merge";
860 argv[2] = sha1_to_hex(sha1);
861 argv[3] = NULL;
862 return run_command_v_opt(argv, RUN_GIT_CMD);
865 static int rollback_single_pick(void)
867 unsigned char head_sha1[20];
869 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
870 !file_exists(git_path("REVERT_HEAD")))
871 return error(_("no cherry-pick or revert in progress"));
872 if (read_ref_full("HEAD", head_sha1, 0, NULL))
873 return error(_("cannot resolve HEAD"));
874 if (is_null_sha1(head_sha1))
875 return error(_("cannot abort from a branch yet to be born"));
876 return reset_for_rollback(head_sha1);
879 static int sequencer_rollback(struct replay_opts *opts)
881 const char *filename;
882 FILE *f;
883 unsigned char sha1[20];
884 struct strbuf buf = STRBUF_INIT;
886 filename = git_path(SEQ_HEAD_FILE);
887 f = fopen(filename, "r");
888 if (!f && errno == ENOENT) {
890 * There is no multiple-cherry-pick in progress.
891 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
892 * a single-cherry-pick in progress, abort that.
894 return rollback_single_pick();
896 if (!f)
897 return error(_("cannot open %s: %s"), filename,
898 strerror(errno));
899 if (strbuf_getline(&buf, f, '\n')) {
900 error(_("cannot read %s: %s"), filename, ferror(f) ?
901 strerror(errno) : _("unexpected end of file"));
902 fclose(f);
903 goto fail;
905 fclose(f);
906 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
907 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
908 filename);
909 goto fail;
911 if (reset_for_rollback(sha1))
912 goto fail;
913 remove_sequencer_state();
914 strbuf_release(&buf);
915 return 0;
916 fail:
917 strbuf_release(&buf);
918 return -1;
921 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
923 const char *todo_file = git_path(SEQ_TODO_FILE);
924 static struct lock_file todo_lock;
925 struct strbuf buf = STRBUF_INIT;
926 int fd;
928 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
929 if (format_todo(&buf, todo_list, opts) < 0)
930 die(_("Could not format %s."), todo_file);
931 if (write_in_full(fd, buf.buf, buf.len) < 0) {
932 strbuf_release(&buf);
933 die_errno(_("Could not write to %s"), todo_file);
935 if (commit_lock_file(&todo_lock) < 0) {
936 strbuf_release(&buf);
937 die(_("Error wrapping up %s."), todo_file);
939 strbuf_release(&buf);
942 static void save_opts(struct replay_opts *opts)
944 const char *opts_file = git_path(SEQ_OPTS_FILE);
946 if (opts->no_commit)
947 git_config_set_in_file(opts_file, "options.no-commit", "true");
948 if (opts->edit)
949 git_config_set_in_file(opts_file, "options.edit", "true");
950 if (opts->signoff)
951 git_config_set_in_file(opts_file, "options.signoff", "true");
952 if (opts->record_origin)
953 git_config_set_in_file(opts_file, "options.record-origin", "true");
954 if (opts->allow_ff)
955 git_config_set_in_file(opts_file, "options.allow-ff", "true");
956 if (opts->mainline) {
957 struct strbuf buf = STRBUF_INIT;
958 strbuf_addf(&buf, "%d", opts->mainline);
959 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
960 strbuf_release(&buf);
962 if (opts->strategy)
963 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
964 if (opts->gpg_sign)
965 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
966 if (opts->xopts) {
967 int i;
968 for (i = 0; i < opts->xopts_nr; i++)
969 git_config_set_multivar_in_file(opts_file,
970 "options.strategy-option",
971 opts->xopts[i], "^$", 0);
975 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
977 struct commit_list *cur;
978 int res;
980 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
981 if (opts->allow_ff)
982 assert(!(opts->signoff || opts->no_commit ||
983 opts->record_origin || opts->edit));
984 read_and_refresh_cache(opts);
986 for (cur = todo_list; cur; cur = cur->next) {
987 save_todo(cur, opts);
988 res = do_pick_commit(cur->item, opts);
989 if (res)
990 return res;
994 * Sequence of picks finished successfully; cleanup by
995 * removing the .git/sequencer directory
997 remove_sequencer_state();
998 return 0;
1001 static int continue_single_pick(void)
1003 const char *argv[] = { "commit", NULL };
1005 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1006 !file_exists(git_path("REVERT_HEAD")))
1007 return error(_("no cherry-pick or revert in progress"));
1008 return run_command_v_opt(argv, RUN_GIT_CMD);
1011 static int sequencer_continue(struct replay_opts *opts)
1013 struct commit_list *todo_list = NULL;
1015 if (!file_exists(git_path(SEQ_TODO_FILE)))
1016 return continue_single_pick();
1017 read_populate_opts(&opts);
1018 read_populate_todo(&todo_list, opts);
1020 /* Verify that the conflict has been resolved */
1021 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1022 file_exists(git_path("REVERT_HEAD"))) {
1023 int ret = continue_single_pick();
1024 if (ret)
1025 return ret;
1027 if (index_differs_from("HEAD", 0))
1028 return error_dirty_index(opts);
1029 todo_list = todo_list->next;
1030 return pick_commits(todo_list, opts);
1033 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1035 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1036 return do_pick_commit(cmit, opts);
1039 int sequencer_pick_revisions(struct replay_opts *opts)
1041 struct commit_list *todo_list = NULL;
1042 unsigned char sha1[20];
1043 int i;
1045 if (opts->subcommand == REPLAY_NONE)
1046 assert(opts->revs);
1048 read_and_refresh_cache(opts);
1051 * Decide what to do depending on the arguments; a fresh
1052 * cherry-pick should be handled differently from an existing
1053 * one that is being continued
1055 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1056 remove_sequencer_state();
1057 return 0;
1059 if (opts->subcommand == REPLAY_ROLLBACK)
1060 return sequencer_rollback(opts);
1061 if (opts->subcommand == REPLAY_CONTINUE)
1062 return sequencer_continue(opts);
1064 for (i = 0; i < opts->revs->pending.nr; i++) {
1065 unsigned char sha1[20];
1066 const char *name = opts->revs->pending.objects[i].name;
1068 /* This happens when using --stdin. */
1069 if (!strlen(name))
1070 continue;
1072 if (!get_sha1(name, sha1)) {
1073 if (!lookup_commit_reference_gently(sha1, 1)) {
1074 enum object_type type = sha1_object_info(sha1, NULL);
1075 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1077 } else
1078 die(_("%s: bad revision"), name);
1082 * If we were called as "git cherry-pick <commit>", just
1083 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1084 * REVERT_HEAD, and don't touch the sequencer state.
1085 * This means it is possible to cherry-pick in the middle
1086 * of a cherry-pick sequence.
1088 if (opts->revs->cmdline.nr == 1 &&
1089 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1090 opts->revs->no_walk &&
1091 !opts->revs->cmdline.rev->flags) {
1092 struct commit *cmit;
1093 if (prepare_revision_walk(opts->revs))
1094 die(_("revision walk setup failed"));
1095 cmit = get_revision(opts->revs);
1096 if (!cmit || get_revision(opts->revs))
1097 die("BUG: expected exactly one commit from walk");
1098 return single_pick(cmit, opts);
1102 * Start a new cherry-pick/ revert sequence; but
1103 * first, make sure that an existing one isn't in
1104 * progress
1107 walk_revs_populate_todo(&todo_list, opts);
1108 if (create_seq_dir() < 0)
1109 return -1;
1110 if (get_sha1("HEAD", sha1)) {
1111 if (opts->action == REPLAY_REVERT)
1112 return error(_("Can't revert as initial commit"));
1113 return error(_("Can't cherry-pick into empty head"));
1115 save_head(sha1_to_hex(sha1));
1116 save_opts(opts);
1117 return pick_commits(todo_list, opts);
1120 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1122 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1123 struct strbuf sob = STRBUF_INIT;
1124 int has_footer;
1126 strbuf_addstr(&sob, sign_off_header);
1127 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1128 getenv("GIT_COMMITTER_EMAIL")));
1129 strbuf_addch(&sob, '\n');
1132 * If the whole message buffer is equal to the sob, pretend that we
1133 * found a conforming footer with a matching sob
1135 if (msgbuf->len - ignore_footer == sob.len &&
1136 !strncmp(msgbuf->buf, sob.buf, sob.len))
1137 has_footer = 3;
1138 else
1139 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1141 if (!has_footer) {
1142 const char *append_newlines = NULL;
1143 size_t len = msgbuf->len - ignore_footer;
1145 if (!len) {
1147 * The buffer is completely empty. Leave foom for
1148 * the title and body to be filled in by the user.
1150 append_newlines = "\n\n";
1151 } else if (msgbuf->buf[len - 1] != '\n') {
1153 * Incomplete line. Complete the line and add a
1154 * blank one so that there is an empty line between
1155 * the message body and the sob.
1157 append_newlines = "\n\n";
1158 } else if (len == 1) {
1160 * Buffer contains a single newline. Add another
1161 * so that we leave room for the title and body.
1163 append_newlines = "\n";
1164 } else if (msgbuf->buf[len - 2] != '\n') {
1166 * Buffer ends with a single newline. Add another
1167 * so that there is an empty line between the message
1168 * body and the sob.
1170 append_newlines = "\n";
1171 } /* else, the buffer already ends with two newlines. */
1173 if (append_newlines)
1174 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1175 append_newlines, strlen(append_newlines));
1178 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1179 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1180 sob.buf, sob.len);
1182 strbuf_release(&sob);