如何为命令行参数(非标志)指定“用法”?

huangapple go评论67阅读模式
英文:

How to specify "usage" for cli arguments (not flags)

问题

对于标志(flags),我可以指定在--help命令中显示的描述信息。

flag.String("a", "", "这是一个标志")

但是我没有标志,只有参数,我像这样使用命令行界面(CLI):

mycommand start 4

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

英文:

For flags I can specify description which appers in --help command

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

But I don't have flags, only arguments, I use cli like this

mycommand start 4

Is it possible use --help to see description to "start" (and other) arguments?

答案1

得分: 1

由于这不是直接由标志支持的功能,我只知道alecthomas/kong包含参数用法:

package main

import "github.com/alecthomas/kong"

var CLI struct {
  Rm struct {
    Force     bool `help:"强制删除。"`
    Recursive bool `help:"递归删除文件。"`

    Paths []string `arg:"" name:"path" help:"要删除的路径。" type:"path"`
  } `cmd:"" help:"删除文件。"`

  Ls struct {
    Paths []string `arg:"" optional:"" name:"path" help:"要列出的路径。" type:"path"`
  } `cmd:"" help:"列出路径。"`
}

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> ...

删除文件。

参数:
  <paths> ...  要删除的路径。      <======  "usage" for cli arguments (not flags)!

标志:
      --debug        调试模式。

  -f, --force        强制删除。
  -r, --recursive    递归删除文件。
英文:

Since this is not directly supported by flags, I know only of alecthomas/kong which does include argument usage:

package main

import &quot;github.com/alecthomas/kong&quot;

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

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

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

func main() {
  ctx := kong.Parse(&amp;CLI)
  switch ctx.Command() {
  case &quot;rm &lt;path&gt;&quot;:
  case &quot;ls&quot;:
  default:
    panic(ctx.Command())
  }
}

You will get with shell --help rm:

$ shell --help rm
usage: shell rm &lt;paths&gt; ...

Remove files.

Arguments:
  &lt;paths&gt; ...  Paths to remove.      &lt;======  &quot;usage&quot; for cli arguments (not flags)!

Flags:
      --debug        Debug mode.

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

huangapple
  • 本文由 发表于 2021年12月24日 18:18:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/70471845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定