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