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