【问题标题】:How to specify "usage" for cli arguments (not flags)如何为 cli 参数(不是标志)指定“用法”
【发布时间】:2022-01-25 00:33:37
【问题描述】:

对于标志,我可以指定 --help 命令中的描述

flag.String("a", "", "Is is a flag")

但我没有标志,只有参数,我像这样使用 cli

mycommand start 4

是否可以使用 --help 来查看“开始”(和其他)参数的描述?

【问题讨论】:

  • 您始终可以检查os.Args[1:],但不能使用flags 包。因此,您需要编写自己的解析器以获取输入并相应地对帮助做出反应。
  • 你可能想要使用不同的东西,比如github.com/alexflint/go-arg
  • 我明白了,谢谢你的回答

标签: go command-line-interface


【解决方案1】:

由于标志不直接支持这一点,我只知道 alecthomas/kong 确实包含参数用法:

package main

import "github.com/alecthomas/kong"

var CLI struct {
  Rm struct {
    Force     bool `help:"Force removal."`
    Recursive bool `help:"Recursively remove files."`

    Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"`
  } `cmd:"" help:"Remove files."`

  Ls struct {
    Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"`
  } `cmd:"" help:"List paths."`
}

func main() {
  ctx := kong.Parse(&CLI)
  switch ctx.Command() {
  case "rm <path>":
  case "ls":
  default:
    panic(ctx.Command())
  }
}

你会得到shell --help rm:

$ shell --help rm
usage: shell rm <paths> ...

Remove files.

Arguments:
  <paths> ...  Paths to remove.      <======  "usage" for cli arguments (not flags)!

Flags:
      --debug        Debug mode.

  -f, --force        Force removal.
  -r, --recursive    Recursively remove files.

【讨论】:

    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 2016-03-11
    • 2014-08-02
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多