首页 > 文章列表 > 合并 'BoolFlags' 为一个,通过使用 urfave/cli 的 go 编程方式

合并 'BoolFlags' 为一个,通过使用 urfave/cli 的 go 编程方式

255 2024-04-17
问题内容

我有一个代码可以获取 -f/--foo-b/--bar 的参数。参数解析是通过 urfave/cli 包完成的,这是第二个最流行的 go 参数解析器。我可以像 go run 一样运行我的程序。 -f -b 但不像 go run 。 -fb 有没有办法让它与 go run 一起工作。 -fb 使用 urfave/cli? 如果不可能,什么 go 模块可以使之成为可能?

代码:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/urfave/cli/v2"
)

func main() {
    var foo_count, bar_count bool

    app := &cli.app{
        flags: []cli.flag{
            &cli.boolflag{
                name:    "foo",
                usage:   "foo",
                aliases: []string{"f"},
                destination:   &foo_count,
            },
            &cli.boolflag{
                name:    "bar",
                usage:   "bar",
                aliases: []string{"b"},
                destination:   &bar_count,
            },
        },
        action: func(cctx *cli.context) error {
            fmt.println("foo_count", foo_count)
            fmt.println("bar_count", bar_count)
            return nil
        },
    }

    if err := app.run(os.args); err != nil {
        log.fatal(err)
    }
}

测试

$ go run . -f
foo_count true
bar_count false
$ go run . -b
foo_count false
bar_count true
$ go run . -bf
Incorrect Usage: flag provided but not defined: -bf

NAME:
   main - A new cli application

USAGE:
   main [global options] command [command options] [arguments...]

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --foo, -f   Foo (default: false)
   --bar, -b   Bar (default: false)
   --help, -h  show help
2023/03/25 15:54:00 flag provided but not defined: -bf
exit status 1


正确答案


这个问题在一个包示例中得到了具体解决。创建 cli 时添加 UseShortOptionHandling: true

https://github .com/urfave/cli/blob/main/docs/v2/examples/combining-short-options.md

来自文档: 这可以使用应用程序配置中的 UseShortOptionHandling bool 来完成,或者通过将其附加到命令配置来完成单个命令。