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