-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattr.go
112 lines (93 loc) · 2.35 KB
/
attr.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
package preview
import (
"fmt"
"github.com/aquasecurity/trivy/pkg/iac/terraform"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
)
type attributeParser struct {
block *terraform.Block
diags hcl.Diagnostics
}
func newAttributeParser(block *terraform.Block) *attributeParser {
return &attributeParser{
block: block,
diags: make(hcl.Diagnostics, 0),
}
}
func (a *attributeParser) attr(key string) *expectedAttribute {
return &expectedAttribute{
Key: key,
p: a,
}
}
type expectedAttribute struct {
Key string
diag hcl.Diagnostics
p *attributeParser
}
func (a *expectedAttribute) error(diag hcl.Diagnostics) *expectedAttribute {
if a.diag != nil {
return a // already have an error, don't overwrite
}
a.p.diags = a.p.diags.Extend(diag)
a.diag = diag
return a
}
func (a *expectedAttribute) required() *expectedAttribute {
attr := a.p.block.GetAttribute(a.Key)
if attr.IsNil() {
r := a.p.block.HCLBlock().Body.MissingItemRange()
a.error(hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("Missing required attribute %q", a.Key),
// This is the error word for word from 'terraform apply'
Detail: fmt.Sprintf("The argument %q is required, but no definition is found.", a.Key),
Subject: &r,
Extra: nil,
},
})
}
return a
}
func (a *expectedAttribute) tryString() string {
attr := a.p.block.GetAttribute(a.Key)
if attr.IsNil() {
return ""
}
if attr.Type() != cty.String {
return ""
}
return attr.Value().AsString()
}
func (a *expectedAttribute) string() string {
attr := a.p.block.GetAttribute(a.Key)
if attr.IsNil() {
return ""
}
if attr.Type() != cty.String {
a.expectedTypeError(attr, "string")
return ""
}
return attr.Value().AsString()
}
func (a *expectedAttribute) expectedTypeError(attr *terraform.Attribute, expectedType string) {
var fn string
if attr.IsNil() || attr.Type().Equals(cty.NilType) {
fn = "nil"
} else {
fn = attr.Type().FriendlyName()
}
a.error(hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Invalid attribute type",
Detail: fmt.Sprintf("The attribute %q must be of type %q, found type %q", attr.Name(), expectedType, fn),
Subject: &attr.HCLAttribute().Range,
Context: &a.p.block.HCLBlock().DefRange,
Expression: attr.HCLAttribute().Expr,
EvalContext: a.p.block.Context().Inner(),
},
})
}