tag.c: implement '--format' option
[git/debian.git] / sequencer.c
blob147adfac818b53156b1ad269211014e21525619c
1 #include "cache.h"
2 #include "lockfile.h"
3 #include "sequencer.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "run-command.h"
9 #include "exec_cmd.h"
10 #include "utf8.h"
11 #include "cache-tree.h"
12 #include "diff.h"
13 #include "revision.h"
14 #include "rerere.h"
15 #include "merge-recursive.h"
16 #include "refs.h"
17 #include "argv-array.h"
19 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
21 const char sign_off_header[] = "Signed-off-by: ";
22 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
24 static GIT_PATH_FUNC(git_path_todo_file, SEQ_TODO_FILE)
25 static GIT_PATH_FUNC(git_path_opts_file, SEQ_OPTS_FILE)
26 static GIT_PATH_FUNC(git_path_seq_dir, SEQ_DIR)
27 static GIT_PATH_FUNC(git_path_head_file, SEQ_HEAD_FILE)
29 static int is_rfc2822_line(const char *buf, int len)
31 int i;
33 for (i = 0; i < len; i++) {
34 int ch = buf[i];
35 if (ch == ':')
36 return 1;
37 if (!isalnum(ch) && ch != '-')
38 break;
41 return 0;
44 static int is_cherry_picked_from_line(const char *buf, int len)
47 * We only care that it looks roughly like (cherry picked from ...)
49 return len > strlen(cherry_picked_prefix) + 1 &&
50 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
54 * Returns 0 for non-conforming footer
55 * Returns 1 for conforming footer
56 * Returns 2 when sob exists within conforming footer
57 * Returns 3 when sob exists within conforming footer as last entry
59 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
60 int ignore_footer)
62 char prev;
63 int i, k;
64 int len = sb->len - ignore_footer;
65 const char *buf = sb->buf;
66 int found_sob = 0;
68 /* footer must end with newline */
69 if (!len || buf[len - 1] != '\n')
70 return 0;
72 prev = '\0';
73 for (i = len - 1; i > 0; i--) {
74 char ch = buf[i];
75 if (prev == '\n' && ch == '\n') /* paragraph break */
76 break;
77 prev = ch;
80 /* require at least one blank line */
81 if (prev != '\n' || buf[i] != '\n')
82 return 0;
84 /* advance to start of last paragraph */
85 while (i < len - 1 && buf[i] == '\n')
86 i++;
88 for (; i < len; i = k) {
89 int found_rfc2822;
91 for (k = i; k < len && buf[k] != '\n'; k++)
92 ; /* do nothing */
93 k++;
95 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
96 if (found_rfc2822 && sob &&
97 !strncmp(buf + i, sob->buf, sob->len))
98 found_sob = k;
100 if (!(found_rfc2822 ||
101 is_cherry_picked_from_line(buf + i, k - i - 1)))
102 return 0;
104 if (found_sob == i)
105 return 3;
106 if (found_sob)
107 return 2;
108 return 1;
111 static void remove_sequencer_state(void)
113 struct strbuf seq_dir = STRBUF_INIT;
115 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
116 remove_dir_recursively(&seq_dir, 0);
117 strbuf_release(&seq_dir);
120 static const char *action_name(const struct replay_opts *opts)
122 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
125 struct commit_message {
126 char *parent_label;
127 const char *label;
128 const char *subject;
129 const char *message;
132 static int get_message(struct commit *commit, struct commit_message *out)
134 const char *abbrev, *subject;
135 int abbrev_len, subject_len;
136 char *q;
138 if (!git_commit_encoding)
139 git_commit_encoding = "UTF-8";
141 out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
142 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
143 abbrev_len = strlen(abbrev);
145 subject_len = find_commit_subject(out->message, &subject);
147 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
148 strlen("... ") + subject_len + 1);
149 q = out->parent_label;
150 q = mempcpy(q, "parent of ", strlen("parent of "));
151 out->label = q;
152 q = mempcpy(q, abbrev, abbrev_len);
153 q = mempcpy(q, "... ", strlen("... "));
154 out->subject = q;
155 q = mempcpy(q, subject, subject_len);
156 *q = '\0';
157 return 0;
160 static void free_message(struct commit *commit, struct commit_message *msg)
162 free(msg->parent_label);
163 unuse_commit_buffer(commit, msg->message);
166 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
168 const char *filename;
169 int fd;
170 struct strbuf buf = STRBUF_INIT;
172 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
174 filename = git_path("%s", pseudoref);
175 fd = open(filename, O_WRONLY | O_CREAT, 0666);
176 if (fd < 0)
177 die_errno(_("Could not open '%s' for writing"), filename);
178 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
179 die_errno(_("Could not write to '%s'"), filename);
180 strbuf_release(&buf);
183 static void print_advice(int show_hint, struct replay_opts *opts)
185 char *msg = getenv("GIT_CHERRY_PICK_HELP");
187 if (msg) {
188 fprintf(stderr, "%s\n", msg);
190 * A conflict has occurred but the porcelain
191 * (typically rebase --interactive) wants to take care
192 * of the commit itself so remove CHERRY_PICK_HEAD
194 unlink(git_path_cherry_pick_head());
195 return;
198 if (show_hint) {
199 if (opts->no_commit)
200 advise(_("after resolving the conflicts, mark the corrected paths\n"
201 "with 'git add <paths>' or 'git rm <paths>'"));
202 else
203 advise(_("after resolving the conflicts, mark the corrected paths\n"
204 "with 'git add <paths>' or 'git rm <paths>'\n"
205 "and commit the result with 'git commit'"));
209 static void write_message(struct strbuf *msgbuf, const char *filename)
211 static struct lock_file msg_file;
213 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
214 LOCK_DIE_ON_ERROR);
215 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
216 die_errno(_("Could not write to %s"), filename);
217 strbuf_release(msgbuf);
218 if (commit_lock_file(&msg_file) < 0)
219 die(_("Error wrapping up %s"), filename);
222 static struct tree *empty_tree(void)
224 return lookup_tree(EMPTY_TREE_SHA1_BIN);
227 static int error_dirty_index(struct replay_opts *opts)
229 if (read_cache_unmerged())
230 return error_resolve_conflict(action_name(opts));
232 /* Different translation strings for cherry-pick and revert */
233 if (opts->action == REPLAY_PICK)
234 error(_("Your local changes would be overwritten by cherry-pick."));
235 else
236 error(_("Your local changes would be overwritten by revert."));
238 if (advice_commit_before_merge)
239 advise(_("Commit your changes or stash them to proceed."));
240 return -1;
243 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
244 int unborn, struct replay_opts *opts)
246 struct ref_transaction *transaction;
247 struct strbuf sb = STRBUF_INIT;
248 struct strbuf err = STRBUF_INIT;
250 read_cache();
251 if (checkout_fast_forward(from, to, 1))
252 exit(128); /* the callee should have complained already */
254 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
256 transaction = ref_transaction_begin(&err);
257 if (!transaction ||
258 ref_transaction_update(transaction, "HEAD",
259 to, unborn ? null_sha1 : from,
260 0, sb.buf, &err) ||
261 ref_transaction_commit(transaction, &err)) {
262 ref_transaction_free(transaction);
263 error("%s", err.buf);
264 strbuf_release(&sb);
265 strbuf_release(&err);
266 return -1;
269 strbuf_release(&sb);
270 strbuf_release(&err);
271 ref_transaction_free(transaction);
272 return 0;
275 void append_conflicts_hint(struct strbuf *msgbuf)
277 int i;
279 strbuf_addch(msgbuf, '\n');
280 strbuf_commented_addf(msgbuf, "Conflicts:\n");
281 for (i = 0; i < active_nr;) {
282 const struct cache_entry *ce = active_cache[i++];
283 if (ce_stage(ce)) {
284 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
285 while (i < active_nr && !strcmp(ce->name,
286 active_cache[i]->name))
287 i++;
292 static int do_recursive_merge(struct commit *base, struct commit *next,
293 const char *base_label, const char *next_label,
294 unsigned char *head, struct strbuf *msgbuf,
295 struct replay_opts *opts)
297 struct merge_options o;
298 struct tree *result, *next_tree, *base_tree, *head_tree;
299 int clean;
300 const char **xopt;
301 static struct lock_file index_lock;
303 hold_locked_index(&index_lock, 1);
305 read_cache();
307 init_merge_options(&o);
308 o.ancestor = base ? base_label : "(empty tree)";
309 o.branch1 = "HEAD";
310 o.branch2 = next ? next_label : "(empty tree)";
312 head_tree = parse_tree_indirect(head);
313 next_tree = next ? next->tree : empty_tree();
314 base_tree = base ? base->tree : empty_tree();
316 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
317 parse_merge_opt(&o, *xopt);
319 clean = merge_trees(&o,
320 head_tree,
321 next_tree, base_tree, &result);
323 if (active_cache_changed &&
324 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
325 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
326 die(_("%s: Unable to write new index file"), action_name(opts));
327 rollback_lock_file(&index_lock);
329 if (opts->signoff)
330 append_signoff(msgbuf, 0, 0);
332 if (!clean)
333 append_conflicts_hint(msgbuf);
335 return !clean;
338 static int is_index_unchanged(void)
340 unsigned char head_sha1[20];
341 struct commit *head_commit;
343 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
344 return error(_("Could not resolve HEAD commit\n"));
346 head_commit = lookup_commit(head_sha1);
349 * If head_commit is NULL, check_commit, called from
350 * lookup_commit, would have indicated that head_commit is not
351 * a commit object already. parse_commit() will return failure
352 * without further complaints in such a case. Otherwise, if
353 * the commit is invalid, parse_commit() will complain. So
354 * there is nothing for us to say here. Just return failure.
356 if (parse_commit(head_commit))
357 return -1;
359 if (!active_cache_tree)
360 active_cache_tree = cache_tree();
362 if (!cache_tree_fully_valid(active_cache_tree))
363 if (cache_tree_update(&the_index, 0))
364 return error(_("Unable to update cache tree\n"));
366 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
370 * If we are cherry-pick, and if the merge did not result in
371 * hand-editing, we will hit this commit and inherit the original
372 * author date and name.
373 * If we are revert, or if our cherry-pick results in a hand merge,
374 * we had better say that the current user is responsible for that.
376 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
377 int allow_empty)
379 struct argv_array array;
380 int rc;
381 const char *value;
383 argv_array_init(&array);
384 argv_array_push(&array, "commit");
385 argv_array_push(&array, "-n");
387 if (opts->gpg_sign)
388 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
389 if (opts->signoff)
390 argv_array_push(&array, "-s");
391 if (!opts->edit) {
392 argv_array_push(&array, "-F");
393 argv_array_push(&array, defmsg);
394 if (!opts->signoff &&
395 !opts->record_origin &&
396 git_config_get_value("commit.cleanup", &value))
397 argv_array_push(&array, "--cleanup=verbatim");
400 if (allow_empty)
401 argv_array_push(&array, "--allow-empty");
403 if (opts->allow_empty_message)
404 argv_array_push(&array, "--allow-empty-message");
406 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
407 argv_array_clear(&array);
408 return rc;
411 static int is_original_commit_empty(struct commit *commit)
413 const unsigned char *ptree_sha1;
415 if (parse_commit(commit))
416 return error(_("Could not parse commit %s\n"),
417 sha1_to_hex(commit->object.sha1));
418 if (commit->parents) {
419 struct commit *parent = commit->parents->item;
420 if (parse_commit(parent))
421 return error(_("Could not parse parent commit %s\n"),
422 sha1_to_hex(parent->object.sha1));
423 ptree_sha1 = parent->tree->object.sha1;
424 } else {
425 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
428 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
432 * Do we run "git commit" with "--allow-empty"?
434 static int allow_empty(struct replay_opts *opts, struct commit *commit)
436 int index_unchanged, empty_commit;
439 * Three cases:
441 * (1) we do not allow empty at all and error out.
443 * (2) we allow ones that were initially empty, but
444 * forbid the ones that become empty;
446 * (3) we allow both.
448 if (!opts->allow_empty)
449 return 0; /* let "git commit" barf as necessary */
451 index_unchanged = is_index_unchanged();
452 if (index_unchanged < 0)
453 return index_unchanged;
454 if (!index_unchanged)
455 return 0; /* we do not have to say --allow-empty */
457 if (opts->keep_redundant_commits)
458 return 1;
460 empty_commit = is_original_commit_empty(commit);
461 if (empty_commit < 0)
462 return empty_commit;
463 if (!empty_commit)
464 return 0;
465 else
466 return 1;
469 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
471 unsigned char head[20];
472 struct commit *base, *next, *parent;
473 const char *base_label, *next_label;
474 struct commit_message msg = { NULL, NULL, NULL, NULL };
475 struct strbuf msgbuf = STRBUF_INIT;
476 int res, unborn = 0, allow;
478 if (opts->no_commit) {
480 * We do not intend to commit immediately. We just want to
481 * merge the differences in, so let's compute the tree
482 * that represents the "current" state for merge-recursive
483 * to work on.
485 if (write_cache_as_tree(head, 0, NULL))
486 die (_("Your index file is unmerged."));
487 } else {
488 unborn = get_sha1("HEAD", head);
489 if (unborn)
490 hashcpy(head, EMPTY_TREE_SHA1_BIN);
491 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
492 return error_dirty_index(opts);
494 discard_cache();
496 if (!commit->parents) {
497 parent = NULL;
499 else if (commit->parents->next) {
500 /* Reverting or cherry-picking a merge commit */
501 int cnt;
502 struct commit_list *p;
504 if (!opts->mainline)
505 return error(_("Commit %s is a merge but no -m option was given."),
506 sha1_to_hex(commit->object.sha1));
508 for (cnt = 1, p = commit->parents;
509 cnt != opts->mainline && p;
510 cnt++)
511 p = p->next;
512 if (cnt != opts->mainline || !p)
513 return error(_("Commit %s does not have parent %d"),
514 sha1_to_hex(commit->object.sha1), opts->mainline);
515 parent = p->item;
516 } else if (0 < opts->mainline)
517 return error(_("Mainline was specified but commit %s is not a merge."),
518 sha1_to_hex(commit->object.sha1));
519 else
520 parent = commit->parents->item;
522 if (opts->allow_ff &&
523 ((parent && !hashcmp(parent->object.sha1, head)) ||
524 (!parent && unborn)))
525 return fast_forward_to(commit->object.sha1, head, unborn, opts);
527 if (parent && parse_commit(parent) < 0)
528 /* TRANSLATORS: The first %s will be "revert" or
529 "cherry-pick", the second %s a SHA1 */
530 return error(_("%s: cannot parse parent commit %s"),
531 action_name(opts), sha1_to_hex(parent->object.sha1));
533 if (get_message(commit, &msg) != 0)
534 return error(_("Cannot get commit message for %s"),
535 sha1_to_hex(commit->object.sha1));
538 * "commit" is an existing commit. We would want to apply
539 * the difference it introduces since its first parent "prev"
540 * on top of the current HEAD if we are cherry-pick. Or the
541 * reverse of it if we are revert.
544 if (opts->action == REPLAY_REVERT) {
545 base = commit;
546 base_label = msg.label;
547 next = parent;
548 next_label = msg.parent_label;
549 strbuf_addstr(&msgbuf, "Revert \"");
550 strbuf_addstr(&msgbuf, msg.subject);
551 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
552 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
554 if (commit->parents && commit->parents->next) {
555 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
556 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
558 strbuf_addstr(&msgbuf, ".\n");
559 } else {
560 const char *p;
562 base = parent;
563 base_label = msg.parent_label;
564 next = commit;
565 next_label = msg.label;
568 * Append the commit log message to msgbuf; it starts
569 * after the tree, parent, author, committer
570 * information followed by "\n\n".
572 p = strstr(msg.message, "\n\n");
573 if (p) {
574 p += 2;
575 strbuf_addstr(&msgbuf, p);
578 if (opts->record_origin) {
579 if (!has_conforming_footer(&msgbuf, NULL, 0))
580 strbuf_addch(&msgbuf, '\n');
581 strbuf_addstr(&msgbuf, cherry_picked_prefix);
582 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
583 strbuf_addstr(&msgbuf, ")\n");
587 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
588 res = do_recursive_merge(base, next, base_label, next_label,
589 head, &msgbuf, opts);
590 write_message(&msgbuf, git_path_merge_msg());
591 } else {
592 struct commit_list *common = NULL;
593 struct commit_list *remotes = NULL;
595 write_message(&msgbuf, git_path_merge_msg());
597 commit_list_insert(base, &common);
598 commit_list_insert(next, &remotes);
599 res = try_merge_command(opts->strategy, opts->xopts_nr, 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 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
613 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
614 write_cherry_pick_head(commit, "REVERT_HEAD");
616 if (res) {
617 error(opts->action == REPLAY_REVERT
618 ? _("could not revert %s... %s")
619 : _("could not apply %s... %s"),
620 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
621 msg.subject);
622 print_advice(res == 1, opts);
623 rerere(opts->allow_rerere_auto);
624 goto leave;
627 allow = allow_empty(opts, commit);
628 if (allow < 0) {
629 res = allow;
630 goto leave;
632 if (!opts->no_commit)
633 res = run_git_commit(git_path_merge_msg(), opts, allow);
635 leave:
636 free_message(commit, &msg);
638 return res;
641 static void prepare_revs(struct replay_opts *opts)
644 * picking (but not reverting) ranges (but not individual revisions)
645 * should be done in reverse
647 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
648 opts->revs->reverse ^= 1;
650 if (prepare_revision_walk(opts->revs))
651 die(_("revision walk setup failed"));
653 if (!opts->revs->commits)
654 die(_("empty commit set passed"));
657 static void read_and_refresh_cache(struct replay_opts *opts)
659 static struct lock_file index_lock;
660 int index_fd = hold_locked_index(&index_lock, 0);
661 if (read_index_preload(&the_index, NULL) < 0)
662 die(_("git %s: failed to read the index"), action_name(opts));
663 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
664 if (the_index.cache_changed && index_fd >= 0) {
665 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
666 die(_("git %s: failed to refresh the index"), action_name(opts));
668 rollback_lock_file(&index_lock);
671 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
672 struct replay_opts *opts)
674 struct commit_list *cur = NULL;
675 const char *sha1_abbrev = NULL;
676 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
677 const char *subject;
678 int subject_len;
680 for (cur = todo_list; cur; cur = cur->next) {
681 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
682 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
683 subject_len = find_commit_subject(commit_buffer, &subject);
684 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
685 subject_len, subject);
686 unuse_commit_buffer(cur->item, commit_buffer);
688 return 0;
691 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
693 unsigned char commit_sha1[20];
694 enum replay_action action;
695 char *end_of_object_name;
696 int saved, status, padding;
698 if (starts_with(bol, "pick")) {
699 action = REPLAY_PICK;
700 bol += strlen("pick");
701 } else if (starts_with(bol, "revert")) {
702 action = REPLAY_REVERT;
703 bol += strlen("revert");
704 } else
705 return NULL;
707 /* Eat up extra spaces/ tabs before object name */
708 padding = strspn(bol, " \t");
709 if (!padding)
710 return NULL;
711 bol += padding;
713 end_of_object_name = bol + strcspn(bol, " \t\n");
714 saved = *end_of_object_name;
715 *end_of_object_name = '\0';
716 status = get_sha1(bol, commit_sha1);
717 *end_of_object_name = saved;
720 * Verify that the action matches up with the one in
721 * opts; we don't support arbitrary instructions
723 if (action != opts->action) {
724 const char *action_str;
725 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
726 error(_("Cannot %s during a %s"), action_str, action_name(opts));
727 return NULL;
730 if (status < 0)
731 return NULL;
733 return lookup_commit_reference(commit_sha1);
736 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
737 struct replay_opts *opts)
739 struct commit_list **next = todo_list;
740 struct commit *commit;
741 char *p = buf;
742 int i;
744 for (i = 1; *p; i++) {
745 char *eol = strchrnul(p, '\n');
746 commit = parse_insn_line(p, eol, opts);
747 if (!commit)
748 return error(_("Could not parse line %d."), i);
749 next = commit_list_append(commit, next);
750 p = *eol ? eol + 1 : eol;
752 if (!*todo_list)
753 return error(_("No commits parsed."));
754 return 0;
757 static void read_populate_todo(struct commit_list **todo_list,
758 struct replay_opts *opts)
760 struct strbuf buf = STRBUF_INIT;
761 int fd, res;
763 fd = open(git_path_todo_file(), O_RDONLY);
764 if (fd < 0)
765 die_errno(_("Could not open %s"), git_path_todo_file());
766 if (strbuf_read(&buf, fd, 0) < 0) {
767 close(fd);
768 strbuf_release(&buf);
769 die(_("Could not read %s."), git_path_todo_file());
771 close(fd);
773 res = parse_insn_buffer(buf.buf, todo_list, opts);
774 strbuf_release(&buf);
775 if (res)
776 die(_("Unusable instruction sheet: %s"), git_path_todo_file());
779 static int populate_opts_cb(const char *key, const char *value, void *data)
781 struct replay_opts *opts = data;
782 int error_flag = 1;
784 if (!value)
785 error_flag = 0;
786 else if (!strcmp(key, "options.no-commit"))
787 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
788 else if (!strcmp(key, "options.edit"))
789 opts->edit = git_config_bool_or_int(key, value, &error_flag);
790 else if (!strcmp(key, "options.signoff"))
791 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
792 else if (!strcmp(key, "options.record-origin"))
793 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
794 else if (!strcmp(key, "options.allow-ff"))
795 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
796 else if (!strcmp(key, "options.mainline"))
797 opts->mainline = git_config_int(key, value);
798 else if (!strcmp(key, "options.strategy"))
799 git_config_string(&opts->strategy, key, value);
800 else if (!strcmp(key, "options.gpg-sign"))
801 git_config_string(&opts->gpg_sign, key, value);
802 else if (!strcmp(key, "options.strategy-option")) {
803 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
804 opts->xopts[opts->xopts_nr++] = xstrdup(value);
805 } else
806 return error(_("Invalid key: %s"), key);
808 if (!error_flag)
809 return error(_("Invalid value for %s: %s"), key, value);
811 return 0;
814 static void read_populate_opts(struct replay_opts **opts_ptr)
816 if (!file_exists(git_path_opts_file()))
817 return;
818 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), *opts_ptr) < 0)
819 die(_("Malformed options sheet: %s"), git_path_opts_file());
822 static void walk_revs_populate_todo(struct commit_list **todo_list,
823 struct replay_opts *opts)
825 struct commit *commit;
826 struct commit_list **next;
828 prepare_revs(opts);
830 next = todo_list;
831 while ((commit = get_revision(opts->revs)))
832 next = commit_list_append(commit, next);
835 static int create_seq_dir(void)
837 if (file_exists(git_path_seq_dir())) {
838 error(_("a cherry-pick or revert is already in progress"));
839 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
840 return -1;
842 else if (mkdir(git_path_seq_dir(), 0777) < 0)
843 die_errno(_("Could not create sequencer directory %s"),
844 git_path_seq_dir());
845 return 0;
848 static void save_head(const char *head)
850 static struct lock_file head_lock;
851 struct strbuf buf = STRBUF_INIT;
852 int fd;
854 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), LOCK_DIE_ON_ERROR);
855 strbuf_addf(&buf, "%s\n", head);
856 if (write_in_full(fd, buf.buf, buf.len) < 0)
857 die_errno(_("Could not write to %s"), git_path_head_file());
858 if (commit_lock_file(&head_lock) < 0)
859 die(_("Error wrapping up %s."), git_path_head_file());
862 static int reset_for_rollback(const unsigned char *sha1)
864 const char *argv[4]; /* reset --merge <arg> + NULL */
865 argv[0] = "reset";
866 argv[1] = "--merge";
867 argv[2] = sha1_to_hex(sha1);
868 argv[3] = NULL;
869 return run_command_v_opt(argv, RUN_GIT_CMD);
872 static int rollback_single_pick(void)
874 unsigned char head_sha1[20];
876 if (!file_exists(git_path_cherry_pick_head()) &&
877 !file_exists(git_path_revert_head()))
878 return error(_("no cherry-pick or revert in progress"));
879 if (read_ref_full("HEAD", 0, head_sha1, NULL))
880 return error(_("cannot resolve HEAD"));
881 if (is_null_sha1(head_sha1))
882 return error(_("cannot abort from a branch yet to be born"));
883 return reset_for_rollback(head_sha1);
886 static int sequencer_rollback(struct replay_opts *opts)
888 FILE *f;
889 unsigned char sha1[20];
890 struct strbuf buf = STRBUF_INIT;
892 f = fopen(git_path_head_file(), "r");
893 if (!f && errno == ENOENT) {
895 * There is no multiple-cherry-pick in progress.
896 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
897 * a single-cherry-pick in progress, abort that.
899 return rollback_single_pick();
901 if (!f)
902 return error(_("cannot open %s: %s"), git_path_head_file(),
903 strerror(errno));
904 if (strbuf_getline(&buf, f, '\n')) {
905 error(_("cannot read %s: %s"), git_path_head_file(),
906 ferror(f) ? strerror(errno) : _("unexpected end of file"));
907 fclose(f);
908 goto fail;
910 fclose(f);
911 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
912 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
913 git_path_head_file());
914 goto fail;
916 if (reset_for_rollback(sha1))
917 goto fail;
918 remove_sequencer_state();
919 strbuf_release(&buf);
920 return 0;
921 fail:
922 strbuf_release(&buf);
923 return -1;
926 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
928 static struct lock_file todo_lock;
929 struct strbuf buf = STRBUF_INIT;
930 int fd;
932 fd = hold_lock_file_for_update(&todo_lock, git_path_todo_file(), LOCK_DIE_ON_ERROR);
933 if (format_todo(&buf, todo_list, opts) < 0)
934 die(_("Could not format %s."), git_path_todo_file());
935 if (write_in_full(fd, buf.buf, buf.len) < 0) {
936 strbuf_release(&buf);
937 die_errno(_("Could not write to %s"), git_path_todo_file());
939 if (commit_lock_file(&todo_lock) < 0) {
940 strbuf_release(&buf);
941 die(_("Error wrapping up %s."), git_path_todo_file());
943 strbuf_release(&buf);
946 static void save_opts(struct replay_opts *opts)
948 const char *opts_file = git_path_opts_file();
950 if (opts->no_commit)
951 git_config_set_in_file(opts_file, "options.no-commit", "true");
952 if (opts->edit)
953 git_config_set_in_file(opts_file, "options.edit", "true");
954 if (opts->signoff)
955 git_config_set_in_file(opts_file, "options.signoff", "true");
956 if (opts->record_origin)
957 git_config_set_in_file(opts_file, "options.record-origin", "true");
958 if (opts->allow_ff)
959 git_config_set_in_file(opts_file, "options.allow-ff", "true");
960 if (opts->mainline) {
961 struct strbuf buf = STRBUF_INIT;
962 strbuf_addf(&buf, "%d", opts->mainline);
963 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
964 strbuf_release(&buf);
966 if (opts->strategy)
967 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
968 if (opts->gpg_sign)
969 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
970 if (opts->xopts) {
971 int i;
972 for (i = 0; i < opts->xopts_nr; i++)
973 git_config_set_multivar_in_file(opts_file,
974 "options.strategy-option",
975 opts->xopts[i], "^$", 0);
979 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
981 struct commit_list *cur;
982 int res;
984 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
985 if (opts->allow_ff)
986 assert(!(opts->signoff || opts->no_commit ||
987 opts->record_origin || opts->edit));
988 read_and_refresh_cache(opts);
990 for (cur = todo_list; cur; cur = cur->next) {
991 save_todo(cur, opts);
992 res = do_pick_commit(cur->item, opts);
993 if (res)
994 return res;
998 * Sequence of picks finished successfully; cleanup by
999 * removing the .git/sequencer directory
1001 remove_sequencer_state();
1002 return 0;
1005 static int continue_single_pick(void)
1007 const char *argv[] = { "commit", NULL };
1009 if (!file_exists(git_path_cherry_pick_head()) &&
1010 !file_exists(git_path_revert_head()))
1011 return error(_("no cherry-pick or revert in progress"));
1012 return run_command_v_opt(argv, RUN_GIT_CMD);
1015 static int sequencer_continue(struct replay_opts *opts)
1017 struct commit_list *todo_list = NULL;
1019 if (!file_exists(git_path_todo_file()))
1020 return continue_single_pick();
1021 read_populate_opts(&opts);
1022 read_populate_todo(&todo_list, opts);
1024 /* Verify that the conflict has been resolved */
1025 if (file_exists(git_path_cherry_pick_head()) ||
1026 file_exists(git_path_revert_head())) {
1027 int ret = continue_single_pick();
1028 if (ret)
1029 return ret;
1031 if (index_differs_from("HEAD", 0))
1032 return error_dirty_index(opts);
1033 todo_list = todo_list->next;
1034 return pick_commits(todo_list, opts);
1037 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1039 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1040 return do_pick_commit(cmit, opts);
1043 int sequencer_pick_revisions(struct replay_opts *opts)
1045 struct commit_list *todo_list = NULL;
1046 unsigned char sha1[20];
1047 int i;
1049 if (opts->subcommand == REPLAY_NONE)
1050 assert(opts->revs);
1052 read_and_refresh_cache(opts);
1055 * Decide what to do depending on the arguments; a fresh
1056 * cherry-pick should be handled differently from an existing
1057 * one that is being continued
1059 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1060 remove_sequencer_state();
1061 return 0;
1063 if (opts->subcommand == REPLAY_ROLLBACK)
1064 return sequencer_rollback(opts);
1065 if (opts->subcommand == REPLAY_CONTINUE)
1066 return sequencer_continue(opts);
1068 for (i = 0; i < opts->revs->pending.nr; i++) {
1069 unsigned char sha1[20];
1070 const char *name = opts->revs->pending.objects[i].name;
1072 /* This happens when using --stdin. */
1073 if (!strlen(name))
1074 continue;
1076 if (!get_sha1(name, sha1)) {
1077 if (!lookup_commit_reference_gently(sha1, 1)) {
1078 enum object_type type = sha1_object_info(sha1, NULL);
1079 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1081 } else
1082 die(_("%s: bad revision"), name);
1086 * If we were called as "git cherry-pick <commit>", just
1087 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1088 * REVERT_HEAD, and don't touch the sequencer state.
1089 * This means it is possible to cherry-pick in the middle
1090 * of a cherry-pick sequence.
1092 if (opts->revs->cmdline.nr == 1 &&
1093 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1094 opts->revs->no_walk &&
1095 !opts->revs->cmdline.rev->flags) {
1096 struct commit *cmit;
1097 if (prepare_revision_walk(opts->revs))
1098 die(_("revision walk setup failed"));
1099 cmit = get_revision(opts->revs);
1100 if (!cmit || get_revision(opts->revs))
1101 die("BUG: expected exactly one commit from walk");
1102 return single_pick(cmit, opts);
1106 * Start a new cherry-pick/ revert sequence; but
1107 * first, make sure that an existing one isn't in
1108 * progress
1111 walk_revs_populate_todo(&todo_list, opts);
1112 if (create_seq_dir() < 0)
1113 return -1;
1114 if (get_sha1("HEAD", sha1)) {
1115 if (opts->action == REPLAY_REVERT)
1116 return error(_("Can't revert as initial commit"));
1117 return error(_("Can't cherry-pick into empty head"));
1119 save_head(sha1_to_hex(sha1));
1120 save_opts(opts);
1121 return pick_commits(todo_list, opts);
1124 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1126 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1127 struct strbuf sob = STRBUF_INIT;
1128 int has_footer;
1130 strbuf_addstr(&sob, sign_off_header);
1131 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1132 getenv("GIT_COMMITTER_EMAIL")));
1133 strbuf_addch(&sob, '\n');
1136 * If the whole message buffer is equal to the sob, pretend that we
1137 * found a conforming footer with a matching sob
1139 if (msgbuf->len - ignore_footer == sob.len &&
1140 !strncmp(msgbuf->buf, sob.buf, sob.len))
1141 has_footer = 3;
1142 else
1143 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1145 if (!has_footer) {
1146 const char *append_newlines = NULL;
1147 size_t len = msgbuf->len - ignore_footer;
1149 if (!len) {
1151 * The buffer is completely empty. Leave foom for
1152 * the title and body to be filled in by the user.
1154 append_newlines = "\n\n";
1155 } else if (msgbuf->buf[len - 1] != '\n') {
1157 * Incomplete line. Complete the line and add a
1158 * blank one so that there is an empty line between
1159 * the message body and the sob.
1161 append_newlines = "\n\n";
1162 } else if (len == 1) {
1164 * Buffer contains a single newline. Add another
1165 * so that we leave room for the title and body.
1167 append_newlines = "\n";
1168 } else if (msgbuf->buf[len - 2] != '\n') {
1170 * Buffer ends with a single newline. Add another
1171 * so that there is an empty line between the message
1172 * body and the sob.
1174 append_newlines = "\n";
1175 } /* else, the buffer already ends with two newlines. */
1177 if (append_newlines)
1178 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1179 append_newlines, strlen(append_newlines));
1182 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1183 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1184 sob.buf, sob.len);
1186 strbuf_release(&sob);