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