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