Go语言 Cobra允许的标志值

jc3wubiy  于 2023-11-14  发布在  Go
关注(0)|答案(3)|浏览(128)

在Cobra库中是否有内置工具(如果有,我如何使用它?)要求标志是几个值之一,如果标志不是允许的值之一,则抛出错误?我在Github页面上没有看到这一点。

um6iljoc

um6iljoc1#

Cobra允许您通过pflag.(*FlagSet).Var()方法(来自Cobra使用的https://github.com/spf13/pflag包)定义自定义值类型用作标志。您必须创建一个实现pflag.Value接口的新类型:

  1. type Value interface {
  2. String() string
  3. Set(string) error
  4. Type() string
  5. }

字符集
示例类型定义:

  1. type myEnum string
  2. const (
  3. myEnumFoo myEnum = "foo"
  4. myEnumBar myEnum = "bar"
  5. myEnumMoo myEnum = "moo"
  6. )
  7. // String is used both by fmt.Print and by Cobra in help text
  8. func (e *myEnum) String() string {
  9. return string(*e)
  10. }
  11. // Set must have pointer receiver so it doesn't change the value of a copy
  12. func (e *myEnum) Set(v string) error {
  13. switch v {
  14. case "foo", "bar", "moo":
  15. *e = myEnum(v)
  16. return nil
  17. default:
  18. return errors.New(`must be one of "foo", "bar", or "moo"`)
  19. }
  20. }
  21. // Type is only used in help text
  22. func (e *myEnum) Type() string {
  23. return "myEnum"
  24. }


注册示例:

  1. func init() {
  2. var flagMyEnum = myEnumFoo
  3. var myCmd = &cobra.Command{
  4. Use: "mycmd",
  5. Short: "A brief description of your command",
  6. Run: func(cmd *cobra.Command, args []string) {
  7. fmt.Println("myenum value:", flagMyEnum)
  8. },
  9. }
  10. rootCmd.AddCommand(myCmd)
  11. myCmd.Flags().Var(&flagMyEnum, "myenum", `my custom enum. allowed: "foo", "bar", "moo"`)
  12. }


示例用法:(注意下面控制台输出中的第一行)

  1. $ go run . mycmd --myenum raz
  2. Error: invalid argument "raz" for "--myenum" flag: must be one of "foo", "bar", or "moo"
  3. Usage:
  4. main mycmd [flags]
  5. Flags:
  6. -h, --help help for mycmd
  7. --myenum myEnum my custom enum. allowed: "foo", "bar", "moo" (default foo)
  8. exit status 1
  1. $ go run . mycmd --myenum bar
  2. myenum value: bar

完成

要添加自动补全功能,可以使用隐藏的文档cobra/shell_completions. md #completions-for-flags。对于我们的示例,您可以添加如下内容:

  1. func init() {
  2. // ...
  3. myCmd.Flags().Var(&flagMyEnum, "myenum", `my custom enum. allowed: "foo", "bar", "moo"`)
  4. myCmd.RegisterFlagCompletionFunc("myenum", myEnumCompletion)
  5. }
  6. // myEnumCompletion should probably live next to the myEnum definition
  7. func myEnumCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  8. return []string{
  9. "foo\thelp text for foo",
  10. "bar\thelp text for bar",
  11. "moo\thelp text for moo",
  12. }, cobra.ShellCompDirectiveDefault
  13. }


示例用法:

  1. $ go build -o main .
  2. $ source <(main completion bash)
  3. $ main mycmd --myenum <TAB><TAB>
  4. bar (help text for bar)
  5. foo (help text for foo)
  6. moo (help text for moo)

展开查看全部
cotxawn7

cotxawn72#

它看起来像一个enumflag包作为一个附加组件发布,以满足此用例:https://pkg.go.dev/github.com/thediveo/enumflag

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/spf13/cobra"
  5. "github.com/thediveo/enumflag"
  6. )
  7. // ① Define your new enum flag type. It can be derived from enumflag.Flag, but
  8. // it doesn't need to be as long as it is compatible with enumflag.Flag, so
  9. // either an int or uint.
  10. type FooMode enumflag.Flag
  11. // ② Define the enumeration values for FooMode.
  12. const (
  13. Foo FooMode = iota
  14. Bar
  15. )
  16. // ③ Map enumeration values to their textual representations (value
  17. // identifiers).
  18. var FooModeIds = map[FooMode][]string{
  19. Foo: {"foo"},
  20. Bar: {"bar"},
  21. }
  22. // User-defined enum flag types should be derived from "enumflag.Flag"; however
  23. // this is not strictly necessary as long as they can be converted into the
  24. // "enumflag.Flag" type. Actually, "enumflag.Flag" is just a fancy name for an
  25. // "uint". In order to use such user-defined enum flags, simply wrap them using
  26. // enumflag.New.
  27. func main() {
  28. // ④ Define your enum flag value.
  29. var foomode FooMode
  30. rootCmd := &cobra.Command{
  31. Run: func(cmd *cobra.Command, _ []string) {
  32. fmt.Printf("mode is: %d=%q\n",
  33. foomode,
  34. cmd.PersistentFlags().Lookup("mode").Value.String())
  35. },
  36. }
  37. // ⑤ Define the CLI flag parameters for your wrapped enum flag.
  38. rootCmd.PersistentFlags().VarP(
  39. enumflag.New(&foomode, "mode", FooModeIds, enumflag.EnumCaseInsensitive),
  40. "mode", "m",
  41. "foos the output; can be 'foo' or 'bar'")
  42. rootCmd.SetArgs([]string{"--mode", "bAr"})
  43. _ = rootCmd.Execute()
  44. }

字符集
注意:它似乎不包括完成逻辑。

展开查看全部
qvk1mo1f

qvk1mo1f3#

虽然很难证明一个否定的,它不看这是目前的一个功能。

相关问题