sequencer: remove useless get_dir() function
[git.git] / sequencer.c
blob3ac4cb8d3baa19a7a532d131d6b16af179236062
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"
18 #include "quote.h"
20 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
22 const char sign_off_header[] = "Signed-off-by: ";
23 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
25 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
27 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
28 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
29 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
30 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
33 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
34 * GIT_AUTHOR_DATE that will be used for the commit that is currently
35 * being rebased.
37 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
39 * The following files are written by git-rebase just after parsing the
40 * command-line (and are only consumed, not modified, by the sequencer).
42 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
44 /* We will introduce the 'interactive rebase' mode later */
45 static inline int is_rebase_i(const struct replay_opts *opts)
47 return 0;
50 static const char *get_todo_path(const struct replay_opts *opts)
52 return git_path_todo_file();
55 static int is_rfc2822_line(const char *buf, int len)
57 int i;
59 for (i = 0; i < len; i++) {
60 int ch = buf[i];
61 if (ch == ':')
62 return 1;
63 if (!isalnum(ch) && ch != '-')
64 break;
67 return 0;
70 static int is_cherry_picked_from_line(const char *buf, int len)
73 * We only care that it looks roughly like (cherry picked from ...)
75 return len > strlen(cherry_picked_prefix) + 1 &&
76 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
80 * Returns 0 for non-conforming footer
81 * Returns 1 for conforming footer
82 * Returns 2 when sob exists within conforming footer
83 * Returns 3 when sob exists within conforming footer as last entry
85 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
86 int ignore_footer)
88 char prev;
89 int i, k;
90 int len = sb->len - ignore_footer;
91 const char *buf = sb->buf;
92 int found_sob = 0;
94 /* footer must end with newline */
95 if (!len || buf[len - 1] != '\n')
96 return 0;
98 prev = '\0';
99 for (i = len - 1; i > 0; i--) {
100 char ch = buf[i];
101 if (prev == '\n' && ch == '\n') /* paragraph break */
102 break;
103 prev = ch;
106 /* require at least one blank line */
107 if (prev != '\n' || buf[i] != '\n')
108 return 0;
110 /* advance to start of last paragraph */
111 while (i < len - 1 && buf[i] == '\n')
112 i++;
114 for (; i < len; i = k) {
115 int found_rfc2822;
117 for (k = i; k < len && buf[k] != '\n'; k++)
118 ; /* do nothing */
119 k++;
121 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
122 if (found_rfc2822 && sob &&
123 !strncmp(buf + i, sob->buf, sob->len))
124 found_sob = k;
126 if (!(found_rfc2822 ||
127 is_cherry_picked_from_line(buf + i, k - i - 1)))
128 return 0;
130 if (found_sob == i)
131 return 3;
132 if (found_sob)
133 return 2;
134 return 1;
137 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
139 static struct strbuf buf = STRBUF_INIT;
141 strbuf_reset(&buf);
142 if (opts->gpg_sign)
143 sq_quotef(&buf, "-S%s", opts->gpg_sign);
144 return buf.buf;
147 int sequencer_remove_state(struct replay_opts *opts)
149 struct strbuf dir = STRBUF_INIT;
150 int i;
152 free(opts->gpg_sign);
153 free(opts->strategy);
154 for (i = 0; i < opts->xopts_nr; i++)
155 free(opts->xopts[i]);
156 free(opts->xopts);
158 strbuf_addf(&dir, "%s", git_path_seq_dir());
159 remove_dir_recursively(&dir, 0);
160 strbuf_release(&dir);
162 return 0;
165 static const char *action_name(const struct replay_opts *opts)
167 return opts->action == REPLAY_REVERT ? N_("revert") : N_("cherry-pick");
170 struct commit_message {
171 char *parent_label;
172 char *label;
173 char *subject;
174 const char *message;
177 static const char *short_commit_name(struct commit *commit)
179 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
182 static int get_message(struct commit *commit, struct commit_message *out)
184 const char *abbrev, *subject;
185 int subject_len;
187 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
188 abbrev = short_commit_name(commit);
190 subject_len = find_commit_subject(out->message, &subject);
192 out->subject = xmemdupz(subject, subject_len);
193 out->label = xstrfmt("%s... %s", abbrev, out->subject);
194 out->parent_label = xstrfmt("parent of %s", out->label);
196 return 0;
199 static void free_message(struct commit *commit, struct commit_message *msg)
201 free(msg->parent_label);
202 free(msg->label);
203 free(msg->subject);
204 unuse_commit_buffer(commit, msg->message);
207 static void print_advice(int show_hint, struct replay_opts *opts)
209 char *msg = getenv("GIT_CHERRY_PICK_HELP");
211 if (msg) {
212 fprintf(stderr, "%s\n", msg);
214 * A conflict has occurred but the porcelain
215 * (typically rebase --interactive) wants to take care
216 * of the commit itself so remove CHERRY_PICK_HEAD
218 unlink(git_path_cherry_pick_head());
219 return;
222 if (show_hint) {
223 if (opts->no_commit)
224 advise(_("after resolving the conflicts, mark the corrected paths\n"
225 "with 'git add <paths>' or 'git rm <paths>'"));
226 else
227 advise(_("after resolving the conflicts, mark the corrected paths\n"
228 "with 'git add <paths>' or 'git rm <paths>'\n"
229 "and commit the result with 'git commit'"));
233 static int write_message(const void *buf, size_t len, const char *filename,
234 int append_eol)
236 static struct lock_file msg_file;
238 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
239 if (msg_fd < 0)
240 return error_errno(_("could not lock '%s'"), filename);
241 if (write_in_full(msg_fd, buf, len) < 0) {
242 rollback_lock_file(&msg_file);
243 return error_errno(_("could not write to '%s'"), filename);
245 if (append_eol && write(msg_fd, "\n", 1) < 0) {
246 rollback_lock_file(&msg_file);
247 return error_errno(_("could not write eol to '%s'"), filename);
249 if (commit_lock_file(&msg_file) < 0) {
250 rollback_lock_file(&msg_file);
251 return error(_("failed to finalize '%s'."), filename);
254 return 0;
258 * Reads a file that was presumably written by a shell script, i.e. with an
259 * end-of-line marker that needs to be stripped.
261 * Note that only the last end-of-line marker is stripped, consistent with the
262 * behavior of "$(cat path)" in a shell script.
264 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
266 static int read_oneliner(struct strbuf *buf,
267 const char *path, int skip_if_empty)
269 int orig_len = buf->len;
271 if (!file_exists(path))
272 return 0;
274 if (strbuf_read_file(buf, path, 0) < 0) {
275 warning_errno(_("could not read '%s'"), path);
276 return 0;
279 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
280 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
281 --buf->len;
282 buf->buf[buf->len] = '\0';
285 if (skip_if_empty && buf->len == orig_len)
286 return 0;
288 return 1;
291 static struct tree *empty_tree(void)
293 return lookup_tree(EMPTY_TREE_SHA1_BIN);
296 static int error_dirty_index(struct replay_opts *opts)
298 if (read_cache_unmerged())
299 return error_resolve_conflict(_(action_name(opts)));
301 error(_("your local changes would be overwritten by %s."),
302 _(action_name(opts)));
304 if (advice_commit_before_merge)
305 advise(_("commit your changes or stash them to proceed."));
306 return -1;
309 static void update_abort_safety_file(void)
311 struct object_id head;
313 /* Do nothing on a single-pick */
314 if (!file_exists(git_path_seq_dir()))
315 return;
317 if (!get_oid("HEAD", &head))
318 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
319 else
320 write_file(git_path_abort_safety_file(), "%s", "");
323 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
324 int unborn, struct replay_opts *opts)
326 struct ref_transaction *transaction;
327 struct strbuf sb = STRBUF_INIT;
328 struct strbuf err = STRBUF_INIT;
330 read_cache();
331 if (checkout_fast_forward(from, to, 1))
332 return -1; /* the callee should have complained already */
334 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
336 transaction = ref_transaction_begin(&err);
337 if (!transaction ||
338 ref_transaction_update(transaction, "HEAD",
339 to, unborn ? null_sha1 : from,
340 0, sb.buf, &err) ||
341 ref_transaction_commit(transaction, &err)) {
342 ref_transaction_free(transaction);
343 error("%s", err.buf);
344 strbuf_release(&sb);
345 strbuf_release(&err);
346 return -1;
349 strbuf_release(&sb);
350 strbuf_release(&err);
351 ref_transaction_free(transaction);
352 update_abort_safety_file();
353 return 0;
356 void append_conflicts_hint(struct strbuf *msgbuf)
358 int i;
360 strbuf_addch(msgbuf, '\n');
361 strbuf_commented_addf(msgbuf, "Conflicts:\n");
362 for (i = 0; i < active_nr;) {
363 const struct cache_entry *ce = active_cache[i++];
364 if (ce_stage(ce)) {
365 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
366 while (i < active_nr && !strcmp(ce->name,
367 active_cache[i]->name))
368 i++;
373 static int do_recursive_merge(struct commit *base, struct commit *next,
374 const char *base_label, const char *next_label,
375 unsigned char *head, struct strbuf *msgbuf,
376 struct replay_opts *opts)
378 struct merge_options o;
379 struct tree *result, *next_tree, *base_tree, *head_tree;
380 int clean;
381 char **xopt;
382 static struct lock_file index_lock;
384 hold_locked_index(&index_lock, 1);
386 read_cache();
388 init_merge_options(&o);
389 o.ancestor = base ? base_label : "(empty tree)";
390 o.branch1 = "HEAD";
391 o.branch2 = next ? next_label : "(empty tree)";
393 head_tree = parse_tree_indirect(head);
394 next_tree = next ? next->tree : empty_tree();
395 base_tree = base ? base->tree : empty_tree();
397 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
398 parse_merge_opt(&o, *xopt);
400 clean = merge_trees(&o,
401 head_tree,
402 next_tree, base_tree, &result);
403 strbuf_release(&o.obuf);
404 if (clean < 0)
405 return clean;
407 if (active_cache_changed &&
408 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
409 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
410 return error(_("%s: Unable to write new index file"),
411 _(action_name(opts)));
412 rollback_lock_file(&index_lock);
414 if (opts->signoff)
415 append_signoff(msgbuf, 0, 0);
417 if (!clean)
418 append_conflicts_hint(msgbuf);
420 return !clean;
423 static int is_index_unchanged(void)
425 unsigned char head_sha1[20];
426 struct commit *head_commit;
428 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
429 return error(_("could not resolve HEAD commit\n"));
431 head_commit = lookup_commit(head_sha1);
434 * If head_commit is NULL, check_commit, called from
435 * lookup_commit, would have indicated that head_commit is not
436 * a commit object already. parse_commit() will return failure
437 * without further complaints in such a case. Otherwise, if
438 * the commit is invalid, parse_commit() will complain. So
439 * there is nothing for us to say here. Just return failure.
441 if (parse_commit(head_commit))
442 return -1;
444 if (!active_cache_tree)
445 active_cache_tree = cache_tree();
447 if (!cache_tree_fully_valid(active_cache_tree))
448 if (cache_tree_update(&the_index, 0))
449 return error(_("unable to update cache tree\n"));
451 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
455 * Read the author-script file into an environment block, ready for use in
456 * run_command(), that can be free()d afterwards.
458 static char **read_author_script(void)
460 struct strbuf script = STRBUF_INIT;
461 int i, count = 0;
462 char *p, *p2, **env;
463 size_t env_size;
465 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
466 return NULL;
468 for (p = script.buf; *p; p++)
469 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
470 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
471 else if (*p == '\'')
472 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
473 else if (*p == '\n') {
474 *p = '\0';
475 count++;
478 env_size = (count + 1) * sizeof(*env);
479 strbuf_grow(&script, env_size);
480 memmove(script.buf + env_size, script.buf, script.len);
481 p = script.buf + env_size;
482 env = (char **)strbuf_detach(&script, NULL);
484 for (i = 0; i < count; i++) {
485 env[i] = p;
486 p += strlen(p) + 1;
488 env[count] = NULL;
490 return env;
493 static const char staged_changes_advice[] =
494 N_("you have staged changes in your working tree\n"
495 "If these changes are meant to be squashed into the previous commit, run:\n"
496 "\n"
497 " git commit --amend %s\n"
498 "\n"
499 "If they are meant to go into a new commit, run:\n"
500 "\n"
501 " git commit %s\n"
502 "\n"
503 "In both cases, once you're done, continue with:\n"
504 "\n"
505 " git rebase --continue\n");
508 * If we are cherry-pick, and if the merge did not result in
509 * hand-editing, we will hit this commit and inherit the original
510 * author date and name.
512 * If we are revert, or if our cherry-pick results in a hand merge,
513 * we had better say that the current user is responsible for that.
515 * An exception is when run_git_commit() is called during an
516 * interactive rebase: in that case, we will want to retain the
517 * author metadata.
519 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
520 int allow_empty, int edit, int amend,
521 int cleanup_commit_message)
523 char **env = NULL;
524 struct argv_array array;
525 int rc;
526 const char *value;
528 if (is_rebase_i(opts)) {
529 env = read_author_script();
530 if (!env) {
531 const char *gpg_opt = gpg_sign_opt_quoted(opts);
533 return error(_(staged_changes_advice),
534 gpg_opt, gpg_opt);
538 argv_array_init(&array);
539 argv_array_push(&array, "commit");
540 argv_array_push(&array, "-n");
542 if (amend)
543 argv_array_push(&array, "--amend");
544 if (opts->gpg_sign)
545 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
546 if (opts->signoff)
547 argv_array_push(&array, "-s");
548 if (defmsg)
549 argv_array_pushl(&array, "-F", defmsg, NULL);
550 if (cleanup_commit_message)
551 argv_array_push(&array, "--cleanup=strip");
552 if (edit)
553 argv_array_push(&array, "-e");
554 else if (!cleanup_commit_message &&
555 !opts->signoff && !opts->record_origin &&
556 git_config_get_value("commit.cleanup", &value))
557 argv_array_push(&array, "--cleanup=verbatim");
559 if (allow_empty)
560 argv_array_push(&array, "--allow-empty");
562 if (opts->allow_empty_message)
563 argv_array_push(&array, "--allow-empty-message");
565 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
566 (const char *const *)env);
567 argv_array_clear(&array);
568 free(env);
570 return rc;
573 static int is_original_commit_empty(struct commit *commit)
575 const unsigned char *ptree_sha1;
577 if (parse_commit(commit))
578 return error(_("could not parse commit %s\n"),
579 oid_to_hex(&commit->object.oid));
580 if (commit->parents) {
581 struct commit *parent = commit->parents->item;
582 if (parse_commit(parent))
583 return error(_("could not parse parent commit %s\n"),
584 oid_to_hex(&parent->object.oid));
585 ptree_sha1 = parent->tree->object.oid.hash;
586 } else {
587 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
590 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
594 * Do we run "git commit" with "--allow-empty"?
596 static int allow_empty(struct replay_opts *opts, struct commit *commit)
598 int index_unchanged, empty_commit;
601 * Three cases:
603 * (1) we do not allow empty at all and error out.
605 * (2) we allow ones that were initially empty, but
606 * forbid the ones that become empty;
608 * (3) we allow both.
610 if (!opts->allow_empty)
611 return 0; /* let "git commit" barf as necessary */
613 index_unchanged = is_index_unchanged();
614 if (index_unchanged < 0)
615 return index_unchanged;
616 if (!index_unchanged)
617 return 0; /* we do not have to say --allow-empty */
619 if (opts->keep_redundant_commits)
620 return 1;
622 empty_commit = is_original_commit_empty(commit);
623 if (empty_commit < 0)
624 return empty_commit;
625 if (!empty_commit)
626 return 0;
627 else
628 return 1;
631 enum todo_command {
632 TODO_PICK = 0,
633 TODO_REVERT
636 static const char *todo_command_strings[] = {
637 "pick",
638 "revert"
641 static const char *command_to_string(const enum todo_command command)
643 if ((size_t)command < ARRAY_SIZE(todo_command_strings))
644 return todo_command_strings[command];
645 die("Unknown command: %d", command);
649 static int do_pick_commit(enum todo_command command, struct commit *commit,
650 struct replay_opts *opts)
652 unsigned char head[20];
653 struct commit *base, *next, *parent;
654 const char *base_label, *next_label;
655 struct commit_message msg = { NULL, NULL, NULL, NULL };
656 struct strbuf msgbuf = STRBUF_INIT;
657 int res, unborn = 0, allow;
659 if (opts->no_commit) {
661 * We do not intend to commit immediately. We just want to
662 * merge the differences in, so let's compute the tree
663 * that represents the "current" state for merge-recursive
664 * to work on.
666 if (write_cache_as_tree(head, 0, NULL))
667 return error(_("your index file is unmerged."));
668 } else {
669 unborn = get_sha1("HEAD", head);
670 if (unborn)
671 hashcpy(head, EMPTY_TREE_SHA1_BIN);
672 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
673 return error_dirty_index(opts);
675 discard_cache();
677 if (!commit->parents) {
678 parent = NULL;
680 else if (commit->parents->next) {
681 /* Reverting or cherry-picking a merge commit */
682 int cnt;
683 struct commit_list *p;
685 if (!opts->mainline)
686 return error(_("commit %s is a merge but no -m option was given."),
687 oid_to_hex(&commit->object.oid));
689 for (cnt = 1, p = commit->parents;
690 cnt != opts->mainline && p;
691 cnt++)
692 p = p->next;
693 if (cnt != opts->mainline || !p)
694 return error(_("commit %s does not have parent %d"),
695 oid_to_hex(&commit->object.oid), opts->mainline);
696 parent = p->item;
697 } else if (0 < opts->mainline)
698 return error(_("mainline was specified but commit %s is not a merge."),
699 oid_to_hex(&commit->object.oid));
700 else
701 parent = commit->parents->item;
703 if (opts->allow_ff &&
704 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
705 (!parent && unborn)))
706 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
708 if (parent && parse_commit(parent) < 0)
709 /* TRANSLATORS: The first %s will be a "todo" command like
710 "revert" or "pick", the second %s a SHA1. */
711 return error(_("%s: cannot parse parent commit %s"),
712 command_to_string(command),
713 oid_to_hex(&parent->object.oid));
715 if (get_message(commit, &msg) != 0)
716 return error(_("cannot get commit message for %s"),
717 oid_to_hex(&commit->object.oid));
720 * "commit" is an existing commit. We would want to apply
721 * the difference it introduces since its first parent "prev"
722 * on top of the current HEAD if we are cherry-pick. Or the
723 * reverse of it if we are revert.
726 if (command == TODO_REVERT) {
727 base = commit;
728 base_label = msg.label;
729 next = parent;
730 next_label = msg.parent_label;
731 strbuf_addstr(&msgbuf, "Revert \"");
732 strbuf_addstr(&msgbuf, msg.subject);
733 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
734 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
736 if (commit->parents && commit->parents->next) {
737 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
738 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
740 strbuf_addstr(&msgbuf, ".\n");
741 } else {
742 const char *p;
744 base = parent;
745 base_label = msg.parent_label;
746 next = commit;
747 next_label = msg.label;
750 * Append the commit log message to msgbuf; it starts
751 * after the tree, parent, author, committer
752 * information followed by "\n\n".
754 p = strstr(msg.message, "\n\n");
755 if (p)
756 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
758 if (opts->record_origin) {
759 if (!has_conforming_footer(&msgbuf, NULL, 0))
760 strbuf_addch(&msgbuf, '\n');
761 strbuf_addstr(&msgbuf, cherry_picked_prefix);
762 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
763 strbuf_addstr(&msgbuf, ")\n");
767 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
768 res = do_recursive_merge(base, next, base_label, next_label,
769 head, &msgbuf, opts);
770 if (res < 0)
771 return res;
772 res |= write_message(msgbuf.buf, msgbuf.len,
773 git_path_merge_msg(), 0);
774 } else {
775 struct commit_list *common = NULL;
776 struct commit_list *remotes = NULL;
778 res = write_message(msgbuf.buf, msgbuf.len,
779 git_path_merge_msg(), 0);
781 commit_list_insert(base, &common);
782 commit_list_insert(next, &remotes);
783 res |= try_merge_command(opts->strategy,
784 opts->xopts_nr, (const char **)opts->xopts,
785 common, sha1_to_hex(head), remotes);
786 free_commit_list(common);
787 free_commit_list(remotes);
789 strbuf_release(&msgbuf);
792 * If the merge was clean or if it failed due to conflict, we write
793 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
794 * However, if the merge did not even start, then we don't want to
795 * write it at all.
797 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
798 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
799 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
800 res = -1;
801 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
802 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
803 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
804 res = -1;
806 if (res) {
807 error(command == TODO_REVERT
808 ? _("could not revert %s... %s")
809 : _("could not apply %s... %s"),
810 short_commit_name(commit), msg.subject);
811 print_advice(res == 1, opts);
812 rerere(opts->allow_rerere_auto);
813 goto leave;
816 allow = allow_empty(opts, commit);
817 if (allow < 0) {
818 res = allow;
819 goto leave;
821 if (!opts->no_commit)
822 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
823 opts, allow, opts->edit, 0, 0);
825 leave:
826 free_message(commit, &msg);
827 update_abort_safety_file();
829 return res;
832 static int prepare_revs(struct replay_opts *opts)
835 * picking (but not reverting) ranges (but not individual revisions)
836 * should be done in reverse
838 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
839 opts->revs->reverse ^= 1;
841 if (prepare_revision_walk(opts->revs))
842 return error(_("revision walk setup failed"));
844 if (!opts->revs->commits)
845 return error(_("empty commit set passed"));
846 return 0;
849 static int read_and_refresh_cache(struct replay_opts *opts)
851 static struct lock_file index_lock;
852 int index_fd = hold_locked_index(&index_lock, 0);
853 if (read_index_preload(&the_index, NULL) < 0) {
854 rollback_lock_file(&index_lock);
855 return error(_("git %s: failed to read the index"),
856 _(action_name(opts)));
858 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
859 if (the_index.cache_changed && index_fd >= 0) {
860 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
861 rollback_lock_file(&index_lock);
862 return error(_("git %s: failed to refresh the index"),
863 _(action_name(opts)));
866 rollback_lock_file(&index_lock);
867 return 0;
870 struct todo_item {
871 enum todo_command command;
872 struct commit *commit;
873 const char *arg;
874 int arg_len;
875 size_t offset_in_buf;
878 struct todo_list {
879 struct strbuf buf;
880 struct todo_item *items;
881 int nr, alloc, current;
884 #define TODO_LIST_INIT { STRBUF_INIT }
886 static void todo_list_release(struct todo_list *todo_list)
888 strbuf_release(&todo_list->buf);
889 free(todo_list->items);
890 todo_list->items = NULL;
891 todo_list->nr = todo_list->alloc = 0;
894 static struct todo_item *append_new_todo(struct todo_list *todo_list)
896 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
897 return todo_list->items + todo_list->nr++;
900 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
902 unsigned char commit_sha1[20];
903 char *end_of_object_name;
904 int i, saved, status, padding;
906 /* left-trim */
907 bol += strspn(bol, " \t");
909 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
910 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
911 item->command = i;
912 break;
914 if (i >= ARRAY_SIZE(todo_command_strings))
915 return -1;
917 /* Eat up extra spaces/ tabs before object name */
918 padding = strspn(bol, " \t");
919 if (!padding)
920 return -1;
921 bol += padding;
923 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
924 saved = *end_of_object_name;
925 *end_of_object_name = '\0';
926 status = get_sha1(bol, commit_sha1);
927 *end_of_object_name = saved;
929 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
930 item->arg_len = (int)(eol - item->arg);
932 if (status < 0)
933 return -1;
935 item->commit = lookup_commit_reference(commit_sha1);
936 return !item->commit;
939 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
941 struct todo_item *item;
942 char *p = buf, *next_p;
943 int i, res = 0;
945 for (i = 1; *p; i++, p = next_p) {
946 char *eol = strchrnul(p, '\n');
948 next_p = *eol ? eol + 1 /* skip LF */ : eol;
950 if (p != eol && eol[-1] == '\r')
951 eol--; /* strip Carriage Return */
953 item = append_new_todo(todo_list);
954 item->offset_in_buf = p - todo_list->buf.buf;
955 if (parse_insn_line(item, p, eol)) {
956 res = error(_("invalid line %d: %.*s"),
957 i, (int)(eol - p), p);
958 item->command = -1;
961 if (!todo_list->nr)
962 return error(_("no commits parsed."));
963 return res;
966 static int read_populate_todo(struct todo_list *todo_list,
967 struct replay_opts *opts)
969 const char *todo_file = get_todo_path(opts);
970 int fd, res;
972 strbuf_reset(&todo_list->buf);
973 fd = open(todo_file, O_RDONLY);
974 if (fd < 0)
975 return error_errno(_("could not open '%s'"), todo_file);
976 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
977 close(fd);
978 return error(_("could not read '%s'."), todo_file);
980 close(fd);
982 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
983 if (res)
984 return error(_("unusable instruction sheet: '%s'"), todo_file);
986 if (!is_rebase_i(opts)) {
987 enum todo_command valid =
988 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
989 int i;
991 for (i = 0; i < todo_list->nr; i++)
992 if (valid == todo_list->items[i].command)
993 continue;
994 else if (valid == TODO_PICK)
995 return error(_("cannot cherry-pick during a revert."));
996 else
997 return error(_("cannot revert during a cherry-pick."));
1000 return 0;
1003 static int git_config_string_dup(char **dest,
1004 const char *var, const char *value)
1006 if (!value)
1007 return config_error_nonbool(var);
1008 free(*dest);
1009 *dest = xstrdup(value);
1010 return 0;
1013 static int populate_opts_cb(const char *key, const char *value, void *data)
1015 struct replay_opts *opts = data;
1016 int error_flag = 1;
1018 if (!value)
1019 error_flag = 0;
1020 else if (!strcmp(key, "options.no-commit"))
1021 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1022 else if (!strcmp(key, "options.edit"))
1023 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1024 else if (!strcmp(key, "options.signoff"))
1025 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1026 else if (!strcmp(key, "options.record-origin"))
1027 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1028 else if (!strcmp(key, "options.allow-ff"))
1029 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1030 else if (!strcmp(key, "options.mainline"))
1031 opts->mainline = git_config_int(key, value);
1032 else if (!strcmp(key, "options.strategy"))
1033 git_config_string_dup(&opts->strategy, key, value);
1034 else if (!strcmp(key, "options.gpg-sign"))
1035 git_config_string_dup(&opts->gpg_sign, key, value);
1036 else if (!strcmp(key, "options.strategy-option")) {
1037 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1038 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1039 } else
1040 return error(_("invalid key: %s"), key);
1042 if (!error_flag)
1043 return error(_("invalid value for %s: %s"), key, value);
1045 return 0;
1048 static int read_populate_opts(struct replay_opts *opts)
1050 if (is_rebase_i(opts)) {
1051 struct strbuf buf = STRBUF_INIT;
1053 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1054 if (!starts_with(buf.buf, "-S"))
1055 strbuf_reset(&buf);
1056 else {
1057 free(opts->gpg_sign);
1058 opts->gpg_sign = xstrdup(buf.buf + 2);
1061 strbuf_release(&buf);
1063 return 0;
1066 if (!file_exists(git_path_opts_file()))
1067 return 0;
1069 * The function git_parse_source(), called from git_config_from_file(),
1070 * may die() in case of a syntactically incorrect file. We do not care
1071 * about this case, though, because we wrote that file ourselves, so we
1072 * are pretty certain that it is syntactically correct.
1074 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1075 return error(_("malformed options sheet: '%s'"),
1076 git_path_opts_file());
1077 return 0;
1080 static int walk_revs_populate_todo(struct todo_list *todo_list,
1081 struct replay_opts *opts)
1083 enum todo_command command = opts->action == REPLAY_PICK ?
1084 TODO_PICK : TODO_REVERT;
1085 const char *command_string = todo_command_strings[command];
1086 struct commit *commit;
1088 if (prepare_revs(opts))
1089 return -1;
1091 while ((commit = get_revision(opts->revs))) {
1092 struct todo_item *item = append_new_todo(todo_list);
1093 const char *commit_buffer = get_commit_buffer(commit, NULL);
1094 const char *subject;
1095 int subject_len;
1097 item->command = command;
1098 item->commit = commit;
1099 item->arg = NULL;
1100 item->arg_len = 0;
1101 item->offset_in_buf = todo_list->buf.len;
1102 subject_len = find_commit_subject(commit_buffer, &subject);
1103 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1104 short_commit_name(commit), subject_len, subject);
1105 unuse_commit_buffer(commit, commit_buffer);
1107 return 0;
1110 static int create_seq_dir(void)
1112 if (file_exists(git_path_seq_dir())) {
1113 error(_("a cherry-pick or revert is already in progress"));
1114 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1115 return -1;
1117 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1118 return error_errno(_("could not create sequencer directory '%s'"),
1119 git_path_seq_dir());
1120 return 0;
1123 static int save_head(const char *head)
1125 static struct lock_file head_lock;
1126 struct strbuf buf = STRBUF_INIT;
1127 int fd;
1129 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1130 if (fd < 0) {
1131 rollback_lock_file(&head_lock);
1132 return error_errno(_("could not lock HEAD"));
1134 strbuf_addf(&buf, "%s\n", head);
1135 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1136 rollback_lock_file(&head_lock);
1137 return error_errno(_("could not write to '%s'"),
1138 git_path_head_file());
1140 if (commit_lock_file(&head_lock) < 0) {
1141 rollback_lock_file(&head_lock);
1142 return error(_("failed to finalize '%s'."), git_path_head_file());
1144 return 0;
1147 static int rollback_is_safe(void)
1149 struct strbuf sb = STRBUF_INIT;
1150 struct object_id expected_head, actual_head;
1152 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1153 strbuf_trim(&sb);
1154 if (get_oid_hex(sb.buf, &expected_head)) {
1155 strbuf_release(&sb);
1156 die(_("could not parse %s"), git_path_abort_safety_file());
1158 strbuf_release(&sb);
1160 else if (errno == ENOENT)
1161 oidclr(&expected_head);
1162 else
1163 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1165 if (get_oid("HEAD", &actual_head))
1166 oidclr(&actual_head);
1168 return !oidcmp(&actual_head, &expected_head);
1171 static int reset_for_rollback(const unsigned char *sha1)
1173 const char *argv[4]; /* reset --merge <arg> + NULL */
1175 argv[0] = "reset";
1176 argv[1] = "--merge";
1177 argv[2] = sha1_to_hex(sha1);
1178 argv[3] = NULL;
1179 return run_command_v_opt(argv, RUN_GIT_CMD);
1182 static int rollback_single_pick(void)
1184 unsigned char head_sha1[20];
1186 if (!file_exists(git_path_cherry_pick_head()) &&
1187 !file_exists(git_path_revert_head()))
1188 return error(_("no cherry-pick or revert in progress"));
1189 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1190 return error(_("cannot resolve HEAD"));
1191 if (is_null_sha1(head_sha1))
1192 return error(_("cannot abort from a branch yet to be born"));
1193 return reset_for_rollback(head_sha1);
1196 int sequencer_rollback(struct replay_opts *opts)
1198 FILE *f;
1199 unsigned char sha1[20];
1200 struct strbuf buf = STRBUF_INIT;
1202 f = fopen(git_path_head_file(), "r");
1203 if (!f && errno == ENOENT) {
1205 * There is no multiple-cherry-pick in progress.
1206 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1207 * a single-cherry-pick in progress, abort that.
1209 return rollback_single_pick();
1211 if (!f)
1212 return error_errno(_("cannot open '%s'"), git_path_head_file());
1213 if (strbuf_getline_lf(&buf, f)) {
1214 error(_("cannot read '%s': %s"), git_path_head_file(),
1215 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1216 fclose(f);
1217 goto fail;
1219 fclose(f);
1220 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1221 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1222 git_path_head_file());
1223 goto fail;
1225 if (is_null_sha1(sha1)) {
1226 error(_("cannot abort from a branch yet to be born"));
1227 goto fail;
1230 if (!rollback_is_safe()) {
1231 /* Do not error, just do not rollback */
1232 warning(_("You seem to have moved HEAD. "
1233 "Not rewinding, check your HEAD!"));
1234 } else
1235 if (reset_for_rollback(sha1))
1236 goto fail;
1237 strbuf_release(&buf);
1238 return sequencer_remove_state(opts);
1239 fail:
1240 strbuf_release(&buf);
1241 return -1;
1244 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1246 static struct lock_file todo_lock;
1247 const char *todo_path = get_todo_path(opts);
1248 int next = todo_list->current, offset, fd;
1250 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1251 if (fd < 0)
1252 return error_errno(_("could not lock '%s'"), todo_path);
1253 offset = next < todo_list->nr ?
1254 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1255 if (write_in_full(fd, todo_list->buf.buf + offset,
1256 todo_list->buf.len - offset) < 0)
1257 return error_errno(_("could not write to '%s'"), todo_path);
1258 if (commit_lock_file(&todo_lock) < 0)
1259 return error(_("failed to finalize '%s'."), todo_path);
1260 return 0;
1263 static int save_opts(struct replay_opts *opts)
1265 const char *opts_file = git_path_opts_file();
1266 int res = 0;
1268 if (opts->no_commit)
1269 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1270 if (opts->edit)
1271 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1272 if (opts->signoff)
1273 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1274 if (opts->record_origin)
1275 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1276 if (opts->allow_ff)
1277 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1278 if (opts->mainline) {
1279 struct strbuf buf = STRBUF_INIT;
1280 strbuf_addf(&buf, "%d", opts->mainline);
1281 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1282 strbuf_release(&buf);
1284 if (opts->strategy)
1285 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1286 if (opts->gpg_sign)
1287 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1288 if (opts->xopts) {
1289 int i;
1290 for (i = 0; i < opts->xopts_nr; i++)
1291 res |= git_config_set_multivar_in_file_gently(opts_file,
1292 "options.strategy-option",
1293 opts->xopts[i], "^$", 0);
1295 return res;
1298 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1300 int res;
1302 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1303 if (opts->allow_ff)
1304 assert(!(opts->signoff || opts->no_commit ||
1305 opts->record_origin || opts->edit));
1306 if (read_and_refresh_cache(opts))
1307 return -1;
1309 while (todo_list->current < todo_list->nr) {
1310 struct todo_item *item = todo_list->items + todo_list->current;
1311 if (save_todo(todo_list, opts))
1312 return -1;
1313 res = do_pick_commit(item->command, item->commit, opts);
1314 todo_list->current++;
1315 if (res)
1316 return res;
1320 * Sequence of picks finished successfully; cleanup by
1321 * removing the .git/sequencer directory
1323 return sequencer_remove_state(opts);
1326 static int continue_single_pick(void)
1328 const char *argv[] = { "commit", NULL };
1330 if (!file_exists(git_path_cherry_pick_head()) &&
1331 !file_exists(git_path_revert_head()))
1332 return error(_("no cherry-pick or revert in progress"));
1333 return run_command_v_opt(argv, RUN_GIT_CMD);
1336 int sequencer_continue(struct replay_opts *opts)
1338 struct todo_list todo_list = TODO_LIST_INIT;
1339 int res;
1341 if (read_and_refresh_cache(opts))
1342 return -1;
1344 if (!file_exists(get_todo_path(opts)))
1345 return continue_single_pick();
1346 if (read_populate_opts(opts))
1347 return -1;
1348 if ((res = read_populate_todo(&todo_list, opts)))
1349 goto release_todo_list;
1351 /* Verify that the conflict has been resolved */
1352 if (file_exists(git_path_cherry_pick_head()) ||
1353 file_exists(git_path_revert_head())) {
1354 res = continue_single_pick();
1355 if (res)
1356 goto release_todo_list;
1358 if (index_differs_from("HEAD", 0, 0)) {
1359 res = error_dirty_index(opts);
1360 goto release_todo_list;
1362 todo_list.current++;
1363 res = pick_commits(&todo_list, opts);
1364 release_todo_list:
1365 todo_list_release(&todo_list);
1366 return res;
1369 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1371 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1372 return do_pick_commit(opts->action == REPLAY_PICK ?
1373 TODO_PICK : TODO_REVERT, cmit, opts);
1376 int sequencer_pick_revisions(struct replay_opts *opts)
1378 struct todo_list todo_list = TODO_LIST_INIT;
1379 unsigned char sha1[20];
1380 int i, res;
1382 assert(opts->revs);
1383 if (read_and_refresh_cache(opts))
1384 return -1;
1386 for (i = 0; i < opts->revs->pending.nr; i++) {
1387 unsigned char sha1[20];
1388 const char *name = opts->revs->pending.objects[i].name;
1390 /* This happens when using --stdin. */
1391 if (!strlen(name))
1392 continue;
1394 if (!get_sha1(name, sha1)) {
1395 if (!lookup_commit_reference_gently(sha1, 1)) {
1396 enum object_type type = sha1_object_info(sha1, NULL);
1397 return error(_("%s: can't cherry-pick a %s"),
1398 name, typename(type));
1400 } else
1401 return error(_("%s: bad revision"), name);
1405 * If we were called as "git cherry-pick <commit>", just
1406 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1407 * REVERT_HEAD, and don't touch the sequencer state.
1408 * This means it is possible to cherry-pick in the middle
1409 * of a cherry-pick sequence.
1411 if (opts->revs->cmdline.nr == 1 &&
1412 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1413 opts->revs->no_walk &&
1414 !opts->revs->cmdline.rev->flags) {
1415 struct commit *cmit;
1416 if (prepare_revision_walk(opts->revs))
1417 return error(_("revision walk setup failed"));
1418 cmit = get_revision(opts->revs);
1419 if (!cmit || get_revision(opts->revs))
1420 return error("BUG: expected exactly one commit from walk");
1421 return single_pick(cmit, opts);
1425 * Start a new cherry-pick/ revert sequence; but
1426 * first, make sure that an existing one isn't in
1427 * progress
1430 if (walk_revs_populate_todo(&todo_list, opts) ||
1431 create_seq_dir() < 0)
1432 return -1;
1433 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1434 return error(_("can't revert as initial commit"));
1435 if (save_head(sha1_to_hex(sha1)))
1436 return -1;
1437 if (save_opts(opts))
1438 return -1;
1439 update_abort_safety_file();
1440 res = pick_commits(&todo_list, opts);
1441 todo_list_release(&todo_list);
1442 return res;
1445 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1447 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1448 struct strbuf sob = STRBUF_INIT;
1449 int has_footer;
1451 strbuf_addstr(&sob, sign_off_header);
1452 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1453 getenv("GIT_COMMITTER_EMAIL")));
1454 strbuf_addch(&sob, '\n');
1457 * If the whole message buffer is equal to the sob, pretend that we
1458 * found a conforming footer with a matching sob
1460 if (msgbuf->len - ignore_footer == sob.len &&
1461 !strncmp(msgbuf->buf, sob.buf, sob.len))
1462 has_footer = 3;
1463 else
1464 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1466 if (!has_footer) {
1467 const char *append_newlines = NULL;
1468 size_t len = msgbuf->len - ignore_footer;
1470 if (!len) {
1472 * The buffer is completely empty. Leave foom for
1473 * the title and body to be filled in by the user.
1475 append_newlines = "\n\n";
1476 } else if (msgbuf->buf[len - 1] != '\n') {
1478 * Incomplete line. Complete the line and add a
1479 * blank one so that there is an empty line between
1480 * the message body and the sob.
1482 append_newlines = "\n\n";
1483 } else if (len == 1) {
1485 * Buffer contains a single newline. Add another
1486 * so that we leave room for the title and body.
1488 append_newlines = "\n";
1489 } else if (msgbuf->buf[len - 2] != '\n') {
1491 * Buffer ends with a single newline. Add another
1492 * so that there is an empty line between the message
1493 * body and the sob.
1495 append_newlines = "\n";
1496 } /* else, the buffer already ends with two newlines. */
1498 if (append_newlines)
1499 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1500 append_newlines, strlen(append_newlines));
1503 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1504 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1505 sob.buf, sob.len);
1507 strbuf_release(&sob);