1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
6 #include "cache-tree.h"
14 #include "merge-recursive.h"
15 #include "object-store.h"
16 #include "parse-options.h"
19 #include "resolve-undo.h"
21 #include "run-command.h"
22 #include "submodule.h"
23 #include "submodule-config.h"
25 #include "tree-walk.h"
26 #include "unpack-trees.h"
27 #include "wt-status.h"
28 #include "xdiff-interface.h"
30 static const char * const checkout_usage[] = {
31 N_("git checkout [<options>] <branch>"),
32 N_("git checkout [<options>] [<branch>] -- <file>..."),
36 static const char * const switch_branch_usage[] = {
37 N_("git switch [<options>] [<branch>]"),
41 static const char * const restore_usage[] = {
42 N_("git restore [<options>] [--source=<branch>] <file>..."),
46 struct checkout_opts {
55 int ignore_skipworktree;
56 int ignore_other_worktrees;
58 int count_checkout_paths;
60 int dwim_new_local_branch;
64 int switch_branch_doing_nothing_is_ok;
65 int only_merge_on_switching_branches;
66 int can_switch_when_in_progress;
67 int orphan_from_empty_tree;
68 int empty_pathspec_ok;
70 int checkout_worktree;
71 const char *ignore_unmerged_opt;
73 int pathspec_file_nul;
74 const char *pathspec_from_file;
76 const char *new_branch;
77 const char *new_branch_force;
78 const char *new_orphan_branch;
80 enum branch_track track;
81 struct diff_options diff_options;
86 struct pathspec pathspec;
87 const char *from_treeish;
88 struct tree *source_tree;
92 const char *name; /* The short name used */
93 const char *path; /* The full name of a real branch */
94 struct commit *commit; /* The named commit */
95 char *refname; /* The full name of the ref being checked out. */
96 struct object_id oid; /* The object ID of the commit being checked out. */
98 * if not null the branch is detached because it's already
99 * checked out in this checkout
104 static int post_checkout_hook(struct commit *old_commit, struct commit *new_commit,
107 return run_hook_le(NULL, "post-checkout",
108 oid_to_hex(old_commit ? &old_commit->object.oid : &null_oid),
109 oid_to_hex(new_commit ? &new_commit->object.oid : &null_oid),
110 changed ? "1" : "0", NULL);
111 /* "new_commit" can be NULL when checking out from the index before
116 static int update_some(const struct object_id *oid, struct strbuf *base,
117 const char *pathname, unsigned mode, int stage, void *context)
120 struct cache_entry *ce;
124 return READ_TREE_RECURSIVE;
126 len = base->len + strlen(pathname);
127 ce = make_empty_cache_entry(&the_index, len);
128 oidcpy(&ce->oid, oid);
129 memcpy(ce->name, base->buf, base->len);
130 memcpy(ce->name + base->len, pathname, len - base->len);
131 ce->ce_flags = create_ce_flags(0) | CE_UPDATE;
132 ce->ce_namelen = len;
133 ce->ce_mode = create_ce_mode(mode);
136 * If the entry is the same as the current index, we can leave the old
137 * entry in place. Whether it is UPTODATE or not, checkout_entry will
138 * do the right thing.
140 pos = cache_name_pos(ce->name, ce->ce_namelen);
142 struct cache_entry *old = active_cache[pos];
143 if (ce->ce_mode == old->ce_mode &&
144 !ce_intent_to_add(old) &&
145 oideq(&ce->oid, &old->oid)) {
146 old->ce_flags |= CE_UPDATE;
147 discard_cache_entry(ce);
152 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
156 static int read_tree_some(struct tree *tree, const struct pathspec *pathspec)
158 read_tree_recursive(the_repository, tree, "", 0, 0,
159 pathspec, update_some, NULL);
161 /* update the index with the given tree's info
162 * for all args, expanding wildcards, and exit
163 * with any non-zero return code.
168 static int skip_same_name(const struct cache_entry *ce, int pos)
170 while (++pos < active_nr &&
171 !strcmp(active_cache[pos]->name, ce->name))
176 static int check_stage(int stage, const struct cache_entry *ce, int pos,
179 while (pos < active_nr &&
180 !strcmp(active_cache[pos]->name, ce->name)) {
181 if (ce_stage(active_cache[pos]) == stage)
188 return error(_("path '%s' does not have our version"), ce->name);
190 return error(_("path '%s' does not have their version"), ce->name);
193 static int check_stages(unsigned stages, const struct cache_entry *ce, int pos)
196 const char *name = ce->name;
198 while (pos < active_nr) {
199 ce = active_cache[pos];
200 if (strcmp(name, ce->name))
202 seen |= (1 << ce_stage(ce));
205 if ((stages & seen) != stages)
206 return error(_("path '%s' does not have all necessary versions"),
211 static int checkout_stage(int stage, const struct cache_entry *ce, int pos,
212 const struct checkout *state, int *nr_checkouts,
215 while (pos < active_nr &&
216 !strcmp(active_cache[pos]->name, ce->name)) {
217 if (ce_stage(active_cache[pos]) == stage)
218 return checkout_entry(active_cache[pos], state,
227 return error(_("path '%s' does not have our version"), ce->name);
229 return error(_("path '%s' does not have their version"), ce->name);
232 static int checkout_merged(int pos, const struct checkout *state, int *nr_checkouts)
234 struct cache_entry *ce = active_cache[pos];
235 const char *path = ce->name;
236 mmfile_t ancestor, ours, theirs;
238 struct object_id oid;
239 mmbuffer_t result_buf;
240 struct object_id threeway[3];
243 memset(threeway, 0, sizeof(threeway));
244 while (pos < active_nr) {
246 stage = ce_stage(ce);
247 if (!stage || strcmp(path, ce->name))
249 oidcpy(&threeway[stage - 1], &ce->oid);
251 mode = create_ce_mode(ce->ce_mode);
253 ce = active_cache[pos];
255 if (is_null_oid(&threeway[1]) || is_null_oid(&threeway[2]))
256 return error(_("path '%s' does not have necessary versions"), path);
258 read_mmblob(&ancestor, &threeway[0]);
259 read_mmblob(&ours, &threeway[1]);
260 read_mmblob(&theirs, &threeway[2]);
263 * NEEDSWORK: re-create conflicts from merges with
264 * merge.renormalize set, too
266 status = ll_merge(&result_buf, path, &ancestor, "base",
267 &ours, "ours", &theirs, "theirs",
268 state->istate, NULL);
272 if (status < 0 || !result_buf.ptr) {
273 free(result_buf.ptr);
274 return error(_("path '%s': cannot merge"), path);
279 * There is absolutely no reason to write this as a blob object
280 * and create a phony cache entry. This hack is primarily to get
281 * to the write_entry() machinery that massages the contents to
282 * work-tree format and writes out which only allows it for a
283 * cache entry. The code in write_entry() needs to be refactored
284 * to allow us to feed a <buffer, size, mode> instead of a cache
285 * entry. Such a refactoring would help merge_recursive as well
286 * (it also writes the merge result to the object database even
287 * when it may contain conflicts).
289 if (write_object_file(result_buf.ptr, result_buf.size, blob_type, &oid))
290 die(_("Unable to add merge result for '%s'"), path);
291 free(result_buf.ptr);
292 ce = make_transient_cache_entry(mode, &oid, path, 2);
294 die(_("make_cache_entry failed for path '%s'"), path);
295 status = checkout_entry(ce, state, NULL, nr_checkouts);
296 discard_cache_entry(ce);
300 static void mark_ce_for_checkout_overlay(struct cache_entry *ce,
302 const struct checkout_opts *opts)
304 ce->ce_flags &= ~CE_MATCHED;
305 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
307 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
309 * "git checkout tree-ish -- path", but this entry
310 * is in the original index but is not in tree-ish
311 * or does not match the pathspec; it will not be
312 * checked out to the working tree. We will not do
313 * anything to this entry at all.
317 * Either this entry came from the tree-ish we are
318 * checking the paths out of, or we are checking out
321 * If it comes from the tree-ish, we already know it
322 * matches the pathspec and could just stamp
323 * CE_MATCHED to it from update_some(). But we still
324 * need ps_matched and read_tree_recursive (and
325 * eventually tree_entry_interesting) cannot fill
326 * ps_matched yet. Once it can, we can avoid calling
327 * match_pathspec() for _all_ entries when
328 * opts->source_tree != NULL.
330 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched))
331 ce->ce_flags |= CE_MATCHED;
334 static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
336 const struct checkout_opts *opts)
338 ce->ce_flags &= ~CE_MATCHED;
339 if (!opts->ignore_skipworktree && ce_skip_worktree(ce))
341 if (ce_path_match(&the_index, ce, &opts->pathspec, ps_matched)) {
342 ce->ce_flags |= CE_MATCHED;
343 if (opts->source_tree && !(ce->ce_flags & CE_UPDATE))
345 * In overlay mode, but the path is not in
346 * tree-ish, which means we should remove it
347 * from the index and the working tree.
349 ce->ce_flags |= CE_REMOVE | CE_WT_REMOVE;
353 static int checkout_worktree(const struct checkout_opts *opts,
354 const struct branch_info *info)
356 struct checkout state = CHECKOUT_INIT;
357 int nr_checkouts = 0, nr_unmerged = 0;
362 state.refresh_cache = 1;
363 state.istate = &the_index;
365 init_checkout_metadata(&state.meta, info->refname,
366 info->commit ? &info->commit->object.oid : &info->oid,
369 enable_delayed_checkout(&state);
370 for (pos = 0; pos < active_nr; pos++) {
371 struct cache_entry *ce = active_cache[pos];
372 if (ce->ce_flags & CE_MATCHED) {
374 errs |= checkout_entry(ce, &state,
375 NULL, &nr_checkouts);
378 if (opts->writeout_stage)
379 errs |= checkout_stage(opts->writeout_stage,
382 &nr_checkouts, opts->overlay_mode);
383 else if (opts->merge)
384 errs |= checkout_merged(pos, &state,
386 pos = skip_same_name(ce, pos) - 1;
389 remove_marked_cache_entries(&the_index, 1);
390 remove_scheduled_dirs();
391 errs |= finish_delayed_checkout(&state, &nr_checkouts);
393 if (opts->count_checkout_paths) {
395 fprintf_ln(stderr, Q_("Recreated %d merge conflict",
396 "Recreated %d merge conflicts",
399 if (opts->source_tree)
400 fprintf_ln(stderr, Q_("Updated %d path from %s",
401 "Updated %d paths from %s",
404 find_unique_abbrev(&opts->source_tree->object.oid,
406 else if (!nr_unmerged || nr_checkouts)
407 fprintf_ln(stderr, Q_("Updated %d path from the index",
408 "Updated %d paths from the index",
416 static int checkout_paths(const struct checkout_opts *opts,
417 const struct branch_info *new_branch_info)
420 static char *ps_matched;
421 struct object_id rev;
424 struct lock_file lock_file = LOCK_INIT;
427 trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
429 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
430 die(_("'%s' cannot be used with updating paths"), "--track");
432 if (opts->new_branch_log)
433 die(_("'%s' cannot be used with updating paths"), "-l");
435 if (opts->ignore_unmerged && opts->patch_mode)
436 die(_("'%s' cannot be used with updating paths"),
437 opts->ignore_unmerged_opt);
439 if (opts->force_detach)
440 die(_("'%s' cannot be used with updating paths"), "--detach");
442 if (opts->merge && opts->patch_mode)
443 die(_("'%s' cannot be used with %s"), "--merge", "--patch");
445 if (opts->ignore_unmerged && opts->merge)
446 die(_("'%s' cannot be used with %s"),
447 opts->ignore_unmerged_opt, "-m");
449 if (opts->new_branch)
450 die(_("Cannot update paths and switch to branch '%s' at the same time."),
453 if (!opts->checkout_worktree && !opts->checkout_index)
454 die(_("neither '%s' or '%s' is specified"),
455 "--staged", "--worktree");
457 if (!opts->checkout_worktree && !opts->from_treeish)
458 die(_("'%s' must be used when '%s' is not specified"),
459 "--worktree", "--source");
461 if (opts->checkout_index && !opts->checkout_worktree &&
462 opts->writeout_stage)
463 die(_("'%s' or '%s' cannot be used with %s"),
464 "--ours", "--theirs", "--staged");
466 if (opts->checkout_index && !opts->checkout_worktree &&
468 die(_("'%s' or '%s' cannot be used with %s"),
469 "--merge", "--conflict", "--staged");
471 if (opts->patch_mode) {
472 const char *patch_mode;
474 if (opts->checkout_index && opts->checkout_worktree)
475 patch_mode = "--patch=checkout";
476 else if (opts->checkout_index && !opts->checkout_worktree)
477 patch_mode = "--patch=reset";
478 else if (!opts->checkout_index && opts->checkout_worktree)
479 patch_mode = "--patch=worktree";
481 BUG("either flag must have been set, worktree=%d, index=%d",
482 opts->checkout_worktree, opts->checkout_index);
483 return run_add_interactive(new_branch_info->name, patch_mode, &opts->pathspec);
486 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
487 if (read_cache_preload(&opts->pathspec) < 0)
488 return error(_("index file corrupt"));
490 if (opts->source_tree)
491 read_tree_some(opts->source_tree, &opts->pathspec);
493 ps_matched = xcalloc(opts->pathspec.nr, 1);
496 * Make sure all pathspecs participated in locating the paths
499 for (pos = 0; pos < active_nr; pos++)
500 if (opts->overlay_mode)
501 mark_ce_for_checkout_overlay(active_cache[pos],
505 mark_ce_for_checkout_no_overlay(active_cache[pos],
509 if (report_path_error(ps_matched, &opts->pathspec)) {
515 /* "checkout -m path" to recreate conflicted state */
517 unmerge_marked_index(&the_index);
519 /* Any unmerged paths? */
520 for (pos = 0; pos < active_nr; pos++) {
521 const struct cache_entry *ce = active_cache[pos];
522 if (ce->ce_flags & CE_MATCHED) {
525 if (opts->ignore_unmerged) {
527 warning(_("path '%s' is unmerged"), ce->name);
528 } else if (opts->writeout_stage) {
529 errs |= check_stage(opts->writeout_stage, ce, pos, opts->overlay_mode);
530 } else if (opts->merge) {
531 errs |= check_stages((1<<2) | (1<<3), ce, pos);
534 error(_("path '%s' is unmerged"), ce->name);
536 pos = skip_same_name(ce, pos) - 1;
542 /* Now we are committed to check them out */
543 if (opts->checkout_worktree)
544 errs |= checkout_worktree(opts, new_branch_info);
546 remove_marked_cache_entries(&the_index, 1);
549 * Allow updating the index when checking out from the index.
550 * This is to save new stat info.
552 if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
555 checkout_index = opts->checkout_index;
557 if (checkout_index) {
558 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
559 die(_("unable to write new index file"));
562 * NEEDSWORK: if --worktree is not specified, we
563 * should save stat info of checked out files in the
564 * index to avoid the next (potentially costly)
565 * refresh. But it's a bit tricker to do...
567 rollback_lock_file(&lock_file);
570 read_ref_full("HEAD", 0, &rev, NULL);
571 head = lookup_commit_reference_gently(the_repository, &rev, 1);
573 errs |= post_checkout_hook(head, head, 0);
577 static void show_local_changes(struct object *head,
578 const struct diff_options *opts)
581 /* I think we want full paths, even if we're in a subdirectory. */
582 repo_init_revisions(the_repository, &rev, NULL);
583 rev.diffopt.flags = opts->flags;
584 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
585 diff_setup_done(&rev.diffopt);
586 add_pending_object(&rev, head, NULL);
587 run_diff_index(&rev, 0);
590 static void describe_detached_head(const char *msg, struct commit *commit)
592 struct strbuf sb = STRBUF_INIT;
594 if (!parse_commit(commit))
595 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
596 if (print_sha1_ellipsis()) {
597 fprintf(stderr, "%s %s... %s\n", msg,
598 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
600 fprintf(stderr, "%s %s %s\n", msg,
601 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV), sb.buf);
606 static int reset_tree(struct tree *tree, const struct checkout_opts *o,
607 int worktree, int *writeout_error)
609 struct unpack_trees_options opts;
610 struct tree_desc tree_desc;
612 memset(&opts, 0, sizeof(opts));
614 opts.update = worktree;
615 opts.skip_unmerged = !worktree;
618 opts.fn = oneway_merge;
619 opts.verbose_update = o->show_progress;
620 opts.src_index = &the_index;
621 opts.dst_index = &the_index;
623 init_tree_desc(&tree_desc, tree->buffer, tree->size);
624 switch (unpack_trees(1, &tree_desc, &opts)) {
628 * We return 0 nevertheless, as the index is all right
629 * and more importantly we have made best efforts to
630 * update paths in the work tree, and we cannot revert
641 static void setup_branch_path(struct branch_info *branch)
643 struct strbuf buf = STRBUF_INIT;
646 * If this is a ref, resolve it; otherwise, look up the OID for our
647 * expression. Failure here is okay.
649 if (!dwim_ref(branch->name, strlen(branch->name), &branch->oid, &branch->refname))
650 repo_get_oid_committish(the_repository, branch->name, &branch->oid);
652 strbuf_branchname(&buf, branch->name, INTERPRET_BRANCH_LOCAL);
653 if (strcmp(buf.buf, branch->name))
654 branch->name = xstrdup(buf.buf);
655 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
656 branch->path = strbuf_detach(&buf, NULL);
659 static int merge_working_tree(const struct checkout_opts *opts,
660 struct branch_info *old_branch_info,
661 struct branch_info *new_branch_info,
665 struct lock_file lock_file = LOCK_INIT;
666 struct tree *new_tree;
668 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
669 if (read_cache_preload(NULL) < 0)
670 return error(_("index file corrupt"));
672 resolve_undo_clear();
673 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
674 if (new_branch_info->commit)
675 BUG("'switch --orphan' should never accept a commit as starting point");
676 new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
678 new_tree = get_commit_tree(new_branch_info->commit);
679 if (opts->discard_changes) {
680 ret = reset_tree(new_tree, opts, 1, writeout_error);
684 struct tree_desc trees[2];
686 struct unpack_trees_options topts;
688 memset(&topts, 0, sizeof(topts));
690 topts.src_index = &the_index;
691 topts.dst_index = &the_index;
693 setup_unpack_trees_porcelain(&topts, "checkout");
695 refresh_cache(REFRESH_QUIET);
697 if (unmerged_cache()) {
698 error(_("you need to resolve your current index first"));
702 /* 2-way merge to the new branch */
703 topts.initial_checkout = is_cache_unborn();
706 topts.quiet = opts->merge && old_branch_info->commit;
707 topts.verbose_update = opts->show_progress;
708 topts.fn = twoway_merge;
709 if (opts->overwrite_ignore) {
710 topts.dir = xcalloc(1, sizeof(*topts.dir));
711 topts.dir->flags |= DIR_SHOW_IGNORED;
712 setup_standard_excludes(topts.dir);
714 tree = parse_tree_indirect(old_branch_info->commit ?
715 &old_branch_info->commit->object.oid :
716 the_hash_algo->empty_tree);
717 init_tree_desc(&trees[0], tree->buffer, tree->size);
718 parse_tree(new_tree);
720 init_tree_desc(&trees[1], tree->buffer, tree->size);
722 ret = unpack_trees(2, trees, &topts);
723 clear_unpack_trees_porcelain(&topts);
726 * Unpack couldn't do a trivial merge; either
727 * give up or do a real merge, depending on
728 * whether the merge flag was used.
731 struct tree *old_tree;
732 struct merge_options o;
733 struct strbuf sb = STRBUF_INIT;
734 struct strbuf old_commit_shortname = STRBUF_INIT;
740 * Without old_branch_info->commit, the below is the same as
741 * the two-tree unpack we already tried and failed.
743 if (!old_branch_info->commit)
745 old_tree = get_commit_tree(old_branch_info->commit);
747 if (repo_index_has_changes(the_repository, old_tree, &sb))
748 die(_("cannot continue with staged changes in "
749 "the following files:\n%s"), sb.buf);
752 /* Do more real merge */
755 * We update the index fully, then write the
756 * tree from the index, then merge the new
757 * branch with the current tree, with the old
758 * branch as the base. Then we reset the index
759 * (but not the working tree) to the new
760 * branch, leaving the working tree as the
761 * merged version, but skipping unmerged
762 * entries in the index.
765 add_files_to_cache(NULL, NULL, 0);
767 * NEEDSWORK: carrying over local changes
768 * when branches have different end-of-line
769 * normalization (or clean+smudge rules) is
770 * a pain; plumb in an option to set
773 init_merge_options(&o, the_repository);
775 work = write_in_core_index_as_tree(the_repository);
777 ret = reset_tree(new_tree,
782 o.ancestor = old_branch_info->name;
783 if (old_branch_info->name == NULL) {
784 strbuf_add_unique_abbrev(&old_commit_shortname,
785 &old_branch_info->commit->object.oid,
787 o.ancestor = old_commit_shortname.buf;
789 o.branch1 = new_branch_info->name;
791 ret = merge_trees(&o,
797 ret = reset_tree(new_tree,
800 strbuf_release(&o.obuf);
801 strbuf_release(&old_commit_shortname);
807 if (!active_cache_tree)
808 active_cache_tree = cache_tree();
810 if (!cache_tree_fully_valid(active_cache_tree))
811 cache_tree_update(&the_index, WRITE_TREE_SILENT | WRITE_TREE_REPAIR);
813 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
814 die(_("unable to write new index file"));
816 if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
817 show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
822 static void report_tracking(struct branch_info *new_branch_info)
824 struct strbuf sb = STRBUF_INIT;
825 struct branch *branch = branch_get(new_branch_info->name);
827 if (!format_tracking_info(branch, &sb, AHEAD_BEHIND_FULL))
829 fputs(sb.buf, stdout);
833 static void update_refs_for_switch(const struct checkout_opts *opts,
834 struct branch_info *old_branch_info,
835 struct branch_info *new_branch_info)
837 struct strbuf msg = STRBUF_INIT;
838 const char *old_desc, *reflog_msg;
839 if (opts->new_branch) {
840 if (opts->new_orphan_branch) {
843 refname = mkpathdup("refs/heads/%s", opts->new_orphan_branch);
844 if (opts->new_branch_log &&
845 !should_autocreate_reflog(refname)) {
847 struct strbuf err = STRBUF_INIT;
849 ret = safe_create_reflog(refname, 1, &err);
851 fprintf(stderr, _("Can not do reflog for '%s': %s\n"),
852 opts->new_orphan_branch, err.buf);
853 strbuf_release(&err);
857 strbuf_release(&err);
862 create_branch(the_repository,
863 opts->new_branch, new_branch_info->name,
864 opts->new_branch_force ? 1 : 0,
865 opts->new_branch_force ? 1 : 0,
866 opts->new_branch_log,
869 new_branch_info->name = opts->new_branch;
870 setup_branch_path(new_branch_info);
873 old_desc = old_branch_info->name;
874 if (!old_desc && old_branch_info->commit)
875 old_desc = oid_to_hex(&old_branch_info->commit->object.oid);
877 reflog_msg = getenv("GIT_REFLOG_ACTION");
879 strbuf_addf(&msg, "checkout: moving from %s to %s",
880 old_desc ? old_desc : "(invalid)", new_branch_info->name);
882 strbuf_insertstr(&msg, 0, reflog_msg);
884 if (!strcmp(new_branch_info->name, "HEAD") && !new_branch_info->path && !opts->force_detach) {
886 } else if (opts->force_detach || !new_branch_info->path) { /* No longer on any branch. */
887 update_ref(msg.buf, "HEAD", &new_branch_info->commit->object.oid, NULL,
888 REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
890 if (old_branch_info->path &&
891 advice_detached_head && !opts->force_detach)
892 detach_advice(new_branch_info->name);
893 describe_detached_head(_("HEAD is now at"), new_branch_info->commit);
895 } else if (new_branch_info->path) { /* Switch branches. */
896 if (create_symref("HEAD", new_branch_info->path, msg.buf) < 0)
897 die(_("unable to update HEAD"));
899 if (old_branch_info->path && !strcmp(new_branch_info->path, old_branch_info->path)) {
900 if (opts->new_branch_force)
901 fprintf(stderr, _("Reset branch '%s'\n"),
902 new_branch_info->name);
904 fprintf(stderr, _("Already on '%s'\n"),
905 new_branch_info->name);
906 } else if (opts->new_branch) {
907 if (opts->branch_exists)
908 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new_branch_info->name);
910 fprintf(stderr, _("Switched to a new branch '%s'\n"), new_branch_info->name);
912 fprintf(stderr, _("Switched to branch '%s'\n"),
913 new_branch_info->name);
916 if (old_branch_info->path && old_branch_info->name) {
917 if (!ref_exists(old_branch_info->path) && reflog_exists(old_branch_info->path))
918 delete_reflog(old_branch_info->path);
921 remove_branch_state(the_repository, !opts->quiet);
922 strbuf_release(&msg);
924 (new_branch_info->path || (!opts->force_detach && !strcmp(new_branch_info->name, "HEAD"))))
925 report_tracking(new_branch_info);
928 static int add_pending_uninteresting_ref(const char *refname,
929 const struct object_id *oid,
930 int flags, void *cb_data)
932 add_pending_oid(cb_data, refname, oid, UNINTERESTING);
936 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
938 strbuf_addstr(sb, " ");
939 strbuf_add_unique_abbrev(sb, &commit->object.oid, DEFAULT_ABBREV);
940 strbuf_addch(sb, ' ');
941 if (!parse_commit(commit))
942 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
943 strbuf_addch(sb, '\n');
946 #define ORPHAN_CUTOFF 4
947 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
949 struct commit *c, *last = NULL;
950 struct strbuf sb = STRBUF_INIT;
952 while ((c = get_revision(revs)) != NULL) {
953 if (lost < ORPHAN_CUTOFF)
954 describe_one_orphan(&sb, c);
958 if (ORPHAN_CUTOFF < lost) {
959 int more = lost - ORPHAN_CUTOFF;
961 describe_one_orphan(&sb, last);
963 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
968 /* The singular version */
969 "Warning: you are leaving %d commit behind, "
971 "any of your branches:\n\n"
973 /* The plural version */
974 "Warning: you are leaving %d commits behind, "
976 "any of your branches:\n\n"
978 /* Give ngettext() the count */
984 if (advice_detached_head)
987 /* The singular version */
988 "If you want to keep it by creating a new branch, "
989 "this may be a good time\nto do so with:\n\n"
990 " git branch <new-branch-name> %s\n\n",
991 /* The plural version */
992 "If you want to keep them by creating a new branch, "
993 "this may be a good time\nto do so with:\n\n"
994 " git branch <new-branch-name> %s\n\n",
995 /* Give ngettext() the count */
997 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
1001 * We are about to leave commit that was at the tip of a detached
1002 * HEAD. If it is not reachable from any ref, this is the last chance
1003 * for the user to do so without resorting to reflog.
1005 static void orphaned_commit_warning(struct commit *old_commit, struct commit *new_commit)
1007 struct rev_info revs;
1008 struct object *object = &old_commit->object;
1010 repo_init_revisions(the_repository, &revs, NULL);
1011 setup_revisions(0, NULL, &revs, NULL);
1013 object->flags &= ~UNINTERESTING;
1014 add_pending_object(&revs, object, oid_to_hex(&object->oid));
1016 for_each_ref(add_pending_uninteresting_ref, &revs);
1018 add_pending_oid(&revs, "HEAD",
1019 &new_commit->object.oid,
1022 if (prepare_revision_walk(&revs))
1023 die(_("internal error in revision walk"));
1024 if (!(old_commit->object.flags & UNINTERESTING))
1025 suggest_reattach(old_commit, &revs);
1027 describe_detached_head(_("Previous HEAD position was"), old_commit);
1029 /* Clean up objects used, as they will be reused. */
1030 clear_commit_marks_all(ALL_REV_FLAGS);
1033 static int switch_branches(const struct checkout_opts *opts,
1034 struct branch_info *new_branch_info)
1037 struct branch_info old_branch_info;
1039 struct object_id rev;
1040 int flag, writeout_error = 0;
1043 trace2_cmd_mode("branch");
1045 memset(&old_branch_info, 0, sizeof(old_branch_info));
1046 old_branch_info.path = path_to_free = resolve_refdup("HEAD", 0, &rev, &flag);
1047 if (old_branch_info.path)
1048 old_branch_info.commit = lookup_commit_reference_gently(the_repository, &rev, 1);
1049 if (!(flag & REF_ISSYMREF))
1050 old_branch_info.path = NULL;
1052 if (old_branch_info.path)
1053 skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
1055 if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
1056 if (new_branch_info->name)
1057 BUG("'switch --orphan' should never accept a commit as starting point");
1058 new_branch_info->commit = NULL;
1059 new_branch_info->name = "(empty)";
1063 if (!new_branch_info->name) {
1064 new_branch_info->name = "HEAD";
1065 new_branch_info->commit = old_branch_info.commit;
1066 if (!new_branch_info->commit)
1067 die(_("You are on a branch yet to be born"));
1068 parse_commit_or_die(new_branch_info->commit);
1070 if (opts->only_merge_on_switching_branches)
1075 ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
1082 if (!opts->quiet && !old_branch_info.path && old_branch_info.commit && new_branch_info->commit != old_branch_info.commit)
1083 orphaned_commit_warning(old_branch_info.commit, new_branch_info->commit);
1085 update_refs_for_switch(opts, &old_branch_info, new_branch_info);
1087 ret = post_checkout_hook(old_branch_info.commit, new_branch_info->commit, 1);
1089 return ret || writeout_error;
1092 static int git_checkout_config(const char *var, const char *value, void *cb)
1094 if (!strcmp(var, "diff.ignoresubmodules")) {
1095 struct checkout_opts *opts = cb;
1096 handle_ignore_submodules_arg(&opts->diff_options, value);
1100 if (starts_with(var, "submodule."))
1101 return git_default_submodule_config(var, value, NULL);
1103 return git_xmerge_config(var, value, NULL);
1106 static void setup_new_branch_info_and_source_tree(
1107 struct branch_info *new_branch_info,
1108 struct checkout_opts *opts,
1109 struct object_id *rev,
1112 struct tree **source_tree = &opts->source_tree;
1113 struct object_id branch_rev;
1115 new_branch_info->name = arg;
1116 setup_branch_path(new_branch_info);
1118 if (!check_refname_format(new_branch_info->path, 0) &&
1119 !read_ref(new_branch_info->path, &branch_rev))
1120 oidcpy(rev, &branch_rev);
1122 new_branch_info->path = NULL; /* not an existing branch */
1124 new_branch_info->commit = lookup_commit_reference_gently(the_repository, rev, 1);
1125 if (!new_branch_info->commit) {
1127 *source_tree = parse_tree_indirect(rev);
1129 parse_commit_or_die(new_branch_info->commit);
1130 *source_tree = get_commit_tree(new_branch_info->commit);
1134 static const char *parse_remote_branch(const char *arg,
1135 struct object_id *rev,
1136 int could_be_checkout_paths)
1138 int num_matches = 0;
1139 const char *remote = unique_tracking_name(arg, rev, &num_matches);
1141 if (remote && could_be_checkout_paths) {
1142 die(_("'%s' could be both a local file and a tracking branch.\n"
1143 "Please use -- (and optionally --no-guess) to disambiguate"),
1147 if (!remote && num_matches > 1) {
1148 if (advice_checkout_ambiguous_remote_branch_name) {
1149 advise(_("If you meant to check out a remote tracking branch on, e.g. 'origin',\n"
1150 "you can do so by fully qualifying the name with the --track option:\n"
1152 " git checkout --track origin/<name>\n"
1154 "If you'd like to always have checkouts of an ambiguous <name> prefer\n"
1155 "one remote, e.g. the 'origin' remote, consider setting\n"
1156 "checkout.defaultRemote=origin in your config."));
1159 die(_("'%s' matched multiple (%d) remote tracking branches"),
1166 static int parse_branchname_arg(int argc, const char **argv,
1167 int dwim_new_local_branch_ok,
1168 struct branch_info *new_branch_info,
1169 struct checkout_opts *opts,
1170 struct object_id *rev)
1172 const char **new_branch = &opts->new_branch;
1176 int has_dash_dash = 0;
1180 * case 1: git checkout <ref> -- [<paths>]
1182 * <ref> must be a valid tree, everything after the '--' must be
1185 * case 2: git checkout -- [<paths>]
1187 * everything after the '--' must be paths.
1189 * case 3: git checkout <something> [--]
1191 * (a) If <something> is a commit, that is to
1192 * switch to the branch or detach HEAD at it. As a special case,
1193 * if <something> is A...B (missing A or B means HEAD but you can
1194 * omit at most one side), and if there is a unique merge base
1195 * between A and B, A...B names that merge base.
1197 * (b) If <something> is _not_ a commit, either "--" is present
1198 * or <something> is not a path, no -t or -b was given, and
1199 * and there is a tracking branch whose name is <something>
1200 * in one and only one remote (or if the branch exists on the
1201 * remote named in checkout.defaultRemote), then this is a
1202 * short-hand to fork local <something> from that
1203 * remote-tracking branch.
1205 * (c) Otherwise, if "--" is present, treat it like case (1).
1208 * - if it's a reference, treat it like case (1)
1209 * - else if it's a path, treat it like case (2)
1212 * case 4: git checkout <something> <paths>
1214 * The first argument must not be ambiguous.
1215 * - If it's *only* a reference, treat it like case (1).
1216 * - If it's only a path, treat it like case (2).
1223 if (!opts->accept_pathspec) {
1225 die(_("only one reference expected"));
1226 has_dash_dash = 1; /* helps disambiguate */
1231 for (i = 0; i < argc; i++) {
1232 if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
1237 if (dash_dash_pos == 0)
1238 return 1; /* case (2) */
1239 else if (dash_dash_pos == 1)
1240 has_dash_dash = 1; /* case (3) or (1) */
1241 else if (dash_dash_pos >= 2)
1242 die(_("only one reference expected, %d given."), dash_dash_pos);
1243 opts->count_checkout_paths = !opts->quiet && !has_dash_dash;
1245 if (!strcmp(arg, "-"))
1248 if (get_oid_mb(arg, rev)) {
1250 * Either case (3) or (4), with <something> not being
1251 * a commit, or an attempt to use case (1) with an
1254 * It's likely an error, but we need to find out if
1255 * we should auto-create the branch, case (3).(b).
1257 int recover_with_dwim = dwim_new_local_branch_ok;
1259 int could_be_checkout_paths = !has_dash_dash &&
1260 check_filename(opts->prefix, arg);
1262 if (!has_dash_dash && !no_wildcard(arg))
1263 recover_with_dwim = 0;
1266 * Accept "git checkout foo", "git checkout foo --"
1267 * and "git switch foo" as candidates for dwim.
1269 if (!(argc == 1 && !has_dash_dash) &&
1270 !(argc == 2 && has_dash_dash) &&
1271 opts->accept_pathspec)
1272 recover_with_dwim = 0;
1274 if (recover_with_dwim) {
1275 const char *remote = parse_remote_branch(arg, rev,
1276 could_be_checkout_paths);
1280 /* DWIMmed to create local branch, case (3).(b) */
1282 recover_with_dwim = 0;
1286 if (!recover_with_dwim) {
1288 die(_("invalid reference: %s"), arg);
1293 /* we can't end up being in (2) anymore, eat the argument */
1298 setup_new_branch_info_and_source_tree(new_branch_info, opts, rev, arg);
1300 if (!opts->source_tree) /* case (1): want a tree */
1301 die(_("reference is not a tree: %s"), arg);
1303 if (!has_dash_dash) { /* case (3).(d) -> (1) */
1305 * Do not complain the most common case
1306 * git checkout branch
1307 * even if there happen to be a file called 'branch';
1308 * it would be extremely annoying.
1311 verify_non_filename(opts->prefix, arg);
1312 } else if (opts->accept_pathspec) {
1321 static int switch_unborn_to_new_branch(const struct checkout_opts *opts)
1324 struct strbuf branch_ref = STRBUF_INIT;
1326 trace2_cmd_mode("unborn");
1328 if (!opts->new_branch)
1329 die(_("You are on a branch yet to be born"));
1330 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
1331 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
1332 strbuf_release(&branch_ref);
1334 fprintf(stderr, _("Switched to a new branch '%s'\n"),
1339 static void die_expecting_a_branch(const struct branch_info *branch_info)
1341 struct object_id oid;
1344 if (dwim_ref(branch_info->name, strlen(branch_info->name), &oid, &to_free) == 1) {
1345 const char *ref = to_free;
1347 if (skip_prefix(ref, "refs/tags/", &ref))
1348 die(_("a branch is expected, got tag '%s'"), ref);
1349 if (skip_prefix(ref, "refs/remotes/", &ref))
1350 die(_("a branch is expected, got remote branch '%s'"), ref);
1351 die(_("a branch is expected, got '%s'"), ref);
1353 if (branch_info->commit)
1354 die(_("a branch is expected, got commit '%s'"), branch_info->name);
1356 * This case should never happen because we already die() on
1357 * non-commit, but just in case.
1359 die(_("a branch is expected, got '%s'"), branch_info->name);
1362 static void die_if_some_operation_in_progress(void)
1364 struct wt_status_state state;
1366 memset(&state, 0, sizeof(state));
1367 wt_status_get_state(the_repository, &state, 0);
1369 if (state.merge_in_progress)
1370 die(_("cannot switch branch while merging\n"
1371 "Consider \"git merge --quit\" "
1372 "or \"git worktree add\"."));
1373 if (state.am_in_progress)
1374 die(_("cannot switch branch in the middle of an am session\n"
1375 "Consider \"git am --quit\" "
1376 "or \"git worktree add\"."));
1377 if (state.rebase_interactive_in_progress || state.rebase_in_progress)
1378 die(_("cannot switch branch while rebasing\n"
1379 "Consider \"git rebase --quit\" "
1380 "or \"git worktree add\"."));
1381 if (state.cherry_pick_in_progress)
1382 die(_("cannot switch branch while cherry-picking\n"
1383 "Consider \"git cherry-pick --quit\" "
1384 "or \"git worktree add\"."));
1385 if (state.revert_in_progress)
1386 die(_("cannot switch branch while reverting\n"
1387 "Consider \"git revert --quit\" "
1388 "or \"git worktree add\"."));
1389 if (state.bisect_in_progress)
1390 warning(_("you are switching branch while bisecting"));
1393 static int checkout_branch(struct checkout_opts *opts,
1394 struct branch_info *new_branch_info)
1396 if (opts->pathspec.nr)
1397 die(_("paths cannot be used with switching branches"));
1399 if (opts->patch_mode)
1400 die(_("'%s' cannot be used with switching branches"),
1403 if (opts->overlay_mode != -1)
1404 die(_("'%s' cannot be used with switching branches"),
1407 if (opts->writeout_stage)
1408 die(_("'%s' cannot be used with switching branches"),
1411 if (opts->force && opts->merge)
1412 die(_("'%s' cannot be used with '%s'"), "-f", "-m");
1414 if (opts->discard_changes && opts->merge)
1415 die(_("'%s' cannot be used with '%s'"), "--discard-changes", "--merge");
1417 if (opts->force_detach && opts->new_branch)
1418 die(_("'%s' cannot be used with '%s'"),
1419 "--detach", "-b/-B/--orphan");
1421 if (opts->new_orphan_branch) {
1422 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1423 die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
1424 if (opts->orphan_from_empty_tree && new_branch_info->name)
1425 die(_("'%s' cannot take <start-point>"), "--orphan");
1426 } else if (opts->force_detach) {
1427 if (opts->track != BRANCH_TRACK_UNSPECIFIED)
1428 die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
1429 } else if (opts->track == BRANCH_TRACK_UNSPECIFIED)
1430 opts->track = git_branch_track;
1432 if (new_branch_info->name && !new_branch_info->commit)
1433 die(_("Cannot switch branch to a non-commit '%s'"),
1434 new_branch_info->name);
1436 if (!opts->switch_branch_doing_nothing_is_ok &&
1437 !new_branch_info->name &&
1438 !opts->new_branch &&
1439 !opts->force_detach)
1440 die(_("missing branch or commit argument"));
1442 if (!opts->implicit_detach &&
1443 !opts->force_detach &&
1444 !opts->new_branch &&
1445 !opts->new_branch_force &&
1446 new_branch_info->name &&
1447 !new_branch_info->path)
1448 die_expecting_a_branch(new_branch_info);
1450 if (!opts->can_switch_when_in_progress)
1451 die_if_some_operation_in_progress();
1453 if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
1454 !opts->ignore_other_worktrees) {
1456 char *head_ref = resolve_refdup("HEAD", 0, NULL, &flag);
1458 (!(flag & REF_ISSYMREF) || strcmp(head_ref, new_branch_info->path)))
1459 die_if_checked_out(new_branch_info->path, 1);
1463 if (!new_branch_info->commit && opts->new_branch) {
1464 struct object_id rev;
1467 if (!read_ref_full("HEAD", 0, &rev, &flag) &&
1468 (flag & REF_ISSYMREF) && is_null_oid(&rev))
1469 return switch_unborn_to_new_branch(opts);
1471 return switch_branches(opts, new_branch_info);
1474 static struct option *add_common_options(struct checkout_opts *opts,
1475 struct option *prevopts)
1477 struct option options[] = {
1478 OPT__QUIET(&opts->quiet, N_("suppress progress reporting")),
1479 { OPTION_CALLBACK, 0, "recurse-submodules", NULL,
1480 "checkout", "control recursive updating of submodules",
1481 PARSE_OPT_OPTARG, option_parse_recurse_submodules_worktree_updater },
1482 OPT_BOOL(0, "progress", &opts->show_progress, N_("force progress reporting")),
1483 OPT_BOOL('m', "merge", &opts->merge, N_("perform a 3-way merge with the new branch")),
1484 OPT_STRING(0, "conflict", &opts->conflict_style, N_("style"),
1485 N_("conflict style (merge or diff3)")),
1488 struct option *newopts = parse_options_concat(prevopts, options);
1493 static struct option *add_common_switch_branch_options(
1494 struct checkout_opts *opts, struct option *prevopts)
1496 struct option options[] = {
1497 OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
1498 OPT_SET_INT('t', "track", &opts->track, N_("set upstream info for new branch"),
1499 BRANCH_TRACK_EXPLICIT),
1500 OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
1501 PARSE_OPT_NOCOMPLETE),
1502 OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unparented branch")),
1503 OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
1504 N_("update ignored files (default)"),
1505 PARSE_OPT_NOCOMPLETE),
1506 OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
1507 N_("do not check if another worktree is holding the given ref")),
1510 struct option *newopts = parse_options_concat(prevopts, options);
1515 static struct option *add_checkout_path_options(struct checkout_opts *opts,
1516 struct option *prevopts)
1518 struct option options[] = {
1519 OPT_SET_INT_F('2', "ours", &opts->writeout_stage,
1520 N_("checkout our version for unmerged files"),
1521 2, PARSE_OPT_NONEG),
1522 OPT_SET_INT_F('3', "theirs", &opts->writeout_stage,
1523 N_("checkout their version for unmerged files"),
1524 3, PARSE_OPT_NONEG),
1525 OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
1526 OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
1527 N_("do not limit pathspecs to sparse entries only")),
1528 OPT_PATHSPEC_FROM_FILE(&opts->pathspec_from_file),
1529 OPT_PATHSPEC_FILE_NUL(&opts->pathspec_file_nul),
1532 struct option *newopts = parse_options_concat(prevopts, options);
1537 static int checkout_main(int argc, const char **argv, const char *prefix,
1538 struct checkout_opts *opts, struct option *options,
1539 const char * const usagestr[])
1541 struct branch_info new_branch_info;
1542 int parseopt_flags = 0;
1544 memset(&new_branch_info, 0, sizeof(new_branch_info));
1545 opts->overwrite_ignore = 1;
1546 opts->prefix = prefix;
1547 opts->show_progress = -1;
1549 git_config(git_checkout_config, opts);
1551 opts->track = BRANCH_TRACK_UNSPECIFIED;
1553 if (!opts->accept_pathspec && !opts->accept_ref)
1554 BUG("make up your mind, you need to take _something_");
1555 if (opts->accept_pathspec && opts->accept_ref)
1556 parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
1558 argc = parse_options(argc, argv, prefix, options,
1559 usagestr, parseopt_flags);
1561 if (opts->show_progress < 0) {
1563 opts->show_progress = 0;
1565 opts->show_progress = isatty(2);
1568 if (opts->conflict_style) {
1569 opts->merge = 1; /* implied */
1570 git_xmerge_config("merge.conflictstyle", opts->conflict_style, NULL);
1573 opts->discard_changes = 1;
1574 opts->ignore_unmerged_opt = "--force";
1575 opts->ignore_unmerged = 1;
1578 if ((!!opts->new_branch + !!opts->new_branch_force + !!opts->new_orphan_branch) > 1)
1579 die(_("-b, -B and --orphan are mutually exclusive"));
1581 if (opts->overlay_mode == 1 && opts->patch_mode)
1582 die(_("-p and --overlay are mutually exclusive"));
1584 if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
1585 if (opts->checkout_index < 0)
1586 opts->checkout_index = 0;
1587 if (opts->checkout_worktree < 0)
1588 opts->checkout_worktree = 0;
1590 if (opts->checkout_index < 0)
1591 opts->checkout_index = -opts->checkout_index - 1;
1592 if (opts->checkout_worktree < 0)
1593 opts->checkout_worktree = -opts->checkout_worktree - 1;
1595 if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
1596 BUG("these flags should be non-negative by now");
1598 * convenient shortcut: "git restore --staged" equals
1599 * "git restore --staged --source HEAD"
1601 if (!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)
1602 opts->from_treeish = "HEAD";
1605 * From here on, new_branch will contain the branch to be checked out,
1606 * and new_branch_force and new_orphan_branch will tell us which one of
1607 * -b/-B/--orphan is being used.
1609 if (opts->new_branch_force)
1610 opts->new_branch = opts->new_branch_force;
1612 if (opts->new_orphan_branch)
1613 opts->new_branch = opts->new_orphan_branch;
1615 /* --track without -b/-B/--orphan should DWIM */
1616 if (opts->track != BRANCH_TRACK_UNSPECIFIED && !opts->new_branch) {
1617 const char *argv0 = argv[0];
1618 if (!argc || !strcmp(argv0, "--"))
1619 die(_("--track needs a branch name"));
1620 skip_prefix(argv0, "refs/", &argv0);
1621 skip_prefix(argv0, "remotes/", &argv0);
1622 argv0 = strchr(argv0, '/');
1623 if (!argv0 || !argv0[1])
1624 die(_("missing branch name; try -b"));
1625 opts->new_branch = argv0 + 1;
1629 * Extract branch name from command line arguments, so
1630 * all that is left is pathspecs.
1634 * 1) git checkout <tree> -- [<paths>]
1635 * 2) git checkout -- [<paths>]
1636 * 3) git checkout <something> [<paths>]
1638 * including "last branch" syntax and DWIM-ery for names of
1639 * remote branches, erroring out for invalid or ambiguous cases.
1641 if (argc && opts->accept_ref) {
1642 struct object_id rev;
1644 !opts->patch_mode &&
1645 opts->dwim_new_local_branch &&
1646 opts->track == BRANCH_TRACK_UNSPECIFIED &&
1648 int n = parse_branchname_arg(argc, argv, dwim_ok,
1649 &new_branch_info, opts, &rev);
1652 } else if (!opts->accept_ref && opts->from_treeish) {
1653 struct object_id rev;
1655 if (get_oid_mb(opts->from_treeish, &rev))
1656 die(_("could not resolve %s"), opts->from_treeish);
1658 setup_new_branch_info_and_source_tree(&new_branch_info,
1660 opts->from_treeish);
1662 if (!opts->source_tree)
1663 die(_("reference is not a tree: %s"), opts->from_treeish);
1667 parse_pathspec(&opts->pathspec, 0,
1668 opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
1671 if (!opts->pathspec.nr)
1672 die(_("invalid path specification"));
1675 * Try to give more helpful suggestion.
1676 * new_branch && argc > 1 will be caught later.
1678 if (opts->new_branch && argc == 1)
1679 die(_("'%s' is not a commit and a branch '%s' cannot be created from it"),
1680 argv[0], opts->new_branch);
1682 if (opts->force_detach)
1683 die(_("git checkout: --detach does not take a path argument '%s'"),
1687 if (opts->pathspec_from_file) {
1688 if (opts->pathspec.nr)
1689 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1691 if (opts->force_detach)
1692 die(_("--pathspec-from-file is incompatible with --detach"));
1694 if (opts->patch_mode)
1695 die(_("--pathspec-from-file is incompatible with --patch"));
1697 parse_pathspec_file(&opts->pathspec, 0,
1699 prefix, opts->pathspec_from_file, opts->pathspec_file_nul);
1700 } else if (opts->pathspec_file_nul) {
1701 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1704 if (opts->pathspec.nr) {
1705 if (1 < !!opts->writeout_stage + !!opts->force + !!opts->merge)
1706 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\n"
1707 "checking out of the index."));
1709 if (opts->accept_pathspec && !opts->empty_pathspec_ok &&
1710 !opts->patch_mode) /* patch mode is special */
1711 die(_("you must specify path(s) to restore"));
1714 if (opts->new_branch) {
1715 struct strbuf buf = STRBUF_INIT;
1717 if (opts->new_branch_force)
1718 opts->branch_exists = validate_branchname(opts->new_branch, &buf);
1720 opts->branch_exists =
1721 validate_new_branchname(opts->new_branch, &buf, 0);
1722 strbuf_release(&buf);
1726 if (opts->patch_mode || opts->pathspec.nr)
1727 return checkout_paths(opts, &new_branch_info);
1729 return checkout_branch(opts, &new_branch_info);
1732 int cmd_checkout(int argc, const char **argv, const char *prefix)
1734 struct checkout_opts opts;
1735 struct option *options;
1736 struct option checkout_options[] = {
1737 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
1738 N_("create and checkout a new branch")),
1739 OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
1740 N_("create/reset and checkout a branch")),
1741 OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
1742 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1743 N_("second guess 'git checkout <no-such-branch>' (default)")),
1744 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
1749 memset(&opts, 0, sizeof(opts));
1750 opts.dwim_new_local_branch = 1;
1751 opts.switch_branch_doing_nothing_is_ok = 1;
1752 opts.only_merge_on_switching_branches = 0;
1753 opts.accept_ref = 1;
1754 opts.accept_pathspec = 1;
1755 opts.implicit_detach = 1;
1756 opts.can_switch_when_in_progress = 1;
1757 opts.orphan_from_empty_tree = 0;
1758 opts.empty_pathspec_ok = 1;
1759 opts.overlay_mode = -1;
1760 opts.checkout_index = -2; /* default on */
1761 opts.checkout_worktree = -2; /* default on */
1763 if (argc == 3 && !strcmp(argv[1], "-b")) {
1765 * User ran 'git checkout -b <branch>' and expects
1766 * the same behavior as 'git switch -c <branch>'.
1768 opts.switch_branch_doing_nothing_is_ok = 0;
1769 opts.only_merge_on_switching_branches = 1;
1772 options = parse_options_dup(checkout_options);
1773 options = add_common_options(&opts, options);
1774 options = add_common_switch_branch_options(&opts, options);
1775 options = add_checkout_path_options(&opts, options);
1777 ret = checkout_main(argc, argv, prefix, &opts,
1778 options, checkout_usage);
1779 FREE_AND_NULL(options);
1783 int cmd_switch(int argc, const char **argv, const char *prefix)
1785 struct checkout_opts opts;
1786 struct option *options = NULL;
1787 struct option switch_options[] = {
1788 OPT_STRING('c', "create", &opts.new_branch, N_("branch"),
1789 N_("create and switch to a new branch")),
1790 OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
1791 N_("create/reset and switch to a branch")),
1792 OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
1793 N_("second guess 'git switch <no-such-branch>'")),
1794 OPT_BOOL(0, "discard-changes", &opts.discard_changes,
1795 N_("throw away local modifications")),
1800 memset(&opts, 0, sizeof(opts));
1801 opts.dwim_new_local_branch = 1;
1802 opts.accept_ref = 1;
1803 opts.accept_pathspec = 0;
1804 opts.switch_branch_doing_nothing_is_ok = 0;
1805 opts.only_merge_on_switching_branches = 1;
1806 opts.implicit_detach = 0;
1807 opts.can_switch_when_in_progress = 0;
1808 opts.orphan_from_empty_tree = 1;
1809 opts.overlay_mode = -1;
1811 options = parse_options_dup(switch_options);
1812 options = add_common_options(&opts, options);
1813 options = add_common_switch_branch_options(&opts, options);
1815 ret = checkout_main(argc, argv, prefix, &opts,
1816 options, switch_branch_usage);
1817 FREE_AND_NULL(options);
1821 int cmd_restore(int argc, const char **argv, const char *prefix)
1823 struct checkout_opts opts;
1824 struct option *options;
1825 struct option restore_options[] = {
1826 OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
1827 N_("which tree-ish to checkout from")),
1828 OPT_BOOL('S', "staged", &opts.checkout_index,
1829 N_("restore the index")),
1830 OPT_BOOL('W', "worktree", &opts.checkout_worktree,
1831 N_("restore the working tree (default)")),
1832 OPT_BOOL(0, "ignore-unmerged", &opts.ignore_unmerged,
1833 N_("ignore unmerged entries")),
1834 OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
1839 memset(&opts, 0, sizeof(opts));
1840 opts.accept_ref = 0;
1841 opts.accept_pathspec = 1;
1842 opts.empty_pathspec_ok = 0;
1843 opts.overlay_mode = 0;
1844 opts.checkout_index = -1; /* default off */
1845 opts.checkout_worktree = -2; /* default on */
1846 opts.ignore_unmerged_opt = "--ignore-unmerged";
1848 options = parse_options_dup(restore_options);
1849 options = add_common_options(&opts, options);
1850 options = add_checkout_path_options(&opts, options);
1852 ret = checkout_main(argc, argv, prefix, &opts,
1853 options, restore_usage);
1854 FREE_AND_NULL(options);