隐藏标志默认值

时间:2017-10-19 08:02:00

标签: go

Go提供简单的CLI切换,即标志。

var debug = flag.Bool("debug", false, "enable debugging")
var hostname = flag.String("hostname", "127.0.0.1", "hostname")
flag.Parse()

正如所料,这会产生

> ./program -h
Usage:
    -debug
          enable debugging
    -hostname string
          hostname (default "127.0.0.1")

我想隐藏特定标志的(default "127.0.0.1")部分。

在SO和周围搜索建议使用flag.FlagSet。

var shown flag.FlagSet
var hidden flag.FlagSet
var debug = shown.Bool("debug", false, "enable debugging")
var hostname = hidden.String("hostname", "127.0.0.1", "hostname")
flag.Usage = func() {
    shown.PrintDefaults()
}
flag.Parse()
//shown.Parse(os.Args[0:]) // tried to solve "flag provided but not defined"

输出部分仅显示" debug" flag,但这打破了实际的标志用法。

> ./program -debug
flag provided but not defined: -debug
Usage of ./program:
    -debug
          enable debugging

这也不理想,因为我希望看到可用的标志,只需隐藏默认值。

期望的输出:

> ./program -h
Usage:
    -debug
          enable debugging
    -hostname string
          hostname

2 个答案:

答案 0 :(得分:0)

到目前为止,最佳解决方案是Eugene提出的解决方案。谢谢!

var debug = flag.Bool("debug", false, "enable debugging")
var hostname = flag.String("hostname", "", "hostname")
flag.Parse()

defaultHostname := "127.0.0.1"

if *hostname == "" {
    *hostname = defaultHostname
}

答案 1 :(得分:0)

您可以从源代码复制并粘贴代码并删除打印默认部分。

flag.Usage = func() {
    f := flag.CommandLine
    _, _ = fmt.Fprintf(f.Output(), "Usage of %s:\n", os.Args[0])
    flag.VisitAll(func(flag_ *flag.Flag) {
        if flag_.Usage == "" {
            return
        }
        s := fmt.Sprintf("  -%s", flag_.Name) // Two spaces before -; see next two comments.
        name, usage := flag.UnquoteUsage(flag_)
        if len(name) > 0 {
            s += " " + name
        }
        // Boolean flags of one ASCII letter are so common we
        // treat them specially, putting their usage on the same line.
        if len(s) <= 4 { // space, space, '-', 'x'.
            s += "\t"
        } else {
            // Four spaces before the tab triggers good alignment
            // for both 4- and 8-space tab stops.
            s += "\n    \t"
        }
        s += strings.ReplaceAll(usage, "\n", "\n    \t")
        _, _ = fmt.Fprint(f.Output(), s, "\n")
    })
}
flag.Parse()