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