github.com/lyft/flytestdlib@v0.3.12-0.20210213045714-8cdd111ecda1/config/files/finder.go (about) 1 package files 2 3 import ( 4 "os" 5 "path/filepath" 6 ) 7 8 const ( 9 configFileType = "yaml" 10 configFileName = "config" 11 ) 12 13 var configLocations = [][]string{ 14 {"."}, 15 {"/etc", "flyte", "config"}, 16 {os.ExpandEnv("$GOPATH"), "src", "github.com", "lyft", "flytestdlib"}, 17 } 18 19 // Check if File / Directory Exists 20 func exists(path string) (bool, error) { 21 _, err := os.Stat(path) 22 if err == nil { 23 return true, nil 24 } 25 26 if os.IsNotExist(err) { 27 return false, nil 28 } 29 30 return false, err 31 } 32 33 func isFile(path string) (bool, error) { 34 s, err := os.Stat(path) 35 if err != nil { 36 return false, err 37 } 38 39 return !s.IsDir(), nil 40 } 41 42 func contains(slice []string, value string) bool { 43 for _, s := range slice { 44 if s == value { 45 return true 46 } 47 } 48 49 return false 50 } 51 52 // Finds config files in search paths. If searchPaths is empty, it'll look in default locations (see configLocations above) 53 // If searchPaths is not empty but no configs are found there, it'll still look into configLocations. 54 // If it found any config file in searchPaths, it'll stop the search. 55 // searchPaths can contain patterns to match (behavior is OS-dependent). And it'll try to Glob the pattern for any matching 56 // files. 57 func FindConfigFiles(searchPaths []string) []string { 58 res := make([]string, 0, 1) 59 60 for _, location := range searchPaths { 61 matchedFiles, err := filepath.Glob(location) 62 if err != nil { 63 continue 64 } 65 66 for _, matchedFile := range matchedFiles { 67 if file, err := isFile(matchedFile); err == nil && file && !contains(res, matchedFile) { 68 res = append(res, matchedFile) 69 } 70 } 71 } 72 73 if len(res) == 0 { 74 for _, location := range configLocations { 75 pathToTest := filepath.Join(append(location, configFileName+"."+configFileType)...) 76 if b, err := exists(pathToTest); err == nil && b && !contains(res, pathToTest) { 77 res = append(res, pathToTest) 78 } 79 } 80 } 81 82 return res 83 }