This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathtemplate.go
338 lines (293 loc) · 8.92 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
package funcs
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
ctyconvert "github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
)
// MakeTemplateFuncs adds the template functions to the function map. The
// template family of functions has access to the context, except they cannot
// call further template functions.
func MakeTemplateFuncs(hclCtx *hcl.EvalContext) map[string]function.Function {
// Create a child context cause we're going to put template stubs in it.
hclCtx = hclCtx.NewChild()
hclCtx.Functions = map[string]function.Function{}
// Get all our specs
specs := map[string]*function.Spec{
"templatestring": makeTemplateString(hclCtx),
"templatefile": makeTemplateFile(hclCtx),
"templatedir": makeTemplateDir(hclCtx),
}
// Override each to prevent template calls within template calls, for now.
for k, spec := range specs {
kCopy := k // have to copy since loops reuse variables
specCopy := *spec
specCopy.Type = func(args []cty.Value) (cty.Type, error) {
return cty.NilType, fmt.Errorf(
"cannot call %s from inside a template function",
kCopy)
}
hclCtx.Functions[k] = function.New(&specCopy)
}
result := map[string]function.Function{}
for k, spec := range specs {
result[k] = function.New(spec)
}
return result
}
func makeTemplateString(hclCtx *hcl.EvalContext) *function.Spec {
loadTmpl := func(v string) (hcl.Expression, error) {
expr, diags := hclsyntax.ParseTemplate([]byte(v), "template", hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return nil, diags
}
return expr, nil
}
return &function.Spec{
Params: []function.Parameter{
{
Name: "template",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "vars",
Type: cty.DynamicPseudoType,
},
Type: func(args []cty.Value) (cty.Type, error) {
for _, arg := range args {
if !arg.IsKnown() {
return cty.DynamicPseudoType, nil
}
}
// We'll render our template now to see what result type it produces.
// A template consisting only of a single interpolation an potentially
// return any type.
expr, err := loadTmpl(args[0].AsString())
if err != nil {
return cty.DynamicPseudoType, err
}
// This is safe even if args[1] contains unknowns because the HCL
// template renderer itself knows how to short-circuit those.
val, err := renderTmpl(expr, hclCtx, args[1:]...)
return val.Type(), err
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
expr, err := loadTmpl(args[0].AsString())
if err != nil {
return cty.DynamicVal, err
}
return renderTmpl(expr, hclCtx, args[1:]...)
},
}
}
func makeTemplateFile(hclCtx *hcl.EvalContext) *function.Spec {
loadTmpl := func(fn string) (hcl.Expression, error) {
// We re-use File here to ensure the same filename interpretation
// as it does, along with its other safety checks.
tmplVal, err := File(cty.StringVal(fn))
if err != nil {
return nil, err
}
expr, diags := hclsyntax.ParseTemplate([]byte(tmplVal.AsString()), fn, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return nil, diags
}
return expr, nil
}
return &function.Spec{
Params: []function.Parameter{
{
Name: "template_path",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "vars",
Type: cty.DynamicPseudoType,
},
Type: func(args []cty.Value) (cty.Type, error) {
for _, arg := range args {
if !arg.IsKnown() {
return cty.DynamicPseudoType, nil
}
}
// We'll render our template now to see what result type it produces.
// A template consisting only of a single interpolation an potentially
// return any type.
_, err := loadTmpl(args[0].AsString())
if err != nil {
return cty.DynamicPseudoType, err
}
return cty.String, nil
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
expr, err := loadTmpl(args[0].AsString())
if err != nil {
return cty.DynamicVal, err
}
val, err := renderTmpl(expr, hclCtx, args[1:]...)
if err != nil {
return cty.DynamicVal, err
}
if val.Type() != cty.String {
val, err = ctyconvert.Convert(val, cty.String)
if err != nil {
return cty.DynamicVal, err
}
}
td, err := ioutil.TempDir("", "waypoint")
if err != nil {
return cty.DynamicVal, err
}
path := filepath.Join(td, filepath.Base(args[0].AsString()))
return cty.StringVal(path), ioutil.WriteFile(path, []byte(val.AsString()), 0600)
},
}
}
func makeTemplateDir(hclCtx *hcl.EvalContext) *function.Spec {
loadTmpl := func(fn string) (hcl.Expression, error) {
// We re-use File here to ensure the same filename interpretation
// as it does, along with its other safety checks.
tmplVal, err := File(cty.StringVal(fn))
if err != nil {
return nil, err
}
expr, diags := hclsyntax.ParseTemplate([]byte(tmplVal.AsString()), fn, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return nil, diags
}
return expr, nil
}
return &function.Spec{
Params: []function.Parameter{
{
Name: "dir",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "vars",
Type: cty.DynamicPseudoType,
},
Type: func(args []cty.Value) (cty.Type, error) {
for _, arg := range args {
if !arg.IsKnown() {
return cty.DynamicPseudoType, nil
}
}
return cty.String, nil
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
td, err := ioutil.TempDir("", "waypoint")
if err != nil {
return cty.DynamicVal, err
}
root := args[0].AsString()
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
dir := td
// Determine if we have any directory
stripped := strings.TrimPrefix(path, root)
if len(stripped) == 0 {
panic("empty path") // should never happen
}
if stripped[0] == '/' || stripped[0] == '\\' {
// Get rid of any prefix '/' which could happen if tpl.Path doesn't
// end in a directory sep.
stripped = stripped[1:]
}
if v := filepath.Dir(stripped); v != "." {
dir = filepath.Join(dir, v)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
}
// Render
expr, err := loadTmpl(path)
if err != nil {
return err
}
val, err := renderTmpl(expr, hclCtx, args[1:]...)
if err != nil {
return err
}
if val.Type() != cty.String {
val, err = ctyconvert.Convert(val, cty.String)
if err != nil {
return err
}
}
// We'll copy the file into the temporary directory
path = filepath.Join(dir, filepath.Base(path))
return ioutil.WriteFile(path, []byte(val.AsString()), 0600)
})
if err != nil {
return cty.DynamicVal, err
}
return cty.StringVal(td), nil
},
}
}
func renderTmpl(expr hcl.Expression, parentCtx *hcl.EvalContext, varsVal ...cty.Value) (cty.Value, error) {
// Validate all user-supplied variables are maps/objects
for _, v := range varsVal {
if varsTy := v.Type(); !(varsTy.IsMapType() || varsTy.IsObjectType()) {
return cty.DynamicVal, function.NewArgErrorf(1, "invalid vars value: must be a map")
}
}
// Add user-supplied variables to our context
child := parentCtx.NewChild()
child.Variables = map[string]cty.Value{}
for _, val := range varsVal {
for k, v := range val.AsValueMap() {
child.Variables[k] = v
}
}
// We require all of the variables to be valid HCL identifiers, because
// otherwise there would be no way to refer to them in the template
// anyway. Rejecting this here gives better feedback to the user
// than a syntax error somewhere in the template itself.
for n := range child.Variables {
if !hclsyntax.ValidIdentifier(n) {
// This error message intentionally doesn't describe _all_ of
// the different permutations that are technically valid as an
// HCL identifier, but rather focuses on what we might
// consider to be an "idiomatic" variable name.
return cty.DynamicVal, function.NewArgErrorf(1, "invalid template variable name %q: must start with a letter, followed by zero or more letters, digits, and underscores", n)
}
}
// We'll pre-check references in the template here so we can give a
// more specialized error message than HCL would by default, so it's
// clearer that this problem is coming from a templatefile call.
hasVar := func(n string) bool {
for ctx := child; ctx != nil; ctx = ctx.Parent() {
if _, ok := ctx.Variables[n]; ok {
return true
}
}
return false
}
for _, traversal := range expr.Variables() {
root := traversal.RootName()
if !hasVar(root) {
return cty.DynamicVal, function.NewArgErrorf(1, "vars map does not contain key %q, referenced at %s", root, traversal[0].SourceRange())
}
}
val, diags := expr.Value(child)
if diags.HasErrors() {
return cty.DynamicVal, diags
}
return val, nil
}