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->checkout_index && !opts->checkout_worktree && 437 opts->writeout_stage) 438die(_("'%s' or '%s' cannot be used with%s"), 439"--ours","--theirs","--staged"); 440 441if(opts->checkout_index && !opts->checkout_worktree && 442 opts->merge) 443die(_("'%s' or '%s' cannot be used with%s"), 444"--merge","--conflict","--staged"); 445 446if(opts->patch_mode) { 447const char*patch_mode; 448 449if(opts->checkout_index && opts->checkout_worktree) 450 patch_mode ="--patch=checkout"; 451else if(opts->checkout_index && !opts->checkout_worktree) 452 patch_mode ="--patch=reset"; 453else 454die(_("'%s' with only '%s' is not currently supported"), 455"--patch","--worktree"); 456returnrun_add_interactive(revision, patch_mode, &opts->pathspec); 457} 458 459repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 460if(read_cache_preload(&opts->pathspec) <0) 461returnerror(_("index file corrupt")); 462 463if(opts->source_tree) 464read_tree_some(opts->source_tree, &opts->pathspec); 465 466 ps_matched =xcalloc(opts->pathspec.nr,1); 467 468/* 469 * Make sure all pathspecs participated in locating the paths 470 * to be checked out. 471 */ 472for(pos =0; pos < active_nr; pos++) 473if(opts->overlay_mode) 474mark_ce_for_checkout_overlay(active_cache[pos], 475 ps_matched, 476 opts); 477else 478mark_ce_for_checkout_no_overlay(active_cache[pos], 479 ps_matched, 480 opts); 481 482if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 483free(ps_matched); 484return1; 485} 486free(ps_matched); 487 488/* "checkout -m path" to recreate conflicted state */ 489if(opts->merge) 490unmerge_marked_index(&the_index); 491 492/* Any unmerged paths? */ 493for(pos =0; pos < active_nr; pos++) { 494const struct cache_entry *ce = active_cache[pos]; 495if(ce->ce_flags & CE_MATCHED) { 496if(!ce_stage(ce)) 497continue; 498if(opts->force) { 499warning(_("path '%s' is unmerged"), ce->name); 500}else if(opts->writeout_stage) { 501 errs |=check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 502}else if(opts->merge) { 503 errs |=check_stages((1<<2) | (1<<3), ce, pos); 504}else{ 505 errs =1; 506error(_("path '%s' is unmerged"), ce->name); 507} 508 pos =skip_same_name(ce, pos) -1; 509} 510} 511if(errs) 512return1; 513 514/* Now we are committed to check them out */ 515if(opts->checkout_worktree) 516 errs |=checkout_worktree(opts); 517 518/* 519 * Allow updating the index when checking out from the index. 520 * This is to save new stat info. 521 */ 522if(opts->checkout_worktree && !opts->checkout_index && !opts->source_tree) 523 checkout_index =1; 524else 525 checkout_index = opts->checkout_index; 526 527if(checkout_index) { 528if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 529die(_("unable to write new index file")); 530}else{ 531/* 532 * NEEDSWORK: if --worktree is not specified, we 533 * should save stat info of checked out files in the 534 * index to avoid the next (potentially costly) 535 * refresh. But it's a bit tricker to do... 536 */ 537rollback_lock_file(&lock_file); 538} 539 540read_ref_full("HEAD",0, &rev, NULL); 541 head =lookup_commit_reference_gently(the_repository, &rev,1); 542 543 errs |=post_checkout_hook(head, head,0); 544return errs; 545} 546 547static voidshow_local_changes(struct object *head, 548const struct diff_options *opts) 549{ 550struct rev_info rev; 551/* I think we want full paths, even if we're in a subdirectory. */ 552repo_init_revisions(the_repository, &rev, NULL); 553 rev.diffopt.flags = opts->flags; 554 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 555diff_setup_done(&rev.diffopt); 556add_pending_object(&rev, head, NULL); 557run_diff_index(&rev,0); 558} 559 560static voiddescribe_detached_head(const char*msg,struct commit *commit) 561{ 562struct strbuf sb = STRBUF_INIT; 563 564if(!parse_commit(commit)) 565pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 566if(print_sha1_ellipsis()) { 567fprintf(stderr,"%s %s...%s\n", msg, 568find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 569}else{ 570fprintf(stderr,"%s %s %s\n", msg, 571find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 572} 573strbuf_release(&sb); 574} 575 576static intreset_tree(struct tree *tree,const struct checkout_opts *o, 577int worktree,int*writeout_error) 578{ 579struct unpack_trees_options opts; 580struct tree_desc tree_desc; 581 582memset(&opts,0,sizeof(opts)); 583 opts.head_idx = -1; 584 opts.update = worktree; 585 opts.skip_unmerged = !worktree; 586 opts.reset =1; 587 opts.merge =1; 588 opts.fn = oneway_merge; 589 opts.verbose_update = o->show_progress; 590 opts.src_index = &the_index; 591 opts.dst_index = &the_index; 592parse_tree(tree); 593init_tree_desc(&tree_desc, tree->buffer, tree->size); 594switch(unpack_trees(1, &tree_desc, &opts)) { 595case-2: 596*writeout_error =1; 597/* 598 * We return 0 nevertheless, as the index is all right 599 * and more importantly we have made best efforts to 600 * update paths in the work tree, and we cannot revert 601 * them. 602 */ 603/* fallthrough */ 604case0: 605return0; 606default: 607return128; 608} 609} 610 611struct branch_info { 612const char*name;/* The short name used */ 613const char*path;/* The full name of a real branch */ 614struct commit *commit;/* The named commit */ 615/* 616 * if not null the branch is detached because it's already 617 * checked out in this checkout 618 */ 619char*checkout; 620}; 621 622static voidsetup_branch_path(struct branch_info *branch) 623{ 624struct strbuf buf = STRBUF_INIT; 625 626strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 627if(strcmp(buf.buf, branch->name)) 628 branch->name =xstrdup(buf.buf); 629strbuf_splice(&buf,0,0,"refs/heads/",11); 630 branch->path =strbuf_detach(&buf, NULL); 631} 632 633static intmerge_working_tree(const struct checkout_opts *opts, 634struct branch_info *old_branch_info, 635struct branch_info *new_branch_info, 636int*writeout_error) 637{ 638int ret; 639struct lock_file lock_file = LOCK_INIT; 640struct tree *new_tree; 641 642hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 643if(read_cache_preload(NULL) <0) 644returnerror(_("index file corrupt")); 645 646resolve_undo_clear(); 647if(opts->new_orphan_branch && opts->orphan_from_empty_tree) { 648if(new_branch_info->commit) 649BUG("'switch --orphan' should never accept a commit as starting point"); 650 new_tree =parse_tree_indirect(the_hash_algo->empty_tree); 651}else 652 new_tree =get_commit_tree(new_branch_info->commit); 653if(opts->discard_changes) { 654 ret =reset_tree(new_tree, opts,1, writeout_error); 655if(ret) 656return ret; 657}else{ 658struct tree_desc trees[2]; 659struct tree *tree; 660struct unpack_trees_options topts; 661 662memset(&topts,0,sizeof(topts)); 663 topts.head_idx = -1; 664 topts.src_index = &the_index; 665 topts.dst_index = &the_index; 666 667setup_unpack_trees_porcelain(&topts,"checkout"); 668 669refresh_cache(REFRESH_QUIET); 670 671if(unmerged_cache()) { 672error(_("you need to resolve your current index first")); 673return1; 674} 675 676/* 2-way merge to the new branch */ 677 topts.initial_checkout =is_cache_unborn(); 678 topts.update =1; 679 topts.merge =1; 680 topts.gently = opts->merge && old_branch_info->commit; 681 topts.verbose_update = opts->show_progress; 682 topts.fn = twoway_merge; 683if(opts->overwrite_ignore) { 684 topts.dir =xcalloc(1,sizeof(*topts.dir)); 685 topts.dir->flags |= DIR_SHOW_IGNORED; 686setup_standard_excludes(topts.dir); 687} 688 tree =parse_tree_indirect(old_branch_info->commit ? 689&old_branch_info->commit->object.oid : 690 the_hash_algo->empty_tree); 691init_tree_desc(&trees[0], tree->buffer, tree->size); 692parse_tree(new_tree); 693 tree = new_tree; 694init_tree_desc(&trees[1], tree->buffer, tree->size); 695 696 ret =unpack_trees(2, trees, &topts); 697clear_unpack_trees_porcelain(&topts); 698if(ret == -1) { 699/* 700 * Unpack couldn't do a trivial merge; either 701 * give up or do a real merge, depending on 702 * whether the merge flag was used. 703 */ 704struct tree *result; 705struct tree *work; 706struct merge_options o; 707if(!opts->merge) 708return1; 709 710/* 711 * Without old_branch_info->commit, the below is the same as 712 * the two-tree unpack we already tried and failed. 713 */ 714if(!old_branch_info->commit) 715return1; 716 717/* Do more real merge */ 718 719/* 720 * We update the index fully, then write the 721 * tree from the index, then merge the new 722 * branch with the current tree, with the old 723 * branch as the base. Then we reset the index 724 * (but not the working tree) to the new 725 * branch, leaving the working tree as the 726 * merged version, but skipping unmerged 727 * entries in the index. 728 */ 729 730add_files_to_cache(NULL, NULL,0); 731/* 732 * NEEDSWORK: carrying over local changes 733 * when branches have different end-of-line 734 * normalization (or clean+smudge rules) is 735 * a pain; plumb in an option to set 736 * o.renormalize? 737 */ 738init_merge_options(&o, the_repository); 739 o.verbosity =0; 740 work =write_tree_from_memory(&o); 741 742 ret =reset_tree(new_tree, 743 opts,1, 744 writeout_error); 745if(ret) 746return ret; 747 o.ancestor = old_branch_info->name; 748 o.branch1 = new_branch_info->name; 749 o.branch2 ="local"; 750 ret =merge_trees(&o, 751 new_tree, 752 work, 753get_commit_tree(old_branch_info->commit), 754&result); 755if(ret <0) 756exit(128); 757 ret =reset_tree(new_tree, 758 opts,0, 759 writeout_error); 760strbuf_release(&o.obuf); 761if(ret) 762return ret; 763} 764} 765 766if(!active_cache_tree) 767 active_cache_tree =cache_tree(); 768 769if(!cache_tree_fully_valid(active_cache_tree)) 770cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 771 772if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 773die(_("unable to write new index file")); 774 775if(!opts->discard_changes && !opts->quiet && new_branch_info->commit) 776show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 777 778return0; 779} 780 781static voidreport_tracking(struct branch_info *new_branch_info) 782{ 783struct strbuf sb = STRBUF_INIT; 784struct branch *branch =branch_get(new_branch_info->name); 785 786if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 787return; 788fputs(sb.buf, stdout); 789strbuf_release(&sb); 790} 791 792static voidupdate_refs_for_switch(const struct checkout_opts *opts, 793struct branch_info *old_branch_info, 794struct branch_info *new_branch_info) 795{ 796struct strbuf msg = STRBUF_INIT; 797const char*old_desc, *reflog_msg; 798if(opts->new_branch) { 799if(opts->new_orphan_branch) { 800char*refname; 801 802 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 803if(opts->new_branch_log && 804!should_autocreate_reflog(refname)) { 805int ret; 806struct strbuf err = STRBUF_INIT; 807 808 ret =safe_create_reflog(refname,1, &err); 809if(ret) { 810fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 811 opts->new_orphan_branch, err.buf); 812strbuf_release(&err); 813free(refname); 814return; 815} 816strbuf_release(&err); 817} 818free(refname); 819} 820else 821create_branch(the_repository, 822 opts->new_branch, new_branch_info->name, 823 opts->new_branch_force ?1:0, 824 opts->new_branch_force ?1:0, 825 opts->new_branch_log, 826 opts->quiet, 827 opts->track); 828 new_branch_info->name = opts->new_branch; 829setup_branch_path(new_branch_info); 830} 831 832 old_desc = old_branch_info->name; 833if(!old_desc && old_branch_info->commit) 834 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 835 836 reflog_msg =getenv("GIT_REFLOG_ACTION"); 837if(!reflog_msg) 838strbuf_addf(&msg,"checkout: moving from%sto%s", 839 old_desc ? old_desc :"(invalid)", new_branch_info->name); 840else 841strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 842 843if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 844/* Nothing to do. */ 845}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 846update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 847 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 848if(!opts->quiet) { 849if(old_branch_info->path && 850 advice_detached_head && !opts->force_detach) 851detach_advice(new_branch_info->name); 852describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 853} 854}else if(new_branch_info->path) {/* Switch branches. */ 855if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 856die(_("unable to update HEAD")); 857if(!opts->quiet) { 858if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 859if(opts->new_branch_force) 860fprintf(stderr,_("Reset branch '%s'\n"), 861 new_branch_info->name); 862else 863fprintf(stderr,_("Already on '%s'\n"), 864 new_branch_info->name); 865}else if(opts->new_branch) { 866if(opts->branch_exists) 867fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 868else 869fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 870}else{ 871fprintf(stderr,_("Switched to branch '%s'\n"), 872 new_branch_info->name); 873} 874} 875if(old_branch_info->path && old_branch_info->name) { 876if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 877delete_reflog(old_branch_info->path); 878} 879} 880remove_branch_state(the_repository, !opts->quiet); 881strbuf_release(&msg); 882if(!opts->quiet && 883(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 884report_tracking(new_branch_info); 885} 886 887static intadd_pending_uninteresting_ref(const char*refname, 888const struct object_id *oid, 889int flags,void*cb_data) 890{ 891add_pending_oid(cb_data, refname, oid, UNINTERESTING); 892return0; 893} 894 895static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 896{ 897strbuf_addstr(sb," "); 898strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 899strbuf_addch(sb,' '); 900if(!parse_commit(commit)) 901pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 902strbuf_addch(sb,'\n'); 903} 904 905#define ORPHAN_CUTOFF 4 906static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 907{ 908struct commit *c, *last = NULL; 909struct strbuf sb = STRBUF_INIT; 910int lost =0; 911while((c =get_revision(revs)) != NULL) { 912if(lost < ORPHAN_CUTOFF) 913describe_one_orphan(&sb, c); 914 last = c; 915 lost++; 916} 917if(ORPHAN_CUTOFF < lost) { 918int more = lost - ORPHAN_CUTOFF; 919if(more ==1) 920describe_one_orphan(&sb, last); 921else 922strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 923} 924 925fprintf(stderr, 926Q_( 927/* The singular version */ 928"Warning: you are leaving%dcommit behind, " 929"not connected to\n" 930"any of your branches:\n\n" 931"%s\n", 932/* The plural version */ 933"Warning: you are leaving%dcommits behind, " 934"not connected to\n" 935"any of your branches:\n\n" 936"%s\n", 937/* Give ngettext() the count */ 938 lost), 939 lost, 940 sb.buf); 941strbuf_release(&sb); 942 943if(advice_detached_head) 944fprintf(stderr, 945Q_( 946/* The singular version */ 947"If you want to keep it by creating a new branch, " 948"this may be a good time\nto do so with:\n\n" 949" git branch <new-branch-name>%s\n\n", 950/* The plural version */ 951"If you want to keep them by creating a new branch, " 952"this may be a good time\nto do so with:\n\n" 953" git branch <new-branch-name>%s\n\n", 954/* Give ngettext() the count */ 955 lost), 956find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 957} 958 959/* 960 * We are about to leave commit that was at the tip of a detached 961 * HEAD. If it is not reachable from any ref, this is the last chance 962 * for the user to do so without resorting to reflog. 963 */ 964static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 965{ 966struct rev_info revs; 967struct object *object = &old_commit->object; 968 969repo_init_revisions(the_repository, &revs, NULL); 970setup_revisions(0, NULL, &revs, NULL); 971 972 object->flags &= ~UNINTERESTING; 973add_pending_object(&revs, object,oid_to_hex(&object->oid)); 974 975for_each_ref(add_pending_uninteresting_ref, &revs); 976if(new_commit) 977add_pending_oid(&revs,"HEAD", 978&new_commit->object.oid, 979 UNINTERESTING); 980 981if(prepare_revision_walk(&revs)) 982die(_("internal error in revision walk")); 983if(!(old_commit->object.flags & UNINTERESTING)) 984suggest_reattach(old_commit, &revs); 985else 986describe_detached_head(_("Previous HEAD position was"), old_commit); 987 988/* Clean up objects used, as they will be reused. */ 989clear_commit_marks_all(ALL_REV_FLAGS); 990} 991 992static intswitch_branches(const struct checkout_opts *opts, 993struct branch_info *new_branch_info) 994{ 995int ret =0; 996struct branch_info old_branch_info; 997void*path_to_free; 998struct object_id rev; 999int flag, writeout_error =0;1000int do_merge =1;10011002trace2_cmd_mode("branch");10031004memset(&old_branch_info,0,sizeof(old_branch_info));1005 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag);1006if(old_branch_info.path)1007 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1);1008if(!(flag & REF_ISSYMREF))1009 old_branch_info.path = NULL;10101011if(old_branch_info.path)1012skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name);10131014if(opts->new_orphan_branch && opts->orphan_from_empty_tree) {1015if(new_branch_info->name)1016BUG("'switch --orphan' should never accept a commit as starting point");1017 new_branch_info->commit = NULL;1018 new_branch_info->name ="(empty)";1019 do_merge =1;1020}10211022if(!new_branch_info->name) {1023 new_branch_info->name ="HEAD";1024 new_branch_info->commit = old_branch_info.commit;1025if(!new_branch_info->commit)1026die(_("You are on a branch yet to be born"));1027parse_commit_or_die(new_branch_info->commit);10281029if(opts->only_merge_on_switching_branches)1030 do_merge =0;1031}10321033if(do_merge) {1034 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);1035if(ret) {1036free(path_to_free);1037return ret;1038}1039}10401041if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)1042orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);10431044update_refs_for_switch(opts, &old_branch_info, new_branch_info);10451046 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1);1047free(path_to_free);1048return ret || writeout_error;1049}10501051static intgit_checkout_config(const char*var,const char*value,void*cb)1052{1053if(!strcmp(var,"diff.ignoresubmodules")) {1054struct checkout_opts *opts = cb;1055handle_ignore_submodules_arg(&opts->diff_options, value);1056return0;1057}10581059if(starts_with(var,"submodule."))1060returngit_default_submodule_config(var, value, NULL);10611062returngit_xmerge_config(var, value, NULL);1063}10641065static voidsetup_new_branch_info_and_source_tree(1066struct branch_info *new_branch_info,1067struct checkout_opts *opts,1068struct object_id *rev,1069const char*arg)1070{1071struct tree **source_tree = &opts->source_tree;1072struct object_id branch_rev;10731074 new_branch_info->name = arg;1075setup_branch_path(new_branch_info);10761077if(!check_refname_format(new_branch_info->path,0) &&1078!read_ref(new_branch_info->path, &branch_rev))1079oidcpy(rev, &branch_rev);1080else1081 new_branch_info->path = NULL;/* not an existing branch */10821083 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1084if(!new_branch_info->commit) {1085/* not a commit */1086*source_tree =parse_tree_indirect(rev);1087}else{1088parse_commit_or_die(new_branch_info->commit);1089*source_tree =get_commit_tree(new_branch_info->commit);1090}1091}10921093static intparse_branchname_arg(int argc,const char**argv,1094int dwim_new_local_branch_ok,1095struct branch_info *new_branch_info,1096struct checkout_opts *opts,1097struct object_id *rev,1098int*dwim_remotes_matched)1099{1100const char**new_branch = &opts->new_branch;1101int argcount =0;1102const char*arg;1103int dash_dash_pos;1104int has_dash_dash =0;1105int i;11061107/*1108 * case 1: git checkout <ref> -- [<paths>]1109 *1110 * <ref> must be a valid tree, everything after the '--' must be1111 * a path.1112 *1113 * case 2: git checkout -- [<paths>]1114 *1115 * everything after the '--' must be paths.1116 *1117 * case 3: git checkout <something> [--]1118 *1119 * (a) If <something> is a commit, that is to1120 * switch to the branch or detach HEAD at it. As a special case,1121 * if <something> is A...B (missing A or B means HEAD but you can1122 * omit at most one side), and if there is a unique merge base1123 * between A and B, A...B names that merge base.1124 *1125 * (b) If <something> is _not_ a commit, either "--" is present1126 * or <something> is not a path, no -t or -b was given, and1127 * and there is a tracking branch whose name is <something>1128 * in one and only one remote (or if the branch exists on the1129 * remote named in checkout.defaultRemote), then this is a1130 * short-hand to fork local <something> from that1131 * remote-tracking branch.1132 *1133 * (c) Otherwise, if "--" is present, treat it like case (1).1134 *1135 * (d) Otherwise :1136 * - if it's a reference, treat it like case (1)1137 * - else if it's a path, treat it like case (2)1138 * - else: fail.1139 *1140 * case 4: git checkout <something> <paths>1141 *1142 * The first argument must not be ambiguous.1143 * - If it's *only* a reference, treat it like case (1).1144 * - If it's only a path, treat it like case (2).1145 * - else: fail.1146 *1147 */1148if(!argc)1149return0;11501151if(!opts->accept_pathspec) {1152if(argc >1)1153die(_("only one reference expected"));1154 has_dash_dash =1;/* helps disambiguate */1155}11561157 arg = argv[0];1158 dash_dash_pos = -1;1159for(i =0; i < argc; i++) {1160if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1161 dash_dash_pos = i;1162break;1163}1164}1165if(dash_dash_pos ==0)1166return1;/* case (2) */1167else if(dash_dash_pos ==1)1168 has_dash_dash =1;/* case (3) or (1) */1169else if(dash_dash_pos >=2)1170die(_("only one reference expected,%dgiven."), dash_dash_pos);1171 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;11721173if(!strcmp(arg,"-"))1174 arg ="@{-1}";11751176if(get_oid_mb(arg, rev)) {1177/*1178 * Either case (3) or (4), with <something> not being1179 * a commit, or an attempt to use case (1) with an1180 * invalid ref.1181 *1182 * It's likely an error, but we need to find out if1183 * we should auto-create the branch, case (3).(b).1184 */1185int recover_with_dwim = dwim_new_local_branch_ok;11861187int could_be_checkout_paths = !has_dash_dash &&1188check_filename(opts->prefix, arg);11891190if(!has_dash_dash && !no_wildcard(arg))1191 recover_with_dwim =0;11921193/*1194 * Accept "git checkout foo", "git checkout foo --"1195 * and "git switch foo" as candidates for dwim.1196 */1197if(!(argc ==1&& !has_dash_dash) &&1198!(argc ==2&& has_dash_dash) &&1199 opts->accept_pathspec)1200 recover_with_dwim =0;12011202if(recover_with_dwim) {1203const char*remote =unique_tracking_name(arg, rev,1204 dwim_remotes_matched);1205if(remote) {1206if(could_be_checkout_paths)1207die(_("'%s' could be both a local file and a tracking branch.\n"1208"Please use -- (and optionally --no-guess) to disambiguate"),1209 arg);1210*new_branch = arg;1211 arg = remote;1212/* DWIMmed to create local branch, case (3).(b) */1213}else{1214 recover_with_dwim =0;1215}1216}12171218if(!recover_with_dwim) {1219if(has_dash_dash)1220die(_("invalid reference:%s"), arg);1221return argcount;1222}1223}12241225/* we can't end up being in (2) anymore, eat the argument */1226 argcount++;1227 argv++;1228 argc--;12291230setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);12311232if(!opts->source_tree)/* case (1): want a tree */1233die(_("reference is not a tree:%s"), arg);12341235if(!has_dash_dash) {/* case (3).(d) -> (1) */1236/*1237 * Do not complain the most common case1238 * git checkout branch1239 * even if there happen to be a file called 'branch';1240 * it would be extremely annoying.1241 */1242if(argc)1243verify_non_filename(opts->prefix, arg);1244}else if(opts->accept_pathspec) {1245 argcount++;1246 argv++;1247 argc--;1248}12491250return argcount;1251}12521253static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1254{1255int status;1256struct strbuf branch_ref = STRBUF_INIT;12571258trace2_cmd_mode("unborn");12591260if(!opts->new_branch)1261die(_("You are on a branch yet to be born"));1262strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1263 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1264strbuf_release(&branch_ref);1265if(!opts->quiet)1266fprintf(stderr,_("Switched to a new branch '%s'\n"),1267 opts->new_branch);1268return status;1269}12701271static voiddie_expecting_a_branch(const struct branch_info *branch_info)1272{1273struct object_id oid;1274char*to_free;12751276if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1277const char*ref = to_free;12781279if(skip_prefix(ref,"refs/tags/", &ref))1280die(_("a branch is expected, got tag '%s'"), ref);1281if(skip_prefix(ref,"refs/remotes/", &ref))1282die(_("a branch is expected, got remote branch '%s'"), ref);1283die(_("a branch is expected, got '%s'"), ref);1284}1285if(branch_info->commit)1286die(_("a branch is expected, got commit '%s'"), branch_info->name);1287/*1288 * This case should never happen because we already die() on1289 * non-commit, but just in case.1290 */1291die(_("a branch is expected, got '%s'"), branch_info->name);1292}12931294static voiddie_if_some_operation_in_progress(void)1295{1296struct wt_status_state state;12971298memset(&state,0,sizeof(state));1299wt_status_get_state(the_repository, &state,0);13001301if(state.merge_in_progress)1302die(_("cannot switch branch while merging\n"1303"Consider\"git merge --quit\""1304"or\"git worktree add\"."));1305if(state.am_in_progress)1306die(_("cannot switch branch in the middle of an am session\n"1307"Consider\"git am --quit\""1308"or\"git worktree add\"."));1309if(state.rebase_interactive_in_progress || state.rebase_in_progress)1310die(_("cannot switch branch while rebasing\n"1311"Consider\"git rebase --quit\""1312"or\"git worktree add\"."));1313if(state.cherry_pick_in_progress)1314die(_("cannot switch branch while cherry-picking\n"1315"Consider\"git cherry-pick --quit\""1316"or\"git worktree add\"."));1317if(state.revert_in_progress)1318die(_("cannot switch branch while reverting\n"1319"Consider\"git revert --quit\""1320"or\"git worktree add\"."));1321if(state.bisect_in_progress)1322die(_("cannot switch branch while bisecting\n"1323"Consider\"git bisect reset HEAD\""1324"or\"git worktree add\"."));1325}13261327static intcheckout_branch(struct checkout_opts *opts,1328struct branch_info *new_branch_info)1329{1330if(opts->pathspec.nr)1331die(_("paths cannot be used with switching branches"));13321333if(opts->patch_mode)1334die(_("'%s' cannot be used with switching branches"),1335"--patch");13361337if(opts->overlay_mode != -1)1338die(_("'%s' cannot be used with switching branches"),1339"--[no]-overlay");13401341if(opts->writeout_stage)1342die(_("'%s' cannot be used with switching branches"),1343"--ours/--theirs");13441345if(opts->force && opts->merge)1346die(_("'%s' cannot be used with '%s'"),"-f","-m");13471348if(opts->discard_changes && opts->merge)1349die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");13501351if(opts->force_detach && opts->new_branch)1352die(_("'%s' cannot be used with '%s'"),1353"--detach","-b/-B/--orphan");13541355if(opts->new_orphan_branch) {1356if(opts->track != BRANCH_TRACK_UNSPECIFIED)1357die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1358if(opts->orphan_from_empty_tree && new_branch_info->name)1359die(_("'%s' cannot take <start-point>"),"--orphan");1360}else if(opts->force_detach) {1361if(opts->track != BRANCH_TRACK_UNSPECIFIED)1362die(_("'%s' cannot be used with '%s'"),"--detach","-t");1363}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1364 opts->track = git_branch_track;13651366if(new_branch_info->name && !new_branch_info->commit)1367die(_("Cannot switch branch to a non-commit '%s'"),1368 new_branch_info->name);13691370if(!opts->switch_branch_doing_nothing_is_ok &&1371!new_branch_info->name &&1372!opts->new_branch &&1373!opts->force_detach)1374die(_("missing branch or commit argument"));13751376if(!opts->implicit_detach &&1377!opts->force_detach &&1378!opts->new_branch &&1379!opts->new_branch_force &&1380 new_branch_info->name &&1381!new_branch_info->path)1382die_expecting_a_branch(new_branch_info);13831384if(!opts->can_switch_when_in_progress)1385die_if_some_operation_in_progress();13861387if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1388!opts->ignore_other_worktrees) {1389int flag;1390char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1391if(head_ref &&1392(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1393die_if_checked_out(new_branch_info->path,1);1394free(head_ref);1395}13961397if(!new_branch_info->commit && opts->new_branch) {1398struct object_id rev;1399int flag;14001401if(!read_ref_full("HEAD",0, &rev, &flag) &&1402(flag & REF_ISSYMREF) &&is_null_oid(&rev))1403returnswitch_unborn_to_new_branch(opts);1404}1405returnswitch_branches(opts, new_branch_info);1406}14071408static struct option *add_common_options(struct checkout_opts *opts,1409struct option *prevopts)1410{1411struct option options[] = {1412OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1413{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1414"checkout","control recursive updating of submodules",1415 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1416OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1417OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1418 PARSE_OPT_NOCOMPLETE),1419OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1420OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1421N_("conflict style (merge or diff3)")),1422OPT_END()1423};1424struct option *newopts =parse_options_concat(prevopts, options);1425free(prevopts);1426return newopts;1427}14281429static struct option *add_common_switch_branch_options(1430struct checkout_opts *opts,struct option *prevopts)1431{1432struct option options[] = {1433OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1434OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1435 BRANCH_TRACK_EXPLICIT),1436OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1437OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1438N_("update ignored files (default)"),1439 PARSE_OPT_NOCOMPLETE),1440OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1441N_("do not check if another worktree is holding the given ref")),1442OPT_END()1443};1444struct option *newopts =parse_options_concat(prevopts, options);1445free(prevopts);1446return newopts;1447}14481449static struct option *add_checkout_path_options(struct checkout_opts *opts,1450struct option *prevopts)1451{1452struct option options[] = {1453OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1454N_("checkout our version for unmerged files"),14552, PARSE_OPT_NONEG),1456OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1457N_("checkout their version for unmerged files"),14583, PARSE_OPT_NONEG),1459OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1460OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1461N_("do not limit pathspecs to sparse entries only")),1462OPT_END()1463};1464struct option *newopts =parse_options_concat(prevopts, options);1465free(prevopts);1466return newopts;1467}14681469static intcheckout_main(int argc,const char**argv,const char*prefix,1470struct checkout_opts *opts,struct option *options,1471const char*const usagestr[])1472{1473struct branch_info new_branch_info;1474int dwim_remotes_matched =0;1475int parseopt_flags =0;14761477memset(&new_branch_info,0,sizeof(new_branch_info));1478 opts->overwrite_ignore =1;1479 opts->prefix = prefix;1480 opts->show_progress = -1;14811482git_config(git_checkout_config, opts);14831484 opts->track = BRANCH_TRACK_UNSPECIFIED;14851486if(!opts->accept_pathspec && !opts->accept_ref)1487BUG("make up your mind, you need to take _something_");1488if(opts->accept_pathspec && opts->accept_ref)1489 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;14901491 argc =parse_options(argc, argv, prefix, options,1492 usagestr, parseopt_flags);14931494if(opts->show_progress <0) {1495if(opts->quiet)1496 opts->show_progress =0;1497else1498 opts->show_progress =isatty(2);1499}15001501if(opts->conflict_style) {1502 opts->merge =1;/* implied */1503git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1504}1505if(opts->force)1506 opts->discard_changes =1;15071508if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1509die(_("-b, -B and --orphan are mutually exclusive"));15101511if(opts->overlay_mode ==1&& opts->patch_mode)1512die(_("-p and --overlay are mutually exclusive"));15131514if(opts->checkout_index >=0|| opts->checkout_worktree >=0) {1515if(opts->checkout_index <0)1516 opts->checkout_index =0;1517if(opts->checkout_worktree <0)1518 opts->checkout_worktree =0;1519}else{1520if(opts->checkout_index <0)1521 opts->checkout_index = -opts->checkout_index -1;1522if(opts->checkout_worktree <0)1523 opts->checkout_worktree = -opts->checkout_worktree -1;1524}1525if(opts->checkout_index <0|| opts->checkout_worktree <0)1526BUG("these flags should be non-negative by now");1527/*1528 * convenient shortcut: "git restore --staged" equals1529 * "git restore --staged --source HEAD"1530 */1531if(!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)1532 opts->from_treeish ="HEAD";15331534/*1535 * From here on, new_branch will contain the branch to be checked out,1536 * and new_branch_force and new_orphan_branch will tell us which one of1537 * -b/-B/--orphan is being used.1538 */1539if(opts->new_branch_force)1540 opts->new_branch = opts->new_branch_force;15411542if(opts->new_orphan_branch)1543 opts->new_branch = opts->new_orphan_branch;15441545/* --track without -b/-B/--orphan should DWIM */1546if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1547const char*argv0 = argv[0];1548if(!argc || !strcmp(argv0,"--"))1549die(_("--track needs a branch name"));1550skip_prefix(argv0,"refs/", &argv0);1551skip_prefix(argv0,"remotes/", &argv0);1552 argv0 =strchr(argv0,'/');1553if(!argv0 || !argv0[1])1554die(_("missing branch name; try -b"));1555 opts->new_branch = argv0 +1;1556}15571558/*1559 * Extract branch name from command line arguments, so1560 * all that is left is pathspecs.1561 *1562 * Handle1563 *1564 * 1) git checkout <tree> -- [<paths>]1565 * 2) git checkout -- [<paths>]1566 * 3) git checkout <something> [<paths>]1567 *1568 * including "last branch" syntax and DWIM-ery for names of1569 * remote branches, erroring out for invalid or ambiguous cases.1570 */1571if(argc && opts->accept_ref) {1572struct object_id rev;1573int dwim_ok =1574!opts->patch_mode &&1575 opts->dwim_new_local_branch &&1576 opts->track == BRANCH_TRACK_UNSPECIFIED &&1577!opts->new_branch;1578int n =parse_branchname_arg(argc, argv, dwim_ok,1579&new_branch_info, opts, &rev,1580&dwim_remotes_matched);1581 argv += n;1582 argc -= n;1583}else if(!opts->accept_ref && opts->from_treeish) {1584struct object_id rev;15851586if(get_oid_mb(opts->from_treeish, &rev))1587die(_("could not resolve%s"), opts->from_treeish);15881589setup_new_branch_info_and_source_tree(&new_branch_info,1590 opts, &rev,1591 opts->from_treeish);15921593if(!opts->source_tree)1594die(_("reference is not a tree:%s"), opts->from_treeish);1595}15961597if(opts->accept_pathspec && !opts->empty_pathspec_ok && !argc &&1598!opts->patch_mode)/* patch mode is special */1599die(_("you must specify path(s) to restore"));16001601if(argc) {1602parse_pathspec(&opts->pathspec,0,1603 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1604 prefix, argv);16051606if(!opts->pathspec.nr)1607die(_("invalid path specification"));16081609/*1610 * Try to give more helpful suggestion.1611 * new_branch && argc > 1 will be caught later.1612 */1613if(opts->new_branch && argc ==1)1614die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1615 argv[0], opts->new_branch);16161617if(opts->force_detach)1618die(_("git checkout: --detach does not take a path argument '%s'"),1619 argv[0]);16201621if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1622die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1623"checking out of the index."));1624}16251626if(opts->new_branch) {1627struct strbuf buf = STRBUF_INIT;16281629if(opts->new_branch_force)1630 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1631else1632 opts->branch_exists =1633validate_new_branchname(opts->new_branch, &buf,0);1634strbuf_release(&buf);1635}16361637UNLEAK(opts);1638if(opts->patch_mode || opts->pathspec.nr) {1639int ret =checkout_paths(opts, new_branch_info.name);1640if(ret && dwim_remotes_matched >1&&1641 advice_checkout_ambiguous_remote_branch_name)1642advise(_("'%s' matched more than one remote tracking branch.\n"1643"We found%dremotes with a reference that matched. So we fell back\n"1644"on trying to resolve the argument as a path, but failed there too!\n"1645"\n"1646"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1647"you can do so by fully qualifying the name with the --track option:\n"1648"\n"1649" git checkout --track origin/<name>\n"1650"\n"1651"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1652"one remote, e.g. the 'origin' remote, consider setting\n"1653"checkout.defaultRemote=origin in your config."),1654 argv[0],1655 dwim_remotes_matched);1656return ret;1657}else{1658returncheckout_branch(opts, &new_branch_info);1659}1660}16611662intcmd_checkout(int argc,const char**argv,const char*prefix)1663{1664struct checkout_opts opts;1665struct option *options;1666struct option checkout_options[] = {1667OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1668N_("create and checkout a new branch")),1669OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1670N_("create/reset and checkout a branch")),1671OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1672OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1673N_("second guess 'git checkout <no-such-branch>' (default)")),1674OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode (default)")),1675OPT_END()1676};1677int ret;16781679memset(&opts,0,sizeof(opts));1680 opts.dwim_new_local_branch =1;1681 opts.switch_branch_doing_nothing_is_ok =1;1682 opts.only_merge_on_switching_branches =0;1683 opts.accept_ref =1;1684 opts.accept_pathspec =1;1685 opts.implicit_detach =1;1686 opts.can_switch_when_in_progress =1;1687 opts.orphan_from_empty_tree =0;1688 opts.empty_pathspec_ok =1;1689 opts.overlay_mode = -1;1690 opts.checkout_index = -2;/* default on */1691 opts.checkout_worktree = -2;/* default on */16921693 options =parse_options_dup(checkout_options);1694 options =add_common_options(&opts, options);1695 options =add_common_switch_branch_options(&opts, options);1696 options =add_checkout_path_options(&opts, options);16971698 ret =checkout_main(argc, argv, prefix, &opts,1699 options, checkout_usage);1700FREE_AND_NULL(options);1701return ret;1702}17031704intcmd_switch(int argc,const char**argv,const char*prefix)1705{1706struct checkout_opts opts;1707struct option *options = NULL;1708struct option switch_options[] = {1709OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1710N_("create and switch to a new branch")),1711OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1712N_("create/reset and switch to a branch")),1713OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1714N_("second guess 'git switch <no-such-branch>'")),1715OPT_BOOL(0,"discard-changes", &opts.discard_changes,1716N_("throw away local modifications")),1717OPT_END()1718};1719int ret;17201721memset(&opts,0,sizeof(opts));1722 opts.dwim_new_local_branch =1;1723 opts.accept_ref =1;1724 opts.accept_pathspec =0;1725 opts.switch_branch_doing_nothing_is_ok =0;1726 opts.only_merge_on_switching_branches =1;1727 opts.implicit_detach =0;1728 opts.can_switch_when_in_progress =0;1729 opts.orphan_from_empty_tree =1;1730 opts.overlay_mode = -1;17311732 options =parse_options_dup(switch_options);1733 options =add_common_options(&opts, options);1734 options =add_common_switch_branch_options(&opts, options);17351736 ret =checkout_main(argc, argv, prefix, &opts,1737 options, switch_branch_usage);1738FREE_AND_NULL(options);1739return ret;1740}17411742intcmd_restore(int argc,const char**argv,const char*prefix)1743{1744struct checkout_opts opts;1745struct option *options;1746struct option restore_options[] = {1747OPT_STRING('s',"source", &opts.from_treeish,"<tree-ish>",1748N_("where the checkout from")),1749OPT_BOOL('S',"staged", &opts.checkout_index,1750N_("restore the index")),1751OPT_BOOL('W',"worktree", &opts.checkout_worktree,1752N_("restore the working tree (default)")),1753OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode")),1754OPT_END()1755};1756int ret;17571758memset(&opts,0,sizeof(opts));1759 opts.accept_ref =0;1760 opts.accept_pathspec =1;1761 opts.empty_pathspec_ok =0;1762 opts.overlay_mode =0;1763 opts.checkout_index = -1;/* default off */1764 opts.checkout_worktree = -2;/* default on */17651766 options =parse_options_dup(restore_options);1767 options =add_common_options(&opts, options);1768 options =add_checkout_path_options(&opts, options);17691770 ret =checkout_main(argc, argv, prefix, &opts,1771 options, restore_usage);1772FREE_AND_NULL(options);1773return ret;1774}