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