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