-
Notifications
You must be signed in to change notification settings - Fork 8
/
config.go
367 lines (306 loc) · 10.1 KB
/
config.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// Package config holds all of the data structures for DeployStack.
// Having them in main package caused circular dependecy issues.
package config
import (
"encoding/json"
"fmt"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/yaml.v2"
)
// Config represents the settings this app will collect from a user. It should
// be in a json file. The idea is minimal programming has to be done to setup
// a DeployStack and export out a tfvars file for terraform part of solution.
type Config struct {
Title string `json:"title" yaml:"title"`
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Duration int `json:"duration" yaml:"duration"`
Project bool `json:"collect_project" yaml:"collect_project"`
ProjectNumber bool `json:"collect_project_number" yaml:"collect_project_number"`
BillingAccount bool `json:"collect_billing_account" yaml:"collect_billing_account"`
Domain bool `json:"register_domain" yaml:"register_domain"`
Region bool `json:"collect_region" yaml:"collect_region"`
RegionType string `json:"region_type" yaml:"region_type"`
RegionDefault string `json:"region_default" yaml:"region_default"`
Zone bool `json:"collect_zone" yaml:"collect_zone"`
HardSet map[string]string `json:"hard_settings" yaml:"hard_settings"`
CustomSettings Customs `json:"custom_settings" yaml:"custom_settings"`
AuthorSettings Settings `json:"author_settings" yaml:"author_settings"`
ConfigureGCEInstance bool `json:"configure_gce_instance" yaml:"configure_gce_instance"`
DocumentationLink string `json:"documentation_link" yaml:"documentation_link"`
PathTerraform string `json:"path_terraform" yaml:"path_terraform"`
PathMessages string `json:"path_messages" yaml:"path_messages"`
PathScripts string `json:"path_scripts" yaml:"path_scripts"`
Projects Projects `json:"projects" yaml:"projects"`
Products []struct {
Info string `json:"info" yaml:"info"`
Product string `json:"product" yaml:"product"`
} `json:"products" yaml:"products"`
}
func (c *Config) convertHardset() {
for i, v := range c.HardSet {
c.AuthorSettings.AddComplete(Setting{Name: i, Value: v, Type: "string"})
}
// Blow hardset away so that if anywhere is looking for them, it fails.
c.HardSet = nil
}
func (c *Config) defaultAuthorSettings() {
for i, v := range c.AuthorSettings {
if v.Type == "" {
v.Type = "string"
c.AuthorSettings[i] = v
}
}
}
// GetAuthorSettings delivers the combined Hardset and AuthorSettings variables
func (c *Config) GetAuthorSettings() Settings {
c.convertHardset()
c.AuthorSettings.Sort()
return c.AuthorSettings
}
// ComputeName uses the git repo in the working directory to compute the
// shortname for the application.
func (c *Config) ComputeName() error {
repo, err := git.PlainOpen(".")
if err != nil {
return fmt.Errorf("could not open local git directory: %s", err)
}
remotes, err := repo.Remotes()
if err != nil {
return err
}
remote := ""
for _, v := range remotes {
for _, url := range v.Config().URLs {
if strings.Contains(strings.ToLower(url), "googlecloudplatform") {
remote = strings.ToLower(url)
}
}
}
// Fixes bug where ssh called repos have issues. Super edge case, but
// now its all testable
remote = strings.ReplaceAll(remote, "git@github.com:", "https://github.com/")
u, err := url.Parse(remote)
if err != nil {
return fmt.Errorf("could not parse git url: %s", err)
}
shortname := filepath.Base(u.Path)
shortname = strings.ReplaceAll(shortname, ".git", "")
shortname = strings.ReplaceAll(shortname, "deploystack-", "")
c.Name = shortname
return nil
}
// NewConfigJSON returns a Config object from a file read.
func NewConfigJSON(content []byte) (Config, error) {
result := Config{}
if err := json.Unmarshal(content, &result); err != nil {
return result, fmt.Errorf("unable to convert content to Config: %s", err)
}
return result, nil
}
// NewConfigYAML returns a Config object from a file read.
func NewConfigYAML(content []byte) (Config, error) {
result := Config{}
if err := yaml.Unmarshal(content, &result); err != nil {
return result, fmt.Errorf("unable to convert content to Config: %s", err)
}
return result, nil
}
// Project represets a GCP project for use in a stack
type Project struct {
Name string `json:"variable_name" yaml:"variable_name"`
UserPrompt string `json:"user_prompt" yaml:"user_prompt"`
SetAsDefault bool `json:"set_as_default" yaml:"set_as_default"`
value string
}
// Projects is a list of projects that we will collect info for
type Projects struct {
Items []Project `json:"items" yaml:"items"`
AllowDuplicates bool `json:"allow_duplicates" yaml:"allow_duplicates"`
}
// Setting is a item that will be translated to a varaible in a terraform file
type Setting struct {
Name string `json:"name" yaml:"name"`
Value string `json:"value" yaml:"value"`
Type string `json:"type" yaml:"type"`
List []string `json:"list" yaml:"list"`
Map map[string]string `json:"map" yaml:"map"`
}
// TFVars emits the name value combination here in away that terraform excepts
// in a tfvars file
func (s *Setting) TFVars() string {
return fmt.Sprintf("%s=%s\n", s.TFvarsName(), s.TFvarsValue())
}
// TFvarsName formats the name for the tfvars format
func (s Setting) TFvarsName() string {
name := strings.ToLower(strings.ReplaceAll(s.Name, " ", "_"))
return name
}
// TFvarsValue formats the value for the tfvars format
func (s Setting) TFvarsValue() string {
result := ""
// If we used the workaround for lists in strings, convert it to a list
// under the covers
if s.Value != "" && s.Value[0:1] == "[" {
replacer := strings.NewReplacer("[", "", "]", "")
s.List = strings.Split(replacer.Replace(s.Value), ",")
s.Type = "list"
s.Value = ""
}
switch s.Type {
case "string", "":
result = fmt.Sprintf("\"%s\"", s.Value)
case "list":
tmp := []string{}
for _, v := range s.List {
tmp = append(tmp, fmt.Sprintf("\"%s\"", v))
}
str := strings.Join(tmp, ",")
result = fmt.Sprintf("[%s]", str)
case "map":
tmp := []string{}
for i, v := range s.Map {
tmp = append(tmp, fmt.Sprintf("%s=\"%s\"", i, v))
}
sort.Strings(tmp)
str := strings.Join(tmp, ",")
result = fmt.Sprintf("{%s}", str)
default:
result = s.Value
}
return result
}
// Settings are a collection of setting
type Settings []Setting
// AddComplete adds an whole setting to the settings control
func (s *Settings) AddComplete(set Setting) {
setting := s.Find(set.Name)
if setting != nil {
s.Replace(set)
return
}
(*s) = append((*s), set)
return
}
// Add either creates a new setting or updates the existing one
func (s *Settings) Add(key, value string) {
k := strings.ToLower(key)
set := s.Find(key)
if set != nil {
set.Name = key
set.Value = value
set.Type = "string"
s.Replace(*set)
return
}
set = &Setting{Name: k, Value: value, Type: "string"}
(*s) = append((*s), *set)
return
}
// Sort sorts the slice according to Setting.Name ascendings
func (s *Settings) Sort() {
sort.Slice(*s, func(i, j int) bool {
return (*s)[i].Name < (*s)[j].Name
})
}
// Replace will look for a setting with the same name, and overwrite the value
func (s *Settings) Replace(set Setting) {
for i, v := range *s {
if v.Name == set.Name {
(*s)[i] = set
}
}
}
// Search returns all settings whose names contain a particular string
func (s *Settings) Search(q string) Settings {
result := Settings{}
for _, v := range *s {
if strings.Contains(v.Name, q) {
result = append(result, v)
}
}
return result
}
// Find locates a setting in the slice
func (s *Settings) Find(key string) *Setting {
k := strings.ToLower(key)
for _, v := range *s {
if v.Name == k {
return &v
}
}
return nil
}
// Custom represents a custom setting that we would like to collect from a user
// We will collect these settings from the user before continuing.
type Custom struct {
Setting
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Default string `json:"default" yaml:"default"`
Options []string `json:"options" yaml:"options"`
PrependProject bool `json:"prepend_project" yaml:"prepend_project"`
Validation string `json:"validation,omitempty" yaml:"validation,omitempty"`
project string
}
// Customs are a slice of Custom variables.
type Customs []Custom
// Get returns one Custom Variable
func (cs Customs) Get(name string) Custom {
for _, v := range cs {
if v.Name == name {
return v
}
}
return Custom{}
}
// Report is collection of data about multiple configs in the same root
// used for multi stack repos
type Report struct {
Path string
WD string
Config Config
}
// NewReport Generates a new config report for a given file
func NewReport(file string) (Report, error) {
result := Report{Path: file}
result.WD = strings.ReplaceAll(filepath.Dir(file), "/.deploystack", "")
dat, err := os.ReadFile(file)
if err != nil {
return result, err
}
switch filepath.Ext(file) {
case ".json":
result.Config, err = NewConfigJSON(dat)
if err != nil {
return result, err
}
case ".yaml":
result.Config, err = NewConfigYAML(dat)
if err != nil {
return result, err
}
}
return result, nil
}
// FindConfigReports walks through a directory and finds all of the configs in
// the folder
func FindConfigReports(dir string) ([]Report, error) {
var result []Report
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.Name() == "deploystack.json" || info.Name() == "deploystack.yaml" {
cr, err := NewReport(path)
if err != nil {
return err
}
result = append(result, cr)
}
return nil
})
return result, err
}