Skip to content

Commit 486066a

Browse files
Implement HCL2-style maps/key-value pairs.
1 parent 55c3d40 commit 486066a

File tree

4 files changed

+45
-10
lines changed

4 files changed

+45
-10
lines changed

_tests/maps.hcl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Foo {
2+
KeyVals = {
3+
baz = "buzz"
4+
}
5+
}

_tests/nested-slices.hcl

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
bar = [
2-
["bar"],
3-
["baz"],
4-
["buzz"],
5-
]
1+
{
2+
bar = [
3+
["bar"],
4+
["baz"],
5+
["buzz"],
6+
]
67

7-
foo = [
8-
"bar",
9-
"baz",
10-
]
8+
foo = [
9+
"bar",
10+
"baz",
11+
]
12+
}

hclencoder_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,23 @@ func TestEncoder(t *testing.T) {
152152
},
153153
Output: "nested-struct-slice-no-key",
154154
},
155+
{
156+
ID: "maps",
157+
Input: struct {
158+
Foo struct {
159+
KeyVals map[string]string
160+
}
161+
}{
162+
struct {
163+
KeyVals map[string]string
164+
}{
165+
KeyVals: map[string]string{
166+
"baz": "buzz",
167+
},
168+
},
169+
},
170+
Output: "maps",
171+
},
155172
{
156173
ID: "nested slices",
157174
Input: map[string]interface{}{

nodes.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,18 @@ func encodeMap(in reflect.Value) (ast.Node, []*ast.ObjectKey, error) {
225225
}
226226

227227
sort.Sort(l)
228-
return &ast.ObjectType{List: &ast.ObjectList{Items: []*ast.ObjectItem(l)}}, nil, nil
228+
229+
// here we wrap the map into an object with an empty key, just so that the map is not treated as an HCL object and
230+
// is instead viewed an opaque node that can be used in an assignment. this is what happens when we try to write
231+
// HCL2 with a HCL1 framework :)
232+
return &ast.ObjectItem{
233+
Keys: []*ast.ObjectKey{
234+
{Token: token.Token{
235+
Type: token.STRING,
236+
Text: "",
237+
}},
238+
}, Val: &ast.ObjectType{List: &ast.ObjectList{Items: l}},
239+
}, nil, nil
229240
}
230241

231242
// encodeStruct converts a struct type into an ast.ObjectType. An ast.ObjectKey

0 commit comments

Comments
 (0)