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