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