From 2b73e6213777bc097472a4a4f419ec4fe540583b Mon Sep 17 00:00:00 2001 From: George MacRorie Date: Thu, 21 Nov 2024 13:50:50 +0000 Subject: [PATCH] refactor(config): loop over files and stat to check for existence --- pkg/config/config.go | 35 ++++++++++++----------------------- 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 834dc58..3f2ff36 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -92,40 +92,29 @@ func processValue[T any](val reflect.Value, method func(T) error) error { } func ReadFromFS(filesystem fs.FS) (_ *Config, err error) { - dirfs, ok := filesystem.(fs.ReadDirFS) + statfs, ok := filesystem.(fs.StatFS) if !ok { return nil, errors.New("filesystem provided does not support opening directories") } - entries, err := dirfs.ReadDir(".") - if err != nil { - return nil, err - } - - var configPath string + files := []string{"glu.yaml", "glu.yml", "glu.json"} + for _, path := range files { + if _, err := statfs.Stat(path); err != nil { + if errors.Is(err, fs.ErrNotExist) { + continue + } - for _, ent := range entries { - if ent.IsDir() { - continue + return nil, err } - switch ent.Name() { - case "glu.yaml", "glu.yml", "glu.json": - configPath = ent.Name() + slog.Debug("configuration found", "path", path) - slog.Debug("configuration found", "path", configPath) - - break - } + return readFromPath(filesystem, path) } - if configPath == "" { - slog.Debug("could not locate glu configuration file", "attempted", []string{"glu.yaml", "glu.yml", "glu.json"}) - - return readFrom(config.NewDecoder[Config](&emptyReader{}, yaml.Unmarshal)) - } + slog.Debug("could not locate glu configuration file", "attempted", files) - return readFromPath(filesystem, configPath) + return readFrom(config.NewDecoder[Config](&emptyReader{}, yaml.Unmarshal)) } func readFromPath(fs fs.FS, configPath string) (_ *Config, err error) {