-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathwrapper_validate.go
73 lines (59 loc) · 1.85 KB
/
wrapper_validate.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package sdk
import (
"fmt"
"reflect"
"strings"
)
// ValidateModelObject validates that the object contains the specified `tfschema` tags
// required to be used with the Encode and Decode functions
func ValidateModelObject(input interface{}) error {
if input == nil {
// model not used for this resource
return nil
}
if reflect.TypeOf(input).Kind() != reflect.Ptr {
return fmt.Errorf("need a pointer to the model object")
}
// TODO: could we also validate that each `tfschema` tag exists in the schema?
objType := reflect.TypeOf(input).Elem()
objVal := reflect.ValueOf(input).Elem()
if objVal.Kind() == reflect.Interface {
return fmt.Errorf("cannot resolve pointer to interface")
}
return validateModelObjectRecursively("", objType, objVal)
}
func validateModelObjectRecursively(prefix string, objType reflect.Type, objVal reflect.Value) (errOut error) {
defer func() {
if r := recover(); r != nil {
out, ok := r.(error)
if !ok {
return
}
errOut = out
}
}()
for i := 0; i < objType.NumField(); i++ {
field := objType.Field(i)
fieldVal := objVal.Field(i)
if field.Type.Kind() == reflect.Slice {
sv := fieldVal.Slice(0, fieldVal.Len())
innerType := sv.Type().Elem()
innerVal := reflect.Indirect(reflect.New(innerType))
fieldName := strings.TrimPrefix(fmt.Sprintf("%s.%s", prefix, field.Name), ".")
if err := validateModelObjectRecursively(fieldName, innerType, innerVal); err != nil {
return err
}
}
fieldName := strings.TrimPrefix(fmt.Sprintf("%s.%s", prefix, field.Name), ".")
structTags, err := parseStructTags(field.Tag)
if err != nil {
return fmt.Errorf("parsing struct tags for %q", fieldName)
}
if structTags == nil {
return fmt.Errorf("field %q is missing a struct tag for `tfschema`", fieldName)
}
}
return nil
}