Cobra: Error from RootCmd.PersistentPreRunE printed twice, with usage string

Created on 12 Jun 2017  路  9Comments  路  Source: spf13/cobra

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:

  1. why is foo error printed twice (at the very beginning and at the very end)?
  2. why is the full usage string printed? Is there a way to prevent it?

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

All 9 comments

  1. I think, it's because you print an error returned from cmd.Execute(). Execute func already prints an error if it occurred in PersistentPreRunE.
  2. You can prevent it with 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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

groenborg picture groenborg  路  5Comments

supershal picture supershal  路  4Comments

anentropic picture anentropic  路  4Comments

icholy picture icholy  路  6Comments

joernott picture joernott  路  6Comments