/
source.go
98 lines (82 loc) · 2.17 KB
/
source.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package graphql
import (
"bytes"
"errors"
"fmt"
"regexp"
"strings"
"text/template"
)
type (
// Source is a datasource configuration
Source struct {
Name string `yaml:"name"`
Dynamo *DynamoSource `yaml:"dynamo"`
SQL *SQLSource `yaml:"sql"`
// Set automatically
Type string
}
// DynamoKeyType represents a key with type
DynamoKeyType struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
}
// DynamoSource represents a dynamo db data source
DynamoSource struct {
HashKey *DynamoKeyType `yaml:"hash_key"`
SortKey *DynamoKeyType `yaml:"sort_key,omitempty"`
Backup bool `yaml:"backup,omitempty"`
}
// SQLSource represents a sql based db data source
SQLSource struct {
PrimaryKey string `yaml:"primary_key"`
// TODO other fields
}
unmarshalSource Source
)
var reSupportedDataSourceTypes = regexp.MustCompile(`(dynamo|aurora)`)
// UnmarshalYAML satisfies the custom unmarshaler interface for go-yaml. It is
// called automatically by the YAML unmarshal.
func (ds *Source) UnmarshalYAML(unmarshal func(interface{}) error) error {
var u unmarshalSource
if err := unmarshal(&u); err != nil {
return err
}
*ds = Source(u)
if ds.Name == "" {
return errors.New("datasource does not declare a name")
}
switch {
case ds.Dynamo != nil:
ds.Type = "dynamo"
if ds.Dynamo.HashKey.Type == "" {
ds.Dynamo.HashKey.Type = "S"
}
if ds.Dynamo.SortKey != nil {
if ds.Dynamo.SortKey.Type == "" {
ds.Dynamo.SortKey.Type = "S"
}
}
case ds.SQL != nil:
ds.Type = "sql"
default:
return errors.New("must specify a support data source type")
}
return nil
}
// GenerateBytes renders the datasource ready to be written to the output stream
func (ds *Source) GenerateBytes() ([]byte, error) {
generated := bytes.Buffer{}
t, err := template.New(ds.Name).Funcs(funcMap).Parse(sourceTemplate)
if err != nil {
return nil, err
}
if err := t.Execute(&generated, ds); err != nil {
return nil, err
}
return generated.Bytes(), nil
}
// OutputName returns the file name to be written for the data source
func (ds *Source) OutputName() string {
return strings.ToLower(fmt.Sprintf("_datasource_%s_%s.tf", ds.Type, ds.Name))
}