-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparameter.go
More file actions
476 lines (402 loc) · 11.6 KB
/
Copy pathparameter.go
File metadata and controls
476 lines (402 loc) · 11.6 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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package extract
import (
"encoding/json"
"fmt"
"slices"
"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"
"github.com/coder/terraform-provider-coder/v2/provider"
)
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)
}
formType, formTypeDiags := optionalStringEnum[provider.ParameterFormType](block, "form_type", provider.ParameterFormTypeDefault, func(s provider.ParameterFormType) error {
if !slices.Contains(provider.ParameterFormTypes(), s) {
return fmt.Errorf("invalid form type %q, expected one of [%s]", s, strings.Join(toStrings(provider.ParameterFormTypes()), ", "))
}
return nil
})
if formTypeDiags != nil {
diags = diags.Append(formTypeDiags)
}
pName, nameDiag := requiredString(block, "name")
if nameDiag != nil {
diags = diags.Append(nameDiag)
}
if diags.HasErrors() {
return nil, diags
}
pVal := richParameterValue(block)
requiredValue := true
def := types.NullString()
defAttr := block.GetAttribute("default")
if !defAttr.IsNil() {
def = types.ToHCLString(block, defAttr)
requiredValue = false
}
ftmeta := optionalString(block, "styling")
var formTypeMeta types.ParameterStyling
if ftmeta != "" {
_ = json.Unmarshal([]byte(ftmeta), &formTypeMeta)
}
p := types.Parameter{
Value: pVal,
ParameterData: types.ParameterData{
Name: pName,
Description: optionalString(block, "description"),
Type: pType,
FormType: formType,
Styling: formTypeMeta,
Mutable: optionalBoolean(block, "mutable"),
// Default value is always written as a string, then converted
// to the correct type.
DefaultValue: def,
Icon: optionalString(block, "icon"),
Options: make([]*types.ParameterOption, 0),
Validations: make([]*types.ParameterValidation, 0),
Required: requiredValue,
DisplayName: optionalString(block, "display_name"),
Order: optionalInteger(block, "order"),
Ephemeral: optionalBoolean(block, "ephemeral"),
Source: block,
},
}
optBlocks := block.GetBlocks("option")
optionType, newFormType, err := provider.ValidateFormType(provider.OptionType(p.Type), len(optBlocks), p.FormType)
var _ = optionType // TODO: Should we enforce this anywhere?
if err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Invalid parameter `type=%q` and `form_type=%q`", p.Type, p.FormType),
Detail: err.Error(),
Context: &block.HCLBlock().DefRange,
})
// Parameter cannot be used
p.FormType = provider.ParameterFormTypeError
} else {
p.FormType = newFormType
}
for _, b := range optBlocks {
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)
}
if !diags.HasErrors() {
// Only do this validation if the parameter is valid, as if some errors
// exist, then this is likely to fail be excess information.
diags = diags.Extend(p.Valid(p.Value))
}
usageDiags := ParameterUsageDiagnostics(p)
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.Value.IsNull() {
// Allow null values
} else 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)
if diags.HasErrors() {
return types.ParameterValidation{}, diags
}
if diags.HasErrors() {
return types.ParameterValidation{}, diags
}
p := types.ParameterValidation{
Regex: nullableString(block, "regex"),
Error: optionalString(block, "error"),
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")
if diags.HasErrors() {
return types.ParameterOption{}, diags
}
p := types.ParameterOption{
Name: pName,
Description: optionalString(block, "description"),
Value: types.ToHCLString(block, valAttr),
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
}
// nolint:gocritic // string type asserted
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 nullableBoolean(block *terraform.Block, key string) *bool {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return nil
}
val := attr.Value()
if val.Type() != cty.Bool {
return nil
}
b := val.True()
return &b
}
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
}
str, ok := hclext.AsString(attr.Value())
if !ok {
return nil
}
return &str
}
func optionalString(block *terraform.Block, key string) string {
attr := block.GetAttribute(key)
if attr == nil || attr.IsNil() {
return ""
}
str, _ := hclext.AsString(attr.Value())
return str
}
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)
// If no value attribute exists, then the value is `null`.
if diags.HasErrors() && diags[0].Summary == "Unsupported attribute" {
s := types.NullString()
s.Source = &source
return s
}
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)
}
}
func toStrings[A ~string](l []A) []string {
var r []string
for _, v := range l {
r = append(r, string(v))
}
return r
}