f75c9cb6c83473bf9e499bbe71f06d4c0cc73110
   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
  17/*
  18 * This implements the builtins revert and cherry-pick.
  19 *
  20 * Copyright (c) 2007 Johannes E. Schindelin
  21 *
  22 * Based on git-revert.sh, which is
  23 *
  24 * Copyright (c) 2005 Linus Torvalds
  25 * Copyright (c) 2005 Junio C Hamano
  26 */
  27
  28static const char * const revert_usage[] = {
  29        "git revert [options] <commit-ish>",
  30        NULL
  31};
  32
  33static const char * const cherry_pick_usage[] = {
  34        "git cherry-pick [options] <commit-ish>",
  35        NULL
  36};
  37
  38enum replay_action { REVERT, CHERRY_PICK };
  39
  40struct replay_opts {
  41        enum replay_action action;
  42
  43        /* Boolean options */
  44        int edit;
  45        int record_origin;
  46        int no_commit;
  47        int signoff;
  48        int allow_ff;
  49        int allow_rerere_auto;
  50
  51        int mainline;
  52        int commit_argc;
  53        const char **commit_argv;
  54
  55        /* Merge strategy */
  56        const char *strategy;
  57        const char **xopts;
  58        size_t xopts_nr, xopts_alloc;
  59};
  60
  61#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
  62
  63static const char *action_name(const struct replay_opts *opts)
  64{
  65        return opts->action == REVERT ? "revert" : "cherry-pick";
  66}
  67
  68static char *get_encoding(const char *message);
  69
  70static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
  71{
  72        return opts->action == REVERT ? revert_usage : cherry_pick_usage;
  73}
  74
  75static int option_parse_x(const struct option *opt,
  76                          const char *arg, int unset)
  77{
  78        struct replay_opts **opts_ptr = opt->value;
  79        struct replay_opts *opts = *opts_ptr;
  80
  81        if (unset)
  82                return 0;
  83
  84        ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
  85        opts->xopts[opts->xopts_nr++] = xstrdup(arg);
  86        return 0;
  87}
  88
  89static void verify_opt_compatible(const char *me, const char *base_opt, ...)
  90{
  91        const char *this_opt;
  92        va_list ap;
  93
  94        va_start(ap, base_opt);
  95        while ((this_opt = va_arg(ap, const char *))) {
  96                if (va_arg(ap, int))
  97                        break;
  98        }
  99        va_end(ap);
 100
 101        if (this_opt)
 102                die(_("%s: %s cannot be used with %s"), me, this_opt, base_opt);
 103}
 104
 105static void parse_args(int argc, const char **argv, struct replay_opts *opts)
 106{
 107        const char * const * usage_str = revert_or_cherry_pick_usage(opts);
 108        const char *me = action_name(opts);
 109        int noop;
 110        struct option options[] = {
 111                OPT_BOOLEAN('n', "no-commit", &opts->no_commit, "don't automatically commit"),
 112                OPT_BOOLEAN('e', "edit", &opts->edit, "edit the commit message"),
 113                { OPTION_BOOLEAN, 'r', NULL, &noop, NULL, "no-op (backward compatibility)",
 114                  PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 0 },
 115                OPT_BOOLEAN('s', "signoff", &opts->signoff, "add Signed-off-by:"),
 116                OPT_INTEGER('m', "mainline", &opts->mainline, "parent number"),
 117                OPT_RERERE_AUTOUPDATE(&opts->allow_rerere_auto),
 118                OPT_STRING(0, "strategy", &opts->strategy, "strategy", "merge strategy"),
 119                OPT_CALLBACK('X', "strategy-option", &opts, "option",
 120                        "option for merge strategy", option_parse_x),
 121                OPT_END(),
 122                OPT_END(),
 123                OPT_END(),
 124        };
 125
 126        if (opts->action == CHERRY_PICK) {
 127                struct option cp_extra[] = {
 128                        OPT_BOOLEAN('x', NULL, &opts->record_origin, "append commit name"),
 129                        OPT_BOOLEAN(0, "ff", &opts->allow_ff, "allow fast-forward"),
 130                        OPT_END(),
 131                };
 132                if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
 133                        die(_("program error"));
 134        }
 135
 136        opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
 137                                        PARSE_OPT_KEEP_ARGV0 |
 138                                        PARSE_OPT_KEEP_UNKNOWN);
 139        if (opts->commit_argc < 2)
 140                usage_with_options(usage_str, options);
 141
 142        if (opts->allow_ff)
 143                verify_opt_compatible(me, "--ff",
 144                                "--signoff", opts->signoff,
 145                                "--no-commit", opts->no_commit,
 146                                "-x", opts->record_origin,
 147                                "--edit", opts->edit,
 148                                NULL);
 149        opts->commit_argv = argv;
 150}
 151
 152struct commit_message {
 153        char *parent_label;
 154        const char *label;
 155        const char *subject;
 156        char *reencoded_message;
 157        const char *message;
 158};
 159
 160static int get_message(struct commit *commit, struct commit_message *out)
 161{
 162        const char *encoding;
 163        const char *abbrev, *subject;
 164        int abbrev_len, subject_len;
 165        char *q;
 166
 167        if (!commit->buffer)
 168                return -1;
 169        encoding = get_encoding(commit->buffer);
 170        if (!encoding)
 171                encoding = "UTF-8";
 172        if (!git_commit_encoding)
 173                git_commit_encoding = "UTF-8";
 174
 175        out->reencoded_message = NULL;
 176        out->message = commit->buffer;
 177        if (strcmp(encoding, git_commit_encoding))
 178                out->reencoded_message = reencode_string(commit->buffer,
 179                                        git_commit_encoding, encoding);
 180        if (out->reencoded_message)
 181                out->message = out->reencoded_message;
 182
 183        abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
 184        abbrev_len = strlen(abbrev);
 185
 186        subject_len = find_commit_subject(out->message, &subject);
 187
 188        out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
 189                              strlen("... ") + subject_len + 1);
 190        q = out->parent_label;
 191        q = mempcpy(q, "parent of ", strlen("parent of "));
 192        out->label = q;
 193        q = mempcpy(q, abbrev, abbrev_len);
 194        q = mempcpy(q, "... ", strlen("... "));
 195        out->subject = q;
 196        q = mempcpy(q, subject, subject_len);
 197        *q = '\0';
 198        return 0;
 199}
 200
 201static void free_message(struct commit_message *msg)
 202{
 203        free(msg->parent_label);
 204        free(msg->reencoded_message);
 205}
 206
 207static char *get_encoding(const char *message)
 208{
 209        const char *p = message, *eol;
 210
 211        while (*p && *p != '\n') {
 212                for (eol = p + 1; *eol && *eol != '\n'; eol++)
 213                        ; /* do nothing */
 214                if (!prefixcmp(p, "encoding ")) {
 215                        char *result = xmalloc(eol - 8 - p);
 216                        strlcpy(result, p + 9, eol - 8 - p);
 217                        return result;
 218                }
 219                p = eol;
 220                if (*p == '\n')
 221                        p++;
 222        }
 223        return NULL;
 224}
 225
 226static void write_cherry_pick_head(struct commit *commit)
 227{
 228        int fd;
 229        struct strbuf buf = STRBUF_INIT;
 230
 231        strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
 232
 233        fd = open(git_path("CHERRY_PICK_HEAD"), O_WRONLY | O_CREAT, 0666);
 234        if (fd < 0)
 235                die_errno(_("Could not open '%s' for writing"),
 236                          git_path("CHERRY_PICK_HEAD"));
 237        if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
 238                die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
 239        strbuf_release(&buf);
 240}
 241
 242static void print_advice(void)
 243{
 244        char *msg = getenv("GIT_CHERRY_PICK_HELP");
 245
 246        if (msg) {
 247                fprintf(stderr, "%s\n", msg);
 248                /*
 249                 * A conflict has occured but the porcelain
 250                 * (typically rebase --interactive) wants to take care
 251                 * of the commit itself so remove CHERRY_PICK_HEAD
 252                 */
 253                unlink(git_path("CHERRY_PICK_HEAD"));
 254                return;
 255        }
 256
 257        advise("after resolving the conflicts, mark the corrected paths");
 258        advise("with 'git add <paths>' or 'git rm <paths>'");
 259        advise("and commit the result with 'git commit'");
 260}
 261
 262static void write_message(struct strbuf *msgbuf, const char *filename)
 263{
 264        static struct lock_file msg_file;
 265
 266        int msg_fd = hold_lock_file_for_update(&msg_file, filename,
 267                                               LOCK_DIE_ON_ERROR);
 268        if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
 269                die_errno(_("Could not write to %s."), filename);
 270        strbuf_release(msgbuf);
 271        if (commit_lock_file(&msg_file) < 0)
 272                die(_("Error wrapping up %s"), filename);
 273}
 274
 275static struct tree *empty_tree(void)
 276{
 277        struct tree *tree = xcalloc(1, sizeof(struct tree));
 278
 279        tree->object.parsed = 1;
 280        tree->object.type = OBJ_TREE;
 281        pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
 282        return tree;
 283}
 284
 285static NORETURN void die_dirty_index(struct replay_opts *opts)
 286{
 287        if (read_cache_unmerged()) {
 288                die_resolve_conflict(action_name(opts));
 289        } else {
 290                if (advice_commit_before_merge) {
 291                        if (opts->action == REVERT)
 292                                die(_("Your local changes would be overwritten by revert.\n"
 293                                          "Please, commit your changes or stash them to proceed."));
 294                        else
 295                                die(_("Your local changes would be overwritten by cherry-pick.\n"
 296                                          "Please, commit your changes or stash them to proceed."));
 297                } else {
 298                        if (opts->action == REVERT)
 299                                die(_("Your local changes would be overwritten by revert.\n"));
 300                        else
 301                                die(_("Your local changes would be overwritten by cherry-pick.\n"));
 302                }
 303        }
 304}
 305
 306static int fast_forward_to(const unsigned char *to, const unsigned char *from)
 307{
 308        struct ref_lock *ref_lock;
 309
 310        read_cache();
 311        if (checkout_fast_forward(from, to))
 312                exit(1); /* the callee should have complained already */
 313        ref_lock = lock_any_ref_for_update("HEAD", from, 0);
 314        return write_ref_sha1(ref_lock, to, "cherry-pick");
 315}
 316
 317static int do_recursive_merge(struct commit *base, struct commit *next,
 318                              const char *base_label, const char *next_label,
 319                              unsigned char *head, struct strbuf *msgbuf,
 320                              struct replay_opts *opts)
 321{
 322        struct merge_options o;
 323        struct tree *result, *next_tree, *base_tree, *head_tree;
 324        int clean, index_fd;
 325        const char **xopt;
 326        static struct lock_file index_lock;
 327
 328        index_fd = hold_locked_index(&index_lock, 1);
 329
 330        read_cache();
 331
 332        init_merge_options(&o);
 333        o.ancestor = base ? base_label : "(empty tree)";
 334        o.branch1 = "HEAD";
 335        o.branch2 = next ? next_label : "(empty tree)";
 336
 337        head_tree = parse_tree_indirect(head);
 338        next_tree = next ? next->tree : empty_tree();
 339        base_tree = base ? base->tree : empty_tree();
 340
 341        for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
 342                parse_merge_opt(&o, *xopt);
 343
 344        clean = merge_trees(&o,
 345                            head_tree,
 346                            next_tree, base_tree, &result);
 347
 348        if (active_cache_changed &&
 349            (write_cache(index_fd, active_cache, active_nr) ||
 350             commit_locked_index(&index_lock)))
 351                /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
 352                die(_("%s: Unable to write new index file"), action_name(opts));
 353        rollback_lock_file(&index_lock);
 354
 355        if (!clean) {
 356                int i;
 357                strbuf_addstr(msgbuf, "\nConflicts:\n\n");
 358                for (i = 0; i < active_nr;) {
 359                        struct cache_entry *ce = active_cache[i++];
 360                        if (ce_stage(ce)) {
 361                                strbuf_addch(msgbuf, '\t');
 362                                strbuf_addstr(msgbuf, ce->name);
 363                                strbuf_addch(msgbuf, '\n');
 364                                while (i < active_nr && !strcmp(ce->name,
 365                                                active_cache[i]->name))
 366                                        i++;
 367                        }
 368                }
 369        }
 370
 371        return !clean;
 372}
 373
 374/*
 375 * If we are cherry-pick, and if the merge did not result in
 376 * hand-editing, we will hit this commit and inherit the original
 377 * author date and name.
 378 * If we are revert, or if our cherry-pick results in a hand merge,
 379 * we had better say that the current user is responsible for that.
 380 */
 381static int run_git_commit(const char *defmsg, struct replay_opts *opts)
 382{
 383        /* 6 is max possible length of our args array including NULL */
 384        const char *args[6];
 385        int i = 0;
 386
 387        args[i++] = "commit";
 388        args[i++] = "-n";
 389        if (opts->signoff)
 390                args[i++] = "-s";
 391        if (!opts->edit) {
 392                args[i++] = "-F";
 393                args[i++] = defmsg;
 394        }
 395        args[i] = NULL;
 396
 397        return run_command_v_opt(args, RUN_GIT_CMD);
 398}
 399
 400static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
 401{
 402        unsigned char head[20];
 403        struct commit *base, *next, *parent;
 404        const char *base_label, *next_label;
 405        struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
 406        char *defmsg = NULL;
 407        struct strbuf msgbuf = STRBUF_INIT;
 408        int res;
 409
 410        if (opts->no_commit) {
 411                /*
 412                 * We do not intend to commit immediately.  We just want to
 413                 * merge the differences in, so let's compute the tree
 414                 * that represents the "current" state for merge-recursive
 415                 * to work on.
 416                 */
 417                if (write_cache_as_tree(head, 0, NULL))
 418                        die (_("Your index file is unmerged."));
 419        } else {
 420                if (get_sha1("HEAD", head))
 421                        die (_("You do not have a valid HEAD"));
 422                if (index_differs_from("HEAD", 0))
 423                        die_dirty_index(opts);
 424        }
 425        discard_cache();
 426
 427        if (!commit->parents) {
 428                parent = NULL;
 429        }
 430        else if (commit->parents->next) {
 431                /* Reverting or cherry-picking a merge commit */
 432                int cnt;
 433                struct commit_list *p;
 434
 435                if (!opts->mainline)
 436                        die(_("Commit %s is a merge but no -m option was given."),
 437                            sha1_to_hex(commit->object.sha1));
 438
 439                for (cnt = 1, p = commit->parents;
 440                     cnt != opts->mainline && p;
 441                     cnt++)
 442                        p = p->next;
 443                if (cnt != opts->mainline || !p)
 444                        die(_("Commit %s does not have parent %d"),
 445                            sha1_to_hex(commit->object.sha1), opts->mainline);
 446                parent = p->item;
 447        } else if (0 < opts->mainline)
 448                die(_("Mainline was specified but commit %s is not a merge."),
 449                    sha1_to_hex(commit->object.sha1));
 450        else
 451                parent = commit->parents->item;
 452
 453        if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
 454                return fast_forward_to(commit->object.sha1, head);
 455
 456        if (parent && parse_commit(parent) < 0)
 457                /* TRANSLATORS: The first %s will be "revert" or
 458                   "cherry-pick", the second %s a SHA1 */
 459                die(_("%s: cannot parse parent commit %s"),
 460                    action_name(opts), sha1_to_hex(parent->object.sha1));
 461
 462        if (get_message(commit, &msg) != 0)
 463                die(_("Cannot get commit message for %s"),
 464                                sha1_to_hex(commit->object.sha1));
 465
 466        /*
 467         * "commit" is an existing commit.  We would want to apply
 468         * the difference it introduces since its first parent "prev"
 469         * on top of the current HEAD if we are cherry-pick.  Or the
 470         * reverse of it if we are revert.
 471         */
 472
 473        defmsg = git_pathdup("MERGE_MSG");
 474
 475        if (opts->action == REVERT) {
 476                base = commit;
 477                base_label = msg.label;
 478                next = parent;
 479                next_label = msg.parent_label;
 480                strbuf_addstr(&msgbuf, "Revert \"");
 481                strbuf_addstr(&msgbuf, msg.subject);
 482                strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
 483                strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 484
 485                if (commit->parents && commit->parents->next) {
 486                        strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
 487                        strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
 488                }
 489                strbuf_addstr(&msgbuf, ".\n");
 490        } else {
 491                const char *p;
 492
 493                base = parent;
 494                base_label = msg.parent_label;
 495                next = commit;
 496                next_label = msg.label;
 497
 498                /*
 499                 * Append the commit log message to msgbuf; it starts
 500                 * after the tree, parent, author, committer
 501                 * information followed by "\n\n".
 502                 */
 503                p = strstr(msg.message, "\n\n");
 504                if (p) {
 505                        p += 2;
 506                        strbuf_addstr(&msgbuf, p);
 507                }
 508
 509                if (opts->record_origin) {
 510                        strbuf_addstr(&msgbuf, "(cherry picked from commit ");
 511                        strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
 512                        strbuf_addstr(&msgbuf, ")\n");
 513                }
 514                if (!opts->no_commit)
 515                        write_cherry_pick_head(commit);
 516        }
 517
 518        if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
 519                res = do_recursive_merge(base, next, base_label, next_label,
 520                                         head, &msgbuf, opts);
 521                write_message(&msgbuf, defmsg);
 522        } else {
 523                struct commit_list *common = NULL;
 524                struct commit_list *remotes = NULL;
 525
 526                write_message(&msgbuf, defmsg);
 527
 528                commit_list_insert(base, &common);
 529                commit_list_insert(next, &remotes);
 530                res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
 531                                        common, sha1_to_hex(head), remotes);
 532                free_commit_list(common);
 533                free_commit_list(remotes);
 534        }
 535
 536        if (res) {
 537                error(opts->action == REVERT
 538                      ? _("could not revert %s... %s")
 539                      : _("could not apply %s... %s"),
 540                      find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
 541                      msg.subject);
 542                print_advice();
 543                rerere(opts->allow_rerere_auto);
 544        } else {
 545                if (!opts->no_commit)
 546                        res = run_git_commit(defmsg, opts);
 547        }
 548
 549        free_message(&msg);
 550        free(defmsg);
 551
 552        return res;
 553}
 554
 555static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
 556{
 557        int argc;
 558
 559        init_revisions(revs, NULL);
 560        revs->no_walk = 1;
 561        if (opts->action != REVERT)
 562                revs->reverse = 1;
 563
 564        argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
 565        if (argc > 1)
 566                usage(*revert_or_cherry_pick_usage(opts));
 567
 568        if (prepare_revision_walk(revs))
 569                die(_("revision walk setup failed"));
 570
 571        if (!revs->commits)
 572                die(_("empty commit set passed"));
 573}
 574
 575static void read_and_refresh_cache(struct replay_opts *opts)
 576{
 577        static struct lock_file index_lock;
 578        int index_fd = hold_locked_index(&index_lock, 0);
 579        if (read_index_preload(&the_index, NULL) < 0)
 580                die(_("git %s: failed to read the index"), action_name(opts));
 581        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
 582        if (the_index.cache_changed) {
 583                if (write_index(&the_index, index_fd) ||
 584                    commit_locked_index(&index_lock))
 585                        die(_("git %s: failed to refresh the index"), action_name(opts));
 586        }
 587        rollback_lock_file(&index_lock);
 588}
 589
 590static int pick_commits(struct replay_opts *opts)
 591{
 592        struct rev_info revs;
 593        struct commit *commit;
 594
 595        setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
 596        if (opts->allow_ff)
 597                assert(!(opts->signoff || opts->no_commit ||
 598                                opts->record_origin || opts->edit));
 599        read_and_refresh_cache(opts);
 600
 601        prepare_revs(&revs, opts);
 602
 603        while ((commit = get_revision(&revs))) {
 604                int res = do_pick_commit(commit, opts);
 605                if (res)
 606                        return res;
 607        }
 608
 609        return 0;
 610}
 611
 612int cmd_revert(int argc, const char **argv, const char *prefix)
 613{
 614        struct replay_opts opts;
 615
 616        memset(&opts, 0, sizeof(opts));
 617        if (isatty(0))
 618                opts.edit = 1;
 619        opts.action = REVERT;
 620        git_config(git_default_config, NULL);
 621        parse_args(argc, argv, &opts);
 622        return pick_commits(&opts);
 623}
 624
 625int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
 626{
 627        struct replay_opts opts;
 628
 629        memset(&opts, 0, sizeof(opts));
 630        opts.action = CHERRY_PICK;
 631        git_config(git_default_config, NULL);
 632        parse_args(argc, argv, &opts);
 633        return pick_commits(&opts);
 634}