viper_go1_15.go 1.4 KB

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