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