sequencer: use a helper to find the commit message
[git/debian.git] / sequencer.c
blob720857bedaa051a30663dab2fff11bf25d52fd66
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"
19 #include "trailer.h"
21 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
23 const char sign_off_header[] = "Signed-off-by: ";
24 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
26 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
28 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
29 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
30 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
31 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
34 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
35 * GIT_AUTHOR_DATE that will be used for the commit that is currently
36 * being rebased.
38 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
40 * The following files are written by git-rebase just after parsing the
41 * command-line (and are only consumed, not modified, by the sequencer).
43 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
45 /* We will introduce the 'interactive rebase' mode later */
46 static inline int is_rebase_i(const struct replay_opts *opts)
48 return 0;
51 static const char *get_dir(const struct replay_opts *opts)
53 return git_path_seq_dir();
56 static const char *get_todo_path(const struct replay_opts *opts)
58 return git_path_todo_file();
62 * Returns 0 for non-conforming footer
63 * Returns 1 for conforming footer
64 * Returns 2 when sob exists within conforming footer
65 * Returns 3 when sob exists within conforming footer as last entry
67 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
68 int ignore_footer)
70 struct trailer_info info;
71 int i;
72 int found_sob = 0, found_sob_last = 0;
74 trailer_info_get(&info, sb->buf);
76 if (info.trailer_start == info.trailer_end)
77 return 0;
79 for (i = 0; i < info.trailer_nr; i++)
80 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
81 found_sob = 1;
82 if (i == info.trailer_nr - 1)
83 found_sob_last = 1;
86 trailer_info_release(&info);
88 if (found_sob_last)
89 return 3;
90 if (found_sob)
91 return 2;
92 return 1;
95 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
97 static struct strbuf buf = STRBUF_INIT;
99 strbuf_reset(&buf);
100 if (opts->gpg_sign)
101 sq_quotef(&buf, "-S%s", opts->gpg_sign);
102 return buf.buf;
105 int sequencer_remove_state(struct replay_opts *opts)
107 struct strbuf dir = STRBUF_INIT;
108 int i;
110 free(opts->gpg_sign);
111 free(opts->strategy);
112 for (i = 0; i < opts->xopts_nr; i++)
113 free(opts->xopts[i]);
114 free(opts->xopts);
116 strbuf_addf(&dir, "%s", get_dir(opts));
117 remove_dir_recursively(&dir, 0);
118 strbuf_release(&dir);
120 return 0;
123 static const char *action_name(const struct replay_opts *opts)
125 return opts->action == REPLAY_REVERT ? N_("revert") : N_("cherry-pick");
128 struct commit_message {
129 char *parent_label;
130 char *label;
131 char *subject;
132 const char *message;
135 static const char *short_commit_name(struct commit *commit)
137 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
140 static int get_message(struct commit *commit, struct commit_message *out)
142 const char *abbrev, *subject;
143 int subject_len;
145 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
146 abbrev = short_commit_name(commit);
148 subject_len = find_commit_subject(out->message, &subject);
150 out->subject = xmemdupz(subject, subject_len);
151 out->label = xstrfmt("%s... %s", abbrev, out->subject);
152 out->parent_label = xstrfmt("parent of %s", out->label);
154 return 0;
157 static void free_message(struct commit *commit, struct commit_message *msg)
159 free(msg->parent_label);
160 free(msg->label);
161 free(msg->subject);
162 unuse_commit_buffer(commit, msg->message);
165 static void print_advice(int show_hint, struct replay_opts *opts)
167 char *msg = getenv("GIT_CHERRY_PICK_HELP");
169 if (msg) {
170 fprintf(stderr, "%s\n", msg);
172 * A conflict has occurred but the porcelain
173 * (typically rebase --interactive) wants to take care
174 * of the commit itself so remove CHERRY_PICK_HEAD
176 unlink(git_path_cherry_pick_head());
177 return;
180 if (show_hint) {
181 if (opts->no_commit)
182 advise(_("after resolving the conflicts, mark the corrected paths\n"
183 "with 'git add <paths>' or 'git rm <paths>'"));
184 else
185 advise(_("after resolving the conflicts, mark the corrected paths\n"
186 "with 'git add <paths>' or 'git rm <paths>'\n"
187 "and commit the result with 'git commit'"));
191 static int write_message(const void *buf, size_t len, const char *filename,
192 int append_eol)
194 static struct lock_file msg_file;
196 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
197 if (msg_fd < 0)
198 return error_errno(_("could not lock '%s'"), filename);
199 if (write_in_full(msg_fd, buf, len) < 0) {
200 rollback_lock_file(&msg_file);
201 return error_errno(_("could not write to '%s'"), filename);
203 if (append_eol && write(msg_fd, "\n", 1) < 0) {
204 rollback_lock_file(&msg_file);
205 return error_errno(_("could not write eol to '%s'"), filename);
207 if (commit_lock_file(&msg_file) < 0) {
208 rollback_lock_file(&msg_file);
209 return error(_("failed to finalize '%s'."), filename);
212 return 0;
216 * Reads a file that was presumably written by a shell script, i.e. with an
217 * end-of-line marker that needs to be stripped.
219 * Note that only the last end-of-line marker is stripped, consistent with the
220 * behavior of "$(cat path)" in a shell script.
222 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
224 static int read_oneliner(struct strbuf *buf,
225 const char *path, int skip_if_empty)
227 int orig_len = buf->len;
229 if (!file_exists(path))
230 return 0;
232 if (strbuf_read_file(buf, path, 0) < 0) {
233 warning_errno(_("could not read '%s'"), path);
234 return 0;
237 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
238 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
239 --buf->len;
240 buf->buf[buf->len] = '\0';
243 if (skip_if_empty && buf->len == orig_len)
244 return 0;
246 return 1;
249 static struct tree *empty_tree(void)
251 return lookup_tree(EMPTY_TREE_SHA1_BIN);
254 static int error_dirty_index(struct replay_opts *opts)
256 if (read_cache_unmerged())
257 return error_resolve_conflict(_(action_name(opts)));
259 error(_("your local changes would be overwritten by %s."),
260 _(action_name(opts)));
262 if (advice_commit_before_merge)
263 advise(_("commit your changes or stash them to proceed."));
264 return -1;
267 static void update_abort_safety_file(void)
269 struct object_id head;
271 /* Do nothing on a single-pick */
272 if (!file_exists(git_path_seq_dir()))
273 return;
275 if (!get_oid("HEAD", &head))
276 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
277 else
278 write_file(git_path_abort_safety_file(), "%s", "");
281 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
282 int unborn, struct replay_opts *opts)
284 struct ref_transaction *transaction;
285 struct strbuf sb = STRBUF_INIT;
286 struct strbuf err = STRBUF_INIT;
288 read_cache();
289 if (checkout_fast_forward(from, to, 1))
290 return -1; /* the callee should have complained already */
292 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
294 transaction = ref_transaction_begin(&err);
295 if (!transaction ||
296 ref_transaction_update(transaction, "HEAD",
297 to, unborn ? null_sha1 : from,
298 0, sb.buf, &err) ||
299 ref_transaction_commit(transaction, &err)) {
300 ref_transaction_free(transaction);
301 error("%s", err.buf);
302 strbuf_release(&sb);
303 strbuf_release(&err);
304 return -1;
307 strbuf_release(&sb);
308 strbuf_release(&err);
309 ref_transaction_free(transaction);
310 update_abort_safety_file();
311 return 0;
314 void append_conflicts_hint(struct strbuf *msgbuf)
316 int i;
318 strbuf_addch(msgbuf, '\n');
319 strbuf_commented_addf(msgbuf, "Conflicts:\n");
320 for (i = 0; i < active_nr;) {
321 const struct cache_entry *ce = active_cache[i++];
322 if (ce_stage(ce)) {
323 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
324 while (i < active_nr && !strcmp(ce->name,
325 active_cache[i]->name))
326 i++;
331 static int do_recursive_merge(struct commit *base, struct commit *next,
332 const char *base_label, const char *next_label,
333 unsigned char *head, struct strbuf *msgbuf,
334 struct replay_opts *opts)
336 struct merge_options o;
337 struct tree *result, *next_tree, *base_tree, *head_tree;
338 int clean;
339 char **xopt;
340 static struct lock_file index_lock;
342 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
344 read_cache();
346 init_merge_options(&o);
347 o.ancestor = base ? base_label : "(empty tree)";
348 o.branch1 = "HEAD";
349 o.branch2 = next ? next_label : "(empty tree)";
351 head_tree = parse_tree_indirect(head);
352 next_tree = next ? next->tree : empty_tree();
353 base_tree = base ? base->tree : empty_tree();
355 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
356 parse_merge_opt(&o, *xopt);
358 clean = merge_trees(&o,
359 head_tree,
360 next_tree, base_tree, &result);
361 strbuf_release(&o.obuf);
362 if (clean < 0)
363 return clean;
365 if (active_cache_changed &&
366 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
367 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
368 return error(_("%s: Unable to write new index file"),
369 _(action_name(opts)));
370 rollback_lock_file(&index_lock);
372 if (opts->signoff)
373 append_signoff(msgbuf, 0, 0);
375 if (!clean)
376 append_conflicts_hint(msgbuf);
378 return !clean;
381 static int is_index_unchanged(void)
383 unsigned char head_sha1[20];
384 struct commit *head_commit;
386 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
387 return error(_("could not resolve HEAD commit\n"));
389 head_commit = lookup_commit(head_sha1);
392 * If head_commit is NULL, check_commit, called from
393 * lookup_commit, would have indicated that head_commit is not
394 * a commit object already. parse_commit() will return failure
395 * without further complaints in such a case. Otherwise, if
396 * the commit is invalid, parse_commit() will complain. So
397 * there is nothing for us to say here. Just return failure.
399 if (parse_commit(head_commit))
400 return -1;
402 if (!active_cache_tree)
403 active_cache_tree = cache_tree();
405 if (!cache_tree_fully_valid(active_cache_tree))
406 if (cache_tree_update(&the_index, 0))
407 return error(_("unable to update cache tree\n"));
409 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
413 * Read the author-script file into an environment block, ready for use in
414 * run_command(), that can be free()d afterwards.
416 static char **read_author_script(void)
418 struct strbuf script = STRBUF_INIT;
419 int i, count = 0;
420 char *p, *p2, **env;
421 size_t env_size;
423 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
424 return NULL;
426 for (p = script.buf; *p; p++)
427 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
428 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
429 else if (*p == '\'')
430 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
431 else if (*p == '\n') {
432 *p = '\0';
433 count++;
436 env_size = (count + 1) * sizeof(*env);
437 strbuf_grow(&script, env_size);
438 memmove(script.buf + env_size, script.buf, script.len);
439 p = script.buf + env_size;
440 env = (char **)strbuf_detach(&script, NULL);
442 for (i = 0; i < count; i++) {
443 env[i] = p;
444 p += strlen(p) + 1;
446 env[count] = NULL;
448 return env;
451 static const char staged_changes_advice[] =
452 N_("you have staged changes in your working tree\n"
453 "If these changes are meant to be squashed into the previous commit, run:\n"
454 "\n"
455 " git commit --amend %s\n"
456 "\n"
457 "If they are meant to go into a new commit, run:\n"
458 "\n"
459 " git commit %s\n"
460 "\n"
461 "In both cases, once you're done, continue with:\n"
462 "\n"
463 " git rebase --continue\n");
466 * If we are cherry-pick, and if the merge did not result in
467 * hand-editing, we will hit this commit and inherit the original
468 * author date and name.
470 * If we are revert, or if our cherry-pick results in a hand merge,
471 * we had better say that the current user is responsible for that.
473 * An exception is when run_git_commit() is called during an
474 * interactive rebase: in that case, we will want to retain the
475 * author metadata.
477 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
478 int allow_empty, int edit, int amend,
479 int cleanup_commit_message)
481 char **env = NULL;
482 struct argv_array array;
483 int rc;
484 const char *value;
486 if (is_rebase_i(opts)) {
487 env = read_author_script();
488 if (!env) {
489 const char *gpg_opt = gpg_sign_opt_quoted(opts);
491 return error(_(staged_changes_advice),
492 gpg_opt, gpg_opt);
496 argv_array_init(&array);
497 argv_array_push(&array, "commit");
498 argv_array_push(&array, "-n");
500 if (amend)
501 argv_array_push(&array, "--amend");
502 if (opts->gpg_sign)
503 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
504 if (opts->signoff)
505 argv_array_push(&array, "-s");
506 if (defmsg)
507 argv_array_pushl(&array, "-F", defmsg, NULL);
508 if (cleanup_commit_message)
509 argv_array_push(&array, "--cleanup=strip");
510 if (edit)
511 argv_array_push(&array, "-e");
512 else if (!cleanup_commit_message &&
513 !opts->signoff && !opts->record_origin &&
514 git_config_get_value("commit.cleanup", &value))
515 argv_array_push(&array, "--cleanup=verbatim");
517 if (allow_empty)
518 argv_array_push(&array, "--allow-empty");
520 if (opts->allow_empty_message)
521 argv_array_push(&array, "--allow-empty-message");
523 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
524 (const char *const *)env);
525 argv_array_clear(&array);
526 free(env);
528 return rc;
531 static int is_original_commit_empty(struct commit *commit)
533 const unsigned char *ptree_sha1;
535 if (parse_commit(commit))
536 return error(_("could not parse commit %s\n"),
537 oid_to_hex(&commit->object.oid));
538 if (commit->parents) {
539 struct commit *parent = commit->parents->item;
540 if (parse_commit(parent))
541 return error(_("could not parse parent commit %s\n"),
542 oid_to_hex(&parent->object.oid));
543 ptree_sha1 = parent->tree->object.oid.hash;
544 } else {
545 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
548 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
552 * Do we run "git commit" with "--allow-empty"?
554 static int allow_empty(struct replay_opts *opts, struct commit *commit)
556 int index_unchanged, empty_commit;
559 * Three cases:
561 * (1) we do not allow empty at all and error out.
563 * (2) we allow ones that were initially empty, but
564 * forbid the ones that become empty;
566 * (3) we allow both.
568 if (!opts->allow_empty)
569 return 0; /* let "git commit" barf as necessary */
571 index_unchanged = is_index_unchanged();
572 if (index_unchanged < 0)
573 return index_unchanged;
574 if (!index_unchanged)
575 return 0; /* we do not have to say --allow-empty */
577 if (opts->keep_redundant_commits)
578 return 1;
580 empty_commit = is_original_commit_empty(commit);
581 if (empty_commit < 0)
582 return empty_commit;
583 if (!empty_commit)
584 return 0;
585 else
586 return 1;
589 enum todo_command {
590 TODO_PICK = 0,
591 TODO_REVERT
594 static const char *todo_command_strings[] = {
595 "pick",
596 "revert"
599 static const char *command_to_string(const enum todo_command command)
601 if ((size_t)command < ARRAY_SIZE(todo_command_strings))
602 return todo_command_strings[command];
603 die("Unknown command: %d", command);
607 static int do_pick_commit(enum todo_command command, struct commit *commit,
608 struct replay_opts *opts)
610 unsigned char head[20];
611 struct commit *base, *next, *parent;
612 const char *base_label, *next_label;
613 struct commit_message msg = { NULL, NULL, NULL, NULL };
614 struct strbuf msgbuf = STRBUF_INIT;
615 int res, unborn = 0, allow;
617 if (opts->no_commit) {
619 * We do not intend to commit immediately. We just want to
620 * merge the differences in, so let's compute the tree
621 * that represents the "current" state for merge-recursive
622 * to work on.
624 if (write_cache_as_tree(head, 0, NULL))
625 return error(_("your index file is unmerged."));
626 } else {
627 unborn = get_sha1("HEAD", head);
628 if (unborn)
629 hashcpy(head, EMPTY_TREE_SHA1_BIN);
630 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
631 return error_dirty_index(opts);
633 discard_cache();
635 if (!commit->parents)
636 parent = NULL;
637 else if (commit->parents->next) {
638 /* Reverting or cherry-picking a merge commit */
639 int cnt;
640 struct commit_list *p;
642 if (!opts->mainline)
643 return error(_("commit %s is a merge but no -m option was given."),
644 oid_to_hex(&commit->object.oid));
646 for (cnt = 1, p = commit->parents;
647 cnt != opts->mainline && p;
648 cnt++)
649 p = p->next;
650 if (cnt != opts->mainline || !p)
651 return error(_("commit %s does not have parent %d"),
652 oid_to_hex(&commit->object.oid), opts->mainline);
653 parent = p->item;
654 } else if (0 < opts->mainline)
655 return error(_("mainline was specified but commit %s is not a merge."),
656 oid_to_hex(&commit->object.oid));
657 else
658 parent = commit->parents->item;
660 if (opts->allow_ff &&
661 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
662 (!parent && unborn)))
663 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
665 if (parent && parse_commit(parent) < 0)
666 /* TRANSLATORS: The first %s will be a "todo" command like
667 "revert" or "pick", the second %s a SHA1. */
668 return error(_("%s: cannot parse parent commit %s"),
669 command_to_string(command),
670 oid_to_hex(&parent->object.oid));
672 if (get_message(commit, &msg) != 0)
673 return error(_("cannot get commit message for %s"),
674 oid_to_hex(&commit->object.oid));
677 * "commit" is an existing commit. We would want to apply
678 * the difference it introduces since its first parent "prev"
679 * on top of the current HEAD if we are cherry-pick. Or the
680 * reverse of it if we are revert.
683 if (command == TODO_REVERT) {
684 base = commit;
685 base_label = msg.label;
686 next = parent;
687 next_label = msg.parent_label;
688 strbuf_addstr(&msgbuf, "Revert \"");
689 strbuf_addstr(&msgbuf, msg.subject);
690 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
691 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
693 if (commit->parents && commit->parents->next) {
694 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
695 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
697 strbuf_addstr(&msgbuf, ".\n");
698 } else {
699 const char *p;
701 base = parent;
702 base_label = msg.parent_label;
703 next = commit;
704 next_label = msg.label;
706 /* Append the commit log message to msgbuf. */
707 if (find_commit_subject(msg.message, &p))
708 strbuf_addstr(&msgbuf, p);
710 if (opts->record_origin) {
711 if (!has_conforming_footer(&msgbuf, NULL, 0))
712 strbuf_addch(&msgbuf, '\n');
713 strbuf_addstr(&msgbuf, cherry_picked_prefix);
714 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
715 strbuf_addstr(&msgbuf, ")\n");
719 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
720 res = do_recursive_merge(base, next, base_label, next_label,
721 head, &msgbuf, opts);
722 if (res < 0)
723 return res;
724 res |= write_message(msgbuf.buf, msgbuf.len,
725 git_path_merge_msg(), 0);
726 } else {
727 struct commit_list *common = NULL;
728 struct commit_list *remotes = NULL;
730 res = write_message(msgbuf.buf, msgbuf.len,
731 git_path_merge_msg(), 0);
733 commit_list_insert(base, &common);
734 commit_list_insert(next, &remotes);
735 res |= try_merge_command(opts->strategy,
736 opts->xopts_nr, (const char **)opts->xopts,
737 common, sha1_to_hex(head), remotes);
738 free_commit_list(common);
739 free_commit_list(remotes);
741 strbuf_release(&msgbuf);
744 * If the merge was clean or if it failed due to conflict, we write
745 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
746 * However, if the merge did not even start, then we don't want to
747 * write it at all.
749 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
750 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
751 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
752 res = -1;
753 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
754 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
755 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
756 res = -1;
758 if (res) {
759 error(command == TODO_REVERT
760 ? _("could not revert %s... %s")
761 : _("could not apply %s... %s"),
762 short_commit_name(commit), msg.subject);
763 print_advice(res == 1, opts);
764 rerere(opts->allow_rerere_auto);
765 goto leave;
768 allow = allow_empty(opts, commit);
769 if (allow < 0) {
770 res = allow;
771 goto leave;
773 if (!opts->no_commit)
774 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
775 opts, allow, opts->edit, 0, 0);
777 leave:
778 free_message(commit, &msg);
779 update_abort_safety_file();
781 return res;
784 static int prepare_revs(struct replay_opts *opts)
787 * picking (but not reverting) ranges (but not individual revisions)
788 * should be done in reverse
790 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
791 opts->revs->reverse ^= 1;
793 if (prepare_revision_walk(opts->revs))
794 return error(_("revision walk setup failed"));
796 if (!opts->revs->commits)
797 return error(_("empty commit set passed"));
798 return 0;
801 static int read_and_refresh_cache(struct replay_opts *opts)
803 static struct lock_file index_lock;
804 int index_fd = hold_locked_index(&index_lock, 0);
805 if (read_index_preload(&the_index, NULL) < 0) {
806 rollback_lock_file(&index_lock);
807 return error(_("git %s: failed to read the index"),
808 _(action_name(opts)));
810 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
811 if (the_index.cache_changed && index_fd >= 0) {
812 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
813 rollback_lock_file(&index_lock);
814 return error(_("git %s: failed to refresh the index"),
815 _(action_name(opts)));
818 rollback_lock_file(&index_lock);
819 return 0;
822 struct todo_item {
823 enum todo_command command;
824 struct commit *commit;
825 const char *arg;
826 int arg_len;
827 size_t offset_in_buf;
830 struct todo_list {
831 struct strbuf buf;
832 struct todo_item *items;
833 int nr, alloc, current;
836 #define TODO_LIST_INIT { STRBUF_INIT }
838 static void todo_list_release(struct todo_list *todo_list)
840 strbuf_release(&todo_list->buf);
841 free(todo_list->items);
842 todo_list->items = NULL;
843 todo_list->nr = todo_list->alloc = 0;
846 static struct todo_item *append_new_todo(struct todo_list *todo_list)
848 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
849 return todo_list->items + todo_list->nr++;
852 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
854 unsigned char commit_sha1[20];
855 char *end_of_object_name;
856 int i, saved, status, padding;
858 /* left-trim */
859 bol += strspn(bol, " \t");
861 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
862 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
863 item->command = i;
864 break;
866 if (i >= ARRAY_SIZE(todo_command_strings))
867 return -1;
869 /* Eat up extra spaces/ tabs before object name */
870 padding = strspn(bol, " \t");
871 if (!padding)
872 return -1;
873 bol += padding;
875 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
876 saved = *end_of_object_name;
877 *end_of_object_name = '\0';
878 status = get_sha1(bol, commit_sha1);
879 *end_of_object_name = saved;
881 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
882 item->arg_len = (int)(eol - item->arg);
884 if (status < 0)
885 return -1;
887 item->commit = lookup_commit_reference(commit_sha1);
888 return !item->commit;
891 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
893 struct todo_item *item;
894 char *p = buf, *next_p;
895 int i, res = 0;
897 for (i = 1; *p; i++, p = next_p) {
898 char *eol = strchrnul(p, '\n');
900 next_p = *eol ? eol + 1 /* skip LF */ : eol;
902 if (p != eol && eol[-1] == '\r')
903 eol--; /* strip Carriage Return */
905 item = append_new_todo(todo_list);
906 item->offset_in_buf = p - todo_list->buf.buf;
907 if (parse_insn_line(item, p, eol)) {
908 res = error(_("invalid line %d: %.*s"),
909 i, (int)(eol - p), p);
910 item->command = -1;
913 if (!todo_list->nr)
914 return error(_("no commits parsed."));
915 return res;
918 static int read_populate_todo(struct todo_list *todo_list,
919 struct replay_opts *opts)
921 const char *todo_file = get_todo_path(opts);
922 int fd, res;
924 strbuf_reset(&todo_list->buf);
925 fd = open(todo_file, O_RDONLY);
926 if (fd < 0)
927 return error_errno(_("could not open '%s'"), todo_file);
928 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
929 close(fd);
930 return error(_("could not read '%s'."), todo_file);
932 close(fd);
934 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
935 if (res)
936 return error(_("unusable instruction sheet: '%s'"), todo_file);
938 if (!is_rebase_i(opts)) {
939 enum todo_command valid =
940 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
941 int i;
943 for (i = 0; i < todo_list->nr; i++)
944 if (valid == todo_list->items[i].command)
945 continue;
946 else if (valid == TODO_PICK)
947 return error(_("cannot cherry-pick during a revert."));
948 else
949 return error(_("cannot revert during a cherry-pick."));
952 return 0;
955 static int git_config_string_dup(char **dest,
956 const char *var, const char *value)
958 if (!value)
959 return config_error_nonbool(var);
960 free(*dest);
961 *dest = xstrdup(value);
962 return 0;
965 static int populate_opts_cb(const char *key, const char *value, void *data)
967 struct replay_opts *opts = data;
968 int error_flag = 1;
970 if (!value)
971 error_flag = 0;
972 else if (!strcmp(key, "options.no-commit"))
973 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
974 else if (!strcmp(key, "options.edit"))
975 opts->edit = git_config_bool_or_int(key, value, &error_flag);
976 else if (!strcmp(key, "options.signoff"))
977 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
978 else if (!strcmp(key, "options.record-origin"))
979 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
980 else if (!strcmp(key, "options.allow-ff"))
981 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
982 else if (!strcmp(key, "options.mainline"))
983 opts->mainline = git_config_int(key, value);
984 else if (!strcmp(key, "options.strategy"))
985 git_config_string_dup(&opts->strategy, key, value);
986 else if (!strcmp(key, "options.gpg-sign"))
987 git_config_string_dup(&opts->gpg_sign, key, value);
988 else if (!strcmp(key, "options.strategy-option")) {
989 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
990 opts->xopts[opts->xopts_nr++] = xstrdup(value);
991 } else
992 return error(_("invalid key: %s"), key);
994 if (!error_flag)
995 return error(_("invalid value for %s: %s"), key, value);
997 return 0;
1000 static int read_populate_opts(struct replay_opts *opts)
1002 if (is_rebase_i(opts)) {
1003 struct strbuf buf = STRBUF_INIT;
1005 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1006 if (!starts_with(buf.buf, "-S"))
1007 strbuf_reset(&buf);
1008 else {
1009 free(opts->gpg_sign);
1010 opts->gpg_sign = xstrdup(buf.buf + 2);
1013 strbuf_release(&buf);
1015 return 0;
1018 if (!file_exists(git_path_opts_file()))
1019 return 0;
1021 * The function git_parse_source(), called from git_config_from_file(),
1022 * may die() in case of a syntactically incorrect file. We do not care
1023 * about this case, though, because we wrote that file ourselves, so we
1024 * are pretty certain that it is syntactically correct.
1026 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1027 return error(_("malformed options sheet: '%s'"),
1028 git_path_opts_file());
1029 return 0;
1032 static int walk_revs_populate_todo(struct todo_list *todo_list,
1033 struct replay_opts *opts)
1035 enum todo_command command = opts->action == REPLAY_PICK ?
1036 TODO_PICK : TODO_REVERT;
1037 const char *command_string = todo_command_strings[command];
1038 struct commit *commit;
1040 if (prepare_revs(opts))
1041 return -1;
1043 while ((commit = get_revision(opts->revs))) {
1044 struct todo_item *item = append_new_todo(todo_list);
1045 const char *commit_buffer = get_commit_buffer(commit, NULL);
1046 const char *subject;
1047 int subject_len;
1049 item->command = command;
1050 item->commit = commit;
1051 item->arg = NULL;
1052 item->arg_len = 0;
1053 item->offset_in_buf = todo_list->buf.len;
1054 subject_len = find_commit_subject(commit_buffer, &subject);
1055 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1056 short_commit_name(commit), subject_len, subject);
1057 unuse_commit_buffer(commit, commit_buffer);
1059 return 0;
1062 static int create_seq_dir(void)
1064 if (file_exists(git_path_seq_dir())) {
1065 error(_("a cherry-pick or revert is already in progress"));
1066 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1067 return -1;
1068 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1069 return error_errno(_("could not create sequencer directory '%s'"),
1070 git_path_seq_dir());
1071 return 0;
1074 static int save_head(const char *head)
1076 static struct lock_file head_lock;
1077 struct strbuf buf = STRBUF_INIT;
1078 int fd;
1080 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1081 if (fd < 0) {
1082 rollback_lock_file(&head_lock);
1083 return error_errno(_("could not lock HEAD"));
1085 strbuf_addf(&buf, "%s\n", head);
1086 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1087 rollback_lock_file(&head_lock);
1088 return error_errno(_("could not write to '%s'"),
1089 git_path_head_file());
1091 if (commit_lock_file(&head_lock) < 0) {
1092 rollback_lock_file(&head_lock);
1093 return error(_("failed to finalize '%s'."), git_path_head_file());
1095 return 0;
1098 static int rollback_is_safe(void)
1100 struct strbuf sb = STRBUF_INIT;
1101 struct object_id expected_head, actual_head;
1103 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1104 strbuf_trim(&sb);
1105 if (get_oid_hex(sb.buf, &expected_head)) {
1106 strbuf_release(&sb);
1107 die(_("could not parse %s"), git_path_abort_safety_file());
1109 strbuf_release(&sb);
1111 else if (errno == ENOENT)
1112 oidclr(&expected_head);
1113 else
1114 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1116 if (get_oid("HEAD", &actual_head))
1117 oidclr(&actual_head);
1119 return !oidcmp(&actual_head, &expected_head);
1122 static int reset_for_rollback(const unsigned char *sha1)
1124 const char *argv[4]; /* reset --merge <arg> + NULL */
1126 argv[0] = "reset";
1127 argv[1] = "--merge";
1128 argv[2] = sha1_to_hex(sha1);
1129 argv[3] = NULL;
1130 return run_command_v_opt(argv, RUN_GIT_CMD);
1133 static int rollback_single_pick(void)
1135 unsigned char head_sha1[20];
1137 if (!file_exists(git_path_cherry_pick_head()) &&
1138 !file_exists(git_path_revert_head()))
1139 return error(_("no cherry-pick or revert in progress"));
1140 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1141 return error(_("cannot resolve HEAD"));
1142 if (is_null_sha1(head_sha1))
1143 return error(_("cannot abort from a branch yet to be born"));
1144 return reset_for_rollback(head_sha1);
1147 int sequencer_rollback(struct replay_opts *opts)
1149 FILE *f;
1150 unsigned char sha1[20];
1151 struct strbuf buf = STRBUF_INIT;
1153 f = fopen(git_path_head_file(), "r");
1154 if (!f && errno == ENOENT) {
1156 * There is no multiple-cherry-pick in progress.
1157 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1158 * a single-cherry-pick in progress, abort that.
1160 return rollback_single_pick();
1162 if (!f)
1163 return error_errno(_("cannot open '%s'"), git_path_head_file());
1164 if (strbuf_getline_lf(&buf, f)) {
1165 error(_("cannot read '%s': %s"), git_path_head_file(),
1166 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1167 fclose(f);
1168 goto fail;
1170 fclose(f);
1171 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1172 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1173 git_path_head_file());
1174 goto fail;
1176 if (is_null_sha1(sha1)) {
1177 error(_("cannot abort from a branch yet to be born"));
1178 goto fail;
1181 if (!rollback_is_safe()) {
1182 /* Do not error, just do not rollback */
1183 warning(_("You seem to have moved HEAD. "
1184 "Not rewinding, check your HEAD!"));
1185 } else
1186 if (reset_for_rollback(sha1))
1187 goto fail;
1188 strbuf_release(&buf);
1189 return sequencer_remove_state(opts);
1190 fail:
1191 strbuf_release(&buf);
1192 return -1;
1195 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1197 static struct lock_file todo_lock;
1198 const char *todo_path = get_todo_path(opts);
1199 int next = todo_list->current, offset, fd;
1201 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1202 if (fd < 0)
1203 return error_errno(_("could not lock '%s'"), todo_path);
1204 offset = next < todo_list->nr ?
1205 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1206 if (write_in_full(fd, todo_list->buf.buf + offset,
1207 todo_list->buf.len - offset) < 0)
1208 return error_errno(_("could not write to '%s'"), todo_path);
1209 if (commit_lock_file(&todo_lock) < 0)
1210 return error(_("failed to finalize '%s'."), todo_path);
1211 return 0;
1214 static int save_opts(struct replay_opts *opts)
1216 const char *opts_file = git_path_opts_file();
1217 int res = 0;
1219 if (opts->no_commit)
1220 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1221 if (opts->edit)
1222 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1223 if (opts->signoff)
1224 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1225 if (opts->record_origin)
1226 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1227 if (opts->allow_ff)
1228 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1229 if (opts->mainline) {
1230 struct strbuf buf = STRBUF_INIT;
1231 strbuf_addf(&buf, "%d", opts->mainline);
1232 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1233 strbuf_release(&buf);
1235 if (opts->strategy)
1236 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1237 if (opts->gpg_sign)
1238 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1239 if (opts->xopts) {
1240 int i;
1241 for (i = 0; i < opts->xopts_nr; i++)
1242 res |= git_config_set_multivar_in_file_gently(opts_file,
1243 "options.strategy-option",
1244 opts->xopts[i], "^$", 0);
1246 return res;
1249 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1251 int res;
1253 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1254 if (opts->allow_ff)
1255 assert(!(opts->signoff || opts->no_commit ||
1256 opts->record_origin || opts->edit));
1257 if (read_and_refresh_cache(opts))
1258 return -1;
1260 while (todo_list->current < todo_list->nr) {
1261 struct todo_item *item = todo_list->items + todo_list->current;
1262 if (save_todo(todo_list, opts))
1263 return -1;
1264 res = do_pick_commit(item->command, item->commit, opts);
1265 todo_list->current++;
1266 if (res)
1267 return res;
1271 * Sequence of picks finished successfully; cleanup by
1272 * removing the .git/sequencer directory
1274 return sequencer_remove_state(opts);
1277 static int continue_single_pick(void)
1279 const char *argv[] = { "commit", NULL };
1281 if (!file_exists(git_path_cherry_pick_head()) &&
1282 !file_exists(git_path_revert_head()))
1283 return error(_("no cherry-pick or revert in progress"));
1284 return run_command_v_opt(argv, RUN_GIT_CMD);
1287 int sequencer_continue(struct replay_opts *opts)
1289 struct todo_list todo_list = TODO_LIST_INIT;
1290 int res;
1292 if (read_and_refresh_cache(opts))
1293 return -1;
1295 if (!file_exists(get_todo_path(opts)))
1296 return continue_single_pick();
1297 if (read_populate_opts(opts))
1298 return -1;
1299 if ((res = read_populate_todo(&todo_list, opts)))
1300 goto release_todo_list;
1302 /* Verify that the conflict has been resolved */
1303 if (file_exists(git_path_cherry_pick_head()) ||
1304 file_exists(git_path_revert_head())) {
1305 res = continue_single_pick();
1306 if (res)
1307 goto release_todo_list;
1309 if (index_differs_from("HEAD", 0, 0)) {
1310 res = error_dirty_index(opts);
1311 goto release_todo_list;
1313 todo_list.current++;
1314 res = pick_commits(&todo_list, opts);
1315 release_todo_list:
1316 todo_list_release(&todo_list);
1317 return res;
1320 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1322 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1323 return do_pick_commit(opts->action == REPLAY_PICK ?
1324 TODO_PICK : TODO_REVERT, cmit, opts);
1327 int sequencer_pick_revisions(struct replay_opts *opts)
1329 struct todo_list todo_list = TODO_LIST_INIT;
1330 unsigned char sha1[20];
1331 int i, res;
1333 assert(opts->revs);
1334 if (read_and_refresh_cache(opts))
1335 return -1;
1337 for (i = 0; i < opts->revs->pending.nr; i++) {
1338 unsigned char sha1[20];
1339 const char *name = opts->revs->pending.objects[i].name;
1341 /* This happens when using --stdin. */
1342 if (!strlen(name))
1343 continue;
1345 if (!get_sha1(name, sha1)) {
1346 if (!lookup_commit_reference_gently(sha1, 1)) {
1347 enum object_type type = sha1_object_info(sha1, NULL);
1348 return error(_("%s: can't cherry-pick a %s"),
1349 name, typename(type));
1351 } else
1352 return error(_("%s: bad revision"), name);
1356 * If we were called as "git cherry-pick <commit>", just
1357 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1358 * REVERT_HEAD, and don't touch the sequencer state.
1359 * This means it is possible to cherry-pick in the middle
1360 * of a cherry-pick sequence.
1362 if (opts->revs->cmdline.nr == 1 &&
1363 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1364 opts->revs->no_walk &&
1365 !opts->revs->cmdline.rev->flags) {
1366 struct commit *cmit;
1367 if (prepare_revision_walk(opts->revs))
1368 return error(_("revision walk setup failed"));
1369 cmit = get_revision(opts->revs);
1370 if (!cmit || get_revision(opts->revs))
1371 return error("BUG: expected exactly one commit from walk");
1372 return single_pick(cmit, opts);
1376 * Start a new cherry-pick/ revert sequence; but
1377 * first, make sure that an existing one isn't in
1378 * progress
1381 if (walk_revs_populate_todo(&todo_list, opts) ||
1382 create_seq_dir() < 0)
1383 return -1;
1384 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1385 return error(_("can't revert as initial commit"));
1386 if (save_head(sha1_to_hex(sha1)))
1387 return -1;
1388 if (save_opts(opts))
1389 return -1;
1390 update_abort_safety_file();
1391 res = pick_commits(&todo_list, opts);
1392 todo_list_release(&todo_list);
1393 return res;
1396 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1398 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1399 struct strbuf sob = STRBUF_INIT;
1400 int has_footer;
1402 strbuf_addstr(&sob, sign_off_header);
1403 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1404 getenv("GIT_COMMITTER_EMAIL")));
1405 strbuf_addch(&sob, '\n');
1408 * If the whole message buffer is equal to the sob, pretend that we
1409 * found a conforming footer with a matching sob
1411 if (msgbuf->len - ignore_footer == sob.len &&
1412 !strncmp(msgbuf->buf, sob.buf, sob.len))
1413 has_footer = 3;
1414 else
1415 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1417 if (!has_footer) {
1418 const char *append_newlines = NULL;
1419 size_t len = msgbuf->len - ignore_footer;
1421 if (!len) {
1423 * The buffer is completely empty. Leave foom for
1424 * the title and body to be filled in by the user.
1426 append_newlines = "\n\n";
1427 } else if (msgbuf->buf[len - 1] != '\n') {
1429 * Incomplete line. Complete the line and add a
1430 * blank one so that there is an empty line between
1431 * the message body and the sob.
1433 append_newlines = "\n\n";
1434 } else if (len == 1) {
1436 * Buffer contains a single newline. Add another
1437 * so that we leave room for the title and body.
1439 append_newlines = "\n";
1440 } else if (msgbuf->buf[len - 2] != '\n') {
1442 * Buffer ends with a single newline. Add another
1443 * so that there is an empty line between the message
1444 * body and the sob.
1446 append_newlines = "\n";
1447 } /* else, the buffer already ends with two newlines. */
1449 if (append_newlines)
1450 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1451 append_newlines, strlen(append_newlines));
1454 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1455 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1456 sob.buf, sob.len);
1458 strbuf_release(&sob);