Cobra: Required flags are not enforced in subcommands

Created on 7 Aug 2018  路  2Comments  路  Source: spf13/cobra

Hi,

let's say I have some command "foo" with a mandatory parameter "bar":

var fooCmd = &cobra.Command{
    Use:   "foo",
}
...
func init() {
    fooCmd.PersistentFlags().StringVar(&bar "bar", "", "...")
    fooCmd.MarkFlagRequired("bar")
    rootCmd.AddCommand(fooCmd)
}

Testing this works just fine, I get an error message if the "bar" flag is omitted on the command line.

Now I want to add a subcommand "frobozz" to "foo":

var frobozzCmd = &cobra.Command{
    Use:   "frobozz",
    ...
}
...
func init() {
    fooCmd.AddCommand(frobozzCmd)
}

But I now find that the presence of the "bar" parameter is not enforced for the "frobozz" command. Is this by design/intentional?

Most helpful comment

Use

fooCmd.MarkPersistentFlagRequired("bar")

instead of

fooCmd.MarkFlagRequired("bar")

when marking it as required, since the last one will enforce it only when calling your root command alone.

fooCmd.MarkPersistentFlagRequired("bar") will enforce it for all your root subcommands if you declare it in your init() function for your fooCmd.

You can restrict enforcement to a single subcommand by setting it in your subcommand init() function:

func init() {
        fooCmd.MarkPersistentFlagRequired("bar")
    fooCmd.AddCommand(frobozzCmd)
}

All 2 comments

Use

fooCmd.MarkPersistentFlagRequired("bar")

instead of

fooCmd.MarkFlagRequired("bar")

when marking it as required, since the last one will enforce it only when calling your root command alone.

fooCmd.MarkPersistentFlagRequired("bar") will enforce it for all your root subcommands if you declare it in your init() function for your fooCmd.

You can restrict enforcement to a single subcommand by setting it in your subcommand init() function:

func init() {
        fooCmd.MarkPersistentFlagRequired("bar")
    fooCmd.AddCommand(frobozzCmd)
}

Ah, that makes sense. Thank you for the detailed explanation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rogercoll picture rogercoll  路  5Comments

supershal picture supershal  路  4Comments

lukasmalkmus picture lukasmalkmus  路  4Comments

anentropic picture anentropic  路  4Comments

icholy picture icholy  路  6Comments