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 23static const char*const checkout_usage[] = { 24N_("git checkout [options] <branch>"), 25N_("git checkout [options] [<branch>] -- <file>..."), 26 NULL, 27}; 28 29struct checkout_opts { 30int patch_mode; 31int quiet; 32int merge; 33int force; 34int force_detach; 35int writeout_stage; 36int overwrite_ignore; 37int ignore_skipworktree; 38int ignore_other_worktrees; 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 52int new_worktree_mode; 53}; 54 55static intpost_checkout_hook(struct commit *old,struct commit *new, 56int changed) 57{ 58returnrun_hook_le(NULL,"post-checkout", 59sha1_to_hex(old ? old->object.sha1 : null_sha1), 60sha1_to_hex(new?new->object.sha1 : null_sha1), 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,const char*base,int baselen, 68const char*pathname,unsigned mode,int stage,void*context) 69{ 70int len; 71struct cache_entry *ce; 72 73if(S_ISDIR(mode)) 74return READ_TREE_RECURSIVE; 75 76 len = baselen +strlen(pathname); 77 ce =xcalloc(1,cache_entry_size(len)); 78hashcpy(ce->sha1, sha1); 79memcpy(ce->name, base, baselen); 80memcpy(ce->name + baselen, pathname, len - baselen); 81 ce->ce_flags =create_ce_flags(0) | CE_UPDATE; 82 ce->ce_namelen = len; 83 ce->ce_mode =create_ce_mode(mode); 84add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 85return0; 86} 87 88static intread_tree_some(struct tree *tree,const struct pathspec *pathspec) 89{ 90read_tree_recursive(tree,"",0,0, pathspec, update_some, NULL); 91 92/* update the index with the given tree's info 93 * for all args, expanding wildcards, and exit 94 * with any non-zero return code. 95 */ 96return0; 97} 98 99static intskip_same_name(const struct cache_entry *ce,int pos) 100{ 101while(++pos < active_nr && 102!strcmp(active_cache[pos]->name, ce->name)) 103;/* skip */ 104return pos; 105} 106 107static intcheck_stage(int stage,const struct cache_entry *ce,int pos) 108{ 109while(pos < active_nr && 110!strcmp(active_cache[pos]->name, ce->name)) { 111if(ce_stage(active_cache[pos]) == stage) 112return0; 113 pos++; 114} 115if(stage ==2) 116returnerror(_("path '%s' does not have our version"), ce->name); 117else 118returnerror(_("path '%s' does not have their version"), ce->name); 119} 120 121static intcheck_stages(unsigned stages,const struct cache_entry *ce,int pos) 122{ 123unsigned seen =0; 124const char*name = ce->name; 125 126while(pos < active_nr) { 127 ce = active_cache[pos]; 128if(strcmp(name, ce->name)) 129break; 130 seen |= (1<<ce_stage(ce)); 131 pos++; 132} 133if((stages & seen) != stages) 134returnerror(_("path '%s' does not have all necessary versions"), 135 name); 136return0; 137} 138 139static intcheckout_stage(int stage,struct cache_entry *ce,int pos, 140struct checkout *state) 141{ 142while(pos < active_nr && 143!strcmp(active_cache[pos]->name, ce->name)) { 144if(ce_stage(active_cache[pos]) == stage) 145returncheckout_entry(active_cache[pos], state, NULL); 146 pos++; 147} 148if(stage ==2) 149returnerror(_("path '%s' does not have our version"), ce->name); 150else 151returnerror(_("path '%s' does not have their version"), ce->name); 152} 153 154static intcheckout_merged(int pos,struct checkout *state) 155{ 156struct cache_entry *ce = active_cache[pos]; 157const char*path = ce->name; 158 mmfile_t ancestor, ours, theirs; 159int status; 160unsigned char sha1[20]; 161 mmbuffer_t result_buf; 162unsigned char threeway[3][20]; 163unsigned mode =0; 164 165memset(threeway,0,sizeof(threeway)); 166while(pos < active_nr) { 167int stage; 168 stage =ce_stage(ce); 169if(!stage ||strcmp(path, ce->name)) 170break; 171hashcpy(threeway[stage -1], ce->sha1); 172if(stage ==2) 173 mode =create_ce_mode(ce->ce_mode); 174 pos++; 175 ce = active_cache[pos]; 176} 177if(is_null_sha1(threeway[1]) ||is_null_sha1(threeway[2])) 178returnerror(_("path '%s' does not have necessary versions"), path); 179 180read_mmblob(&ancestor, threeway[0]); 181read_mmblob(&ours, threeway[1]); 182read_mmblob(&theirs, threeway[2]); 183 184/* 185 * NEEDSWORK: re-create conflicts from merges with 186 * merge.renormalize set, too 187 */ 188 status =ll_merge(&result_buf, path, &ancestor,"base", 189&ours,"ours", &theirs,"theirs", NULL); 190free(ancestor.ptr); 191free(ours.ptr); 192free(theirs.ptr); 193if(status <0|| !result_buf.ptr) { 194free(result_buf.ptr); 195returnerror(_("path '%s': cannot merge"), path); 196} 197 198/* 199 * NEEDSWORK: 200 * There is absolutely no reason to write this as a blob object 201 * and create a phony cache entry just to leak. This hack is 202 * primarily to get to the write_entry() machinery that massages 203 * the contents to work-tree format and writes out which only 204 * allows it for a cache entry. The code in write_entry() needs 205 * to be refactored to allow us to feed a <buffer, size, mode> 206 * instead of a cache entry. Such a refactoring would help 207 * merge_recursive as well (it also writes the merge result to the 208 * object database even when it may contain conflicts). 209 */ 210if(write_sha1_file(result_buf.ptr, result_buf.size, 211 blob_type, sha1)) 212die(_("Unable to add merge result for '%s'"), path); 213 ce =make_cache_entry(mode, sha1, path,2,0); 214if(!ce) 215die(_("make_cache_entry failed for path '%s'"), path); 216 status =checkout_entry(ce, state, NULL); 217return status; 218} 219 220static intcheckout_paths(const struct checkout_opts *opts, 221const char*revision) 222{ 223int pos; 224struct checkout state; 225static char*ps_matched; 226unsigned char rev[20]; 227int flag; 228struct commit *head; 229int errs =0; 230struct lock_file *lock_file; 231 232if(opts->track != BRANCH_TRACK_UNSPECIFIED) 233die(_("'%s' cannot be used with updating paths"),"--track"); 234 235if(opts->new_branch_log) 236die(_("'%s' cannot be used with updating paths"),"-l"); 237 238if(opts->force && opts->patch_mode) 239die(_("'%s' cannot be used with updating paths"),"-f"); 240 241if(opts->force_detach) 242die(_("'%s' cannot be used with updating paths"),"--detach"); 243 244if(opts->merge && opts->patch_mode) 245die(_("'%s' cannot be used with%s"),"--merge","--patch"); 246 247if(opts->force && opts->merge) 248die(_("'%s' cannot be used with%s"),"-f","-m"); 249 250if(opts->new_branch) 251die(_("Cannot update paths and switch to branch '%s' at the same time."), 252 opts->new_branch); 253 254if(opts->patch_mode) 255returnrun_add_interactive(revision,"--patch=checkout", 256&opts->pathspec); 257 258 lock_file =xcalloc(1,sizeof(struct lock_file)); 259 260hold_locked_index(lock_file,1); 261if(read_cache_preload(&opts->pathspec) <0) 262returnerror(_("corrupt index file")); 263 264if(opts->source_tree) 265read_tree_some(opts->source_tree, &opts->pathspec); 266 267 ps_matched =xcalloc(1, opts->pathspec.nr); 268 269/* 270 * Make sure all pathspecs participated in locating the paths 271 * to be checked out. 272 */ 273for(pos =0; pos < active_nr; pos++) { 274struct cache_entry *ce = active_cache[pos]; 275 ce->ce_flags &= ~CE_MATCHED; 276if(!opts->ignore_skipworktree &&ce_skip_worktree(ce)) 277continue; 278if(opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 279/* 280 * "git checkout tree-ish -- path", but this entry 281 * is in the original index; it will not be checked 282 * out to the working tree and it does not matter 283 * if pathspec matched this entry. We will not do 284 * anything to this entry at all. 285 */ 286continue; 287/* 288 * Either this entry came from the tree-ish we are 289 * checking the paths out of, or we are checking out 290 * of the index. 291 * 292 * If it comes from the tree-ish, we already know it 293 * matches the pathspec and could just stamp 294 * CE_MATCHED to it from update_some(). But we still 295 * need ps_matched and read_tree_recursive (and 296 * eventually tree_entry_interesting) cannot fill 297 * ps_matched yet. Once it can, we can avoid calling 298 * match_pathspec() for _all_ entries when 299 * opts->source_tree != NULL. 300 */ 301if(ce_path_match(ce, &opts->pathspec, ps_matched)) 302 ce->ce_flags |= CE_MATCHED; 303} 304 305if(report_path_error(ps_matched, &opts->pathspec, opts->prefix)) { 306free(ps_matched); 307return1; 308} 309free(ps_matched); 310 311/* "checkout -m path" to recreate conflicted state */ 312if(opts->merge) 313unmerge_marked_index(&the_index); 314 315/* Any unmerged paths? */ 316for(pos =0; pos < active_nr; pos++) { 317const struct cache_entry *ce = active_cache[pos]; 318if(ce->ce_flags & CE_MATCHED) { 319if(!ce_stage(ce)) 320continue; 321if(opts->force) { 322warning(_("path '%s' is unmerged"), ce->name); 323}else if(opts->writeout_stage) { 324 errs |=check_stage(opts->writeout_stage, ce, pos); 325}else if(opts->merge) { 326 errs |=check_stages((1<<2) | (1<<3), ce, pos); 327}else{ 328 errs =1; 329error(_("path '%s' is unmerged"), ce->name); 330} 331 pos =skip_same_name(ce, pos) -1; 332} 333} 334if(errs) 335return1; 336 337/* Now we are committed to check them out */ 338memset(&state,0,sizeof(state)); 339 state.force =1; 340 state.refresh_cache =1; 341 state.istate = &the_index; 342for(pos =0; pos < active_nr; pos++) { 343struct cache_entry *ce = active_cache[pos]; 344if(ce->ce_flags & CE_MATCHED) { 345if(!ce_stage(ce)) { 346 errs |=checkout_entry(ce, &state, NULL); 347continue; 348} 349if(opts->writeout_stage) 350 errs |=checkout_stage(opts->writeout_stage, ce, pos, &state); 351else if(opts->merge) 352 errs |=checkout_merged(pos, &state); 353 pos =skip_same_name(ce, pos) -1; 354} 355} 356 357if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 358die(_("unable to write new index file")); 359 360read_ref_full("HEAD",0, rev, &flag); 361 head =lookup_commit_reference_gently(rev,1); 362 363 errs |=post_checkout_hook(head, head,0); 364return errs; 365} 366 367static voidshow_local_changes(struct object *head, 368const struct diff_options *opts) 369{ 370struct rev_info rev; 371/* I think we want full paths, even if we're in a subdirectory. */ 372init_revisions(&rev, NULL); 373 rev.diffopt.flags = opts->flags; 374 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 375diff_setup_done(&rev.diffopt); 376add_pending_object(&rev, head, NULL); 377run_diff_index(&rev,0); 378} 379 380static voiddescribe_detached_head(const char*msg,struct commit *commit) 381{ 382struct strbuf sb = STRBUF_INIT; 383if(!parse_commit(commit)) 384pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 385fprintf(stderr,"%s %s...%s\n", msg, 386find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf); 387strbuf_release(&sb); 388} 389 390static intreset_tree(struct tree *tree,const struct checkout_opts *o, 391int worktree,int*writeout_error) 392{ 393struct unpack_trees_options opts; 394struct tree_desc tree_desc; 395 396memset(&opts,0,sizeof(opts)); 397 opts.head_idx = -1; 398 opts.update = worktree; 399 opts.skip_unmerged = !worktree; 400 opts.reset =1; 401 opts.merge =1; 402 opts.fn = oneway_merge; 403 opts.verbose_update = !o->quiet &&isatty(2); 404 opts.src_index = &the_index; 405 opts.dst_index = &the_index; 406parse_tree(tree); 407init_tree_desc(&tree_desc, tree->buffer, tree->size); 408switch(unpack_trees(1, &tree_desc, &opts)) { 409case-2: 410*writeout_error =1; 411/* 412 * We return 0 nevertheless, as the index is all right 413 * and more importantly we have made best efforts to 414 * update paths in the work tree, and we cannot revert 415 * them. 416 */ 417case0: 418return0; 419default: 420return128; 421} 422} 423 424struct branch_info { 425const char*name;/* The short name used */ 426const char*path;/* The full name of a real branch */ 427struct commit *commit;/* The named commit */ 428/* 429 * if not null the branch is detached because it's already 430 * checked out in this checkout 431 */ 432char*checkout; 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 intgit_checkout_config(const char*var,const char*value,void*cb) 822{ 823if(!strcmp(var,"diff.ignoresubmodules")) { 824struct checkout_opts *opts = cb; 825handle_ignore_submodules_arg(&opts->diff_options, value); 826return0; 827} 828 829if(starts_with(var,"submodule.")) 830returnparse_submodule_config_option(var, value); 831 832returngit_xmerge_config(var, value, NULL); 833} 834 835struct tracking_name_data { 836/* const */char*src_ref; 837char*dst_ref; 838unsigned char*dst_sha1; 839int unique; 840}; 841 842static intcheck_tracking_name(struct remote *remote,void*cb_data) 843{ 844struct tracking_name_data *cb = cb_data; 845struct refspec query; 846memset(&query,0,sizeof(struct refspec)); 847 query.src = cb->src_ref; 848if(remote_find_tracking(remote, &query) || 849get_sha1(query.dst, cb->dst_sha1)) { 850free(query.dst); 851return0; 852} 853if(cb->dst_ref) { 854free(query.dst); 855 cb->unique =0; 856return0; 857} 858 cb->dst_ref = query.dst; 859return0; 860} 861 862static const char*unique_tracking_name(const char*name,unsigned char*sha1) 863{ 864struct tracking_name_data cb_data = { NULL, NULL, NULL,1}; 865char src_ref[PATH_MAX]; 866snprintf(src_ref, PATH_MAX,"refs/heads/%s", name); 867 cb_data.src_ref = src_ref; 868 cb_data.dst_sha1 = sha1; 869for_each_remote(check_tracking_name, &cb_data); 870if(cb_data.unique) 871return cb_data.dst_ref; 872free(cb_data.dst_ref); 873return NULL; 874} 875 876static intparse_branchname_arg(int argc,const char**argv, 877int dwim_new_local_branch_ok, 878struct branch_info *new, 879struct checkout_opts *opts, 880unsigned char rev[20]) 881{ 882struct tree **source_tree = &opts->source_tree; 883const char**new_branch = &opts->new_branch; 884int argcount =0; 885unsigned char branch_rev[20]; 886const char*arg; 887int dash_dash_pos; 888int has_dash_dash =0; 889int i; 890 891/* 892 * case 1: git checkout <ref> -- [<paths>] 893 * 894 * <ref> must be a valid tree, everything after the '--' must be 895 * a path. 896 * 897 * case 2: git checkout -- [<paths>] 898 * 899 * everything after the '--' must be paths. 900 * 901 * case 3: git checkout <something> [--] 902 * 903 * (a) If <something> is a commit, that is to 904 * switch to the branch or detach HEAD at it. As a special case, 905 * if <something> is A...B (missing A or B means HEAD but you can 906 * omit at most one side), and if there is a unique merge base 907 * between A and B, A...B names that merge base. 908 * 909 * (b) If <something> is _not_ a commit, either "--" is present 910 * or <something> is not a path, no -t or -b was given, and 911 * and there is a tracking branch whose name is <something> 912 * in one and only one remote, then this is a short-hand to 913 * fork local <something> from that remote-tracking branch. 914 * 915 * (c) Otherwise, if "--" is present, treat it like case (1). 916 * 917 * (d) Otherwise : 918 * - if it's a reference, treat it like case (1) 919 * - else if it's a path, treat it like case (2) 920 * - else: fail. 921 * 922 * case 4: git checkout <something> <paths> 923 * 924 * The first argument must not be ambiguous. 925 * - If it's *only* a reference, treat it like case (1). 926 * - If it's only a path, treat it like case (2). 927 * - else: fail. 928 * 929 */ 930if(!argc) 931return0; 932 933 arg = argv[0]; 934 dash_dash_pos = -1; 935for(i =0; i < argc; i++) { 936if(!strcmp(argv[i],"--")) { 937 dash_dash_pos = i; 938break; 939} 940} 941if(dash_dash_pos ==0) 942return1;/* case (2) */ 943else if(dash_dash_pos ==1) 944 has_dash_dash =1;/* case (3) or (1) */ 945else if(dash_dash_pos >=2) 946die(_("only one reference expected,%dgiven."), dash_dash_pos); 947 948if(!strcmp(arg,"-")) 949 arg ="@{-1}"; 950 951if(get_sha1_mb(arg, rev)) { 952/* 953 * Either case (3) or (4), with <something> not being 954 * a commit, or an attempt to use case (1) with an 955 * invalid ref. 956 * 957 * It's likely an error, but we need to find out if 958 * we should auto-create the branch, case (3).(b). 959 */ 960int recover_with_dwim = dwim_new_local_branch_ok; 961 962if(check_filename(NULL, arg) && !has_dash_dash) 963 recover_with_dwim =0; 964/* 965 * Accept "git checkout foo" and "git checkout foo --" 966 * as candidates for dwim. 967 */ 968if(!(argc ==1&& !has_dash_dash) && 969!(argc ==2&& has_dash_dash)) 970 recover_with_dwim =0; 971 972if(recover_with_dwim) { 973const char*remote =unique_tracking_name(arg, rev); 974if(remote) { 975*new_branch = arg; 976 arg = remote; 977/* DWIMmed to create local branch, case (3).(b) */ 978}else{ 979 recover_with_dwim =0; 980} 981} 982 983if(!recover_with_dwim) { 984if(has_dash_dash) 985die(_("invalid reference:%s"), arg); 986return argcount; 987} 988} 989 990/* we can't end up being in (2) anymore, eat the argument */ 991 argcount++; 992 argv++; 993 argc--; 994 995new->name = arg; 996setup_branch_path(new); 997 998if(!check_refname_format(new->path,0) && 999!read_ref(new->path, branch_rev))1000hashcpy(rev, branch_rev);1001else1002new->path = NULL;/* not an existing branch */10031004new->commit =lookup_commit_reference_gently(rev,1);1005if(!new->commit) {1006/* not a commit */1007*source_tree =parse_tree_indirect(rev);1008}else{1009parse_commit_or_die(new->commit);1010*source_tree =new->commit->tree;1011}10121013if(!*source_tree)/* case (1): want a tree */1014die(_("reference is not a tree:%s"), arg);1015if(!has_dash_dash) {/* case (3).(d) -> (1) */1016/*1017 * Do not complain the most common case1018 * git checkout branch1019 * even if there happen to be a file called 'branch';1020 * it would be extremely annoying.1021 */1022if(argc)1023verify_non_filename(NULL, arg);1024}else{1025 argcount++;1026 argv++;1027 argc--;1028}10291030return argcount;1031}10321033static intswitch_unborn_to_new_branch(const struct checkout_opts *opts)1034{1035int status;1036struct strbuf branch_ref = STRBUF_INIT;10371038if(!opts->new_branch)1039die(_("You are on a branch yet to be born"));1040strbuf_addf(&branch_ref,"refs/heads/%s", opts->new_branch);1041 status =create_symref("HEAD", branch_ref.buf,"checkout -b");1042strbuf_release(&branch_ref);1043if(!opts->quiet)1044fprintf(stderr,_("Switched to a new branch '%s'\n"),1045 opts->new_branch);1046return status;1047}10481049static intcheckout_branch(struct checkout_opts *opts,1050struct branch_info *new)1051{1052if(opts->pathspec.nr)1053die(_("paths cannot be used with switching branches"));10541055if(opts->patch_mode)1056die(_("'%s' cannot be used with switching branches"),1057"--patch");10581059if(opts->writeout_stage)1060die(_("'%s' cannot be used with switching branches"),1061"--ours/--theirs");10621063if(opts->force && opts->merge)1064die(_("'%s' cannot be used with '%s'"),"-f","-m");10651066if(opts->force_detach && opts->new_branch)1067die(_("'%s' cannot be used with '%s'"),1068"--detach","-b/-B/--orphan");10691070if(opts->new_orphan_branch) {1071if(opts->track != BRANCH_TRACK_UNSPECIFIED)1072die(_("'%s' cannot be used with '%s'"),"--orphan","-t");1073}else if(opts->force_detach) {1074if(opts->track != BRANCH_TRACK_UNSPECIFIED)1075die(_("'%s' cannot be used with '%s'"),"--detach","-t");1076}else if(opts->track == BRANCH_TRACK_UNSPECIFIED)1077 opts->track = git_branch_track;10781079if(new->name && !new->commit)1080die(_("Cannot switch branch to a non-commit '%s'"),1081new->name);10821083if(new->path && !opts->force_detach && !opts->new_branch &&1084!opts->ignore_other_worktrees) {1085unsigned char sha1[20];1086int flag;1087char*head_ref =resolve_refdup("HEAD",0, sha1, &flag);1088if(head_ref &&1089(!(flag & REF_ISSYMREF) ||strcmp(head_ref,new->path)))1090die_if_checked_out(new->path);1091free(head_ref);1092}10931094if(!new->commit && opts->new_branch) {1095unsigned char rev[20];1096int flag;10971098if(!read_ref_full("HEAD",0, rev, &flag) &&1099(flag & REF_ISSYMREF) &&is_null_sha1(rev))1100returnswitch_unborn_to_new_branch(opts);1101}1102returnswitch_branches(opts,new);1103}11041105intcmd_checkout(int argc,const char**argv,const char*prefix)1106{1107struct checkout_opts opts;1108struct branch_info new;1109char*conflict_style = NULL;1110int dwim_new_local_branch =1;1111struct option options[] = {1112OPT__QUIET(&opts.quiet,N_("suppress progress reporting")),1113OPT_STRING('b', NULL, &opts.new_branch,N_("branch"),1114N_("create and checkout a new branch")),1115OPT_STRING('B', NULL, &opts.new_branch_force,N_("branch"),1116N_("create/reset and checkout a branch")),1117OPT_BOOL('l', NULL, &opts.new_branch_log,N_("create reflog for new branch")),1118OPT_BOOL(0,"detach", &opts.force_detach,N_("detach the HEAD at named commit")),1119OPT_SET_INT('t',"track", &opts.track,N_("set upstream info for new branch"),1120 BRANCH_TRACK_EXPLICIT),1121OPT_STRING(0,"orphan", &opts.new_orphan_branch,N_("new-branch"),N_("new unparented branch")),1122OPT_SET_INT('2',"ours", &opts.writeout_stage,N_("checkout our version for unmerged files"),11232),1124OPT_SET_INT('3',"theirs", &opts.writeout_stage,N_("checkout their version for unmerged files"),11253),1126OPT__FORCE(&opts.force,N_("force checkout (throw away local modifications)")),1127OPT_BOOL('m',"merge", &opts.merge,N_("perform a 3-way merge with the new branch")),1128OPT_BOOL(0,"overwrite-ignore", &opts.overwrite_ignore,N_("update ignored files (default)")),1129OPT_STRING(0,"conflict", &conflict_style,N_("style"),1130N_("conflict style (merge or diff3)")),1131OPT_BOOL('p',"patch", &opts.patch_mode,N_("select hunks interactively")),1132OPT_BOOL(0,"ignore-skip-worktree-bits", &opts.ignore_skipworktree,1133N_("do not limit pathspecs to sparse entries only")),1134OPT_HIDDEN_BOOL(0,"guess", &dwim_new_local_branch,1135N_("second guess 'git checkout no-such-branch'")),1136OPT_BOOL(0,"ignore-other-worktrees", &opts.ignore_other_worktrees,1137N_("do not check if another worktree is holding the given ref")),1138OPT_END(),1139};11401141memset(&opts,0,sizeof(opts));1142memset(&new,0,sizeof(new));1143 opts.overwrite_ignore =1;1144 opts.prefix = prefix;11451146gitmodules_config();1147git_config(git_checkout_config, &opts);11481149 opts.track = BRANCH_TRACK_UNSPECIFIED;11501151 argc =parse_options(argc, argv, prefix, options, checkout_usage,1152 PARSE_OPT_KEEP_DASHDASH);11531154 opts.new_worktree_mode =getenv("GIT_CHECKOUT_NEW_WORKTREE") != NULL;11551156if(conflict_style) {1157 opts.merge =1;/* implied */1158git_xmerge_config("merge.conflictstyle", conflict_style, NULL);1159}11601161if((!!opts.new_branch + !!opts.new_branch_force + !!opts.new_orphan_branch) >1)1162die(_("-b, -B and --orphan are mutually exclusive"));11631164/*1165 * From here on, new_branch will contain the branch to be checked out,1166 * and new_branch_force and new_orphan_branch will tell us which one of1167 * -b/-B/--orphan is being used.1168 */1169if(opts.new_branch_force)1170 opts.new_branch = opts.new_branch_force;11711172if(opts.new_orphan_branch)1173 opts.new_branch = opts.new_orphan_branch;11741175/* --track without -b/-B/--orphan should DWIM */1176if(opts.track != BRANCH_TRACK_UNSPECIFIED && !opts.new_branch) {1177const char*argv0 = argv[0];1178if(!argc || !strcmp(argv0,"--"))1179die(_("--track needs a branch name"));1180skip_prefix(argv0,"refs/", &argv0);1181skip_prefix(argv0,"remotes/", &argv0);1182 argv0 =strchr(argv0,'/');1183if(!argv0 || !argv0[1])1184die(_("Missing branch name; try -b"));1185 opts.new_branch = argv0 +1;1186}11871188/*1189 * Extract branch name from command line arguments, so1190 * all that is left is pathspecs.1191 *1192 * Handle1193 *1194 * 1) git checkout <tree> -- [<paths>]1195 * 2) git checkout -- [<paths>]1196 * 3) git checkout <something> [<paths>]1197 *1198 * including "last branch" syntax and DWIM-ery for names of1199 * remote branches, erroring out for invalid or ambiguous cases.1200 */1201if(argc) {1202unsigned char rev[20];1203int dwim_ok =1204!opts.patch_mode &&1205 dwim_new_local_branch &&1206 opts.track == BRANCH_TRACK_UNSPECIFIED &&1207!opts.new_branch;1208int n =parse_branchname_arg(argc, argv, dwim_ok,1209&new, &opts, rev);1210 argv += n;1211 argc -= n;1212}12131214if(argc) {1215parse_pathspec(&opts.pathspec,0,1216 opts.patch_mode ? PATHSPEC_PREFIX_ORIGIN :0,1217 prefix, argv);12181219if(!opts.pathspec.nr)1220die(_("invalid path specification"));12211222/*1223 * Try to give more helpful suggestion.1224 * new_branch && argc > 1 will be caught later.1225 */1226if(opts.new_branch && argc ==1)1227die(_("Cannot update paths and switch to branch '%s' at the same time.\n"1228"Did you intend to checkout '%s' which can not be resolved as commit?"),1229 opts.new_branch, argv[0]);12301231if(opts.force_detach)1232die(_("git checkout: --detach does not take a path argument '%s'"),1233 argv[0]);12341235if(1< !!opts.writeout_stage + !!opts.force + !!opts.merge)1236die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"1237"checking out of the index."));1238}12391240if(opts.new_branch) {1241struct strbuf buf = STRBUF_INIT;12421243 opts.branch_exists =1244validate_new_branchname(opts.new_branch, &buf,1245!!opts.new_branch_force,1246!!opts.new_branch_force);12471248strbuf_release(&buf);1249}12501251if(opts.patch_mode || opts.pathspec.nr)1252returncheckout_paths(&opts,new.name);1253else1254returncheckout_branch(&opts, &new);1255}