-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_finder.go
78 lines (67 loc) · 1.62 KB
/
config_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
package policy
import (
"fmt"
"path/filepath"
"github.com/spf13/afero"
"github.com/suzuki-shunsuke/go-findconfig/findconfig"
)
type ConfigFinder interface {
Find(policyFilePath, wd string) (string, error)
}
type MockConfigFinder struct {
path string
err error
}
func (finder *MockConfigFinder) Find(policyFilePath, wd string) (string, error) {
return finder.path, finder.err
}
type ConfigFinderImpl struct {
fs afero.Fs
}
func NewConfigFinder(fs afero.Fs) *ConfigFinderImpl {
return &ConfigFinderImpl{
fs: fs,
}
}
func configFileNames() []string {
return []string{
"khulnasoft-policy.yaml",
".khulnasoft-policy.yaml",
filepath.Join("khulnasoft", "khulnasoft-policy.yaml"),
filepath.Join(".khulnasoft", "khulnasoft-policy.yaml"),
}
}
func (finder *ConfigFinderImpl) Find(policyFilePath, wd string) (string, error) {
if policyFilePath != "" {
f, err := afero.Exists(finder.fs, policyFilePath)
if err != nil {
return "", fmt.Errorf("check if a policy file exists: %w", err)
}
if !f {
return "", ErrConfigFileNotFound
}
if filepath.IsAbs(policyFilePath) {
return policyFilePath, nil
}
return filepath.Join(wd, policyFilePath), nil
}
gitDir := findconfig.Find(wd, finder.exist, ".git")
if gitDir == "" {
return "", nil
}
gitParentDir := filepath.Dir(gitDir)
for _, p := range configFileNames() {
if _, err := finder.fs.Stat(filepath.Join(gitParentDir, p)); err != nil {
continue
}
return filepath.Join(gitParentDir, p), nil
}
return "", nil
}
func (finder *ConfigFinderImpl) exist(p string) bool {
b, err := afero.IsDir(finder.fs, p)
if err != nil {
return false
}
return b
}