I've created a cobra command and added a flag:
cmd.Flags().StringVarP(&primaryIP, "primary-ip", "p", "", "Help text")
Is there a way to make it required other than checking the value myself and returning an error?
Persistent flags are flags that are available to a command and all its sub-commands. In particular it is common to define persistent flags on the root command that will be available for all commands. For example, --verbose or --help are good examples for global flags that can apply to any command.
cobra-cli is a command line program to generate cobra applications and command files. It will bootstrap your application scaffolding to rapidly develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.
A few months ago this behavior was changed in cobra
, although the documentation is not very clear on this. Now if you mark a flag as MarkFlagRequired("primary-ip")
and you don't supply such a flag, running the command will print the help plus
required flag(s) "primary-ip"
exit status 1
at the end where the missing required flags are stated.
Late but i hope this help you !
First of all, we need to know that cobra
defines two types of flags.
Persistent flags: they will be available to the command and every sub-command under it.
Local flags: they will available only to the specific command which define them.
So cobra
provides two approaches to make flags required regarding the type of the flag.
On the init
function of your command, it could be the root
or any other command or sub-command. Lets create a cli app called my-cmd
with a sub-command called xD sub-command
// root.go file
var Foo bool
func init() {
cobra.OnInitialize(initConfig)
// define required persistent flag
myCmd.PersistentFlags().BoolVarP(&Foo, "foo", "f", false, "set foo (*)")
myCmd.MarkPersistentFlagRequired("foo")
}
// subCommand.go file
var Bar string
func init() {
// just add subCmd as a sub-command of my-cmd
myCmd.AddCommand(subCmd)
// define required local flag
subCmd.Flags().StringVarP(&Bar, "bar", "b", "", "set bar (*)")
subCmd.MarkFlagRequired("bar")
}
When you call your command in the CLI
# if you don't pass a value for 'foo' flag
> my-cmd
required flag(s) "foo" not set
exit status 1
# here you must pass a value for 'foo' because is persistent as well as 'bar' because is local for sub-cmd
> my-cmd sub-cmd
required flag(s) "foo", "bar" not set
exit status 1
No, you have to check yourself whether the input is correct for your program.
Note that this makes sense, since you may want to check if the input is correct at the same time. In your example you should check if the input exists AND if the input is a valid ip-address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With