-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathfolder_handler.go
More file actions
80 lines (62 loc) · 1.77 KB
/
folder_handler.go
File metadata and controls
80 lines (62 loc) · 1.77 KB
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
package cmd
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
"github.com/Skarlso/crd-to-sample-yaml/pkg"
"github.com/Skarlso/crd-to-sample-yaml/pkg/sanitize"
)
// FolderHandler scans folders and returns schemas found in that folder.
type FolderHandler struct {
location string
group string
}
// CRDs goes through schemas in folders.
func (h *FolderHandler) CRDs() ([]*pkg.SchemaType, error) {
if _, err := os.Stat(h.location); os.IsNotExist(err) {
return nil, fmt.Errorf("file under '%s' does not exist", h.location)
}
var crds []*pkg.SchemaType
if err := filepath.Walk(h.location, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".yaml" {
_, _ = fmt.Fprintln(os.Stderr, "skipping file "+path)
return nil
}
content, err := os.ReadFile(filepath.Clean(path))
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
content, err = sanitize.Sanitize(content)
if err != nil {
return fmt.Errorf("failed to sanitize content: %w", err)
}
crd := &unstructured.Unstructured{}
if err := yaml.Unmarshal(content, crd); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "skipping none CRD file: "+path)
return nil //nolint:nilerr // intentional
}
schemaType, err := pkg.ExtractSchemaType(crd)
if err != nil {
return fmt.Errorf("failed to extract schema type: %w", err)
}
if schemaType != nil {
if h.group != "" {
schemaType.Rendering = pkg.Rendering{Group: h.group}
}
crds = append(crds, schemaType)
}
return nil
}); err != nil {
return nil, fmt.Errorf("failed to walk the selected folder: %w", err)
}
return crds, nil
}