"git checkout <commit>" will checkout the commit in question and
detach HEAD from the current branch. It is naturally a right thing to
do once you get git references. But detached HEAD is a scary concept
to new users because we show a lot of warnings and stuff, and it could
be hard to get out of (until you know better).

To keep switch a bit more friendly to new users, we only allow
entering detached HEAD mode when --detach is given. "git
switch" must take a branch (unless you create a new branch,
then of course switch can take any commit-ish)

Signed-off-by: Nguyễn Thái Ngọc Duy <pclo...@gmail.com>
---
 builtin/checkout.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/builtin/checkout.c b/builtin/checkout.c
index 9a58fccd71..69df3a1547 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -44,6 +44,7 @@ struct checkout_opts {
        int merge;
        int force;
        int force_detach;
+       int implicit_detach;
        int writeout_stage;
        int overwrite_ignore;
        int ignore_skipworktree;
@@ -1326,6 +1327,14 @@ static int checkout_branch(struct checkout_opts *opts,
            !opts->force_detach)
                die(_("nothing to do"));
 
+       if (!opts->implicit_detach &&
+           !opts->force_detach &&
+           !opts->new_branch &&
+           !opts->new_branch_force &&
+           new_branch_info->name &&
+           !new_branch_info->path)
+               die(_("a branch is expected, got %s"), new_branch_info->name);
+
        if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
            !opts->ignore_other_worktrees) {
                int flag;
@@ -1581,6 +1590,7 @@ int cmd_checkout(int argc, const char **argv, const char 
*prefix)
        opts.no_dwim_new_local_branch = 0;
        opts.switch_branch_doing_nothing_is_ok = 1;
        opts.accept_pathspec = 1;
+       opts.implicit_detach = 1;
 
        options = parse_options_dup(checkout_options);
        options = add_common_options(&opts, options);
@@ -1610,6 +1620,7 @@ int cmd_switch(int argc, const char **argv, const char 
*prefix)
        opts.no_dwim_new_local_branch = 0;
        opts.accept_pathspec = 0;
        opts.switch_branch_doing_nothing_is_ok = 0;
+       opts.implicit_detach = 0;
 
        options = parse_options_dup(switch_options);
        options = add_common_options(&opts, options);
-- 
2.20.1.682.gd5861c6d90

Reply via email to