-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathautocomplete.go
450 lines (327 loc) · 11.5 KB
/
autocomplete.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/getkin/kin-openapi/openapi3"
)
func runAutocomplete() {
filename, _ := os.Executable()
filename = filepath.Base(filename)
trimmed := strings.TrimLeft(os.Getenv("COMP_LINE"), filename)
trimmed = strings.TrimLeft(trimmed, " ")
flags := strings.Split(trimmed, " ")
//List basic flags
autoBasic(flags)
//Load all available flags and options from OpenAPI
allFlags := collectFlagsAndOptions()
prefix := flags[len(flags)-1]
//List all available commands
autoCommands(allFlags, flags, prefix)
//Get current command
var command string
for _, flag := range flags {
if flag[:1] != "-" {
command = flag
break
}
}
//List flag-options for specific flag
autoOptions(allFlags, command, prefix)
//List flags for specific command
autoFlags(allFlags, flags, command, prefix)
}
func listComplete(items []string, prefix string) {
for _, item := range items {
if !strings.HasPrefix(item, prefix) || item == prefix {
continue
}
fmt.Println(item)
}
os.Exit(0)
}
// List basic flags
func autoBasic(flags []string) {
if flags[0] != "" && flags[0][:1] == "-" && len(flags) == 1 {
listComplete([]string{"-version ", "-help ", "-verbose ", "-configure ", "-update ", "-autocomplete "}, flags[0])
}
}
// List all available commands
func autoCommands(allFlags map[string]map[string][]string, flags []string, prefix string) {
if len(flags) <= 1 || (len(flags) == 2 && flags[0][:1] == "-") {
var commands []string
for command := range allFlags {
commands = append(commands, command+" ")
}
listComplete(commands, prefix)
}
}
// List flags for specific command
func autoFlags(allFlags map[string]map[string][]string, flags []string, command string, prefix string) {
var params []string
for item := range allFlags[command] {
params = append(params, "-"+item+"=")
}
listComplete(params, prefix)
}
// List flag-options for specific flag
func autoOptions(allFlags map[string]map[string][]string, command string, prefix string) {
if strings.Contains(prefix, "=") {
var params []string
parts := strings.Split(prefix, "=")
flag := strings.TrimLeft(parts[0], "-")
parts2 := strings.Split(parts[1], ",")
//Collect previous options for lists
options := strings.Join(parts2[:len(parts2)-1], ",")
if options != "" {
options = options + ","
}
prefix = options + parts2[len(parts2)-1]
for _, parameter := range allFlags[command][flag] {
params = append(params, options+parameter)
}
listComplete(params, prefix)
}
}
// Load all available flags and options from OpenAPI
func collectFlagsAndOptions() map[string]map[string][]string {
allFlags := make(map[string]map[string][]string)
doc := loadAPI()
for _, path := range doc.Paths.Map() {
for _, object := range path.Operations() {
command := strings.ReplaceAll(object.OperationID, "_", "-")
allFlags[command] = make(map[string][]string)
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
}
allFlags[command][renameFlag(parameter.Value.Name)] = []string{}
//Collect valid flag values
var enums []any
if parameter.Value.Schema.Value.Type == "array" &&
parameter.Value.Schema.Value.Items != nil &&
parameter.Value.Schema.Value.Items.Value.Enum != nil {
enums = parameter.Value.Schema.Value.Items.Value.Enum
}
if parameter.Value.Schema.Value.Enum != nil {
enums = parameter.Value.Schema.Value.Enum
}
for _, enum := range enums {
allFlags[command][renameFlag(parameter.Value.Name)] = append(allFlags[command][renameFlag(parameter.Value.Name)], enum.(string))
}
}
if object.RequestBody == nil {
continue
}
//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 {
continue
}
//Recursively collect all required fields
requiredFlags := collectRequired(object.RequestBody.Value.Content[contentType].Schema.Value)
var collectAttributes func(*openapi3.Schema, string, string)
//Function to support nested objects
collectAttributes = func(nested *openapi3.Schema, prefix string, inheritType string) {
//Collect all availble attributes for this command
for name, attribute := range nested.Properties {
//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 == "object" {
collectAttributes(attribute.Value, flagName+"-", "")
continue
}
//Arrays might include objects that needs to be drilled down deeper
if attribute.Value.Type == "array" && attribute.Value.Items.Value.Type == "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
}
//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)
}
flagName = strings.TrimPrefix(flagName, "data-")
allFlags[command][flagName] = []string{}
//Collect valid flag values
if attribute.Value.Enum != nil {
for _, enum := range attribute.Value.Enum {
switch v := enum.(type) {
case string:
allFlags[command][flagName] = append(allFlags[command][flagName], v+" ")
case float64:
allFlags[command][flagName] = append(allFlags[command][flagName], fmt.Sprintf("%f ", v))
}
}
}
//Collect valid flag values in case of AnyOf
if attribute.Value.AnyOf != nil {
for _, item := range attribute.Value.AnyOf {
if item.Value.Enum != nil {
for _, enum := range item.Value.Enum {
allFlags[command][flagName] = append(allFlags[command][flagName], enum.(string)+" ")
}
}
}
}
}
}
collectAttributes(object.RequestBody.Value.Content[contentType].Schema.Value, "", "")
}
}
return allFlags
}
func enableAutocomplete() {
fname, err := exec.LookPath("scalr")
if err != nil {
fmt.Println("Could not find any 'scalr' binary in your $PATH. Please place a scalr binary in your $PATH before activating tab auto-complete.")
os.Exit(1)
}
fname, err = filepath.Abs(fname)
checkErr(err)
//Get user home dir
home, err := os.UserHomeDir()
checkErr(err)
//Guess current shell
shell := filepath.Base(os.Getenv("SHELL"))
checkErr(err)
fmt.Println("Detected shell: " + shell)
theConfig := ""
switch shell {
case "bash":
//Install auto-complete for bash
theConfig = autoCompleteBash(home, fname)
case "zsh":
//Install auto-complete for zsh
theConfig = autoCompleteZsh(home, fname)
case "bash.exe":
//Install auto-complete for gitbash
theConfig = autoCompleteGitbash(home, fname)
default:
fmt.Println("Could not find any shell that supports the auto-complete feature.")
os.Exit(1)
}
fmt.Println("Auto-complete has been enabled in " + theConfig + "! Please restart your shell to enable it.")
os.Exit(0)
}
func convertPath(windowsPath string) string {
// Replace backslashes with forward slashes
unixPath := strings.ReplaceAll(windowsPath, "\\", "/")
// Add leading slash and convert drive letter to lowercase
if len(unixPath) > 1 && unixPath[1] == ':' {
unixPath = "/" + strings.ToLower(string(unixPath[0])) + unixPath[2:]
}
return unixPath
}
// Install auto-complete for gitbash
func autoCompleteGitbash(home string, fname string) string {
theConfig := home + "\\" + ".bashrc"
// Check if a .bashrc file already exist
_, err := os.Stat(theConfig)
if err != nil {
// Create a new .bashrc file based on the global .bashrc file
input, err := os.ReadFile(os.Getenv("EXEPATH") + "\\etc\\bash.bashrc")
checkErr(err)
err = os.WriteFile(theConfig, input, 0666)
checkErr(err)
}
f, err := os.OpenFile(theConfig, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0666)
checkErr(err)
defer f.Close()
findLine := regexp.MustCompile("^complete (.*) scalr$")
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if findLine.MatchString(scanner.Text()) {
fmt.Println("Looks like auto-complete is already installed in " + theConfig + ". Please restart your shell to enable it.")
os.Exit(0)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
_, err = f.WriteString("complete -o nospace -C " + convertPath(fname) + " scalr.exe\n")
checkErr(err)
_, err = f.WriteString("complete -o nospace -C " + convertPath(fname) + " scalr\n")
checkErr(err)
return theConfig
}
// Install auto-complete for bash
func autoCompleteBash(home string, fname string) string {
theConfig := home + "/" + ".bashrc"
f, err := os.OpenFile(theConfig, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0666)
checkErr(err)
defer f.Close()
findLine := regexp.MustCompile("^complete (.*) scalr$")
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if findLine.MatchString(scanner.Text()) {
fmt.Println("Looks like auto-complete is already installed in " + theConfig + ". Please restart your shell to enable it.")
os.Exit(0)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
_, err = f.WriteString("complete -o nospace -C " + fname + " scalr\n")
checkErr(err)
return theConfig
}
// Install auto-complete for zsh
func autoCompleteZsh(home string, fname string) string {
theConfig := home + "/" + ".zshrc"
f, err := os.OpenFile(theConfig, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0666)
checkErr(err)
defer f.Close()
findLine := regexp.MustCompile("^complete (.*) scalr$")
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if findLine.MatchString(scanner.Text()) {
fmt.Println("Looks like auto-complete is already installed in " + theConfig + ". Please restart your shell to enable it.")
os.Exit(0)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
_, err = f.WriteString("autoload -U +X compinit\n" +
"compinit\n" +
"autoload -U +X bashcompinit\n" +
"bashcompinit\n" +
"complete -o nospace -C " + fname + " scalr\n")
checkErr(err)
return theConfig
}