Using spf13/Cobra for cli flag parsing.
root command has a field marked required:
rootCmd.PersistentFlags().StringVarP(&configFilePath, "config", "c","", "REQUIRED: config file")
rootCmd.MarkPersistentFlagRequired("config")
rootCmd.MarkFlagRequired("config")
However, cobra does not raise an error if it's the root command.
If I add a subcommand and add a required field, .MarkFlagRequired raises an error as expected if the argument is not provided on the command line.
I'm facing the same issue.
Before the upgrade, I've been using revision a1f051bc3eba734da4772d60e2d677f47cf93ef4 and it was working (at least this issue was not present there).
I came across this issue in one of my CLI tools built with cobra in which I have a command for which I have defined some flags which I marked as required, which works fine as long as I define the flag with Flags().StringP(...) but does not work if I use Flags().StringVarP(...) so I think it does not relate to the flags being persistent.
Code to replicate the issue:
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var testCmd = &cobra.Command{
Use: "test",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(Foo)
},
}
var Foo string
func init() {
rootCmd.AddCommand(testCmd)
testCmd.Flags().StringVarP(&Foo, "foo", "f", "", "A help for foo")
testCmd.MarkFlagRequired(Foo)
}
The problem is, that the command executes without printing any error, unlike how it does when defining flags with Flags().StringP().
This works just fine:
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var testCmd = &cobra.Command{
Use: "test",
RunE: func(cmd *cobra.Command, args []string) error {
Foo, err := cmd.Flags().GetString("foo")
if err != nil {
return err
}
fmt.Println(Foo)
return nil
},
}
func init() {
rootCmd.AddCommand(testCmd)
testCmd.Flags().StringP("foo", "f", "", "A help for foo")
testCmd.MarkFlagRequired("foo")
}
This issue is being marked as stale due to a long period of inactivity
Most helpful comment
I came across this issue in one of my CLI tools built with cobra in which I have a command for which I have defined some flags which I marked as required, which works fine as long as I define the flag with Flags().StringP(...) but does not work if I use Flags().StringVarP(...) so I think it does not relate to the flags being persistent.
Code to replicate the issue:
The problem is, that the command executes without printing any error, unlike how it does when defining flags with Flags().StringP().
This works just fine: