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