-
Notifications
You must be signed in to change notification settings - Fork 78
/
crd.go
76 lines (64 loc) · 1.38 KB
/
crd.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
package crd
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"k8s.io/apimachinery/pkg/util/yaml"
"kusionstack.io/kusion/pkg/resources"
)
const (
Directory = "crd"
)
var FileExtensions = []string{".yaml", ".yml", ".json"}
type crdVisitor struct {
Path string
}
func NewVisitor(path string) resources.Visitor {
return &crdVisitor{Path: path}
}
// Visit read all YAML files under target path
func (v *crdVisitor) Visit() (objs []interface{}, err error) {
err = filepath.WalkDir(v.Path, func(filePath string, d os.DirEntry, err error) error {
if err != nil {
return err
}
// check file extension
if ignoreFile(filePath, FileExtensions) {
return nil
}
f, err := os.Open(filePath)
if err != nil {
return err
}
decoder := yaml.NewYAMLOrJSONDecoder(f, 4096)
for {
data := make(map[string]interface{})
if err := decoder.Decode(&data); err != nil {
if err == io.EOF {
return nil
}
return fmt.Errorf("error parsing %s: %v", filePath, err)
}
if len(data) == 0 {
continue
}
objs = append(objs, data)
}
})
return objs, err
}
// ignoreFile indicates a filename is ended with specified extension or not
func ignoreFile(path string, extensions []string) bool {
if len(extensions) == 0 {
return false
}
ext := filepath.Ext(path)
for _, s := range extensions {
if strings.EqualFold(s, ext) {
return false
}
}
return true
}