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