70a5fbb672f14bec432447b37ce9b012577fe510
   1#include "cache.h"
   2#include "builtin.h"
   3#include "object.h"
   4#include "commit.h"
   5#include "tag.h"
   6#include "run-command.h"
   7#include "exec_cmd.h"
   8#include "utf8.h"
   9#include "parse-options.h"
  10#include "cache-tree.h"
  11#include "diff.h"
  12#include "revision.h"
  13#include "rerere.h"
  14#include "merge-recursive.h"
  15#include "refs.h"
  16#include "dir.h"
  17#include "sequencer.h"
  18
  19/*
  20 * This implements the builtins revert and cherry-pick.
  21 *
  22 * Copyright (c) 2007 Johannes E. Schindelin
  23 *
  24 * Based on git-revert.sh, which is
  25 *
  26 * Copyright (c) 2005 Linus Torvalds
  27 * Copyright (c) 2005 Junio C Hamano
  28 */
  29
  30static const char * const revert_usage[] = {
  31        "git revert [options] <commit-ish>",
  32        "git revert <subcommand>",
  33        NULL
  34};
  35
  36static const char * const cherry_pick_usage[] = {
  37        "git cherry-pick [options] <commit-ish>",
  38        "git cherry-pick <subcommand>",
  39        NULL
  40};
  41
  42enum replay_action { REVERT, CHERRY_PICK };
  43enum replay_subcommand {
  44        REPLAY_NONE,
  45        REPLAY_REMOVE_STATE,
  46        REPLAY_CONTINUE,
  47        REPLAY_ROLLBACK
  48};
  49
  50struct replay_opts {
  51        enum replay_action action;
  52        enum replay_subcommand subcommand;
  53
  54        /* Boolean options */
  55        int edit;
  56        int record_origin;
  57        int no_commit;
  58        int signoff;
  59        int allow_ff;
  60        int allow_rerere_auto;
  61
  62        int mainline;
  63        int commit_argc;
  64        const char **commit_argv;
  65
  66        /* Merge strategy */
  67        const char *strategy;
  68        const char **xopts;
  69        size_t xopts_nr, xopts_alloc;
  70};
  71
  72#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  73
  74static const char *action_name(const struct replay_opts *opts)
  75{
  76        return opts->action == REVERT ? "revert" : "cherry-pick";
  77}
  78
  79static char *get_encoding(const char *message);
  80
  81static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
  82{
  83        return opts->action == REVERT ? revert_usage : cherry_pick_usage;
  84}
  85
  86static int option_parse_x(const struct option *opt,
  87                          const char *arg, int unset)
  88{
  89        struct replay_opts **opts_ptr = opt->value;
  90        struct replay_opts *opts = *opts_ptr;
  91
  92        if (unset)
  93                return 0;
  94
  95        ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
  96        opts->xopts[opts->xopts_nr++] = xstrdup(arg);
  97        return 0;
  98}
  99
 100static void verify_opt_compatible(const char *me, const char *base_opt, ...)
 101{
 102        const char *this_opt;
 103        va_list ap;
 104
 105        va_start(ap, base_opt);
 106        while ((this_opt = va_arg(ap, const char *))) {
 107                if (va_arg(ap, int))
 108                        break;
 109        }
 110        va_end(ap);
 111
 112        if (this_opt)
 113                die(_("%s: %s cannot be used with %s"), me, this_opt, base_opt);
 114}
 115
 116static void verify_opt_mutually_compatible(const char *me, ...)
 117{
 118        const char *opt1, *opt2 = NULL;
 119        va_list ap;
 120
 121        va_start(ap, me);
 122        while ((opt1 = va_arg(ap, const char *))) {
 123                if (va_arg(ap, int))
 124                        break;
 125        }
 126        if (opt1) {
 127                while ((opt2 = va_arg(ap, const char *))) {
 128                        if (va_arg(ap, int))
 129                                break;
 130                }
 131        }
 132
 133        if (opt1 && opt2)
 134                die(_("%s: %s cannot be used with %s"), me, opt1, opt2);
 135}
 136
 137static void parse_args(int argc, const char **argv, struct replay_opts *opts)
 138{
 139        const char * const * usage_str = revert_or_cherry_pick_usage(opts);
 140        const char *me = action_name(opts);
 141        int remove_state = 0;
 142        int contin = 0;
 143        int rollback = 0;
 144        struct option options[] = {
 145                OPT_BOOLEAN(0, "quit", &remove_state, "end revert or cherry-pick sequence"),
 146                OPT_BOOLEAN(0, "continue", &contin, "resume revert or cherry-pick sequence"),
 147                OPT_BOOLEAN(0, "abort", &rollback, "cancel revert or cherry-pick sequence"),
 148                OPT_BOOLEAN('n', "no-commit", &opts->no_commit, "don't automatically commit"),
 149                OPT_BOOLEAN('e', "edit", &opts->edit, "edit the commit message"),
 150                OPT_NOOP_NOARG('r', NULL),
 151                OPT_BOOLEAN('s', "signoff", &opts->signoff, "add Signed-off-by:"),
 152                OPT_INTEGER('m', "mainline", &opts->mainline, "parent number"),
 153                OPT_RERERE_AUTOUPDATE(&opts->allow_rerere_auto),
 154                OPT_STRING(0, "strategy", &opts->strategy, "strategy", "merge strategy"),
 155                OPT_CALLBACK('X', "strategy-option", &opts, "option",
 156                        "option for merge strategy", option_parse_x),
 157                { OPTION_BOOLEAN, 0, "reset", &remove_state, NULL,
 158                        "alias for --quit (deprecated)",
 159                        PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
 160                OPT_END(),
 161                OPT_END(),
 162                OPT_END(),
 163        };
 164
 165        if (opts->action == CHERRY_PICK) {
 166                struct option cp_extra[] = {
 167                        OPT_BOOLEAN('x', NULL, &opts->record_origin, "append commit name"),
 168                        OPT_BOOLEAN(0, "ff", &opts->allow_ff, "allow fast-forward"),
 169                        OPT_END(),
 170                };
 171                if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
 172                        die(_("program error"));
 173        }
 174
 175        opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
 176                                        PARSE_OPT_KEEP_ARGV0 |
 177                                        PARSE_OPT_KEEP_UNKNOWN);
 178
 179        /* Check for incompatible subcommands */
 180        verify_opt_mutually_compatible(me,
 181                                "--quit", remove_state,
 182                                "--continue", contin,
 183                                "--abort", rollback,
 184                                NULL);
 185
 186        /* Set the subcommand */
 187        if (remove_state)
 188                opts->subcommand = REPLAY_REMOVE_STATE;
 189        else if (contin)
 190                opts->subcommand = REPLAY_CONTINUE;
 191        else if (rollback)
 192                opts->subcommand = REPLAY_ROLLBACK;
 193        else
 194                opts->subcommand = REPLAY_NONE;
 195
 196        /* Check for incompatible command line arguments */
 197        if (opts->subcommand != REPLAY_NONE) {
 198                char *this_operation;
 199                if (opts->subcommand == REPLAY_REMOVE_STATE)
 200                        this_operation = "--quit";
 201                else if (opts->subcommand == REPLAY_CONTINUE)
 202                        this_operation = "--continue";
 203                else {
 204                        assert(opts->subcommand == REPLAY_ROLLBACK);
 205                        this_operation = "--abort";
 206                }
 207
 208                verify_opt_compatible(me, this_operation,
 209                                "--no-commit", opts->no_commit,
 210                                "--signoff", opts->signoff,
 211                                "--mainline", opts->mainline,
 212                                "--strategy", opts->strategy ? 1 : 0,
 213                                "--strategy-option", opts->xopts ? 1 : 0,
 214                                "-x", opts->record_origin,
 215                                "--ff", opts->allow_ff,
 216                                NULL);
 217        }
 218
 219        else if (opts->commit_argc < 2)
 220                usage_with_options(usage_str, options);
 221
 222        if (opts->allow_ff)
 223                verify_opt_compatible(me, "--ff",
 224                                "--signoff", opts->signoff,
 225                                "--no-commit", opts->no_commit,
 226                                "-x", opts->record_origin,
 227                                "--edit", opts->edit,
 228                                NULL);
 229        opts->commit_argv = argv;
 230}
 231
 232struct commit_message {
 233        char *parent_label;
 234        const char *label;
 235        const char *subject;
 236        char *reencoded_message;
 237        const char *message;
 238};
 239
 240static int get_message(struct commit *commit, struct commit_message *out)
 241{
 242        const char *encoding;
 243        const char *abbrev, *subject;
 244        int abbrev_len, subject_len;
 245        char *q;
 246
 247        if (!commit->buffer)
 248                return -1;
 249        encoding = get_encoding(commit->buffer);
 250        if (!encoding)
 251                encoding = "UTF-8";
 252        if (!git_commit_encoding)
 253                git_commit_encoding = "UTF-8";
 254
 255        out->reencoded_message = NULL;
 256        out->message = commit->buffer;
 257        if (strcmp(encoding, git_commit_encoding))
 258                out->reencoded_message = reencode_string(commit->buffer,
 259                                        git_commit_encoding, encoding);
 260        if (out->reencoded_message)
 261                out->message = out->reencoded_message;
 262
 263        abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
 264        abbrev_len = strlen(abbrev);
 265
 266        subject_len = find_commit_subject(out->message, &subject);
 267
 268        out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
 269                              strlen("... ") + subject_len + 1);
 270        q = out->parent_label;
 271        q = mempcpy(q, "parent of ", strlen("parent of "));
 272        out->label = q;
 273        q = mempcpy(q, abbrev, abbrev_len);
 274        q = mempcpy(q, "... ", strlen("... "));
 275        out->subject = q;
 276        q = mempcpy(q, subject, subject_len);
 277        *q = '\0';
 278        return 0;
 279}
 280
 281static void free_message(struct commit_message *msg)
 282{
 283        free(msg->parent_label);
 284        free(msg->reencoded_message);
 285}
 286
 287static char *get_encoding(const char *message)
 288{
 289        const char *p = message, *eol;
 290
 291        while (*p && *p != '\n') {
 292                for (eol = p + 1; *eol && *eol != '\n'; eol++)
 293                        ; /* do nothing */
 294                if (!prefixcmp(p, "encoding ")) {
 295                        char *result = xmalloc(eol - 8 - p);
 296                        strlcpy(result, p + 9, eol - 8 - p);
 297                        return result;
 298                }
 299                p = eol;
 300                if (*p == '\n')
 301                        p++;
 302        }
 303        return NULL;
 304}
 305
 306static void write_cherry_pick_head(struct commit *commit, const char *pseudoref)
 307{
 308        const char *filename;
 309        int fd;
 310        struct strbuf buf = STRBUF_INIT;
 311
 312        strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
 313
 314        filename = git_path(pseudoref);
 315        fd = open(filename, O_WRONLY | O_CREAT, 0666);
 316        if (fd < 0)
 317                die_errno(_("Could not open '%s' for writing"), filename);
 318        if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
 319                die_errno(_("Could not write to '%s'"), filename);
 320        strbuf_release(&buf);
 321}
 322
 323static void print_advice(int show_hint)
 324{
 325        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 326
 327        if (msg) {
 328                fprintf(stderr, "%s\n", msg);
 329                /*
 330                 * A conflict has occured but the porcelain
 331                 * (typically rebase --interactive) wants to take care
 332                 * of the commit itself so remove CHERRY_PICK_HEAD
 333                 */
 334                unlink(git_path("CHERRY_PICK_HEAD"));
 335                return;
 336        }
 337
 338        if (show_hint) {
 339                advise("after resolving the conflicts, mark the corrected paths");
 340                advise("with 'git add <paths>' or 'git rm <paths>'");
 341                advise("and commit the result with 'git commit'");
 342        }
 343}
 344
 345static void write_message(struct strbuf *msgbuf, const char *filename)
 346{
 347        static struct lock_file msg_file;
 348
 349        int msg_fd = hold_lock_file_for_update(&msg_file, filename,
 350                                               LOCK_DIE_ON_ERROR);
 351        if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
 352                die_errno(_("Could not write to %s"), filename);
 353        strbuf_release(msgbuf);
 354        if (commit_lock_file(&msg_file) < 0)
 355                die(_("Error wrapping up %s"), filename);
 356}
 357
 358static struct tree *empty_tree(void)
 359{
 360        return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
 361}
 362
 363static int error_dirty_index(struct replay_opts *opts)
 364{
 365        if (read_cache_unmerged())
 366                return error_resolve_conflict(action_name(opts));
 367
 368        /* Different translation strings for cherry-pick and revert */
 369        if (opts->action == CHERRY_PICK)
 370                error(_("Your local changes would be overwritten by cherry-pick."));
 371        else
 372                error(_("Your local changes would be overwritten by revert."));
 373
 374        if (advice_commit_before_merge)
 375                advise(_("Commit your changes or stash them to proceed."));
 376        return -1;
 377}
 378
 379static int fast_forward_to(const unsigned char *to, const unsigned char *from)
 380{
 381        struct ref_lock *ref_lock;
 382
 383        read_cache();
 384        if (checkout_fast_forward(from, to))
 385                exit(1); /* the callee should have complained already */
 386        ref_lock = lock_any_ref_for_update("HEAD", from, 0);
 387        return write_ref_sha1(ref_lock, to, "cherry-pick");
 388}
 389
 390static int do_recursive_merge(struct commit *base, struct commit *next,
 391                              const char *base_label, const char *next_label,
 392                              unsigned char *head, struct strbuf *msgbuf,
 393                              struct replay_opts *opts)
 394{
 395        struct merge_options o;
 396        struct tree *result, *next_tree, *base_tree, *head_tree;
 397        int clean, index_fd;
 398        const char **xopt;
 399        static struct lock_file index_lock;
 400
 401        index_fd = hold_locked_index(&index_lock, 1);
 402
 403        read_cache();
 404
 405        init_merge_options(&o);
 406        o.ancestor = base ? base_label : "(empty tree)";
 407        o.branch1 = "HEAD";
 408        o.branch2 = next ? next_label : "(empty tree)";
 409
 410        head_tree = parse_tree_indirect(head);
 411        next_tree = next ? next->tree : empty_tree();
 412        base_tree = base ? base->tree : empty_tree();
 413
 414        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 415                parse_merge_opt(&o, *xopt);
 416
 417        clean = merge_trees(&o,
 418                            head_tree,
 419                            next_tree, base_tree, &result);
 420
 421        if (active_cache_changed &&
 422            (write_cache(index_fd, active_cache, active_nr) ||
 423             commit_locked_index(&index_lock)))
 424                /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
 425                die(_("%s: Unable to write new index file"), action_name(opts));
 426        rollback_lock_file(&index_lock);
 427
 428        if (!clean) {
 429                int i;
 430                strbuf_addstr(msgbuf, "\nConflicts:\n\n");
 431                for (i = 0; i < active_nr;) {
 432                        struct cache_entry *ce = active_cache[i++];
 433                        if (ce_stage(ce)) {
 434                                strbuf_addch(msgbuf, '\t');
 435                                strbuf_addstr(msgbuf, ce->name);
 436                                strbuf_addch(msgbuf, '\n');
 437                                while (i < active_nr && !strcmp(ce->name,
 438                                                active_cache[i]->name))
 439                                        i++;
 440                        }
 441                }
 442        }
 443
 444        return !clean;
 445}
 446
 447/*
 448 * If we are cherry-pick, and if the merge did not result in
 449 * hand-editing, we will hit this commit and inherit the original
 450 * author date and name.
 451 * If we are revert, or if our cherry-pick results in a hand merge,
 452 * we had better say that the current user is responsible for that.
 453 */
 454static int run_git_commit(const char *defmsg, struct replay_opts *opts)
 455{
 456        /* 6 is max possible length of our args array including NULL */
 457        const char *args[6];
 458        int i = 0;
 459
 460        args[i++] = "commit";
 461        args[i++] = "-n";
 462        if (opts->signoff)
 463                args[i++] = "-s";
 464        if (!opts->edit) {
 465                args[i++] = "-F";
 466                args[i++] = defmsg;
 467        }
 468        args[i] = NULL;
 469
 470        return run_command_v_opt(args, RUN_GIT_CMD);
 471}
 472
 473static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 474{
 475        unsigned char head[20];
 476        struct commit *base, *next, *parent;
 477        const char *base_label, *next_label;
 478        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 479        char *defmsg = NULL;
 480        struct strbuf msgbuf = STRBUF_INIT;
 481        int res;
 482
 483        if (opts->no_commit) {
 484                /*
 485                 * We do not intend to commit immediately.  We just want to
 486                 * merge the differences in, so let's compute the tree
 487                 * that represents the "current" state for merge-recursive
 488                 * to work on.
 489                 */
 490                if (write_cache_as_tree(head, 0, NULL))
 491                        die (_("Your index file is unmerged."));
 492        } else {
 493                if (get_sha1("HEAD", head))
 494                        return error(_("You do not have a valid HEAD"));
 495                if (index_differs_from("HEAD", 0))
 496                        return error_dirty_index(opts);
 497        }
 498        discard_cache();
 499
 500        if (!commit->parents) {
 501                parent = NULL;
 502        }
 503        else if (commit->parents->next) {
 504                /* Reverting or cherry-picking a merge commit */
 505                int cnt;
 506                struct commit_list *p;
 507
 508                if (!opts->mainline)
 509                        return error(_("Commit %s is a merge but no -m option was given."),
 510                                sha1_to_hex(commit->object.sha1));
 511
 512                for (cnt = 1, p = commit->parents;
 513                     cnt != opts->mainline && p;
 514                     cnt++)
 515                        p = p->next;
 516                if (cnt != opts->mainline || !p)
 517                        return error(_("Commit %s does not have parent %d"),
 518                                sha1_to_hex(commit->object.sha1), opts->mainline);
 519                parent = p->item;
 520        } else if (0 < opts->mainline)
 521                return error(_("Mainline was specified but commit %s is not a merge."),
 522                        sha1_to_hex(commit->object.sha1));
 523        else
 524                parent = commit->parents->item;
 525
 526        if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
 527                return fast_forward_to(commit->object.sha1, head);
 528
 529        if (parent && parse_commit(parent) < 0)
 530                /* TRANSLATORS: The first %s will be "revert" or
 531                   "cherry-pick", the second %s a SHA1 */
 532                return error(_("%s: cannot parse parent commit %s"),
 533                        action_name(opts), sha1_to_hex(parent->object.sha1));
 534
 535        if (get_message(commit, &msg) != 0)
 536                return error(_("Cannot get commit message for %s"),
 537                        sha1_to_hex(commit->object.sha1));
 538
 539        /*
 540         * "commit" is an existing commit.  We would want to apply
 541         * the difference it introduces since its first parent "prev"
 542         * on top of the current HEAD if we are cherry-pick.  Or the
 543         * reverse of it if we are revert.
 544         */
 545
 546        defmsg = git_pathdup("MERGE_MSG");
 547
 548        if (opts->action == REVERT) {
 549                base = commit;
 550                base_label = msg.label;
 551                next = parent;
 552                next_label = msg.parent_label;
 553                strbuf_addstr(&msgbuf, "Revert \"");
 554                strbuf_addstr(&msgbuf, msg.subject);
 555                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 556                strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 557
 558                if (commit->parents && commit->parents->next) {
 559                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 560                        strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
 561                }
 562                strbuf_addstr(&msgbuf, ".\n");
 563        } else {
 564                const char *p;
 565
 566                base = parent;
 567                base_label = msg.parent_label;
 568                next = commit;
 569                next_label = msg.label;
 570
 571                /*
 572                 * Append the commit log message to msgbuf; it starts
 573                 * after the tree, parent, author, committer
 574                 * information followed by "\n\n".
 575                 */
 576                p = strstr(msg.message, "\n\n");
 577                if (p) {
 578                        p += 2;
 579                        strbuf_addstr(&msgbuf, p);
 580                }
 581
 582                if (opts->record_origin) {
 583                        strbuf_addstr(&msgbuf, "(cherry picked from commit ");
 584                        strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 585                        strbuf_addstr(&msgbuf, ")\n");
 586                }
 587        }
 588
 589        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
 590                res = do_recursive_merge(base, next, base_label, next_label,
 591                                         head, &msgbuf, opts);
 592                write_message(&msgbuf, defmsg);
 593        } else {
 594                struct commit_list *common = NULL;
 595                struct commit_list *remotes = NULL;
 596
 597                write_message(&msgbuf, defmsg);
 598
 599                commit_list_insert(base, &common);
 600                commit_list_insert(next, &remotes);
 601                res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 602                                        common, sha1_to_hex(head), remotes);
 603                free_commit_list(common);
 604                free_commit_list(remotes);
 605        }
 606
 607        /*
 608         * If the merge was clean or if it failed due to conflict, we write
 609         * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
 610         * However, if the merge did not even start, then we don't want to
 611         * write it at all.
 612         */
 613        if (opts->action == CHERRY_PICK && !opts->no_commit && (res == 0 || res == 1))
 614                write_cherry_pick_head(commit, "CHERRY_PICK_HEAD");
 615        if (opts->action == REVERT && ((opts->no_commit && res == 0) || res == 1))
 616                write_cherry_pick_head(commit, "REVERT_HEAD");
 617
 618        if (res) {
 619                error(opts->action == REVERT
 620                      ? _("could not revert %s... %s")
 621                      : _("could not apply %s... %s"),
 622                      find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
 623                      msg.subject);
 624                print_advice(res == 1);
 625                rerere(opts->allow_rerere_auto);
 626        } else {
 627                if (!opts->no_commit)
 628                        res = run_git_commit(defmsg, opts);
 629        }
 630
 631        free_message(&msg);
 632        free(defmsg);
 633
 634        return res;
 635}
 636
 637static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
 638{
 639        int argc;
 640
 641        init_revisions(revs, NULL);
 642        revs->no_walk = 1;
 643        if (opts->action != REVERT)
 644                revs->reverse = 1;
 645
 646        argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
 647        if (argc > 1)
 648                usage(*revert_or_cherry_pick_usage(opts));
 649
 650        if (prepare_revision_walk(revs))
 651                die(_("revision walk setup failed"));
 652
 653        if (!revs->commits)
 654                die(_("empty commit set passed"));
 655}
 656
 657static void read_and_refresh_cache(struct replay_opts *opts)
 658{
 659        static struct lock_file index_lock;
 660        int index_fd = hold_locked_index(&index_lock, 0);
 661        if (read_index_preload(&the_index, NULL) < 0)
 662                die(_("git %s: failed to read the index"), action_name(opts));
 663        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 664        if (the_index.cache_changed) {
 665                if (write_index(&the_index, index_fd) ||
 666                    commit_locked_index(&index_lock))
 667                        die(_("git %s: failed to refresh the index"), action_name(opts));
 668        }
 669        rollback_lock_file(&index_lock);
 670}
 671
 672/*
 673 * Append a commit to the end of the commit_list.
 674 *
 675 * next starts by pointing to the variable that holds the head of an
 676 * empty commit_list, and is updated to point to the "next" field of
 677 * the last item on the list as new commits are appended.
 678 *
 679 * Usage example:
 680 *
 681 *     struct commit_list *list;
 682 *     struct commit_list **next = &list;
 683 *
 684 *     next = commit_list_append(c1, next);
 685 *     next = commit_list_append(c2, next);
 686 *     assert(commit_list_count(list) == 2);
 687 *     return list;
 688 */
 689static struct commit_list **commit_list_append(struct commit *commit,
 690                                               struct commit_list **next)
 691{
 692        struct commit_list *new = xmalloc(sizeof(struct commit_list));
 693        new->item = commit;
 694        *next = new;
 695        new->next = NULL;
 696        return &new->next;
 697}
 698
 699static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
 700                struct replay_opts *opts)
 701{
 702        struct commit_list *cur = NULL;
 703        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 704        const char *sha1_abbrev = NULL;
 705        const char *action_str = opts->action == REVERT ? "revert" : "pick";
 706
 707        for (cur = todo_list; cur; cur = cur->next) {
 708                sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
 709                if (get_message(cur->item, &msg))
 710                        return error(_("Cannot get commit message for %s"), sha1_abbrev);
 711                strbuf_addf(buf, "%s %s %s\n", action_str, sha1_abbrev, msg.subject);
 712        }
 713        return 0;
 714}
 715
 716static struct commit *parse_insn_line(char *start, struct replay_opts *opts)
 717{
 718        unsigned char commit_sha1[20];
 719        char sha1_abbrev[40];
 720        enum replay_action action;
 721        int insn_len = 0;
 722        char *p, *q;
 723
 724        if (!prefixcmp(start, "pick ")) {
 725                action = CHERRY_PICK;
 726                insn_len = strlen("pick");
 727                p = start + insn_len + 1;
 728        } else if (!prefixcmp(start, "revert ")) {
 729                action = REVERT;
 730                insn_len = strlen("revert");
 731                p = start + insn_len + 1;
 732        } else
 733                return NULL;
 734
 735        q = strchr(p, ' ');
 736        if (!q)
 737                return NULL;
 738        q++;
 739
 740        strlcpy(sha1_abbrev, p, q - p);
 741
 742        /*
 743         * Verify that the action matches up with the one in
 744         * opts; we don't support arbitrary instructions
 745         */
 746        if (action != opts->action) {
 747                const char *action_str;
 748                action_str = action == REVERT ? "revert" : "cherry-pick";
 749                error(_("Cannot %s during a %s"), action_str, action_name(opts));
 750                return NULL;
 751        }
 752
 753        if (get_sha1(sha1_abbrev, commit_sha1) < 0)
 754                return NULL;
 755
 756        return lookup_commit_reference(commit_sha1);
 757}
 758
 759static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
 760                        struct replay_opts *opts)
 761{
 762        struct commit_list **next = todo_list;
 763        struct commit *commit;
 764        char *p = buf;
 765        int i;
 766
 767        for (i = 1; *p; i++) {
 768                commit = parse_insn_line(p, opts);
 769                if (!commit)
 770                        return error(_("Could not parse line %d."), i);
 771                next = commit_list_append(commit, next);
 772                p = strchrnul(p, '\n');
 773                if (*p)
 774                        p++;
 775        }
 776        if (!*todo_list)
 777                return error(_("No commits parsed."));
 778        return 0;
 779}
 780
 781static void read_populate_todo(struct commit_list **todo_list,
 782                        struct replay_opts *opts)
 783{
 784        const char *todo_file = git_path(SEQ_TODO_FILE);
 785        struct strbuf buf = STRBUF_INIT;
 786        int fd, res;
 787
 788        fd = open(todo_file, O_RDONLY);
 789        if (fd < 0)
 790                die_errno(_("Could not open %s"), todo_file);
 791        if (strbuf_read(&buf, fd, 0) < 0) {
 792                close(fd);
 793                strbuf_release(&buf);
 794                die(_("Could not read %s."), todo_file);
 795        }
 796        close(fd);
 797
 798        res = parse_insn_buffer(buf.buf, todo_list, opts);
 799        strbuf_release(&buf);
 800        if (res)
 801                die(_("Unusable instruction sheet: %s"), todo_file);
 802}
 803
 804static int populate_opts_cb(const char *key, const char *value, void *data)
 805{
 806        struct replay_opts *opts = data;
 807        int error_flag = 1;
 808
 809        if (!value)
 810                error_flag = 0;
 811        else if (!strcmp(key, "options.no-commit"))
 812                opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
 813        else if (!strcmp(key, "options.edit"))
 814                opts->edit = git_config_bool_or_int(key, value, &error_flag);
 815        else if (!strcmp(key, "options.signoff"))
 816                opts->signoff = git_config_bool_or_int(key, value, &error_flag);
 817        else if (!strcmp(key, "options.record-origin"))
 818                opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
 819        else if (!strcmp(key, "options.allow-ff"))
 820                opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
 821        else if (!strcmp(key, "options.mainline"))
 822                opts->mainline = git_config_int(key, value);
 823        else if (!strcmp(key, "options.strategy"))
 824                git_config_string(&opts->strategy, key, value);
 825        else if (!strcmp(key, "options.strategy-option")) {
 826                ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
 827                opts->xopts[opts->xopts_nr++] = xstrdup(value);
 828        } else
 829                return error(_("Invalid key: %s"), key);
 830
 831        if (!error_flag)
 832                return error(_("Invalid value for %s: %s"), key, value);
 833
 834        return 0;
 835}
 836
 837static void read_populate_opts(struct replay_opts **opts_ptr)
 838{
 839        const char *opts_file = git_path(SEQ_OPTS_FILE);
 840
 841        if (!file_exists(opts_file))
 842                return;
 843        if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
 844                die(_("Malformed options sheet: %s"), opts_file);
 845}
 846
 847static void walk_revs_populate_todo(struct commit_list **todo_list,
 848                                struct replay_opts *opts)
 849{
 850        struct rev_info revs;
 851        struct commit *commit;
 852        struct commit_list **next;
 853
 854        prepare_revs(&revs, opts);
 855
 856        next = todo_list;
 857        while ((commit = get_revision(&revs)))
 858                next = commit_list_append(commit, next);
 859}
 860
 861static int create_seq_dir(void)
 862{
 863        const char *seq_dir = git_path(SEQ_DIR);
 864
 865        if (file_exists(seq_dir)) {
 866                error(_("a cherry-pick or revert is already in progress"));
 867                advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
 868                return -1;
 869        }
 870        else if (mkdir(seq_dir, 0777) < 0)
 871                die_errno(_("Could not create sequencer directory %s"), seq_dir);
 872        return 0;
 873}
 874
 875static void save_head(const char *head)
 876{
 877        const char *head_file = git_path(SEQ_HEAD_FILE);
 878        static struct lock_file head_lock;
 879        struct strbuf buf = STRBUF_INIT;
 880        int fd;
 881
 882        fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
 883        strbuf_addf(&buf, "%s\n", head);
 884        if (write_in_full(fd, buf.buf, buf.len) < 0)
 885                die_errno(_("Could not write to %s"), head_file);
 886        if (commit_lock_file(&head_lock) < 0)
 887                die(_("Error wrapping up %s."), head_file);
 888}
 889
 890static int reset_for_rollback(const unsigned char *sha1)
 891{
 892        const char *argv[4];    /* reset --merge <arg> + NULL */
 893        argv[0] = "reset";
 894        argv[1] = "--merge";
 895        argv[2] = sha1_to_hex(sha1);
 896        argv[3] = NULL;
 897        return run_command_v_opt(argv, RUN_GIT_CMD);
 898}
 899
 900static int rollback_single_pick(void)
 901{
 902        unsigned char head_sha1[20];
 903
 904        if (!file_exists(git_path("CHERRY_PICK_HEAD")) &&
 905            !file_exists(git_path("REVERT_HEAD")))
 906                return error(_("no cherry-pick or revert in progress"));
 907        if (!resolve_ref("HEAD", head_sha1, 0, NULL))
 908                return error(_("cannot resolve HEAD"));
 909        if (is_null_sha1(head_sha1))
 910                return error(_("cannot abort from a branch yet to be born"));
 911        return reset_for_rollback(head_sha1);
 912}
 913
 914static int sequencer_rollback(struct replay_opts *opts)
 915{
 916        const char *filename;
 917        FILE *f;
 918        unsigned char sha1[20];
 919        struct strbuf buf = STRBUF_INIT;
 920
 921        filename = git_path(SEQ_HEAD_FILE);
 922        f = fopen(filename, "r");
 923        if (!f && errno == ENOENT) {
 924                /*
 925                 * There is no multiple-cherry-pick in progress.
 926                 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
 927                 * a single-cherry-pick in progress, abort that.
 928                 */
 929                return rollback_single_pick();
 930        }
 931        if (!f)
 932                return error(_("cannot open %s: %s"), filename,
 933                                                strerror(errno));
 934        if (strbuf_getline(&buf, f, '\n')) {
 935                error(_("cannot read %s: %s"), filename, ferror(f) ?
 936                        strerror(errno) : _("unexpected end of file"));
 937                goto fail;
 938        }
 939        if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
 940                error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
 941                        filename);
 942                goto fail;
 943        }
 944        if (reset_for_rollback(sha1))
 945                goto fail;
 946        strbuf_release(&buf);
 947        fclose(f);
 948        return 0;
 949fail:
 950        strbuf_release(&buf);
 951        fclose(f);
 952        return -1;
 953}
 954
 955static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
 956{
 957        const char *todo_file = git_path(SEQ_TODO_FILE);
 958        static struct lock_file todo_lock;
 959        struct strbuf buf = STRBUF_INIT;
 960        int fd;
 961
 962        fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
 963        if (format_todo(&buf, todo_list, opts) < 0)
 964                die(_("Could not format %s."), todo_file);
 965        if (write_in_full(fd, buf.buf, buf.len) < 0) {
 966                strbuf_release(&buf);
 967                die_errno(_("Could not write to %s"), todo_file);
 968        }
 969        if (commit_lock_file(&todo_lock) < 0) {
 970                strbuf_release(&buf);
 971                die(_("Error wrapping up %s."), todo_file);
 972        }
 973        strbuf_release(&buf);
 974}
 975
 976static void save_opts(struct replay_opts *opts)
 977{
 978        const char *opts_file = git_path(SEQ_OPTS_FILE);
 979
 980        if (opts->no_commit)
 981                git_config_set_in_file(opts_file, "options.no-commit", "true");
 982        if (opts->edit)
 983                git_config_set_in_file(opts_file, "options.edit", "true");
 984        if (opts->signoff)
 985                git_config_set_in_file(opts_file, "options.signoff", "true");
 986        if (opts->record_origin)
 987                git_config_set_in_file(opts_file, "options.record-origin", "true");
 988        if (opts->allow_ff)
 989                git_config_set_in_file(opts_file, "options.allow-ff", "true");
 990        if (opts->mainline) {
 991                struct strbuf buf = STRBUF_INIT;
 992                strbuf_addf(&buf, "%d", opts->mainline);
 993                git_config_set_in_file(opts_file, "options.mainline", buf.buf);
 994                strbuf_release(&buf);
 995        }
 996        if (opts->strategy)
 997                git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
 998        if (opts->xopts) {
 999                int i;
1000                for (i = 0; i < opts->xopts_nr; i++)
1001                        git_config_set_multivar_in_file(opts_file,
1002                                                        "options.strategy-option",
1003                                                        opts->xopts[i], "^$", 0);
1004        }
1005}
1006
1007static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
1008{
1009        struct commit_list *cur;
1010        int res;
1011
1012        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1013        if (opts->allow_ff)
1014                assert(!(opts->signoff || opts->no_commit ||
1015                                opts->record_origin || opts->edit));
1016        read_and_refresh_cache(opts);
1017
1018        for (cur = todo_list; cur; cur = cur->next) {
1019                save_todo(cur, opts);
1020                res = do_pick_commit(cur->item, opts);
1021                if (res) {
1022                        if (!cur->next)
1023                                /*
1024                                 * An error was encountered while
1025                                 * picking the last commit; the
1026                                 * sequencer state is useless now --
1027                                 * the user simply needs to resolve
1028                                 * the conflict and commit
1029                                 */
1030                                remove_sequencer_state(0);
1031                        return res;
1032                }
1033        }
1034
1035        /*
1036         * Sequence of picks finished successfully; cleanup by
1037         * removing the .git/sequencer directory
1038         */
1039        remove_sequencer_state(1);
1040        return 0;
1041}
1042
1043static int pick_revisions(struct replay_opts *opts)
1044{
1045        struct commit_list *todo_list = NULL;
1046        unsigned char sha1[20];
1047
1048        read_and_refresh_cache(opts);
1049
1050        /*
1051         * Decide what to do depending on the arguments; a fresh
1052         * cherry-pick should be handled differently from an existing
1053         * one that is being continued
1054         */
1055        if (opts->subcommand == REPLAY_REMOVE_STATE) {
1056                remove_sequencer_state(1);
1057                return 0;
1058        }
1059        if (opts->subcommand == REPLAY_ROLLBACK)
1060                return sequencer_rollback(opts);
1061        if (opts->subcommand == REPLAY_CONTINUE) {
1062                if (!file_exists(git_path(SEQ_TODO_FILE)))
1063                        return error(_("No %s in progress"), action_name(opts));
1064                read_populate_opts(&opts);
1065                read_populate_todo(&todo_list, opts);
1066
1067                /* Verify that the conflict has been resolved */
1068                if (!index_differs_from("HEAD", 0))
1069                        todo_list = todo_list->next;
1070                return pick_commits(todo_list, opts);
1071        }
1072
1073        /*
1074         * Start a new cherry-pick/ revert sequence; but
1075         * first, make sure that an existing one isn't in
1076         * progress
1077         */
1078
1079        walk_revs_populate_todo(&todo_list, opts);
1080        if (create_seq_dir() < 0)
1081                return -1;
1082        if (get_sha1("HEAD", sha1)) {
1083                if (opts->action == REVERT)
1084                        return error(_("Can't revert as initial commit"));
1085                return error(_("Can't cherry-pick into empty head"));
1086        }
1087        save_head(sha1_to_hex(sha1));
1088        save_opts(opts);
1089        return pick_commits(todo_list, opts);
1090}
1091
1092int cmd_revert(int argc, const char **argv, const char *prefix)
1093{
1094        struct replay_opts opts;
1095        int res;
1096
1097        memset(&opts, 0, sizeof(opts));
1098        if (isatty(0))
1099                opts.edit = 1;
1100        opts.action = REVERT;
1101        git_config(git_default_config, NULL);
1102        parse_args(argc, argv, &opts);
1103        res = pick_revisions(&opts);
1104        if (res < 0)
1105                die(_("revert failed"));
1106        return res;
1107}
1108
1109int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1110{
1111        struct replay_opts opts;
1112        int res;
1113
1114        memset(&opts, 0, sizeof(opts));
1115        opts.action = CHERRY_PICK;
1116        git_config(git_default_config, NULL);
1117        parse_args(argc, argv, &opts);
1118        res = pick_revisions(&opts);
1119        if (res < 0)
1120                die(_("cherry-pick failed"));
1121        return res;
1122}