forked from aquasecurity/tfsec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
60 lines (50 loc) · 1.33 KB
/
struct.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
package convert
import (
"reflect"
"strings"
"github.com/mightymarty/tfsec/defsec/internal/types"
)
type metadataProvider interface {
GetMetadata() types.Metadata
}
var metadataInterface = reflect.TypeOf((*metadataProvider)(nil)).Elem()
func StructToRego(inputValue reflect.Value) map[string]interface{} {
// make sure we have a struct literal
for inputValue.Type().Kind() == reflect.Ptr {
if inputValue.IsNil() {
return nil
}
inputValue = inputValue.Elem()
}
if inputValue.Type().Kind() != reflect.Struct {
panic("not a struct")
}
output := make(map[string]interface{}, inputValue.NumField())
for i := 0; i < inputValue.NumField(); i++ {
field := inputValue.Field(i)
typ := inputValue.Type().Field(i)
name := typ.Name
if !typ.IsExported() {
continue
}
if field.Interface() == nil {
continue
}
val := anonymousToRego(reflect.ValueOf(field.Interface()))
if val == nil {
continue
}
key := strings.ToLower(name)
if _, ok := field.Interface().(types.Metadata); key == "metadata" && ok {
continue
}
output[strings.ToLower(name)] = val
}
if inputValue.Type().Implements(metadataInterface) {
returns := inputValue.MethodByName("GetMetadata").Call(nil)
if metadata, ok := returns[0].Interface().(types.Metadata); ok {
output["__defsec_metadata"] = metadata.ToRego()
}
}
return output
}