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"wt-status.h" 28#include"xdiff-interface.h" 29 30static const char*const checkout_usage[] = { 31N_("git checkout [<options>] <branch>"), 32N_("git checkout [<options>] [<branch>] -- <file>..."), 33 NULL, 34}; 35 36static const char*const switch_branch_usage[] = { 37N_("git switch [<options>] [<branch>]"), 38 NULL, 39}; 40 41struct checkout_opts { 42int patch_mode; 43int quiet; 44int merge; 45int force; 46int force_detach; 47int implicit_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 dwim_new_local_branch; 56int discard_changes; 57int accept_pathspec; 58int switch_branch_doing_nothing_is_ok; 59int only_merge_on_switching_branches; 60int can_switch_when_in_progress; 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 564static intmerge_working_tree(const struct checkout_opts *opts, 565struct branch_info *old_branch_info, 566struct branch_info *new_branch_info, 567int*writeout_error) 568{ 569int ret; 570struct lock_file lock_file = LOCK_INIT; 571 572hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 573if(read_cache_preload(NULL) <0) 574returnerror(_("index file corrupt")); 575 576resolve_undo_clear(); 577if(opts->discard_changes) { 578 ret =reset_tree(get_commit_tree(new_branch_info->commit), 579 opts,1, writeout_error); 580if(ret) 581return ret; 582}else{ 583struct tree_desc trees[2]; 584struct tree *tree; 585struct unpack_trees_options topts; 586 587memset(&topts,0,sizeof(topts)); 588 topts.head_idx = -1; 589 topts.src_index = &the_index; 590 topts.dst_index = &the_index; 591 592setup_unpack_trees_porcelain(&topts,"checkout"); 593 594refresh_cache(REFRESH_QUIET); 595 596if(unmerged_cache()) { 597error(_("you need to resolve your current index first")); 598return1; 599} 600 601/* 2-way merge to the new branch */ 602 topts.initial_checkout =is_cache_unborn(); 603 topts.update =1; 604 topts.merge =1; 605 topts.gently = opts->merge && old_branch_info->commit; 606 topts.verbose_update = opts->show_progress; 607 topts.fn = twoway_merge; 608if(opts->overwrite_ignore) { 609 topts.dir =xcalloc(1,sizeof(*topts.dir)); 610 topts.dir->flags |= DIR_SHOW_IGNORED; 611setup_standard_excludes(topts.dir); 612} 613 tree =parse_tree_indirect(old_branch_info->commit ? 614&old_branch_info->commit->object.oid : 615 the_hash_algo->empty_tree); 616init_tree_desc(&trees[0], tree->buffer, tree->size); 617 tree =parse_tree_indirect(&new_branch_info->commit->object.oid); 618init_tree_desc(&trees[1], tree->buffer, tree->size); 619 620 ret =unpack_trees(2, trees, &topts); 621clear_unpack_trees_porcelain(&topts); 622if(ret == -1) { 623/* 624 * Unpack couldn't do a trivial merge; either 625 * give up or do a real merge, depending on 626 * whether the merge flag was used. 627 */ 628struct tree *result; 629struct tree *work; 630struct merge_options o; 631if(!opts->merge) 632return1; 633 634/* 635 * Without old_branch_info->commit, the below is the same as 636 * the two-tree unpack we already tried and failed. 637 */ 638if(!old_branch_info->commit) 639return1; 640 641/* Do more real merge */ 642 643/* 644 * We update the index fully, then write the 645 * tree from the index, then merge the new 646 * branch with the current tree, with the old 647 * branch as the base. Then we reset the index 648 * (but not the working tree) to the new 649 * branch, leaving the working tree as the 650 * merged version, but skipping unmerged 651 * entries in the index. 652 */ 653 654add_files_to_cache(NULL, NULL,0); 655/* 656 * NEEDSWORK: carrying over local changes 657 * when branches have different end-of-line 658 * normalization (or clean+smudge rules) is 659 * a pain; plumb in an option to set 660 * o.renormalize? 661 */ 662init_merge_options(&o, the_repository); 663 o.verbosity =0; 664 work =write_tree_from_memory(&o); 665 666 ret =reset_tree(get_commit_tree(new_branch_info->commit), 667 opts,1, 668 writeout_error); 669if(ret) 670return ret; 671 o.ancestor = old_branch_info->name; 672 o.branch1 = new_branch_info->name; 673 o.branch2 ="local"; 674 ret =merge_trees(&o, 675get_commit_tree(new_branch_info->commit), 676 work, 677get_commit_tree(old_branch_info->commit), 678&result); 679if(ret <0) 680exit(128); 681 ret =reset_tree(get_commit_tree(new_branch_info->commit), 682 opts,0, 683 writeout_error); 684strbuf_release(&o.obuf); 685if(ret) 686return ret; 687} 688} 689 690if(!active_cache_tree) 691 active_cache_tree =cache_tree(); 692 693if(!cache_tree_fully_valid(active_cache_tree)) 694cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 695 696if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 697die(_("unable to write new index file")); 698 699if(!opts->discard_changes && !opts->quiet) 700show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 701 702return0; 703} 704 705static voidreport_tracking(struct branch_info *new_branch_info) 706{ 707struct strbuf sb = STRBUF_INIT; 708struct branch *branch =branch_get(new_branch_info->name); 709 710if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 711return; 712fputs(sb.buf, stdout); 713strbuf_release(&sb); 714} 715 716static voidupdate_refs_for_switch(const struct checkout_opts *opts, 717struct branch_info *old_branch_info, 718struct branch_info *new_branch_info) 719{ 720struct strbuf msg = STRBUF_INIT; 721const char*old_desc, *reflog_msg; 722if(opts->new_branch) { 723if(opts->new_orphan_branch) { 724char*refname; 725 726 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 727if(opts->new_branch_log && 728!should_autocreate_reflog(refname)) { 729int ret; 730struct strbuf err = STRBUF_INIT; 731 732 ret =safe_create_reflog(refname,1, &err); 733if(ret) { 734fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 735 opts->new_orphan_branch, err.buf); 736strbuf_release(&err); 737free(refname); 738return; 739} 740strbuf_release(&err); 741} 742free(refname); 743} 744else 745create_branch(the_repository, 746 opts->new_branch, new_branch_info->name, 747 opts->new_branch_force ?1:0, 748 opts->new_branch_force ?1:0, 749 opts->new_branch_log, 750 opts->quiet, 751 opts->track); 752 new_branch_info->name = opts->new_branch; 753setup_branch_path(new_branch_info); 754} 755 756 old_desc = old_branch_info->name; 757if(!old_desc && old_branch_info->commit) 758 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 759 760 reflog_msg =getenv("GIT_REFLOG_ACTION"); 761if(!reflog_msg) 762strbuf_addf(&msg,"checkout: moving from%sto%s", 763 old_desc ? old_desc :"(invalid)", new_branch_info->name); 764else 765strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 766 767if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 768/* Nothing to do. */ 769}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 770update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 771 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 772if(!opts->quiet) { 773if(old_branch_info->path && 774 advice_detached_head && !opts->force_detach) 775detach_advice(new_branch_info->name); 776describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 777} 778}else if(new_branch_info->path) {/* Switch branches. */ 779if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 780die(_("unable to update HEAD")); 781if(!opts->quiet) { 782if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 783if(opts->new_branch_force) 784fprintf(stderr,_("Reset branch '%s'\n"), 785 new_branch_info->name); 786else 787fprintf(stderr,_("Already on '%s'\n"), 788 new_branch_info->name); 789}else if(opts->new_branch) { 790if(opts->branch_exists) 791fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 792else 793fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 794}else{ 795fprintf(stderr,_("Switched to branch '%s'\n"), 796 new_branch_info->name); 797} 798} 799if(old_branch_info->path && old_branch_info->name) { 800if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 801delete_reflog(old_branch_info->path); 802} 803} 804remove_branch_state(the_repository, !opts->quiet); 805strbuf_release(&msg); 806if(!opts->quiet && 807(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 808report_tracking(new_branch_info); 809} 810 811static intadd_pending_uninteresting_ref(const char*refname, 812const struct object_id *oid, 813int flags,void*cb_data) 814{ 815add_pending_oid(cb_data, refname, oid, UNINTERESTING); 816return0; 817} 818 819static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 820{ 821strbuf_addstr(sb," "); 822strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 823strbuf_addch(sb,' '); 824if(!parse_commit(commit)) 825pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 826strbuf_addch(sb,'\n'); 827} 828 829#define ORPHAN_CUTOFF 4 830static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 831{ 832struct commit *c, *last = NULL; 833struct strbuf sb = STRBUF_INIT; 834int lost =0; 835while((c =get_revision(revs)) != NULL) { 836if(lost < ORPHAN_CUTOFF) 837describe_one_orphan(&sb, c); 838 last = c; 839 lost++; 840} 841if(ORPHAN_CUTOFF < lost) { 842int more = lost - ORPHAN_CUTOFF; 843if(more ==1) 844describe_one_orphan(&sb, last); 845else 846strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 847} 848 849fprintf(stderr, 850Q_( 851/* The singular version */ 852"Warning: you are leaving%dcommit behind, " 853"not connected to\n" 854"any of your branches:\n\n" 855"%s\n", 856/* The plural version */ 857"Warning: you are leaving%dcommits behind, " 858"not connected to\n" 859"any of your branches:\n\n" 860"%s\n", 861/* Give ngettext() the count */ 862 lost), 863 lost, 864 sb.buf); 865strbuf_release(&sb); 866 867if(advice_detached_head) 868fprintf(stderr, 869Q_( 870/* The singular version */ 871"If you want to keep it by creating a new branch, " 872"this may be a good time\nto do so with:\n\n" 873" git branch <new-branch-name>%s\n\n", 874/* The plural version */ 875"If you want to keep them by creating a new branch, " 876"this may be a good time\nto do so with:\n\n" 877" git branch <new-branch-name>%s\n\n", 878/* Give ngettext() the count */ 879 lost), 880find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 881} 882 883/* 884 * We are about to leave commit that was at the tip of a detached 885 * HEAD. If it is not reachable from any ref, this is the last chance 886 * for the user to do so without resorting to reflog. 887 */ 888static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 889{ 890struct rev_info revs; 891struct object *object = &old_commit->object; 892 893repo_init_revisions(the_repository, &revs, NULL); 894setup_revisions(0, NULL, &revs, NULL); 895 896 object->flags &= ~UNINTERESTING; 897add_pending_object(&revs, object,oid_to_hex(&object->oid)); 898 899for_each_ref(add_pending_uninteresting_ref, &revs); 900add_pending_oid(&revs,"HEAD", &new_commit->object.oid, UNINTERESTING); 901 902if(prepare_revision_walk(&revs)) 903die(_("internal error in revision walk")); 904if(!(old_commit->object.flags & UNINTERESTING)) 905suggest_reattach(old_commit, &revs); 906else 907describe_detached_head(_("Previous HEAD position was"), old_commit); 908 909/* Clean up objects used, as they will be reused. */ 910clear_commit_marks_all(ALL_REV_FLAGS); 911} 912 913static intswitch_branches(const struct checkout_opts *opts, 914struct branch_info *new_branch_info) 915{ 916int ret =0; 917struct branch_info old_branch_info; 918void*path_to_free; 919struct object_id rev; 920int flag, writeout_error =0; 921int do_merge =1; 922 923trace2_cmd_mode("branch"); 924 925memset(&old_branch_info,0,sizeof(old_branch_info)); 926 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag); 927if(old_branch_info.path) 928 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1); 929if(!(flag & REF_ISSYMREF)) 930 old_branch_info.path = NULL; 931 932if(old_branch_info.path) 933skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name); 934 935if(!new_branch_info->name) { 936 new_branch_info->name ="HEAD"; 937 new_branch_info->commit = old_branch_info.commit; 938if(!new_branch_info->commit) 939die(_("You are on a branch yet to be born")); 940parse_commit_or_die(new_branch_info->commit); 941 942if(opts->only_merge_on_switching_branches) 943 do_merge =0; 944} 945 946if(do_merge) { 947 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error); 948if(ret) { 949free(path_to_free); 950return ret; 951} 952} 953 954if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit) 955orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit); 956 957update_refs_for_switch(opts, &old_branch_info, new_branch_info); 958 959 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1); 960free(path_to_free); 961return ret || writeout_error; 962} 963 964static intgit_checkout_config(const char*var,const char*value,void*cb) 965{ 966if(!strcmp(var,"diff.ignoresubmodules")) { 967struct checkout_opts *opts = cb; 968handle_ignore_submodules_arg(&opts->diff_options, value); 969return0; 970} 971 972if(starts_with(var,"submodule.")) 973returngit_default_submodule_config(var, value, NULL); 974 975returngit_xmerge_config(var, value, NULL); 976} 977 978static voidsetup_new_branch_info_and_source_tree( 979struct branch_info *new_branch_info, 980struct checkout_opts *opts, 981struct object_id *rev, 982const char*arg) 983{ 984struct tree **source_tree = &opts->source_tree; 985struct object_id branch_rev; 986 987 new_branch_info->name = arg; 988setup_branch_path(new_branch_info); 989 990if(!check_refname_format(new_branch_info->path,0) && 991!read_ref(new_branch_info->path, &branch_rev)) 992oidcpy(rev, &branch_rev); 993else 994 new_branch_info->path = NULL;/* not an existing branch */ 995 996 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1); 997if(!new_branch_info->commit) { 998/* not a commit */ 999*source_tree =parse_tree_indirect(rev);1000}else{1001parse_commit_or_die(new_branch_info->commit);1002*source_tree =get_commit_tree(new_branch_info->commit);1003}1004}10051006static intparse_branchname_arg(int argc,const char**argv,1007int dwim_new_local_branch_ok,1008struct branch_info *new_branch_info,1009struct checkout_opts *opts,1010struct object_id *rev,1011int*dwim_remotes_matched)1012{1013const char**new_branch = &opts->new_branch;1014int argcount =0;1015const char*arg;1016int dash_dash_pos;1017int has_dash_dash =0;1018int i;10191020/*1021 * case 1: git checkout <ref> -- [<paths>]1022 *1023 * <ref> must be a valid tree, everything after the '--' must be1024 * a path.1025 *1026 * case 2: git checkout -- [<paths>]1027 *1028 * everything after the '--' must be paths.1029 *1030 * case 3: git checkout <something> [--]1031 *1032 * (a) If <something> is a commit, that is to1033 * switch to the branch or detach HEAD at it. As a special case,1034 * if <something> is A...B (missing A or B means HEAD but you can1035 * omit at most one side), and if there is a unique merge base1036 * between A and B, A...B names that merge base.1037 *1038 * (b) If <something> is _not_ a commit, either "--" is present1039 * or <something> is not a path, no -t or -b was given, and1040 * and there is a tracking branch whose name is <something>1041 * in one and only one remote (or if the branch exists on the1042 * remote named in checkout.defaultRemote), then this is a1043 * short-hand to fork local <something> from that1044 * remote-tracking branch.1045 *1046 * (c) Otherwise, if "--" is present, treat it like case (1).1047 *1048 * (d) Otherwise :1049 * - if it's a reference, treat it like case (1)1050 * - else if it's a path, treat it like case (2)1051 * - else: fail.1052 *1053 * case 4: git checkout <something> <paths>1054 *1055 * The first argument must not be ambiguous.1056 * - If it's *only* a reference, treat it like case (1).1057 * - If it's only a path, treat it like case (2).1058 * - else: fail.1059 *1060 */1061if(!argc)1062return0;10631064if(!opts->accept_pathspec) {1065if(argc >1)1066die(_("only one reference expected"));1067 has_dash_dash =1;/* helps disambiguate */1068}10691070 arg = argv[0];1071 dash_dash_pos = -1;1072for(i =0; i < argc; i++) {1073if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1074 dash_dash_pos = i;1075break;1076}1077}1078if(dash_dash_pos ==0)1079return1;/* case (2) */1080else if(dash_dash_pos ==1)1081 has_dash_dash =1;/* case (3) or (1) */1082else if(dash_dash_pos >=2)1083die(_("only one reference expected,%dgiven."), dash_dash_pos);1084 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;10851086if(!strcmp(arg,"-"))1087 arg ="@{-1}";10881089if(get_oid_mb(arg, rev)) {1090/*1091 * Either case (3) or (4), with <something> not being1092 * a commit, or an attempt to use case (1) with an1093 * invalid ref.1094 *1095 * It's likely an error, but we need to find out if1096 * we should auto-create the branch, case (3).(b).1097 */1098int recover_with_dwim = dwim_new_local_branch_ok;10991100int could_be_checkout_paths = !has_dash_dash &&1101check_filename(opts->prefix, arg);11021103if(!has_dash_dash && !no_wildcard(arg))1104 recover_with_dwim =0;11051106/*1107 * Accept "git checkout foo", "git checkout foo --"1108 * and "git switch foo" as candidates for dwim.1109 */1110if(!(argc ==1&& !has_dash_dash) &&1111!(argc ==2&& has_dash_dash) &&1112 opts->accept_pathspec)1113 recover_with_dwim =0;11141115if(recover_with_dwim) {1116const char*remote =unique_tracking_name(arg, rev,1117 dwim_remotes_matched);1118if(remote) {1119if(could_be_checkout_paths)1120die(_("'%s' could be both a local file and a tracking branch.\n"1121"Please use -- (and optionally --no-guess) to disambiguate"),1122 arg);1123*new_branch = arg;1124 arg = remote;1125/* DWIMmed to create local branch, case (3).(b) */1126}else{1127 recover_with_dwim =0;1128}1129}11301131if(!recover_with_dwim) {1132if(has_dash_dash)1133die(_("invalid reference:%s"), arg);1134return argcount;1135}1136}11371138/* we can't end up being in (2) anymore, eat the argument */1139 argcount++;1140 argv++;1141 argc--;11421143setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);11441145if(!opts->source_tree)/* case (1): want a tree */1146die(_("reference is not a tree:%s"), arg);11471148if(!has_dash_dash) {/* case (3).(d) -> (1) */1149/*1150 * Do not complain the most common case1151 * git checkout branch1152 * even if there happen to be a file called 'branch';1153 * it would be extremely annoying.1154 */1155if(argc)1156verify_non_filename(opts->prefix, arg);1157}else if(opts->accept_pathspec) {1158 argcount++;1159 argv++;1160 argc--;1161}11621163return argcount;1164}11651166static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1167{1168int status;1169struct strbuf branch_ref = STRBUF_INIT;11701171trace2_cmd_mode("unborn");11721173if(!opts->new_branch)1174die(_("You are on a branch yet to be born"));1175strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1176 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1177strbuf_release(&branch_ref);1178if(!opts->quiet)1179fprintf(stderr,_("Switched to a new branch '%s'\n"),1180 opts->new_branch);1181return status;1182}11831184static voiddie_expecting_a_branch(const struct branch_info *branch_info)1185{1186struct object_id oid;1187char*to_free;11881189if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1190const char*ref = to_free;11911192if(skip_prefix(ref,"refs/tags/", &ref))1193die(_("a branch is expected, got tag '%s'"), ref);1194if(skip_prefix(ref,"refs/remotes/", &ref))1195die(_("a branch is expected, got remote branch '%s'"), ref);1196die(_("a branch is expected, got '%s'"), ref);1197}1198if(branch_info->commit)1199die(_("a branch is expected, got commit '%s'"), branch_info->name);1200/*1201 * This case should never happen because we already die() on1202 * non-commit, but just in case.1203 */1204die(_("a branch is expected, got '%s'"), branch_info->name);1205}12061207static voiddie_if_some_operation_in_progress(void)1208{1209struct wt_status_state state;12101211memset(&state,0,sizeof(state));1212wt_status_get_state(the_repository, &state,0);12131214if(state.merge_in_progress)1215die(_("cannot switch branch while merging\n"1216"Consider\"git merge --quit\""1217"or\"git worktree add\"."));1218if(state.am_in_progress)1219die(_("cannot switch branch in the middle of an am session\n"1220"Consider\"git am --quit\""1221"or\"git worktree add\"."));1222if(state.rebase_interactive_in_progress || state.rebase_in_progress)1223die(_("cannot switch branch while rebasing\n"1224"Consider\"git rebase --quit\""1225"or\"git worktree add\"."));1226if(state.cherry_pick_in_progress)1227die(_("cannot switch branch while cherry-picking\n"1228"Consider\"git cherry-pick --quit\""1229"or\"git worktree add\"."));1230if(state.revert_in_progress)1231die(_("cannot switch branch while reverting\n"1232"Consider\"git revert --quit\""1233"or\"git worktree add\"."));1234if(state.bisect_in_progress)1235die(_("cannot switch branch while bisecting\n"1236"Consider\"git bisect reset HEAD\""1237"or\"git worktree add\"."));1238}12391240static intcheckout_branch(struct checkout_opts *opts,1241struct branch_info *new_branch_info)1242{1243if(opts->pathspec.nr)1244die(_("paths cannot be used with switching branches"));12451246if(opts->patch_mode)1247die(_("'%s' cannot be used with switching branches"),1248"--patch");12491250if(!opts->overlay_mode)1251die(_("'%s' cannot be used with switching branches"),1252"--no-overlay");12531254if(opts->writeout_stage)1255die(_("'%s' cannot be used with switching branches"),1256"--ours/--theirs");12571258if(opts->force && opts->merge)1259die(_("'%s' cannot be used with '%s'"),"-f","-m");12601261if(opts->discard_changes && opts->merge)1262die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");12631264if(opts->force_detach && opts->new_branch)1265die(_("'%s' cannot be used with '%s'"),1266"--detach","-b/-B/--orphan");12671268if(opts->new_orphan_branch) {1269if(opts->track != BRANCH_TRACK_UNSPECIFIED)1270die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1271}else if(opts->force_detach) {1272if(opts->track != BRANCH_TRACK_UNSPECIFIED)1273die(_("'%s' cannot be used with '%s'"),"--detach","-t");1274}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1275 opts->track = git_branch_track;12761277if(new_branch_info->name && !new_branch_info->commit)1278die(_("Cannot switch branch to a non-commit '%s'"),1279 new_branch_info->name);12801281if(!opts->switch_branch_doing_nothing_is_ok &&1282!new_branch_info->name &&1283!opts->new_branch &&1284!opts->force_detach)1285die(_("missing branch or commit argument"));12861287if(!opts->implicit_detach &&1288!opts->force_detach &&1289!opts->new_branch &&1290!opts->new_branch_force &&1291 new_branch_info->name &&1292!new_branch_info->path)1293die_expecting_a_branch(new_branch_info);12941295if(!opts->can_switch_when_in_progress)1296die_if_some_operation_in_progress();12971298if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1299!opts->ignore_other_worktrees) {1300int flag;1301char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1302if(head_ref &&1303(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1304die_if_checked_out(new_branch_info->path,1);1305free(head_ref);1306}13071308if(!new_branch_info->commit && opts->new_branch) {1309struct object_id rev;1310int flag;13111312if(!read_ref_full("HEAD",0, &rev, &flag) &&1313(flag & REF_ISSYMREF) &&is_null_oid(&rev))1314returnswitch_unborn_to_new_branch(opts);1315}1316returnswitch_branches(opts, new_branch_info);1317}13181319static struct option *add_common_options(struct checkout_opts *opts,1320struct option *prevopts)1321{1322struct option options[] = {1323OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1324{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1325"checkout","control recursive updating of submodules",1326 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1327OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1328OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1329 PARSE_OPT_NOCOMPLETE),1330OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1331OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1332N_("conflict style (merge or diff3)")),1333OPT_END()1334};1335struct option *newopts =parse_options_concat(prevopts, options);1336free(prevopts);1337return newopts;1338}13391340static struct option *add_common_switch_branch_options(1341struct checkout_opts *opts,struct option *prevopts)1342{1343struct option options[] = {1344OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1345OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1346 BRANCH_TRACK_EXPLICIT),1347OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1348OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1349N_("update ignored files (default)"),1350 PARSE_OPT_NOCOMPLETE),1351OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1352N_("do not check if another worktree is holding the given ref")),1353OPT_END()1354};1355struct option *newopts =parse_options_concat(prevopts, options);1356free(prevopts);1357return newopts;1358}13591360static struct option *add_checkout_path_options(struct checkout_opts *opts,1361struct option *prevopts)1362{1363struct option options[] = {1364OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1365N_("checkout our version for unmerged files"),13662, PARSE_OPT_NONEG),1367OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1368N_("checkout their version for unmerged files"),13693, PARSE_OPT_NONEG),1370OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1371OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1372N_("do not limit pathspecs to sparse entries only")),1373OPT_BOOL(0,"overlay", &opts->overlay_mode,N_("use overlay mode (default)")),1374OPT_END()1375};1376struct option *newopts =parse_options_concat(prevopts, options);1377free(prevopts);1378return newopts;1379}13801381static intcheckout_main(int argc,const char**argv,const char*prefix,1382struct checkout_opts *opts,struct option *options,1383const char*const usagestr[])1384{1385struct branch_info new_branch_info;1386int dwim_remotes_matched =0;13871388memset(&new_branch_info,0,sizeof(new_branch_info));1389 opts->overwrite_ignore =1;1390 opts->prefix = prefix;1391 opts->show_progress = -1;1392 opts->overlay_mode = -1;13931394git_config(git_checkout_config, opts);13951396 opts->track = BRANCH_TRACK_UNSPECIFIED;13971398 argc =parse_options(argc, argv, prefix, options, usagestr,1399 PARSE_OPT_KEEP_DASHDASH);14001401if(opts->show_progress <0) {1402if(opts->quiet)1403 opts->show_progress =0;1404else1405 opts->show_progress =isatty(2);1406}14071408if(opts->conflict_style) {1409 opts->merge =1;/* implied */1410git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1411}1412if(opts->force)1413 opts->discard_changes =1;14141415if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1416die(_("-b, -B and --orphan are mutually exclusive"));14171418if(opts->overlay_mode ==1&& opts->patch_mode)1419die(_("-p and --overlay are mutually exclusive"));14201421/*1422 * From here on, new_branch will contain the branch to be checked out,1423 * and new_branch_force and new_orphan_branch will tell us which one of1424 * -b/-B/--orphan is being used.1425 */1426if(opts->new_branch_force)1427 opts->new_branch = opts->new_branch_force;14281429if(opts->new_orphan_branch)1430 opts->new_branch = opts->new_orphan_branch;14311432/* --track without -b/-B/--orphan should DWIM */1433if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1434const char*argv0 = argv[0];1435if(!argc || !strcmp(argv0,"--"))1436die(_("--track needs a branch name"));1437skip_prefix(argv0,"refs/", &argv0);1438skip_prefix(argv0,"remotes/", &argv0);1439 argv0 =strchr(argv0,'/');1440if(!argv0 || !argv0[1])1441die(_("missing branch name; try -b"));1442 opts->new_branch = argv0 +1;1443}14441445/*1446 * Extract branch name from command line arguments, so1447 * all that is left is pathspecs.1448 *1449 * Handle1450 *1451 * 1) git checkout <tree> -- [<paths>]1452 * 2) git checkout -- [<paths>]1453 * 3) git checkout <something> [<paths>]1454 *1455 * including "last branch" syntax and DWIM-ery for names of1456 * remote branches, erroring out for invalid or ambiguous cases.1457 */1458if(argc) {1459struct object_id rev;1460int dwim_ok =1461!opts->patch_mode &&1462 opts->dwim_new_local_branch &&1463 opts->track == BRANCH_TRACK_UNSPECIFIED &&1464!opts->new_branch;1465int n =parse_branchname_arg(argc, argv, dwim_ok,1466&new_branch_info, opts, &rev,1467&dwim_remotes_matched);1468 argv += n;1469 argc -= n;1470}14711472if(argc) {1473parse_pathspec(&opts->pathspec,0,1474 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1475 prefix, argv);14761477if(!opts->pathspec.nr)1478die(_("invalid path specification"));14791480/*1481 * Try to give more helpful suggestion.1482 * new_branch && argc > 1 will be caught later.1483 */1484if(opts->new_branch && argc ==1)1485die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1486 argv[0], opts->new_branch);14871488if(opts->force_detach)1489die(_("git checkout: --detach does not take a path argument '%s'"),1490 argv[0]);14911492if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1493die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1494"checking out of the index."));1495}14961497if(opts->new_branch) {1498struct strbuf buf = STRBUF_INIT;14991500if(opts->new_branch_force)1501 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1502else1503 opts->branch_exists =1504validate_new_branchname(opts->new_branch, &buf,0);1505strbuf_release(&buf);1506}15071508UNLEAK(opts);1509if(opts->patch_mode || opts->pathspec.nr) {1510int ret =checkout_paths(opts, new_branch_info.name);1511if(ret && dwim_remotes_matched >1&&1512 advice_checkout_ambiguous_remote_branch_name)1513advise(_("'%s' matched more than one remote tracking branch.\n"1514"We found%dremotes with a reference that matched. So we fell back\n"1515"on trying to resolve the argument as a path, but failed there too!\n"1516"\n"1517"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1518"you can do so by fully qualifying the name with the --track option:\n"1519"\n"1520" git checkout --track origin/<name>\n"1521"\n"1522"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1523"one remote, e.g. the 'origin' remote, consider setting\n"1524"checkout.defaultRemote=origin in your config."),1525 argv[0],1526 dwim_remotes_matched);1527return ret;1528}else{1529returncheckout_branch(opts, &new_branch_info);1530}1531}15321533intcmd_checkout(int argc,const char**argv,const char*prefix)1534{1535struct checkout_opts opts;1536struct option *options;1537struct option checkout_options[] = {1538OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1539N_("create and checkout a new branch")),1540OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1541N_("create/reset and checkout a branch")),1542OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1543OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1544N_("second guess 'git checkout <no-such-branch>' (default)")),1545OPT_END()1546};1547int ret;15481549memset(&opts,0,sizeof(opts));1550 opts.dwim_new_local_branch =1;1551 opts.switch_branch_doing_nothing_is_ok =1;1552 opts.only_merge_on_switching_branches =0;1553 opts.accept_pathspec =1;1554 opts.implicit_detach =1;1555 opts.can_switch_when_in_progress =1;15561557 options =parse_options_dup(checkout_options);1558 options =add_common_options(&opts, options);1559 options =add_common_switch_branch_options(&opts, options);1560 options =add_checkout_path_options(&opts, options);15611562 ret =checkout_main(argc, argv, prefix, &opts,1563 options, checkout_usage);1564FREE_AND_NULL(options);1565return ret;1566}15671568intcmd_switch(int argc,const char**argv,const char*prefix)1569{1570struct checkout_opts opts;1571struct option *options = NULL;1572struct option switch_options[] = {1573OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1574N_("create and switch to a new branch")),1575OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1576N_("create/reset and switch to a branch")),1577OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1578N_("second guess 'git switch <no-such-branch>'")),1579OPT_BOOL(0,"discard-changes", &opts.discard_changes,1580N_("throw away local modifications")),1581OPT_END()1582};1583int ret;15841585memset(&opts,0,sizeof(opts));1586 opts.dwim_new_local_branch =1;1587 opts.accept_pathspec =0;1588 opts.switch_branch_doing_nothing_is_ok =0;1589 opts.only_merge_on_switching_branches =1;1590 opts.implicit_detach =0;1591 opts.can_switch_when_in_progress =0;15921593 options =parse_options_dup(switch_options);1594 options =add_common_options(&opts, options);1595 options =add_common_switch_branch_options(&opts, options);15961597 ret =checkout_main(argc, argv, prefix, &opts,1598 options, switch_branch_usage);1599FREE_AND_NULL(options);1600return ret;1601}