-
Notifications
You must be signed in to change notification settings - Fork 4
/
block_value.go
50 lines (41 loc) · 990 Bytes
/
block_value.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
package golden
import (
"reflect"
"strings"
"github.com/zclconf/go-cty/cty"
)
func Value(b Block) map[string]cty.Value {
values := make(map[string]cty.Value)
blockType := reflect.TypeOf(b)
blockValue := reflect.ValueOf(b)
// Check if the block is a pointer and dereference it if so
if blockType.Kind() == reflect.Ptr {
blockType = blockType.Elem()
blockValue = blockValue.Elem()
}
for i := 0; i < blockType.NumField(); i++ {
field := blockType.Field(i)
tagName, tagDefined := fieldName(field)
if !tagDefined {
continue
}
fieldValue := blockValue.Field(i)
values[tagName] = ToCtyValue(fieldValue.Interface())
}
return values
}
func fieldName(f reflect.StructField) (string, bool) {
attributeTag := f.Tag.Get("attribute")
tag := f.Tag.Get("hcl")
if attributeTag != "" {
tag = attributeTag
}
if tag == "" {
return f.Name, false
}
tagSegments := strings.Split(tag, ",")
if len(tagSegments) > 1 {
tag = tagSegments[0]
}
return tag, true
}