Skip tests that fail due to incomplete implementations, missing tools...
[git/mingw/j6t.git] / sequencer.c
bloba0600aebcadb81e67921d953e8ed626d08529a9b
1 #include "cache.h"
2 #include "lockfile.h"
3 #include "sequencer.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "run-command.h"
9 #include "exec_cmd.h"
10 #include "utf8.h"
11 #include "cache-tree.h"
12 #include "diff.h"
13 #include "revision.h"
14 #include "rerere.h"
15 #include "merge-recursive.h"
16 #include "refs.h"
17 #include "argv-array.h"
19 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
21 const char sign_off_header[] = "Signed-off-by: ";
22 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
24 static GIT_PATH_FUNC(git_path_todo_file, SEQ_TODO_FILE)
25 static GIT_PATH_FUNC(git_path_opts_file, SEQ_OPTS_FILE)
26 static GIT_PATH_FUNC(git_path_seq_dir, SEQ_DIR)
27 static GIT_PATH_FUNC(git_path_head_file, SEQ_HEAD_FILE)
29 static int is_rfc2822_line(const char *buf, int len)
31 int i;
33 for (i = 0; i < len; i++) {
34 int ch = buf[i];
35 if (ch == ':')
36 return 1;
37 if (!isalnum(ch) && ch != '-')
38 break;
41 return 0;
44 static int is_cherry_picked_from_line(const char *buf, int len)
47 * We only care that it looks roughly like (cherry picked from ...)
49 return len > strlen(cherry_picked_prefix) + 1 &&
50 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
54 * Returns 0 for non-conforming footer
55 * Returns 1 for conforming footer
56 * Returns 2 when sob exists within conforming footer
57 * Returns 3 when sob exists within conforming footer as last entry
59 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
60 int ignore_footer)
62 char prev;
63 int i, k;
64 int len = sb->len - ignore_footer;
65 const char *buf = sb->buf;
66 int found_sob = 0;
68 /* footer must end with newline */
69 if (!len || buf[len - 1] != '\n')
70 return 0;
72 prev = '\0';
73 for (i = len - 1; i > 0; i--) {
74 char ch = buf[i];
75 if (prev == '\n' && ch == '\n') /* paragraph break */
76 break;
77 prev = ch;
80 /* require at least one blank line */
81 if (prev != '\n' || buf[i] != '\n')
82 return 0;
84 /* advance to start of last paragraph */
85 while (i < len - 1 && buf[i] == '\n')
86 i++;
88 for (; i < len; i = k) {
89 int found_rfc2822;
91 for (k = i; k < len && buf[k] != '\n'; k++)
92 ; /* do nothing */
93 k++;
95 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
96 if (found_rfc2822 && sob &&
97 !strncmp(buf + i, sob->buf, sob->len))
98 found_sob = k;
100 if (!(found_rfc2822 ||
101 is_cherry_picked_from_line(buf + i, k - i - 1)))
102 return 0;
104 if (found_sob == i)
105 return 3;
106 if (found_sob)
107 return 2;
108 return 1;
111 static void remove_sequencer_state(void)
113 struct strbuf seq_dir = STRBUF_INIT;
115 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
116 remove_dir_recursively(&seq_dir, 0);
117 strbuf_release(&seq_dir);
120 static const char *action_name(const struct replay_opts *opts)
122 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
125 struct commit_message {
126 char *parent_label;
127 const char *label;
128 const char *subject;
129 const char *message;
132 static int get_message(struct commit *commit, struct commit_message *out)
134 const char *abbrev, *subject;
135 int abbrev_len, subject_len;
136 char *q;
138 if (!git_commit_encoding)
139 git_commit_encoding = "UTF-8";
141 out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
142 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
143 abbrev_len = strlen(abbrev);
145 subject_len = find_commit_subject(out->message, &subject);
147 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
148 strlen("... ") + subject_len + 1);
149 q = out->parent_label;
150 q = mempcpy(q, "parent of ", strlen("parent of "));
151 out->label = q;
152 q = mempcpy(q, abbrev, abbrev_len);
153 q = mempcpy(q, "... ", strlen("... "));
154 out->subject = q;
155 q = mempcpy(q, subject, subject_len);
156 *q = '\0';
157 return 0;
160 static void free_message(struct commit *commit, struct commit_message *msg)
162 free(msg->parent_label);
163 unuse_commit_buffer(commit, msg->message);
166 static void print_advice(int show_hint, struct replay_opts *opts)
168 char *msg = getenv("GIT_CHERRY_PICK_HELP");
170 if (msg) {
171 fprintf(stderr, "%s\n", msg);
173 * A conflict has occurred but the porcelain
174 * (typically rebase --interactive) wants to take care
175 * of the commit itself so remove CHERRY_PICK_HEAD
177 unlink(git_path_cherry_pick_head());
178 return;
181 if (show_hint) {
182 if (opts->no_commit)
183 advise(_("after resolving the conflicts, mark the corrected paths\n"
184 "with 'git add <paths>' or 'git rm <paths>'"));
185 else
186 advise(_("after resolving the conflicts, mark the corrected paths\n"
187 "with 'git add <paths>' or 'git rm <paths>'\n"
188 "and commit the result with 'git commit'"));
192 static void write_message(struct strbuf *msgbuf, const char *filename)
194 static struct lock_file msg_file;
196 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
197 LOCK_DIE_ON_ERROR);
198 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
199 die_errno(_("Could not write to %s"), filename);
200 strbuf_release(msgbuf);
201 if (commit_lock_file(&msg_file) < 0)
202 die(_("Error wrapping up %s"), filename);
205 static struct tree *empty_tree(void)
207 return lookup_tree(EMPTY_TREE_SHA1_BIN);
210 static int error_dirty_index(struct replay_opts *opts)
212 if (read_cache_unmerged())
213 return error_resolve_conflict(action_name(opts));
215 /* Different translation strings for cherry-pick and revert */
216 if (opts->action == REPLAY_PICK)
217 error(_("Your local changes would be overwritten by cherry-pick."));
218 else
219 error(_("Your local changes would be overwritten by revert."));
221 if (advice_commit_before_merge)
222 advise(_("Commit your changes or stash them to proceed."));
223 return -1;
226 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
227 int unborn, struct replay_opts *opts)
229 struct ref_transaction *transaction;
230 struct strbuf sb = STRBUF_INIT;
231 struct strbuf err = STRBUF_INIT;
233 read_cache();
234 if (checkout_fast_forward(from, to, 1))
235 exit(128); /* the callee should have complained already */
237 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
239 transaction = ref_transaction_begin(&err);
240 if (!transaction ||
241 ref_transaction_update(transaction, "HEAD",
242 to, unborn ? null_sha1 : from,
243 0, sb.buf, &err) ||
244 ref_transaction_commit(transaction, &err)) {
245 ref_transaction_free(transaction);
246 error("%s", err.buf);
247 strbuf_release(&sb);
248 strbuf_release(&err);
249 return -1;
252 strbuf_release(&sb);
253 strbuf_release(&err);
254 ref_transaction_free(transaction);
255 return 0;
258 void append_conflicts_hint(struct strbuf *msgbuf)
260 int i;
262 strbuf_addch(msgbuf, '\n');
263 strbuf_commented_addf(msgbuf, "Conflicts:\n");
264 for (i = 0; i < active_nr;) {
265 const struct cache_entry *ce = active_cache[i++];
266 if (ce_stage(ce)) {
267 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
268 while (i < active_nr && !strcmp(ce->name,
269 active_cache[i]->name))
270 i++;
275 static int do_recursive_merge(struct commit *base, struct commit *next,
276 const char *base_label, const char *next_label,
277 unsigned char *head, struct strbuf *msgbuf,
278 struct replay_opts *opts)
280 struct merge_options o;
281 struct tree *result, *next_tree, *base_tree, *head_tree;
282 int clean;
283 const char **xopt;
284 static struct lock_file index_lock;
286 hold_locked_index(&index_lock, 1);
288 read_cache();
290 init_merge_options(&o);
291 o.ancestor = base ? base_label : "(empty tree)";
292 o.branch1 = "HEAD";
293 o.branch2 = next ? next_label : "(empty tree)";
295 head_tree = parse_tree_indirect(head);
296 next_tree = next ? next->tree : empty_tree();
297 base_tree = base ? base->tree : empty_tree();
299 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
300 parse_merge_opt(&o, *xopt);
302 clean = merge_trees(&o,
303 head_tree,
304 next_tree, base_tree, &result);
306 if (active_cache_changed &&
307 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
308 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
309 die(_("%s: Unable to write new index file"), action_name(opts));
310 rollback_lock_file(&index_lock);
312 if (opts->signoff)
313 append_signoff(msgbuf, 0, 0);
315 if (!clean)
316 append_conflicts_hint(msgbuf);
318 return !clean;
321 static int is_index_unchanged(void)
323 unsigned char head_sha1[20];
324 struct commit *head_commit;
326 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
327 return error(_("Could not resolve HEAD commit\n"));
329 head_commit = lookup_commit(head_sha1);
332 * If head_commit is NULL, check_commit, called from
333 * lookup_commit, would have indicated that head_commit is not
334 * a commit object already. parse_commit() will return failure
335 * without further complaints in such a case. Otherwise, if
336 * the commit is invalid, parse_commit() will complain. So
337 * there is nothing for us to say here. Just return failure.
339 if (parse_commit(head_commit))
340 return -1;
342 if (!active_cache_tree)
343 active_cache_tree = cache_tree();
345 if (!cache_tree_fully_valid(active_cache_tree))
346 if (cache_tree_update(&the_index, 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;
364 const char *value;
366 argv_array_init(&array);
367 argv_array_push(&array, "commit");
368 argv_array_push(&array, "-n");
370 if (opts->gpg_sign)
371 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
372 if (opts->signoff)
373 argv_array_push(&array, "-s");
374 if (!opts->edit) {
375 argv_array_push(&array, "-F");
376 argv_array_push(&array, defmsg);
377 if (!opts->signoff &&
378 !opts->record_origin &&
379 git_config_get_value("commit.cleanup", &value))
380 argv_array_push(&array, "--cleanup=verbatim");
383 if (allow_empty)
384 argv_array_push(&array, "--allow-empty");
386 if (opts->allow_empty_message)
387 argv_array_push(&array, "--allow-empty-message");
389 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
390 argv_array_clear(&array);
391 return rc;
394 static int is_original_commit_empty(struct commit *commit)
396 const unsigned char *ptree_sha1;
398 if (parse_commit(commit))
399 return error(_("Could not parse commit %s\n"),
400 sha1_to_hex(commit->object.sha1));
401 if (commit->parents) {
402 struct commit *parent = commit->parents->item;
403 if (parse_commit(parent))
404 return error(_("Could not parse parent commit %s\n"),
405 sha1_to_hex(parent->object.sha1));
406 ptree_sha1 = parent->tree->object.sha1;
407 } else {
408 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
411 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
415 * Do we run "git commit" with "--allow-empty"?
417 static int allow_empty(struct replay_opts *opts, struct commit *commit)
419 int index_unchanged, empty_commit;
422 * Three cases:
424 * (1) we do not allow empty at all and error out.
426 * (2) we allow ones that were initially empty, but
427 * forbid the ones that become empty;
429 * (3) we allow both.
431 if (!opts->allow_empty)
432 return 0; /* let "git commit" barf as necessary */
434 index_unchanged = is_index_unchanged();
435 if (index_unchanged < 0)
436 return index_unchanged;
437 if (!index_unchanged)
438 return 0; /* we do not have to say --allow-empty */
440 if (opts->keep_redundant_commits)
441 return 1;
443 empty_commit = is_original_commit_empty(commit);
444 if (empty_commit < 0)
445 return empty_commit;
446 if (!empty_commit)
447 return 0;
448 else
449 return 1;
452 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
454 unsigned char head[20];
455 struct commit *base, *next, *parent;
456 const char *base_label, *next_label;
457 struct commit_message msg = { NULL, NULL, NULL, NULL };
458 struct strbuf msgbuf = STRBUF_INIT;
459 int res, unborn = 0, allow;
461 if (opts->no_commit) {
463 * We do not intend to commit immediately. We just want to
464 * merge the differences in, so let's compute the tree
465 * that represents the "current" state for merge-recursive
466 * to work on.
468 if (write_cache_as_tree(head, 0, NULL))
469 die (_("Your index file is unmerged."));
470 } else {
471 unborn = get_sha1("HEAD", head);
472 if (unborn)
473 hashcpy(head, EMPTY_TREE_SHA1_BIN);
474 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
475 return error_dirty_index(opts);
477 discard_cache();
479 if (!commit->parents) {
480 parent = NULL;
482 else if (commit->parents->next) {
483 /* Reverting or cherry-picking a merge commit */
484 int cnt;
485 struct commit_list *p;
487 if (!opts->mainline)
488 return error(_("Commit %s is a merge but no -m option was given."),
489 sha1_to_hex(commit->object.sha1));
491 for (cnt = 1, p = commit->parents;
492 cnt != opts->mainline && p;
493 cnt++)
494 p = p->next;
495 if (cnt != opts->mainline || !p)
496 return error(_("Commit %s does not have parent %d"),
497 sha1_to_hex(commit->object.sha1), opts->mainline);
498 parent = p->item;
499 } else if (0 < opts->mainline)
500 return error(_("Mainline was specified but commit %s is not a merge."),
501 sha1_to_hex(commit->object.sha1));
502 else
503 parent = commit->parents->item;
505 if (opts->allow_ff &&
506 ((parent && !hashcmp(parent->object.sha1, head)) ||
507 (!parent && unborn)))
508 return fast_forward_to(commit->object.sha1, head, unborn, opts);
510 if (parent && parse_commit(parent) < 0)
511 /* TRANSLATORS: The first %s will be "revert" or
512 "cherry-pick", the second %s a SHA1 */
513 return error(_("%s: cannot parse parent commit %s"),
514 action_name(opts), sha1_to_hex(parent->object.sha1));
516 if (get_message(commit, &msg) != 0)
517 return error(_("Cannot get commit message for %s"),
518 sha1_to_hex(commit->object.sha1));
521 * "commit" is an existing commit. We would want to apply
522 * the difference it introduces since its first parent "prev"
523 * on top of the current HEAD if we are cherry-pick. Or the
524 * reverse of it if we are revert.
527 if (opts->action == REPLAY_REVERT) {
528 base = commit;
529 base_label = msg.label;
530 next = parent;
531 next_label = msg.parent_label;
532 strbuf_addstr(&msgbuf, "Revert \"");
533 strbuf_addstr(&msgbuf, msg.subject);
534 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
535 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
537 if (commit->parents && commit->parents->next) {
538 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
539 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
541 strbuf_addstr(&msgbuf, ".\n");
542 } else {
543 const char *p;
545 base = parent;
546 base_label = msg.parent_label;
547 next = commit;
548 next_label = msg.label;
551 * Append the commit log message to msgbuf; it starts
552 * after the tree, parent, author, committer
553 * information followed by "\n\n".
555 p = strstr(msg.message, "\n\n");
556 if (p) {
557 p += 2;
558 strbuf_addstr(&msgbuf, p);
561 if (opts->record_origin) {
562 if (!has_conforming_footer(&msgbuf, NULL, 0))
563 strbuf_addch(&msgbuf, '\n');
564 strbuf_addstr(&msgbuf, cherry_picked_prefix);
565 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
566 strbuf_addstr(&msgbuf, ")\n");
570 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
571 res = do_recursive_merge(base, next, base_label, next_label,
572 head, &msgbuf, opts);
573 write_message(&msgbuf, git_path_merge_msg());
574 } else {
575 struct commit_list *common = NULL;
576 struct commit_list *remotes = NULL;
578 write_message(&msgbuf, git_path_merge_msg());
580 commit_list_insert(base, &common);
581 commit_list_insert(next, &remotes);
582 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
583 common, sha1_to_hex(head), remotes);
584 free_commit_list(common);
585 free_commit_list(remotes);
589 * If the merge was clean or if it failed due to conflict, we write
590 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
591 * However, if the merge did not even start, then we don't want to
592 * write it at all.
594 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
595 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.sha1, NULL,
596 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
597 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
598 update_ref(NULL, "REVERT_HEAD", commit->object.sha1, NULL,
599 REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
601 if (res) {
602 error(opts->action == REPLAY_REVERT
603 ? _("could not revert %s... %s")
604 : _("could not apply %s... %s"),
605 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
606 msg.subject);
607 print_advice(res == 1, opts);
608 rerere(opts->allow_rerere_auto);
609 goto leave;
612 allow = allow_empty(opts, commit);
613 if (allow < 0) {
614 res = allow;
615 goto leave;
617 if (!opts->no_commit)
618 res = run_git_commit(git_path_merge_msg(), opts, allow);
620 leave:
621 free_message(commit, &msg);
623 return res;
626 static void prepare_revs(struct replay_opts *opts)
629 * picking (but not reverting) ranges (but not individual revisions)
630 * should be done in reverse
632 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
633 opts->revs->reverse ^= 1;
635 if (prepare_revision_walk(opts->revs))
636 die(_("revision walk setup failed"));
638 if (!opts->revs->commits)
639 die(_("empty commit set passed"));
642 static void read_and_refresh_cache(struct replay_opts *opts)
644 static struct lock_file index_lock;
645 int index_fd = hold_locked_index(&index_lock, 0);
646 if (read_index_preload(&the_index, NULL) < 0)
647 die(_("git %s: failed to read the index"), action_name(opts));
648 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
649 if (the_index.cache_changed && index_fd >= 0) {
650 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
651 die(_("git %s: failed to refresh the index"), action_name(opts));
653 rollback_lock_file(&index_lock);
656 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
657 struct replay_opts *opts)
659 struct commit_list *cur = NULL;
660 const char *sha1_abbrev = NULL;
661 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
662 const char *subject;
663 int subject_len;
665 for (cur = todo_list; cur; cur = cur->next) {
666 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
667 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
668 subject_len = find_commit_subject(commit_buffer, &subject);
669 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
670 subject_len, subject);
671 unuse_commit_buffer(cur->item, commit_buffer);
673 return 0;
676 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
678 unsigned char commit_sha1[20];
679 enum replay_action action;
680 char *end_of_object_name;
681 int saved, status, padding;
683 if (starts_with(bol, "pick")) {
684 action = REPLAY_PICK;
685 bol += strlen("pick");
686 } else if (starts_with(bol, "revert")) {
687 action = REPLAY_REVERT;
688 bol += strlen("revert");
689 } else
690 return NULL;
692 /* Eat up extra spaces/ tabs before object name */
693 padding = strspn(bol, " \t");
694 if (!padding)
695 return NULL;
696 bol += padding;
698 end_of_object_name = bol + strcspn(bol, " \t\n");
699 saved = *end_of_object_name;
700 *end_of_object_name = '\0';
701 status = get_sha1(bol, commit_sha1);
702 *end_of_object_name = saved;
705 * Verify that the action matches up with the one in
706 * opts; we don't support arbitrary instructions
708 if (action != opts->action) {
709 const char *action_str;
710 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
711 error(_("Cannot %s during a %s"), action_str, action_name(opts));
712 return NULL;
715 if (status < 0)
716 return NULL;
718 return lookup_commit_reference(commit_sha1);
721 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
722 struct replay_opts *opts)
724 struct commit_list **next = todo_list;
725 struct commit *commit;
726 char *p = buf;
727 int i;
729 for (i = 1; *p; i++) {
730 char *eol = strchrnul(p, '\n');
731 commit = parse_insn_line(p, eol, opts);
732 if (!commit)
733 return error(_("Could not parse line %d."), i);
734 next = commit_list_append(commit, next);
735 p = *eol ? eol + 1 : eol;
737 if (!*todo_list)
738 return error(_("No commits parsed."));
739 return 0;
742 static void read_populate_todo(struct commit_list **todo_list,
743 struct replay_opts *opts)
745 struct strbuf buf = STRBUF_INIT;
746 int fd, res;
748 fd = open(git_path_todo_file(), O_RDONLY);
749 if (fd < 0)
750 die_errno(_("Could not open %s"), git_path_todo_file());
751 if (strbuf_read(&buf, fd, 0) < 0) {
752 close(fd);
753 strbuf_release(&buf);
754 die(_("Could not read %s."), git_path_todo_file());
756 close(fd);
758 res = parse_insn_buffer(buf.buf, todo_list, opts);
759 strbuf_release(&buf);
760 if (res)
761 die(_("Unusable instruction sheet: %s"), git_path_todo_file());
764 static int populate_opts_cb(const char *key, const char *value, void *data)
766 struct replay_opts *opts = data;
767 int error_flag = 1;
769 if (!value)
770 error_flag = 0;
771 else if (!strcmp(key, "options.no-commit"))
772 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
773 else if (!strcmp(key, "options.edit"))
774 opts->edit = git_config_bool_or_int(key, value, &error_flag);
775 else if (!strcmp(key, "options.signoff"))
776 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
777 else if (!strcmp(key, "options.record-origin"))
778 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
779 else if (!strcmp(key, "options.allow-ff"))
780 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
781 else if (!strcmp(key, "options.mainline"))
782 opts->mainline = git_config_int(key, value);
783 else if (!strcmp(key, "options.strategy"))
784 git_config_string(&opts->strategy, key, value);
785 else if (!strcmp(key, "options.gpg-sign"))
786 git_config_string(&opts->gpg_sign, key, value);
787 else if (!strcmp(key, "options.strategy-option")) {
788 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
789 opts->xopts[opts->xopts_nr++] = xstrdup(value);
790 } else
791 return error(_("Invalid key: %s"), key);
793 if (!error_flag)
794 return error(_("Invalid value for %s: %s"), key, value);
796 return 0;
799 static void read_populate_opts(struct replay_opts **opts_ptr)
801 if (!file_exists(git_path_opts_file()))
802 return;
803 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), *opts_ptr) < 0)
804 die(_("Malformed options sheet: %s"), git_path_opts_file());
807 static void walk_revs_populate_todo(struct commit_list **todo_list,
808 struct replay_opts *opts)
810 struct commit *commit;
811 struct commit_list **next;
813 prepare_revs(opts);
815 next = todo_list;
816 while ((commit = get_revision(opts->revs)))
817 next = commit_list_append(commit, next);
820 static int create_seq_dir(void)
822 if (file_exists(git_path_seq_dir())) {
823 error(_("a cherry-pick or revert is already in progress"));
824 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
825 return -1;
827 else if (mkdir(git_path_seq_dir(), 0777) < 0)
828 die_errno(_("Could not create sequencer directory %s"),
829 git_path_seq_dir());
830 return 0;
833 static void save_head(const char *head)
835 static struct lock_file head_lock;
836 struct strbuf buf = STRBUF_INIT;
837 int fd;
839 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), LOCK_DIE_ON_ERROR);
840 strbuf_addf(&buf, "%s\n", head);
841 if (write_in_full(fd, buf.buf, buf.len) < 0)
842 die_errno(_("Could not write to %s"), git_path_head_file());
843 if (commit_lock_file(&head_lock) < 0)
844 die(_("Error wrapping up %s."), git_path_head_file());
847 static int reset_for_rollback(const unsigned char *sha1)
849 const char *argv[4]; /* reset --merge <arg> + NULL */
850 argv[0] = "reset";
851 argv[1] = "--merge";
852 argv[2] = sha1_to_hex(sha1);
853 argv[3] = NULL;
854 return run_command_v_opt(argv, RUN_GIT_CMD);
857 static int rollback_single_pick(void)
859 unsigned char head_sha1[20];
861 if (!file_exists(git_path_cherry_pick_head()) &&
862 !file_exists(git_path_revert_head()))
863 return error(_("no cherry-pick or revert in progress"));
864 if (read_ref_full("HEAD", 0, head_sha1, NULL))
865 return error(_("cannot resolve HEAD"));
866 if (is_null_sha1(head_sha1))
867 return error(_("cannot abort from a branch yet to be born"));
868 return reset_for_rollback(head_sha1);
871 static int sequencer_rollback(struct replay_opts *opts)
873 FILE *f;
874 unsigned char sha1[20];
875 struct strbuf buf = STRBUF_INIT;
877 f = fopen(git_path_head_file(), "r");
878 if (!f && errno == ENOENT) {
880 * There is no multiple-cherry-pick in progress.
881 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
882 * a single-cherry-pick in progress, abort that.
884 return rollback_single_pick();
886 if (!f)
887 return error(_("cannot open %s: %s"), git_path_head_file(),
888 strerror(errno));
889 if (strbuf_getline(&buf, f, '\n')) {
890 error(_("cannot read %s: %s"), git_path_head_file(),
891 ferror(f) ? strerror(errno) : _("unexpected end of file"));
892 fclose(f);
893 goto fail;
895 fclose(f);
896 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
897 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
898 git_path_head_file());
899 goto fail;
901 if (reset_for_rollback(sha1))
902 goto fail;
903 remove_sequencer_state();
904 strbuf_release(&buf);
905 return 0;
906 fail:
907 strbuf_release(&buf);
908 return -1;
911 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
913 static struct lock_file todo_lock;
914 struct strbuf buf = STRBUF_INIT;
915 int fd;
917 fd = hold_lock_file_for_update(&todo_lock, git_path_todo_file(), LOCK_DIE_ON_ERROR);
918 if (format_todo(&buf, todo_list, opts) < 0)
919 die(_("Could not format %s."), git_path_todo_file());
920 if (write_in_full(fd, buf.buf, buf.len) < 0) {
921 strbuf_release(&buf);
922 die_errno(_("Could not write to %s"), git_path_todo_file());
924 if (commit_lock_file(&todo_lock) < 0) {
925 strbuf_release(&buf);
926 die(_("Error wrapping up %s."), git_path_todo_file());
928 strbuf_release(&buf);
931 static void save_opts(struct replay_opts *opts)
933 const char *opts_file = git_path_opts_file();
935 if (opts->no_commit)
936 git_config_set_in_file(opts_file, "options.no-commit", "true");
937 if (opts->edit)
938 git_config_set_in_file(opts_file, "options.edit", "true");
939 if (opts->signoff)
940 git_config_set_in_file(opts_file, "options.signoff", "true");
941 if (opts->record_origin)
942 git_config_set_in_file(opts_file, "options.record-origin", "true");
943 if (opts->allow_ff)
944 git_config_set_in_file(opts_file, "options.allow-ff", "true");
945 if (opts->mainline) {
946 struct strbuf buf = STRBUF_INIT;
947 strbuf_addf(&buf, "%d", opts->mainline);
948 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
949 strbuf_release(&buf);
951 if (opts->strategy)
952 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
953 if (opts->gpg_sign)
954 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
955 if (opts->xopts) {
956 int i;
957 for (i = 0; i < opts->xopts_nr; i++)
958 git_config_set_multivar_in_file(opts_file,
959 "options.strategy-option",
960 opts->xopts[i], "^$", 0);
964 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
966 struct commit_list *cur;
967 int res;
969 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
970 if (opts->allow_ff)
971 assert(!(opts->signoff || opts->no_commit ||
972 opts->record_origin || opts->edit));
973 read_and_refresh_cache(opts);
975 for (cur = todo_list; cur; cur = cur->next) {
976 save_todo(cur, opts);
977 res = do_pick_commit(cur->item, opts);
978 if (res)
979 return res;
983 * Sequence of picks finished successfully; cleanup by
984 * removing the .git/sequencer directory
986 remove_sequencer_state();
987 return 0;
990 static int continue_single_pick(void)
992 const char *argv[] = { "commit", NULL };
994 if (!file_exists(git_path_cherry_pick_head()) &&
995 !file_exists(git_path_revert_head()))
996 return error(_("no cherry-pick or revert in progress"));
997 return run_command_v_opt(argv, RUN_GIT_CMD);
1000 static int sequencer_continue(struct replay_opts *opts)
1002 struct commit_list *todo_list = NULL;
1004 if (!file_exists(git_path_todo_file()))
1005 return continue_single_pick();
1006 read_populate_opts(&opts);
1007 read_populate_todo(&todo_list, opts);
1009 /* Verify that the conflict has been resolved */
1010 if (file_exists(git_path_cherry_pick_head()) ||
1011 file_exists(git_path_revert_head())) {
1012 int ret = continue_single_pick();
1013 if (ret)
1014 return ret;
1016 if (index_differs_from("HEAD", 0))
1017 return error_dirty_index(opts);
1018 todo_list = todo_list->next;
1019 return pick_commits(todo_list, opts);
1022 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1024 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1025 return do_pick_commit(cmit, opts);
1028 int sequencer_pick_revisions(struct replay_opts *opts)
1030 struct commit_list *todo_list = NULL;
1031 unsigned char sha1[20];
1032 int i;
1034 if (opts->subcommand == REPLAY_NONE)
1035 assert(opts->revs);
1037 read_and_refresh_cache(opts);
1040 * Decide what to do depending on the arguments; a fresh
1041 * cherry-pick should be handled differently from an existing
1042 * one that is being continued
1044 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1045 remove_sequencer_state();
1046 return 0;
1048 if (opts->subcommand == REPLAY_ROLLBACK)
1049 return sequencer_rollback(opts);
1050 if (opts->subcommand == REPLAY_CONTINUE)
1051 return sequencer_continue(opts);
1053 for (i = 0; i < opts->revs->pending.nr; i++) {
1054 unsigned char sha1[20];
1055 const char *name = opts->revs->pending.objects[i].name;
1057 /* This happens when using --stdin. */
1058 if (!strlen(name))
1059 continue;
1061 if (!get_sha1(name, sha1)) {
1062 if (!lookup_commit_reference_gently(sha1, 1)) {
1063 enum object_type type = sha1_object_info(sha1, NULL);
1064 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1066 } else
1067 die(_("%s: bad revision"), name);
1071 * If we were called as "git cherry-pick <commit>", just
1072 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1073 * REVERT_HEAD, and don't touch the sequencer state.
1074 * This means it is possible to cherry-pick in the middle
1075 * of a cherry-pick sequence.
1077 if (opts->revs->cmdline.nr == 1 &&
1078 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1079 opts->revs->no_walk &&
1080 !opts->revs->cmdline.rev->flags) {
1081 struct commit *cmit;
1082 if (prepare_revision_walk(opts->revs))
1083 die(_("revision walk setup failed"));
1084 cmit = get_revision(opts->revs);
1085 if (!cmit || get_revision(opts->revs))
1086 die("BUG: expected exactly one commit from walk");
1087 return single_pick(cmit, opts);
1091 * Start a new cherry-pick/ revert sequence; but
1092 * first, make sure that an existing one isn't in
1093 * progress
1096 walk_revs_populate_todo(&todo_list, opts);
1097 if (create_seq_dir() < 0)
1098 return -1;
1099 if (get_sha1("HEAD", sha1)) {
1100 if (opts->action == REPLAY_REVERT)
1101 return error(_("Can't revert as initial commit"));
1102 return error(_("Can't cherry-pick into empty head"));
1104 save_head(sha1_to_hex(sha1));
1105 save_opts(opts);
1106 return pick_commits(todo_list, opts);
1109 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1111 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1112 struct strbuf sob = STRBUF_INIT;
1113 int has_footer;
1115 strbuf_addstr(&sob, sign_off_header);
1116 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1117 getenv("GIT_COMMITTER_EMAIL")));
1118 strbuf_addch(&sob, '\n');
1121 * If the whole message buffer is equal to the sob, pretend that we
1122 * found a conforming footer with a matching sob
1124 if (msgbuf->len - ignore_footer == sob.len &&
1125 !strncmp(msgbuf->buf, sob.buf, sob.len))
1126 has_footer = 3;
1127 else
1128 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1130 if (!has_footer) {
1131 const char *append_newlines = NULL;
1132 size_t len = msgbuf->len - ignore_footer;
1134 if (!len) {
1136 * The buffer is completely empty. Leave foom for
1137 * the title and body to be filled in by the user.
1139 append_newlines = "\n\n";
1140 } else if (msgbuf->buf[len - 1] != '\n') {
1142 * Incomplete line. Complete the line and add a
1143 * blank one so that there is an empty line between
1144 * the message body and the sob.
1146 append_newlines = "\n\n";
1147 } else if (len == 1) {
1149 * Buffer contains a single newline. Add another
1150 * so that we leave room for the title and body.
1152 append_newlines = "\n";
1153 } else if (msgbuf->buf[len - 2] != '\n') {
1155 * Buffer ends with a single newline. Add another
1156 * so that there is an empty line between the message
1157 * body and the sob.
1159 append_newlines = "\n";
1160 } /* else, the buffer already ends with two newlines. */
1162 if (append_newlines)
1163 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1164 append_newlines, strlen(append_newlines));
1167 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1168 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1169 sob.buf, sob.len);
1171 strbuf_release(&sob);