This repository has been archived by the owner on Dec 30, 2024. It is now read-only.
generated from FrangipaneTeam/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 1
/
attrtypes.go
71 lines (60 loc) · 1.78 KB
/
attrtypes.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
package supertypes
import (
"context"
"fmt"
"reflect"
"github.com/hashicorp/terraform-plugin-framework/attr"
)
// AttributeTypes returns a map of attribute types for the specified type T.
// T must be a struct and reflection is used to find exported fields of T with the `tfsdk` tag.
func AttributeTypes[T any](ctx context.Context) (map[string]attr.Type, error) {
var t T
val := reflect.ValueOf(t)
typ := val.Type()
if typ.Kind() != reflect.Struct {
return nil, fmt.Errorf("%T has unsupported type: %s", t, typ)
}
attributeTypes := make(map[string]attr.Type)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.PkgPath != "" {
continue // Skip unexported fields.
}
tag := field.Tag.Get(`tfsdk`)
if tag == "-" {
continue // Skip explicitly excluded fields.
}
if tag == "" {
return nil, fmt.Errorf(`%T needs a struct tag for "tfsdk" on %s`, t, field.Name)
}
if v, ok := val.Field(i).Interface().(attr.Value); ok {
attributeTypes[tag] = v.Type(ctx)
}
}
return attributeTypes, nil
}
func AttributeTypesMust[T any](ctx context.Context) map[string]attr.Type {
return Must(AttributeTypes[T](ctx))
}
// ElementType returns the element type of the specified type T.
// T must be a slice or map and reflection is used to find the element type.
func ElementType[T any](_ context.Context) (attr.Type, error) {
var t T
val := reflect.ValueOf(t)
typ := val.Type()
switch typ.Kind() {
case reflect.String:
return StringType{}, nil
case reflect.Bool:
return BoolType{}, nil
case reflect.Int64:
return Int64Type{}, nil
case reflect.Float64:
return Float64Type{}, nil
default:
return nil, fmt.Errorf("%T has unsupported type: %s", t, typ)
}
}
func ElementTypeMust[T any](ctx context.Context) attr.Type {
return Must(ElementType[T](ctx))
}