Git fork
at reftables-rust 2111 lines 66 kB view raw
1#define USE_THE_REPOSITORY_VARIABLE 2#define DISABLE_SIGN_COMPARE_WARNINGS 3 4#include "builtin.h" 5#include "advice.h" 6#include "branch.h" 7#include "cache-tree.h" 8#include "checkout.h" 9#include "commit.h" 10#include "config.h" 11#include "diff.h" 12#include "dir.h" 13#include "environment.h" 14#include "gettext.h" 15#include "hex.h" 16#include "hook.h" 17#include "merge-ll.h" 18#include "lockfile.h" 19#include "mem-pool.h" 20#include "merge-ort-wrappers.h" 21#include "object-file.h" 22#include "object-name.h" 23#include "odb.h" 24#include "parse-options.h" 25#include "path.h" 26#include "preload-index.h" 27#include "read-cache.h" 28#include "refs.h" 29#include "remote.h" 30#include "repo-settings.h" 31#include "resolve-undo.h" 32#include "revision.h" 33#include "setup.h" 34#include "submodule.h" 35#include "symlinks.h" 36#include "trace2.h" 37#include "tree.h" 38#include "tree-walk.h" 39#include "unpack-trees.h" 40#include "wt-status.h" 41#include "xdiff-interface.h" 42#include "entry.h" 43#include "parallel-checkout.h" 44#include "add-interactive.h" 45 46static const char * const checkout_usage[] = { 47 N_("git checkout [<options>] <branch>"), 48 N_("git checkout [<options>] [<branch>] -- <file>..."), 49 NULL, 50}; 51 52static const char * const switch_branch_usage[] = { 53 N_("git switch [<options>] [<branch>]"), 54 NULL, 55}; 56 57static const char * const restore_usage[] = { 58 N_("git restore [<options>] [--source=<branch>] <file>..."), 59 NULL, 60}; 61 62struct checkout_opts { 63 int patch_mode; 64 int patch_context; 65 int patch_interhunk_context; 66 int quiet; 67 int merge; 68 int force; 69 int force_detach; 70 int implicit_detach; 71 int writeout_stage; 72 int overwrite_ignore; 73 int ignore_skipworktree; 74 int ignore_other_worktrees; 75 int show_progress; 76 int count_checkout_paths; 77 int overlay_mode; 78 int dwim_new_local_branch; 79 int discard_changes; 80 int accept_ref; 81 int accept_pathspec; 82 int switch_branch_doing_nothing_is_ok; 83 int only_merge_on_switching_branches; 84 int can_switch_when_in_progress; 85 int orphan_from_empty_tree; 86 int empty_pathspec_ok; 87 int checkout_index; 88 int checkout_worktree; 89 const char *ignore_unmerged_opt; 90 int ignore_unmerged; 91 int pathspec_file_nul; 92 char *pathspec_from_file; 93 94 const char *new_branch; 95 const char *new_branch_force; 96 const char *new_orphan_branch; 97 int new_branch_log; 98 enum branch_track track; 99 struct diff_options diff_options; 100 int conflict_style; 101 102 int branch_exists; 103 const char *prefix; 104 struct pathspec pathspec; 105 const char *from_treeish; 106 struct tree *source_tree; 107}; 108 109#define CHECKOUT_OPTS_INIT { \ 110 .conflict_style = -1, \ 111 .merge = -1, \ 112 .patch_context = -1, \ 113 .patch_interhunk_context = -1, \ 114} 115 116struct branch_info { 117 char *name; /* The short name used */ 118 char *path; /* The full name of a real branch */ 119 struct commit *commit; /* The named commit */ 120 char *refname; /* The full name of the ref being checked out. */ 121 struct object_id oid; /* The object ID of the commit being checked out. */ 122 /* 123 * if not null the branch is detached because it's already 124 * checked out in this checkout 125 */ 126 char *checkout; 127}; 128 129static void branch_info_release(struct branch_info *info) 130{ 131 free(info->name); 132 free(info->path); 133 free(info->refname); 134 free(info->checkout); 135} 136 137static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit, 138 int changed) 139{ 140 return run_hooks_l(the_repository, "post-checkout", 141 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid(the_hash_algo)), 142 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid(the_hash_algo)), 143 changed ? "1" : "0", NULL); 144 /* "new_commit" can be NULL when checking out from the index before 145 a commit exists. */ 146 147} 148 149static int update_some(const struct object_id *oid, struct strbuf *base, 150 const char *pathname, unsigned mode, void *context UNUSED) 151{ 152 int len; 153 struct cache_entry *ce; 154 int pos; 155 156 if (S_ISDIR(mode)) 157 return READ_TREE_RECURSIVE; 158 159 len = base->len + strlen(pathname); 160 ce = make_empty_cache_entry(the_repository->index, len); 161 oidcpy(&ce->oid, oid); 162 memcpy(ce->name, base->buf, base->len); 163 memcpy(ce->name + base->len, pathname, len - base->len); 164 ce->ce_flags = create_ce_flags(0) | CE_UPDATE; 165 ce->ce_namelen = len; 166 ce->ce_mode = create_ce_mode(mode); 167 168 /* 169 * If the entry is the same as the current index, we can leave the old 170 * entry in place. Whether it is UPTODATE or not, checkout_entry will 171 * do the right thing. 172 */ 173 pos = index_name_pos(the_repository->index, ce->name, ce->ce_namelen); 174 if (pos >= 0) { 175 struct cache_entry *old = the_repository->index->cache[pos]; 176 if (ce->ce_mode == old->ce_mode && 177 !ce_intent_to_add(old) && 178 oideq(&ce->oid, &old->oid)) { 179 old->ce_flags |= CE_UPDATE; 180 discard_cache_entry(ce); 181 return 0; 182 } 183 } 184 185 add_index_entry(the_repository->index, ce, 186 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 187 return 0; 188} 189 190static int read_tree_some(struct tree *tree, const struct pathspec *pathspec) 191{ 192 read_tree(the_repository, tree, 193 pathspec, update_some, NULL); 194 195 /* update the index with the given tree's info 196 * for all args, expanding wildcards, and exit 197 * with any non-zero return code. 198 */ 199 return 0; 200} 201 202static int skip_same_name(const struct cache_entry *ce, int pos) 203{ 204 while (++pos < the_repository->index->cache_nr && 205 !strcmp(the_repository->index->cache[pos]->name, ce->name)) 206 ; /* skip */ 207 return pos; 208} 209 210static int check_stage(int stage, const struct cache_entry *ce, int pos, 211 int overlay_mode) 212{ 213 while (pos < the_repository->index->cache_nr && 214 !strcmp(the_repository->index->cache[pos]->name, ce->name)) { 215 if (ce_stage(the_repository->index->cache[pos]) == stage) 216 return 0; 217 pos++; 218 } 219 if (!overlay_mode) 220 return 0; 221 if (stage == 2) 222 return error(_("path '%s' does not have our version"), ce->name); 223 else 224 return error(_("path '%s' does not have their version"), ce->name); 225} 226 227static int check_stages(unsigned stages, const struct cache_entry *ce, int pos) 228{ 229 unsigned seen = 0; 230 const char *name = ce->name; 231 232 while (pos < the_repository->index->cache_nr) { 233 ce = the_repository->index->cache[pos]; 234 if (strcmp(name, ce->name)) 235 break; 236 seen |= (1 << ce_stage(ce)); 237 pos++; 238 } 239 if ((stages & seen) != stages) 240 return error(_("path '%s' does not have all necessary versions"), 241 name); 242 return 0; 243} 244 245static int checkout_stage(int stage, const struct cache_entry *ce, int pos, 246 const struct checkout *state, int *nr_checkouts, 247 int overlay_mode) 248{ 249 while (pos < the_repository->index->cache_nr && 250 !strcmp(the_repository->index->cache[pos]->name, ce->name)) { 251 if (ce_stage(the_repository->index->cache[pos]) == stage) 252 return checkout_entry(the_repository->index->cache[pos], state, 253 NULL, nr_checkouts); 254 pos++; 255 } 256 if (!overlay_mode) { 257 unlink_entry(ce, NULL); 258 return 0; 259 } 260 if (stage == 2) 261 return error(_("path '%s' does not have our version"), ce->name); 262 else 263 return error(_("path '%s' does not have their version"), ce->name); 264} 265 266static int checkout_merged(int pos, const struct checkout *state, 267 int *nr_checkouts, struct mem_pool *ce_mem_pool, 268 int conflict_style) 269{ 270 struct cache_entry *ce = the_repository->index->cache[pos]; 271 const char *path = ce->name; 272 mmfile_t ancestor, ours, theirs; 273 enum ll_merge_result merge_status; 274 int status; 275 struct object_id oid; 276 mmbuffer_t result_buf; 277 struct object_id threeway[3]; 278 unsigned mode = 0; 279 struct ll_merge_options ll_opts = LL_MERGE_OPTIONS_INIT; 280 int renormalize = 0; 281 282 memset(threeway, 0, sizeof(threeway)); 283 while (pos < the_repository->index->cache_nr) { 284 int stage; 285 stage = ce_stage(ce); 286 if (!stage || strcmp(path, ce->name)) 287 break; 288 oidcpy(&threeway[stage - 1], &ce->oid); 289 if (stage == 2) 290 mode = create_ce_mode(ce->ce_mode); 291 pos++; 292 ce = the_repository->index->cache[pos]; 293 } 294 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2])) 295 return error(_("path '%s' does not have necessary versions"), path); 296 297 read_mmblob(&ancestor, &threeway[0]); 298 read_mmblob(&ours, &threeway[1]); 299 read_mmblob(&theirs, &threeway[2]); 300 301 repo_config_get_bool(the_repository, "merge.renormalize", &renormalize); 302 ll_opts.renormalize = renormalize; 303 ll_opts.conflict_style = conflict_style; 304 merge_status = ll_merge(&result_buf, path, &ancestor, "base", 305 &ours, "ours", &theirs, "theirs", 306 state->istate, &ll_opts); 307 free(ancestor.ptr); 308 free(ours.ptr); 309 free(theirs.ptr); 310 if (merge_status == LL_MERGE_BINARY_CONFLICT) 311 warning("Cannot merge binary files: %s (%s vs. %s)", 312 path, "ours", "theirs"); 313 if (merge_status < 0 || !result_buf.ptr) { 314 free(result_buf.ptr); 315 return error(_("path '%s': cannot merge"), path); 316 } 317 318 /* 319 * NEEDSWORK: 320 * There is absolutely no reason to write this as a blob object 321 * and create a phony cache entry. This hack is primarily to get 322 * to the write_entry() machinery that massages the contents to 323 * work-tree format and writes out which only allows it for a 324 * cache entry. The code in write_entry() needs to be refactored 325 * to allow us to feed a <buffer, size, mode> instead of a cache 326 * entry. Such a refactoring would help merge_recursive as well 327 * (it also writes the merge result to the object database even 328 * when it may contain conflicts). 329 */ 330 if (odb_write_object(the_repository->objects, result_buf.ptr, result_buf.size, OBJ_BLOB, &oid)) 331 die(_("Unable to add merge result for '%s'"), path); 332 free(result_buf.ptr); 333 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool); 334 if (!ce) 335 die(_("make_cache_entry failed for path '%s'"), path); 336 status = checkout_entry(ce, state, NULL, nr_checkouts); 337 return status; 338} 339 340static void mark_ce_for_checkout_overlay(struct cache_entry *ce, 341 char *ps_matched, 342 const struct checkout_opts *opts) 343{ 344 ce->ce_flags &= ~CE_MATCHED; 345 if (!opts->ignore_skipworktree && ce_skip_worktree(ce)) 346 return; 347 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 348 /* 349 * "git checkout tree-ish -- path", but this entry 350 * is in the original index but is not in tree-ish 351 * or does not match the pathspec; it will not be 352 * checked out to the working tree. We will not do 353 * anything to this entry at all. 354 */ 355 return; 356 /* 357 * Either this entry came from the tree-ish we are 358 * checking the paths out of, or we are checking out 359 * of the index. 360 * 361 * If it comes from the tree-ish, we already know it 362 * matches the pathspec and could just stamp 363 * CE_MATCHED to it from update_some(). But we still 364 * need ps_matched and read_tree (and 365 * eventually tree_entry_interesting) cannot fill 366 * ps_matched yet. Once it can, we can avoid calling 367 * match_pathspec() for _all_ entries when 368 * opts->source_tree != NULL. 369 */ 370 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched)) 371 ce->ce_flags |= CE_MATCHED; 372} 373 374static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce, 375 char *ps_matched, 376 const struct checkout_opts *opts) 377{ 378 ce->ce_flags &= ~CE_MATCHED; 379 if (!opts->ignore_skipworktree && ce_skip_worktree(ce)) 380 return; 381 if (ce_path_match(the_repository->index, ce, &opts->pathspec, ps_matched)) { 382 ce->ce_flags |= CE_MATCHED; 383 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE)) 384 /* 385 * In overlay mode, but the path is not in 386 * tree-ish, which means we should remove it 387 * from the index and the working tree. 388 */ 389 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE; 390 } 391} 392 393static int checkout_worktree(const struct checkout_opts *opts, 394 const struct branch_info *info) 395{ 396 struct checkout state = CHECKOUT_INIT; 397 int nr_checkouts = 0, nr_unmerged = 0; 398 int errs = 0; 399 int pos; 400 int pc_workers, pc_threshold; 401 struct mem_pool ce_mem_pool; 402 403 state.force = 1; 404 state.refresh_cache = 1; 405 state.istate = the_repository->index; 406 407 mem_pool_init(&ce_mem_pool, 0); 408 get_parallel_checkout_configs(&pc_workers, &pc_threshold); 409 init_checkout_metadata(&state.meta, info->refname, 410 info->commit ? &info->commit->object.oid : &info->oid, 411 NULL); 412 413 enable_delayed_checkout(&state); 414 415 if (pc_workers > 1) 416 init_parallel_checkout(); 417 418 for (pos = 0; pos < the_repository->index->cache_nr; pos++) { 419 struct cache_entry *ce = the_repository->index->cache[pos]; 420 if (ce->ce_flags & CE_MATCHED) { 421 if (!ce_stage(ce)) { 422 errs |= checkout_entry(ce, &state, 423 NULL, &nr_checkouts); 424 continue; 425 } 426 if (opts->writeout_stage) 427 errs |= checkout_stage(opts->writeout_stage, 428 ce, pos, 429 &state, 430 &nr_checkouts, opts->overlay_mode); 431 else if (opts->merge) 432 errs |= checkout_merged(pos, &state, 433 &nr_unmerged, 434 &ce_mem_pool, 435 opts->conflict_style); 436 pos = skip_same_name(ce, pos) - 1; 437 } 438 } 439 if (pc_workers > 1) 440 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold, 441 NULL, NULL); 442 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries()); 443 remove_marked_cache_entries(the_repository->index, 1); 444 remove_scheduled_dirs(); 445 errs |= finish_delayed_checkout(&state, opts->show_progress); 446 447 if (opts->count_checkout_paths) { 448 if (nr_unmerged) 449 fprintf_ln(stderr, Q_("Recreated %d merge conflict", 450 "Recreated %d merge conflicts", 451 nr_unmerged), 452 nr_unmerged); 453 if (opts->source_tree) 454 fprintf_ln(stderr, Q_("Updated %d path from %s", 455 "Updated %d paths from %s", 456 nr_checkouts), 457 nr_checkouts, 458 repo_find_unique_abbrev(the_repository, &opts->source_tree->object.oid, 459 DEFAULT_ABBREV)); 460 else if (!nr_unmerged || nr_checkouts) 461 fprintf_ln(stderr, Q_("Updated %d path from the index", 462 "Updated %d paths from the index", 463 nr_checkouts), 464 nr_checkouts); 465 } 466 467 return errs; 468} 469 470static int checkout_paths(const struct checkout_opts *opts, 471 const struct branch_info *new_branch_info) 472{ 473 int pos; 474 static char *ps_matched; 475 struct object_id rev; 476 struct commit *head; 477 int errs = 0; 478 struct lock_file lock_file = LOCK_INIT; 479 int checkout_index; 480 481 trace2_cmd_mode(opts->patch_mode ? "patch" : "path"); 482 483 if (opts->track != BRANCH_TRACK_UNSPECIFIED) 484 die(_("'%s' cannot be used with updating paths"), "--track"); 485 486 if (opts->new_branch_log) 487 die(_("'%s' cannot be used with updating paths"), "-l"); 488 489 if (opts->ignore_unmerged && opts->patch_mode) 490 die(_("'%s' cannot be used with updating paths"), 491 opts->ignore_unmerged_opt); 492 493 if (opts->force_detach) 494 die(_("'%s' cannot be used with updating paths"), "--detach"); 495 496 if (opts->merge && opts->patch_mode) 497 die(_("options '%s' and '%s' cannot be used together"), "--merge", "--patch"); 498 499 if (opts->ignore_unmerged && opts->merge) 500 die(_("options '%s' and '%s' cannot be used together"), 501 opts->ignore_unmerged_opt, "-m"); 502 503 if (opts->new_branch) 504 die(_("Cannot update paths and switch to branch '%s' at the same time."), 505 opts->new_branch); 506 507 if (!opts->checkout_worktree && !opts->checkout_index) 508 die(_("neither '%s' or '%s' is specified"), 509 "--staged", "--worktree"); 510 511 if (!opts->checkout_worktree && !opts->from_treeish) 512 die(_("'%s' must be used when '%s' is not specified"), 513 "--worktree", "--source"); 514 515 /* 516 * Reject --staged option to the restore command when combined with 517 * merge-related options. Use the accept_ref flag to distinguish it 518 * from the checkout command, which does not accept --staged anyway. 519 * 520 * `restore --ours|--theirs --worktree --staged` could mean resolving 521 * conflicted paths to one side in both the worktree and the index, 522 * but does not currently. 523 * 524 * `restore --merge|--conflict=<style>` already recreates conflicts 525 * in both the worktree and the index, so adding --staged would be 526 * meaningless. 527 */ 528 if (!opts->accept_ref && opts->checkout_index) { 529 if (opts->writeout_stage) 530 die(_("'%s' or '%s' cannot be used with %s"), 531 "--ours", "--theirs", "--staged"); 532 533 if (opts->merge) 534 die(_("'%s' or '%s' cannot be used with %s"), 535 "--merge", "--conflict", "--staged"); 536 } 537 538 /* 539 * recreating unmerged index entries and writing out data from 540 * unmerged index entries would make no sense when checking out 541 * of a tree-ish. 542 */ 543 if ((opts->merge || opts->writeout_stage) && opts->source_tree) 544 die(_("'%s', '%s', or '%s' cannot be used when checking out of a tree"), 545 "--merge", "--ours", "--theirs"); 546 547 if (opts->patch_mode) { 548 enum add_p_mode patch_mode; 549 struct add_p_opt add_p_opt = { 550 .context = opts->patch_context, 551 .interhunkcontext = opts->patch_interhunk_context, 552 }; 553 const char *rev = new_branch_info->name; 554 char rev_oid[GIT_MAX_HEXSZ + 1]; 555 556 /* 557 * Since rev can be in the form of `<a>...<b>` (which is not 558 * recognized by diff-index), we will always replace the name 559 * with the hex of the commit (whether it's in `...` form or 560 * not) for the run_add_interactive() machinery to work 561 * properly. However, there is special logic for the HEAD case 562 * so we mustn't replace that. Also, when we were given a 563 * tree-object, new_branch_info->commit would be NULL, but we 564 * do not have to do any replacement, either. 565 */ 566 if (rev && new_branch_info->commit && strcmp(rev, "HEAD")) 567 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid); 568 569 if (opts->checkout_index && opts->checkout_worktree) 570 patch_mode = ADD_P_CHECKOUT; 571 else if (opts->checkout_index && !opts->checkout_worktree) 572 patch_mode = ADD_P_RESET; 573 else if (!opts->checkout_index && opts->checkout_worktree) 574 patch_mode = ADD_P_WORKTREE; 575 else 576 BUG("either flag must have been set, worktree=%d, index=%d", 577 opts->checkout_worktree, opts->checkout_index); 578 return !!run_add_p(the_repository, patch_mode, &add_p_opt, 579 rev, &opts->pathspec); 580 } 581 582 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 583 if (repo_read_index_preload(the_repository, &opts->pathspec, 0) < 0) 584 return error(_("index file corrupt")); 585 586 if (opts->source_tree) 587 read_tree_some(opts->source_tree, &opts->pathspec); 588 if (opts->merge) 589 unmerge_index(the_repository->index, &opts->pathspec, CE_MATCHED); 590 591 ps_matched = xcalloc(opts->pathspec.nr, 1); 592 593 /* 594 * Make sure all pathspecs participated in locating the paths 595 * to be checked out. 596 */ 597 for (pos = 0; pos < the_repository->index->cache_nr; pos++) 598 if (opts->overlay_mode) 599 mark_ce_for_checkout_overlay(the_repository->index->cache[pos], 600 ps_matched, 601 opts); 602 else 603 mark_ce_for_checkout_no_overlay(the_repository->index->cache[pos], 604 ps_matched, 605 opts); 606 607 if (report_path_error(ps_matched, &opts->pathspec)) { 608 free(ps_matched); 609 return 1; 610 } 611 free(ps_matched); 612 613 /* Any unmerged paths? */ 614 for (pos = 0; pos < the_repository->index->cache_nr; pos++) { 615 const struct cache_entry *ce = the_repository->index->cache[pos]; 616 if (ce->ce_flags & CE_MATCHED) { 617 if (!ce_stage(ce)) 618 continue; 619 if (opts->ignore_unmerged) { 620 if (!opts->quiet) 621 warning(_("path '%s' is unmerged"), ce->name); 622 } else if (opts->writeout_stage) { 623 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode); 624 } else if (opts->merge) { 625 errs |= check_stages((1<<2) | (1<<3), ce, pos); 626 } else { 627 errs = 1; 628 error(_("path '%s' is unmerged"), ce->name); 629 } 630 pos = skip_same_name(ce, pos) - 1; 631 } 632 } 633 if (errs) 634 return 1; 635 636 /* Now we are committed to check them out */ 637 if (opts->checkout_worktree) 638 errs |= checkout_worktree(opts, new_branch_info); 639 else 640 remove_marked_cache_entries(the_repository->index, 1); 641 642 /* 643 * Allow updating the index when checking out from the index. 644 * This is to save new stat info. 645 */ 646 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree) 647 checkout_index = 1; 648 else 649 checkout_index = opts->checkout_index; 650 651 if (checkout_index) { 652 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK)) 653 die(_("unable to write new index file")); 654 } else { 655 /* 656 * NEEDSWORK: if --worktree is not specified, we 657 * should save stat info of checked out files in the 658 * index to avoid the next (potentially costly) 659 * refresh. But it's a bit tricker to do... 660 */ 661 rollback_lock_file(&lock_file); 662 } 663 664 refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, 665 &rev, NULL); 666 head = lookup_commit_reference_gently(the_repository, &rev, 1); 667 668 errs |= post_checkout_hook(head, head, 0); 669 return errs; 670} 671 672static void show_local_changes(struct object *head, 673 const struct diff_options *opts) 674{ 675 struct rev_info rev; 676 /* I think we want full paths, even if we're in a subdirectory. */ 677 repo_init_revisions(the_repository, &rev, NULL); 678 rev.diffopt.flags = opts->flags; 679 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS; 680 rev.diffopt.flags.recursive = 1; 681 diff_setup_done(&rev.diffopt); 682 add_pending_object(&rev, head, NULL); 683 run_diff_index(&rev, 0); 684 release_revisions(&rev); 685} 686 687static void describe_detached_head(const char *msg, struct commit *commit) 688{ 689 struct strbuf sb = STRBUF_INIT; 690 691 if (!repo_parse_commit(the_repository, commit)) 692 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb); 693 if (print_sha1_ellipsis()) { 694 fprintf(stderr, "%s %s... %s\n", msg, 695 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV), 696 sb.buf); 697 } else { 698 fprintf(stderr, "%s %s %s\n", msg, 699 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV), 700 sb.buf); 701 } 702 strbuf_release(&sb); 703} 704 705static int reset_tree(struct tree *tree, const struct checkout_opts *o, 706 int worktree, int *writeout_error, 707 struct branch_info *info) 708{ 709 struct unpack_trees_options opts; 710 struct tree_desc tree_desc; 711 712 memset(&opts, 0, sizeof(opts)); 713 opts.head_idx = -1; 714 opts.update = worktree; 715 opts.skip_unmerged = !worktree; 716 opts.reset = o->force ? UNPACK_RESET_OVERWRITE_UNTRACKED : 717 UNPACK_RESET_PROTECT_UNTRACKED; 718 opts.preserve_ignored = (!o->force && !o->overwrite_ignore); 719 opts.merge = 1; 720 opts.fn = oneway_merge; 721 opts.verbose_update = o->show_progress; 722 opts.src_index = the_repository->index; 723 opts.dst_index = the_repository->index; 724 init_checkout_metadata(&opts.meta, info->refname, 725 info->commit ? &info->commit->object.oid : null_oid(the_hash_algo), 726 NULL); 727 if (parse_tree(tree) < 0) 728 return 128; 729 init_tree_desc(&tree_desc, &tree->object.oid, tree->buffer, tree->size); 730 switch (unpack_trees(1, &tree_desc, &opts)) { 731 case -2: 732 *writeout_error = 1; 733 /* 734 * We return 0 nevertheless, as the index is all right 735 * and more importantly we have made best efforts to 736 * update paths in the work tree, and we cannot revert 737 * them. 738 */ 739 /* fallthrough */ 740 case 0: 741 return 0; 742 default: 743 return 128; 744 } 745} 746 747static void setup_branch_path(struct branch_info *branch) 748{ 749 struct strbuf buf = STRBUF_INIT; 750 751 /* 752 * If this is a ref, resolve it; otherwise, look up the OID for our 753 * expression. Failure here is okay. 754 */ 755 if (!repo_dwim_ref(the_repository, branch->name, strlen(branch->name), 756 &branch->oid, &branch->refname, 0)) 757 repo_get_oid_committish(the_repository, branch->name, &branch->oid); 758 759 copy_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL); 760 if (strcmp(buf.buf, branch->name)) { 761 free(branch->name); 762 branch->name = xstrdup(buf.buf); 763 } 764 strbuf_splice(&buf, 0, 0, "refs/heads/", 11); 765 free(branch->path); 766 branch->path = strbuf_detach(&buf, NULL); 767} 768 769static void init_topts(struct unpack_trees_options *topts, int merge, 770 int show_progress, int overwrite_ignore, 771 struct commit *old_commit) 772{ 773 memset(topts, 0, sizeof(*topts)); 774 topts->head_idx = -1; 775 topts->src_index = the_repository->index; 776 topts->dst_index = the_repository->index; 777 778 setup_unpack_trees_porcelain(topts, "checkout"); 779 780 topts->initial_checkout = is_index_unborn(the_repository->index); 781 topts->update = 1; 782 topts->merge = 1; 783 topts->quiet = merge && old_commit; 784 topts->verbose_update = show_progress; 785 topts->fn = twoway_merge; 786 topts->preserve_ignored = !overwrite_ignore; 787} 788 789static int merge_working_tree(const struct checkout_opts *opts, 790 struct branch_info *old_branch_info, 791 struct branch_info *new_branch_info, 792 int *writeout_error) 793{ 794 int ret; 795 struct lock_file lock_file = LOCK_INIT; 796 struct tree *new_tree; 797 798 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR); 799 if (repo_read_index_preload(the_repository, NULL, 0) < 0) 800 return error(_("index file corrupt")); 801 802 resolve_undo_clear_index(the_repository->index); 803 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) { 804 if (new_branch_info->commit) 805 BUG("'switch --orphan' should never accept a commit as starting point"); 806 new_tree = parse_tree_indirect(the_hash_algo->empty_tree); 807 if (!new_tree) 808 BUG("unable to read empty tree"); 809 } else { 810 new_tree = repo_get_commit_tree(the_repository, 811 new_branch_info->commit); 812 if (!new_tree) 813 return error(_("unable to read tree (%s)"), 814 oid_to_hex(&new_branch_info->commit->object.oid)); 815 } 816 if (opts->discard_changes) { 817 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info); 818 if (ret) 819 return ret; 820 } else { 821 struct tree_desc trees[2]; 822 struct tree *tree; 823 struct unpack_trees_options topts; 824 const struct object_id *old_commit_oid; 825 826 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL); 827 828 if (unmerged_index(the_repository->index)) { 829 error(_("you need to resolve your current index first")); 830 return 1; 831 } 832 833 /* 2-way merge to the new branch */ 834 init_topts(&topts, opts->merge, opts->show_progress, 835 opts->overwrite_ignore, old_branch_info->commit); 836 init_checkout_metadata(&topts.meta, new_branch_info->refname, 837 new_branch_info->commit ? 838 &new_branch_info->commit->object.oid : 839 &new_branch_info->oid, NULL); 840 841 old_commit_oid = old_branch_info->commit ? 842 &old_branch_info->commit->object.oid : 843 the_hash_algo->empty_tree; 844 tree = parse_tree_indirect(old_commit_oid); 845 if (!tree) 846 die(_("unable to parse commit %s"), 847 oid_to_hex(old_commit_oid)); 848 849 init_tree_desc(&trees[0], &tree->object.oid, 850 tree->buffer, tree->size); 851 if (parse_tree(new_tree) < 0) 852 die(NULL); 853 tree = new_tree; 854 init_tree_desc(&trees[1], &tree->object.oid, 855 tree->buffer, tree->size); 856 857 ret = unpack_trees(2, trees, &topts); 858 clear_unpack_trees_porcelain(&topts); 859 if (ret == -1) { 860 /* 861 * Unpack couldn't do a trivial merge; either 862 * give up or do a real merge, depending on 863 * whether the merge flag was used. 864 */ 865 struct tree *work; 866 struct tree *old_tree; 867 struct merge_options o; 868 struct strbuf sb = STRBUF_INIT; 869 struct strbuf old_commit_shortname = STRBUF_INIT; 870 871 if (!opts->merge) 872 return 1; 873 874 /* 875 * Without old_branch_info->commit, the below is the same as 876 * the two-tree unpack we already tried and failed. 877 */ 878 if (!old_branch_info->commit) 879 return 1; 880 old_tree = repo_get_commit_tree(the_repository, 881 old_branch_info->commit); 882 883 if (repo_index_has_changes(the_repository, old_tree, &sb)) 884 die(_("cannot continue with staged changes in " 885 "the following files:\n%s"), sb.buf); 886 strbuf_release(&sb); 887 888 /* Do more real merge */ 889 890 /* 891 * We update the index fully, then write the 892 * tree from the index, then merge the new 893 * branch with the current tree, with the old 894 * branch as the base. Then we reset the index 895 * (but not the working tree) to the new 896 * branch, leaving the working tree as the 897 * merged version, but skipping unmerged 898 * entries in the index. 899 */ 900 901 add_files_to_cache(the_repository, NULL, NULL, NULL, 0, 902 0); 903 init_ui_merge_options(&o, the_repository); 904 o.verbosity = 0; 905 work = write_in_core_index_as_tree(the_repository); 906 907 ret = reset_tree(new_tree, 908 opts, 1, 909 writeout_error, new_branch_info); 910 if (ret) 911 return ret; 912 o.ancestor = old_branch_info->name; 913 if (!old_branch_info->name) { 914 strbuf_add_unique_abbrev(&old_commit_shortname, 915 &old_branch_info->commit->object.oid, 916 DEFAULT_ABBREV); 917 o.ancestor = old_commit_shortname.buf; 918 } 919 o.branch1 = new_branch_info->name; 920 o.branch2 = "local"; 921 o.conflict_style = opts->conflict_style; 922 ret = merge_ort_nonrecursive(&o, 923 new_tree, 924 work, 925 old_tree); 926 if (ret < 0) 927 die(NULL); 928 ret = reset_tree(new_tree, 929 opts, 0, 930 writeout_error, new_branch_info); 931 strbuf_release(&o.obuf); 932 strbuf_release(&old_commit_shortname); 933 if (ret) 934 return ret; 935 } 936 } 937 938 if (!cache_tree_fully_valid(the_repository->index->cache_tree)) 939 cache_tree_update(the_repository->index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR); 940 941 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK)) 942 die(_("unable to write new index file")); 943 944 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit) 945 show_local_changes(&new_branch_info->commit->object, &opts->diff_options); 946 947 return 0; 948} 949 950static void report_tracking(struct branch_info *new_branch_info) 951{ 952 struct strbuf sb = STRBUF_INIT; 953 struct branch *branch = branch_get(new_branch_info->name); 954 955 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL, 1)) 956 return; 957 fputs(sb.buf, stdout); 958 strbuf_release(&sb); 959} 960 961static void update_refs_for_switch(const struct checkout_opts *opts, 962 struct branch_info *old_branch_info, 963 struct branch_info *new_branch_info) 964{ 965 struct strbuf msg = STRBUF_INIT; 966 const char *old_desc, *reflog_msg; 967 if (opts->new_branch) { 968 if (opts->new_orphan_branch) { 969 enum log_refs_config log_all_ref_updates = 970 repo_settings_get_log_all_ref_updates(the_repository); 971 char *refname; 972 973 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch); 974 if (opts->new_branch_log && 975 !should_autocreate_reflog(log_all_ref_updates, refname)) { 976 int ret; 977 struct strbuf err = STRBUF_INIT; 978 979 ret = refs_create_reflog(get_main_ref_store(the_repository), 980 refname, &err); 981 if (ret) { 982 fprintf(stderr, _("Can not do reflog for '%s': %s\n"), 983 opts->new_orphan_branch, err.buf); 984 strbuf_release(&err); 985 free(refname); 986 return; 987 } 988 strbuf_release(&err); 989 } 990 free(refname); 991 } 992 else 993 create_branch(the_repository, 994 opts->new_branch, new_branch_info->name, 995 opts->new_branch_force ? 1 : 0, 996 opts->new_branch_force ? 1 : 0, 997 opts->new_branch_log, 998 opts->quiet, 999 opts->track, 1000 0); 1001 free(new_branch_info->name); 1002 free(new_branch_info->refname); 1003 new_branch_info->name = xstrdup(opts->new_branch); 1004 setup_branch_path(new_branch_info); 1005 } 1006 1007 old_desc = old_branch_info->name; 1008 if (!old_desc && old_branch_info->commit) 1009 old_desc = oid_to_hex(&old_branch_info->commit->object.oid); 1010 1011 reflog_msg = getenv("GIT_REFLOG_ACTION"); 1012 if (!reflog_msg) 1013 strbuf_addf(&msg, "checkout: moving from %s to %s", 1014 old_desc ? old_desc : "(invalid)", new_branch_info->name); 1015 else 1016 strbuf_insertstr(&msg, 0, reflog_msg); 1017 1018 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) { 1019 /* Nothing to do. */ 1020 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */ 1021 refs_update_ref(get_main_ref_store(the_repository), msg.buf, 1022 "HEAD", &new_branch_info->commit->object.oid, 1023 NULL, 1024 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR); 1025 if (!opts->quiet) { 1026 if (old_branch_info->path && 1027 advice_enabled(ADVICE_DETACHED_HEAD) && !opts->force_detach) 1028 detach_advice(new_branch_info->name); 1029 describe_detached_head(_("HEAD is now at"), new_branch_info->commit); 1030 } 1031 } else if (new_branch_info->path) { /* Switch branches. */ 1032 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", new_branch_info->path, msg.buf) < 0) 1033 die(_("unable to update HEAD")); 1034 if (!opts->quiet) { 1035 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) { 1036 if (opts->new_branch_force) 1037 fprintf(stderr, _("Reset branch '%s'\n"), 1038 new_branch_info->name); 1039 else 1040 fprintf(stderr, _("Already on '%s'\n"), 1041 new_branch_info->name); 1042 } else if (opts->new_branch) { 1043 if (opts->branch_exists) 1044 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name); 1045 else 1046 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name); 1047 } else { 1048 fprintf(stderr, _("Switched to branch '%s'\n"), 1049 new_branch_info->name); 1050 } 1051 } 1052 if (old_branch_info->path && old_branch_info->name) { 1053 if (!refs_ref_exists(get_main_ref_store(the_repository), old_branch_info->path) && refs_reflog_exists(get_main_ref_store(the_repository), old_branch_info->path)) 1054 refs_delete_reflog(get_main_ref_store(the_repository), 1055 old_branch_info->path); 1056 } 1057 } 1058 remove_branch_state(the_repository, !opts->quiet); 1059 strbuf_release(&msg); 1060 if (!opts->quiet && 1061 !opts->force_detach && 1062 (new_branch_info->path || !strcmp(new_branch_info->name, "HEAD"))) 1063 report_tracking(new_branch_info); 1064} 1065 1066static int add_pending_uninteresting_ref(const char *refname, const char *referent UNUSED, 1067 const struct object_id *oid, 1068 int flags UNUSED, void *cb_data) 1069{ 1070 add_pending_oid(cb_data, refname, oid, UNINTERESTING); 1071 return 0; 1072} 1073 1074static void describe_one_orphan(struct strbuf *sb, struct commit *commit) 1075{ 1076 strbuf_addstr(sb, " "); 1077 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV); 1078 strbuf_addch(sb, ' '); 1079 if (!repo_parse_commit(the_repository, commit)) 1080 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb); 1081 strbuf_addch(sb, '\n'); 1082} 1083 1084#define ORPHAN_CUTOFF 4 1085static void suggest_reattach(struct commit *commit, struct rev_info *revs) 1086{ 1087 struct commit *c, *last = NULL; 1088 struct strbuf sb = STRBUF_INIT; 1089 int lost = 0; 1090 while ((c = get_revision(revs)) != NULL) { 1091 if (lost < ORPHAN_CUTOFF) 1092 describe_one_orphan(&sb, c); 1093 last = c; 1094 lost++; 1095 } 1096 if (ORPHAN_CUTOFF < lost) { 1097 int more = lost - ORPHAN_CUTOFF; 1098 if (more == 1) 1099 describe_one_orphan(&sb, last); 1100 else 1101 strbuf_addf(&sb, _(" ... and %d more.\n"), more); 1102 } 1103 1104 fprintf(stderr, 1105 Q_( 1106 /* The singular version */ 1107 "Warning: you are leaving %d commit behind, " 1108 "not connected to\n" 1109 "any of your branches:\n\n" 1110 "%s\n", 1111 /* The plural version */ 1112 "Warning: you are leaving %d commits behind, " 1113 "not connected to\n" 1114 "any of your branches:\n\n" 1115 "%s\n", 1116 /* Give ngettext() the count */ 1117 lost), 1118 lost, 1119 sb.buf); 1120 strbuf_release(&sb); 1121 1122 if (advice_enabled(ADVICE_DETACHED_HEAD)) 1123 fprintf(stderr, 1124 Q_( 1125 /* The singular version */ 1126 "If you want to keep it by creating a new branch, " 1127 "this may be a good time\nto do so with:\n\n" 1128 " git branch <new-branch-name> %s\n\n", 1129 /* The plural version */ 1130 "If you want to keep them by creating a new branch, " 1131 "this may be a good time\nto do so with:\n\n" 1132 " git branch <new-branch-name> %s\n\n", 1133 /* Give ngettext() the count */ 1134 lost), 1135 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV)); 1136} 1137 1138/* 1139 * We are about to leave commit that was at the tip of a detached 1140 * HEAD. If it is not reachable from any ref, this is the last chance 1141 * for the user to do so without resorting to reflog. 1142 */ 1143static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit) 1144{ 1145 struct rev_info revs; 1146 struct object *object = &old_commit->object; 1147 1148 repo_init_revisions(the_repository, &revs, NULL); 1149 setup_revisions(0, NULL, &revs, NULL); 1150 1151 object->flags &= ~UNINTERESTING; 1152 add_pending_object(&revs, object, oid_to_hex(&object->oid)); 1153 1154 refs_for_each_ref(get_main_ref_store(the_repository), 1155 add_pending_uninteresting_ref, &revs); 1156 if (new_commit) 1157 add_pending_oid(&revs, "HEAD", 1158 &new_commit->object.oid, 1159 UNINTERESTING); 1160 1161 if (prepare_revision_walk(&revs)) 1162 die(_("internal error in revision walk")); 1163 if (!(old_commit->object.flags & UNINTERESTING)) 1164 suggest_reattach(old_commit, &revs); 1165 else 1166 describe_detached_head(_("Previous HEAD position was"), old_commit); 1167 1168 /* Clean up objects used, as they will be reused. */ 1169 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS); 1170 release_revisions(&revs); 1171} 1172 1173static int switch_branches(const struct checkout_opts *opts, 1174 struct branch_info *new_branch_info) 1175{ 1176 int ret = 0; 1177 struct branch_info old_branch_info = { 0 }; 1178 struct object_id rev; 1179 int flag, writeout_error = 0; 1180 int do_merge = 1; 1181 1182 trace2_cmd_mode("branch"); 1183 1184 memset(&old_branch_info, 0, sizeof(old_branch_info)); 1185 old_branch_info.path = refs_resolve_refdup(get_main_ref_store(the_repository), 1186 "HEAD", 0, &rev, &flag); 1187 if (old_branch_info.path) 1188 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1); 1189 if (!(flag & REF_ISSYMREF)) 1190 FREE_AND_NULL(old_branch_info.path); 1191 1192 if (old_branch_info.path) { 1193 const char *const prefix = "refs/heads/"; 1194 const char *p; 1195 if (skip_prefix(old_branch_info.path, prefix, &p)) 1196 old_branch_info.name = xstrdup(p); 1197 } 1198 1199 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) { 1200 if (new_branch_info->name) 1201 BUG("'switch --orphan' should never accept a commit as starting point"); 1202 new_branch_info->commit = NULL; 1203 new_branch_info->name = xstrdup("(empty)"); 1204 do_merge = 1; 1205 } 1206 1207 if (!new_branch_info->name) { 1208 new_branch_info->name = xstrdup("HEAD"); 1209 new_branch_info->commit = old_branch_info.commit; 1210 if (!new_branch_info->commit) 1211 die(_("You are on a branch yet to be born")); 1212 parse_commit_or_die(new_branch_info->commit); 1213 1214 if (opts->only_merge_on_switching_branches) 1215 do_merge = 0; 1216 } 1217 1218 if (do_merge) { 1219 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error); 1220 if (ret) { 1221 branch_info_release(&old_branch_info); 1222 return ret; 1223 } 1224 } 1225 1226 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit) 1227 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit); 1228 1229 update_refs_for_switch(opts, &old_branch_info, new_branch_info); 1230 1231 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1); 1232 branch_info_release(&old_branch_info); 1233 1234 return ret || writeout_error; 1235} 1236 1237static int git_checkout_config(const char *var, const char *value, 1238 const struct config_context *ctx, void *cb) 1239{ 1240 struct checkout_opts *opts = cb; 1241 1242 if (!strcmp(var, "diff.ignoresubmodules")) { 1243 if (!value) 1244 return config_error_nonbool(var); 1245 handle_ignore_submodules_arg(&opts->diff_options, value); 1246 return 0; 1247 } 1248 if (!strcmp(var, "checkout.guess")) { 1249 opts->dwim_new_local_branch = git_config_bool(var, value); 1250 return 0; 1251 } 1252 1253 if (starts_with(var, "submodule.")) 1254 return git_default_submodule_config(var, value, NULL); 1255 1256 return git_xmerge_config(var, value, ctx, NULL); 1257} 1258 1259static void setup_new_branch_info_and_source_tree( 1260 struct branch_info *new_branch_info, 1261 struct checkout_opts *opts, 1262 struct object_id *rev, 1263 const char *arg) 1264{ 1265 struct tree **source_tree = &opts->source_tree; 1266 struct object_id branch_rev; 1267 1268 /* treat '@' as a shortcut for 'HEAD' */ 1269 new_branch_info->name = !strcmp(arg, "@") ? xstrdup("HEAD") : 1270 xstrdup(arg); 1271 setup_branch_path(new_branch_info); 1272 1273 if (!check_refname_format(new_branch_info->path, 0) && 1274 !refs_read_ref(get_main_ref_store(the_repository), new_branch_info->path, &branch_rev)) 1275 oidcpy(rev, &branch_rev); 1276 else 1277 /* not an existing branch */ 1278 FREE_AND_NULL(new_branch_info->path); 1279 1280 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1); 1281 if (!new_branch_info->commit) { 1282 /* not a commit */ 1283 *source_tree = parse_tree_indirect(rev); 1284 if (!*source_tree) 1285 die(_("unable to read tree (%s)"), oid_to_hex(rev)); 1286 } else { 1287 parse_commit_or_die(new_branch_info->commit); 1288 *source_tree = repo_get_commit_tree(the_repository, 1289 new_branch_info->commit); 1290 if (!*source_tree) 1291 die(_("unable to read tree (%s)"), 1292 oid_to_hex(&new_branch_info->commit->object.oid)); 1293 } 1294} 1295 1296static char *parse_remote_branch(const char *arg, 1297 struct object_id *rev, 1298 int could_be_checkout_paths) 1299{ 1300 int num_matches = 0; 1301 char *remote = unique_tracking_name(arg, rev, &num_matches); 1302 1303 if (remote && could_be_checkout_paths) { 1304 die(_("'%s' could be both a local file and a tracking branch.\n" 1305 "Please use -- (and optionally --no-guess) to disambiguate"), 1306 arg); 1307 } 1308 1309 if (!remote && num_matches > 1) { 1310 if (advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME)) { 1311 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n" 1312 "you can do so by fully qualifying the name with the --track option:\n" 1313 "\n" 1314 " git checkout --track origin/<name>\n" 1315 "\n" 1316 "If you'd like to always have checkouts of an ambiguous <name> prefer\n" 1317 "one remote, e.g. the 'origin' remote, consider setting\n" 1318 "checkout.defaultRemote=origin in your config.")); 1319 } 1320 1321 die(_("'%s' matched multiple (%d) remote tracking branches"), 1322 arg, num_matches); 1323 } 1324 1325 return remote; 1326} 1327 1328static int parse_branchname_arg(int argc, const char **argv, 1329 int dwim_new_local_branch_ok, 1330 struct branch_info *new_branch_info, 1331 struct checkout_opts *opts, 1332 struct object_id *rev) 1333{ 1334 const char **new_branch = &opts->new_branch; 1335 int argcount = 0; 1336 const char *arg; 1337 char *remote = NULL; 1338 int dash_dash_pos; 1339 int has_dash_dash = 0; 1340 int i; 1341 1342 /* 1343 * case 1: git checkout <ref> -- [<paths>] 1344 * 1345 * <ref> must be a valid tree, everything after the '--' must be 1346 * a path. 1347 * 1348 * case 2: git checkout -- [<paths>] 1349 * 1350 * everything after the '--' must be paths. 1351 * 1352 * case 3: git checkout <something> [--] 1353 * 1354 * (a) If <something> is a commit, that is to 1355 * switch to the branch or detach HEAD at it. As a special case, 1356 * if <something> is A...B (missing A or B means HEAD but you can 1357 * omit at most one side), and if there is a unique merge base 1358 * between A and B, A...B names that merge base. 1359 * 1360 * (b) If <something> is _not_ a commit, either "--" is present 1361 * or <something> is not a path, no -t or -b was given, 1362 * and there is a tracking branch whose name is <something> 1363 * in one and only one remote (or if the branch exists on the 1364 * remote named in checkout.defaultRemote), then this is a 1365 * short-hand to fork local <something> from that 1366 * remote-tracking branch. 1367 * 1368 * (c) Otherwise, if "--" is present, treat it like case (1). 1369 * 1370 * (d) Otherwise : 1371 * - if it's a reference, treat it like case (1) 1372 * - else if it's a path, treat it like case (2) 1373 * - else: fail. 1374 * 1375 * case 4: git checkout <something> <paths> 1376 * 1377 * The first argument must not be ambiguous. 1378 * - If it's *only* a reference, treat it like case (1). 1379 * - If it's only a path, treat it like case (2). 1380 * - else: fail. 1381 * 1382 */ 1383 if (!argc) 1384 return 0; 1385 1386 if (!opts->accept_pathspec) { 1387 if (argc > 1) 1388 die(_("only one reference expected")); 1389 has_dash_dash = 1; /* helps disambiguate */ 1390 } 1391 1392 arg = argv[0]; 1393 dash_dash_pos = -1; 1394 for (i = 0; i < argc; i++) { 1395 if (opts->accept_pathspec && !strcmp(argv[i], "--")) { 1396 dash_dash_pos = i; 1397 break; 1398 } 1399 } 1400 if (dash_dash_pos == 0) 1401 return 1; /* case (2) */ 1402 else if (dash_dash_pos == 1) 1403 has_dash_dash = 1; /* case (3) or (1) */ 1404 else if (dash_dash_pos >= 2) 1405 die(_("only one reference expected, %d given."), dash_dash_pos); 1406 opts->count_checkout_paths = !opts->quiet && !has_dash_dash; 1407 1408 if (!strcmp(arg, "-")) 1409 arg = "@{-1}"; 1410 1411 if (repo_get_oid_mb(the_repository, arg, rev)) { 1412 /* 1413 * Either case (3) or (4), with <something> not being 1414 * a commit, or an attempt to use case (1) with an 1415 * invalid ref. 1416 * 1417 * It's likely an error, but we need to find out if 1418 * we should auto-create the branch, case (3).(b). 1419 */ 1420 int recover_with_dwim = dwim_new_local_branch_ok; 1421 1422 int could_be_checkout_paths = !has_dash_dash && 1423 check_filename(opts->prefix, arg); 1424 1425 if (!has_dash_dash && !no_wildcard(arg)) 1426 recover_with_dwim = 0; 1427 1428 /* 1429 * Accept "git checkout foo", "git checkout foo --" 1430 * and "git switch foo" as candidates for dwim. 1431 */ 1432 if (!(argc == 1 && !has_dash_dash) && 1433 !(argc == 2 && has_dash_dash) && 1434 opts->accept_pathspec) 1435 recover_with_dwim = 0; 1436 1437 if (recover_with_dwim) { 1438 remote = parse_remote_branch(arg, rev, 1439 could_be_checkout_paths); 1440 if (remote) { 1441 *new_branch = arg; 1442 arg = remote; 1443 /* DWIMmed to create local branch, case (3).(b) */ 1444 } else { 1445 recover_with_dwim = 0; 1446 } 1447 } 1448 1449 if (!recover_with_dwim) { 1450 if (has_dash_dash) 1451 die(_("invalid reference: %s"), arg); 1452 return argcount; 1453 } 1454 } 1455 1456 /* we can't end up being in (2) anymore, eat the argument */ 1457 argcount++; 1458 argv++; 1459 argc--; 1460 1461 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg); 1462 1463 if (!opts->source_tree) /* case (1): want a tree */ 1464 die(_("reference is not a tree: %s"), arg); 1465 1466 if (!has_dash_dash) { /* case (3).(d) -> (1) */ 1467 /* 1468 * Do not complain the most common case 1469 * git checkout branch 1470 * even if there happen to be a file called 'branch'; 1471 * it would be extremely annoying. 1472 */ 1473 if (argc) 1474 verify_non_filename(opts->prefix, arg); 1475 } else if (opts->accept_pathspec) { 1476 argcount++; 1477 argv++; 1478 argc--; 1479 } 1480 1481 free(remote); 1482 return argcount; 1483} 1484 1485static int switch_unborn_to_new_branch(const struct checkout_opts *opts) 1486{ 1487 int status; 1488 struct strbuf branch_ref = STRBUF_INIT; 1489 1490 trace2_cmd_mode("unborn"); 1491 1492 if (!opts->new_branch) 1493 die(_("You are on a branch yet to be born")); 1494 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch); 1495 status = refs_update_symref(get_main_ref_store(the_repository), 1496 "HEAD", branch_ref.buf, "checkout -b"); 1497 strbuf_release(&branch_ref); 1498 if (!opts->quiet) 1499 fprintf(stderr, _("Switched to a new branch '%s'\n"), 1500 opts->new_branch); 1501 return status; 1502} 1503 1504static void die_expecting_a_branch(const struct branch_info *branch_info) 1505{ 1506 struct object_id oid; 1507 char *to_free; 1508 int code; 1509 1510 if (repo_dwim_ref(the_repository, branch_info->name, 1511 strlen(branch_info->name), &oid, &to_free, 0) == 1) { 1512 const char *ref = to_free; 1513 1514 if (skip_prefix(ref, "refs/tags/", &ref)) 1515 code = die_message(_("a branch is expected, got tag '%s'"), ref); 1516 else if (skip_prefix(ref, "refs/remotes/", &ref)) 1517 code = die_message(_("a branch is expected, got remote branch '%s'"), ref); 1518 else 1519 code = die_message(_("a branch is expected, got '%s'"), ref); 1520 } 1521 else if (branch_info->commit) 1522 code = die_message(_("a branch is expected, got commit '%s'"), branch_info->name); 1523 else 1524 /* 1525 * This case should never happen because we already die() on 1526 * non-commit, but just in case. 1527 */ 1528 code = die_message(_("a branch is expected, got '%s'"), branch_info->name); 1529 1530 if (advice_enabled(ADVICE_SUGGEST_DETACHING_HEAD)) 1531 advise(_("If you want to detach HEAD at the commit, try again with the --detach option.")); 1532 1533 exit(code); 1534} 1535 1536static void die_if_some_operation_in_progress(void) 1537{ 1538 struct wt_status_state state; 1539 1540 memset(&state, 0, sizeof(state)); 1541 wt_status_get_state(the_repository, &state, 0); 1542 1543 if (state.merge_in_progress) 1544 die(_("cannot switch branch while merging\n" 1545 "Consider \"git merge --quit\" " 1546 "or \"git worktree add\".")); 1547 if (state.am_in_progress) 1548 die(_("cannot switch branch in the middle of an am session\n" 1549 "Consider \"git am --quit\" " 1550 "or \"git worktree add\".")); 1551 if (state.rebase_interactive_in_progress || state.rebase_in_progress) 1552 die(_("cannot switch branch while rebasing\n" 1553 "Consider \"git rebase --quit\" " 1554 "or \"git worktree add\".")); 1555 if (state.cherry_pick_in_progress) 1556 die(_("cannot switch branch while cherry-picking\n" 1557 "Consider \"git cherry-pick --quit\" " 1558 "or \"git worktree add\".")); 1559 if (state.revert_in_progress) 1560 die(_("cannot switch branch while reverting\n" 1561 "Consider \"git revert --quit\" " 1562 "or \"git worktree add\".")); 1563 if (state.bisect_in_progress) 1564 warning(_("you are switching branch while bisecting")); 1565 1566 wt_status_state_free_buffers(&state); 1567} 1568 1569/* 1570 * die if attempting to checkout an existing branch that is in use 1571 * in another worktree, unless ignore-other-wortrees option is given. 1572 * The check is bypassed when the branch is already the current one, 1573 * as it will not make things any worse. 1574 */ 1575static void die_if_switching_to_a_branch_in_use(struct checkout_opts *opts, 1576 const char *full_ref) 1577{ 1578 int flags; 1579 char *head_ref; 1580 1581 if (opts->ignore_other_worktrees) 1582 return; 1583 head_ref = refs_resolve_refdup(get_main_ref_store(the_repository), 1584 "HEAD", 0, NULL, &flags); 1585 if (head_ref && (!(flags & REF_ISSYMREF) || strcmp(head_ref, full_ref))) 1586 die_if_checked_out(full_ref, 1); 1587 free(head_ref); 1588} 1589 1590static int checkout_branch(struct checkout_opts *opts, 1591 struct branch_info *new_branch_info) 1592{ 1593 int noop_switch = (!new_branch_info->name && 1594 !opts->new_branch && 1595 !opts->force_detach); 1596 1597 if (opts->pathspec.nr) 1598 die(_("paths cannot be used with switching branches")); 1599 1600 if (opts->patch_mode) 1601 die(_("'%s' cannot be used with switching branches"), 1602 "--patch"); 1603 1604 if (opts->overlay_mode != -1) 1605 die(_("'%s' cannot be used with switching branches"), 1606 "--[no]-overlay"); 1607 1608 if (opts->writeout_stage) { 1609 const char *msg; 1610 if (noop_switch) 1611 msg = _("'%s' needs the paths to check out"); 1612 else 1613 msg = _("'%s' cannot be used with switching branches"); 1614 die(msg, "--ours/--theirs"); 1615 } 1616 1617 if (opts->force && opts->merge) 1618 die(_("'%s' cannot be used with '%s'"), "-f", "-m"); 1619 1620 if (opts->discard_changes && opts->merge) 1621 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge"); 1622 1623 if (opts->force_detach && opts->new_branch) 1624 die(_("'%s' cannot be used with '%s'"), 1625 "--detach", "-b/-B/--orphan"); 1626 1627 if (opts->new_orphan_branch) { 1628 if (opts->track != BRANCH_TRACK_UNSPECIFIED) 1629 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t"); 1630 if (opts->orphan_from_empty_tree && new_branch_info->name) 1631 die(_("'%s' cannot take <start-point>"), "--orphan"); 1632 } else if (opts->force_detach) { 1633 if (opts->track != BRANCH_TRACK_UNSPECIFIED) 1634 die(_("'%s' cannot be used with '%s'"), "--detach", "-t"); 1635 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED) 1636 opts->track = git_branch_track; 1637 1638 if (new_branch_info->name && !new_branch_info->commit) 1639 die(_("Cannot switch branch to a non-commit '%s'"), 1640 new_branch_info->name); 1641 1642 if (noop_switch && 1643 !opts->switch_branch_doing_nothing_is_ok) 1644 die(_("missing branch or commit argument")); 1645 1646 if (!opts->implicit_detach && 1647 !opts->force_detach && 1648 !opts->new_branch && 1649 !opts->new_branch_force && 1650 new_branch_info->name && 1651 !new_branch_info->path) 1652 die_expecting_a_branch(new_branch_info); 1653 1654 if (!opts->can_switch_when_in_progress) 1655 die_if_some_operation_in_progress(); 1656 1657 /* "git checkout <branch>" */ 1658 if (new_branch_info->path && !opts->force_detach && !opts->new_branch) 1659 die_if_switching_to_a_branch_in_use(opts, new_branch_info->path); 1660 1661 /* "git checkout -B <branch>" */ 1662 if (opts->new_branch_force) { 1663 char *full_ref = xstrfmt("refs/heads/%s", opts->new_branch); 1664 die_if_switching_to_a_branch_in_use(opts, full_ref); 1665 free(full_ref); 1666 } 1667 1668 if (!new_branch_info->commit && opts->new_branch) { 1669 struct object_id rev; 1670 int flag; 1671 1672 if (!refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &rev, &flag) && 1673 (flag & REF_ISSYMREF) && is_null_oid(&rev)) 1674 return switch_unborn_to_new_branch(opts); 1675 } 1676 return switch_branches(opts, new_branch_info); 1677} 1678 1679static int parse_opt_conflict(const struct option *o, const char *arg, int unset) 1680{ 1681 struct checkout_opts *opts = o->value; 1682 1683 if (unset) { 1684 opts->conflict_style = -1; 1685 return 0; 1686 } 1687 opts->conflict_style = parse_conflict_style_name(arg); 1688 if (opts->conflict_style < 0) 1689 return error(_("unknown conflict style '%s'"), arg); 1690 /* --conflict overrides a previous --no-merge */ 1691 if (!opts->merge) 1692 opts->merge = -1; 1693 1694 return 0; 1695} 1696 1697static struct option *add_common_options(struct checkout_opts *opts, 1698 struct option *prevopts) 1699{ 1700 struct option options[] = { 1701 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")), 1702 OPT_CALLBACK_F(0, "recurse-submodules", NULL, 1703 "checkout", "control recursive updating of submodules", 1704 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater), 1705 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")), 1706 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")), 1707 OPT_CALLBACK(0, "conflict", opts, N_("style"), 1708 N_("conflict style (merge, diff3, or zdiff3)"), 1709 parse_opt_conflict), 1710 OPT_END() 1711 }; 1712 struct option *newopts = parse_options_concat(prevopts, options); 1713 free(prevopts); 1714 return newopts; 1715} 1716 1717static struct option *add_common_switch_branch_options( 1718 struct checkout_opts *opts, struct option *prevopts) 1719{ 1720 struct option options[] = { 1721 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")), 1722 OPT_CALLBACK_F('t', "track", &opts->track, "(direct|inherit)", 1723 N_("set branch tracking configuration"), 1724 PARSE_OPT_OPTARG, 1725 parse_opt_tracking_mode), 1726 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"), 1727 PARSE_OPT_NOCOMPLETE), 1728 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")), 1729 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore, 1730 N_("update ignored files (default)"), 1731 PARSE_OPT_NOCOMPLETE), 1732 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees, 1733 N_("do not check if another worktree is using this branch")), 1734 OPT_END() 1735 }; 1736 struct option *newopts = parse_options_concat(prevopts, options); 1737 free(prevopts); 1738 return newopts; 1739} 1740 1741static struct option *add_checkout_path_options(struct checkout_opts *opts, 1742 struct option *prevopts) 1743{ 1744 struct option options[] = { 1745 OPT_SET_INT_F('2', "ours", &opts->writeout_stage, 1746 N_("checkout our version for unmerged files"), 1747 2, PARSE_OPT_NONEG), 1748 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage, 1749 N_("checkout their version for unmerged files"), 1750 3, PARSE_OPT_NONEG), 1751 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")), 1752 OPT_DIFF_UNIFIED(&opts->patch_context), 1753 OPT_DIFF_INTERHUNK_CONTEXT(&opts->patch_interhunk_context), 1754 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree, 1755 N_("do not limit pathspecs to sparse entries only")), 1756 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file), 1757 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul), 1758 OPT_END() 1759 }; 1760 struct option *newopts = parse_options_concat(prevopts, options); 1761 free(prevopts); 1762 return newopts; 1763} 1764 1765/* create-branch option (either b or c) */ 1766static char cb_option = 'b'; 1767 1768static int checkout_main(int argc, const char **argv, const char *prefix, 1769 struct checkout_opts *opts, struct option *options, 1770 const char * const usagestr[]) 1771{ 1772 int parseopt_flags = 0; 1773 struct branch_info new_branch_info = { 0 }; 1774 int ret; 1775 1776 opts->overwrite_ignore = 1; 1777 opts->prefix = prefix; 1778 opts->show_progress = -1; 1779 1780 repo_config(the_repository, git_checkout_config, opts); 1781 if (the_repository->gitdir) { 1782 prepare_repo_settings(the_repository); 1783 the_repository->settings.command_requires_full_index = 0; 1784 } 1785 1786 opts->track = BRANCH_TRACK_UNSPECIFIED; 1787 1788 if (!opts->accept_pathspec && !opts->accept_ref) 1789 BUG("make up your mind, you need to take _something_"); 1790 if (opts->accept_pathspec && opts->accept_ref) 1791 parseopt_flags = PARSE_OPT_KEEP_DASHDASH; 1792 1793 argc = parse_options(argc, argv, prefix, options, 1794 usagestr, parseopt_flags); 1795 1796 if (opts->patch_context < -1) 1797 die(_("'%s' cannot be negative"), "--unified"); 1798 if (opts->patch_interhunk_context < -1) 1799 die(_("'%s' cannot be negative"), "--inter-hunk-context"); 1800 1801 if (!opts->patch_mode) { 1802 if (opts->patch_context != -1) 1803 die(_("the option '%s' requires '%s'"), "--unified", "--patch"); 1804 if (opts->patch_interhunk_context != -1) 1805 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--patch"); 1806 } 1807 1808 if (opts->show_progress < 0) { 1809 if (opts->quiet) 1810 opts->show_progress = 0; 1811 else 1812 opts->show_progress = isatty(2); 1813 } 1814 1815 /* --conflicts implies --merge */ 1816 if (opts->merge == -1) 1817 opts->merge = opts->conflict_style >= 0; 1818 1819 if (opts->force) { 1820 opts->discard_changes = 1; 1821 opts->ignore_unmerged_opt = "--force"; 1822 opts->ignore_unmerged = 1; 1823 } 1824 1825 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1) 1826 die(_("options '-%c', '-%c', and '%s' cannot be used together"), 1827 cb_option, toupper(cb_option), "--orphan"); 1828 1829 if (opts->overlay_mode == 1 && opts->patch_mode) 1830 die(_("options '%s' and '%s' cannot be used together"), "-p", "--overlay"); 1831 1832 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) { 1833 if (opts->checkout_index < 0) 1834 opts->checkout_index = 0; 1835 if (opts->checkout_worktree < 0) 1836 opts->checkout_worktree = 0; 1837 } else { 1838 if (opts->checkout_index < 0) 1839 opts->checkout_index = -opts->checkout_index - 1; 1840 if (opts->checkout_worktree < 0) 1841 opts->checkout_worktree = -opts->checkout_worktree - 1; 1842 } 1843 if (opts->checkout_index < 0 || opts->checkout_worktree < 0) 1844 BUG("these flags should be non-negative by now"); 1845 /* 1846 * convenient shortcut: "git restore --staged [--worktree]" equals 1847 * "git restore --staged [--worktree] --source HEAD" 1848 */ 1849 if (!opts->from_treeish && opts->checkout_index) 1850 opts->from_treeish = "HEAD"; 1851 1852 /* 1853 * From here on, new_branch will contain the branch to be checked out, 1854 * and new_branch_force and new_orphan_branch will tell us which one of 1855 * -b/-B/-c/-C/--orphan is being used. 1856 */ 1857 if (opts->new_branch_force) 1858 opts->new_branch = opts->new_branch_force; 1859 1860 if (opts->new_orphan_branch) 1861 opts->new_branch = opts->new_orphan_branch; 1862 1863 /* --track without -c/-C/-b/-B/--orphan should DWIM */ 1864 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) { 1865 const char *argv0 = argv[0]; 1866 if (!argc || !strcmp(argv0, "--")) 1867 die(_("--track needs a branch name")); 1868 skip_prefix(argv0, "refs/", &argv0); 1869 skip_prefix(argv0, "remotes/", &argv0); 1870 argv0 = strchr(argv0, '/'); 1871 if (!argv0 || !argv0[1]) 1872 die(_("missing branch name; try -%c"), cb_option); 1873 opts->new_branch = argv0 + 1; 1874 } 1875 1876 /* 1877 * Extract branch name from command line arguments, so 1878 * all that is left is pathspecs. 1879 * 1880 * Handle 1881 * 1882 * 1) git checkout <tree> -- [<paths>] 1883 * 2) git checkout -- [<paths>] 1884 * 3) git checkout <something> [<paths>] 1885 * 1886 * including "last branch" syntax and DWIM-ery for names of 1887 * remote branches, erroring out for invalid or ambiguous cases. 1888 */ 1889 if (argc && opts->accept_ref) { 1890 struct object_id rev; 1891 int dwim_ok = 1892 !opts->patch_mode && 1893 opts->dwim_new_local_branch && 1894 opts->track == BRANCH_TRACK_UNSPECIFIED && 1895 !opts->new_branch; 1896 int n = parse_branchname_arg(argc, argv, dwim_ok, 1897 &new_branch_info, opts, &rev); 1898 argv += n; 1899 argc -= n; 1900 } else if (!opts->accept_ref && opts->from_treeish) { 1901 struct object_id rev; 1902 1903 if (repo_get_oid_mb(the_repository, opts->from_treeish, &rev)) 1904 die(_("could not resolve %s"), opts->from_treeish); 1905 1906 setup_new_branch_info_and_source_tree(&new_branch_info, 1907 opts, &rev, 1908 opts->from_treeish); 1909 1910 if (!opts->source_tree) 1911 die(_("reference is not a tree: %s"), opts->from_treeish); 1912 } 1913 1914 if (argc) { 1915 parse_pathspec(&opts->pathspec, 0, 1916 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0, 1917 prefix, argv); 1918 1919 if (!opts->pathspec.nr) 1920 die(_("invalid path specification")); 1921 1922 /* 1923 * Try to give more helpful suggestion. 1924 * new_branch && argc > 1 will be caught later. 1925 */ 1926 if (opts->new_branch && argc == 1 && !new_branch_info.commit) 1927 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"), 1928 argv[0], opts->new_branch); 1929 1930 if (opts->force_detach) 1931 die(_("git checkout: --detach does not take a path argument '%s'"), 1932 argv[0]); 1933 } 1934 1935 if (opts->pathspec_from_file) { 1936 if (opts->pathspec.nr) 1937 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file"); 1938 1939 if (opts->force_detach) 1940 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--detach"); 1941 1942 if (opts->patch_mode) 1943 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch"); 1944 1945 parse_pathspec_file(&opts->pathspec, 0, 1946 0, 1947 prefix, opts->pathspec_from_file, opts->pathspec_file_nul); 1948 } else if (opts->pathspec_file_nul) { 1949 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file"); 1950 } 1951 1952 opts->pathspec.recursive = 1; 1953 1954 if (opts->pathspec.nr) { 1955 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge) 1956 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n" 1957 "checking out of the index.")); 1958 } else { 1959 if (opts->accept_pathspec && !opts->empty_pathspec_ok && 1960 !opts->patch_mode) /* patch mode is special */ 1961 die(_("you must specify path(s) to restore")); 1962 } 1963 1964 if (opts->new_branch) { 1965 struct strbuf buf = STRBUF_INIT; 1966 1967 if (opts->new_branch_force) 1968 opts->branch_exists = validate_branchname(opts->new_branch, &buf); 1969 else 1970 opts->branch_exists = 1971 validate_new_branchname(opts->new_branch, &buf, 0); 1972 strbuf_release(&buf); 1973 } 1974 1975 if (opts->patch_mode || opts->pathspec.nr) 1976 ret = checkout_paths(opts, &new_branch_info); 1977 else 1978 ret = checkout_branch(opts, &new_branch_info); 1979 1980 branch_info_release(&new_branch_info); 1981 clear_pathspec(&opts->pathspec); 1982 free(opts->pathspec_from_file); 1983 free(options); 1984 1985 return ret; 1986} 1987 1988int cmd_checkout(int argc, 1989 const char **argv, 1990 const char *prefix, 1991 struct repository *repo UNUSED) 1992{ 1993 struct checkout_opts opts = CHECKOUT_OPTS_INIT; 1994 struct option *options; 1995 struct option checkout_options[] = { 1996 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"), 1997 N_("create and checkout a new branch")), 1998 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"), 1999 N_("create/reset and checkout a branch")), 2000 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")), 2001 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch, 2002 N_("second guess 'git checkout <no-such-branch>' (default)")), 2003 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")), 2004 OPT_END() 2005 }; 2006 2007 opts.dwim_new_local_branch = 1; 2008 opts.switch_branch_doing_nothing_is_ok = 1; 2009 opts.only_merge_on_switching_branches = 0; 2010 opts.accept_ref = 1; 2011 opts.accept_pathspec = 1; 2012 opts.implicit_detach = 1; 2013 opts.can_switch_when_in_progress = 1; 2014 opts.orphan_from_empty_tree = 0; 2015 opts.empty_pathspec_ok = 1; 2016 opts.overlay_mode = -1; 2017 opts.checkout_index = -2; /* default on */ 2018 opts.checkout_worktree = -2; /* default on */ 2019 2020 if (argc == 3 && !strcmp(argv[1], "-b")) { 2021 /* 2022 * User ran 'git checkout -b <branch>' and expects 2023 * the same behavior as 'git switch -c <branch>'. 2024 */ 2025 opts.switch_branch_doing_nothing_is_ok = 0; 2026 opts.only_merge_on_switching_branches = 1; 2027 } 2028 2029 options = parse_options_dup(checkout_options); 2030 options = add_common_options(&opts, options); 2031 options = add_common_switch_branch_options(&opts, options); 2032 options = add_checkout_path_options(&opts, options); 2033 2034 return checkout_main(argc, argv, prefix, &opts, options, 2035 checkout_usage); 2036} 2037 2038int cmd_switch(int argc, 2039 const char **argv, 2040 const char *prefix, 2041 struct repository *repo UNUSED) 2042{ 2043 struct checkout_opts opts = CHECKOUT_OPTS_INIT; 2044 struct option *options = NULL; 2045 struct option switch_options[] = { 2046 OPT_STRING('c', "create", &opts.new_branch, N_("branch"), 2047 N_("create and switch to a new branch")), 2048 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"), 2049 N_("create/reset and switch to a branch")), 2050 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch, 2051 N_("second guess 'git switch <no-such-branch>'")), 2052 OPT_BOOL(0, "discard-changes", &opts.discard_changes, 2053 N_("throw away local modifications")), 2054 OPT_END() 2055 }; 2056 2057 opts.dwim_new_local_branch = 1; 2058 opts.accept_ref = 1; 2059 opts.accept_pathspec = 0; 2060 opts.switch_branch_doing_nothing_is_ok = 0; 2061 opts.only_merge_on_switching_branches = 1; 2062 opts.implicit_detach = 0; 2063 opts.can_switch_when_in_progress = 0; 2064 opts.orphan_from_empty_tree = 1; 2065 opts.overlay_mode = -1; 2066 2067 options = parse_options_dup(switch_options); 2068 options = add_common_options(&opts, options); 2069 options = add_common_switch_branch_options(&opts, options); 2070 2071 cb_option = 'c'; 2072 2073 return checkout_main(argc, argv, prefix, &opts, options, 2074 switch_branch_usage); 2075} 2076 2077int cmd_restore(int argc, 2078 const char **argv, 2079 const char *prefix, 2080 struct repository *repo UNUSED) 2081{ 2082 struct checkout_opts opts = CHECKOUT_OPTS_INIT; 2083 struct option *options; 2084 struct option restore_options[] = { 2085 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>", 2086 N_("which tree-ish to checkout from")), 2087 OPT_BOOL('S', "staged", &opts.checkout_index, 2088 N_("restore the index")), 2089 OPT_BOOL('W', "worktree", &opts.checkout_worktree, 2090 N_("restore the working tree (default)")), 2091 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged, 2092 N_("ignore unmerged entries")), 2093 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")), 2094 OPT_END() 2095 }; 2096 2097 opts.accept_ref = 0; 2098 opts.accept_pathspec = 1; 2099 opts.empty_pathspec_ok = 0; 2100 opts.overlay_mode = 0; 2101 opts.checkout_index = -1; /* default off */ 2102 opts.checkout_worktree = -2; /* default on */ 2103 opts.ignore_unmerged_opt = "--ignore-unmerged"; 2104 2105 options = parse_options_dup(restore_options); 2106 options = add_common_options(&opts, options); 2107 options = add_checkout_path_options(&opts, options); 2108 2109 return checkout_main(argc, argv, prefix, &opts, options, 2110 restore_usage); 2111}