cobra
cobra copied to clipboard
Marked Required with Default Value on a Flag
I might be misunderstanding something or my approach is wrong but I am having trouble achieving something.
What I want
I want to have a REQUIRED parameter on a command, lets call it Important URL
.
I want to be able to set it as a ENVIRONMENT VARIABLE or override it on the cli with a FLAG.
The logic is very simple: The variable needs to be set some way. If the env variable is not set then the cli command needs to inform the user that they need to specify the flag. If the flag is not set it needs to use the value defined in the Environment Variable.
What I tried.
After gooling arround I found out I can do this:
var url string
CobraCmd.Flags().StringVarP(&url, "url", "u", os.Getenv("IMPORTANT_URL"), "The Important URL [may also set with $IMPORTANT_URL]")
_ = CobraCmd.MarkFlagRequired("url")
I thought that this would work as the default value for the flag would be set to either VALUE or "" (empty string) and would then prompt the user to set the flag if it was empty.
Sadly it seems that when you mark a flag as required, cobra requires it to be specified when the command is called (even if it has a default value set):
/> IMPORTANT_URL="https://example.com"
/> app cmd
(... help output ...)
required flag(s) "url" not set
This obviously works (but defeats the purpose):
/> app cmd --url "https://example.com"
(... help output ...)
required flag(s) "url" not set
When I don't mark the flag as required the command will go through without specifying --url
and use the value in the environment variable.
I then need to deal with the existence checking in the code itself. Because the variable might not be set.
Thoughts
This might be a situation where I need to change how I need to do input checking.
Command Line Level (in cobra) vs. Application Level (in function).
I will need to do the verification in code anyway to check that they entered a valid URL which turns this example into somewhat of a mute point.
HOWEVER
I was surprised by the way that both setting a default
value of a flag interacted with how marking it required
.
If I give a flag a default value and then I set it to being required I expected the command to succeed with out needing me to set it as it is already set by the default value.
What would be the point of setting a default value on a marked required flag?