Skip to content
This repository was archived by the owner on Mar 20, 2024. It is now read-only.

Commit fb9757b

Browse files
avorimarodaine
authored andcommitted
Set keys when squashing struct (#14)
1 parent 70229ed commit fb9757b

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

nodes.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ func encodeStruct(in reflect.Value) (ast.Node, []*ast.ObjectKey, error) {
248248
}
249249
}
250250

251-
val, childKey, err := encode(rawVal)
251+
val, childKeys, err := encode(rawVal)
252252
if err != nil {
253253
return nil, nil, err
254254
}
@@ -270,6 +270,9 @@ func encodeStruct(in reflect.Value) (ast.Node, []*ast.ObjectKey, error) {
270270
switch val := val.(type) {
271271
case *ast.ObjectType:
272272
list.Items = append(list.Items, val.List.Items...)
273+
if childKeys != nil {
274+
keys = childKeys
275+
}
273276
continue
274277
}
275278
}
@@ -292,8 +295,8 @@ func encodeStruct(in reflect.Value) (ast.Node, []*ast.ObjectKey, error) {
292295
Keys: []*ast.ObjectKey{itemKey},
293296
Val: val,
294297
}
295-
if childKey != nil {
296-
item.Keys = append(item.Keys, childKey...)
298+
if childKeys != nil {
299+
item.Keys = append(item.Keys, childKeys...)
297300
}
298301
list.Add(item)
299302
}

nodes_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,16 @@ func TestEncodeStruct(t *testing.T) {
405405
},
406406
}}},
407407
},
408+
{
409+
ID: "squash keyed child struct",
410+
Input: reflect.ValueOf(SquashKeyChildStruct{KeyChildStruct: KeyChildStruct{Foo: KeyStruct{Bar: "baz"}}}),
411+
Expected: &ast.ObjectType{List: &ast.ObjectList{Items: []*ast.ObjectItem{
412+
&ast.ObjectItem{
413+
Keys: []*ast.ObjectKey{{Token: token.Token{Type: token.IDENT, Text: "Foo"}}, {Token: token.Token{Type: token.STRING, Text: `"baz"`}}},
414+
Val: &ast.ObjectType{List: &ast.ObjectList{Items: []*ast.ObjectItem{}}},
415+
},
416+
}}},
417+
},
408418
{
409419
ID: "nested unkeyed struct slice",
410420
Input: reflect.ValueOf(struct{ Foo []TestStruct }{[]TestStruct{{"Test"}}}),
@@ -701,6 +711,10 @@ type SquashStruct struct {
701711
TestStruct `hcl:",squash"`
702712
}
703713

714+
type SquashKeyChildStruct struct {
715+
KeyChildStruct `hcl:",squash"`
716+
}
717+
704718
func strAddr(s string) *string {
705719
return &s
706720
}

0 commit comments

Comments
 (0)