Skip to content

Commit f0ca9aa

Browse files
authored
Merge pull request cli#41 from github/silence-usage
Silence Cobra usage on errors
2 parents eefb6d1 + e877758 commit f0ca9aa

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

command/root.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,25 @@ func init() {
1616
RootCmd.PersistentFlags().StringP("current-branch", "B", "", "current git branch")
1717
// TODO:
1818
// RootCmd.PersistentFlags().BoolP("verbose", "V", false, "enable verbose output")
19+
20+
RootCmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
21+
return FlagError{err}
22+
})
23+
}
24+
25+
// FlagError is the kind of error raised in flag processing
26+
type FlagError struct {
27+
error
1928
}
2029

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: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@ package main
33
import (
44
"fmt"
55
"os"
6+
"strings"
67

78
"github.com/github/gh-cli/command"
89
)
910

1011
func main() {
11-
if err := command.RootCmd.Execute(); err != nil {
12-
fmt.Println(err)
12+
if cmd, err := command.RootCmd.ExecuteC(); err != nil {
13+
fmt.Fprintln(os.Stderr, err)
14+
_, isFlagError := err.(command.FlagError)
15+
if isFlagError || strings.HasPrefix(err.Error(), "unknown command ") {
16+
fmt.Fprintln(os.Stderr, cmd.UsageString())
17+
}
1318
os.Exit(1)
1419
}
1520
}

0 commit comments

Comments
 (0)