-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.go
69 lines (57 loc) · 1.39 KB
/
convert.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
package tfconv
import (
"reflect"
"strings"
"github.com/ettle/strcase"
)
// ConverterFn is a function that can convert a value.
type ConverterFn func(v any) (any, error)
type conversion struct {
expand ConverterFn
flatten ConverterFn
}
// NameFunc is a function used to define a field name.
type NameFunc = func(name string) string
// Converter converts Terraform formatted data to and from
// object types.
type Converter struct {
tag string
conversions map[reflect.Type]conversion
nameFn NameFunc
}
// New returns a new converter.
func New(tag string) *Converter {
return NewWithName(nil, tag)
}
// NewWithName returns a new converter with the give nameFn.
func NewWithName(nameFn NameFunc, tag string) *Converter {
if tag == "" {
tag = "json"
}
if nameFn == nil {
nameFn = strcase.ToSnake
}
return &Converter{
tag: tag,
conversions: map[reflect.Type]conversion{},
nameFn: nameFn,
}
}
// Register registers a custom type conversion.
func (c *Converter) Register(v any, expand, flatten ConverterFn) {
t := reflect.TypeOf(v)
c.conversions[t] = conversion{
expand: expand,
flatten: flatten,
}
}
func (c *Converter) resolveName(sf reflect.StructField) string {
jsonName := sf.Tag.Get(c.tag)
if name, _, ok := strings.Cut(jsonName, ","); ok {
jsonName = name
}
if jsonName != "" && jsonName != "-" {
return c.nameFn(jsonName)
}
return c.nameFn(sf.Name)
}