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