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