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