sequencer: future-proof read_populate_todo()
[git/raj.git] / sequencer.c
blobfb0b94bcf37faf39a3589b4473e08c2580bcb5c8
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 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
26 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
27 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
28 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
30 static const char *get_dir(const struct replay_opts *opts)
32 return git_path_seq_dir();
35 static const char *get_todo_path(const struct replay_opts *opts)
37 return git_path_todo_file();
40 static int is_rfc2822_line(const char *buf, int len)
42 int i;
44 for (i = 0; i < len; i++) {
45 int ch = buf[i];
46 if (ch == ':')
47 return 1;
48 if (!isalnum(ch) && ch != '-')
49 break;
52 return 0;
55 static int is_cherry_picked_from_line(const char *buf, int len)
58 * We only care that it looks roughly like (cherry picked from ...)
60 return len > strlen(cherry_picked_prefix) + 1 &&
61 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
65 * Returns 0 for non-conforming footer
66 * Returns 1 for conforming footer
67 * Returns 2 when sob exists within conforming footer
68 * Returns 3 when sob exists within conforming footer as last entry
70 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
71 int ignore_footer)
73 char prev;
74 int i, k;
75 int len = sb->len - ignore_footer;
76 const char *buf = sb->buf;
77 int found_sob = 0;
79 /* footer must end with newline */
80 if (!len || buf[len - 1] != '\n')
81 return 0;
83 prev = '\0';
84 for (i = len - 1; i > 0; i--) {
85 char ch = buf[i];
86 if (prev == '\n' && ch == '\n') /* paragraph break */
87 break;
88 prev = ch;
91 /* require at least one blank line */
92 if (prev != '\n' || buf[i] != '\n')
93 return 0;
95 /* advance to start of last paragraph */
96 while (i < len - 1 && buf[i] == '\n')
97 i++;
99 for (; i < len; i = k) {
100 int found_rfc2822;
102 for (k = i; k < len && buf[k] != '\n'; k++)
103 ; /* do nothing */
104 k++;
106 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
107 if (found_rfc2822 && sob &&
108 !strncmp(buf + i, sob->buf, sob->len))
109 found_sob = k;
111 if (!(found_rfc2822 ||
112 is_cherry_picked_from_line(buf + i, k - i - 1)))
113 return 0;
115 if (found_sob == i)
116 return 3;
117 if (found_sob)
118 return 2;
119 return 1;
122 static void remove_sequencer_state(const struct replay_opts *opts)
124 struct strbuf dir = STRBUF_INIT;
125 int i;
127 free(opts->gpg_sign);
128 free(opts->strategy);
129 for (i = 0; i < opts->xopts_nr; i++)
130 free(opts->xopts[i]);
131 free(opts->xopts);
133 strbuf_addf(&dir, "%s", get_dir(opts));
134 remove_dir_recursively(&dir, 0);
135 strbuf_release(&dir);
138 static const char *action_name(const struct replay_opts *opts)
140 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
143 struct commit_message {
144 char *parent_label;
145 char *label;
146 char *subject;
147 const char *message;
150 static int get_message(struct commit *commit, struct commit_message *out)
152 const char *abbrev, *subject;
153 int subject_len;
155 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
156 abbrev = find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
158 subject_len = find_commit_subject(out->message, &subject);
160 out->subject = xmemdupz(subject, subject_len);
161 out->label = xstrfmt("%s... %s", abbrev, out->subject);
162 out->parent_label = xstrfmt("parent of %s", out->label);
164 return 0;
167 static void free_message(struct commit *commit, struct commit_message *msg)
169 free(msg->parent_label);
170 free(msg->label);
171 free(msg->subject);
172 unuse_commit_buffer(commit, msg->message);
175 static void print_advice(int show_hint, struct replay_opts *opts)
177 char *msg = getenv("GIT_CHERRY_PICK_HELP");
179 if (msg) {
180 fprintf(stderr, "%s\n", msg);
182 * A conflict has occurred but the porcelain
183 * (typically rebase --interactive) wants to take care
184 * of the commit itself so remove CHERRY_PICK_HEAD
186 unlink(git_path_cherry_pick_head());
187 return;
190 if (show_hint) {
191 if (opts->no_commit)
192 advise(_("after resolving the conflicts, mark the corrected paths\n"
193 "with 'git add <paths>' or 'git rm <paths>'"));
194 else
195 advise(_("after resolving the conflicts, mark the corrected paths\n"
196 "with 'git add <paths>' or 'git rm <paths>'\n"
197 "and commit the result with 'git commit'"));
201 static int write_message(struct strbuf *msgbuf, const char *filename)
203 static struct lock_file msg_file;
205 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
206 if (msg_fd < 0)
207 return error_errno(_("Could not lock '%s'"), filename);
208 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
209 return error_errno(_("Could not write to %s"), filename);
210 strbuf_release(msgbuf);
211 if (commit_lock_file(&msg_file) < 0)
212 return error(_("Error wrapping up %s."), filename);
214 return 0;
217 static struct tree *empty_tree(void)
219 return lookup_tree(EMPTY_TREE_SHA1_BIN);
222 static int error_dirty_index(struct replay_opts *opts)
224 if (read_cache_unmerged())
225 return error_resolve_conflict(action_name(opts));
227 /* Different translation strings for cherry-pick and revert */
228 if (opts->action == REPLAY_PICK)
229 error(_("Your local changes would be overwritten by cherry-pick."));
230 else
231 error(_("Your local changes would be overwritten by revert."));
233 if (advice_commit_before_merge)
234 advise(_("Commit your changes or stash them to proceed."));
235 return -1;
238 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
239 int unborn, struct replay_opts *opts)
241 struct ref_transaction *transaction;
242 struct strbuf sb = STRBUF_INIT;
243 struct strbuf err = STRBUF_INIT;
245 read_cache();
246 if (checkout_fast_forward(from, to, 1))
247 return -1; /* the callee should have complained already */
249 strbuf_addf(&sb, _("%s: fast-forward"), action_name(opts));
251 transaction = ref_transaction_begin(&err);
252 if (!transaction ||
253 ref_transaction_update(transaction, "HEAD",
254 to, unborn ? null_sha1 : from,
255 0, sb.buf, &err) ||
256 ref_transaction_commit(transaction, &err)) {
257 ref_transaction_free(transaction);
258 error("%s", err.buf);
259 strbuf_release(&sb);
260 strbuf_release(&err);
261 return -1;
264 strbuf_release(&sb);
265 strbuf_release(&err);
266 ref_transaction_free(transaction);
267 return 0;
270 void append_conflicts_hint(struct strbuf *msgbuf)
272 int i;
274 strbuf_addch(msgbuf, '\n');
275 strbuf_commented_addf(msgbuf, "Conflicts:\n");
276 for (i = 0; i < active_nr;) {
277 const struct cache_entry *ce = active_cache[i++];
278 if (ce_stage(ce)) {
279 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
280 while (i < active_nr && !strcmp(ce->name,
281 active_cache[i]->name))
282 i++;
287 static int do_recursive_merge(struct commit *base, struct commit *next,
288 const char *base_label, const char *next_label,
289 unsigned char *head, struct strbuf *msgbuf,
290 struct replay_opts *opts)
292 struct merge_options o;
293 struct tree *result, *next_tree, *base_tree, *head_tree;
294 int clean;
295 char **xopt;
296 static struct lock_file index_lock;
298 hold_locked_index(&index_lock, 1);
300 read_cache();
302 init_merge_options(&o);
303 o.ancestor = base ? base_label : "(empty tree)";
304 o.branch1 = "HEAD";
305 o.branch2 = next ? next_label : "(empty tree)";
307 head_tree = parse_tree_indirect(head);
308 next_tree = next ? next->tree : empty_tree();
309 base_tree = base ? base->tree : empty_tree();
311 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
312 parse_merge_opt(&o, *xopt);
314 clean = merge_trees(&o,
315 head_tree,
316 next_tree, base_tree, &result);
317 strbuf_release(&o.obuf);
318 if (clean < 0)
319 return clean;
321 if (active_cache_changed &&
322 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
323 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
324 return error(_("%s: Unable to write new index file"),
325 action_name(opts));
326 rollback_lock_file(&index_lock);
328 if (opts->signoff)
329 append_signoff(msgbuf, 0, 0);
331 if (!clean)
332 append_conflicts_hint(msgbuf);
334 return !clean;
337 static int is_index_unchanged(void)
339 unsigned char head_sha1[20];
340 struct commit *head_commit;
342 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
343 return error(_("Could not resolve HEAD commit\n"));
345 head_commit = lookup_commit(head_sha1);
348 * If head_commit is NULL, check_commit, called from
349 * lookup_commit, would have indicated that head_commit is not
350 * a commit object already. parse_commit() will return failure
351 * without further complaints in such a case. Otherwise, if
352 * the commit is invalid, parse_commit() will complain. So
353 * there is nothing for us to say here. Just return failure.
355 if (parse_commit(head_commit))
356 return -1;
358 if (!active_cache_tree)
359 active_cache_tree = cache_tree();
361 if (!cache_tree_fully_valid(active_cache_tree))
362 if (cache_tree_update(&the_index, 0))
363 return error(_("Unable to update cache tree\n"));
365 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
369 * If we are cherry-pick, and if the merge did not result in
370 * hand-editing, we will hit this commit and inherit the original
371 * author date and name.
372 * If we are revert, or if our cherry-pick results in a hand merge,
373 * we had better say that the current user is responsible for that.
375 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
376 int allow_empty)
378 struct argv_array array;
379 int rc;
380 const char *value;
382 argv_array_init(&array);
383 argv_array_push(&array, "commit");
384 argv_array_push(&array, "-n");
386 if (opts->gpg_sign)
387 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
388 if (opts->signoff)
389 argv_array_push(&array, "-s");
390 if (!opts->edit) {
391 argv_array_push(&array, "-F");
392 argv_array_push(&array, defmsg);
393 if (!opts->signoff &&
394 !opts->record_origin &&
395 git_config_get_value("commit.cleanup", &value))
396 argv_array_push(&array, "--cleanup=verbatim");
399 if (allow_empty)
400 argv_array_push(&array, "--allow-empty");
402 if (opts->allow_empty_message)
403 argv_array_push(&array, "--allow-empty-message");
405 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
406 argv_array_clear(&array);
407 return rc;
410 static int is_original_commit_empty(struct commit *commit)
412 const unsigned char *ptree_sha1;
414 if (parse_commit(commit))
415 return error(_("Could not parse commit %s\n"),
416 oid_to_hex(&commit->object.oid));
417 if (commit->parents) {
418 struct commit *parent = commit->parents->item;
419 if (parse_commit(parent))
420 return error(_("Could not parse parent commit %s\n"),
421 oid_to_hex(&parent->object.oid));
422 ptree_sha1 = parent->tree->object.oid.hash;
423 } else {
424 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
427 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
431 * Do we run "git commit" with "--allow-empty"?
433 static int allow_empty(struct replay_opts *opts, struct commit *commit)
435 int index_unchanged, empty_commit;
438 * Three cases:
440 * (1) we do not allow empty at all and error out.
442 * (2) we allow ones that were initially empty, but
443 * forbid the ones that become empty;
445 * (3) we allow both.
447 if (!opts->allow_empty)
448 return 0; /* let "git commit" barf as necessary */
450 index_unchanged = is_index_unchanged();
451 if (index_unchanged < 0)
452 return index_unchanged;
453 if (!index_unchanged)
454 return 0; /* we do not have to say --allow-empty */
456 if (opts->keep_redundant_commits)
457 return 1;
459 empty_commit = is_original_commit_empty(commit);
460 if (empty_commit < 0)
461 return empty_commit;
462 if (!empty_commit)
463 return 0;
464 else
465 return 1;
468 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
470 unsigned char head[20];
471 struct commit *base, *next, *parent;
472 const char *base_label, *next_label;
473 struct commit_message msg = { NULL, NULL, NULL, NULL };
474 struct strbuf msgbuf = STRBUF_INIT;
475 int res, unborn = 0, allow;
477 if (opts->no_commit) {
479 * We do not intend to commit immediately. We just want to
480 * merge the differences in, so let's compute the tree
481 * that represents the "current" state for merge-recursive
482 * to work on.
484 if (write_cache_as_tree(head, 0, NULL))
485 return error(_("Your index file is unmerged."));
486 } else {
487 unborn = get_sha1("HEAD", head);
488 if (unborn)
489 hashcpy(head, EMPTY_TREE_SHA1_BIN);
490 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
491 return error_dirty_index(opts);
493 discard_cache();
495 if (!commit->parents) {
496 parent = NULL;
498 else if (commit->parents->next) {
499 /* Reverting or cherry-picking a merge commit */
500 int cnt;
501 struct commit_list *p;
503 if (!opts->mainline)
504 return error(_("Commit %s is a merge but no -m option was given."),
505 oid_to_hex(&commit->object.oid));
507 for (cnt = 1, p = commit->parents;
508 cnt != opts->mainline && p;
509 cnt++)
510 p = p->next;
511 if (cnt != opts->mainline || !p)
512 return error(_("Commit %s does not have parent %d"),
513 oid_to_hex(&commit->object.oid), opts->mainline);
514 parent = p->item;
515 } else if (0 < opts->mainline)
516 return error(_("Mainline was specified but commit %s is not a merge."),
517 oid_to_hex(&commit->object.oid));
518 else
519 parent = commit->parents->item;
521 if (opts->allow_ff &&
522 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
523 (!parent && unborn)))
524 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
526 if (parent && parse_commit(parent) < 0)
527 /* TRANSLATORS: The first %s will be "revert" or
528 "cherry-pick", the second %s a SHA1 */
529 return error(_("%s: cannot parse parent commit %s"),
530 action_name(opts), oid_to_hex(&parent->object.oid));
532 if (get_message(commit, &msg) != 0)
533 return error(_("Cannot get commit message for %s"),
534 oid_to_hex(&commit->object.oid));
537 * "commit" is an existing commit. We would want to apply
538 * the difference it introduces since its first parent "prev"
539 * on top of the current HEAD if we are cherry-pick. Or the
540 * reverse of it if we are revert.
543 if (opts->action == REPLAY_REVERT) {
544 base = commit;
545 base_label = msg.label;
546 next = parent;
547 next_label = msg.parent_label;
548 strbuf_addstr(&msgbuf, "Revert \"");
549 strbuf_addstr(&msgbuf, msg.subject);
550 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
551 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
553 if (commit->parents && commit->parents->next) {
554 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
555 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
557 strbuf_addstr(&msgbuf, ".\n");
558 } else {
559 const char *p;
561 base = parent;
562 base_label = msg.parent_label;
563 next = commit;
564 next_label = msg.label;
567 * Append the commit log message to msgbuf; it starts
568 * after the tree, parent, author, committer
569 * information followed by "\n\n".
571 p = strstr(msg.message, "\n\n");
572 if (p)
573 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
575 if (opts->record_origin) {
576 if (!has_conforming_footer(&msgbuf, NULL, 0))
577 strbuf_addch(&msgbuf, '\n');
578 strbuf_addstr(&msgbuf, cherry_picked_prefix);
579 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
580 strbuf_addstr(&msgbuf, ")\n");
584 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
585 res = do_recursive_merge(base, next, base_label, next_label,
586 head, &msgbuf, opts);
587 if (res < 0)
588 return res;
589 res |= write_message(&msgbuf, git_path_merge_msg());
590 } else {
591 struct commit_list *common = NULL;
592 struct commit_list *remotes = NULL;
594 res = write_message(&msgbuf, git_path_merge_msg());
596 commit_list_insert(base, &common);
597 commit_list_insert(next, &remotes);
598 res |= try_merge_command(opts->strategy,
599 opts->xopts_nr, (const char **)opts->xopts,
600 common, sha1_to_hex(head), remotes);
601 free_commit_list(common);
602 free_commit_list(remotes);
606 * If the merge was clean or if it failed due to conflict, we write
607 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
608 * However, if the merge did not even start, then we don't want to
609 * write it at all.
611 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1) &&
612 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
613 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
614 res = -1;
615 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
616 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
617 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
618 res = -1;
620 if (res) {
621 error(opts->action == REPLAY_REVERT
622 ? _("could not revert %s... %s")
623 : _("could not apply %s... %s"),
624 find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV),
625 msg.subject);
626 print_advice(res == 1, opts);
627 rerere(opts->allow_rerere_auto);
628 goto leave;
631 allow = allow_empty(opts, commit);
632 if (allow < 0) {
633 res = allow;
634 goto leave;
636 if (!opts->no_commit)
637 res = run_git_commit(git_path_merge_msg(), opts, allow);
639 leave:
640 free_message(commit, &msg);
642 return res;
645 static int prepare_revs(struct replay_opts *opts)
648 * picking (but not reverting) ranges (but not individual revisions)
649 * should be done in reverse
651 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
652 opts->revs->reverse ^= 1;
654 if (prepare_revision_walk(opts->revs))
655 return error(_("revision walk setup failed"));
657 if (!opts->revs->commits)
658 return error(_("empty commit set passed"));
659 return 0;
662 static int read_and_refresh_cache(struct replay_opts *opts)
664 static struct lock_file index_lock;
665 int index_fd = hold_locked_index(&index_lock, 0);
666 if (read_index_preload(&the_index, NULL) < 0) {
667 rollback_lock_file(&index_lock);
668 return error(_("git %s: failed to read the index"),
669 action_name(opts));
671 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
672 if (the_index.cache_changed && index_fd >= 0) {
673 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
674 rollback_lock_file(&index_lock);
675 return error(_("git %s: failed to refresh the index"),
676 action_name(opts));
679 rollback_lock_file(&index_lock);
680 return 0;
683 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
684 struct replay_opts *opts)
686 struct commit_list *cur = NULL;
687 const char *sha1_abbrev = NULL;
688 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
689 const char *subject;
690 int subject_len;
692 for (cur = todo_list; cur; cur = cur->next) {
693 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
694 sha1_abbrev = find_unique_abbrev(cur->item->object.oid.hash, DEFAULT_ABBREV);
695 subject_len = find_commit_subject(commit_buffer, &subject);
696 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
697 subject_len, subject);
698 unuse_commit_buffer(cur->item, commit_buffer);
700 return 0;
703 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
705 unsigned char commit_sha1[20];
706 enum replay_action action;
707 char *end_of_object_name;
708 int saved, status, padding;
710 if (starts_with(bol, "pick")) {
711 action = REPLAY_PICK;
712 bol += strlen("pick");
713 } else if (starts_with(bol, "revert")) {
714 action = REPLAY_REVERT;
715 bol += strlen("revert");
716 } else
717 return NULL;
719 /* Eat up extra spaces/ tabs before object name */
720 padding = strspn(bol, " \t");
721 if (!padding)
722 return NULL;
723 bol += padding;
725 end_of_object_name = bol + strcspn(bol, " \t\n");
726 saved = *end_of_object_name;
727 *end_of_object_name = '\0';
728 status = get_sha1(bol, commit_sha1);
729 *end_of_object_name = saved;
732 * Verify that the action matches up with the one in
733 * opts; we don't support arbitrary instructions
735 if (action != opts->action) {
736 if (action == REPLAY_REVERT)
737 error((opts->action == REPLAY_REVERT)
738 ? _("Cannot revert during another revert.")
739 : _("Cannot revert during a cherry-pick."));
740 else
741 error((opts->action == REPLAY_REVERT)
742 ? _("Cannot cherry-pick during a revert.")
743 : _("Cannot cherry-pick during another cherry-pick."));
744 return NULL;
747 if (status < 0)
748 return NULL;
750 return lookup_commit_reference(commit_sha1);
753 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
754 struct replay_opts *opts)
756 struct commit_list **next = todo_list;
757 struct commit *commit;
758 char *p = buf;
759 int i;
761 for (i = 1; *p; i++) {
762 char *eol = strchrnul(p, '\n');
763 commit = parse_insn_line(p, eol, opts);
764 if (!commit)
765 return error(_("Could not parse line %d."), i);
766 next = commit_list_append(commit, next);
767 p = *eol ? eol + 1 : eol;
769 if (!*todo_list)
770 return error(_("No commits parsed."));
771 return 0;
774 static int read_populate_todo(struct commit_list **todo_list,
775 struct replay_opts *opts)
777 const char *todo_file = get_todo_path(opts);
778 struct strbuf buf = STRBUF_INIT;
779 int fd, res;
781 fd = open(todo_file, O_RDONLY);
782 if (fd < 0)
783 return error_errno(_("Could not open %s"), todo_file);
784 if (strbuf_read(&buf, fd, 0) < 0) {
785 close(fd);
786 strbuf_release(&buf);
787 return error(_("Could not read %s."), todo_file);
789 close(fd);
791 res = parse_insn_buffer(buf.buf, todo_list, opts);
792 strbuf_release(&buf);
793 if (res)
794 return error(_("Unusable instruction sheet: %s"), todo_file);
795 return 0;
798 static int git_config_string_dup(char **dest,
799 const char *var, const char *value)
801 if (!value)
802 return config_error_nonbool(var);
803 free(*dest);
804 *dest = xstrdup(value);
805 return 0;
808 static int populate_opts_cb(const char *key, const char *value, void *data)
810 struct replay_opts *opts = data;
811 int error_flag = 1;
813 if (!value)
814 error_flag = 0;
815 else if (!strcmp(key, "options.no-commit"))
816 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
817 else if (!strcmp(key, "options.edit"))
818 opts->edit = git_config_bool_or_int(key, value, &error_flag);
819 else if (!strcmp(key, "options.signoff"))
820 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
821 else if (!strcmp(key, "options.record-origin"))
822 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
823 else if (!strcmp(key, "options.allow-ff"))
824 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
825 else if (!strcmp(key, "options.mainline"))
826 opts->mainline = git_config_int(key, value);
827 else if (!strcmp(key, "options.strategy"))
828 git_config_string_dup(&opts->strategy, key, value);
829 else if (!strcmp(key, "options.gpg-sign"))
830 git_config_string_dup(&opts->gpg_sign, key, value);
831 else if (!strcmp(key, "options.strategy-option")) {
832 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
833 opts->xopts[opts->xopts_nr++] = xstrdup(value);
834 } else
835 return error(_("Invalid key: %s"), key);
837 if (!error_flag)
838 return error(_("Invalid value for %s: %s"), key, value);
840 return 0;
843 static int read_populate_opts(struct replay_opts *opts)
845 if (!file_exists(git_path_opts_file()))
846 return 0;
848 * The function git_parse_source(), called from git_config_from_file(),
849 * may die() in case of a syntactically incorrect file. We do not care
850 * about this case, though, because we wrote that file ourselves, so we
851 * are pretty certain that it is syntactically correct.
853 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
854 return error(_("Malformed options sheet: %s"),
855 git_path_opts_file());
856 return 0;
859 static int walk_revs_populate_todo(struct commit_list **todo_list,
860 struct replay_opts *opts)
862 struct commit *commit;
863 struct commit_list **next;
865 if (prepare_revs(opts))
866 return -1;
868 next = todo_list;
869 while ((commit = get_revision(opts->revs)))
870 next = commit_list_append(commit, next);
871 return 0;
874 static int create_seq_dir(void)
876 if (file_exists(git_path_seq_dir())) {
877 error(_("a cherry-pick or revert is already in progress"));
878 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
879 return -1;
881 else if (mkdir(git_path_seq_dir(), 0777) < 0)
882 return error_errno(_("Could not create sequencer directory %s"),
883 git_path_seq_dir());
884 return 0;
887 static int save_head(const char *head)
889 static struct lock_file head_lock;
890 struct strbuf buf = STRBUF_INIT;
891 int fd;
893 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
894 if (fd < 0) {
895 rollback_lock_file(&head_lock);
896 return error_errno(_("Could not lock HEAD"));
898 strbuf_addf(&buf, "%s\n", head);
899 if (write_in_full(fd, buf.buf, buf.len) < 0) {
900 rollback_lock_file(&head_lock);
901 return error_errno(_("Could not write to %s"),
902 git_path_head_file());
904 if (commit_lock_file(&head_lock) < 0) {
905 rollback_lock_file(&head_lock);
906 return error(_("Error wrapping up %s."), git_path_head_file());
908 return 0;
911 static int reset_for_rollback(const unsigned char *sha1)
913 const char *argv[4]; /* reset --merge <arg> + NULL */
914 argv[0] = "reset";
915 argv[1] = "--merge";
916 argv[2] = sha1_to_hex(sha1);
917 argv[3] = NULL;
918 return run_command_v_opt(argv, RUN_GIT_CMD);
921 static int rollback_single_pick(void)
923 unsigned char head_sha1[20];
925 if (!file_exists(git_path_cherry_pick_head()) &&
926 !file_exists(git_path_revert_head()))
927 return error(_("no cherry-pick or revert in progress"));
928 if (read_ref_full("HEAD", 0, head_sha1, NULL))
929 return error(_("cannot resolve HEAD"));
930 if (is_null_sha1(head_sha1))
931 return error(_("cannot abort from a branch yet to be born"));
932 return reset_for_rollback(head_sha1);
935 static int sequencer_rollback(struct replay_opts *opts)
937 FILE *f;
938 unsigned char sha1[20];
939 struct strbuf buf = STRBUF_INIT;
941 f = fopen(git_path_head_file(), "r");
942 if (!f && errno == ENOENT) {
944 * There is no multiple-cherry-pick in progress.
945 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
946 * a single-cherry-pick in progress, abort that.
948 return rollback_single_pick();
950 if (!f)
951 return error_errno(_("cannot open %s"), git_path_head_file());
952 if (strbuf_getline_lf(&buf, f)) {
953 error(_("cannot read %s: %s"), git_path_head_file(),
954 ferror(f) ? strerror(errno) : _("unexpected end of file"));
955 fclose(f);
956 goto fail;
958 fclose(f);
959 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
960 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
961 git_path_head_file());
962 goto fail;
964 if (is_null_sha1(sha1)) {
965 error(_("cannot abort from a branch yet to be born"));
966 goto fail;
968 if (reset_for_rollback(sha1))
969 goto fail;
970 remove_sequencer_state(opts);
971 strbuf_release(&buf);
972 return 0;
973 fail:
974 strbuf_release(&buf);
975 return -1;
978 static int save_todo(struct commit_list *todo_list, struct replay_opts *opts)
980 static struct lock_file todo_lock;
981 struct strbuf buf = STRBUF_INIT;
982 int fd;
984 fd = hold_lock_file_for_update(&todo_lock, git_path_todo_file(), 0);
985 if (fd < 0)
986 return error_errno(_("Could not lock '%s'"),
987 git_path_todo_file());
988 if (format_todo(&buf, todo_list, opts) < 0) {
989 strbuf_release(&buf);
990 return error(_("Could not format %s."), git_path_todo_file());
992 if (write_in_full(fd, buf.buf, buf.len) < 0) {
993 strbuf_release(&buf);
994 return error_errno(_("Could not write to %s"),
995 git_path_todo_file());
997 if (commit_lock_file(&todo_lock) < 0) {
998 strbuf_release(&buf);
999 return error(_("Error wrapping up %s."), git_path_todo_file());
1001 strbuf_release(&buf);
1002 return 0;
1005 static int save_opts(struct replay_opts *opts)
1007 const char *opts_file = git_path_opts_file();
1008 int res = 0;
1010 if (opts->no_commit)
1011 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1012 if (opts->edit)
1013 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1014 if (opts->signoff)
1015 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1016 if (opts->record_origin)
1017 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1018 if (opts->allow_ff)
1019 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1020 if (opts->mainline) {
1021 struct strbuf buf = STRBUF_INIT;
1022 strbuf_addf(&buf, "%d", opts->mainline);
1023 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1024 strbuf_release(&buf);
1026 if (opts->strategy)
1027 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1028 if (opts->gpg_sign)
1029 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1030 if (opts->xopts) {
1031 int i;
1032 for (i = 0; i < opts->xopts_nr; i++)
1033 res |= git_config_set_multivar_in_file_gently(opts_file,
1034 "options.strategy-option",
1035 opts->xopts[i], "^$", 0);
1037 return res;
1040 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1042 struct commit_list *cur;
1043 int res;
1045 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1046 if (opts->allow_ff)
1047 assert(!(opts->signoff || opts->no_commit ||
1048 opts->record_origin || opts->edit));
1049 if (read_and_refresh_cache(opts))
1050 return -1;
1052 for (cur = todo_list; cur; cur = cur->next) {
1053 if (save_todo(cur, opts))
1054 return -1;
1055 res = do_pick_commit(cur->item, opts);
1056 if (res)
1057 return res;
1061 * Sequence of picks finished successfully; cleanup by
1062 * removing the .git/sequencer directory
1064 remove_sequencer_state(opts);
1065 return 0;
1068 static int continue_single_pick(void)
1070 const char *argv[] = { "commit", NULL };
1072 if (!file_exists(git_path_cherry_pick_head()) &&
1073 !file_exists(git_path_revert_head()))
1074 return error(_("no cherry-pick or revert in progress"));
1075 return run_command_v_opt(argv, RUN_GIT_CMD);
1078 static int sequencer_continue(struct replay_opts *opts)
1080 struct commit_list *todo_list = NULL;
1082 if (!file_exists(get_todo_path(opts)))
1083 return continue_single_pick();
1084 if (read_populate_opts(opts) ||
1085 read_populate_todo(&todo_list, opts))
1086 return -1;
1088 /* Verify that the conflict has been resolved */
1089 if (file_exists(git_path_cherry_pick_head()) ||
1090 file_exists(git_path_revert_head())) {
1091 int ret = continue_single_pick();
1092 if (ret)
1093 return ret;
1095 if (index_differs_from("HEAD", 0))
1096 return error_dirty_index(opts);
1097 todo_list = todo_list->next;
1098 return pick_commits(todo_list, opts);
1101 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1103 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1104 return do_pick_commit(cmit, opts);
1107 int sequencer_pick_revisions(struct replay_opts *opts)
1109 struct commit_list *todo_list = NULL;
1110 unsigned char sha1[20];
1111 int i;
1113 if (opts->subcommand == REPLAY_NONE)
1114 assert(opts->revs);
1116 if (read_and_refresh_cache(opts))
1117 return -1;
1120 * Decide what to do depending on the arguments; a fresh
1121 * cherry-pick should be handled differently from an existing
1122 * one that is being continued
1124 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1125 remove_sequencer_state(opts);
1126 return 0;
1128 if (opts->subcommand == REPLAY_ROLLBACK)
1129 return sequencer_rollback(opts);
1130 if (opts->subcommand == REPLAY_CONTINUE)
1131 return sequencer_continue(opts);
1133 for (i = 0; i < opts->revs->pending.nr; i++) {
1134 unsigned char sha1[20];
1135 const char *name = opts->revs->pending.objects[i].name;
1137 /* This happens when using --stdin. */
1138 if (!strlen(name))
1139 continue;
1141 if (!get_sha1(name, sha1)) {
1142 if (!lookup_commit_reference_gently(sha1, 1)) {
1143 enum object_type type = sha1_object_info(sha1, NULL);
1144 return error(_("%s: can't cherry-pick a %s"),
1145 name, typename(type));
1147 } else
1148 return error(_("%s: bad revision"), name);
1152 * If we were called as "git cherry-pick <commit>", just
1153 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1154 * REVERT_HEAD, and don't touch the sequencer state.
1155 * This means it is possible to cherry-pick in the middle
1156 * of a cherry-pick sequence.
1158 if (opts->revs->cmdline.nr == 1 &&
1159 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1160 opts->revs->no_walk &&
1161 !opts->revs->cmdline.rev->flags) {
1162 struct commit *cmit;
1163 if (prepare_revision_walk(opts->revs))
1164 return error(_("revision walk setup failed"));
1165 cmit = get_revision(opts->revs);
1166 if (!cmit || get_revision(opts->revs))
1167 return error("BUG: expected exactly one commit from walk");
1168 return single_pick(cmit, opts);
1172 * Start a new cherry-pick/ revert sequence; but
1173 * first, make sure that an existing one isn't in
1174 * progress
1177 if (walk_revs_populate_todo(&todo_list, opts) ||
1178 create_seq_dir() < 0)
1179 return -1;
1180 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1181 return error(_("Can't revert as initial commit"));
1182 if (save_head(sha1_to_hex(sha1)))
1183 return -1;
1184 if (save_opts(opts))
1185 return -1;
1186 return pick_commits(todo_list, opts);
1189 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1191 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1192 struct strbuf sob = STRBUF_INIT;
1193 int has_footer;
1195 strbuf_addstr(&sob, sign_off_header);
1196 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1197 getenv("GIT_COMMITTER_EMAIL")));
1198 strbuf_addch(&sob, '\n');
1201 * If the whole message buffer is equal to the sob, pretend that we
1202 * found a conforming footer with a matching sob
1204 if (msgbuf->len - ignore_footer == sob.len &&
1205 !strncmp(msgbuf->buf, sob.buf, sob.len))
1206 has_footer = 3;
1207 else
1208 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1210 if (!has_footer) {
1211 const char *append_newlines = NULL;
1212 size_t len = msgbuf->len - ignore_footer;
1214 if (!len) {
1216 * The buffer is completely empty. Leave foom for
1217 * the title and body to be filled in by the user.
1219 append_newlines = "\n\n";
1220 } else if (msgbuf->buf[len - 1] != '\n') {
1222 * Incomplete line. Complete the line and add a
1223 * blank one so that there is an empty line between
1224 * the message body and the sob.
1226 append_newlines = "\n\n";
1227 } else if (len == 1) {
1229 * Buffer contains a single newline. Add another
1230 * so that we leave room for the title and body.
1232 append_newlines = "\n";
1233 } else if (msgbuf->buf[len - 2] != '\n') {
1235 * Buffer ends with a single newline. Add another
1236 * so that there is an empty line between the message
1237 * body and the sob.
1239 append_newlines = "\n";
1240 } /* else, the buffer already ends with two newlines. */
1242 if (append_newlines)
1243 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1244 append_newlines, strlen(append_newlines));
1247 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1248 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1249 sob.buf, sob.len);
1251 strbuf_release(&sob);