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