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