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