t2104: make sure split index mode is off for the version test
[git/gitweb.git] / sequencer.c
blob4b709dba5f2e427afa87bc1b2e1f16e32f946c87
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 static char *get_encoding(const char *message);
121 struct commit_message {
122 char *parent_label;
123 const char *label;
124 const char *subject;
125 char *reencoded_message;
126 const char *message;
129 static int get_message(struct commit *commit, struct commit_message *out)
131 const char *encoding;
132 const char *abbrev, *subject;
133 int abbrev_len, subject_len;
134 char *q;
136 if (!commit->buffer)
137 return -1;
138 encoding = get_encoding(commit->buffer);
139 if (!encoding)
140 encoding = "UTF-8";
141 if (!git_commit_encoding)
142 git_commit_encoding = "UTF-8";
144 out->reencoded_message = NULL;
145 out->message = commit->buffer;
146 if (same_encoding(encoding, git_commit_encoding))
147 out->reencoded_message = reencode_string(commit->buffer,
148 git_commit_encoding, encoding);
149 if (out->reencoded_message)
150 out->message = out->reencoded_message;
152 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
153 abbrev_len = strlen(abbrev);
155 subject_len = find_commit_subject(out->message, &subject);
157 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
158 strlen("... ") + subject_len + 1);
159 q = out->parent_label;
160 q = mempcpy(q, "parent of ", strlen("parent of "));
161 out->label = q;
162 q = mempcpy(q, abbrev, abbrev_len);
163 q = mempcpy(q, "... ", strlen("... "));
164 out->subject = q;
165 q = mempcpy(q, subject, subject_len);
166 *q = '\0';
167 return 0;
170 static void free_message(struct commit_message *msg)
172 free(msg->parent_label);
173 free(msg->reencoded_message);
176 static char *get_encoding(const char *message)
178 const char *p = message, *eol;
180 while (*p && *p != '\n') {
181 for (eol = p + 1; *eol && *eol != '\n'; eol++)
182 ; /* do nothing */
183 if (starts_with(p, "encoding ")) {
184 char *result = xmalloc(eol - 8 - p);
185 strlcpy(result, p + 9, eol - 8 - p);
186 return result;
188 p = eol;
189 if (*p == '\n')
190 p++;
192 return NULL;
195 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
197 const char *filename;
198 int fd;
199 struct strbuf buf = STRBUF_INIT;
201 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
203 filename = git_path("%s", pseudoref);
204 fd = open(filename, O_WRONLY | O_CREAT, 0666);
205 if (fd < 0)
206 die_errno(_("Could not open '%s' for writing"), filename);
207 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
208 die_errno(_("Could not write to '%s'"), filename);
209 strbuf_release(&buf);
212 static void print_advice(int show_hint, struct replay_opts *opts)
214 char *msg = getenv("GIT_CHERRY_PICK_HELP");
216 if (msg) {
217 fprintf(stderr, "%s\n", msg);
219 * A conflict has occurred but the porcelain
220 * (typically rebase --interactive) wants to take care
221 * of the commit itself so remove CHERRY_PICK_HEAD
223 unlink(git_path("CHERRY_PICK_HEAD"));
224 return;
227 if (show_hint) {
228 if (opts->no_commit)
229 advise(_("after resolving the conflicts, mark the corrected paths\n"
230 "with 'git add <paths>' or 'git rm <paths>'"));
231 else
232 advise(_("after resolving the conflicts, mark the corrected paths\n"
233 "with 'git add <paths>' or 'git rm <paths>'\n"
234 "and commit the result with 'git commit'"));
238 static void write_message(struct strbuf *msgbuf, const char *filename)
240 static struct lock_file msg_file;
242 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
243 LOCK_DIE_ON_ERROR);
244 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
245 die_errno(_("Could not write to %s"), filename);
246 strbuf_release(msgbuf);
247 if (commit_lock_file(&msg_file) < 0)
248 die(_("Error wrapping up %s"), filename);
251 static struct tree *empty_tree(void)
253 return lookup_tree(EMPTY_TREE_SHA1_BIN);
256 static int error_dirty_index(struct replay_opts *opts)
258 if (read_cache_unmerged())
259 return error_resolve_conflict(action_name(opts));
261 /* Different translation strings for cherry-pick and revert */
262 if (opts->action == REPLAY_PICK)
263 error(_("Your local changes would be overwritten by cherry-pick."));
264 else
265 error(_("Your local changes would be overwritten by revert."));
267 if (advice_commit_before_merge)
268 advise(_("Commit your changes or stash them to proceed."));
269 return -1;
272 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
273 int unborn, struct replay_opts *opts)
275 struct ref_lock *ref_lock;
276 struct strbuf sb = STRBUF_INIT;
277 int ret;
279 read_cache();
280 if (checkout_fast_forward(from, to, 1))
281 exit(1); /* the callee should have complained already */
282 ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
283 0, NULL);
284 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
285 ret = write_ref_sha1(ref_lock, to, sb.buf);
286 strbuf_release(&sb);
287 return ret;
290 static int do_recursive_merge(struct commit *base, struct commit *next,
291 const char *base_label, const char *next_label,
292 unsigned char *head, struct strbuf *msgbuf,
293 struct replay_opts *opts)
295 struct merge_options o;
296 struct tree *result, *next_tree, *base_tree, *head_tree;
297 int clean;
298 const char **xopt;
299 static struct lock_file index_lock;
301 hold_locked_index(&index_lock, 1);
303 read_cache();
305 init_merge_options(&o);
306 o.ancestor = base ? base_label : "(empty tree)";
307 o.branch1 = "HEAD";
308 o.branch2 = next ? next_label : "(empty tree)";
310 head_tree = parse_tree_indirect(head);
311 next_tree = next ? next->tree : empty_tree();
312 base_tree = base ? base->tree : empty_tree();
314 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
315 parse_merge_opt(&o, *xopt);
317 clean = merge_trees(&o,
318 head_tree,
319 next_tree, base_tree, &result);
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 die(_("%s: Unable to write new index file"), action_name(opts));
325 rollback_lock_file(&index_lock);
327 if (opts->signoff)
328 append_signoff(msgbuf, 0, 0);
330 if (!clean) {
331 int i;
332 strbuf_addstr(msgbuf, "\nConflicts:\n");
333 for (i = 0; i < active_nr;) {
334 const struct cache_entry *ce = active_cache[i++];
335 if (ce_stage(ce)) {
336 strbuf_addch(msgbuf, '\t');
337 strbuf_addstr(msgbuf, ce->name);
338 strbuf_addch(msgbuf, '\n');
339 while (i < active_nr && !strcmp(ce->name,
340 active_cache[i]->name))
341 i++;
346 return !clean;
349 static int is_index_unchanged(void)
351 unsigned char head_sha1[20];
352 struct commit *head_commit;
354 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
355 return error(_("Could not resolve HEAD commit\n"));
357 head_commit = lookup_commit(head_sha1);
360 * If head_commit is NULL, check_commit, called from
361 * lookup_commit, would have indicated that head_commit is not
362 * a commit object already. parse_commit() will return failure
363 * without further complaints in such a case. Otherwise, if
364 * the commit is invalid, parse_commit() will complain. So
365 * there is nothing for us to say here. Just return failure.
367 if (parse_commit(head_commit))
368 return -1;
370 if (!active_cache_tree)
371 active_cache_tree = cache_tree();
373 if (!cache_tree_fully_valid(active_cache_tree))
374 if (cache_tree_update(&the_index, 0))
375 return error(_("Unable to update cache tree\n"));
377 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
381 * If we are cherry-pick, and if the merge did not result in
382 * hand-editing, we will hit this commit and inherit the original
383 * author date and name.
384 * If we are revert, or if our cherry-pick results in a hand merge,
385 * we had better say that the current user is responsible for that.
387 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
388 int allow_empty)
390 struct argv_array array;
391 int rc;
392 char *gpg_sign;
394 argv_array_init(&array);
395 argv_array_push(&array, "commit");
396 argv_array_push(&array, "-n");
398 if (opts->gpg_sign) {
399 gpg_sign = xmalloc(3 + strlen(opts->gpg_sign));
400 sprintf(gpg_sign, "-S%s", opts->gpg_sign);
401 argv_array_push(&array, gpg_sign);
402 free(gpg_sign);
404 if (opts->signoff)
405 argv_array_push(&array, "-s");
406 if (!opts->edit) {
407 argv_array_push(&array, "-F");
408 argv_array_push(&array, defmsg);
411 if (allow_empty)
412 argv_array_push(&array, "--allow-empty");
414 if (opts->allow_empty_message)
415 argv_array_push(&array, "--allow-empty-message");
417 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
418 argv_array_clear(&array);
419 return rc;
422 static int is_original_commit_empty(struct commit *commit)
424 const unsigned char *ptree_sha1;
426 if (parse_commit(commit))
427 return error(_("Could not parse commit %s\n"),
428 sha1_to_hex(commit->object.sha1));
429 if (commit->parents) {
430 struct commit *parent = commit->parents->item;
431 if (parse_commit(parent))
432 return error(_("Could not parse parent commit %s\n"),
433 sha1_to_hex(parent->object.sha1));
434 ptree_sha1 = parent->tree->object.sha1;
435 } else {
436 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
439 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
443 * Do we run "git commit" with "--allow-empty"?
445 static int allow_empty(struct replay_opts *opts, struct commit *commit)
447 int index_unchanged, empty_commit;
450 * Three cases:
452 * (1) we do not allow empty at all and error out.
454 * (2) we allow ones that were initially empty, but
455 * forbid the ones that become empty;
457 * (3) we allow both.
459 if (!opts->allow_empty)
460 return 0; /* let "git commit" barf as necessary */
462 index_unchanged = is_index_unchanged();
463 if (index_unchanged < 0)
464 return index_unchanged;
465 if (!index_unchanged)
466 return 0; /* we do not have to say --allow-empty */
468 if (opts->keep_redundant_commits)
469 return 1;
471 empty_commit = is_original_commit_empty(commit);
472 if (empty_commit < 0)
473 return empty_commit;
474 if (!empty_commit)
475 return 0;
476 else
477 return 1;
480 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
482 unsigned char head[20];
483 struct commit *base, *next, *parent;
484 const char *base_label, *next_label;
485 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
486 char *defmsg = NULL;
487 struct strbuf msgbuf = STRBUF_INIT;
488 int res, unborn = 0, allow;
490 if (opts->no_commit) {
492 * We do not intend to commit immediately. We just want to
493 * merge the differences in, so let's compute the tree
494 * that represents the "current" state for merge-recursive
495 * to work on.
497 if (write_cache_as_tree(head, 0, NULL))
498 die (_("Your index file is unmerged."));
499 } else {
500 unborn = get_sha1("HEAD", head);
501 if (unborn)
502 hashcpy(head, EMPTY_TREE_SHA1_BIN);
503 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
504 return error_dirty_index(opts);
506 discard_cache();
508 if (!commit->parents) {
509 parent = NULL;
511 else if (commit->parents->next) {
512 /* Reverting or cherry-picking a merge commit */
513 int cnt;
514 struct commit_list *p;
516 if (!opts->mainline)
517 return error(_("Commit %s is a merge but no -m option was given."),
518 sha1_to_hex(commit->object.sha1));
520 for (cnt = 1, p = commit->parents;
521 cnt != opts->mainline && p;
522 cnt++)
523 p = p->next;
524 if (cnt != opts->mainline || !p)
525 return error(_("Commit %s does not have parent %d"),
526 sha1_to_hex(commit->object.sha1), opts->mainline);
527 parent = p->item;
528 } else if (0 < opts->mainline)
529 return error(_("Mainline was specified but commit %s is not a merge."),
530 sha1_to_hex(commit->object.sha1));
531 else
532 parent = commit->parents->item;
534 if (opts->allow_ff &&
535 ((parent && !hashcmp(parent->object.sha1, head)) ||
536 (!parent && unborn)))
537 return fast_forward_to(commit->object.sha1, head, unborn, opts);
539 if (parent && parse_commit(parent) < 0)
540 /* TRANSLATORS: The first %s will be "revert" or
541 "cherry-pick", the second %s a SHA1 */
542 return error(_("%s: cannot parse parent commit %s"),
543 action_name(opts), sha1_to_hex(parent->object.sha1));
545 if (get_message(commit, &msg) != 0)
546 return error(_("Cannot get commit message for %s"),
547 sha1_to_hex(commit->object.sha1));
550 * "commit" is an existing commit. We would want to apply
551 * the difference it introduces since its first parent "prev"
552 * on top of the current HEAD if we are cherry-pick. Or the
553 * reverse of it if we are revert.
556 defmsg = git_pathdup("MERGE_MSG");
558 if (opts->action == REPLAY_REVERT) {
559 base = commit;
560 base_label = msg.label;
561 next = parent;
562 next_label = msg.parent_label;
563 strbuf_addstr(&msgbuf, "Revert \"");
564 strbuf_addstr(&msgbuf, msg.subject);
565 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
566 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
568 if (commit->parents && commit->parents->next) {
569 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
570 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
572 strbuf_addstr(&msgbuf, ".\n");
573 } else {
574 const char *p;
576 base = parent;
577 base_label = msg.parent_label;
578 next = commit;
579 next_label = msg.label;
582 * Append the commit log message to msgbuf; it starts
583 * after the tree, parent, author, committer
584 * information followed by "\n\n".
586 p = strstr(msg.message, "\n\n");
587 if (p) {
588 p += 2;
589 strbuf_addstr(&msgbuf, p);
592 if (opts->record_origin) {
593 if (!has_conforming_footer(&msgbuf, NULL, 0))
594 strbuf_addch(&msgbuf, '\n');
595 strbuf_addstr(&msgbuf, cherry_picked_prefix);
596 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
597 strbuf_addstr(&msgbuf, ")\n");
601 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
602 res = do_recursive_merge(base, next, base_label, next_label,
603 head, &msgbuf, opts);
604 write_message(&msgbuf, defmsg);
605 } else {
606 struct commit_list *common = NULL;
607 struct commit_list *remotes = NULL;
609 write_message(&msgbuf, defmsg);
611 commit_list_insert(base, &common);
612 commit_list_insert(next, &remotes);
613 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
614 common, sha1_to_hex(head), remotes);
615 free_commit_list(common);
616 free_commit_list(remotes);
620 * If the merge was clean or if it failed due to conflict, we write
621 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
622 * However, if the merge did not even start, then we don't want to
623 * write it at all.
625 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
626 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
627 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
628 write_cherry_pick_head(commit, "REVERT_HEAD");
630 if (res) {
631 error(opts->action == REPLAY_REVERT
632 ? _("could not revert %s... %s")
633 : _("could not apply %s... %s"),
634 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
635 msg.subject);
636 print_advice(res == 1, opts);
637 rerere(opts->allow_rerere_auto);
638 goto leave;
641 allow = allow_empty(opts, commit);
642 if (allow < 0) {
643 res = allow;
644 goto leave;
646 if (!opts->no_commit)
647 res = run_git_commit(defmsg, opts, allow);
649 leave:
650 free_message(&msg);
651 free(defmsg);
653 return res;
656 static void prepare_revs(struct replay_opts *opts)
659 * picking (but not reverting) ranges (but not individual revisions)
660 * should be done in reverse
662 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
663 opts->revs->reverse ^= 1;
665 if (prepare_revision_walk(opts->revs))
666 die(_("revision walk setup failed"));
668 if (!opts->revs->commits)
669 die(_("empty commit set passed"));
672 static void read_and_refresh_cache(struct replay_opts *opts)
674 static struct lock_file index_lock;
675 int index_fd = hold_locked_index(&index_lock, 0);
676 if (read_index_preload(&the_index, NULL) < 0)
677 die(_("git %s: failed to read the index"), action_name(opts));
678 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
679 if (the_index.cache_changed && index_fd >= 0) {
680 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
681 die(_("git %s: failed to refresh the index"), action_name(opts));
683 rollback_lock_file(&index_lock);
686 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
687 struct replay_opts *opts)
689 struct commit_list *cur = NULL;
690 const char *sha1_abbrev = NULL;
691 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
692 const char *subject;
693 int subject_len;
695 for (cur = todo_list; cur; cur = cur->next) {
696 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
697 subject_len = find_commit_subject(cur->item->buffer, &subject);
698 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
699 subject_len, subject);
701 return 0;
704 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
706 unsigned char commit_sha1[20];
707 enum replay_action action;
708 char *end_of_object_name;
709 int saved, status, padding;
711 if (starts_with(bol, "pick")) {
712 action = REPLAY_PICK;
713 bol += strlen("pick");
714 } else if (starts_with(bol, "revert")) {
715 action = REPLAY_REVERT;
716 bol += strlen("revert");
717 } else
718 return NULL;
720 /* Eat up extra spaces/ tabs before object name */
721 padding = strspn(bol, " \t");
722 if (!padding)
723 return NULL;
724 bol += padding;
726 end_of_object_name = bol + strcspn(bol, " \t\n");
727 saved = *end_of_object_name;
728 *end_of_object_name = '\0';
729 status = get_sha1(bol, commit_sha1);
730 *end_of_object_name = saved;
733 * Verify that the action matches up with the one in
734 * opts; we don't support arbitrary instructions
736 if (action != opts->action) {
737 const char *action_str;
738 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
739 error(_("Cannot %s during a %s"), action_str, action_name(opts));
740 return NULL;
743 if (status < 0)
744 return NULL;
746 return lookup_commit_reference(commit_sha1);
749 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
750 struct replay_opts *opts)
752 struct commit_list **next = todo_list;
753 struct commit *commit;
754 char *p = buf;
755 int i;
757 for (i = 1; *p; i++) {
758 char *eol = strchrnul(p, '\n');
759 commit = parse_insn_line(p, eol, opts);
760 if (!commit)
761 return error(_("Could not parse line %d."), i);
762 next = commit_list_append(commit, next);
763 p = *eol ? eol + 1 : eol;
765 if (!*todo_list)
766 return error(_("No commits parsed."));
767 return 0;
770 static void read_populate_todo(struct commit_list **todo_list,
771 struct replay_opts *opts)
773 const char *todo_file = git_path(SEQ_TODO_FILE);
774 struct strbuf buf = STRBUF_INIT;
775 int fd, res;
777 fd = open(todo_file, O_RDONLY);
778 if (fd < 0)
779 die_errno(_("Could not open %s"), todo_file);
780 if (strbuf_read(&buf, fd, 0) < 0) {
781 close(fd);
782 strbuf_release(&buf);
783 die(_("Could not read %s."), todo_file);
785 close(fd);
787 res = parse_insn_buffer(buf.buf, todo_list, opts);
788 strbuf_release(&buf);
789 if (res)
790 die(_("Unusable instruction sheet: %s"), todo_file);
793 static int populate_opts_cb(const char *key, const char *value, void *data)
795 struct replay_opts *opts = data;
796 int error_flag = 1;
798 if (!value)
799 error_flag = 0;
800 else if (!strcmp(key, "options.no-commit"))
801 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
802 else if (!strcmp(key, "options.edit"))
803 opts->edit = git_config_bool_or_int(key, value, &error_flag);
804 else if (!strcmp(key, "options.signoff"))
805 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
806 else if (!strcmp(key, "options.record-origin"))
807 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
808 else if (!strcmp(key, "options.allow-ff"))
809 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
810 else if (!strcmp(key, "options.mainline"))
811 opts->mainline = git_config_int(key, value);
812 else if (!strcmp(key, "options.strategy"))
813 git_config_string(&opts->strategy, key, value);
814 else if (!strcmp(key, "options.gpg-sign"))
815 git_config_string(&opts->gpg_sign, key, value);
816 else if (!strcmp(key, "options.strategy-option")) {
817 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
818 opts->xopts[opts->xopts_nr++] = xstrdup(value);
819 } else
820 return error(_("Invalid key: %s"), key);
822 if (!error_flag)
823 return error(_("Invalid value for %s: %s"), key, value);
825 return 0;
828 static void read_populate_opts(struct replay_opts **opts_ptr)
830 const char *opts_file = git_path(SEQ_OPTS_FILE);
832 if (!file_exists(opts_file))
833 return;
834 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
835 die(_("Malformed options sheet: %s"), opts_file);
838 static void walk_revs_populate_todo(struct commit_list **todo_list,
839 struct replay_opts *opts)
841 struct commit *commit;
842 struct commit_list **next;
844 prepare_revs(opts);
846 next = todo_list;
847 while ((commit = get_revision(opts->revs)))
848 next = commit_list_append(commit, next);
851 static int create_seq_dir(void)
853 const char *seq_dir = git_path(SEQ_DIR);
855 if (file_exists(seq_dir)) {
856 error(_("a cherry-pick or revert is already in progress"));
857 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
858 return -1;
860 else if (mkdir(seq_dir, 0777) < 0)
861 die_errno(_("Could not create sequencer directory %s"), seq_dir);
862 return 0;
865 static void save_head(const char *head)
867 const char *head_file = git_path(SEQ_HEAD_FILE);
868 static struct lock_file head_lock;
869 struct strbuf buf = STRBUF_INIT;
870 int fd;
872 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
873 strbuf_addf(&buf, "%s\n", head);
874 if (write_in_full(fd, buf.buf, buf.len) < 0)
875 die_errno(_("Could not write to %s"), head_file);
876 if (commit_lock_file(&head_lock) < 0)
877 die(_("Error wrapping up %s."), head_file);
880 static int reset_for_rollback(const unsigned char *sha1)
882 const char *argv[4]; /* reset --merge <arg> + NULL */
883 argv[0] = "reset";
884 argv[1] = "--merge";
885 argv[2] = sha1_to_hex(sha1);
886 argv[3] = NULL;
887 return run_command_v_opt(argv, RUN_GIT_CMD);
890 static int rollback_single_pick(void)
892 unsigned char head_sha1[20];
894 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
895 !file_exists(git_path("REVERT_HEAD")))
896 return error(_("no cherry-pick or revert in progress"));
897 if (read_ref_full("HEAD", head_sha1, 0, NULL))
898 return error(_("cannot resolve HEAD"));
899 if (is_null_sha1(head_sha1))
900 return error(_("cannot abort from a branch yet to be born"));
901 return reset_for_rollback(head_sha1);
904 static int sequencer_rollback(struct replay_opts *opts)
906 const char *filename;
907 FILE *f;
908 unsigned char sha1[20];
909 struct strbuf buf = STRBUF_INIT;
911 filename = git_path(SEQ_HEAD_FILE);
912 f = fopen(filename, "r");
913 if (!f && errno == ENOENT) {
915 * There is no multiple-cherry-pick in progress.
916 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
917 * a single-cherry-pick in progress, abort that.
919 return rollback_single_pick();
921 if (!f)
922 return error(_("cannot open %s: %s"), filename,
923 strerror(errno));
924 if (strbuf_getline(&buf, f, '\n')) {
925 error(_("cannot read %s: %s"), filename, ferror(f) ?
926 strerror(errno) : _("unexpected end of file"));
927 fclose(f);
928 goto fail;
930 fclose(f);
931 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
932 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
933 filename);
934 goto fail;
936 if (reset_for_rollback(sha1))
937 goto fail;
938 remove_sequencer_state();
939 strbuf_release(&buf);
940 return 0;
941 fail:
942 strbuf_release(&buf);
943 return -1;
946 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
948 const char *todo_file = git_path(SEQ_TODO_FILE);
949 static struct lock_file todo_lock;
950 struct strbuf buf = STRBUF_INIT;
951 int fd;
953 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
954 if (format_todo(&buf, todo_list, opts) < 0)
955 die(_("Could not format %s."), todo_file);
956 if (write_in_full(fd, buf.buf, buf.len) < 0) {
957 strbuf_release(&buf);
958 die_errno(_("Could not write to %s"), todo_file);
960 if (commit_lock_file(&todo_lock) < 0) {
961 strbuf_release(&buf);
962 die(_("Error wrapping up %s."), todo_file);
964 strbuf_release(&buf);
967 static void save_opts(struct replay_opts *opts)
969 const char *opts_file = git_path(SEQ_OPTS_FILE);
971 if (opts->no_commit)
972 git_config_set_in_file(opts_file, "options.no-commit", "true");
973 if (opts->edit)
974 git_config_set_in_file(opts_file, "options.edit", "true");
975 if (opts->signoff)
976 git_config_set_in_file(opts_file, "options.signoff", "true");
977 if (opts->record_origin)
978 git_config_set_in_file(opts_file, "options.record-origin", "true");
979 if (opts->allow_ff)
980 git_config_set_in_file(opts_file, "options.allow-ff", "true");
981 if (opts->mainline) {
982 struct strbuf buf = STRBUF_INIT;
983 strbuf_addf(&buf, "%d", opts->mainline);
984 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
985 strbuf_release(&buf);
987 if (opts->strategy)
988 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
989 if (opts->gpg_sign)
990 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
991 if (opts->xopts) {
992 int i;
993 for (i = 0; i < opts->xopts_nr; i++)
994 git_config_set_multivar_in_file(opts_file,
995 "options.strategy-option",
996 opts->xopts[i], "^$", 0);
1000 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1002 struct commit_list *cur;
1003 int res;
1005 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1006 if (opts->allow_ff)
1007 assert(!(opts->signoff || opts->no_commit ||
1008 opts->record_origin || opts->edit));
1009 read_and_refresh_cache(opts);
1011 for (cur = todo_list; cur; cur = cur->next) {
1012 save_todo(cur, opts);
1013 res = do_pick_commit(cur->item, opts);
1014 if (res)
1015 return res;
1019 * Sequence of picks finished successfully; cleanup by
1020 * removing the .git/sequencer directory
1022 remove_sequencer_state();
1023 return 0;
1026 static int continue_single_pick(void)
1028 const char *argv[] = { "commit", NULL };
1030 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1031 !file_exists(git_path("REVERT_HEAD")))
1032 return error(_("no cherry-pick or revert in progress"));
1033 return run_command_v_opt(argv, RUN_GIT_CMD);
1036 static int sequencer_continue(struct replay_opts *opts)
1038 struct commit_list *todo_list = NULL;
1040 if (!file_exists(git_path(SEQ_TODO_FILE)))
1041 return continue_single_pick();
1042 read_populate_opts(&opts);
1043 read_populate_todo(&todo_list, opts);
1045 /* Verify that the conflict has been resolved */
1046 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1047 file_exists(git_path("REVERT_HEAD"))) {
1048 int ret = continue_single_pick();
1049 if (ret)
1050 return ret;
1052 if (index_differs_from("HEAD", 0))
1053 return error_dirty_index(opts);
1054 todo_list = todo_list->next;
1055 return pick_commits(todo_list, opts);
1058 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1060 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1061 return do_pick_commit(cmit, opts);
1064 int sequencer_pick_revisions(struct replay_opts *opts)
1066 struct commit_list *todo_list = NULL;
1067 unsigned char sha1[20];
1068 int i;
1070 if (opts->subcommand == REPLAY_NONE)
1071 assert(opts->revs);
1073 read_and_refresh_cache(opts);
1076 * Decide what to do depending on the arguments; a fresh
1077 * cherry-pick should be handled differently from an existing
1078 * one that is being continued
1080 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1081 remove_sequencer_state();
1082 return 0;
1084 if (opts->subcommand == REPLAY_ROLLBACK)
1085 return sequencer_rollback(opts);
1086 if (opts->subcommand == REPLAY_CONTINUE)
1087 return sequencer_continue(opts);
1089 for (i = 0; i < opts->revs->pending.nr; i++) {
1090 unsigned char sha1[20];
1091 const char *name = opts->revs->pending.objects[i].name;
1093 /* This happens when using --stdin. */
1094 if (!strlen(name))
1095 continue;
1097 if (!get_sha1(name, sha1)) {
1098 if (!lookup_commit_reference_gently(sha1, 1)) {
1099 enum object_type type = sha1_object_info(sha1, NULL);
1100 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1102 } else
1103 die(_("%s: bad revision"), name);
1107 * If we were called as "git cherry-pick <commit>", just
1108 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1109 * REVERT_HEAD, and don't touch the sequencer state.
1110 * This means it is possible to cherry-pick in the middle
1111 * of a cherry-pick sequence.
1113 if (opts->revs->cmdline.nr == 1 &&
1114 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1115 opts->revs->no_walk &&
1116 !opts->revs->cmdline.rev->flags) {
1117 struct commit *cmit;
1118 if (prepare_revision_walk(opts->revs))
1119 die(_("revision walk setup failed"));
1120 cmit = get_revision(opts->revs);
1121 if (!cmit || get_revision(opts->revs))
1122 die("BUG: expected exactly one commit from walk");
1123 return single_pick(cmit, opts);
1127 * Start a new cherry-pick/ revert sequence; but
1128 * first, make sure that an existing one isn't in
1129 * progress
1132 walk_revs_populate_todo(&todo_list, opts);
1133 if (create_seq_dir() < 0)
1134 return -1;
1135 if (get_sha1("HEAD", sha1)) {
1136 if (opts->action == REPLAY_REVERT)
1137 return error(_("Can't revert as initial commit"));
1138 return error(_("Can't cherry-pick into empty head"));
1140 save_head(sha1_to_hex(sha1));
1141 save_opts(opts);
1142 return pick_commits(todo_list, opts);
1145 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1147 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1148 struct strbuf sob = STRBUF_INIT;
1149 int has_footer;
1151 strbuf_addstr(&sob, sign_off_header);
1152 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1153 getenv("GIT_COMMITTER_EMAIL")));
1154 strbuf_addch(&sob, '\n');
1157 * If the whole message buffer is equal to the sob, pretend that we
1158 * found a conforming footer with a matching sob
1160 if (msgbuf->len - ignore_footer == sob.len &&
1161 !strncmp(msgbuf->buf, sob.buf, sob.len))
1162 has_footer = 3;
1163 else
1164 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1166 if (!has_footer) {
1167 const char *append_newlines = NULL;
1168 size_t len = msgbuf->len - ignore_footer;
1170 if (!len) {
1172 * The buffer is completely empty. Leave foom for
1173 * the title and body to be filled in by the user.
1175 append_newlines = "\n\n";
1176 } else if (msgbuf->buf[len - 1] != '\n') {
1178 * Incomplete line. Complete the line and add a
1179 * blank one so that there is an empty line between
1180 * the message body and the sob.
1182 append_newlines = "\n\n";
1183 } else if (len == 1) {
1185 * Buffer contains a single newline. Add another
1186 * so that we leave room for the title and body.
1188 append_newlines = "\n";
1189 } else if (msgbuf->buf[len - 2] != '\n') {
1191 * Buffer ends with a single newline. Add another
1192 * so that there is an empty line between the message
1193 * body and the sob.
1195 append_newlines = "\n";
1196 } /* else, the buffer already ends with two newlines. */
1198 if (append_newlines)
1199 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1200 append_newlines, strlen(append_newlines));
1203 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1204 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1205 sob.buf, sob.len);
1207 strbuf_release(&sob);