2021-09-21 08:25:51 +00:00
|
|
|
//go:build go1.16
|
|
|
|
// +build go1.16
|
|
|
|
|
|
|
|
package viper
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"io/fs"
|
2021-09-22 09:18:45 +00:00
|
|
|
"path"
|
2021-09-21 08:25:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type finder struct {
|
|
|
|
paths []string
|
|
|
|
fileNames []string
|
|
|
|
extensions []string
|
|
|
|
|
|
|
|
withoutExtension bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f finder) Find(fsys fs.FS) (string, error) {
|
2021-09-22 09:18:45 +00:00
|
|
|
for _, searchPath := range f.paths {
|
2021-09-21 08:25:51 +00:00
|
|
|
for _, fileName := range f.fileNames {
|
|
|
|
for _, extension := range f.extensions {
|
2021-09-22 09:18:45 +00:00
|
|
|
filePath := path.Join(searchPath, fileName+"."+extension)
|
2021-09-21 08:25:51 +00:00
|
|
|
|
|
|
|
ok, err := fileExists(fsys, filePath)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if ok {
|
|
|
|
return filePath, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if f.withoutExtension {
|
2021-09-22 09:18:45 +00:00
|
|
|
filePath := path.Join(searchPath, fileName)
|
2021-09-21 08:25:51 +00:00
|
|
|
|
|
|
|
ok, err := fileExists(fsys, filePath)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if ok {
|
|
|
|
return filePath, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func fileExists(fsys fs.FS, filePath string) (bool, error) {
|
|
|
|
fileInfo, err := fs.Stat(fsys, filePath)
|
|
|
|
if err == nil {
|
|
|
|
return !fileInfo.IsDir(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, err
|
|
|
|
}
|