show-branch: use a strbuf for reflog descriptions
[git/debian.git] / sequencer.c
bloba03d4fa2521fbc119a8d6b471b9e3c1046610b84
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 int is_rfc2822_line(const char *buf, int len)
26 int i;
28 for (i = 0; i < len; i++) {
29 int ch = buf[i];
30 if (ch == ':')
31 return 1;
32 if (!isalnum(ch) && ch != '-')
33 break;
36 return 0;
39 static int is_cherry_picked_from_line(const char *buf, int len)
42 * We only care that it looks roughly like (cherry picked from ...)
44 return len > strlen(cherry_picked_prefix) + 1 &&
45 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
49 * Returns 0 for non-conforming footer
50 * Returns 1 for conforming footer
51 * Returns 2 when sob exists within conforming footer
52 * Returns 3 when sob exists within conforming footer as last entry
54 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
55 int ignore_footer)
57 char prev;
58 int i, k;
59 int len = sb->len - ignore_footer;
60 const char *buf = sb->buf;
61 int found_sob = 0;
63 /* footer must end with newline */
64 if (!len || buf[len - 1] != '\n')
65 return 0;
67 prev = '\0';
68 for (i = len - 1; i > 0; i--) {
69 char ch = buf[i];
70 if (prev == '\n' && ch == '\n') /* paragraph break */
71 break;
72 prev = ch;
75 /* require at least one blank line */
76 if (prev != '\n' || buf[i] != '\n')
77 return 0;
79 /* advance to start of last paragraph */
80 while (i < len - 1 && buf[i] == '\n')
81 i++;
83 for (; i < len; i = k) {
84 int found_rfc2822;
86 for (k = i; k < len && buf[k] != '\n'; k++)
87 ; /* do nothing */
88 k++;
90 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
91 if (found_rfc2822 && sob &&
92 !strncmp(buf + i, sob->buf, sob->len))
93 found_sob = k;
95 if (!(found_rfc2822 ||
96 is_cherry_picked_from_line(buf + i, k - i - 1)))
97 return 0;
99 if (found_sob == i)
100 return 3;
101 if (found_sob)
102 return 2;
103 return 1;
106 static void remove_sequencer_state(void)
108 struct strbuf seq_dir = STRBUF_INIT;
110 strbuf_addf(&seq_dir, "%s", git_path(SEQ_DIR));
111 remove_dir_recursively(&seq_dir, 0);
112 strbuf_release(&seq_dir);
115 static const char *action_name(const struct replay_opts *opts)
117 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
120 struct commit_message {
121 char *parent_label;
122 const char *label;
123 const char *subject;
124 const char *message;
127 static int get_message(struct commit *commit, struct commit_message *out)
129 const char *abbrev, *subject;
130 int abbrev_len, subject_len;
131 char *q;
133 if (!git_commit_encoding)
134 git_commit_encoding = "UTF-8";
136 out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
137 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
138 abbrev_len = strlen(abbrev);
140 subject_len = find_commit_subject(out->message, &subject);
142 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
143 strlen("... ") + subject_len + 1);
144 q = out->parent_label;
145 q = mempcpy(q, "parent of ", strlen("parent of "));
146 out->label = q;
147 q = mempcpy(q, abbrev, abbrev_len);
148 q = mempcpy(q, "... ", strlen("... "));
149 out->subject = q;
150 q = mempcpy(q, subject, subject_len);
151 *q = '\0';
152 return 0;
155 static void free_message(struct commit *commit, struct commit_message *msg)
157 free(msg->parent_label);
158 unuse_commit_buffer(commit, msg->message);
161 static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
163 const char *filename;
164 int fd;
165 struct strbuf buf = STRBUF_INIT;
167 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
169 filename = git_path("%s", pseudoref);
170 fd = open(filename, O_WRONLY | O_CREAT, 0666);
171 if (fd < 0)
172 die_errno(_("Could not open '%s' for writing"), filename);
173 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
174 die_errno(_("Could not write to '%s'"), filename);
175 strbuf_release(&buf);
178 static void print_advice(int show_hint, struct replay_opts *opts)
180 char *msg = getenv("GIT_CHERRY_PICK_HELP");
182 if (msg) {
183 fprintf(stderr, "%s\n", msg);
185 * A conflict has occurred but the porcelain
186 * (typically rebase --interactive) wants to take care
187 * of the commit itself so remove CHERRY_PICK_HEAD
189 unlink(git_path("CHERRY_PICK_HEAD"));
190 return;
193 if (show_hint) {
194 if (opts->no_commit)
195 advise(_("after resolving the conflicts, mark the corrected paths\n"
196 "with 'git add <paths>' or 'git rm <paths>'"));
197 else
198 advise(_("after resolving the conflicts, mark the corrected paths\n"
199 "with 'git add <paths>' or 'git rm <paths>'\n"
200 "and commit the result with 'git commit'"));
204 static void write_message(struct strbuf *msgbuf, const char *filename)
206 static struct lock_file msg_file;
208 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
209 LOCK_DIE_ON_ERROR);
210 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
211 die_errno(_("Could not write to %s"), filename);
212 strbuf_release(msgbuf);
213 if (commit_lock_file(&msg_file) < 0)
214 die(_("Error wrapping up %s"), filename);
217 static struct tree *empty_tree(void)
219 return lookup_tree(EMPTY_TREE_SHA1_BIN);
222 static int error_dirty_index(struct replay_opts *opts)
224 if (read_cache_unmerged())
225 return error_resolve_conflict(action_name(opts));
227 /* Different translation strings for cherry-pick and revert */
228 if (opts->action == REPLAY_PICK)
229 error(_("Your local changes would be overwritten by cherry-pick."));
230 else
231 error(_("Your local changes would be overwritten by revert."));
233 if (advice_commit_before_merge)
234 advise(_("Commit your changes or stash them to proceed."));
235 return -1;
238 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
239 int unborn, struct replay_opts *opts)
241 struct ref_transaction *transaction;
242 struct strbuf sb = STRBUF_INIT;
243 struct strbuf err = STRBUF_INIT;
245 read_cache();
246 if (checkout_fast_forward(from, to, 1))
247 exit(128); /* the callee should have complained already */
249 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
251 transaction = ref_transaction_begin(&err);
252 if (!transaction ||
253 ref_transaction_update(transaction, "HEAD",
254 to, unborn ? null_sha1 : from,
255 0, 1, sb.buf, &err) ||
256 ref_transaction_commit(transaction, &err)) {
257 ref_transaction_free(transaction);
258 error("%s", err.buf);
259 strbuf_release(&sb);
260 strbuf_release(&err);
261 return -1;
264 strbuf_release(&sb);
265 strbuf_release(&err);
266 ref_transaction_free(transaction);
267 return 0;
270 static int do_recursive_merge(struct commit *base, struct commit *next,
271 const char *base_label, const char *next_label,
272 unsigned char *head, struct strbuf *msgbuf,
273 struct replay_opts *opts)
275 struct merge_options o;
276 struct tree *result, *next_tree, *base_tree, *head_tree;
277 int clean;
278 const char **xopt;
279 static struct lock_file index_lock;
281 hold_locked_index(&index_lock, 1);
283 read_cache();
285 init_merge_options(&o);
286 o.ancestor = base ? base_label : "(empty tree)";
287 o.branch1 = "HEAD";
288 o.branch2 = next ? next_label : "(empty tree)";
290 head_tree = parse_tree_indirect(head);
291 next_tree = next ? next->tree : empty_tree();
292 base_tree = base ? base->tree : empty_tree();
294 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
295 parse_merge_opt(&o, *xopt);
297 clean = merge_trees(&o,
298 head_tree,
299 next_tree, base_tree, &result);
301 if (active_cache_changed &&
302 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
303 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
304 die(_("%s: Unable to write new index file"), action_name(opts));
305 rollback_lock_file(&index_lock);
307 if (opts->signoff)
308 append_signoff(msgbuf, 0, 0);
310 if (!clean) {
311 int i;
312 strbuf_addstr(msgbuf, "\nConflicts:\n");
313 for (i = 0; i < active_nr;) {
314 const struct cache_entry *ce = active_cache[i++];
315 if (ce_stage(ce)) {
316 strbuf_addch(msgbuf, '\t');
317 strbuf_addstr(msgbuf, ce->name);
318 strbuf_addch(msgbuf, '\n');
319 while (i < active_nr && !strcmp(ce->name,
320 active_cache[i]->name))
321 i++;
326 return !clean;
329 static int is_index_unchanged(void)
331 unsigned char head_sha1[20];
332 struct commit *head_commit;
334 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
335 return error(_("Could not resolve HEAD commit\n"));
337 head_commit = lookup_commit(head_sha1);
340 * If head_commit is NULL, check_commit, called from
341 * lookup_commit, would have indicated that head_commit is not
342 * a commit object already. parse_commit() will return failure
343 * without further complaints in such a case. Otherwise, if
344 * the commit is invalid, parse_commit() will complain. So
345 * there is nothing for us to say here. Just return failure.
347 if (parse_commit(head_commit))
348 return -1;
350 if (!active_cache_tree)
351 active_cache_tree = cache_tree();
353 if (!cache_tree_fully_valid(active_cache_tree))
354 if (cache_tree_update(&the_index, 0))
355 return error(_("Unable to update cache tree\n"));
357 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.sha1);
361 * If we are cherry-pick, and if the merge did not result in
362 * hand-editing, we will hit this commit and inherit the original
363 * author date and name.
364 * If we are revert, or if our cherry-pick results in a hand merge,
365 * we had better say that the current user is responsible for that.
367 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
368 int allow_empty)
370 struct argv_array array;
371 int rc;
373 argv_array_init(&array);
374 argv_array_push(&array, "commit");
375 argv_array_push(&array, "-n");
377 if (opts->gpg_sign)
378 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
379 if (opts->signoff)
380 argv_array_push(&array, "-s");
381 if (!opts->edit) {
382 argv_array_push(&array, "-F");
383 argv_array_push(&array, defmsg);
386 if (allow_empty)
387 argv_array_push(&array, "--allow-empty");
389 if (opts->allow_empty_message)
390 argv_array_push(&array, "--allow-empty-message");
392 rc = run_command_v_opt(array.argv, RUN_GIT_CMD);
393 argv_array_clear(&array);
394 return rc;
397 static int is_original_commit_empty(struct commit *commit)
399 const unsigned char *ptree_sha1;
401 if (parse_commit(commit))
402 return error(_("Could not parse commit %s\n"),
403 sha1_to_hex(commit->object.sha1));
404 if (commit->parents) {
405 struct commit *parent = commit->parents->item;
406 if (parse_commit(parent))
407 return error(_("Could not parse parent commit %s\n"),
408 sha1_to_hex(parent->object.sha1));
409 ptree_sha1 = parent->tree->object.sha1;
410 } else {
411 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
414 return !hashcmp(ptree_sha1, commit->tree->object.sha1);
418 * Do we run "git commit" with "--allow-empty"?
420 static int allow_empty(struct replay_opts *opts, struct commit *commit)
422 int index_unchanged, empty_commit;
425 * Three cases:
427 * (1) we do not allow empty at all and error out.
429 * (2) we allow ones that were initially empty, but
430 * forbid the ones that become empty;
432 * (3) we allow both.
434 if (!opts->allow_empty)
435 return 0; /* let "git commit" barf as necessary */
437 index_unchanged = is_index_unchanged();
438 if (index_unchanged < 0)
439 return index_unchanged;
440 if (!index_unchanged)
441 return 0; /* we do not have to say --allow-empty */
443 if (opts->keep_redundant_commits)
444 return 1;
446 empty_commit = is_original_commit_empty(commit);
447 if (empty_commit < 0)
448 return empty_commit;
449 if (!empty_commit)
450 return 0;
451 else
452 return 1;
455 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
457 unsigned char head[20];
458 struct commit *base, *next, *parent;
459 const char *base_label, *next_label;
460 struct commit_message msg = { NULL, NULL, NULL, NULL };
461 char *defmsg = NULL;
462 struct strbuf msgbuf = STRBUF_INIT;
463 int res, unborn = 0, allow;
465 if (opts->no_commit) {
467 * We do not intend to commit immediately. We just want to
468 * merge the differences in, so let's compute the tree
469 * that represents the "current" state for merge-recursive
470 * to work on.
472 if (write_cache_as_tree(head, 0, NULL))
473 die (_("Your index file is unmerged."));
474 } else {
475 unborn = get_sha1("HEAD", head);
476 if (unborn)
477 hashcpy(head, EMPTY_TREE_SHA1_BIN);
478 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
479 return error_dirty_index(opts);
481 discard_cache();
483 if (!commit->parents) {
484 parent = NULL;
486 else if (commit->parents->next) {
487 /* Reverting or cherry-picking a merge commit */
488 int cnt;
489 struct commit_list *p;
491 if (!opts->mainline)
492 return error(_("Commit %s is a merge but no -m option was given."),
493 sha1_to_hex(commit->object.sha1));
495 for (cnt = 1, p = commit->parents;
496 cnt != opts->mainline && p;
497 cnt++)
498 p = p->next;
499 if (cnt != opts->mainline || !p)
500 return error(_("Commit %s does not have parent %d"),
501 sha1_to_hex(commit->object.sha1), opts->mainline);
502 parent = p->item;
503 } else if (0 < opts->mainline)
504 return error(_("Mainline was specified but commit %s is not a merge."),
505 sha1_to_hex(commit->object.sha1));
506 else
507 parent = commit->parents->item;
509 if (opts->allow_ff &&
510 ((parent && !hashcmp(parent->object.sha1, head)) ||
511 (!parent && unborn)))
512 return fast_forward_to(commit->object.sha1, head, unborn, opts);
514 if (parent && parse_commit(parent) < 0)
515 /* TRANSLATORS: The first %s will be "revert" or
516 "cherry-pick", the second %s a SHA1 */
517 return error(_("%s: cannot parse parent commit %s"),
518 action_name(opts), sha1_to_hex(parent->object.sha1));
520 if (get_message(commit, &msg) != 0)
521 return error(_("Cannot get commit message for %s"),
522 sha1_to_hex(commit->object.sha1));
525 * "commit" is an existing commit. We would want to apply
526 * the difference it introduces since its first parent "prev"
527 * on top of the current HEAD if we are cherry-pick. Or the
528 * reverse of it if we are revert.
531 defmsg = git_pathdup("MERGE_MSG");
533 if (opts->action == REPLAY_REVERT) {
534 base = commit;
535 base_label = msg.label;
536 next = parent;
537 next_label = msg.parent_label;
538 strbuf_addstr(&msgbuf, "Revert \"");
539 strbuf_addstr(&msgbuf, msg.subject);
540 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
541 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
543 if (commit->parents && commit->parents->next) {
544 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
545 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
547 strbuf_addstr(&msgbuf, ".\n");
548 } else {
549 const char *p;
551 base = parent;
552 base_label = msg.parent_label;
553 next = commit;
554 next_label = msg.label;
557 * Append the commit log message to msgbuf; it starts
558 * after the tree, parent, author, committer
559 * information followed by "\n\n".
561 p = strstr(msg.message, "\n\n");
562 if (p) {
563 p += 2;
564 strbuf_addstr(&msgbuf, p);
567 if (opts->record_origin) {
568 if (!has_conforming_footer(&msgbuf, NULL, 0))
569 strbuf_addch(&msgbuf, '\n');
570 strbuf_addstr(&msgbuf, cherry_picked_prefix);
571 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
572 strbuf_addstr(&msgbuf, ")\n");
576 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REPLAY_REVERT) {
577 res = do_recursive_merge(base, next, base_label, next_label,
578 head, &msgbuf, opts);
579 write_message(&msgbuf, defmsg);
580 } else {
581 struct commit_list *common = NULL;
582 struct commit_list *remotes = NULL;
584 write_message(&msgbuf, defmsg);
586 commit_list_insert(base, &common);
587 commit_list_insert(next, &remotes);
588 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
589 common, sha1_to_hex(head), remotes);
590 free_commit_list(common);
591 free_commit_list(remotes);
595 * If the merge was clean or if it failed due to conflict, we write
596 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
597 * However, if the merge did not even start, then we don't want to
598 * write it at all.
600 if (opts->action == REPLAY_PICK && !opts->no_commit && (res == 0 || res == 1))
601 write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
602 if (opts->action == REPLAY_REVERT && ((opts->no_commit && res == 0) || res == 1))
603 write_cherry_pick_head(commit, "REVERT_HEAD");
605 if (res) {
606 error(opts->action == REPLAY_REVERT
607 ? _("could not revert %s... %s")
608 : _("could not apply %s... %s"),
609 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
610 msg.subject);
611 print_advice(res == 1, opts);
612 rerere(opts->allow_rerere_auto);
613 goto leave;
616 allow = allow_empty(opts, commit);
617 if (allow < 0) {
618 res = allow;
619 goto leave;
621 if (!opts->no_commit)
622 res = run_git_commit(defmsg, opts, allow);
624 leave:
625 free_message(commit, &msg);
626 free(defmsg);
628 return res;
631 static void prepare_revs(struct replay_opts *opts)
634 * picking (but not reverting) ranges (but not individual revisions)
635 * should be done in reverse
637 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
638 opts->revs->reverse ^= 1;
640 if (prepare_revision_walk(opts->revs))
641 die(_("revision walk setup failed"));
643 if (!opts->revs->commits)
644 die(_("empty commit set passed"));
647 static void read_and_refresh_cache(struct replay_opts *opts)
649 static struct lock_file index_lock;
650 int index_fd = hold_locked_index(&index_lock, 0);
651 if (read_index_preload(&the_index, NULL) < 0)
652 die(_("git %s: failed to read the index"), action_name(opts));
653 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
654 if (the_index.cache_changed && index_fd >= 0) {
655 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
656 die(_("git %s: failed to refresh the index"), action_name(opts));
658 rollback_lock_file(&index_lock);
661 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
662 struct replay_opts *opts)
664 struct commit_list *cur = NULL;
665 const char *sha1_abbrev = NULL;
666 const char *action_str = opts->action == REPLAY_REVERT ? "revert" : "pick";
667 const char *subject;
668 int subject_len;
670 for (cur = todo_list; cur; cur = cur->next) {
671 const char *commit_buffer = get_commit_buffer(cur->item, NULL);
672 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
673 subject_len = find_commit_subject(commit_buffer, &subject);
674 strbuf_addf(buf, "%s %s %.*s\n", action_str, sha1_abbrev,
675 subject_len, subject);
676 unuse_commit_buffer(cur->item, commit_buffer);
678 return 0;
681 static struct commit *parse_insn_line(char *bol, char *eol, struct replay_opts *opts)
683 unsigned char commit_sha1[20];
684 enum replay_action action;
685 char *end_of_object_name;
686 int saved, status, padding;
688 if (starts_with(bol, "pick")) {
689 action = REPLAY_PICK;
690 bol += strlen("pick");
691 } else if (starts_with(bol, "revert")) {
692 action = REPLAY_REVERT;
693 bol += strlen("revert");
694 } else
695 return NULL;
697 /* Eat up extra spaces/ tabs before object name */
698 padding = strspn(bol, " \t");
699 if (!padding)
700 return NULL;
701 bol += padding;
703 end_of_object_name = bol + strcspn(bol, " \t\n");
704 saved = *end_of_object_name;
705 *end_of_object_name = '\0';
706 status = get_sha1(bol, commit_sha1);
707 *end_of_object_name = saved;
710 * Verify that the action matches up with the one in
711 * opts; we don't support arbitrary instructions
713 if (action != opts->action) {
714 const char *action_str;
715 action_str = action == REPLAY_REVERT ? "revert" : "cherry-pick";
716 error(_("Cannot %s during a %s"), action_str, action_name(opts));
717 return NULL;
720 if (status < 0)
721 return NULL;
723 return lookup_commit_reference(commit_sha1);
726 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
727 struct replay_opts *opts)
729 struct commit_list **next = todo_list;
730 struct commit *commit;
731 char *p = buf;
732 int i;
734 for (i = 1; *p; i++) {
735 char *eol = strchrnul(p, '\n');
736 commit = parse_insn_line(p, eol, opts);
737 if (!commit)
738 return error(_("Could not parse line %d."), i);
739 next = commit_list_append(commit, next);
740 p = *eol ? eol + 1 : eol;
742 if (!*todo_list)
743 return error(_("No commits parsed."));
744 return 0;
747 static void read_populate_todo(struct commit_list **todo_list,
748 struct replay_opts *opts)
750 const char *todo_file = git_path(SEQ_TODO_FILE);
751 struct strbuf buf = STRBUF_INIT;
752 int fd, res;
754 fd = open(todo_file, O_RDONLY);
755 if (fd < 0)
756 die_errno(_("Could not open %s"), todo_file);
757 if (strbuf_read(&buf, fd, 0) < 0) {
758 close(fd);
759 strbuf_release(&buf);
760 die(_("Could not read %s."), todo_file);
762 close(fd);
764 res = parse_insn_buffer(buf.buf, todo_list, opts);
765 strbuf_release(&buf);
766 if (res)
767 die(_("Unusable instruction sheet: %s"), todo_file);
770 static int populate_opts_cb(const char *key, const char *value, void *data)
772 struct replay_opts *opts = data;
773 int error_flag = 1;
775 if (!value)
776 error_flag = 0;
777 else if (!strcmp(key, "options.no-commit"))
778 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
779 else if (!strcmp(key, "options.edit"))
780 opts->edit = git_config_bool_or_int(key, value, &error_flag);
781 else if (!strcmp(key, "options.signoff"))
782 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
783 else if (!strcmp(key, "options.record-origin"))
784 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
785 else if (!strcmp(key, "options.allow-ff"))
786 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
787 else if (!strcmp(key, "options.mainline"))
788 opts->mainline = git_config_int(key, value);
789 else if (!strcmp(key, "options.strategy"))
790 git_config_string(&opts->strategy, key, value);
791 else if (!strcmp(key, "options.gpg-sign"))
792 git_config_string(&opts->gpg_sign, key, value);
793 else if (!strcmp(key, "options.strategy-option")) {
794 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
795 opts->xopts[opts->xopts_nr++] = xstrdup(value);
796 } else
797 return error(_("Invalid key: %s"), key);
799 if (!error_flag)
800 return error(_("Invalid value for %s: %s"), key, value);
802 return 0;
805 static void read_populate_opts(struct replay_opts **opts_ptr)
807 const char *opts_file = git_path(SEQ_OPTS_FILE);
809 if (!file_exists(opts_file))
810 return;
811 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
812 die(_("Malformed options sheet: %s"), opts_file);
815 static void walk_revs_populate_todo(struct commit_list **todo_list,
816 struct replay_opts *opts)
818 struct commit *commit;
819 struct commit_list **next;
821 prepare_revs(opts);
823 next = todo_list;
824 while ((commit = get_revision(opts->revs)))
825 next = commit_list_append(commit, next);
828 static int create_seq_dir(void)
830 const char *seq_dir = git_path(SEQ_DIR);
832 if (file_exists(seq_dir)) {
833 error(_("a cherry-pick or revert is already in progress"));
834 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
835 return -1;
837 else if (mkdir(seq_dir, 0777) < 0)
838 die_errno(_("Could not create sequencer directory %s"), seq_dir);
839 return 0;
842 static void save_head(const char *head)
844 const char *head_file = git_path(SEQ_HEAD_FILE);
845 static struct lock_file head_lock;
846 struct strbuf buf = STRBUF_INIT;
847 int fd;
849 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
850 strbuf_addf(&buf, "%s\n", head);
851 if (write_in_full(fd, buf.buf, buf.len) < 0)
852 die_errno(_("Could not write to %s"), head_file);
853 if (commit_lock_file(&head_lock) < 0)
854 die(_("Error wrapping up %s."), head_file);
857 static int reset_for_rollback(const unsigned char *sha1)
859 const char *argv[4]; /* reset --merge <arg> + NULL */
860 argv[0] = "reset";
861 argv[1] = "--merge";
862 argv[2] = sha1_to_hex(sha1);
863 argv[3] = NULL;
864 return run_command_v_opt(argv, RUN_GIT_CMD);
867 static int rollback_single_pick(void)
869 unsigned char head_sha1[20];
871 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
872 !file_exists(git_path("REVERT_HEAD")))
873 return error(_("no cherry-pick or revert in progress"));
874 if (read_ref_full("HEAD", 0, head_sha1, NULL))
875 return error(_("cannot resolve HEAD"));
876 if (is_null_sha1(head_sha1))
877 return error(_("cannot abort from a branch yet to be born"));
878 return reset_for_rollback(head_sha1);
881 static int sequencer_rollback(struct replay_opts *opts)
883 const char *filename;
884 FILE *f;
885 unsigned char sha1[20];
886 struct strbuf buf = STRBUF_INIT;
888 filename = git_path(SEQ_HEAD_FILE);
889 f = fopen(filename, "r");
890 if (!f && errno == ENOENT) {
892 * There is no multiple-cherry-pick in progress.
893 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
894 * a single-cherry-pick in progress, abort that.
896 return rollback_single_pick();
898 if (!f)
899 return error(_("cannot open %s: %s"), filename,
900 strerror(errno));
901 if (strbuf_getline(&buf, f, '\n')) {
902 error(_("cannot read %s: %s"), filename, ferror(f) ?
903 strerror(errno) : _("unexpected end of file"));
904 fclose(f);
905 goto fail;
907 fclose(f);
908 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
909 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
910 filename);
911 goto fail;
913 if (reset_for_rollback(sha1))
914 goto fail;
915 remove_sequencer_state();
916 strbuf_release(&buf);
917 return 0;
918 fail:
919 strbuf_release(&buf);
920 return -1;
923 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
925 const char *todo_file = git_path(SEQ_TODO_FILE);
926 static struct lock_file todo_lock;
927 struct strbuf buf = STRBUF_INIT;
928 int fd;
930 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
931 if (format_todo(&buf, todo_list, opts) < 0)
932 die(_("Could not format %s."), todo_file);
933 if (write_in_full(fd, buf.buf, buf.len) < 0) {
934 strbuf_release(&buf);
935 die_errno(_("Could not write to %s"), todo_file);
937 if (commit_lock_file(&todo_lock) < 0) {
938 strbuf_release(&buf);
939 die(_("Error wrapping up %s."), todo_file);
941 strbuf_release(&buf);
944 static void save_opts(struct replay_opts *opts)
946 const char *opts_file = git_path(SEQ_OPTS_FILE);
948 if (opts->no_commit)
949 git_config_set_in_file(opts_file, "options.no-commit", "true");
950 if (opts->edit)
951 git_config_set_in_file(opts_file, "options.edit", "true");
952 if (opts->signoff)
953 git_config_set_in_file(opts_file, "options.signoff", "true");
954 if (opts->record_origin)
955 git_config_set_in_file(opts_file, "options.record-origin", "true");
956 if (opts->allow_ff)
957 git_config_set_in_file(opts_file, "options.allow-ff", "true");
958 if (opts->mainline) {
959 struct strbuf buf = STRBUF_INIT;
960 strbuf_addf(&buf, "%d", opts->mainline);
961 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
962 strbuf_release(&buf);
964 if (opts->strategy)
965 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
966 if (opts->gpg_sign)
967 git_config_set_in_file(opts_file, "options.gpg-sign", opts->gpg_sign);
968 if (opts->xopts) {
969 int i;
970 for (i = 0; i < opts->xopts_nr; i++)
971 git_config_set_multivar_in_file(opts_file,
972 "options.strategy-option",
973 opts->xopts[i], "^$", 0);
977 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
979 struct commit_list *cur;
980 int res;
982 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
983 if (opts->allow_ff)
984 assert(!(opts->signoff || opts->no_commit ||
985 opts->record_origin || opts->edit));
986 read_and_refresh_cache(opts);
988 for (cur = todo_list; cur; cur = cur->next) {
989 save_todo(cur, opts);
990 res = do_pick_commit(cur->item, opts);
991 if (res)
992 return res;
996 * Sequence of picks finished successfully; cleanup by
997 * removing the .git/sequencer directory
999 remove_sequencer_state();
1000 return 0;
1003 static int continue_single_pick(void)
1005 const char *argv[] = { "commit", NULL };
1007 if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
1008 !file_exists(git_path("REVERT_HEAD")))
1009 return error(_("no cherry-pick or revert in progress"));
1010 return run_command_v_opt(argv, RUN_GIT_CMD);
1013 static int sequencer_continue(struct replay_opts *opts)
1015 struct commit_list *todo_list = NULL;
1017 if (!file_exists(git_path(SEQ_TODO_FILE)))
1018 return continue_single_pick();
1019 read_populate_opts(&opts);
1020 read_populate_todo(&todo_list, opts);
1022 /* Verify that the conflict has been resolved */
1023 if (file_exists(git_path("CHERRY_PICK_HEAD")) ||
1024 file_exists(git_path("REVERT_HEAD"))) {
1025 int ret = continue_single_pick();
1026 if (ret)
1027 return ret;
1029 if (index_differs_from("HEAD", 0))
1030 return error_dirty_index(opts);
1031 todo_list = todo_list->next;
1032 return pick_commits(todo_list, opts);
1035 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1037 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1038 return do_pick_commit(cmit, opts);
1041 int sequencer_pick_revisions(struct replay_opts *opts)
1043 struct commit_list *todo_list = NULL;
1044 unsigned char sha1[20];
1045 int i;
1047 if (opts->subcommand == REPLAY_NONE)
1048 assert(opts->revs);
1050 read_and_refresh_cache(opts);
1053 * Decide what to do depending on the arguments; a fresh
1054 * cherry-pick should be handled differently from an existing
1055 * one that is being continued
1057 if (opts->subcommand == REPLAY_REMOVE_STATE) {
1058 remove_sequencer_state();
1059 return 0;
1061 if (opts->subcommand == REPLAY_ROLLBACK)
1062 return sequencer_rollback(opts);
1063 if (opts->subcommand == REPLAY_CONTINUE)
1064 return sequencer_continue(opts);
1066 for (i = 0; i < opts->revs->pending.nr; i++) {
1067 unsigned char sha1[20];
1068 const char *name = opts->revs->pending.objects[i].name;
1070 /* This happens when using --stdin. */
1071 if (!strlen(name))
1072 continue;
1074 if (!get_sha1(name, sha1)) {
1075 if (!lookup_commit_reference_gently(sha1, 1)) {
1076 enum object_type type = sha1_object_info(sha1, NULL);
1077 die(_("%s: can't cherry-pick a %s"), name, typename(type));
1079 } else
1080 die(_("%s: bad revision"), name);
1084 * If we were called as "git cherry-pick <commit>", just
1085 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1086 * REVERT_HEAD, and don't touch the sequencer state.
1087 * This means it is possible to cherry-pick in the middle
1088 * of a cherry-pick sequence.
1090 if (opts->revs->cmdline.nr == 1 &&
1091 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1092 opts->revs->no_walk &&
1093 !opts->revs->cmdline.rev->flags) {
1094 struct commit *cmit;
1095 if (prepare_revision_walk(opts->revs))
1096 die(_("revision walk setup failed"));
1097 cmit = get_revision(opts->revs);
1098 if (!cmit || get_revision(opts->revs))
1099 die("BUG: expected exactly one commit from walk");
1100 return single_pick(cmit, opts);
1104 * Start a new cherry-pick/ revert sequence; but
1105 * first, make sure that an existing one isn't in
1106 * progress
1109 walk_revs_populate_todo(&todo_list, opts);
1110 if (create_seq_dir() < 0)
1111 return -1;
1112 if (get_sha1("HEAD", sha1)) {
1113 if (opts->action == REPLAY_REVERT)
1114 return error(_("Can't revert as initial commit"));
1115 return error(_("Can't cherry-pick into empty head"));
1117 save_head(sha1_to_hex(sha1));
1118 save_opts(opts);
1119 return pick_commits(todo_list, opts);
1122 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1124 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1125 struct strbuf sob = STRBUF_INIT;
1126 int has_footer;
1128 strbuf_addstr(&sob, sign_off_header);
1129 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1130 getenv("GIT_COMMITTER_EMAIL")));
1131 strbuf_addch(&sob, '\n');
1134 * If the whole message buffer is equal to the sob, pretend that we
1135 * found a conforming footer with a matching sob
1137 if (msgbuf->len - ignore_footer == sob.len &&
1138 !strncmp(msgbuf->buf, sob.buf, sob.len))
1139 has_footer = 3;
1140 else
1141 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1143 if (!has_footer) {
1144 const char *append_newlines = NULL;
1145 size_t len = msgbuf->len - ignore_footer;
1147 if (!len) {
1149 * The buffer is completely empty. Leave foom for
1150 * the title and body to be filled in by the user.
1152 append_newlines = "\n\n";
1153 } else if (msgbuf->buf[len - 1] != '\n') {
1155 * Incomplete line. Complete the line and add a
1156 * blank one so that there is an empty line between
1157 * the message body and the sob.
1159 append_newlines = "\n\n";
1160 } else if (len == 1) {
1162 * Buffer contains a single newline. Add another
1163 * so that we leave room for the title and body.
1165 append_newlines = "\n";
1166 } else if (msgbuf->buf[len - 2] != '\n') {
1168 * Buffer ends with a single newline. Add another
1169 * so that there is an empty line between the message
1170 * body and the sob.
1172 append_newlines = "\n";
1173 } /* else, the buffer already ends with two newlines. */
1175 if (append_newlines)
1176 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1177 append_newlines, strlen(append_newlines));
1180 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1181 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1182 sob.buf, sob.len);
1184 strbuf_release(&sob);