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