Home > Enterprise >  Using no flag options with Cobra Command?
Using no flag options with Cobra Command?

Time:07-09

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!

CodePudding user response:

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.

  • Related