sequencer.con commit sequencer: use a helper to find the commit message (23aa514)
   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                /* Append the commit log message to msgbuf. */
 707                if (find_commit_subject(msg.message, &p))
 708                        strbuf_addstr(&msgbuf, p);
 709
 710                if (opts->record_origin) {
 711                        if (!has_conforming_footer(&msgbuf, NULL, 0))
 712                                strbuf_addch(&msgbuf, '\n');
 713                        strbuf_addstr(&msgbuf, cherry_picked_prefix);
 714                        strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
 715                        strbuf_addstr(&msgbuf, ")\n");
 716                }
 717        }
 718
 719        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
 720                res = do_recursive_merge(base, next, base_label, next_label,
 721                                         head, &msgbuf, opts);
 722                if (res < 0)
 723                        return res;
 724                res |= write_message(msgbuf.buf, msgbuf.len,
 725                                     git_path_merge_msg(), 0);
 726        } else {
 727                struct commit_list *common = NULL;
 728                struct commit_list *remotes = NULL;
 729
 730                res = write_message(msgbuf.buf, msgbuf.len,
 731                                    git_path_merge_msg(), 0);
 732
 733                commit_list_insert(base, &common);
 734                commit_list_insert(next, &remotes);
 735                res |= try_merge_command(opts->strategy,
 736                                         opts->xopts_nr, (const char **)opts->xopts,
 737                                        common, sha1_to_hex(head), remotes);
 738                free_commit_list(common);
 739                free_commit_list(remotes);
 740        }
 741        strbuf_release(&msgbuf);
 742
 743        /*
 744         * If the merge was clean or if it failed due to conflict, we write
 745         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 746         * However, if the merge did not even start, then we don't want to
 747         * write it at all.
 748         */
 749        if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
 750            update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
 751                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 752                res = -1;
 753        if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
 754            update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
 755                       REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
 756                res = -1;
 757
 758        if (res) {
 759                error(command == TODO_REVERT
 760                      ? _("could not revert %s... %s")
 761                      : _("could not apply %s... %s"),
 762                      short_commit_name(commit), msg.subject);
 763                print_advice(res == 1, opts);
 764                rerere(opts->allow_rerere_auto);
 765                goto leave;
 766        }
 767
 768        allow = allow_empty(opts, commit);
 769        if (allow < 0) {
 770                res = allow;
 771                goto leave;
 772        }
 773        if (!opts->no_commit)
 774                res = run_git_commit(opts->edit ? NULL : git_path_merge_msg(),
 775                                     opts, allow, opts->edit, 0, 0);
 776
 777leave:
 778        free_message(commit, &msg);
 779        update_abort_safety_file();
 780
 781        return res;
 782}
 783
 784static int prepare_revs(struct replay_opts *opts)
 785{
 786        /*
 787         * picking (but not reverting) ranges (but not individual revisions)
 788         * should be done in reverse
 789         */
 790        if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
 791                opts->revs->reverse ^= 1;
 792
 793        if (prepare_revision_walk(opts->revs))
 794                return error(_("revision walk setup failed"));
 795
 796        if (!opts->revs->commits)
 797                return error(_("empty commit set passed"));
 798        return 0;
 799}
 800
 801static int read_and_refresh_cache(struct replay_opts *opts)
 802{
 803        static struct lock_file index_lock;
 804        int index_fd = hold_locked_index(&index_lock, 0);
 805        if (read_index_preload(&the_index, NULL) < 0) {
 806                rollback_lock_file(&index_lock);
 807                return error(_("git %s: failed to read the index"),
 808                        _(action_name(opts)));
 809        }
 810        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 811        if (the_index.cache_changed && index_fd >= 0) {
 812                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
 813                        rollback_lock_file(&index_lock);
 814                        return error(_("git %s: failed to refresh the index"),
 815                                _(action_name(opts)));
 816                }
 817        }
 818        rollback_lock_file(&index_lock);
 819        return 0;
 820}
 821
 822struct todo_item {
 823        enum todo_command command;
 824        struct commit *commit;
 825        const char *arg;
 826        int arg_len;
 827        size_t offset_in_buf;
 828};
 829
 830struct todo_list {
 831        struct strbuf buf;
 832        struct todo_item *items;
 833        int nr, alloc, current;
 834};
 835
 836#define TODO_LIST_INIT { STRBUF_INIT }
 837
 838static void todo_list_release(struct todo_list *todo_list)
 839{
 840        strbuf_release(&todo_list->buf);
 841        free(todo_list->items);
 842        todo_list->items = NULL;
 843        todo_list->nr = todo_list->alloc = 0;
 844}
 845
 846static struct todo_item *append_new_todo(struct todo_list *todo_list)
 847{
 848        ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
 849        return todo_list->items + todo_list->nr++;
 850}
 851
 852static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
 853{
 854        unsigned char commit_sha1[20];
 855        char *end_of_object_name;
 856        int i, saved, status, padding;
 857
 858        /* left-trim */
 859        bol += strspn(bol, " \t");
 860
 861        for (i = 0; i < ARRAY_SIZE(todo_command_strings); i++)
 862                if (skip_prefix(bol, todo_command_strings[i], &bol)) {
 863                        item->command = i;
 864                        break;
 865                }
 866        if (i >= ARRAY_SIZE(todo_command_strings))
 867                return -1;
 868
 869        /* Eat up extra spaces/ tabs before object name */
 870        padding = strspn(bol, " \t");
 871        if (!padding)
 872                return -1;
 873        bol += padding;
 874
 875        end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
 876        saved = *end_of_object_name;
 877        *end_of_object_name = '\0';
 878        status = get_sha1(bol, commit_sha1);
 879        *end_of_object_name = saved;
 880
 881        item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
 882        item->arg_len = (int)(eol - item->arg);
 883
 884        if (status < 0)
 885                return -1;
 886
 887        item->commit = lookup_commit_reference(commit_sha1);
 888        return !item->commit;
 889}
 890
 891static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
 892{
 893        struct todo_item *item;
 894        char *p = buf, *next_p;
 895        int i, res = 0;
 896
 897        for (i = 1; *p; i++, p = next_p) {
 898                char *eol = strchrnul(p, '\n');
 899
 900                next_p = *eol ? eol + 1 /* skip LF */ : eol;
 901
 902                if (p != eol && eol[-1] == '\r')
 903                        eol--; /* strip Carriage Return */
 904
 905                item = append_new_todo(todo_list);
 906                item->offset_in_buf = p - todo_list->buf.buf;
 907                if (parse_insn_line(item, p, eol)) {
 908                        res = error(_("invalid line %d: %.*s"),
 909                                i, (int)(eol - p), p);
 910                        item->command = -1;
 911                }
 912        }
 913        if (!todo_list->nr)
 914                return error(_("no commits parsed."));
 915        return res;
 916}
 917
 918static int read_populate_todo(struct todo_list *todo_list,
 919                        struct replay_opts *opts)
 920{
 921        const char *todo_file = get_todo_path(opts);
 922        int fd, res;
 923
 924        strbuf_reset(&todo_list->buf);
 925        fd = open(todo_file, O_RDONLY);
 926        if (fd < 0)
 927                return error_errno(_("could not open '%s'"), todo_file);
 928        if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
 929                close(fd);
 930                return error(_("could not read '%s'."), todo_file);
 931        }
 932        close(fd);
 933
 934        res = parse_insn_buffer(todo_list->buf.buf, todo_list);
 935        if (res)
 936                return error(_("unusable instruction sheet: '%s'"), todo_file);
 937
 938        if (!is_rebase_i(opts)) {
 939                enum todo_command valid =
 940                        opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
 941                int i;
 942
 943                for (i = 0; i < todo_list->nr; i++)
 944                        if (valid == todo_list->items[i].command)
 945                                continue;
 946                        else if (valid == TODO_PICK)
 947                                return error(_("cannot cherry-pick during a revert."));
 948                        else
 949                                return error(_("cannot revert during a cherry-pick."));
 950        }
 951
 952        return 0;
 953}
 954
 955static int git_config_string_dup(char **dest,
 956                                 const char *var, const char *value)
 957{
 958        if (!value)
 959                return config_error_nonbool(var);
 960        free(*dest);
 961        *dest = xstrdup(value);
 962        return 0;
 963}
 964
 965static int populate_opts_cb(const char *key, const char *value, void *data)
 966{
 967        struct replay_opts *opts = data;
 968        int error_flag = 1;
 969
 970        if (!value)
 971                error_flag = 0;
 972        else if (!strcmp(key, "options.no-commit"))
 973                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
 974        else if (!strcmp(key, "options.edit"))
 975                opts->edit = git_config_bool_or_int(key, value, &error_flag);
 976        else if (!strcmp(key, "options.signoff"))
 977                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
 978        else if (!strcmp(key, "options.record-origin"))
 979                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
 980        else if (!strcmp(key, "options.allow-ff"))
 981                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
 982        else if (!strcmp(key, "options.mainline"))
 983                opts->mainline = git_config_int(key, value);
 984        else if (!strcmp(key, "options.strategy"))
 985                git_config_string_dup(&opts->strategy, key, value);
 986        else if (!strcmp(key, "options.gpg-sign"))
 987                git_config_string_dup(&opts->gpg_sign, key, value);
 988        else if (!strcmp(key, "options.strategy-option")) {
 989                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
 990                opts->xopts[opts->xopts_nr++] = xstrdup(value);
 991        } else
 992                return error(_("invalid key: %s"), key);
 993
 994        if (!error_flag)
 995                return error(_("invalid value for %s: %s"), key, value);
 996
 997        return 0;
 998}
 999
