add GetOrDefault functionality to config

This commit is contained in:
nate smith 2022-01-11 14:56:58 -06:00
parent eaa64df801
commit 562f1b3d0d
33 changed files with 116 additions and 58 deletions

View file

@ -22,10 +22,10 @@ hosts:
`, "")()
config, err := parseConfig("config.yml")
assert.NoError(t, err)
user, err := config.Get("github.com", "user")
user, err := config.GetOrDefault("github.com", "user")
assert.NoError(t, err)
assert.Equal(t, "monalisa", user)
token, err := config.Get("github.com", "oauth_token")
token, err := config.GetOrDefault("github.com", "oauth_token")
assert.NoError(t, err)
assert.Equal(t, "OTOKEN", token)
}
@ -42,10 +42,10 @@ hosts:
`, "")()
config, err := parseConfig("config.yml")
assert.NoError(t, err)
user, err := config.Get("github.com", "user")
user, err := config.GetOrDefault("github.com", "user")
assert.NoError(t, err)
assert.Equal(t, "monalisa", user)
token, err := config.Get("github.com", "oauth_token")
token, err := config.GetOrDefault("github.com", "oauth_token")
assert.NoError(t, err)
assert.Equal(t, "OTOKEN", token)
}
@ -58,10 +58,10 @@ github.com:
`)()
config, err := parseConfig("config.yml")
assert.NoError(t, err)
user, err := config.Get("github.com", "user")
user, err := config.GetOrDefault("github.com", "user")
assert.NoError(t, err)
assert.Equal(t, "monalisa", user)
token, err := config.Get("github.com", "oauth_token")
token, err := config.GetOrDefault("github.com", "oauth_token")
assert.NoError(t, err)
assert.Equal(t, "OTOKEN", token)
}
@ -80,13 +80,13 @@ example.com:
`)()
config, err := parseConfig("config.yml")
assert.NoError(t, err)
val, err := config.Get("example.com", "git_protocol")
val, err := config.GetOrDefault("example.com", "git_protocol")
assert.NoError(t, err)
assert.Equal(t, "https", val)
val, err = config.Get("github.com", "git_protocol")
val, err = config.GetOrDefault("github.com", "git_protocol")
assert.NoError(t, err)
assert.Equal(t, "ssh", val)
val, err = config.Get("nonexistent.io", "git_protocol")
val, err = config.GetOrDefault("nonexistent.io", "git_protocol")
assert.NoError(t, err)
assert.Equal(t, "ssh", val)
}

View file

@ -9,7 +9,10 @@ import (
// This interface describes interacting with some persistent configuration for gh.
type Config interface {
Get(string, string) (string, error)
GetOrDefault(string, string) (string, error)
GetWithSource(string, string) (string, string, error)
GetOrDefaultWithSource(string, string) (string, string, error)
Default(string) string
Set(string, string, string) error
UnsetHost(string)
Hosts() ([]string, error)

View file

@ -58,11 +58,11 @@ func Test_defaultConfig(t *testing.T) {
assert.Equal(t, expected, mainBuf.String())
assert.Equal(t, "", hostsBuf.String())
proto, err := cfg.Get("", "git_protocol")
proto, err := cfg.GetOrDefault("", "git_protocol")
assert.NoError(t, err)
assert.Equal(t, "https", proto)
editor, err := cfg.Get("", "editor")
editor, err := cfg.GetOrDefault("", "editor")
assert.NoError(t, err)
assert.Equal(t, "", editor)
@ -72,7 +72,7 @@ func Test_defaultConfig(t *testing.T) {
expansion, _ := aliases.Get("co")
assert.Equal(t, expansion, "pr checkout")
browser, err := cfg.Get("", "browser")
browser, err := cfg.GetOrDefault("", "browser")
assert.NoError(t, err)
assert.Equal(t, "", browser)
}

View file

@ -76,6 +76,24 @@ func (c *envConfig) GetWithSource(hostname, key string) (string, string, error)
return c.Config.GetWithSource(hostname, key)
}
func (c *envConfig) GetOrDefault(hostname, key string) (val string, err error) {
val, _, err = c.GetOrDefaultWithSource(hostname, key)
return
}
func (c *envConfig) GetOrDefaultWithSource(hostname, key string) (val string, src string, err error) {
val, src, err = c.GetWithSource(hostname, key)
if err == nil && val == "" {
val = c.Default(key)
}
return
}
func (c *envConfig) Default(key string) string {
return c.Config.Default(key)
}
func (c *envConfig) CheckWriteable(hostname, key string) error {
if hostname != "" && key == "oauth_token" {
if token, env := AuthTokenFromEnv(hostname); token != "" {

View file

@ -301,11 +301,11 @@ func TestInheritEnv(t *testing.T) {
hosts, _ := cfg.Hosts()
assert.Equal(t, tt.wants.hosts, hosts)
val, source, _ := cfg.GetWithSource(tt.hostname, "oauth_token")
val, source, _ := cfg.GetOrDefaultWithSource(tt.hostname, "oauth_token")
assert.Equal(t, tt.wants.token, val)
assert.Regexp(t, tt.wants.source, source)
val, _ = cfg.Get(tt.hostname, "oauth_token")
val, _ = cfg.GetOrDefault(tt.hostname, "oauth_token")
assert.Equal(t, tt.wants.token, val)
err := cfg.CheckWriteable(tt.hostname, "oauth_token")

View file

@ -65,13 +65,26 @@ func (c *fileConfig) GetWithSource(hostname, key string) (string, string, error)
return "", defaultSource, err
}
if value == "" {
return defaultFor(key), defaultSource, nil
}
return value, defaultSource, nil
}
func (c *fileConfig) GetOrDefault(hostname, key string) (val string, err error) {
val, _, err = c.GetOrDefaultWithSource(hostname, key)
return
}
func (c *fileConfig) GetOrDefaultWithSource(hostname, key string) (val string, src string, err error) {
val, src, err = c.GetWithSource(hostname, key)
if err != nil && val == "" {
val = c.Default(key)
}
return
}
func (c *fileConfig) Default(key string) string {
return defaultFor(key)
}
func (c *fileConfig) Set(hostname, key, value string) error {
if hostname == "" {
return c.SetStringValue(key, value)

View file

@ -25,6 +25,24 @@ func (c ConfigStub) GetWithSource(host, key string) (string, string, error) {
return "", "", errors.New("not found")
}
func (c ConfigStub) GetOrDefault(hostname, key string) (val string, err error) {
val, _, err = c.GetOrDefaultWithSource(hostname, key)
return
}
func (c ConfigStub) GetOrDefaultWithSource(hostname, key string) (val string, src string, err error) {
val, src, err = c.GetWithSource(hostname, key)
if err == nil && val == "" {
val = c.Default(key)
}
return
}
func (c ConfigStub) Default(key string) string {
// TODO may regret this
return defaultFor(key)
}
func (c ConfigStub) Set(host, key, value string) error {
c[genKey(host, key)] = value
return nil

View file

@ -14,7 +14,7 @@ import (
const tokenUser = "x-access-token"
type config interface {
GetWithSource(string, string) (string, string, error)
GetOrDefaultWithSource(string, string) (string, string, error)
}
type CredentialOptions struct {
@ -101,11 +101,11 @@ func helperRun(opts *CredentialOptions) error {
}
var gotUser string
gotToken, source, _ := cfg.GetWithSource(wants["host"], "oauth_token")
gotToken, source, _ := cfg.GetOrDefaultWithSource(wants["host"], "oauth_token")
if strings.HasSuffix(source, "_TOKEN") {
gotUser = tokenUser
} else {
gotUser, _, _ = cfg.GetWithSource(wants["host"], "user")
gotUser, _, _ = cfg.GetOrDefaultWithSource(wants["host"], "user")
}
if gotUser == "" || gotToken == "" {

View file

@ -8,12 +8,18 @@ import (
"github.com/cli/cli/v2/pkg/iostreams"
)
// why not just use the config stub argh
type tinyConfig map[string]string
func (c tinyConfig) GetWithSource(host, key string) (string, string, error) {
func (c tinyConfig) GetOrDefaultWithSource(host, key string) (string, string, error) {
return c[fmt.Sprintf("%s:%s", host, key)], c["_source"], nil
}
func (c tinyConfig) GetOrDefault(host, key string) (val string, err error) {
val, _, err = c.GetOrDefaultWithSource(host, key)
return
}
func Test_helperRun(t *testing.T) {
tests := []struct {
name string

View file

@ -165,7 +165,7 @@ func loginRun(opts *LoginOptions) error {
return cfg.Write()
}
existingToken, _ := cfg.Get(hostname, "oauth_token")
existingToken, _ := cfg.GetOrDefault(hostname, "oauth_token")
if existingToken != "" && opts.Interactive {
if err := shared.HasMinimumScopes(httpClient, hostname, existingToken); err == nil {
var keepGoing bool

View file

@ -127,7 +127,7 @@ func logoutRun(opts *LogoutOptions) error {
if err != nil {
// suppressing; the user is trying to delete this token and it might be bad.
// we'll see if the username is in the config and fall back to that.
username, _ = cfg.Get(hostname, "user")
username, _ = cfg.GetOrDefault(hostname, "user")
}
usernameStr := ""

View file

@ -132,7 +132,7 @@ func refreshRun(opts *RefreshOptions) error {
}
var additionalScopes []string
if oldToken, _ := cfg.Get(hostname, "oauth_token"); oldToken != "" {
if oldToken, _ := cfg.GetOrDefault(hostname, "oauth_token"); oldToken != "" {
if oldScopes, err := shared.GetScopes(opts.httpClient, hostname, oldToken); err == nil {
for _, s := range strings.Split(oldScopes, ",") {
s = strings.TrimSpace(s)
@ -146,7 +146,7 @@ func refreshRun(opts *RefreshOptions) error {
credentialFlow := &shared.GitCredentialFlow{
Executable: opts.MainExecutable,
}
gitProtocol, _ := cfg.Get(hostname, "git_protocol")
gitProtocol, _ := cfg.GetOrDefault(hostname, "git_protocol")
if opts.Interactive && gitProtocol == "https" {
if err := credentialFlow.Prompt(hostname); err != nil {
return err
@ -159,8 +159,8 @@ func refreshRun(opts *RefreshOptions) error {
}
if credentialFlow.ShouldSetup() {
username, _ := cfg.Get(hostname, "user")
password, _ := cfg.Get(hostname, "oauth_token")
username, _ := cfg.GetOrDefault(hostname, "user")
password, _ := cfg.GetOrDefault(hostname, "oauth_token")
if err := credentialFlow.Setup(hostname, username, password); err != nil {
return err
}

View file

@ -15,7 +15,7 @@ import (
)
type iconfig interface {
Get(string, string) (string, error)
GetOrDefault(string, string) (string, error)
Set(string, string, string) error
Write() error
}
@ -147,7 +147,7 @@ func Login(opts *LoginOptions) error {
var username string
if userValidated {
username, _ = cfg.Get(hostname, "user")
username, _ = cfg.GetOrDefault(hostname, "user")
} else {
apiClient := api.NewClientFromHTTP(httpClient)
var err error

View file

@ -17,7 +17,7 @@ import (
type tinyConfig map[string]string
func (c tinyConfig) Get(host, key string) (string, error) {
func (c tinyConfig) GetOrDefault(host, key string) (string, error) {
return c[fmt.Sprintf("%s:%s", host, key)], nil
}

View file

@ -92,7 +92,7 @@ func statusRun(opts *StatusOptions) error {
}
isHostnameFound = true
token, tokenSource, _ := cfg.GetWithSource(hostname, "oauth_token")
token, tokenSource, _ := cfg.GetOrDefaultWithSource(hostname, "oauth_token")
tokenIsWriteable := cfg.CheckWriteable(hostname, "oauth_token") == nil
statusInfo[hostname] = []string{}
@ -127,7 +127,7 @@ func statusRun(opts *StatusOptions) error {
addMsg("%s %s: api call failed: %s", cs.Red("X"), hostname, err)
}
addMsg("%s Logged in to %s as %s (%s)", cs.SuccessIcon(), hostname, cs.Bold(username), tokenSource)
proto, _ := cfg.Get(hostname, "git_protocol")
proto, _ := cfg.GetOrDefault(hostname, "git_protocol")
if proto != "" {
addMsg("%s Git operations for %s configured to use %s protocol.",
cs.SuccessIcon(), hostname, cs.Bold(proto))

View file

@ -53,7 +53,7 @@ func NewCmdConfigGet(f *cmdutil.Factory, runF func(*GetOptions) error) *cobra.Co
}
func getRun(opts *GetOptions) error {
val, err := opts.Config.Get(opts.Hostname, opts.Key)
val, err := opts.Config.GetOrDefault(opts.Hostname, opts.Key)
if err != nil {
return err
}

View file

@ -115,7 +115,7 @@ func Test_getRun(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, tt.stdout, stdout.String())
assert.Equal(t, tt.stderr, stderr.String())
_, err = tt.input.Config.Get("", "_written")
_, err = tt.input.Config.GetOrDefault("", "_written")
assert.Error(t, err)
})
}

View file

@ -59,7 +59,7 @@ func listRun(opts *ListOptions) error {
configOptions := config.ConfigOptions()
for _, key := range configOptions {
val, err := cfg.Get(host, key.Key)
val, err := cfg.GetOrDefault(host, key.Key)
if err != nil {
return err
}

View file

@ -145,11 +145,11 @@ func Test_setRun(t *testing.T) {
assert.Equal(t, tt.stdout, stdout.String())
assert.Equal(t, tt.stderr, stderr.String())
val, err := tt.input.Config.Get(tt.input.Hostname, tt.input.Key)
val, err := tt.input.Config.GetOrDefault(tt.input.Hostname, tt.input.Key)
assert.NoError(t, err)
assert.Equal(t, tt.expectedValue, val)
val, err = tt.input.Config.Get("", "_written")
val, err = tt.input.Config.GetOrDefault("", "_written")
assert.NoError(t, err)
assert.Equal(t, "true", val)
})

View file

@ -337,7 +337,7 @@ func (m *Manager) Install(repo ghrepo.Interface) error {
return errors.New("extension is uninstallable: missing executable")
}
protocol, _ := m.config.Get(repo.RepoHost(), "git_protocol")
protocol, _ := m.config.GetOrDefault(repo.RepoHost(), "git_protocol")
return m.installGit(ghrepo.FormatRemoteURL(repo, protocol), m.io.Out, m.io.ErrOut)
}

View file

@ -113,7 +113,7 @@ func browserLauncher(f *cmdutil.Factory) string {
cfg, err := f.Config()
if err == nil {
if cfgBrowser, _ := cfg.Get("", "browser"); cfgBrowser != "" {
if cfgBrowser, _ := cfg.GetOrDefault("", "browser"); cfgBrowser != "" {
return cfgBrowser
}
}
@ -220,7 +220,7 @@ func ioStreams(f *cmdutil.Factory) *iostreams.IOStreams {
return io
}
if prompt, _ := cfg.Get("", "prompt"); prompt == "disabled" {
if prompt, _ := cfg.GetOrDefault("", "prompt"); prompt == "disabled" {
io.SetNeverPrompt(true)
}
@ -230,7 +230,7 @@ func ioStreams(f *cmdutil.Factory) *iostreams.IOStreams {
// 3. PAGER
if ghPager, ghPagerExists := os.LookupEnv("GH_PAGER"); ghPagerExists {
io.SetPager(ghPager)
} else if pager, _ := cfg.Get("", "pager"); pager != "" {
} else if pager, _ := cfg.GetOrDefault("", "pager"); pager != "" {
io.SetPager(pager)
}

View file

@ -54,7 +54,7 @@ var timezoneNames = map[int]string{
}
type configGetter interface {
Get(string, string) (string, error)
GetOrDefault(string, string) (string, error)
}
// generic authenticated HTTP client for commands
@ -73,7 +73,7 @@ func NewHTTPClient(io *iostreams.IOStreams, cfg configGetter, appVersion string,
// which would use that non-default behavior is right here, and it doesn't
// seem worth the cognitive overhead everywhere else just to serve this one
// use case.
unixSocket, err := cfg.Get("", "http_unix_socket")
unixSocket, err := cfg.GetOrDefault("", "http_unix_socket")
if err != nil {
return nil, err
}
@ -92,7 +92,7 @@ func NewHTTPClient(io *iostreams.IOStreams, cfg configGetter, appVersion string,
api.AddHeader("User-Agent", fmt.Sprintf("GitHub CLI %s", appVersion)),
api.AddHeaderFunc("Authorization", func(req *http.Request) (string, error) {
hostname := ghinstance.NormalizeHostname(getHost(req))
if token, err := cfg.Get(hostname, "oauth_token"); err == nil && token != "" {
if token, err := cfg.GetOrDefault(hostname, "oauth_token"); err == nil && token != "" {
return fmt.Sprintf("token %s", token), nil
}
return "", nil

View file

@ -157,7 +157,7 @@ func TestNewHTTPClient(t *testing.T) {
type tinyConfig map[string]string
func (c tinyConfig) Get(host, key string) (string, error) {
func (c tinyConfig) GetOrDefault(host, key string) (string, error) {
return c[fmt.Sprintf("%s:%s", host, key)], nil
}

View file

@ -83,7 +83,7 @@ func (rr *remoteResolver) Resolver() func() (context.Remotes, error) {
dummyHostname := "example.com" // any non-github.com hostname is fine here
if config.IsHostEnv(src) {
return nil, fmt.Errorf("none of the git remotes configured for this repository correspond to the %s environment variable. Try adding a matching remote or unsetting the variable.", src)
} else if v, src, _ := cfg.GetWithSource(dummyHostname, "oauth_token"); v != "" && config.IsEnterpriseEnv(src) {
} else if v, src, _ := cfg.GetOrDefaultWithSource(dummyHostname, "oauth_token"); v != "" && config.IsEnterpriseEnv(src) {
return nil, errors.New("set the GH_HOST environment variable to specify which GitHub host to use")
}
return nil, errors.New("none of the git remotes configured for this repository point to a known GitHub host. To tell gh about a new GitHub host, please use `gh auth login`")

View file

@ -79,7 +79,7 @@ func cloneRun(opts *CloneOptions) error {
if err != nil {
return err
}
protocol, err := cfg.Get(hostname, "git_protocol")
protocol, err := cfg.GetOrDefault(hostname, "git_protocol")
if err != nil {
return err
}

View file

@ -85,7 +85,7 @@ func checkoutRun(opts *CheckoutOptions) error {
if err != nil {
return err
}
protocol, _ := cfg.Get(baseRepo.RepoHost(), "git_protocol")
protocol, _ := cfg.GetOrDefault(baseRepo.RepoHost(), "git_protocol")
remotes, err := opts.Remotes()
if err != nil {

View file

@ -701,7 +701,7 @@ func handlePush(opts CreateOptions, ctx CreateContext) error {
if err != nil {
return err
}
cloneProtocol, _ := cfg.Get(headRepo.RepoHost(), "git_protocol")
cloneProtocol, _ := cfg.GetOrDefault(headRepo.RepoHost(), "git_protocol")
headRepoURL := ghrepo.FormatRemoteURL(headRepo, cloneProtocol)

View file

@ -121,7 +121,7 @@ func cloneRun(opts *CloneOptions) error {
return err
}
protocol, err = cfg.Get(repo.RepoHost(), "git_protocol")
protocol, err = cfg.GetOrDefault(repo.RepoHost(), "git_protocol")
if err != nil {
return err
}
@ -156,7 +156,7 @@ func cloneRun(opts *CloneOptions) error {
// If the repo is a fork, add the parent as an upstream
if canonicalRepo.Parent != nil {
protocol, err := cfg.Get(canonicalRepo.Parent.RepoHost(), "git_protocol")
protocol, err := cfg.GetOrDefault(canonicalRepo.Parent.RepoHost(), "git_protocol")
if err != nil {
return err
}

View file

@ -361,7 +361,7 @@ func createFromScratch(opts *CreateOptions) error {
}
if opts.Clone {
protocol, err := cfg.Get(repo.RepoHost(), "git_protocol")
protocol, err := cfg.GetOrDefault(repo.RepoHost(), "git_protocol")
if err != nil {
return err
}
@ -498,7 +498,7 @@ func createFromLocal(opts *CreateOptions) error {
fmt.Fprintln(stdout, repo.URL)
}
protocol, err := cfg.Get(repo.RepoHost(), "git_protocol")
protocol, err := cfg.GetOrDefault(repo.RepoHost(), "git_protocol")
if err != nil {
return err
}

View file

@ -209,7 +209,7 @@ func forkRun(opts *ForkOptions) error {
if err != nil {
return err
}
protocol, err := cfg.Get(repoToFork.RepoHost(), "git_protocol")
protocol, err := cfg.GetOrDefault(repoToFork.RepoHost(), "git_protocol")
if err != nil {
return err
}

View file

@ -144,7 +144,7 @@ func updateRemote(repo ghrepo.Interface, renamed ghrepo.Interface, opts *RenameO
return nil, err
}
protocol, err := cfg.Get(repo.RepoHost(), "git_protocol")
protocol, err := cfg.GetOrDefault(repo.RepoHost(), "git_protocol")
if err != nil {
return nil, err
}

View file

@ -24,7 +24,7 @@ func CheckAuth(cfg config.Config) bool {
}
for _, hostname := range hosts {
token, _ := cfg.Get(hostname, "oauth_token")
token, _ := cfg.GetOrDefault(hostname, "oauth_token")
if token != "" {
return true
}

View file

@ -16,7 +16,7 @@ func DetermineEditor(cf func() (config.Config, error)) (string, error) {
if err != nil {
return "", fmt.Errorf("could not read config: %w", err)
}
editorCommand, _ = cfg.Get("", "editor")
editorCommand, _ = cfg.GetOrDefault("", "editor")
}
return editorCommand, nil