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