在Go语言中使用Cobra创建具有相同名称的子命令

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

Creating sub-commands with the same name in Go w/ Cobra

问题

我对Go和Cobra都非常陌生,这是我在Cobra中的第一个项目。

使用Cobra命令行工具创建命令似乎很容易:
cobra add <command>

添加子命令也很简单:
cobra add <subcommand> -p '<command>'

然而,我遇到的问题是为两个不同的命令添加两个同名的子命令。例如:

我可能有一个名为'people'的命令和一个名为'places'的命令。
cobra add people
cobra add places

每个命令都需要自己的名为'add'的子命令。
cobra add add -p 'people'
cobra add add -p 'places'

第二个命令会失败,因为它会尝试创建一个已经被第一个命令创建的'add.go'文件。是否有可能为不同的父命令添加同名的子命令?最终的结果会是这样的:
people add --first "bob" --last "smith"
places add "someplace" --zip "12345"

英文:

I'm very new to Go in general, and this is my first project in Cobra.

It seems easy enough to create commands in Cobra with the command-line tool:<br/>
cobra add &lt;command&gt;

And adding sub-commands seems easy enough as well.<br/>
cobra add &lt;subcommand&gt; -p &#39;&lt;command&gt;&#39;

Where I've run into an issue is having two sub-commands for two different commands, but having the sub-commands have the same name. For instance:

I may have a command named 'people' and a command named 'places'.<br/>
cobra add people<br/>
cobra add places

Each command needs its own sub-command called 'add'.<br/>
cobra add add -p &#39;people&#39;<br/>
cobra add add -p &#39;places&#39;

The second command will fail because it will attempt to create an 'add.go' file which was already created by the first command. Is it possible to add sub-commands of the same name to different parent commands? Where the end result would be something like:<br/>
people add --first &quot;bob&quot; --last &quot;smith&quot;<br/>
places add &quot;someplace&quot; --zip &quot;12345&quot;

答案1

得分: 2

command add的作用只是为您生成一个Go源文件。您可以自己编写文件,或者您可以使用第一个创建的文件,将其重命名,然后创建下一个文件。您还可能需要重命名生成文件中的一些全局变量/函数,以避免名称冲突。

英文:

All command add does is generate a Go source file for you. You could write the file yourself; or you could take the first one that was created, rename it, then create the next one. You'll also likely have to rename some global variables/functions in the generated files to avoid name collisions.

huangapple
  • 本文由 发表于 2017年7月6日 13:54:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/44940787.html
匿名

发表评论

匿名网友

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

确定