Skip to content

Commit a6e61a3

Browse files
committed
Silence Cobra usage on errors
When an error occurs anywhere in a command, Cobra used to print the error itself and command usage help. We already print error in `main()`, and we don't want to use command usage string on anything other than flag-parsing errors. This also fixes the double output of each error.
1 parent eefb6d1 commit a6e61a3

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

command/root.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package command
22

33
import (
4+
"errors"
45
"fmt"
56
"os"
67

@@ -16,17 +17,24 @@ func init() {
1617
RootCmd.PersistentFlags().StringP("current-branch", "B", "", "current git branch")
1718
// TODO:
1819
// RootCmd.PersistentFlags().BoolP("verbose", "V", false, "enable verbose output")
20+
21+
RootCmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
22+
cmd.Println(err)
23+
cmd.Println(cmd.UsageString())
24+
return SilentErr
25+
})
1926
}
2027

28+
var SilentErr = errors.New("SilentErr")
29+
2130
// RootCmd is the entry point of command-line execution
2231
var RootCmd = &cobra.Command{
2332
Use: "gh",
2433
Short: "GitHub CLI",
2534
Long: `Do things with GitHub from your terminal`,
26-
Args: cobra.MinimumNArgs(1),
27-
Run: func(cmd *cobra.Command, args []string) {
28-
fmt.Println("root")
29-
},
35+
36+
SilenceErrors: true,
37+
SilenceUsage: true,
3038
}
3139

3240
// overriden in tests

main.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import (
99

1010
func main() {
1111
if err := command.RootCmd.Execute(); err != nil {
12-
fmt.Println(err)
12+
if err != command.SilentErr {
13+
fmt.Println(err)
14+
}
1315
os.Exit(1)
1416
}
1517
}

0 commit comments

Comments
 (0)