1#define USE_THE_INDEX_COMPATIBILITY_MACROS 2#include"builtin.h" 3#include"advice.h" 4#include"blob.h" 5#include"branch.h" 6#include"cache-tree.h" 7#include"checkout.h" 8#include"commit.h" 9#include"config.h" 10#include"diff.h" 11#include"dir.h" 12#include"ll-merge.h" 13#include"lockfile.h" 14#include"merge-recursive.h" 15#include"object-store.h" 16#include"parse-options.h" 17#include"refs.h" 18#include"remote.h" 19#include"resolve-undo.h" 20#include"revision.h" 21#include"run-command.h" 22#include"submodule.h" 23#include"submodule-config.h" 24#include"tree.h" 25#include"tree-walk.h" 26#include"unpack-trees.h" 27#include"wt-status.h" 28#include"xdiff-interface.h" 29 30static const char*const checkout_usage[] = { 31N_("git checkout [<options>] <branch>"), 32N_("git checkout [<options>] [<branch>] -- <file>..."), 33 NULL, 34}; 35 36static const char*const switch_branch_usage[] = { 37N_("git switch [<options>] [<branch>]"), 38 NULL, 39}; 40 41static const char*const restore_usage[] = { 42N_("git restore [<options>] [--source=<branch>] <file>..."), 43 NULL, 44}; 45 46struct checkout_opts { 47int patch_mode; 48int quiet; 49int merge; 50int force; 51int force_detach; 52int implicit_detach; 53int writeout_stage; 54int overwrite_ignore; 55int ignore_skipworktree; 56int ignore_other_worktrees; 57int show_progress; 58int count_checkout_paths; 59int overlay_mode; 60int dwim_new_local_branch; 61int discard_changes; 62int accept_ref; 63int accept_pathspec; 64int switch_branch_doing_nothing_is_ok; 65int only_merge_on_switching_branches; 66int can_switch_when_in_progress; 67int orphan_from_empty_tree; 68int empty_pathspec_ok; 69int checkout_index; 70int checkout_worktree; 71const char*ignore_unmerged_opt; 72int ignore_unmerged; 73 74const char*new_branch; 75const char*new_branch_force; 76const char*new_orphan_branch; 77int new_branch_log; 78enum branch_track track; 79struct diff_options diff_options; 80char*conflict_style; 81 82int branch_exists; 83const char*prefix; 84struct pathspec pathspec; 85const char*from_treeish; 86struct tree *source_tree; 87}; 88 89static intpost_checkout_hook(struct commit *old_commit,struct commit *new_commit, 90int changed) 91{ 92returnrun_hook_le(NULL,"post-checkout", 93oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid), 94oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid), 95 changed ?"1":"0", NULL); 96/* "new_commit" can be NULL when checking out from the index before 97 a commit exists. */ 98 99} 100 101static intupdate_some(const struct object_id *oid,struct strbuf *base, 102const char*pathname,unsigned mode,int stage,void*context) 103{ 104int len; 105struct cache_entry *ce; 106int pos; 107 108if(S_ISDIR(mode)) 109return READ_TREE_RECURSIVE; 110 111 len = base->len +strlen(pathname); 112 ce =make_empty_cache_entry(&the_index, len); 113oidcpy(&ce->oid, oid); 114memcpy(ce->name, base->buf, base->len); 115memcpy(ce->name + base->len, pathname, len - base->len); 116 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 117 ce->ce_namelen = len; 118 ce->ce_mode =create_ce_mode(mode); 119 120/* 121 * If the entry is the same as the current index, we can leave the old 122 * entry in place. Whether it is UPTODATE or not, checkout_entry will 123 * do the right thing. 124 */ 125 pos =cache_name_pos(ce->name, ce->ce_namelen); 126if(pos >=0) { 127struct cache_entry *old = active_cache[pos]; 128if(ce->ce_mode == old->ce_mode && 129oideq(&ce->oid, &old->oid)) { 130 old->ce_flags |= CE_UPDATE; 131discard_cache_entry(ce); 132return0; 133} 134} 135 136add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 137return0; 138} 139 140static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 141{ 142read_tree_recursive(the_repository, tree,"",0,0, 143 pathspec, update_some, NULL); 144 145/* update the index with the given tree's info 146 * for all args, expanding wildcards, and exit 147 * with any non-zero return code. 148 */ 149return0; 150} 151 152static intskip_same_name(const struct cache_entry *ce,int pos) 153{ 154while(++pos < active_nr && 155!strcmp(active_cache[pos]->name, ce->name)) 156;/* skip */ 157return pos; 158} 159 160static intcheck_stage(int stage,const struct cache_entry *ce,int pos, 161int overlay_mode) 162{ 163while(pos < active_nr && 164!strcmp(active_cache[pos]->name, ce->name)) { 165if(ce_stage(active_cache[pos]) == stage) 166return0; 167 pos++; 168} 169if(!overlay_mode) 170return0; 171if(stage ==2) 172returnerror(_("path '%s' does not have our version"), ce->name); 173else 174returnerror(_("path '%s' does not have their version"), ce->name); 175} 176 177static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 178{ 179unsigned seen =0; 180const char*name = ce->name; 181 182while(pos < active_nr) { 183 ce = active_cache[pos]; 184if(strcmp(name, ce->name)) 185break; 186 seen |= (1<<ce_stage(ce)); 187 pos++; 188} 189if((stages & seen) != stages) 190returnerror(_("path '%s' does not have all necessary versions"), 191 name); 192return0; 193} 194 195static intcheckout_stage(int stage,const struct cache_entry *ce,int pos, 196const struct checkout *state,int*nr_checkouts, 197int overlay_mode) 198{ 199while(pos < active_nr && 200!strcmp(active_cache[pos]->name, ce->name)) { 201if(ce_stage(active_cache[pos]) == stage) 202returncheckout_entry(active_cache[pos], state, 203 NULL, nr_checkouts); 204 pos++; 205} 206if(!overlay_mode) { 207unlink_entry(ce); 208return0; 209} 210if(stage ==2) 211returnerror(_("path '%s' does not have our version"), ce->name); 212else 213returnerror(_("path '%s' does not have their version"), ce->name); 214} 215 216static intcheckout_merged(int pos,const struct checkout *state,int*nr_checkouts) 217{ 218struct cache_entry *ce = active_cache[pos]; 219const char*path = ce->name; 220 mmfile_t ancestor, ours, theirs; 221int status; 222struct object_id oid; 223 mmbuffer_t result_buf; 224struct object_id threeway[3]; 225unsigned mode =0; 226 227memset(threeway,0,sizeof(threeway)); 228while(pos < active_nr) { 229int stage; 230 stage =ce_stage(ce); 231if(!stage ||strcmp(path, ce->name)) 232break; 233oidcpy(&threeway[stage -1], &ce->oid); 234if(stage ==2) 235 mode =create_ce_mode(ce->ce_mode); 236 pos++; 237 ce = active_cache[pos]; 238} 239if(is_null_oid(&threeway[1]) ||is_null_oid(&threeway[2])) 240returnerror(_("path '%s' does not have necessary versions"), path); 241 242read_mmblob(&ancestor, &threeway[0]); 243read_mmblob(&ours, &threeway[1]); 244read_mmblob(&theirs, &threeway[2]); 245 246/* 247 * NEEDSWORK: re-create conflicts from merges with 248 * merge.renormalize set, too 249 */ 250 status =ll_merge(&result_buf, path, &ancestor,"base", 251&ours,"ours", &theirs,"theirs", 252 state->istate, NULL); 253free(ancestor.ptr); 254free(ours.ptr); 255free(theirs.ptr); 256if(status <0|| !result_buf.ptr) { 257free(result_buf.ptr); 258returnerror(_("path '%s': cannot merge"), path); 259} 260 261/* 262 * NEEDSWORK: 263 * There is absolutely no reason to write this as a blob object 264 * and create a phony cache entry. This hack is primarily to get 265 * to the write_entry() machinery that massages the contents to 266 * work-tree format and writes out which only allows it for a 267 * cache entry. The code in write_entry() needs to be refactored 268 * to allow us to feed a <buffer, size, mode> instead of a cache 269 * entry. Such a refactoring would help merge_recursive as well 270 * (it also writes the merge result to the object database even 271 * when it may contain conflicts). 272 */ 273if(write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid)) 274die(_("Unable to add merge result for '%s'"), path); 275free(result_buf.ptr); 276 ce =make_transient_cache_entry(mode, &oid, path,2); 277if(!ce) 278die(_("make_cache_entry failed for path '%s'"), path); 279 status =checkout_entry(ce, state, NULL, nr_checkouts); 280discard_cache_entry(ce); 281return status; 282} 283 284static voidmark_ce_for_checkout_overlay(struct cache_entry *ce, 285char*ps_matched, 286const struct checkout_opts *opts) 287{ 288 ce->ce_flags &= ~CE_MATCHED; 289if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 290return; 291if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 292/* 293 * "git checkout tree-ish -- path", but this entry 294 * is in the original index but is not in tree-ish 295 * or does not match the pathspec; it will not be 296 * checked out to the working tree. We will not do 297 * anything to this entry at all. 298 */ 299return; 300/* 301 * Either this entry came from the tree-ish we are 302 * checking the paths out of, or we are checking out 303 * of the index. 304 * 305 * If it comes from the tree-ish, we already know it 306 * matches the pathspec and could just stamp 307 * CE_MATCHED to it from update_some(). But we still 308 * need ps_matched and read_tree_recursive (and 309 * eventually tree_entry_interesting) cannot fill 310 * ps_matched yet. Once it can, we can avoid calling 311 * match_pathspec() for _all_ entries when 312 * opts->source_tree != NULL. 313 */ 314if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) 315 ce->ce_flags |= CE_MATCHED; 316} 317 318static voidmark_ce_for_checkout_no_overlay(struct cache_entry *ce, 319char*ps_matched, 320const struct checkout_opts *opts) 321{ 322 ce->ce_flags &= ~CE_MATCHED; 323if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 324return; 325if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) { 326 ce->ce_flags |= CE_MATCHED; 327if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 328/* 329 * In overlay mode, but the path is not in 330 * tree-ish, which means we should remove it 331 * from the index and the working tree. 332 */ 333 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE; 334} 335} 336 337static intcheckout_worktree(const struct checkout_opts *opts) 338{ 339struct checkout state = CHECKOUT_INIT; 340int nr_checkouts =0, nr_unmerged =0; 341int errs =0; 342int pos; 343 344 state.force =1; 345 state.refresh_cache =1; 346 state.istate = &the_index; 347 348enable_delayed_checkout(&state); 349for(pos =0; pos < active_nr; pos++) { 350struct cache_entry *ce = active_cache[pos]; 351if(ce->ce_flags & CE_MATCHED) { 352if(!ce_stage(ce)) { 353 errs |=checkout_entry(ce, &state, 354 NULL, &nr_checkouts); 355continue; 356} 357if(opts->writeout_stage) 358 errs |=checkout_stage(opts->writeout_stage, 359 ce, pos, 360&state, 361&nr_checkouts, opts->overlay_mode); 362else if(opts->merge) 363 errs |=checkout_merged(pos, &state, 364&nr_unmerged); 365 pos =skip_same_name(ce, pos) -1; 366} 367} 368remove_marked_cache_entries(&the_index,1); 369remove_scheduled_dirs(); 370 errs |=finish_delayed_checkout(&state, &nr_checkouts); 371 372if(opts->count_checkout_paths) { 373if(nr_unmerged) 374fprintf_ln(stderr,Q_("Recreated%dmerge conflict", 375"Recreated%dmerge conflicts", 376 nr_unmerged), 377 nr_unmerged); 378if(opts->source_tree) 379fprintf_ln(stderr,Q_("Updated%dpath from%s", 380"Updated%dpaths from%s", 381 nr_checkouts), 382 nr_checkouts, 383find_unique_abbrev(&opts->source_tree->object.oid, 384 DEFAULT_ABBREV)); 385else if(!nr_unmerged || nr_checkouts) 386fprintf_ln(stderr,Q_("Updated%dpath from the index", 387"Updated%dpaths from the index", 388 nr_checkouts), 389 nr_checkouts); 390} 391 392return errs; 393} 394 395static intcheckout_paths(const struct checkout_opts *opts, 396const char*revision) 397{ 398int pos; 399static char*ps_matched; 400struct object_id rev; 401struct commit *head; 402int errs =0; 403struct lock_file lock_file = LOCK_INIT; 404int checkout_index; 405 406trace2_cmd_mode(opts->patch_mode ?"patch":"path"); 407 408if(opts->track != BRANCH_TRACK_UNSPECIFIED) 409die(_("'%s' cannot be used with updating paths"),"--track"); 410 411if(opts->new_branch_log) 412die(_("'%s' cannot be used with updating paths"),"-l"); 413 414if(opts->ignore_unmerged && opts->patch_mode) 415die(_("'%s' cannot be used with updating paths"), 416 opts->ignore_unmerged_opt); 417 418if(opts->force_detach) 419die(_("'%s' cannot be used with updating paths"),"--detach"); 420 421if(opts->merge && opts->patch_mode) 422die(_("'%s' cannot be used with%s"),"--merge","--patch"); 423 424if(opts->ignore_unmerged && opts->merge) 425die(_("'%s' cannot be used with%s"), 426 opts->ignore_unmerged_opt,"-m"); 427 428if(opts->new_branch) 429die(_("Cannot update paths and switch to branch '%s' at the same time."), 430 opts->new_branch); 431 432if(!opts->checkout_worktree && !opts->checkout_index) 433die(_("neither '%s' or '%s' is specified"), 434"--staged","--worktree"); 435 436if(!opts->checkout_worktree && !opts->from_treeish) 437die(_("'%s' must be used when '%s' is not specified"), 438"--worktree","--source"); 439 440if(opts->checkout_index && !opts->checkout_worktree && 441 opts->writeout_stage) 442die(_("'%s' or '%s' cannot be used with%s"), 443"--ours","--theirs","--staged"); 444 445if(opts->checkout_index && !opts->checkout_worktree && 446 opts->merge) 447die(_("'%s' or '%s' cannot be used with%s"), 448"--merge","--conflict","--staged"); 449 450if(opts->patch_mode) { 451const char*patch_mode; 452 453if(opts->checkout_index && opts->checkout_worktree) 454 patch_mode ="--patch=checkout"; 455else if(opts->checkout_index && !opts->checkout_worktree) 456 patch_mode ="--patch=reset"; 457else 458die(_("'%s' with only '%s' is not currently supported"), 459"--patch","--worktree"); 460returnrun_add_interactive(revision, patch_mode, &opts->pathspec); 461} 462 463repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 464if(read_cache_preload(&opts->pathspec) <0) 465returnerror(_("index file corrupt")); 466 467if(opts->source_tree) 468read_tree_some(opts->source_tree, &opts->pathspec); 469 470 ps_matched =xcalloc(opts->pathspec.nr,1); 471 472/* 473 * Make sure all pathspecs participated in locating the paths 474 * to be checked out. 475 */ 476for(pos =0; pos < active_nr; pos++) 477if(opts->overlay_mode) 478mark_ce_for_checkout_overlay(active_cache[pos], 479 ps_matched, 480 opts); 481else 482mark_ce_for_checkout_no_overlay(active_cache[pos], 483 ps_matched, 484 opts); 485 486if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 487free(ps_matched); 488return1; 489} 490free(ps_matched); 491 492/* "checkout -m path" to recreate conflicted state */ 493if(opts->merge) 494unmerge_marked_index(&the_index); 495 496/* Any unmerged paths? */ 497for(pos =0; pos < active_nr; pos++) { 498const struct cache_entry *ce = active_cache[pos]; 499if(ce->ce_flags & CE_MATCHED) { 500if(!ce_stage(ce)) 501continue; 502if(opts->ignore_unmerged) { 503if(!opts->quiet) 504warning(_("path '%s' is unmerged"), ce->name); 505}else if(opts->writeout_stage) { 506 errs |=check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 507}else if(opts->merge) { 508 errs |=check_stages((1<<2) | (1<<3), ce, pos); 509}else{ 510 errs =1; 511error(_("path '%s' is unmerged"), ce->name); 512} 513 pos =skip_same_name(ce, pos) -1; 514} 515} 516if(errs) 517return1; 518 519/* Now we are committed to check them out */ 520if(opts->checkout_worktree) 521 errs |=checkout_worktree(opts); 522 523/* 524 * Allow updating the index when checking out from the index. 525 * This is to save new stat info. 526 */ 527if(opts->checkout_worktree && !opts->checkout_index && !opts->source_tree) 528 checkout_index =1; 529else 530 checkout_index = opts->checkout_index; 531 532if(checkout_index) { 533if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 534die(_("unable to write new index file")); 535}else{ 536/* 537 * NEEDSWORK: if --worktree is not specified, we 538 * should save stat info of checked out files in the 539 * index to avoid the next (potentially costly) 540 * refresh. But it's a bit tricker to do... 541 */ 542rollback_lock_file(&lock_file); 543} 544 545read_ref_full("HEAD",0, &rev, NULL); 546 head =lookup_commit_reference_gently(the_repository, &rev,1); 547 548 errs |=post_checkout_hook(head, head,0); 549return errs; 550} 551 552static voidshow_local_changes(struct object *head, 553const struct diff_options *opts) 554{ 555struct rev_info rev; 556/* I think we want full paths, even if we're in a subdirectory. */ 557repo_init_revisions(the_repository, &rev, NULL); 558 rev.diffopt.flags = opts->flags; 559 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 560diff_setup_done(&rev.diffopt); 561add_pending_object(&rev, head, NULL); 562run_diff_index(&rev,0); 563} 564 565static voiddescribe_detached_head(const char*msg,struct commit *commit) 566{ 567struct strbuf sb = STRBUF_INIT; 568 569if(!parse_commit(commit)) 570pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 571if(print_sha1_ellipsis()) { 572fprintf(stderr,"%s %s...%s\n", msg, 573find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 574}else{ 575fprintf(stderr,"%s %s %s\n", msg, 576find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 577} 578strbuf_release(&sb); 579} 580 581static intreset_tree(struct tree *tree,const struct checkout_opts *o, 582int worktree,int*writeout_error) 583{ 584struct unpack_trees_options opts; 585struct tree_desc tree_desc; 586 587memset(&opts,0,sizeof(opts)); 588 opts.head_idx = -1; 589 opts.update = worktree; 590 opts.skip_unmerged = !worktree; 591 opts.reset =1; 592 opts.merge =1; 593 opts.fn = oneway_merge; 594 opts.verbose_update = o->show_progress; 595 opts.src_index = &the_index; 596 opts.dst_index = &the_index; 597parse_tree(tree); 598init_tree_desc(&tree_desc, tree->buffer, tree->size); 599switch(unpack_trees(1, &tree_desc, &opts)) { 600case-2: 601*writeout_error =1; 602/* 603 * We return 0 nevertheless, as the index is all right 604 * and more importantly we have made best efforts to 605 * update paths in the work tree, and we cannot revert 606 * them. 607 */ 608/* fallthrough */ 609case0: 610return0; 611default: 612return128; 613} 614} 615 616struct branch_info { 617const char*name;/* The short name used */ 618const char*path;/* The full name of a real branch */ 619struct commit *commit;/* The named commit */ 620/* 621 * if not null the branch is detached because it's already 622 * checked out in this checkout 623 */ 624char*checkout; 625}; 626 627static voidsetup_branch_path(struct branch_info *branch) 628{ 629struct strbuf buf = STRBUF_INIT; 630 631strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 632if(strcmp(buf.buf, branch->name)) 633 branch->name =xstrdup(buf.buf); 634strbuf_splice(&buf,0,0,"refs/heads/",11); 635 branch->path =strbuf_detach(&buf, NULL); 636} 637 638static intmerge_working_tree(const struct checkout_opts *opts, 639struct branch_info *old_branch_info, 640struct branch_info *new_branch_info, 641int*writeout_error) 642{ 643int ret; 644struct lock_file lock_file = LOCK_INIT; 645struct tree *new_tree; 646 647hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 648if(read_cache_preload(NULL) <0) 649returnerror(_("index file corrupt")); 650 651resolve_undo_clear(); 652if(opts->new_orphan_branch && opts->orphan_from_empty_tree) { 653if(new_branch_info->commit) 654BUG("'switch --orphan' should never accept a commit as starting point"); 655 new_tree =parse_tree_indirect(the_hash_algo->empty_tree); 656}else 657 new_tree =get_commit_tree(new_branch_info->commit); 658if(opts->discard_changes) { 659 ret =reset_tree(new_tree, opts,1, writeout_error); 660if(ret) 661return ret; 662}else{ 663struct tree_desc trees[2]; 664struct tree *tree; 665struct unpack_trees_options topts; 666 667memset(&topts,0,sizeof(topts)); 668 topts.head_idx = -1; 669 topts.src_index = &the_index; 670 topts.dst_index = &the_index; 671 672setup_unpack_trees_porcelain(&topts,"checkout"); 673 674refresh_cache(REFRESH_QUIET); 675 676if(unmerged_cache()) { 677error(_("you need to resolve your current index first")); 678return1; 679} 680 681/* 2-way merge to the new branch */ 682 topts.initial_checkout =is_cache_unborn(); 683 topts.update =1; 684 topts.merge =1; 685 topts.gently = opts->merge && old_branch_info->commit; 686 topts.verbose_update = opts->show_progress; 687 topts.fn = twoway_merge; 688if(opts->overwrite_ignore) { 689 topts.dir =xcalloc(1,sizeof(*topts.dir)); 690 topts.dir->flags |= DIR_SHOW_IGNORED; 691setup_standard_excludes(topts.dir); 692} 693 tree =parse_tree_indirect(old_branch_info->commit ? 694&old_branch_info->commit->object.oid : 695 the_hash_algo->empty_tree); 696init_tree_desc(&trees[0], tree->buffer, tree->size); 697parse_tree(new_tree); 698 tree = new_tree; 699init_tree_desc(&trees[1], tree->buffer, tree->size); 700 701 ret =unpack_trees(2, trees, &topts); 702clear_unpack_trees_porcelain(&topts); 703if(ret == -1) { 704/* 705 * Unpack couldn't do a trivial merge; either 706 * give up or do a real merge, depending on 707 * whether the merge flag was used. 708 */ 709struct tree *result; 710struct tree *work; 711struct merge_options o; 712if(!opts->merge) 713return1; 714 715/* 716 * Without old_branch_info->commit, the below is the same as 717 * the two-tree unpack we already tried and failed. 718 */ 719if(!old_branch_info->commit) 720return1; 721 722/* Do more real merge */ 723 724/* 725 * We update the index fully, then write the 726 * tree from the index, then merge the new 727 * branch with the current tree, with the old 728 * branch as the base. Then we reset the index 729 * (but not the working tree) to the new 730 * branch, leaving the working tree as the 731 * merged version, but skipping unmerged 732 * entries in the index. 733 */ 734 735add_files_to_cache(NULL, NULL,0); 736/* 737 * NEEDSWORK: carrying over local changes 738 * when branches have different end-of-line 739 * normalization (or clean+smudge rules) is 740 * a pain; plumb in an option to set 741 * o.renormalize? 742 */ 743init_merge_options(&o, the_repository); 744 o.verbosity =0; 745 work =write_tree_from_memory(&o); 746 747 ret =reset_tree(new_tree, 748 opts,1, 749 writeout_error); 750if(ret) 751return ret; 752 o.ancestor = old_branch_info->name; 753 o.branch1 = new_branch_info->name; 754 o.branch2 ="local"; 755 ret =merge_trees(&o, 756 new_tree, 757 work, 758get_commit_tree(old_branch_info->commit), 759&result); 760if(ret <0) 761exit(128); 762 ret =reset_tree(new_tree, 763 opts,0, 764 writeout_error); 765strbuf_release(&o.obuf); 766if(ret) 767return ret; 768} 769} 770 771if(!active_cache_tree) 772 active_cache_tree =cache_tree(); 773 774if(!cache_tree_fully_valid(active_cache_tree)) 775cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 776 777if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 778die(_("unable to write new index file")); 779 780if(!opts->discard_changes && !opts->quiet && new_branch_info->commit) 781show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 782 783return0; 784} 785 786static voidreport_tracking(struct branch_info *new_branch_info) 787{ 788struct strbuf sb = STRBUF_INIT; 789struct branch *branch =branch_get(new_branch_info->name); 790 791if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 792return; 793fputs(sb.buf, stdout); 794strbuf_release(&sb); 795} 796 797static voidupdate_refs_for_switch(const struct checkout_opts *opts, 798struct branch_info *old_branch_info, 799struct branch_info *new_branch_info) 800{ 801struct strbuf msg = STRBUF_INIT; 802const char*old_desc, *reflog_msg; 803if(opts->new_branch) { 804if(opts->new_orphan_branch) { 805char*refname; 806 807 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 808if(opts->new_branch_log && 809!should_autocreate_reflog(refname)) { 810int ret; 811struct strbuf err = STRBUF_INIT; 812 813 ret =safe_create_reflog(refname,1, &err); 814if(ret) { 815fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 816 opts->new_orphan_branch, err.buf); 817strbuf_release(&err); 818free(refname); 819return; 820} 821strbuf_release(&err); 822} 823free(refname); 824} 825else 826create_branch(the_repository, 827 opts->new_branch, new_branch_info->name, 828 opts->new_branch_force ?1:0, 829 opts->new_branch_force ?1:0, 830 opts->new_branch_log, 831 opts->quiet, 832 opts->track); 833 new_branch_info->name = opts->new_branch; 834setup_branch_path(new_branch_info); 835} 836 837 old_desc = old_branch_info->name; 838if(!old_desc && old_branch_info->commit) 839 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 840 841 reflog_msg =getenv("GIT_REFLOG_ACTION"); 842if(!reflog_msg) 843strbuf_addf(&msg,"checkout: moving from%sto%s", 844 old_desc ? old_desc :"(invalid)", new_branch_info->name); 845else 846strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 847 848if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 849/* Nothing to do. */ 850}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 851update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 852 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 853if(!opts->quiet) { 854if(old_branch_info->path && 855 advice_detached_head && !opts->force_detach) 856detach_advice(new_branch_info->name); 857describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 858} 859}else if(new_branch_info->path) {/* Switch branches. */ 860if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 861die(_("unable to update HEAD")); 862if(!opts->quiet) { 863if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 864if(opts->new_branch_force) 865fprintf(stderr,_("Reset branch '%s'\n"), 866 new_branch_info->name); 867else 868fprintf(stderr,_("Already on '%s'\n"), 869 new_branch_info->name); 870}else if(opts->new_branch) { 871if(opts->branch_exists) 872fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 873else 874fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 875}else{ 876fprintf(stderr,_("Switched to branch '%s'\n"), 877 new_branch_info->name); 878} 879} 880if(old_branch_info->path && old_branch_info->name) { 881if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 882delete_reflog(old_branch_info->path); 883} 884} 885remove_branch_state(the_repository, !opts->quiet); 886strbuf_release(&msg); 887if(!opts->quiet && 888(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 889report_tracking(new_branch_info); 890} 891 892static intadd_pending_uninteresting_ref(const char*refname, 893const struct object_id *oid, 894int flags,void*cb_data) 895{ 896add_pending_oid(cb_data, refname, oid, UNINTERESTING); 897return0; 898} 899 900static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 901{ 902strbuf_addstr(sb," "); 903strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 904strbuf_addch(sb,' '); 905if(!parse_commit(commit)) 906pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 907strbuf_addch(sb,'\n'); 908} 909 910#define ORPHAN_CUTOFF 4 911static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 912{ 913struct commit *c, *last = NULL; 914struct strbuf sb = STRBUF_INIT; 915int lost =0; 916while((c =get_revision(revs)) != NULL) { 917if(lost < ORPHAN_CUTOFF) 918describe_one_orphan(&sb, c); 919 last = c; 920 lost++; 921} 922if(ORPHAN_CUTOFF < lost) { 923int more = lost - ORPHAN_CUTOFF; 924if(more ==1) 925describe_one_orphan(&sb, last); 926else 927strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 928} 929 930fprintf(stderr, 931Q_( 932/* The singular version */ 933"Warning: you are leaving%dcommit behind, " 934"not connected to\n" 935"any of your branches:\n\n" 936"%s\n", 937/* The plural version */ 938"Warning: you are leaving%dcommits behind, " 939"not connected to\n" 940"any of your branches:\n\n" 941"%s\n", 942/* Give ngettext() the count */ 943 lost), 944 lost, 945 sb.buf); 946strbuf_release(&sb); 947 948if(advice_detached_head) 949fprintf(stderr, 950Q_( 951/* The singular version */ 952"If you want to keep it by creating a new branch, " 953"this may be a good time\nto do so with:\n\n" 954" git branch <new-branch-name>%s\n\n", 955/* The plural version */ 956"If you want to keep them by creating a new branch, " 957"this may be a good time\nto do so with:\n\n" 958" git branch <new-branch-name>%s\n\n", 959/* Give ngettext() the count */ 960 lost), 961find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 962} 963 964/* 965 * We are about to leave commit that was at the tip of a detached 966 * HEAD. If it is not reachable from any ref, this is the last chance 967 * for the user to do so without resorting to reflog. 968 */ 969static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 970{ 971struct rev_info revs; 972struct object *object = &old_commit->object; 973 974repo_init_revisions(the_repository, &revs, NULL); 975setup_revisions(0, NULL, &revs, NULL); 976 977 object->flags &= ~UNINTERESTING; 978add_pending_object(&revs, object,oid_to_hex(&object->oid)); 979 980for_each_ref(add_pending_uninteresting_ref, &revs); 981if(new_commit) 982add_pending_oid(&revs,"HEAD", 983&new_commit->object.oid, 984 UNINTERESTING); 985 986if(prepare_revision_walk(&revs)) 987die(_("internal error in revision walk")); 988if(!(old_commit->object.flags & UNINTERESTING)) 989suggest_reattach(old_commit, &revs); 990else 991describe_detached_head(_("Previous HEAD position was"), old_commit); 992 993/* Clean up objects used, as they will be reused. */ 994clear_commit_marks_all(ALL_REV_FLAGS); 995} 996 997static intswitch_branches(const struct checkout_opts *opts, 998struct branch_info *new_branch_info) 999{1000int ret =0;1001struct branch_info old_branch_info;1002void*path_to_free;1003struct object_id rev;1004int flag, writeout_error =0;1005int do_merge =1;10061007trace2_cmd_mode("branch");10081009memset(&old_branch_info,0,sizeof(old_branch_info));1010 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag);1011if(old_branch_info.path)1012 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1);1013if(!(flag & REF_ISSYMREF))1014 old_branch_info.path = NULL;10151016if(old_branch_info.path)1017skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name);10181019if(opts->new_orphan_branch && opts->orphan_from_empty_tree) {1020if(new_branch_info->name)1021BUG("'switch --orphan' should never accept a commit as starting point");1022 new_branch_info->commit = NULL;1023 new_branch_info->name ="(empty)";1024 do_merge =1;1025}10261027if(!new_branch_info->name) {1028 new_branch_info->name ="HEAD";1029 new_branch_info->commit = old_branch_info.commit;1030if(!new_branch_info->commit)1031die(_("You are on a branch yet to be born"));1032parse_commit_or_die(new_branch_info->commit);10331034if(opts->only_merge_on_switching_branches)1035 do_merge =0;1036}10371038if(do_merge) {1039 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);1040if(ret) {1041free(path_to_free);1042return ret;1043}1044}10451046if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)1047orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);10481049update_refs_for_switch(opts, &old_branch_info, new_branch_info);10501051 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1);1052free(path_to_free);1053return ret || writeout_error;1054}10551056static intgit_checkout_config(const char*var,const char*value,void*cb)1057{1058if(!strcmp(var,"diff.ignoresubmodules")) {1059struct checkout_opts *opts = cb;1060handle_ignore_submodules_arg(&opts->diff_options, value);1061return0;1062}10631064if(starts_with(var,"submodule."))1065returngit_default_submodule_config(var, value, NULL);10661067returngit_xmerge_config(var, value, NULL);1068}10691070static voidsetup_new_branch_info_and_source_tree(1071struct branch_info *new_branch_info,1072struct checkout_opts *opts,1073struct object_id *rev,1074const char*arg)1075{1076struct tree **source_tree = &opts->source_tree;1077struct object_id branch_rev;10781079 new_branch_info->name = arg;1080setup_branch_path(new_branch_info);10811082if(!check_refname_format(new_branch_info->path,0) &&1083!read_ref(new_branch_info->path, &branch_rev))1084oidcpy(rev, &branch_rev);1085else1086 new_branch_info->path = NULL;/* not an existing branch */10871088 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1089if(!new_branch_info->commit) {1090/* not a commit */1091*source_tree =parse_tree_indirect(rev);1092}else{1093parse_commit_or_die(new_branch_info->commit);1094*source_tree =get_commit_tree(new_branch_info->commit);1095}1096}10971098static intparse_branchname_arg(int argc,const char**argv,1099int dwim_new_local_branch_ok,1100struct branch_info *new_branch_info,1101struct checkout_opts *opts,1102struct object_id *rev,1103int*dwim_remotes_matched)1104{1105const char**new_branch = &opts->new_branch;1106int argcount =0;1107const char*arg;1108int dash_dash_pos;1109int has_dash_dash =0;1110int i;11111112/*1113 * case 1: git checkout <ref> -- [<paths>]1114 *1115 * <ref> must be a valid tree, everything after the '--' must be1116 * a path.1117 *1118 * case 2: git checkout -- [<paths>]1119 *1120 * everything after the '--' must be paths.1121 *1122 * case 3: git checkout <something> [--]1123 *1124 * (a) If <something> is a commit, that is to1125 * switch to the branch or detach HEAD at it. As a special case,1126 * if <something> is A...B (missing A or B means HEAD but you can1127 * omit at most one side), and if there is a unique merge base1128 * between A and B, A...B names that merge base.1129 *1130 * (b) If <something> is _not_ a commit, either "--" is present1131 * or <something> is not a path, no -t or -b was given, and1132 * and there is a tracking branch whose name is <something>1133 * in one and only one remote (or if the branch exists on the1134 * remote named in checkout.defaultRemote), then this is a1135 * short-hand to fork local <something> from that1136 * remote-tracking branch.1137 *1138 * (c) Otherwise, if "--" is present, treat it like case (1).1139 *1140 * (d) Otherwise :1141 * - if it's a reference, treat it like case (1)1142 * - else if it's a path, treat it like case (2)1143 * - else: fail.1144 *1145 * case 4: git checkout <something> <paths>1146 *1147 * The first argument must not be ambiguous.1148 * - If it's *only* a reference, treat it like case (1).1149 * - If it's only a path, treat it like case (2).1150 * - else: fail.1151 *1152 */1153if(!argc)1154return0;11551156if(!opts->accept_pathspec) {1157if(argc >1)1158die(_("only one reference expected"));1159 has_dash_dash =1;/* helps disambiguate */1160}11611162 arg = argv[0];1163 dash_dash_pos = -1;1164for(i =0; i < argc; i++) {1165if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1166 dash_dash_pos = i;1167break;1168}1169}1170if(dash_dash_pos ==0)1171return1;/* case (2) */1172else if(dash_dash_pos ==1)1173 has_dash_dash =1;/* case (3) or (1) */1174else if(dash_dash_pos >=2)1175die(_("only one reference expected,%dgiven."), dash_dash_pos);1176 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;11771178if(!strcmp(arg,"-"))1179 arg ="@{-1}";11801181if(get_oid_mb(arg, rev)) {1182/*1183 * Either case (3) or (4), with <something> not being1184 * a commit, or an attempt to use case (1) with an1185 * invalid ref.1186 *1187 * It's likely an error, but we need to find out if1188 * we should auto-create the branch, case (3).(b).1189 */1190int recover_with_dwim = dwim_new_local_branch_ok;11911192int could_be_checkout_paths = !has_dash_dash &&1193check_filename(opts->prefix, arg);11941195if(!has_dash_dash && !no_wildcard(arg))1196 recover_with_dwim =0;11971198/*1199 * Accept "git checkout foo", "git checkout foo --"1200 * and "git switch foo" as candidates for dwim.1201 */1202if(!(argc ==1&& !has_dash_dash) &&1203!(argc ==2&& has_dash_dash) &&1204 opts->accept_pathspec)1205 recover_with_dwim =0;12061207if(recover_with_dwim) {1208const char*remote =unique_tracking_name(arg, rev,1209 dwim_remotes_matched);1210if(remote) {1211if(could_be_checkout_paths)1212die(_("'%s' could be both a local file and a tracking branch.\n"1213"Please use -- (and optionally --no-guess) to disambiguate"),1214 arg);1215*new_branch = arg;1216 arg = remote;1217/* DWIMmed to create local branch, case (3).(b) */1218}else{1219 recover_with_dwim =0;1220}1221}12221223if(!recover_with_dwim) {1224if(has_dash_dash)1225die(_("invalid reference:%s"), arg);1226return argcount;1227}1228}12291230/* we can't end up being in (2) anymore, eat the argument */1231 argcount++;1232 argv++;1233 argc--;12341235setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);12361237if(!opts->source_tree)/* case (1): want a tree */1238die(_("reference is not a tree:%s"), arg);12391240if(!has_dash_dash) {/* case (3).(d) -> (1) */1241/*1242 * Do not complain the most common case1243 * git checkout branch1244 * even if there happen to be a file called 'branch';1245 * it would be extremely annoying.1246 */1247if(argc)1248verify_non_filename(opts->prefix, arg);1249}else if(opts->accept_pathspec) {1250 argcount++;1251 argv++;1252 argc--;1253}12541255return argcount;1256}12571258static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1259{1260int status;1261struct strbuf branch_ref = STRBUF_INIT;12621263trace2_cmd_mode("unborn");12641265if(!opts->new_branch)1266die(_("You are on a branch yet to be born"));1267strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1268 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1269strbuf_release(&branch_ref);1270if(!opts->quiet)1271fprintf(stderr,_("Switched to a new branch '%s'\n"),1272 opts->new_branch);1273return status;1274}12751276static voiddie_expecting_a_branch(const struct branch_info *branch_info)1277{1278struct object_id oid;1279char*to_free;12801281if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1282const char*ref = to_free;12831284if(skip_prefix(ref,"refs/tags/", &ref))1285die(_("a branch is expected, got tag '%s'"), ref);1286if(skip_prefix(ref,"refs/remotes/", &ref))1287die(_("a branch is expected, got remote branch '%s'"), ref);1288die(_("a branch is expected, got '%s'"), ref);1289}1290if(branch_info->commit)1291die(_("a branch is expected, got commit '%s'"), branch_info->name);1292/*1293 * This case should never happen because we already die() on1294 * non-commit, but just in case.1295 */1296die(_("a branch is expected, got '%s'"), branch_info->name);1297}12981299static voiddie_if_some_operation_in_progress(void)1300{1301struct wt_status_state state;13021303memset(&state,0,sizeof(state));1304wt_status_get_state(the_repository, &state,0);13051306if(state.merge_in_progress)1307die(_("cannot switch branch while merging\n"1308"Consider\"git merge --quit\""1309"or\"git worktree add\"."));1310if(state.am_in_progress)1311die(_("cannot switch branch in the middle of an am session\n"1312"Consider\"git am --quit\""1313"or\"git worktree add\"."));1314if(state.rebase_interactive_in_progress || state.rebase_in_progress)1315die(_("cannot switch branch while rebasing\n"1316"Consider\"git rebase --quit\""1317"or\"git worktree add\"."));1318if(state.cherry_pick_in_progress)1319die(_("cannot switch branch while cherry-picking\n"1320"Consider\"git cherry-pick --quit\""1321"or\"git worktree add\"."));1322if(state.revert_in_progress)1323die(_("cannot switch branch while reverting\n"1324"Consider\"git revert --quit\""1325"or\"git worktree add\"."));1326if(state.bisect_in_progress)1327die(_("cannot switch branch while bisecting\n"1328"Consider\"git bisect reset HEAD\""1329"or\"git worktree add\"."));1330}13311332static intcheckout_branch(struct checkout_opts *opts,1333struct branch_info *new_branch_info)1334{1335if(opts->pathspec.nr)1336die(_("paths cannot be used with switching branches"));13371338if(opts->patch_mode)1339die(_("'%s' cannot be used with switching branches"),1340"--patch");13411342if(opts->overlay_mode != -1)1343die(_("'%s' cannot be used with switching branches"),1344"--[no]-overlay");13451346if(opts->writeout_stage)1347die(_("'%s' cannot be used with switching branches"),1348"--ours/--theirs");13491350if(opts->force && opts->merge)1351die(_("'%s' cannot be used with '%s'"),"-f","-m");13521353if(opts->discard_changes && opts->merge)1354die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");13551356if(opts->force_detach && opts->new_branch)1357die(_("'%s' cannot be used with '%s'"),1358"--detach","-b/-B/--orphan");13591360if(opts->new_orphan_branch) {1361if(opts->track != BRANCH_TRACK_UNSPECIFIED)1362die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1363if(opts->orphan_from_empty_tree && new_branch_info->name)1364die(_("'%s' cannot take <start-point>"),"--orphan");1365}else if(opts->force_detach) {1366if(opts->track != BRANCH_TRACK_UNSPECIFIED)1367die(_("'%s' cannot be used with '%s'"),"--detach","-t");1368}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1369 opts->track = git_branch_track;13701371if(new_branch_info->name && !new_branch_info->commit)1372die(_("Cannot switch branch to a non-commit '%s'"),1373 new_branch_info->name);13741375if(!opts->switch_branch_doing_nothing_is_ok &&1376!new_branch_info->name &&1377!opts->new_branch &&1378!opts->force_detach)1379die(_("missing branch or commit argument"));13801381if(!opts->implicit_detach &&1382!opts->force_detach &&1383!opts->new_branch &&1384!opts->new_branch_force &&1385 new_branch_info->name &&1386!new_branch_info->path)1387die_expecting_a_branch(new_branch_info);13881389if(!opts->can_switch_when_in_progress)1390die_if_some_operation_in_progress();13911392if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1393!opts->ignore_other_worktrees) {1394int flag;1395char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1396if(head_ref &&1397(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1398die_if_checked_out(new_branch_info->path,1);1399free(head_ref);1400}14011402if(!new_branch_info->commit && opts->new_branch) {1403struct object_id rev;1404int flag;14051406if(!read_ref_full("HEAD",0, &rev, &flag) &&1407(flag & REF_ISSYMREF) &&is_null_oid(&rev))1408returnswitch_unborn_to_new_branch(opts);1409}1410returnswitch_branches(opts, new_branch_info);1411}14121413static struct option *add_common_options(struct checkout_opts *opts,1414struct option *prevopts)1415{1416struct option options[] = {1417OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1418{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1419"checkout","control recursive updating of submodules",1420 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1421OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1422OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1423OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1424N_("conflict style (merge or diff3)")),1425OPT_END()1426};1427struct option *newopts =parse_options_concat(prevopts, options);1428free(prevopts);1429return newopts;1430}14311432static struct option *add_common_switch_branch_options(1433struct checkout_opts *opts,struct option *prevopts)1434{1435struct option options[] = {1436OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1437OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1438 BRANCH_TRACK_EXPLICIT),1439OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1440 PARSE_OPT_NOCOMPLETE),1441OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1442OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1443N_("update ignored files (default)"),1444 PARSE_OPT_NOCOMPLETE),1445OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1446N_("do not check if another worktree is holding the given ref")),1447OPT_END()1448};1449struct option *newopts =parse_options_concat(prevopts, options);1450free(prevopts);1451return newopts;1452}14531454static struct option *add_checkout_path_options(struct checkout_opts *opts,1455struct option *prevopts)1456{1457struct option options[] = {1458OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1459N_("checkout our version for unmerged files"),14602, PARSE_OPT_NONEG),1461OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1462N_("checkout their version for unmerged files"),14633, PARSE_OPT_NONEG),1464OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1465OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1466N_("do not limit pathspecs to sparse entries only")),1467OPT_END()1468};1469struct option *newopts =parse_options_concat(prevopts, options);1470free(prevopts);1471return newopts;1472}14731474static intcheckout_main(int argc,const char**argv,const char*prefix,1475struct checkout_opts *opts,struct option *options,1476const char*const usagestr[])1477{1478struct branch_info new_branch_info;1479int dwim_remotes_matched =0;1480int parseopt_flags =0;14811482memset(&new_branch_info,0,sizeof(new_branch_info));1483 opts->overwrite_ignore =1;1484 opts->prefix = prefix;1485 opts->show_progress = -1;14861487git_config(git_checkout_config, opts);14881489 opts->track = BRANCH_TRACK_UNSPECIFIED;14901491if(!opts->accept_pathspec && !opts->accept_ref)1492BUG("make up your mind, you need to take _something_");1493if(opts->accept_pathspec && opts->accept_ref)1494 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;14951496 argc =parse_options(argc, argv, prefix, options,1497 usagestr, parseopt_flags);14981499if(opts->show_progress <0) {1500if(opts->quiet)1501 opts->show_progress =0;1502else1503 opts->show_progress =isatty(2);1504}15051506if(opts->conflict_style) {1507 opts->merge =1;/* implied */1508git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1509}1510if(opts->force) {1511 opts->discard_changes =1;1512 opts->ignore_unmerged_opt ="--force";1513 opts->ignore_unmerged =1;1514}15151516if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1517die(_("-b, -B and --orphan are mutually exclusive"));15181519if(opts->overlay_mode ==1&& opts->patch_mode)1520die(_("-p and --overlay are mutually exclusive"));15211522if(opts->checkout_index >=0|| opts->checkout_worktree >=0) {1523if(opts->checkout_index <0)1524 opts->checkout_index =0;1525if(opts->checkout_worktree <0)1526 opts->checkout_worktree =0;1527}else{1528if(opts->checkout_index <0)1529 opts->checkout_index = -opts->checkout_index -1;1530if(opts->checkout_worktree <0)1531 opts->checkout_worktree = -opts->checkout_worktree -1;1532}1533if(opts->checkout_index <0|| opts->checkout_worktree <0)1534BUG("these flags should be non-negative by now");1535/*1536 * convenient shortcut: "git restore --staged" equals1537 * "git restore --staged --source HEAD"1538 */1539if(!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)1540 opts->from_treeish ="HEAD";15411542/*1543 * From here on, new_branch will contain the branch to be checked out,1544 * and new_branch_force and new_orphan_branch will tell us which one of1545 * -b/-B/--orphan is being used.1546 */1547if(opts->new_branch_force)1548 opts->new_branch = opts->new_branch_force;15491550if(opts->new_orphan_branch)1551 opts->new_branch = opts->new_orphan_branch;15521553/* --track without -b/-B/--orphan should DWIM */1554if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1555const char*argv0 = argv[0];1556if(!argc || !strcmp(argv0,"--"))1557die(_("--track needs a branch name"));1558skip_prefix(argv0,"refs/", &argv0);1559skip_prefix(argv0,"remotes/", &argv0);1560 argv0 =strchr(argv0,'/');1561if(!argv0 || !argv0[1])1562die(_("missing branch name; try -b"));1563 opts->new_branch = argv0 +1;1564}15651566/*1567 * Extract branch name from command line arguments, so1568 * all that is left is pathspecs.1569 *1570 * Handle1571 *1572 * 1) git checkout <tree> -- [<paths>]1573 * 2) git checkout -- [<paths>]1574 * 3) git checkout <something> [<paths>]1575 *1576 * including "last branch" syntax and DWIM-ery for names of1577 * remote branches, erroring out for invalid or ambiguous cases.1578 */1579if(argc && opts->accept_ref) {1580struct object_id rev;1581int dwim_ok =1582!opts->patch_mode &&1583 opts->dwim_new_local_branch &&1584 opts->track == BRANCH_TRACK_UNSPECIFIED &&1585!opts->new_branch;1586int n =parse_branchname_arg(argc, argv, dwim_ok,1587&new_branch_info, opts, &rev,1588&dwim_remotes_matched);1589 argv += n;1590 argc -= n;1591}else if(!opts->accept_ref && opts->from_treeish) {1592struct object_id rev;15931594if(get_oid_mb(opts->from_treeish, &rev))1595die(_("could not resolve%s"), opts->from_treeish);15961597setup_new_branch_info_and_source_tree(&new_branch_info,1598 opts, &rev,1599 opts->from_treeish);16001601if(!opts->source_tree)1602die(_("reference is not a tree:%s"), opts->from_treeish);1603}16041605if(opts->accept_pathspec && !opts->empty_pathspec_ok && !argc &&1606!opts->patch_mode)/* patch mode is special */1607die(_("you must specify path(s) to restore"));16081609if(argc) {1610parse_pathspec(&opts->pathspec,0,1611 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1612 prefix, argv);16131614if(!opts->pathspec.nr)1615die(_("invalid path specification"));16161617/*1618 * Try to give more helpful suggestion.1619 * new_branch && argc > 1 will be caught later.1620 */1621if(opts->new_branch && argc ==1)1622die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1623 argv[0], opts->new_branch);16241625if(opts->force_detach)1626die(_("git checkout: --detach does not take a path argument '%s'"),1627 argv[0]);16281629if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1630die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1631"checking out of the index."));1632}16331634if(opts->new_branch) {1635struct strbuf buf = STRBUF_INIT;16361637if(opts->new_branch_force)1638 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1639else1640 opts->branch_exists =1641validate_new_branchname(opts->new_branch, &buf,0);1642strbuf_release(&buf);1643}16441645UNLEAK(opts);1646if(opts->patch_mode || opts->pathspec.nr) {1647int ret =checkout_paths(opts, new_branch_info.name);1648if(ret && dwim_remotes_matched >1&&1649 advice_checkout_ambiguous_remote_branch_name)1650advise(_("'%s' matched more than one remote tracking branch.\n"1651"We found%dremotes with a reference that matched. So we fell back\n"1652"on trying to resolve the argument as a path, but failed there too!\n"1653"\n"1654"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1655"you can do so by fully qualifying the name with the --track option:\n"1656"\n"1657" git checkout --track origin/<name>\n"1658"\n"1659"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1660"one remote, e.g. the 'origin' remote, consider setting\n"1661"checkout.defaultRemote=origin in your config."),1662 argv[0],1663 dwim_remotes_matched);1664return ret;1665}else{1666returncheckout_branch(opts, &new_branch_info);1667}1668}16691670intcmd_checkout(int argc,const char**argv,const char*prefix)1671{1672struct checkout_opts opts;1673struct option *options;1674struct option checkout_options[] = {1675OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1676N_("create and checkout a new branch")),1677OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1678N_("create/reset and checkout a branch")),1679OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1680OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1681N_("second guess 'git checkout <no-such-branch>' (default)")),1682OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode (default)")),1683OPT_END()1684};1685int ret;16861687memset(&opts,0,sizeof(opts));1688 opts.dwim_new_local_branch =1;1689 opts.switch_branch_doing_nothing_is_ok =1;1690 opts.only_merge_on_switching_branches =0;1691 opts.accept_ref =1;1692 opts.accept_pathspec =1;1693 opts.implicit_detach =1;1694 opts.can_switch_when_in_progress =1;1695 opts.orphan_from_empty_tree =0;1696 opts.empty_pathspec_ok =1;1697 opts.overlay_mode = -1;1698 opts.checkout_index = -2;/* default on */1699 opts.checkout_worktree = -2;/* default on */17001701 options =parse_options_dup(checkout_options);1702 options =add_common_options(&opts, options);1703 options =add_common_switch_branch_options(&opts, options);1704 options =add_checkout_path_options(&opts, options);17051706 ret =checkout_main(argc, argv, prefix, &opts,1707 options, checkout_usage);1708FREE_AND_NULL(options);1709return ret;1710}17111712intcmd_switch(int argc,const char**argv,const char*prefix)1713{1714struct checkout_opts opts;1715struct option *options = NULL;1716struct option switch_options[] = {1717OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1718N_("create and switch to a new branch")),1719OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1720N_("create/reset and switch to a branch")),1721OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1722N_("second guess 'git switch <no-such-branch>'")),1723OPT_BOOL(0,"discard-changes", &opts.discard_changes,1724N_("throw away local modifications")),1725OPT_END()1726};1727int ret;17281729memset(&opts,0,sizeof(opts));1730 opts.dwim_new_local_branch =1;1731 opts.accept_ref =1;1732 opts.accept_pathspec =0;1733 opts.switch_branch_doing_nothing_is_ok =0;1734 opts.only_merge_on_switching_branches =1;1735 opts.implicit_detach =0;1736 opts.can_switch_when_in_progress =0;1737 opts.orphan_from_empty_tree =1;1738 opts.overlay_mode = -1;17391740 options =parse_options_dup(switch_options);1741 options =add_common_options(&opts, options);1742 options =add_common_switch_branch_options(&opts, options);17431744 ret =checkout_main(argc, argv, prefix, &opts,1745 options, switch_branch_usage);1746FREE_AND_NULL(options);1747return ret;1748}17491750intcmd_restore(int argc,const char**argv,const char*prefix)1751{1752struct checkout_opts opts;1753struct option *options;1754struct option restore_options[] = {1755OPT_STRING('s',"source", &opts.from_treeish,"<tree-ish>",1756N_("where the checkout from")),1757OPT_BOOL('S',"staged", &opts.checkout_index,1758N_("restore the index")),1759OPT_BOOL('W',"worktree", &opts.checkout_worktree,1760N_("restore the working tree (default)")),1761OPT_BOOL(0,"ignore-unmerged", &opts.ignore_unmerged,1762N_("ignore unmerged entries")),1763OPT_BOOL(0,"overlay", &opts.overlay_mode,N_("use overlay mode")),1764OPT_END()1765};1766int ret;17671768memset(&opts,0,sizeof(opts));1769 opts.accept_ref =0;1770 opts.accept_pathspec =1;1771 opts.empty_pathspec_ok =0;1772 opts.overlay_mode =0;1773 opts.checkout_index = -1;/* default off */1774 opts.checkout_worktree = -2;/* default on */1775 opts.ignore_unmerged_opt ="--ignore-unmerged";17761777 options =parse_options_dup(restore_options);1778 options =add_common_options(&opts, options);1779 options =add_checkout_path_options(&opts, options);17801781 ret =checkout_main(argc, argv, prefix, &opts,1782 options, restore_usage);1783FREE_AND_NULL(options);1784return ret;1785}