|
1 //go:build !go1.16 || !finder |
|
2 // +build !go1.16 !finder |
|
3 |
|
4 package viper |
|
5 |
|
6 import ( |
|
7 "fmt" |
|
8 "os" |
|
9 "path/filepath" |
|
10 |
|
11 "github.com/spf13/afero" |
|
12 ) |
|
13 |
|
14 // Search all configPaths for any config file. |
|
15 // Returns the first path that exists (and is a config file). |
|
16 func (v *Viper) findConfigFile() (string, error) { |
|
17 v.logger.Info("searching for config in paths", "paths", v.configPaths) |
|
18 |
|
19 for _, cp := range v.configPaths { |
|
20 file := v.searchInPath(cp) |
|
21 if file != "" { |
|
22 return file, nil |
|
23 } |
|
24 } |
|
25 return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)} |
|
26 } |
|
27 |
|
28 func (v *Viper) searchInPath(in string) (filename string) { |
|
29 v.logger.Debug("searching for config in path", "path", in) |
|
30 for _, ext := range SupportedExts { |
|
31 v.logger.Debug("checking if file exists", "file", filepath.Join(in, v.configName+"."+ext)) |
|
32 if b, _ := exists(v.fs, filepath.Join(in, v.configName+"."+ext)); b { |
|
33 v.logger.Debug("found file", "file", filepath.Join(in, v.configName+"."+ext)) |
|
34 return filepath.Join(in, v.configName+"."+ext) |
|
35 } |
|
36 } |
|
37 |
|
38 if v.configType != "" { |
|
39 if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b { |
|
40 return filepath.Join(in, v.configName) |
|
41 } |
|
42 } |
|
43 |
|
44 return "" |
|
45 } |
|
46 |
|
47 // Check if file Exists |
|
48 func exists(fs afero.Fs, path string) (bool, error) { |
|
49 stat, err := fs.Stat(path) |
|
50 if err == nil { |
|
51 return !stat.IsDir(), nil |
|
52 } |
|
53 if os.IsNotExist(err) { |
|
54 return false, nil |
|
55 } |
|
56 return false, err |
|
57 } |