fast-import.c: use a ref transaction when dumping tags
[git/git-svn.git] / sequencer.c
blob5e93b6ab5fdf2f5af4233986137d15351f7a741b
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_transaction *transaction;
276 struct strbuf sb = STRBUF_INIT;
277 struct strbuf err = STRBUF_INIT;
279 read_cache();
280 if (checkout_fast_forward(from, to, 1))
281 exit(1); /* the callee should have complained already */
283 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
285 transaction = ref_transaction_begin(&err);
286 if (!transaction ||
287 ref_transaction_update(transaction, "HEAD",
288 to, unborn ? null_sha1 : from,
289 0, 1, &err) ||
290 ref_transaction_commit(transaction, sb.buf, &err)) {
291 ref_transaction_free(transaction);
292 error("%s", err.buf);
293 strbuf_release(&sb);
294 strbuf_release(&err);
295 return -1;
298 strbuf_release(&sb);
299 strbuf_release(&err);
300 ref_transaction_free(transaction);
301 return 0;
304 static int do_recursive_merge(struct commit *base, struct commit *next,
305 const char *base_label, const char *next_label,
306 unsigned char *head, struct strbuf *msgbuf,
307 struct replay_opts *opts)
309 struct merge_options o;
310 struct tree *result, *next_tree, *base_tree, *head_tree;
311 int clean, index_fd;
312 const char **xopt;
313 static struct lock_file index_lock;
315 index_fd = hold_locked_index(&index_lock, 1);
317 read_cache();
319 init_merge_options(&o);
320 o.ancestor = base ? base_label : "(empty tree)";
321 o.branch1 = "HEAD";
322 o.branch2 = next ? next_label : "(empty tree)";
324 head_tree = parse_tree_indirect(head);
325 next_tree = next ? next->tree : empty_tree();
326 base_tree = base ? base->tree : empty_tree();
328 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
329 parse_merge_opt(&o, *xopt);
331 clean = merge_trees(&o,
332 head_tree,
333 next_tree, base_tree, &result);
335 if (active_cache_changed &&
336 (write_cache(index_fd, active_cache, active_nr) ||
337 commit_locked_index(&index_lock)))
338 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
339 die(_("%s: Unable to write new index file"), action_name(opts));
340 rollback_lock_file(&index_lock);
342 if (opts->signoff)
343 append_signoff(msgbuf, 0, 0);
345 if (!clean) {
346 int i;
347 strbuf_addstr(msgbuf, "\nConflicts:\n");
348 for (i = 0; i < active_nr;) {
349 const struct cache_entry *ce = active_cache[i++];
350 if (ce_stage(ce)) {
351 strbuf_addch(msgbuf, '\t');
352 strbuf_addstr(msgbuf, ce->name);
353 strbuf_addch(msgbuf, '\n');
354 while (i < active_nr && !strcmp(ce->name,
355 active_cache[i]->name))
356 i++;
361 return !clean;
364 static int is_index_unchanged(void)
366 unsigned char head_sha1[20];
367 struct commit *head_commit;
369 if (!resolve_ref_unsafe("HEAD", head_sha1, 1, NULL))
370 return error(_("Could not resolve HEAD commit\n"));
372 head_commit = lookup_commit(head_sha1);
375 * If head_commit is NULL, check_commit, called from
376 * lookup_commit, would have indicated that head_commit is not
377 * a commit object already. parse_commit() will return failure
378 * without further complaints in such a case. Otherwise, if
379 * the commit is invalid, parse_commit() will complain. So
380 * there is nothing for us to say here. Just return failure.
382 if (parse_commit(head_commit))
383 return -1;
385 if (!active_cache_tree)
386 active_cache_tree = cache_tree();
388 if (!cache_tree_fully_valid(active_cache_tree))
389 if (cache_tree_update(active_cache_tree,
390 (const struct cache_entry * const *)active_cache,
391 active_nr, 0))
392 return error(_("Unable to update cache tree\n"));
394 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
398 * If we are cherry-pick, and if the merge did not result in
399 * hand-editing, we will hit this commit and inherit the original
400 * author date and name.
401 * If we are revert, or if our cherry-pick results in a hand merge,
402 * we had better say that the current user is responsible for that.
404 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
405 int allow_empty)
407 struct argv_array array;
408 int rc;
409 char *gpg_sign;
411 argv_array_init(&array);
412 argv_array_push(&array, "commit");
413 argv_array_push(&array, "-n");
415 if (opts->gpg_sign) {
416 gpg_sign = xmalloc(3 + strlen(opts->gpg_sign));
417 sprintf(gpg_sign, "-S%s", opts->gpg_sign);
418 argv_array_push(&array, gpg_sign);
419 free(gpg_sign);
421 if (opts->signoff)
422 argv_array_push(&array, "-s");
423 if (!opts->edit) {
424 argv_array_push(&array, "-F");
425 argv_array_push(&array, defmsg);
428 if (allow_empty)
429 argv_array_push(&array, "--allow-empty");
431 if (opts->allow_empty_message)
432 argv_array_push(&array, "--allow-empty-message");
434 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
435 argv_array_clear(&array);
436 return rc;
439 static int is_original_commit_empty(struct commit *commit)
441 const unsigned char *ptree_sha1;
443 if (parse_commit(commit))
444 return error(_("Could not parse commit %s\n"),
445 sha1_to_hex(commit->object.sha1));
446 if (commit->parents) {
447 struct commit *parent = commit->parents->item;
448 if (parse_commit(parent))
449 return error(_("Could not parse parent commit %s\n"),
450 sha1_to_hex(parent->object.sha1));
451 ptree_sha1 = parent->tree->object.sha1;
452 } else {
453 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
456 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
460 * Do we run "git commit" with "--allow-empty"?
462 static int allow_empty(struct replay_opts *opts, struct commit *commit)
464 int index_unchanged, empty_commit;
467 * Three cases:
469 * (1) we do not allow empty at all and error out.
471 * (2) we allow ones that were initially empty, but
472 * forbid the ones that become empty;
474 * (3) we allow both.
476 if (!opts->allow_empty)
477 return 0; /* let "git commit" barf as necessary */
479 index_unchanged = is_index_unchanged();
480 if (index_unchanged < 0)
481 return index_unchanged;
482 if (!index_unchanged)
483 return 0; /* we do not have to say --allow-empty */
485 if (opts->keep_redundant_commits)
486 return 1;
488 empty_commit = is_original_commit_empty(commit);
489 if (empty_commit < 0)
490 return empty_commit;
491 if (!empty_commit)
492 return 0;
493 else
494 return 1;
497 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
499 unsigned char head[20];
500 struct commit *base, *next, *parent;
501 const char *base_label, *next_label;
502 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
503 char *defmsg = NULL;
504 struct strbuf msgbuf = STRBUF_INIT;
505 int res, unborn = 0, allow;
507 if (opts->no_commit) {
509 * We do not intend to commit immediately. We just want to
510 * merge the differences in, so let's compute the tree
511 * that represents the "current" state for merge-recursive
512 * to work on.
514 if (write_cache_as_tree(head, 0, NULL))
515 die (_("Your index file is unmerged."));
516 } else {
517 unborn = get_sha1("HEAD", head);
518 if (unborn)
519 hashcpy(head, EMPTY_TREE_SHA1_BIN);
520 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
521 return error_dirty_index(opts);
523 discard_cache();
525 if (!commit->parents) {
526 parent = NULL;
528 else if (commit->parents->next) {
529 /* Reverting or cherry-picking a merge commit */
530 int cnt;
531 struct commit_list *p;
533 if (!opts->mainline)
534 return error(_("Commit %s is a merge but no -m option was given."),
535 sha1_to_hex(commit->object.sha1));
537 for (cnt = 1, p = commit->parents;
538 cnt != opts->mainline && p;
539 cnt++)
540 p = p->next;
541 if (cnt != opts->mainline || !p)
542 return error(_("Commit %s does not have parent %d"),
543 sha1_to_hex(commit->object.sha1), opts->mainline);
544 parent = p->item;
545 } else if (0 < opts->mainline)
546 return error(_("Mainline was specified but commit %s is not a merge."),
547 sha1_to_hex(commit->object.sha1));
548 else
549 parent = commit->parents->item;
551 if (opts->allow_ff &&
552 ((parent && !hashcmp(parent->object.sha1, head)) ||
553 (!parent && unborn)))
554 return fast_forward_to(commit->object.sha1, head, unborn, opts);
556 if (parent && parse_commit(parent) < 0)
557 /* TRANSLATORS: The first %s will be "revert" or
558 "cherry-pick", the second %s a SHA1 */
559 return error(_("%s: cannot parse parent commit %s"),
560 action_name(opts), sha1_to_hex(parent->object.sha1));
562 if (get_message(commit, &msg) != 0)
563 return error(_("Cannot get commit message for %s"),
564 sha1_to_hex(commit->object.sha1));
567 * "commit" is an existing commit. We would want to apply
568 * the difference it introduces since its first parent "prev"
569 * on top of the current HEAD if we are cherry-pick. Or the
570 * reverse of it if we are revert.
573 defmsg = git_pathdup("MERGE_MSG");
575 if (opts->action == REPLAY_REVERT) {
576 base = commit;
577 base_label = msg.label;
578 next = parent;
579 next_label = msg.parent_label;
580 strbuf_addstr(&msgbuf, "Revert \"");
581 strbuf_addstr(&msgbuf, msg.subject);
582 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
583 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
585 if (commit->parents && commit->parents->next) {
586 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
587 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
589 strbuf_addstr(&msgbuf, ".\n");
590 } else {
591 const char *p;
593 base = parent;
594 base_label = msg.parent_label;
595 next = commit;
596 next_label = msg.label;
599 * Append the commit log message to msgbuf; it starts
600 * after the tree, parent, author, committer
601 * information followed by "\n\n".
603 p = strstr(msg.message, "\n\n");
604 if (p) {
605 p += 2;
606 strbuf_addstr(&msgbuf, p);
609 if (opts->record_origin) {
610 if (!has_conforming_footer(&msgbuf, NULL, 0))
611 strbuf_addch(&msgbuf, '\n');
612 strbuf_addstr(&msgbuf, cherry_picked_prefix);
613 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
614 strbuf_addstr(&msgbuf, ")\n");
618 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
619 res = do_recursive_merge(base, next, base_label, next_label,
620 head, &msgbuf, opts);
621 write_message(&msgbuf, defmsg);
622 } else {
623 struct commit_list *common = NULL;
624 struct commit_list *remotes = NULL;
626 write_message(&msgbuf, defmsg);
628 commit_list_insert(base, &common);
629 commit_list_insert(next, &remotes);
630 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
631 common, sha1_to_hex(head), remotes);
632 free_commit_list(common);
633 free_commit_list(remotes);
637 * If the merge was clean or if it failed due to conflict, we write
638 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
639 * However, if the merge did not even start, then we don't want to
640 * write it at all.
642 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
643 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
644 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
645 write_cherry_pick_head(commit, "REVERT_HEAD");
647 if (res) {
648 error(opts->action == REPLAY_REVERT
649 ? _("could not revert %s... %s")
650 : _("could not apply %s... %s"),
651 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
652 msg.subject);
653 print_advice(res == 1, opts);
654 rerere(opts->allow_rerere_auto);
655 goto leave;
658 allow = allow_empty(opts, commit);
659 if (allow < 0) {
660 res = allow;
661 goto leave;
663 if (!opts->no_commit)
664 res = run_git_commit(defmsg, opts, allow);
666 leave:
667 free_message(&msg);
668 free(defmsg);
670 return res;
673 static void prepare_revs(struct replay_opts *opts)
676 * picking (but not reverting) ranges (but not individual revisions)
677 * should be done in reverse
679 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
680 opts->revs->reverse ^= 1;
682 if (prepare_revision_walk(opts->revs))
683 die(_("revision walk setup failed"));
685 if (!opts->revs->commits)
686 die(_("empty commit set passed"));
689 static void read_and_refresh_cache(struct replay_opts *opts)
691 static struct lock_file index_lock;
692 int index_fd = hold_locked_index(&index_lock, 0);
693 if (read_index_preload(&the_index, NULL) < 0)
694 die(_("git %s: failed to read the index"), action_name(opts));
695 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
696 if (the_index.cache_changed) {
697 if (write_index(&the_index, index_fd) ||
698 commit_locked_index(&index_lock))
699 die(_("git %s: failed to refresh the index"), action_name(opts));
701 rollback_lock_file(&index_lock);
704 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
705 struct replay_opts *opts)
707 struct commit_list *cur = NULL;
708 const char *sha1_abbrev = NULL;
709 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
710 const char *subject;
711 int subject_len;
713 for (cur = todo_list; cur; cur = cur->next) {
714 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
715 subject_len = find_commit_subject(cur->item->buffer, &subject);
716 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
717 subject_len, subject);
719 return 0;
722 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
724 unsigned char commit_sha1[20];
725 enum replay_action action;
726 char *end_of_object_name;
727 int saved, status, padding;
729 if (starts_with(bol, "pick")) {
730 action = REPLAY_PICK;
731 bol += strlen("pick");
732 } else if (starts_with(bol, "revert")) {
733 action = REPLAY_REVERT;
734 bol += strlen("revert");
735 } else
736 return NULL;
738 /* Eat up extra spaces/ tabs before object name */
739 padding = strspn(bol, " \t");
740 if (!padding)
741 return NULL;
742 bol += padding;
744 end_of_object_name = bol + strcspn(bol, " \t\n");
745 saved = *end_of_object_name;
746 *end_of_object_name = '\0';
747 status = get_sha1(bol, commit_sha1);
748 *end_of_object_name = saved;
751 * Verify that the action matches up with the one in
752 * opts; we don't support arbitrary instructions
754 if (action != opts->action) {
755 const char *action_str;
756 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
757 error(_("Cannot %s during a %s"), action_str, action_name(opts));
758 return NULL;
761 if (status < 0)
762 return NULL;
764 return lookup_commit_reference(commit_sha1);
767 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
768 struct replay_opts *opts)
770 struct commit_list **next = todo_list;
771 struct commit *commit;
772 char *p = buf;
773 int i;
775 for (i = 1; *p; i++) {
776 char *eol = strchrnul(p, '\n');
777 commit = parse_insn_line(p, eol, opts);
778 if (!commit)
779 return error(_("Could not parse line %d."), i);
780 next = commit_list_append(commit, next);
781 p = *eol ? eol + 1 : eol;
783 if (!*todo_list)
784 return error(_("No commits parsed."));
785 return 0;
788 static void read_populate_todo(struct commit_list **todo_list,
789 struct replay_opts *opts)
791 const char *todo_file = git_path(SEQ_TODO_FILE);
792 struct strbuf buf = STRBUF_INIT;
793 int fd, res;
795 fd = open(todo_file, O_RDONLY);
796 if (fd < 0)
797 die_errno(_("Could not open %s"), todo_file);
798 if (strbuf_read(&buf, fd, 0) < 0) {
799 close(fd);
800 strbuf_release(&buf);
801 die(_("Could not read %s."), todo_file);
803 close(fd);
805 res = parse_insn_buffer(buf.buf, todo_list, opts);
806 strbuf_release(&buf);
807 if (res)
808 die(_("Unusable instruction sheet: %s"), todo_file);
811 static int populate_opts_cb(const char *key, const char *value, void *data)
813 struct replay_opts *opts = data;
814 int error_flag = 1;
816 if (!value)
817 error_flag = 0;
818 else if (!strcmp(key, "options.no-commit"))
819 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
820 else if (!strcmp(key, "options.edit"))
821 opts->edit = git_config_bool_or_int(key, value, &error_flag);
822 else if (!strcmp(key, "options.signoff"))
823 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
824 else if (!strcmp(key, "options.record-origin"))
825 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
826 else if (!strcmp(key, "options.allow-ff"))
827 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
828 else if (!strcmp(key, "options.mainline"))
829 opts->mainline = git_config_int(key, value);
830 else if (!strcmp(key, "options.strategy"))
831 git_config_string(&opts->strategy, key, value);
832 else if (!strcmp(key, "options.gpg-sign"))
833 git_config_string(&opts->gpg_sign, key, value);
834 else if (!strcmp(key, "options.strategy-option")) {
835 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
836 opts->xopts[opts->xopts_nr++] = xstrdup(value);
837 } else
838 return error(_("Invalid key: %s"), key);
840 if (!error_flag)
841 return error(_("Invalid value for %s: %s"), key, value);
843 return 0;
846 static void read_populate_opts(struct replay_opts **opts_ptr)
848 const char *opts_file = git_path(SEQ_OPTS_FILE);
850 if (!file_exists(opts_file))
851 return;
852 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
853 die(_("Malformed options sheet: %s"), opts_file);
856 static void walk_revs_populate_todo(struct commit_list **todo_list,
857 struct replay_opts *opts)
859 struct commit *commit;
860 struct commit_list **next;
862 prepare_revs(opts);
864 next = todo_list;
865 while ((commit = get_revision(opts->revs)))
866 next = commit_list_append(commit, next);
869 static int create_seq_dir(void)
871 const char *seq_dir = git_path(SEQ_DIR);
873 if (file_exists(seq_dir)) {
874 error(_("a cherry-pick or revert is already in progress"));
875 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
876 return -1;
878 else if (mkdir(seq_dir, 0777) < 0)
879 die_errno(_("Could not create sequencer directory %s"), seq_dir);
880 return 0;
883 static void save_head(const char *head)
885 const char *head_file = git_path(SEQ_HEAD_FILE);
886 static struct lock_file head_lock;
887 struct strbuf buf = STRBUF_INIT;
888 int fd;
890 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
891 strbuf_addf(&buf, "%s\n", head);
892 if (write_in_full(fd, buf.buf, buf.len) < 0)
893 die_errno(_("Could not write to %s"), head_file);
894 if (commit_lock_file(&head_lock) < 0)
895 die(_("Error wrapping up %s."), head_file);
898 static int reset_for_rollback(const unsigned char *sha1)
900 const char *argv[4]; /* reset --merge <arg> + NULL */
901 argv[0] = "reset";
902 argv[1] = "--merge";
903 argv[2] = sha1_to_hex(sha1);
904 argv[3] = NULL;
905 return run_command_v_opt(argv, RUN_GIT_CMD);
908 static int rollback_single_pick(void)
910 unsigned char head_sha1[20];
912 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
913 !file_exists(git_path("REVERT_HEAD")))
914 return error(_("no cherry-pick or revert in progress"));
915 if (read_ref_full("HEAD", head_sha1, 0, NULL))
916 return error(_("cannot resolve HEAD"));
917 if (is_null_sha1(head_sha1))
918 return error(_("cannot abort from a branch yet to be born"));
919 return reset_for_rollback(head_sha1);
922 static int sequencer_rollback(struct replay_opts *opts)
924 const char *filename;
925 FILE *f;
926 unsigned char sha1[20];
927 struct strbuf buf = STRBUF_INIT;
929 filename = git_path(SEQ_HEAD_FILE);
930 f = fopen(filename, "r");
931 if (!f && errno == ENOENT) {
933 * There is no multiple-cherry-pick in progress.
934 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
935 * a single-cherry-pick in progress, abort that.
937 return rollback_single_pick();
939 if (!f)
940 return error(_("cannot open %s: %s"), filename,
941 strerror(errno));
942 if (strbuf_getline(&buf, f, '\n')) {
943 error(_("cannot read %s: %s"), filename, ferror(f) ?
944 strerror(errno) : _("unexpected end of file"));
945 fclose(f);
946 goto fail;
948 fclose(f);
949 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
950 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
951 filename);
952 goto fail;
954 if (reset_for_rollback(sha1))
955 goto fail;
956 remove_sequencer_state();
957 strbuf_release(&buf);
958 return 0;
959 fail:
960 strbuf_release(&buf);
961 return -1;
964 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
966 const char *todo_file = git_path(SEQ_TODO_FILE);
967 static struct lock_file todo_lock;
968 struct strbuf buf = STRBUF_INIT;
969 int fd;
971 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
972 if (format_todo(&buf, todo_list, opts) < 0)
973 die(_("Could not format %s."), todo_file);
974 if (write_in_full(fd, buf.buf, buf.len) < 0) {
975 strbuf_release(&buf);
976 die_errno(_("Could not write to %s"), todo_file);
978 if (commit_lock_file(&todo_lock) < 0) {
979 strbuf_release(&buf);
980 die(_("Error wrapping up %s."), todo_file);
982 strbuf_release(&buf);
985 static void save_opts(struct replay_opts *opts)
987 const char *opts_file = git_path(SEQ_OPTS_FILE);
989 if (opts->no_commit)
990 git_config_set_in_file(opts_file, "options.no-commit", "true");
991 if (opts->edit)
992 git_config_set_in_file(opts_file, "options.edit", "true");
993 if (opts->signoff)
994 git_config_set_in_file(opts_file, "options.signoff", "true");
995 if (opts->record_origin)
996 git_config_set_in_file(opts_file, "options.record-origin", "true");
997 if (opts->allow_ff)
998 git_config_set_in_file(opts_file, "options.allow-ff", "true");
999 if (opts->mainline) {
1000 struct strbuf buf = STRBUF_INIT;
1001 strbuf_addf(&buf, "%d", opts->mainline);
1002 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
1003 strbuf_release(&buf);
1005 if (opts->strategy)
1006 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
1007 if (opts->gpg_sign)
1008 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
1009 if (opts->xopts) {
1010 int i;
1011 for (i = 0; i < opts->xopts_nr; i++)
1012 git_config_set_multivar_in_file(opts_file,
1013 "options.strategy-option",
1014 opts->xopts[i], "^$", 0);
1018 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1020 struct commit_list *cur;
1021 int res;
1023 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1024 if (opts->allow_ff)
1025 assert(!(opts->signoff || opts->no_commit ||
1026 opts->record_origin || opts->edit));
1027 read_and_refresh_cache(opts);
1029 for (cur = todo_list; cur; cur = cur->next) {
1030 save_todo(cur, opts);
1031 res = do_pick_commit(cur->item, opts);
1032 if (res)
1033 return res;
1037 * Sequence of picks finished successfully; cleanup by
1038 * removing the .git/sequencer directory
1040 remove_sequencer_state();
1041 return 0;
1044 static int continue_single_pick(void)
1046 const char *argv[] = { "commit", NULL };
1048 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1049 !file_exists(git_path("REVERT_HEAD")))
1050 return error(_("no cherry-pick or revert in progress"));
1051 return run_command_v_opt(argv, RUN_GIT_CMD);
1054 static int sequencer_continue(struct replay_opts *opts)
1056 struct commit_list *todo_list = NULL;
1058 if (!file_exists(git_path(SEQ_TODO_FILE)))
1059 return continue_single_pick();
1060 read_populate_opts(&opts);
1061 read_populate_todo(&todo_list, opts);
1063 /* Verify that the conflict has been resolved */
1064 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1065 file_exists(git_path("REVERT_HEAD"))) {
1066 int ret = continue_single_pick();
1067 if (ret)
1068 return ret;
1070 if (index_differs_from("HEAD", 0))
1071 return error_dirty_index(opts);
1072 todo_list = todo_list->next;
1073 return pick_commits(todo_list, opts);
1076 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1078 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1079 return do_pick_commit(cmit, opts);
1082 int sequencer_pick_revisions(struct replay_opts *opts)
1084 struct commit_list *todo_list = NULL;
1085 unsigned char sha1[20];
1086 int i;
1088 if (opts->subcommand == REPLAY_NONE)
1089 assert(opts->revs);
1091 read_and_refresh_cache(opts);
1094 * Decide what to do depending on the arguments; a fresh
1095 * cherry-pick should be handled differently from an existing
1096 * one that is being continued
1098 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1099 remove_sequencer_state();
1100 return 0;
1102 if (opts->subcommand == REPLAY_ROLLBACK)
1103 return sequencer_rollback(opts);
1104 if (opts->subcommand == REPLAY_CONTINUE)
1105 return sequencer_continue(opts);
1107 for (i = 0; i < opts->revs->pending.nr; i++) {
1108 unsigned char sha1[20];
1109 const char *name = opts->revs->pending.objects[i].name;
1111 /* This happens when using --stdin. */
1112 if (!strlen(name))
1113 continue;
1115 if (!get_sha1(name, sha1)) {
1116 if (!lookup_commit_reference_gently(sha1, 1)) {
1117 enum object_type type = sha1_object_info(sha1, NULL);
1118 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1120 } else
1121 die(_("%s: bad revision"), name);
1125 * If we were called as "git cherry-pick <commit>", just
1126 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1127 * REVERT_HEAD, and don't touch the sequencer state.
1128 * This means it is possible to cherry-pick in the middle
1129 * of a cherry-pick sequence.
1131 if (opts->revs->cmdline.nr == 1 &&
1132 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1133 opts->revs->no_walk &&
1134 !opts->revs->cmdline.rev->flags) {
1135 struct commit *cmit;
1136 if (prepare_revision_walk(opts->revs))
1137 die(_("revision walk setup failed"));
1138 cmit = get_revision(opts->revs);
1139 if (!cmit || get_revision(opts->revs))
1140 die("BUG: expected exactly one commit from walk");
1141 return single_pick(cmit, opts);
1145 * Start a new cherry-pick/ revert sequence; but
1146 * first, make sure that an existing one isn't in
1147 * progress
1150 walk_revs_populate_todo(&todo_list, opts);
1151 if (create_seq_dir() < 0)
1152 return -1;
1153 if (get_sha1("HEAD", sha1)) {
1154 if (opts->action == REPLAY_REVERT)
1155 return error(_("Can't revert as initial commit"));
1156 return error(_("Can't cherry-pick into empty head"));
1158 save_head(sha1_to_hex(sha1));
1159 save_opts(opts);
1160 return pick_commits(todo_list, opts);
1163 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1165 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1166 struct strbuf sob = STRBUF_INIT;
1167 int has_footer;
1169 strbuf_addstr(&sob, sign_off_header);
1170 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1171 getenv("GIT_COMMITTER_EMAIL")));
1172 strbuf_addch(&sob, '\n');
1175 * If the whole message buffer is equal to the sob, pretend that we
1176 * found a conforming footer with a matching sob
1178 if (msgbuf->len - ignore_footer == sob.len &&
1179 !strncmp(msgbuf->buf, sob.buf, sob.len))
1180 has_footer = 3;
1181 else
1182 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1184 if (!has_footer) {
1185 const char *append_newlines = NULL;
1186 size_t len = msgbuf->len - ignore_footer;
1188 if (!len) {
1190 * The buffer is completely empty. Leave foom for
1191 * the title and body to be filled in by the user.
1193 append_newlines = "\n\n";
1194 } else if (msgbuf->buf[len - 1] != '\n') {
1196 * Incomplete line. Complete the line and add a
1197 * blank one so that there is an empty line between
1198 * the message body and the sob.
1200 append_newlines = "\n\n";
1201 } else if (len == 1) {
1203 * Buffer contains a single newline. Add another
1204 * so that we leave room for the title and body.
1206 append_newlines = "\n";
1207 } else if (msgbuf->buf[len - 2] != '\n') {
1209 * Buffer ends with a single newline. Add another
1210 * so that there is an empty line between the message
1211 * body and the sob.
1213 append_newlines = "\n";
1214 } /* else, the buffer already ends with two newlines. */
1216 if (append_newlines)
1217 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1218 append_newlines, strlen(append_newlines));
1221 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1222 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1223 sob.buf, sob.len);
1225 strbuf_release(&sob);