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