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