标志:枚举值
Valid Args
枚举值
可以为一个标志设置有效枚举值集合。这样的标志要求用户输入的值必须在有效集合之中。
一般来说,该标志的默认值应该是字符串值,除非预设的代码接受自动转换,转换由标准的 Go 转换接口完成。
定义
.ValidArgs(...) 可以为标志设置用于校验目的的枚举值列表。
package main
import (
"context"
"fmt"
"os"
"gopkg.in/hedzr/errors.v3"
"github.com/hedzr/cmdr/v2"
"github.com/hedzr/cmdr/v2/cli"
"github.com/hedzr/is/term/color"
logz "github.com/hedzr/logg/slog"
)
const (
appName = "valid-args"
desc = `a sample to show u how to using enum values in option.`
version = cmdr.Version
author = ``
)
func main() {
app := cmdr.Create(appName, version, author, desc).
With(func(app cli.App) {}).
WithBuilders(validArgsCommand).
WithAdders().
Build()
ctx := context.Background()
if err := app.Run(ctx); err != nil {
if errors.Is(err, cli.ErrValidArgs) {
fmt.Printf(color.StripLeftTabsC(`
The input is not in valid list:
<font color="red">%s</red>
`),
err)
os.Exit(1)
}
logz.ErrorContext(ctx, "Application Error:", "err", err) // stacktrace if in debug mode/build
os.Exit(app.SuggestRetCode())
} else if rc := app.SuggestRetCode(); rc != 0 {
os.Exit(rc)
}
}
func validArgsCommand(parent cli.CommandBuilder) { //nolint:revive
parent.Flg("enum", "e").
Description("valid args option", "").
Group("Test").
ValidArgs("apple", "banana", "orange").
Default("").
Build()
// give root command an action to handle it
parent.OnAction(func(ctx context.Context, cmd cli.Cmd, args []string) (err error) {
v := cmd.Store().MustString("enum")
println("enum value is: ", v)
return
})
parent.Examples(`Try to use value-args app,
$ $APP -e apple
this command works ok.
$ $APP -e mongo
can't work because valid args are: apple, banana, and orange.
$ $APP --help
check out the valid values in help screen.
`)
}package examples
import (
"github.com/hedzr/cmdr/v2/cli"
)
func AddValidArgsFlag(c cli.CommandBuilder) { //nolint:revive
c.Flg("fruit", "fr").
Default("").
Description("the message.", "").
Group("Valid Args").
PlaceHolder("FRUIT").
ValidArgs("apple", "banana", "orange").
Build()
}运行时
一个运行时未能满足枚举列表要求的反馈如同这样:
$ go run ./examples/valid-args -e mongo
The input is not in valid list:
Flag "Flg{'.enum'}" expects a valid input is in list: [apple banana orange] | cmd=Cmd{''}
exit status 1
$额外的话题
What is Next?
How is this guide?
最后更新于