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