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