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