This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
/
finder.go
83 lines (68 loc) · 1.82 KB
/
finder.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package files
import (
"os"
"path/filepath"
)
const (
configFileType = "yaml"
configFileName = "config"
)
var configLocations = [][]string{
{"."},
{"/etc", "flyte", "config"},
{os.ExpandEnv("$GOPATH"), "src", "github.com", "lyft", "flytestdlib"},
}
// Check if File / Directory Exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func isFile(path string) (bool, error) {
s, err := os.Stat(path)
if err != nil {
return false, err
}
return !s.IsDir(), nil
}
func contains(slice []string, value string) bool {
for _, s := range slice {
if s == value {
return true
}
}
return false
}
// Finds config files in search paths. If searchPaths is empty, it'll look in default locations (see configLocations above)
// If searchPaths is not empty but no configs are found there, it'll still look into configLocations.
// If it found any config file in searchPaths, it'll stop the search.
// searchPaths can contain patterns to match (behavior is OS-dependent). And it'll try to Glob the pattern for any matching
// files.
func FindConfigFiles(searchPaths []string) []string {
res := make([]string, 0, 1)
for _, location := range searchPaths {
matchedFiles, err := filepath.Glob(location)
if err != nil {
continue
}
for _, matchedFile := range matchedFiles {
if file, err := isFile(matchedFile); err == nil && file && !contains(res, matchedFile) {
res = append(res, matchedFile)
}
}
}
if len(res) == 0 {
for _, location := range configLocations {
pathToTest := filepath.Join(append(location, configFileName+"."+configFileType)...)
if b, err := exists(pathToTest); err == nil && b && !contains(res, pathToTest) {
res = append(res, pathToTest)
}
}
}
return res
}