Skip to content

Commit 26c31da

Browse files
author
Matthew Coleman
committed
fix: return not found error if setting config
1 parent 260b8e9 commit 26c31da

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

viper.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,12 @@ type ConfigFileNotFoundError struct {
7676

7777
// Error returns the formatted configuration error.
7878
func (fnfe ConfigFileNotFoundError) Error() string {
79-
return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
79+
message := fmt.Sprintf("Config file %q Not Found", fnfe.name)
80+
if fnfe.locations != "" {
81+
message += fmt.Sprintf(" in %q", fnfe.locations)
82+
}
83+
84+
return message
8085
}
8186

8287
// ConfigFileAlreadyExistsError denotes failure to write new configuration file.
@@ -1522,11 +1527,16 @@ func (v *Viper) ReadInConfig() error {
15221527
}
15231528

15241529
v.logger.Debug("reading file", "file", filename)
1530+
exists, err := afero.Exists(v.fs, filename)
1531+
if !exists {
1532+
return ConfigFileNotFoundError{filename, ""}
1533+
} else if err != nil {
1534+
return err
1535+
}
15251536
file, err := afero.ReadFile(v.fs, filename)
15261537
if err != nil {
15271538
return err
15281539
}
1529-
15301540
config := make(map[string]any)
15311541

15321542
err = v.unmarshalReader(bytes.NewReader(file), config)

viper_test.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ func TestReadInConfig(t *testing.T) {
359359
t.Run("config file set", func(t *testing.T) {
360360
fs := afero.NewMemMapFs()
361361

362-
err := fs.Mkdir("/etc/viper", 0o777)
362+
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
363363
require.NoError(t, err)
364364

365365
file, err := fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
@@ -1573,6 +1573,23 @@ func TestReadConfigWithSetConfigFile(t *testing.T) {
15731573
assert.Equal(t, 45000, v.GetInt("hello.pop"))
15741574
}
15751575

1576+
func TestWrongConfigWithSetConfigFileNotFound(t *testing.T) {
1577+
_, config := initDirs(t)
1578+
1579+
v := New()
1580+
v.SetConfigName(config)
1581+
v.SetDefault(`key`, `default`)
1582+
1583+
v.SetConfigFile(`whatareyoutalkingabout.yaml`)
1584+
1585+
err := v.ReadInConfig()
1586+
assert.IsType(t, ConfigFileNotFoundError{"", ""}, err)
1587+
1588+
// Even though config did not load and the error might have
1589+
// been ignored by the client, the default still loads
1590+
assert.Equal(t, `default`, v.GetString(`key`))
1591+
}
1592+
15761593
func TestIsSet(t *testing.T) {
15771594
v := New()
15781595
v.SetConfigType("yaml")

0 commit comments

Comments
 (0)