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