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