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