Path: blob/main/vendor/github.com/spf13/viper/file.go
2875 views
package viper12import (3"fmt"4"os"5"path/filepath"67"github.com/sagikazarmark/locafero"8"github.com/spf13/afero"9)1011// ExperimentalFinder tells Viper to use the new Finder interface for finding configuration files.12func ExperimentalFinder() Option {13return optionFunc(func(v *Viper) {14v.experimentalFinder = true15})16}1718// Search for a config file.19func (v *Viper) findConfigFile() (string, error) {20finder := v.finder2122if finder == nil && v.experimentalFinder {23var names []string2425if v.configType != "" {26names = locafero.NameWithOptionalExtensions(v.configName, SupportedExts...)27} else {28names = locafero.NameWithExtensions(v.configName, SupportedExts...)29}3031finder = locafero.Finder{32Paths: v.configPaths,33Names: names,34Type: locafero.FileTypeFile,35}36}3738if finder != nil {39return v.findConfigFileWithFinder(finder)40}4142return v.findConfigFileOld()43}4445func (v *Viper) findConfigFileWithFinder(finder Finder) (string, error) {46results, err := finder.Find(v.fs)47if err != nil {48return "", err49}5051if len(results) == 0 {52return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}53}5455// We call clean on the final result to ensure that the path is in its canonical form.56// This is mostly for consistent path handling and to make sure tests pass.57return results[0], nil58}5960// Search all configPaths for any config file.61// Returns the first path that exists (and is a config file).62func (v *Viper) findConfigFileOld() (string, error) {63v.logger.Info("searching for config in paths", "paths", v.configPaths)6465for _, cp := range v.configPaths {66file := v.searchInPath(cp)67if file != "" {68return file, nil69}70}71return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}72}7374func (v *Viper) searchInPath(in string) (filename string) {75v.logger.Debug("searching for config in path", "path", in)76for _, ext := range SupportedExts {77v.logger.Debug("checking if file exists", "file", filepath.Join(in, v.configName+"."+ext))78if b, _ := exists(v.fs, filepath.Join(in, v.configName+"."+ext)); b {79v.logger.Debug("found file", "file", filepath.Join(in, v.configName+"."+ext))80return filepath.Join(in, v.configName+"."+ext)81}82}8384if v.configType != "" {85if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b {86return filepath.Join(in, v.configName)87}88}8990return ""91}9293// exists checks if file exists.94func exists(fs afero.Fs, path string) (bool, error) {95stat, err := fs.Stat(path)96if err == nil {97return !stat.IsDir(), nil98}99if os.IsNotExist(err) {100return false, nil101}102return false, err103}104105106