与Cobra命令一起使用没有标志选项?
我有一个带有默认选项的命令-ID。也可能还有其他标志,因此可以调用以下任何一个。
cmd 81313 # 81313 is the ID
cmd -i 81313
cmd -f foo.txt 81313
cmd -i 81313 -f foo.txt
cmd 81313 -f foo.txt
COBRA命令处理此操作的正确方法是什么?
当前,我正在查看-i
的值,如果它是空的,请从
但是,这似乎不仅容易出错,例如,如果有人放下2个ID,该怎么办。
谢谢!
I have a command with a default option - id. There may be other flags as well, so any of the following could be called.
cmd 81313 # 81313 is the ID
cmd -i 81313
cmd -f foo.txt 81313
cmd -i 81313 -f foo.txt
cmd 81313 -f foo.txt
What is the correct way to handle this with Cobra command?
Currently, i'm looking at the value for -i
and if it's empty, reading the values from cmdArgs
(if there's something in there, and doesn't have a flag, then I'm assuming it's my ID).
However, this seems more than a little error prone - e.g. what if someone puts down 2 ids.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是这样做的,这是我试图在评论中引起的想法:不要提供多种方式在命令行上指定相同的选项。
在位置参数与选项之间选择时,问题通常是“该值是命令运行的内容吗?”。例如,像
rm
之类的命令在文件上操作,因此文件被指定为位置参数:我们不需要编写rm -f file1 -f file2 -f file2 -f file2 -f file3
等等。同样,
ssh
命令连接到远程主机,因此主机名是位置参数。关于该连接的元数据(使用的身份,要使用的端口,配置选项等)也被指定为命令行选项。您的问题很难回答,因为您还没有告诉我们您的命令实际上是什么。如果每个调用
cmd
都需要“ ID”,并且如果它标识了命令运行的内容,则您可能应该只是将其作为位置参数:如果有任何情况不是需要指定ID,那么它应该是一个可选的参数:
在某些情况下,您可能具有“强制性选项”,但是这些情况相对较少。
I think there is, and it's the idea I was trying to get across in the comments: don't provide multiple ways of specifying the same option on the command line.
When choosing between a positional argument vs. an option, the question is usually "is this value the thing on which the command is operating?". For example, a command like
rm
operates on files, so files are specified as positional arguments: we don't need to writerm -f file1 -f file2 -f file3
, etc.Similarly, the
ssh
command connects to a remote host, so the hostname is a positional argument. Metadata about that connection (the identity to use, the port to use, configuration options, etc) are also specified as command line options instead.Your question is a little hard to answer because you haven't told us what your command actually does. If the "id" is required for every invocation of
cmd
and if it identifies the thing upon which the command operates, you should probably just make it a positional argument:If there are ever situations in which you do not need to specify the ID, then it should be an optional argument:
There are situations in which you may have "mandatory options", but these are relatively rare.