diff --git a/command/root.go b/command/root.go index be46358e6..2967c2550 100644 --- a/command/root.go +++ b/command/root.go @@ -66,8 +66,19 @@ var initContext = func() context.Context { return ctx } +// BasicClient returns an API client that borrows from but does not depend on +// user configuration func BasicClient() (*api.Client, error) { - return apiClientForContext(initContext()) + opts := []api.ClientOption{ + api.AddHeader("User-Agent", fmt.Sprintf("GitHub CLI %s", Version)), + } + if c, err := context.ParseDefaultConfig(); err == nil { + opts = append(opts, api.AddHeader("Authorization", fmt.Sprintf("token %s", c.Token))) + } + if verbose := os.Getenv("DEBUG"); verbose != "" { + opts = append(opts, api.VerboseLog(os.Stderr)) + } + return api.NewClient(opts...), nil } func contextForCommand(cmd *cobra.Command) context.Context { diff --git a/context/config_file.go b/context/config_file.go index 48f9ce482..e37fb1ca2 100644 --- a/context/config_file.go +++ b/context/config_file.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" + "github.com/mitchellh/go-homedir" "gopkg.in/yaml.v3" ) @@ -15,18 +16,30 @@ type configEntry struct { Token string `yaml:"oauth_token"` } +func parseOrSetupConfigFile(fn string) (*configEntry, error) { + entry, err := parseConfigFile(fn) + if err != nil && errors.Is(err, os.ErrNotExist) { + return setupConfigFile(fn) + } + return entry, err +} + func parseConfigFile(fn string) (*configEntry, error) { f, err := os.Open(fn) if err != nil { - if errors.Is(err, os.ErrNotExist) { - return setupConfigFile(fn) - } return nil, err } defer f.Close() return parseConfig(f) } +// ParseDefaultConfig reads the configuration from ~/.config/gh +func ParseDefaultConfig() (*configEntry, error) { + // FIXME: this duplicates fsContext.configFile + fn, _ := homedir.Expand("~/.config/gh") + return parseConfigFile(fn) +} + func parseConfig(r io.Reader) (*configEntry, error) { data, err := ioutil.ReadAll(r) if err != nil { diff --git a/context/context.go b/context/context.go index 7e165299d..220330d83 100644 --- a/context/context.go +++ b/context/context.go @@ -46,7 +46,7 @@ func (c *fsContext) configFile() string { func (c *fsContext) getConfig() (*configEntry, error) { if c.config == nil { - entry, err := parseConfigFile(c.configFile()) + entry, err := parseOrSetupConfigFile(c.configFile()) if err != nil { return nil, err }