builtin / checkout.con commit submodule: use new config API for worktree configurations (851e18c)
   1#include "builtin.h"
   2#include "lockfile.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 "cache-tree.h"
   9#include "unpack-trees.h"
  10#include "dir.h"
  11#include "run-command.h"
  12#include "merge-recursive.h"
  13#include "branch.h"
  14#include "diff.h"
  15#include "revision.h"
  16#include "remote.h"
  17#include "blob.h"
  18#include "xdiff-interface.h"
  19#include "ll-merge.h"
  20#include "resolve-undo.h"
  21#include "submodule-config.h"
  22#include "submodule.h"
  23#include "argv-array.h"
  24#include "sigchain.h"
  25
  26static const char * const checkout_usage[] = {
  27        N_("git checkout [<options>] <branch>"),
  28        N_("git checkout [<options>] [<branch>] -- <file>..."),
  29        NULL,
  30};
  31
  32struct checkout_opts {
  33        int patch_mode;
  34        int quiet;
  35        int merge;
  36        int force;
  37        int force_detach;
  38        int writeout_stage;
  39        int overwrite_ignore;
  40        int ignore_skipworktree;
  41        int ignore_other_worktrees;
  42
  43        const char *new_branch;
  44        const char *new_branch_force;
  45        const char *new_orphan_branch;
  46        int new_branch_log;
  47        enum branch_track track;
  48        struct diff_options diff_options;
  49
  50        int branch_exists;
  51        const char *prefix;
  52        struct pathspec pathspec;
  53        struct tree *source_tree;
  54
  55        const char *new_worktree;
  56        const char **saved_argv;
  57        int new_worktree_mode;
  58};
  59
  60static int post_checkout_hook(struct commit *old, struct commit *new,
  61                              int changed)
  62{
  63        return run_hook_le(NULL, "post-checkout",
  64                           sha1_to_hex(old ? old->object.sha1 : null_sha1),
  65                           sha1_to_hex(new ? new->object.sha1 : null_sha1),
  66                           changed ? "1" : "0", NULL);
  67        /* "new" can be NULL when checking out from the index before
  68           a commit exists. */
  69
  70}
  71
  72static int update_some(const unsigned char *sha1, struct strbuf *base,
  73                const char *pathname, unsigned mode, int stage, void *context)
  74{
  75        int len;
  76        struct cache_entry *ce;
  77        int pos;
  78
  79        if (S_ISDIR(mode))
  80                return READ_TREE_RECURSIVE;
  81
  82        len = base->len + strlen(pathname);
  83        ce = xcalloc(1, cache_entry_size(len));
  84        hashcpy(ce->sha1, sha1);
  85        memcpy(ce->name, base->buf, base->len);
  86        memcpy(ce->name + base->len, pathname, len - base->len);
  87        ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
  88        ce->ce_namelen = len;
  89        ce->ce_mode = create_ce_mode(mode);
  90
  91        /*
  92         * If the entry is the same as the current index, we can leave the old
  93         * entry in place. Whether it is UPTODATE or not, checkout_entry will
  94         * do the right thing.
  95         */
  96        pos = cache_name_pos(ce->name, ce->ce_namelen);
  97        if (pos >= 0) {
  98                struct cache_entry *old = active_cache[pos];
  99                if (ce->ce_mode == old->ce_mode &&
 100                    !hashcmp(ce->sha1, old->sha1)) {
 101                        old->ce_flags |= CE_UPDATE;
 102                        free(ce);
 103                        return 0;
 104                }
 105        }
 106
 107        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
 108        return 0;
 109}
 110
 111static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
 112{
 113        read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
 114
 115        /* update the index with the given tree's info
 116         * for all args, expanding wildcards, and exit
 117         * with any non-zero return code.
 118         */
 119        return 0;
 120}
 121
 122static int skip_same_name(const struct cache_entry *ce, int pos)
 123{
 124        while (++pos < active_nr &&
 125               !strcmp(active_cache[pos]->name, ce->name))
 126                ; /* skip */
 127        return pos;
 128}
 129
 130static int check_stage(int stage, const struct cache_entry *ce, int pos)
 131{
 132        while (pos < active_nr &&
 133               !strcmp(active_cache[pos]->name, ce->name)) {
 134                if (ce_stage(active_cache[pos]) == stage)
 135                        return 0;
 136                pos++;
 137        }
 138        if (stage == 2)
 139                return error(_("path '%s' does not have our version"), ce->name);
 140        else
 141                return error(_("path '%s' does not have their version"), ce->name);
 142}
 143
 144static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
 145{
 146        unsigned seen = 0;
 147        const char *name = ce->name;
 148
 149        while (pos < active_nr) {
 150                ce = active_cache[pos];
 151                if (strcmp(name, ce->name))
 152                        break;
 153                seen |= (1 << ce_stage(ce));
 154                pos++;
 155        }
 156        if ((stages & seen) != stages)
 157                return error(_("path '%s' does not have all necessary versions"),
 158                             name);
 159        return 0;
 160}
 161
 162static int checkout_stage(int stage, struct cache_entry *ce, int pos,
 163                          struct checkout *state)
 164{
 165        while (pos < active_nr &&
 166               !strcmp(active_cache[pos]->name, ce->name)) {
 167                if (ce_stage(active_cache[pos]) == stage)
 168                        return checkout_entry(active_cache[pos], state, NULL);
 169                pos++;
 170        }
 171        if (stage == 2)
 172                return error(_("path '%s' does not have our version"), ce->name);
 173        else
 174                return error(_("path '%s' does not have their version"), ce->name);
 175}
 176
 177static int checkout_merged(int pos, struct checkout *state)
 178{
 179        struct cache_entry *ce = active_cache[pos];
 180        const char *path = ce->name;
 181        mmfile_t ancestor, ours, theirs;
 182        int status;
 183        unsigned char sha1[20];
 184        mmbuffer_t result_buf;
 185        unsigned char threeway[3][20];
 186        unsigned mode = 0;
 187
 188        memset(threeway, 0, sizeof(threeway));
 189        while (pos < active_nr) {
 190                int stage;
 191                stage = ce_stage(ce);
 192                if (!stage || strcmp(path, ce->name))
 193                        break;
 194                hashcpy(threeway[stage - 1], ce->sha1);
 195                if (stage == 2)
 196                        mode = create_ce_mode(ce->ce_mode);
 197                pos++;
 198                ce = active_cache[pos];
 199        }
 200        if (is_null_sha1(threeway[1]) || is_null_sha1(threeway[2]))
 201                return error(_("path '%s' does not have necessary versions"), path);
 202
 203        read_mmblob(&ancestor, threeway[0]);
 204        read_mmblob(&ours, threeway[1]);
 205        read_mmblob(&theirs, threeway[2]);
 206
 207        /*
 208         * NEEDSWORK: re-create conflicts from merges with
 209         * merge.renormalize set, too
 210         */
 211        status = ll_merge(&result_buf, path, &ancestor, "base",
 212                          &ours, "ours", &theirs, "theirs", NULL);
 213        free(ancestor.ptr);
 214        free(ours.ptr);
 215        free(theirs.ptr);
 216        if (status < 0 || !result_buf.ptr) {
 217                free(result_buf.ptr);
 218                return error(_("path '%s': cannot merge"), path);
 219        }
 220
 221        /*
 222         * NEEDSWORK:
 223         * There is absolutely no reason to write this as a blob object
 224         * and create a phony cache entry just to leak.  This hack is
 225         * primarily to get to the write_entry() machinery that massages
 226         * the contents to work-tree format and writes out which only
 227         * allows it for a cache entry.  The code in write_entry() needs
 228         * to be refactored to allow us to feed a <buffer, size, mode>
 229         * instead of a cache entry.  Such a refactoring would help
 230         * merge_recursive as well (it also writes the merge result to the
 231         * object database even when it may contain conflicts).
 232         */
 233        if (write_sha1_file(result_buf.ptr, result_buf.size,
 234                            blob_type, sha1))
 235                die(_("Unable to add merge result for '%s'"), path);
 236        ce = make_cache_entry(mode, sha1, path, 2, 0);
 237        if (!ce)
 238                die(_("make_cache_entry failed for path '%s'"), path);
 239        status = checkout_entry(ce, state, NULL);
 240        return status;
 241}
 242
 243static int checkout_paths(const struct checkout_opts *opts,
 244                          const char *revision)
 245{
 246        int pos;
 247        struct checkout state;
 248        static char *ps_matched;
 249        unsigned char rev[20];
 250        int flag;
 251        struct commit *head;
 252        int errs = 0;
 253        struct lock_file *lock_file;
 254
 255        if (opts->track != BRANCH_TRACK_UNSPECIFIED)
 256                die(_("'%s' cannot be used with updating paths"), "--track");
 257
 258        if (opts->new_branch_log)
 259                die(_("'%s' cannot be used with updating paths"), "-l");
 260
 261        if (opts->force && opts->patch_mode)
 262                die(_("'%s' cannot be used with updating paths"), "-f");
 263
 264        if (opts->force_detach)
 265                die(_("'%s' cannot be used with updating paths"), "--detach");
 266
 267        if (opts->merge && opts->patch_mode)
 268                die(_("'%s' cannot be used with %s"), "--merge", "--patch");
 269
 270        if (opts->force && opts->merge)
 271                die(_("'%s' cannot be used with %s"), "-f", "-m");
 272
 273        if (opts->new_branch)
 274                die(_("Cannot update paths and switch to branch '%s' at the same time."),
 275                    opts->new_branch);
 276
 277        if (opts->new_worktree)
 278                die(_("'%s' cannot be used with updating paths"), "--to");
 279
 280        if (opts->patch_mode)
 281                return run_add_interactive(revision, "--patch=checkout",
 282                                           &opts->pathspec);
 283
 284        lock_file = xcalloc(1, sizeof(struct lock_file));
 285
 286        hold_locked_index(lock_file, 1);
 287        if (read_cache_preload(&opts->pathspec) < 0)
 288                return error(_("corrupt index file"));
 289
 290        if (opts->source_tree)
 291                read_tree_some(opts->source_tree, &opts->pathspec);
 292
 293        ps_matched = xcalloc(1, opts->pathspec.nr);
 294
 295        /*
 296         * Make sure all pathspecs participated in locating the paths
 297         * to be checked out.
 298         */
 299        for (pos = 0; pos < active_nr; pos++) {
 300                struct cache_entry *ce = active_cache[pos];
 301                ce->ce_flags &= ~CE_MATCHED;
 302                if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
 303                        continue;
 304                if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
 305                        /*
 306                         * "git checkout tree-ish -- path", but this entry
 307                         * is in the original index; it will not be checked
 308                         * out to the working tree and it does not matter
 309                         * if pathspec matched this entry.  We will not do
 310                         * anything to this entry at all.
 311                         */
 312                        continue;
 313                /*
 314                 * Either this entry came from the tree-ish we are
 315                 * checking the paths out of, or we are checking out
 316                 * of the index.
 317                 *
 318                 * If it comes from the tree-ish, we already know it
 319                 * matches the pathspec and could just stamp
 320                 * CE_MATCHED to it from update_some(). But we still
 321                 * need ps_matched and read_tree_recursive (and
 322                 * eventually tree_entry_interesting) cannot fill
 323                 * ps_matched yet. Once it can, we can avoid calling
 324                 * match_pathspec() for _all_ entries when
 325                 * opts->source_tree != NULL.
 326                 */
 327                if (ce_path_match(ce, &opts->pathspec, ps_matched))
 328                        ce->ce_flags |= CE_MATCHED;
 329        }
 330
 331        if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
 332                free(ps_matched);
 333                return 1;
 334        }
 335        free(ps_matched);
 336
 337        /* "checkout -m path" to recreate conflicted state */
 338        if (opts->merge)
 339                unmerge_marked_index(&the_index);
 340
 341        /* Any unmerged paths? */
 342        for (pos = 0; pos < active_nr; pos++) {
 343                const struct cache_entry *ce = active_cache[pos];
 344                if (ce->ce_flags & CE_MATCHED) {
 345                        if (!ce_stage(ce))
 346                                continue;
 347                        if (opts->force) {
 348                                warning(_("path '%s' is unmerged"), ce->name);
 349                        } else if (opts->writeout_stage) {
 350                                errs |= check_stage(opts->writeout_stage, ce, pos);
 351                        } else if (opts->merge) {
 352                                errs |= check_stages((1<<2) | (1<<3), ce, pos);
 353                        } else {
 354                                errs = 1;
 355                                error(_("path '%s' is unmerged"), ce->name);
 356                        }
 357                        pos = skip_same_name(ce, pos) - 1;
 358                }
 359        }
 360        if (errs)
 361                return 1;
 362
 363        /* Now we are committed to check them out */
 364        memset(&state, 0, sizeof(state));
 365        state.force = 1;
 366        state.refresh_cache = 1;
 367        state.istate = &the_index;
 368        for (pos = 0; pos < active_nr; pos++) {
 369                struct cache_entry *ce = active_cache[pos];
 370                if (ce->ce_flags & CE_MATCHED) {
 371                        if (!ce_stage(ce)) {
 372                                errs |= checkout_entry(ce, &state, NULL);
 373                                continue;
 374                        }
 375                        if (opts->writeout_stage)
 376                                errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
 377                        else if (opts->merge)
 378                                errs |= checkout_merged(pos, &state);
 379                        pos = skip_same_name(ce, pos) - 1;
 380                }
 381        }
 382
 383        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
 384                die(_("unable to write new index file"));
 385
 386        read_ref_full("HEAD", 0, rev, &flag);
 387        head = lookup_commit_reference_gently(rev, 1);
 388
 389        errs |= post_checkout_hook(head, head, 0);
 390        return errs;
 391}
 392
 393static void show_local_changes(struct object *head,
 394                               const struct diff_options *opts)
 395{
 396        struct rev_info rev;
 397        /* I think we want full paths, even if we're in a subdirectory. */
 398        init_revisions(&rev, NULL);
 399        rev.diffopt.flags = opts->flags;
 400        rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
 401        diff_setup_done(&rev.diffopt);
 402        add_pending_object(&rev, head, NULL);
 403        run_diff_index(&rev, 0);
 404}
 405
 406static void describe_detached_head(const char *msg, struct commit *commit)
 407{
 408        struct strbuf sb = STRBUF_INIT;
 409        if (!parse_commit(commit))
 410                pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
 411        fprintf(stderr, "%s %s... %s\n", msg,
 412                find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
 413        strbuf_release(&sb);
 414}
 415
 416static int reset_tree(struct tree *tree, const struct checkout_opts *o,
 417                      int worktree, int *writeout_error)
 418{
 419        struct unpack_trees_options opts;
 420        struct tree_desc tree_desc;
 421
 422        memset(&opts, 0, sizeof(opts));
 423        opts.head_idx = -1;
 424        opts.update = worktree;
 425        opts.skip_unmerged = !worktree;
 426        opts.reset = 1;
 427        opts.merge = 1;
 428        opts.fn = oneway_merge;
 429        opts.verbose_update = !o->quiet && isatty(2);
 430        opts.src_index = &the_index;
 431        opts.dst_index = &the_index;
 432        parse_tree(tree);
 433        init_tree_desc(&tree_desc, tree->buffer, tree->size);
 434        switch (unpack_trees(1, &tree_desc, &opts)) {
 435        case -2:
 436                *writeout_error = 1;
 437                /*
 438                 * We return 0 nevertheless, as the index is all right
 439                 * and more importantly we have made best efforts to
 440                 * update paths in the work tree, and we cannot revert
 441                 * them.
 442                 */
 443        case 0:
 444                return 0;
 445        default:
 446                return 128;
 447        }
 448}
 449
 450struct branch_info {
 451        const char *name; /* The short name used */
 452        const char *path; /* The full name of a real branch */
 453        struct commit *commit; /* The named commit */
 454        /*
 455         * if not null the branch is detached because it's already
 456         * checked out in this checkout
 457         */
 458        char *checkout;
 459};
 460
 461static void setup_branch_path(struct branch_info *branch)
 462{
 463        struct strbuf buf = STRBUF_INIT;
 464
 465        strbuf_branchname(&buf, branch->name);
 466        if (strcmp(buf.buf, branch->name))
 467                branch->name = xstrdup(buf.buf);
 468        strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
 469        branch->path = strbuf_detach(&buf, NULL);
 470}
 471
 472static int merge_working_tree(const struct checkout_opts *opts,
 473                              struct branch_info *old,
 474                              struct branch_info *new,
 475                              int *writeout_error)
 476{
 477        int ret;
 478        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 479
 480        hold_locked_index(lock_file, 1);
 481        if (read_cache_preload(NULL) < 0)
 482                return error(_("corrupt index file"));
 483
 484        resolve_undo_clear();
 485        if (opts->force) {
 486                ret = reset_tree(new->commit->tree, opts, 1, writeout_error);
 487                if (ret)
 488                        return ret;
 489        } else {
 490                struct tree_desc trees[2];
 491                struct tree *tree;
 492                struct unpack_trees_options topts;
 493
 494                memset(&topts, 0, sizeof(topts));
 495                topts.head_idx = -1;
 496                topts.src_index = &the_index;
 497                topts.dst_index = &the_index;
 498
 499                setup_unpack_trees_porcelain(&topts, "checkout");
 500
 501                refresh_cache(REFRESH_QUIET);
 502
 503                if (unmerged_cache()) {
 504                        error(_("you need to resolve your current index first"));
 505                        return 1;
 506                }
 507
 508                /* 2-way merge to the new branch */
 509                topts.initial_checkout = is_cache_unborn();
 510                topts.update = 1;
 511                topts.merge = 1;
 512                topts.gently = opts->merge && old->commit;
 513                topts.verbose_update = !opts->quiet && isatty(2);
 514                topts.fn = twoway_merge;
 515                if (opts->overwrite_ignore) {
 516                        topts.dir = xcalloc(1, sizeof(*topts.dir));
 517                        topts.dir->flags |= DIR_SHOW_IGNORED;
 518                        setup_standard_excludes(topts.dir);
 519                }
 520                tree = parse_tree_indirect(old->commit && !opts->new_worktree_mode ?
 521                                           old->commit->object.sha1 :
 522                                           EMPTY_TREE_SHA1_BIN);
 523                init_tree_desc(&trees[0], tree->buffer, tree->size);
 524                tree = parse_tree_indirect(new->commit->object.sha1);
 525                init_tree_desc(&trees[1], tree->buffer, tree->size);
 526
 527                ret = unpack_trees(2, trees, &topts);
 528                if (ret == -1) {
 529                        /*
 530                         * Unpack couldn't do a trivial merge; either
 531                         * give up or do a real merge, depending on
 532                         * whether the merge flag was used.
 533                         */
 534                        struct tree *result;
 535                        struct tree *work;
 536                        struct merge_options o;
 537                        if (!opts->merge)
 538                                return 1;
 539
 540                        /*
 541                         * Without old->commit, the below is the same as
 542                         * the two-tree unpack we already tried and failed.
 543                         */
 544                        if (!old->commit)
 545                                return 1;
 546
 547                        /* Do more real merge */
 548
 549                        /*
 550                         * We update the index fully, then write the
 551                         * tree from the index, then merge the new
 552                         * branch with the current tree, with the old
 553                         * branch as the base. Then we reset the index
 554                         * (but not the working tree) to the new
 555                         * branch, leaving the working tree as the
 556                         * merged version, but skipping unmerged
 557                         * entries in the index.
 558                         */
 559
 560                        add_files_to_cache(NULL, NULL, 0);
 561                        /*
 562                         * NEEDSWORK: carrying over local changes
 563                         * when branches have different end-of-line
 564                         * normalization (or clean+smudge rules) is
 565                         * a pain; plumb in an option to set
 566                         * o.renormalize?
 567                         */
 568                        init_merge_options(&o);
 569                        o.verbosity = 0;
 570                        work = write_tree_from_memory(&o);
 571
 572                        ret = reset_tree(new->commit->tree, opts, 1,
 573                                         writeout_error);
 574                        if (ret)
 575                                return ret;
 576                        o.ancestor = old->name;
 577                        o.branch1 = new->name;
 578                        o.branch2 = "local";
 579                        merge_trees(&o, new->commit->tree, work,
 580                                old->commit->tree, &result);
 581                        ret = reset_tree(new->commit->tree, opts, 0,
 582                                         writeout_error);
 583                        if (ret)
 584                                return ret;
 585                }
 586        }
 587
 588        if (!active_cache_tree)
 589                active_cache_tree = cache_tree();
 590
 591        if (!cache_tree_fully_valid(active_cache_tree))
 592                cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
 593
 594        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
 595                die(_("unable to write new index file"));
 596
 597        if (!opts->force && !opts->quiet)
 598                show_local_changes(&new->commit->object, &opts->diff_options);
 599
 600        return 0;
 601}
 602
 603static void report_tracking(struct branch_info *new)
 604{
 605        struct strbuf sb = STRBUF_INIT;
 606        struct branch *branch = branch_get(new->name);
 607
 608        if (!format_tracking_info(branch, &sb))
 609                return;
 610        fputs(sb.buf, stdout);
 611        strbuf_release(&sb);
 612}
 613
 614static void update_refs_for_switch(const struct checkout_opts *opts,
 615                                   struct branch_info *old,
 616                                   struct branch_info *new)
 617{
 618        struct strbuf msg = STRBUF_INIT;
 619        const char *old_desc, *reflog_msg;
 620        if (opts->new_branch) {
 621                if (opts->new_orphan_branch) {
 622                        if (opts->new_branch_log && !log_all_ref_updates) {
 623                                int temp;
 624                                struct strbuf log_file = STRBUF_INIT;
 625                                int ret;
 626                                const char *ref_name;
 627
 628                                ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
 629                                temp = log_all_ref_updates;
 630                                log_all_ref_updates = 1;
 631                                ret = log_ref_setup(ref_name, &log_file);
 632                                log_all_ref_updates = temp;
 633                                strbuf_release(&log_file);
 634                                if (ret) {
 635                                        fprintf(stderr, _("Can not do reflog for '%s'\n"),
 636                                            opts->new_orphan_branch);
 637                                        return;
 638                                }
 639                        }
 640                }
 641                else
 642                        create_branch(old->name, opts->new_branch, new->name,
 643                                      opts->new_branch_force ? 1 : 0,
 644                                      opts->new_branch_log,
 645                                      opts->new_branch_force ? 1 : 0,
 646                                      opts->quiet,
 647                                      opts->track);
 648                new->name = opts->new_branch;
 649                setup_branch_path(new);
 650        }
 651
 652        old_desc = old->name;
 653        if (!old_desc && old->commit)
 654                old_desc = sha1_to_hex(old->commit->object.sha1);
 655
 656        reflog_msg = getenv("GIT_REFLOG_ACTION");
 657        if (!reflog_msg)
 658                strbuf_addf(&msg, "checkout: moving from %s to %s",
 659                        old_desc ? old_desc : "(invalid)", new->name);
 660        else
 661                strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
 662
 663        if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
 664                /* Nothing to do. */
 665        } else if (opts->force_detach || !new->path) {  /* No longer on any branch. */
 666                update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
 667                           REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
 668                if (!opts->quiet) {
 669                        if (old->path && advice_detached_head)
 670                                detach_advice(new->name);
 671                        describe_detached_head(_("HEAD is now at"), new->commit);
 672                }
 673        } else if (new->path) { /* Switch branches. */
 674                create_symref("HEAD", new->path, msg.buf);
 675                if (!opts->quiet) {
 676                        if (old->path && !strcmp(new->path, old->path)) {
 677                                if (opts->new_branch_force)
 678                                        fprintf(stderr, _("Reset branch '%s'\n"),
 679                                                new->name);
 680                                else
 681                                        fprintf(stderr, _("Already on '%s'\n"),
 682                                                new->name);
 683                        } else if (opts->new_branch) {
 684                                if (opts->branch_exists)
 685                                        fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
 686                                else
 687                                        fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
 688                        } else {
 689                                fprintf(stderr, _("Switched to branch '%s'\n"),
 690                                        new->name);
 691                        }
 692                }
 693                if (old->path && old->name) {
 694                        if (!ref_exists(old->path) && reflog_exists(old->path))
 695                                delete_reflog(old->path);
 696                }
 697        }
 698        remove_branch_state();
 699        strbuf_release(&msg);
 700        if (!opts->quiet &&
 701            (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
 702                report_tracking(new);
 703}
 704
 705static int add_pending_uninteresting_ref(const char *refname,
 706                                         const unsigned char *sha1,
 707                                         int flags, void *cb_data)
 708{
 709        add_pending_sha1(cb_data, refname, sha1, UNINTERESTING);
 710        return 0;
 711}
 712
 713static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
 714{
 715        strbuf_addstr(sb, "  ");
 716        strbuf_addstr(sb,
 717                find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
 718        strbuf_addch(sb, ' ');
 719        if (!parse_commit(commit))
 720                pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
 721        strbuf_addch(sb, '\n');
 722}
 723
 724#define ORPHAN_CUTOFF 4
 725static void suggest_reattach(struct commit *commit, struct rev_info *revs)
 726{
 727        struct commit *c, *last = NULL;
 728        struct strbuf sb = STRBUF_INIT;
 729        int lost = 0;
 730        while ((c = get_revision(revs)) != NULL) {
 731                if (lost < ORPHAN_CUTOFF)
 732                        describe_one_orphan(&sb, c);
 733                last = c;
 734                lost++;
 735        }
 736        if (ORPHAN_CUTOFF < lost) {
 737                int more = lost - ORPHAN_CUTOFF;
 738                if (more == 1)
 739                        describe_one_orphan(&sb, last);
 740                else
 741                        strbuf_addf(&sb, _(" ... and %d more.\n"), more);
 742        }
 743
 744        fprintf(stderr,
 745                Q_(
 746                /* The singular version */
 747                "Warning: you are leaving %d commit behind, "
 748                "not connected to\n"
 749                "any of your branches:\n\n"
 750                "%s\n",
 751                /* The plural version */
 752                "Warning: you are leaving %d commits behind, "
 753                "not connected to\n"
 754                "any of your branches:\n\n"
 755                "%s\n",
 756                /* Give ngettext() the count */
 757                lost),
 758                lost,
 759                sb.buf);
 760        strbuf_release(&sb);
 761
 762        if (advice_detached_head)
 763                fprintf(stderr,
 764                        Q_(
 765                        /* The singular version */
 766                        "If you want to keep it by creating a new branch, "
 767                        "this may be a good time\nto do so with:\n\n"
 768                        " git branch <new-branch-name> %s\n\n",
 769                        /* The plural version */
 770                        "If you want to keep them by creating a new branch, "
 771                        "this may be a good time\nto do so with:\n\n"
 772                        " git branch <new-branch-name> %s\n\n",
 773                        /* Give ngettext() the count */
 774                        lost),
 775                        find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
 776}
 777
 778/*
 779 * We are about to leave commit that was at the tip of a detached
 780 * HEAD.  If it is not reachable from any ref, this is the last chance
 781 * for the user to do so without resorting to reflog.
 782 */
 783static void orphaned_commit_warning(struct commit *old, struct commit *new)
 784{
 785        struct rev_info revs;
 786        struct object *object = &old->object;
 787        struct object_array refs;
 788
 789        init_revisions(&revs, NULL);
 790        setup_revisions(0, NULL, &revs, NULL);
 791
 792        object->flags &= ~UNINTERESTING;
 793        add_pending_object(&revs, object, sha1_to_hex(object->sha1));
 794
 795        for_each_ref(add_pending_uninteresting_ref, &revs);
 796        add_pending_sha1(&revs, "HEAD", new->object.sha1, UNINTERESTING);
 797
 798        refs = revs.pending;
 799        revs.leak_pending = 1;
 800
 801        if (prepare_revision_walk(&revs))
 802                die(_("internal error in revision walk"));
 803        if (!(old->object.flags & UNINTERESTING))
 804                suggest_reattach(old, &revs);
 805        else
 806                describe_detached_head(_("Previous HEAD position was"), old);
 807
 808        clear_commit_marks_for_object_array(&refs, ALL_REV_FLAGS);
 809        free(refs.objects);
 810}
 811
 812static int switch_branches(const struct checkout_opts *opts,
 813                           struct branch_info *new)
 814{
 815        int ret = 0;
 816        struct branch_info old;
 817        void *path_to_free;
 818        unsigned char rev[20];
 819        int flag, writeout_error = 0;
 820        memset(&old, 0, sizeof(old));
 821        old.path = path_to_free = resolve_refdup("HEAD", 0, rev, &flag);
 822        old.commit = lookup_commit_reference_gently(rev, 1);
 823        if (!(flag & REF_ISSYMREF))
 824                old.path = NULL;
 825
 826        if (old.path)
 827                skip_prefix(old.path, "refs/heads/", &old.name);
 828
 829        if (!new->name) {
 830                new->name = "HEAD";
 831                new->commit = old.commit;
 832                if (!new->commit)
 833                        die(_("You are on a branch yet to be born"));
 834                parse_commit_or_die(new->commit);
 835        }
 836
 837        ret = merge_working_tree(opts, &old, new, &writeout_error);
 838        if (ret) {
 839                free(path_to_free);
 840                return ret;
 841        }
 842
 843        if (!opts->quiet && !old.path && old.commit &&
 844            new->commit != old.commit && !opts->new_worktree_mode)
 845                orphaned_commit_warning(old.commit, new->commit);
 846
 847        update_refs_for_switch(opts, &old, new);
 848
 849        ret = post_checkout_hook(old.commit, new->commit, 1);
 850        free(path_to_free);
 851        return ret || writeout_error;
 852}
 853
 854static char *junk_work_tree;
 855static char *junk_git_dir;
 856static int is_junk;
 857static pid_t junk_pid;
 858
 859static void remove_junk(void)
 860{
 861        struct strbuf sb = STRBUF_INIT;
 862        if (!is_junk || getpid() != junk_pid)
 863                return;
 864        if (junk_git_dir) {
 865                strbuf_addstr(&sb, junk_git_dir);
 866                remove_dir_recursively(&sb, 0);
 867                strbuf_reset(&sb);
 868        }
 869        if (junk_work_tree) {
 870                strbuf_addstr(&sb, junk_work_tree);
 871                remove_dir_recursively(&sb, 0);
 872        }
 873        strbuf_release(&sb);
 874}
 875
 876static void remove_junk_on_signal(int signo)
 877{
 878        remove_junk();
 879        sigchain_pop(signo);
 880        raise(signo);
 881}
 882
 883static int prepare_linked_checkout(const struct checkout_opts *opts,
 884                                   struct branch_info *new)
 885{
 886        struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
 887        struct strbuf sb = STRBUF_INIT;
 888        const char *path = opts->new_worktree, *name;
 889        struct stat st;
 890        struct child_process cp;
 891        int counter = 0, len, ret;
 892
 893        if (!new->commit)
 894                die(_("no branch specified"));
 895        if (file_exists(path) && !is_empty_dir(path))
 896                die(_("'%s' already exists"), path);
 897
 898        len = strlen(path);
 899        while (len && is_dir_sep(path[len - 1]))
 900                len--;
 901
 902        for (name = path + len - 1; name > path; name--)
 903                if (is_dir_sep(*name)) {
 904                        name++;
 905                        break;
 906                }
 907        strbuf_addstr(&sb_repo,
 908                      git_path("worktrees/%.*s", (int)(path + len - name), name));
 909        len = sb_repo.len;
 910        if (safe_create_leading_directories_const(sb_repo.buf))
 911                die_errno(_("could not create leading directories of '%s'"),
 912                          sb_repo.buf);
 913        while (!stat(sb_repo.buf, &st)) {
 914                counter++;
 915                strbuf_setlen(&sb_repo, len);
 916                strbuf_addf(&sb_repo, "%d", counter);
 917        }
 918        name = strrchr(sb_repo.buf, '/') + 1;
 919
 920        junk_pid = getpid();
 921        atexit(remove_junk);
 922        sigchain_push_common(remove_junk_on_signal);
 923
 924        if (mkdir(sb_repo.buf, 0777))
 925                die_errno(_("could not create directory of '%s'"), sb_repo.buf);
 926        junk_git_dir = xstrdup(sb_repo.buf);
 927        is_junk = 1;
 928
 929        /*
 930         * lock the incomplete repo so prune won't delete it, unlock
 931         * after the preparation is over.
 932         */
 933        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 934        write_file(sb.buf, 1, "initializing\n");
 935
 936        strbuf_addf(&sb_git, "%s/.git", path);
 937        if (safe_create_leading_directories_const(sb_git.buf))
 938                die_errno(_("could not create leading directories of '%s'"),
 939                          sb_git.buf);
 940        junk_work_tree = xstrdup(path);
 941
 942        strbuf_reset(&sb);
 943        strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
 944        write_file(sb.buf, 1, "%s\n", real_path(sb_git.buf));
 945        write_file(sb_git.buf, 1, "gitdir: %s/worktrees/%s\n",
 946                   real_path(get_git_common_dir()), name);
 947        /*
 948         * This is to keep resolve_ref() happy. We need a valid HEAD
 949         * or is_git_directory() will reject the directory. Any valid
 950         * value would do because this value will be ignored and
 951         * replaced at the next (real) checkout.
 952         */
 953        strbuf_reset(&sb);
 954        strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
 955        write_file(sb.buf, 1, "%s\n", sha1_to_hex(new->commit->object.sha1));
 956        strbuf_reset(&sb);
 957        strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
 958        write_file(sb.buf, 1, "../..\n");
 959
 960        if (!opts->quiet)
 961                fprintf_ln(stderr, _("Enter %s (identifier %s)"), path, name);
 962
 963        setenv("GIT_CHECKOUT_NEW_WORKTREE", "1", 1);
 964        setenv(GIT_DIR_ENVIRONMENT, sb_git.buf, 1);
 965        setenv(GIT_WORK_TREE_ENVIRONMENT, path, 1);
 966        memset(&cp, 0, sizeof(cp));
 967        cp.git_cmd = 1;
 968        cp.argv = opts->saved_argv;
 969        ret = run_command(&cp);
 970        if (!ret) {
 971                is_junk = 0;
 972                free(junk_work_tree);
 973                free(junk_git_dir);
 974                junk_work_tree = NULL;
 975                junk_git_dir = NULL;
 976        }
 977        strbuf_reset(&sb);
 978        strbuf_addf(&sb, "%s/locked", sb_repo.buf);
 979        unlink_or_warn(sb.buf);
 980        strbuf_release(&sb);
 981        strbuf_release(&sb_repo);
 982        strbuf_release(&sb_git);
 983        return ret;
 984}
 985
 986static int git_checkout_config(const char *var, const char *value, void *cb)
 987{
 988        if (!strcmp(var, "diff.ignoresubmodules")) {
 989                struct checkout_opts *opts = cb;
 990                handle_ignore_submodules_arg(&opts->diff_options, value);
 991                return 0;
 992        }
 993
 994        if (starts_with(var, "submodule."))
 995                return parse_submodule_config_option(var, value);
 996
 997        return git_xmerge_config(var, value, NULL);
 998}
 999
1000struct tracking_name_data {
1001        /* const */ char *src_ref;
1002        char *dst_ref;
1003        unsigned char *dst_sha1;
1004        int unique;
1005};
1006
1007static int check_tracking_name(struct remote *remote, void *cb_data)
1008{
1009        struct tracking_name_data *cb = cb_data;
1010        struct refspec query;
1011        memset(&query, 0, sizeof(struct refspec));
1012        query.src = cb->src_ref;
1013        if (remote_find_tracking(remote, &query) ||
1014            get_sha1(query.dst, cb->dst_sha1)) {
1015                free(query.dst);
1016                return 0;
1017        }
1018        if (cb->dst_ref) {
1019                free(query.dst);
1020                cb->unique = 0;
1021                return 0;
1022        }
1023        cb->dst_ref = query.dst;
1024        return 0;
1025}
1026
1027static const char *unique_tracking_name(const char *name, unsigned char *sha1)
1028{
1029        struct tracking_name_data cb_data = { NULL, NULL, NULL, 1 };
1030        char src_ref[PATH_MAX];
1031        snprintf(src_ref, PATH_MAX, "refs/heads/%s", name);
1032        cb_data.src_ref = src_ref;
1033        cb_data.dst_sha1 = sha1;
1034        for_each_remote(check_tracking_name, &cb_data);
1035        if (cb_data.unique)
1036                return cb_data.dst_ref;
1037        free(cb_data.dst_ref);
1038        return NULL;
1039}
1040
1041static void check_linked_checkout(struct branch_info *new, const char *id)
1042{
1043        struct strbuf sb = STRBUF_INIT;
1044        struct strbuf path = STRBUF_INIT;
1045        struct strbuf gitdir = STRBUF_INIT;
1046        const char *start, *end;
1047
1048        if (id)
1049                strbuf_addf(&path, "%s/worktrees/%s/HEAD", get_git_common_dir(), id);
1050        else
1051                strbuf_addf(&path, "%s/HEAD", get_git_common_dir());
1052
1053        if (strbuf_read_file(&sb, path.buf, 0) < 0 ||
1054            !skip_prefix(sb.buf, "ref:", &start))
1055                goto done;
1056        while (isspace(*start))
1057                start++;
1058        end = start;
1059        while (*end && !isspace(*end))
1060                end++;
1061        if (strncmp(start, new->path, end - start) || new->path[end - start] != '\0')
1062                goto done;
1063        if (id) {
1064                strbuf_reset(&path);
1065                strbuf_addf(&path, "%s/worktrees/%s/gitdir", get_git_common_dir(), id);
1066                if (strbuf_read_file(&gitdir, path.buf, 0) <= 0)
1067                        goto done;
1068                strbuf_rtrim(&gitdir);
1069        } else
1070                strbuf_addstr(&gitdir, get_git_common_dir());
1071        die(_("'%s' is already checked out at '%s'"), new->name, gitdir.buf);
1072done:
1073        strbuf_release(&path);
1074        strbuf_release(&sb);
1075        strbuf_release(&gitdir);
1076}
1077
1078static void check_linked_checkouts(struct branch_info *new)
1079{
1080        struct strbuf path = STRBUF_INIT;
1081        DIR *dir;
1082        struct dirent *d;
1083
1084        strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
1085        if ((dir = opendir(path.buf)) == NULL) {
1086                strbuf_release(&path);
1087                return;
1088        }
1089
1090        /*
1091         * $GIT_COMMON_DIR/HEAD is practically outside
1092         * $GIT_DIR so resolve_ref_unsafe() won't work (it
1093         * uses git_path). Parse the ref ourselves.
1094         */
1095        check_linked_checkout(new, NULL);
1096
1097        while ((d = readdir(dir)) != NULL) {
1098                if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1099                        continue;
1100                check_linked_checkout(new, d->d_name);
1101        }
1102        strbuf_release(&path);
1103        closedir(dir);
1104}
1105
1106static int parse_branchname_arg(int argc, const char **argv,
1107                                int dwim_new_local_branch_ok,
1108                                struct branch_info *new,
1109                                struct checkout_opts *opts,
1110                                unsigned char rev[20])
1111{
1112        struct tree **source_tree = &opts->source_tree;
1113        const char **new_branch = &opts->new_branch;
1114        int force_detach = opts->force_detach;
1115        int argcount = 0;
1116        unsigned char branch_rev[20];
1117        const char *arg;
1118        int dash_dash_pos;
1119        int has_dash_dash = 0;
1120        int i;
1121
1122        /*
1123         * case 1: git checkout <ref> -- [<paths>]
1124         *
1125         *   <ref> must be a valid tree, everything after the '--' must be
1126         *   a path.
1127         *
1128         * case 2: git checkout -- [<paths>]
1129         *
1130         *   everything after the '--' must be paths.
1131         *
1132         * case 3: git checkout <something> [--]
1133         *
1134         *   (a) If <something> is a commit, that is to
1135         *       switch to the branch or detach HEAD at it.  As a special case,
1136         *       if <something> is A...B (missing A or B means HEAD but you can
1137         *       omit at most one side), and if there is a unique merge base
1138         *       between A and B, A...B names that merge base.
1139         *
1140         *   (b) If <something> is _not_ a commit, either "--" is present
1141         *       or <something> is not a path, no -t or -b was given, and
1142         *       and there is a tracking branch whose name is <something>
1143         *       in one and only one remote, then this is a short-hand to
1144         *       fork local <something> from that remote-tracking branch.
1145         *
1146         *   (c) Otherwise, if "--" is present, treat it like case (1).
1147         *
1148         *   (d) Otherwise :
1149         *       - if it's a reference, treat it like case (1)
1150         *       - else if it's a path, treat it like case (2)
1151         *       - else: fail.
1152         *
1153         * case 4: git checkout <something> <paths>
1154         *
1155         *   The first argument must not be ambiguous.
1156         *   - If it's *only* a reference, treat it like case (1).
1157         *   - If it's only a path, treat it like case (2).
1158         *   - else: fail.
1159         *
1160         */
1161        if (!argc)
1162                return 0;
1163
1164        arg = argv[0];
1165        dash_dash_pos = -1;
1166        for (i = 0; i < argc; i++) {
1167                if (!strcmp(argv[i], "--")) {
1168                        dash_dash_pos = i;
1169                        break;
1170                }
1171        }
1172        if (dash_dash_pos == 0)
1173                return 1; /* case (2) */
1174        else if (dash_dash_pos == 1)
1175                has_dash_dash = 1; /* case (3) or (1) */
1176        else if (dash_dash_pos >= 2)
1177                die(_("only one reference expected, %d given."), dash_dash_pos);
1178
1179        if (!strcmp(arg, "-"))
1180                arg = "@{-1}";
1181
1182        if (get_sha1_mb(arg, rev)) {
1183                /*
1184                 * Either case (3) or (4), with <something> not being
1185                 * a commit, or an attempt to use case (1) with an
1186                 * invalid ref.
1187                 *
1188                 * It's likely an error, but we need to find out if
1189                 * we should auto-create the branch, case (3).(b).
1190                 */
1191                int recover_with_dwim = dwim_new_local_branch_ok;
1192
1193                if (check_filename(NULL, arg) && !has_dash_dash)
1194                        recover_with_dwim = 0;
1195                /*
1196                 * Accept "git checkout foo" and "git checkout foo --"
1197                 * as candidates for dwim.
1198                 */
1199                if (!(argc == 1 && !has_dash_dash) &&
1200                    !(argc == 2 && has_dash_dash))
1201                        recover_with_dwim = 0;
1202
1203                if (recover_with_dwim) {
1204                        const char *remote = unique_tracking_name(arg, rev);
1205                        if (remote) {
1206                                *new_branch = arg;
1207                                arg = remote;
1208                                /* DWIMmed to create local branch, case (3).(b) */
1209                        } else {
1210                                recover_with_dwim = 0;
1211                        }
1212                }
1213
1214                if (!recover_with_dwim) {
1215                        if (has_dash_dash)
1216                                die(_("invalid reference: %s"), arg);
1217                        return argcount;
1218                }
1219        }
1220
1221        /* we can't end up being in (2) anymore, eat the argument */
1222        argcount++;
1223        argv++;
1224        argc--;
1225
1226        new->name = arg;
1227        setup_branch_path(new);
1228
1229        if (!check_refname_format(new->path, 0) &&
1230            !read_ref(new->path, branch_rev))
1231                hashcpy(rev, branch_rev);
1232        else
1233                new->path = NULL; /* not an existing branch */
1234
1235        if (new->path && !force_detach && !*new_branch) {
1236                unsigned char sha1[20];
1237                int flag;
1238                char *head_ref = resolve_refdup("HEAD", 0, sha1, &flag);
1239                if (head_ref &&
1240                    (!(flag & REF_ISSYMREF) || strcmp(head_ref, new->path)) &&
1241                    !opts->ignore_other_worktrees)
1242                        check_linked_checkouts(new);
1243                free(head_ref);
1244        }
1245
1246        new->commit = lookup_commit_reference_gently(rev, 1);
1247        if (!new->commit) {
1248                /* not a commit */
1249                *source_tree = parse_tree_indirect(rev);
1250        } else {
1251                parse_commit_or_die(new->commit);
1252                *source_tree = new->commit->tree;
1253        }
1254
1255        if (!*source_tree)                   /* case (1): want a tree */
1256                die(_("reference is not a tree: %s"), arg);
1257        if (!has_dash_dash) {/* case (3).(d) -> (1) */
1258                /*
1259                 * Do not complain the most common case
1260                 *      git checkout branch
1261                 * even if there happen to be a file called 'branch';
1262                 * it would be extremely annoying.
1263                 */
1264                if (argc)
1265                        verify_non_filename(NULL, arg);
1266        } else {
1267                argcount++;
1268                argv++;
1269                argc--;
1270        }
1271
1272        return argcount;
1273}
1274
1275static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1276{
1277        int status;
1278        struct strbuf branch_ref = STRBUF_INIT;
1279
1280        if (!opts->new_branch)
1281                die(_("You are on a branch yet to be born"));
1282        strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1283        status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1284        strbuf_release(&branch_ref);
1285        if (!opts->quiet)
1286                fprintf(stderr, _("Switched to a new branch '%s'\n"),
1287                        opts->new_branch);
1288        return status;
1289}
1290
1291static int checkout_branch(struct checkout_opts *opts,
1292                           struct branch_info *new)
1293{
1294        if (opts->pathspec.nr)
1295                die(_("paths cannot be used with switching branches"));
1296
1297        if (opts->patch_mode)
1298                die(_("'%s' cannot be used with switching branches"),
1299                    "--patch");
1300
1301        if (opts->writeout_stage)
1302                die(_("'%s' cannot be used with switching branches"),
1303                    "--ours/--theirs");
1304
1305        if (opts->force && opts->merge)
1306                die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1307
1308        if (opts->force_detach && opts->new_branch)
1309                die(_("'%s' cannot be used with '%s'"),
1310                    "--detach", "-b/-B/--orphan");
1311
1312        if (opts->new_orphan_branch) {
1313                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1314                        die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1315        } else if (opts->force_detach) {
1316                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1317                        die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1318        } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1319                opts->track = git_branch_track;
1320
1321        if (new->name && !new->commit)
1322                die(_("Cannot switch branch to a non-commit '%s'"),
1323                    new->name);
1324
1325        if (opts->new_worktree)
1326                return prepare_linked_checkout(opts, new);
1327
1328        if (!new->commit && opts->new_branch) {
1329                unsigned char rev[20];
1330                int flag;
1331
1332                if (!read_ref_full("HEAD", 0, rev, &flag) &&
1333                    (flag & REF_ISSYMREF) && is_null_sha1(rev))
1334                        return switch_unborn_to_new_branch(opts);
1335        }
1336        return switch_branches(opts, new);
1337}
1338
1339int cmd_checkout(int argc, const char **argv, const char *prefix)
1340{
1341        struct checkout_opts opts;
1342        struct branch_info new;
1343        char *conflict_style = NULL;
1344        int dwim_new_local_branch = 1;
1345        struct option options[] = {
1346                OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
1347                OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1348                           N_("create and checkout a new branch")),
1349                OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1350                           N_("create/reset and checkout a branch")),
1351                OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1352                OPT_BOOL(0, "detach", &opts.force_detach, N_("detach the HEAD at named commit")),
1353                OPT_SET_INT('t', "track",  &opts.track, N_("set upstream info for new branch"),
1354                        BRANCH_TRACK_EXPLICIT),
1355                OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1356                OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
1357                            2),
1358                OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
1359                            3),
1360                OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
1361                OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1362                OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
1363                OPT_STRING(0, "conflict", &conflict_style, N_("style"),
1364                           N_("conflict style (merge or diff3)")),
1365                OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1366                OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
1367                         N_("do not limit pathspecs to sparse entries only")),
1368                OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1369                                N_("second guess 'git checkout <no-such-branch>'")),
1370                OPT_FILENAME(0, "to", &opts.new_worktree,
1371                           N_("check a branch out in a separate working directory")),
1372                OPT_BOOL(0, "ignore-other-worktrees", &opts.ignore_other_worktrees,
1373                         N_("do not check if another worktree is holding the given ref")),
1374                OPT_END(),
1375        };
1376
1377        memset(&opts, 0, sizeof(opts));
1378        memset(&new, 0, sizeof(new));
1379        opts.overwrite_ignore = 1;
1380        opts.prefix = prefix;
1381
1382        opts.saved_argv = xmalloc(sizeof(const char *) * (argc + 2));
1383        memcpy(opts.saved_argv, argv, sizeof(const char *) * (argc + 1));
1384
1385        gitmodules_config();
1386        git_config(git_checkout_config, &opts);
1387
1388        opts.track = BRANCH_TRACK_UNSPECIFIED;
1389
1390        argc = parse_options(argc, argv, prefix, options, checkout_usage,
1391                             PARSE_OPT_KEEP_DASHDASH);
1392
1393        /* recursive execution from checkout_new_worktree() */
1394        opts.new_worktree_mode = getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;
1395        if (opts.new_worktree_mode)
1396                opts.new_worktree = NULL;
1397
1398        if (!opts.new_worktree)
1399                setup_work_tree();
1400
1401        if (conflict_style) {
1402                opts.merge = 1; /* implied */
1403                git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1404        }
1405
1406        if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
1407                die(_("-b, -B and --orphan are mutually exclusive"));
1408
1409        /*
1410         * From here on, new_branch will contain the branch to be checked out,
1411         * and new_branch_force and new_orphan_branch will tell us which one of
1412         * -b/-B/--orphan is being used.
1413         */
1414        if (opts.new_branch_force)
1415                opts.new_branch = opts.new_branch_force;
1416
1417        if (opts.new_orphan_branch)
1418                opts.new_branch = opts.new_orphan_branch;
1419
1420        /* --track without -b/-B/--orphan should DWIM */
1421        if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1422                const char *argv0 = argv[0];
1423                if (!argc || !strcmp(argv0, "--"))
1424                        die (_("--track needs a branch name"));
1425                skip_prefix(argv0, "refs/", &argv0);
1426                skip_prefix(argv0, "remotes/", &argv0);
1427                argv0 = strchr(argv0, '/');
1428                if (!argv0 || !argv0[1])
1429                        die (_("Missing branch name; try -b"));
1430                opts.new_branch = argv0 + 1;
1431        }
1432
1433        /*
1434         * Extract branch name from command line arguments, so
1435         * all that is left is pathspecs.
1436         *
1437         * Handle
1438         *
1439         *  1) git checkout <tree> -- [<paths>]
1440         *  2) git checkout -- [<paths>]
1441         *  3) git checkout <something> [<paths>]
1442         *
1443         * including "last branch" syntax and DWIM-ery for names of
1444         * remote branches, erroring out for invalid or ambiguous cases.
1445         */
1446        if (argc) {
1447                unsigned char rev[20];
1448                int dwim_ok =
1449                        !opts.patch_mode &&
1450                        dwim_new_local_branch &&
1451                        opts.track == BRANCH_TRACK_UNSPECIFIED &&
1452                        !opts.new_branch;
1453                int n = parse_branchname_arg(argc, argv, dwim_ok,
1454                                             &new, &opts, rev);
1455                argv += n;
1456                argc -= n;
1457        }
1458
1459        if (argc) {
1460                parse_pathspec(&opts.pathspec, 0,
1461                               opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1462                               prefix, argv);
1463
1464                if (!opts.pathspec.nr)
1465                        die(_("invalid path specification"));
1466
1467                /*
1468                 * Try to give more helpful suggestion.
1469                 * new_branch && argc > 1 will be caught later.
1470                 */
1471                if (opts.new_branch && argc == 1)
1472                        die(_("Cannot update paths and switch to branch '%s' at the same time.\n"
1473                              "Did you intend to checkout '%s' which can not be resolved as commit?"),
1474                            opts.new_branch, argv[0]);
1475
1476                if (opts.force_detach)
1477                        die(_("git checkout: --detach does not take a path argument '%s'"),
1478                            argv[0]);
1479
1480                if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1481                        die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1482                              "checking out of the index."));
1483        }
1484
1485        if (opts.new_branch) {
1486                struct strbuf buf = STRBUF_INIT;
1487
1488                opts.branch_exists =
1489                        validate_new_branchname(opts.new_branch, &buf,
1490                                                !!opts.new_branch_force,
1491                                                !!opts.new_branch_force);
1492
1493                strbuf_release(&buf);
1494        }
1495
1496        if (opts.patch_mode || opts.pathspec.nr)
1497                return checkout_paths(&opts, new.name);
1498        else
1499                return checkout_branch(&opts, &new);
1500}