restore: default to --source=HEAD when only --staged is specified
[gitweb.git] / builtin / checkout.c
index 11308ab80c650a5a9f5d24cc304726e321202680..09a03f1ff874683d02fc3deb1608a29e310149b1 100644 (file)
 #include "tree.h"
 #include "tree-walk.h"
 #include "unpack-trees.h"
+#include "wt-status.h"
 #include "xdiff-interface.h"
 
-static int checkout_optimize_new_branch;
-
 static const char * const checkout_usage[] = {
        N_("git checkout [<options>] <branch>"),
        N_("git checkout [<options>] [<branch>] -- <file>..."),
@@ -39,6 +38,11 @@ static const char * const switch_branch_usage[] = {
        NULL,
 };
 
+static const char * const restore_usage[] = {
+       N_("git restore [<options>] [--source=<branch>] <file>..."),
+       NULL,
+};
+
 struct checkout_opts {
        int patch_mode;
        int quiet;
@@ -53,15 +57,17 @@ struct checkout_opts {
        int show_progress;
        int count_checkout_paths;
        int overlay_mode;
-       int no_dwim_new_local_branch;
+       int dwim_new_local_branch;
        int discard_changes;
+       int accept_ref;
        int accept_pathspec;
        int switch_branch_doing_nothing_is_ok;
-
-       /*
-        * If new checkout options are added, skip_merge_working_tree
-        * should be updated accordingly.
-        */
+       int only_merge_on_switching_branches;
+       int can_switch_when_in_progress;
+       int orphan_from_empty_tree;
+       int empty_pathspec_ok;
+       int checkout_index;
+       int checkout_worktree;
 
        const char *new_branch;
        const char *new_branch_force;
@@ -74,6 +80,7 @@ struct checkout_opts {
        int branch_exists;
        const char *prefix;
        struct pathspec pathspec;
+       const char *from_treeish;
        struct tree *source_tree;
 };
 
@@ -325,17 +332,74 @@ static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
        }
 }
 
+static int checkout_worktree(const struct checkout_opts *opts)
+{
+       struct checkout state = CHECKOUT_INIT;
+       int nr_checkouts = 0, nr_unmerged = 0;
+       int errs = 0;
+       int pos;
+
+       state.force = 1;
+       state.refresh_cache = 1;
+       state.istate = &the_index;
+
+       enable_delayed_checkout(&state);
+       for (pos = 0; pos < active_nr; pos++) {
+               struct cache_entry *ce = active_cache[pos];
+               if (ce->ce_flags & CE_MATCHED) {
+                       if (!ce_stage(ce)) {
+                               errs |= checkout_entry(ce, &state,
+                                                      NULL, &nr_checkouts);
+                               continue;
+                       }
+                       if (opts->writeout_stage)
+                               errs |= checkout_stage(opts->writeout_stage,
+                                                      ce, pos,
+                                                      &state,
+                                                      &nr_checkouts, opts->overlay_mode);
+                       else if (opts->merge)
+                               errs |= checkout_merged(pos, &state,
+                                                       &nr_unmerged);
+                       pos = skip_same_name(ce, pos) - 1;
+               }
+       }
+       remove_marked_cache_entries(&the_index, 1);
+       remove_scheduled_dirs();
+       errs |= finish_delayed_checkout(&state, &nr_checkouts);
+
+       if (opts->count_checkout_paths) {
+               if (nr_unmerged)
+                       fprintf_ln(stderr, Q_("Recreated %d merge conflict",
+                                             "Recreated %d merge conflicts",
+                                             nr_unmerged),
+                                  nr_unmerged);
+               if (opts->source_tree)
+                       fprintf_ln(stderr, Q_("Updated %d path from %s",
+                                             "Updated %d paths from %s",
+                                             nr_checkouts),
+                                  nr_checkouts,
+                                  find_unique_abbrev(&opts->source_tree->object.oid,
+                                                     DEFAULT_ABBREV));
+               else if (!nr_unmerged || nr_checkouts)
+                       fprintf_ln(stderr, Q_("Updated %d path from the index",
+                                             "Updated %d paths from the index",
+                                             nr_checkouts),
+                                  nr_checkouts);
+       }
+
+       return errs;
+}
+
 static int checkout_paths(const struct checkout_opts *opts,
                          const char *revision)
 {
        int pos;
-       struct checkout state = CHECKOUT_INIT;
        static char *ps_matched;
        struct object_id rev;
        struct commit *head;
        int errs = 0;
        struct lock_file lock_file = LOCK_INIT;
-       int nr_checkouts = 0, nr_unmerged = 0;
+       int checkout_index;
 
        trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
 
@@ -361,9 +425,36 @@ static int checkout_paths(const struct checkout_opts *opts,
                die(_("Cannot update paths and switch to branch '%s' at the same time."),
                    opts->new_branch);
 
-       if (opts->patch_mode)
-               return run_add_interactive(revision, "--patch=checkout",
-                                          &opts->pathspec);
+       if (!opts->checkout_worktree && !opts->checkout_index)
+               die(_("neither '%s' or '%s' is specified"),
+                   "--staged", "--worktree");
+
+       if (!opts->checkout_worktree && !opts->from_treeish)
+               die(_("'%s' must be used when '%s' is not specified"),
+                   "--worktree", "--source");
+
+       if (opts->checkout_index && !opts->checkout_worktree &&
+           opts->writeout_stage)
+               die(_("'%s' or '%s' cannot be used with %s"),
+                   "--ours", "--theirs", "--staged");
+
+       if (opts->checkout_index && !opts->checkout_worktree &&
+           opts->merge)
+               die(_("'%s' or '%s' cannot be used with %s"),
+                   "--merge", "--conflict", "--staged");
+
+       if (opts->patch_mode) {
+               const char *patch_mode;
+
+               if (opts->checkout_index && opts->checkout_worktree)
+                       patch_mode = "--patch=checkout";
+               else if (opts->checkout_index && !opts->checkout_worktree)
+                       patch_mode = "--patch=reset";
+               else
+                       die(_("'%s' with only '%s' is not currently supported"),
+                           "--patch", "--worktree");
+               return run_add_interactive(revision, patch_mode, &opts->pathspec);
+       }
 
        repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
        if (read_cache_preload(&opts->pathspec) < 0)
@@ -421,57 +512,31 @@ static int checkout_paths(const struct checkout_opts *opts,
                return 1;
 
        /* Now we are committed to check them out */
-       state.force = 1;
-       state.refresh_cache = 1;
-       state.istate = &the_index;
+       if (opts->checkout_worktree)
+               errs |= checkout_worktree(opts);
 
-       enable_delayed_checkout(&state);
-       for (pos = 0; pos < active_nr; pos++) {
-               struct cache_entry *ce = active_cache[pos];
-               if (ce->ce_flags & CE_MATCHED) {
-                       if (!ce_stage(ce)) {
-                               errs |= checkout_entry(ce, &state,
-                                                      NULL, &nr_checkouts);
-                               continue;
-                       }
-                       if (opts->writeout_stage)
-                               errs |= checkout_stage(opts->writeout_stage,
-                                                      ce, pos,
-                                                      &state,
-                                                      &nr_checkouts, opts->overlay_mode);
-                       else if (opts->merge)
-                               errs |= checkout_merged(pos, &state,
-                                                       &nr_unmerged);
-                       pos = skip_same_name(ce, pos) - 1;
-               }
-       }
-       remove_marked_cache_entries(&the_index, 1);
-       remove_scheduled_dirs();
-       errs |= finish_delayed_checkout(&state, &nr_checkouts);
+       /*
+        * Allow updating the index when checking out from the index.
+        * This is to save new stat info.
+        */
+       if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
+               checkout_index = 1;
+       else
+               checkout_index = opts->checkout_index;
 
-       if (opts->count_checkout_paths) {
-               if (nr_unmerged)
-                       fprintf_ln(stderr, Q_("Recreated %d merge conflict",
-                                             "Recreated %d merge conflicts",
-                                             nr_unmerged),
-                                  nr_unmerged);
-               if (opts->source_tree)
-                       fprintf_ln(stderr, Q_("Updated %d path from %s",
-                                             "Updated %d paths from %s",
-                                             nr_checkouts),
-                                  nr_checkouts,
-                                  find_unique_abbrev(&opts->source_tree->object.oid,
-                                                     DEFAULT_ABBREV));
-               else if (!nr_unmerged || nr_checkouts)
-                       fprintf_ln(stderr, Q_("Updated %d path from the index",
-                                             "Updated %d paths from the index",
-                                             nr_checkouts),
-                                  nr_checkouts);
+       if (checkout_index) {
+               if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
+                       die(_("unable to write new index file"));
+       } else {
+               /*
+                * NEEDSWORK: if --worktree is not specified, we
+                * should save stat info of checked out files in the
+                * index to avoid the next (potentially costly)
+                * refresh. But it's a bit tricker to do...
+                */
+               rollback_lock_file(&lock_file);
        }
 
-       if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
-               die(_("unable to write new index file"));
-
        read_ref_full("HEAD", 0, &rev, NULL);
        head = lookup_commit_reference_gently(the_repository, &rev, 1);
 
@@ -565,112 +630,6 @@ static void setup_branch_path(struct branch_info *branch)
        branch->path = strbuf_detach(&buf, NULL);
 }
 
-/*
- * Skip merging the trees, updating the index and working directory if and
- * only if we are creating a new branch via "git checkout -b <new_branch>."
- */
-static int skip_merge_working_tree(const struct checkout_opts *opts,
-       const struct branch_info *old_branch_info,
-       const struct branch_info *new_branch_info)
-{
-       /*
-        * Do the merge if sparse checkout is on and the user has not opted in
-        * to the optimized behavior
-        */
-       if (core_apply_sparse_checkout && !checkout_optimize_new_branch)
-               return 0;
-
-       /*
-        * We must do the merge if we are actually moving to a new commit.
-        */
-       if (!old_branch_info->commit || !new_branch_info->commit ||
-               !oideq(&old_branch_info->commit->object.oid,
-                      &new_branch_info->commit->object.oid))
-               return 0;
-
-       /*
-        * opts->patch_mode cannot be used with switching branches so is
-        * not tested here
-        */
-
-       /*
-        * opts->quiet only impacts output so doesn't require a merge
-        */
-
-       /*
-        * Honor the explicit request for a three-way merge or to throw away
-        * local changes
-        */
-       if (opts->merge || opts->force)
-               return 0;
-
-       /*
-        * --detach is documented as "updating the index and the files in the
-        * working tree" but this optimization skips those steps so fall through
-        * to the regular code path.
-        */
-       if (opts->force_detach)
-               return 0;
-
-       /*
-        * opts->writeout_stage cannot be used with switching branches so is
-        * not tested here
-        */
-
-       /*
-        * Honor the explicit ignore requests
-        */
-       if (!opts->overwrite_ignore || opts->ignore_skipworktree ||
-               opts->ignore_other_worktrees)
-               return 0;
-
-       /*
-        * opts->show_progress only impacts output so doesn't require a merge
-        */
-
-       /*
-        * opts->overlay_mode cannot be used with switching branches so is
-        * not tested here
-        */
-
-       /*
-        * If we aren't creating a new branch any changes or updates will
-        * happen in the existing branch.  Since that could only be updating
-        * the index and working directory, we don't want to skip those steps
-        * or we've defeated any purpose in running the command.
-        */
-       if (!opts->new_branch)
-               return 0;
-
-       /*
-        * new_branch_force is defined to "create/reset and checkout a branch"
-        * so needs to go through the merge to do the reset
-        */
-       if (opts->new_branch_force)
-               return 0;
-
-       /*
-        * A new orphaned branch requrires the index and the working tree to be
-        * adjusted to <start_point>
-        */
-       if (opts->new_orphan_branch)
-               return 0;
-
-       /*
-        * Remaining variables are not checkout options but used to track state
-        */
-
-        /*
-         * Do the merge if this is the initial checkout. We cannot use
-         * is_cache_unborn() here because the index hasn't been loaded yet
-         * so cache_nr and timestamp.sec are always zero.
-         */
-       if (!file_exists(get_index_file()))
-               return 0;
-
-       return 1;
-}
-
 static int merge_working_tree(const struct checkout_opts *opts,
                              struct branch_info *old_branch_info,
                              struct branch_info *new_branch_info,
@@ -678,15 +637,21 @@ static int merge_working_tree(const struct checkout_opts *opts,
 {
        int ret;
        struct lock_file lock_file = LOCK_INIT;
+       struct tree *new_tree;
 
        hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
        if (read_cache_preload(NULL) < 0)
                return error(_("index file corrupt"));
 
        resolve_undo_clear();
+       if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
+               if (new_branch_info->commit)
+                       BUG("'switch --orphan' should never accept a commit as starting point");
+               new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
+       } else
+               new_tree = get_commit_tree(new_branch_info->commit);
        if (opts->discard_changes) {
-               ret = reset_tree(get_commit_tree(new_branch_info->commit),
-                                opts, 1, writeout_error);
+               ret = reset_tree(new_tree, opts, 1, writeout_error);
                if (ret)
                        return ret;
        } else {
@@ -724,7 +689,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
                                           &old_branch_info->commit->object.oid :
                                           the_hash_algo->empty_tree);
                init_tree_desc(&trees[0], tree->buffer, tree->size);
-               tree = parse_tree_indirect(&new_branch_info->commit->object.oid);
+               parse_tree(new_tree);
+               tree = new_tree;
                init_tree_desc(&trees[1], tree->buffer, tree->size);
 
                ret = unpack_trees(2, trees, &topts);
@@ -773,7 +739,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
                        o.verbosity = 0;
                        work = write_tree_from_memory(&o);
 
-                       ret = reset_tree(get_commit_tree(new_branch_info->commit),
+                       ret = reset_tree(new_tree,
                                         opts, 1,
                                         writeout_error);
                        if (ret)
@@ -782,13 +748,13 @@ static int merge_working_tree(const struct checkout_opts *opts,
                        o.branch1 = new_branch_info->name;
                        o.branch2 = "local";
                        ret = merge_trees(&o,
-                                         get_commit_tree(new_branch_info->commit),
+                                         new_tree,
                                          work,
                                          get_commit_tree(old_branch_info->commit),
                                          &result);
                        if (ret < 0)
                                exit(128);
-                       ret = reset_tree(get_commit_tree(new_branch_info->commit),
+                       ret = reset_tree(new_tree,
                                         opts, 0,
                                         writeout_error);
                        strbuf_release(&o.obuf);
@@ -806,7 +772,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
        if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
                die(_("unable to write new index file"));
 
-       if (!opts->discard_changes && !opts->quiet)
+       if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
                show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
 
        return 0;
@@ -1007,7 +973,10 @@ static void orphaned_commit_warning(struct commit *old_commit, struct commit *ne
        add_pending_object(&revs, object, oid_to_hex(&object->oid));
 
        for_each_ref(add_pending_uninteresting_ref, &revs);
-       add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
+       if (new_commit)
+               add_pending_oid(&revs, "HEAD",
+                               &new_commit->object.oid,
+                               UNINTERESTING);
 
        if (prepare_revision_walk(&revs))
                die(_("internal error in revision walk"));
@@ -1028,6 +997,7 @@ static int switch_branches(const struct checkout_opts *opts,
        void *path_to_free;
        struct object_id rev;
        int flag, writeout_error = 0;
+       int do_merge = 1;
 
        trace2_cmd_mode("branch");
 
@@ -1041,22 +1011,26 @@ static int switch_branches(const struct checkout_opts *opts,
        if (old_branch_info.path)
                skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
 
+       if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
+               if (new_branch_info->name)
+                       BUG("'switch --orphan' should never accept a commit as starting point");
+               new_branch_info->commit = NULL;
+               new_branch_info->name = "(empty)";
+               do_merge = 1;
+       }
+
        if (!new_branch_info->name) {
                new_branch_info->name = "HEAD";
                new_branch_info->commit = old_branch_info.commit;
                if (!new_branch_info->commit)
                        die(_("You are on a branch yet to be born"));
                parse_commit_or_die(new_branch_info->commit);
+
+               if (opts->only_merge_on_switching_branches)
+                       do_merge = 0;
        }
 
-       /* optimize the "checkout -b <new_branch> path */
-       if (skip_merge_working_tree(opts, &old_branch_info, new_branch_info)) {
-               if (!checkout_optimize_new_branch && !opts->quiet) {
-                       if (read_cache_preload(NULL) < 0)
-                               return error(_("index file corrupt"));
-                       show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
-               }
-       } else {
+       if (do_merge) {
                ret = merge_working_tree(opts, &old_branch_info, new_branch_info, &writeout_error);
                if (ret) {
                        free(path_to_free);
@@ -1076,11 +1050,6 @@ static int switch_branches(const struct checkout_opts *opts,
 
 static int git_checkout_config(const char *var, const char *value, void *cb)
 {
-       if (!strcmp(var, "checkout.optimizenewbranch")) {
-               checkout_optimize_new_branch = git_config_bool(var, value);
-               return 0;
-       }
-
        if (!strcmp(var, "diff.ignoresubmodules")) {
                struct checkout_opts *opts = cb;
                handle_ignore_submodules_arg(&opts->diff_options, value);
@@ -1322,6 +1291,39 @@ static void die_expecting_a_branch(const struct branch_info *branch_info)
        die(_("a branch is expected, got '%s'"), branch_info->name);
 }
 
+static void die_if_some_operation_in_progress(void)
+{
+       struct wt_status_state state;
+
+       memset(&state, 0, sizeof(state));
+       wt_status_get_state(the_repository, &state, 0);
+
+       if (state.merge_in_progress)
+               die(_("cannot switch branch while merging\n"
+                     "Consider \"git merge --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.am_in_progress)
+               die(_("cannot switch branch in the middle of an am session\n"
+                     "Consider \"git am --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.rebase_interactive_in_progress || state.rebase_in_progress)
+               die(_("cannot switch branch while rebasing\n"
+                     "Consider \"git rebase --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.cherry_pick_in_progress)
+               die(_("cannot switch branch while cherry-picking\n"
+                     "Consider \"git cherry-pick --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.revert_in_progress)
+               die(_("cannot switch branch while reverting\n"
+                     "Consider \"git revert --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.bisect_in_progress)
+               die(_("cannot switch branch while bisecting\n"
+                     "Consider \"git bisect reset HEAD\" "
+                     "or \"git worktree add\"."));
+}
+
 static int checkout_branch(struct checkout_opts *opts,
                           struct branch_info *new_branch_info)
 {
@@ -1332,9 +1334,9 @@ static int checkout_branch(struct checkout_opts *opts,
                die(_("'%s' cannot be used with switching branches"),
                    "--patch");
 
-       if (!opts->overlay_mode)
+       if (opts->overlay_mode != -1)
                die(_("'%s' cannot be used with switching branches"),
-                   "--no-overlay");
+                   "--[no]-overlay");
 
        if (opts->writeout_stage)
                die(_("'%s' cannot be used with switching branches"),
@@ -1353,6 +1355,8 @@ static int checkout_branch(struct checkout_opts *opts,
        if (opts->new_orphan_branch) {
                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
                        die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
+               if (opts->orphan_from_empty_tree && new_branch_info->name)
+                       die(_("'%s' cannot take <start-point>"), "--orphan");
        } else if (opts->force_detach) {
                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
                        die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
@@ -1377,6 +1381,9 @@ static int checkout_branch(struct checkout_opts *opts,
            !new_branch_info->path)
                die_expecting_a_branch(new_branch_info);
 
+       if (!opts->can_switch_when_in_progress)
+               die_if_some_operation_in_progress();
+
        if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
            !opts->ignore_other_worktrees) {
                int flag;
@@ -1430,8 +1437,6 @@ static struct option *add_common_switch_branch_options(
                OPT_BOOL_F(0, "overwrite-ignore", &opts->overwrite_ignore,
                           N_("update ignored files (default)"),
                           PARSE_OPT_NOCOMPLETE),
-               OPT_BOOL(0, "no-guess", &opts->no_dwim_new_local_branch,
-                        N_("second guess 'git checkout <no-such-branch>'")),
                OPT_BOOL(0, "ignore-other-worktrees", &opts->ignore_other_worktrees,
                         N_("do not check if another worktree is holding the given ref")),
                OPT_END()
@@ -1454,7 +1459,6 @@ static struct option *add_checkout_path_options(struct checkout_opts *opts,
                OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
                OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
                         N_("do not limit pathspecs to sparse entries only")),
-               OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
                OPT_END()
        };
        struct option *newopts = parse_options_concat(prevopts, options);
@@ -1468,22 +1472,25 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 {
        struct branch_info new_branch_info;
        int dwim_remotes_matched = 0;
-       int dwim_new_local_branch;
+       int parseopt_flags = 0;
 
        memset(&new_branch_info, 0, sizeof(new_branch_info));
        opts->overwrite_ignore = 1;
        opts->prefix = prefix;
        opts->show_progress = -1;
-       opts->overlay_mode = -1;
 
        git_config(git_checkout_config, opts);
 
        opts->track = BRANCH_TRACK_UNSPECIFIED;
 
-       argc = parse_options(argc, argv, prefix, options, usagestr,
-                            PARSE_OPT_KEEP_DASHDASH);
+       if (!opts->accept_pathspec && !opts->accept_ref)
+               BUG("make up your mind, you need to take _something_");
+       if (opts->accept_pathspec && opts->accept_ref)
+               parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
+
+       argc = parse_options(argc, argv, prefix, options,
+                            usagestr, parseopt_flags);
 
-       dwim_new_local_branch = !opts->no_dwim_new_local_branch;
        if (opts->show_progress < 0) {
                if (opts->quiet)
                        opts->show_progress = 0;
@@ -1504,6 +1511,26 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
        if (opts->overlay_mode == 1 && opts->patch_mode)
                die(_("-p and --overlay are mutually exclusive"));
 
+       if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
+               if (opts->checkout_index < 0)
+                       opts->checkout_index = 0;
+               if (opts->checkout_worktree < 0)
+                       opts->checkout_worktree = 0;
+       } else {
+               if (opts->checkout_index < 0)
+                       opts->checkout_index = -opts->checkout_index - 1;
+               if (opts->checkout_worktree < 0)
+                       opts->checkout_worktree = -opts->checkout_worktree - 1;
+       }
+       if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
+               BUG("these flags should be non-negative by now");
+       /*
+        * convenient shortcut: "git restore --staged" equals
+        * "git restore --staged --source HEAD"
+        */
+       if (!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)
+               opts->from_treeish = "HEAD";
+
        /*
         * From here on, new_branch will contain the branch to be checked out,
         * and new_branch_force and new_orphan_branch will tell us which one of
@@ -1541,11 +1568,11 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
         * including "last branch" syntax and DWIM-ery for names of
         * remote branches, erroring out for invalid or ambiguous cases.
         */
-       if (argc) {
+       if (argc && opts->accept_ref) {
                struct object_id rev;
                int dwim_ok =
                        !opts->patch_mode &&
-                       dwim_new_local_branch &&
+                       opts->dwim_new_local_branch &&
                        opts->track == BRANCH_TRACK_UNSPECIFIED &&
                        !opts->new_branch;
                int n = parse_branchname_arg(argc, argv, dwim_ok,
@@ -1553,8 +1580,24 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
                                             &dwim_remotes_matched);
                argv += n;
                argc -= n;
+       } else if (!opts->accept_ref && opts->from_treeish) {
+               struct object_id rev;
+
+               if (get_oid_mb(opts->from_treeish, &rev))
+                       die(_("could not resolve %s"), opts->from_treeish);
+
+               setup_new_branch_info_and_source_tree(&new_branch_info,
+                                                     opts, &rev,
+                                                     opts->from_treeish);
+
+               if (!opts->source_tree)
+                       die(_("reference is not a tree: %s"), opts->from_treeish);
        }
 
+       if (opts->accept_pathspec && !opts->empty_pathspec_ok && !argc &&
+           !opts->patch_mode)  /* patch mode is special */
+               die(_("you must specify path(s) to restore"));
+
        if (argc) {
                parse_pathspec(&opts->pathspec, 0,
                               opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
@@ -1626,15 +1669,26 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
                OPT_STRING('B', NULL, &opts.new_branch_force, N_("branch"),
                           N_("create/reset and checkout a branch")),
                OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
+               OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+                        N_("second guess 'git checkout <no-such-branch>' (default)")),
+               OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
                OPT_END()
        };
        int ret;
 
        memset(&opts, 0, sizeof(opts));
-       opts.no_dwim_new_local_branch = 0;
+       opts.dwim_new_local_branch = 1;
        opts.switch_branch_doing_nothing_is_ok = 1;
+       opts.only_merge_on_switching_branches = 0;
+       opts.accept_ref = 1;
        opts.accept_pathspec = 1;
        opts.implicit_detach = 1;
+       opts.can_switch_when_in_progress = 1;
+       opts.orphan_from_empty_tree = 0;
+       opts.empty_pathspec_ok = 1;
+       opts.overlay_mode = -1;
+       opts.checkout_index = -2;    /* default on */
+       opts.checkout_worktree = -2; /* default on */
 
        options = parse_options_dup(checkout_options);
        options = add_common_options(&opts, options);
@@ -1656,6 +1710,8 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
                           N_("create and switch to a new branch")),
                OPT_STRING('C', "force-create", &opts.new_branch_force, N_("branch"),
                           N_("create/reset and switch to a branch")),
+               OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
+                        N_("second guess 'git switch <no-such-branch>'")),
                OPT_BOOL(0, "discard-changes", &opts.discard_changes,
                         N_("throw away local modifications")),
                OPT_END()
@@ -1663,10 +1719,15 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
        int ret;
 
        memset(&opts, 0, sizeof(opts));
-       opts.no_dwim_new_local_branch = 0;
+       opts.dwim_new_local_branch = 1;
+       opts.accept_ref = 1;
        opts.accept_pathspec = 0;
        opts.switch_branch_doing_nothing_is_ok = 0;
+       opts.only_merge_on_switching_branches = 1;
        opts.implicit_detach = 0;
+       opts.can_switch_when_in_progress = 0;
+       opts.orphan_from_empty_tree = 1;
+       opts.overlay_mode = -1;
 
        options = parse_options_dup(switch_options);
        options = add_common_options(&opts, options);
@@ -1677,3 +1738,37 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
        FREE_AND_NULL(options);
        return ret;
 }
+
+int cmd_restore(int argc, const char **argv, const char *prefix)
+{
+       struct checkout_opts opts;
+       struct option *options;
+       struct option restore_options[] = {
+               OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
+                          N_("where the checkout from")),
+               OPT_BOOL('S', "staged", &opts.checkout_index,
+                          N_("restore the index")),
+               OPT_BOOL('W', "worktree", &opts.checkout_worktree,
+                          N_("restore the working tree (default)")),
+               OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
+               OPT_END()
+       };
+       int ret;
+
+       memset(&opts, 0, sizeof(opts));
+       opts.accept_ref = 0;
+       opts.accept_pathspec = 1;
+       opts.empty_pathspec_ok = 0;
+       opts.overlay_mode = 0;
+       opts.checkout_index = -1;    /* default off */
+       opts.checkout_worktree = -2; /* default on */
+
+       options = parse_options_dup(restore_options);
+       options = add_common_options(&opts, options);
+       options = add_checkout_path_options(&opts, options);
+
+       ret = checkout_main(argc, argv, prefix, &opts,
+                           options, restore_usage);
+       FREE_AND_NULL(options);
+       return ret;
+}