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