-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.go
192 lines (176 loc) · 6.21 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package kgen
import (
"fmt"
"os"
"path"
"strings"
"github.com/blesswinsamuel/kgen/internal"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
type yamlOutputType string
// inspired by cdk8s (https://cdk8s.io/docs/latest/reference/cdk8s/python/#yamloutputtype)
const (
// All resources are output into a single YAML file.
YamlOutputTypeSingleFile yamlOutputType = "single"
// Resources are split into seperate files by scope.
YamlOutputTypeFilePerScope yamlOutputType = "scope"
// Each resource is output to its own file.
YamlOutputTypeFilePerResource yamlOutputType = "resource"
// Each resource is output to its own file in a folder named after the scope.
YamlOutputTypeFolderPerScopeFilePerResource yamlOutputType = "folder"
// Resources are split into seperate files by scope, while creating a folder for each scope.
YamlOutputTypeFolderPerScopeFilePerLeafScope yamlOutputType = "folder-per-parent"
)
type RenderManifestsOptions struct {
// The directory to write the YAML files to. If set to "-", the YAML files will be written to stdout.
Outdir string
// The output format for the YAML files.
YamlOutputType yamlOutputType
// Include a number in the filenames to maintain order.
IncludeNumberInFilenames bool
// Delete the output directory before writing the YAML files.
DeleteOutDir bool
// PatchObject is a function that can be used to modify the ApiObjects before they are rendered.
PatchObject func(ApiObject) error
}
// Builder is the main interface for adding Kubernetes API objects and rendering them to YAML files.
type Builder interface {
Scope
// RenderManifests writes the Kubernetes API objects to disk or stdout in YAML format.
RenderManifests(opts RenderManifestsOptions)
}
type BuilderOptions struct {
// SchemeBuilder is used to add custom Kubernetes API types to the scheme.
SchemeBuilder runtime.SchemeBuilder
// Logger is used to log messages. If not set, a default logger is used.
Logger Logger
}
type builder struct {
Scope
}
type globalContext struct {
scheme *runtime.Scheme
logger Logger
}
// NewBuilder creates a new Builder instance.
func NewBuilder(opts BuilderOptions) Builder {
if opts.SchemeBuilder == nil {
panic("SchemeBuilder is required")
}
scheme := runtime.NewScheme()
utilruntime.Must(opts.SchemeBuilder.AddToScheme(scheme))
if opts.Logger == nil {
opts.Logger = NewCustomLogger(nil)
}
scope := newScope("__root__", ScopeProps{}, &globalContext{
scheme: scheme,
logger: opts.Logger,
})
return &builder{
Scope: scope,
}
}
func getObjectNameAndNamespace(apiObject ApiObject) string {
obj := apiObject.GetObject().(*unstructured.Unstructured)
out := []string{}
for _, part := range []string{obj.GetNamespace(), strings.ToLower(obj.GetKind()), obj.GetName()} {
if part != "" {
out = append(out, part)
}
}
return strings.Join(out, "-")
}
func constructFilenameToApiObjectsMap(files map[string][]ApiObject, scope *scope, currentScopeID []string, level int, opts RenderManifestsOptions) {
if scope == nil {
return
}
sprintfWithNumber := func(n int, s string) string {
if opts.IncludeNumberInFilenames {
return fmt.Sprintf("%02d-%s", n, s)
}
return s
}
if len(scope.objects) > 0 {
switch opts.YamlOutputType {
case YamlOutputTypeSingleFile:
filePath := "all"
files[filePath] = append(files[filePath], scope.objects...)
case YamlOutputTypeFilePerResource:
for i, apiObject := range scope.objects {
filePath := strings.Join([]string{strings.Join(currentScopeID, "-"), sprintfWithNumber(i+1, getObjectNameAndNamespace(apiObject))}, "-")
files[filePath] = append(files[filePath], apiObject)
}
case YamlOutputTypeFilePerScope:
filePath := strings.Join(currentScopeID, "-")
files[filePath] = append(files[filePath], scope.objects...)
case YamlOutputTypeFolderPerScopeFilePerResource:
filePath := path.Join(currentScopeID...)
if len(scope.children) > 0 {
filePath = path.Join(filePath, sprintfWithNumber(0, scope.ID()))
}
for i, apiObject := range scope.objects {
filePath := path.Join(filePath, sprintfWithNumber(i+1, getObjectNameAndNamespace(apiObject)))
files[filePath] = append(files[filePath], apiObject)
}
case YamlOutputTypeFolderPerScopeFilePerLeafScope:
filePath := path.Join(path.Join(currentScopeID...))
if len(scope.children) > 0 {
filePath = path.Join(filePath, sprintfWithNumber(0, scope.ID()))
}
files[filePath] = append(files[filePath], scope.objects...)
}
}
for i, childScope := range scope.children {
thisScopeID := append(currentScopeID, sprintfWithNumber(i+1, childScope.ID()))
constructFilenameToApiObjectsMap(files, childScope, thisScopeID, level+1, opts)
}
}
func (a *builder) RenderManifests(opts RenderManifestsOptions) {
if opts.PatchObject != nil {
if err := a.Scope.WalkApiObjects(opts.PatchObject); err != nil {
a.Logger().Panicf("PatchObject: %v", err)
}
}
if opts.YamlOutputType == "" {
opts.YamlOutputType = YamlOutputTypeSingleFile
}
files := map[string][]ApiObject{} // map[filename]apiObjects
constructFilenameToApiObjectsMap(files, a.Scope.(*scope), []string{}, 0, opts)
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.Outdir == "-" || opts.Outdir == "" {
for i, filePath := range internal.MapKeysSorted(fileContents) {
fileContent := fileContents[filePath]
if i > 0 {
fmt.Println("---")
}
fmt.Println(string(fileContent))
}
return
}
if opts.DeleteOutDir {
if err := os.RemoveAll(opts.Outdir); err != nil {
a.Logger().Panicf("RemoveAll: %v", err)
}
}
for filePath, fileContent := range fileContents {
parentDir := path.Dir(filePath)
if err := os.MkdirAll(parentDir, 0755); err != nil {
a.Logger().Panicf("MkdirAll: %v", err)
}
if err := os.WriteFile(filePath, fileContent, 0644); err != nil {
a.Logger().Panicf("WriteFile: %v", err)
}
}
}