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