Skip to content

Commit

Permalink
refactor(xmd): add SetExecuterAsUsage
Browse files Browse the repository at this point in the history
  • Loading branch information
hui.wang committed Jan 25, 2022
1 parent 2a8c8eb commit b45626c
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 2 deletions.
12 changes: 12 additions & 0 deletions xcmd/commander.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,18 @@ func (c *Command) BindFieldPathReomove(filePath ...string) *Command {
return c
}

// SetExecuterAsUsage 设定Executer为Usage,一般不用设定,不设定默认为Executer为Usage
// driveCmd := xcmd.NewCommand("drive").SetExecuterAsUsage()
// 希望driveCmd的后续子命令都绑定到cc但是driveCmd本身不绑定,此时主动设定driveCmd.SetExecuterAsUsage会切断driveCmd后续pre middleware与Executer的关系
// driveCmd.UsePre(func(ctx context.Context, cmd *xcmd.Command, next xcmd.Executer) error {
// cmd.BindSet(cc)
// cmd.BindFieldPathSet("drive_token", "permission", "credentials")
// return next(ctx, cmd)
// })
func (c *Command) SetExecuterAsUsage() *Command {
return c.SetExecuter(usageExecuter)
}

// SetExecuter 设定新的Executer,会缓存此时的中间件,只有此时缓存的中间件会被应用到Executer,如果Executer为nil,则所有的中间件都会被应用到默认的Executer
func (c *Command) SetExecuter(executer Executer) *Command {
c.executer = executer
Expand Down
3 changes: 3 additions & 0 deletions xcmd/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ func BindFieldPathReomove(filePath ...string) *Command {
return rootCmd.BindFieldPathReomove(filePath...)
}

// SetExecuterAsUsage 设定Executer为Usage打印帮助信息
func SetExecuterAsUsage() *Command { return rootCmd.SetExecuterAsUsage() }

// SetExecuter 设定新的Executer,会缓存此时的中间件,只有此时缓存的中间件会被应用到Executer,如果Executer为nil,则所有的中间件都会被应用到默认的Executer
func SetExecuter(executer Executer) *Command { return rootCmd.SetExecuter(executer) }

Expand Down
2 changes: 1 addition & 1 deletion xcmd/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
// Executer 命令执行方法
type Executer = func(ctx context.Context, cmd *Command) error

var defaultExecuter = func(ctx context.Context, cmd *Command) error {
var usageExecuter = func(ctx context.Context, cmd *Command) error {
cmd.Usage()
return ErrHelp
}
Expand Down
2 changes: 1 addition & 1 deletion xcmd/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func configOptionDeclareWithDefault() interface{} {
// annotation@Parser(comment="配置解析")
"Parser": MiddlewareFunc(ParserXConf),
// annotation@Executer(comment="当未配置Parser时触发该默认逻辑")
"OnExecuterLost": Executer(defaultExecuter),
"OnExecuterLost": Executer(usageExecuter),
// annotation@SuggestionsMinDistance(comment="推荐命令最低关联长度")
"SuggestionsMinDistance": 2,
// annotation@Output(comment="输出")
Expand Down

0 comments on commit b45626c

Please sign in to comment.