-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrender.go
More file actions
360 lines (340 loc) · 11.9 KB
/
Copy pathrender.go
File metadata and controls
360 lines (340 loc) · 11.9 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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package sawchain
import (
"bytes"
"context"
"os"
"github.com/onsi/gomega"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
"github.com/guidewire-oss/sawchain/internal/chainsaw"
"github.com/guidewire-oss/sawchain/internal/options"
"github.com/guidewire-oss/sawchain/internal/util"
)
// RenderSingle renders a single-resource Chainsaw template (or unmarshals a static manifest) into
// an object and returns it.
//
// # Arguments
//
// The following arguments may be provided in any order:
//
// - Template (string): Required. File path or content of a static manifest or Chainsaw template to render.
// Must contain exactly one complete resource definition matching the type of the object (if provided).
//
// - Bindings (map[string]any): Bindings to be applied to the Chainsaw template (if provided) in addition
// to (or overriding) Sawchain's global bindings. If multiple maps are provided, they will be merged in
// natural order.
//
// - Object (client.Object): Typed or unstructured object to render into.
//
// When no object is provided, RenderSingle attempts to return a typed object. If a typed object cannot be
// created (i.e., if the client scheme does not support the necessary type), an unstructured object will be
// returned instead.
//
// # Notes
//
// - Invalid input will result in immediate test failure.
//
// - When dealing with typed objects, the client scheme will be used for internal conversions.
//
// - Templates will be sanitized before use, including de-indenting (removing any common leading
// whitespace prefix from non-empty lines) and pruning empty documents.
//
// - RenderSingle supports two usage modes: returning a client.Object for use in generic worklows, or
// populating a provided client.Object pointer for type-safe access (without needing type assertions).
//
// - With populate mode, the provided object will also be returned.
//
// # Examples
//
// Render a template with bindings (return mode, generic):
//
// obj := sc.RenderSingle(`
// apiVersion: v1
// kind: ConfigMap
// metadata:
// name: ($name)
// namespace: ($namespace)
// data:
// key: value
// `, map[string]any{"name": "test-cm", "namespace": "default"})
//
// Render a template with bindings (populate mode, type-safe):
//
// configMap := &corev1.ConfigMap{}
// sc.RenderSingle(configMap, `
// apiVersion: v1
// kind: ConfigMap
// metadata:
// name: ($name)
// namespace: ($namespace)
// data:
// key: value
// `, map[string]any{"name": "test-cm", "namespace": "default"})
//
// Unmarshal a static manifest file (populate mode, type-safe):
//
// configMap := &corev1.ConfigMap{}
// sc.RenderSingle(configMap, "path/to/configmap.yaml")
func (s *Sawchain) RenderSingle(args ...any) client.Object {
s.t.Helper()
// Parse options
opts, err := options.ParseAndApplyDefaults(&s.opts, false, false, true, false, true, args...)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidArgs)
s.g.Expect(opts).NotTo(gomega.BeNil(), errNilOpts)
// Check required options
s.g.Expect(options.RequireTemplate(opts)).To(gomega.Succeed(), errInvalidArgs)
// Render template
bindings, err := chainsaw.BindingsFromMap(opts.Bindings)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidBindings)
unstructuredObj, err := chainsaw.RenderTemplateSingle(context.TODO(), opts.Template, bindings)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidTemplate)
// Save/return object
if opts.Object != nil {
s.g.Expect(util.CopyUnstructuredToObject(s.c, unstructuredObj, opts.Object)).To(gomega.Succeed(), errFailedSave)
return opts.Object
} else {
return s.convertReturnObject(unstructuredObj)
}
}
// RenderMultiple renders a multi-resource Chainsaw template (or unmarshals a static manifest) into
// a slice of objects and returns it.
//
// # Arguments
//
// The following arguments may be provided in any order:
//
// - Template (string): Required. File path or content of a static manifest or Chainsaw template to render.
// Must contain complete resource definitions exactly matching the count, order, and types of the objects
// (if provided).
//
// - Bindings (map[string]any): Bindings to be applied to the Chainsaw template (if provided) in addition
// to (or overriding) Sawchain's global bindings. If multiple maps are provided, they will be merged in
// natural order.
//
// - Objects ([]client.Object): Slice of typed or unstructured objects to render into.
//
// When no objects are provided, RenderMultiple attempts to return typed objects. If typed objects cannot be
// created (i.e., if the client scheme does not support the necessary types), unstructured objects will be
// returned instead.
//
// # Notes
//
// - Invalid input will result in immediate test failure.
//
// - When dealing with typed objects, the client scheme will be used for internal conversions.
//
// - Templates will be sanitized before use, including de-indenting (removing any common leading
// whitespace prefix from non-empty lines) and pruning empty documents.
//
// - RenderMultiple supports two usage modes: returning a slice of client.Object for use in generic
// worklows, or populating a slice of provided client.Object pointers for type-safe access
// (without needing type assertions).
//
// - With populate mode, the provided objects will also be returned.
//
// # Examples
//
// Render a template with bindings (return mode, generic):
//
// objs := sc.RenderMultiple(`
// apiVersion: v1
// kind: ConfigMap
// metadata:
// name: (concat($prefix, '-cm'))
// namespace: ($namespace)
// data:
// key: value
// ---
// apiVersion: v1
// kind: Secret
// metadata:
// name: (concat($prefix, '-secret'))
// namespace: ($namespace)
// type: Opaque
// stringData:
// username: admin
// password: secret
// `, map[string]any{"prefix": "test", "namespace": "default"})
//
// Render a template with bindings (populate mode, type-safe):
//
// configMap := &corev1.ConfigMap{}
// secret := &corev1.Secret{}
// sc.RenderMultiple([]client.Object{configMap, secret}, `
// apiVersion: v1
// kind: ConfigMap
// metadata:
// name: (concat($prefix, '-cm'))
// namespace: ($namespace)
// data:
// key: value
// ---
// apiVersion: v1
// kind: Secret
// metadata:
// name: (concat($prefix, '-secret'))
// namespace: ($namespace)
// type: Opaque
// stringData:
// username: admin
// password: secret
// `, map[string]any{"prefix": "test", "namespace": "default"})
//
// Unmarshal a static manifest file (populate mode, type-safe):
//
// configMap := &corev1.ConfigMap{}
// secret := &corev1.Secret{}
// sc.RenderMultiple([]client.Object{configMap, secret}, "path/to/resources.yaml")
func (s *Sawchain) RenderMultiple(args ...any) []client.Object {
s.t.Helper()
// Parse options
opts, err := options.ParseAndApplyDefaults(&s.opts, false, false, false, true, true, args...)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidArgs)
s.g.Expect(opts).NotTo(gomega.BeNil(), errNilOpts)
// Check required options
s.g.Expect(options.RequireTemplate(opts)).To(gomega.Succeed(), errInvalidArgs)
// Render template
bindings, err := chainsaw.BindingsFromMap(opts.Bindings)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidBindings)
unstructuredObjs, err := chainsaw.RenderTemplate(context.TODO(), opts.Template, bindings)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidTemplate)
// Validate objects length
if opts.Objects != nil {
s.g.Expect(opts.Objects).To(gomega.HaveLen(len(unstructuredObjs)), errObjectsWrongLength)
}
// Save/return objects
if opts.Objects != nil {
for i, unstructuredObj := range unstructuredObjs {
s.g.Expect(util.CopyUnstructuredToObject(s.c, unstructuredObj, opts.Objects[i])).To(gomega.Succeed(), errFailedSave)
}
return opts.Objects
} else {
objs := make([]client.Object, len(unstructuredObjs))
for i, unstructuredObj := range unstructuredObjs {
objs[i] = s.convertReturnObject(unstructuredObj)
}
return objs
}
}
// RenderToString renders a Chainsaw template with optional bindings into a YAML string.
//
// # Arguments
//
// - Template (string): File path or content of a Chainsaw template to render.
//
// - Bindings (map[string]any): Bindings to be applied to the template in addition to (or overriding)
// Sawchain's global bindings. If multiple maps are provided, they will be merged in natural order.
//
// # Notes
//
// - Invalid input and marshaling errors will result in immediate test failure.
//
// - Templates will be sanitized before use, including de-indenting (removing any common leading
// whitespace prefix from non-empty lines) and pruning empty documents.
//
// # Examples
//
// Render a template with bindings:
//
// yaml := sc.RenderToString(`
// apiVersion: v1
// kind: ConfigMap
// metadata:
// name: (concat($prefix, '-cm'))
// namespace: ($namespace)
// data:
// key: value
// ---
// apiVersion: v1
// kind: Secret
// metadata:
// name: (concat($prefix, '-secret'))
// namespace: ($namespace)
// type: Opaque
// stringData:
// username: admin
// password: secret
// `, map[string]any{"prefix": "test", "namespace": "default"})
//
// Render a template file with bindings:
//
// yaml := sc.RenderToString("path/to/template.yaml",
// map[string]any{"prefix": "test", "namespace": "default"})
func (s *Sawchain) RenderToString(template string, bindings ...map[string]any) string {
s.t.Helper()
// Process template
var err error
template, err = options.ProcessTemplate(template)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidArgs)
// Render template
b, err := chainsaw.BindingsFromMap(s.mergeBindings(bindings...))
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidBindings)
objs, err := chainsaw.RenderTemplate(context.TODO(), template, b)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errInvalidTemplate)
// Marshal objects
var buf bytes.Buffer
for i, obj := range objs {
y, err := yaml.Marshal(obj.Object)
s.g.Expect(err).NotTo(gomega.HaveOccurred(), errFailedMarshalObject)
if i > 0 {
buf.WriteString("---\n")
}
buf.Write(y)
buf.WriteString("\n")
}
return buf.String()
}
// RenderToFile renders a Chainsaw template with optional bindings and writes it to a file.
//
// # Arguments
//
// - Filepath (string): The file path where the rendered YAML will be written.
//
// - Template (string): File path or content of a Chainsaw template to render.
//
// - Bindings (map[string]any): Bindings to be applied to the template in addition to (or overriding)
// Sawchain's global bindings. If multiple maps are provided, they will be merged in natural order.
//
// # Notes
//
// - Invalid input, marshaling errors, and I/O errors will result in immediate test failure.
//
// - Templates will be sanitized before use, including de-indenting (removing any common leading
// whitespace prefix from non-empty lines) and pruning empty documents.
//
// - When running tests in parallel, use unique file paths per process to prevent write collisions.
// See docs/parallel-tests.md for isolation strategies.
//
// # Examples
//
// Render a template to a file:
//
// sc.RenderToFile("output.yaml", `
// apiVersion: v1
// kind: ConfigMap
// metadata:
// name: (concat($prefix, '-cm'))
// namespace: ($namespace)
// data:
// key: value
// ---
// apiVersion: v1
// kind: Secret
// metadata:
// name: (concat($prefix, '-secret'))
// namespace: ($namespace)
// type: Opaque
// stringData:
// username: admin
// password: secret
// `, map[string]any{"prefix": "test", "namespace": "default"})
//
// Render a template file to another file:
//
// sc.RenderToFile("output.yaml", "path/to/template.yaml",
// map[string]any{"prefix": "test", "namespace": "default"})
func (s *Sawchain) RenderToFile(filepath, template string, bindings ...map[string]any) {
s.t.Helper()
rendered := s.RenderToString(template, bindings...)
s.g.Expect(os.WriteFile(filepath, []byte(rendered), 0644)).To(gomega.Succeed(), errFailedWrite)
}