与Cobra命令一起使用没有标志选项?

发布于 2025-02-13 10:25:18 字数 363 浏览 1 评论 0原文

我有一个带有默认选项的命令-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的值,如果它是空的,请从cmdargs 中读取值(如果其中有东西,并且没有标志,那我假设这是我的ID)。

但是,这似乎不仅容易出错,例如,如果有人放下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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲世九天 2025-02-20 10:25:18

我希望有一种更惯用的方式,可以做到这一点

我认为这是这样做的,这是我试图在评论中引起的想法:不要提供多种方式在命令行上指定相同的选项。

在位置参数与选项之间选择时,问题通常是“该值是命令运行的内容吗?”。例如,像rm之类的命令在文件上操作,因此文件被指定为位置参数:我们不需要编写rm -f file1 -f file2 -f file2 -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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文