From ba96587f56746c8ff8a88d1be618db854c9098c9 Mon Sep 17 00:00:00 2001 From: devinnwang Date: Tue, 25 Oct 2022 14:14:04 +0800 Subject: [PATCH] Fix:(issue_1548) Check root before run default cmd --- command.go | 2 +- command_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/command.go b/command.go index a63048d..c5939d4 100644 --- a/command.go +++ b/command.go @@ -252,7 +252,7 @@ func (c *Command) Run(cCtx *Context, arguments ...string) (err error) { } } } - } else if cCtx.App.DefaultCommand != "" { + } else if c.isRoot && cCtx.App.DefaultCommand != "" { if dc := cCtx.App.Command(cCtx.App.DefaultCommand); dc != c { cmd = dc } diff --git a/command_test.go b/command_test.go index fad6c07..478c325 100644 --- a/command_test.go +++ b/command_test.go @@ -485,3 +485,33 @@ func TestCommand_VisibleFlagCategories(t *testing.T) { t.Errorf("unexpected flag %+v", fl.Names()) } } + +func TestCommand_RunSubcommandWithDefault(t *testing.T) { + app := &App{ + Version: "some version", + Name: "app", + DefaultCommand: "foo", + Commands: []*Command{ + { + Name: "foo", + Action: func(ctx *Context) error { + return errors.New("should not run this subcommand") + }, + }, + { + Name: "bar", + Usage: "this is for testing", + Subcommands: []*Command{{}}, // some subcommand + Action: func(*Context) error { + return nil + }, + }, + }, + } + + err := app.Run([]string{"app", "bar"}) + expect(t, err, nil) + + err = app.Run([]string{"app"}) + expect(t, err, errors.New("should not run this subcommand")) +}