sequencer (rebase -i): implement the 'edit' command
[alt-git.git] / sequencer.c
blobb138a3906cf386d3335aba01beadcdb447cd8721
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"
20 #include "log-tree.h"
22 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
24 const char sign_off_header[] = "Signed-off-by: ";
25 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
27 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
29 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
30 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
31 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
32 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
34 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
36 * The file containing rebase commands, comments, and empty lines.
37 * This file is created by "git rebase -i" then edited by the user. As
38 * the lines are processed, they are removed from the front of this
39 * file and written to the tail of 'done'.
41 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
43 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
44 * GIT_AUTHOR_DATE that will be used for the commit that is currently
45 * being rebased.
47 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
49 * When an "edit" rebase command is being processed, the SHA1 of the
50 * commit to be edited is recorded in this file. When "git rebase
51 * --continue" is executed, if there are any staged changes then they
52 * will be amended to the HEAD commit, but only provided the HEAD
53 * commit is still the commit to be edited. When any other rebase
54 * command is processed, this file is deleted.
56 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
58 * When we stop at a given patch via the "edit" command, this file contains
59 * the abbreviated commit name of the corresponding patch.
61 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
63 * The following files are written by git-rebase just after parsing the
64 * command-line (and are only consumed, not modified, by the sequencer).
66 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
68 static inline int is_rebase_i(const struct replay_opts *opts)
70 return opts->action == REPLAY_INTERACTIVE_REBASE;
73 static const char *get_dir(const struct replay_opts *opts)
75 if (is_rebase_i(opts))
76 return rebase_path();
77 return git_path_seq_dir();
80 static const char *get_todo_path(const struct replay_opts *opts)
82 if (is_rebase_i(opts))
83 return rebase_path_todo();
84 return git_path_todo_file();
88 * Returns 0 for non-conforming footer
89 * Returns 1 for conforming footer
90 * Returns 2 when sob exists within conforming footer
91 * Returns 3 when sob exists within conforming footer as last entry
93 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
94 int ignore_footer)
96 struct trailer_info info;
97 int i;
98 int found_sob = 0, found_sob_last = 0;
100 trailer_info_get(&info, sb->buf);
102 if (info.trailer_start == info.trailer_end)
103 return 0;
105 for (i = 0; i < info.trailer_nr; i++)
106 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
107 found_sob = 1;
108 if (i == info.trailer_nr - 1)
109 found_sob_last = 1;
112 trailer_info_release(&info);
114 if (found_sob_last)
115 return 3;
116 if (found_sob)
117 return 2;
118 return 1;
121 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
123 static struct strbuf buf = STRBUF_INIT;
125 strbuf_reset(&buf);
126 if (opts->gpg_sign)
127 sq_quotef(&buf, "-S%s", opts->gpg_sign);
128 return buf.buf;
131 int sequencer_remove_state(struct replay_opts *opts)
133 struct strbuf dir = STRBUF_INIT;
134 int i;
136 free(opts->gpg_sign);
137 free(opts->strategy);
138 for (i = 0; i < opts->xopts_nr; i++)
139 free(opts->xopts[i]);
140 free(opts->xopts);
142 strbuf_addf(&dir, "%s", get_dir(opts));
143 remove_dir_recursively(&dir, 0);
144 strbuf_release(&dir);
146 return 0;
149 static const char *action_name(const struct replay_opts *opts)
151 switch (opts->action) {
152 case REPLAY_REVERT:
153 return N_("revert");
154 case REPLAY_PICK:
155 return N_("cherry-pick");
156 case REPLAY_INTERACTIVE_REBASE:
157 return N_("rebase -i");
159 die(_("Unknown action: %d"), opts->action);
162 struct commit_message {
163 char *parent_label;
164 char *label;
165 char *subject;
166 const char *message;
169 static const char *short_commit_name(struct commit *commit)
171 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
174 static int get_message(struct commit *commit, struct commit_message *out)
176 const char *abbrev, *subject;
177 int subject_len;
179 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
180 abbrev = short_commit_name(commit);
182 subject_len = find_commit_subject(out->message, &subject);
184 out->subject = xmemdupz(subject, subject_len);
185 out->label = xstrfmt("%s... %s", abbrev, out->subject);
186 out->parent_label = xstrfmt("parent of %s", out->label);
188 return 0;
191 static void free_message(struct commit *commit, struct commit_message *msg)
193 free(msg->parent_label);
194 free(msg->label);
195 free(msg->subject);
196 unuse_commit_buffer(commit, msg->message);
199 static void print_advice(int show_hint, struct replay_opts *opts)
201 char *msg = getenv("GIT_CHERRY_PICK_HELP");
203 if (msg) {
204 fprintf(stderr, "%s\n", msg);
206 * A conflict has occurred but the porcelain
207 * (typically rebase --interactive) wants to take care
208 * of the commit itself so remove CHERRY_PICK_HEAD
210 unlink(git_path_cherry_pick_head());
211 return;
214 if (show_hint) {
215 if (opts->no_commit)
216 advise(_("after resolving the conflicts, mark the corrected paths\n"
217 "with 'git add <paths>' or 'git rm <paths>'"));
218 else
219 advise(_("after resolving the conflicts, mark the corrected paths\n"
220 "with 'git add <paths>' or 'git rm <paths>'\n"
221 "and commit the result with 'git commit'"));
225 static int write_message(const void *buf, size_t len, const char *filename,
226 int append_eol)
228 static struct lock_file msg_file;
230 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
231 if (msg_fd < 0)
232 return error_errno(_("could not lock '%s'"), filename);
233 if (write_in_full(msg_fd, buf, len) < 0) {
234 rollback_lock_file(&msg_file);
235 return error_errno(_("could not write to '%s'"), filename);
237 if (append_eol && write(msg_fd, "\n", 1) < 0) {
238 rollback_lock_file(&msg_file);
239 return error_errno(_("could not write eol to '%s'"), filename);
241 if (commit_lock_file(&msg_file) < 0) {
242 rollback_lock_file(&msg_file);
243 return error(_("failed to finalize '%s'."), filename);
246 return 0;
250 * Reads a file that was presumably written by a shell script, i.e. with an
251 * end-of-line marker that needs to be stripped.
253 * Note that only the last end-of-line marker is stripped, consistent with the
254 * behavior of "$(cat path)" in a shell script.
256 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
258 static int read_oneliner(struct strbuf *buf,
259 const char *path, int skip_if_empty)
261 int orig_len = buf->len;
263 if (!file_exists(path))
264 return 0;
266 if (strbuf_read_file(buf, path, 0) < 0) {
267 warning_errno(_("could not read '%s'"), path);
268 return 0;
271 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
272 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
273 --buf->len;
274 buf->buf[buf->len] = '\0';
277 if (skip_if_empty && buf->len == orig_len)
278 return 0;
280 return 1;
283 static struct tree *empty_tree(void)
285 return lookup_tree(EMPTY_TREE_SHA1_BIN);
288 static int error_dirty_index(struct replay_opts *opts)
290 if (read_cache_unmerged())
291 return error_resolve_conflict(_(action_name(opts)));
293 error(_("your local changes would be overwritten by %s."),
294 _(action_name(opts)));
296 if (advice_commit_before_merge)
297 advise(_("commit your changes or stash them to proceed."));
298 return -1;
301 static void update_abort_safety_file(void)
303 struct object_id head;
305 /* Do nothing on a single-pick */
306 if (!file_exists(git_path_seq_dir()))
307 return;
309 if (!get_oid("HEAD", &head))
310 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
311 else
312 write_file(git_path_abort_safety_file(), "%s", "");
315 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
316 int unborn, struct replay_opts *opts)
318 struct ref_transaction *transaction;
319 struct strbuf sb = STRBUF_INIT;
320 struct strbuf err = STRBUF_INIT;
322 read_cache();
323 if (checkout_fast_forward(from, to, 1))
324 return -1; /* the callee should have complained already */
326 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
328 transaction = ref_transaction_begin(&err);
329 if (!transaction ||
330 ref_transaction_update(transaction, "HEAD",
331 to, unborn ? null_sha1 : from,
332 0, sb.buf, &err) ||
333 ref_transaction_commit(transaction, &err)) {
334 ref_transaction_free(transaction);
335 error("%s", err.buf);
336 strbuf_release(&sb);
337 strbuf_release(&err);
338 return -1;
341 strbuf_release(&sb);
342 strbuf_release(&err);
343 ref_transaction_free(transaction);
344 update_abort_safety_file();
345 return 0;
348 void append_conflicts_hint(struct strbuf *msgbuf)
350 int i;
352 strbuf_addch(msgbuf, '\n');
353 strbuf_commented_addf(msgbuf, "Conflicts:\n");
354 for (i = 0; i < active_nr;) {
355 const struct cache_entry *ce = active_cache[i++];
356 if (ce_stage(ce)) {
357 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
358 while (i < active_nr && !strcmp(ce->name,
359 active_cache[i]->name))
360 i++;
365 static int do_recursive_merge(struct commit *base, struct commit *next,
366 const char *base_label, const char *next_label,
367 unsigned char *head, struct strbuf *msgbuf,
368 struct replay_opts *opts)
370 struct merge_options o;
371 struct tree *result, *next_tree, *base_tree, *head_tree;
372 int clean;
373 char **xopt;
374 static struct lock_file index_lock;
376 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
378 read_cache();
380 init_merge_options(&o);
381 o.ancestor = base ? base_label : "(empty tree)";
382 o.branch1 = "HEAD";
383 o.branch2 = next ? next_label : "(empty tree)";
385 head_tree = parse_tree_indirect(head);
386 next_tree = next ? next->tree : empty_tree();
387 base_tree = base ? base->tree : empty_tree();
389 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
390 parse_merge_opt(&o, *xopt);
392 clean = merge_trees(&o,
393 head_tree,
394 next_tree, base_tree, &result);
395 strbuf_release(&o.obuf);
396 if (clean < 0)
397 return clean;
399 if (active_cache_changed &&
400 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
401 /* TRANSLATORS: %s will be "revert", "cherry-pick" or
402 * "rebase -i".
404 return error(_("%s: Unable to write new index file"),
405 _(action_name(opts)));
406 rollback_lock_file(&index_lock);
408 if (opts->signoff)
409 append_signoff(msgbuf, 0, 0);
411 if (!clean)
412 append_conflicts_hint(msgbuf);
414 return !clean;
417 static int is_index_unchanged(void)
419 unsigned char head_sha1[20];
420 struct commit *head_commit;
422 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
423 return error(_("could not resolve HEAD commit\n"));
425 head_commit = lookup_commit(head_sha1);
428 * If head_commit is NULL, check_commit, called from
429 * lookup_commit, would have indicated that head_commit is not
430 * a commit object already. parse_commit() will return failure
431 * without further complaints in such a case. Otherwise, if
432 * the commit is invalid, parse_commit() will complain. So
433 * there is nothing for us to say here. Just return failure.
435 if (parse_commit(head_commit))
436 return -1;
438 if (!active_cache_tree)
439 active_cache_tree = cache_tree();
441 if (!cache_tree_fully_valid(active_cache_tree))
442 if (cache_tree_update(&the_index, 0))
443 return error(_("unable to update cache tree\n"));
445 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
449 * Read the author-script file into an environment block, ready for use in
450 * run_command(), that can be free()d afterwards.
452 static char **read_author_script(void)
454 struct strbuf script = STRBUF_INIT;
455 int i, count = 0;
456 char *p, *p2, **env;
457 size_t env_size;
459 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
460 return NULL;
462 for (p = script.buf; *p; p++)
463 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
464 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
465 else if (*p == '\'')
466 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
467 else if (*p == '\n') {
468 *p = '\0';
469 count++;
472 env_size = (count + 1) * sizeof(*env);
473 strbuf_grow(&script, env_size);
474 memmove(script.buf + env_size, script.buf, script.len);
475 p = script.buf + env_size;
476 env = (char **)strbuf_detach(&script, NULL);
478 for (i = 0; i < count; i++) {
479 env[i] = p;
480 p += strlen(p) + 1;
482 env[count] = NULL;
484 return env;
487 static const char staged_changes_advice[] =
488 N_("you have staged changes in your working tree\n"
489 "If these changes are meant to be squashed into the previous commit, run:\n"
490 "\n"
491 " git commit --amend %s\n"
492 "\n"
493 "If they are meant to go into a new commit, run:\n"
494 "\n"
495 " git commit %s\n"
496 "\n"
497 "In both cases, once you're done, continue with:\n"
498 "\n"
499 " git rebase --continue\n");
502 * If we are cherry-pick, and if the merge did not result in
503 * hand-editing, we will hit this commit and inherit the original
504 * author date and name.
506 * If we are revert, or if our cherry-pick results in a hand merge,
507 * we had better say that the current user is responsible for that.
509 * An exception is when run_git_commit() is called during an
510 * interactive rebase: in that case, we will want to retain the
511 * author metadata.
513 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
514 int allow_empty, int edit, int amend,
515 int cleanup_commit_message)
517 char **env = NULL;
518 struct argv_array array;
519 int rc;
520 const char *value;
522 if (is_rebase_i(opts)) {
523 env = read_author_script();
524 if (!env) {
525 const char *gpg_opt = gpg_sign_opt_quoted(opts);
527 return error(_(staged_changes_advice),
528 gpg_opt, gpg_opt);
532 argv_array_init(&array);
533 argv_array_push(&array, "commit");
534 argv_array_push(&array, "-n");
536 if (amend)
537 argv_array_push(&array, "--amend");
538 if (opts->gpg_sign)
539 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
540 if (opts->signoff)
541 argv_array_push(&array, "-s");
542 if (defmsg)
543 argv_array_pushl(&array, "-F", defmsg, NULL);
544 if (cleanup_commit_message)
545 argv_array_push(&array, "--cleanup=strip");
546 if (edit)
547 argv_array_push(&array, "-e");
548 else if (!cleanup_commit_message &&
549 !opts->signoff && !opts->record_origin &&
550 git_config_get_value("commit.cleanup", &value))
551 argv_array_push(&array, "--cleanup=verbatim");
553 if (allow_empty)
554 argv_array_push(&array, "--allow-empty");
556 if (opts->allow_empty_message)
557 argv_array_push(&array, "--allow-empty-message");
559 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
560 (const char *const *)env);
561 argv_array_clear(&array);
562 free(env);
564 return rc;
567 static int is_original_commit_empty(struct commit *commit)
569 const unsigned char *ptree_sha1;
571 if (parse_commit(commit))
572 return error(_("could not parse commit %s\n"),
573 oid_to_hex(&commit->object.oid));
574 if (commit->parents) {
575 struct commit *parent = commit->parents->item;
576 if (parse_commit(parent))
577 return error(_("could not parse parent commit %s\n"),
578 oid_to_hex(&parent->object.oid));
579 ptree_sha1 = parent->tree->object.oid.hash;
580 } else {
581 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
584 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
588 * Do we run "git commit" with "--allow-empty"?
590 static int allow_empty(struct replay_opts *opts, struct commit *commit)
592 int index_unchanged, empty_commit;
595 * Three cases:
597 * (1) we do not allow empty at all and error out.
599 * (2) we allow ones that were initially empty, but
600 * forbid the ones that become empty;
602 * (3) we allow both.
604 if (!opts->allow_empty)
605 return 0; /* let "git commit" barf as necessary */
607 index_unchanged = is_index_unchanged();
608 if (index_unchanged < 0)
609 return index_unchanged;
610 if (!index_unchanged)
611 return 0; /* we do not have to say --allow-empty */
613 if (opts->keep_redundant_commits)
614 return 1;
616 empty_commit = is_original_commit_empty(commit);
617 if (empty_commit < 0)
618 return empty_commit;
619 if (!empty_commit)
620 return 0;
621 else
622 return 1;
626 * Note that ordering matters in this enum. Not only must it match the mapping
627 * below, it is also divided into several sections that matter. When adding
628 * new commands, make sure you add it in the right section.
630 enum todo_command {
631 /* commands that handle commits */
632 TODO_PICK = 0,
633 TODO_REVERT,
634 TODO_EDIT,
635 /* commands that do nothing but are counted for reporting progress */
636 TODO_NOOP
639 static const char *todo_command_strings[] = {
640 "pick",
641 "revert",
642 "edit",
643 "noop"
646 static const char *command_to_string(const enum todo_command command)
648 if ((size_t)command < ARRAY_SIZE(todo_command_strings))
649 return todo_command_strings[command];
650 die("Unknown command: %d", command);
653 static int is_noop(const enum todo_command command)
655 return TODO_NOOP <= (size_t)command;
658 static int do_pick_commit(enum todo_command command, struct commit *commit,
659 struct replay_opts *opts)
661 unsigned char head[20];
662 struct commit *base, *next, *parent;
663 const char *base_label, *next_label;
664 struct commit_message msg = { NULL, NULL, NULL, NULL };
665 struct strbuf msgbuf = STRBUF_INIT;
666 int res, unborn = 0, allow;
668 if (opts->no_commit) {
670 * We do not intend to commit immediately. We just want to
671 * merge the differences in, so let's compute the tree
672 * that represents the "current" state for merge-recursive
673 * to work on.
675 if (write_cache_as_tree(head, 0, NULL))
676 return error(_("your index file is unmerged."));
677 } else {
678 unborn = get_sha1("HEAD", head);
679 if (unborn)
680 hashcpy(head, EMPTY_TREE_SHA1_BIN);
681 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
682 return error_dirty_index(opts);
684 discard_cache();
686 if (!commit->parents)
687 parent = NULL;
688 else if (commit->parents->next) {
689 /* Reverting or cherry-picking a merge commit */
690 int cnt;
691 struct commit_list *p;
693 if (!opts->mainline)
694 return error(_("commit %s is a merge but no -m option was given."),
695 oid_to_hex(&commit->object.oid));
697 for (cnt = 1, p = commit->parents;
698 cnt != opts->mainline && p;
699 cnt++)
700 p = p->next;
701 if (cnt != opts->mainline || !p)
702 return error(_("commit %s does not have parent %d"),
703 oid_to_hex(&commit->object.oid), opts->mainline);
704 parent = p->item;
705 } else if (0 < opts->mainline)
706 return error(_("mainline was specified but commit %s is not a merge."),
707 oid_to_hex(&commit->object.oid));
708 else
709 parent = commit->parents->item;
711 if (opts->allow_ff &&
712 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
713 (!parent && unborn)))
714 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
716 if (parent && parse_commit(parent) < 0)
717 /* TRANSLATORS: The first %s will be a "todo" command like
718 "revert" or "pick", the second %s a SHA1. */
719 return error(_("%s: cannot parse parent commit %s"),
720 command_to_string(command),
721 oid_to_hex(&parent->object.oid));
723 if (get_message(commit, &msg) != 0)
724 return error(_("cannot get commit message for %s"),
725 oid_to_hex(&commit->object.oid));
728 * "commit" is an existing commit. We would want to apply
729 * the difference it introduces since its first parent "prev"
730 * on top of the current HEAD if we are cherry-pick. Or the
731 * reverse of it if we are revert.
734 if (command == TODO_REVERT) {
735 base = commit;
736 base_label = msg.label;
737 next = parent;
738 next_label = msg.parent_label;
739 strbuf_addstr(&msgbuf, "Revert \"");
740 strbuf_addstr(&msgbuf, msg.subject);
741 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
742 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
744 if (commit->parents && commit->parents->next) {
745 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
746 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
748 strbuf_addstr(&msgbuf, ".\n");
749 } else {
750 const char *p;
752 base = parent;
753 base_label = msg.parent_label;
754 next = commit;
755 next_label = msg.label;
757 /* Append the commit log message to msgbuf. */
758 if (find_commit_subject(msg.message, &p))
759 strbuf_addstr(&msgbuf, p);
761 if (opts->record_origin) {
762 if (!has_conforming_footer(&msgbuf, NULL, 0))
763 strbuf_addch(&msgbuf, '\n');
764 strbuf_addstr(&msgbuf, cherry_picked_prefix);
765 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
766 strbuf_addstr(&msgbuf, ")\n");
770 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
771 res = do_recursive_merge(base, next, base_label, next_label,
772 head, &msgbuf, opts);
773 if (res < 0)
774 return res;
775 res |= write_message(msgbuf.buf, msgbuf.len,
776 git_path_merge_msg(), 0);
777 } else {
778 struct commit_list *common = NULL;
779 struct commit_list *remotes = NULL;
781 res = write_message(msgbuf.buf, msgbuf.len,
782 git_path_merge_msg(), 0);
784 commit_list_insert(base, &common);
785 commit_list_insert(next, &remotes);
786 res |= try_merge_command(opts->strategy,
787 opts->xopts_nr, (const char **)opts->xopts,
788 common, sha1_to_hex(head), remotes);
789 free_commit_list(common);
790 free_commit_list(remotes);
792 strbuf_release(&msgbuf);
795 * If the merge was clean or if it failed due to conflict, we write
796 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
797 * However, if the merge did not even start, then we don't want to
798 * write it at all.
800 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
801 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
802 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
803 res = -1;
804 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
805 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
806 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
807 res = -1;
809 if (res) {
810 error(command == TODO_REVERT
811 ? _("could not revert %s... %s")
812 : _("could not apply %s... %s"),
813 short_commit_name(commit), msg.subject);
814 print_advice(res == 1, opts);
815 rerere(opts->allow_rerere_auto);
816 goto leave;
819 allow = allow_empty(opts, commit);
820 if (allow < 0) {
821 res = allow;
822 goto leave;
824 if (!opts->no_commit)
825 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
826 opts, allow, opts->edit, 0, 0);
828 leave:
829 free_message(commit, &msg);
830 update_abort_safety_file();
832 return res;
835 static int prepare_revs(struct replay_opts *opts)
838 * picking (but not reverting) ranges (but not individual revisions)
839 * should be done in reverse
841 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
842 opts->revs->reverse ^= 1;
844 if (prepare_revision_walk(opts->revs))
845 return error(_("revision walk setup failed"));
847 if (!opts->revs->commits)
848 return error(_("empty commit set passed"));
849 return 0;
852 static int read_and_refresh_cache(struct replay_opts *opts)
854 static struct lock_file index_lock;
855 int index_fd = hold_locked_index(&index_lock, 0);
856 if (read_index_preload(&the_index, NULL) < 0) {
857 rollback_lock_file(&index_lock);
858 return error(_("git %s: failed to read the index"),
859 _(action_name(opts)));
861 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
862 if (the_index.cache_changed && index_fd >= 0) {
863 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
864 rollback_lock_file(&index_lock);
865 return error(_("git %s: failed to refresh the index"),
866 _(action_name(opts)));
869 rollback_lock_file(&index_lock);
870 return 0;
873 struct todo_item {
874 enum todo_command command;
875 struct commit *commit;
876 const char *arg;
877 int arg_len;
878 size_t offset_in_buf;
881 struct todo_list {
882 struct strbuf buf;
883 struct todo_item *items;
884 int nr, alloc, current;
887 #define TODO_LIST_INIT { STRBUF_INIT }
889 static void todo_list_release(struct todo_list *todo_list)
891 strbuf_release(&todo_list->buf);
892 free(todo_list->items);
893 todo_list->items = NULL;
894 todo_list->nr = todo_list->alloc = 0;
897 static struct todo_item *append_new_todo(struct todo_list *todo_list)
899 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
900 return todo_list->items + todo_list->nr++;
903 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
905 unsigned char commit_sha1[20];
906 char *end_of_object_name;
907 int i, saved, status, padding;
909 /* left-trim */
910 bol += strspn(bol, " \t");
912 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
913 item->command = TODO_NOOP;
914 item->commit = NULL;
915 item->arg = bol;
916 item->arg_len = eol - bol;
917 return 0;
920 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
921 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
922 item->command = i;
923 break;
925 if (i >= ARRAY_SIZE(todo_command_strings))
926 return -1;
928 if (item->command == TODO_NOOP) {
929 item->commit = NULL;
930 item->arg = bol;
931 item->arg_len = eol - bol;
932 return 0;
935 /* Eat up extra spaces/ tabs before object name */
936 padding = strspn(bol, " \t");
937 if (!padding)
938 return -1;
939 bol += padding;
941 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
942 saved = *end_of_object_name;
943 *end_of_object_name = '\0';
944 status = get_sha1(bol, commit_sha1);
945 *end_of_object_name = saved;
947 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
948 item->arg_len = (int)(eol - item->arg);
950 if (status < 0)
951 return -1;
953 item->commit = lookup_commit_reference(commit_sha1);
954 return !item->commit;
957 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
959 struct todo_item *item;
960 char *p = buf, *next_p;
961 int i, res = 0;
963 for (i = 1; *p; i++, p = next_p) {
964 char *eol = strchrnul(p, '\n');
966 next_p = *eol ? eol + 1 /* skip LF */ : eol;
968 if (p != eol && eol[-1] == '\r')
969 eol--; /* strip Carriage Return */
971 item = append_new_todo(todo_list);
972 item->offset_in_buf = p - todo_list->buf.buf;
973 if (parse_insn_line(item, p, eol)) {
974 res = error(_("invalid line %d: %.*s"),
975 i, (int)(eol - p), p);
976 item->command = -1;
979 if (!todo_list->nr)
980 return error(_("no commits parsed."));
981 return res;
984 static int read_populate_todo(struct todo_list *todo_list,
985 struct replay_opts *opts)
987 const char *todo_file = get_todo_path(opts);
988 int fd, res;
990 strbuf_reset(&todo_list->buf);
991 fd = open(todo_file, O_RDONLY);
992 if (fd < 0)
993 return error_errno(_("could not open '%s'"), todo_file);
994 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
995 close(fd);
996 return error(_("could not read '%s'."), todo_file);
998 close(fd);
1000 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1001 if (res)
1002 return error(_("unusable instruction sheet: '%s'"), todo_file);
1004 if (!is_rebase_i(opts)) {
1005 enum todo_command valid =
1006 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1007 int i;
1009 for (i = 0; i < todo_list->nr; i++)
1010 if (valid == todo_list->items[i].command)
1011 continue;
1012 else if (valid == TODO_PICK)
1013 return error(_("cannot cherry-pick during a revert."));
1014 else
1015 return error(_("cannot revert during a cherry-pick."));
1018 return 0;
1021 static int git_config_string_dup(char **dest,
1022 const char *var, const char *value)
1024 if (!value)
1025 return config_error_nonbool(var);
1026 free(*dest);
1027 *dest = xstrdup(value);
1028 return 0;
1031 static int populate_opts_cb(const char *key, const char *value, void *data)
1033 struct replay_opts *opts = data;
1034 int error_flag = 1;
1036 if (!value)
1037 error_flag = 0;
1038 else if (!strcmp(key, "options.no-commit"))
1039 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1040 else if (!strcmp(key, "options.edit"))
1041 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1042 else if (!strcmp(key, "options.signoff"))
1043 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1044 else if (!strcmp(key, "options.record-origin"))
1045 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1046 else if (!strcmp(key, "options.allow-ff"))
1047 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1048 else if (!strcmp(key, "options.mainline"))
1049 opts->mainline = git_config_int(key, value);
1050 else if (!strcmp(key, "options.strategy"))
1051 git_config_string_dup(&opts->strategy, key, value);
1052 else if (!strcmp(key, "options.gpg-sign"))
1053 git_config_string_dup(&opts->gpg_sign, key, value);
1054 else if (!strcmp(key, "options.strategy-option")) {
1055 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1056 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1057 } else
1058 return error(_("invalid key: %s"), key);
1060 if (!error_flag)
1061 return error(_("invalid value for %s: %s"), key, value);
1063 return 0;
1066 static int read_populate_opts(struct replay_opts *opts)
1068 if (is_rebase_i(opts)) {
1069 struct strbuf buf = STRBUF_INIT;
1071 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1072 if (!starts_with(buf.buf, "-S"))
1073 strbuf_reset(&buf);
1074 else {
1075 free(opts->gpg_sign);
1076 opts->gpg_sign = xstrdup(buf.buf + 2);
1079 strbuf_release(&buf);
1081 return 0;
1084 if (!file_exists(git_path_opts_file()))
1085 return 0;
1087 * The function git_parse_source(), called from git_config_from_file(),
1088 * may die() in case of a syntactically incorrect file. We do not care
1089 * about this case, though, because we wrote that file ourselves, so we
1090 * are pretty certain that it is syntactically correct.
1092 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1093 return error(_("malformed options sheet: '%s'"),
1094 git_path_opts_file());
1095 return 0;
1098 static int walk_revs_populate_todo(struct todo_list *todo_list,
1099 struct replay_opts *opts)
1101 enum todo_command command = opts->action == REPLAY_PICK ?
1102 TODO_PICK : TODO_REVERT;
1103 const char *command_string = todo_command_strings[command];
1104 struct commit *commit;
1106 if (prepare_revs(opts))
1107 return -1;
1109 while ((commit = get_revision(opts->revs))) {
1110 struct todo_item *item = append_new_todo(todo_list);
1111 const char *commit_buffer = get_commit_buffer(commit, NULL);
1112 const char *subject;
1113 int subject_len;
1115 item->command = command;
1116 item->commit = commit;
1117 item->arg = NULL;
1118 item->arg_len = 0;
1119 item->offset_in_buf = todo_list->buf.len;
1120 subject_len = find_commit_subject(commit_buffer, &subject);
1121 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1122 short_commit_name(commit), subject_len, subject);
1123 unuse_commit_buffer(commit, commit_buffer);
1125 return 0;
1128 static int create_seq_dir(void)
1130 if (file_exists(git_path_seq_dir())) {
1131 error(_("a cherry-pick or revert is already in progress"));
1132 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1133 return -1;
1134 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1135 return error_errno(_("could not create sequencer directory '%s'"),
1136 git_path_seq_dir());
1137 return 0;
1140 static int save_head(const char *head)
1142 static struct lock_file head_lock;
1143 struct strbuf buf = STRBUF_INIT;
1144 int fd;
1146 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1147 if (fd < 0) {
1148 rollback_lock_file(&head_lock);
1149 return error_errno(_("could not lock HEAD"));
1151 strbuf_addf(&buf, "%s\n", head);
1152 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1153 rollback_lock_file(&head_lock);
1154 return error_errno(_("could not write to '%s'"),
1155 git_path_head_file());
1157 if (commit_lock_file(&head_lock) < 0) {
1158 rollback_lock_file(&head_lock);
1159 return error(_("failed to finalize '%s'."), git_path_head_file());
1161 return 0;
1164 static int rollback_is_safe(void)
1166 struct strbuf sb = STRBUF_INIT;
1167 struct object_id expected_head, actual_head;
1169 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1170 strbuf_trim(&sb);
1171 if (get_oid_hex(sb.buf, &expected_head)) {
1172 strbuf_release(&sb);
1173 die(_("could not parse %s"), git_path_abort_safety_file());
1175 strbuf_release(&sb);
1177 else if (errno == ENOENT)
1178 oidclr(&expected_head);
1179 else
1180 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1182 if (get_oid("HEAD", &actual_head))
1183 oidclr(&actual_head);
1185 return !oidcmp(&actual_head, &expected_head);
1188 static int reset_for_rollback(const unsigned char *sha1)
1190 const char *argv[4]; /* reset --merge <arg> + NULL */
1192 argv[0] = "reset";
1193 argv[1] = "--merge";
1194 argv[2] = sha1_to_hex(sha1);
1195 argv[3] = NULL;
1196 return run_command_v_opt(argv, RUN_GIT_CMD);
1199 static int rollback_single_pick(void)
1201 unsigned char head_sha1[20];
1203 if (!file_exists(git_path_cherry_pick_head()) &&
1204 !file_exists(git_path_revert_head()))
1205 return error(_("no cherry-pick or revert in progress"));
1206 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1207 return error(_("cannot resolve HEAD"));
1208 if (is_null_sha1(head_sha1))
1209 return error(_("cannot abort from a branch yet to be born"));
1210 return reset_for_rollback(head_sha1);
1213 int sequencer_rollback(struct replay_opts *opts)
1215 FILE *f;
1216 unsigned char sha1[20];
1217 struct strbuf buf = STRBUF_INIT;
1219 f = fopen(git_path_head_file(), "r");
1220 if (!f && errno == ENOENT) {
1222 * There is no multiple-cherry-pick in progress.
1223 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1224 * a single-cherry-pick in progress, abort that.
1226 return rollback_single_pick();
1228 if (!f)
1229 return error_errno(_("cannot open '%s'"), git_path_head_file());
1230 if (strbuf_getline_lf(&buf, f)) {
1231 error(_("cannot read '%s': %s"), git_path_head_file(),
1232 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1233 fclose(f);
1234 goto fail;
1236 fclose(f);
1237 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1238 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1239 git_path_head_file());
1240 goto fail;
1242 if (is_null_sha1(sha1)) {
1243 error(_("cannot abort from a branch yet to be born"));
1244 goto fail;
1247 if (!rollback_is_safe()) {
1248 /* Do not error, just do not rollback */
1249 warning(_("You seem to have moved HEAD. "
1250 "Not rewinding, check your HEAD!"));
1251 } else
1252 if (reset_for_rollback(sha1))
1253 goto fail;
1254 strbuf_release(&buf);
1255 return sequencer_remove_state(opts);
1256 fail:
1257 strbuf_release(&buf);
1258 return -1;
1261 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1263 static struct lock_file todo_lock;
1264 const char *todo_path = get_todo_path(opts);
1265 int next = todo_list->current, offset, fd;
1268 * rebase -i writes "git-rebase-todo" without the currently executing
1269 * command, appending it to "done" instead.
1271 if (is_rebase_i(opts))
1272 next++;
1274 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1275 if (fd < 0)
1276 return error_errno(_("could not lock '%s'"), todo_path);
1277 offset = next < todo_list->nr ?
1278 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1279 if (write_in_full(fd, todo_list->buf.buf + offset,
1280 todo_list->buf.len - offset) < 0)
1281 return error_errno(_("could not write to '%s'"), todo_path);
1282 if (commit_lock_file(&todo_lock) < 0)
1283 return error(_("failed to finalize '%s'."), todo_path);
1284 return 0;
1287 static int save_opts(struct replay_opts *opts)
1289 const char *opts_file = git_path_opts_file();
1290 int res = 0;
1292 if (opts->no_commit)
1293 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1294 if (opts->edit)
1295 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1296 if (opts->signoff)
1297 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1298 if (opts->record_origin)
1299 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1300 if (opts->allow_ff)
1301 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1302 if (opts->mainline) {
1303 struct strbuf buf = STRBUF_INIT;
1304 strbuf_addf(&buf, "%d", opts->mainline);
1305 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1306 strbuf_release(&buf);
1308 if (opts->strategy)
1309 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1310 if (opts->gpg_sign)
1311 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1312 if (opts->xopts) {
1313 int i;
1314 for (i = 0; i < opts->xopts_nr; i++)
1315 res |= git_config_set_multivar_in_file_gently(opts_file,
1316 "options.strategy-option",
1317 opts->xopts[i], "^$", 0);
1319 return res;
1322 static int make_patch(struct commit *commit, struct replay_opts *opts)
1324 struct strbuf buf = STRBUF_INIT;
1325 struct rev_info log_tree_opt;
1326 const char *subject, *p;
1327 int res = 0;
1329 p = short_commit_name(commit);
1330 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1331 return -1;
1333 strbuf_addf(&buf, "%s/patch", get_dir(opts));
1334 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1335 init_revisions(&log_tree_opt, NULL);
1336 log_tree_opt.abbrev = 0;
1337 log_tree_opt.diff = 1;
1338 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1339 log_tree_opt.disable_stdin = 1;
1340 log_tree_opt.no_commit_id = 1;
1341 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1342 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1343 if (!log_tree_opt.diffopt.file)
1344 res |= error_errno(_("could not open '%s'"), buf.buf);
1345 else {
1346 res |= log_tree_commit(&log_tree_opt, commit);
1347 fclose(log_tree_opt.diffopt.file);
1349 strbuf_reset(&buf);
1351 strbuf_addf(&buf, "%s/message", get_dir(opts));
1352 if (!file_exists(buf.buf)) {
1353 const char *commit_buffer = get_commit_buffer(commit, NULL);
1354 find_commit_subject(commit_buffer, &subject);
1355 res |= write_message(subject, strlen(subject), buf.buf, 1);
1356 unuse_commit_buffer(commit, commit_buffer);
1358 strbuf_release(&buf);
1360 return res;
1363 static int intend_to_amend(void)
1365 unsigned char head[20];
1366 char *p;
1368 if (get_sha1("HEAD", head))
1369 return error(_("cannot read HEAD"));
1371 p = sha1_to_hex(head);
1372 return write_message(p, strlen(p), rebase_path_amend(), 1);
1375 static int error_with_patch(struct commit *commit,
1376 const char *subject, int subject_len,
1377 struct replay_opts *opts, int exit_code, int to_amend)
1379 if (make_patch(commit, opts))
1380 return -1;
1382 if (to_amend) {
1383 if (intend_to_amend())
1384 return -1;
1386 fprintf(stderr, "You can amend the commit now, with\n"
1387 "\n"
1388 " git commit --amend %s\n"
1389 "\n"
1390 "Once you are satisfied with your changes, run\n"
1391 "\n"
1392 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
1393 } else if (exit_code)
1394 fprintf(stderr, "Could not apply %s... %.*s\n",
1395 short_commit_name(commit), subject_len, subject);
1397 return exit_code;
1400 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1402 int res = 0;
1404 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1405 if (opts->allow_ff)
1406 assert(!(opts->signoff || opts->no_commit ||
1407 opts->record_origin || opts->edit));
1408 if (read_and_refresh_cache(opts))
1409 return -1;
1411 while (todo_list->current < todo_list->nr) {
1412 struct todo_item *item = todo_list->items + todo_list->current;
1413 if (save_todo(todo_list, opts))
1414 return -1;
1415 if (item->command <= TODO_EDIT) {
1416 res = do_pick_commit(item->command, item->commit,
1417 opts);
1418 if (item->command == TODO_EDIT) {
1419 struct commit *commit = item->commit;
1420 if (!res)
1421 warning(_("stopped at %s... %.*s"),
1422 short_commit_name(commit),
1423 item->arg_len, item->arg);
1424 return error_with_patch(commit,
1425 item->arg, item->arg_len, opts, res,
1426 !res);
1428 } else if (!is_noop(item->command))
1429 return error(_("unknown command %d"), item->command);
1431 todo_list->current++;
1432 if (res)
1433 return res;
1436 if (is_rebase_i(opts)) {
1437 /* Stopped in the middle, as planned? */
1438 if (todo_list->current < todo_list->nr)
1439 return 0;
1443 * Sequence of picks finished successfully; cleanup by
1444 * removing the .git/sequencer directory
1446 return sequencer_remove_state(opts);
1449 static int continue_single_pick(void)
1451 const char *argv[] = { "commit", NULL };
1453 if (!file_exists(git_path_cherry_pick_head()) &&
1454 !file_exists(git_path_revert_head()))
1455 return error(_("no cherry-pick or revert in progress"));
1456 return run_command_v_opt(argv, RUN_GIT_CMD);
1459 int sequencer_continue(struct replay_opts *opts)
1461 struct todo_list todo_list = TODO_LIST_INIT;
1462 int res;
1464 if (read_and_refresh_cache(opts))
1465 return -1;
1467 if (!file_exists(get_todo_path(opts)))
1468 return continue_single_pick();
1469 if (read_populate_opts(opts))
1470 return -1;
1471 if ((res = read_populate_todo(&todo_list, opts)))
1472 goto release_todo_list;
1474 /* Verify that the conflict has been resolved */
1475 if (file_exists(git_path_cherry_pick_head()) ||
1476 file_exists(git_path_revert_head())) {
1477 res = continue_single_pick();
1478 if (res)
1479 goto release_todo_list;
1481 if (index_differs_from("HEAD", 0, 0)) {
1482 res = error_dirty_index(opts);
1483 goto release_todo_list;
1485 todo_list.current++;
1486 res = pick_commits(&todo_list, opts);
1487 release_todo_list:
1488 todo_list_release(&todo_list);
1489 return res;
1492 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1494 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1495 return do_pick_commit(opts->action == REPLAY_PICK ?
1496 TODO_PICK : TODO_REVERT, cmit, opts);
1499 int sequencer_pick_revisions(struct replay_opts *opts)
1501 struct todo_list todo_list = TODO_LIST_INIT;
1502 unsigned char sha1[20];
1503 int i, res;
1505 assert(opts->revs);
1506 if (read_and_refresh_cache(opts))
1507 return -1;
1509 for (i = 0; i < opts->revs->pending.nr; i++) {
1510 unsigned char sha1[20];
1511 const char *name = opts->revs->pending.objects[i].name;
1513 /* This happens when using --stdin. */
1514 if (!strlen(name))
1515 continue;
1517 if (!get_sha1(name, sha1)) {
1518 if (!lookup_commit_reference_gently(sha1, 1)) {
1519 enum object_type type = sha1_object_info(sha1, NULL);
1520 return error(_("%s: can't cherry-pick a %s"),
1521 name, typename(type));
1523 } else
1524 return error(_("%s: bad revision"), name);
1528 * If we were called as "git cherry-pick <commit>", just
1529 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1530 * REVERT_HEAD, and don't touch the sequencer state.
1531 * This means it is possible to cherry-pick in the middle
1532 * of a cherry-pick sequence.
1534 if (opts->revs->cmdline.nr == 1 &&
1535 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1536 opts->revs->no_walk &&
1537 !opts->revs->cmdline.rev->flags) {
1538 struct commit *cmit;
1539 if (prepare_revision_walk(opts->revs))
1540 return error(_("revision walk setup failed"));
1541 cmit = get_revision(opts->revs);
1542 if (!cmit || get_revision(opts->revs))
1543 return error("BUG: expected exactly one commit from walk");
1544 return single_pick(cmit, opts);
1548 * Start a new cherry-pick/ revert sequence; but
1549 * first, make sure that an existing one isn't in
1550 * progress
1553 if (walk_revs_populate_todo(&todo_list, opts) ||
1554 create_seq_dir() < 0)
1555 return -1;
1556 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1557 return error(_("can't revert as initial commit"));
1558 if (save_head(sha1_to_hex(sha1)))
1559 return -1;
1560 if (save_opts(opts))
1561 return -1;
1562 update_abort_safety_file();
1563 res = pick_commits(&todo_list, opts);
1564 todo_list_release(&todo_list);
1565 return res;
1568 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1570 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1571 struct strbuf sob = STRBUF_INIT;
1572 int has_footer;
1574 strbuf_addstr(&sob, sign_off_header);
1575 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1576 getenv("GIT_COMMITTER_EMAIL")));
1577 strbuf_addch(&sob, '\n');
1580 * If the whole message buffer is equal to the sob, pretend that we
1581 * found a conforming footer with a matching sob
1583 if (msgbuf->len - ignore_footer == sob.len &&
1584 !strncmp(msgbuf->buf, sob.buf, sob.len))
1585 has_footer = 3;
1586 else
1587 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1589 if (!has_footer) {
1590 const char *append_newlines = NULL;
1591 size_t len = msgbuf->len - ignore_footer;
1593 if (!len) {
1595 * The buffer is completely empty. Leave foom for
1596 * the title and body to be filled in by the user.
1598 append_newlines = "\n\n";
1599 } else if (msgbuf->buf[len - 1] != '\n') {
1601 * Incomplete line. Complete the line and add a
1602 * blank one so that there is an empty line between
1603 * the message body and the sob.
1605 append_newlines = "\n\n";
1606 } else if (len == 1) {
1608 * Buffer contains a single newline. Add another
1609 * so that we leave room for the title and body.
1611 append_newlines = "\n";
1612 } else if (msgbuf->buf[len - 2] != '\n') {
1614 * Buffer ends with a single newline. Add another
1615 * so that there is an empty line between the message
1616 * body and the sob.
1618 append_newlines = "\n";
1619 } /* else, the buffer already ends with two newlines. */
1621 if (append_newlines)
1622 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1623 append_newlines, strlen(append_newlines));
1626 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1627 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1628 sob.buf, sob.len);
1630 strbuf_release(&sob);