feat: use new finder even when build tag is disabled

Signed-off-by: Mark Sagi-Kazar <mark.sagikazar@gmail.com>
This commit is contained in:
Mark Sagi-Kazar 2024-06-04 13:51:18 +02:00 committed by Márk Sági-Kazár
parent 1be81c313a
commit db0bbd8f97
2 changed files with 42 additions and 0 deletions

13
file.go
View file

@ -13,6 +13,19 @@ import (
// Search all configPaths for any config file.
// Returns the first path that exists (and is a config file).
func (v *Viper) findConfigFile() (string, error) {
if v.finder != nil {
results, err := v.finder.Find(v.fs)
if err != nil {
return "", err
}
if len(results) == 0 {
return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
}
return results[0], nil
}
v.logger.Info("searching for config in paths", "paths", v.configPaths)
for _, cp := range v.configPaths {

View file

@ -22,6 +22,7 @@ import (
"github.com/fsnotify/fsnotify"
"github.com/go-viper/mapstructure/v2"
"github.com/sagikazarmark/locafero"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/spf13/pflag"
@ -415,6 +416,34 @@ func TestReadInConfig(t *testing.T) {
assert.Equal(t, "value", v.Get("key"))
})
t.Run("find file using a finder", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
finder := locafero.Finder{
Paths: []string{"/etc/viper"},
Names: locafero.NameWithExtensions("config", SupportedExts...),
Type: locafero.FileTypeFile,
}
v := NewWithOptions(WithFinder(finder))
v.SetFs(fs)
// These should be ineffective
v.AddConfigPath("/etc/something_else")
v.SetConfigName("not-config")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/viper/config.yaml"), filename)
assert.NoError(t, err)
})
}
func TestDefault(t *testing.T) {