add root tag in matadata of struct to specify the root command function for the object for package gcmd

This commit is contained in:
John Guo 2021-12-02 23:31:06 +08:00
parent b840405af6
commit 26ef8c5872
2 changed files with 62 additions and 5 deletions

View File

@ -24,8 +24,9 @@ import (
)
const (
tagNameDc = `dc`
tagNameAd = `ad`
tagNameDc = `dc`
tagNameAd = `ad`
tagNameRoot = `root`
)
var (
@ -50,8 +51,9 @@ func NewFromObject(object interface{}) (rootCmd Command, err error) {
}
// Sub command creating.
var (
nameSet = gset.NewStrSet()
subCommands []Command
nameSet = gset.NewStrSet()
rootCommandName = gmeta.Get(object, tagNameRoot).String()
subCommands []Command
)
for i := 0; i < originValueAndKind.InputValue.NumMethod(); i++ {
var (
@ -69,7 +71,19 @@ func NewFromObject(object interface{}) (rootCmd Command, err error) {
)
return
}
subCommands = append(subCommands, methodCommand)
if rootCommandName == methodCommand.Name {
if rootCmd.Func == nil {
rootCmd.Func = methodCommand.Func
}
if rootCmd.FuncWithValue == nil {
rootCmd.FuncWithValue = methodCommand.FuncWithValue
}
if len(rootCmd.Options) == 0 {
rootCmd.Options = methodCommand.Options
}
} else {
subCommands = append(subCommands, methodCommand)
}
}
if len(subCommands) > 0 {
err = rootCmd.AddCommand(subCommands...)

View File

@ -96,3 +96,46 @@ func Test_Command_AddObject(t *testing.T) {
t.Assert(value, `{"Content":"john"}`)
})
}
type TestObjectForRootTag struct {
g.Meta `name:"root" root:"root"`
}
type TestObjectForRootTagEnvInput struct {
g.Meta `name:"env" usage:"root env" brief:"root env command" dc:"root env command description" ad:"root env command ad"`
}
type TestObjectForRootTagEnvOutput struct{}
type TestObjectForRootTagTestInput struct {
g.Meta `name:"root"`
Name string `v:"required" short:"n" orphan:"false" brief:"name for test command"`
}
type TestObjectForRootTagTestOutput struct {
Content string
}
func (TestObjectForRootTag) Env(ctx context.Context, in TestObjectForRootTagEnvInput) (out *TestObjectForRootTagEnvOutput, err error) {
return
}
func (TestObjectForRootTag) Root(ctx context.Context, in TestObjectForRootTagTestInput) (out *TestObjectForRootTagTestOutput, err error) {
out = &TestObjectForRootTagTestOutput{
Content: in.Name,
}
return
}
func Test_Command_RootTag(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
ctx = gctx.New()
)
cmd, err := gcmd.NewFromObject(TestObjectForRootTag{})
t.AssertNil(err)
os.Args = []string{"root", "-n=john"}
value, err := cmd.RunWithValue(ctx)
t.AssertNil(err)
t.Assert(value, `{"Content":"john"}`)
})
}