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