This repository has been archived by the owner on Oct 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
216 lines (197 loc) · 7.02 KB
/
main.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"fmt"
"os"
"sort"
"strings"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/crossplane-contrib/terraform-provider-gen/pkg/integration"
"github.com/crossplane-contrib/terraform-provider-gen/pkg/provider"
"github.com/crossplane-contrib/terraform-provider-gen/pkg/template"
"github.com/crossplane-contrib/terraform-runtime/pkg/client"
)
var (
gen = kingpin.New("terraform-provider-gen", "A cli for interacting with terraform providers.")
updateFixturesCmd = gen.Command("update-fixtures", "update test fixtures based on current codegen output")
repositoryRoot = updateFixturesCmd.Flag("repo-root", "Path to root of repository so that the fixture generator can find paths").Required().String()
generateCmd = gen.Command("generate", "code generator subcommands")
pluginPath = gen.Flag("plugin-path", "Path to provider plugin binary.").Required().String()
providerName = gen.Flag("providerName", "Terraform provider name. must match the value given to the 'provider' directive in a terraform config.").String()
outputDir = generateCmd.Flag("output-dir", "output path").String()
overlayBasePath = generateCmd.Flag("overlay-dir", "Path to search for files to overlay instead of generated code. Nesting mirrors output tree.").String()
cfgPath = generateCmd.Flag("cfg-path", "path to schema generation config yaml").String()
bootStrapCmd = generateCmd.Command("bootstrap", "bootstrap a new provider")
generateTypesCmd = generateCmd.Command("types", "Use Provider.GetSchema() to generate crossplane types.")
generateRuntimeCmd = generateCmd.Command("runtime", "Generate terraform-runtime methods for generated crossplane types.")
analyzeCmd = gen.Command("analyze", "perform analysis on a provider's schemas")
nestingCmd = analyzeCmd.Command("nesting", "report on the different nesting paths and modes observed in a provider")
nestingCmdStyle = nestingCmd.Flag("report-style", "Choose between summary (organized by nesting type and min/max), or dump (showing all nested values for all resources)").Default("dump").String()
flatCmd = analyzeCmd.Command("flat", "Find resources that do not use nesting at all")
typesIndexCmd = analyzeCmd.Command("cty-index", "Build an index showing which resources use which cty types")
excludeTypesList = typesIndexCmd.Flag("exclude-types", "comma separated list of types to ignore (mutually exclusive with include-types)").String()
includeTypesList = typesIndexCmd.Flag("include-types", "comma separated list of types to include (mutually exclusive with ignore-types)").String()
listTypes = typesIndexCmd.Flag("list-types", "Only list the types, leave out the breakdown of where they can be found").Bool()
)
func main() {
gen.FatalIfError(run(), "Error while executing hiveworld command")
}
func run() error {
cmd := kingpin.MustParse(gen.Parse(os.Args[1:]))
switch cmd {
case bootStrapCmd.FullCommand():
cfg, err := provider.ConfigFromFile(*cfgPath)
if err != nil {
return err
}
tg := template.NewCompiledTemplateGetter()
p, err := client.NewGRPCProvider(cfg.Name, *pluginPath)
if err != nil {
return err
}
schema := p.GetSchema()
bs := provider.NewBootstrapper(cfg, tg, schema)
return bs.Bootstrap()
case updateFixturesCmd.FullCommand():
opts := []integration.TestConfigOption{
integration.WithPluginPath(*pluginPath),
integration.WithProvidername(*providerName),
}
if repositoryRoot != nil {
opts = append(opts, integration.WithRepoRoot(*repositoryRoot))
}
itc := integration.NewIntegrationTestConfig(opts...)
err := integration.UpdateAllFixtures(itc)
if err != nil {
return err
}
case generateTypesCmd.FullCommand(), generateRuntimeCmd.FullCommand():
cfg, err := provider.ConfigFromFile(*cfgPath)
if err != nil {
return err
}
if len(cfg.ExcludeResources) > 0 {
fmt.Println("Excluding the following resources from codegen:")
for _, p := range cfg.ExcludeResources {
fmt.Println(p)
}
}
tg := template.NewCompiledTemplateGetter()
p, err := client.NewGRPCProvider(cfg.Name, *pluginPath)
if err != nil {
return err
}
st := provider.NewSchemaTranslator(cfg, *outputDir, *overlayBasePath, p.GetSchema(), tg)
switch cmd {
case generateTypesCmd.FullCommand():
return st.WriteGeneratedTypes()
case generateRuntimeCmd.FullCommand():
return st.WriteGeneratedRuntime()
}
case nestingCmd.FullCommand():
p, err := client.NewGRPCProvider(*providerName, *pluginPath)
if err != nil {
return err
}
unmm := make(integration.UniqueNestingModeMap)
for name, s := range p.GetSchema().ResourceTypes {
integration.VisitAllBlocks(unmm.Visitor, name, *s.Block)
}
switch *nestingCmdStyle {
case "dump":
inverted := make(map[string]integration.UniqueNestingMode)
keys := make([]string, 0)
for mode, paths := range unmm {
for _, p := range paths {
inverted[p] = mode
keys = append(keys, p)
}
}
sort.Strings(keys)
for _, k := range keys {
b := inverted[k]
fmt.Printf("%s: %s (%d, %d, %t)\n", k, b.Mode, b.MinItems, b.MaxItems, b.IsRequired)
}
default:
return fmt.Errorf("report-style=%s not recognized", nestingCmdStyle)
}
case flatCmd.FullCommand():
p, err := client.NewGRPCProvider(*providerName, *pluginPath)
if err != nil {
return err
}
frf := make(integration.FlatResourceFinder, 0)
for name, s := range p.GetSchema().ResourceTypes {
integration.VisitAllBlocks(frf.Visitor, name, *s.Block)
}
sort.Strings(frf)
for _, r := range frf {
fmt.Println(r)
}
case typesIndexCmd.FullCommand():
skipType, err := skipTypeFunc(*includeTypesList, *excludeTypesList)
if err != nil {
return err
}
cti := make(integration.CtyTypeIndexer)
err = doBlockVisit(cti.Visitor)
if err != nil {
return err
}
for t, l := range cti {
if skipType(t) {
continue
}
fmt.Printf("%s:\n", t)
if *listTypes {
continue
}
for _, path := range l {
fmt.Printf("\t%s\n", path)
}
}
}
return nil
}
type filterFunc func(t string) bool
func skipTypeFunc(incTypes, exclTypes string) (filterFunc, error) {
if incTypes != "" && exclTypes != "" {
return nil, fmt.Errorf("--include-types and --exclude-types flags are mutually exclusive")
}
if incTypes == "" && exclTypes == "" {
return func(t string) bool {
return false
}, nil
}
if exclTypes != "" {
ignoreTypes := make(map[string]bool)
for _, tn := range strings.Split(exclTypes, ",") {
ignoreTypes[tn] = true
}
return func(t string) bool {
if _, ignored := ignoreTypes[t]; ignored {
return true
}
return false
}, nil
}
includeTypes := make(map[string]bool)
for _, tn := range strings.Split(incTypes, ",") {
includeTypes[tn] = true
}
return func(t string) bool {
if _, included := includeTypes[t]; included {
return false
}
return true
}, nil
}
func doBlockVisit(visitor integration.Visitor) error {
p, err := client.NewGRPCProvider(*providerName, *pluginPath)
if err != nil {
return err
}
for name, s := range p.GetSchema().ResourceTypes {
integration.VisitAllBlocks(visitor, name, *s.Block)
}
return nil
}