1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
6 #include "cache-tree.h"
15 #include "merge-recursive.h"
16 #include "object-store.h"
17 #include "parse-options.h"
20 #include "resolve-undo.h"
22 #include "run-command.h"
23 #include "submodule.h"
24 #include "submodule-config.h"
26 #include "tree-walk.h"
27 #include "unpack-trees.h"
28 #include "wt-status.h"
29 #include "xdiff-interface.h"
31 #include "parallel-checkout.h"
33 static const char * const checkout_usage[] = {
34 N_("git checkout [<options>] <branch>"),
35 N_("git checkout [<options>] [<branch>] -- <file>..."),
39 static const char * const switch_branch_usage[] = {
40 N_("git switch [<options>] [<branch>]"),
44 static const char * const restore_usage[] = {
45 N_("git restore [<options>] [--source=<branch>] <file>..."),
49 struct checkout_opts {
58 int ignore_skipworktree;
59 int ignore_other_worktrees;
61 int count_checkout_paths;
63 int dwim_new_local_branch;
67 int switch_branch_doing_nothing_is_ok;
68 int only_merge_on_switching_branches;
69 int can_switch_when_in_progress;
70 int orphan_from_empty_tree;
71 int empty_pathspec_ok;
73 int checkout_worktree;
74 const char *ignore_unmerged_opt;
76 int pathspec_file_nul;
77 const char *pathspec_from_file;
79 const char *new_branch;
80 const char *new_branch_force;
81 const char *new_orphan_branch;
83 enum branch_track track;
84 struct diff_options diff_options;
89 struct pathspec pathspec;
90 const char *from_treeish;
91 struct tree *source_tree;
95 const char *name; /* The short name used */
96 const char *path; /* The full name of a real branch */
97 struct commit *commit; /* The named commit */
98 char *refname; /* The full name of the ref being checked out. */
99 struct object_id oid; /* The object ID of the commit being checked out. */
101 * if not null the branch is detached because it's already
102 * checked out in this checkout
107 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
110 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
113 /* "new_commit" can be NULL when checking out from the index before
115 strvec_pushl(&opt.args,
116 oid_to_hex(old_commit ? &old_commit->object.oid : null_oid()),
117 oid_to_hex(new_commit ? &new_commit->object.oid : null_oid()),
120 rc = run_hooks("post-checkout", &opt);
121 run_hooks_opt_clear(&opt);
125 static int update_some(const struct object_id *oid, struct strbuf *base,
126 const char *pathname, unsigned mode, void *context)
129 struct cache_entry *ce;
133 return READ_TREE_RECURSIVE;
135 len = base->len + strlen(pathname);
136 ce = make_empty_cache_entry(&the_index, len);
137 oidcpy(&ce->oid, oid);
138 memcpy(ce->name, base->buf, base->len);
139 memcpy(ce->name + base->len, pathname, len - base->len);
140 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
141 ce->ce_namelen = len;
142 ce->ce_mode = create_ce_mode(mode);
145 * If the entry is the same as the current index, we can leave the old
146 * entry in place. Whether it is UPTODATE or not, checkout_entry will
147 * do the right thing.
149 pos = cache_name_pos(ce->name, ce->ce_namelen);
151 struct cache_entry *old = active_cache[pos];
152 if (ce->ce_mode == old->ce_mode &&
153 !ce_intent_to_add(old) &&
154 oideq(&ce->oid, &old->oid)) {
155 old->ce_flags |= CE_UPDATE;
156 discard_cache_entry(ce);
161 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
165 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
167 read_tree(the_repository, tree,
168 pathspec, update_some, NULL);
170 /* update the index with the given tree's info
171 * for all args, expanding wildcards, and exit
172 * with any non-zero return code.
177 static int skip_same_name(const struct cache_entry *ce, int pos)
179 while (++pos < active_nr &&
180 !strcmp(active_cache[pos]->name, ce->name))
185 static int check_stage(int stage, const struct cache_entry *ce, int pos,
188 while (pos < active_nr &&
189 !strcmp(active_cache[pos]->name, ce->name)) {
190 if (ce_stage(active_cache[pos]) == stage)
197 return error(_("path '%s' does not have our version"), ce->name);
199 return error(_("path '%s' does not have their version"), ce->name);
202 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
205 const char *name = ce->name;
207 while (pos < active_nr) {
208 ce = active_cache[pos];
209 if (strcmp(name, ce->name))
211 seen |= (1 << ce_stage(ce));
214 if ((stages & seen) != stages)
215 return error(_("path '%s' does not have all necessary versions"),
220 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
221 const struct checkout *state, int *nr_checkouts,
224 while (pos < active_nr &&
225 !strcmp(active_cache[pos]->name, ce->name)) {
226 if (ce_stage(active_cache[pos]) == stage)
227 return checkout_entry(active_cache[pos], state,
236 return error(_("path '%s' does not have our version"), ce->name);
238 return error(_("path '%s' does not have their version"), ce->name);
241 static int checkout_merged(int pos, const struct checkout *state,
242 int *nr_checkouts, struct mem_pool *ce_mem_pool)
244 struct cache_entry *ce = active_cache[pos];
245 const char *path = ce->name;
246 mmfile_t ancestor, ours, theirs;
248 struct object_id oid;
249 mmbuffer_t result_buf;
250 struct object_id threeway[3];
252 struct ll_merge_options ll_opts;
255 memset(threeway, 0, sizeof(threeway));
256 while (pos < active_nr) {
258 stage = ce_stage(ce);
259 if (!stage || strcmp(path, ce->name))
261 oidcpy(&threeway[stage - 1], &ce->oid);
263 mode = create_ce_mode(ce->ce_mode);
265 ce = active_cache[pos];
267 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
268 return error(_("path '%s' does not have necessary versions"), path);
270 read_mmblob(&ancestor, &threeway[0]);
271 read_mmblob(&ours, &threeway[1]);
272 read_mmblob(&theirs, &threeway[2]);
274 memset(&ll_opts, 0, sizeof(ll_opts));
275 git_config_get_bool("merge.renormalize", &renormalize);
276 ll_opts.renormalize = renormalize;
277 status = ll_merge(&result_buf, path, &ancestor, "base",
278 &ours, "ours", &theirs, "theirs",
279 state->istate, &ll_opts);
283 if (status < 0 || !result_buf.ptr) {
284 free(result_buf.ptr);
285 return error(_("path '%s': cannot merge"), path);
290 * There is absolutely no reason to write this as a blob object
291 * and create a phony cache entry. This hack is primarily to get
292 * to the write_entry() machinery that massages the contents to
293 * work-tree format and writes out which only allows it for a
294 * cache entry. The code in write_entry() needs to be refactored
295 * to allow us to feed a <buffer, size, mode> instead of a cache
296 * entry. Such a refactoring would help merge_recursive as well
297 * (it also writes the merge result to the object database even
298 * when it may contain conflicts).
300 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
301 die(_("Unable to add merge result for '%s'"), path);
302 free(result_buf.ptr);
303 ce = make_transient_cache_entry(mode, &oid, path, 2, ce_mem_pool);
305 die(_("make_cache_entry failed for path '%s'"), path);
306 status = checkout_entry(ce, state, NULL, nr_checkouts);
310 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
312 const struct checkout_opts *opts)
314 ce->ce_flags &= ~CE_MATCHED;
315 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
317 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
319 * "git checkout tree-ish -- path", but this entry
320 * is in the original index but is not in tree-ish
321 * or does not match the pathspec; it will not be
322 * checked out to the working tree. We will not do
323 * anything to this entry at all.
327 * Either this entry came from the tree-ish we are
328 * checking the paths out of, or we are checking out
331 * If it comes from the tree-ish, we already know it
332 * matches the pathspec and could just stamp
333 * CE_MATCHED to it from update_some(). But we still
334 * need ps_matched and read_tree (and
335 * eventually tree_entry_interesting) cannot fill
336 * ps_matched yet. Once it can, we can avoid calling
337 * match_pathspec() for _all_ entries when
338 * opts->source_tree != NULL.
340 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
341 ce->ce_flags |= CE_MATCHED;
344 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
346 const struct checkout_opts *opts)
348 ce->ce_flags &= ~CE_MATCHED;
349 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
351 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
352 ce->ce_flags |= CE_MATCHED;
353 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
355 * In overlay mode, but the path is not in
356 * tree-ish, which means we should remove it
357 * from the index and the working tree.
359 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
363 static int checkout_worktree(const struct checkout_opts *opts,
364 const struct branch_info *info)
366 struct checkout state = CHECKOUT_INIT;
367 int nr_checkouts = 0, nr_unmerged = 0;
370 int pc_workers, pc_threshold;
371 struct mem_pool ce_mem_pool;
374 state.refresh_cache = 1;
375 state.istate = &the_index;
377 mem_pool_init(&ce_mem_pool, 0);
378 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
379 init_checkout_metadata(&state.meta, info->refname,
380 info->commit ? &info->commit->object.oid : &info->oid,
383 enable_delayed_checkout(&state);
386 init_parallel_checkout();
388 /* TODO: audit for interaction with sparse-index. */
389 ensure_full_index(&the_index);
391 for (pos = 0; pos < active_nr; pos++) {
392 struct cache_entry *ce = active_cache[pos];
393 if (ce->ce_flags & CE_MATCHED) {
395 errs |= checkout_entry(ce, &state,
396 NULL, &nr_checkouts);
399 if (opts->writeout_stage)
400 errs |= checkout_stage(opts->writeout_stage,
403 &nr_checkouts, opts->overlay_mode);
404 else if (opts->merge)
405 errs |= checkout_merged(pos, &state,
408 pos = skip_same_name(ce, pos) - 1;
412 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
414 mem_pool_discard(&ce_mem_pool, should_validate_cache_entries());
415 remove_marked_cache_entries(&the_index, 1);
416 remove_scheduled_dirs();
417 errs |= finish_delayed_checkout(&state, &nr_checkouts);
419 if (opts->count_checkout_paths) {
421 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
422 "Recreated %d merge conflicts",
425 if (opts->source_tree)
426 fprintf_ln(stderr, Q_("Updated %d path from %s",
427 "Updated %d paths from %s",
430 find_unique_abbrev(&opts->source_tree->object.oid,
432 else if (!nr_unmerged || nr_checkouts)
433 fprintf_ln(stderr, Q_("Updated %d path from the index",
434 "Updated %d paths from the index",
442 static int checkout_paths(const struct checkout_opts *opts,
443 const struct branch_info *new_branch_info)
446 static char *ps_matched;
447 struct object_id rev;
450 struct lock_file lock_file = LOCK_INIT;
453 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
455 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
456 die(_("'%s' cannot be used with updating paths"), "--track");
458 if (opts->new_branch_log)
459 die(_("'%s' cannot be used with updating paths"), "-l");
461 if (opts->ignore_unmerged && opts->patch_mode)
462 die(_("'%s' cannot be used with updating paths"),
463 opts->ignore_unmerged_opt);
465 if (opts->force_detach)
466 die(_("'%s' cannot be used with updating paths"), "--detach");
468 if (opts->merge && opts->patch_mode)
469 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
471 if (opts->ignore_unmerged && opts->merge)
472 die(_("'%s' cannot be used with %s"),
473 opts->ignore_unmerged_opt, "-m");
475 if (opts->new_branch)
476 die(_("Cannot update paths and switch to branch '%s' at the same time."),
479 if (!opts->checkout_worktree && !opts->checkout_index)
480 die(_("neither '%s' or '%s' is specified"),
481 "--staged", "--worktree");
483 if (!opts->checkout_worktree && !opts->from_treeish)
484 die(_("'%s' must be used when '%s' is not specified"),
485 "--worktree", "--source");
487 if (opts->checkout_index && !opts->checkout_worktree &&
488 opts->writeout_stage)
489 die(_("'%s' or '%s' cannot be used with %s"),
490 "--ours", "--theirs", "--staged");
492 if (opts->checkout_index && !opts->checkout_worktree &&
494 die(_("'%s' or '%s' cannot be used with %s"),
495 "--merge", "--conflict", "--staged");
497 if (opts->patch_mode) {
498 const char *patch_mode;
499 const char *rev = new_branch_info->name;
500 char rev_oid[GIT_MAX_HEXSZ + 1];
503 * Since rev can be in the form of `<a>...<b>` (which is not
504 * recognized by diff-index), we will always replace the name
505 * with the hex of the commit (whether it's in `...` form or
506 * not) for the run_add_interactive() machinery to work
507 * properly. However, there is special logic for the HEAD case
508 * so we mustn't replace that. Also, when we were given a
509 * tree-object, new_branch_info->commit would be NULL, but we
510 * do not have to do any replacement, either.
512 if (rev && new_branch_info->commit && strcmp(rev, "HEAD"))
513 rev = oid_to_hex_r(rev_oid, &new_branch_info->commit->object.oid);
515 if (opts->checkout_index && opts->checkout_worktree)
516 patch_mode = "--patch=checkout";
517 else if (opts->checkout_index && !opts->checkout_worktree)
518 patch_mode = "--patch=reset";
519 else if (!opts->checkout_index && opts->checkout_worktree)
520 patch_mode = "--patch=worktree";
522 BUG("either flag must have been set, worktree=%d, index=%d",
523 opts->checkout_worktree, opts->checkout_index);
524 return run_add_interactive(rev, patch_mode, &opts->pathspec);
527 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
528 if (read_cache_preload(&opts->pathspec) < 0)
529 return error(_("index file corrupt"));
531 if (opts->source_tree)
532 read_tree_some(opts->source_tree, &opts->pathspec);
534 ps_matched = xcalloc(opts->pathspec.nr, 1);
537 * Make sure all pathspecs participated in locating the paths
540 /* TODO: audit for interaction with sparse-index. */
541 ensure_full_index(&the_index);
542 for (pos = 0; pos < active_nr; pos++)
543 if (opts->overlay_mode)
544 mark_ce_for_checkout_overlay(active_cache[pos],
548 mark_ce_for_checkout_no_overlay(active_cache[pos],
552 if (report_path_error(ps_matched, &opts->pathspec)) {
558 /* "checkout -m path" to recreate conflicted state */
560 unmerge_marked_index(&the_index);
562 /* Any unmerged paths? */
563 for (pos = 0; pos < active_nr; pos++) {
564 const struct cache_entry *ce = active_cache[pos];
565 if (ce->ce_flags & CE_MATCHED) {
568 if (opts->ignore_unmerged) {
570 warning(_("path '%s' is unmerged"), ce->name);
571 } else if (opts->writeout_stage) {
572 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
573 } else if (opts->merge) {
574 errs |= check_stages((1<<2) | (1<<3), ce, pos);
577 error(_("path '%s' is unmerged"), ce->name);
579 pos = skip_same_name(ce, pos) - 1;
585 /* Now we are committed to check them out */
586 if (opts->checkout_worktree)
587 errs |= checkout_worktree(opts, new_branch_info);
589 remove_marked_cache_entries(&the_index, 1);
592 * Allow updating the index when checking out from the index.
593 * This is to save new stat info.
595 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
598 checkout_index = opts->checkout_index;
600 if (checkout_index) {
601 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
602 die(_("unable to write new index file"));
605 * NEEDSWORK: if --worktree is not specified, we
606 * should save stat info of checked out files in the
607 * index to avoid the next (potentially costly)
608 * refresh. But it's a bit tricker to do...
610 rollback_lock_file(&lock_file);
613 read_ref_full("HEAD", 0, &rev, NULL);
614 head = lookup_commit_reference_gently(the_repository, &rev, 1);
616 errs |= post_checkout_hook(head, head, 0);
620 static void show_local_changes(struct object *head,
621 const struct diff_options *opts)
624 /* I think we want full paths, even if we're in a subdirectory. */
625 repo_init_revisions(the_repository, &rev, NULL);
626 rev.diffopt.flags = opts->flags;
627 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
628 diff_setup_done(&rev.diffopt);
629 add_pending_object(&rev, head, NULL);
630 run_diff_index(&rev, 0);
631 object_array_clear(&rev.pending);
634 static void describe_detached_head(const char *msg, struct commit *commit)
636 struct strbuf sb = STRBUF_INIT;
638 if (!parse_commit(commit))
639 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
640 if (print_sha1_ellipsis()) {
641 fprintf(stderr, "%s %s... %s\n", msg,
642 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
644 fprintf(stderr, "%s %s %s\n", msg,
645 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
650 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
651 int worktree, int *writeout_error,
652 struct branch_info *info)
654 struct unpack_trees_options opts;
655 struct tree_desc tree_desc;
657 memset(&opts, 0, sizeof(opts));
659 opts.update = worktree;
660 opts.skip_unmerged = !worktree;
663 opts.fn = oneway_merge;
664 opts.verbose_update = o->show_progress;
665 opts.src_index = &the_index;
666 opts.dst_index = &the_index;
667 init_checkout_metadata(&opts.meta, info->refname,
668 info->commit ? &info->commit->object.oid : null_oid(),
671 init_tree_desc(&tree_desc, tree->buffer, tree->size);
672 switch (unpack_trees(1, &tree_desc, &opts)) {
676 * We return 0 nevertheless, as the index is all right
677 * and more importantly we have made best efforts to
678 * update paths in the work tree, and we cannot revert
689 static void setup_branch_path(struct branch_info *branch)
691 struct strbuf buf = STRBUF_INIT;
694 * If this is a ref, resolve it; otherwise, look up the OID for our
695 * expression. Failure here is okay.
697 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname, 0))
698 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
700 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
701 if (strcmp(buf.buf, branch->name))
702 branch->name = xstrdup(buf.buf);
703 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
704 branch->path = strbuf_detach(&buf, NULL);
707 static int merge_working_tree(const struct checkout_opts *opts,
708 struct branch_info *old_branch_info,
709 struct branch_info *new_branch_info,
713 struct lock_file lock_file = LOCK_INIT;
714 struct tree *new_tree;
716 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
717 if (read_cache_preload(NULL) < 0)
718 return error(_("index file corrupt"));
720 resolve_undo_clear();
721 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
722 if (new_branch_info->commit)
723 BUG("'switch --orphan' should never accept a commit as starting point");
724 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
726 new_tree = get_commit_tree(new_branch_info->commit);
727 if (opts->discard_changes) {
728 ret = reset_tree(new_tree, opts, 1, writeout_error, new_branch_info);
732 struct tree_desc trees[2];
734 struct unpack_trees_options topts;
736 memset(&topts, 0, sizeof(topts));
738 topts.src_index = &the_index;
739 topts.dst_index = &the_index;
741 setup_unpack_trees_porcelain(&topts, "checkout");
743 refresh_cache(REFRESH_QUIET);
745 if (unmerged_cache()) {
746 error(_("you need to resolve your current index first"));
750 /* 2-way merge to the new branch */
751 topts.initial_checkout = is_cache_unborn();
754 topts.quiet = opts->merge && old_branch_info->commit;
755 topts.verbose_update = opts->show_progress;
756 topts.fn = twoway_merge;
757 init_checkout_metadata(&topts.meta, new_branch_info->refname,
758 new_branch_info->commit ?
759 &new_branch_info->commit->object.oid :
760 &new_branch_info->oid, NULL);
761 if (opts->overwrite_ignore) {
762 topts.dir = xcalloc(1, sizeof(*topts.dir));
763 topts.dir->flags |= DIR_SHOW_IGNORED;
764 setup_standard_excludes(topts.dir);
766 tree = parse_tree_indirect(old_branch_info->commit ?
767 &old_branch_info->commit->object.oid :
768 the_hash_algo->empty_tree);
769 init_tree_desc(&trees[0], tree->buffer, tree->size);
770 parse_tree(new_tree);
772 init_tree_desc(&trees[1], tree->buffer, tree->size);
774 ret = unpack_trees(2, trees, &topts);
775 clear_unpack_trees_porcelain(&topts);
778 * Unpack couldn't do a trivial merge; either
779 * give up or do a real merge, depending on
780 * whether the merge flag was used.
783 struct tree *old_tree;
784 struct merge_options o;
785 struct strbuf sb = STRBUF_INIT;
786 struct strbuf old_commit_shortname = STRBUF_INIT;
792 * Without old_branch_info->commit, the below is the same as
793 * the two-tree unpack we already tried and failed.
795 if (!old_branch_info->commit)
797 old_tree = get_commit_tree(old_branch_info->commit);
799 if (repo_index_has_changes(the_repository, old_tree, &sb))
800 die(_("cannot continue with staged changes in "
801 "the following files:\n%s"), sb.buf);
804 /* Do more real merge */
807 * We update the index fully, then write the
808 * tree from the index, then merge the new
809 * branch with the current tree, with the old
810 * branch as the base. Then we reset the index
811 * (but not the working tree) to the new
812 * branch, leaving the working tree as the
813 * merged version, but skipping unmerged
814 * entries in the index.
817 add_files_to_cache(NULL, NULL, 0);
818 init_merge_options(&o, the_repository);
820 work = write_in_core_index_as_tree(the_repository);
822 ret = reset_tree(new_tree,
824 writeout_error, new_branch_info);
827 o.ancestor = old_branch_info->name;
828 if (old_branch_info->name == NULL) {
829 strbuf_add_unique_abbrev(&old_commit_shortname,
830 &old_branch_info->commit->object.oid,
832 o.ancestor = old_commit_shortname.buf;
834 o.branch1 = new_branch_info->name;
836 ret = merge_trees(&o,
842 ret = reset_tree(new_tree,
844 writeout_error, new_branch_info);
845 strbuf_release(&o.obuf);
846 strbuf_release(&old_commit_shortname);
852 if (!cache_tree_fully_valid(active_cache_tree))
853 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
855 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
856 die(_("unable to write new index file"));
858 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
859 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
864 static void report_tracking(struct branch_info *new_branch_info)
866 struct strbuf sb = STRBUF_INIT;
867 struct branch *branch = branch_get(new_branch_info->name);
869 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
871 fputs(sb.buf, stdout);
875 static void update_refs_for_switch(const struct checkout_opts *opts,
876 struct branch_info *old_branch_info,
877 struct branch_info *new_branch_info)
879 struct strbuf msg = STRBUF_INIT;
880 const char *old_desc, *reflog_msg;
881 if (opts->new_branch) {
882 if (opts->new_orphan_branch) {
885 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
886 if (opts->new_branch_log &&
887 !should_autocreate_reflog(refname)) {
889 struct strbuf err = STRBUF_INIT;
891 ret = safe_create_reflog(refname, 1, &err);
893 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
894 opts->new_orphan_branch, err.buf);
895 strbuf_release(&err);
899 strbuf_release(&err);
904 create_branch(the_repository,
905 opts->new_branch, new_branch_info->name,
906 opts->new_branch_force ? 1 : 0,
907 opts->new_branch_force ? 1 : 0,
908 opts->new_branch_log,
911 new_branch_info->name = opts->new_branch;
912 setup_branch_path(new_branch_info);
915 old_desc = old_branch_info->name;
916 if (!old_desc && old_branch_info->commit)
917 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
919 reflog_msg = getenv("GIT_REFLOG_ACTION");
921 strbuf_addf(&msg, "checkout: moving from %s to %s",
922 old_desc ? old_desc : "(invalid)", new_branch_info->name);
924 strbuf_insertstr(&msg, 0, reflog_msg);
926 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
928 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
929 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
930 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
932 if (old_branch_info->path &&
933 advice_detached_head && !opts->force_detach)
934 detach_advice(new_branch_info->name);
935 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
937 } else if (new_branch_info->path) { /* Switch branches. */
938 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
939 die(_("unable to update HEAD"));
941 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
942 if (opts->new_branch_force)
943 fprintf(stderr, _("Reset branch '%s'\n"),
944 new_branch_info->name);
946 fprintf(stderr, _("Already on '%s'\n"),
947 new_branch_info->name);
948 } else if (opts->new_branch) {
949 if (opts->branch_exists)
950 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
952 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
954 fprintf(stderr, _("Switched to branch '%s'\n"),
955 new_branch_info->name);
958 if (old_branch_info->path && old_branch_info->name) {
959 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
960 delete_reflog(old_branch_info->path);
963 remove_branch_state(the_repository, !opts->quiet);
964 strbuf_release(&msg);
966 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
967 report_tracking(new_branch_info);
970 static int add_pending_uninteresting_ref(const char *refname,
971 const struct object_id *oid,
972 int flags, void *cb_data)
974 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
978 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
980 strbuf_addstr(sb, " ");
981 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
982 strbuf_addch(sb, ' ');
983 if (!parse_commit(commit))
984 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
985 strbuf_addch(sb, '\n');
988 #define ORPHAN_CUTOFF 4
989 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
991 struct commit *c, *last = NULL;
992 struct strbuf sb = STRBUF_INIT;
994 while ((c = get_revision(revs)) != NULL) {
995 if (lost < ORPHAN_CUTOFF)
996 describe_one_orphan(&sb, c);
1000 if (ORPHAN_CUTOFF < lost) {
1001 int more = lost - ORPHAN_CUTOFF;
1003 describe_one_orphan(&sb, last);
1005 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
1010 /* The singular version */
1011 "Warning: you are leaving %d commit behind, "
1012 "not connected to\n"
1013 "any of your branches:\n\n"
1015 /* The plural version */
1016 "Warning: you are leaving %d commits behind, "
1017 "not connected to\n"
1018 "any of your branches:\n\n"
1020 /* Give ngettext() the count */
1024 strbuf_release(&sb);
1026 if (advice_detached_head)
1029 /* The singular version */
1030 "If you want to keep it by creating a new branch, "
1031 "this may be a good time\nto do so with:\n\n"
1032 " git branch <new-branch-name> %s\n\n",
1033 /* The plural version */
1034 "If you want to keep them by creating a new branch, "
1035 "this may be a good time\nto do so with:\n\n"
1036 " git branch <new-branch-name> %s\n\n",
1037 /* Give ngettext() the count */
1039 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1043 * We are about to leave commit that was at the tip of a detached
1044 * HEAD. If it is not reachable from any ref, this is the last chance
1045 * for the user to do so without resorting to reflog.
1047 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1049 struct rev_info revs;
1050 struct object *object = &old_commit->object;
1052 repo_init_revisions(the_repository, &revs, NULL);
1053 setup_revisions(0, NULL, &revs, NULL);
1055 object->flags &= ~UNINTERESTING;
1056 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1058 for_each_ref(add_pending_uninteresting_ref, &revs);
1060 add_pending_oid(&revs, "HEAD",
1061 &new_commit->object.oid,
1064 if (prepare_revision_walk(&revs))
1065 die(_("internal error in revision walk"));
1066 if (!(old_commit->object.flags & UNINTERESTING))
1067 suggest_reattach(old_commit, &revs);
1069 describe_detached_head(_("Previous HEAD position was"), old_commit);
1071 /* Clean up objects used, as they will be reused. */
1072 repo_clear_commit_marks(the_repository, ALL_REV_FLAGS);
1075 static int switch_branches(const struct checkout_opts *opts,
1076 struct branch_info *new_branch_info)
1079 struct branch_info old_branch_info;
1081 struct object_id rev;
1082 int flag, writeout_error = 0;
1085 trace2_cmd_mode("branch");
1087 memset(&old_branch_info, 0, sizeof(old_branch_info));
1088 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
1089 if (old_branch_info.path)
1090 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1091 if (!(flag & REF_ISSYMREF))
1092 old_branch_info.path = NULL;
1094 if (old_branch_info.path)
1095 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
1097 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1098 if (new_branch_info->name)
1099 BUG("'switch --orphan' should never accept a commit as starting point");
1100 new_branch_info->commit = NULL;
1101 new_branch_info->name = "(empty)";
1105 if (!new_branch_info->name) {
1106 new_branch_info->name = "HEAD";
1107 new_branch_info->commit = old_branch_info.commit;
1108 if (!new_branch_info->commit)
1109 die(_("You are on a branch yet to be born"));
1110 parse_commit_or_die(new_branch_info->commit);
1112 if (opts->only_merge_on_switching_branches)
1117 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1124 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1125 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1127 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1129 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1131 return ret || writeout_error;
1134 static int git_checkout_config(const char *var, const char *value, void *cb)
1136 struct checkout_opts *opts = cb;
1138 if (!strcmp(var, "diff.ignoresubmodules")) {
1139 handle_ignore_submodules_arg(&opts->diff_options, value);
1142 if (!strcmp(var, "checkout.guess")) {
1143 opts->dwim_new_local_branch = git_config_bool(var, value);
1147 if (starts_with(var, "submodule."))
1148 return git_default_submodule_config(var, value, NULL);
1150 return git_xmerge_config(var, value, NULL);
1153 static void setup_new_branch_info_and_source_tree(
1154 struct branch_info *new_branch_info,
1155 struct checkout_opts *opts,
1156 struct object_id *rev,
1159 struct tree **source_tree = &opts->source_tree;
1160 struct object_id branch_rev;
1162 new_branch_info->name = arg;
1163 setup_branch_path(new_branch_info);
1165 if (!check_refname_format(new_branch_info->path, 0) &&
1166 !read_ref(new_branch_info->path, &branch_rev))
1167 oidcpy(rev, &branch_rev);
1169 free((char *)new_branch_info->path);
1170 new_branch_info->path = NULL; /* not an existing branch */
1173 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1174 if (!new_branch_info->commit) {
1176 *source_tree = parse_tree_indirect(rev);
1178 parse_commit_or_die(new_branch_info->commit);
1179 *source_tree = get_commit_tree(new_branch_info->commit);
1183 static const char *parse_remote_branch(const char *arg,
1184 struct object_id *rev,
1185 int could_be_checkout_paths)
1187 int num_matches = 0;
1188 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1190 if (remote && could_be_checkout_paths) {
1191 die(_("'%s' could be both a local file and a tracking branch.\n"
1192 "Please use -- (and optionally --no-guess) to disambiguate"),
1196 if (!remote && num_matches > 1) {
1197 if (advice_checkout_ambiguous_remote_branch_name) {
1198 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1199 "you can do so by fully qualifying the name with the --track option:\n"
1201 " git checkout --track origin/<name>\n"
1203 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1204 "one remote, e.g. the 'origin' remote, consider setting\n"
1205 "checkout.defaultRemote=origin in your config."));
1208 die(_("'%s' matched multiple (%d) remote tracking branches"),
1215 static int parse_branchname_arg(int argc, const char **argv,
1216 int dwim_new_local_branch_ok,
1217 struct branch_info *new_branch_info,
1218 struct checkout_opts *opts,
1219 struct object_id *rev)
1221 const char **new_branch = &opts->new_branch;
1225 int has_dash_dash = 0;
1229 * case 1: git checkout <ref> -- [<paths>]
1231 * <ref> must be a valid tree, everything after the '--' must be
1234 * case 2: git checkout -- [<paths>]
1236 * everything after the '--' must be paths.
1238 * case 3: git checkout <something> [--]
1240 * (a) If <something> is a commit, that is to
1241 * switch to the branch or detach HEAD at it. As a special case,
1242 * if <something> is A...B (missing A or B means HEAD but you can
1243 * omit at most one side), and if there is a unique merge base
1244 * between A and B, A...B names that merge base.
1246 * (b) If <something> is _not_ a commit, either "--" is present
1247 * or <something> is not a path, no -t or -b was given, and
1248 * and there is a tracking branch whose name is <something>
1249 * in one and only one remote (or if the branch exists on the
1250 * remote named in checkout.defaultRemote), then this is a
1251 * short-hand to fork local <something> from that
1252 * remote-tracking branch.
1254 * (c) Otherwise, if "--" is present, treat it like case (1).
1257 * - if it's a reference, treat it like case (1)
1258 * - else if it's a path, treat it like case (2)
1261 * case 4: git checkout <something> <paths>
1263 * The first argument must not be ambiguous.
1264 * - If it's *only* a reference, treat it like case (1).
1265 * - If it's only a path, treat it like case (2).
1272 if (!opts->accept_pathspec) {
1274 die(_("only one reference expected"));
1275 has_dash_dash = 1; /* helps disambiguate */
1280 for (i = 0; i < argc; i++) {
1281 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1286 if (dash_dash_pos == 0)
1287 return 1; /* case (2) */
1288 else if (dash_dash_pos == 1)
1289 has_dash_dash = 1; /* case (3) or (1) */
1290 else if (dash_dash_pos >= 2)
1291 die(_("only one reference expected, %d given."), dash_dash_pos);
1292 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1294 if (!strcmp(arg, "-"))
1297 if (get_oid_mb(arg, rev)) {
1299 * Either case (3) or (4), with <something> not being
1300 * a commit, or an attempt to use case (1) with an
1303 * It's likely an error, but we need to find out if
1304 * we should auto-create the branch, case (3).(b).
1306 int recover_with_dwim = dwim_new_local_branch_ok;
1308 int could_be_checkout_paths = !has_dash_dash &&
1309 check_filename(opts->prefix, arg);
1311 if (!has_dash_dash && !no_wildcard(arg))
1312 recover_with_dwim = 0;
1315 * Accept "git checkout foo", "git checkout foo --"
1316 * and "git switch foo" as candidates for dwim.
1318 if (!(argc == 1 && !has_dash_dash) &&
1319 !(argc == 2 && has_dash_dash) &&
1320 opts->accept_pathspec)
1321 recover_with_dwim = 0;
1323 if (recover_with_dwim) {
1324 const char *remote = parse_remote_branch(arg, rev,
1325 could_be_checkout_paths);
1329 /* DWIMmed to create local branch, case (3).(b) */
1331 recover_with_dwim = 0;
1335 if (!recover_with_dwim) {
1337 die(_("invalid reference: %s"), arg);
1342 /* we can't end up being in (2) anymore, eat the argument */
1347 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1349 if (!opts->source_tree) /* case (1): want a tree */
1350 die(_("reference is not a tree: %s"), arg);
1352 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1354 * Do not complain the most common case
1355 * git checkout branch
1356 * even if there happen to be a file called 'branch';
1357 * it would be extremely annoying.
1360 verify_non_filename(opts->prefix, arg);
1361 } else if (opts->accept_pathspec) {
1370 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1373 struct strbuf branch_ref = STRBUF_INIT;
1375 trace2_cmd_mode("unborn");
1377 if (!opts->new_branch)
1378 die(_("You are on a branch yet to be born"));
1379 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1380 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1381 strbuf_release(&branch_ref);
1383 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1388 static void die_expecting_a_branch(const struct branch_info *branch_info)
1390 struct object_id oid;
1393 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free, 0) == 1) {
1394 const char *ref = to_free;
1396 if (skip_prefix(ref, "refs/tags/", &ref))
1397 die(_("a branch is expected, got tag '%s'"), ref);
1398 if (skip_prefix(ref, "refs/remotes/", &ref))
1399 die(_("a branch is expected, got remote branch '%s'"), ref);
1400 die(_("a branch is expected, got '%s'"), ref);
1402 if (branch_info->commit)
1403 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1405 * This case should never happen because we already die() on
1406 * non-commit, but just in case.
1408 die(_("a branch is expected, got '%s'"), branch_info->name);
1411 static void die_if_some_operation_in_progress(void)
1413 struct wt_status_state state;
1415 memset(&state, 0, sizeof(state));
1416 wt_status_get_state(the_repository, &state, 0);
1418 if (state.merge_in_progress)
1419 die(_("cannot switch branch while merging\n"
1420 "Consider \"git merge --quit\" "
1421 "or \"git worktree add\"."));
1422 if (state.am_in_progress)
1423 die(_("cannot switch branch in the middle of an am session\n"
1424 "Consider \"git am --quit\" "
1425 "or \"git worktree add\"."));
1426 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1427 die(_("cannot switch branch while rebasing\n"
1428 "Consider \"git rebase --quit\" "
1429 "or \"git worktree add\"."));
1430 if (state.cherry_pick_in_progress)
1431 die(_("cannot switch branch while cherry-picking\n"
1432 "Consider \"git cherry-pick --quit\" "
1433 "or \"git worktree add\"."));
1434 if (state.revert_in_progress)
1435 die(_("cannot switch branch while reverting\n"
1436 "Consider \"git revert --quit\" "
1437 "or \"git worktree add\"."));
1438 if (state.bisect_in_progress)
1439 warning(_("you are switching branch while bisecting"));
1442 static int checkout_branch(struct checkout_opts *opts,
1443 struct branch_info *new_branch_info)
1445 if (opts->pathspec.nr)
1446 die(_("paths cannot be used with switching branches"));
1448 if (opts->patch_mode)
1449 die(_("'%s' cannot be used with switching branches"),
1452 if (opts->overlay_mode != -1)
1453 die(_("'%s' cannot be used with switching branches"),
1456 if (opts->writeout_stage)
1457 die(_("'%s' cannot be used with switching branches"),
1460 if (opts->force && opts->merge)
1461 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1463 if (opts->discard_changes && opts->merge)
1464 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1466 if (opts->force_detach && opts->new_branch)
1467 die(_("'%s' cannot be used with '%s'"),
1468 "--detach", "-b/-B/--orphan");
1470 if (opts->new_orphan_branch) {
1471 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1472 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1473 if (opts->orphan_from_empty_tree && new_branch_info->name)
1474 die(_("'%s' cannot take <start-point>"), "--orphan");
1475 } else if (opts->force_detach) {
1476 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1477 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1478 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1479 opts->track = git_branch_track;
1481 if (new_branch_info->name && !new_branch_info->commit)
1482 die(_("Cannot switch branch to a non-commit '%s'"),
1483 new_branch_info->name);
1485 if (!opts->switch_branch_doing_nothing_is_ok &&
1486 !new_branch_info->name &&
1487 !opts->new_branch &&
1488 !opts->force_detach)
1489 die(_("missing branch or commit argument"));
1491 if (!opts->implicit_detach &&
1492 !opts->force_detach &&
1493 !opts->new_branch &&
1494 !opts->new_branch_force &&
1495 new_branch_info->name &&
1496 !new_branch_info->path)
1497 die_expecting_a_branch(new_branch_info);
1499 if (!opts->can_switch_when_in_progress)
1500 die_if_some_operation_in_progress();
1502 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1503 !opts->ignore_other_worktrees) {
1505 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1507 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1508 die_if_checked_out(new_branch_info->path, 1);
1512 if (!new_branch_info->commit && opts->new_branch) {
1513 struct object_id rev;
1516 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1517 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1518 return switch_unborn_to_new_branch(opts);
1520 return switch_branches(opts, new_branch_info);
1523 static struct option *add_common_options(struct checkout_opts *opts,
1524 struct option *prevopts)
1526 struct option options[] = {
1527 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1528 OPT_CALLBACK_F(0, "recurse-submodules", NULL,
1529 "checkout", "control recursive updating of submodules",
1530 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater),
1531 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1532 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1533 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1534 N_("conflict style (merge, diff3, or zdiff3)")),
1537 struct option *newopts = parse_options_concat(prevopts, options);
1542 static struct option *add_common_switch_branch_options(
1543 struct checkout_opts *opts, struct option *prevopts)
1545 struct option options[] = {
1546 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1547 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1548 BRANCH_TRACK_EXPLICIT),
1549 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1550 PARSE_OPT_NOCOMPLETE),
1551 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1552 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1553 N_("update ignored files (default)"),
1554 PARSE_OPT_NOCOMPLETE),
1555 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1556 N_("do not check if another worktree is holding the given ref")),
1559 struct option *newopts = parse_options_concat(prevopts, options);
1564 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1565 struct option *prevopts)
1567 struct option options[] = {
1568 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1569 N_("checkout our version for unmerged files"),
1570 2, PARSE_OPT_NONEG),
1571 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1572 N_("checkout their version for unmerged files"),
1573 3, PARSE_OPT_NONEG),
1574 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1575 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1576 N_("do not limit pathspecs to sparse entries only")),
1577 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1578 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1581 struct option *newopts = parse_options_concat(prevopts, options);
1586 /* create-branch option (either b or c) */
1587 static char cb_option = 'b';
1589 static int checkout_main(int argc, const char **argv, const char *prefix,
1590 struct checkout_opts *opts, struct option *options,
1591 const char * const usagestr[])
1593 struct branch_info new_branch_info;
1594 int parseopt_flags = 0;
1596 memset(&new_branch_info, 0, sizeof(new_branch_info));
1597 opts->overwrite_ignore = 1;
1598 opts->prefix = prefix;
1599 opts->show_progress = -1;
1601 git_config(git_checkout_config, opts);
1603 opts->track = BRANCH_TRACK_UNSPECIFIED;
1605 if (!opts->accept_pathspec && !opts->accept_ref)
1606 BUG("make up your mind, you need to take _something_");
1607 if (opts->accept_pathspec && opts->accept_ref)
1608 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1610 argc = parse_options(argc, argv, prefix, options,
1611 usagestr, parseopt_flags);
1613 if (opts->show_progress < 0) {
1615 opts->show_progress = 0;
1617 opts->show_progress = isatty(2);
1620 if (opts->conflict_style) {
1621 opts->merge = 1; /* implied */
1622 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1625 opts->discard_changes = 1;
1626 opts->ignore_unmerged_opt = "--force";
1627 opts->ignore_unmerged = 1;
1630 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1631 die(_("-%c, -%c and --orphan are mutually exclusive"),
1632 cb_option, toupper(cb_option));
1634 if (opts->overlay_mode == 1 && opts->patch_mode)
1635 die(_("-p and --overlay are mutually exclusive"));
1637 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1638 if (opts->checkout_index < 0)
1639 opts->checkout_index = 0;
1640 if (opts->checkout_worktree < 0)
1641 opts->checkout_worktree = 0;
1643 if (opts->checkout_index < 0)
1644 opts->checkout_index = -opts->checkout_index - 1;
1645 if (opts->checkout_worktree < 0)
1646 opts->checkout_worktree = -opts->checkout_worktree - 1;
1648 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1649 BUG("these flags should be non-negative by now");
1651 * convenient shortcut: "git restore --staged [--worktree]" equals
1652 * "git restore --staged [--worktree] --source HEAD"
1654 if (!opts->from_treeish && opts->checkout_index)
1655 opts->from_treeish = "HEAD";
1658 * From here on, new_branch will contain the branch to be checked out,
1659 * and new_branch_force and new_orphan_branch will tell us which one of
1660 * -b/-B/-c/-C/--orphan is being used.
1662 if (opts->new_branch_force)
1663 opts->new_branch = opts->new_branch_force;
1665 if (opts->new_orphan_branch)
1666 opts->new_branch = opts->new_orphan_branch;
1668 /* --track without -c/-C/-b/-B/--orphan should DWIM */
1669 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1670 const char *argv0 = argv[0];
1671 if (!argc || !strcmp(argv0, "--"))
1672 die(_("--track needs a branch name"));
1673 skip_prefix(argv0, "refs/", &argv0);
1674 skip_prefix(argv0, "remotes/", &argv0);
1675 argv0 = strchr(argv0, '/');
1676 if (!argv0 || !argv0[1])
1677 die(_("missing branch name; try -%c"), cb_option);
1678 opts->new_branch = argv0 + 1;
1682 * Extract branch name from command line arguments, so
1683 * all that is left is pathspecs.
1687 * 1) git checkout <tree> -- [<paths>]
1688 * 2) git checkout -- [<paths>]
1689 * 3) git checkout <something> [<paths>]
1691 * including "last branch" syntax and DWIM-ery for names of
1692 * remote branches, erroring out for invalid or ambiguous cases.
1694 if (argc && opts->accept_ref) {
1695 struct object_id rev;
1697 !opts->patch_mode &&
1698 opts->dwim_new_local_branch &&
1699 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1701 int n = parse_branchname_arg(argc, argv, dwim_ok,
1702 &new_branch_info, opts, &rev);
1705 } else if (!opts->accept_ref && opts->from_treeish) {
1706 struct object_id rev;
1708 if (get_oid_mb(opts->from_treeish, &rev))
1709 die(_("could not resolve %s"), opts->from_treeish);
1711 setup_new_branch_info_and_source_tree(&new_branch_info,
1713 opts->from_treeish);
1715 if (!opts->source_tree)
1716 die(_("reference is not a tree: %s"), opts->from_treeish);
1720 parse_pathspec(&opts->pathspec, 0,
1721 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1724 if (!opts->pathspec.nr)
1725 die(_("invalid path specification"));
1728 * Try to give more helpful suggestion.
1729 * new_branch && argc > 1 will be caught later.
1731 if (opts->new_branch && argc == 1 && !new_branch_info.commit)
1732 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1733 argv[0], opts->new_branch);
1735 if (opts->force_detach)
1736 die(_("git checkout: --detach does not take a path argument '%s'"),
1740 if (opts->pathspec_from_file) {
1741 if (opts->pathspec.nr)
1742 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1744 if (opts->force_detach)
1745 die(_("--pathspec-from-file is incompatible with --detach"));
1747 if (opts->patch_mode)
1748 die(_("--pathspec-from-file is incompatible with --patch"));
1750 parse_pathspec_file(&opts->pathspec, 0,
1752 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1753 } else if (opts->pathspec_file_nul) {
1754 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1757 opts->pathspec.recursive = 1;
1759 if (opts->pathspec.nr) {
1760 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1761 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1762 "checking out of the index."));
1764 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1765 !opts->patch_mode) /* patch mode is special */
1766 die(_("you must specify path(s) to restore"));
1769 if (opts->new_branch) {
1770 struct strbuf buf = STRBUF_INIT;
1772 if (opts->new_branch_force)
1773 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1775 opts->branch_exists =
1776 validate_new_branchname(opts->new_branch, &buf, 0);
1777 strbuf_release(&buf);
1781 if (opts->patch_mode || opts->pathspec.nr)
1782 return checkout_paths(opts, &new_branch_info);
1784 return checkout_branch(opts, &new_branch_info);
1787 int cmd_checkout(int argc, const char **argv, const char *prefix)
1789 struct checkout_opts opts;
1790 struct option *options;
1791 struct option checkout_options[] = {
1792 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1793 N_("create and checkout a new branch")),
1794 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1795 N_("create/reset and checkout a branch")),
1796 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1797 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1798 N_("second guess 'git checkout <no-such-branch>' (default)")),
1799 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1804 memset(&opts, 0, sizeof(opts));
1805 opts.dwim_new_local_branch = 1;
1806 opts.switch_branch_doing_nothing_is_ok = 1;
1807 opts.only_merge_on_switching_branches = 0;
1808 opts.accept_ref = 1;
1809 opts.accept_pathspec = 1;
1810 opts.implicit_detach = 1;
1811 opts.can_switch_when_in_progress = 1;
1812 opts.orphan_from_empty_tree = 0;
1813 opts.empty_pathspec_ok = 1;
1814 opts.overlay_mode = -1;
1815 opts.checkout_index = -2; /* default on */
1816 opts.checkout_worktree = -2; /* default on */
1818 if (argc == 3 && !strcmp(argv[1], "-b")) {
1820 * User ran 'git checkout -b <branch>' and expects
1821 * the same behavior as 'git switch -c <branch>'.
1823 opts.switch_branch_doing_nothing_is_ok = 0;
1824 opts.only_merge_on_switching_branches = 1;
1827 options = parse_options_dup(checkout_options);
1828 options = add_common_options(&opts, options);
1829 options = add_common_switch_branch_options(&opts, options);
1830 options = add_checkout_path_options(&opts, options);
1832 ret = checkout_main(argc, argv, prefix, &opts,
1833 options, checkout_usage);
1834 FREE_AND_NULL(options);
1838 int cmd_switch(int argc, const char **argv, const char *prefix)
1840 struct checkout_opts opts;
1841 struct option *options = NULL;
1842 struct option switch_options[] = {
1843 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1844 N_("create and switch to a new branch")),
1845 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1846 N_("create/reset and switch to a branch")),
1847 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1848 N_("second guess 'git switch <no-such-branch>'")),
1849 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1850 N_("throw away local modifications")),
1855 memset(&opts, 0, sizeof(opts));
1856 opts.dwim_new_local_branch = 1;
1857 opts.accept_ref = 1;
1858 opts.accept_pathspec = 0;
1859 opts.switch_branch_doing_nothing_is_ok = 0;
1860 opts.only_merge_on_switching_branches = 1;
1861 opts.implicit_detach = 0;
1862 opts.can_switch_when_in_progress = 0;
1863 opts.orphan_from_empty_tree = 1;
1864 opts.overlay_mode = -1;
1866 options = parse_options_dup(switch_options);
1867 options = add_common_options(&opts, options);
1868 options = add_common_switch_branch_options(&opts, options);
1872 ret = checkout_main(argc, argv, prefix, &opts,
1873 options, switch_branch_usage);
1874 FREE_AND_NULL(options);
1878 int cmd_restore(int argc, const char **argv, const char *prefix)
1880 struct checkout_opts opts;
1881 struct option *options;
1882 struct option restore_options[] = {
1883 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1884 N_("which tree-ish to checkout from")),
1885 OPT_BOOL('S', "staged", &opts.checkout_index,
1886 N_("restore the index")),
1887 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1888 N_("restore the working tree (default)")),
1889 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1890 N_("ignore unmerged entries")),
1891 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1896 memset(&opts, 0, sizeof(opts));
1897 opts.accept_ref = 0;
1898 opts.accept_pathspec = 1;
1899 opts.empty_pathspec_ok = 0;
1900 opts.overlay_mode = 0;
1901 opts.checkout_index = -1; /* default off */
1902 opts.checkout_worktree = -2; /* default on */
1903 opts.ignore_unmerged_opt = "--ignore-unmerged";
1905 options = parse_options_dup(restore_options);
1906 options = add_common_options(&opts, options);
1907 options = add_checkout_path_options(&opts, options);
1909 ret = checkout_main(argc, argv, prefix, &opts,
1910 options, restore_usage);
1911 FREE_AND_NULL(options);