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