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