-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
349 lines (263 loc) · 8 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
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
package main
import (
"crypto/md5"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/Jeffail/gabs/v2"
"github.com/getkin/kin-openapi/openapi3"
)
var (
ScalrHostname string
ScalrToken string
ScalrAccount string
BasePath string
)
const (
versionCLI = "0.0.0"
colorReset = "\033[0m"
colorRed = "\033[31m"
//colorGreen = "\033[32m"
//colorYellow = "\033[33m"
colorBlue = "\033[34m"
//colorPurple = "\033[35m"
//colorCyan = "\033[36m"
//colorWhite = "\033[37m"
)
func main() {
//Handle panics
defer func() {
err := recover()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}()
//Disable unwanted built-in flag features
flag.Usage = func() {}
flag.Bool("h", false, "")
help := flag.Bool("help", false, "")
configure := flag.Bool("configure", false, "")
verbose := flag.Bool("verbose", false, "")
version := flag.Bool("version", false, "")
format := flag.String("format", "json", "")
update := flag.Bool("update", false, "")
autocomplete := flag.Bool("autocomplete", false, "")
//Only parse the flags if this is not a tab completion request
if os.Getenv("COMP_LINE") == "" {
if len(os.Args[1:]) == 0 {
printInfo()
return
}
flag.Parse()
if *version {
runVersion()
return
}
if *configure {
runConfigure()
return
}
if *update {
runUpdate()
return
}
if *autocomplete {
enableAutocomplete()
return
}
}
//Load config from environment
ScalrHostname = os.Getenv("SCALR_HOSTNAME")
ScalrToken = os.Getenv("SCALR_TOKEN")
ScalrAccount = os.Getenv("SCALR_ACCOUNT")
//Load config from scalr.conf
ScalrHostname, ScalrToken, ScalrAccount = loadConfigScalr(ScalrHostname, ScalrToken, ScalrAccount)
//Load config from credentials.tfrc.json
ScalrHostname, ScalrToken = loadConfigTerraform(ScalrHostname, ScalrToken)
if ScalrHostname == "" || ScalrToken == "" {
//End here if this is a completion request
if os.Getenv("COMP_LINE") != "" {
return
}
fmt.Print("\n", "Not configured! Please run 'scalr -configure' or set environment variables SCALR_HOSTNAME and SCALR_TOKEN", "\n\n")
return
}
//This is tab compretion request
if os.Getenv("COMP_LINE") != "" {
runAutocomplete()
return
}
if *help {
printHelp()
return
}
parseCommand(*format, *verbose)
}
// Check for error and panic
func checkErr(e error) {
if e != nil {
panic(e)
}
}
// Load config from scalr.conf
func loadConfigScalr(hostname string, token string, account string) (string, string, string) {
home, err := os.UserHomeDir()
checkErr(err)
home = home + "/.scalr/"
config := "scalr.conf"
content, err := os.ReadFile(home + config)
if err != nil {
return hostname, token, account
}
jsonParsed, err := gabs.ParseJSON(content)
checkErr(err)
if jsonParsed.Search("hostname") != nil && hostname == "" {
hostname = jsonParsed.Search("hostname").Data().(string)
}
if jsonParsed.Search("token") != nil && token == "" {
token = jsonParsed.Search("token").Data().(string)
}
if jsonParsed.Search("account") != nil && account == "" {
account = jsonParsed.Search("account").Data().(string)
}
return hostname, token, account
}
// Load config from credentials.tfrc.json
func loadConfigTerraform(hostname string, token string) (string, string) {
home, err := os.UserHomeDir()
checkErr(err)
content, err := os.ReadFile(home + "/.terraform.d/credentials.tfrc.json")
if err != nil {
return hostname, token
}
jsonParsed, err := gabs.ParseJSON(content)
checkErr(err)
if hostname != "" {
//Try to load token for current hostname
if jsonParsed.Search("credentials", hostname, "token") != nil {
token = jsonParsed.Search("credentials", hostname, "token").Data().(string)
}
} else {
credentials := jsonParsed.Search("credentials").ChildrenMap()
if len(credentials) == 1 {
//Only exactly one credential entry exists, use it
for key, value := range credentials {
hostname = key
if value.Search("token") != nil {
token = value.Search("token").Data().(string)
}
}
}
}
return hostname, token
}
// Loads OpenAPI specification
func loadAPI() *openapi3.T {
cacheDir, err := os.UserCacheDir()
checkErr(err)
cacheDir = cacheDir + "/.scalr/"
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
os.MkdirAll(cacheDir, 0700)
}
spec := cacheDir + "cache-" + fmt.Sprintf("%x", md5.Sum([]byte(ScalrHostname))) + "-openapi-preview.yml"
if info, err := os.Stat(spec); !os.IsNotExist(err) {
if time.Since(info.ModTime()).Hours() > 24 {
//Cache is more than 24 hours old, re-Download...
downloadFile("https://"+ScalrHostname+"/api/iacp/v3/openapi-preview.yml", spec)
}
} else {
//Download spec
downloadFile("https://"+ScalrHostname+"/api/iacp/v3/openapi-preview.yml", spec)
}
loader := openapi3.NewLoader()
loader.IsExternalRefsAllowed = true
//Prevent loading external example files which makes the CLI too slow
loader.ReadFromURIFunc = disableExternalFiles(openapi3.ReadFromURIs(openapi3.ReadFromHTTP(http.DefaultClient), openapi3.ReadFromFile))
doc, err := loader.LoadFromFile(spec)
//api, _ := url.Parse("https://scalr.io/api/iacp/v3/openapi-preview.yml")
//doc, err := loader.LoadFromURI(api)
checkErr(err)
//Validate the specification
err = doc.Validate(loader.Context)
checkErr(err)
//Read BasePath from servers section, if exists
BasePath = ""
if doc.Servers != nil {
//fmt.Printf("%+#v", doc.Servers[0].URL)
u := strings.ReplaceAll(doc.Servers[0].URL, "{", "")
u = strings.ReplaceAll(u, "}", "")
parts, err := url.Parse(u)
checkErr(err)
BasePath = parts.Path
}
return doc
}
func disableExternalFiles(reader openapi3.ReadFromURIFunc) openapi3.ReadFromURIFunc {
return func(loader *openapi3.Loader, location *url.URL) (buf []byte, err error) {
//Skip examples
if strings.Contains(location.Path, "/examples/") {
return []byte("value: {}"), nil
}
return reader(loader, location)
}
}
// Downloads a file
func downloadFile(URL string, fileName string) {
client := &http.Client{}
req, err := http.NewRequest("GET", URL, nil)
checkErr(err)
req.Header.Set("User-Agent", "scalr-cli/"+versionCLI)
resp, err := client.Do(req)
checkErr(err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
checkErr(err)
if resp.StatusCode != 200 {
panic(errors.New("received non-200 response code from server"))
}
//Create a empty file
file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
checkErr(err)
defer file.Close()
file.WriteString(string(body))
file.Sync()
}
// Recursively collect all required fields
func collectRequired(root *openapi3.Schema) map[string]bool {
requiredFields := make(map[string]bool)
var recursive func(*openapi3.Schema, string)
//Function to support nested objects
recursive = func(nested *openapi3.Schema, prefix string) {
//data should always be considered as required
if prefix == "" && nested.Properties["data"] != nil {
if nested.Properties["data"].Value.Type == "array" {
recursive(nested.Properties["data"].Value.Items.Value, prefix+"data-")
} else {
recursive(nested.Properties["data"].Value, prefix+"data-")
}
}
//Collect all availble attributes for this command
for _, name := range nested.Required {
requiredFields[prefix+name] = true
//Nested object, needs to drill down deeper
if nested.Properties[name].Value.Type == "object" {
recursive(nested.Properties[name].Value, prefix+name+"-")
continue
}
//Nested array of objects, needs to dril down deeper
if nested.Properties[name].Value.Type == "array" && nested.Properties[name].Value.Items.Value.Type == "object" {
recursive(nested.Properties[name].Value.Items.Value, prefix+name+"-")
continue
}
}
}
recursive(root, "")
return requiredFields
}