sequencer: allow editing the commit message on a case-by-case basis
[git/raj.git] / sequencer.c
blobc0a0aa0ed62b164f615da7b024bdb1610b3b7c37
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")
32 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
33 * GIT_AUTHOR_DATE that will be used for the commit that is currently
34 * being rebased.
36 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
38 * The following files are written by git-rebase just after parsing the
39 * command-line (and are only consumed, not modified, by the sequencer).
41 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
43 /* We will introduce the 'interactive rebase' mode later */
44 static inline int is_rebase_i(const struct replay_opts *opts)
46 return 0;
49 static const char *get_dir(const struct replay_opts *opts)
51 return git_path_seq_dir();
54 static const char *get_todo_path(const struct replay_opts *opts)
56 return git_path_todo_file();
59 static int is_rfc2822_line(const char *buf, int len)
61 int i;
63 for (i = 0; i < len; i++) {
64 int ch = buf[i];
65 if (ch == ':')
66 return 1;
67 if (!isalnum(ch) && ch != '-')
68 break;
71 return 0;
74 static int is_cherry_picked_from_line(const char *buf, int len)
77 * We only care that it looks roughly like (cherry picked from ...)
79 return len > strlen(cherry_picked_prefix) + 1 &&
80 starts_with(buf, cherry_picked_prefix) && buf[len - 1] == ')';
84 * Returns 0 for non-conforming footer
85 * Returns 1 for conforming footer
86 * Returns 2 when sob exists within conforming footer
87 * Returns 3 when sob exists within conforming footer as last entry
89 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
90 int ignore_footer)
92 char prev;
93 int i, k;
94 int len = sb->len - ignore_footer;
95 const char *buf = sb->buf;
96 int found_sob = 0;
98 /* footer must end with newline */
99 if (!len || buf[len - 1] != '\n')
100 return 0;
102 prev = '\0';
103 for (i = len - 1; i > 0; i--) {
104 char ch = buf[i];
105 if (prev == '\n' && ch == '\n') /* paragraph break */
106 break;
107 prev = ch;
110 /* require at least one blank line */
111 if (prev != '\n' || buf[i] != '\n')
112 return 0;
114 /* advance to start of last paragraph */
115 while (i < len - 1 && buf[i] == '\n')
116 i++;
118 for (; i < len; i = k) {
119 int found_rfc2822;
121 for (k = i; k < len && buf[k] != '\n'; k++)
122 ; /* do nothing */
123 k++;
125 found_rfc2822 = is_rfc2822_line(buf + i, k - i - 1);
126 if (found_rfc2822 && sob &&
127 !strncmp(buf + i, sob->buf, sob->len))
128 found_sob = k;
130 if (!(found_rfc2822 ||
131 is_cherry_picked_from_line(buf + i, k - i - 1)))
132 return 0;
134 if (found_sob == i)
135 return 3;
136 if (found_sob)
137 return 2;
138 return 1;
141 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
143 static struct strbuf buf = STRBUF_INIT;
145 strbuf_reset(&buf);
146 if (opts->gpg_sign)
147 sq_quotef(&buf, "-S%s", opts->gpg_sign);
148 return buf.buf;
151 int sequencer_remove_state(struct replay_opts *opts)
153 struct strbuf dir = STRBUF_INIT;
154 int i;
156 free(opts->gpg_sign);
157 free(opts->strategy);
158 for (i = 0; i < opts->xopts_nr; i++)
159 free(opts->xopts[i]);
160 free(opts->xopts);
162 strbuf_addf(&dir, "%s", get_dir(opts));
163 remove_dir_recursively(&dir, 0);
164 strbuf_release(&dir);
166 return 0;
169 static const char *action_name(const struct replay_opts *opts)
171 return opts->action == REPLAY_REVERT ? "revert" : "cherry-pick";
174 struct commit_message {
175 char *parent_label;
176 char *label;
177 char *subject;
178 const char *message;
181 static const char *short_commit_name(struct commit *commit)
183 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
186 static int get_message(struct commit *commit, struct commit_message *out)
188 const char *abbrev, *subject;
189 int subject_len;
191 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
192 abbrev = short_commit_name(commit);
194 subject_len = find_commit_subject(out->message, &subject);
196 out->subject = xmemdupz(subject, subject_len);
197 out->label = xstrfmt("%s... %s", abbrev, out->subject);
198 out->parent_label = xstrfmt("parent of %s", out->label);
200 return 0;
203 static void free_message(struct commit *commit, struct commit_message *msg)
205 free(msg->parent_label);
206 free(msg->label);
207 free(msg->subject);
208 unuse_commit_buffer(commit, msg->message);
211 static void print_advice(int show_hint, struct replay_opts *opts)
213 char *msg = getenv("GIT_CHERRY_PICK_HELP");
215 if (msg) {
216 fprintf(stderr, "%s\n", msg);
218 * A conflict has occurred but the porcelain
219 * (typically rebase --interactive) wants to take care
220 * of the commit itself so remove CHERRY_PICK_HEAD
222 unlink(git_path_cherry_pick_head());
223 return;
226 if (show_hint) {
227 if (opts->no_commit)
228 advise(_("after resolving the conflicts, mark the corrected paths\n"
229 "with 'git add <paths>' or 'git rm <paths>'"));
230 else
231 advise(_("after resolving the conflicts, mark the corrected paths\n"
232 "with 'git add <paths>' or 'git rm <paths>'\n"
233 "and commit the result with 'git commit'"));
237 static int write_message(struct strbuf *msgbuf, const char *filename)
239 static struct lock_file msg_file;
241 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
242 if (msg_fd < 0)
243 return error_errno(_("Could not lock '%s'"), filename);
244 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
245 return error_errno(_("Could not write to %s"), filename);
246 strbuf_release(msgbuf);
247 if (commit_lock_file(&msg_file) < 0)
248 return error(_("Error wrapping up %s."), filename);
250 return 0;
254 * Reads a file that was presumably written by a shell script, i.e. with an
255 * end-of-line marker that needs to be stripped.
257 * Note that only the last end-of-line marker is stripped, consistent with the
258 * behavior of "$(cat path)" in a shell script.
260 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
262 static int read_oneliner(struct strbuf *buf,
263 const char *path, int skip_if_empty)
265 int orig_len = buf->len;
267 if (!file_exists(path))
268 return 0;
270 if (strbuf_read_file(buf, path, 0) < 0) {
271 warning_errno(_("could not read '%s'"), path);
272 return 0;
275 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
276 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
277 --buf->len;
278 buf->buf[buf->len] = '\0';
281 if (skip_if_empty && buf->len == orig_len)
282 return 0;
284 return 1;
287 static struct tree *empty_tree(void)
289 return lookup_tree(EMPTY_TREE_SHA1_BIN);
292 static int error_dirty_index(struct replay_opts *opts)
294 if (read_cache_unmerged())
295 return error_resolve_conflict(action_name(opts));
297 error(_("Your local changes would be overwritten by %s."),
298 action_name(opts));
300 if (advice_commit_before_merge)
301 advise(_("Commit your changes or stash them to proceed."));
302 return -1;
305 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
306 int unborn, struct replay_opts *opts)
308 struct ref_transaction *transaction;
309 struct strbuf sb = STRBUF_INIT;
310 struct strbuf err = STRBUF_INIT;
312 read_cache();
313 if (checkout_fast_forward(from, to, 1))
314 return -1; /* the callee should have complained already */
316 strbuf_addf(&sb, _("%s: fast-forward"), action_name(opts));
318 transaction = ref_transaction_begin(&err);
319 if (!transaction ||
320 ref_transaction_update(transaction, "HEAD",
321 to, unborn ? null_sha1 : from,
322 0, sb.buf, &err) ||
323 ref_transaction_commit(transaction, &err)) {
324 ref_transaction_free(transaction);
325 error("%s", err.buf);
326 strbuf_release(&sb);
327 strbuf_release(&err);
328 return -1;
331 strbuf_release(&sb);
332 strbuf_release(&err);
333 ref_transaction_free(transaction);
334 return 0;
337 void append_conflicts_hint(struct strbuf *msgbuf)
339 int i;
341 strbuf_addch(msgbuf, '\n');
342 strbuf_commented_addf(msgbuf, "Conflicts:\n");
343 for (i = 0; i < active_nr;) {
344 const struct cache_entry *ce = active_cache[i++];
345 if (ce_stage(ce)) {
346 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
347 while (i < active_nr && !strcmp(ce->name,
348 active_cache[i]->name))
349 i++;
354 static int do_recursive_merge(struct commit *base, struct commit *next,
355 const char *base_label, const char *next_label,
356 unsigned char *head, struct strbuf *msgbuf,
357 struct replay_opts *opts)
359 struct merge_options o;
360 struct tree *result, *next_tree, *base_tree, *head_tree;
361 int clean;
362 char **xopt;
363 static struct lock_file index_lock;
365 hold_locked_index(&index_lock, 1);
367 read_cache();
369 init_merge_options(&o);
370 o.ancestor = base ? base_label : "(empty tree)";
371 o.branch1 = "HEAD";
372 o.branch2 = next ? next_label : "(empty tree)";
374 head_tree = parse_tree_indirect(head);
375 next_tree = next ? next->tree : empty_tree();
376 base_tree = base ? base->tree : empty_tree();
378 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
379 parse_merge_opt(&o, *xopt);
381 clean = merge_trees(&o,
382 head_tree,
383 next_tree, base_tree, &result);
384 strbuf_release(&o.obuf);
385 if (clean < 0)
386 return clean;
388 if (active_cache_changed &&
389 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
390 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
391 return error(_("%s: Unable to write new index file"),
392 action_name(opts));
393 rollback_lock_file(&index_lock);
395 if (opts->signoff)
396 append_signoff(msgbuf, 0, 0);
398 if (!clean)
399 append_conflicts_hint(msgbuf);
401 return !clean;
404 static int is_index_unchanged(void)
406 unsigned char head_sha1[20];
407 struct commit *head_commit;
409 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
410 return error(_("Could not resolve HEAD commit\n"));
412 head_commit = lookup_commit(head_sha1);
415 * If head_commit is NULL, check_commit, called from
416 * lookup_commit, would have indicated that head_commit is not
417 * a commit object already. parse_commit() will return failure
418 * without further complaints in such a case. Otherwise, if
419 * the commit is invalid, parse_commit() will complain. So
420 * there is nothing for us to say here. Just return failure.
422 if (parse_commit(head_commit))
423 return -1;
425 if (!active_cache_tree)
426 active_cache_tree = cache_tree();
428 if (!cache_tree_fully_valid(active_cache_tree))
429 if (cache_tree_update(&the_index, 0))
430 return error(_("Unable to update cache tree\n"));
432 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
436 * Read the author-script file into an environment block, ready for use in
437 * run_command(), that can be free()d afterwards.
439 static char **read_author_script(void)
441 struct strbuf script = STRBUF_INIT;
442 int i, count = 0;
443 char *p, *p2, **env;
444 size_t env_size;
446 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
447 return NULL;
449 for (p = script.buf; *p; p++)
450 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
451 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
452 else if (*p == '\'')
453 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
454 else if (*p == '\n') {
455 *p = '\0';
456 count++;
459 env_size = (count + 1) * sizeof(*env);
460 strbuf_grow(&script, env_size);
461 memmove(script.buf + env_size, script.buf, script.len);
462 p = script.buf + env_size;
463 env = (char **)strbuf_detach(&script, NULL);
465 for (i = 0; i < count; i++) {
466 env[i] = p;
467 p += strlen(p) + 1;
469 env[count] = NULL;
471 return env;
475 * If we are cherry-pick, and if the merge did not result in
476 * hand-editing, we will hit this commit and inherit the original
477 * author date and name.
479 * If we are revert, or if our cherry-pick results in a hand merge,
480 * we had better say that the current user is responsible for that.
482 * An exception is when run_git_commit() is called during an
483 * interactive rebase: in that case, we will want to retain the
484 * author metadata.
486 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
487 int allow_empty, int edit)
489 char **env = NULL;
490 struct argv_array array;
491 int rc;
492 const char *value;
494 if (is_rebase_i(opts)) {
495 env = read_author_script();
496 if (!env) {
497 const char *gpg_opt = gpg_sign_opt_quoted(opts);
499 return error("You have staged changes in your working "
500 "tree. If these changes are meant to be\n"
501 "squashed into the previous commit, run:\n\n"
502 " git commit --amend %s\n\n"
503 "If they are meant to go into a new commit, "
504 "run:\n\n"
505 " git commit %s\n\n"
506 "In both cases, once you're done, continue "
507 "with:\n\n"
508 " git rebase --continue\n", gpg_opt, gpg_opt);
512 argv_array_init(&array);
513 argv_array_push(&array, "commit");
514 argv_array_push(&array, "-n");
516 if (opts->gpg_sign)
517 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
518 if (opts->signoff)
519 argv_array_push(&array, "-s");
520 if (defmsg)
521 argv_array_pushl(&array, "-F", defmsg, NULL);
522 if (edit)
523 argv_array_push(&array, "-e");
524 else if (!opts->signoff && !opts->record_origin &&
525 git_config_get_value("commit.cleanup", &value))
526 argv_array_push(&array, "--cleanup=verbatim");
528 if (allow_empty)
529 argv_array_push(&array, "--allow-empty");
531 if (opts->allow_empty_message)
532 argv_array_push(&array, "--allow-empty-message");
534 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
535 (const char *const *)env);
536 argv_array_clear(&array);
537 free(env);
539 return rc;
542 static int is_original_commit_empty(struct commit *commit)
544 const unsigned char *ptree_sha1;
546 if (parse_commit(commit))
547 return error(_("Could not parse commit %s\n"),
548 oid_to_hex(&commit->object.oid));
549 if (commit->parents) {
550 struct commit *parent = commit->parents->item;
551 if (parse_commit(parent))
552 return error(_("Could not parse parent commit %s\n"),
553 oid_to_hex(&parent->object.oid));
554 ptree_sha1 = parent->tree->object.oid.hash;
555 } else {
556 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
559 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
563 * Do we run "git commit" with "--allow-empty"?
565 static int allow_empty(struct replay_opts *opts, struct commit *commit)
567 int index_unchanged, empty_commit;
570 * Three cases:
572 * (1) we do not allow empty at all and error out.
574 * (2) we allow ones that were initially empty, but
575 * forbid the ones that become empty;
577 * (3) we allow both.
579 if (!opts->allow_empty)
580 return 0; /* let "git commit" barf as necessary */
582 index_unchanged = is_index_unchanged();
583 if (index_unchanged < 0)
584 return index_unchanged;
585 if (!index_unchanged)
586 return 0; /* we do not have to say --allow-empty */
588 if (opts->keep_redundant_commits)
589 return 1;
591 empty_commit = is_original_commit_empty(commit);
592 if (empty_commit < 0)
593 return empty_commit;
594 if (!empty_commit)
595 return 0;
596 else
597 return 1;
600 enum todo_command {
601 TODO_PICK = 0,
602 TODO_REVERT
605 static const char *todo_command_strings[] = {
606 "pick",
607 "revert"
610 static const char *command_to_string(const enum todo_command command)
612 if (command < ARRAY_SIZE(todo_command_strings))
613 return todo_command_strings[command];
614 die("Unknown command: %d", command);
618 static int do_pick_commit(enum todo_command command, struct commit *commit,
619 struct replay_opts *opts)
621 unsigned char head[20];
622 struct commit *base, *next, *parent;
623 const char *base_label, *next_label;
624 struct commit_message msg = { NULL, NULL, NULL, NULL };
625 struct strbuf msgbuf = STRBUF_INIT;
626 int res, unborn = 0, allow;
628 if (opts->no_commit) {
630 * We do not intend to commit immediately. We just want to
631 * merge the differences in, so let's compute the tree
632 * that represents the "current" state for merge-recursive
633 * to work on.
635 if (write_cache_as_tree(head, 0, NULL))
636 return error(_("Your index file is unmerged."));
637 } else {
638 unborn = get_sha1("HEAD", head);
639 if (unborn)
640 hashcpy(head, EMPTY_TREE_SHA1_BIN);
641 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
642 return error_dirty_index(opts);
644 discard_cache();
646 if (!commit->parents) {
647 parent = NULL;
649 else if (commit->parents->next) {
650 /* Reverting or cherry-picking a merge commit */
651 int cnt;
652 struct commit_list *p;
654 if (!opts->mainline)
655 return error(_("Commit %s is a merge but no -m option was given."),
656 oid_to_hex(&commit->object.oid));
658 for (cnt = 1, p = commit->parents;
659 cnt != opts->mainline && p;
660 cnt++)
661 p = p->next;
662 if (cnt != opts->mainline || !p)
663 return error(_("Commit %s does not have parent %d"),
664 oid_to_hex(&commit->object.oid), opts->mainline);
665 parent = p->item;
666 } else if (0 < opts->mainline)
667 return error(_("Mainline was specified but commit %s is not a merge."),
668 oid_to_hex(&commit->object.oid));
669 else
670 parent = commit->parents->item;
672 if (opts->allow_ff &&
673 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
674 (!parent && unborn)))
675 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
677 if (parent && parse_commit(parent) < 0)
678 /* TRANSLATORS: The first %s will be a "todo" command like
679 "revert" or "pick", the second %s a SHA1. */
680 return error(_("%s: cannot parse parent commit %s"),
681 command_to_string(command),
682 oid_to_hex(&parent->object.oid));
684 if (get_message(commit, &msg) != 0)
685 return error(_("Cannot get commit message for %s"),
686 oid_to_hex(&commit->object.oid));
689 * "commit" is an existing commit. We would want to apply
690 * the difference it introduces since its first parent "prev"
691 * on top of the current HEAD if we are cherry-pick. Or the
692 * reverse of it if we are revert.
695 if (command == TODO_REVERT) {
696 base = commit;
697 base_label = msg.label;
698 next = parent;
699 next_label = msg.parent_label;
700 strbuf_addstr(&msgbuf, "Revert \"");
701 strbuf_addstr(&msgbuf, msg.subject);
702 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
703 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
705 if (commit->parents && commit->parents->next) {
706 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
707 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
709 strbuf_addstr(&msgbuf, ".\n");
710 } else {
711 const char *p;
713 base = parent;
714 base_label = msg.parent_label;
715 next = commit;
716 next_label = msg.label;
719 * Append the commit log message to msgbuf; it starts
720 * after the tree, parent, author, committer
721 * information followed by "\n\n".
723 p = strstr(msg.message, "\n\n");
724 if (p)
725 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
727 if (opts->record_origin) {
728 if (!has_conforming_footer(&msgbuf, NULL, 0))
729 strbuf_addch(&msgbuf, '\n');
730 strbuf_addstr(&msgbuf, cherry_picked_prefix);
731 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
732 strbuf_addstr(&msgbuf, ")\n");
736 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
737 res = do_recursive_merge(base, next, base_label, next_label,
738 head, &msgbuf, opts);
739 if (res < 0)
740 return res;
741 res |= write_message(&msgbuf, git_path_merge_msg());
742 } else {
743 struct commit_list *common = NULL;
744 struct commit_list *remotes = NULL;
746 res = write_message(&msgbuf, git_path_merge_msg());
748 commit_list_insert(base, &common);
749 commit_list_insert(next, &remotes);
750 res |= try_merge_command(opts->strategy,
751 opts->xopts_nr, (const char **)opts->xopts,
752 common, sha1_to_hex(head), remotes);
753 free_commit_list(common);
754 free_commit_list(remotes);
758 * If the merge was clean or if it failed due to conflict, we write
759 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
760 * However, if the merge did not even start, then we don't want to
761 * write it at all.
763 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
764 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
765 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
766 res = -1;
767 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
768 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
769 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
770 res = -1;
772 if (res) {
773 error(command == TODO_REVERT
774 ? _("could not revert %s... %s")
775 : _("could not apply %s... %s"),
776 short_commit_name(commit), msg.subject);
777 print_advice(res == 1, opts);
778 rerere(opts->allow_rerere_auto);
779 goto leave;
782 allow = allow_empty(opts, commit);
783 if (allow < 0) {
784 res = allow;
785 goto leave;
787 if (!opts->no_commit)
788 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
789 opts, allow, opts->edit);
791 leave:
792 free_message(commit, &msg);
794 return res;
797 static int prepare_revs(struct replay_opts *opts)
800 * picking (but not reverting) ranges (but not individual revisions)
801 * should be done in reverse
803 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
804 opts->revs->reverse ^= 1;
806 if (prepare_revision_walk(opts->revs))
807 return error(_("revision walk setup failed"));
809 if (!opts->revs->commits)
810 return error(_("empty commit set passed"));
811 return 0;
814 static int read_and_refresh_cache(struct replay_opts *opts)
816 static struct lock_file index_lock;
817 int index_fd = hold_locked_index(&index_lock, 0);
818 if (read_index_preload(&the_index, NULL) < 0) {
819 rollback_lock_file(&index_lock);
820 return error(_("git %s: failed to read the index"),
821 action_name(opts));
823 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
824 if (the_index.cache_changed && index_fd >= 0) {
825 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
826 rollback_lock_file(&index_lock);
827 return error(_("git %s: failed to refresh the index"),
828 action_name(opts));
831 rollback_lock_file(&index_lock);
832 return 0;
835 struct todo_item {
836 enum todo_command command;
837 struct commit *commit;
838 const char *arg;
839 int arg_len;
840 size_t offset_in_buf;
843 struct todo_list {
844 struct strbuf buf;
845 struct todo_item *items;
846 int nr, alloc, current;
849 #define TODO_LIST_INIT { STRBUF_INIT }
851 static void todo_list_release(struct todo_list *todo_list)
853 strbuf_release(&todo_list->buf);
854 free(todo_list->items);
855 todo_list->items = NULL;
856 todo_list->nr = todo_list->alloc = 0;
859 static struct todo_item *append_new_todo(struct todo_list *todo_list)
861 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
862 return todo_list->items + todo_list->nr++;
865 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
867 unsigned char commit_sha1[20];
868 char *end_of_object_name;
869 int i, saved, status, padding;
871 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
872 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
873 item->command = i;
874 break;
876 if (i >= ARRAY_SIZE(todo_command_strings))
877 return -1;
879 /* Eat up extra spaces/ tabs before object name */
880 padding = strspn(bol, " \t");
881 if (!padding)
882 return -1;
883 bol += padding;
885 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
886 saved = *end_of_object_name;
887 *end_of_object_name = '\0';
888 status = get_sha1(bol, commit_sha1);
889 *end_of_object_name = saved;
891 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
892 item->arg_len = (int)(eol - item->arg);
894 if (status < 0)
895 return -1;
897 item->commit = lookup_commit_reference(commit_sha1);
898 return !item->commit;
901 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
903 struct todo_item *item;
904 char *p = buf, *next_p;
905 int i, res = 0;
907 for (i = 1; *p; i++, p = next_p) {
908 char *eol = strchrnul(p, '\n');
910 next_p = *eol ? eol + 1 /* skip LF */ : eol;
912 if (p != eol && eol[-1] == '\r')
913 eol--; /* strip Carriage Return */
915 item = append_new_todo(todo_list);
916 item->offset_in_buf = p - todo_list->buf.buf;
917 if (parse_insn_line(item, p, eol)) {
918 res = error(_("Invalid line %d: %.*s"),
919 i, (int)(eol - p), p);
920 item->command = -1;
923 if (!todo_list->nr)
924 return error(_("No commits parsed."));
925 return res;
928 static int read_populate_todo(struct todo_list *todo_list,
929 struct replay_opts *opts)
931 const char *todo_file = get_todo_path(opts);
932 int fd, res;
934 strbuf_reset(&todo_list->buf);
935 fd = open(todo_file, O_RDONLY);
936 if (fd < 0)
937 return error_errno(_("Could not open %s"), todo_file);
938 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
939 close(fd);
940 return error(_("Could not read %s."), todo_file);
942 close(fd);
944 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
945 if (!res) {
946 enum todo_command valid =
947 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
948 int i;
950 for (i = 0; i < todo_list->nr; i++)
951 if (valid == todo_list->items[i].command)
952 continue;
953 else if (valid == TODO_PICK)
954 return error(_("Cannot cherry-pick during a revert."));
955 else
956 return error(_("Cannot revert during a cherry-pick."));
959 if (res)
960 return error(_("Unusable instruction sheet: %s"), todo_file);
961 return 0;
964 static int git_config_string_dup(char **dest,
965 const char *var, const char *value)
967 if (!value)
968 return config_error_nonbool(var);
969 free(*dest);
970 *dest = xstrdup(value);
971 return 0;
974 static int populate_opts_cb(const char *key, const char *value, void *data)
976 struct replay_opts *opts = data;
977 int error_flag = 1;
979 if (!value)
980 error_flag = 0;
981 else if (!strcmp(key, "options.no-commit"))
982 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
983 else if (!strcmp(key, "options.edit"))
984 opts->edit = git_config_bool_or_int(key, value, &error_flag);
985 else if (!strcmp(key, "options.signoff"))
986 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
987 else if (!strcmp(key, "options.record-origin"))
988 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
989 else if (!strcmp(key, "options.allow-ff"))
990 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
991 else if (!strcmp(key, "options.mainline"))
992 opts->mainline = git_config_int(key, value);
993 else if (!strcmp(key, "options.strategy"))
994 git_config_string_dup(&opts->strategy, key, value);
995 else if (!strcmp(key, "options.gpg-sign"))
996 git_config_string_dup(&opts->gpg_sign, key, value);
997 else if (!strcmp(key, "options.strategy-option")) {
998 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
999 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1000 } else
1001 return error(_("Invalid key: %s"), key);
1003 if (!error_flag)
1004 return error(_("Invalid value for %s: %s"), key, value);
1006 return 0;
1009 static int read_populate_opts(struct replay_opts *opts)
1011 if (is_rebase_i(opts)) {
1012 struct strbuf buf = STRBUF_INIT;
1014 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1015 if (!starts_with(buf.buf, "-S"))
1016 strbuf_reset(&buf);
1017 else {
1018 free(opts->gpg_sign);
1019 opts->gpg_sign = xstrdup(buf.buf + 2);
1022 strbuf_release(&buf);
1024 return 0;
1027 if (!file_exists(git_path_opts_file()))
1028 return 0;
1030 * The function git_parse_source(), called from git_config_from_file(),
1031 * may die() in case of a syntactically incorrect file. We do not care
1032 * about this case, though, because we wrote that file ourselves, so we
1033 * are pretty certain that it is syntactically correct.
1035 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1036 return error(_("Malformed options sheet: %s"),
1037 git_path_opts_file());
1038 return 0;
1041 static int walk_revs_populate_todo(struct todo_list *todo_list,
1042 struct replay_opts *opts)
1044 enum todo_command command = opts->action == REPLAY_PICK ?
1045 TODO_PICK : TODO_REVERT;
1046 const char *command_string = todo_command_strings[command];
1047 struct commit *commit;
1049 if (prepare_revs(opts))
1050 return -1;
1052 while ((commit = get_revision(opts->revs))) {
1053 struct todo_item *item = append_new_todo(todo_list);
1054 const char *commit_buffer = get_commit_buffer(commit, NULL);
1055 const char *subject;
1056 int subject_len;
1058 item->command = command;
1059 item->commit = commit;
1060 item->arg = NULL;
1061 item->arg_len = 0;
1062 item->offset_in_buf = todo_list->buf.len;
1063 subject_len = find_commit_subject(commit_buffer, &subject);
1064 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1065 short_commit_name(commit), subject_len, subject);
1066 unuse_commit_buffer(commit, commit_buffer);
1068 return 0;
1071 static int create_seq_dir(void)
1073 if (file_exists(git_path_seq_dir())) {
1074 error(_("a cherry-pick or revert is already in progress"));
1075 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1076 return -1;
1078 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1079 return error_errno(_("Could not create sequencer directory %s"),
1080 git_path_seq_dir());
1081 return 0;
1084 static int save_head(const char *head)
1086 static struct lock_file head_lock;
1087 struct strbuf buf = STRBUF_INIT;
1088 int fd;
1090 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1091 if (fd < 0) {
1092 rollback_lock_file(&head_lock);
1093 return error_errno(_("Could not lock HEAD"));
1095 strbuf_addf(&buf, "%s\n", head);
1096 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1097 rollback_lock_file(&head_lock);
1098 return error_errno(_("Could not write to %s"),
1099 git_path_head_file());
1101 if (commit_lock_file(&head_lock) < 0) {
1102 rollback_lock_file(&head_lock);
1103 return error(_("Error wrapping up %s."), git_path_head_file());
1105 return 0;
1108 static int reset_for_rollback(const unsigned char *sha1)
1110 const char *argv[4]; /* reset --merge <arg> + NULL */
1111 argv[0] = "reset";
1112 argv[1] = "--merge";
1113 argv[2] = sha1_to_hex(sha1);
1114 argv[3] = NULL;
1115 return run_command_v_opt(argv, RUN_GIT_CMD);
1118 static int rollback_single_pick(void)
1120 unsigned char head_sha1[20];
1122 if (!file_exists(git_path_cherry_pick_head()) &&
1123 !file_exists(git_path_revert_head()))
1124 return error(_("no cherry-pick or revert in progress"));
1125 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1126 return error(_("cannot resolve HEAD"));
1127 if (is_null_sha1(head_sha1))
1128 return error(_("cannot abort from a branch yet to be born"));
1129 return reset_for_rollback(head_sha1);
1132 int sequencer_rollback(struct replay_opts *opts)
1134 FILE *f;
1135 unsigned char sha1[20];
1136 struct strbuf buf = STRBUF_INIT;
1138 f = fopen(git_path_head_file(), "r");
1139 if (!f && errno == ENOENT) {
1141 * There is no multiple-cherry-pick in progress.
1142 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1143 * a single-cherry-pick in progress, abort that.
1145 return rollback_single_pick();
1147 if (!f)
1148 return error_errno(_("cannot open %s"), git_path_head_file());
1149 if (strbuf_getline_lf(&buf, f)) {
1150 error(_("cannot read %s: %s"), git_path_head_file(),
1151 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1152 fclose(f);
1153 goto fail;
1155 fclose(f);
1156 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1157 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1158 git_path_head_file());
1159 goto fail;
1161 if (is_null_sha1(sha1)) {
1162 error(_("cannot abort from a branch yet to be born"));
1163 goto fail;
1165 if (reset_for_rollback(sha1))
1166 goto fail;
1167 strbuf_release(&buf);
1168 return sequencer_remove_state(opts);
1169 fail:
1170 strbuf_release(&buf);
1171 return -1;
1174 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1176 static struct lock_file todo_lock;
1177 const char *todo_path = get_todo_path(opts);
1178 int next = todo_list->current, offset, fd;
1180 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1181 if (fd < 0)
1182 return error_errno(_("Could not lock '%s'"), todo_path);
1183 offset = next < todo_list->nr ?
1184 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1185 if (write_in_full(fd, todo_list->buf.buf + offset,
1186 todo_list->buf.len - offset) < 0)
1187 return error_errno(_("Could not write to '%s'"), todo_path);
1188 if (commit_lock_file(&todo_lock) < 0)
1189 return error(_("Error wrapping up %s."), todo_path);
1190 return 0;
1193 static int save_opts(struct replay_opts *opts)
1195 const char *opts_file = git_path_opts_file();
1196 int res = 0;
1198 if (opts->no_commit)
1199 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1200 if (opts->edit)
1201 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1202 if (opts->signoff)
1203 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1204 if (opts->record_origin)
1205 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1206 if (opts->allow_ff)
1207 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1208 if (opts->mainline) {
1209 struct strbuf buf = STRBUF_INIT;
1210 strbuf_addf(&buf, "%d", opts->mainline);
1211 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1212 strbuf_release(&buf);
1214 if (opts->strategy)
1215 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1216 if (opts->gpg_sign)
1217 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1218 if (opts->xopts) {
1219 int i;
1220 for (i = 0; i < opts->xopts_nr; i++)
1221 res |= git_config_set_multivar_in_file_gently(opts_file,
1222 "options.strategy-option",
1223 opts->xopts[i], "^$", 0);
1225 return res;
1228 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1230 int res;
1232 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1233 if (opts->allow_ff)
1234 assert(!(opts->signoff || opts->no_commit ||
1235 opts->record_origin || opts->edit));
1236 if (read_and_refresh_cache(opts))
1237 return -1;
1239 while (todo_list->current < todo_list->nr) {
1240 struct todo_item *item = todo_list->items + todo_list->current;
1241 if (save_todo(todo_list, opts))
1242 return -1;
1243 res = do_pick_commit(item->command, item->commit, opts);
1244 todo_list->current++;
1245 if (res)
1246 return res;
1250 * Sequence of picks finished successfully; cleanup by
1251 * removing the .git/sequencer directory
1253 return sequencer_remove_state(opts);
1256 static int continue_single_pick(void)
1258 const char *argv[] = { "commit", NULL };
1260 if (!file_exists(git_path_cherry_pick_head()) &&
1261 !file_exists(git_path_revert_head()))
1262 return error(_("no cherry-pick or revert in progress"));
1263 return run_command_v_opt(argv, RUN_GIT_CMD);
1266 int sequencer_continue(struct replay_opts *opts)
1268 struct todo_list todo_list = TODO_LIST_INIT;
1269 int res;
1271 if (read_and_refresh_cache(opts))
1272 return -1;
1274 if (!file_exists(get_todo_path(opts)))
1275 return continue_single_pick();
1276 if (read_populate_opts(opts))
1277 return -1;
1278 if ((res = read_populate_todo(&todo_list, opts)))
1279 goto release_todo_list;
1281 /* Verify that the conflict has been resolved */
1282 if (file_exists(git_path_cherry_pick_head()) ||
1283 file_exists(git_path_revert_head())) {
1284 res = continue_single_pick();
1285 if (res)
1286 goto release_todo_list;
1288 if (index_differs_from("HEAD", 0)) {
1289 res = error_dirty_index(opts);
1290 goto release_todo_list;
1292 todo_list.current++;
1293 res = pick_commits(&todo_list, opts);
1294 release_todo_list:
1295 todo_list_release(&todo_list);
1296 return res;
1299 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1301 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1302 return do_pick_commit(opts->action == REPLAY_PICK ?
1303 TODO_PICK : TODO_REVERT, cmit, opts);
1306 int sequencer_pick_revisions(struct replay_opts *opts)
1308 struct todo_list todo_list = TODO_LIST_INIT;
1309 unsigned char sha1[20];
1310 int i, res;
1312 assert(opts->revs);
1313 if (read_and_refresh_cache(opts))
1314 return -1;
1316 for (i = 0; i < opts->revs->pending.nr; i++) {
1317 unsigned char sha1[20];
1318 const char *name = opts->revs->pending.objects[i].name;
1320 /* This happens when using --stdin. */
1321 if (!strlen(name))
1322 continue;
1324 if (!get_sha1(name, sha1)) {
1325 if (!lookup_commit_reference_gently(sha1, 1)) {
1326 enum object_type type = sha1_object_info(sha1, NULL);
1327 return error(_("%s: can't cherry-pick a %s"),
1328 name, typename(type));
1330 } else
1331 return error(_("%s: bad revision"), name);
1335 * If we were called as "git cherry-pick <commit>", just
1336 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1337 * REVERT_HEAD, and don't touch the sequencer state.
1338 * This means it is possible to cherry-pick in the middle
1339 * of a cherry-pick sequence.
1341 if (opts->revs->cmdline.nr == 1 &&
1342 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1343 opts->revs->no_walk &&
1344 !opts->revs->cmdline.rev->flags) {
1345 struct commit *cmit;
1346 if (prepare_revision_walk(opts->revs))
1347 return error(_("revision walk setup failed"));
1348 cmit = get_revision(opts->revs);
1349 if (!cmit || get_revision(opts->revs))
1350 return error("BUG: expected exactly one commit from walk");
1351 return single_pick(cmit, opts);
1355 * Start a new cherry-pick/ revert sequence; but
1356 * first, make sure that an existing one isn't in
1357 * progress
1360 if (walk_revs_populate_todo(&todo_list, opts) ||
1361 create_seq_dir() < 0)
1362 return -1;
1363 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1364 return error(_("Can't revert as initial commit"));
1365 if (save_head(sha1_to_hex(sha1)))
1366 return -1;
1367 if (save_opts(opts))
1368 return -1;
1369 res = pick_commits(&todo_list, opts);
1370 todo_list_release(&todo_list);
1371 return res;
1374 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1376 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1377 struct strbuf sob = STRBUF_INIT;
1378 int has_footer;
1380 strbuf_addstr(&sob, sign_off_header);
1381 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1382 getenv("GIT_COMMITTER_EMAIL")));
1383 strbuf_addch(&sob, '\n');
1386 * If the whole message buffer is equal to the sob, pretend that we
1387 * found a conforming footer with a matching sob
1389 if (msgbuf->len - ignore_footer == sob.len &&
1390 !strncmp(msgbuf->buf, sob.buf, sob.len))
1391 has_footer = 3;
1392 else
1393 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1395 if (!has_footer) {
1396 const char *append_newlines = NULL;
1397 size_t len = msgbuf->len - ignore_footer;
1399 if (!len) {
1401 * The buffer is completely empty. Leave foom for
1402 * the title and body to be filled in by the user.
1404 append_newlines = "\n\n";
1405 } else if (msgbuf->buf[len - 1] != '\n') {
1407 * Incomplete line. Complete the line and add a
1408 * blank one so that there is an empty line between
1409 * the message body and the sob.
1411 append_newlines = "\n\n";
1412 } else if (len == 1) {
1414 * Buffer contains a single newline. Add another
1415 * so that we leave room for the title and body.
1417 append_newlines = "\n";
1418 } else if (msgbuf->buf[len - 2] != '\n') {
1420 * Buffer ends with a single newline. Add another
1421 * so that there is an empty line between the message
1422 * body and the sob.
1424 append_newlines = "\n";
1425 } /* else, the buffer already ends with two newlines. */
1427 if (append_newlines)
1428 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1429 append_newlines, strlen(append_newlines));
1432 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1433 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1434 sob.buf, sob.len);
1436 strbuf_release(&sob);