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