-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparameter.go
442 lines (376 loc) · 10.8 KB
/
parameter.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package extract
import (
"fmt"
"strings"
"github.com/aquasecurity/trivy/pkg/iac/terraform"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
"github.com/coder/preview/hclext"
"github.com/coder/preview/types"
)
func ParameterFromBlock(block *terraform.Block) (*types.Parameter, hcl.Diagnostics) {
diags := required(block, "name")
if diags.HasErrors() {
return nil, diags
}
pType, typDiag := optionalStringEnum[types.ParameterType](block, "type", types.ParameterTypeString, func(s types.ParameterType) error {
return s.Valid()
})
if typDiag != nil {
diags = diags.Append(typDiag)
}
pName, nameDiag := requiredString(block, "name")
if nameDiag != nil {
diags = diags.Append(nameDiag)
}
if diags.HasErrors() {
return nil, diags
}
pVal := richParameterValue(block)
p := types.Parameter{
Value: pVal,
RichParameter: types.RichParameter{
Name: pName,
Description: optionalString(block, "description"),
Type: pType,
Mutable: optionalBoolean(block, "mutable"),
// Default value is always written as a string, then converted
// to the correct type.
DefaultValue: optionalString(block, "default"),
Icon: optionalString(block, "icon"),
Options: make([]*types.ParameterOption, 0),
Validations: make([]*types.ParameterValidation, 0),
Required: optionalBoolean(block, "required"),
DisplayName: optionalString(block, "display_name"),
Order: optionalInteger(block, "order"),
Ephemeral: optionalBoolean(block, "ephemeral"),
Source: block,
},
}
for _, b := range block.GetBlocks("option") {
opt, optDiags := ParameterOptionFromBlock(b)
diags = diags.Extend(optDiags)
if optDiags.HasErrors() {
continue
}
p.Options = append(p.Options, &opt)
}
validBlocks := block.GetBlocks("validation")
if len(validBlocks) > 1 {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Multiple 'validation' blocks found",
Detail: "Only one validation block is allowed",
Subject: &validBlocks[0].HCLBlock().TypeRange,
Context: &validBlocks[0].HCLBlock().DefRange,
})
}
for _, b := range block.GetBlocks("validation") {
// TODO: Only parse if only 1 valid block exists
valid, validDiags := ParameterValidationFromBlock(b)
diags = diags.Extend(validDiags)
if validDiags.HasErrors() {
continue
}
p.Validations = append(p.Validations, &valid)
}
ctyType, err := p.CtyType()
if err != nil {
paramTypeDiag := &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Invalid parameter type %q", p.Type),
Detail: err.Error(),
Context: &block.HCLBlock().DefRange,
}
if attr := block.GetAttribute("type"); attr != nil && !attr.IsNil() {
paramTypeDiag.Subject = &attr.HCLAttribute().Range
paramTypeDiag.Expression = attr.HCLAttribute().Expr
paramTypeDiag.EvalContext = block.Context().Inner()
}
diags = diags.Append(paramTypeDiag)
}
if ctyType != cty.NilType && pVal.Value.Type().Equals(cty.String) {
// TODO: Wish we could support more types, but only string types are
// allowed.
valStr := pVal.Value.AsString()
// Apply validations to the parameter value
for _, v := range p.Validations {
if err := v.Valid(string(pType), valStr); err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Paramater validation failed for value %q", valStr),
Detail: err.Error(),
Expression: pVal.ValueExpr,
})
}
}
}
// Parameter usage diags are useful.
usageDiags := ParameterUsageDiagnostics(p)
if usageDiags.HasErrors() {
p.FormControl = types.FormControlError
}
diags = diags.Extend(usageDiags)
// Diagnostics are scoped to the parameter
p.Diagnostics = types.Diagnostics(diags)
return &p, nil
}
func ParameterUsageDiagnostics(p types.Parameter) hcl.Diagnostics {
valErr := "The value of a parameter is required to be sourced (default or input) for the parameter to function."
var diags hcl.Diagnostics
if !p.Value.Valid() {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Parameter value is not valid",
Detail: valErr,
Expression: p.Value.ValueExpr,
})
} else if !p.Value.IsKnown() {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Parameter value is unknown, it likely includes a reference without a value",
Detail: valErr,
Expression: p.Value.ValueExpr,
})
}
var badOpts int
for _, opt := range p.Options {
if !opt.Value.IsKnown() || !opt.Value.Valid() {
badOpts++
}
}
if badOpts > 0 {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Parameter contains %d invalid options", badOpts),
Detail: "The set of options cannot be resolved, and use of the parameter is limited.",
})
}
return diags
}
func ParameterValidationFromBlock(block *terraform.Block) (types.ParameterValidation, hcl.Diagnostics) {
diags := required(block, "error")
if diags.HasErrors() {
return types.ParameterValidation{}, diags
}
pErr, errDiag := requiredString(block, "error")
if errDiag != nil {
diags = diags.Append(errDiag)
}
if diags.HasErrors() {
return types.ParameterValidation{}, diags
}
p := types.ParameterValidation{
Regex: nullableString(block, "regex"),
Error: pErr,
Min: nullableInteger(block, "min"),
Max: nullableInteger(block, "max"),
Monotonic: nullableString(block, "monotonic"),
}
return p, diags
}
func ParameterOptionFromBlock(block *terraform.Block) (types.ParameterOption, hcl.Diagnostics) {
diags := required(block, "name", "value")
if diags.HasErrors() {
return types.ParameterOption{}, diags
}
pName, nameDiag := requiredString(block, "name")
if nameDiag != nil {
diags = diags.Append(nameDiag)
}
valAttr := block.GetAttribute("value")
pVal := types.HCLString{
Value: hclext.Value(valAttr.HCLAttribute().Expr, block.Context().Inner()),
ValueDiags: nil,
ValueExpr: valAttr.HCLAttribute().Expr,
}
if diags.HasErrors() {
return types.ParameterOption{}, diags
}
p := types.ParameterOption{
Name: pName,
Description: optionalString(block, "description"),
Value: pVal,
Icon: optionalString(block, "icon"),
}
return p, diags
}
func optionalStringEnum[T ~string](block *terraform.Block, key string, def T, valid func(s T) error) (T, *hcl.Diagnostic) {
str := optionalString(block, key)
if str == "" {
return def, nil
}
if err := valid(T(str)); err != nil {
tyAttr := block.GetAttribute(key)
return "", &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Invalid %q attribute", key),
Detail: err.Error(),
Subject: &(tyAttr.HCLAttribute().Range),
//Context: &(block.HCLBlock().DefRange),
Expression: tyAttr.HCLAttribute().Expr,
EvalContext: block.Context().Inner(),
}
}
return T(str), nil
}
func requiredString(block *terraform.Block, key string) (string, *hcl.Diagnostic) {
tyAttr := block.GetAttribute(key)
tyVal := tyAttr.Value()
if tyVal.Type() != cty.String {
typeName := "<nil>"
if !tyVal.Type().Equals(cty.NilType) {
typeName = tyVal.Type().FriendlyName()
}
diag := &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Invalid %q attribute", key),
Detail: fmt.Sprintf("Expected a string, got %q", typeName),
Subject: &(tyAttr.HCLAttribute().Range),
//Context: &(block.HCLBlock().DefRange),
Expression: tyAttr.HCLAttribute().Expr,
EvalContext: block.Context().Inner(),
}
if !tyVal.IsWhollyKnown() {
refs := hclext.ReferenceNames(tyAttr.HCLAttribute().Expr)
if len(refs) > 0 {
diag.Detail = fmt.Sprintf("Value is not known, check the references [%s] are resolvable",
strings.Join(refs, ", "))
}
}
return "", diag
}
return tyVal.AsString(), nil
}
func optionalBoolean(block *terraform.Block, key string) bool {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return false
}
val := attr.Value()
if val.Type() != cty.Bool {
return false
}
return val.True()
}
func nullableInteger(block *terraform.Block, key string) *int64 {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return nil
}
val := attr.Value()
if val.Type() != cty.Number {
return nil
}
i, acc := val.AsBigFloat().Int64()
var _ = acc // acc should be 0
return &i
}
func optionalInteger(block *terraform.Block, key string) int64 {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return 0
}
val := attr.Value()
if val.Type() != cty.Number {
return 0
}
i, acc := val.AsBigFloat().Int64()
var _ = acc // acc should be 0
return i
}
func nullableString(block *terraform.Block, key string) *string {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return nil
}
val := attr.Value()
if val.Type() != cty.String {
return nil
}
str := val.AsString()
return &str
}
func optionalString(block *terraform.Block, key string) string {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return ""
}
val := attr.Value()
if val.Type() != cty.String {
return ""
}
return val.AsString()
}
func required(block *terraform.Block, keys ...string) hcl.Diagnostics {
var diags hcl.Diagnostics
for _, key := range keys {
attr := block.GetAttribute(key)
value := cty.NilVal
if attr != nil {
value, _ = attr.HCLAttribute().Expr.Value(block.Context().Inner())
}
if attr == nil || attr.IsNil() || value == cty.NilVal {
r := block.HCLBlock().Body.MissingItemRange()
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Missing required attribute %q", key),
Detail: fmt.Sprintf("The %s attribute is required", key),
Subject: &r,
Extra: nil,
})
}
}
return diags
}
func richParameterValue(block *terraform.Block) types.HCLString {
// Find the value of the parameter from the context.
ref := block.Reference()
travs := []hcl.Traverser{
hcl.TraverseRoot{
Name: "data",
},
hcl.TraverseAttr{
Name: ref.TypeLabel(),
},
hcl.TraverseAttr{
Name: ref.NameLabel(),
},
}
raw := ref.RawKey()
if !raw.IsNull() {
travs = append(travs, hcl.TraverseIndex{
Key: raw,
SrcRange: hcl.Range{},
})
}
travs = append(travs, hcl.TraverseAttr{
Name: "value",
})
valRef := hclsyntax.ScopeTraversalExpr{
Traversal: travs,
}
val, diags := valRef.Value(block.Context().Inner())
source := hclext.CreateDotReferenceFromTraversal(valRef.Traversal)
return types.HCLString{
Value: val,
ValueDiags: diags,
ValueExpr: &valRef,
Source: &source,
}
}
func ParameterCtyType(typ string) (cty.Type, error) {
switch typ {
case "string":
return cty.String, nil
case "number":
return cty.Number, nil
case "bool":
return cty.Bool, nil
case "list(string)":
return cty.List(cty.String), nil
default:
return cty.Type{}, fmt.Errorf("unsupported type: %q", typ)
}
}