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