forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
401 lines (320 loc) · 8.77 KB
/
template.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package template
import (
"fmt"
"regexp"
"sort"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
"github.com/cppforlife/go-patch/patch"
"gopkg.in/yaml.v2"
)
type Template struct {
bytes []byte
}
type EvaluateOpts struct {
ExpectAllKeys bool
ExpectAllVarsUsed bool
PostVarSubstitutionOp patch.Op
UnescapedMultiline bool
}
func NewTemplate(bytes []byte) Template {
return Template{bytes: bytes}
}
func (t Template) Evaluate(vars Variables, op patch.Op, opts EvaluateOpts) ([]byte, error) {
var obj interface{}
err := yaml.Unmarshal(t.bytes, &obj)
if err != nil {
return []byte{}, err
}
if op != nil {
obj, err = op.Apply(obj)
if err != nil {
return []byte{}, err
}
}
obj, err = t.interpolateRoot(obj, newVarsTracker(vars, opts.ExpectAllKeys, opts.ExpectAllVarsUsed))
if err != nil {
return []byte{}, err
}
if opts.PostVarSubstitutionOp != nil {
obj, err = opts.PostVarSubstitutionOp.Apply(obj)
if err != nil {
return []byte{}, err
}
}
if _, ok := obj.(string); opts.UnescapedMultiline && ok {
return []byte(fmt.Sprintf("%s\n", obj)), nil
}
bytes, err := yaml.Marshal(obj)
if err != nil {
return []byte{}, err
}
return bytes, nil
}
func (t Template) interpolateRoot(obj interface{}, tracker varsTracker) (interface{}, error) {
err := tracker.ExtractDefinitions(obj)
if err != nil {
return nil, err
}
obj, err = interpolator{}.Interpolate(obj, varsLookup{tracker})
if err != nil {
return nil, err
}
obj, err = tracker.FoundVars(obj)
if err != nil {
return nil, err
}
return obj, tracker.Error()
}
type interpolator struct{}
var (
interpolationRegex = regexp.MustCompile(`\(\((!?[-/\.\w\pL]+)\)\)`)
interpolationAnchoredRegex = regexp.MustCompile("\\A" + interpolationRegex.String() + "\\z")
)
func (i interpolator) Interpolate(node interface{}, varsLookup varsLookup) (interface{}, error) {
switch typedNode := node.(type) {
case map[interface{}]interface{}:
for k, v := range typedNode {
evaluatedValue, err := i.Interpolate(v, varsLookup)
if err != nil {
return nil, err
}
evaluatedKey, err := i.Interpolate(k, varsLookup)
if err != nil {
return nil, err
}
delete(typedNode, k) // delete in case key has changed
typedNode[evaluatedKey] = evaluatedValue
}
case []interface{}:
for idx, x := range typedNode {
var err error
typedNode[idx], err = i.Interpolate(x, varsLookup)
if err != nil {
return nil, err
}
}
case string:
for _, name := range i.extractVarNames(typedNode) {
foundVal, found, err := varsLookup.Get(name)
if err != nil {
return nil, bosherr.WrapErrorf(err, "Finding variable '%s'", name)
}
if found {
// ensure that value type is preserved when replacing the entire field
if interpolationAnchoredRegex.MatchString(typedNode) {
return foundVal, nil
}
switch foundVal.(type) {
case string, int, int16, int32, int64, uint, uint16, uint32, uint64:
foundValStr := fmt.Sprintf("%v", foundVal)
typedNode = strings.Replace(typedNode, fmt.Sprintf("((%s))", name), foundValStr, -1)
typedNode = strings.Replace(typedNode, fmt.Sprintf("((!%s))", name), foundValStr, -1)
default:
errMsg := "Invalid type '%T' for value '%v' and variable '%s'. Supported types for interpolation within a string are integers and strings."
return nil, fmt.Errorf(errMsg, foundVal, foundVal, name)
}
}
}
return typedNode, nil
}
return node, nil
}
func (i interpolator) extractVarNames(value string) []string {
var names []string
for _, match := range interpolationRegex.FindAllSubmatch([]byte(value), -1) {
names = append(names, strings.TrimPrefix(string(match[1]), "!"))
}
return names
}
type varsLookup struct {
varsTracker
}
func (l varsLookup) Get(name string) (interface{}, bool, error) {
splitName := strings.Split(name, ".")
val, found, err := l.varsTracker.Get(splitName[0])
if !found || err != nil {
return val, found, err
}
if len(splitName) > 1 {
tokens := []patch.Token{patch.RootToken{}}
for _, token := range splitName[1:] {
tokens = append(tokens, patch.KeyToken{Key: token})
}
findOp := patch.FindOp{
Path: patch.NewPointer(tokens),
}
val, err = findOp.Apply(val)
if err != nil {
return nil, false, err
}
}
return val, true, err
}
type varsTracker struct {
vars Variables
defs varDefinitions
expectAllFound bool
expectAllUsed bool
missing map[string]struct{} // track missing var names
visited map[string]struct{}
visitedAll map[string]struct{} // track all var names that were accessed
}
func newVarsTracker(vars Variables, expectAllFound, expectAllUsed bool) varsTracker {
return varsTracker{
vars: vars,
expectAllFound: expectAllFound,
expectAllUsed: expectAllUsed,
missing: map[string]struct{}{},
visited: map[string]struct{}{},
visitedAll: map[string]struct{}{},
}
}
func (t varsTracker) Get(name string) (interface{}, bool, error) {
t.visitedAll[name] = struct{}{}
defVarTracker, err := t.scopedVarsTracker(name)
if err != nil {
return nil, false, err
}
def := t.defs.Find(name)
def.Options, err = interpolator{}.Interpolate(def.Options, varsLookup{defVarTracker})
if err != nil {
return nil, false, bosherr.WrapErrorf(err, "Interpolating variable '%s' definition options", name)
}
if len(defVarTracker.missing) > 0 {
return nil, false, nil
}
for name, _ := range defVarTracker.missing {
t.missing[name] = struct{}{}
}
val, found, err := t.vars.Get(def)
if !found {
t.missing[name] = struct{}{}
}
return val, found, err
}
func (t varsTracker) scopedVarsTracker(name string) (varsTracker, error) {
if _, found := t.visited[name]; found {
return varsTracker{}, bosherr.Error("Detected recursion")
}
varsTracker := newVarsTracker(t.vars, t.expectAllFound, t.expectAllUsed)
varsTracker.defs = t.defs
varsTracker.visited[name] = struct{}{}
for k, _ := range t.visited {
varsTracker.visited[k] = struct{}{}
}
return varsTracker, nil
}
func (t *varsTracker) ExtractDefinitions(obj interface{}) error {
if _, isMap := obj.(map[interface{}]interface{}); isMap {
defsBytes, err := yaml.Marshal(obj)
if err != nil {
return err
}
err = yaml.Unmarshal(defsBytes, &t.defs)
if err != nil {
return err
}
}
// Run through all variable definitions in order
// to provide basic variable dependency management (ie sort definitions manually)
for _, def := range t.defs.Definitions {
if len(def.Type) > 0 {
_, _, err := t.Get(def.Name)
if err != nil {
return bosherr.WrapError(err, "Getting all variables from variable definitions sections")
}
}
}
return nil
}
func (t varsTracker) FoundVars(obj interface{}) (interface{}, error) {
var foundDefs []string
var err error
for _, def := range t.defs.Definitions {
_, found, err := t.Get(def.Name)
if err != nil {
return nil, bosherr.WrapError(err, "Getting all variables from variable definitions sections")
}
if found {
foundDefs = append(foundDefs, def.Name)
}
}
for _, name := range foundDefs {
removeKeyOp := patch.RemoveOp{
Path: patch.NewPointer([]patch.Token{
patch.RootToken{},
patch.KeyToken{Key: "variables"},
patch.MatchingIndexToken{Key: "name", Value: name},
}),
}
obj, err = removeKeyOp.Apply(obj)
if err != nil {
return nil, err
}
}
return obj, err
}
func (t varsTracker) Error() error {
var errs []error
missingErr := t.MissingError()
if missingErr != nil {
errs = append(errs, missingErr)
}
extraErr := t.ExtraError()
if extraErr != nil {
errs = append(errs, extraErr)
}
if len(errs) > 0 {
return bosherr.NewMultiError(errs...)
}
return nil
}
func (t varsTracker) MissingError() error {
if !t.expectAllFound || len(t.missing) == 0 {
return nil
}
return bosherr.WrapError(t.multiErr(t.missing), "Expected to find variables")
}
func (t varsTracker) ExtraError() error {
if !t.expectAllUsed {
return nil
}
allDefs, err := t.vars.List()
if err != nil {
return err
}
unusedNames := map[string]struct{}{}
for _, def := range allDefs {
if _, found := t.visitedAll[def.Name]; !found {
unusedNames[def.Name] = struct{}{}
}
}
if len(unusedNames) == 0 {
return nil
}
return bosherr.WrapError(t.multiErr(unusedNames), "Expected to use variables")
}
func (t varsTracker) multiErr(mapWithNames map[string]struct{}) error {
var names []string
for name, _ := range mapWithNames {
names = append(names, name)
}
sort.Strings(names)
var errs []error
for _, name := range names {
errs = append(errs, bosherr.Error(name))
}
return bosherr.NewMultiError(errs...)
}
type varDefinitions struct {
Definitions []VariableDefinition `yaml:"variables"`
}
func (defs varDefinitions) Find(name string) VariableDefinition {
for _, def := range defs.Definitions {
if def.Name == name {
return def
}
}
return VariableDefinition{Name: name}
}