-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhelp.go
389 lines (292 loc) · 11.5 KB
/
help.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package main
import (
"flag"
"fmt"
"regexp"
"sort"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
func printInfo() {
fmt.Print("\n", "Usage: scalr [OPTION] COMMAND [FLAGS]", "\n\n")
fmt.Print(" 'scalr' is a command-line interface tool that communicates directly with the Scalr API", "\n\n")
fmt.Print("Examples:", "\n")
fmt.Print(" $ scalr -help", "\n")
fmt.Print(" $ scalr -help get-workspaces", "\n")
fmt.Print(" $ scalr get-foo-bar -flag=value", "\n")
fmt.Print(" $ scalr -verbose create-foo-bar -flag=value -flag2=value2", "\n")
fmt.Print(" $ scalr create-foo-bar < json-blob.txt", "\n\n")
fmt.Print("Environment variables:", "\n")
fmt.Print(" SCALR_HOSTNAME", " ", "Scalr Hostname, i.e example.scalr.io", "\n")
fmt.Print(" SCALR_TOKEN", " ", "Scalr API Token", "\n")
fmt.Print(" SCALR_ACCOUNT", " ", "Default Scalr Account ID, i.e acc-tq8cgt2hu6hpfuj", "\n\n")
fmt.Print("Options:", "\n")
fmt.Print(" -version", " ", "Shows current version of this binary", "\n")
fmt.Print(" -help", " ", "Shows documentation for all (or specified) command(s)", "\n")
fmt.Print(" -verbose", " ", "Shows complete request and response communication data", "\n")
fmt.Print(" -configure", " ", "Run configuration wizard", "\n")
fmt.Print(" -update", " ", "Updates this tool to the latest version by downloading and replacing current binary", "\n")
fmt.Print(" -autocomplete", " ", "Enable shell tab auto-complete", "\n")
fmt.Print(" -quiet", " ", "Disables printing server responses", "\n\n")
//fmt.Print(" -format=STRING", " ", "Specify output format. Options: json (default), table", "\n")
}
// Prints CLI help
func printHelp() {
//Help for specified command
if flag.Arg(0) != "" {
printHelpCommand(flag.Arg(0))
return
}
//Load OpenAPI specification
doc := loadAPI()
groups := make(map[string]map[string]string)
for _, path := range doc.Paths.Map() {
for _, method := range path.Operations() {
group := ""
if method.Extensions["x-resource"] == nil {
//Fallback to Tag if x-resource group is missing
group = strings.Title(method.Tags[0])
} else {
group = method.Extensions["x-resource"].(string)
}
//Add a space before each uppercase letter
group = strings.TrimPrefix(string(regexp.MustCompile(`([A-Z])`).ReplaceAll([]byte(group), []byte(" $1"))), " ")
//If group does not exist, add to map
if groups[group] == nil {
groups[group] = make(map[string]string)
}
groups[group][strings.ReplaceAll(method.OperationID, "_", "-")] = method.Summary
}
}
//Create a sorted array with group names
sortedGroups := make([]string, 0, len(groups))
for group := range groups {
sortedGroups = append(sortedGroups, group)
}
sort.Strings(sortedGroups)
for _, group := range sortedGroups {
fmt.Println("\n" + group + ":")
//Create a sorted array with commands
sortedCommands := make([]string, 0, len(groups[group]))
maxLength := 0
for command := range groups[group] {
sortedCommands = append(sortedCommands, command)
if len(command) <= maxLength {
continue
}
maxLength = len(command)
}
sort.Strings(sortedCommands)
for _, command := range sortedCommands {
fmt.Println(" ", command, strings.Repeat(" ", maxLength-len(command)), groups[group][command])
}
}
}
func printHelpCommand(command string) {
//Load OpenAPI specification
doc := loadAPI()
for _, path := range doc.Paths.Map() {
for method, object := range path.Operations() {
if command != strings.ReplaceAll(object.OperationID, "_", "-") {
continue
}
flags := make(map[string]Parameter)
for _, parameter := range object.Parameters {
//Ignore some parameters
if parameter.Value.Name == "page[number]" ||
parameter.Value.Name == "page[size]" ||
parameter.Value.Name == "fields" ||
parameter.Value.Name == "Prefer" {
continue
}
//Collect valid flag values
var enum []any
if parameter.Value.Schema.Value.Type.Is("array") &&
parameter.Value.Schema.Value.Items != nil &&
parameter.Value.Schema.Value.Items.Value.Enum != nil {
enum = parameter.Value.Schema.Value.Items.Value.Enum
}
if parameter.Value.Schema.Value.Enum != nil {
enum = parameter.Value.Schema.Value.Enum
}
// Convert type to string representation
varType := "string"
if parameter.Value.Schema.Value.Type.Is("boolean") {
varType = "boolean"
} else if parameter.Value.Schema.Value.Type.Is("integer") {
varType = "integer"
} else if parameter.Value.Schema.Value.Type.Is("array") {
varType = "array"
}
flags[renameFlag(parameter.Value.Name)] = Parameter{
varType: varType,
description: renameFlag(parameter.Value.Description),
required: parameter.Value.Required,
enum: enum,
}
}
if object.RequestBody == nil {
fmt.Printf("\nUsage: scalr [OPTION] %s [FLAGS]\n\n", command)
} else {
//This command requires a body
fmt.Printf("\nUsage: scalr [OPTION] %s [FLAGS] [< json-blob.txt]\n\n", command)
//Get contentType of this command
var contentType string
for contentType = range object.RequestBody.Value.Content {
}
//If no schema is defined for the body, no need to look for futher fields
if object.RequestBody.Value.Content[contentType].Schema != nil {
//Recursively collect all required fields
requiredFlags := map[string]bool{}
// FIXME: Disable required attributes for PATCH requests as the specs are incorrect
if method != "PATCH" {
requiredFlags = collectRequired(object.RequestBody.Value.Content[contentType].Schema.Value)
}
relationshipDesc := make(map[string]string)
var collectAttributes func(*openapi3.Schema, string, string)
//Function to support nested objects
//TODO: Should probably move this outside of the loop for performance reason, but will make code less readable
collectAttributes = func(nested *openapi3.Schema, prefix string, inheritType string) {
//Collect all availble attributes for this command
for name, attribute := range nested.Properties {
//Special collection of descriptions for relationships
if name == "relationships" {
for rel, desc := range attribute.Value.Properties {
relationshipDesc[rel+"-id"] = desc.Value.Description
}
}
//Ignore read-only attributes in body
if attribute.Value.ReadOnly {
continue
}
flagName := prefix + name
//Ignore ID-field that is redundant
if flagName == "data-id" && inheritType == "" {
continue
}
//Nested object, needs to drill down deeper
if attribute.Value.Type.Is("object") {
collectAttributes(attribute.Value, flagName+"-", "")
continue
}
//Arrays might include objects that needs to be drilled down deeper
if attribute.Value.Type.Is("array") && attribute.Value.Items.Value.Type.Is("object") {
collectAttributes(attribute.Value.Items.Value, flagName+"-", "array")
continue
}
required := false
if requiredFlags[flagName] {
required = true
}
//If flag is required and only one value is available, no need to offer it to the user
if required && attribute.Value.Enum != nil && len(attribute.Value.Enum) == 1 {
continue
}
description := attribute.Value.Description
//If this is an attribute, strip prefix to shorten flag-names
flagName = strings.TrimPrefix(flagName, "data-attributes-")
//If this is a relationship, strip prefix and -data- to shorten flag-names
if strings.HasPrefix(flagName, "data-relationships-") {
//If this is not the relationship ID field, ignore it
if !strings.HasSuffix(flagName, "-id") {
continue
}
flagName = strings.TrimPrefix(flagName, "data-relationships-")
flagName = strings.Replace(flagName, "-data-id", "-id", 1)
//Fetch description from parent instead
description = relationshipDesc[flagName]
}
flagName = strings.TrimPrefix(flagName, "data-")
theType := attribute.Value.Type
if inheritType != "" {
// Instead of trying to create a new type, we'll use the existing type
// and just handle the type conversion in the string representation
theType = attribute.Value.Type
}
enum := attribute.Value.Enum
//Special case: ProviderConfiguration and maybe others?
if theType == nil && attribute.Value.AnyOf != nil {
for _, item := range attribute.Value.AnyOf {
if item.Value.Enum != nil {
enum = item.Value.Enum
}
if item.Value.Type != nil {
theType = item.Value.Type
}
}
}
// Convert type to string representation
varType := "string"
if theType != nil {
if theType.Is("boolean") {
varType = "boolean"
} else if theType.Is("integer") {
varType = "integer"
} else if theType.Is("array") {
varType = "array"
} else if theType.Is("object") {
varType = "object"
}
} else if inheritType != "" {
varType = inheritType
}
flags[flagName] = Parameter{
varType: varType,
description: description,
required: required,
enum: enum,
}
}
}
collectAttributes(object.RequestBody.Value.Content[contentType].Schema.Value, "", "")
}
}
var description string
if object.Description != "" {
description = object.Description
} else if object.Summary != "" {
description = object.Summary
}
fmt.Print(" ", strings.ReplaceAll(strings.TrimSpace(description), "\n", "\n "), "\n")
if len(flags) > 0 {
fmt.Print("\nFlags:", "\n")
//Create a sorted array with flags
sortedFlags := make([]string, 0, len(flags))
maxLength := 0
for flg := range flags {
sortedFlags = append(sortedFlags, flg)
completeLength := len(flg + "=" + flags[flg].varType)
if completeLength <= maxLength {
continue
}
maxLength = completeLength
}
sort.Strings(sortedFlags)
for _, flg := range sortedFlags {
varType := strings.ToUpper(flags[flg].varType)
if varType == "ARRAY" {
varType = "LIST"
}
completeColor := "-" + flg + colorBlue + "=" + varType + colorReset
complete := "-" + flg + "=" + varType
//TODO: IF DESCRIPTION INCLUDES LINK, CONVERT IT TO A HTTP LINK TO THE DOCS
description := strings.ReplaceAll(flags[flg].description, "\n", " ")
if flags[flg].required {
description = description + colorRed + " [*required]" + colorReset
}
fmt.Println(" ", completeColor, strings.Repeat(" ", maxLength-len(complete)+1), description)
if flags[flg].enum != nil {
options := make([]string, len(flags[flg].enum))
for index, value := range flags[flg].enum {
options[index] = value.(string)
}
fmt.Println(colorBlue, strings.Repeat(" ", maxLength+3), "[", strings.Join(options, ", "), "]", colorReset)
}
}
}
fmt.Println("")
return
}
}
fmt.Printf("\nCommand '%s' not found. Use -help to list available commands.\n\n", command)
}