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; 71 72const char*new_branch; 73const char*new_branch_force; 74const char*new_orphan_branch; 75int new_branch_log; 76enum branch_track track; 77struct diff_options diff_options; 78char*conflict_style; 79 80int branch_exists; 81const char*prefix; 82struct pathspec pathspec; 83const char*from_treeish; 84struct tree *source_tree; 85}; 86 87static intpost_checkout_hook(struct commit *old_commit,struct commit *new_commit, 88int changed) 89{ 90returnrun_hook_le(NULL,"post-checkout", 91oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid), 92oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid), 93 changed ?"1":"0", NULL); 94/* "new_commit" can be NULL when checking out from the index before 95 a commit exists. */ 96 97} 98 99static intupdate_some(const struct object_id *oid,struct strbuf *base, 100const char*pathname,unsigned mode,int stage,void*context) 101{ 102int len; 103struct cache_entry *ce; 104int pos; 105 106if(S_ISDIR(mode)) 107return READ_TREE_RECURSIVE; 108 109 len = base->len +strlen(pathname); 110 ce =make_empty_cache_entry(&the_index, len); 111oidcpy(&ce->oid, oid); 112memcpy(ce->name, base->buf, base->len); 113memcpy(ce->name + base->len, pathname, len - base->len); 114 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 115 ce->ce_namelen = len; 116 ce->ce_mode =create_ce_mode(mode); 117 118/* 119 * If the entry is the same as the current index, we can leave the old 120 * entry in place. Whether it is UPTODATE or not, checkout_entry will 121 * do the right thing. 122 */ 123 pos =cache_name_pos(ce->name, ce->ce_namelen); 124if(pos >=0) { 125struct cache_entry *old = active_cache[pos]; 126if(ce->ce_mode == old->ce_mode && 127oideq(&ce->oid, &old->oid)) { 128 old->ce_flags |= CE_UPDATE; 129discard_cache_entry(ce); 130return0; 131} 132} 133 134add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 135return0; 136} 137 138static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 139{ 140read_tree_recursive(the_repository, tree,"",0,0, 141 pathspec, update_some, NULL); 142 143/* update the index with the given tree's info 144 * for all args, expanding wildcards, and exit 145 * with any non-zero return code. 146 */ 147return0; 148} 149 150static intskip_same_name(const struct cache_entry *ce,int pos) 151{ 152while(++pos < active_nr && 153!strcmp(active_cache[pos]->name, ce->name)) 154;/* skip */ 155return pos; 156} 157 158static intcheck_stage(int stage,const struct cache_entry *ce,int pos, 159int overlay_mode) 160{ 161while(pos < active_nr && 162!strcmp(active_cache[pos]->name, ce->name)) { 163if(ce_stage(active_cache[pos]) == stage) 164return0; 165 pos++; 166} 167if(!overlay_mode) 168return0; 169if(stage ==2) 170returnerror(_("path '%s' does not have our version"), ce->name); 171else 172returnerror(_("path '%s' does not have their version"), ce->name); 173} 174 175static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 176{ 177unsigned seen =0; 178const char*name = ce->name; 179 180while(pos < active_nr) { 181 ce = active_cache[pos]; 182if(strcmp(name, ce->name)) 183break; 184 seen |= (1<<ce_stage(ce)); 185 pos++; 186} 187if((stages & seen) != stages) 188returnerror(_("path '%s' does not have all necessary versions"), 189 name); 190return0; 191} 192 193static intcheckout_stage(int stage,const struct cache_entry *ce,int pos, 194const struct checkout *state,int*nr_checkouts, 195int overlay_mode) 196{ 197while(pos < active_nr && 198!strcmp(active_cache[pos]->name, ce->name)) { 199if(ce_stage(active_cache[pos]) == stage) 200returncheckout_entry(active_cache[pos], state, 201 NULL, nr_checkouts); 202 pos++; 203} 204if(!overlay_mode) { 205unlink_entry(ce); 206return0; 207} 208if(stage ==2) 209returnerror(_("path '%s' does not have our version"), ce->name); 210else 211returnerror(_("path '%s' does not have their version"), ce->name); 212} 213 214static intcheckout_merged(int pos,const struct checkout *state,int*nr_checkouts) 215{ 216struct cache_entry *ce = active_cache[pos]; 217const char*path = ce->name; 218 mmfile_t ancestor, ours, theirs; 219int status; 220struct object_id oid; 221 mmbuffer_t result_buf; 222struct object_id threeway[3]; 223unsigned mode =0; 224 225memset(threeway,0,sizeof(threeway)); 226while(pos < active_nr) { 227int stage; 228 stage =ce_stage(ce); 229if(!stage ||strcmp(path, ce->name)) 230break; 231oidcpy(&threeway[stage -1], &ce->oid); 232if(stage ==2) 233 mode =create_ce_mode(ce->ce_mode); 234 pos++; 235 ce = active_cache[pos]; 236} 237if(is_null_oid(&threeway[1]) ||is_null_oid(&threeway[2])) 238returnerror(_("path '%s' does not have necessary versions"), path); 239 240read_mmblob(&ancestor, &threeway[0]); 241read_mmblob(&ours, &threeway[1]); 242read_mmblob(&theirs, &threeway[2]); 243 244/* 245 * NEEDSWORK: re-create conflicts from merges with 246 * merge.renormalize set, too 247 */ 248 status =ll_merge(&result_buf, path, &ancestor,"base", 249&ours,"ours", &theirs,"theirs", 250 state->istate, NULL); 251free(ancestor.ptr); 252free(ours.ptr); 253free(theirs.ptr); 254if(status <0|| !result_buf.ptr) { 255free(result_buf.ptr); 256returnerror(_("path '%s': cannot merge"), path); 257} 258 259/* 260 * NEEDSWORK: 261 * There is absolutely no reason to write this as a blob object 262 * and create a phony cache entry. This hack is primarily to get 263 * to the write_entry() machinery that massages the contents to 264 * work-tree format and writes out which only allows it for a 265 * cache entry. The code in write_entry() needs to be refactored 266 * to allow us to feed a <buffer, size, mode> instead of a cache 267 * entry. Such a refactoring would help merge_recursive as well 268 * (it also writes the merge result to the object database even 269 * when it may contain conflicts). 270 */ 271if(write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid)) 272die(_("Unable to add merge result for '%s'"), path); 273free(result_buf.ptr); 274 ce =make_transient_cache_entry(mode, &oid, path,2); 275if(!ce) 276die(_("make_cache_entry failed for path '%s'"), path); 277 status =checkout_entry(ce, state, NULL, nr_checkouts); 278discard_cache_entry(ce); 279return status; 280} 281 282static voidmark_ce_for_checkout_overlay(struct cache_entry *ce, 283char*ps_matched, 284const struct checkout_opts *opts) 285{ 286 ce->ce_flags &= ~CE_MATCHED; 287if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 288return; 289if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 290/* 291 * "git checkout tree-ish -- path", but this entry 292 * is in the original index but is not in tree-ish 293 * or does not match the pathspec; it will not be 294 * checked out to the working tree. We will not do 295 * anything to this entry at all. 296 */ 297return; 298/* 299 * Either this entry came from the tree-ish we are 300 * checking the paths out of, or we are checking out 301 * of the index. 302 * 303 * If it comes from the tree-ish, we already know it 304 * matches the pathspec and could just stamp 305 * CE_MATCHED to it from update_some(). But we still 306 * need ps_matched and read_tree_recursive (and 307 * eventually tree_entry_interesting) cannot fill 308 * ps_matched yet. Once it can, we can avoid calling 309 * match_pathspec() for _all_ entries when 310 * opts->source_tree != NULL. 311 */ 312if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) 313 ce->ce_flags |= CE_MATCHED; 314} 315 316static voidmark_ce_for_checkout_no_overlay(struct cache_entry *ce, 317char*ps_matched, 318const struct checkout_opts *opts) 319{ 320 ce->ce_flags &= ~CE_MATCHED; 321if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 322return; 323if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) { 324 ce->ce_flags |= CE_MATCHED; 325if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 326/* 327 * In overlay mode, but the path is not in 328 * tree-ish, which means we should remove it 329 * from the index and the working tree. 330 */ 331 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE; 332} 333} 334 335static intcheckout_worktree(const struct checkout_opts *opts) 336{ 337struct checkout state = CHECKOUT_INIT; 338int nr_checkouts =0, nr_unmerged =0; 339int errs =0; 340int pos; 341 342 state.force =1; 343 state.refresh_cache =1; 344 state.istate = &the_index; 345 346enable_delayed_checkout(&state); 347for(pos =0; pos < active_nr; pos++) { 348struct cache_entry *ce = active_cache[pos]; 349if(ce->ce_flags & CE_MATCHED) { 350if(!ce_stage(ce)) { 351 errs |=checkout_entry(ce, &state, 352 NULL, &nr_checkouts); 353continue; 354} 355if(opts->writeout_stage) 356 errs |=checkout_stage(opts->writeout_stage, 357 ce, pos, 358&state, 359&nr_checkouts, opts->overlay_mode); 360else if(opts->merge) 361 errs |=checkout_merged(pos, &state, 362&nr_unmerged); 363 pos =skip_same_name(ce, pos) -1; 364} 365} 366remove_marked_cache_entries(&the_index,1); 367remove_scheduled_dirs(); 368 errs |=finish_delayed_checkout(&state, &nr_checkouts); 369 370if(opts->count_checkout_paths) { 371if(nr_unmerged) 372fprintf_ln(stderr,Q_("Recreated%dmerge conflict", 373"Recreated%dmerge conflicts", 374 nr_unmerged), 375 nr_unmerged); 376if(opts->source_tree) 377fprintf_ln(stderr,Q_("Updated%dpath from%s", 378"Updated%dpaths from%s", 379 nr_checkouts), 380 nr_checkouts, 381find_unique_abbrev(&opts->source_tree->object.oid, 382 DEFAULT_ABBREV)); 383else if(!nr_unmerged || nr_checkouts) 384fprintf_ln(stderr,Q_("Updated%dpath from the index", 385"Updated%dpaths from the index", 386 nr_checkouts), 387 nr_checkouts); 388} 389 390return errs; 391} 392 393static intcheckout_paths(const struct checkout_opts *opts, 394const char*revision) 395{ 396int pos; 397static char*ps_matched; 398struct object_id rev; 399struct commit *head; 400int errs =0; 401struct lock_file lock_file = LOCK_INIT; 402int checkout_index; 403 404trace2_cmd_mode(opts->patch_mode ?"patch":"path"); 405 406if(opts->track != BRANCH_TRACK_UNSPECIFIED) 407die(_("'%s' cannot be used with updating paths"),"--track"); 408 409if(opts->new_branch_log) 410die(_("'%s' cannot be used with updating paths"),"-l"); 411 412if(opts->force && opts->patch_mode) 413die(_("'%s' cannot be used with updating paths"),"-f"); 414 415if(opts->force_detach) 416die(_("'%s' cannot be used with updating paths"),"--detach"); 417 418if(opts->merge && opts->patch_mode) 419die(_("'%s' cannot be used with%s"),"--merge","--patch"); 420 421if(opts->force && opts->merge) 422die(_("'%s' cannot be used with%s"),"-f","-m"); 423 424if(opts->new_branch) 425die(_("Cannot update paths and switch to branch '%s' at the same time."), 426 opts->new_branch); 427 428if(!opts->checkout_worktree && !opts->checkout_index) 429die(_("neither '%s' or '%s' is specified"), 430"--staged","--worktree"); 431 432if(!opts->checkout_worktree && !opts->from_treeish) 433die(_("'%s' must be used when '%s' is not specified"), 434"--worktree","--source"); 435 436if(opts->patch_mode) { 437const char*patch_mode; 438 439if(opts->checkout_index && opts->checkout_worktree) 440 patch_mode ="--patch=checkout"; 441else if(opts->checkout_index && !opts->checkout_worktree) 442 patch_mode ="--patch=reset"; 443else 444die(_("'%s' with only '%s' is not currently supported"), 445"--patch","--worktree"); 446returnrun_add_interactive(revision, patch_mode, &opts->pathspec); 447} 448 449repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 450if(read_cache_preload(&opts->pathspec) <0) 451returnerror(_("index file corrupt")); 452 453if(opts->source_tree) 454read_tree_some(opts->source_tree, &opts->pathspec); 455 456 ps_matched =xcalloc(opts->pathspec.nr,1); 457 458/* 459 * Make sure all pathspecs participated in locating the paths 460 * to be checked out. 461 */ 462for(pos =0; pos < active_nr; pos++) 463if(opts->overlay_mode) 464mark_ce_for_checkout_overlay(active_cache[pos], 465 ps_matched, 466 opts); 467else 468mark_ce_for_checkout_no_overlay(active_cache[pos], 469 ps_matched, 470 opts); 471 472if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 473free(ps_matched); 474return1; 475} 476free(ps_matched); 477 478/* "checkout -m path" to recreate conflicted state */ 479if(opts->merge) 480unmerge_marked_index(&the_index); 481 482/* Any unmerged paths? */ 483for(pos =0; pos < active_nr; pos++) { 484const struct cache_entry *ce = active_cache[pos]; 485if(ce->ce_flags & CE_MATCHED) { 486if(!ce_stage(ce)) 487continue; 488if(opts->force) { 489warning(_("path '%s' is unmerged"), ce->name); 490}else if(opts->writeout_stage) { 491 errs |=check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 492}else if(opts->merge) { 493 errs |=check_stages((1<<2) | (1<<3), ce, pos); 494}else{ 495 errs =1; 496error(_("path '%s' is unmerged"), ce->name); 497} 498 pos =skip_same_name(ce, pos) -1; 499} 500} 501if(errs) 502return1; 503 504/* Now we are committed to check them out */ 505if(opts->checkout_worktree) 506 errs |=checkout_worktree(opts); 507 508/* 509 * Allow updating the index when checking out from the index. 510 * This is to save new stat info. 511 */ 512if(opts->checkout_worktree && !opts->checkout_index && !opts->source_tree) 513 checkout_index =1; 514else 515 checkout_index = opts->checkout_index; 516 517if(checkout_index) { 518if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 519die(_("unable to write new index file")); 520}else{ 521/* 522 * NEEDSWORK: if --worktree is not specified, we 523 * should save stat info of checked out files in the 524 * index to avoid the next (potentially costly) 525 * refresh. But it's a bit tricker to do... 526 */ 527rollback_lock_file(&lock_file); 528} 529 530read_ref_full("HEAD",0, &rev, NULL); 531 head =lookup_commit_reference_gently(the_repository, &rev,1); 532 533 errs |=post_checkout_hook(head, head,0); 534return errs; 535} 536 537static voidshow_local_changes(struct object *head, 538const struct diff_options *opts) 539{ 540struct rev_info rev; 541/* I think we want full paths, even if we're in a subdirectory. */ 542repo_init_revisions(the_repository, &rev, NULL); 543 rev.diffopt.flags = opts->flags; 544 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 545diff_setup_done(&rev.diffopt); 546add_pending_object(&rev, head, NULL); 547run_diff_index(&rev,0); 548} 549 550static voiddescribe_detached_head(const char*msg,struct commit *commit) 551{ 552struct strbuf sb = STRBUF_INIT; 553 554if(!parse_commit(commit)) 555pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 556if(print_sha1_ellipsis()) { 557fprintf(stderr,"%s %s...%s\n", msg, 558find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 559}else{ 560fprintf(stderr,"%s %s %s\n", msg, 561find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 562} 563strbuf_release(&sb); 564} 565 566static intreset_tree(struct tree *tree,const struct checkout_opts *o, 567int worktree,int*writeout_error) 568{ 569struct unpack_trees_options opts; 570struct tree_desc tree_desc; 571 572memset(&opts,0,sizeof(opts)); 573 opts.head_idx = -1; 574 opts.update = worktree; 575 opts.skip_unmerged = !worktree; 576 opts.reset =1; 577 opts.merge =1; 578 opts.fn = oneway_merge; 579 opts.verbose_update = o->show_progress; 580 opts.src_index = &the_index; 581 opts.dst_index = &the_index; 582parse_tree(tree); 583init_tree_desc(&tree_desc, tree->buffer, tree->size); 584switch(unpack_trees(1, &tree_desc, &opts)) { 585case-2: 586*writeout_error =1; 587/* 588 * We return 0 nevertheless, as the index is all right 589 * and more importantly we have made best efforts to 590 * update paths in the work tree, and we cannot revert 591 * them. 592 */ 593/* fallthrough */ 594case0: 595return0; 596default: 597return128; 598} 599} 600 601struct branch_info { 602const char*name;/* The short name used */ 603const char*path;/* The full name of a real branch */ 604struct commit *commit;/* The named commit */ 605/* 606 * if not null the branch is detached because it's already 607 * checked out in this checkout 608 */ 609char*checkout; 610}; 611 612static voidsetup_branch_path(struct branch_info *branch) 613{ 614struct strbuf buf = STRBUF_INIT; 615 616strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 617if(strcmp(buf.buf, branch->name)) 618 branch->name =xstrdup(buf.buf); 619strbuf_splice(&buf,0,0,"refs/heads/",11); 620 branch->path =strbuf_detach(&buf, NULL); 621} 622 623static intmerge_working_tree(const struct checkout_opts *opts, 624struct branch_info *old_branch_info, 625struct branch_info *new_branch_info, 626int*writeout_error) 627{ 628int ret; 629struct lock_file lock_file = LOCK_INIT; 630struct tree *new_tree; 631 632hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 633if(read_cache_preload(NULL) <0) 634returnerror(_("index file corrupt")); 635 636resolve_undo_clear(); 637if(opts->new_orphan_branch && opts->orphan_from_empty_tree) { 638if(new_branch_info->commit) 639BUG("'switch --orphan' should never accept a commit as starting point"); 640 new_tree =parse_tree_indirect(the_hash_algo->empty_tree); 641}else 642 new_tree =get_commit_tree(new_branch_info->commit); 643if(opts->discard_changes) { 644 ret =reset_tree(new_tree, opts,1, writeout_error); 645if(ret) 646return ret; 647}else{ 648struct tree_desc trees[2]; 649struct tree *tree; 650struct unpack_trees_options topts; 651 652memset(&topts,0,sizeof(topts)); 653 topts.head_idx = -1; 654 topts.src_index = &the_index; 655 topts.dst_index = &the_index; 656 657setup_unpack_trees_porcelain(&topts,"checkout"); 658 659refresh_cache(REFRESH_QUIET); 660 661if(unmerged_cache()) { 662error(_("you need to resolve your current index first")); 663return1; 664} 665 666/* 2-way merge to the new branch */ 667 topts.initial_checkout =is_cache_unborn(); 668 topts.update =1; 669 topts.merge =1; 670 topts.gently = opts->merge && old_branch_info->commit; 671 topts.verbose_update = opts->show_progress; 672 topts.fn = twoway_merge; 673if(opts->overwrite_ignore) { 674 topts.dir =xcalloc(1,sizeof(*topts.dir)); 675 topts.dir->flags |= DIR_SHOW_IGNORED; 676setup_standard_excludes(topts.dir); 677} 678 tree =parse_tree_indirect(old_branch_info->commit ? 679&old_branch_info->commit->object.oid : 680 the_hash_algo->empty_tree); 681init_tree_desc(&trees[0], tree->buffer, tree->size); 682parse_tree(new_tree); 683 tree = new_tree; 684init_tree_desc(&trees[1], tree->buffer, tree->size); 685 686 ret =unpack_trees(2, trees, &topts); 687clear_unpack_trees_porcelain(&topts); 688if(ret == -1) { 689/* 690 * Unpack couldn't do a trivial merge; either 691 * give up or do a real merge, depending on 692 * whether the merge flag was used. 693 */ 694struct tree *result; 695struct tree *work; 696struct merge_options o; 697if(!opts->merge) 698return1; 699 700/* 701 * Without old_branch_info->commit, the below is the same as 702 * the two-tree unpack we already tried and failed. 703 */ 704if(!old_branch_info->commit) 705return1; 706 707/* Do more real merge */ 708 709/* 710 * We update the index fully, then write the 711 * tree from the index, then merge the new 712 * branch with the current tree, with the old 713 * branch as the base. Then we reset the index 714 * (but not the working tree) to the new 715 * branch, leaving the working tree as the 716 * merged version, but skipping unmerged 717 * entries in the index. 718 */ 719 720add_files_to_cache(NULL, NULL,0); 721/* 722 * NEEDSWORK: carrying over local changes 723 * when branches have different end-of-line 724 * normalization (or clean+smudge rules) is 725 * a pain; plumb in an option to set 726 * o.renormalize? 727 */ 728init_merge_options(&o, the_repository); 729 o.verbosity =0; 730 work =write_tree_from_memory(&o); 731 732 ret =reset_tree(new_tree, 733 opts,1, 734 writeout_error); 735if(ret) 736return ret; 737 o.ancestor = old_branch_info->name; 738 o.branch1 = new_branch_info->name; 739 o.branch2 ="local"; 740 ret =merge_trees(&o, 741 new_tree, 742 work, 743get_commit_tree(old_branch_info->commit), 744&result); 745if(ret <0) 746exit(128); 747 ret =reset_tree(new_tree, 748 opts,0, 749 writeout_error); 750strbuf_release(&o.obuf); 751if(ret) 752return ret; 753} 754} 755 756if(!active_cache_tree) 757 active_cache_tree =cache_tree(); 758 759if(!cache_tree_fully_valid(active_cache_tree)) 760cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 761 762if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 763die(_("unable to write new index file")); 764 765if(!opts->discard_changes && !opts->quiet && new_branch_info->commit) 766show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 767 768return0; 769} 770 771static voidreport_tracking(struct branch_info *new_branch_info) 772{ 773struct strbuf sb = STRBUF_INIT; 774struct branch *branch =branch_get(new_branch_info->name); 775 776if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 777return; 778fputs(sb.buf, stdout); 779strbuf_release(&sb); 780} 781 782static voidupdate_refs_for_switch(const struct checkout_opts *opts, 783struct branch_info *old_branch_info, 784struct branch_info *new_branch_info) 785{ 786struct strbuf msg = STRBUF_INIT; 787const char*old_desc, *reflog_msg; 788if(opts->new_branch) { 789if(opts->new_orphan_branch) { 790char*refname; 791 792 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 793if(opts->new_branch_log && 794!should_autocreate_reflog(refname)) { 795int ret; 796struct strbuf err = STRBUF_INIT; 797 798 ret =safe_create_reflog(refname,1, &err); 799if(ret) { 800fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 801 opts->new_orphan_branch, err.buf); 802strbuf_release(&err); 803free(refname); 804return; 805} 806strbuf_release(&err); 807} 808free(refname); 809} 810else 811create_branch(the_repository, 812 opts->new_branch, new_branch_info->name, 813 opts->new_branch_force ?1:0, 814 opts->new_branch_force ?1:0, 815 opts->new_branch_log, 816 opts->quiet, 817 opts->track); 818 new_branch_info->name = opts->new_branch; 819setup_branch_path(new_branch_info); 820} 821 822 old_desc = old_branch_info->name; 823if(!old_desc && old_branch_info->commit) 824 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 825 826 reflog_msg =getenv("GIT_REFLOG_ACTION"); 827if(!reflog_msg) 828strbuf_addf(&msg,"checkout: moving from%sto%s", 829 old_desc ? old_desc :"(invalid)", new_branch_info->name); 830else 831strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 832 833if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 834/* Nothing to do. */ 835}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 836update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 837 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 838if(!opts->quiet) { 839if(old_branch_info->path && 840 advice_detached_head && !opts->force_detach) 841detach_advice(new_branch_info->name); 842describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 843} 844}else if(new_branch_info->path) {/* Switch branches. */ 845if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 846die(_("unable to update HEAD")); 847if(!opts->quiet) { 848if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 849if(opts->new_branch_force) 850fprintf(stderr,_("Reset branch '%s'\n"), 851 new_branch_info->name); 852else 853fprintf(stderr,_("Already on '%s'\n"), 854 new_branch_info->name); 855}else if(opts->new_branch) { 856if(opts->branch_exists) 857fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 858else 859fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 860}else{ 861fprintf(stderr,_("Switched to branch '%s'\n"), 862 new_branch_info->name); 863} 864} 865if(old_branch_info->path && old_branch_info->name) { 866if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 867delete_reflog(old_branch_info->path); 868} 869} 870remove_branch_state(the_repository, !opts->quiet); 871strbuf_release(&msg); 872if(!opts->quiet && 873(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 874report_tracking(new_branch_info); 875} 876 877static intadd_pending_uninteresting_ref(const char*refname, 878const struct object_id *oid, 879int flags,void*cb_data) 880{ 881add_pending_oid(cb_data, refname, oid, UNINTERESTING); 882return0; 883} 884 885static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 886{ 887strbuf_addstr(sb," "); 888strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 889strbuf_addch(sb,' '); 890if(!parse_commit(commit)) 891pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 892strbuf_addch(sb,'\n'); 893} 894 895#define ORPHAN_CUTOFF 4 896static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 897{ 898struct commit *c, *last = NULL; 899struct strbuf sb = STRBUF_INIT; 900int lost =0; 901while((c =get_revision(revs)) != NULL) { 902if(lost < ORPHAN_CUTOFF) 903describe_one_orphan(&sb, c); 904 last = c; 905 lost++; 906} 907if(ORPHAN_CUTOFF < lost) { 908int more = lost - ORPHAN_CUTOFF; 909if(more ==1) 910describe_one_orphan(&sb, last); 911else 912strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 913} 914 915fprintf(stderr, 916Q_( 917/* The singular version */ 918"Warning: you are leaving%dcommit behind, " 919"not connected to\n" 920"any of your branches:\n\n" 921"%s\n", 922/* The plural version */ 923"Warning: you are leaving%dcommits behind, " 924"not connected to\n" 925"any of your branches:\n\n" 926"%s\n", 927/* Give ngettext() the count */ 928 lost), 929 lost, 930 sb.buf); 931strbuf_release(&sb); 932 933if(advice_detached_head) 934fprintf(stderr, 935Q_( 936/* The singular version */ 937"If you want to keep it by creating a new branch, " 938"this may be a good time\nto do so with:\n\n" 939" git branch <new-branch-name>%s\n\n", 940/* The plural version */ 941"If you want to keep them by creating a new branch, " 942"this may be a good time\nto do so with:\n\n" 943" git branch <new-branch-name>%s\n\n", 944/* Give ngettext() the count */ 945 lost), 946find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 947} 948 949/* 950 * We are about to leave commit that was at the tip of a detached 951 * HEAD. If it is not reachable from any ref, this is the last chance 952 * for the user to do so without resorting to reflog. 953 */ 954static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 955{ 956struct rev_info revs; 957struct object *object = &old_commit->object; 958 959repo_init_revisions(the_repository, &revs, NULL); 960setup_revisions(0, NULL, &revs, NULL); 961 962 object->flags &= ~UNINTERESTING; 963add_pending_object(&revs, object,oid_to_hex(&object->oid)); 964 965for_each_ref(add_pending_uninteresting_ref, &revs); 966if(new_commit) 967add_pending_oid(&revs,"HEAD", 968&new_commit->object.oid, 969 UNINTERESTING); 970 971if(prepare_revision_walk(&revs)) 972die(_("internal error in revision walk")); 973if(!(old_commit->object.flags & UNINTERESTING)) 974suggest_reattach(old_commit, &revs); 975else 976describe_detached_head(_("Previous HEAD position was"), old_commit); 977 978/* Clean up objects used, as they will be reused. */ 979clear_commit_marks_all(ALL_REV_FLAGS); 980} 981 982static intswitch_branches(const struct checkout_opts *opts, 983struct branch_info *new_branch_info) 984{ 985int ret =0; 986struct branch_info old_branch_info; 987void*path_to_free; 988struct object_id rev; 989int flag, writeout_error =0; 990int do_merge =1; 991 992trace2_cmd_mode("branch"); 993 994memset(&old_branch_info,0,sizeof(old_branch_info)); 995 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag); 996if(old_branch_info.path) 997 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1); 998if(!(flag & REF_ISSYMREF)) 999 old_branch_info.path = NULL;10001001if(old_branch_info.path)1002skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name);10031004if(opts->new_orphan_branch && opts->orphan_from_empty_tree) {1005if(new_branch_info->name)1006BUG("'switch --orphan' should never accept a commit as starting point");1007 new_branch_info->commit = NULL;1008 new_branch_info->name ="(empty)";1009 do_merge =1;1010}10111012if(!new_branch_info->name) {1013 new_branch_info->name ="HEAD";1014 new_branch_info->commit = old_branch_info.commit;1015if(!new_branch_info->commit)1016die(_("You are on a branch yet to be born"));1017parse_commit_or_die(new_branch_info->commit);10181019if(opts->only_merge_on_switching_branches)1020 do_merge =0;1021}10221023if(do_merge) {1024 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);1025if(ret) {1026free(path_to_free);1027return ret;1028}1029}10301031if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)1032orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);10331034update_refs_for_switch(opts, &old_branch_info, new_branch_info);10351036 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1);1037free(path_to_free);1038return ret || writeout_error;1039}10401041static intgit_checkout_config(const char*var,const char*value,void*cb)1042{1043if(!strcmp(var,"diff.ignoresubmodules")) {1044struct checkout_opts *opts = cb;1045handle_ignore_submodules_arg(&opts->diff_options, value);1046return0;1047}10481049if(starts_with(var,"submodule."))1050returngit_default_submodule_config(var, value, NULL);10511052returngit_xmerge_config(var, value, NULL);1053}10541055static voidsetup_new_branch_info_and_source_tree(1056struct branch_info *new_branch_info,1057struct checkout_opts *opts,1058struct object_id *rev,1059const char*arg)1060{1061struct tree **source_tree = &opts->source_tree;1062struct object_id branch_rev;10631064 new_branch_info->name = arg;1065setup_branch_path(new_branch_info);10661067if(!check_refname_format(new_branch_info->path,0) &&1068!read_ref(new_branch_info->path, &branch_rev))1069oidcpy(rev, &branch_rev);1070else1071 new_branch_info->path = NULL;/* not an existing branch */10721073 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1074if(!new_branch_info->commit) {1075/* not a commit */1076*source_tree =parse_tree_indirect(rev);1077}else{1078parse_commit_or_die(new_branch_info->commit);1079*source_tree =get_commit_tree(new_branch_info->commit);1080}1081}10821083static intparse_branchname_arg(int argc,const char**argv,1084int dwim_new_local_branch_ok,1085struct branch_info *new_branch_info,1086struct checkout_opts *opts,1087struct object_id *rev,1088int*dwim_remotes_matched)1089{1090const char**new_branch = &opts->new_branch;1091int argcount =0;1092const char*arg;1093int dash_dash_pos;1094int has_dash_dash =0;1095int i;10961097/*1098 * case 1: git checkout <ref> -- [<paths>]1099 *1100 * <ref> must be a valid tree, everything after the '--' must be1101 * a path.1102 *1103 * case 2: git checkout -- [<paths>]1104 *1105 * everything after the '--' must be paths.1106 *1107 * case 3: git checkout <something> [--]1108 *1109 * (a) If <something> is a commit, that is to1110 * switch to the branch or detach HEAD at it. As a special case,1111 * if <something> is A...B (missing A or B means HEAD but you can1112 * omit at most one side), and if there is a unique merge base1113 * between A and B, A...B names that merge base.1114 *1115 * (b) If <something> is _not_ a commit, either "--" is present1116 * or <something> is not a path, no -t or -b was given, and1117 * and there is a tracking branch whose name is <something>1118 * in one and only one remote (or if the branch exists on the1119 * remote named in checkout.defaultRemote), then this is a1120 * short-hand to fork local <something> from that1121 * remote-tracking branch.1122 *1123 * (c) Otherwise, if "--" is present, treat it like case (1).1124 *1125 * (d) Otherwise :1126 * - if it's a reference, treat it like case (1)1127 * - else if it's a path, treat it like case (2)1128 * - else: fail.1129 *1130 * case 4: git checkout <something> <paths>1131 *1132 * The first argument must not be ambiguous.1133 * - If it's *only* a reference, treat it like case (1).1134 * - If it's only a path, treat it like case (2).1135 * - else: fail.1136 *1137 */1138if(!argc)1139return0;11401141if(!opts->accept_pathspec) {1142if(argc >1)1143die(_("only one reference expected"));1144 has_dash_dash =1;/* helps disambiguate */1145}11461147 arg = argv[0];1148 dash_dash_pos = -1;1149for(i =0; i < argc; i++) {1150if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1151 dash_dash_pos = i;1152break;1153}1154}1155if(dash_dash_pos ==0)1156return1;/* case (2) */1157else if(dash_dash_pos ==1)1158 has_dash_dash =1;/* case (3) or (1) */1159else if(dash_dash_pos >=2)1160die(_("only one reference expected,%dgiven."), dash_dash_pos);1161 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;11621163if(!strcmp(arg,"-"))1164 arg ="@{-1}";11651166if(get_oid_mb(arg, rev)) {1167/*1168 * Either case (3) or (4), with <something> not being1169 * a commit, or an attempt to use case (1) with an1170 * invalid ref.1171 *1172 * It's likely an error, but we need to find out if1173 * we should auto-create the branch, case (3).(b).1174 */1175int recover_with_dwim = dwim_new_local_branch_ok;11761177int could_be_checkout_paths = !has_dash_dash &&1178check_filename(opts->prefix, arg);11791180if(!has_dash_dash && !no_wildcard(arg))1181 recover_with_dwim =0;11821183/*1184 * Accept "git checkout foo", "git checkout foo --"1185 * and "git switch foo" as candidates for dwim.1186 */1187if(!(argc ==1&& !has_dash_dash) &&1188!(argc ==2&& has_dash_dash) &&1189 opts->accept_pathspec)1190 recover_with_dwim =0;11911192if(recover_with_dwim) {1193const char*remote =unique_tracking_name(arg, rev,1194 dwim_remotes_matched);1195if(remote) {1196if(could_be_checkout_paths)1197die(_("'%s' could be both a local file and a tracking branch.\n"1198"Please use -- (and optionally --no-guess) to disambiguate"),1199 arg);1200*new_branch = arg;1201 arg = remote;1202/* DWIMmed to create local branch, case (3).(b) */1203}else{1204 recover_with_dwim =0;1205}1206}12071208if(!recover_with_dwim) {1209if(has_dash_dash)1210die(_("invalid reference:%s"), arg);1211return argcount;1212}1213}12141215/* we can't end up being in (2) anymore, eat the argument */1216 argcount++;1217 argv++;1218 argc--;12191220setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);12211222if(!opts->source_tree)/* case (1): want a tree */1223die(_("reference is not a tree:%s"), arg);12241225if(!has_dash_dash) {/* case (3).(d) -> (1) */1226/*1227 * Do not complain the most common case1228 * git checkout branch1229 * even if there happen to be a file called 'branch';1230 * it would be extremely annoying.1231 */1232if(argc)1233verify_non_filename(opts->prefix, arg);1234}else if(opts->accept_pathspec) {1235 argcount++;1236 argv++;1237 argc--;1238}12391240return argcount;1241}12421243static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1244{1245int status;1246struct strbuf branch_ref = STRBUF_INIT;12471248trace2_cmd_mode("unborn");12491250if(!opts->new_branch)1251die(_("You are on a branch yet to be born"));1252strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1253 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1254strbuf_release(&branch_ref);1255if(!opts->quiet)1256fprintf(stderr,_("Switched to a new branch '%s'\n"),1257 opts->new_branch);1258return status;1259}12601261static voiddie_expecting_a_branch(const struct branch_info *branch_info)1262{1263struct object_id oid;1264char*to_free;12651266if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1267const char*ref = to_free;12681269if(skip_prefix(ref,"refs/tags/", &ref))1270die(_("a branch is expected, got tag '%s'"), ref);1271if(skip_prefix(ref,"refs/remotes/", &ref))1272die(_("a branch is expected, got remote branch '%s'"), ref);1273die(_("a branch is expected, got '%s'"), ref);1274}1275if(branch_info->commit)1276die(_("a branch is expected, got commit '%s'"), branch_info->name);1277/*1278 * This case should never happen because we already die() on1279 * non-commit, but just in case.1280 */1281die(_("a branch is expected, got '%s'"), branch_info->name);1282}12831284static voiddie_if_some_operation_in_progress(void)1285{1286struct wt_status_state state;12871288memset(&state,0,sizeof(state));1289wt_status_get_state(the_repository, &state,0);12901291if(state.merge_in_progress)1292die(_("cannot switch branch while merging\n"1293"Consider\"git merge --quit\""1294"or\"git worktree add\"."));1295if(state.am_in_progress)1296die(_("cannot switch branch in the middle of an am session\n"1297"Consider\"git am --quit\""1298"or\"git worktree add\"."));1299if(state.rebase_interactive_in_progress || state.rebase_in_progress)1300die(_("cannot switch branch while rebasing\n"1301"Consider\"git rebase --quit\""1302"or\"git worktree add\"."));1303if(state.cherry_pick_in_progress)1304die(_("cannot switch branch while cherry-picking\n"1305"Consider\"git cherry-pick --quit\""1306"or\"git worktree add\"."));1307if(state.revert_in_progress)1308die(_("cannot switch branch while reverting\n"1309"Consider\"git revert --quit\""1310"or\"git worktree add\"."));1311if(state.bisect_in_progress)1312die(_("cannot switch branch while bisecting\n"1313"Consider\"git bisect reset HEAD\""1314"or\"git worktree add\"."));1315}13161317static intcheckout_branch(struct checkout_opts *opts,1318struct branch_info *new_branch_info)1319{1320if(opts->pathspec.nr)1321die(_("paths cannot be used with switching branches"));13221323if(opts->patch_mode)1324die(_("'%s' cannot be used with switching branches"),1325"--patch");13261327if(opts->overlay_mode != -1)1328die(_("'%s' cannot be used with switching branches"),1329"--[no]-overlay");13301331if(opts->writeout_stage)1332die(_("'%s' cannot be used with switching branches"),1333"--ours/--theirs");13341335if(opts->force && opts->merge)1336die(_("'%s' cannot be used with '%s'"),"-f","-m");13371338if(opts->discard_changes && opts->merge)1339die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");13401341if(opts->force_detach && opts->new_branch)1342die(_("'%s' cannot be used with '%s'"),1343"--detach","-b/-B/--orphan");13441345if(opts->new_orphan_branch) {1346if(opts->track != BRANCH_TRACK_UNSPECIFIED)1347die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1348if(opts->orphan_from_empty_tree && new_branch_info->name)1349die(_("'%s' cannot take <start-point>"),"--orphan");1350}else if(opts->force_detach) {1351if(opts->track != BRANCH_TRACK_UNSPECIFIED)1352die(_("'%s' cannot be used with '%s'"),"--detach","-t");1353}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1354 opts->track = git_branch_track;13551356if(new_branch_info->name && !new_branch_info->commit)1357die(_("Cannot switch branch to a non-commit '%s'"),1358 new_branch_info->name);13591360if(!opts->switch_branch_doing_nothing_is_ok &&1361!new_branch_info->name &&1362!opts->new_branch &&1363!opts->force_detach)1364die(_("missing branch or commit argument"));13651366if(!opts->implicit_detach &&1367!opts->force_detach &&1368!opts->new_branch &&1369!opts->new_branch_force &&1370 new_branch_info->name &&1371!new_branch_info->path)1372die_expecting_a_branch(new_branch_info);13731374if(!opts->can_switch_when_in_progress)1375die_if_some_operation_in_progress();13761377if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1378!opts->ignore_other_worktrees) {1379int flag;1380char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1381if(head_ref &&1382(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1383die_if_checked_out(new_branch_info->path,1);1384free(head_ref);1385}13861387if(!new_branch_info->commit && opts->new_branch) {1388struct object_id rev;1389int flag;13901391if(!read_ref_full("HEAD",0, &rev, &flag) &&1392(flag & REF_ISSYMREF) &&is_null_oid(&rev))1393returnswitch_unborn_to_new_branch(opts);1394}1395returnswitch_branches(opts, new_branch_info);1396}13971398static struct option *add_common_options(struct checkout_opts *opts,1399struct option *prevopts)1400{1401struct option options[] = {1402OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1403{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1404"checkout","control recursive updating of submodules",1405 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1406OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1407OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1408 PARSE_OPT_NOCOMPLETE),1409OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1410OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1411N_("conflict style (merge or diff3)")),1412OPT_END()1413};1414struct option *newopts =parse_options_concat(prevopts, options);1415free(prevopts);1416return newopts;1417}14181419static struct option *add_common_switch_branch_options(1420struct checkout_opts *opts,struct option *prevopts)1421{1422struct option options[] = {1423OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1424OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1425 BRANCH_TRACK_EXPLICIT),1426OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1427OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1428N_("update ignored files (default)"),1429 PARSE_OPT_NOCOMPLETE),1430OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1431N_("do not check if another worktree is holding the given ref")),1432OPT_END()1433};1434struct option *newopts =parse_options_concat(prevopts, options);1435free(prevopts);1436return newopts;1437}14381439static struct option *add_checkout_path_options(struct checkout_opts *opts,1440struct option *prevopts)1441{1442struct option options[] = {1443OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1444N_("checkout our version for unmerged files"),14452, PARSE_OPT_NONEG),1446OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1447N_("checkout their version for unmerged files"),14483, PARSE_OPT_NONEG),1449OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1450OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1451N_("do not limit pathspecs to sparse entries only")),1452OPT_END()1453};1454struct option *newopts =parse_options_concat(prevopts, options);1455free(prevopts);1456return newopts;1457}14581459static intcheckout_main(int argc,const char**argv,const char*prefix,1460struct checkout_opts *opts,struct option *options,1461const char*const usagestr[])1462{1463struct branch_info new_branch_info;1464int dwim_remotes_matched =0;1465int parseopt_flags =0;14661467memset(&new_branch_info,0,sizeof(new_branch_info));1468 opts->overwrite_ignore =1;1469 opts->prefix = prefix;1470 opts->show_progress = -1;14711472git_config(git_checkout_config, opts);14731474 opts->track = BRANCH_TRACK_UNSPECIFIED;14751476if(!opts->accept_pathspec && !opts->accept_ref)1477BUG("make up your mind, you need to take _something_");1478if(opts->accept_pathspec && opts->accept_ref)1479 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;14801481 argc =parse_options(argc, argv, prefix, options,1482 usagestr, parseopt_flags);14831484if(opts->show_progress <0) {1485if(opts->quiet)1486 opts->show_progress =0;1487else1488 opts->show_progress =isatty(2);1489}14901491if(opts->conflict_style) {1492 opts->merge =1;/* implied */1493git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1494}1495if(opts->force)1496 opts->discard_changes =1;14971498if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1499die(_("-b, -B and --orphan are mutually exclusive"));15001501if(opts->overlay_mode ==1&& opts->patch_mode)1502die(_("-p and --overlay are mutually exclusive"));15031504if(opts->checkout_index >=0|| opts->checkout_worktree >=0) {1505if(opts->checkout_index <0)1506 opts->checkout_index =0;1507if(opts->checkout_worktree <0)1508 opts->checkout_worktree =0;1509}else{1510if(opts->checkout_index <0)1511 opts->checkout_index = -opts->checkout_index -1;1512if(opts->checkout_worktree <0)1513 opts->checkout_worktree = -opts->checkout_worktree -1;1514}1515if(opts->checkout_index <0|| opts->checkout_worktree <0)1516BUG("these flags should be non-negative by now");15171518/*1519 * From here on, new_branch will contain the branch to be checked out,1520 * and new_branch_force and new_orphan_branch will tell us which one of1521 * -b/-B/--orphan is being used.1522 */1523if(opts->new_branch_force)1524 opts->new_branch = opts->new_branch_force;15251526if(opts->new_orphan_branch)1527 opts->new_branch = opts->new_orphan_branch;15281529/* --track without -b/-B/--orphan should DWIM */1530if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1531const char*argv0 = argv[0];1532if(!argc || !strcmp(argv0,"--"))1533die(_("--track needs a branch name"));1534skip_prefix(argv0,"refs/", &argv0);1535skip_prefix(argv0,"remotes/", &argv0);1536 argv0 =strchr(argv0,'/');1537if(!argv0 || !argv0[1])1538die(_("missing branch name; try -b"));1539 opts->new_branch = argv0 +1;1540}15411542/*1543 * Extract branch name from command line arguments, so1544 * all that is left is pathspecs.1545 *1546 * Handle1547 *1548 * 1) git checkout <tree> -- [<paths>]1549 * 2) git checkout -- [<paths>]1550 * 3) git checkout <something> [<paths>]1551 *1552 * including "last branch" syntax and DWIM-ery for names of1553 * remote branches, erroring out for invalid or ambiguous cases.1554 */1555if(argc && opts->accept_ref) {1556struct object_id rev;1557int dwim_ok =1558!opts->patch_mode &&1559 opts->dwim_new_local_branch &&1560 opts->track == BRANCH_TRACK_UNSPECIFIED &&1561!opts->new_branch;1562int n =parse_branchname_arg(argc, argv, dwim_ok,1563&new_branch_info, opts, &rev,1564&dwim_remotes_matched);1565 argv += n;1566 argc -= n;1567}else if(!opts->accept_ref && opts->from_treeish) {1568struct object_id rev;15691570if(get_oid_mb(opts->from_treeish, &rev))1571die(_("could not resolve%s"), opts->from_treeish);15721573setup_new_branch_info_and_source_tree(&new_branch_info,1574 opts, &rev,1575 opts->from_treeish);15761577if(!opts->source_tree)1578die(_("reference is not a tree:%s"), opts->from_treeish);1579}15801581if(opts->accept_pathspec && !opts->empty_pathspec_ok && !argc &&1582!opts->patch_mode)/* patch mode is special */1583die(_("you must specify path(s) to restore"));15841585if(argc) {1586parse_pathspec(&opts->pathspec,0,1587 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1588 prefix, argv);15891590if(!opts->pathspec.nr)1591die(_("invalid path specification"));15921593/*1594 * Try to give more helpful suggestion.1595 * new_branch && argc > 1 will be caught later.1596 */1597if(opts->new_branch && argc ==1)1598die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1599 argv[0], opts->new_branch);16001601if(opts->force_detach)1602die(_("git checkout: --detach does not take a path argument '%s'"),1603 argv[0]);16041605if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1606die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1607"checking out of the index."));1608}16091610if(opts->new_branch) {1611struct strbuf buf = STRBUF_INIT;16121613if(opts->new_branch_force)1614 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1615else1616 opts->branch_exists =1617validate_new_branchname(opts->new_branch, &buf,0);1618strbuf_release(&buf);1619}16201621UNLEAK(opts);1622if(opts->patch_mode || opts->pathspec.nr) {1623int ret =checkout_paths(opts, new_branch_info.name);1624if(ret && dwim_remotes_matched >1&&1625 advice_checkout_ambiguous_remote_branch_name)1626advise(_("'%s' matched more than one remote tracking branch.\n"1627"We found%dremotes with a reference that matched. So we fell back\n"1628"on trying to resolve the argument as a path, but failed there too!\n"1629"\n"1630"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1631"you can do so by fully qualifying the name with the --track option:\n"1632"\n"1633" git checkout --track origin/<name>\n"1634"\n"1635"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1636"one remote, e.g. the 'origin' remote, consider setting\n"1637"checkout.defaultRemote=origin in your config."),1638 argv[0],1639 dwim_remotes_matched);1640return ret;1641}else{1642returncheckout_branch(opts, &new_branch_info);1643}1644}16451646intcmd_checkout(int argc,const char**argv,const char*prefix)1647{1648struct checkout_opts opts;1649struct option *options;1650struct option checkout_options[] = {1651OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1652N_("create and checkout a new branch")),1653OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1654N_("create/reset and checkout a branch")),1655OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1656OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1657N_("second guess 'git checkout <no-such-branch>' (default)")),1658OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode (default)")),1659OPT_END()1660};1661int ret;16621663memset(&opts,0,sizeof(opts));1664 opts.dwim_new_local_branch =1;1665 opts.switch_branch_doing_nothing_is_ok =1;1666 opts.only_merge_on_switching_branches =0;1667 opts.accept_ref =1;1668 opts.accept_pathspec =1;1669 opts.implicit_detach =1;1670 opts.can_switch_when_in_progress =1;1671 opts.orphan_from_empty_tree =0;1672 opts.empty_pathspec_ok =1;1673 opts.overlay_mode = -1;1674 opts.checkout_index = -2;/* default on */1675 opts.checkout_worktree = -2;/* default on */16761677 options =parse_options_dup(checkout_options);1678 options =add_common_options(&opts, options);1679 options =add_common_switch_branch_options(&opts, options);1680 options =add_checkout_path_options(&opts, options);16811682 ret =checkout_main(argc, argv, prefix, &opts,1683 options, checkout_usage);1684FREE_AND_NULL(options);1685return ret;1686}16871688intcmd_switch(int argc,const char**argv,const char*prefix)1689{1690struct checkout_opts opts;1691struct option *options = NULL;1692struct option switch_options[] = {1693OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1694N_("create and switch to a new branch")),1695OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1696N_("create/reset and switch to a branch")),1697OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1698N_("second guess 'git switch <no-such-branch>'")),1699OPT_BOOL(0,"discard-changes", &opts.discard_changes,1700N_("throw away local modifications")),1701OPT_END()1702};1703int ret;17041705memset(&opts,0,sizeof(opts));1706 opts.dwim_new_local_branch =1;1707 opts.accept_ref =1;1708 opts.accept_pathspec =0;1709 opts.switch_branch_doing_nothing_is_ok =0;1710 opts.only_merge_on_switching_branches =1;1711 opts.implicit_detach =0;1712 opts.can_switch_when_in_progress =0;1713 opts.orphan_from_empty_tree =1;1714 opts.overlay_mode = -1;17151716 options =parse_options_dup(switch_options);1717 options =add_common_options(&opts, options);1718 options =add_common_switch_branch_options(&opts, options);17191720 ret =checkout_main(argc, argv, prefix, &opts,1721 options, switch_branch_usage);1722FREE_AND_NULL(options);1723return ret;1724}17251726intcmd_restore(int argc,const char**argv,const char*prefix)1727{1728struct checkout_opts opts;1729struct option *options;1730struct option restore_options[] = {1731OPT_STRING('s',"source", &opts.from_treeish,"<tree-ish>",1732N_("where the checkout from")),1733OPT_BOOL('S',"staged", &opts.checkout_index,1734N_("restore the index")),1735OPT_BOOL('W',"worktree", &opts.checkout_worktree,1736N_("restore the working tree (default)")),1737OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode")),1738OPT_END()1739};1740int ret;17411742memset(&opts,0,sizeof(opts));1743 opts.accept_ref =0;1744 opts.accept_pathspec =1;1745 opts.empty_pathspec_ok =0;1746 opts.overlay_mode =0;1747 opts.checkout_index = -1;/* default off */1748 opts.checkout_worktree = -2;/* default on */17491750 options =parse_options_dup(restore_options);1751 options =add_common_options(&opts, options);1752 options =add_checkout_path_options(&opts, options);17531754 ret =checkout_main(argc, argv, prefix, &opts,1755 options, restore_usage);1756FREE_AND_NULL(options);1757return ret;1758}