sequencer: stop releasing the strbuf in write_message()
[git/raj.git] / sequencer.c
blob745c86f6541053014dddcb1a5774982bbbdc40f5
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 if (commit_lock_file(&msg_file) < 0)
247 return error(_("Error wrapping up %s."), filename);
249 return 0;
253 * Reads a file that was presumably written by a shell script, i.e. with an
254 * end-of-line marker that needs to be stripped.
256 * Note that only the last end-of-line marker is stripped, consistent with the
257 * behavior of "$(cat path)" in a shell script.
259 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
261 static int read_oneliner(struct strbuf *buf,
262 const char *path, int skip_if_empty)
264 int orig_len = buf->len;
266 if (!file_exists(path))
267 return 0;
269 if (strbuf_read_file(buf, path, 0) < 0) {
270 warning_errno(_("could not read '%s'"), path);
271 return 0;
274 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
275 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
276 --buf->len;
277 buf->buf[buf->len] = '\0';
280 if (skip_if_empty && buf->len == orig_len)
281 return 0;
283 return 1;
286 static struct tree *empty_tree(void)
288 return lookup_tree(EMPTY_TREE_SHA1_BIN);
291 static int error_dirty_index(struct replay_opts *opts)
293 if (read_cache_unmerged())
294 return error_resolve_conflict(action_name(opts));
296 error(_("Your local changes would be overwritten by %s."),
297 action_name(opts));
299 if (advice_commit_before_merge)
300 advise(_("Commit your changes or stash them to proceed."));
301 return -1;
304 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
305 int unborn, struct replay_opts *opts)
307 struct ref_transaction *transaction;
308 struct strbuf sb = STRBUF_INIT;
309 struct strbuf err = STRBUF_INIT;
311 read_cache();
312 if (checkout_fast_forward(from, to, 1))
313 return -1; /* the callee should have complained already */
315 strbuf_addf(&sb, _("%s: fast-forward"), action_name(opts));
317 transaction = ref_transaction_begin(&err);
318 if (!transaction ||
319 ref_transaction_update(transaction, "HEAD",
320 to, unborn ? null_sha1 : from,
321 0, sb.buf, &err) ||
322 ref_transaction_commit(transaction, &err)) {
323 ref_transaction_free(transaction);
324 error("%s", err.buf);
325 strbuf_release(&sb);
326 strbuf_release(&err);
327 return -1;
330 strbuf_release(&sb);
331 strbuf_release(&err);
332 ref_transaction_free(transaction);
333 return 0;
336 void append_conflicts_hint(struct strbuf *msgbuf)
338 int i;
340 strbuf_addch(msgbuf, '\n');
341 strbuf_commented_addf(msgbuf, "Conflicts:\n");
342 for (i = 0; i < active_nr;) {
343 const struct cache_entry *ce = active_cache[i++];
344 if (ce_stage(ce)) {
345 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
346 while (i < active_nr && !strcmp(ce->name,
347 active_cache[i]->name))
348 i++;
353 static int do_recursive_merge(struct commit *base, struct commit *next,
354 const char *base_label, const char *next_label,
355 unsigned char *head, struct strbuf *msgbuf,
356 struct replay_opts *opts)
358 struct merge_options o;
359 struct tree *result, *next_tree, *base_tree, *head_tree;
360 int clean;
361 char **xopt;
362 static struct lock_file index_lock;
364 hold_locked_index(&index_lock, 1);
366 read_cache();
368 init_merge_options(&o);
369 o.ancestor = base ? base_label : "(empty tree)";
370 o.branch1 = "HEAD";
371 o.branch2 = next ? next_label : "(empty tree)";
373 head_tree = parse_tree_indirect(head);
374 next_tree = next ? next->tree : empty_tree();
375 base_tree = base ? base->tree : empty_tree();
377 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
378 parse_merge_opt(&o, *xopt);
380 clean = merge_trees(&o,
381 head_tree,
382 next_tree, base_tree, &result);
383 strbuf_release(&o.obuf);
384 if (clean < 0)
385 return clean;
387 if (active_cache_changed &&
388 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
389 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
390 return error(_("%s: Unable to write new index file"),
391 action_name(opts));
392 rollback_lock_file(&index_lock);
394 if (opts->signoff)
395 append_signoff(msgbuf, 0, 0);
397 if (!clean)
398 append_conflicts_hint(msgbuf);
400 return !clean;
403 static int is_index_unchanged(void)
405 unsigned char head_sha1[20];
406 struct commit *head_commit;
408 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
409 return error(_("Could not resolve HEAD commit\n"));
411 head_commit = lookup_commit(head_sha1);
414 * If head_commit is NULL, check_commit, called from
415 * lookup_commit, would have indicated that head_commit is not
416 * a commit object already. parse_commit() will return failure
417 * without further complaints in such a case. Otherwise, if
418 * the commit is invalid, parse_commit() will complain. So
419 * there is nothing for us to say here. Just return failure.
421 if (parse_commit(head_commit))
422 return -1;
424 if (!active_cache_tree)
425 active_cache_tree = cache_tree();
427 if (!cache_tree_fully_valid(active_cache_tree))
428 if (cache_tree_update(&the_index, 0))
429 return error(_("Unable to update cache tree\n"));
431 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
435 * Read the author-script file into an environment block, ready for use in
436 * run_command(), that can be free()d afterwards.
438 static char **read_author_script(void)
440 struct strbuf script = STRBUF_INIT;
441 int i, count = 0;
442 char *p, *p2, **env;
443 size_t env_size;
445 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
446 return NULL;
448 for (p = script.buf; *p; p++)
449 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
450 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
451 else if (*p == '\'')
452 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
453 else if (*p == '\n') {
454 *p = '\0';
455 count++;
458 env_size = (count + 1) * sizeof(*env);
459 strbuf_grow(&script, env_size);
460 memmove(script.buf + env_size, script.buf, script.len);
461 p = script.buf + env_size;
462 env = (char **)strbuf_detach(&script, NULL);
464 for (i = 0; i < count; i++) {
465 env[i] = p;
466 p += strlen(p) + 1;
468 env[count] = NULL;
470 return env;
474 * If we are cherry-pick, and if the merge did not result in
475 * hand-editing, we will hit this commit and inherit the original
476 * author date and name.
478 * If we are revert, or if our cherry-pick results in a hand merge,
479 * we had better say that the current user is responsible for that.
481 * An exception is when run_git_commit() is called during an
482 * interactive rebase: in that case, we will want to retain the
483 * author metadata.
485 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
486 int allow_empty, int edit, int amend,
487 int cleanup_commit_message)
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 (amend)
517 argv_array_push(&array, "--amend");
518 if (opts->gpg_sign)
519 argv_array_pushf(&array, "-S%s", opts->gpg_sign);
520 if (opts->signoff)
521 argv_array_push(&array, "-s");
522 if (defmsg)
523 argv_array_pushl(&array, "-F", defmsg, NULL);
524 if (cleanup_commit_message)
525 argv_array_push(&array, "--cleanup=strip");
526 if (edit)
527 argv_array_push(&array, "-e");
528 else if (!cleanup_commit_message &&
529 !opts->signoff && !opts->record_origin &&
530 git_config_get_value("commit.cleanup", &value))
531 argv_array_push(&array, "--cleanup=verbatim");
533 if (allow_empty)
534 argv_array_push(&array, "--allow-empty");
536 if (opts->allow_empty_message)
537 argv_array_push(&array, "--allow-empty-message");
539 rc = run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL,
540 (const char *const *)env);
541 argv_array_clear(&array);
542 free(env);
544 return rc;
547 static int is_original_commit_empty(struct commit *commit)
549 const unsigned char *ptree_sha1;
551 if (parse_commit(commit))
552 return error(_("Could not parse commit %s\n"),
553 oid_to_hex(&commit->object.oid));
554 if (commit->parents) {
555 struct commit *parent = commit->parents->item;
556 if (parse_commit(parent))
557 return error(_("Could not parse parent commit %s\n"),
558 oid_to_hex(&parent->object.oid));
559 ptree_sha1 = parent->tree->object.oid.hash;
560 } else {
561 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
564 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
568 * Do we run "git commit" with "--allow-empty"?
570 static int allow_empty(struct replay_opts *opts, struct commit *commit)
572 int index_unchanged, empty_commit;
575 * Three cases:
577 * (1) we do not allow empty at all and error out.
579 * (2) we allow ones that were initially empty, but
580 * forbid the ones that become empty;
582 * (3) we allow both.
584 if (!opts->allow_empty)
585 return 0; /* let "git commit" barf as necessary */
587 index_unchanged = is_index_unchanged();
588 if (index_unchanged < 0)
589 return index_unchanged;
590 if (!index_unchanged)
591 return 0; /* we do not have to say --allow-empty */
593 if (opts->keep_redundant_commits)
594 return 1;
596 empty_commit = is_original_commit_empty(commit);
597 if (empty_commit < 0)
598 return empty_commit;
599 if (!empty_commit)
600 return 0;
601 else
602 return 1;
605 enum todo_command {
606 TODO_PICK = 0,
607 TODO_REVERT
610 static const char *todo_command_strings[] = {
611 "pick",
612 "revert"
615 static const char *command_to_string(const enum todo_command command)
617 if (command < ARRAY_SIZE(todo_command_strings))
618 return todo_command_strings[command];
619 die("Unknown command: %d", command);
623 static int do_pick_commit(enum todo_command command, struct commit *commit,
624 struct replay_opts *opts)
626 unsigned char head[20];
627 struct commit *base, *next, *parent;
628 const char *base_label, *next_label;
629 struct commit_message msg = { NULL, NULL, NULL, NULL };
630 struct strbuf msgbuf = STRBUF_INIT;
631 int res, unborn = 0, allow;
633 if (opts->no_commit) {
635 * We do not intend to commit immediately. We just want to
636 * merge the differences in, so let's compute the tree
637 * that represents the "current" state for merge-recursive
638 * to work on.
640 if (write_cache_as_tree(head, 0, NULL))
641 return error(_("Your index file is unmerged."));
642 } else {
643 unborn = get_sha1("HEAD", head);
644 if (unborn)
645 hashcpy(head, EMPTY_TREE_SHA1_BIN);
646 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0))
647 return error_dirty_index(opts);
649 discard_cache();
651 if (!commit->parents) {
652 parent = NULL;
654 else if (commit->parents->next) {
655 /* Reverting or cherry-picking a merge commit */
656 int cnt;
657 struct commit_list *p;
659 if (!opts->mainline)
660 return error(_("Commit %s is a merge but no -m option was given."),
661 oid_to_hex(&commit->object.oid));
663 for (cnt = 1, p = commit->parents;
664 cnt != opts->mainline && p;
665 cnt++)
666 p = p->next;
667 if (cnt != opts->mainline || !p)
668 return error(_("Commit %s does not have parent %d"),
669 oid_to_hex(&commit->object.oid), opts->mainline);
670 parent = p->item;
671 } else if (0 < opts->mainline)
672 return error(_("Mainline was specified but commit %s is not a merge."),
673 oid_to_hex(&commit->object.oid));
674 else
675 parent = commit->parents->item;
677 if (opts->allow_ff &&
678 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
679 (!parent && unborn)))
680 return fast_forward_to(commit->object.oid.hash, head, unborn, opts);
682 if (parent && parse_commit(parent) < 0)
683 /* TRANSLATORS: The first %s will be a "todo" command like
684 "revert" or "pick", the second %s a SHA1. */
685 return error(_("%s: cannot parse parent commit %s"),
686 command_to_string(command),
687 oid_to_hex(&parent->object.oid));
689 if (get_message(commit, &msg) != 0)
690 return error(_("Cannot get commit message for %s"),
691 oid_to_hex(&commit->object.oid));
694 * "commit" is an existing commit. We would want to apply
695 * the difference it introduces since its first parent "prev"
696 * on top of the current HEAD if we are cherry-pick. Or the
697 * reverse of it if we are revert.
700 if (command == TODO_REVERT) {
701 base = commit;
702 base_label = msg.label;
703 next = parent;
704 next_label = msg.parent_label;
705 strbuf_addstr(&msgbuf, "Revert \"");
706 strbuf_addstr(&msgbuf, msg.subject);
707 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
708 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
710 if (commit->parents && commit->parents->next) {
711 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
712 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
714 strbuf_addstr(&msgbuf, ".\n");
715 } else {
716 const char *p;
718 base = parent;
719 base_label = msg.parent_label;
720 next = commit;
721 next_label = msg.label;
724 * Append the commit log message to msgbuf; it starts
725 * after the tree, parent, author, committer
726 * information followed by "\n\n".
728 p = strstr(msg.message, "\n\n");
729 if (p)
730 strbuf_addstr(&msgbuf, skip_blank_lines(p + 2));
732 if (opts->record_origin) {
733 if (!has_conforming_footer(&msgbuf, NULL, 0))
734 strbuf_addch(&msgbuf, '\n');
735 strbuf_addstr(&msgbuf, cherry_picked_prefix);
736 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
737 strbuf_addstr(&msgbuf, ")\n");
741 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
742 res = do_recursive_merge(base, next, base_label, next_label,
743 head, &msgbuf, opts);
744 if (res < 0)
745 return res;
746 res |= write_message(&msgbuf, git_path_merge_msg());
747 } else {
748 struct commit_list *common = NULL;
749 struct commit_list *remotes = NULL;
751 res = write_message(&msgbuf, git_path_merge_msg());
753 commit_list_insert(base, &common);
754 commit_list_insert(next, &remotes);
755 res |= try_merge_command(opts->strategy,
756 opts->xopts_nr, (const char **)opts->xopts,
757 common, sha1_to_hex(head), remotes);
758 free_commit_list(common);
759 free_commit_list(remotes);
761 strbuf_release(&msgbuf);
764 * If the merge was clean or if it failed due to conflict, we write
765 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
766 * However, if the merge did not even start, then we don't want to
767 * write it at all.
769 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
770 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
771 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
772 res = -1;
773 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
774 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
775 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
776 res = -1;
778 if (res) {
779 error(command == TODO_REVERT
780 ? _("could not revert %s... %s")
781 : _("could not apply %s... %s"),
782 short_commit_name(commit), msg.subject);
783 print_advice(res == 1, opts);
784 rerere(opts->allow_rerere_auto);
785 goto leave;
788 allow = allow_empty(opts, commit);
789 if (allow < 0) {
790 res = allow;
791 goto leave;
793 if (!opts->no_commit)
794 res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
795 opts, allow, opts->edit, 0, 0);
797 leave:
798 free_message(commit, &msg);
800 return res;
803 static int prepare_revs(struct replay_opts *opts)
806 * picking (but not reverting) ranges (but not individual revisions)
807 * should be done in reverse
809 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
810 opts->revs->reverse ^= 1;
812 if (prepare_revision_walk(opts->revs))
813 return error(_("revision walk setup failed"));
815 if (!opts->revs->commits)
816 return error(_("empty commit set passed"));
817 return 0;
820 static int read_and_refresh_cache(struct replay_opts *opts)
822 static struct lock_file index_lock;
823 int index_fd = hold_locked_index(&index_lock, 0);
824 if (read_index_preload(&the_index, NULL) < 0) {
825 rollback_lock_file(&index_lock);
826 return error(_("git %s: failed to read the index"),
827 action_name(opts));
829 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
830 if (the_index.cache_changed && index_fd >= 0) {
831 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
832 rollback_lock_file(&index_lock);
833 return error(_("git %s: failed to refresh the index"),
834 action_name(opts));
837 rollback_lock_file(&index_lock);
838 return 0;
841 struct todo_item {
842 enum todo_command command;
843 struct commit *commit;
844 const char *arg;
845 int arg_len;
846 size_t offset_in_buf;
849 struct todo_list {
850 struct strbuf buf;
851 struct todo_item *items;
852 int nr, alloc, current;
855 #define TODO_LIST_INIT { STRBUF_INIT }
857 static void todo_list_release(struct todo_list *todo_list)
859 strbuf_release(&todo_list->buf);
860 free(todo_list->items);
861 todo_list->items = NULL;
862 todo_list->nr = todo_list->alloc = 0;
865 static struct todo_item *append_new_todo(struct todo_list *todo_list)
867 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
868 return todo_list->items + todo_list->nr++;
871 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
873 unsigned char commit_sha1[20];
874 char *end_of_object_name;
875 int i, saved, status, padding;
877 /* left-trim */
878 bol += strspn(bol, " \t");
880 for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
881 if (skip_prefix(bol, todo_command_strings[i], &bol)) {
882 item->command = i;
883 break;
885 if (i >= ARRAY_SIZE(todo_command_strings))
886 return -1;
888 /* Eat up extra spaces/ tabs before object name */
889 padding = strspn(bol, " \t");
890 if (!padding)
891 return -1;
892 bol += padding;
894 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
895 saved = *end_of_object_name;
896 *end_of_object_name = '\0';
897 status = get_sha1(bol, commit_sha1);
898 *end_of_object_name = saved;
900 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
901 item->arg_len = (int)(eol - item->arg);
903 if (status < 0)
904 return -1;
906 item->commit = lookup_commit_reference(commit_sha1);
907 return !item->commit;
910 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
912 struct todo_item *item;
913 char *p = buf, *next_p;
914 int i, res = 0;
916 for (i = 1; *p; i++, p = next_p) {
917 char *eol = strchrnul(p, '\n');
919 next_p = *eol ? eol + 1 /* skip LF */ : eol;
921 if (p != eol && eol[-1] == '\r')
922 eol--; /* strip Carriage Return */
924 item = append_new_todo(todo_list);
925 item->offset_in_buf = p - todo_list->buf.buf;
926 if (parse_insn_line(item, p, eol)) {
927 res = error(_("Invalid line %d: %.*s"),
928 i, (int)(eol - p), p);
929 item->command = -1;
932 if (!todo_list->nr)
933 return error(_("No commits parsed."));
934 return res;
937 static int read_populate_todo(struct todo_list *todo_list,
938 struct replay_opts *opts)
940 const char *todo_file = get_todo_path(opts);
941 int fd, res;
943 strbuf_reset(&todo_list->buf);
944 fd = open(todo_file, O_RDONLY);
945 if (fd < 0)
946 return error_errno(_("Could not open %s"), todo_file);
947 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
948 close(fd);
949 return error(_("Could not read %s."), todo_file);
951 close(fd);
953 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
954 if (!res) {
955 enum todo_command valid =
956 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
957 int i;
959 for (i = 0; i < todo_list->nr; i++)
960 if (valid == todo_list->items[i].command)
961 continue;
962 else if (valid == TODO_PICK)
963 return error(_("Cannot cherry-pick during a revert."));
964 else
965 return error(_("Cannot revert during a cherry-pick."));
968 if (res)
969 return error(_("Unusable instruction sheet: %s"), todo_file);
970 return 0;
973 static int git_config_string_dup(char **dest,
974 const char *var, const char *value)
976 if (!value)
977 return config_error_nonbool(var);
978 free(*dest);
979 *dest = xstrdup(value);
980 return 0;
983 static int populate_opts_cb(const char *key, const char *value, void *data)
985 struct replay_opts *opts = data;
986 int error_flag = 1;
988 if (!value)
989 error_flag = 0;
990 else if (!strcmp(key, "options.no-commit"))
991 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
992 else if (!strcmp(key, "options.edit"))
993 opts->edit = git_config_bool_or_int(key, value, &error_flag);
994 else if (!strcmp(key, "options.signoff"))
995 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
996 else if (!strcmp(key, "options.record-origin"))
997 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
998 else if (!strcmp(key, "options.allow-ff"))
999 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1000 else if (!strcmp(key, "options.mainline"))
1001 opts->mainline = git_config_int(key, value);
1002 else if (!strcmp(key, "options.strategy"))
1003 git_config_string_dup(&opts->strategy, key, value);
1004 else if (!strcmp(key, "options.gpg-sign"))
1005 git_config_string_dup(&opts->gpg_sign, key, value);
1006 else if (!strcmp(key, "options.strategy-option")) {
1007 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1008 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1009 } else
1010 return error(_("Invalid key: %s"), key);
1012 if (!error_flag)
1013 return error(_("Invalid value for %s: %s"), key, value);
1015 return 0;
1018 static int read_populate_opts(struct replay_opts *opts)
1020 if (is_rebase_i(opts)) {
1021 struct strbuf buf = STRBUF_INIT;
1023 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1024 if (!starts_with(buf.buf, "-S"))
1025 strbuf_reset(&buf);
1026 else {
1027 free(opts->gpg_sign);
1028 opts->gpg_sign = xstrdup(buf.buf + 2);
1031 strbuf_release(&buf);
1033 return 0;
1036 if (!file_exists(git_path_opts_file()))
1037 return 0;
1039 * The function git_parse_source(), called from git_config_from_file(),
1040 * may die() in case of a syntactically incorrect file. We do not care
1041 * about this case, though, because we wrote that file ourselves, so we
1042 * are pretty certain that it is syntactically correct.
1044 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1045 return error(_("Malformed options sheet: %s"),
1046 git_path_opts_file());
1047 return 0;
1050 static int walk_revs_populate_todo(struct todo_list *todo_list,
1051 struct replay_opts *opts)
1053 enum todo_command command = opts->action == REPLAY_PICK ?
1054 TODO_PICK : TODO_REVERT;
1055 const char *command_string = todo_command_strings[command];
1056 struct commit *commit;
1058 if (prepare_revs(opts))
1059 return -1;
1061 while ((commit = get_revision(opts->revs))) {
1062 struct todo_item *item = append_new_todo(todo_list);
1063 const char *commit_buffer = get_commit_buffer(commit, NULL);
1064 const char *subject;
1065 int subject_len;
1067 item->command = command;
1068 item->commit = commit;
1069 item->arg = NULL;
1070 item->arg_len = 0;
1071 item->offset_in_buf = todo_list->buf.len;
1072 subject_len = find_commit_subject(commit_buffer, &subject);
1073 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1074 short_commit_name(commit), subject_len, subject);
1075 unuse_commit_buffer(commit, commit_buffer);
1077 return 0;
1080 static int create_seq_dir(void)
1082 if (file_exists(git_path_seq_dir())) {
1083 error(_("a cherry-pick or revert is already in progress"));
1084 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1085 return -1;
1087 else if (mkdir(git_path_seq_dir(), 0777) < 0)
1088 return error_errno(_("Could not create sequencer directory %s"),
1089 git_path_seq_dir());
1090 return 0;
1093 static int save_head(const char *head)
1095 static struct lock_file head_lock;
1096 struct strbuf buf = STRBUF_INIT;
1097 int fd;
1099 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1100 if (fd < 0) {
1101 rollback_lock_file(&head_lock);
1102 return error_errno(_("Could not lock HEAD"));
1104 strbuf_addf(&buf, "%s\n", head);
1105 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1106 rollback_lock_file(&head_lock);
1107 return error_errno(_("Could not write to %s"),
1108 git_path_head_file());
1110 if (commit_lock_file(&head_lock) < 0) {
1111 rollback_lock_file(&head_lock);
1112 return error(_("Error wrapping up %s."), git_path_head_file());
1114 return 0;
1117 static int reset_for_rollback(const unsigned char *sha1)
1119 const char *argv[4]; /* reset --merge <arg> + NULL */
1120 argv[0] = "reset";
1121 argv[1] = "--merge";
1122 argv[2] = sha1_to_hex(sha1);
1123 argv[3] = NULL;
1124 return run_command_v_opt(argv, RUN_GIT_CMD);
1127 static int rollback_single_pick(void)
1129 unsigned char head_sha1[20];
1131 if (!file_exists(git_path_cherry_pick_head()) &&
1132 !file_exists(git_path_revert_head()))
1133 return error(_("no cherry-pick or revert in progress"));
1134 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1135 return error(_("cannot resolve HEAD"));
1136 if (is_null_sha1(head_sha1))
1137 return error(_("cannot abort from a branch yet to be born"));
1138 return reset_for_rollback(head_sha1);
1141 int sequencer_rollback(struct replay_opts *opts)
1143 FILE *f;
1144 unsigned char sha1[20];
1145 struct strbuf buf = STRBUF_INIT;
1147 f = fopen(git_path_head_file(), "r");
1148 if (!f && errno == ENOENT) {
1150 * There is no multiple-cherry-pick in progress.
1151 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1152 * a single-cherry-pick in progress, abort that.
1154 return rollback_single_pick();
1156 if (!f)
1157 return error_errno(_("cannot open %s"), git_path_head_file());
1158 if (strbuf_getline_lf(&buf, f)) {
1159 error(_("cannot read %s: %s"), git_path_head_file(),
1160 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1161 fclose(f);
1162 goto fail;
1164 fclose(f);
1165 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1166 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1167 git_path_head_file());
1168 goto fail;
1170 if (is_null_sha1(sha1)) {
1171 error(_("cannot abort from a branch yet to be born"));
1172 goto fail;
1174 if (reset_for_rollback(sha1))
1175 goto fail;
1176 strbuf_release(&buf);
1177 return sequencer_remove_state(opts);
1178 fail:
1179 strbuf_release(&buf);
1180 return -1;
1183 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1185 static struct lock_file todo_lock;
1186 const char *todo_path = get_todo_path(opts);
1187 int next = todo_list->current, offset, fd;
1189 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1190 if (fd < 0)
1191 return error_errno(_("Could not lock '%s'"), todo_path);
1192 offset = next < todo_list->nr ?
1193 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1194 if (write_in_full(fd, todo_list->buf.buf + offset,
1195 todo_list->buf.len - offset) < 0)
1196 return error_errno(_("Could not write to '%s'"), todo_path);
1197 if (commit_lock_file(&todo_lock) < 0)
1198 return error(_("Error wrapping up %s."), todo_path);
1199 return 0;
1202 static int save_opts(struct replay_opts *opts)
1204 const char *opts_file = git_path_opts_file();
1205 int res = 0;
1207 if (opts->no_commit)
1208 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1209 if (opts->edit)
1210 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1211 if (opts->signoff)
1212 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1213 if (opts->record_origin)
1214 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1215 if (opts->allow_ff)
1216 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1217 if (opts->mainline) {
1218 struct strbuf buf = STRBUF_INIT;
1219 strbuf_addf(&buf, "%d", opts->mainline);
1220 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1221 strbuf_release(&buf);
1223 if (opts->strategy)
1224 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1225 if (opts->gpg_sign)
1226 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1227 if (opts->xopts) {
1228 int i;
1229 for (i = 0; i < opts->xopts_nr; i++)
1230 res |= git_config_set_multivar_in_file_gently(opts_file,
1231 "options.strategy-option",
1232 opts->xopts[i], "^$", 0);
1234 return res;
1237 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1239 int res;
1241 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1242 if (opts->allow_ff)
1243 assert(!(opts->signoff || opts->no_commit ||
1244 opts->record_origin || opts->edit));
1245 if (read_and_refresh_cache(opts))
1246 return -1;
1248 while (todo_list->current < todo_list->nr) {
1249 struct todo_item *item = todo_list->items + todo_list->current;
1250 if (save_todo(todo_list, opts))
1251 return -1;
1252 res = do_pick_commit(item->command, item->commit, opts);
1253 todo_list->current++;
1254 if (res)
1255 return res;
1259 * Sequence of picks finished successfully; cleanup by
1260 * removing the .git/sequencer directory
1262 return sequencer_remove_state(opts);
1265 static int continue_single_pick(void)
1267 const char *argv[] = { "commit", NULL };
1269 if (!file_exists(git_path_cherry_pick_head()) &&
1270 !file_exists(git_path_revert_head()))
1271 return error(_("no cherry-pick or revert in progress"));
1272 return run_command_v_opt(argv, RUN_GIT_CMD);
1275 int sequencer_continue(struct replay_opts *opts)
1277 struct todo_list todo_list = TODO_LIST_INIT;
1278 int res;
1280 if (read_and_refresh_cache(opts))
1281 return -1;
1283 if (!file_exists(get_todo_path(opts)))
1284 return continue_single_pick();
1285 if (read_populate_opts(opts))
1286 return -1;
1287 if ((res = read_populate_todo(&todo_list, opts)))
1288 goto release_todo_list;
1290 /* Verify that the conflict has been resolved */
1291 if (file_exists(git_path_cherry_pick_head()) ||
1292 file_exists(git_path_revert_head())) {
1293 res = continue_single_pick();
1294 if (res)
1295 goto release_todo_list;
1297 if (index_differs_from("HEAD", 0)) {
1298 res = error_dirty_index(opts);
1299 goto release_todo_list;
1301 todo_list.current++;
1302 res = pick_commits(&todo_list, opts);
1303 release_todo_list:
1304 todo_list_release(&todo_list);
1305 return res;
1308 static int single_pick(struct commit *cmit, struct replay_opts *opts)
1310 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1311 return do_pick_commit(opts->action == REPLAY_PICK ?
1312 TODO_PICK : TODO_REVERT, cmit, opts);
1315 int sequencer_pick_revisions(struct replay_opts *opts)
1317 struct todo_list todo_list = TODO_LIST_INIT;
1318 unsigned char sha1[20];
1319 int i, res;
1321 assert(opts->revs);
1322 if (read_and_refresh_cache(opts))
1323 return -1;
1325 for (i = 0; i < opts->revs->pending.nr; i++) {
1326 unsigned char sha1[20];
1327 const char *name = opts->revs->pending.objects[i].name;
1329 /* This happens when using --stdin. */
1330 if (!strlen(name))
1331 continue;
1333 if (!get_sha1(name, sha1)) {
1334 if (!lookup_commit_reference_gently(sha1, 1)) {
1335 enum object_type type = sha1_object_info(sha1, NULL);
1336 return error(_("%s: can't cherry-pick a %s"),
1337 name, typename(type));
1339 } else
1340 return error(_("%s: bad revision"), name);
1344 * If we were called as "git cherry-pick <commit>", just
1345 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1346 * REVERT_HEAD, and don't touch the sequencer state.
1347 * This means it is possible to cherry-pick in the middle
1348 * of a cherry-pick sequence.
1350 if (opts->revs->cmdline.nr == 1 &&
1351 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1352 opts->revs->no_walk &&
1353 !opts->revs->cmdline.rev->flags) {
1354 struct commit *cmit;
1355 if (prepare_revision_walk(opts->revs))
1356 return error(_("revision walk setup failed"));
1357 cmit = get_revision(opts->revs);
1358 if (!cmit || get_revision(opts->revs))
1359 return error("BUG: expected exactly one commit from walk");
1360 return single_pick(cmit, opts);
1364 * Start a new cherry-pick/ revert sequence; but
1365 * first, make sure that an existing one isn't in
1366 * progress
1369 if (walk_revs_populate_todo(&todo_list, opts) ||
1370 create_seq_dir() < 0)
1371 return -1;
1372 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1373 return error(_("Can't revert as initial commit"));
1374 if (save_head(sha1_to_hex(sha1)))
1375 return -1;
1376 if (save_opts(opts))
1377 return -1;
1378 res = pick_commits(&todo_list, opts);
1379 todo_list_release(&todo_list);
1380 return res;
1383 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1385 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1386 struct strbuf sob = STRBUF_INIT;
1387 int has_footer;
1389 strbuf_addstr(&sob, sign_off_header);
1390 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1391 getenv("GIT_COMMITTER_EMAIL")));
1392 strbuf_addch(&sob, '\n');
1395 * If the whole message buffer is equal to the sob, pretend that we
1396 * found a conforming footer with a matching sob
1398 if (msgbuf->len - ignore_footer == sob.len &&
1399 !strncmp(msgbuf->buf, sob.buf, sob.len))
1400 has_footer = 3;
1401 else
1402 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1404 if (!has_footer) {
1405 const char *append_newlines = NULL;
1406 size_t len = msgbuf->len - ignore_footer;
1408 if (!len) {
1410 * The buffer is completely empty. Leave foom for
1411 * the title and body to be filled in by the user.
1413 append_newlines = "\n\n";
1414 } else if (msgbuf->buf[len - 1] != '\n') {
1416 * Incomplete line. Complete the line and add a
1417 * blank one so that there is an empty line between
1418 * the message body and the sob.
1420 append_newlines = "\n\n";
1421 } else if (len == 1) {
1423 * Buffer contains a single newline. Add another
1424 * so that we leave room for the title and body.
1426 append_newlines = "\n";
1427 } else if (msgbuf->buf[len - 2] != '\n') {
1429 * Buffer ends with a single newline. Add another
1430 * so that there is an empty line between the message
1431 * body and the sob.
1433 append_newlines = "\n";
1434 } /* else, the buffer already ends with two newlines. */
1436 if (append_newlines)
1437 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1438 append_newlines, strlen(append_newlines));
1441 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1442 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1443 sob.buf, sob.len);
1445 strbuf_release(&sob);