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; 69int checkout_index; 70int checkout_worktree; 71const char*ignore_unmerged_opt; 72int ignore_unmerged; 73 74const char*new_branch; 75const char*new_branch_force; 76const char*new_orphan_branch; 77int new_branch_log; 78enum branch_track track; 79struct diff_options diff_options; 80char*conflict_style; 81 82int branch_exists; 83const char*prefix; 84struct pathspec pathspec; 85const char*from_treeish; 86struct tree *source_tree; 87}; 88 89static intpost_checkout_hook(struct commit *old_commit,struct commit *new_commit, 90int changed) 91{ 92returnrun_hook_le(NULL,"post-checkout", 93oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid), 94oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid), 95 changed ?"1":"0", NULL); 96/* "new_commit" can be NULL when checking out from the index before 97 a commit exists. */ 98 99} 100 101static intupdate_some(const struct object_id *oid,struct strbuf *base, 102const char*pathname,unsigned mode,int stage,void*context) 103{ 104int len; 105struct cache_entry *ce; 106int pos; 107 108if(S_ISDIR(mode)) 109return READ_TREE_RECURSIVE; 110 111 len = base->len +strlen(pathname); 112 ce =make_empty_cache_entry(&the_index, len); 113oidcpy(&ce->oid, oid); 114memcpy(ce->name, base->buf, base->len); 115memcpy(ce->name + base->len, pathname, len - base->len); 116 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 117 ce->ce_namelen = len; 118 ce->ce_mode =create_ce_mode(mode); 119 120/* 121 * If the entry is the same as the current index, we can leave the old 122 * entry in place. Whether it is UPTODATE or not, checkout_entry will 123 * do the right thing. 124 */ 125 pos =cache_name_pos(ce->name, ce->ce_namelen); 126if(pos >=0) { 127struct cache_entry *old = active_cache[pos]; 128if(ce->ce_mode == old->ce_mode && 129!ce_intent_to_add(old) && 130oideq(&ce->oid, &old->oid)) { 131 old->ce_flags |= CE_UPDATE; 132discard_cache_entry(ce); 133return0; 134} 135} 136 137add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 138return0; 139} 140 141static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 142{ 143read_tree_recursive(the_repository, tree,"",0,0, 144 pathspec, update_some, NULL); 145 146/* update the index with the given tree's info 147 * for all args, expanding wildcards, and exit 148 * with any non-zero return code. 149 */ 150return0; 151} 152 153static intskip_same_name(const struct cache_entry *ce,int pos) 154{ 155while(++pos < active_nr && 156!strcmp(active_cache[pos]->name, ce->name)) 157;/* skip */ 158return pos; 159} 160 161static intcheck_stage(int stage,const struct cache_entry *ce,int pos, 162int overlay_mode) 163{ 164while(pos < active_nr && 165!strcmp(active_cache[pos]->name, ce->name)) { 166if(ce_stage(active_cache[pos]) == stage) 167return0; 168 pos++; 169} 170if(!overlay_mode) 171return0; 172if(stage ==2) 173returnerror(_("path '%s' does not have our version"), ce->name); 174else 175returnerror(_("path '%s' does not have their version"), ce->name); 176} 177 178static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 179{ 180unsigned seen =0; 181const char*name = ce->name; 182 183while(pos < active_nr) { 184 ce = active_cache[pos]; 185if(strcmp(name, ce->name)) 186break; 187 seen |= (1<<ce_stage(ce)); 188 pos++; 189} 190if((stages & seen) != stages) 191returnerror(_("path '%s' does not have all necessary versions"), 192 name); 193return0; 194} 195 196static intcheckout_stage(int stage,const struct cache_entry *ce,int pos, 197const struct checkout *state,int*nr_checkouts, 198int overlay_mode) 199{ 200while(pos < active_nr && 201!strcmp(active_cache[pos]->name, ce->name)) { 202if(ce_stage(active_cache[pos]) == stage) 203returncheckout_entry(active_cache[pos], state, 204 NULL, nr_checkouts); 205 pos++; 206} 207if(!overlay_mode) { 208unlink_entry(ce); 209return0; 210} 211if(stage ==2) 212returnerror(_("path '%s' does not have our version"), ce->name); 213else 214returnerror(_("path '%s' does not have their version"), ce->name); 215} 216 217static intcheckout_merged(int pos,const struct checkout *state,int*nr_checkouts) 218{ 219struct cache_entry *ce = active_cache[pos]; 220const char*path = ce->name; 221 mmfile_t ancestor, ours, theirs; 222int status; 223struct object_id oid; 224 mmbuffer_t result_buf; 225struct object_id threeway[3]; 226unsigned mode =0; 227 228memset(threeway,0,sizeof(threeway)); 229while(pos < active_nr) { 230int stage; 231 stage =ce_stage(ce); 232if(!stage ||strcmp(path, ce->name)) 233break; 234oidcpy(&threeway[stage -1], &ce->oid); 235if(stage ==2) 236 mode =create_ce_mode(ce->ce_mode); 237 pos++; 238 ce = active_cache[pos]; 239} 240if(is_null_oid(&threeway[1]) ||is_null_oid(&threeway[2])) 241returnerror(_("path '%s' does not have necessary versions"), path); 242 243read_mmblob(&ancestor, &threeway[0]); 244read_mmblob(&ours, &threeway[1]); 245read_mmblob(&theirs, &threeway[2]); 246 247/* 248 * NEEDSWORK: re-create conflicts from merges with 249 * merge.renormalize set, too 250 */ 251 status =ll_merge(&result_buf, path, &ancestor,"base", 252&ours,"ours", &theirs,"theirs", 253 state->istate, NULL); 254free(ancestor.ptr); 255free(ours.ptr); 256free(theirs.ptr); 257if(status <0|| !result_buf.ptr) { 258free(result_buf.ptr); 259returnerror(_("path '%s': cannot merge"), path); 260} 261 262/* 263 * NEEDSWORK: 264 * There is absolutely no reason to write this as a blob object 265 * and create a phony cache entry. This hack is primarily to get 266 * to the write_entry() machinery that massages the contents to 267 * work-tree format and writes out which only allows it for a 268 * cache entry. The code in write_entry() needs to be refactored 269 * to allow us to feed a <buffer, size, mode> instead of a cache 270 * entry. Such a refactoring would help merge_recursive as well 271 * (it also writes the merge result to the object database even 272 * when it may contain conflicts). 273 */ 274if(write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid)) 275die(_("Unable to add merge result for '%s'"), path); 276free(result_buf.ptr); 277 ce =make_transient_cache_entry(mode, &oid, path,2); 278if(!ce) 279die(_("make_cache_entry failed for path '%s'"), path); 280 status =checkout_entry(ce, state, NULL, nr_checkouts); 281discard_cache_entry(ce); 282return status; 283} 284 285static voidmark_ce_for_checkout_overlay(struct cache_entry *ce, 286char*ps_matched, 287const struct checkout_opts *opts) 288{ 289 ce->ce_flags &= ~CE_MATCHED; 290if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 291return; 292if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 293/* 294 * "git checkout tree-ish -- path", but this entry 295 * is in the original index but is not in tree-ish 296 * or does not match the pathspec; it will not be 297 * checked out to the working tree. We will not do 298 * anything to this entry at all. 299 */ 300return; 301/* 302 * Either this entry came from the tree-ish we are 303 * checking the paths out of, or we are checking out 304 * of the index. 305 * 306 * If it comes from the tree-ish, we already know it 307 * matches the pathspec and could just stamp 308 * CE_MATCHED to it from update_some(). But we still 309 * need ps_matched and read_tree_recursive (and 310 * eventually tree_entry_interesting) cannot fill 311 * ps_matched yet. Once it can, we can avoid calling 312 * match_pathspec() for _all_ entries when 313 * opts->source_tree != NULL. 314 */ 315if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) 316 ce->ce_flags |= CE_MATCHED; 317} 318 319static voidmark_ce_for_checkout_no_overlay(struct cache_entry *ce, 320char*ps_matched, 321const struct checkout_opts *opts) 322{ 323 ce->ce_flags &= ~CE_MATCHED; 324if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 325return; 326if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) { 327 ce->ce_flags |= CE_MATCHED; 328if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 329/* 330 * In overlay mode, but the path is not in 331 * tree-ish, which means we should remove it 332 * from the index and the working tree. 333 */ 334 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE; 335} 336} 337 338static intcheckout_worktree(const struct checkout_opts *opts) 339{ 340struct checkout state = CHECKOUT_INIT; 341int nr_checkouts =0, nr_unmerged =0; 342int errs =0; 343int pos; 344 345 state.force =1; 346 state.refresh_cache =1; 347 state.istate = &the_index; 348 349enable_delayed_checkout(&state); 350for(pos =0; pos < active_nr; pos++) { 351struct cache_entry *ce = active_cache[pos]; 352if(ce->ce_flags & CE_MATCHED) { 353if(!ce_stage(ce)) { 354 errs |=checkout_entry(ce, &state, 355 NULL, &nr_checkouts); 356continue; 357} 358if(opts->writeout_stage) 359 errs |=checkout_stage(opts->writeout_stage, 360 ce, pos, 361&state, 362&nr_checkouts, opts->overlay_mode); 363else if(opts->merge) 364 errs |=checkout_merged(pos, &state, 365&nr_unmerged); 366 pos =skip_same_name(ce, pos) -1; 367} 368} 369remove_marked_cache_entries(&the_index,1); 370remove_scheduled_dirs(); 371 errs |=finish_delayed_checkout(&state, &nr_checkouts); 372 373if(opts->count_checkout_paths) { 374if(nr_unmerged) 375fprintf_ln(stderr,Q_("Recreated%dmerge conflict", 376"Recreated%dmerge conflicts", 377 nr_unmerged), 378 nr_unmerged); 379if(opts->source_tree) 380fprintf_ln(stderr,Q_("Updated%dpath from%s", 381"Updated%dpaths from%s", 382 nr_checkouts), 383 nr_checkouts, 384find_unique_abbrev(&opts->source_tree->object.oid, 385 DEFAULT_ABBREV)); 386else if(!nr_unmerged || nr_checkouts) 387fprintf_ln(stderr,Q_("Updated%dpath from the index", 388"Updated%dpaths from the index", 389 nr_checkouts), 390 nr_checkouts); 391} 392 393return errs; 394} 395 396static intcheckout_paths(const struct checkout_opts *opts, 397const char*revision) 398{ 399int pos; 400static char*ps_matched; 401struct object_id rev; 402struct commit *head; 403int errs =0; 404struct lock_file lock_file = LOCK_INIT; 405int checkout_index; 406 407trace2_cmd_mode(opts->patch_mode ?"patch":"path"); 408 409if(opts->track != BRANCH_TRACK_UNSPECIFIED) 410die(_("'%s' cannot be used with updating paths"),"--track"); 411 412if(opts->new_branch_log) 413die(_("'%s' cannot be used with updating paths"),"-l"); 414 415if(opts->ignore_unmerged && opts->patch_mode) 416die(_("'%s' cannot be used with updating paths"), 417 opts->ignore_unmerged_opt); 418 419if(opts->force_detach) 420die(_("'%s' cannot be used with updating paths"),"--detach"); 421 422if(opts->merge && opts->patch_mode) 423die(_("'%s' cannot be used with%s"),"--merge","--patch"); 424 425if(opts->ignore_unmerged && opts->merge) 426die(_("'%s' cannot be used with%s"), 427 opts->ignore_unmerged_opt,"-m"); 428 429if(opts->new_branch) 430die(_("Cannot update paths and switch to branch '%s' at the same time."), 431 opts->new_branch); 432 433if(!opts->checkout_worktree && !opts->checkout_index) 434die(_("neither '%s' or '%s' is specified"), 435"--staged","--worktree"); 436 437if(!opts->checkout_worktree && !opts->from_treeish) 438die(_("'%s' must be used when '%s' is not specified"), 439"--worktree","--source"); 440 441if(opts->checkout_index && !opts->checkout_worktree && 442 opts->writeout_stage) 443die(_("'%s' or '%s' cannot be used with%s"), 444"--ours","--theirs","--staged"); 445 446if(opts->checkout_index && !opts->checkout_worktree && 447 opts->merge) 448die(_("'%s' or '%s' cannot be used with%s"), 449"--merge","--conflict","--staged"); 450 451if(opts->patch_mode) { 452const char*patch_mode; 453 454if(opts->checkout_index && opts->checkout_worktree) 455 patch_mode ="--patch=checkout"; 456else if(opts->checkout_index && !opts->checkout_worktree) 457 patch_mode ="--patch=reset"; 458else if(!opts->checkout_index && opts->checkout_worktree) 459 patch_mode ="--patch=worktree"; 460else 461BUG("either flag must have been set, worktree=%d, index=%d", 462 opts->checkout_worktree, opts->checkout_index); 463returnrun_add_interactive(revision, patch_mode, &opts->pathspec); 464} 465 466repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 467if(read_cache_preload(&opts->pathspec) <0) 468returnerror(_("index file corrupt")); 469 470if(opts->source_tree) 471read_tree_some(opts->source_tree, &opts->pathspec); 472 473 ps_matched =xcalloc(opts->pathspec.nr,1); 474 475/* 476 * Make sure all pathspecs participated in locating the paths 477 * to be checked out. 478 */ 479for(pos =0; pos < active_nr; pos++) 480if(opts->overlay_mode) 481mark_ce_for_checkout_overlay(active_cache[pos], 482 ps_matched, 483 opts); 484else 485mark_ce_for_checkout_no_overlay(active_cache[pos], 486 ps_matched, 487 opts); 488 489if(report_path_error(ps_matched, &opts->pathspec)) { 490free(ps_matched); 491return1; 492} 493free(ps_matched); 494 495/* "checkout -m path" to recreate conflicted state */ 496if(opts->merge) 497unmerge_marked_index(&the_index); 498 499/* Any unmerged paths? */ 500for(pos =0; pos < active_nr; pos++) { 501const struct cache_entry *ce = active_cache[pos]; 502if(ce->ce_flags & CE_MATCHED) { 503if(!ce_stage(ce)) 504continue; 505if(opts->ignore_unmerged) { 506if(!opts->quiet) 507warning(_("path '%s' is unmerged"), ce->name); 508}else if(opts->writeout_stage) { 509 errs |=check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 510}else if(opts->merge) { 511 errs |=check_stages((1<<2) | (1<<3), ce, pos); 512}else{ 513 errs =1; 514error(_("path '%s' is unmerged"), ce->name); 515} 516 pos =skip_same_name(ce, pos) -1; 517} 518} 519if(errs) 520return1; 521 522/* Now we are committed to check them out */ 523if(opts->checkout_worktree) 524 errs |=checkout_worktree(opts); 525 526/* 527 * Allow updating the index when checking out from the index. 528 * This is to save new stat info. 529 */ 530if(opts->checkout_worktree && !opts->checkout_index && !opts->source_tree) 531 checkout_index =1; 532else 533 checkout_index = opts->checkout_index; 534 535if(checkout_index) { 536if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 537die(_("unable to write new index file")); 538}else{ 539/* 540 * NEEDSWORK: if --worktree is not specified, we 541 * should save stat info of checked out files in the 542 * index to avoid the next (potentially costly) 543 * refresh. But it's a bit tricker to do... 544 */ 545rollback_lock_file(&lock_file); 546} 547 548read_ref_full("HEAD",0, &rev, NULL); 549 head =lookup_commit_reference_gently(the_repository, &rev,1); 550 551 errs |=post_checkout_hook(head, head,0); 552return errs; 553} 554 555static voidshow_local_changes(struct object *head, 556const struct diff_options *opts) 557{ 558struct rev_info rev; 559/* I think we want full paths, even if we're in a subdirectory. */ 560repo_init_revisions(the_repository, &rev, NULL); 561 rev.diffopt.flags = opts->flags; 562 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 563diff_setup_done(&rev.diffopt); 564add_pending_object(&rev, head, NULL); 565run_diff_index(&rev,0); 566} 567 568static voiddescribe_detached_head(const char*msg,struct commit *commit) 569{ 570struct strbuf sb = STRBUF_INIT; 571 572if(!parse_commit(commit)) 573pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 574if(print_sha1_ellipsis()) { 575fprintf(stderr,"%s %s...%s\n", msg, 576find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 577}else{ 578fprintf(stderr,"%s %s %s\n", msg, 579find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 580} 581strbuf_release(&sb); 582} 583 584static intreset_tree(struct tree *tree,const struct checkout_opts *o, 585int worktree,int*writeout_error) 586{ 587struct unpack_trees_options opts; 588struct tree_desc tree_desc; 589 590memset(&opts,0,sizeof(opts)); 591 opts.head_idx = -1; 592 opts.update = worktree; 593 opts.skip_unmerged = !worktree; 594 opts.reset =1; 595 opts.merge =1; 596 opts.fn = oneway_merge; 597 opts.verbose_update = o->show_progress; 598 opts.src_index = &the_index; 599 opts.dst_index = &the_index; 600parse_tree(tree); 601init_tree_desc(&tree_desc, tree->buffer, tree->size); 602switch(unpack_trees(1, &tree_desc, &opts)) { 603case-2: 604*writeout_error =1; 605/* 606 * We return 0 nevertheless, as the index is all right 607 * and more importantly we have made best efforts to 608 * update paths in the work tree, and we cannot revert 609 * them. 610 */ 611/* fallthrough */ 612case0: 613return0; 614default: 615return128; 616} 617} 618 619struct branch_info { 620const char*name;/* The short name used */ 621const char*path;/* The full name of a real branch */ 622struct commit *commit;/* The named commit */ 623/* 624 * if not null the branch is detached because it's already 625 * checked out in this checkout 626 */ 627char*checkout; 628}; 629 630static voidsetup_branch_path(struct branch_info *branch) 631{ 632struct strbuf buf = STRBUF_INIT; 633 634strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 635if(strcmp(buf.buf, branch->name)) 636 branch->name =xstrdup(buf.buf); 637strbuf_splice(&buf,0,0,"refs/heads/",11); 638 branch->path =strbuf_detach(&buf, NULL); 639} 640 641static intmerge_working_tree(const struct checkout_opts *opts, 642struct branch_info *old_branch_info, 643struct branch_info *new_branch_info, 644int*writeout_error) 645{ 646int ret; 647struct lock_file lock_file = LOCK_INIT; 648struct tree *new_tree; 649 650hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 651if(read_cache_preload(NULL) <0) 652returnerror(_("index file corrupt")); 653 654resolve_undo_clear(); 655if(opts->new_orphan_branch && opts->orphan_from_empty_tree) { 656if(new_branch_info->commit) 657BUG("'switch --orphan' should never accept a commit as starting point"); 658 new_tree =parse_tree_indirect(the_hash_algo->empty_tree); 659}else 660 new_tree =get_commit_tree(new_branch_info->commit); 661if(opts->discard_changes) { 662 ret =reset_tree(new_tree, opts,1, writeout_error); 663if(ret) 664return ret; 665}else{ 666struct tree_desc trees[2]; 667struct tree *tree; 668struct unpack_trees_options topts; 669 670memset(&topts,0,sizeof(topts)); 671 topts.head_idx = -1; 672 topts.src_index = &the_index; 673 topts.dst_index = &the_index; 674 675setup_unpack_trees_porcelain(&topts,"checkout"); 676 677refresh_cache(REFRESH_QUIET); 678 679if(unmerged_cache()) { 680error(_("you need to resolve your current index first")); 681return1; 682} 683 684/* 2-way merge to the new branch */ 685 topts.initial_checkout =is_cache_unborn(); 686 topts.update =1; 687 topts.merge =1; 688 topts.quiet = opts->merge && old_branch_info->commit; 689 topts.verbose_update = opts->show_progress; 690 topts.fn = twoway_merge; 691if(opts->overwrite_ignore) { 692 topts.dir =xcalloc(1,sizeof(*topts.dir)); 693 topts.dir->flags |= DIR_SHOW_IGNORED; 694setup_standard_excludes(topts.dir); 695} 696 tree =parse_tree_indirect(old_branch_info->commit ? 697&old_branch_info->commit->object.oid : 698 the_hash_algo->empty_tree); 699init_tree_desc(&trees[0], tree->buffer, tree->size); 700parse_tree(new_tree); 701 tree = new_tree; 702init_tree_desc(&trees[1], tree->buffer, tree->size); 703 704 ret =unpack_trees(2, trees, &topts); 705clear_unpack_trees_porcelain(&topts); 706if(ret == -1) { 707/* 708 * Unpack couldn't do a trivial merge; either 709 * give up or do a real merge, depending on 710 * whether the merge flag was used. 711 */ 712struct tree *result; 713struct tree *work; 714struct tree *old_tree; 715struct merge_options o; 716struct strbuf sb = STRBUF_INIT; 717 718if(!opts->merge) 719return1; 720 721/* 722 * Without old_branch_info->commit, the below is the same as 723 * the two-tree unpack we already tried and failed. 724 */ 725if(!old_branch_info->commit) 726return1; 727 old_tree =get_commit_tree(old_branch_info->commit); 728 729if(repo_index_has_changes(the_repository, old_tree, &sb)) 730die(_("cannot continue with staged changes in " 731"the following files:\n%s"), sb.buf); 732strbuf_release(&sb); 733 734/* Do more real merge */ 735 736/* 737 * We update the index fully, then write the 738 * tree from the index, then merge the new 739 * branch with the current tree, with the old 740 * branch as the base. Then we reset the index 741 * (but not the working tree) to the new 742 * branch, leaving the working tree as the 743 * merged version, but skipping unmerged 744 * entries in the index. 745 */ 746 747add_files_to_cache(NULL, NULL,0); 748/* 749 * NEEDSWORK: carrying over local changes 750 * when branches have different end-of-line 751 * normalization (or clean+smudge rules) is 752 * a pain; plumb in an option to set 753 * o.renormalize? 754 */ 755init_merge_options(&o, the_repository); 756 o.verbosity =0; 757 work =write_tree_from_memory(&o); 758 759 ret =reset_tree(new_tree, 760 opts,1, 761 writeout_error); 762if(ret) 763return ret; 764 o.ancestor = old_branch_info->name; 765 o.branch1 = new_branch_info->name; 766 o.branch2 ="local"; 767 ret =merge_trees(&o, 768 new_tree, 769 work, 770 old_tree, 771&result); 772if(ret <0) 773exit(128); 774 ret =reset_tree(new_tree, 775 opts,0, 776 writeout_error); 777strbuf_release(&o.obuf); 778if(ret) 779return ret; 780} 781} 782 783if(!active_cache_tree) 784 active_cache_tree =cache_tree(); 785 786if(!cache_tree_fully_valid(active_cache_tree)) 787cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 788 789if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 790die(_("unable to write new index file")); 791 792if(!opts->discard_changes && !opts->quiet && new_branch_info->commit) 793show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 794 795return0; 796} 797 798static voidreport_tracking(struct branch_info *new_branch_info) 799{ 800struct strbuf sb = STRBUF_INIT; 801struct branch *branch =branch_get(new_branch_info->name); 802 803if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 804return; 805fputs(sb.buf, stdout); 806strbuf_release(&sb); 807} 808 809static voidupdate_refs_for_switch(const struct checkout_opts *opts, 810struct branch_info *old_branch_info, 811struct branch_info *new_branch_info) 812{ 813struct strbuf msg = STRBUF_INIT; 814const char*old_desc, *reflog_msg; 815if(opts->new_branch) { 816if(opts->new_orphan_branch) { 817char*refname; 818 819 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 820if(opts->new_branch_log && 821!should_autocreate_reflog(refname)) { 822int ret; 823struct strbuf err = STRBUF_INIT; 824 825 ret =safe_create_reflog(refname,1, &err); 826if(ret) { 827fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 828 opts->new_orphan_branch, err.buf); 829strbuf_release(&err); 830free(refname); 831return; 832} 833strbuf_release(&err); 834} 835free(refname); 836} 837else 838create_branch(the_repository, 839 opts->new_branch, new_branch_info->name, 840 opts->new_branch_force ?1:0, 841 opts->new_branch_force ?1:0, 842 opts->new_branch_log, 843 opts->quiet, 844 opts->track); 845 new_branch_info->name = opts->new_branch; 846setup_branch_path(new_branch_info); 847} 848 849 old_desc = old_branch_info->name; 850if(!old_desc && old_branch_info->commit) 851 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 852 853 reflog_msg =getenv("GIT_REFLOG_ACTION"); 854if(!reflog_msg) 855strbuf_addf(&msg,"checkout: moving from%sto%s", 856 old_desc ? old_desc :"(invalid)", new_branch_info->name); 857else 858strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 859 860if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 861/* Nothing to do. */ 862}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 863update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 864 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 865if(!opts->quiet) { 866if(old_branch_info->path && 867 advice_detached_head && !opts->force_detach) 868detach_advice(new_branch_info->name); 869describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 870} 871}else if(new_branch_info->path) {/* Switch branches. */ 872if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 873die(_("unable to update HEAD")); 874if(!opts->quiet) { 875if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 876if(opts->new_branch_force) 877fprintf(stderr,_("Reset branch '%s'\n"), 878 new_branch_info->name); 879else 880fprintf(stderr,_("Already on '%s'\n"), 881 new_branch_info->name); 882}else if(opts->new_branch) { 883if(opts->branch_exists) 884fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 885else 886fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 887}else{ 888fprintf(stderr,_("Switched to branch '%s'\n"), 889 new_branch_info->name); 890} 891} 892if(old_branch_info->path && old_branch_info->name) { 893if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 894delete_reflog(old_branch_info->path); 895} 896} 897remove_branch_state(the_repository, !opts->quiet); 898strbuf_release(&msg); 899if(!opts->quiet && 900(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 901report_tracking(new_branch_info); 902} 903 904static intadd_pending_uninteresting_ref(const char*refname, 905const struct object_id *oid, 906int flags,void*cb_data) 907{ 908add_pending_oid(cb_data, refname, oid, UNINTERESTING); 909return0; 910} 911 912static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 913{ 914strbuf_addstr(sb," "); 915strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 916strbuf_addch(sb,' '); 917if(!parse_commit(commit)) 918pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 919strbuf_addch(sb,'\n'); 920} 921 922#define ORPHAN_CUTOFF 4 923static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 924{ 925struct commit *c, *last = NULL; 926struct strbuf sb = STRBUF_INIT; 927int lost =0; 928while((c =get_revision(revs)) != NULL) { 929if(lost < ORPHAN_CUTOFF) 930describe_one_orphan(&sb, c); 931 last = c; 932 lost++; 933} 934if(ORPHAN_CUTOFF < lost) { 935int more = lost - ORPHAN_CUTOFF; 936if(more ==1) 937describe_one_orphan(&sb, last); 938else 939strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 940} 941 942fprintf(stderr, 943Q_( 944/* The singular version */ 945"Warning: you are leaving%dcommit behind, " 946"not connected to\n" 947"any of your branches:\n\n" 948"%s\n", 949/* The plural version */ 950"Warning: you are leaving%dcommits behind, " 951"not connected to\n" 952"any of your branches:\n\n" 953"%s\n", 954/* Give ngettext() the count */ 955 lost), 956 lost, 957 sb.buf); 958strbuf_release(&sb); 959 960if(advice_detached_head) 961fprintf(stderr, 962Q_( 963/* The singular version */ 964"If you want to keep it by creating a new branch, " 965"this may be a good time\nto do so with:\n\n" 966" git branch <new-branch-name>%s\n\n", 967/* The plural version */ 968"If you want to keep them by creating a new branch, " 969"this may be a good time\nto do so with:\n\n" 970" git branch <new-branch-name>%s\n\n", 971/* Give ngettext() the count */ 972 lost), 973find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 974} 975 976/* 977 * We are about to leave commit that was at the tip of a detached 978 * HEAD. If it is not reachable from any ref, this is the last chance 979 * for the user to do so without resorting to reflog. 980 */ 981static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 982{ 983struct rev_info revs; 984struct object *object = &old_commit->object; 985 986repo_init_revisions(the_repository, &revs, NULL); 987setup_revisions(0, NULL, &revs, NULL); 988 989 object->flags &= ~UNINTERESTING; 990add_pending_object(&revs, object,oid_to_hex(&object->oid)); 991 992for_each_ref(add_pending_uninteresting_ref, &revs); 993if(new_commit) 994add_pending_oid(&revs,"HEAD", 995&new_commit->object.oid, 996 UNINTERESTING); 997 998if(prepare_revision_walk(&revs)) 999die(_("internal error in revision walk"));1000if(!(old_commit->object.flags & UNINTERESTING))1001suggest_reattach(old_commit, &revs);1002else1003describe_detached_head(_("Previous HEAD position was"), old_commit);10041005/* Clean up objects used, as they will be reused. */1006clear_commit_marks_all(ALL_REV_FLAGS);1007}10081009static intswitch_branches(const struct checkout_opts *opts,1010struct branch_info *new_branch_info)1011{1012int ret =0;1013struct branch_info old_branch_info;1014void*path_to_free;1015struct object_id rev;1016int flag, writeout_error =0;1017int do_merge =1;10181019trace2_cmd_mode("branch");10201021memset(&old_branch_info,0,sizeof(old_branch_info));1022 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag);1023if(old_branch_info.path)1024 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1);1025if(!(flag & REF_ISSYMREF))1026 old_branch_info.path = NULL;10271028if(old_branch_info.path)1029skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name);10301031if(opts->new_orphan_branch && opts->orphan_from_empty_tree) {1032if(new_branch_info->name)1033BUG("'switch --orphan' should never accept a commit as starting point");1034 new_branch_info->commit = NULL;1035 new_branch_info->name ="(empty)";1036 do_merge =1;1037}10381039if(!new_branch_info->name) {1040 new_branch_info->name ="HEAD";1041 new_branch_info->commit = old_branch_info.commit;1042if(!new_branch_info->commit)1043die(_("You are on a branch yet to be born"));1044parse_commit_or_die(new_branch_info->commit);10451046if(opts->only_merge_on_switching_branches)1047 do_merge =0;1048}10491050if(do_merge) {1051 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);1052if(ret) {1053free(path_to_free);1054return ret;1055}1056}10571058if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)1059orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);10601061update_refs_for_switch(opts, &old_branch_info, new_branch_info);10621063 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1);1064free(path_to_free);1065return ret || writeout_error;1066}10671068static intgit_checkout_config(const char*var,const char*value,void*cb)1069{1070if(!strcmp(var,"diff.ignoresubmodules")) {1071struct checkout_opts *opts = cb;1072handle_ignore_submodules_arg(&opts->diff_options, value);1073return0;1074}10751076if(starts_with(var,"submodule."))1077returngit_default_submodule_config(var, value, NULL);10781079returngit_xmerge_config(var, value, NULL);1080}10811082static voidsetup_new_branch_info_and_source_tree(1083struct branch_info *new_branch_info,1084struct checkout_opts *opts,1085struct object_id *rev,1086const char*arg)1087{1088struct tree **source_tree = &opts->source_tree;1089struct object_id branch_rev;10901091 new_branch_info->name = arg;1092setup_branch_path(new_branch_info);10931094if(!check_refname_format(new_branch_info->path,0) &&1095!read_ref(new_branch_info->path, &branch_rev))1096oidcpy(rev, &branch_rev);1097else1098 new_branch_info->path = NULL;/* not an existing branch */10991100 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1101if(!new_branch_info->commit) {1102/* not a commit */1103*source_tree =parse_tree_indirect(rev);1104}else{1105parse_commit_or_die(new_branch_info->commit);1106*source_tree =get_commit_tree(new_branch_info->commit);1107}1108}11091110static intparse_branchname_arg(int argc,const char**argv,1111int dwim_new_local_branch_ok,1112struct branch_info *new_branch_info,1113struct checkout_opts *opts,1114struct object_id *rev,1115int*dwim_remotes_matched)1116{1117const char**new_branch = &opts->new_branch;1118int argcount =0;1119const char*arg;1120int dash_dash_pos;1121int has_dash_dash =0;1122int i;11231124/*1125 * case 1: git checkout <ref> -- [<paths>]1126 *1127 * <ref> must be a valid tree, everything after the '--' must be1128 * a path.1129 *1130 * case 2: git checkout -- [<paths>]1131 *1132 * everything after the '--' must be paths.1133 *1134 * case 3: git checkout <something> [--]1135 *1136 * (a) If <something> is a commit, that is to1137 * switch to the branch or detach HEAD at it. As a special case,1138 * if <something> is A...B (missing A or B means HEAD but you can1139 * omit at most one side), and if there is a unique merge base1140 * between A and B, A...B names that merge base.1141 *1142 * (b) If <something> is _not_ a commit, either "--" is present1143 * or <something> is not a path, no -t or -b was given, and1144 * and there is a tracking branch whose name is <something>1145 * in one and only one remote (or if the branch exists on the1146 * remote named in checkout.defaultRemote), then this is a1147 * short-hand to fork local <something> from that1148 * remote-tracking branch.1149 *1150 * (c) Otherwise, if "--" is present, treat it like case (1).1151 *1152 * (d) Otherwise :1153 * - if it's a reference, treat it like case (1)1154 * - else if it's a path, treat it like case (2)1155 * - else: fail.1156 *1157 * case 4: git checkout <something> <paths>1158 *1159 * The first argument must not be ambiguous.1160 * - If it's *only* a reference, treat it like case (1).1161 * - If it's only a path, treat it like case (2).1162 * - else: fail.1163 *1164 */1165if(!argc)1166return0;11671168if(!opts->accept_pathspec) {1169if(argc >1)1170die(_("only one reference expected"));1171 has_dash_dash =1;/* helps disambiguate */1172}11731174 arg = argv[0];1175 dash_dash_pos = -1;1176for(i =0; i < argc; i++) {1177if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1178 dash_dash_pos = i;1179break;1180}1181}1182if(dash_dash_pos ==0)1183return1;/* case (2) */1184else if(dash_dash_pos ==1)1185 has_dash_dash =1;/* case (3) or (1) */1186else if(dash_dash_pos >=2)1187die(_("only one reference expected,%dgiven."), dash_dash_pos);1188 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;11891190if(!strcmp(arg,"-"))1191 arg ="@{-1}";11921193if(get_oid_mb(arg, rev)) {1194/*1195 * Either case (3) or (4), with <something> not being1196 * a commit, or an attempt to use case (1) with an1197 * invalid ref.1198 *1199 * It's likely an error, but we need to find out if1200 * we should auto-create the branch, case (3).(b).1201 */1202int recover_with_dwim = dwim_new_local_branch_ok;12031204int could_be_checkout_paths = !has_dash_dash &&1205check_filename(opts->prefix, arg);12061207if(!has_dash_dash && !no_wildcard(arg))1208 recover_with_dwim =0;12091210/*1211 * Accept "git checkout foo", "git checkout foo --"1212 * and "git switch foo" as candidates for dwim.1213 */1214if(!(argc ==1&& !has_dash_dash) &&1215!(argc ==2&& has_dash_dash) &&1216 opts->accept_pathspec)1217 recover_with_dwim =0;12181219if(recover_with_dwim) {1220const char*remote =unique_tracking_name(arg, rev,1221 dwim_remotes_matched);1222if(remote) {1223if(could_be_checkout_paths)1224die(_("'%s' could be both a local file and a tracking branch.\n"1225"Please use -- (and optionally --no-guess) to disambiguate"),1226 arg);1227*new_branch = arg;1228 arg = remote;1229/* DWIMmed to create local branch, case (3).(b) */1230}else{1231 recover_with_dwim =0;1232}1233}12341235if(!recover_with_dwim) {1236if(has_dash_dash)1237die(_("invalid reference:%s"), arg);1238return argcount;1239}1240}12411242/* we can't end up being in (2) anymore, eat the argument */1243 argcount++;1244 argv++;1245 argc--;12461247setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);12481249if(!opts->source_tree)/* case (1): want a tree */1250die(_("reference is not a tree:%s"), arg);12511252if(!has_dash_dash) {/* case (3).(d) -> (1) */1253/*1254 * Do not complain the most common case1255 * git checkout branch1256 * even if there happen to be a file called 'branch';1257 * it would be extremely annoying.1258 */1259if(argc)1260verify_non_filename(opts->prefix, arg);1261}else if(opts->accept_pathspec) {1262 argcount++;1263 argv++;1264 argc--;1265}12661267return argcount;1268}12691270static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1271{1272int status;1273struct strbuf branch_ref = STRBUF_INIT;12741275trace2_cmd_mode("unborn");12761277if(!opts->new_branch)1278die(_("You are on a branch yet to be born"));1279strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1280 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1281strbuf_release(&branch_ref);1282if(!opts->quiet)1283fprintf(stderr,_("Switched to a new branch '%s'\n"),1284 opts->new_branch);1285return status;1286}12871288static voiddie_expecting_a_branch(const struct branch_info *branch_info)1289{1290struct object_id oid;1291char*to_free;12921293if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1294const char*ref = to_free;12951296if(skip_prefix(ref,"refs/tags/", &ref))1297die(_("a branch is expected, got tag '%s'"), ref);1298if(skip_prefix(ref,"refs/remotes/", &ref))1299die(_("a branch is expected, got remote branch '%s'"), ref);1300die(_("a branch is expected, got '%s'"), ref);1301}1302if(branch_info->commit)1303die(_("a branch is expected, got commit '%s'"), branch_info->name);1304/*1305 * This case should never happen because we already die() on1306 * non-commit, but just in case.1307 */1308die(_("a branch is expected, got '%s'"), branch_info->name);1309}13101311static voiddie_if_some_operation_in_progress(void)1312{1313struct wt_status_state state;13141315memset(&state,0,sizeof(state));1316wt_status_get_state(the_repository, &state,0);13171318if(state.merge_in_progress)1319die(_("cannot switch branch while merging\n"1320"Consider\"git merge --quit\""1321"or\"git worktree add\"."));1322if(state.am_in_progress)1323die(_("cannot switch branch in the middle of an am session\n"1324"Consider\"git am --quit\""1325"or\"git worktree add\"."));1326if(state.rebase_interactive_in_progress || state.rebase_in_progress)1327die(_("cannot switch branch while rebasing\n"1328"Consider\"git rebase --quit\""1329"or\"git worktree add\"."));1330if(state.cherry_pick_in_progress)1331die(_("cannot switch branch while cherry-picking\n"1332"Consider\"git cherry-pick --quit\""1333"or\"git worktree add\"."));1334if(state.revert_in_progress)1335die(_("cannot switch branch while reverting\n"1336"Consider\"git revert --quit\""1337"or\"git worktree add\"."));1338if(state.bisect_in_progress)1339warning(_("you are switching branch while bisecting"));1340}13411342static intcheckout_branch(struct checkout_opts *opts,1343struct branch_info *new_branch_info)1344{1345if(opts->pathspec.nr)1346die(_("paths cannot be used with switching branches"));13471348if(opts->patch_mode)1349die(_("'%s' cannot be used with switching branches"),1350"--patch");13511352if(opts->overlay_mode != -1)1353die(_("'%s' cannot be used with switching branches"),1354"--[no]-overlay");13551356if(opts->writeout_stage)1357die(_("'%s' cannot be used with switching branches"),1358"--ours/--theirs");13591360if(opts->force && opts->merge)1361die(_("'%s' cannot be used with '%s'"),"-f","-m");13621363if(opts->discard_changes && opts->merge)1364die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");13651366if(opts->force_detach && opts->new_branch)1367die(_("'%s' cannot be used with '%s'"),1368"--detach","-b/-B/--orphan");13691370if(opts->new_orphan_branch) {1371if(opts->track != BRANCH_TRACK_UNSPECIFIED)1372die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1373if(opts->orphan_from_empty_tree && new_branch_info->name)1374die(_("'%s' cannot take <start-point>"),"--orphan");1375}else if(opts->force_detach) {1376if(opts->track != BRANCH_TRACK_UNSPECIFIED)1377die(_("'%s' cannot be used with '%s'"),"--detach","-t");1378}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1379 opts->track = git_branch_track;13801381if(new_branch_info->name && !new_branch_info->commit)1382die(_("Cannot switch branch to a non-commit '%s'"),1383 new_branch_info->name);13841385if(!opts->switch_branch_doing_nothing_is_ok &&1386!new_branch_info->name &&1387!opts->new_branch &&1388!opts->force_detach)1389die(_("missing branch or commit argument"));13901391if(!opts->implicit_detach &&1392!opts->force_detach &&1393!opts->new_branch &&1394!opts->new_branch_force &&1395 new_branch_info->name &&1396!new_branch_info->path)1397die_expecting_a_branch(new_branch_info);13981399if(!opts->can_switch_when_in_progress)1400die_if_some_operation_in_progress();14011402if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1403!opts->ignore_other_worktrees) {1404int flag;1405char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1406if(head_ref &&1407(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1408die_if_checked_out(new_branch_info->path,1);1409free(head_ref);1410}14111412if(!new_branch_info->commit && opts->new_branch) {1413struct object_id rev;1414int flag;14151416if(!read_ref_full("HEAD",0, &rev, &flag) &&1417(flag & REF_ISSYMREF) &&is_null_oid(&rev))1418returnswitch_unborn_to_new_branch(opts);1419}1420returnswitch_branches(opts, new_branch_info);1421}14221423static struct option *add_common_options(struct checkout_opts *opts,1424struct option *prevopts)1425{1426struct option options[] = {1427OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1428{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1429"checkout","control recursive updating of submodules",1430 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1431OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1432OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1433OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1434N_("conflict style (merge or diff3)")),1435OPT_END()1436};1437struct option *newopts =parse_options_concat(prevopts, options);1438free(prevopts);1439return newopts;1440}14411442static struct option *add_common_switch_branch_options(1443struct checkout_opts *opts,struct option *prevopts)1444{1445struct option options[] = {1446OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1447OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1448 BRANCH_TRACK_EXPLICIT),1449OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1450 PARSE_OPT_NOCOMPLETE),1451OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1452OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1453N_("update ignored files (default)"),1454 PARSE_OPT_NOCOMPLETE),1455OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1456N_("do not check if another worktree is holding the given ref")),1457OPT_END()1458};1459struct option *newopts =parse_options_concat(prevopts, options);1460free(prevopts);1461return newopts;1462}14631464static struct option *add_checkout_path_options(struct checkout_opts *opts,1465struct option *prevopts)1466{1467struct option options[] = {1468OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1469N_("checkout our version for unmerged files"),14702, PARSE_OPT_NONEG),1471OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1472N_("checkout their version for unmerged files"),14733, PARSE_OPT_NONEG),1474OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1475OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1476N_("do not limit pathspecs to sparse entries only")),1477OPT_END()1478};1479struct option *newopts =parse_options_concat(prevopts, options);1480free(prevopts);1481return newopts;1482}14831484static intcheckout_main(int argc,const char**argv,const char*prefix,1485struct checkout_opts *opts,struct option *options,1486const char*const usagestr[])1487{1488struct branch_info new_branch_info;1489int dwim_remotes_matched =0;1490int parseopt_flags =0;14911492memset(&new_branch_info,0,sizeof(new_branch_info));1493 opts->overwrite_ignore =1;1494 opts->prefix = prefix;1495 opts->show_progress = -1;14961497git_config(git_checkout_config, opts);14981499 opts->track = BRANCH_TRACK_UNSPECIFIED;15001501if(!opts->accept_pathspec && !opts->accept_ref)1502BUG("make up your mind, you need to take _something_");1503if(opts->accept_pathspec && opts->accept_ref)1504 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;15051506 argc =parse_options(argc, argv, prefix, options,1507 usagestr, parseopt_flags);15081509if(opts->show_progress <0) {1510if(opts->quiet)1511 opts->show_progress =0;1512else1513 opts->show_progress =isatty(2);1514}15151516if(opts->conflict_style) {1517 opts->merge =1;/* implied */1518git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1519}1520if(opts->force) {1521 opts->discard_changes =1;1522 opts->ignore_unmerged_opt ="--force";1523 opts->ignore_unmerged =1;1524}15251526if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1527die(_("-b, -B and --orphan are mutually exclusive"));15281529if(opts->overlay_mode ==1&& opts->patch_mode)1530die(_("-p and --overlay are mutually exclusive"));15311532if(opts->checkout_index >=0|| opts->checkout_worktree >=0) {1533if(opts->checkout_index <0)1534 opts->checkout_index =0;1535if(opts->checkout_worktree <0)1536 opts->checkout_worktree =0;1537}else{1538if(opts->checkout_index <0)1539 opts->checkout_index = -opts->checkout_index -1;1540if(opts->checkout_worktree <0)1541 opts->checkout_worktree = -opts->checkout_worktree -1;1542}1543if(opts->checkout_index <0|| opts->checkout_worktree <0)1544BUG("these flags should be non-negative by now");1545/*1546 * convenient shortcut: "git restore --staged" equals1547 * "git restore --staged --source HEAD"1548 */1549if(!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)1550 opts->from_treeish ="HEAD";15511552/*1553 * From here on, new_branch will contain the branch to be checked out,1554 * and new_branch_force and new_orphan_branch will tell us which one of1555 * -b/-B/--orphan is being used.1556 */1557if(opts->new_branch_force)1558 opts->new_branch = opts->new_branch_force;15591560if(opts->new_orphan_branch)1561 opts->new_branch = opts->new_orphan_branch;15621563/* --track without -b/-B/--orphan should DWIM */1564if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1565const char*argv0 = argv[0];1566if(!argc || !strcmp(argv0,"--"))1567die(_("--track needs a branch name"));1568skip_prefix(argv0,"refs/", &argv0);1569skip_prefix(argv0,"remotes/", &argv0);1570 argv0 =strchr(argv0,'/');1571if(!argv0 || !argv0[1])1572die(_("missing branch name; try -b"));1573 opts->new_branch = argv0 +1;1574}15751576/*1577 * Extract branch name from command line arguments, so1578 * all that is left is pathspecs.1579 *1580 * Handle1581 *1582 * 1) git checkout <tree> -- [<paths>]1583 * 2) git checkout -- [<paths>]1584 * 3) git checkout <something> [<paths>]1585 *1586 * including "last branch" syntax and DWIM-ery for names of1587 * remote branches, erroring out for invalid or ambiguous cases.1588 */1589if(argc && opts->accept_ref) {1590struct object_id rev;1591int dwim_ok =1592!opts->patch_mode &&1593 opts->dwim_new_local_branch &&1594 opts->track == BRANCH_TRACK_UNSPECIFIED &&1595!opts->new_branch;1596int n =parse_branchname_arg(argc, argv, dwim_ok,1597&new_branch_info, opts, &rev,1598&dwim_remotes_matched);1599 argv += n;1600 argc -= n;1601}else if(!opts->accept_ref && opts->from_treeish) {1602struct object_id rev;16031604if(get_oid_mb(opts->from_treeish, &rev))1605die(_("could not resolve%s"), opts->from_treeish);16061607setup_new_branch_info_and_source_tree(&new_branch_info,1608 opts, &rev,1609 opts->from_treeish);16101611if(!opts->source_tree)1612die(_("reference is not a tree:%s"), opts->from_treeish);1613}16141615if(opts->accept_pathspec && !opts->empty_pathspec_ok && !argc &&1616!opts->patch_mode)/* patch mode is special */1617die(_("you must specify path(s) to restore"));16181619if(argc) {1620parse_pathspec(&opts->pathspec,0,1621 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1622 prefix, argv);16231624if(!opts->pathspec.nr)1625die(_("invalid path specification"));16261627/*1628 * Try to give more helpful suggestion.1629 * new_branch && argc > 1 will be caught later.1630 */1631if(opts->new_branch && argc ==1)1632die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1633 argv[0], opts->new_branch);16341635if(opts->force_detach)1636die(_("git checkout: --detach does not take a path argument '%s'"),1637 argv[0]);16381639if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1640die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1641"checking out of the index."));1642}16431644if(opts->new_branch) {1645struct strbuf buf = STRBUF_INIT;16461647if(opts->new_branch_force)1648 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1649else1650 opts->branch_exists =1651validate_new_branchname(opts->new_branch, &buf,0);1652strbuf_release(&buf);1653}16541655UNLEAK(opts);1656if(opts->patch_mode || opts->pathspec.nr) {1657int ret =checkout_paths(opts, new_branch_info.name);1658if(ret && dwim_remotes_matched >1&&1659 advice_checkout_ambiguous_remote_branch_name)1660advise(_("'%s' matched more than one remote tracking branch.\n"1661"We found%dremotes with a reference that matched. So we fell back\n"1662"on trying to resolve the argument as a path, but failed there too!\n"1663"\n"1664"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1665"you can do so by fully qualifying the name with the --track option:\n"1666"\n"1667" git checkout --track origin/<name>\n"1668"\n"1669"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1670"one remote, e.g. the 'origin' remote, consider setting\n"1671"checkout.defaultRemote=origin in your config."),1672 argv[0],1673 dwim_remotes_matched);1674return ret;1675}else{1676returncheckout_branch(opts, &new_branch_info);1677}1678}16791680intcmd_checkout(int argc,const char**argv,const char*prefix)1681{1682struct checkout_opts opts;1683struct option *options;1684struct option checkout_options[] = {1685OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1686N_("create and checkout a new branch")),1687OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1688N_("create/reset and checkout a branch")),1689OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1690OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1691N_("second guess 'git checkout <no-such-branch>' (default)")),1692OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode (default)")),1693OPT_END()1694};1695int ret;16961697memset(&opts,0,sizeof(opts));1698 opts.dwim_new_local_branch =1;1699 opts.switch_branch_doing_nothing_is_ok =1;1700 opts.only_merge_on_switching_branches =0;1701 opts.accept_ref =1;1702 opts.accept_pathspec =1;1703 opts.implicit_detach =1;1704 opts.can_switch_when_in_progress =1;1705 opts.orphan_from_empty_tree =0;1706 opts.empty_pathspec_ok =1;1707 opts.overlay_mode = -1;1708 opts.checkout_index = -2;/* default on */1709 opts.checkout_worktree = -2;/* default on */17101711if(argc ==3&& !strcmp(argv[1],"-b")) {1712/*1713 * User ran 'git checkout -b <branch>' and expects1714 * the same behavior as 'git switch -c <branch>'.1715 */1716 opts.switch_branch_doing_nothing_is_ok =0;1717 opts.only_merge_on_switching_branches =1;1718}17191720 options =parse_options_dup(checkout_options);1721 options =add_common_options(&opts, options);1722 options =add_common_switch_branch_options(&opts, options);1723 options =add_checkout_path_options(&opts, options);17241725 ret =checkout_main(argc, argv, prefix, &opts,1726 options, checkout_usage);1727FREE_AND_NULL(options);1728return ret;1729}17301731intcmd_switch(int argc,const char**argv,const char*prefix)1732{1733struct checkout_opts opts;1734struct option *options = NULL;1735struct option switch_options[] = {1736OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1737N_("create and switch to a new branch")),1738OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1739N_("create/reset and switch to a branch")),1740OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1741N_("second guess 'git switch <no-such-branch>'")),1742OPT_BOOL(0,"discard-changes", &opts.discard_changes,1743N_("throw away local modifications")),1744OPT_END()1745};1746int ret;17471748memset(&opts,0,sizeof(opts));1749 opts.dwim_new_local_branch =1;1750 opts.accept_ref =1;1751 opts.accept_pathspec =0;1752 opts.switch_branch_doing_nothing_is_ok =0;1753 opts.only_merge_on_switching_branches =1;1754 opts.implicit_detach =0;1755 opts.can_switch_when_in_progress =0;1756 opts.orphan_from_empty_tree =1;1757 opts.overlay_mode = -1;17581759 options =parse_options_dup(switch_options);1760 options =add_common_options(&opts, options);1761 options =add_common_switch_branch_options(&opts, options);17621763 ret =checkout_main(argc, argv, prefix, &opts,1764 options, switch_branch_usage);1765FREE_AND_NULL(options);1766return ret;1767}17681769intcmd_restore(int argc,const char**argv,const char*prefix)1770{1771struct checkout_opts opts;1772struct option *options;1773struct option restore_options[] = {1774OPT_STRING('s',"source", &opts.from_treeish,"<tree-ish>",1775N_("which tree-ish to checkout from")),1776OPT_BOOL('S',"staged", &opts.checkout_index,1777N_("restore the index")),1778OPT_BOOL('W',"worktree", &opts.checkout_worktree,1779N_("restore the working tree (default)")),1780OPT_BOOL(0,"ignore-unmerged", &opts.ignore_unmerged,1781N_("ignore unmerged entries")),1782OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode")),1783OPT_END()1784};1785int ret;17861787memset(&opts,0,sizeof(opts));1788 opts.accept_ref =0;1789 opts.accept_pathspec =1;1790 opts.empty_pathspec_ok =0;1791 opts.overlay_mode =0;1792 opts.checkout_index = -1;/* default off */1793 opts.checkout_worktree = -2;/* default on */1794 opts.ignore_unmerged_opt ="--ignore-unmerged";17951796 options =parse_options_dup(restore_options);1797 options =add_common_options(&opts, options);1798 options =add_checkout_path_options(&opts, options);17991800 ret =checkout_main(argc, argv, prefix, &opts,1801 options, restore_usage);1802FREE_AND_NULL(options);1803return ret;1804}