cli/command/root.go
Mislav Marohnić a6e61a3a8d 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.
2019-10-31 13:47:10 +01:00

74 lines
1.8 KiB
Go

package command
import (
"errors"
"fmt"
"os"
"github.com/github/gh-cli/api"
"github.com/github/gh-cli/context"
"github.com/github/gh-cli/version"
"github.com/spf13/cobra"
)
func init() {
RootCmd.PersistentFlags().StringP("repo", "R", "", "current GitHub repository")
RootCmd.PersistentFlags().StringP("current-branch", "B", "", "current git branch")
// TODO:
// RootCmd.PersistentFlags().BoolP("verbose", "V", false, "enable verbose output")
RootCmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
cmd.Println(err)
cmd.Println(cmd.UsageString())
return SilentErr
})
}
var SilentErr = errors.New("SilentErr")
// RootCmd is the entry point of command-line execution
var RootCmd = &cobra.Command{
Use: "gh",
Short: "GitHub CLI",
Long: `Do things with GitHub from your terminal`,
SilenceErrors: true,
SilenceUsage: true,
}
// overriden in tests
var initContext = func() context.Context {
ctx := context.New()
if repo := os.Getenv("GH_REPO"); repo != "" {
ctx.SetBaseRepo(repo)
}
return ctx
}
func contextForCommand(cmd *cobra.Command) context.Context {
ctx := initContext()
if repo, err := cmd.Flags().GetString("repo"); err == nil && repo != "" {
ctx.SetBaseRepo(repo)
}
if branch, err := cmd.Flags().GetString("current-branch"); err == nil && branch != "" {
ctx.SetBranch(branch)
}
return ctx
}
// overriden in tests
var apiClientForContext = func(ctx context.Context) (*api.Client, error) {
token, err := ctx.AuthToken()
if err != nil {
return nil, err
}
opts := []api.ClientOption{
api.AddHeader("Authorization", fmt.Sprintf("token %s", token)),
api.AddHeader("User-Agent", fmt.Sprintf("GitHub CLI %s", version.Version)),
}
if verbose := os.Getenv("DEBUG"); verbose != "" {
opts = append(opts, api.VerboseLog(os.Stderr))
}
return api.NewClient(opts...), nil
}