1000static int read_populate_opts(struct replay_opts *opts)
1001{
1002        if (is_rebase_i(opts)) {
1003                struct strbuf buf = STRBUF_INIT;
1004
1005                if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1006                        if (!starts_with(buf.buf, "-S"))
1007                                strbuf_reset(&buf);
1008                        else {
1009                                free(opts->gpg_sign);
1010                                opts->gpg_sign = xstrdup(buf.buf + 2);
1011                        }
1012                }
1013                strbuf_release(&buf);
1014
1015                return 0;
1016        }
1017
1018        if (!file_exists(git_path_opts_file()))
1019                return 0;
1020        /*
1021         * The function git_parse_source(), called from git_config_from_file(),
1022         * may die() in case of a syntactically incorrect file. We do not care
1023         * about this case, though, because we wrote that file ourselves, so we
1024         * are pretty certain that it is syntactically correct.
1025         */
1026        if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1027                return error(_("malformed options sheet: '%s'"),
1028                        git_path_opts_file());
1029        return 0;
1030}
1031
1032static int walk_revs_populate_todo(struct todo_list *todo_list,
1033                                struct replay_opts *opts)
1034{
1035        enum todo_command command = opts->action == REPLAY_PICK ?
1036                TODO_PICK : TODO_REVERT;
1037        const char *command_string = todo_command_strings[command];
1038        struct commit *commit;
1039
1040        if (prepare_revs(opts))
1041                return -1;
1042
1043        while ((commit = get_revision(opts->revs))) {
1044                struct todo_item *item = append_new_todo(todo_list);
1045                const char *commit_buffer = get_commit_buffer(commit, NULL);
1046                const char *subject;
1047                int subject_len;
1048
1049                item->command = command;
1050                item->commit = commit;
1051                item->arg = NULL;
1052                item->arg_len = 0;
1053                item->offset_in_buf = todo_list->buf.len;
1054                subject_len = find_commit_subject(commit_buffer, &subject);
1055                strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1056                        short_commit_name(commit), subject_len, subject);
1057                unuse_commit_buffer(commit, commit_buffer);
1058        }
1059        return 0;
1060}
1061
1062static int create_seq_dir(void)
1063{
1064        if (file_exists(git_path_seq_dir())) {
1065                error(_("a cherry-pick or revert is already in progress"));
1066                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1067                return -1;
1068        } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1069                return error_errno(_("could not create sequencer directory '%s'"),
1070                                   git_path_seq_dir());
1071        return 0;
1072}
1073
1074static int save_head(const char *head)
1075{
1076        static struct lock_file head_lock;
1077        struct strbuf buf = STRBUF_INIT;
1078        int fd;
1079
1080        fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1081        if (fd < 0) {
1082                rollback_lock_file(&head_lock);
1083                return error_errno(_("could not lock HEAD"));
1084        }
1085        strbuf_addf(&buf, "%s\n", head);
1086        if (write_in_full(fd, buf.buf, buf.len) < 0) {
1087                rollback_lock_file(&head_lock);
1088                return error_errno(_("could not write to '%s'"),
1089                                   git_path_head_file());
1090        }
1091        if (commit_lock_file(&head_lock) < 0) {
1092                rollback_lock_file(&head_lock);
1093                return error(_("failed to finalize '%s'."), git_path_head_file());
1094        }
1095        return 0;
1096}
1097
1098static int rollback_is_safe(void)
1099{
1100        struct strbuf sb = STRBUF_INIT;
1101        struct object_id expected_head, actual_head;
1102
1103        if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1104                strbuf_trim(&sb);
1105                if (get_oid_hex(sb.buf, &expected_head)) {
1106                        strbuf_release(&sb);
1107                        die(_("could not parse %s"), git_path_abort_safety_file());
1108                }
1109                strbuf_release(&sb);
1110        }
1111        else if (errno == ENOENT)
1112                oidclr(&expected_head);
1113        else
1114                die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1115
1116        if (get_oid("HEAD", &actual_head))
1117                oidclr(&actual_head);
1118
1119        return !oidcmp(&actual_head, &expected_head);
1120}
1121
1122static int reset_for_rollback(const unsigned char *sha1)
1123{
1124        const char *argv[4];    /* reset --merge <arg> + NULL */
1125
1126        argv[0] = "reset";
1127        argv[1] = "--merge";
1128        argv[2] = sha1_to_hex(sha1);
1129        argv[3] = NULL;
1130        return run_command_v_opt(argv, RUN_GIT_CMD);
1131}
1132
1133static int rollback_single_pick(void)
1134{
1135        unsigned char head_sha1[20];
1136
1137        if (!file_exists(git_path_cherry_pick_head()) &&
1138            !file_exists(git_path_revert_head()))
1139                return error(_("no cherry-pick or revert in progress"));
1140        if (read_ref_full("HEAD", 0, head_sha1, NULL))
1141                return error(_("cannot resolve HEAD"));
1142        if (is_null_sha1(head_sha1))
1143                return error(_("cannot abort from a branch yet to be born"));
1144        return reset_for_rollback(head_sha1);
1145}
1146
1147int sequencer_rollback(struct replay_opts *opts)
1148{
1149        FILE *f;
1150        unsigned char sha1[20];
1151        struct strbuf buf = STRBUF_INIT;
1152
1153        f = fopen(git_path_head_file(), "r");
1154        if (!f && errno == ENOENT) {
1155                /*
1156                 * There is no multiple-cherry-pick in progress.
1157                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1158                 * a single-cherry-pick in progress, abort that.
1159                 */
1160                return rollback_single_pick();
1161        }
1162        if (!f)
1163                return error_errno(_("cannot open '%s'"), git_path_head_file());
1164        if (strbuf_getline_lf(&buf, f)) {
1165                error(_("cannot read '%s': %s"), git_path_head_file(),
1166                      ferror(f) ?  strerror(errno) : _("unexpected end of file"));
1167                fclose(f);
1168                goto fail;
1169        }
1170        fclose(f);
1171        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1172                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1173                        git_path_head_file());
1174                goto fail;
1175        }
1176        if (is_null_sha1(sha1)) {
1177                error(_("cannot abort from a branch yet to be born"));
1178                goto fail;
1179        }
1180
1181        if (!rollback_is_safe()) {
1182                /* Do not error, just do not rollback */
1183                warning(_("You seem to have moved HEAD. "
1184                          "Not rewinding, check your HEAD!"));
1185        } else
1186        if (reset_for_rollback(sha1))
1187                goto fail;
1188        strbuf_release(&buf);
1189        return sequencer_remove_state(opts);
1190fail:
1191        strbuf_release(&buf);
1192        return -1;
1193}
1194
1195static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1196{
1197        static struct lock_file todo_lock;
1198        const char *todo_path = get_todo_path(opts);
1199        int next = todo_list->current, offset, fd;
1200
1201        fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1202        if (fd < 0)
1203                return error_errno(_("could not lock '%s'"), todo_path);
1204        offset = next < todo_list->nr ?
1205                todo_list->items[next].offset_in_buf : todo_list->buf.len;
1206        if (write_in_full(fd, todo_list->buf.buf + offset,
1207                        todo_list->buf.len - offset) < 0)
1208                return error_errno(_("could not write to '%s'"), todo_path);
1209        if (commit_lock_file(&todo_lock) < 0)
1210                return error(_("failed to finalize '%s'."), todo_path);
1211        return 0;
1212}
1213
1214static int save_opts(struct replay_opts *opts)
1215{
1216        const char *opts_file = git_path_opts_file();
1217        int res = 0;
1218
1219        if (opts->no_commit)
1220                res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1221        if (opts->edit)
1222                res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1223        if (opts->signoff)
1224                res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1225        if (opts->record_origin)
1226                res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1227        if (opts->allow_ff)
1228                res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1229        if (opts->mainline) {
1230                struct strbuf buf = STRBUF_INIT;
1231                strbuf_addf(&buf, "%d", opts->mainline);
1232                res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1233                strbuf_release(&buf);
1234        }
1235        if (opts->strategy)
1236                res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1237        if (opts->gpg_sign)
1238                res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1239        if (opts->xopts) {
1240                int i;
1241                for (i = 0; i < opts->xopts_nr; i++)
1242                        res |= git_config_set_multivar_in_file_gently(opts_file,
1243                                                        "options.strategy-option",
1244                                                        opts->xopts[i], "^$", 0);
1245        }
1246        return res;
1247}
1248
1249static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1250{
1251        int res;
1252
1253        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1254        if (opts->allow_ff)
1255                assert(!(opts->signoff || opts->no_commit ||
1256                                opts->record_origin || opts->edit));
1257        if (read_and_refresh_cache(opts))
1258                return -1;
1259
1260        while (todo_list->current < todo_list->nr) {
1261                struct todo_item *item = todo_list->items + todo_list->current;
1262                if (save_todo(todo_list, opts))
1263                        return -1;
1264                res = do_pick_commit(item->command, item->commit, opts);
1265                todo_list->current++;
1266                if (res)
1267                        return res;
1268        }
1269
1270        /*
1271         * Sequence of picks finished successfully; cleanup by
1272         * removing the .git/sequencer directory
1273         */
1274        return sequencer_remove_state(opts);
1275}
1276
1277static int continue_single_pick(void)
1278{
1279        const char *argv[] = { "commit", NULL };
1280
1281        if (!file_exists(git_path_cherry_pick_head()) &&
1282            !file_exists(git_path_revert_head()))
1283                return error(_("no cherry-pick or revert in progress"));
1284        return run_command_v_opt(argv, RUN_GIT_CMD);
1285}
1286
1287int sequencer_continue(struct replay_opts *opts)
1288{
1289        struct todo_list todo_list = TODO_LIST_INIT;
1290        int res;
1291
1292        if (read_and_refresh_cache(opts))
1293                return -1;
1294
1295        if (!file_exists(get_todo_path(opts)))
1296                return continue_single_pick();
1297        if (read_populate_opts(opts))
1298                return -1;
1299        if ((res = read_populate_todo(&todo_list, opts)))
1300                goto release_todo_list;
1301
1302        /* Verify that the conflict has been resolved */
1303        if (file_exists(git_path_cherry_pick_head()) ||
1304            file_exists(git_path_revert_head())) {
1305                res = continue_single_pick();
1306                if (res)
1307                        goto release_todo_list;
1308        }
1309        if (index_differs_from("HEAD", 0, 0)) {
1310                res = error_dirty_index(opts);
1311                goto release_todo_list;
1312        }
1313        todo_list.current++;
1314        res = pick_commits(&todo_list, opts);
1315release_todo_list:
1316        todo_list_release(&todo_list);
1317        return res;
1318}
1319
1320static int single_pick(struct commit *cmit, struct replay_opts *opts)
1321{
1322        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1323        return do_pick_commit(opts->action == REPLAY_PICK ?
1324                TODO_PICK : TODO_REVERT, cmit, opts);
1325}
1326
1327int sequencer_pick_revisions(struct replay_opts *opts)
1328{
1329        struct todo_list todo_list = TODO_LIST_INIT;
1330        unsigned char sha1[20];
1331        int i, res;
1332
1333        assert(opts->revs);
1334        if (read_and_refresh_cache(opts))
1335                return -1;
1336
1337        for (i = 0; i < opts->revs->pending.nr; i++) {
1338                unsigned char sha1[20];
1339                const char *name = opts->revs->pending.objects[i].name;
1340
1341                /* This happens when using --stdin. */
1342                if (!strlen(name))
1343                        continue;
1344
1345                if (!get_sha1(name, sha1)) {
1346                        if (!lookup_commit_reference_gently(sha1, 1)) {
1347                                enum object_type type = sha1_object_info(sha1, NULL);
1348                                return error(_("%s: can't cherry-pick a %s"),
1349                                        name, typename(type));
1350                        }
1351                } else
1352                        return error(_("%s: bad revision"), name);
1353        }
1354
1355        /*
1356         * If we were called as "git cherry-pick <commit>", just
1357         * cherry-pick/revert it, set CHERRY_PICK_HEAD /
1358         * REVERT_HEAD, and don't touch the sequencer state.
1359         * This means it is possible to cherry-pick in the middle
1360         * of a cherry-pick sequence.
1361         */
1362        if (opts->revs->cmdline.nr == 1 &&
1363            opts->revs->cmdline.rev->whence == REV_CMD_REV &&
1364            opts->revs->no_walk &&
1365            !opts->revs->cmdline.rev->flags) {
1366                struct commit *cmit;
1367                if (prepare_revision_walk(opts->revs))
1368                        return error(_("revision walk setup failed"));
1369                cmit = get_revision(opts->revs);
1370                if (!cmit || get_revision(opts->revs))
1371                        return error("BUG: expected exactly one commit from walk");
1372                return single_pick(cmit, opts);
1373        }
1374
1375        /*
1376         * Start a new cherry-pick/ revert sequence; but
1377         * first, make sure that an existing one isn't in
1378         * progress
1379         */
1380
1381        if (walk_revs_populate_todo(&todo_list, opts) ||
1382                        create_seq_dir() < 0)
1383                return -1;
1384        if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
1385                return error(_("can't revert as initial commit"));
1386        if (save_head(sha1_to_hex(sha1)))
1387                return -1;
1388        if (save_opts(opts))
1389                return -1;
1390        update_abort_safety_file();
1391        res = pick_commits(&todo_list, opts);
1392        todo_list_release(&todo_list);
1393        return res;
1394}
1395
1396void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
1397{
1398        unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
1399        struct strbuf sob = STRBUF_INIT;
1400        int has_footer;
1401
1402        strbuf_addstr(&sob, sign_off_header);
1403        strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
1404                                getenv("GIT_COMMITTER_EMAIL")));
1405        strbuf_addch(&sob, '\n');
1406
1407        /*
1408         * If the whole message buffer is equal to the sob, pretend that we
1409         * found a conforming footer with a matching sob
1410         */
1411        if (msgbuf->len - ignore_footer == sob.len &&
1412            !strncmp(msgbuf->buf, sob.buf, sob.len))
1413                has_footer = 3;
1414        else
1415                has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
1416
1417        if (!has_footer) {
1418                const char *append_newlines = NULL;
1419                size_t len = msgbuf->len - ignore_footer;
1420
1421                if (!len) {
1422                        /*
1423                         * The buffer is completely empty.  Leave foom for
1424                         * the title and body to be filled in by the user.
1425                         */
1426                        append_newlines = "\n\n";
1427                } else if (msgbuf->buf[len - 1] != '\n') {
1428                        /*
1429                         * Incomplete line.  Complete the line and add a
1430                         * blank one so that there is an empty line between
1431                         * the message body and the sob.
1432                         */
1433                        append_newlines = "\n\n";
1434                } else if (len == 1) {
1435                        /*
1436                         * Buffer contains a single newline.  Add another
1437                         * so that we leave room for the title and body.
1438                         */
1439                        append_newlines = "\n";
1440                } else if (msgbuf->buf[len - 2] != '\n') {
1441                        /*
1442                         * Buffer ends with a single newline.  Add another
1443                         * so that there is an empty line between the message
1444                         * body and the sob.
1445                         */
1446                        append_newlines = "\n";
1447                } /* else, the buffer already ends with two newlines. */
1448
1449                if (append_newlines)
1450                        strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1451                                append_newlines, strlen(append_newlines));
1452        }
1453
1454        if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
1455                strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
1456                                sob.buf, sob.len);
1457
1458        strbuf_release(&sob);
1459}