Improvements to update notifier authentication

- Check for updates even if `~/.config/gh` does not exist. In this case,
  the API call is unauthenticated.

- Avoid having the update notifier ever triggering the OAuth flow.
This commit is contained in:
Mislav Marohnić 2019-12-04 15:41:08 +01:00
parent aaad263a3e
commit 87a1490d1e
3 changed files with 29 additions and 5 deletions

View file

@ -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 {

View file

@ -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 {

View file

@ -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
}