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