简体   繁体   English

Cobra 命令不使用标志选项?

[英]Using no flag options with Cobra Command?

I have a command with a default option - id.我有一个带有默认选项的命令 - 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?使用 Cobra 命令处理此问题的正确方法是什么?

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).目前,我正在查看-i的值,如果它为空,则从cmdArgs读取值(如果里面有东西,并且没有标志,那么我假设它是我的 ID)。

However, this seems more than a little error prone - eg what if someone puts down 2 ids.然而,这似乎有点容易出错 - 例如,如果有人放下 2 个 ID 怎么办。

Thanks!谢谢!

i wish there was a more idiomatic way that this is done我希望有一种更惯用的方式来完成

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 write rm -f file1 -f file2 -f file3 , etc.例如,像rm这样的命令对文件进行操作,因此文件被指定为位置参数:我们不需要写rm -f file1 -f file2 -f file3等。

Similarly, the ssh command connects to a remote host, so the hostname is a positional argument.同样, ssh命令连接到远程主机,因此主机名是一个位置参数。 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:如果每次调用cmd都需要“id”,并且如果它标识了命令操作的对象,则您可能应该将其设置为位置参数:

cmd 81313

If there are ever situations in which you do not need to specify the ID, then it should be an optional argument:如果在某些情况下您不需要指定 ID,那么它应该是一个可选参数:

cmd -i 81313

There are situations in which you may have "mandatory options", but these are relatively rare.在某些情况下,您可能有“强制性选项”,但这些情况相对较少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM