From 7908c214dfcea2df5f2111e68312bd326d6f4e1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Wed, 12 Aug 2020 15:33:26 +0200 Subject: [PATCH] Avoid erroring when looking up config keys for nonexistent host --- internal/config/config_file_test.go | 25 ++++++++++++++++++------- internal/config/config_type.go | 17 ++++++++++------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.go index f921d2c67..2d7fd4b73 100644 --- a/internal/config/config_file_test.go +++ b/internal/config/config_file_test.go @@ -2,7 +2,6 @@ package config import ( "bytes" - "errors" "fmt" "reflect" "testing" @@ -71,17 +70,29 @@ github.com: eq(t, token, "OTOKEN") } -func Test_parseConfig_notFound(t *testing.T) { +func Test_parseConfig_hostFallback(t *testing.T) { defer StubConfig(`--- -hosts: - example.com: +git_protocol: ssh +`, `--- +github.com: + user: monalisa + oauth_token: OTOKEN +example.com: user: wronguser oauth_token: NOTTHIS -`, "")() + git_protocol: https +`)() config, err := ParseConfig("config.yml") eq(t, err, nil) - _, err = config.Get("github.com", "user") - eq(t, err, &NotFoundError{errors.New(`could not find config entry for "github.com"`)}) + val, err := config.Get("example.com", "git_protocol") + eq(t, err, nil) + eq(t, val, "https") + val, err = config.Get("github.com", "git_protocol") + eq(t, err, nil) + eq(t, val, "ssh") + val, err = config.Get("nonexist.io", "git_protocol") + eq(t, err, nil) + eq(t, val, "ssh") } func Test_ParseConfig_migrateConfig(t *testing.T) { diff --git a/internal/config/config_type.go b/internal/config/config_type.go index 9b216cae0..28d91f9b0 100644 --- a/internal/config/config_type.go +++ b/internal/config/config_type.go @@ -201,16 +201,19 @@ func (c *fileConfig) Root() *yaml.Node { func (c *fileConfig) Get(hostname, key string) (string, error) { if hostname != "" { + var notFound *NotFoundError + hostCfg, err := c.configForHost(hostname) - if err != nil { + if err != nil && !errors.As(err, ¬Found) { return "", err } - hostValue, err := hostCfg.GetStringValue(key) - var notFound *NotFoundError - - if err != nil && !errors.As(err, ¬Found) { - return "", err + var hostValue string + if hostCfg != nil { + hostValue, err = hostCfg.GetStringValue(key) + if err != nil && !errors.As(err, ¬Found) { + return "", err + } } if hostValue != "" { @@ -385,7 +388,7 @@ func (c *fileConfig) hostEntries() ([]*HostConfig, error) { return hostConfigs, nil } -// Hosts returns a list of all known hostnames configred in hosts.yml +// Hosts returns a list of all known hostnames configured in hosts.yml func (c *fileConfig) Hosts() ([]string, error) { entries, err := c.hostEntries() if err != nil {