X Tutup
Skip to content

Commit 7908c21

Browse files
committed
Avoid erroring when looking up config keys for nonexistent host
1 parent 55a13a3 commit 7908c21

File tree

2 files changed

+28
-14
lines changed

2 files changed

+28
-14
lines changed

internal/config/config_file_test.go

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package config
22

33
import (
44
"bytes"
5-
"errors"
65
"fmt"
76
"reflect"
87
"testing"
@@ -71,17 +70,29 @@ github.com:
7170
eq(t, token, "OTOKEN")
7271
}
7372

74-
func Test_parseConfig_notFound(t *testing.T) {
73+
func Test_parseConfig_hostFallback(t *testing.T) {
7574
defer StubConfig(`---
76-
hosts:
77-
example.com:
75+
git_protocol: ssh
76+
`, `---
77+
github.com:
78+
user: monalisa
79+
oauth_token: OTOKEN
80+
example.com:
7881
user: wronguser
7982
oauth_token: NOTTHIS
80-
`, "")()
83+
git_protocol: https
84+
`)()
8185
config, err := ParseConfig("config.yml")
8286
eq(t, err, nil)
83-
_, err = config.Get("github.com", "user")
84-
eq(t, err, &NotFoundError{errors.New(`could not find config entry for "github.com"`)})
87+
val, err := config.Get("example.com", "git_protocol")
88+
eq(t, err, nil)
89+
eq(t, val, "https")
90+
val, err = config.Get("github.com", "git_protocol")
91+
eq(t, err, nil)
92+
eq(t, val, "ssh")
93+
val, err = config.Get("nonexist.io", "git_protocol")
94+
eq(t, err, nil)
95+
eq(t, val, "ssh")
8596
}
8697

8798
func Test_ParseConfig_migrateConfig(t *testing.T) {

internal/config/config_type.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -201,18 +201,21 @@ func (c *fileConfig) Root() *yaml.Node {
201201

202202
func (c *fileConfig) Get(hostname, key string) (string, error) {
203203
if hostname != "" {
204-
hostCfg, err := c.configForHost(hostname)
205-
if err != nil {
206-
return "", err
207-
}
208-
209-
hostValue, err := hostCfg.GetStringValue(key)
210204
var notFound *NotFoundError
211205

206+
hostCfg, err := c.configForHost(hostname)
212207
if err != nil && !errors.As(err, &notFound) {
213208
return "", err
214209
}
215210

211+
var hostValue string
212+
if hostCfg != nil {
213+
hostValue, err = hostCfg.GetStringValue(key)
214+
if err != nil && !errors.As(err, &notFound) {
215+
return "", err
216+
}
217+
}
218+
216219
if hostValue != "" {
217220
return hostValue, nil
218221
}
@@ -385,7 +388,7 @@ func (c *fileConfig) hostEntries() ([]*HostConfig, error) {
385388
return hostConfigs, nil
386389
}
387390

388-
// Hosts returns a list of all known hostnames configred in hosts.yml
391+
// Hosts returns a list of all known hostnames configured in hosts.yml
389392
func (c *fileConfig) Hosts() ([]string, error) {
390393
entries, err := c.hostEntries()
391394
if err != nil {

0 commit comments

Comments
 (0)
X Tutup