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; 68 69const char*new_branch; 70const char*new_branch_force; 71const char*new_orphan_branch; 72int new_branch_log; 73enum branch_track track; 74struct diff_options diff_options; 75char*conflict_style; 76 77int branch_exists; 78const char*prefix; 79struct pathspec pathspec; 80const char*from_treeish; 81struct tree *source_tree; 82}; 83 84static intpost_checkout_hook(struct commit *old_commit,struct commit *new_commit, 85int changed) 86{ 87returnrun_hook_le(NULL,"post-checkout", 88oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid), 89oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid), 90 changed ?"1":"0", NULL); 91/* "new_commit" can be NULL when checking out from the index before 92 a commit exists. */ 93 94} 95 96static intupdate_some(const struct object_id *oid,struct strbuf *base, 97const char*pathname,unsigned mode,int stage,void*context) 98{ 99int len; 100struct cache_entry *ce; 101int pos; 102 103if(S_ISDIR(mode)) 104return READ_TREE_RECURSIVE; 105 106 len = base->len +strlen(pathname); 107 ce =make_empty_cache_entry(&the_index, len); 108oidcpy(&ce->oid, oid); 109memcpy(ce->name, base->buf, base->len); 110memcpy(ce->name + base->len, pathname, len - base->len); 111 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 112 ce->ce_namelen = len; 113 ce->ce_mode =create_ce_mode(mode); 114 115/* 116 * If the entry is the same as the current index, we can leave the old 117 * entry in place. Whether it is UPTODATE or not, checkout_entry will 118 * do the right thing. 119 */ 120 pos =cache_name_pos(ce->name, ce->ce_namelen); 121if(pos >=0) { 122struct cache_entry *old = active_cache[pos]; 123if(ce->ce_mode == old->ce_mode && 124oideq(&ce->oid, &old->oid)) { 125 old->ce_flags |= CE_UPDATE; 126discard_cache_entry(ce); 127return0; 128} 129} 130 131add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 132return0; 133} 134 135static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 136{ 137read_tree_recursive(the_repository, tree,"",0,0, 138 pathspec, update_some, NULL); 139 140/* update the index with the given tree's info 141 * for all args, expanding wildcards, and exit 142 * with any non-zero return code. 143 */ 144return0; 145} 146 147static intskip_same_name(const struct cache_entry *ce,int pos) 148{ 149while(++pos < active_nr && 150!strcmp(active_cache[pos]->name, ce->name)) 151;/* skip */ 152return pos; 153} 154 155static intcheck_stage(int stage,const struct cache_entry *ce,int pos, 156int overlay_mode) 157{ 158while(pos < active_nr && 159!strcmp(active_cache[pos]->name, ce->name)) { 160if(ce_stage(active_cache[pos]) == stage) 161return0; 162 pos++; 163} 164if(!overlay_mode) 165return0; 166if(stage ==2) 167returnerror(_("path '%s' does not have our version"), ce->name); 168else 169returnerror(_("path '%s' does not have their version"), ce->name); 170} 171 172static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 173{ 174unsigned seen =0; 175const char*name = ce->name; 176 177while(pos < active_nr) { 178 ce = active_cache[pos]; 179if(strcmp(name, ce->name)) 180break; 181 seen |= (1<<ce_stage(ce)); 182 pos++; 183} 184if((stages & seen) != stages) 185returnerror(_("path '%s' does not have all necessary versions"), 186 name); 187return0; 188} 189 190static intcheckout_stage(int stage,const struct cache_entry *ce,int pos, 191const struct checkout *state,int*nr_checkouts, 192int overlay_mode) 193{ 194while(pos < active_nr && 195!strcmp(active_cache[pos]->name, ce->name)) { 196if(ce_stage(active_cache[pos]) == stage) 197returncheckout_entry(active_cache[pos], state, 198 NULL, nr_checkouts); 199 pos++; 200} 201if(!overlay_mode) { 202unlink_entry(ce); 203return0; 204} 205if(stage ==2) 206returnerror(_("path '%s' does not have our version"), ce->name); 207else 208returnerror(_("path '%s' does not have their version"), ce->name); 209} 210 211static intcheckout_merged(int pos,const struct checkout *state,int*nr_checkouts) 212{ 213struct cache_entry *ce = active_cache[pos]; 214const char*path = ce->name; 215 mmfile_t ancestor, ours, theirs; 216int status; 217struct object_id oid; 218 mmbuffer_t result_buf; 219struct object_id threeway[3]; 220unsigned mode =0; 221 222memset(threeway,0,sizeof(threeway)); 223while(pos < active_nr) { 224int stage; 225 stage =ce_stage(ce); 226if(!stage ||strcmp(path, ce->name)) 227break; 228oidcpy(&threeway[stage -1], &ce->oid); 229if(stage ==2) 230 mode =create_ce_mode(ce->ce_mode); 231 pos++; 232 ce = active_cache[pos]; 233} 234if(is_null_oid(&threeway[1]) ||is_null_oid(&threeway[2])) 235returnerror(_("path '%s' does not have necessary versions"), path); 236 237read_mmblob(&ancestor, &threeway[0]); 238read_mmblob(&ours, &threeway[1]); 239read_mmblob(&theirs, &threeway[2]); 240 241/* 242 * NEEDSWORK: re-create conflicts from merges with 243 * merge.renormalize set, too 244 */ 245 status =ll_merge(&result_buf, path, &ancestor,"base", 246&ours,"ours", &theirs,"theirs", 247 state->istate, NULL); 248free(ancestor.ptr); 249free(ours.ptr); 250free(theirs.ptr); 251if(status <0|| !result_buf.ptr) { 252free(result_buf.ptr); 253returnerror(_("path '%s': cannot merge"), path); 254} 255 256/* 257 * NEEDSWORK: 258 * There is absolutely no reason to write this as a blob object 259 * and create a phony cache entry. This hack is primarily to get 260 * to the write_entry() machinery that massages the contents to 261 * work-tree format and writes out which only allows it for a 262 * cache entry. The code in write_entry() needs to be refactored 263 * to allow us to feed a <buffer, size, mode> instead of a cache 264 * entry. Such a refactoring would help merge_recursive as well 265 * (it also writes the merge result to the object database even 266 * when it may contain conflicts). 267 */ 268if(write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid)) 269die(_("Unable to add merge result for '%s'"), path); 270free(result_buf.ptr); 271 ce =make_transient_cache_entry(mode, &oid, path,2); 272if(!ce) 273die(_("make_cache_entry failed for path '%s'"), path); 274 status =checkout_entry(ce, state, NULL, nr_checkouts); 275discard_cache_entry(ce); 276return status; 277} 278 279static voidmark_ce_for_checkout_overlay(struct cache_entry *ce, 280char*ps_matched, 281const struct checkout_opts *opts) 282{ 283 ce->ce_flags &= ~CE_MATCHED; 284if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 285return; 286if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 287/* 288 * "git checkout tree-ish -- path", but this entry 289 * is in the original index but is not in tree-ish 290 * or does not match the pathspec; it will not be 291 * checked out to the working tree. We will not do 292 * anything to this entry at all. 293 */ 294return; 295/* 296 * Either this entry came from the tree-ish we are 297 * checking the paths out of, or we are checking out 298 * of the index. 299 * 300 * If it comes from the tree-ish, we already know it 301 * matches the pathspec and could just stamp 302 * CE_MATCHED to it from update_some(). But we still 303 * need ps_matched and read_tree_recursive (and 304 * eventually tree_entry_interesting) cannot fill 305 * ps_matched yet. Once it can, we can avoid calling 306 * match_pathspec() for _all_ entries when 307 * opts->source_tree != NULL. 308 */ 309if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) 310 ce->ce_flags |= CE_MATCHED; 311} 312 313static voidmark_ce_for_checkout_no_overlay(struct cache_entry *ce, 314char*ps_matched, 315const struct checkout_opts *opts) 316{ 317 ce->ce_flags &= ~CE_MATCHED; 318if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 319return; 320if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) { 321 ce->ce_flags |= CE_MATCHED; 322if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 323/* 324 * In overlay mode, but the path is not in 325 * tree-ish, which means we should remove it 326 * from the index and the working tree. 327 */ 328 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE; 329} 330} 331 332static intcheckout_paths(const struct checkout_opts *opts, 333const char*revision) 334{ 335int pos; 336struct checkout state = CHECKOUT_INIT; 337static char*ps_matched; 338struct object_id rev; 339struct commit *head; 340int errs =0; 341struct lock_file lock_file = LOCK_INIT; 342int nr_checkouts =0, nr_unmerged =0; 343 344trace2_cmd_mode(opts->patch_mode ?"patch":"path"); 345 346if(opts->track != BRANCH_TRACK_UNSPECIFIED) 347die(_("'%s' cannot be used with updating paths"),"--track"); 348 349if(opts->new_branch_log) 350die(_("'%s' cannot be used with updating paths"),"-l"); 351 352if(opts->force && opts->patch_mode) 353die(_("'%s' cannot be used with updating paths"),"-f"); 354 355if(opts->force_detach) 356die(_("'%s' cannot be used with updating paths"),"--detach"); 357 358if(opts->merge && opts->patch_mode) 359die(_("'%s' cannot be used with%s"),"--merge","--patch"); 360 361if(opts->force && opts->merge) 362die(_("'%s' cannot be used with%s"),"-f","-m"); 363 364if(opts->new_branch) 365die(_("Cannot update paths and switch to branch '%s' at the same time."), 366 opts->new_branch); 367 368if(opts->patch_mode) 369returnrun_add_interactive(revision,"--patch=checkout", 370&opts->pathspec); 371 372repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 373if(read_cache_preload(&opts->pathspec) <0) 374returnerror(_("index file corrupt")); 375 376if(opts->source_tree) 377read_tree_some(opts->source_tree, &opts->pathspec); 378 379 ps_matched =xcalloc(opts->pathspec.nr,1); 380 381/* 382 * Make sure all pathspecs participated in locating the paths 383 * to be checked out. 384 */ 385for(pos =0; pos < active_nr; pos++) 386if(opts->overlay_mode) 387mark_ce_for_checkout_overlay(active_cache[pos], 388 ps_matched, 389 opts); 390else 391mark_ce_for_checkout_no_overlay(active_cache[pos], 392 ps_matched, 393 opts); 394 395if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 396free(ps_matched); 397return1; 398} 399free(ps_matched); 400 401/* "checkout -m path" to recreate conflicted state */ 402if(opts->merge) 403unmerge_marked_index(&the_index); 404 405/* Any unmerged paths? */ 406for(pos =0; pos < active_nr; pos++) { 407const struct cache_entry *ce = active_cache[pos]; 408if(ce->ce_flags & CE_MATCHED) { 409if(!ce_stage(ce)) 410continue; 411if(opts->force) { 412warning(_("path '%s' is unmerged"), ce->name); 413}else if(opts->writeout_stage) { 414 errs |=check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 415}else if(opts->merge) { 416 errs |=check_stages((1<<2) | (1<<3), ce, pos); 417}else{ 418 errs =1; 419error(_("path '%s' is unmerged"), ce->name); 420} 421 pos =skip_same_name(ce, pos) -1; 422} 423} 424if(errs) 425return1; 426 427/* Now we are committed to check them out */ 428 state.force =1; 429 state.refresh_cache =1; 430 state.istate = &the_index; 431 432enable_delayed_checkout(&state); 433for(pos =0; pos < active_nr; pos++) { 434struct cache_entry *ce = active_cache[pos]; 435if(ce->ce_flags & CE_MATCHED) { 436if(!ce_stage(ce)) { 437 errs |=checkout_entry(ce, &state, 438 NULL, &nr_checkouts); 439continue; 440} 441if(opts->writeout_stage) 442 errs |=checkout_stage(opts->writeout_stage, 443 ce, pos, 444&state, 445&nr_checkouts, opts->overlay_mode); 446else if(opts->merge) 447 errs |=checkout_merged(pos, &state, 448&nr_unmerged); 449 pos =skip_same_name(ce, pos) -1; 450} 451} 452remove_marked_cache_entries(&the_index,1); 453remove_scheduled_dirs(); 454 errs |=finish_delayed_checkout(&state, &nr_checkouts); 455 456if(opts->count_checkout_paths) { 457if(nr_unmerged) 458fprintf_ln(stderr,Q_("Recreated%dmerge conflict", 459"Recreated%dmerge conflicts", 460 nr_unmerged), 461 nr_unmerged); 462if(opts->source_tree) 463fprintf_ln(stderr,Q_("Updated%dpath from%s", 464"Updated%dpaths from%s", 465 nr_checkouts), 466 nr_checkouts, 467find_unique_abbrev(&opts->source_tree->object.oid, 468 DEFAULT_ABBREV)); 469else if(!nr_unmerged || nr_checkouts) 470fprintf_ln(stderr,Q_("Updated%dpath from the index", 471"Updated%dpaths from the index", 472 nr_checkouts), 473 nr_checkouts); 474} 475 476if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 477die(_("unable to write new index file")); 478 479read_ref_full("HEAD",0, &rev, NULL); 480 head =lookup_commit_reference_gently(the_repository, &rev,1); 481 482 errs |=post_checkout_hook(head, head,0); 483return errs; 484} 485 486static voidshow_local_changes(struct object *head, 487const struct diff_options *opts) 488{ 489struct rev_info rev; 490/* I think we want full paths, even if we're in a subdirectory. */ 491repo_init_revisions(the_repository, &rev, NULL); 492 rev.diffopt.flags = opts->flags; 493 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 494diff_setup_done(&rev.diffopt); 495add_pending_object(&rev, head, NULL); 496run_diff_index(&rev,0); 497} 498 499static voiddescribe_detached_head(const char*msg,struct commit *commit) 500{ 501struct strbuf sb = STRBUF_INIT; 502 503if(!parse_commit(commit)) 504pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 505if(print_sha1_ellipsis()) { 506fprintf(stderr,"%s %s...%s\n", msg, 507find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 508}else{ 509fprintf(stderr,"%s %s %s\n", msg, 510find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 511} 512strbuf_release(&sb); 513} 514 515static intreset_tree(struct tree *tree,const struct checkout_opts *o, 516int worktree,int*writeout_error) 517{ 518struct unpack_trees_options opts; 519struct tree_desc tree_desc; 520 521memset(&opts,0,sizeof(opts)); 522 opts.head_idx = -1; 523 opts.update = worktree; 524 opts.skip_unmerged = !worktree; 525 opts.reset =1; 526 opts.merge =1; 527 opts.fn = oneway_merge; 528 opts.verbose_update = o->show_progress; 529 opts.src_index = &the_index; 530 opts.dst_index = &the_index; 531parse_tree(tree); 532init_tree_desc(&tree_desc, tree->buffer, tree->size); 533switch(unpack_trees(1, &tree_desc, &opts)) { 534case-2: 535*writeout_error =1; 536/* 537 * We return 0 nevertheless, as the index is all right 538 * and more importantly we have made best efforts to 539 * update paths in the work tree, and we cannot revert 540 * them. 541 */ 542/* fallthrough */ 543case0: 544return0; 545default: 546return128; 547} 548} 549 550struct branch_info { 551const char*name;/* The short name used */ 552const char*path;/* The full name of a real branch */ 553struct commit *commit;/* The named commit */ 554/* 555 * if not null the branch is detached because it's already 556 * checked out in this checkout 557 */ 558char*checkout; 559}; 560 561static voidsetup_branch_path(struct branch_info *branch) 562{ 563struct strbuf buf = STRBUF_INIT; 564 565strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 566if(strcmp(buf.buf, branch->name)) 567 branch->name =xstrdup(buf.buf); 568strbuf_splice(&buf,0,0,"refs/heads/",11); 569 branch->path =strbuf_detach(&buf, NULL); 570} 571 572static intmerge_working_tree(const struct checkout_opts *opts, 573struct branch_info *old_branch_info, 574struct branch_info *new_branch_info, 575int*writeout_error) 576{ 577int ret; 578struct lock_file lock_file = LOCK_INIT; 579struct tree *new_tree; 580 581hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 582if(read_cache_preload(NULL) <0) 583returnerror(_("index file corrupt")); 584 585resolve_undo_clear(); 586if(opts->new_orphan_branch && opts->orphan_from_empty_tree) { 587if(new_branch_info->commit) 588BUG("'switch --orphan' should never accept a commit as starting point"); 589 new_tree =parse_tree_indirect(the_hash_algo->empty_tree); 590}else 591 new_tree =get_commit_tree(new_branch_info->commit); 592if(opts->discard_changes) { 593 ret =reset_tree(new_tree, opts,1, writeout_error); 594if(ret) 595return ret; 596}else{ 597struct tree_desc trees[2]; 598struct tree *tree; 599struct unpack_trees_options topts; 600 601memset(&topts,0,sizeof(topts)); 602 topts.head_idx = -1; 603 topts.src_index = &the_index; 604 topts.dst_index = &the_index; 605 606setup_unpack_trees_porcelain(&topts,"checkout"); 607 608refresh_cache(REFRESH_QUIET); 609 610if(unmerged_cache()) { 611error(_("you need to resolve your current index first")); 612return1; 613} 614 615/* 2-way merge to the new branch */ 616 topts.initial_checkout =is_cache_unborn(); 617 topts.update =1; 618 topts.merge =1; 619 topts.gently = opts->merge && old_branch_info->commit; 620 topts.verbose_update = opts->show_progress; 621 topts.fn = twoway_merge; 622if(opts->overwrite_ignore) { 623 topts.dir =xcalloc(1,sizeof(*topts.dir)); 624 topts.dir->flags |= DIR_SHOW_IGNORED; 625setup_standard_excludes(topts.dir); 626} 627 tree =parse_tree_indirect(old_branch_info->commit ? 628&old_branch_info->commit->object.oid : 629 the_hash_algo->empty_tree); 630init_tree_desc(&trees[0], tree->buffer, tree->size); 631parse_tree(new_tree); 632 tree = new_tree; 633init_tree_desc(&trees[1], tree->buffer, tree->size); 634 635 ret =unpack_trees(2, trees, &topts); 636clear_unpack_trees_porcelain(&topts); 637if(ret == -1) { 638/* 639 * Unpack couldn't do a trivial merge; either 640 * give up or do a real merge, depending on 641 * whether the merge flag was used. 642 */ 643struct tree *result; 644struct tree *work; 645struct merge_options o; 646if(!opts->merge) 647return1; 648 649/* 650 * Without old_branch_info->commit, the below is the same as 651 * the two-tree unpack we already tried and failed. 652 */ 653if(!old_branch_info->commit) 654return1; 655 656/* Do more real merge */ 657 658/* 659 * We update the index fully, then write the 660 * tree from the index, then merge the new 661 * branch with the current tree, with the old 662 * branch as the base. Then we reset the index 663 * (but not the working tree) to the new 664 * branch, leaving the working tree as the 665 * merged version, but skipping unmerged 666 * entries in the index. 667 */ 668 669add_files_to_cache(NULL, NULL,0); 670/* 671 * NEEDSWORK: carrying over local changes 672 * when branches have different end-of-line 673 * normalization (or clean+smudge rules) is 674 * a pain; plumb in an option to set 675 * o.renormalize? 676 */ 677init_merge_options(&o, the_repository); 678 o.verbosity =0; 679 work =write_tree_from_memory(&o); 680 681 ret =reset_tree(new_tree, 682 opts,1, 683 writeout_error); 684if(ret) 685return ret; 686 o.ancestor = old_branch_info->name; 687 o.branch1 = new_branch_info->name; 688 o.branch2 ="local"; 689 ret =merge_trees(&o, 690 new_tree, 691 work, 692get_commit_tree(old_branch_info->commit), 693&result); 694if(ret <0) 695exit(128); 696 ret =reset_tree(new_tree, 697 opts,0, 698 writeout_error); 699strbuf_release(&o.obuf); 700if(ret) 701return ret; 702} 703} 704 705if(!active_cache_tree) 706 active_cache_tree =cache_tree(); 707 708if(!cache_tree_fully_valid(active_cache_tree)) 709cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 710 711if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 712die(_("unable to write new index file")); 713 714if(!opts->discard_changes && !opts->quiet && new_branch_info->commit) 715show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 716 717return0; 718} 719 720static voidreport_tracking(struct branch_info *new_branch_info) 721{ 722struct strbuf sb = STRBUF_INIT; 723struct branch *branch =branch_get(new_branch_info->name); 724 725if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 726return; 727fputs(sb.buf, stdout); 728strbuf_release(&sb); 729} 730 731static voidupdate_refs_for_switch(const struct checkout_opts *opts, 732struct branch_info *old_branch_info, 733struct branch_info *new_branch_info) 734{ 735struct strbuf msg = STRBUF_INIT; 736const char*old_desc, *reflog_msg; 737if(opts->new_branch) { 738if(opts->new_orphan_branch) { 739char*refname; 740 741 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 742if(opts->new_branch_log && 743!should_autocreate_reflog(refname)) { 744int ret; 745struct strbuf err = STRBUF_INIT; 746 747 ret =safe_create_reflog(refname,1, &err); 748if(ret) { 749fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 750 opts->new_orphan_branch, err.buf); 751strbuf_release(&err); 752free(refname); 753return; 754} 755strbuf_release(&err); 756} 757free(refname); 758} 759else 760create_branch(the_repository, 761 opts->new_branch, new_branch_info->name, 762 opts->new_branch_force ?1:0, 763 opts->new_branch_force ?1:0, 764 opts->new_branch_log, 765 opts->quiet, 766 opts->track); 767 new_branch_info->name = opts->new_branch; 768setup_branch_path(new_branch_info); 769} 770 771 old_desc = old_branch_info->name; 772if(!old_desc && old_branch_info->commit) 773 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 774 775 reflog_msg =getenv("GIT_REFLOG_ACTION"); 776if(!reflog_msg) 777strbuf_addf(&msg,"checkout: moving from%sto%s", 778 old_desc ? old_desc :"(invalid)", new_branch_info->name); 779else 780strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 781 782if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 783/* Nothing to do. */ 784}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 785update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 786 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 787if(!opts->quiet) { 788if(old_branch_info->path && 789 advice_detached_head && !opts->force_detach) 790detach_advice(new_branch_info->name); 791describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 792} 793}else if(new_branch_info->path) {/* Switch branches. */ 794if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 795die(_("unable to update HEAD")); 796if(!opts->quiet) { 797if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 798if(opts->new_branch_force) 799fprintf(stderr,_("Reset branch '%s'\n"), 800 new_branch_info->name); 801else 802fprintf(stderr,_("Already on '%s'\n"), 803 new_branch_info->name); 804}else if(opts->new_branch) { 805if(opts->branch_exists) 806fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 807else 808fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 809}else{ 810fprintf(stderr,_("Switched to branch '%s'\n"), 811 new_branch_info->name); 812} 813} 814if(old_branch_info->path && old_branch_info->name) { 815if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 816delete_reflog(old_branch_info->path); 817} 818} 819remove_branch_state(the_repository, !opts->quiet); 820strbuf_release(&msg); 821if(!opts->quiet && 822(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 823report_tracking(new_branch_info); 824} 825 826static intadd_pending_uninteresting_ref(const char*refname, 827const struct object_id *oid, 828int flags,void*cb_data) 829{ 830add_pending_oid(cb_data, refname, oid, UNINTERESTING); 831return0; 832} 833 834static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 835{ 836strbuf_addstr(sb," "); 837strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 838strbuf_addch(sb,' '); 839if(!parse_commit(commit)) 840pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 841strbuf_addch(sb,'\n'); 842} 843 844#define ORPHAN_CUTOFF 4 845static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 846{ 847struct commit *c, *last = NULL; 848struct strbuf sb = STRBUF_INIT; 849int lost =0; 850while((c =get_revision(revs)) != NULL) { 851if(lost < ORPHAN_CUTOFF) 852describe_one_orphan(&sb, c); 853 last = c; 854 lost++; 855} 856if(ORPHAN_CUTOFF < lost) { 857int more = lost - ORPHAN_CUTOFF; 858if(more ==1) 859describe_one_orphan(&sb, last); 860else 861strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 862} 863 864fprintf(stderr, 865Q_( 866/* The singular version */ 867"Warning: you are leaving%dcommit behind, " 868"not connected to\n" 869"any of your branches:\n\n" 870"%s\n", 871/* The plural version */ 872"Warning: you are leaving%dcommits behind, " 873"not connected to\n" 874"any of your branches:\n\n" 875"%s\n", 876/* Give ngettext() the count */ 877 lost), 878 lost, 879 sb.buf); 880strbuf_release(&sb); 881 882if(advice_detached_head) 883fprintf(stderr, 884Q_( 885/* The singular version */ 886"If you want to keep it by creating a new branch, " 887"this may be a good time\nto do so with:\n\n" 888" git branch <new-branch-name>%s\n\n", 889/* The plural version */ 890"If you want to keep them by creating a new branch, " 891"this may be a good time\nto do so with:\n\n" 892" git branch <new-branch-name>%s\n\n", 893/* Give ngettext() the count */ 894 lost), 895find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 896} 897 898/* 899 * We are about to leave commit that was at the tip of a detached 900 * HEAD. If it is not reachable from any ref, this is the last chance 901 * for the user to do so without resorting to reflog. 902 */ 903static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 904{ 905struct rev_info revs; 906struct object *object = &old_commit->object; 907 908repo_init_revisions(the_repository, &revs, NULL); 909setup_revisions(0, NULL, &revs, NULL); 910 911 object->flags &= ~UNINTERESTING; 912add_pending_object(&revs, object,oid_to_hex(&object->oid)); 913 914for_each_ref(add_pending_uninteresting_ref, &revs); 915if(new_commit) 916add_pending_oid(&revs,"HEAD", 917&new_commit->object.oid, 918 UNINTERESTING); 919 920if(prepare_revision_walk(&revs)) 921die(_("internal error in revision walk")); 922if(!(old_commit->object.flags & UNINTERESTING)) 923suggest_reattach(old_commit, &revs); 924else 925describe_detached_head(_("Previous HEAD position was"), old_commit); 926 927/* Clean up objects used, as they will be reused. */ 928clear_commit_marks_all(ALL_REV_FLAGS); 929} 930 931static intswitch_branches(const struct checkout_opts *opts, 932struct branch_info *new_branch_info) 933{ 934int ret =0; 935struct branch_info old_branch_info; 936void*path_to_free; 937struct object_id rev; 938int flag, writeout_error =0; 939int do_merge =1; 940 941trace2_cmd_mode("branch"); 942 943memset(&old_branch_info,0,sizeof(old_branch_info)); 944 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag); 945if(old_branch_info.path) 946 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1); 947if(!(flag & REF_ISSYMREF)) 948 old_branch_info.path = NULL; 949 950if(old_branch_info.path) 951skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name); 952 953if(opts->new_orphan_branch && opts->orphan_from_empty_tree) { 954if(new_branch_info->name) 955BUG("'switch --orphan' should never accept a commit as starting point"); 956 new_branch_info->commit = NULL; 957 new_branch_info->name ="(empty)"; 958 do_merge =1; 959} 960 961if(!new_branch_info->name) { 962 new_branch_info->name ="HEAD"; 963 new_branch_info->commit = old_branch_info.commit; 964if(!new_branch_info->commit) 965die(_("You are on a branch yet to be born")); 966parse_commit_or_die(new_branch_info->commit); 967 968if(opts->only_merge_on_switching_branches) 969 do_merge =0; 970} 971 972if(do_merge) { 973 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error); 974if(ret) { 975free(path_to_free); 976return ret; 977} 978} 979 980if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit) 981orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit); 982 983update_refs_for_switch(opts, &old_branch_info, new_branch_info); 984 985 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1); 986free(path_to_free); 987return ret || writeout_error; 988} 989 990static intgit_checkout_config(const char*var,const char*value,void*cb) 991{ 992if(!strcmp(var,"diff.ignoresubmodules")) { 993struct checkout_opts *opts = cb; 994handle_ignore_submodules_arg(&opts->diff_options, value); 995return0; 996} 997 998if(starts_with(var,"submodule.")) 999returngit_default_submodule_config(var, value, NULL);10001001returngit_xmerge_config(var, value, NULL);1002}10031004static voidsetup_new_branch_info_and_source_tree(1005struct branch_info *new_branch_info,1006struct checkout_opts *opts,1007struct object_id *rev,1008const char*arg)1009{1010struct tree **source_tree = &opts->source_tree;1011struct object_id branch_rev;10121013 new_branch_info->name = arg;1014setup_branch_path(new_branch_info);10151016if(!check_refname_format(new_branch_info->path,0) &&1017!read_ref(new_branch_info->path, &branch_rev))1018oidcpy(rev, &branch_rev);1019else1020 new_branch_info->path = NULL;/* not an existing branch */10211022 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1023if(!new_branch_info->commit) {1024/* not a commit */1025*source_tree =parse_tree_indirect(rev);1026}else{1027parse_commit_or_die(new_branch_info->commit);1028*source_tree =get_commit_tree(new_branch_info->commit);1029}1030}10311032static intparse_branchname_arg(int argc,const char**argv,1033int dwim_new_local_branch_ok,1034struct branch_info *new_branch_info,1035struct checkout_opts *opts,1036struct object_id *rev,1037int*dwim_remotes_matched)1038{1039const char**new_branch = &opts->new_branch;1040int argcount =0;1041const char*arg;1042int dash_dash_pos;1043int has_dash_dash =0;1044int i;10451046/*1047 * case 1: git checkout <ref> -- [<paths>]1048 *1049 * <ref> must be a valid tree, everything after the '--' must be1050 * a path.1051 *1052 * case 2: git checkout -- [<paths>]1053 *1054 * everything after the '--' must be paths.1055 *1056 * case 3: git checkout <something> [--]1057 *1058 * (a) If <something> is a commit, that is to1059 * switch to the branch or detach HEAD at it. As a special case,1060 * if <something> is A...B (missing A or B means HEAD but you can1061 * omit at most one side), and if there is a unique merge base1062 * between A and B, A...B names that merge base.1063 *1064 * (b) If <something> is _not_ a commit, either "--" is present1065 * or <something> is not a path, no -t or -b was given, and1066 * and there is a tracking branch whose name is <something>1067 * in one and only one remote (or if the branch exists on the1068 * remote named in checkout.defaultRemote), then this is a1069 * short-hand to fork local <something> from that1070 * remote-tracking branch.1071 *1072 * (c) Otherwise, if "--" is present, treat it like case (1).1073 *1074 * (d) Otherwise :1075 * - if it's a reference, treat it like case (1)1076 * - else if it's a path, treat it like case (2)1077 * - else: fail.1078 *1079 * case 4: git checkout <something> <paths>1080 *1081 * The first argument must not be ambiguous.1082 * - If it's *only* a reference, treat it like case (1).1083 * - If it's only a path, treat it like case (2).1084 * - else: fail.1085 *1086 */1087if(!argc)1088return0;10891090if(!opts->accept_pathspec) {1091if(argc >1)1092die(_("only one reference expected"));1093 has_dash_dash =1;/* helps disambiguate */1094}10951096 arg = argv[0];1097 dash_dash_pos = -1;1098for(i =0; i < argc; i++) {1099if(opts->accept_pathspec && !strcmp(argv[i],"--")) {1100 dash_dash_pos = i;1101break;1102}1103}1104if(dash_dash_pos ==0)1105return1;/* case (2) */1106else if(dash_dash_pos ==1)1107 has_dash_dash =1;/* case (3) or (1) */1108else if(dash_dash_pos >=2)1109die(_("only one reference expected,%dgiven."), dash_dash_pos);1110 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;11111112if(!strcmp(arg,"-"))1113 arg ="@{-1}";11141115if(get_oid_mb(arg, rev)) {1116/*1117 * Either case (3) or (4), with <something> not being1118 * a commit, or an attempt to use case (1) with an1119 * invalid ref.1120 *1121 * It's likely an error, but we need to find out if1122 * we should auto-create the branch, case (3).(b).1123 */1124int recover_with_dwim = dwim_new_local_branch_ok;11251126int could_be_checkout_paths = !has_dash_dash &&1127check_filename(opts->prefix, arg);11281129if(!has_dash_dash && !no_wildcard(arg))1130 recover_with_dwim =0;11311132/*1133 * Accept "git checkout foo", "git checkout foo --"1134 * and "git switch foo" as candidates for dwim.1135 */1136if(!(argc ==1&& !has_dash_dash) &&1137!(argc ==2&& has_dash_dash) &&1138 opts->accept_pathspec)1139 recover_with_dwim =0;11401141if(recover_with_dwim) {1142const char*remote =unique_tracking_name(arg, rev,1143 dwim_remotes_matched);1144if(remote) {1145if(could_be_checkout_paths)1146die(_("'%s' could be both a local file and a tracking branch.\n"1147"Please use -- (and optionally --no-guess) to disambiguate"),1148 arg);1149*new_branch = arg;1150 arg = remote;1151/* DWIMmed to create local branch, case (3).(b) */1152}else{1153 recover_with_dwim =0;1154}1155}11561157if(!recover_with_dwim) {1158if(has_dash_dash)1159die(_("invalid reference:%s"), arg);1160return argcount;1161}1162}11631164/* we can't end up being in (2) anymore, eat the argument */1165 argcount++;1166 argv++;1167 argc--;11681169setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);11701171if(!opts->source_tree)/* case (1): want a tree */1172die(_("reference is not a tree:%s"), arg);11731174if(!has_dash_dash) {/* case (3).(d) -> (1) */1175/*1176 * Do not complain the most common case1177 * git checkout branch1178 * even if there happen to be a file called 'branch';1179 * it would be extremely annoying.1180 */1181if(argc)1182verify_non_filename(opts->prefix, arg);1183}else if(opts->accept_pathspec) {1184 argcount++;1185 argv++;1186 argc--;1187}11881189return argcount;1190}11911192static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1193{1194int status;1195struct strbuf branch_ref = STRBUF_INIT;11961197trace2_cmd_mode("unborn");11981199if(!opts->new_branch)1200die(_("You are on a branch yet to be born"));1201strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1202 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1203strbuf_release(&branch_ref);1204if(!opts->quiet)1205fprintf(stderr,_("Switched to a new branch '%s'\n"),1206 opts->new_branch);1207return status;1208}12091210static voiddie_expecting_a_branch(const struct branch_info *branch_info)1211{1212struct object_id oid;1213char*to_free;12141215if(dwim_ref(branch_info->name,strlen(branch_info->name), &oid, &to_free) ==1) {1216const char*ref = to_free;12171218if(skip_prefix(ref,"refs/tags/", &ref))1219die(_("a branch is expected, got tag '%s'"), ref);1220if(skip_prefix(ref,"refs/remotes/", &ref))1221die(_("a branch is expected, got remote branch '%s'"), ref);1222die(_("a branch is expected, got '%s'"), ref);1223}1224if(branch_info->commit)1225die(_("a branch is expected, got commit '%s'"), branch_info->name);1226/*1227 * This case should never happen because we already die() on1228 * non-commit, but just in case.1229 */1230die(_("a branch is expected, got '%s'"), branch_info->name);1231}12321233static voiddie_if_some_operation_in_progress(void)1234{1235struct wt_status_state state;12361237memset(&state,0,sizeof(state));1238wt_status_get_state(the_repository, &state,0);12391240if(state.merge_in_progress)1241die(_("cannot switch branch while merging\n"1242"Consider\"git merge --quit\""1243"or\"git worktree add\"."));1244if(state.am_in_progress)1245die(_("cannot switch branch in the middle of an am session\n"1246"Consider\"git am --quit\""1247"or\"git worktree add\"."));1248if(state.rebase_interactive_in_progress || state.rebase_in_progress)1249die(_("cannot switch branch while rebasing\n"1250"Consider\"git rebase --quit\""1251"or\"git worktree add\"."));1252if(state.cherry_pick_in_progress)1253die(_("cannot switch branch while cherry-picking\n"1254"Consider\"git cherry-pick --quit\""1255"or\"git worktree add\"."));1256if(state.revert_in_progress)1257die(_("cannot switch branch while reverting\n"1258"Consider\"git revert --quit\""1259"or\"git worktree add\"."));1260if(state.bisect_in_progress)1261die(_("cannot switch branch while bisecting\n"1262"Consider\"git bisect reset HEAD\""1263"or\"git worktree add\"."));1264}12651266static intcheckout_branch(struct checkout_opts *opts,1267struct branch_info *new_branch_info)1268{1269if(opts->pathspec.nr)1270die(_("paths cannot be used with switching branches"));12711272if(opts->patch_mode)1273die(_("'%s' cannot be used with switching branches"),1274"--patch");12751276if(!opts->overlay_mode)1277die(_("'%s' cannot be used with switching branches"),1278"--no-overlay");12791280if(opts->writeout_stage)1281die(_("'%s' cannot be used with switching branches"),1282"--ours/--theirs");12831284if(opts->force && opts->merge)1285die(_("'%s' cannot be used with '%s'"),"-f","-m");12861287if(opts->discard_changes && opts->merge)1288die(_("'%s' cannot be used with '%s'"),"--discard-changes","--merge");12891290if(opts->force_detach && opts->new_branch)1291die(_("'%s' cannot be used with '%s'"),1292"--detach","-b/-B/--orphan");12931294if(opts->new_orphan_branch) {1295if(opts->track != BRANCH_TRACK_UNSPECIFIED)1296die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1297if(opts->orphan_from_empty_tree && new_branch_info->name)1298die(_("'%s' cannot take <start-point>"),"--orphan");1299}else if(opts->force_detach) {1300if(opts->track != BRANCH_TRACK_UNSPECIFIED)1301die(_("'%s' cannot be used with '%s'"),"--detach","-t");1302}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1303 opts->track = git_branch_track;13041305if(new_branch_info->name && !new_branch_info->commit)1306die(_("Cannot switch branch to a non-commit '%s'"),1307 new_branch_info->name);13081309if(!opts->switch_branch_doing_nothing_is_ok &&1310!new_branch_info->name &&1311!opts->new_branch &&1312!opts->force_detach)1313die(_("missing branch or commit argument"));13141315if(!opts->implicit_detach &&1316!opts->force_detach &&1317!opts->new_branch &&1318!opts->new_branch_force &&1319 new_branch_info->name &&1320!new_branch_info->path)1321die_expecting_a_branch(new_branch_info);13221323if(!opts->can_switch_when_in_progress)1324die_if_some_operation_in_progress();13251326if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1327!opts->ignore_other_worktrees) {1328int flag;1329char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1330if(head_ref &&1331(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1332die_if_checked_out(new_branch_info->path,1);1333free(head_ref);1334}13351336if(!new_branch_info->commit && opts->new_branch) {1337struct object_id rev;1338int flag;13391340if(!read_ref_full("HEAD",0, &rev, &flag) &&1341(flag & REF_ISSYMREF) &&is_null_oid(&rev))1342returnswitch_unborn_to_new_branch(opts);1343}1344returnswitch_branches(opts, new_branch_info);1345}13461347static struct option *add_common_options(struct checkout_opts *opts,1348struct option *prevopts)1349{1350struct option options[] = {1351OPT__QUIET(&opts->quiet,N_("suppress progress reporting")),1352{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1353"checkout","control recursive updating of submodules",1354 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1355OPT_BOOL(0,"progress", &opts->show_progress,N_("force progress reporting")),1356OPT__FORCE(&opts->force,N_("force checkout (throw away local modifications)"),1357 PARSE_OPT_NOCOMPLETE),1358OPT_BOOL('m',"merge", &opts->merge,N_("perform a 3-way merge with the new branch")),1359OPT_STRING(0,"conflict", &opts->conflict_style,N_("style"),1360N_("conflict style (merge or diff3)")),1361OPT_END()1362};1363struct option *newopts =parse_options_concat(prevopts, options);1364free(prevopts);1365return newopts;1366}13671368static struct option *add_common_switch_branch_options(1369struct checkout_opts *opts,struct option *prevopts)1370{1371struct option options[] = {1372OPT_BOOL('d',"detach", &opts->force_detach,N_("detach HEAD at named commit")),1373OPT_SET_INT('t',"track", &opts->track,N_("set upstream info for new branch"),1374 BRANCH_TRACK_EXPLICIT),1375OPT_STRING(0,"orphan", &opts->new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1376OPT_BOOL_F(0,"overwrite-ignore", &opts->overwrite_ignore,1377N_("update ignored files (default)"),1378 PARSE_OPT_NOCOMPLETE),1379OPT_BOOL(0,"ignore-other-worktrees", &opts->ignore_other_worktrees,1380N_("do not check if another worktree is holding the given ref")),1381OPT_END()1382};1383struct option *newopts =parse_options_concat(prevopts, options);1384free(prevopts);1385return newopts;1386}13871388static struct option *add_checkout_path_options(struct checkout_opts *opts,1389struct option *prevopts)1390{1391struct option options[] = {1392OPT_SET_INT_F('2',"ours", &opts->writeout_stage,1393N_("checkout our version for unmerged files"),13942, PARSE_OPT_NONEG),1395OPT_SET_INT_F('3',"theirs", &opts->writeout_stage,1396N_("checkout their version for unmerged files"),13973, PARSE_OPT_NONEG),1398OPT_BOOL('p',"patch", &opts->patch_mode,N_("select hunks interactively")),1399OPT_BOOL(0,"ignore-skip-worktree-bits", &opts->ignore_skipworktree,1400N_("do not limit pathspecs to sparse entries only")),1401OPT_BOOL(0,"overlay", &opts->overlay_mode,N_("use overlay mode (default)")),1402OPT_END()1403};1404struct option *newopts =parse_options_concat(prevopts, options);1405free(prevopts);1406return newopts;1407}14081409static intcheckout_main(int argc,const char**argv,const char*prefix,1410struct checkout_opts *opts,struct option *options,1411const char*const usagestr[])1412{1413struct branch_info new_branch_info;1414int dwim_remotes_matched =0;1415int parseopt_flags =0;14161417memset(&new_branch_info,0,sizeof(new_branch_info));1418 opts->overwrite_ignore =1;1419 opts->prefix = prefix;1420 opts->show_progress = -1;1421 opts->overlay_mode = -1;14221423git_config(git_checkout_config, opts);14241425 opts->track = BRANCH_TRACK_UNSPECIFIED;14261427if(!opts->accept_pathspec && !opts->accept_ref)1428BUG("make up your mind, you need to take _something_");1429if(opts->accept_pathspec && opts->accept_ref)1430 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;14311432 argc =parse_options(argc, argv, prefix, options,1433 usagestr, parseopt_flags);14341435if(opts->show_progress <0) {1436if(opts->quiet)1437 opts->show_progress =0;1438else1439 opts->show_progress =isatty(2);1440}14411442if(opts->conflict_style) {1443 opts->merge =1;/* implied */1444git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);1445}1446if(opts->force)1447 opts->discard_changes =1;14481449if((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) >1)1450die(_("-b, -B and --orphan are mutually exclusive"));14511452if(opts->overlay_mode ==1&& opts->patch_mode)1453die(_("-p and --overlay are mutually exclusive"));14541455/*1456 * From here on, new_branch will contain the branch to be checked out,1457 * and new_branch_force and new_orphan_branch will tell us which one of1458 * -b/-B/--orphan is being used.1459 */1460if(opts->new_branch_force)1461 opts->new_branch = opts->new_branch_force;14621463if(opts->new_orphan_branch)1464 opts->new_branch = opts->new_orphan_branch;14651466/* --track without -b/-B/--orphan should DWIM */1467if(opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {1468const char*argv0 = argv[0];1469if(!argc || !strcmp(argv0,"--"))1470die(_("--track needs a branch name"));1471skip_prefix(argv0,"refs/", &argv0);1472skip_prefix(argv0,"remotes/", &argv0);1473 argv0 =strchr(argv0,'/');1474if(!argv0 || !argv0[1])1475die(_("missing branch name; try -b"));1476 opts->new_branch = argv0 +1;1477}14781479/*1480 * Extract branch name from command line arguments, so1481 * all that is left is pathspecs.1482 *1483 * Handle1484 *1485 * 1) git checkout <tree> -- [<paths>]1486 * 2) git checkout -- [<paths>]1487 * 3) git checkout <something> [<paths>]1488 *1489 * including "last branch" syntax and DWIM-ery for names of1490 * remote branches, erroring out for invalid or ambiguous cases.1491 */1492if(argc && opts->accept_ref) {1493struct object_id rev;1494int dwim_ok =1495!opts->patch_mode &&1496 opts->dwim_new_local_branch &&1497 opts->track == BRANCH_TRACK_UNSPECIFIED &&1498!opts->new_branch;1499int n =parse_branchname_arg(argc, argv, dwim_ok,1500&new_branch_info, opts, &rev,1501&dwim_remotes_matched);1502 argv += n;1503 argc -= n;1504}else if(!opts->accept_ref && opts->from_treeish) {1505struct object_id rev;15061507if(get_oid_mb(opts->from_treeish, &rev))1508die(_("could not resolve%s"), opts->from_treeish);15091510setup_new_branch_info_and_source_tree(&new_branch_info,1511 opts, &rev,1512 opts->from_treeish);15131514if(!opts->source_tree)1515die(_("reference is not a tree:%s"), opts->from_treeish);1516}15171518if(argc) {1519parse_pathspec(&opts->pathspec,0,1520 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1521 prefix, argv);15221523if(!opts->pathspec.nr)1524die(_("invalid path specification"));15251526/*1527 * Try to give more helpful suggestion.1528 * new_branch && argc > 1 will be caught later.1529 */1530if(opts->new_branch && argc ==1)1531die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1532 argv[0], opts->new_branch);15331534if(opts->force_detach)1535die(_("git checkout: --detach does not take a path argument '%s'"),1536 argv[0]);15371538if(1< !!opts->writeout_stage + !!opts->force + !!opts->merge)1539die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1540"checking out of the index."));1541}15421543if(opts->new_branch) {1544struct strbuf buf = STRBUF_INIT;15451546if(opts->new_branch_force)1547 opts->branch_exists =validate_branchname(opts->new_branch, &buf);1548else1549 opts->branch_exists =1550validate_new_branchname(opts->new_branch, &buf,0);1551strbuf_release(&buf);1552}15531554UNLEAK(opts);1555if(opts->patch_mode || opts->pathspec.nr) {1556int ret =checkout_paths(opts, new_branch_info.name);1557if(ret && dwim_remotes_matched >1&&1558 advice_checkout_ambiguous_remote_branch_name)1559advise(_("'%s' matched more than one remote tracking branch.\n"1560"We found%dremotes with a reference that matched. So we fell back\n"1561"on trying to resolve the argument as a path, but failed there too!\n"1562"\n"1563"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1564"you can do so by fully qualifying the name with the --track option:\n"1565"\n"1566" git checkout --track origin/<name>\n"1567"\n"1568"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1569"one remote, e.g. the 'origin' remote, consider setting\n"1570"checkout.defaultRemote=origin in your config."),1571 argv[0],1572 dwim_remotes_matched);1573return ret;1574}else{1575returncheckout_branch(opts, &new_branch_info);1576}1577}15781579intcmd_checkout(int argc,const char**argv,const char*prefix)1580{1581struct checkout_opts opts;1582struct option *options;1583struct option checkout_options[] = {1584OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1585N_("create and checkout a new branch")),1586OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1587N_("create/reset and checkout a branch")),1588OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1589OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1590N_("second guess 'git checkout <no-such-branch>' (default)")),1591OPT_END()1592};1593int ret;15941595memset(&opts,0,sizeof(opts));1596 opts.dwim_new_local_branch =1;1597 opts.switch_branch_doing_nothing_is_ok =1;1598 opts.only_merge_on_switching_branches =0;1599 opts.accept_ref =1;1600 opts.accept_pathspec =1;1601 opts.implicit_detach =1;1602 opts.can_switch_when_in_progress =1;1603 opts.orphan_from_empty_tree =0;16041605 options =parse_options_dup(checkout_options);1606 options =add_common_options(&opts, options);1607 options =add_common_switch_branch_options(&opts, options);1608 options =add_checkout_path_options(&opts, options);16091610 ret =checkout_main(argc, argv, prefix, &opts,1611 options, checkout_usage);1612FREE_AND_NULL(options);1613return ret;1614}16151616intcmd_switch(int argc,const char**argv,const char*prefix)1617{1618struct checkout_opts opts;1619struct option *options = NULL;1620struct option switch_options[] = {1621OPT_STRING('c',"create", &opts.new_branch,N_("branch"),1622N_("create and switch to a new branch")),1623OPT_STRING('C',"force-create", &opts.new_branch_force,N_("branch"),1624N_("create/reset and switch to a branch")),1625OPT_BOOL(0,"guess", &opts.dwim_new_local_branch,1626N_("second guess 'git switch <no-such-branch>'")),1627OPT_BOOL(0,"discard-changes", &opts.discard_changes,1628N_("throw away local modifications")),1629OPT_END()1630};1631int ret;16321633memset(&opts,0,sizeof(opts));1634 opts.dwim_new_local_branch =1;1635 opts.accept_ref =1;1636 opts.accept_pathspec =0;1637 opts.switch_branch_doing_nothing_is_ok =0;1638 opts.only_merge_on_switching_branches =1;1639 opts.implicit_detach =0;1640 opts.can_switch_when_in_progress =0;1641 opts.orphan_from_empty_tree =1;16421643 options =parse_options_dup(switch_options);1644 options =add_common_options(&opts, options);1645 options =add_common_switch_branch_options(&opts, options);16461647 ret =checkout_main(argc, argv, prefix, &opts,1648 options, switch_branch_usage);1649FREE_AND_NULL(options);1650return ret;1651}16521653intcmd_restore(int argc,const char**argv,const char*prefix)1654{1655struct checkout_opts opts;1656struct option *options;1657struct option restore_options[] = {1658OPT_STRING('s',"source", &opts.from_treeish,"<tree-ish>",1659N_("where the checkout from")),1660OPT_END()1661};1662int ret;16631664memset(&opts,0,sizeof(opts));1665 opts.accept_ref =0;1666 opts.accept_pathspec =1;16671668 options =parse_options_dup(restore_options);1669 options =add_common_options(&opts, options);1670 options =add_checkout_path_options(&opts, options);16711672 ret =checkout_main(argc, argv, prefix, &opts,1673 options, restore_usage);1674FREE_AND_NULL(options);1675return ret;1676}