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