builtin / checkout.con commit checkout: die_if_checked_out: simplify strbuf management (4e07815)
   1#include "builtin.h"
   2#include "lockfile.h"
   3#include "parse-options.h"
   4#include "refs.h"
   5#include "commit.h"
   6#include "tree.h"
   7#include "tree-walk.h"
   8#include "cache-tree.h"
   9#include "unpack-trees.h"
  10#include "dir.h"
  11#include "run-command.h"
  12#include "merge-recursive.h"
  13#include "branch.h"
  14#include "diff.h"
  15#include "revision.h"
  16#include "remote.h"
  17#include "blob.h"
  18#include "xdiff-interface.h"
  19#include "ll-merge.h"
  20#include "resolve-undo.h"
  21#include "submodule.h"
  22
  23static const char * const checkout_usage[] = {
  24        N_("git checkout [options] <branch>"),
  25        N_("git checkout [options] [<branch>] -- <file>..."),
  26        NULL,
  27};
  28
  29struct checkout_opts {
  30        int patch_mode;
  31        int quiet;
  32        int merge;
  33        int force;
  34        int force_detach;
  35        int writeout_stage;
  36        int overwrite_ignore;
  37        int ignore_skipworktree;
  38        int ignore_other_worktrees;
  39
  40        const char *new_branch;
  41        const char *new_branch_force;
  42        const char *new_orphan_branch;
  43        int new_branch_log;
  44        enum branch_track track;
  45        struct diff_options diff_options;
  46
  47        int branch_exists;
  48        const char *prefix;
  49        struct pathspec pathspec;
  50        struct tree *source_tree;
  51
  52        int new_worktree_mode;
  53};
  54
  55static int post_checkout_hook(struct commit *old, struct commit *new,
  56                              int changed)
  57{
  58        return run_hook_le(NULL, "post-checkout",
  59                           sha1_to_hex(old ? old->object.sha1 : null_sha1),
  60                           sha1_to_hex(new ? new->object.sha1 : null_sha1),
  61                           changed ? "1" : "0", NULL);
  62        /* "new" can be NULL when checking out from the index before
  63           a commit exists. */
  64
  65}
  66
  67static int update_some(const unsigned char *sha1, const char *base, int baselen,
  68                const char *pathname, unsigned mode, int stage, void *context)
  69{
  70        int len;
  71        struct cache_entry *ce;
  72
  73        if (S_ISDIR(mode))
  74                return READ_TREE_RECURSIVE;
  75
  76        len = baselen + strlen(pathname);
  77        ce = xcalloc(1, cache_entry_size(len));
  78        hashcpy(ce->sha1, sha1);
  79        memcpy(ce->name, base, baselen);
  80        memcpy(ce->name + baselen, pathname, len - baselen);
  81        ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
  82        ce->ce_namelen = len;
  83        ce->ce_mode = create_ce_mode(mode);
  84        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
  85        return 0;
  86}
  87
  88static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
  89{
  90        read_tree_recursive(tree, "", 0, 0, pathspec, update_some, NULL);
  91
  92        /* update the index with the given tree's info
  93         * for all args, expanding wildcards, and exit
  94         * with any non-zero return code.
  95         */
  96        return 0;
  97}
  98
  99static int skip_same_name(const struct cache_entry *ce, int pos)
 100{
 101        while (++pos < active_nr &&
 102               !strcmp(active_cache[pos]->name, ce->name))
 103                ; /* skip */
 104        return pos;
 105}
 106
 107static int check_stage(int stage, const struct cache_entry *ce, int pos)
 108{
 109        while (pos < active_nr &&
 110               !strcmp(active_cache[pos]->name, ce->name)) {
 111                if (ce_stage(active_cache[pos]) == stage)
 112                        return 0;
 113                pos++;
 114        }
 115        if (stage == 2)
 116                return error(_("path '%s' does not have our version"), ce->name);
 117        else
 118                return error(_("path '%s' does not have their version"), ce->name);
 119}
 120
 121static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
 122{
 123        unsigned seen = 0;
 124        const char *name = ce->name;
 125
 126        while (pos < active_nr) {
 127                ce = active_cache[pos];
 128                if (strcmp(name, ce->name))
 129                        break;
 130                seen |= (1 << ce_stage(ce));
 131                pos++;
 132        }
 133        if ((stages & seen) != stages)
 134                return error(_("path '%s' does not have all necessary versions"),
 135                             name);
 136        return 0;
 137}
 138
 139static int checkout_stage(int stage, struct cache_entry *ce, int pos,
 140                          struct checkout *state)
 141{
 142        while (pos < active_nr &&
 143               !strcmp(active_cache[pos]->name, ce->name)) {
 144                if (ce_stage(active_cache[pos]) == stage)
 145                        return checkout_entry(active_cache[pos], state, NULL);
 146                pos++;
 147        }
 148        if (stage == 2)
 149                return error(_("path '%s' does not have our version"), ce->name);
 150        else
 151                return error(_("path '%s' does not have their version"), ce->name);
 152}
 153
 154static int checkout_merged(int pos, struct checkout *state)
 155{
 156        struct cache_entry *ce = active_cache[pos];
 157        const char *path = ce->name;
 158        mmfile_t ancestor, ours, theirs;
 159        int status;
 160        unsigned char sha1[20];
 161        mmbuffer_t result_buf;
 162        unsigned char threeway[3][20];
 163        unsigned mode = 0;
 164
 165        memset(threeway, 0, sizeof(threeway));
 166        while (pos < active_nr) {
 167                int stage;
 168                stage = ce_stage(ce);
 169                if (!stage || strcmp(path, ce->name))
 170                        break;
 171                hashcpy(threeway[stage - 1], ce->sha1);
 172                if (stage == 2)
 173                        mode = create_ce_mode(ce->ce_mode);
 174                pos++;
 175                ce = active_cache[pos];
 176        }
 177        if (is_null_sha1(threeway[1]) || is_null_sha1(threeway[2]))
 178                return error(_("path '%s' does not have necessary versions"), path);
 179
 180        read_mmblob(&ancestor, threeway[0]);
 181        read_mmblob(&ours, threeway[1]);
 182        read_mmblob(&theirs, threeway[2]);
 183
 184        /*
 185         * NEEDSWORK: re-create conflicts from merges with
 186         * merge.renormalize set, too
 187         */
 188        status = ll_merge(&result_buf, path, &ancestor, "base",
 189                          &ours, "ours", &theirs, "theirs", NULL);
 190        free(ancestor.ptr);
 191        free(ours.ptr);
 192        free(theirs.ptr);
 193        if (status < 0 || !result_buf.ptr) {
 194                free(result_buf.ptr);
 195                return error(_("path '%s': cannot merge"), path);
 196        }
 197
 198        /*
 199         * NEEDSWORK:
 200         * There is absolutely no reason to write this as a blob object
 201         * and create a phony cache entry just to leak.  This hack is
 202         * primarily to get to the write_entry() machinery that massages
 203         * the contents to work-tree format and writes out which only
 204         * allows it for a cache entry.  The code in write_entry() needs
 205         * to be refactored to allow us to feed a <buffer, size, mode>
 206         * instead of a cache entry.  Such a refactoring would help
 207         * merge_recursive as well (it also writes the merge result to the
 208         * object database even when it may contain conflicts).
 209         */
 210        if (write_sha1_file(result_buf.ptr, result_buf.size,
 211                            blob_type, sha1))
 212                die(_("Unable to add merge result for '%s'"), path);
 213        ce = make_cache_entry(mode, sha1, path, 2, 0);
 214        if (!ce)
 215                die(_("make_cache_entry failed for path '%s'"), path);
 216        status = checkout_entry(ce, state, NULL);
 217        return status;
 218}
 219
 220static int checkout_paths(const struct checkout_opts *opts,
 221                          const char *revision)
 222{
 223        int pos;
 224        struct checkout state;
 225        static char *ps_matched;
 226        unsigned char rev[20];
 227        int flag;
 228        struct commit *head;
 229        int errs = 0;
 230        struct lock_file *lock_file;
 231
 232        if (opts->track != BRANCH_TRACK_UNSPECIFIED)
 233                die(_("'%s' cannot be used with updating paths"), "--track");
 234
 235        if (opts->new_branch_log)
 236                die(_("'%s' cannot be used with updating paths"), "-l");
 237
 238        if (opts->force && opts->patch_mode)
 239                die(_("'%s' cannot be used with updating paths"), "-f");
 240
 241        if (opts->force_detach)
 242                die(_("'%s' cannot be used with updating paths"), "--detach");
 243
 244        if (opts->merge && opts->patch_mode)
 245                die(_("'%s' cannot be used with %s"), "--merge", "--patch");
 246
 247        if (opts->force && opts->merge)
 248                die(_("'%s' cannot be used with %s"), "-f", "-m");
 249
 250        if (opts->new_branch)
 251                die(_("Cannot update paths and switch to branch '%s' at the same time."),
 252                    opts->new_branch);
 253
 254        if (opts->patch_mode)
 255                return run_add_interactive(revision, "--patch=checkout",
 256                                           &opts->pathspec);
 257
 258        lock_file = xcalloc(1, sizeof(struct lock_file));
 259
 260        hold_locked_index(lock_file, 1);
 261        if (read_cache_preload(&opts->pathspec) < 0)
 262                return error(_("corrupt index file"));
 263
 264        if (opts->source_tree)
 265                read_tree_some(opts->source_tree, &opts->pathspec);
 266
 267        ps_matched = xcalloc(1, opts->pathspec.nr);
 268
 269        /*
 270         * Make sure all pathspecs participated in locating the paths
 271         * to be checked out.
 272         */
 273        for (pos = 0; pos < active_nr; pos++) {
 274                struct cache_entry *ce = active_cache[pos];
 275                ce->ce_flags &= ~CE_MATCHED;
 276                if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
 277                        continue;
 278                if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
 279                        /*
 280                         * "git checkout tree-ish -- path", but this entry
 281                         * is in the original index; it will not be checked
 282                         * out to the working tree and it does not matter
 283                         * if pathspec matched this entry.  We will not do
 284                         * anything to this entry at all.
 285                         */
 286                        continue;
 287                /*
 288                 * Either this entry came from the tree-ish we are
 289                 * checking the paths out of, or we are checking out
 290                 * of the index.
 291                 *
 292                 * If it comes from the tree-ish, we already know it
 293                 * matches the pathspec and could just stamp
 294                 * CE_MATCHED to it from update_some(). But we still
 295                 * need ps_matched and read_tree_recursive (and
 296                 * eventually tree_entry_interesting) cannot fill
 297                 * ps_matched yet. Once it can, we can avoid calling
 298                 * match_pathspec() for _all_ entries when
 299                 * opts->source_tree != NULL.
 300                 */
 301                if (ce_path_match(ce, &opts->pathspec, ps_matched))
 302                        ce->ce_flags |= CE_MATCHED;
 303        }
 304
 305        if (report_path_error(ps_matched, &opts->pathspec, opts->prefix)) {
 306                free(ps_matched);
 307                return 1;
 308        }
 309        free(ps_matched);
 310
 311        /* "checkout -m path" to recreate conflicted state */
 312        if (opts->merge)
 313                unmerge_marked_index(&the_index);
 314
 315        /* Any unmerged paths? */
 316        for (pos = 0; pos < active_nr; pos++) {
 317                const struct cache_entry *ce = active_cache[pos];
 318                if (ce->ce_flags & CE_MATCHED) {
 319                        if (!ce_stage(ce))
 320                                continue;
 321                        if (opts->force) {
 322                                warning(_("path '%s' is unmerged"), ce->name);
 323                        } else if (opts->writeout_stage) {
 324                                errs |= check_stage(opts->writeout_stage, ce, pos);
 325                        } else if (opts->merge) {
 326                                errs |= check_stages((1<<2) | (1<<3), ce, pos);
 327                        } else {
 328                                errs = 1;
 329                                error(_("path '%s' is unmerged"), ce->name);
 330                        }
 331                        pos = skip_same_name(ce, pos) - 1;
 332                }
 333        }
 334        if (errs)
 335                return 1;
 336
 337        /* Now we are committed to check them out */
 338        memset(&state, 0, sizeof(state));
 339        state.force = 1;
 340        state.refresh_cache = 1;
 341        state.istate = &the_index;
 342        for (pos = 0; pos < active_nr; pos++) {
 343                struct cache_entry *ce = active_cache[pos];
 344                if (ce->ce_flags & CE_MATCHED) {
 345                        if (!ce_stage(ce)) {
 346                                errs |= checkout_entry(ce, &state, NULL);
 347                                continue;
 348                        }
 349                        if (opts->writeout_stage)
 350                                errs |= checkout_stage(opts->writeout_stage, ce, pos, &state);
 351                        else if (opts->merge)
 352                                errs |= checkout_merged(pos, &state);
 353                        pos = skip_same_name(ce, pos) - 1;
 354                }
 355        }
 356
 357        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
 358                die(_("unable to write new index file"));
 359
 360        read_ref_full("HEAD", 0, rev, &flag);
 361        head = lookup_commit_reference_gently(rev, 1);
 362
 363        errs |= post_checkout_hook(head, head, 0);
 364        return errs;
 365}
 366
 367static void show_local_changes(struct object *head,
 368                               const struct diff_options *opts)
 369{
 370        struct rev_info rev;
 371        /* I think we want full paths, even if we're in a subdirectory. */
 372        init_revisions(&rev, NULL);
 373        rev.diffopt.flags = opts->flags;
 374        rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
 375        diff_setup_done(&rev.diffopt);
 376        add_pending_object(&rev, head, NULL);
 377        run_diff_index(&rev, 0);
 378}
 379
 380static void describe_detached_head(const char *msg, struct commit *commit)
 381{
 382        struct strbuf sb = STRBUF_INIT;
 383        if (!parse_commit(commit))
 384                pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
 385        fprintf(stderr, "%s %s... %s\n", msg,
 386                find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
 387        strbuf_release(&sb);
 388}
 389
 390static int reset_tree(struct tree *tree, const struct checkout_opts *o,
 391                      int worktree, int *writeout_error)
 392{
 393        struct unpack_trees_options opts;
 394        struct tree_desc tree_desc;
 395
 396        memset(&opts, 0, sizeof(opts));
 397        opts.head_idx = -1;
 398        opts.update = worktree;
 399        opts.skip_unmerged = !worktree;
 400        opts.reset = 1;
 401        opts.merge = 1;
 402        opts.fn = oneway_merge;
 403        opts.verbose_update = !o->quiet && isatty(2);
 404        opts.src_index = &the_index;
 405        opts.dst_index = &the_index;
 406        parse_tree(tree);
 407        init_tree_desc(&tree_desc, tree->buffer, tree->size);
 408        switch (unpack_trees(1, &tree_desc, &opts)) {
 409        case -2:
 410                *writeout_error = 1;
 411                /*
 412                 * We return 0 nevertheless, as the index is all right
 413                 * and more importantly we have made best efforts to
 414                 * update paths in the work tree, and we cannot revert
 415                 * them.
 416                 */
 417        case 0:
 418                return 0;
 419        default:
 420                return 128;
 421        }
 422}
 423
 424struct branch_info {
 425        const char *name; /* The short name used */
 426        const char *path; /* The full name of a real branch */
 427        struct commit *commit; /* The named commit */
 428        /*
 429         * if not null the branch is detached because it's already
 430         * checked out in this checkout
 431         */
 432        char *checkout;
 433};
 434
 435static void setup_branch_path(struct branch_info *branch)
 436{
 437        struct strbuf buf = STRBUF_INIT;
 438
 439        strbuf_branchname(&buf, branch->name);
 440        if (strcmp(buf.buf, branch->name))
 441                branch->name = xstrdup(buf.buf);
 442        strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
 443        branch->path = strbuf_detach(&buf, NULL);
 444}
 445
 446static int merge_working_tree(const struct checkout_opts *opts,
 447                              struct branch_info *old,
 448                              struct branch_info *new,
 449                              int *writeout_error)
 450{
 451        int ret;
 452        struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 453
 454        hold_locked_index(lock_file, 1);
 455        if (read_cache_preload(NULL) < 0)
 456                return error(_("corrupt index file"));
 457
 458        resolve_undo_clear();
 459        if (opts->force) {
 460                ret = reset_tree(new->commit->tree, opts, 1, writeout_error);
 461                if (ret)
 462                        return ret;
 463        } else {
 464                struct tree_desc trees[2];
 465                struct tree *tree;
 466                struct unpack_trees_options topts;
 467
 468                memset(&topts, 0, sizeof(topts));
 469                topts.head_idx = -1;
 470                topts.src_index = &the_index;
 471                topts.dst_index = &the_index;
 472
 473                setup_unpack_trees_porcelain(&topts, "checkout");
 474
 475                refresh_cache(REFRESH_QUIET);
 476
 477                if (unmerged_cache()) {
 478                        error(_("you need to resolve your current index first"));
 479                        return 1;
 480                }
 481
 482                /* 2-way merge to the new branch */
 483                topts.initial_checkout = is_cache_unborn();
 484                topts.update = 1;
 485                topts.merge = 1;
 486                topts.gently = opts->merge && old->commit;
 487                topts.verbose_update = !opts->quiet && isatty(2);
 488                topts.fn = twoway_merge;
 489                if (opts->overwrite_ignore) {
 490                        topts.dir = xcalloc(1, sizeof(*topts.dir));
 491                        topts.dir->flags |= DIR_SHOW_IGNORED;
 492                        setup_standard_excludes(topts.dir);
 493                }
 494                tree = parse_tree_indirect(old->commit && !opts->new_worktree_mode ?
 495                                           old->commit->object.sha1 :
 496                                           EMPTY_TREE_SHA1_BIN);
 497                init_tree_desc(&trees[0], tree->buffer, tree->size);
 498                tree = parse_tree_indirect(new->commit->object.sha1);
 499                init_tree_desc(&trees[1], tree->buffer, tree->size);
 500
 501                ret = unpack_trees(2, trees, &topts);
 502                if (ret == -1) {
 503                        /*
 504                         * Unpack couldn't do a trivial merge; either
 505                         * give up or do a real merge, depending on
 506                         * whether the merge flag was used.
 507                         */
 508                        struct tree *result;
 509                        struct tree *work;
 510                        struct merge_options o;
 511                        if (!opts->merge)
 512                                return 1;
 513
 514                        /*
 515                         * Without old->commit, the below is the same as
 516                         * the two-tree unpack we already tried and failed.
 517                         */
 518                        if (!old->commit)
 519                                return 1;
 520
 521                        /* Do more real merge */
 522
 523                        /*
 524                         * We update the index fully, then write the
 525                         * tree from the index, then merge the new
 526                         * branch with the current tree, with the old
 527                         * branch as the base. Then we reset the index
 528                         * (but not the working tree) to the new
 529                         * branch, leaving the working tree as the
 530                         * merged version, but skipping unmerged
 531                         * entries in the index.
 532                         */
 533
 534                        add_files_to_cache(NULL, NULL, 0);
 535                        /*
 536                         * NEEDSWORK: carrying over local changes
 537                         * when branches have different end-of-line
 538                         * normalization (or clean+smudge rules) is
 539                         * a pain; plumb in an option to set
 540                         * o.renormalize?
 541                         */
 542                        init_merge_options(&o);
 543                        o.verbosity = 0;
 544                        work = write_tree_from_memory(&o);
 545
 546                        ret = reset_tree(new->commit->tree, opts, 1,
 547                                         writeout_error);
 548                        if (ret)
 549                                return ret;
 550                        o.ancestor = old->name;
 551                        o.branch1 = new->name;
 552                        o.branch2 = "local";
 553                        merge_trees(&o, new->commit->tree, work,
 554                                old->commit->tree, &result);
 555                        ret = reset_tree(new->commit->tree, opts, 0,
 556                                         writeout_error);
 557                        if (ret)
 558                                return ret;
 559                }
 560        }
 561
 562        if (!active_cache_tree)
 563                active_cache_tree = cache_tree();
 564
 565        if (!cache_tree_fully_valid(active_cache_tree))
 566                cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
 567
 568        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
 569                die(_("unable to write new index file"));
 570
 571        if (!opts->force && !opts->quiet)
 572                show_local_changes(&new->commit->object, &opts->diff_options);
 573
 574        return 0;
 575}
 576
 577static void report_tracking(struct branch_info *new)
 578{
 579        struct strbuf sb = STRBUF_INIT;
 580        struct branch *branch = branch_get(new->name);
 581
 582        if (!format_tracking_info(branch, &sb))
 583                return;
 584        fputs(sb.buf, stdout);
 585        strbuf_release(&sb);
 586}
 587
 588static void update_refs_for_switch(const struct checkout_opts *opts,
 589                                   struct branch_info *old,
 590                                   struct branch_info *new)
 591{
 592        struct strbuf msg = STRBUF_INIT;
 593        const char *old_desc, *reflog_msg;
 594        if (opts->new_branch) {
 595                if (opts->new_orphan_branch) {
 596                        if (opts->new_branch_log && !log_all_ref_updates) {
 597                                int temp;
 598                                struct strbuf log_file = STRBUF_INIT;
 599                                int ret;
 600                                const char *ref_name;
 601
 602                                ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
 603                                temp = log_all_ref_updates;
 604                                log_all_ref_updates = 1;
 605                                ret = log_ref_setup(ref_name, &log_file);
 606                                log_all_ref_updates = temp;
 607                                strbuf_release(&log_file);
 608                                if (ret) {
 609                                        fprintf(stderr, _("Can not do reflog for '%s'\n"),
 610                                            opts->new_orphan_branch);
 611                                        return;
 612                                }
 613                        }
 614                }
 615                else
 616                        create_branch(old->name, opts->new_branch, new->name,
 617                                      opts->new_branch_force ? 1 : 0,
 618                                      opts->new_branch_log,
 619                                      opts->new_branch_force ? 1 : 0,
 620                                      opts->quiet,
 621                                      opts->track);
 622                new->name = opts->new_branch;
 623                setup_branch_path(new);
 624        }
 625
 626        old_desc = old->name;
 627        if (!old_desc && old->commit)
 628                old_desc = sha1_to_hex(old->commit->object.sha1);
 629
 630        reflog_msg = getenv("GIT_REFLOG_ACTION");
 631        if (!reflog_msg)
 632                strbuf_addf(&msg, "checkout: moving from %s to %s",
 633                        old_desc ? old_desc : "(invalid)", new->name);
 634        else
 635                strbuf_insert(&msg, 0, reflog_msg, strlen(reflog_msg));
 636
 637        if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
 638                /* Nothing to do. */
 639        } else if (opts->force_detach || !new->path) {  /* No longer on any branch. */
 640                update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
 641                           REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
 642                if (!opts->quiet) {
 643                        if (old->path && advice_detached_head)
 644                                detach_advice(new->name);
 645                        describe_detached_head(_("HEAD is now at"), new->commit);
 646                }
 647        } else if (new->path) { /* Switch branches. */
 648                create_symref("HEAD", new->path, msg.buf);
 649                if (!opts->quiet) {
 650                        if (old->path && !strcmp(new->path, old->path)) {
 651                                if (opts->new_branch_force)
 652                                        fprintf(stderr, _("Reset branch '%s'\n"),
 653                                                new->name);
 654                                else
 655                                        fprintf(stderr, _("Already on '%s'\n"),
 656                                                new->name);
 657                        } else if (opts->new_branch) {
 658                                if (opts->branch_exists)
 659                                        fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
 660                                else
 661                                        fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
 662                        } else {
 663                                fprintf(stderr, _("Switched to branch '%s'\n"),
 664                                        new->name);
 665                        }
 666                }
 667                if (old->path && old->name) {
 668                        if (!ref_exists(old->path) && reflog_exists(old->path))
 669                                delete_reflog(old->path);
 670                }
 671        }
 672        remove_branch_state();
 673        strbuf_release(&msg);
 674        if (!opts->quiet &&
 675            (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
 676                report_tracking(new);
 677}
 678
 679static int add_pending_uninteresting_ref(const char *refname,
 680                                         const unsigned char *sha1,
 681                                         int flags, void *cb_data)
 682{
 683        add_pending_sha1(cb_data, refname, sha1, UNINTERESTING);
 684        return 0;
 685}
 686
 687static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
 688{
 689        strbuf_addstr(sb, "  ");
 690        strbuf_addstr(sb,
 691                find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
 692        strbuf_addch(sb, ' ');
 693        if (!parse_commit(commit))
 694                pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
 695        strbuf_addch(sb, '\n');
 696}
 697
 698#define ORPHAN_CUTOFF 4
 699static void suggest_reattach(struct commit *commit, struct rev_info *revs)
 700{
 701        struct commit *c, *last = NULL;
 702        struct strbuf sb = STRBUF_INIT;
 703        int lost = 0;
 704        while ((c = get_revision(revs)) != NULL) {
 705                if (lost < ORPHAN_CUTOFF)
 706                        describe_one_orphan(&sb, c);
 707                last = c;
 708                lost++;
 709        }
 710        if (ORPHAN_CUTOFF < lost) {
 711                int more = lost - ORPHAN_CUTOFF;
 712                if (more == 1)
 713                        describe_one_orphan(&sb, last);
 714                else
 715                        strbuf_addf(&sb, _(" ... and %d more.\n"), more);
 716        }
 717
 718        fprintf(stderr,
 719                Q_(
 720                /* The singular version */
 721                "Warning: you are leaving %d commit behind, "
 722                "not connected to\n"
 723                "any of your branches:\n\n"
 724                "%s\n",
 725                /* The plural version */
 726                "Warning: you are leaving %d commits behind, "
 727                "not connected to\n"
 728                "any of your branches:\n\n"
 729                "%s\n",
 730                /* Give ngettext() the count */
 731                lost),
 732                lost,
 733                sb.buf);
 734        strbuf_release(&sb);
 735
 736        if (advice_detached_head)
 737                fprintf(stderr,
 738                        _(
 739                        "If you want to keep them by creating a new branch, "
 740                        "this may be a good time\nto do so with:\n\n"
 741                        " git branch new_branch_name %s\n\n"),
 742                        find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
 743}
 744
 745/*
 746 * We are about to leave commit that was at the tip of a detached
 747 * HEAD.  If it is not reachable from any ref, this is the last chance
 748 * for the user to do so without resorting to reflog.
 749 */
 750static void orphaned_commit_warning(struct commit *old, struct commit *new)
 751{
 752        struct rev_info revs;
 753        struct object *object = &old->object;
 754        struct object_array refs;
 755
 756        init_revisions(&revs, NULL);
 757        setup_revisions(0, NULL, &revs, NULL);
 758
 759        object->flags &= ~UNINTERESTING;
 760        add_pending_object(&revs, object, sha1_to_hex(object->sha1));
 761
 762        for_each_ref(add_pending_uninteresting_ref, &revs);
 763        add_pending_sha1(&revs, "HEAD", new->object.sha1, UNINTERESTING);
 764
 765        refs = revs.pending;
 766        revs.leak_pending = 1;
 767
 768        if (prepare_revision_walk(&revs))
 769                die(_("internal error in revision walk"));
 770        if (!(old->object.flags & UNINTERESTING))
 771                suggest_reattach(old, &revs);
 772        else
 773                describe_detached_head(_("Previous HEAD position was"), old);
 774
 775        clear_commit_marks_for_object_array(&refs, ALL_REV_FLAGS);
 776        free(refs.objects);
 777}
 778
 779static int switch_branches(const struct checkout_opts *opts,
 780                           struct branch_info *new)
 781{
 782        int ret = 0;
 783        struct branch_info old;
 784        void *path_to_free;
 785        unsigned char rev[20];
 786        int flag, writeout_error = 0;
 787        memset(&old, 0, sizeof(old));
 788        old.path = path_to_free = resolve_refdup("HEAD", 0, rev, &flag);
 789        old.commit = lookup_commit_reference_gently(rev, 1);
 790        if (!(flag & REF_ISSYMREF))
 791                old.path = NULL;
 792
 793        if (old.path)
 794                skip_prefix(old.path, "refs/heads/", &old.name);
 795
 796        if (!new->name) {
 797                new->name = "HEAD";
 798                new->commit = old.commit;
 799                if (!new->commit)
 800                        die(_("You are on a branch yet to be born"));
 801                parse_commit_or_die(new->commit);
 802        }
 803
 804        ret = merge_working_tree(opts, &old, new, &writeout_error);
 805        if (ret) {
 806                free(path_to_free);
 807                return ret;
 808        }
 809
 810        if (!opts->quiet && !old.path && old.commit &&
 811            new->commit != old.commit && !opts->new_worktree_mode)
 812                orphaned_commit_warning(old.commit, new->commit);
 813
 814        update_refs_for_switch(opts, &old, new);
 815
 816        ret = post_checkout_hook(old.commit, new->commit, 1);
 817        free(path_to_free);
 818        return ret || writeout_error;
 819}
 820
 821static int git_checkout_config(const char *var, const char *value, void *cb)
 822{
 823        if (!strcmp(var, "diff.ignoresubmodules")) {
 824                struct checkout_opts *opts = cb;
 825                handle_ignore_submodules_arg(&opts->diff_options, value);
 826                return 0;
 827        }
 828
 829        if (starts_with(var, "submodule."))
 830                return parse_submodule_config_option(var, value);
 831
 832        return git_xmerge_config(var, value, NULL);
 833}
 834
 835struct tracking_name_data {
 836        /* const */ char *src_ref;
 837        char *dst_ref;
 838        unsigned char *dst_sha1;
 839        int unique;
 840};
 841
 842static int check_tracking_name(struct remote *remote, void *cb_data)
 843{
 844        struct tracking_name_data *cb = cb_data;
 845        struct refspec query;
 846        memset(&query, 0, sizeof(struct refspec));
 847        query.src = cb->src_ref;
 848        if (remote_find_tracking(remote, &query) ||
 849            get_sha1(query.dst, cb->dst_sha1)) {
 850                free(query.dst);
 851                return 0;
 852        }
 853        if (cb->dst_ref) {
 854                free(query.dst);
 855                cb->unique = 0;
 856                return 0;
 857        }
 858        cb->dst_ref = query.dst;
 859        return 0;
 860}
 861
 862static const char *unique_tracking_name(const char *name, unsigned char *sha1)
 863{
 864        struct tracking_name_data cb_data = { NULL, NULL, NULL, 1 };
 865        char src_ref[PATH_MAX];
 866        snprintf(src_ref, PATH_MAX, "refs/heads/%s", name);
 867        cb_data.src_ref = src_ref;
 868        cb_data.dst_sha1 = sha1;
 869        for_each_remote(check_tracking_name, &cb_data);
 870        if (cb_data.unique)
 871                return cb_data.dst_ref;
 872        free(cb_data.dst_ref);
 873        return NULL;
 874}
 875
 876static void check_linked_checkout(struct branch_info *new, const char *id)
 877{
 878        struct strbuf sb = STRBUF_INIT;
 879        struct strbuf path = STRBUF_INIT;
 880        struct strbuf gitdir = STRBUF_INIT;
 881        const char *start, *end;
 882
 883        /*
 884         * $GIT_COMMON_DIR/HEAD is practically outside
 885         * $GIT_DIR so resolve_ref_unsafe() won't work (it
 886         * uses git_path). Parse the ref ourselves.
 887         */
 888        if (id)
 889                strbuf_addf(&path, "%s/worktrees/%s/HEAD", get_git_common_dir(), id);
 890        else
 891                strbuf_addf(&path, "%s/HEAD", get_git_common_dir());
 892
 893        if (strbuf_read_file(&sb, path.buf, 0) < 0 ||
 894            !skip_prefix(sb.buf, "ref:", &start))
 895                goto done;
 896        while (isspace(*start))
 897                start++;
 898        end = start;
 899        while (*end && !isspace(*end))
 900                end++;
 901        if (strncmp(start, new->path, end - start) || new->path[end - start] != '\0')
 902                goto done;
 903        if (id) {
 904                strbuf_reset(&path);
 905                strbuf_addf(&path, "%s/worktrees/%s/gitdir", get_git_common_dir(), id);
 906                if (strbuf_read_file(&gitdir, path.buf, 0) <= 0)
 907                        goto done;
 908                strbuf_rtrim(&gitdir);
 909        } else
 910                strbuf_addstr(&gitdir, get_git_common_dir());
 911        die(_("'%s' is already checked out at '%s'"), new->name, gitdir.buf);
 912done:
 913        strbuf_release(&path);
 914        strbuf_release(&sb);
 915        strbuf_release(&gitdir);
 916}
 917
 918static void die_if_checked_out(struct branch_info *new)
 919{
 920        struct strbuf path = STRBUF_INIT;
 921        DIR *dir;
 922        struct dirent *d;
 923
 924        check_linked_checkout(new, NULL);
 925
 926        strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
 927        dir = opendir(path.buf);
 928        strbuf_release(&path);
 929        if (!dir)
 930                return;
 931
 932        while ((d = readdir(dir)) != NULL) {
 933                if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
 934                        continue;
 935                check_linked_checkout(new, d->d_name);
 936        }
 937        closedir(dir);
 938}
 939
 940static int parse_branchname_arg(int argc, const char **argv,
 941                                int dwim_new_local_branch_ok,
 942                                struct branch_info *new,
 943                                struct checkout_opts *opts,
 944                                unsigned char rev[20])
 945{
 946        struct tree **source_tree = &opts->source_tree;
 947        const char **new_branch = &opts->new_branch;
 948        int argcount = 0;
 949        unsigned char branch_rev[20];
 950        const char *arg;
 951        int dash_dash_pos;
 952        int has_dash_dash = 0;
 953        int i;
 954
 955        /*
 956         * case 1: git checkout <ref> -- [<paths>]
 957         *
 958         *   <ref> must be a valid tree, everything after the '--' must be
 959         *   a path.
 960         *
 961         * case 2: git checkout -- [<paths>]
 962         *
 963         *   everything after the '--' must be paths.
 964         *
 965         * case 3: git checkout <something> [--]
 966         *
 967         *   (a) If <something> is a commit, that is to
 968         *       switch to the branch or detach HEAD at it.  As a special case,
 969         *       if <something> is A...B (missing A or B means HEAD but you can
 970         *       omit at most one side), and if there is a unique merge base
 971         *       between A and B, A...B names that merge base.
 972         *
 973         *   (b) If <something> is _not_ a commit, either "--" is present
 974         *       or <something> is not a path, no -t or -b was given, and
 975         *       and there is a tracking branch whose name is <something>
 976         *       in one and only one remote, then this is a short-hand to
 977         *       fork local <something> from that remote-tracking branch.
 978         *
 979         *   (c) Otherwise, if "--" is present, treat it like case (1).
 980         *
 981         *   (d) Otherwise :
 982         *       - if it's a reference, treat it like case (1)
 983         *       - else if it's a path, treat it like case (2)
 984         *       - else: fail.
 985         *
 986         * case 4: git checkout <something> <paths>
 987         *
 988         *   The first argument must not be ambiguous.
 989         *   - If it's *only* a reference, treat it like case (1).
 990         *   - If it's only a path, treat it like case (2).
 991         *   - else: fail.
 992         *
 993         */
 994        if (!argc)
 995                return 0;
 996
 997        arg = argv[0];
 998        dash_dash_pos = -1;
 999        for (i = 0; i < argc; i++) {
1000                if (!strcmp(argv[i], "--")) {
1001                        dash_dash_pos = i;
1002                        break;
1003                }
1004        }
1005        if (dash_dash_pos == 0)
1006                return 1; /* case (2) */
1007        else if (dash_dash_pos == 1)
1008                has_dash_dash = 1; /* case (3) or (1) */
1009        else if (dash_dash_pos >= 2)
1010                die(_("only one reference expected, %d given."), dash_dash_pos);
1011
1012        if (!strcmp(arg, "-"))
1013                arg = "@{-1}";
1014
1015        if (get_sha1_mb(arg, rev)) {
1016                /*
1017                 * Either case (3) or (4), with <something> not being
1018                 * a commit, or an attempt to use case (1) with an
1019                 * invalid ref.
1020                 *
1021                 * It's likely an error, but we need to find out if
1022                 * we should auto-create the branch, case (3).(b).
1023                 */
1024                int recover_with_dwim = dwim_new_local_branch_ok;
1025
1026                if (check_filename(NULL, arg) && !has_dash_dash)
1027                        recover_with_dwim = 0;
1028                /*
1029                 * Accept "git checkout foo" and "git checkout foo --"
1030                 * as candidates for dwim.
1031                 */
1032                if (!(argc == 1 && !has_dash_dash) &&
1033                    !(argc == 2 && has_dash_dash))
1034                        recover_with_dwim = 0;
1035
1036                if (recover_with_dwim) {
1037                        const char *remote = unique_tracking_name(arg, rev);
1038                        if (remote) {
1039                                *new_branch = arg;
1040                                arg = remote;
1041                                /* DWIMmed to create local branch, case (3).(b) */
1042                        } else {
1043                                recover_with_dwim = 0;
1044                        }
1045                }
1046
1047                if (!recover_with_dwim) {
1048                        if (has_dash_dash)
1049                                die(_("invalid reference: %s"), arg);
1050                        return argcount;
1051                }
1052        }
1053
1054        /* we can't end up being in (2) anymore, eat the argument */
1055        argcount++;
1056        argv++;
1057        argc--;
1058
1059        new->name = arg;
1060        setup_branch_path(new);
1061
1062        if (!check_refname_format(new->path, 0) &&
1063            !read_ref(new->path, branch_rev))
1064                hashcpy(rev, branch_rev);
1065        else
1066                new->path = NULL; /* not an existing branch */
1067
1068        new->commit = lookup_commit_reference_gently(rev, 1);
1069        if (!new->commit) {
1070                /* not a commit */
1071                *source_tree = parse_tree_indirect(rev);
1072        } else {
1073                parse_commit_or_die(new->commit);
1074                *source_tree = new->commit->tree;
1075        }
1076
1077        if (!*source_tree)                   /* case (1): want a tree */
1078                die(_("reference is not a tree: %s"), arg);
1079        if (!has_dash_dash) {/* case (3).(d) -> (1) */
1080                /*
1081                 * Do not complain the most common case
1082                 *      git checkout branch
1083                 * even if there happen to be a file called 'branch';
1084                 * it would be extremely annoying.
1085                 */
1086                if (argc)
1087                        verify_non_filename(NULL, arg);
1088        } else {
1089                argcount++;
1090                argv++;
1091                argc--;
1092        }
1093
1094        return argcount;
1095}
1096
1097static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1098{
1099        int status;
1100        struct strbuf branch_ref = STRBUF_INIT;
1101
1102        if (!opts->new_branch)
1103                die(_("You are on a branch yet to be born"));
1104        strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1105        status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1106        strbuf_release(&branch_ref);
1107        if (!opts->quiet)
1108                fprintf(stderr, _("Switched to a new branch '%s'\n"),
1109                        opts->new_branch);
1110        return status;
1111}
1112
1113static int checkout_branch(struct checkout_opts *opts,
1114                           struct branch_info *new)
1115{
1116        if (opts->pathspec.nr)
1117                die(_("paths cannot be used with switching branches"));
1118
1119        if (opts->patch_mode)
1120                die(_("'%s' cannot be used with switching branches"),
1121                    "--patch");
1122
1123        if (opts->writeout_stage)
1124                die(_("'%s' cannot be used with switching branches"),
1125                    "--ours/--theirs");
1126
1127        if (opts->force && opts->merge)
1128                die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1129
1130        if (opts->force_detach && opts->new_branch)
1131                die(_("'%s' cannot be used with '%s'"),
1132                    "--detach", "-b/-B/--orphan");
1133
1134        if (opts->new_orphan_branch) {
1135                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1136                        die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1137        } else if (opts->force_detach) {
1138                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1139                        die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1140        } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1141                opts->track = git_branch_track;
1142
1143        if (new->name && !new->commit)
1144                die(_("Cannot switch branch to a non-commit '%s'"),
1145                    new->name);
1146
1147        if (new->path && !opts->force_detach && !opts->new_branch &&
1148            !opts->ignore_other_worktrees) {
1149                unsigned char sha1[20];
1150                int flag;
1151                char *head_ref = resolve_refdup("HEAD", 0, sha1, &flag);
1152                if (head_ref &&
1153                    (!(flag & REF_ISSYMREF) || strcmp(head_ref, new->path)))
1154                        die_if_checked_out(new);
1155                free(head_ref);
1156        }
1157
1158        if (!new->commit && opts->new_branch) {
1159                unsigned char rev[20];
1160                int flag;
1161
1162                if (!read_ref_full("HEAD", 0, rev, &flag) &&
1163                    (flag & REF_ISSYMREF) && is_null_sha1(rev))
1164                        return switch_unborn_to_new_branch(opts);
1165        }
1166        return switch_branches(opts, new);
1167}
1168
1169int cmd_checkout(int argc, const char **argv, const char *prefix)
1170{
1171        struct checkout_opts opts;
1172        struct branch_info new;
1173        char *conflict_style = NULL;
1174        int dwim_new_local_branch = 1;
1175        struct option options[] = {
1176                OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
1177                OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1178                           N_("create and checkout a new branch")),
1179                OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1180                           N_("create/reset and checkout a branch")),
1181                OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1182                OPT_BOOL(0, "detach", &opts.force_detach, N_("detach the HEAD at named commit")),
1183                OPT_SET_INT('t', "track",  &opts.track, N_("set upstream info for new branch"),
1184                        BRANCH_TRACK_EXPLICIT),
1185                OPT_STRING(0, "orphan", &opts.new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1186                OPT_SET_INT('2', "ours", &opts.writeout_stage, N_("checkout our version for unmerged files"),
1187                            2),
1188                OPT_SET_INT('3', "theirs", &opts.writeout_stage, N_("checkout their version for unmerged files"),
1189                            3),
1190                OPT__FORCE(&opts.force, N_("force checkout (throw away local modifications)")),
1191                OPT_BOOL('m', "merge", &opts.merge, N_("perform a 3-way merge with the new branch")),
1192                OPT_BOOL(0, "overwrite-ignore", &opts.overwrite_ignore, N_("update ignored files (default)")),
1193                OPT_STRING(0, "conflict", &conflict_style, N_("style"),
1194                           N_("conflict style (merge or diff3)")),
1195                OPT_BOOL('p', "patch", &opts.patch_mode, N_("select hunks interactively")),
1196                OPT_BOOL(0, "ignore-skip-worktree-bits", &opts.ignore_skipworktree,
1197                         N_("do not limit pathspecs to sparse entries only")),
1198                OPT_HIDDEN_BOOL(0, "guess", &dwim_new_local_branch,
1199                                N_("second guess 'git checkout no-such-branch'")),
1200                OPT_BOOL(0, "ignore-other-worktrees", &opts.ignore_other_worktrees,
1201                         N_("do not check if another worktree is holding the given ref")),
1202                OPT_END(),
1203        };
1204
1205        memset(&opts, 0, sizeof(opts));
1206        memset(&new, 0, sizeof(new));
1207        opts.overwrite_ignore = 1;
1208        opts.prefix = prefix;
1209
1210        gitmodules_config();
1211        git_config(git_checkout_config, &opts);
1212
1213        opts.track = BRANCH_TRACK_UNSPECIFIED;
1214
1215        argc = parse_options(argc, argv, prefix, options, checkout_usage,
1216                             PARSE_OPT_KEEP_DASHDASH);
1217
1218        opts.new_worktree_mode = getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;
1219
1220        if (conflict_style) {
1221                opts.merge = 1; /* implied */
1222                git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1223        }
1224
1225        if ((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) > 1)
1226                die(_("-b, -B and --orphan are mutually exclusive"));
1227
1228        /*
1229         * From here on, new_branch will contain the branch to be checked out,
1230         * and new_branch_force and new_orphan_branch will tell us which one of
1231         * -b/-B/--orphan is being used.
1232         */
1233        if (opts.new_branch_force)
1234                opts.new_branch = opts.new_branch_force;
1235
1236        if (opts.new_orphan_branch)
1237                opts.new_branch = opts.new_orphan_branch;
1238
1239        /* --track without -b/-B/--orphan should DWIM */
1240        if (opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {
1241                const char *argv0 = argv[0];
1242                if (!argc || !strcmp(argv0, "--"))
1243                        die (_("--track needs a branch name"));
1244                skip_prefix(argv0, "refs/", &argv0);
1245                skip_prefix(argv0, "remotes/", &argv0);
1246                argv0 = strchr(argv0, '/');
1247                if (!argv0 || !argv0[1])
1248                        die (_("Missing branch name; try -b"));
1249                opts.new_branch = argv0 + 1;
1250        }
1251
1252        /*
1253         * Extract branch name from command line arguments, so
1254         * all that is left is pathspecs.
1255         *
1256         * Handle
1257         *
1258         *  1) git checkout <tree> -- [<paths>]
1259         *  2) git checkout -- [<paths>]
1260         *  3) git checkout <something> [<paths>]
1261         *
1262         * including "last branch" syntax and DWIM-ery for names of
1263         * remote branches, erroring out for invalid or ambiguous cases.
1264         */
1265        if (argc) {
1266                unsigned char rev[20];
1267                int dwim_ok =
1268                        !opts.patch_mode &&
1269                        dwim_new_local_branch &&
1270                        opts.track == BRANCH_TRACK_UNSPECIFIED &&
1271                        !opts.new_branch;
1272                int n = parse_branchname_arg(argc, argv, dwim_ok,
1273                                             &new, &opts, rev);
1274                argv += n;
1275                argc -= n;
1276        }
1277
1278        if (argc) {
1279                parse_pathspec(&opts.pathspec, 0,
1280                               opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1281                               prefix, argv);
1282
1283                if (!opts.pathspec.nr)
1284                        die(_("invalid path specification"));
1285
1286                /*
1287                 * Try to give more helpful suggestion.
1288                 * new_branch && argc > 1 will be caught later.
1289                 */
1290                if (opts.new_branch && argc == 1)
1291                        die(_("Cannot update paths and switch to branch '%s' at the same time.\n"
1292                              "Did you intend to checkout '%s' which can not be resolved as commit?"),
1293                            opts.new_branch, argv[0]);
1294
1295                if (opts.force_detach)
1296                        die(_("git checkout: --detach does not take a path argument '%s'"),
1297                            argv[0]);
1298
1299                if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1300                        die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1301                              "checking out of the index."));
1302        }
1303
1304        if (opts.new_branch) {
1305                struct strbuf buf = STRBUF_INIT;
1306
1307                opts.branch_exists =
1308                        validate_new_branchname(opts.new_branch, &buf,
1309                                                !!opts.new_branch_force,
1310                                                !!opts.new_branch_force);
1311
1312                strbuf_release(&buf);
1313        }
1314
1315        if (opts.patch_mode || opts.pathspec.nr)
1316                return checkout_paths(&opts, new.name);
1317        else
1318                return checkout_branch(&opts, &new);
1319}