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