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