/
autocomplete.go
434 lines (394 loc) · 13.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
package autocomplete
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"github.com/scaleway/scaleway-cli/internal/args"
"github.com/scaleway/scaleway-cli/internal/core"
"github.com/scaleway/scaleway-cli/internal/interactive"
"github.com/scaleway/scaleway-sdk-go/logger"
)
func GetCommands() *core.Commands {
return core.NewCommands(
autocompleteRootCommand(),
autocompleteInstallCommand(),
autocompleteCompleteBashCommand(),
autocompleteCompleteFishCommand(),
autocompleteCompleteZshCommand(),
autocompleteScriptCommand(),
)
}
func autocompleteRootCommand() *core.Command {
return &core.Command{
Short: `Autocomplete related commands`,
Long: ``,
Namespace: "autocomplete",
}
}
type autocompleteScript struct {
CompleteScript string
CompleteFunc string
ShellConfigurationFile map[string]string
}
// autocompleteScripts regroups the autocomplete scripts for the different shells
// The key is the path of the shell.
func autocompleteScripts(ctx context.Context) map[string]autocompleteScript {
binaryName := core.ExtractBinaryName(ctx)
homePath := core.ExtractUserHomeDir(ctx)
return map[string]autocompleteScript{
"bash": {
// If `scw` is the first word on the command line,
// after hitting [tab] arguments are sent to `scw autocomplete complete bash`:
// - COMP_LINE: the complete command line
// - cword: the index of the word being completed (source COMP_CWORD)
// - words: the words composing the command line (source COMP_WORDS)
//
// Note that `=` signs are excluding from $COMP_WORDBREAKS. As a result, they are NOT be
// considered as breaking words and arguments like `image=` will not be split.
//
// Then `scw autocomplete complete bash` process the line, and tries to returns suggestions.
// These scw suggestions are put into `COMPREPLY` which is used by Bash to provides the shell suggestions.
CompleteFunc: fmt.Sprintf(`
_%[1]s() {
_get_comp_words_by_ref -n = cword words
output=$(%[1]s autocomplete complete bash -- "$COMP_LINE" "$cword" "${words[@]}")
COMPREPLY=($output)
# apply compopt option and ignore failure for older bash versions
[[ $COMPREPLY == *= ]] && compopt -o nospace 2> /dev/null || true
return
}
complete -F _%[1]s %[1]s
`, binaryName),
CompleteScript: fmt.Sprintf(`eval "$(%s autocomplete script shell=bash)"`, binaryName),
ShellConfigurationFile: map[string]string{
"darwin": path.Join(homePath, ".bash_profile"),
"linux": path.Join(homePath, ".bashrc"),
},
},
"fish": {
// (commandline) complete command line
// (commandline --cursor) position of the cursor, as number of chars in the command line
// (commandline --current-token) word to complete
// (commandline --tokenize --cut-at-cursor) tokenized selection up until the current cursor position
// formatted as one string-type token per line
//
// If files are shown although --no-files is set,
// it might be because you are using an alias for scw, such as :
// alias scw='go run "$HOME"/scaleway-cli/cmd/scw/main.go'
// You might want to run 'complete --erase --command go' during development.
//
// TODO: send rightWords
CompleteFunc: fmt.Sprintf(`
complete --erase --command %[1]s;
complete --command %[1]s --no-files;
complete --command %[1]s --arguments '(%[1]s autocomplete complete fish -- (commandline) (commandline --cursor) (commandline --current-token) (commandline --current-process --tokenize --cut-at-cursor))';
`, binaryName),
CompleteScript: fmt.Sprintf(`eval (%s autocomplete script shell=fish)`, binaryName),
ShellConfigurationFile: map[string]string{
"darwin": path.Join(homePath, ".config/fish/config.fish"),
"linux": path.Join(homePath, ".config/fish/config.fish"),
},
},
"zsh": {
// If you are using an alias for scw, such as :
// alias scw='go run "$HOME"/scaleway-cli/cmd/scw/main.go'
// you might want to run 'compdef _scw go' during development.
CompleteFunc: fmt.Sprintf(`
autoload -U compinit && compinit
_%[1]s () {
output=($(%[1]s autocomplete complete zsh -- ${CURRENT} ${words}))
opts=('-S' ' ')
if [[ $output == *= ]]; then
opts=('-S' '')
fi
compadd "${opts[@]}" -- "${output[@]}"
}
compdef _%[1]s %[1]s
`, binaryName),
CompleteScript: fmt.Sprintf(`eval "$(%s autocomplete script shell=zsh)"`, binaryName),
ShellConfigurationFile: map[string]string{
"darwin": path.Join(homePath, ".zshrc"),
"linux": path.Join(homePath, ".zshrc"),
},
},
}
}
type InstallArgs struct {
Shell string
}
func autocompleteInstallCommand() *core.Command {
return &core.Command{
Short: `Install autocomplete script`,
Long: `Install autocomplete script for a given shell and OS.`,
Namespace: "autocomplete",
Resource: "install",
AllowAnonymousClient: true,
ArgSpecs: core.ArgSpecs{
{
Name: "shell",
},
},
ArgsType: reflect.TypeOf(InstallArgs{}),
Run: InstallCommandRun,
}
}
func InstallCommandRun(ctx context.Context, argsI interface{}) (i interface{}, e error) {
// Warning
_, _ = interactive.Println("To enable autocomplete, scw needs to update your shell configuration.")
// If `shell=` is empty, ask for a value for `shell=`.
shellArg := argsI.(*InstallArgs).Shell
logger.Debugf("shellArg: %v", shellArg)
if shellArg == "" {
defaultShellName := "bash"
if os.Getenv("SHELL") != "" {
defaultShellName = filepath.Base(os.Getenv("SHELL"))
}
promptedShell, err := interactive.PromptStringWithConfig(&interactive.PromptStringConfig{
Ctx: ctx,
Prompt: "What type of shell are you using",
DefaultValue: defaultShellName,
DefaultValueDoc: defaultShellName,
})
if err != nil {
return nil, err
}
shellArg = promptedShell
}
shellName := filepath.Base(shellArg)
script, exists := autocompleteScripts(ctx)[shellName]
if !exists {
return nil, unsupportedShellError(shellName)
}
// Find destination file depending on the OS.
shellConfigurationFilePath, exists := script.ShellConfigurationFile[runtime.GOOS]
if !exists {
return nil, unsupportedOsError(runtime.GOOS)
}
// If the file doesn't exist, create it
f, err := os.OpenFile(shellConfigurationFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if f != nil {
defer f.Close()
}
if err != nil {
return nil, installationNotFound(shellName, shellConfigurationFilePath, script.CompleteScript)
}
// Early exit if eval line is already present in the shell configuration.
shellConfigurationFileContent, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
if strings.Contains(string(shellConfigurationFileContent), script.CompleteScript) {
_, _ = interactive.Println()
_, _ = interactive.Println("Autocomplete looks already installed. If it does not work properly, try to open a new shell.")
return "", nil
}
// Autocomplete script content
autoCompleteScript := "\n# Scaleway CLI autocomplete initialization.\n" + script.CompleteScript
// Warning
_, _ = interactive.Println()
_, _ = interactive.PrintlnWithoutIndent("To enable autocomplete we need to append to " + shellConfigurationFilePath + " the following lines:")
_, _ = interactive.Println(strings.ReplaceAll(autoCompleteScript, "\n", "\n\t"))
// Early exit if user disagrees
_, _ = interactive.Println()
continueInstallation, err := interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{
Ctx: ctx,
Prompt: "Do you want to proceed with these changes?",
DefaultValue: true,
})
if err != nil {
return nil, err
}
if !continueInstallation {
return nil, installationCancelledError(shellName, script.CompleteScript)
}
// Append to file
_, err = f.Write([]byte(autoCompleteScript + "\n"))
if err != nil {
return nil, err
}
// Ack
return &core.SuccessResult{
Message: fmt.Sprintf("Autocomplete has been successfully installed for your %v shell.\nUpdated %v.", shellName, shellConfigurationFilePath),
}, nil
}
func autocompleteCompleteBashCommand() *core.Command {
return &core.Command{
Short: `Autocomplete for Bash`,
Long: `Autocomplete for Bash.`,
Namespace: "autocomplete",
Resource: "complete",
Verb: "bash",
// TODO: Switch AllowAnonymousClient to true when cache will be implemented.
AllowAnonymousClient: false,
Hidden: true,
DisableTelemetry: true,
ArgsType: reflect.TypeOf(args.RawArgs{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
rawArgs := *argsI.(*args.RawArgs)
wordIndex, err := strconv.Atoi(rawArgs[1])
if err != nil {
return nil, err
}
words := rawArgs[2:]
leftWords := words[:wordIndex]
wordToComplete := words[wordIndex]
rightWords := words[wordIndex+1:]
// If the wordToComplete is an argument label (cf. `arg=`), remove
// this prefix for all suggestions.
res := core.AutoComplete(ctx, leftWords, wordToComplete, rightWords)
if strings.Contains(wordToComplete, "=") {
prefix := strings.SplitAfterN(wordToComplete, "=", 2)[0]
for k, p := range res.Suggestions {
res.Suggestions[k] = strings.TrimPrefix(p, prefix)
}
}
return strings.Join(res.Suggestions, " "), nil
},
}
}
func autocompleteCompleteFishCommand() *core.Command {
return &core.Command{
Short: `Autocomplete for Fish`,
Long: `Autocomplete for Fish.`,
Namespace: "autocomplete",
Resource: "complete",
Verb: "fish",
// TODO: Switch AllowAnonymousClient to true when cache will be implemented.
AllowAnonymousClient: false,
Hidden: true,
DisableTelemetry: true,
ArgsType: reflect.TypeOf(args.RawArgs{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
rawArgs := *argsI.(*args.RawArgs)
leftWords := rawArgs[3:]
wordToComplete := rawArgs[2]
// TODO: compute rightWords once used by core.AutoComplete()
// line := rawArgs[0]
// charIndex, _ := strconv.Atoi(rawArgs[1])
rightWords := []string(nil)
res := core.AutoComplete(ctx, leftWords, wordToComplete, rightWords)
// TODO: decide if we want to add descriptions
// see https://stackoverflow.com/a/20879411
// "followed optionally by a tab and a short description."
return strings.Join(res.Suggestions, "\n"), nil
},
}
}
func autocompleteCompleteZshCommand() *core.Command {
return &core.Command{
Short: `Autocomplete for Zsh`,
Long: `Autocomplete for Zsh.`,
Namespace: "autocomplete",
Resource: "complete",
Verb: "zsh",
// TODO: Switch AllowAnonymousClient to true when cache will be implemented.
AllowAnonymousClient: false,
Hidden: true,
DisableTelemetry: true,
ArgsType: reflect.TypeOf(args.RawArgs{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
rawArgs := *argsI.(*args.RawArgs)
// First arg is the word index.
wordIndex, err := strconv.Atoi(rawArgs[0])
if err != nil {
return nil, err
}
wordIndex-- // In zsh word index starts at 1.
// Other args are all the words.
words := rawArgs[1:]
if len(words) <= wordIndex {
words = append(words, "") // Handle case when last word is empty.
}
leftWords := words[:wordIndex]
wordToComplete := words[wordIndex]
rightWords := words[wordIndex+1:]
res := core.AutoComplete(ctx, leftWords, wordToComplete, rightWords)
return strings.Join(res.Suggestions, " "), nil
},
}
}
type autocompleteShowArgs struct {
Shell string
}
func autocompleteScriptCommand() *core.Command {
return &core.Command{
Short: `Show autocomplete script for current shell`,
Long: `Show autocomplete script for current shell.`,
Namespace: "autocomplete",
Resource: "script",
AllowAnonymousClient: true,
DisableTelemetry: true,
ArgSpecs: core.ArgSpecs{
{
Name: "shell",
Default: core.DefaultValueSetter(os.Getenv("SHELL")),
},
},
ArgsType: reflect.TypeOf(autocompleteShowArgs{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
shell := filepath.Base(argsI.(*autocompleteShowArgs).Shell)
script, exists := autocompleteScripts(ctx)[shell]
if !exists {
return nil, unsupportedShellError(shell)
}
return trimText(script.CompleteFunc), nil
},
}
}
func trimText(str string) string {
foundFirstNonEmptyLine := false
strToRemove := ""
lines := strings.Split(str, "\n")
for i, line := range lines {
if !foundFirstNonEmptyLine {
if len(line) > 0 {
for _, c := range line {
if c == ' ' || c == '\t' {
strToRemove += string(c)
continue
}
break
}
foundFirstNonEmptyLine = true
}
}
for _, c := range strToRemove {
lines[i] = strings.Replace(lines[i], string(c), "", 1)
}
}
lines = removeStartingAndEndingEmptyLines(lines)
return strings.Join(lines, "\n")
}
func removeStartingAndEndingEmptyLines(lines []string) []string {
lines = removeStartingEmptyLines(lines)
lines = reverseLines(lines)
lines = removeStartingEmptyLines(lines)
lines = reverseLines(lines)
return lines
}
func removeStartingEmptyLines(lines []string) []string {
doAdd := false
lines2 := []string(nil)
for _, line := range lines {
if len(line) > 0 {
doAdd = true
}
if doAdd {
lines2 = append(lines2, line)
}
}
return lines2
}
func reverseLines(lines []string) []string {
for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
lines[i], lines[j] = lines[j], lines[i]
}
return lines
}