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