-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpygohcl.go
276 lines (243 loc) · 7.95 KB
/
pygohcl.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
package main
// typedef struct {
// char *json;
// char *err;
// } parseResponse;
import "C"
import (
"encoding/json"
"fmt"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/ext/tryfunc"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/function/stdlib"
)
//export Parse
func Parse(a *C.char, keepInterpFlag C.int) (resp C.parseResponse) {
defer func() {
if err := recover(); err != nil {
retValue := fmt.Sprintf("panic HCL: %v", err)
resp = C.parseResponse{nil, C.CString(retValue)}
}
}()
input := C.GoString(a)
keepInterp := keepInterpFlag == 1
hclFile, diags := hclparse.NewParser().ParseHCL([]byte(input), "tmp.hcl")
if diags.HasErrors() {
return C.parseResponse{nil, C.CString(diagErrorsToString(diags, "invalid HCL: %s"))}
}
hclMap, err := convertFile(hclFile, keepInterp)
if err != nil {
return C.parseResponse{nil, C.CString(fmt.Sprintf("cannot convert HCL to Go map representation: %s", err))}
}
hclInJson, err := json.Marshal(hclMap)
if err != nil {
return C.parseResponse{nil, C.CString(fmt.Sprintf("cannot convert Go map representation to JSON: %s", err))}
}
resp = C.parseResponse{C.CString(string(hclInJson)), nil}
return
}
//export ParseAttributes
func ParseAttributes(a *C.char) (resp C.parseResponse) {
defer func() {
if err := recover(); err != nil {
retValue := fmt.Sprintf("panic HCL: %v", err)
resp = C.parseResponse{nil, C.CString(retValue)}
}
}()
input := C.GoString(a)
hclFile, parseDiags := hclsyntax.ParseConfig([]byte(input), "tmp.hcl", hcl.InitialPos)
if parseDiags.HasErrors() {
return C.parseResponse{nil, C.CString(diagErrorsToString(parseDiags, "invalid HCL: %s"))}
}
var diags hcl.Diagnostics
hclMap := make(jsonObj)
c := converter{[]byte(input), false}
attrs, attrsDiags := hclFile.Body.JustAttributes()
diags = diags.Extend(attrsDiags)
for _, attr := range attrs {
_, valueDiags := attr.Expr.Value(nil)
diags = diags.Extend(valueDiags)
if valueDiags.HasErrors() {
continue
}
value, err := c.convertExpression(attr.Expr.(hclsyntax.Expression))
if err != nil {
diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Error processing variable value",
Detail: fmt.Sprintf("Cannot convert HCL to Go map representation: %s.", err),
Subject: attr.NameRange.Ptr(),
})
continue
}
hclMap[attr.Name] = value
}
hclInJson, err := json.Marshal(hclMap)
if err != nil {
diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Error preparing JSON result",
Detail: fmt.Sprintf("Cannot convert Go map representation to JSON: %s.", err),
})
return C.parseResponse{nil, C.CString(diagErrorsToString(diags, ""))}
}
if diags.HasErrors() {
resp = C.parseResponse{C.CString(string(hclInJson)), C.CString(diagErrorsToString(diags, ""))}
} else {
resp = C.parseResponse{C.CString(string(hclInJson)), nil}
}
return
}
//export EvalValidationRule
func EvalValidationRule(c *C.char, e *C.char, n *C.char, v *C.char) (resp *C.char) {
defer func() {
if err := recover(); err != nil {
retValue := fmt.Sprintf("panic HCL: %v", err)
resp = C.CString(retValue)
}
}()
condition := C.GoString(c)
errorMsg := C.GoString(e)
varName := C.GoString(n)
varValue := C.GoString(v)
// First evaluate variable value to get its cty representation
varValueCty, diags := expressionValue(varValue, nil)
if diags.HasErrors() {
if containsError(diags, "Variables not allowed") {
// Try again to handle the case when a string value was provided without enclosing quotes
varValueCty, diags = expressionValue(fmt.Sprintf("%q", varValue), nil)
}
}
if diags.HasErrors() {
return C.CString(diagErrorsToString(diags, "cannot process variable value: %s"))
}
// Now evaluate the condition
hclCtx := &hcl.EvalContext{
Variables: map[string]cty.Value{
"var": cty.ObjectVal(map[string]cty.Value{
varName: varValueCty,
}),
},
Functions: knownFunctions,
}
conditionCty, diags := expressionValue(condition, hclCtx)
if diags.HasErrors() {
return C.CString(diagErrorsToString(diags, "cannot process condition expression: %s"))
}
if conditionCty.IsNull() {
return C.CString("condition expression result is null")
}
conditionCty, err := convert.Convert(conditionCty, cty.Bool)
if err != nil {
return C.CString("condition expression result must be bool")
}
if conditionCty.True() {
return nil
}
// Finally evaluate the error message expression
var errorMsgValue = "cannot process error message expression"
errorMsgCty, diags := expressionValue(errorMsg, hclCtx)
if diags.HasErrors() {
errorMsgCty, diags = expressionValue(fmt.Sprintf("%q", errorMsg), hclCtx)
}
if !diags.HasErrors() && !errorMsgCty.IsNull() {
errorMsgCty, err = convert.Convert(errorMsgCty, cty.String)
if err == nil {
errorMsgValue = errorMsgCty.AsString()
}
}
return C.CString(errorMsgValue)
}
func diagErrorsToString(diags hcl.Diagnostics, format string) string {
diagErrs := diags.Errs()
errors := make([]string, 0, len(diagErrs))
for _, err := range diagErrs {
errors = append(errors, err.Error())
}
if format == "" {
return strings.Join(errors, ", ")
}
return fmt.Sprintf(format, strings.Join(errors, ", "))
}
func containsError(diags hcl.Diagnostics, e string) bool {
for _, err := range diags.Errs() {
if strings.Contains(err.Error(), e) {
return true
}
}
return false
}
func expressionValue(in string, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
var diags hcl.Diagnostics
expr, diags := hclsyntax.ParseExpression([]byte(in), "tmp.hcl", hcl.InitialPos)
if diags.HasErrors() {
return cty.NilVal, diags
}
val, diags := expr.Value(ctx)
if diags.HasErrors() {
return cty.NilVal, diags
}
return val, diags
}
var knownFunctions = map[string]function.Function{
"abs": stdlib.AbsoluteFunc,
"can": tryfunc.CanFunc,
"ceil": stdlib.CeilFunc,
"chomp": stdlib.ChompFunc,
"coalescelist": stdlib.CoalesceListFunc,
"compact": stdlib.CompactFunc,
"concat": stdlib.ConcatFunc,
"contains": stdlib.ContainsFunc,
"csvdecode": stdlib.CSVDecodeFunc,
"distinct": stdlib.DistinctFunc,
"element": stdlib.ElementFunc,
"chunklist": stdlib.ChunklistFunc,
"flatten": stdlib.FlattenFunc,
"floor": stdlib.FloorFunc,
"format": stdlib.FormatFunc,
"formatdate": stdlib.FormatDateFunc,
"formatlist": stdlib.FormatListFunc,
"indent": stdlib.IndentFunc,
"join": stdlib.JoinFunc,
"jsondecode": stdlib.JSONDecodeFunc,
"jsonencode": stdlib.JSONEncodeFunc,
"keys": stdlib.KeysFunc,
"log": stdlib.LogFunc,
"lower": stdlib.LowerFunc,
"max": stdlib.MaxFunc,
"merge": stdlib.MergeFunc,
"min": stdlib.MinFunc,
"parseint": stdlib.ParseIntFunc,
"pow": stdlib.PowFunc,
"range": stdlib.RangeFunc,
"regex": stdlib.RegexFunc,
"regexall": stdlib.RegexAllFunc,
"reverse": stdlib.ReverseListFunc,
"setintersection": stdlib.SetIntersectionFunc,
"setproduct": stdlib.SetProductFunc,
"setsubtract": stdlib.SetSubtractFunc,
"setunion": stdlib.SetUnionFunc,
"signum": stdlib.SignumFunc,
"slice": stdlib.SliceFunc,
"sort": stdlib.SortFunc,
"split": stdlib.SplitFunc,
"strrev": stdlib.ReverseFunc,
"substr": stdlib.SubstrFunc,
"timeadd": stdlib.TimeAddFunc,
"title": stdlib.TitleFunc,
"trim": stdlib.TrimFunc,
"trimprefix": stdlib.TrimPrefixFunc,
"trimspace": stdlib.TrimSpaceFunc,
"trimsuffix": stdlib.TrimSuffixFunc,
"try": tryfunc.TryFunc,
"upper": stdlib.UpperFunc,
"values": stdlib.ValuesFunc,
"zipmap": stdlib.ZipmapFunc,
}
func main() {}