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