1#include"builtin.h" 2#include"config.h" 3#include"checkout.h" 4#include"lockfile.h" 5#include"parse-options.h" 6#include"refs.h" 7#include"object-store.h" 8#include"commit.h" 9#include"tree.h" 10#include"tree-walk.h" 11#include"cache-tree.h" 12#include"unpack-trees.h" 13#include"dir.h" 14#include"run-command.h" 15#include"merge-recursive.h" 16#include"branch.h" 17#include"diff.h" 18#include"revision.h" 19#include"remote.h" 20#include"blob.h" 21#include"xdiff-interface.h" 22#include"ll-merge.h" 23#include"resolve-undo.h" 24#include"submodule-config.h" 25#include"submodule.h" 26#include"advice.h" 27 28static int checkout_optimize_new_branch; 29 30static const char*const checkout_usage[] = { 31N_("git checkout [<options>] <branch>"), 32N_("git checkout [<options>] [<branch>] -- <file>..."), 33 NULL, 34}; 35 36struct checkout_opts { 37int patch_mode; 38int quiet; 39int merge; 40int force; 41int force_detach; 42int writeout_stage; 43int overwrite_ignore; 44int ignore_skipworktree; 45int ignore_other_worktrees; 46int show_progress; 47int count_checkout_paths; 48/* 49 * If new checkout options are added, skip_merge_working_tree 50 * should be updated accordingly. 51 */ 52 53const char*new_branch; 54const char*new_branch_force; 55const char*new_orphan_branch; 56int new_branch_log; 57enum branch_track track; 58struct diff_options diff_options; 59 60int branch_exists; 61const char*prefix; 62struct pathspec pathspec; 63struct tree *source_tree; 64}; 65 66static intpost_checkout_hook(struct commit *old_commit,struct commit *new_commit, 67int changed) 68{ 69returnrun_hook_le(NULL,"post-checkout", 70oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid), 71oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid), 72 changed ?"1":"0", NULL); 73/* "new_commit" can be NULL when checking out from the index before 74 a commit exists. */ 75 76} 77 78static intupdate_some(const struct object_id *oid,struct strbuf *base, 79const char*pathname,unsigned mode,int stage,void*context) 80{ 81int len; 82struct cache_entry *ce; 83int pos; 84 85if(S_ISDIR(mode)) 86return READ_TREE_RECURSIVE; 87 88 len = base->len +strlen(pathname); 89 ce =make_empty_cache_entry(&the_index, len); 90oidcpy(&ce->oid, oid); 91memcpy(ce->name, base->buf, base->len); 92memcpy(ce->name + base->len, pathname, len - base->len); 93 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 94 ce->ce_namelen = len; 95 ce->ce_mode =create_ce_mode(mode); 96 97/* 98 * If the entry is the same as the current index, we can leave the old 99 * entry in place. Whether it is UPTODATE or not, checkout_entry will 100 * do the right thing. 101 */ 102 pos =cache_name_pos(ce->name, ce->ce_namelen); 103if(pos >=0) { 104struct cache_entry *old = active_cache[pos]; 105if(ce->ce_mode == old->ce_mode && 106oideq(&ce->oid, &old->oid)) { 107 old->ce_flags |= CE_UPDATE; 108discard_cache_entry(ce); 109return0; 110} 111} 112 113add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 114return0; 115} 116 117static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 118{ 119read_tree_recursive(tree,"",0,0, pathspec, update_some, NULL); 120 121/* update the index with the given tree's info 122 * for all args, expanding wildcards, and exit 123 * with any non-zero return code. 124 */ 125return0; 126} 127 128static intskip_same_name(const struct cache_entry *ce,int pos) 129{ 130while(++pos < active_nr && 131!strcmp(active_cache[pos]->name, ce->name)) 132;/* skip */ 133return pos; 134} 135 136static intcheck_stage(int stage,const struct cache_entry *ce,int pos) 137{ 138while(pos < active_nr && 139!strcmp(active_cache[pos]->name, ce->name)) { 140if(ce_stage(active_cache[pos]) == stage) 141return0; 142 pos++; 143} 144if(stage ==2) 145returnerror(_("path '%s' does not have our version"), ce->name); 146else 147returnerror(_("path '%s' does not have their version"), ce->name); 148} 149 150static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 151{ 152unsigned seen =0; 153const char*name = ce->name; 154 155while(pos < active_nr) { 156 ce = active_cache[pos]; 157if(strcmp(name, ce->name)) 158break; 159 seen |= (1<<ce_stage(ce)); 160 pos++; 161} 162if((stages & seen) != stages) 163returnerror(_("path '%s' does not have all necessary versions"), 164 name); 165return0; 166} 167 168static intcheckout_stage(int stage,const struct cache_entry *ce,int pos, 169const struct checkout *state,int*nr_checkouts) 170{ 171while(pos < active_nr && 172!strcmp(active_cache[pos]->name, ce->name)) { 173if(ce_stage(active_cache[pos]) == stage) 174returncheckout_entry(active_cache[pos], state, 175 NULL, nr_checkouts); 176 pos++; 177} 178if(stage ==2) 179returnerror(_("path '%s' does not have our version"), ce->name); 180else 181returnerror(_("path '%s' does not have their version"), ce->name); 182} 183 184static intcheckout_merged(int pos,const struct checkout *state,int*nr_checkouts) 185{ 186struct cache_entry *ce = active_cache[pos]; 187const char*path = ce->name; 188 mmfile_t ancestor, ours, theirs; 189int status; 190struct object_id oid; 191 mmbuffer_t result_buf; 192struct object_id threeway[3]; 193unsigned mode =0; 194 195memset(threeway,0,sizeof(threeway)); 196while(pos < active_nr) { 197int stage; 198 stage =ce_stage(ce); 199if(!stage ||strcmp(path, ce->name)) 200break; 201oidcpy(&threeway[stage -1], &ce->oid); 202if(stage ==2) 203 mode =create_ce_mode(ce->ce_mode); 204 pos++; 205 ce = active_cache[pos]; 206} 207if(is_null_oid(&threeway[1]) ||is_null_oid(&threeway[2])) 208returnerror(_("path '%s' does not have necessary versions"), path); 209 210read_mmblob(&ancestor, &threeway[0]); 211read_mmblob(&ours, &threeway[1]); 212read_mmblob(&theirs, &threeway[2]); 213 214/* 215 * NEEDSWORK: re-create conflicts from merges with 216 * merge.renormalize set, too 217 */ 218 status =ll_merge(&result_buf, path, &ancestor,"base", 219&ours,"ours", &theirs,"theirs", 220 state->istate, NULL); 221free(ancestor.ptr); 222free(ours.ptr); 223free(theirs.ptr); 224if(status <0|| !result_buf.ptr) { 225free(result_buf.ptr); 226returnerror(_("path '%s': cannot merge"), path); 227} 228 229/* 230 * NEEDSWORK: 231 * There is absolutely no reason to write this as a blob object 232 * and create a phony cache entry. This hack is primarily to get 233 * to the write_entry() machinery that massages the contents to 234 * work-tree format and writes out which only allows it for a 235 * cache entry. The code in write_entry() needs to be refactored 236 * to allow us to feed a <buffer, size, mode> instead of a cache 237 * entry. Such a refactoring would help merge_recursive as well 238 * (it also writes the merge result to the object database even 239 * when it may contain conflicts). 240 */ 241if(write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid)) 242die(_("Unable to add merge result for '%s'"), path); 243free(result_buf.ptr); 244 ce =make_transient_cache_entry(mode, &oid, path,2); 245if(!ce) 246die(_("make_cache_entry failed for path '%s'"), path); 247 status =checkout_entry(ce, state, NULL, nr_checkouts); 248discard_cache_entry(ce); 249return status; 250} 251 252static intcheckout_paths(const struct checkout_opts *opts, 253const char*revision) 254{ 255int pos; 256struct checkout state = CHECKOUT_INIT; 257static char*ps_matched; 258struct object_id rev; 259struct commit *head; 260int errs =0; 261struct lock_file lock_file = LOCK_INIT; 262int nr_checkouts =0; 263 264if(opts->track != BRANCH_TRACK_UNSPECIFIED) 265die(_("'%s' cannot be used with updating paths"),"--track"); 266 267if(opts->new_branch_log) 268die(_("'%s' cannot be used with updating paths"),"-l"); 269 270if(opts->force && opts->patch_mode) 271die(_("'%s' cannot be used with updating paths"),"-f"); 272 273if(opts->force_detach) 274die(_("'%s' cannot be used with updating paths"),"--detach"); 275 276if(opts->merge && opts->patch_mode) 277die(_("'%s' cannot be used with%s"),"--merge","--patch"); 278 279if(opts->force && opts->merge) 280die(_("'%s' cannot be used with%s"),"-f","-m"); 281 282if(opts->new_branch) 283die(_("Cannot update paths and switch to branch '%s' at the same time."), 284 opts->new_branch); 285 286if(opts->patch_mode) 287returnrun_add_interactive(revision,"--patch=checkout", 288&opts->pathspec); 289 290hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 291if(read_cache_preload(&opts->pathspec) <0) 292returnerror(_("index file corrupt")); 293 294if(opts->source_tree) 295read_tree_some(opts->source_tree, &opts->pathspec); 296 297 ps_matched =xcalloc(opts->pathspec.nr,1); 298 299/* 300 * Make sure all pathspecs participated in locating the paths 301 * to be checked out. 302 */ 303for(pos =0; pos < active_nr; pos++) { 304struct cache_entry *ce = active_cache[pos]; 305 ce->ce_flags &= ~CE_MATCHED; 306if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 307continue; 308if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 309/* 310 * "git checkout tree-ish -- path", but this entry 311 * is in the original index; it will not be checked 312 * out to the working tree and it does not matter 313 * if pathspec matched this entry. We will not do 314 * anything to this entry at all. 315 */ 316continue; 317/* 318 * Either this entry came from the tree-ish we are 319 * checking the paths out of, or we are checking out 320 * of the index. 321 * 322 * If it comes from the tree-ish, we already know it 323 * matches the pathspec and could just stamp 324 * CE_MATCHED to it from update_some(). But we still 325 * need ps_matched and read_tree_recursive (and 326 * eventually tree_entry_interesting) cannot fill 327 * ps_matched yet. Once it can, we can avoid calling 328 * match_pathspec() for _all_ entries when 329 * opts->source_tree != NULL. 330 */ 331if(ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) 332 ce->ce_flags |= CE_MATCHED; 333} 334 335if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 336free(ps_matched); 337return1; 338} 339free(ps_matched); 340 341/* "checkout -m path" to recreate conflicted state */ 342if(opts->merge) 343unmerge_marked_index(&the_index); 344 345/* Any unmerged paths? */ 346for(pos =0; pos < active_nr; pos++) { 347const struct cache_entry *ce = active_cache[pos]; 348if(ce->ce_flags & CE_MATCHED) { 349if(!ce_stage(ce)) 350continue; 351if(opts->force) { 352warning(_("path '%s' is unmerged"), ce->name); 353}else if(opts->writeout_stage) { 354 errs |=check_stage(opts->writeout_stage, ce, pos); 355}else if(opts->merge) { 356 errs |=check_stages((1<<2) | (1<<3), ce, pos); 357}else{ 358 errs =1; 359error(_("path '%s' is unmerged"), ce->name); 360} 361 pos =skip_same_name(ce, pos) -1; 362} 363} 364if(errs) 365return1; 366 367/* Now we are committed to check them out */ 368 state.force =1; 369 state.refresh_cache =1; 370 state.istate = &the_index; 371 372enable_delayed_checkout(&state); 373for(pos =0; pos < active_nr; pos++) { 374struct cache_entry *ce = active_cache[pos]; 375if(ce->ce_flags & CE_MATCHED) { 376if(!ce_stage(ce)) { 377 errs |=checkout_entry(ce, &state, 378 NULL, &nr_checkouts); 379continue; 380} 381if(opts->writeout_stage) 382 errs |=checkout_stage(opts->writeout_stage, 383 ce, pos, 384&state, &nr_checkouts); 385else if(opts->merge) 386 errs |=checkout_merged(pos, &state, 387&nr_checkouts); 388 pos =skip_same_name(ce, pos) -1; 389} 390} 391 errs |=finish_delayed_checkout(&state, &nr_checkouts); 392 393if(opts->count_checkout_paths) { 394if(opts->source_tree) 395fprintf_ln(stderr,Q_("Updated%dpath from%s", 396"Updated%dpaths from%s", 397 nr_checkouts), 398 nr_checkouts, 399find_unique_abbrev(&opts->source_tree->object.oid, 400 DEFAULT_ABBREV)); 401else 402fprintf_ln(stderr,Q_("Updated%dpath from the index", 403"Updated%dpaths from the index", 404 nr_checkouts), 405 nr_checkouts); 406} 407 408if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 409die(_("unable to write new index file")); 410 411read_ref_full("HEAD",0, &rev, NULL); 412 head =lookup_commit_reference_gently(the_repository, &rev,1); 413 414 errs |=post_checkout_hook(head, head,0); 415return errs; 416} 417 418static voidshow_local_changes(struct object *head, 419const struct diff_options *opts) 420{ 421struct rev_info rev; 422/* I think we want full paths, even if we're in a subdirectory. */ 423repo_init_revisions(the_repository, &rev, NULL); 424 rev.diffopt.flags = opts->flags; 425 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 426diff_setup_done(&rev.diffopt); 427add_pending_object(&rev, head, NULL); 428run_diff_index(&rev,0); 429} 430 431static voiddescribe_detached_head(const char*msg,struct commit *commit) 432{ 433struct strbuf sb = STRBUF_INIT; 434 435if(!parse_commit(commit)) 436pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 437if(print_sha1_ellipsis()) { 438fprintf(stderr,"%s %s...%s\n", msg, 439find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 440}else{ 441fprintf(stderr,"%s %s %s\n", msg, 442find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf); 443} 444strbuf_release(&sb); 445} 446 447static intreset_tree(struct tree *tree,const struct checkout_opts *o, 448int worktree,int*writeout_error) 449{ 450struct unpack_trees_options opts; 451struct tree_desc tree_desc; 452 453memset(&opts,0,sizeof(opts)); 454 opts.head_idx = -1; 455 opts.update = worktree; 456 opts.skip_unmerged = !worktree; 457 opts.reset =1; 458 opts.merge =1; 459 opts.fn = oneway_merge; 460 opts.verbose_update = o->show_progress; 461 opts.src_index = &the_index; 462 opts.dst_index = &the_index; 463parse_tree(tree); 464init_tree_desc(&tree_desc, tree->buffer, tree->size); 465switch(unpack_trees(1, &tree_desc, &opts)) { 466case-2: 467*writeout_error =1; 468/* 469 * We return 0 nevertheless, as the index is all right 470 * and more importantly we have made best efforts to 471 * update paths in the work tree, and we cannot revert 472 * them. 473 */ 474/* fallthrough */ 475case0: 476return0; 477default: 478return128; 479} 480} 481 482struct branch_info { 483const char*name;/* The short name used */ 484const char*path;/* The full name of a real branch */ 485struct commit *commit;/* The named commit */ 486/* 487 * if not null the branch is detached because it's already 488 * checked out in this checkout 489 */ 490char*checkout; 491}; 492 493static voidsetup_branch_path(struct branch_info *branch) 494{ 495struct strbuf buf = STRBUF_INIT; 496 497strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 498if(strcmp(buf.buf, branch->name)) 499 branch->name =xstrdup(buf.buf); 500strbuf_splice(&buf,0,0,"refs/heads/",11); 501 branch->path =strbuf_detach(&buf, NULL); 502} 503 504/* 505 * Skip merging the trees, updating the index and working directory if and 506 * only if we are creating a new branch via "git checkout -b <new_branch>." 507 */ 508static intskip_merge_working_tree(const struct checkout_opts *opts, 509const struct branch_info *old_branch_info, 510const struct branch_info *new_branch_info) 511{ 512/* 513 * Do the merge if sparse checkout is on and the user has not opted in 514 * to the optimized behavior 515 */ 516if(core_apply_sparse_checkout && !checkout_optimize_new_branch) 517return0; 518 519/* 520 * We must do the merge if we are actually moving to a new commit. 521 */ 522if(!old_branch_info->commit || !new_branch_info->commit || 523!oideq(&old_branch_info->commit->object.oid, 524&new_branch_info->commit->object.oid)) 525return0; 526 527/* 528 * opts->patch_mode cannot be used with switching branches so is 529 * not tested here 530 */ 531 532/* 533 * opts->quiet only impacts output so doesn't require a merge 534 */ 535 536/* 537 * Honor the explicit request for a three-way merge or to throw away 538 * local changes 539 */ 540if(opts->merge || opts->force) 541return0; 542 543/* 544 * --detach is documented as "updating the index and the files in the 545 * working tree" but this optimization skips those steps so fall through 546 * to the regular code path. 547 */ 548if(opts->force_detach) 549return0; 550 551/* 552 * opts->writeout_stage cannot be used with switching branches so is 553 * not tested here 554 */ 555 556/* 557 * Honor the explicit ignore requests 558 */ 559if(!opts->overwrite_ignore || opts->ignore_skipworktree || 560 opts->ignore_other_worktrees) 561return0; 562 563/* 564 * opts->show_progress only impacts output so doesn't require a merge 565 */ 566 567/* 568 * If we aren't creating a new branch any changes or updates will 569 * happen in the existing branch. Since that could only be updating 570 * the index and working directory, we don't want to skip those steps 571 * or we've defeated any purpose in running the command. 572 */ 573if(!opts->new_branch) 574return0; 575 576/* 577 * new_branch_force is defined to "create/reset and checkout a branch" 578 * so needs to go through the merge to do the reset 579 */ 580if(opts->new_branch_force) 581return0; 582 583/* 584 * A new orphaned branch requrires the index and the working tree to be 585 * adjusted to <start_point> 586 */ 587if(opts->new_orphan_branch) 588return0; 589 590/* 591 * Remaining variables are not checkout options but used to track state 592 */ 593 594return1; 595} 596 597static intmerge_working_tree(const struct checkout_opts *opts, 598struct branch_info *old_branch_info, 599struct branch_info *new_branch_info, 600int*writeout_error) 601{ 602int ret; 603struct lock_file lock_file = LOCK_INIT; 604 605hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR); 606if(read_cache_preload(NULL) <0) 607returnerror(_("index file corrupt")); 608 609resolve_undo_clear(); 610if(opts->force) { 611 ret =reset_tree(get_commit_tree(new_branch_info->commit), 612 opts,1, writeout_error); 613if(ret) 614return ret; 615}else{ 616struct tree_desc trees[2]; 617struct tree *tree; 618struct unpack_trees_options topts; 619 620memset(&topts,0,sizeof(topts)); 621 topts.head_idx = -1; 622 topts.src_index = &the_index; 623 topts.dst_index = &the_index; 624 625setup_unpack_trees_porcelain(&topts,"checkout"); 626 627refresh_cache(REFRESH_QUIET); 628 629if(unmerged_cache()) { 630error(_("you need to resolve your current index first")); 631return1; 632} 633 634/* 2-way merge to the new branch */ 635 topts.initial_checkout =is_cache_unborn(); 636 topts.update =1; 637 topts.merge =1; 638 topts.gently = opts->merge && old_branch_info->commit; 639 topts.verbose_update = opts->show_progress; 640 topts.fn = twoway_merge; 641if(opts->overwrite_ignore) { 642 topts.dir =xcalloc(1,sizeof(*topts.dir)); 643 topts.dir->flags |= DIR_SHOW_IGNORED; 644setup_standard_excludes(topts.dir); 645} 646 tree =parse_tree_indirect(old_branch_info->commit ? 647&old_branch_info->commit->object.oid : 648 the_hash_algo->empty_tree); 649init_tree_desc(&trees[0], tree->buffer, tree->size); 650 tree =parse_tree_indirect(&new_branch_info->commit->object.oid); 651init_tree_desc(&trees[1], tree->buffer, tree->size); 652 653 ret =unpack_trees(2, trees, &topts); 654clear_unpack_trees_porcelain(&topts); 655if(ret == -1) { 656/* 657 * Unpack couldn't do a trivial merge; either 658 * give up or do a real merge, depending on 659 * whether the merge flag was used. 660 */ 661struct tree *result; 662struct tree *work; 663struct merge_options o; 664if(!opts->merge) 665return1; 666 667/* 668 * Without old_branch_info->commit, the below is the same as 669 * the two-tree unpack we already tried and failed. 670 */ 671if(!old_branch_info->commit) 672return1; 673 674/* Do more real merge */ 675 676/* 677 * We update the index fully, then write the 678 * tree from the index, then merge the new 679 * branch with the current tree, with the old 680 * branch as the base. Then we reset the index 681 * (but not the working tree) to the new 682 * branch, leaving the working tree as the 683 * merged version, but skipping unmerged 684 * entries in the index. 685 */ 686 687add_files_to_cache(NULL, NULL,0); 688/* 689 * NEEDSWORK: carrying over local changes 690 * when branches have different end-of-line 691 * normalization (or clean+smudge rules) is 692 * a pain; plumb in an option to set 693 * o.renormalize? 694 */ 695init_merge_options(&o); 696 o.verbosity =0; 697 work =write_tree_from_memory(&o); 698 699 ret =reset_tree(get_commit_tree(new_branch_info->commit), 700 opts,1, 701 writeout_error); 702if(ret) 703return ret; 704 o.ancestor = old_branch_info->name; 705 o.branch1 = new_branch_info->name; 706 o.branch2 ="local"; 707 ret =merge_trees(&o, 708get_commit_tree(new_branch_info->commit), 709 work, 710get_commit_tree(old_branch_info->commit), 711&result); 712if(ret <0) 713exit(128); 714 ret =reset_tree(get_commit_tree(new_branch_info->commit), 715 opts,0, 716 writeout_error); 717strbuf_release(&o.obuf); 718if(ret) 719return ret; 720} 721} 722 723if(!active_cache_tree) 724 active_cache_tree =cache_tree(); 725 726if(!cache_tree_fully_valid(active_cache_tree)) 727cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 728 729if(write_locked_index(&the_index, &lock_file, COMMIT_LOCK)) 730die(_("unable to write new index file")); 731 732if(!opts->force && !opts->quiet) 733show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 734 735return0; 736} 737 738static voidreport_tracking(struct branch_info *new_branch_info) 739{ 740struct strbuf sb = STRBUF_INIT; 741struct branch *branch =branch_get(new_branch_info->name); 742 743if(!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL)) 744return; 745fputs(sb.buf, stdout); 746strbuf_release(&sb); 747} 748 749static voidupdate_refs_for_switch(const struct checkout_opts *opts, 750struct branch_info *old_branch_info, 751struct branch_info *new_branch_info) 752{ 753struct strbuf msg = STRBUF_INIT; 754const char*old_desc, *reflog_msg; 755if(opts->new_branch) { 756if(opts->new_orphan_branch) { 757char*refname; 758 759 refname =mkpathdup("refs/heads/%s", opts->new_orphan_branch); 760if(opts->new_branch_log && 761!should_autocreate_reflog(refname)) { 762int ret; 763struct strbuf err = STRBUF_INIT; 764 765 ret =safe_create_reflog(refname,1, &err); 766if(ret) { 767fprintf(stderr,_("Can not do reflog for '%s':%s\n"), 768 opts->new_orphan_branch, err.buf); 769strbuf_release(&err); 770free(refname); 771return; 772} 773strbuf_release(&err); 774} 775free(refname); 776} 777else 778create_branch(opts->new_branch, new_branch_info->name, 779 opts->new_branch_force ?1:0, 780 opts->new_branch_force ?1:0, 781 opts->new_branch_log, 782 opts->quiet, 783 opts->track); 784 new_branch_info->name = opts->new_branch; 785setup_branch_path(new_branch_info); 786} 787 788 old_desc = old_branch_info->name; 789if(!old_desc && old_branch_info->commit) 790 old_desc =oid_to_hex(&old_branch_info->commit->object.oid); 791 792 reflog_msg =getenv("GIT_REFLOG_ACTION"); 793if(!reflog_msg) 794strbuf_addf(&msg,"checkout: moving from%sto%s", 795 old_desc ? old_desc :"(invalid)", new_branch_info->name); 796else 797strbuf_insert(&msg,0, reflog_msg,strlen(reflog_msg)); 798 799if(!strcmp(new_branch_info->name,"HEAD") && !new_branch_info->path && !opts->force_detach) { 800/* Nothing to do. */ 801}else if(opts->force_detach || !new_branch_info->path) {/* No longer on any branch. */ 802update_ref(msg.buf,"HEAD", &new_branch_info->commit->object.oid, NULL, 803 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 804if(!opts->quiet) { 805if(old_branch_info->path && 806 advice_detached_head && !opts->force_detach) 807detach_advice(new_branch_info->name); 808describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 809} 810}else if(new_branch_info->path) {/* Switch branches. */ 811if(create_symref("HEAD", new_branch_info->path, msg.buf) <0) 812die(_("unable to update HEAD")); 813if(!opts->quiet) { 814if(old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 815if(opts->new_branch_force) 816fprintf(stderr,_("Reset branch '%s'\n"), 817 new_branch_info->name); 818else 819fprintf(stderr,_("Already on '%s'\n"), 820 new_branch_info->name); 821}else if(opts->new_branch) { 822if(opts->branch_exists) 823fprintf(stderr,_("Switched to and reset branch '%s'\n"), new_branch_info->name); 824else 825fprintf(stderr,_("Switched to a new branch '%s'\n"), new_branch_info->name); 826}else{ 827fprintf(stderr,_("Switched to branch '%s'\n"), 828 new_branch_info->name); 829} 830} 831if(old_branch_info->path && old_branch_info->name) { 832if(!ref_exists(old_branch_info->path) &&reflog_exists(old_branch_info->path)) 833delete_reflog(old_branch_info->path); 834} 835} 836remove_branch_state(); 837strbuf_release(&msg); 838if(!opts->quiet && 839(new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name,"HEAD")))) 840report_tracking(new_branch_info); 841} 842 843static intadd_pending_uninteresting_ref(const char*refname, 844const struct object_id *oid, 845int flags,void*cb_data) 846{ 847add_pending_oid(cb_data, refname, oid, UNINTERESTING); 848return0; 849} 850 851static voiddescribe_one_orphan(struct strbuf *sb,struct commit *commit) 852{ 853strbuf_addstr(sb," "); 854strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 855strbuf_addch(sb,' '); 856if(!parse_commit(commit)) 857pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 858strbuf_addch(sb,'\n'); 859} 860 861#define ORPHAN_CUTOFF 4 862static voidsuggest_reattach(struct commit *commit,struct rev_info *revs) 863{ 864struct commit *c, *last = NULL; 865struct strbuf sb = STRBUF_INIT; 866int lost =0; 867while((c =get_revision(revs)) != NULL) { 868if(lost < ORPHAN_CUTOFF) 869describe_one_orphan(&sb, c); 870 last = c; 871 lost++; 872} 873if(ORPHAN_CUTOFF < lost) { 874int more = lost - ORPHAN_CUTOFF; 875if(more ==1) 876describe_one_orphan(&sb, last); 877else 878strbuf_addf(&sb,_(" ... and%dmore.\n"), more); 879} 880 881fprintf(stderr, 882Q_( 883/* The singular version */ 884"Warning: you are leaving%dcommit behind, " 885"not connected to\n" 886"any of your branches:\n\n" 887"%s\n", 888/* The plural version */ 889"Warning: you are leaving%dcommits behind, " 890"not connected to\n" 891"any of your branches:\n\n" 892"%s\n", 893/* Give ngettext() the count */ 894 lost), 895 lost, 896 sb.buf); 897strbuf_release(&sb); 898 899if(advice_detached_head) 900fprintf(stderr, 901Q_( 902/* The singular version */ 903"If you want to keep it by creating a new branch, " 904"this may be a good time\nto do so with:\n\n" 905" git branch <new-branch-name>%s\n\n", 906/* The plural version */ 907"If you want to keep them by creating a new branch, " 908"this may be a good time\nto do so with:\n\n" 909" git branch <new-branch-name>%s\n\n", 910/* Give ngettext() the count */ 911 lost), 912find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV)); 913} 914 915/* 916 * We are about to leave commit that was at the tip of a detached 917 * HEAD. If it is not reachable from any ref, this is the last chance 918 * for the user to do so without resorting to reflog. 919 */ 920static voidorphaned_commit_warning(struct commit *old_commit,struct commit *new_commit) 921{ 922struct rev_info revs; 923struct object *object = &old_commit->object; 924 925repo_init_revisions(the_repository, &revs, NULL); 926setup_revisions(0, NULL, &revs, NULL); 927 928 object->flags &= ~UNINTERESTING; 929add_pending_object(&revs, object,oid_to_hex(&object->oid)); 930 931for_each_ref(add_pending_uninteresting_ref, &revs); 932add_pending_oid(&revs,"HEAD", &new_commit->object.oid, UNINTERESTING); 933 934if(prepare_revision_walk(&revs)) 935die(_("internal error in revision walk")); 936if(!(old_commit->object.flags & UNINTERESTING)) 937suggest_reattach(old_commit, &revs); 938else 939describe_detached_head(_("Previous HEAD position was"), old_commit); 940 941/* Clean up objects used, as they will be reused. */ 942clear_commit_marks_all(ALL_REV_FLAGS); 943} 944 945static intswitch_branches(const struct checkout_opts *opts, 946struct branch_info *new_branch_info) 947{ 948int ret =0; 949struct branch_info old_branch_info; 950void*path_to_free; 951struct object_id rev; 952int flag, writeout_error =0; 953memset(&old_branch_info,0,sizeof(old_branch_info)); 954 old_branch_info.path = path_to_free =resolve_refdup("HEAD",0, &rev, &flag); 955if(old_branch_info.path) 956 old_branch_info.commit =lookup_commit_reference_gently(the_repository, &rev,1); 957if(!(flag & REF_ISSYMREF)) 958 old_branch_info.path = NULL; 959 960if(old_branch_info.path) 961skip_prefix(old_branch_info.path,"refs/heads/", &old_branch_info.name); 962 963if(!new_branch_info->name) { 964 new_branch_info->name ="HEAD"; 965 new_branch_info->commit = old_branch_info.commit; 966if(!new_branch_info->commit) 967die(_("You are on a branch yet to be born")); 968parse_commit_or_die(new_branch_info->commit); 969} 970 971/* optimize the "checkout -b <new_branch> path */ 972if(skip_merge_working_tree(opts, &old_branch_info, new_branch_info)) { 973if(!checkout_optimize_new_branch && !opts->quiet) { 974if(read_cache_preload(NULL) <0) 975returnerror(_("index file corrupt")); 976show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 977} 978}else{ 979 ret =merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error); 980if(ret) { 981free(path_to_free); 982return ret; 983} 984} 985 986if(!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit) 987orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit); 988 989update_refs_for_switch(opts, &old_branch_info, new_branch_info); 990 991 ret =post_checkout_hook(old_branch_info.commit, new_branch_info->commit,1); 992free(path_to_free); 993return ret || writeout_error; 994} 995 996static intgit_checkout_config(const char*var,const char*value,void*cb) 997{ 998if(!strcmp(var,"checkout.optimizenewbranch")) { 999 checkout_optimize_new_branch =git_config_bool(var, value);1000return0;1001}10021003if(!strcmp(var,"diff.ignoresubmodules")) {1004struct checkout_opts *opts = cb;1005handle_ignore_submodules_arg(&opts->diff_options, value);1006return0;1007}10081009if(starts_with(var,"submodule."))1010returngit_default_submodule_config(var, value, NULL);10111012returngit_xmerge_config(var, value, NULL);1013}10141015static intparse_branchname_arg(int argc,const char**argv,1016int dwim_new_local_branch_ok,1017struct branch_info *new_branch_info,1018struct checkout_opts *opts,1019struct object_id *rev,1020int*dwim_remotes_matched)1021{1022struct tree **source_tree = &opts->source_tree;1023const char**new_branch = &opts->new_branch;1024int argcount =0;1025struct object_id branch_rev;1026const char*arg;1027int dash_dash_pos;1028int has_dash_dash =0;1029int i;10301031/*1032 * case 1: git checkout <ref> -- [<paths>]1033 *1034 * <ref> must be a valid tree, everything after the '--' must be1035 * a path.1036 *1037 * case 2: git checkout -- [<paths>]1038 *1039 * everything after the '--' must be paths.1040 *1041 * case 3: git checkout <something> [--]1042 *1043 * (a) If <something> is a commit, that is to1044 * switch to the branch or detach HEAD at it. As a special case,1045 * if <something> is A...B (missing A or B means HEAD but you can1046 * omit at most one side), and if there is a unique merge base1047 * between A and B, A...B names that merge base.1048 *1049 * (b) If <something> is _not_ a commit, either "--" is present1050 * or <something> is not a path, no -t or -b was given, and1051 * and there is a tracking branch whose name is <something>1052 * in one and only one remote (or if the branch exists on the1053 * remote named in checkout.defaultRemote), then this is a1054 * short-hand to fork local <something> from that1055 * remote-tracking branch.1056 *1057 * (c) Otherwise, if "--" is present, treat it like case (1).1058 *1059 * (d) Otherwise :1060 * - if it's a reference, treat it like case (1)1061 * - else if it's a path, treat it like case (2)1062 * - else: fail.1063 *1064 * case 4: git checkout <something> <paths>1065 *1066 * The first argument must not be ambiguous.1067 * - If it's *only* a reference, treat it like case (1).1068 * - If it's only a path, treat it like case (2).1069 * - else: fail.1070 *1071 */1072if(!argc)1073return0;10741075 arg = argv[0];1076 dash_dash_pos = -1;1077for(i =0; i < argc; i++) {1078if(!strcmp(argv[i],"--")) {1079 dash_dash_pos = i;1080break;1081}1082}1083if(dash_dash_pos ==0)1084return1;/* case (2) */1085else if(dash_dash_pos ==1)1086 has_dash_dash =1;/* case (3) or (1) */1087else if(dash_dash_pos >=2)1088die(_("only one reference expected,%dgiven."), dash_dash_pos);1089 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;10901091if(!strcmp(arg,"-"))1092 arg ="@{-1}";10931094if(get_oid_mb(arg, rev)) {1095/*1096 * Either case (3) or (4), with <something> not being1097 * a commit, or an attempt to use case (1) with an1098 * invalid ref.1099 *1100 * It's likely an error, but we need to find out if1101 * we should auto-create the branch, case (3).(b).1102 */1103int recover_with_dwim = dwim_new_local_branch_ok;11041105if(!has_dash_dash &&1106(check_filename(opts->prefix, arg) || !no_wildcard(arg)))1107 recover_with_dwim =0;1108/*1109 * Accept "git checkout foo" and "git checkout foo --"1110 * as candidates for dwim.1111 */1112if(!(argc ==1&& !has_dash_dash) &&1113!(argc ==2&& has_dash_dash))1114 recover_with_dwim =0;11151116if(recover_with_dwim) {1117const char*remote =unique_tracking_name(arg, rev,1118 dwim_remotes_matched);1119if(remote) {1120*new_branch = arg;1121 arg = remote;1122/* DWIMmed to create local branch, case (3).(b) */1123}else{1124 recover_with_dwim =0;1125}1126}11271128if(!recover_with_dwim) {1129if(has_dash_dash)1130die(_("invalid reference:%s"), arg);1131return argcount;1132}1133}11341135/* we can't end up being in (2) anymore, eat the argument */1136 argcount++;1137 argv++;1138 argc--;11391140 new_branch_info->name = arg;1141setup_branch_path(new_branch_info);11421143if(!check_refname_format(new_branch_info->path,0) &&1144!read_ref(new_branch_info->path, &branch_rev))1145oidcpy(rev, &branch_rev);1146else1147 new_branch_info->path = NULL;/* not an existing branch */11481149 new_branch_info->commit =lookup_commit_reference_gently(the_repository, rev,1);1150if(!new_branch_info->commit) {1151/* not a commit */1152*source_tree =parse_tree_indirect(rev);1153}else{1154parse_commit_or_die(new_branch_info->commit);1155*source_tree =get_commit_tree(new_branch_info->commit);1156}11571158if(!*source_tree)/* case (1): want a tree */1159die(_("reference is not a tree:%s"), arg);1160if(!has_dash_dash) {/* case (3).(d) -> (1) */1161/*1162 * Do not complain the most common case1163 * git checkout branch1164 * even if there happen to be a file called 'branch';1165 * it would be extremely annoying.1166 */1167if(argc)1168verify_non_filename(opts->prefix, arg);1169}else{1170 argcount++;1171 argv++;1172 argc--;1173}11741175return argcount;1176}11771178static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1179{1180int status;1181struct strbuf branch_ref = STRBUF_INIT;11821183if(!opts->new_branch)1184die(_("You are on a branch yet to be born"));1185strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1186 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1187strbuf_release(&branch_ref);1188if(!opts->quiet)1189fprintf(stderr,_("Switched to a new branch '%s'\n"),1190 opts->new_branch);1191return status;1192}11931194static intcheckout_branch(struct checkout_opts *opts,1195struct branch_info *new_branch_info)1196{1197if(opts->pathspec.nr)1198die(_("paths cannot be used with switching branches"));11991200if(opts->patch_mode)1201die(_("'%s' cannot be used with switching branches"),1202"--patch");12031204if(opts->writeout_stage)1205die(_("'%s' cannot be used with switching branches"),1206"--ours/--theirs");12071208if(opts->force && opts->merge)1209die(_("'%s' cannot be used with '%s'"),"-f","-m");12101211if(opts->force_detach && opts->new_branch)1212die(_("'%s' cannot be used with '%s'"),1213"--detach","-b/-B/--orphan");12141215if(opts->new_orphan_branch) {1216if(opts->track != BRANCH_TRACK_UNSPECIFIED)1217die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1218}else if(opts->force_detach) {1219if(opts->track != BRANCH_TRACK_UNSPECIFIED)1220die(_("'%s' cannot be used with '%s'"),"--detach","-t");1221}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1222 opts->track = git_branch_track;12231224if(new_branch_info->name && !new_branch_info->commit)1225die(_("Cannot switch branch to a non-commit '%s'"),1226 new_branch_info->name);12271228if(new_branch_info->path && !opts->force_detach && !opts->new_branch &&1229!opts->ignore_other_worktrees) {1230int flag;1231char*head_ref =resolve_refdup("HEAD",0, NULL, &flag);1232if(head_ref &&1233(!(flag & REF_ISSYMREF) ||strcmp(head_ref, new_branch_info->path)))1234die_if_checked_out(new_branch_info->path,1);1235free(head_ref);1236}12371238if(!new_branch_info->commit && opts->new_branch) {1239struct object_id rev;1240int flag;12411242if(!read_ref_full("HEAD",0, &rev, &flag) &&1243(flag & REF_ISSYMREF) &&is_null_oid(&rev))1244returnswitch_unborn_to_new_branch(opts);1245}1246returnswitch_branches(opts, new_branch_info);1247}12481249intcmd_checkout(int argc,const char**argv,const char*prefix)1250{1251struct checkout_opts opts;1252struct branch_info new_branch_info;1253char*conflict_style = NULL;1254int dwim_new_local_branch =1;1255int dwim_remotes_matched =0;1256struct option options[] = {1257OPT__QUIET(&opts.quiet,N_("suppress progress reporting")),1258OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1259N_("create and checkout a new branch")),1260OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1261N_("create/reset and checkout a branch")),1262OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1263OPT_BOOL(0,"detach", &opts.force_detach,N_("detach HEAD at named commit")),1264OPT_SET_INT('t',"track", &opts.track,N_("set upstream info for new branch"),1265 BRANCH_TRACK_EXPLICIT),1266OPT_STRING(0,"orphan", &opts.new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1267OPT_SET_INT_F('2',"ours", &opts.writeout_stage,1268N_("checkout our version for unmerged files"),12692, PARSE_OPT_NONEG),1270OPT_SET_INT_F('3',"theirs", &opts.writeout_stage,1271N_("checkout their version for unmerged files"),12723, PARSE_OPT_NONEG),1273OPT__FORCE(&opts.force,N_("force checkout (throw away local modifications)"),1274 PARSE_OPT_NOCOMPLETE),1275OPT_BOOL('m',"merge", &opts.merge,N_("perform a 3-way merge with the new branch")),1276OPT_BOOL_F(0,"overwrite-ignore", &opts.overwrite_ignore,1277N_("update ignored files (default)"),1278 PARSE_OPT_NOCOMPLETE),1279OPT_STRING(0,"conflict", &conflict_style,N_("style"),1280N_("conflict style (merge or diff3)")),1281OPT_BOOL('p',"patch", &opts.patch_mode,N_("select hunks interactively")),1282OPT_BOOL(0,"ignore-skip-worktree-bits", &opts.ignore_skipworktree,1283N_("do not limit pathspecs to sparse entries only")),1284OPT_HIDDEN_BOOL(0,"guess", &dwim_new_local_branch,1285N_("second guess 'git checkout <no-such-branch>'")),1286OPT_BOOL(0,"ignore-other-worktrees", &opts.ignore_other_worktrees,1287N_("do not check if another worktree is holding the given ref")),1288{ OPTION_CALLBACK,0,"recurse-submodules", NULL,1289"checkout","control recursive updating of submodules",1290 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },1291OPT_BOOL(0,"progress", &opts.show_progress,N_("force progress reporting")),1292OPT_END(),1293};12941295memset(&opts,0,sizeof(opts));1296memset(&new_branch_info,0,sizeof(new_branch_info));1297 opts.overwrite_ignore =1;1298 opts.prefix = prefix;1299 opts.show_progress = -1;13001301git_config(git_checkout_config, &opts);13021303 opts.track = BRANCH_TRACK_UNSPECIFIED;13041305 argc =parse_options(argc, argv, prefix, options, checkout_usage,1306 PARSE_OPT_KEEP_DASHDASH);13071308if(opts.show_progress <0) {1309if(opts.quiet)1310 opts.show_progress =0;1311else1312 opts.show_progress =isatty(2);1313}13141315if(conflict_style) {1316 opts.merge =1;/* implied */1317git_xmerge_config("merge.conflictstyle", conflict_style, NULL);1318}13191320if((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) >1)1321die(_("-b, -B and --orphan are mutually exclusive"));13221323/*1324 * From here on, new_branch will contain the branch to be checked out,1325 * and new_branch_force and new_orphan_branch will tell us which one of1326 * -b/-B/--orphan is being used.1327 */1328if(opts.new_branch_force)1329 opts.new_branch = opts.new_branch_force;13301331if(opts.new_orphan_branch)1332 opts.new_branch = opts.new_orphan_branch;13331334/* --track without -b/-B/--orphan should DWIM */1335if(opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {1336const char*argv0 = argv[0];1337if(!argc || !strcmp(argv0,"--"))1338die(_("--track needs a branch name"));1339skip_prefix(argv0,"refs/", &argv0);1340skip_prefix(argv0,"remotes/", &argv0);1341 argv0 =strchr(argv0,'/');1342if(!argv0 || !argv0[1])1343die(_("missing branch name; try -b"));1344 opts.new_branch = argv0 +1;1345}13461347/*1348 * Extract branch name from command line arguments, so1349 * all that is left is pathspecs.1350 *1351 * Handle1352 *1353 * 1) git checkout <tree> -- [<paths>]1354 * 2) git checkout -- [<paths>]1355 * 3) git checkout <something> [<paths>]1356 *1357 * including "last branch" syntax and DWIM-ery for names of1358 * remote branches, erroring out for invalid or ambiguous cases.1359 */1360if(argc) {1361struct object_id rev;1362int dwim_ok =1363!opts.patch_mode &&1364 dwim_new_local_branch &&1365 opts.track == BRANCH_TRACK_UNSPECIFIED &&1366!opts.new_branch;1367int n =parse_branchname_arg(argc, argv, dwim_ok,1368&new_branch_info, &opts, &rev,1369&dwim_remotes_matched);1370 argv += n;1371 argc -= n;1372}13731374if(argc) {1375parse_pathspec(&opts.pathspec,0,1376 opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1377 prefix, argv);13781379if(!opts.pathspec.nr)1380die(_("invalid path specification"));13811382/*1383 * Try to give more helpful suggestion.1384 * new_branch && argc > 1 will be caught later.1385 */1386if(opts.new_branch && argc ==1)1387die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),1388 argv[0], opts.new_branch);13891390if(opts.force_detach)1391die(_("git checkout: --detach does not take a path argument '%s'"),1392 argv[0]);13931394if(1< !!opts.writeout_stage + !!opts.force + !!opts.merge)1395die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1396"checking out of the index."));1397}13981399if(opts.new_branch) {1400struct strbuf buf = STRBUF_INIT;14011402if(opts.new_branch_force)1403 opts.branch_exists =validate_branchname(opts.new_branch, &buf);1404else1405 opts.branch_exists =1406validate_new_branchname(opts.new_branch, &buf,0);1407strbuf_release(&buf);1408}14091410UNLEAK(opts);1411if(opts.patch_mode || opts.pathspec.nr) {1412int ret =checkout_paths(&opts, new_branch_info.name);1413if(ret && dwim_remotes_matched >1&&1414 advice_checkout_ambiguous_remote_branch_name)1415advise(_("'%s' matched more than one remote tracking branch.\n"1416"We found%dremotes with a reference that matched. So we fell back\n"1417"on trying to resolve the argument as a path, but failed there too!\n"1418"\n"1419"If you meant to check out a remote tracking branch on, e.g. 'origin',\n"1420"you can do so by fully qualifying the name with the --track option:\n"1421"\n"1422" git checkout --track origin/<name>\n"1423"\n"1424"If you'd like to always have checkouts of an ambiguous <name> prefer\n"1425"one remote, e.g. the 'origin' remote, consider setting\n"1426"checkout.defaultRemote=origin in your config."),1427 argv[0],1428 dwim_remotes_matched);1429return ret;1430}else{1431returncheckout_branch(&opts, &new_branch_info);1432}1433}