-
Notifications
You must be signed in to change notification settings - Fork 16
/
schema.go
71 lines (61 loc) · 1.66 KB
/
schema.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 schema
import (
"fmt"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/zclconf/go-cty/cty"
)
type Attribute struct {
// name - this will be inferred by the schema map key
Name string
// Type is the type of the value and must be one of the ValueType values.
// TypeBool - bool
// TypeInt - int
// TypeFloat - float64
// TypeString - string
// TypeList - []interface{}
Type ValueType
// Elem represents the element type. This may only be set for only set for TypeList.
Elem *Attribute
// is this attribute required
Required bool
}
func SchemaToObjectSpec(schema map[string]*Attribute) hcldec.ObjectSpec {
spec := hcldec.ObjectSpec{}
for name, attr := range schema {
attr.Name = name
spec[name] = attributeToSpec(attr)
}
return spec
}
func attributeToSpec(attr *Attribute) hcldec.Spec {
return &hcldec.AttrSpec{
Name: attr.Name,
Type: attributeTypeToCty(attr),
// we have validated that Required = !Optional so here we can safely only consider Required
Required: attr.Required,
}
}
func attributeTypeToCty(attr *Attribute) cty.Type {
switch attr.Type {
case TypeString:
return cty.String
case TypeBool:
return cty.Bool
case TypeFloat, TypeInt:
return cty.Number
case TypeList:
if attr.Elem == nil {
panic(fmt.Sprintf("attribute %s is TypeList but 'Elem' is not set", attr.Name))
}
return cty.List(attributeTypeToCty(attr.Elem))
default:
panic(fmt.Sprintf("invalid attribute type %v", attr.Type))
}
}
func attributeTypeMapToCty(attrTypes map[string]*Attribute) map[string]cty.Type {
res := make(map[string]cty.Type, len(attrTypes))
for k, v := range attrTypes {
res[k] = attributeTypeToCty(v)
}
return res
}