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"xdiff-interface.h" 28 29static int checkout_optimize_new_branch; 30 31static const char*const checkout_usage[] = { 32N_("git checkout [<options>] <branch>"), 33N_("git checkout [<options>] [<branch>] -- <file>..."), 34 NULL, 35}; 36 37static const char*const switch_branch_usage[] = { 38N_("git switch [<options>] [<branch>]"), 39 NULL, 40}; 41 42struct checkout_opts { 43int patch_mode; 44int quiet; 45int merge; 46int force; 47int force_detach; 48int implicit_detach; 49int writeout_stage; 50int overwrite_ignore; 51int ignore_skipworktree; 52int ignore_other_worktrees; 53int show_progress; 54int count_checkout_paths; 55int overlay_mode; 56int no_dwim_new_local_branch; 57int discard_changes; 58int accept_pathspec; 59int switch_branch_doing_nothing_is_ok; 60 61/* 62 * If new checkout options are added, skip_merge_working_tree 63 * should be updated accordingly. 64 */ 65 66const char*new_branch; 67const char*new_branch_force; 68const char*new_orphan_branch; 69int new_branch_log; 70enum branch_track track; 71struct diff_options diff_options; 72char*conflict_style; 73 74int branch_exists; 75const char*prefix; 76struct pathspec pathspec; 77struct tree *source_tree; 78}; 79 80static intpost_checkout_hook(struct commit *old_commit,struct commit *new_commit, 81int changed) 82{ 83returnrun_hook_le(NULL,"post-checkout", 84oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid), 85oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid), 86 changed ?"1":"0", NULL); 87/* "new_commit" can be NULL when checking out from the index before 88 a commit exists. */ 89 90} 91 92static intupdate_some(const struct object_id *oid,struct strbuf *base, 93const char*pathname,unsigned mode,int stage,void*context) 94{ 95int len; 96struct cache_entry *ce; 97int pos; 98 99if(S_ISDIR(mode)) 100return READ_TREE_RECURSIVE; 101 102 len = base->len +strlen(pathname); 103 ce =make_empty_cache_entry(&the_index, len); 104oidcpy(&ce->oid, oid); 105memcpy(ce->name, base->buf, base->len); 106memcpy(ce->name + base->len, pathname, len - base->len); 107 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 108 ce->ce_namelen = len; 109 ce->ce_mode =create_ce_mode(mode); 110 111/* 112 * If the entry is the same as the current index, we can leave the old 113 * entry in place. Whether it is UPTODATE or not, checkout_entry will 114 * do the right thing. 115 */ 116 pos =cache_name_pos(ce->name, ce->ce_namelen); 117if(pos >=0) { 118struct cache_entry *old = active_cache[pos]; 119if(ce->ce_mode == old->ce_mode && 120oideq(&ce->oid, &old->oid)) { 121 old->ce_flags |= CE_UPDATE; 122discard_cache_entry(ce); 123return0; 124} 125} 126 127add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 128return0; 129} 130 131static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 132{ 133read_tree_recursive(the_repository, tree,"",0,0, 134 pathspec, update_some, NULL); 135 136/* update the index with the given tree's info 137 * for all args, expanding wildcards, and exit 138 * with any non-zero return code. 139 */ 140return0; 141} 142 143static intskip_same_name(const struct cache_entry *ce,int pos) 144{ 145while(++pos < active_nr && 146!strcmp(active_cache[pos]->name, ce->name)) 147;/* skip */ 148return pos; 149} 150 151static intcheck_stage(int stage,const struct cache_entry *ce,int pos, 152int overlay_mode) 153{ 154while(pos < active_nr && 155!strcmp(active_cache[pos]->name, ce->name)) { 156if(ce_stage(active_cache[pos]) == stage) 157return0; 158 pos++; 159} 160if(!overlay_mode) 161return0; 162if(stage ==2) 163returnerror(_("path '%s' does not have our version"), ce->name); 164else 165returnerror(_("path '%s' does not have their version"), ce->name); 166} 167 168static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 169{ 170unsigned seen =0; 171const char*name = ce->name; 172 173while(pos < active_nr) { 174 ce = active_cache[pos]; 175if(strcmp(name, ce->name)) 176break; 177 seen |= (1<<ce_stage(ce)); 178 pos++; 179} 180if((stages & seen) != stages) 181returnerror(_("path '%s' does not have all necessary versions"), 182 name); 183return0; 184} 185 186static intcheckout_stage(int stage,const struct cache_entry *ce,int pos, 187const struct checkout *state,int*nr_checkouts, 188int overlay_mode) 189{ 190while(pos < active_nr && 191!strcmp(active_cache[pos]->name, ce->name)) { 192if(ce_stage(active_cache[pos]) == stage) 193returncheckout_entry(active_cache[pos], state, 194 NULL, nr_checkouts); 195 pos++; 196} 197if(!overlay_mode) { 198unlink_entry(ce); 199return0; 200} 201if(stage ==2) 202returnerror(_("path '%s' does not have our version"), ce->name); 203else 204returnerror(_("path '%s' does not have their version"), ce->name); 205} 206 207static intcheckout_merged(int pos,const struct checkout *state,int*nr_checkouts) 208{ 209struct cache_entry *ce = active_cache[pos]; 210const char*path = ce->name; 211 mmfile_t ancestor, ours, theirs; 212int status; 213struct object_id oid; 214 mmbuffer_t result_buf; 215struct object_id threeway[3]; 216unsigned mode =0; 217 218memset(threeway,0,sizeof(threeway)); 219while(pos < active_nr) { 220int stage; 221 stage =ce_stage(ce); 222if(!stage ||strcmp(path, ce->name)) 223break; 224oidcpy(&threeway[stage -1], &ce->oid); 225if(stage ==2) 226 mode =create_ce_mode(ce->ce_mode); 227 pos++; 228 ce = active_cache[pos]; 229} 230if(is_null_oid(&threeway[1]) ||is_null_oid(&threeway[2])) 231returnerror(_("path '%s' does not have necessary versions"), path); 232 233read_mmblob(&ancestor, &threeway[0]); 234read_mmblob(&ours, &threeway[1]); 235read_mmblob(&theirs, &threeway[2]); 236 237/* 238 * NEEDSWORK: re-create conflicts from merges with 239 * merge.renormalize set, too 240 */ 241 status =ll_merge(&result_buf, path, &ancestor,"base", 242&ours,"ours", &theirs,"theirs", 243 state->istate, NULL); 244free(ancestor.ptr); 245free(ours.ptr); 246free(theirs.ptr); 247if(status <0|| !result_buf.ptr) { 248free(result_buf.ptr); 249returnerror(_("path '%s': cannot merge"), path); 250} 251 252/* 253 * NEEDSWORK: 254 * There is absolutely no reason to write this as a blob object 255 * and create a phony cache entry. This hack is primarily to get 256 * to the write_entry() machinery that massages the contents to 257 * work-tree format and writes out which only allows it for a 258 * cache entry. The code in write_entry() needs to be refactored 259 * to allow us to feed a <buffer, size, mode> instead of a cache 260 * entry. Such a refactoring would help merge_recursive as well 261 * (it also writes the merge result to the object database even 262 * when it may contain conflicts). 263 */ 264if(write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid)) 265die(_("Unable to add merge result for '%s'"), path); 266free(result_buf.ptr); 267 ce =make_transient_cache_entry(mode, &oid, path,2); 268if(!ce) 269die(_("make_cache_entry failed for path '%s'"), path); 270 status =checkout_entry(ce, state, NULL, nr_checkouts); 271discard_cache_entry(ce); 272return status; 273} 274 275static voidmark_ce_for_checkout_overlay(struct cache_entry *ce, 276char*ps_matched, 277const struct checkout_opts *opts) 278{ 279 ce->ce_flags &= ~CE_MATCHED; 280if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 281return; 282if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 283/* 284 * "git checkout tree-ish -- path", but this entry 285 * is in the original index but is not in tree-ish 286 * or does not match the pathspec; it will not be 287 * checked out to the working tree. We will not do 288 * anything to this entry at all. 289 */ 290return; 291/* 292 * Either this entry came from the tree-ish we are 293 * checking the paths out of, or we are checking out 294 * of the index. 295 * 296 * If it comes from the tree-ish, we already know it 297 * matches the pathspec and could just stamp 298 * CE_MATCHED to it from update_some(). But we still 299 * need ps_matched and read_tree_recursive (and 300 * eventually tree_entry_interesting) cannot fill 301 * ps_matched yet. Once it can, we can avoid calling 302 * match_pathspec() for _all_ entries when 303 * opts->source_tree != NULL. 304 */ 305if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) 306 ce->ce_flags |= CE_MATCHED; 307} 308 309static voidmark_ce_for_checkout_no_overlay(struct cache_entry *ce, 310char*ps_matched, 311const struct checkout_opts *opts) 312{ 313 ce->ce_flags &= ~CE_MATCHED; 314if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 315return; 316if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) { 317 ce->ce_flags |= CE_MATCHED; 318if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 319/* 320 * In overlay mode, but the path is not in 321 * tree-ish, which means we should remove it 322 * from the index and the working tree. 323 */ 324 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE; 325} 326} 327 328static intcheckout_paths(const struct checkout_opts *opts, 329const char*revision) 330{ 331int pos; 332struct checkout state = CHECKOUT_INIT; 333static char*ps_matched; 334struct object_id rev; 335struct commit *head; 336int errs =0; 337struct lock_file lock_file = LOCK_INIT; 338int nr_checkouts =0, nr_unmerged =0; 339 340trace2_cmd_mode(opts->patch_mode ?"patch":"path"); 341 342if(opts->track != BRANCH_TRACK_UNSPECIFIED) 343die(_("'%s' cannot be used with updating paths"),"--track"); 344 345if(opts->new_branch_log) 346die(_("'%s' cannot be used with updating paths"),"-l"); 347 348if(opts->force && opts->patch_mode) 349die(_("'%s' cannot be used with updating paths"),"-f"); 350 351if(opts->force_detach) 352die(_("'%s' cannot be used with updating paths"),"--detach"); 353 354if(opts->merge && opts->patch_mode) 355die(_("'%s' cannot be used with%s"),"--merge","--patch"); 356 357if(opts->force && opts->merge) 358die(_("'%s' cannot be used with%s"),"-f","-m"); 359 360if(opts->new_branch) 361die(_("Cannot update paths and switch to branch '%s' at the same time."), 362 opts->new_branch); 363 364if(opts->patch_mode) 365returnrun_add_interactive(revision,"--patch=checkout", 366&opts->pathspec); 367 368repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 369if(read_cache_preload(&opts->pathspec) <0) 370returnerror(_("index file corrupt")); 371 372if(opts->source_tree) 373read_tree_some(opts->source_tree, &opts->pathspec); 374 375 ps_matched =xcalloc(opts->pathspec.nr,1); 376 377/* 378 * Make sure all pathspecs participated in locating the paths 379 * to be checked out. 380 */ 381for(pos =0; pos < active_nr; pos++) 382if(opts->overlay_mode) 383mark_ce_for_checkout_overlay(active_cache[pos], 384 ps_matched, 385 opts); 386else 387mark_ce_for_checkout_no_overlay(active_cache[pos], 388 ps_matched, 389 opts); 390 391if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 392free(ps_matched); 393return1; 394} 395free(ps_matched); 396 397/* "checkout -m path" to recreate conflicted state */ 398if(opts->merge) 399unmerge_marked_index(&the_index); 400 401/* Any unmerged paths? */ 402for(pos =0; pos < active_nr; pos++) { 403const struct cache_entry *ce = active_cache[pos]; 404if(ce->ce_flags & CE_MATCHED) { 405if(!ce_stage(ce)) 406continue; 407if(opts->force) { 408warning(_("path '%s' is unmerged"), ce->name); 409}else if(opts->writeout_stage) { 410 errs |=check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 411}else if(opts->merge) { 412 errs |=check_stages((1<<2) | (1<<3), ce, pos); 413}else{ 414 errs =1; 415error(_("path '%s' is unmerged"), ce->name); 416} 417 pos =skip_same_name(ce, pos) -1; 418} 419} 420if(errs) 421return1; 422 423/* Now we are committed to check them out */ 424 state.force =1; 425 state.refresh_cache =1; 426 state.istate = &the_index; 427 428enable_delayed_checkout(&state); 429for(pos =0; pos < active_nr; pos++) { 430struct cache_entry *ce = active_cache[pos]; 431if(ce->ce_flags & CE_MATCHED) { 432if(!ce_stage(ce)) { 433 errs |=checkout_entry(ce, &state, 434 NULL, &nr_checkouts); 435continue; 436} 437if(opts->writeout_stage) 438 errs |=checkout_stage(opts->writeout_stage, 439 ce, pos, 440&state, 441&nr_checkouts, opts->overlay_mode); 442else if(opts->merge) 443 errs |=checkout_merged(pos, &state, 444&nr_unmerged); 445 pos =skip_same_name(ce, pos) -1; 446} 447} 448remove_marked_cache_entries(&the_index,1); 449remove_scheduled_dirs(); 450 errs |=finish_delayed_checkout(&state, &nr_checkouts); 451 452if(opts->count_checkout_paths) { 453if(nr_unmerged) 454fprintf_ln(stderr,Q_("Recreated%dmerge conflict", 455"Recreated%dmerge conflicts", 456 nr_unmerged), 457 nr_unmerged); 458if(opts->source_tree) 459fprintf_ln(stderr,Q_("Updated%dpath from%s", 460"Updated%dpaths from%s", 461 nr_checkouts), 462 nr_checkouts, 463find_unique_abbrev(&opts->source_tree->object.oid, 464 DEFAULT_ABBREV)); 465else if(!nr_unmerged || nr_checkouts) 466fprintf_ln(stderr,Q_("Updated%dpath from the index", 467"Updated%dpaths from the index", 468 nr_checkouts), 469 nr_checkouts); 470} 471 472if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 473die(_("unable to write new index file")); 474 475read_ref_full("HEAD",0, &rev, NULL); 476 head =lookup_commit_reference_gently(the_repository, &rev,1); 477 478 errs |=post_checkout_hook(head, head,0); 479return errs; 480} 481 482static voidshow_local_changes(struct object *head, 483const struct diff_options *opts) 484{ 485struct rev_info rev; 486/* I think we want full paths, even if we're in a subdirectory. */ 487repo_init_revisions(the_repository, &rev, NULL); 488 rev.diffopt.flags = opts->flags; 489 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 490diff_setup_done(&rev.diffopt); 491add_pending_object(&rev, head, NULL); 492run_diff_index(&rev,0); 493} 494 495static voiddescribe_detached_head(const char*msg,struct commit *commit) 496{ 497struct strbuf sb = STRBUF_INIT; 498 499if(!parse_commit(commit)) 500pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 501if(print_sha1_ellipsis()) { 502fprintf(stderr,"%s %s...%s\n", msg, 503find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 504}else{ 505fprintf(stderr,"%s %s %s\n", msg, 506find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 507} 508strbuf_release(&sb); 509} 510 511static intreset_tree(struct tree *tree,const struct checkout_opts *o, 512int worktree,int*writeout_error) 513{ 514struct unpack_trees_options opts; 515struct tree_desc tree_desc; 516 517memset(&opts,0,sizeof(opts)); 518 opts.head_idx = -1; 519 opts.update = worktree; 520 opts.skip_unmerged = !worktree; 521 opts.reset =1; 522 opts.merge =1; 523 opts.fn = oneway_merge; 524 opts.verbose_update = o->show_progress; 525 opts.src_index = &the_index; 526 opts.dst_index = &the_index; 527parse_tree(tree); 528init_tree_desc(&tree_desc, tree->buffer, tree->size); 529switch(unpack_trees(1, &tree_desc, &opts)) { 530case-2: 531*writeout_error =1; 532/* 533 * We return 0 nevertheless, as the index is all right 534 * and more importantly we have made best efforts to 535 * update paths in the work tree, and we cannot revert 536 * them. 537 */ 538/* fallthrough */ 539case0: 540return0; 541default: 542return128; 543} 544} 545 546struct branch_info { 547const char*name;/* The short name used */ 548const char*path;/* The full name of a real branch */ 549struct commit *commit;/* The named commit */ 550/* 551 * if not null the branch is detached because it's already 552 * checked out in this checkout 553 */ 554char*checkout; 555}; 556 557static voidsetup_branch_path(struct branch_info *branch) 558{ 559struct strbuf buf = STRBUF_INIT; 560 561strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 562if(strcmp(buf.buf, branch->name)) 563 branch->name =xstrdup(buf.buf); 564strbuf_splice(&buf,0,0,"refs/heads/",11); 565 branch->path =strbuf_detach(&buf, NULL); 566} 567 568/* 569 * Skip merging the trees, updating the index and working directory if and 570 * only if we are creating a new branch via "git checkout -b <new_branch>." 571 */ 572static intskip_merge_working_tree(const struct checkout_opts *opts, 573const struct branch_info *old_branch_info, 574const struct branch_info *new_branch_info) 575{ 576/* 577 * Do the merge if sparse checkout is on and the user has not opted in 578 * to the optimized behavior 579 */ 580if(core_apply_sparse_checkout && !checkout_optimize_new_branch) 581return0; 582 583/* 584 * We must do the merge if we are actually moving to a new commit. 585 */ 586if(!old_branch_info->commit || !new_branch_info->commit || 587!oideq(&old_branch_info->commit->object.oid, 588&new_branch_info->commit->object.oid)) 589return0; 590 591/* 592 * opts->patch_mode cannot be used with switching branches so is 593 * not tested here 594 */ 595 596/* 597 * opts->quiet only impacts output so doesn't require a merge 598 */ 599 600/* 601 * Honor the explicit request for a three-way merge or to throw away 602 * local changes 603 */ 604if(opts->merge || opts->force) 605return0; 606 607/* 608 * --detach is documented as "updating the index and the files in the 609 * working tree" but this optimization skips those steps so fall through 610 * to the regular code path. 611 */ 612if(opts->force_detach) 613return0; 614 615/* 616 * opts->writeout_stage cannot be used with switching branches so is 617 * not tested here 618 */ 619 620/* 621 * Honor the explicit ignore requests 622 */ 623if(!opts->overwrite_ignore || opts->ignore_skipworktree || 624 opts->ignore_other_worktrees) 625return0; 626 627/* 628 * opts->show_progress only impacts output so doesn't require a merge 629 */ 630 631/* 632 * opts->overlay_mode cannot be used with switching branches so is 633 * not tested here 634 */ 635 636/* 637 * If we aren't creating a new branch any changes or updates will 638 * happen in the existing branch. Since that could only be updating 639 * the index and working directory, we don't want to skip those steps 640 * or we've defeated any purpose in running the command. 641 */ 642if(!opts->new_branch) 643return0; 644 645/* 646 * new_branch_force is defined to "create/reset and checkout a branch" 647 * so needs to go through the merge to do the reset 648 */ 649if(opts->new_branch_force) 650return0; 651 652/* 653 * A new orphaned branch requrires the index and the working tree to be 654 * adjusted to <start_point> 655 */ 656if(opts->new_orphan_branch) 657return0; 658 659/* 660 * Remaining variables are not checkout options but used to track state 661 */ 662 663/* 664 * Do the merge if this is the initial checkout. We cannot use 665 * is_cache_unborn() here because the index hasn't been loaded yet 666 * so cache_nr and timestamp.sec are always zero. 667 */ 668if(!file_exists(get_index_file())) 669return0; 670 671return1; 672} 673 674static intmerge_working_tree(const struct checkout_opts *opts, 675struct branch_info *old_branch_info, 676struct branch_info *new_branch_info, 677int*writeout_error) 678{ 679int ret; 680struct lock_file lock_file = LOCK_INIT; 681 682hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 683if(read_cache_preload(NULL) <0) 684returnerror(_("index file corrupt")); 685 686resolve_undo_clear(); 687if(opts->discard_changes) { 688 ret =reset_tree(get_commit_tree(new_branch_info->commit), 689 opts,1, writeout_error); 690if(ret) 691return ret; 692}else{ 693struct tree_desc trees[2]; 694struct tree *tree; 695struct unpack_trees_options topts; 696 697memset(&topts,0,sizeof(topts)); 698 topts.head_idx = -1; 699 topts.src_index = &the_index; 700 topts.dst_index = &the_index; 701 702setup_unpack_trees_porcelain(&topts,"checkout"); 703 704refresh_cache(REFRESH_QUIET); 705 706if(unmerged_cache()) { 707error(_("you need to resolve your current index first")); 708return1; 709} 710 711/* 2-way merge to the new branch */ 712 topts.initial_checkout =is_cache_unborn(); 713 topts.update =1; 714 topts.merge =1; 715 topts.gently = opts->merge && old_branch_info->commit; 716 topts.verbose_update = opts->show_progress; 717 topts.fn = twoway_merge; 718if(opts->overwrite_ignore) { 719 topts.dir =xcalloc(1,sizeof(*topts.dir)); 720 topts.dir->flags |= DIR_SHOW_IGNORED; 721setup_standard_excludes(topts.dir); 722} 723 tree =parse_tree_indirect(old_branch_info->commit ? 724&old_branch_info->commit->object.oid : 725 the_hash_algo->empty_tree); 726init_tree_desc(&trees[0], tree->buffer, tree->size); 727 tree =parse_tree_indirect(&new_branch_info->commit->object.oid); 728init_tree_desc(&trees[1], tree->buffer, tree->size); 729 730 ret =unpack_trees(2, trees, &topts); 731clear_unpack_trees_porcelain(&topts); 732if(ret == -1) { 733/* 734 * Unpack couldn't do a trivial merge; either 735 * give up or do a real merge, depending on 736 * whether the merge flag was used. 737 */ 738struct tree *result; 739struct tree *work; 740struct merge_options o; 741if(!opts->merge) 742return1; 743 744/* 745 * Without old_branch_info->commit, the below is the same as 746 * the two-tree unpack we already tried and failed. 747 */ 748if(!old_branch_info->commit) 749return1; 750 751/* Do more real merge */ 752 753/* 754 * We update the index fully, then write the 755 * tree from the index, then merge the new 756 * branch with the current tree, with the old 757 * branch as the base. Then we reset the index 758 * (but not the working tree) to the new 759 * branch, leaving the working tree as the 760 * merged version, but skipping unmerged 761 * entries in the index. 762 */ 763 764add_files_to_cache(NULL, NULL,0); 765/* 766 * NEEDSWORK: carrying over local changes 767 * when branches have different end-of-line 768 * normalization (or clean+smudge rules) is 769 * a pain; plumb in an option to set 770 * o.renormalize? 771 */ 772init_merge_options(&o, the_repository); 773 o.verbosity =0; 774 work =write_tree_from_memory(&o); 775 776 ret =reset_tree(get_commit_tree(new_branch_info->commit), 777 opts,1, 778 writeout_error); 779if(ret) 780return ret; 781 o.ancestor = old_branch_info->name; 782 o.branch1 = new_branch_info->name; 783 o.branch2 ="local"; 784 ret =merge_trees(&o, 785get_commit_tree(new_branch_info->commit), 786 work, 787get_commit_tree(old_branch_info->commit), 788&result); 789if(ret <0) 790exit(128); 791 ret =reset_tree(get_commit_tree(new_branch_info->commit), 792 opts,0, 793 writeout_error); 794strbuf_release(&o.obuf); 795if(ret) 796return ret; 797} 798} 799 800if(!active_cache_tree) 801 active_cache_tree =cache_tree(); 802 803if(!cache_tree_fully_valid(active_cache_tree)) 804cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 805 806if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 807die(_("unable to write new index file")); 808 809if(!opts->discard_changes && !opts->quiet) 810show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 811 812return0; 813} 814 815static voidreport_tracking(struct branch_info *new_branch_info) 816{ 817struct strbuf sb = STRBUF_INIT; 818struct branch *branch =branch_get(new_branch_info->name); 819 820if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 821return; 822fputs(sb.buf, stdout); 823strbuf_release(&sb); 824} 825 826static voidupdate_refs_for_switch(const struct checkout_opts *opts, 827struct branch_info *old_branch_info, 828struct branch_info *new_branch_info) 829{ 830struct strbuf msg = STRBUF_INIT; 831const char*old_desc, *reflog_msg; 832if(opts->new_branch) { 833if(opts->new_orphan_branch) { 834char*refname; 835 836 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 837if(opts->new_branch_log && 838!should_autocreate_reflog(refname)) { 839int ret; 840struct strbuf err = STRBUF_INIT; 841 842 ret =safe_create_reflog(refname,1, &err); 843if(ret) { 844fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 845 opts->new_orphan_branch, err.buf); 846strbuf_release(&err); 847free(refname); 848return; 849} 850strbuf_release(&err); 851} 852free(refname); 853} 854else 855create_branch(the_repository, 856 opts->new_branch, new_branch_info->name, 857 opts->new_branch_force ?1:0, 858 opts->new_branch_force ?1:0, 859 opts->new_branch_log, 860 opts->quiet, 861 opts->track); 862 new_branch_info->name = opts->new_branch; 863setup_branch_path(new_branch_info); 864} 865 866 old_desc = old_branch_info->name; 867if(!old_desc && old_branch_info->commit) 868 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 869 870 reflog_msg =getenv("GIT_REFLOG_ACTION"); 871if(!reflog_msg) 872strbuf_addf(&msg,"checkout: moving from%sto%s", 873 old_desc ? old_desc :"(invalid)", new_branch_info->name); 874else 875strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 876 877if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 878/* Nothing to do. */ 879}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 880update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 881 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 882if(!opts->quiet) { 883if(old_branch_info->path && 884 advice_detached_head && !opts->force_detach) 885detach_advice(new_branch_info->name); 886describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 887} 888}else if(new_branch_info->path) {/* Switch branches. */ 889if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 890die(_("unable to update HEAD")); 891if(!opts->quiet) { 892if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 893if(opts->new_branch_force) 894fprintf(stderr,_("Reset branch '%s'\n"), 895 new_branch_info->name); 896else 897fprintf(stderr,_("Already on '%s'\n"), 898 new_branch_info->name); 899}else if(opts->new_branch) { 900if(opts->branch_exists) 901fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 902else 903fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 904}else{ 905fprintf(stderr,_("Switched to branch '%s'\n"), 906 new_branch_info->name); 907} 908} 909if(old_branch_info->path && old_branch_info->name) { 910if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 911delete_reflog(old_branch_info->path); 912} 913} 914remove_branch_state(the_repository, !opts->quiet); 915strbuf_release(&msg); 916if(!opts->quiet && 917(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 918report_tracking(new_branch_info); 919} 920 921static intadd_pending_uninteresting_ref(const char*refname, 922const struct object_id *oid, 923int flags,void*cb_data) 924{ 925add_pending_oid(cb_data, refname, oid, UNINTERESTING); 926return0; 927} 928 929static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 930{ 931strbuf_addstr(sb," "); 932strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 933strbuf_addch(sb,' '); 934if(!parse_commit(commit)) 935pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 936strbuf_addch(sb,'\n'); 937} 938 939#define ORPHAN_CUTOFF 4 940static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 941{ 942struct commit *c, *last = NULL; 943struct strbuf sb = STRBUF_INIT; 944int lost =0; 945while((c =get_revision(revs)) != NULL) { 946if(lost < ORPHAN_CUTOFF) 947describe_one_orphan(&sb, c); 948 last = c; 949 lost++; 950} 951if(ORPHAN_CUTOFF < lost) { 952int more = lost - ORPHAN_CUTOFF; 953if(more ==1) 954describe_one_orphan(&sb, last); 955else 956strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 957} 958 959fprintf(stderr, 960Q_( 961/* The singular version */ 962"Warning: you are leaving%dcommit behind, " 963"not connected to\n" 964"any of your branches:\n\n" 965"%s\n", 966/* The plural version */ 967"Warning: you are leaving%dcommits behind, " 968"not connected to\n" 969"any of your branches:\n\n" 970"%s\n", 971/* Give ngettext() the count */ 972 lost), 973 lost, 974 sb.buf); 975strbuf_release(&sb); 976 977if(advice_detached_head) 978fprintf(stderr, 979Q_( 980/* The singular version */ 981"If you want to keep it by creating a new branch, " 982"this may be a good time\nto do so with:\n\n" 983" git branch <new-branch-name>%s\n\n", 984/* The plural version */ 985"If you want to keep them by creating a new branch, " 986"this may be a good time\nto do so with:\n\n" 987" git branch <new-branch-name>%s\n\n", 988/* Give ngettext() the count */ 989 lost), 990find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 991} 992 993/* 994 * We are about to leave commit that was at the tip of a detached 995 * HEAD. If it is not reachable from any ref, this is the last chance 996 * for the user to do so without resorting to reflog. 997 */ 998static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 999{1000struct rev_info revs;1001struct object *object = &old_commit->object;10021003repo_init_revisions(the_repository, &revs, NULL);1004setup_revisions(0, NULL, &revs, NULL);10051006 object->flags &= ~UNINTERESTING;1007add_pending_object(&revs, object,oid_to_hex(&object->oid));10081009for_each_ref(add_pending_uninteresting_ref, &revs);1010add_pending_oid(&revs,"HEAD", &new_commit->object.oid, UNINTERESTING);10111012if(prepare_revision_walk(&revs))1013die(_("internal error in revision walk"));1014if(!(old_commit->object.flags & UNINTERESTING))1015suggest_reattach(old_commit, &revs);1016else1017describe_detached_head(_("Previous HEAD position was"), old_commit);10181019/* Clean up objects used, as they will be reused. */1020clear_commit_marks_all(ALL_REV_FLAGS);1021}10221023static intswitch_branches(const struct checkout_opts *opts,1024struct branch_info *new_branch_info)1025{1026int ret =0;1027struct branch_info old_branch_info;1028void*path_to_free;1029struct object_id rev;1030int flag, writeout_error =0;10311032trace2_cmd_mode("branch");10331034memset(&old_branch_info,0,sizeof(old_branch_info));1035 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag);1036if(old_branch_info.path)1037 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1);1038if(!(flag & REF_ISSYMREF))1039 old_branch_info.path = NULL;10401041if(old_branch_info.path)1042skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name);10431044if(!new_branch_info->name) {1045 new_branch_info->name ="HEAD";1046 new_branch_info->commit = old_branch_info.commit;1047if(!new_branch_info->commit)1048die(_("You are on a branch yet to be born"));1049parse_commit_or_die(new_branch_info->commit);1050}10511052/* optimize the "checkout -b <new_branch> path */1053if(skip_merge_working_tree(opts, &old_branch_info, new_branch_info)) {1054if(!checkout_optimize_new_branch && !opts->quiet) {1055if(read_cache_preload(NULL) <0)1056returnerror(_("index file corrupt"));1057show_local_changes(&new_branch_info->commit->object, &opts->diff_options);1058}1059}else{1060 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);1061if(ret) {1062free(path_to_free);1063return ret;1064}1065}10661067if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)1068orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);10691070update_refs_for_switch(opts, &old_branch_info, new_branch_info);10711072 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1);1073free(path_to_free);1074return ret || writeout_error;1075}10761077static intgit_checkout_config(const char*var,const char*value,void*cb)1078{1079if(!strcmp(var,"checkout.optimizenewbranch")) {1080 checkout_optimize_new_branch =git_config_bool(var, value);1081return0;1082}10831084if(!strcmp(var,"diff.ignoresubmodules")) {1085struct checkout_opts *opts = cb;1086handle_ignore_submodules_arg(&opts->diff_options, value);1087return0;1088}10891090if(starts_with(var,"submodule."))1091returngit_default_submodule_config(var, value, NULL);10921093returngit_xmerge_config(var, value, NULL);1094}10951096static voidsetup_new_branch_info_and_source_tree(1097struct branch_info *new_branch_info,1098struct checkout_opts *opts,1099struct object_id *rev,1100const char*arg)1101{1102struct tree **source_tree = &opts->source_tree;1103struct object_id branch_rev;11041105 new_branch_info->name = arg;1106setup_branch_path(new_branch_info);11071108if(!check_refname_format(new_branch_info->path,0) &&1109!read_ref(new_branch_info->path, &branch_rev))1110oidcpy(rev, &branch_rev);1111else1112 new_branch_info->path = NULL;/* not an existing branch */11131114 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1115if(!new_branch_info->commit) {1116/* not a commit */1117*source_tree =parse_tree_indirect(rev);1118}else{1119parse_commit_or_die(new_branch_info->commit);1120*source_tree =get_commit_tree(new_branch_info->commit);1121}1122}11231124static intparse_branchname_arg(int argc,const char**argv,1125int dwim_new_local_branch_ok,1126struct branch_info *new_branch_info,1127struct checkout_opts *opts,1128struct object_id *rev,1129int*dwim_remotes_matched)1130{1131const char**new_branch = &opts->new_branch;1132int argcount =0;1133const char*arg;1134int dash_dash_pos;1135int has_dash_dash =0;1136int i;11371138/*1139 * case 1: git checkout <ref> -- [<paths>]1140 *1141 * <ref> must be a valid tree, everything after the '--' must be1142 * a path.1143 *1144 * case 2: git checkout -- [<paths>]1145 *1146 * everything after the '--' must be paths.1147 *1148 * case 3: git checkout <something> [--]1149 *1150 * (a) If <something> is a commit, that is to1151 * switch to the branch or detach HEAD at it. As a special case,1152 * if <something> is A...B (missing A or B means HEAD but you can1153 * omit at most one side), and if there is a unique merge base1154 * between A and B, A...B names that merge base.1155 *1156 * (b) If <something> is _not_ a commit, either "--" is present1157 * or <something> is not a path, no -t or -b was given, and1158 * and there is a tracking branch whose name is <something>1159 * in one and only one remote (or if the branch exists on the1160 * remote named in checkout.defaultRemote), then this is a1161 * short-hand to fork local <something> from that1162 * remote-tracking branch.1163 *1164 * (c) Otherwise, if "--" is present, treat it like case (1).1165 *1166 * (d) Otherwise :1167 * - if it's a reference, treat it like case (1)1168 * - else if it's a path, treat it like case (2)1169 * - else: fail.1170 *1171 * case 4: git checkout <something> <paths>1172 *1173 * The first argument must not be ambiguous.1174 * - If it's *only* a reference, treat it like case (1).1175 * - If it's only a path, treat it like case (2).1176 * - else: fail.1177 *1178 */1179if(!argc)1180return0;11811182if(!opts->accept_pathspec) {1183if(argc >1)1184die(_("only one reference expected"));1185 has_dash_dash =1;/* helps disambiguate */1186}11871188 arg = argv[0];1189 dash_dash_pos = -1;1190for(i =0; i < argc; i++) {1191if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1192 dash_dash_pos = i;1193break;1194}1195}1196if(dash_dash_pos ==0)1197return1;/* case (2) */1198else if(dash_dash_pos ==1)1199 has_dash_dash =1;/* case (3) or (1) */1200else if(dash_dash_pos >=2)1201die(_("only one reference expected,%dgiven."), dash_dash_pos);1202 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;12031204if(!strcmp(arg,"-"))1205 arg ="@{-1}";12061207if(get_oid_mb(arg, rev)) {1208/*1209 * Either case (3) or (4), with <something> not being1210 * a commit, or an attempt to use case (1) with an1211 * invalid ref.1212 *1213 * It's likely an error, but we need to find out if1214 * we should auto-create the branch, case (3).(b).1215 */1216int recover_with_dwim = dwim_new_local_branch_ok;12171218int could_be_checkout_paths = !has_dash_dash &&1219check_filename(opts->prefix, arg);12201221if(!has_dash_dash && !no_wildcard(arg))1222 recover_with_dwim =0;12231224/*1225 * Accept "git checkout foo", "git checkout foo --"1226 * and "git switch foo" as candidates for dwim.1227 */1228if(!(argc ==1&& !has_dash_dash) &&1229!(argc ==2&& has_dash_dash) &&1230 opts->accept_pathspec)1231 recover_with_dwim =0;12321233if(recover_with_dwim) {1234const char*remote =unique_tracking_name(arg, rev,1235 dwim_remotes_matched);1236if(remote) {1237if(could_be_checkout_paths)1238die(_("'%s' could be both a local file and a tracking branch.\n"1239"Please use -- (and optionally --no-guess) to disambiguate"),1240 arg);1241*new_branch = arg;1242 arg = remote;1243/* DWIMmed to create local branch, case (3).(b) */1244}else{1245 recover_with_dwim =0;1246}1247}12481249if(!recover_with_dwim) {1250if(has_dash_dash)1251die(_("invalid reference:%s"), arg);1252return argcount;1253}1254}12551256/* we can't end up being in (2) anymore, eat the argument */1257 argcount++;1258 argv++;1259 argc--;12601261setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);12621263if(!opts->source_tree)/* case (1): want a tree */1264die(_("reference is not a tree:%s"), arg);12651266if(!has_dash_dash) {/* case (3).(d) -> (1) */1267/*1268 * Do not complain the most common case1269 * git checkout branch1270 * even if there happen to be a file called 'branch';1271 * it would be extremely annoying.1272 */1273if(argc)1274verify_non_filename(opts->prefix, arg);1275}else if(opts->accept_pathspec) {1276 argcount++;1277 argv++;1278 argc--;1279}12801281return argcount;1282}12831284static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1285{1286int status;1287struct strbuf branch_ref = STRBUF_INIT;12881289trace2_cmd_mode("unborn");12901291if(!opts->new_branch)1292die(_("You are on a branch yet to be born"));1293strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1294 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1295strbuf_release(&branch_ref);1296if(!opts->quiet)1297fprintf(stderr,_("Switched to a new branch '%s'\n"),1298 opts->new_branch);1299return status;1300}13011302static voiddie_expecting_a_branch(const struct branch_info *branch_info)1303{1304struct object_id oid;1305char*to_free;13061307if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1308const char*ref = to_free;13091310if(skip_prefix(ref,"refs/tags/", &ref))1311die(_("a branch is expected, got tag '%s'"), ref);1312if(skip_prefix(ref,"refs/remotes/", &ref))1313die(_("a branch is expected, got remote branch '%s'"), ref);1314die(_("a branch is expected, got '%s'"), ref);1315}1316if(branch_info->commit)1317die(_("a branch is expected, got commit '%s'"), branch_info->name);1318/*1319 * This case should never happen because we already die() on1320 * non-commit, but just in case.1321 */1322die(_("a branch is expected, got '%s'"), branch_info->name);1323}13241325static intcheckout_branch(struct checkout_opts *opts,1326struct branch_info *new_branch_info)1327{1328if(opts->pathspec.nr)1329die(_("paths cannot be used with switching branches"));13301331if(opts->patch_mode)1332die(_("'%s' cannot be used with switching branches"),1333"--patch");13341335if(!opts->overlay_mode)1336die(_("'%s' cannot be used with switching branches"),1337"--no-overlay");13381339if(opts->writeout_stage)1340die(_("'%s' cannot be used with switching branches"),1341"--ours/--theirs");13421343if(opts->force && opts->merge)1344die(_("'%s' cannot be used with '%s'"),"-f","-m");13451346if(opts->discard_changes && opts->merge)1347die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");13481349if(opts->force_detach && opts->new_branch)1350die(_("'%s' cannot be used with '%s'"),1351"--detach","-b/-B/--orphan");13521353if(opts->new_orphan_branch) {1354if(opts->track != BRANCH_TRACK_UNSPECIFIED)1355die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1356}else if(opts->force_detach) {1357if(opts->track != BRANCH_TRACK_UNSPECIFIED)1358die(_("'%s' cannot be used with '%s'"),"--detach","-t");1359}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1360 opts->track = git_branch_track;13611362if(new_branch_info->name && !new_branch_info->commit)1363die(_("Cannot switch branch to a non-commit '%s'"),1364 new_branch_info->name);13651366if(!opts->switch_branch_doing_nothing_is_ok &&1367!new_branch_info->name &&1368!opts->new_branch &&1369!opts->force_detach)1370die(_("missing branch or commit argument"));13711372if(!opts->implicit_detach &&1373!opts->force_detach &&1374!opts->new_branch &&1375!opts->new_branch_force &&1376 new_branch_info->name &&1377!new_branch_info->path)1378die_expecting_a_branch(new_branch_info);13791380if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1381!opts->ignore_other_worktrees) {1382int flag;1383char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1384if(head_ref &&1385(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1386die_if_checked_out(new_branch_info->path,1);1387free(head_ref);1388}13891390if(!new_branch_info->commit && opts->new_branch) {1391struct object_id rev;1392int flag;13931394if(!read_ref_full("HEAD",0, &rev, &flag) &&1395(flag & REF_ISSYMREF) &&is_null_oid(&rev))1396returnswitch_unborn_to_new_branch(opts);1397}1398returnswitch_branches(opts, new_branch_info);1399}14001401static struct option *add_common_options(struct checkout_opts *opts,1402struct option *prevopts)1403{1404struct option options[] = {1405OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1406{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1407"checkout","control recursive updating of submodules",1408 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1409OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1410OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1411 PARSE_OPT_NOCOMPLETE),1412OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1413OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1414N_("conflict style (merge or diff3)")),1415OPT_END()1416};1417struct option *newopts =parse_options_concat(prevopts, options);1418free(prevopts);1419return newopts;1420}14211422static struct option *add_common_switch_branch_options(1423struct checkout_opts *opts,struct option *prevopts)1424{1425struct option options[] = {1426OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1427OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1428 BRANCH_TRACK_EXPLICIT),1429OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1430OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1431N_("update ignored files (default)"),1432 PARSE_OPT_NOCOMPLETE),1433OPT_BOOL(0,"no-guess", &opts->no_dwim_new_local_branch,1434N_("second guess 'git checkout <no-such-branch>'")),1435OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1436N_("do not check if another worktree is holding the given ref")),1437OPT_END()1438};1439struct option *newopts =parse_options_concat(prevopts, options);1440free(prevopts);1441return newopts;1442}14431444static struct option *add_checkout_path_options(struct checkout_opts *opts,1445struct option *prevopts)1446{1447struct option options[] = {1448OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1449N_("checkout our version for unmerged files"),14502, PARSE_OPT_NONEG),1451OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1452N_("checkout their version for unmerged files"),14533, PARSE_OPT_NONEG),1454OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1455OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1456N_("do not limit pathspecs to sparse entries only")),1457OPT_BOOL(0,"overlay", &opts->overlay_mode,N_("use overlay mode (default)")),1458OPT_END()1459};1460struct option *newopts =parse_options_concat(prevopts, options);1461free(prevopts);1462return newopts;1463}14641465static intcheckout_main(int argc,const char**argv,const char*prefix,1466struct checkout_opts *opts,struct option *options,1467const char*const usagestr[])1468{1469struct branch_info new_branch_info;1470int dwim_remotes_matched =0;1471int dwim_new_local_branch;14721473memset(&new_branch_info,0,sizeof(new_branch_info));1474 opts->overwrite_ignore =1;1475 opts->prefix = prefix;1476 opts->show_progress = -1;1477 opts->overlay_mode = -1;14781479git_config(git_checkout_config, opts);14801481 opts->track = BRANCH_TRACK_UNSPECIFIED;14821483 argc =parse_options(argc, argv, prefix, options, usagestr,1484 PARSE_OPT_KEEP_DASHDASH);14851486 dwim_new_local_branch = !opts->no_dwim_new_local_branch;1487if(opts->show_progress <0) {1488if(opts->quiet)1489 opts->show_progress =0;1490else1491 opts->show_progress =isatty(2);1492}14931494if(opts->conflict_style) {1495 opts->merge =1;/* implied */1496git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1497}1498if(opts->force)1499 opts->discard_changes =1;15001501if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1502die(_("-b, -B and --orphan are mutually exclusive"));15031504if(opts->overlay_mode ==1&& opts->patch_mode)1505die(_("-p and --overlay are mutually exclusive"));15061507/*1508 * From here on, new_branch will contain the branch to be checked out,1509 * and new_branch_force and new_orphan_branch will tell us which one of1510 * -b/-B/--orphan is being used.1511 */1512if(opts->new_branch_force)1513 opts->new_branch = opts->new_branch_force;15141515if(opts->new_orphan_branch)1516 opts->new_branch = opts->new_orphan_branch;15171518/* --track without -b/-B/--orphan should DWIM */1519if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1520const char*argv0 = argv[0];1521if(!argc || !strcmp(argv0,"--"))1522die(_("--track needs a branch name"));1523skip_prefix(argv0,"refs/", &argv0);1524skip_prefix(argv0,"remotes/", &argv0);1525 argv0 =strchr(argv0,'/');1526if(!argv0 || !argv0[1])1527die(_("missing branch name; try -b"));1528 opts->new_branch = argv0 +1;1529}15301531/*1532 * Extract branch name from command line arguments, so1533 * all that is left is pathspecs.1534 *1535 * Handle1536 *1537 * 1) git checkout <tree> -- [<paths>]1538 * 2) git checkout -- [<paths>]1539 * 3) git checkout <something> [<paths>]1540 *1541 * including "last branch" syntax and DWIM-ery for names of1542 * remote branches, erroring out for invalid or ambiguous cases.1543 */1544if(argc) {1545struct object_id rev;1546int dwim_ok =1547!opts->patch_mode &&1548 dwim_new_local_branch &&1549 opts->track == BRANCH_TRACK_UNSPECIFIED &&1550!opts->new_branch;1551int n =parse_branchname_arg(argc, argv, dwim_ok,1552&new_branch_info, opts, &rev,1553&dwim_remotes_matched);1554 argv += n;1555 argc -= n;1556}15571558if(argc) {1559parse_pathspec(&opts->pathspec,0,1560 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1561 prefix, argv);15621563if(!opts->pathspec.nr)1564die(_("invalid path specification"));15651566/*1567 * Try to give more helpful suggestion.1568 * new_branch && argc > 1 will be caught later.1569 */1570if(opts->new_branch && argc ==1)1571die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1572 argv[0], opts->new_branch);15731574if(opts->force_detach)1575die(_("git checkout: --detach does not take a path argument '%s'"),1576 argv[0]);15771578if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1579die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1580"checking out of the index."));1581}15821583if(opts->new_branch) {1584struct strbuf buf = STRBUF_INIT;15851586if(opts->new_branch_force)1587 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1588else1589 opts->branch_exists =1590validate_new_branchname(opts->new_branch, &buf,0);1591strbuf_release(&buf);1592}15931594UNLEAK(opts);1595if(opts->patch_mode || opts->pathspec.nr) {1596int ret =checkout_paths(opts, new_branch_info.name);1597if(ret && dwim_remotes_matched >1&&1598 advice_checkout_ambiguous_remote_branch_name)1599advise(_("'%s' matched more than one remote tracking branch.\n"1600"We found%dremotes with a reference that matched. So we fell back\n"1601"on trying to resolve the argument as a path, but failed there too!\n"1602"\n"1603"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1604"you can do so by fully qualifying the name with the --track option:\n"1605"\n"1606" git checkout --track origin/<name>\n"1607"\n"1608"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1609"one remote, e.g. the 'origin' remote, consider setting\n"1610"checkout.defaultRemote=origin in your config."),1611 argv[0],1612 dwim_remotes_matched);1613return ret;1614}else{1615returncheckout_branch(opts, &new_branch_info);1616}1617}16181619intcmd_checkout(int argc,const char**argv,const char*prefix)1620{1621struct checkout_opts opts;1622struct option *options;1623struct option checkout_options[] = {1624OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1625N_("create and checkout a new branch")),1626OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1627N_("create/reset and checkout a branch")),1628OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1629OPT_END()1630};1631int ret;16321633memset(&opts,0,sizeof(opts));1634 opts.no_dwim_new_local_branch =0;1635 opts.switch_branch_doing_nothing_is_ok =1;1636 opts.accept_pathspec =1;1637 opts.implicit_detach =1;16381639 options =parse_options_dup(checkout_options);1640 options =add_common_options(&opts, options);1641 options =add_common_switch_branch_options(&opts, options);1642 options =add_checkout_path_options(&opts, options);16431644 ret =checkout_main(argc, argv, prefix, &opts,1645 options, checkout_usage);1646FREE_AND_NULL(options);1647return ret;1648}16491650intcmd_switch(int argc,const char**argv,const char*prefix)1651{1652struct checkout_opts opts;1653struct option *options = NULL;1654struct option switch_options[] = {1655OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1656N_("create and switch to a new branch")),1657OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1658N_("create/reset and switch to a branch")),1659OPT_BOOL(0,"discard-changes", &opts.discard_changes,1660N_("throw away local modifications")),1661OPT_END()1662};1663int ret;16641665memset(&opts,0,sizeof(opts));1666 opts.no_dwim_new_local_branch =0;1667 opts.accept_pathspec =0;1668 opts.switch_branch_doing_nothing_is_ok =0;1669 opts.implicit_detach =0;16701671 options =parse_options_dup(switch_options);1672 options =add_common_options(&opts, options);1673 options =add_common_switch_branch_options(&opts, options);16741675 ret =checkout_main(argc, argv, prefix, &opts,1676 options, switch_branch_usage);1677FREE_AND_NULL(options);1678return ret;1679}