-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
312 lines (276 loc) · 8.27 KB
/
convert.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
package main
// copied from https://github.com/tmccombs/hcl2json/blob/main/convert/convert.go
import (
"encoding/json"
"fmt"
"strings"
hcl "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"
ctyjson "github.com/zclconf/go-cty/cty/json"
)
// Bytes takes the contents of an HCL file, as bytes, and converts
// them into a JSON representation of the HCL file.
func Bytes(bytes []byte, filename string) ([]byte, error) {
file, diags := hclsyntax.ParseConfig(bytes, filename, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return nil, fmt.Errorf("parse config: %v", diags.Errs())
}
hclBytes, err := File(file)
if err != nil {
return nil, fmt.Errorf("convert to HCL: %w", err)
}
return hclBytes, nil
}
// File takes an HCL file and converts it to its JSON representation.
func File(file *hcl.File) ([]byte, error) {
convertedFile, err := ConvertFile(file)
if err != nil {
return nil, fmt.Errorf("convert file: %w", err)
}
jsonBytes, err := json.Marshal(convertedFile)
if err != nil {
return nil, fmt.Errorf("marshal json: %w", err)
}
return jsonBytes, nil
}
type jsonObj = map[string]interface{}
type converter struct {
bytes []byte
}
func ConvertFile(file *hcl.File) (jsonObj, error) {
body, ok := file.Body.(*hclsyntax.Body)
if !ok {
return nil, fmt.Errorf("convert file body to body type")
}
c := converter{
bytes: file.Bytes,
}
out, err := c.ConvertBody(body)
if err != nil {
return nil, fmt.Errorf("convert body: %w", err)
}
return out, nil
}
func (c *converter) ConvertBody(body *hclsyntax.Body) (jsonObj, error) {
out := make(jsonObj)
for _, block := range body.Blocks {
if err := c.convertBlock(block, out); err != nil {
return nil, fmt.Errorf("convert block: %w", err)
}
}
var err error
for key, value := range body.Attributes {
out[key], err = c.ConvertExpression(value.Expr)
if err != nil {
return nil, fmt.Errorf("convert expression: %w", err)
}
}
return out, nil
}
func (c *converter) rangeSource(r hcl.Range) string {
// for some reason the range doesn't include the ending paren, so
// check if the next character is an ending paren, and include it if it is.
end := r.End.Byte
if end < len(c.bytes) && c.bytes[end] == ')' {
end++
}
return string(c.bytes[r.Start.Byte:end])
}
func (c *converter) convertBlock(block *hclsyntax.Block, out jsonObj) error {
key := block.Type
for _, label := range block.Labels {
// Labels represented in HCL are defined as quoted strings after the name of the block:
// block "label_one" "label_two"
//
// Labels represtend in JSON are nested one after the other:
// "label_one": {
// "label_two": {}
// }
//
// To create the JSON representation, check to see if the label exists in the current output:
//
// When the label exists, move onto the next label reference.
// When a label does not exist, create the label in the output and set that as the next label reference
// in order to append (potential) labels to it.
if _, exists := out[key]; exists {
var ok bool
out, ok = out[key].(jsonObj)
if !ok {
return fmt.Errorf("Unable to convert Block to JSON: %v.%v", block.Type, strings.Join(block.Labels, "."))
}
} else {
out[key] = make(jsonObj)
out = out[key].(jsonObj)
}
key = label
}
value, err := c.ConvertBody(block.Body)
if err != nil {
return fmt.Errorf("convert body: %w", err)
}
// Multiple blocks can exist with the same name, at the same
// level in the JSON document (e.g. locals).
//
// For consistency, always wrap the value in a collection.
// When multiple values are at the same key
if current, exists := out[key]; exists {
switch currentTyped := current.(type) {
case []interface{}:
currentTyped = append(currentTyped, value)
out[key] = currentTyped
default:
return fmt.Errorf("invalid HCL detected for %q block, cannot have blocks with and without labels", key)
}
} else {
out[key] = []interface{}{value}
}
return nil
}
func (c *converter) ConvertExpression(expr hclsyntax.Expression) (interface{}, error) {
// assume it is hcl syntax (because, um, it is)
switch value := expr.(type) {
case *hclsyntax.LiteralValueExpr:
return ctyjson.SimpleJSONValue{Value: value.Val}, nil
case *hclsyntax.UnaryOpExpr:
return c.convertUnary(value)
case *hclsyntax.TemplateExpr:
return c.convertTemplate(value)
case *hclsyntax.TemplateWrapExpr:
return c.ConvertExpression(value.Wrapped)
case *hclsyntax.TupleConsExpr:
list := make([]interface{}, 0)
for _, ex := range value.Exprs {
elem, err := c.ConvertExpression(ex)
if err != nil {
return nil, err
}
list = append(list, elem)
}
return list, nil
case *hclsyntax.ObjectConsExpr:
m := make(jsonObj)
for _, item := range value.Items {
key, err := c.convertKey(item.KeyExpr)
if err != nil {
return nil, err
}
m[key], err = c.ConvertExpression(item.ValueExpr)
if err != nil {
return nil, err
}
}
return m, nil
default:
return c.wrapExpr(expr), nil
}
}
func (c *converter) convertUnary(v *hclsyntax.UnaryOpExpr) (interface{}, error) {
_, isLiteral := v.Val.(*hclsyntax.LiteralValueExpr)
if !isLiteral {
// If the expression after the operator isn't a literal, fall back to
// wrapping the expression with ${...}
return c.wrapExpr(v), nil
}
val, err := v.Value(nil)
if err != nil {
return nil, err
}
return ctyjson.SimpleJSONValue{Value: val}, nil
}
func (c *converter) convertTemplate(t *hclsyntax.TemplateExpr) (string, error) {
if t.IsStringLiteral() {
// safe because the value is just the string
v, err := t.Value(nil)
if err != nil {
return "", err
}
return v.AsString(), nil
}
var builder strings.Builder
for _, part := range t.Parts {
s, err := c.convertStringPart(part)
if err != nil {
return "", err
}
builder.WriteString(s)
}
return builder.String(), nil
}
func (c *converter) convertStringPart(expr hclsyntax.Expression) (string, error) {
switch v := expr.(type) {
case *hclsyntax.LiteralValueExpr:
// If the key is a bare "null", then we end up with null here,
// in this case we should just return the string "null"
if v.Val.IsNull() {
return "null", nil
}
s, err := ctyconvert.Convert(v.Val, cty.String)
if err != nil {
return "", err
}
return s.AsString(), nil
case *hclsyntax.TemplateExpr:
return c.convertTemplate(v)
case *hclsyntax.TemplateWrapExpr:
return c.convertStringPart(v.Wrapped)
case *hclsyntax.ConditionalExpr:
return c.convertTemplateConditional(v)
case *hclsyntax.TemplateJoinExpr:
return c.convertTemplateFor(v.Tuple.(*hclsyntax.ForExpr))
default:
// treating as an embedded expression
return c.wrapExpr(expr), nil
}
}
func (c *converter) convertKey(keyExpr hclsyntax.Expression) (string, error) {
// a key should never have dynamic input
if k, isKeyExpr := keyExpr.(*hclsyntax.ObjectConsKeyExpr); isKeyExpr {
keyExpr = k.Wrapped
if _, isTraversal := keyExpr.(*hclsyntax.ScopeTraversalExpr); isTraversal {
return c.rangeSource(keyExpr.Range()), nil
}
}
return c.convertStringPart(keyExpr)
}
func (c *converter) convertTemplateConditional(expr *hclsyntax.ConditionalExpr) (string, error) {
var builder strings.Builder
builder.WriteString("%{if ")
builder.WriteString(c.rangeSource(expr.Condition.Range()))
builder.WriteString("}")
trueResult, err := c.convertStringPart(expr.TrueResult)
if err != nil {
return "", nil
}
builder.WriteString(trueResult)
falseResult, err := c.convertStringPart(expr.FalseResult)
if len(falseResult) > 0 {
builder.WriteString("%{else}")
builder.WriteString(falseResult)
}
builder.WriteString("%{endif}")
return builder.String(), nil
}
func (c *converter) convertTemplateFor(expr *hclsyntax.ForExpr) (string, error) {
var builder strings.Builder
builder.WriteString("%{for ")
if len(expr.KeyVar) > 0 {
builder.WriteString(expr.KeyVar)
builder.WriteString(", ")
}
builder.WriteString(expr.ValVar)
builder.WriteString(" in ")
builder.WriteString(c.rangeSource(expr.CollExpr.Range()))
builder.WriteString("}")
templ, err := c.convertStringPart(expr.ValExpr)
if err != nil {
return "", err
}
builder.WriteString(templ)
builder.WriteString("%{endfor}")
return builder.String(), nil
}
func (c *converter) wrapExpr(expr hclsyntax.Expression) string {
return "${" + c.rangeSource(expr.Range()) + "}"
}