summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/spf13/viper/fs.go
blob: ecb1769e529305b00ffb899e20dd96cf519e1120 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//go:build go1.16 && finder
// +build go1.16,finder

package viper

import (
	"errors"
	"io/fs"
	"path"
)

type finder struct {
	paths      []string
	fileNames  []string
	extensions []string

	withoutExtension bool
}

func (f finder) Find(fsys fs.FS) (string, error) {
	for _, searchPath := range f.paths {
		for _, fileName := range f.fileNames {
			for _, extension := range f.extensions {
				filePath := path.Join(searchPath, fileName+"."+extension)

				ok, err := fileExists(fsys, filePath)
				if err != nil {
					return "", err
				}

				if ok {
					return filePath, nil
				}
			}

			if f.withoutExtension {
				filePath := path.Join(searchPath, fileName)

				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
}