builtin-checkout.con commit checkout --ours/--theirs: allow checking out one side of a conflicting merge (38901a4)
   1#include "cache.h"
   2#include "builtin.h"
   3#include "parse-options.h"
   4#include "refs.h"
   5#include "commit.h"
   6#include "tree.h"
   7#include "tree-walk.h"
   8#include "unpack-trees.h"
   9#include "dir.h"
  10#include "run-command.h"
  11#include "merge-recursive.h"
  12#include "branch.h"
  13#include "diff.h"
  14#include "revision.h"
  15#include "remote.h"
  16
  17static const char * const checkout_usage[] = {
  18        "git checkout [options] <branch>",
  19        "git checkout [options] [<branch>] -- <file>...",
  20        NULL,
  21};
  22
  23struct checkout_opts {
  24        int quiet;
  25        int merge;
  26        int force;
  27        int writeout_stage;
  28        int writeout_error;
  29
  30        const char *new_branch;
  31        int new_branch_log;
  32        enum branch_track track;
  33};
  34
  35static int post_checkout_hook(struct commit *old, struct commit *new,
  36                              int changed)
  37{
  38        struct child_process proc;
  39        const char *name = git_path("hooks/post-checkout");
  40        const char *argv[5];
  41
  42        if (access(name, X_OK) < 0)
  43                return 0;
  44
  45        memset(&proc, 0, sizeof(proc));
  46        argv[0] = name;
  47        argv[1] = xstrdup(sha1_to_hex(old->object.sha1));
  48        argv[2] = xstrdup(sha1_to_hex(new->object.sha1));
  49        argv[3] = changed ? "1" : "0";
  50        argv[4] = NULL;
  51        proc.argv = argv;
  52        proc.no_stdin = 1;
  53        proc.stdout_to_stderr = 1;
  54        return run_command(&proc);
  55}
  56
  57static int update_some(const unsigned char *sha1, const char *base, int baselen,
  58                const char *pathname, unsigned mode, int stage, void *context)
  59{
  60        int len;
  61        struct cache_entry *ce;
  62
  63        if (S_ISGITLINK(mode))
  64                return 0;
  65
  66        if (S_ISDIR(mode))
  67                return READ_TREE_RECURSIVE;
  68
  69        len = baselen + strlen(pathname);
  70        ce = xcalloc(1, cache_entry_size(len));
  71        hashcpy(ce->sha1, sha1);
  72        memcpy(ce->name, base, baselen);
  73        memcpy(ce->name + baselen, pathname, len - baselen);
  74        ce->ce_flags = create_ce_flags(len, 0);
  75        ce->ce_mode = create_ce_mode(mode);
  76        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
  77        return 0;
  78}
  79
  80static int read_tree_some(struct tree *tree, const char **pathspec)
  81{
  82        read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
  83
  84        /* update the index with the given tree's info
  85         * for all args, expanding wildcards, and exit
  86         * with any non-zero return code.
  87         */
  88        return 0;
  89}
  90
  91static int skip_same_name(struct cache_entry *ce, int pos)
  92{
  93        while (++pos < active_nr &&
  94               !strcmp(active_cache[pos]->name, ce->name))
  95                ; /* skip */
  96        return pos;
  97}
  98
  99static int check_stage(int stage, struct cache_entry *ce, int pos)
 100{
 101        while (pos < active_nr &&
 102               !strcmp(active_cache[pos]->name, ce->name)) {
 103                if (ce_stage(active_cache[pos]) == stage)
 104                        return 0;
 105                pos++;
 106        }
 107        return error("path '%s' does not have %s version",
 108                     ce->name,
 109                     (stage == 2) ? "our" : "their");
 110}
 111
 112static int checkout_stage(int stage, struct cache_entry *ce, int pos,
 113                          struct checkout *state)
 114{
 115        while (pos < active_nr &&
 116               !strcmp(active_cache[pos]->name, ce->name)) {
 117                if (ce_stage(active_cache[pos]) == stage)
 118                        return checkout_entry(active_cache[pos], state, NULL);
 119                pos++;
 120        }
 121        return error("path '%s' does not have %s version",
 122                     ce->name,
 123                     (stage == 2) ? "our" : "their");
 124}
 125
 126static int checkout_paths(struct tree *source_tree, const char **pathspec,
 127                          struct checkout_opts *opts)
 128{
 129        int pos;
 130        struct checkout state;
 131        static char *ps_matched;
 132        unsigned char rev[20];
 133        int flag;
 134        struct commit *head;
 135        int errs = 0;
 136        int stage = opts->writeout_stage;
 137        int newfd;
 138        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 139
 140        newfd = hold_locked_index(lock_file, 1);
 141        read_cache();
 142
 143        if (source_tree)
 144                read_tree_some(source_tree, pathspec);
 145
 146        for (pos = 0; pathspec[pos]; pos++)
 147                ;
 148        ps_matched = xcalloc(1, pos);
 149
 150        for (pos = 0; pos < active_nr; pos++) {
 151                struct cache_entry *ce = active_cache[pos];
 152                pathspec_match(pathspec, ps_matched, ce->name, 0);
 153        }
 154
 155        if (report_path_error(ps_matched, pathspec, 0))
 156                return 1;
 157
 158        /* Any unmerged paths? */
 159        for (pos = 0; pos < active_nr; pos++) {
 160                struct cache_entry *ce = active_cache[pos];
 161                if (pathspec_match(pathspec, NULL, ce->name, 0)) {
 162                        if (!ce_stage(ce))
 163                                continue;
 164                        if (opts->force) {
 165                                warning("path '%s' is unmerged", ce->name);
 166                        } else if (stage) {
 167                                errs |= check_stage(stage, ce, pos);
 168                        } else {
 169                                errs = 1;
 170                                error("path '%s' is unmerged", ce->name);
 171                        }
 172                        pos = skip_same_name(ce, pos) - 1;
 173                }
 174        }
 175        if (errs)
 176                return 1;
 177
 178        /* Now we are committed to check them out */
 179        memset(&state, 0, sizeof(state));
 180        state.force = 1;
 181        state.refresh_cache = 1;
 182        for (pos = 0; pos < active_nr; pos++) {
 183                struct cache_entry *ce = active_cache[pos];
 184                if (pathspec_match(pathspec, NULL, ce->name, 0)) {
 185                        if (!ce_stage(ce)) {
 186                                errs |= checkout_entry(ce, &state, NULL);
 187                                continue;
 188                        }
 189                        if (stage)
 190                                errs |= checkout_stage(stage, ce, pos, &state);
 191                        pos = skip_same_name(ce, pos) - 1;
 192                }
 193        }
 194
 195        if (write_cache(newfd, active_cache, active_nr) ||
 196            commit_locked_index(lock_file))
 197                die("unable to write new index file");
 198
 199        resolve_ref("HEAD", rev, 0, &flag);
 200        head = lookup_commit_reference_gently(rev, 1);
 201
 202        errs |= post_checkout_hook(head, head, 0);
 203        return errs;
 204}
 205
 206static void show_local_changes(struct object *head)
 207{
 208        struct rev_info rev;
 209        /* I think we want full paths, even if we're in a subdirectory. */
 210        init_revisions(&rev, NULL);
 211        rev.abbrev = 0;
 212        rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
 213        add_pending_object(&rev, head, NULL);
 214        run_diff_index(&rev, 0);
 215}
 216
 217static void describe_detached_head(char *msg, struct commit *commit)
 218{
 219        struct strbuf sb;
 220        strbuf_init(&sb, 0);
 221        parse_commit(commit);
 222        pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, NULL, NULL, 0, 0);
 223        fprintf(stderr, "%s %s... %s\n", msg,
 224                find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
 225        strbuf_release(&sb);
 226}
 227
 228static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree)
 229{
 230        struct unpack_trees_options opts;
 231        struct tree_desc tree_desc;
 232
 233        memset(&opts, 0, sizeof(opts));
 234        opts.head_idx = -1;
 235        opts.update = worktree;
 236        opts.skip_unmerged = !worktree;
 237        opts.reset = 1;
 238        opts.merge = 1;
 239        opts.fn = oneway_merge;
 240        opts.verbose_update = !o->quiet;
 241        opts.src_index = &the_index;
 242        opts.dst_index = &the_index;
 243        parse_tree(tree);
 244        init_tree_desc(&tree_desc, tree->buffer, tree->size);
 245        switch (unpack_trees(1, &tree_desc, &opts)) {
 246        case -2:
 247                o->writeout_error = 1;
 248                /*
 249                 * We return 0 nevertheless, as the index is all right
 250                 * and more importantly we have made best efforts to
 251                 * update paths in the work tree, and we cannot revert
 252                 * them.
 253                 */
 254        case 0:
 255                return 0;
 256        default:
 257                return 128;
 258        }
 259}
 260
 261struct branch_info {
 262        const char *name; /* The short name used */
 263        const char *path; /* The full name of a real branch */
 264        struct commit *commit; /* The named commit */
 265};
 266
 267static void setup_branch_path(struct branch_info *branch)
 268{
 269        struct strbuf buf;
 270        strbuf_init(&buf, 0);
 271        strbuf_addstr(&buf, "refs/heads/");
 272        strbuf_addstr(&buf, branch->name);
 273        branch->path = strbuf_detach(&buf, NULL);
 274}
 275
 276static int merge_working_tree(struct checkout_opts *opts,
 277                              struct branch_info *old, struct branch_info *new)
 278{
 279        int ret;
 280        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 281        int newfd = hold_locked_index(lock_file, 1);
 282        read_cache();
 283
 284        if (opts->force) {
 285                ret = reset_tree(new->commit->tree, opts, 1);
 286                if (ret)
 287                        return ret;
 288        } else {
 289                struct tree_desc trees[2];
 290                struct tree *tree;
 291                struct unpack_trees_options topts;
 292
 293                memset(&topts, 0, sizeof(topts));
 294                topts.head_idx = -1;
 295                topts.src_index = &the_index;
 296                topts.dst_index = &the_index;
 297
 298                topts.msgs.not_uptodate_file = "You have local changes to '%s'; cannot switch branches.";
 299
 300                refresh_cache(REFRESH_QUIET);
 301
 302                if (unmerged_cache()) {
 303                        error("you need to resolve your current index first");
 304                        return 1;
 305                }
 306
 307                /* 2-way merge to the new branch */
 308                topts.update = 1;
 309                topts.merge = 1;
 310                topts.gently = opts->merge;
 311                topts.verbose_update = !opts->quiet;
 312                topts.fn = twoway_merge;
 313                topts.dir = xcalloc(1, sizeof(*topts.dir));
 314                topts.dir->show_ignored = 1;
 315                topts.dir->exclude_per_dir = ".gitignore";
 316                tree = parse_tree_indirect(old->commit->object.sha1);
 317                init_tree_desc(&trees[0], tree->buffer, tree->size);
 318                tree = parse_tree_indirect(new->commit->object.sha1);
 319                init_tree_desc(&trees[1], tree->buffer, tree->size);
 320
 321                ret = unpack_trees(2, trees, &topts);
 322                if (ret == -1) {
 323                        /*
 324                         * Unpack couldn't do a trivial merge; either
 325                         * give up or do a real merge, depending on
 326                         * whether the merge flag was used.
 327                         */
 328                        struct tree *result;
 329                        struct tree *work;
 330                        if (!opts->merge)
 331                                return 1;
 332                        parse_commit(old->commit);
 333
 334                        /* Do more real merge */
 335
 336                        /*
 337                         * We update the index fully, then write the
 338                         * tree from the index, then merge the new
 339                         * branch with the current tree, with the old
 340                         * branch as the base. Then we reset the index
 341                         * (but not the working tree) to the new
 342                         * branch, leaving the working tree as the
 343                         * merged version, but skipping unmerged
 344                         * entries in the index.
 345                         */
 346
 347                        add_files_to_cache(NULL, NULL, 0);
 348                        work = write_tree_from_memory();
 349
 350                        ret = reset_tree(new->commit->tree, opts, 1);
 351                        if (ret)
 352                                return ret;
 353                        merge_trees(new->commit->tree, work, old->commit->tree,
 354                                    new->name, "local", &result);
 355                        ret = reset_tree(new->commit->tree, opts, 0);
 356                        if (ret)
 357                                return ret;
 358                }
 359        }
 360
 361        if (write_cache(newfd, active_cache, active_nr) ||
 362            commit_locked_index(lock_file))
 363                die("unable to write new index file");
 364
 365        if (!opts->force)
 366                show_local_changes(&new->commit->object);
 367
 368        return 0;
 369}
 370
 371static void report_tracking(struct branch_info *new)
 372{
 373        struct strbuf sb = STRBUF_INIT;
 374        struct branch *branch = branch_get(new->name);
 375
 376        if (!format_tracking_info(branch, &sb))
 377                return;
 378        fputs(sb.buf, stdout);
 379        strbuf_release(&sb);
 380}
 381
 382static void update_refs_for_switch(struct checkout_opts *opts,
 383                                   struct branch_info *old,
 384                                   struct branch_info *new)
 385{
 386        struct strbuf msg;
 387        const char *old_desc;
 388        if (opts->new_branch) {
 389                create_branch(old->name, opts->new_branch, new->name, 0,
 390                              opts->new_branch_log, opts->track);
 391                new->name = opts->new_branch;
 392                setup_branch_path(new);
 393        }
 394
 395        strbuf_init(&msg, 0);
 396        old_desc = old->name;
 397        if (!old_desc)
 398                old_desc = sha1_to_hex(old->commit->object.sha1);
 399        strbuf_addf(&msg, "checkout: moving from %s to %s",
 400                    old_desc, new->name);
 401
 402        if (new->path) {
 403                create_symref("HEAD", new->path, msg.buf);
 404                if (!opts->quiet) {
 405                        if (old->path && !strcmp(new->path, old->path))
 406                                fprintf(stderr, "Already on \"%s\"\n",
 407                                        new->name);
 408                        else
 409                                fprintf(stderr, "Switched to%s branch \"%s\"\n",
 410                                        opts->new_branch ? " a new" : "",
 411                                        new->name);
 412                }
 413        } else if (strcmp(new->name, "HEAD")) {
 414                update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
 415                           REF_NODEREF, DIE_ON_ERR);
 416                if (!opts->quiet) {
 417                        if (old->path)
 418                                fprintf(stderr, "Note: moving to \"%s\" which isn't a local branch\nIf you want to create a new branch from this checkout, you may do so\n(now or later) by using -b with the checkout command again. Example:\n  git checkout -b <new_branch_name>\n", new->name);
 419                        describe_detached_head("HEAD is now at", new->commit);
 420                }
 421        }
 422        remove_branch_state();
 423        strbuf_release(&msg);
 424        if (!opts->quiet && (new->path || !strcmp(new->name, "HEAD")))
 425                report_tracking(new);
 426}
 427
 428static int switch_branches(struct checkout_opts *opts, struct branch_info *new)
 429{
 430        int ret = 0;
 431        struct branch_info old;
 432        unsigned char rev[20];
 433        int flag;
 434        memset(&old, 0, sizeof(old));
 435        old.path = resolve_ref("HEAD", rev, 0, &flag);
 436        old.commit = lookup_commit_reference_gently(rev, 1);
 437        if (!(flag & REF_ISSYMREF))
 438                old.path = NULL;
 439
 440        if (old.path && !prefixcmp(old.path, "refs/heads/"))
 441                old.name = old.path + strlen("refs/heads/");
 442
 443        if (!new->name) {
 444                new->name = "HEAD";
 445                new->commit = old.commit;
 446                if (!new->commit)
 447                        die("You are on a branch yet to be born");
 448                parse_commit(new->commit);
 449        }
 450
 451        /*
 452         * If the new thing isn't a branch and isn't HEAD and we're
 453         * not starting a new branch, and we want messages, and we
 454         * weren't on a branch, and we're moving to a new commit,
 455         * describe the old commit.
 456         */
 457        if (!new->path && strcmp(new->name, "HEAD") && !opts->new_branch &&
 458            !opts->quiet && !old.path && new->commit != old.commit)
 459                describe_detached_head("Previous HEAD position was", old.commit);
 460
 461        if (!old.commit) {
 462                if (!opts->quiet) {
 463                        fprintf(stderr, "warning: You appear to be on a branch yet to be born.\n");
 464                        fprintf(stderr, "warning: Forcing checkout of %s.\n", new->name);
 465                }
 466                opts->force = 1;
 467        }
 468
 469        ret = merge_working_tree(opts, &old, new);
 470        if (ret)
 471                return ret;
 472
 473        update_refs_for_switch(opts, &old, new);
 474
 475        ret = post_checkout_hook(old.commit, new->commit, 1);
 476        return ret || opts->writeout_error;
 477}
 478
 479int cmd_checkout(int argc, const char **argv, const char *prefix)
 480{
 481        struct checkout_opts opts;
 482        unsigned char rev[20];
 483        const char *arg;
 484        struct branch_info new;
 485        struct tree *source_tree = NULL;
 486        struct option options[] = {
 487                OPT__QUIET(&opts.quiet),
 488                OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"),
 489                OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"),
 490                OPT_SET_INT('t', "track",  &opts.track, "track",
 491                        BRANCH_TRACK_EXPLICIT),
 492                OPT_SET_INT('2', "ours", &opts.writeout_stage, "stage",
 493                            2),
 494                OPT_SET_INT('3', "theirs", &opts.writeout_stage, "stage",
 495                            3),
 496                OPT_BOOLEAN('f', NULL, &opts.force, "force"),
 497                OPT_BOOLEAN('m', NULL, &opts.merge, "merge"),
 498                OPT_END(),
 499        };
 500        int has_dash_dash;
 501
 502        memset(&opts, 0, sizeof(opts));
 503        memset(&new, 0, sizeof(new));
 504
 505        git_config(git_default_config, NULL);
 506
 507        opts.track = git_branch_track;
 508
 509        argc = parse_options(argc, argv, options, checkout_usage,
 510                             PARSE_OPT_KEEP_DASHDASH);
 511
 512        if (!opts.new_branch && (opts.track != git_branch_track))
 513                die("git checkout: --track and --no-track require -b");
 514
 515        if (opts.force && opts.merge)
 516                die("git checkout: -f and -m are incompatible");
 517
 518        /*
 519         * case 1: git checkout <ref> -- [<paths>]
 520         *
 521         *   <ref> must be a valid tree, everything after the '--' must be
 522         *   a path.
 523         *
 524         * case 2: git checkout -- [<paths>]
 525         *
 526         *   everything after the '--' must be paths.
 527         *
 528         * case 3: git checkout <something> [<paths>]
 529         *
 530         *   With no paths, if <something> is a commit, that is to
 531         *   switch to the branch or detach HEAD at it.
 532         *
 533         *   Otherwise <something> shall not be ambiguous.
 534         *   - If it's *only* a reference, treat it like case (1).
 535         *   - If it's only a path, treat it like case (2).
 536         *   - else: fail.
 537         *
 538         */
 539        if (argc) {
 540                if (!strcmp(argv[0], "--")) {       /* case (2) */
 541                        argv++;
 542                        argc--;
 543                        goto no_reference;
 544                }
 545
 546                arg = argv[0];
 547                has_dash_dash = (argc > 1) && !strcmp(argv[1], "--");
 548
 549                if (get_sha1(arg, rev)) {
 550                        if (has_dash_dash)          /* case (1) */
 551                                die("invalid reference: %s", arg);
 552                        goto no_reference;          /* case (3 -> 2) */
 553                }
 554
 555                /* we can't end up being in (2) anymore, eat the argument */
 556                argv++;
 557                argc--;
 558
 559                if ((new.commit = lookup_commit_reference_gently(rev, 1))) {
 560                        new.name = arg;
 561                        setup_branch_path(&new);
 562                        if (resolve_ref(new.path, rev, 1, NULL))
 563                                new.commit = lookup_commit_reference(rev);
 564                        else
 565                                new.path = NULL;
 566                        parse_commit(new.commit);
 567                        source_tree = new.commit->tree;
 568                } else
 569                        source_tree = parse_tree_indirect(rev);
 570
 571                if (!source_tree)                   /* case (1): want a tree */
 572                        die("reference is not a tree: %s", arg);
 573                if (!has_dash_dash) {/* case (3 -> 1) */
 574                        /*
 575                         * Do not complain the most common case
 576                         *      git checkout branch
 577                         * even if there happen to be a file called 'branch';
 578                         * it would be extremely annoying.
 579                         */
 580                        if (argc)
 581                                verify_non_filename(NULL, arg);
 582                }
 583                else {
 584                        argv++;
 585                        argc--;
 586                }
 587        }
 588
 589no_reference:
 590        if (argc) {
 591                const char **pathspec = get_pathspec(prefix, argv);
 592
 593                if (!pathspec)
 594                        die("invalid path specification");
 595
 596                /* Checkout paths */
 597                if (opts.new_branch || opts.merge) {
 598                        if (argc == 1) {
 599                                die("git checkout: updating paths is incompatible with switching branches.\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]);
 600                        } else {
 601                                die("git checkout: updating paths is incompatible with switching branches.");
 602                        }
 603                }
 604
 605                return checkout_paths(source_tree, pathspec, &opts);
 606        }
 607
 608        if (new.name && !new.commit) {
 609                die("Cannot switch branch to a non-commit.");
 610        }
 611        if (opts.writeout_stage)
 612                die("--ours/--theirs is incompatible with switching branches.");
 613
 614        return switch_branches(&opts, &new);
 615}