使用Cobra Command时不使用标志选项?

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

Using no flag options with Cobra Command?

问题

我有一个带有默认选项-id的命令。还可能有其他标志,所以可以调用以下任何一种方式。

cmd 81313 # 81313是ID
cmd -i 81313
cmd -f foo.txt 81313
cmd -i 81313 -f foo.txt
cmd 81313 -f foo.txt

在Cobra命令中,如何正确处理这个问题?

目前,我正在查看-i的值,如果它为空,则从cmdArgs中读取值(如果其中有内容,并且没有标志,则我假设它是我的ID)。

然而,这种方法似乎容易出错-例如,如果有人输入了两个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!

答案1

得分: 1

我认为有一种更习惯用法的方式来完成这个任务,这也是我在评论中试图传达的思想:不要在命令行上提供多种指定相同选项的方式。

在选择位置参数和选项之间时,通常的问题是“这个值是命令操作的对象吗?”例如,像 rm 这样的命令操作文件,所以文件被指定为位置参数:我们不需要写成 rm -f file1 -f file2 -f file3,等等。

同样,ssh 命令连接到远程主机,所以主机名是一个位置参数。关于该连接的元数据(要使用的身份、要使用的端口、配置选项等)也是通过命令行选项指定的。

你的问题有点难以回答,因为你没有告诉我们你的命令实际上是做什么的。如果每次调用 cmd 都需要提供“id”,并且它标识了命令操作的对象,那么你可能只需将其作为位置参数:

cmd 81313

如果有时不需要指定 ID,那么它应该是一个可选参数:

cmd -i 81313

有时可能会有“强制选项”的情况,但这种情况相对较少见。

英文:

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

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:

cmd 81313

If there are ever situations in which you do not need to specify the ID, then it should be an optional argument:

cmd -i 81313

There are situations in which you may have "mandatory options", but these are relatively rare.

huangapple
  • 本文由 发表于 2022年7月6日 06:50:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/72876309.html
匿名

发表评论

匿名网友

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

确定