I have a PersistentPreRunE set on my RootCmd. It is simply:
func check(cmd *cobra.Command, args []string) error { return errors.New("foo error") }
when I run my command, I get:
$ ./my-tool Error: foo error
Usage:
my-tool my-subcommand [flags]
Flags:
-h, --help help for list
Global Flags:
-p, --project string Google Cloud project ID
foo error
Problems:
foo error printed twice (at the very beginning and at the very end)?cmd.Execute(). Execute func already prints an error if it occurred in PersistentPreRunE.cmd.SilenceUsage = true.@bogem thanks for the answer. When I SilenceUsage=true, duplicate printing looks worse:
$ my-tool -s
Error: unknown shorthand flag: 's' in -s
unknown shorthand flag: 's' in -s
Probably, it's because you print an error returned from cmd.Execute() like this:
if err := cmd.Execute(); if err != nil {
fmt.Println(err)
}
but cmd.Execute() prints errors automatically as I said before. So just delete all error handling in your app and leave only cmd.Execute() call.
Thanks.
actually my main.go is already just:
func main() { cmd.Execute() }
and yet I'm still getting errors printed twice, so I'll reopen this.
oh turns out I had this in root.go
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
That part in the rootCmd is generated by the cobra command line tool when generating framework. Should it?
@bogem I got hit by the same issue as @rayjohnson. Do you know if it should?
The README also shows an example which contains the PrintLn
Maybe it should really be removed from the Cobra generator tool, as it is confusing, especially for beginners, who are the most likely ones to use the Cobra generator.
Most helpful comment
@bogem I got hit by the same issue as @rayjohnson. Do you know if it should?
The README also shows an example which contains the
PrintLn