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