-
Notifications
You must be signed in to change notification settings - Fork 0
/
terra.go
52 lines (43 loc) · 1.03 KB
/
terra.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
package terra
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
}
// Converter converts Terraform formatted data to and from
// object types.
type Converter struct {
tag string
conversions map[reflect.Type]conversion
}
// New returns a new converter.
func New() *Converter {
return &Converter{
tag: "json",
conversions: map[reflect.Type]conversion{},
}
}
// 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 strcase.ToSnake(jsonName)
}
return strcase.ToSnake(sf.Name)
}