-
Notifications
You must be signed in to change notification settings - Fork 6
/
hcl_to_json.go
252 lines (226 loc) · 6.25 KB
/
hcl_to_json.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
// Adapted from https://github.com/tmccombs/hcl2json
package main
import (
"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"
)
type jsonObj map[string]interface{}
// Convert an hcl File to a json serializable object
// This assumes that the body is a hclsyntax.Body
func convertFile(file *hcl.File, keepInterp bool) (jsonObj, error) {
c := converter{bytes: file.Bytes, keepInterp: keepInterp}
body := file.Body.(*hclsyntax.Body)
return c.convertBody(body)
}
type converter struct {
bytes []byte
keepInterp bool
}
func (c *converter) rangeSource(r hcl.Range) string {
data := string(c.bytes[r.Start.Byte:r.End.Byte])
data = strings.ReplaceAll(data, "\n", " ")
data = strings.Join(strings.Fields(data), " ")
return data
}
func (c *converter) convertBody(body *hclsyntax.Body) (jsonObj, error) {
var err error
out := make(jsonObj)
for key, value := range body.Attributes {
out[key], err = c.convertExpression(value.Expr)
if err != nil {
return nil, err
}
}
for _, block := range body.Blocks {
err = c.convertBlock(block, out)
if err != nil {
return nil, err
}
}
return out, nil
}
func (c *converter) convertBlock(block *hclsyntax.Block, out jsonObj) error {
var key string = block.Type
value, err := c.convertBody(block.Body)
if err != nil {
return err
}
for _, label := range block.Labels {
if inner, exists := out[key]; exists {
var ok bool
out, ok = inner.(jsonObj)
if !ok {
// TODO: better diagnostics
return fmt.Errorf("unable to convert Block to JSON: %v.%v", block.Type, strings.Join(block.Labels, "."))
}
} else {
obj := make(jsonObj)
out[key] = obj
out = obj
}
key = label
}
if current, exists := out[key]; exists {
if list, ok := current.([]interface{}); ok {
out[key] = append(list, value)
} else {
out[key] = []interface{}{current, value}
}
} else {
out[key] = 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) 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:
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))
case *hclsyntax.ScopeTraversalExpr:
return c.wrapTraversal(expr), nil
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, _ := 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())
}
func (c *converter) wrapTraversal(expr hclsyntax.Expression) string {
res := c.wrapExpr(expr)
if c.keepInterp {
res = "${" + res + "}"
}
return res
}
func (c *converter) convertUnary(v *hclsyntax.UnaryOpExpr) (interface{}, error) {
_, isLiteral := v.Val.(*hclsyntax.LiteralValueExpr)
if !isLiteral {
return c.wrapExpr(v), nil
}
val, err := v.Value(nil)
if err != nil {
return nil, err
}
return ctyjson.SimpleJSONValue{Value: val}, nil
}