-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.go
95 lines (85 loc) · 2.53 KB
/
builder.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
84
85
86
87
88
89
90
91
92
93
94
95
package kgen
import (
"fmt"
"os"
"path"
"strings"
"github.com/blesswinsamuel/kgen/internal"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
type WriteOpts struct {
Outdir string
DeleteOutDir bool
PatchObject func(ApiObject) error
}
type Builder interface {
Scope
WriteYAMLsToDisk(opts WriteOpts) error
}
type BuilderOptions struct {
SchemeBuilder runtime.SchemeBuilder
}
type builder struct {
Scope
}
func NewBuilder(opts BuilderOptions) Builder {
scheme := runtime.NewScheme()
utilruntime.Must(opts.SchemeBuilder.AddToScheme(scheme))
scope := newScope("__root__", ScopeProps{}, &globalContext{
scheme: scheme,
})
return &builder{
Scope: scope,
}
}
func constructFilenameToApiObjectsMap(files map[string][]ApiObject, scope *scope, currentScopeID []string, level int) error {
if scope == nil {
return nil
}
if len(scope.objects) > 0 {
currentScopeID := strings.Join(currentScopeID, "-")
files[currentScopeID] = append(files[currentScopeID], scope.objects...)
}
for i, childNode := range scope.children {
thisScopeID := append(currentScopeID, fmt.Sprintf("%02d", i+1), childNode.ID())
if err := constructFilenameToApiObjectsMap(files, childNode, thisScopeID, level+1); err != nil {
return fmt.Errorf("constructFilenameToApiObjectsMap: %w", err)
}
}
return nil
}
func (a *builder) WriteYAMLsToDisk(opts WriteOpts) error {
if opts.PatchObject != nil {
a.Scope.(*scope).patchObjects(opts.PatchObject)
}
files := map[string][]ApiObject{} // map[filename]apiObjects
if err := constructFilenameToApiObjectsMap(files, a.Scope.(*scope), []string{}, 0); err != nil {
return fmt.Errorf("constructFilenameToApiObjectsMap: %w", err)
}
fileContents := map[string][]byte{}
for _, currentScopeID := range internal.MapKeysSorted(files) {
apiObjects := files[currentScopeID]
filePath := path.Join(opts.Outdir, fmt.Sprintf("%s.yaml", currentScopeID))
for i, apiObject := range apiObjects {
if i > 0 {
fileContents[filePath] = append(fileContents[filePath], []byte("---\n")...)
}
fileContents[filePath] = append(fileContents[filePath], apiObject.ToYAML()...)
}
}
if opts.DeleteOutDir {
if err := os.RemoveAll(opts.Outdir); err != nil {
return fmt.Errorf("RemoveAll: %w", err)
}
}
if err := os.MkdirAll(opts.Outdir, 0755); err != nil {
return fmt.Errorf("MkdirAll: %w", err)
}
for filePath, fileContent := range fileContents {
if err := os.WriteFile(filePath, fileContent, 0644); err != nil {
return fmt.Errorf("WriteFile: %w", err)
}
}
return nil
}