-
Notifications
You must be signed in to change notification settings - Fork 150
/
shell.go
338 lines (285 loc) · 8.97 KB
/
shell.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
//go:build !freebsd && !wasm
// shell is disabled on freebsd as current version of github.com/pkg/term@v1.1.0 is not compiling
package core
import (
"context"
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/c-bata/go-prompt"
"github.com/fatih/color"
"github.com/scaleway/scaleway-cli/v2/internal/cache"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-cli/v2/internal/sentry"
"github.com/scaleway/scaleway-cli/v2/internal/terminal"
"github.com/spf13/cobra"
)
type Completer struct {
ctx context.Context
}
type ShellSuggestion struct {
Text string
Arg *ArgSpec
Cmd *Command
}
// lastArg returns last element of string or empty string
func lastArg(args []string) string {
l := len(args)
if l >= 2 {
return args[l-1]
}
if l == 1 {
return args[0]
}
return ""
}
// firstArg returns first element of list or empty string
func firstArg(args []string) string {
l := len(args)
if l >= 1 {
return args[0]
}
return ""
}
// trimLastArg returns all arguments but the last one
// return a nil slice if there is no previous arguments
func trimLastArg(args []string) []string {
l := len(args)
if l > 1 {
return args[:l-1]
}
return []string(nil)
}
// trimLastArg returns all arguments but the first one
// return a nil slice if there is no other arguments
func trimFirstArg(args []string) []string {
l := len(args)
if l > 1 {
return args[1:]
}
return []string(nil)
}
// ArgIsOption returns if an argument is an option
func ArgIsOption(arg string) bool {
return strings.Contains(arg, "=") || strings.Contains(arg, ".")
}
func argIsPositional(cmd *Command, arg string) bool {
if cmd.Verb != "" && cmd.Verb == arg {
return false
} else if cmd.Resource != "" && cmd.Resource == arg {
return false
} else if cmd.Namespace != "" && cmd.Resource == arg {
return false
}
return true
}
// removeOptions removes options from a list of argument
// ex: scw instance create name=myserver
// will be changed to: scw instance server create
func removeOptions(args []string) []string {
filteredArgs := []string(nil)
for _, arg := range args {
if !ArgIsOption(arg) {
filteredArgs = append(filteredArgs, arg)
}
}
return filteredArgs
}
// OptionToArgSpecName convert option to arg spec name
// from additional-volumes.0=hello to additional-volumes.{index}
// also with multiple indexes pools.0.kubelet-args. to pools.{index}.kubelet-args.{key}
func OptionToArgSpecName(option string) string {
optionName := strings.Split(option, "=")[0]
if strings.Contains(optionName, ".") {
// If option is formatted like "additional-volumes.0"
// it should be converted to "additional-volumes.{index}
elems := strings.Split(optionName, ".")
for i := range elems {
_, err := strconv.Atoi(elems[i])
if err == nil {
elems[i] = "{index}"
}
}
if elems[len(elems)-1] == "" {
elems[len(elems)-1] = "{key}"
}
optionName = strings.Join(elems, ".")
}
return optionName
}
// getCommand return command object from args and suggest
func getCommand(meta *Meta, args []string, suggest string) *Command {
rawCommand := removeOptions(args)
suggestIsOption := ArgIsOption(suggest)
if !suggestIsOption {
rawCommand = append(rawCommand, suggest)
}
rawCommand = meta.CliConfig.Alias.ResolveAliases(rawCommand)
// Find the closest command in case there is multiple positional arguments
for ; len(rawCommand) > 1; rawCommand = rawCommand[:len(rawCommand)-1] {
command, foundCommand := meta.Commands.find(rawCommand...)
if foundCommand {
return command
}
}
return nil
}
// getSuggestDescription will return suggest description
// it will return command description if it is a command
// or option description if suggest is an option of a command
func getSuggestDescription(meta *Meta, args []string, suggest string) string {
command := getCommand(meta, args, suggest)
if command == nil {
return "command not found"
}
if ArgIsOption(suggest) {
option := command.ArgSpecs.GetByName(OptionToArgSpecName(suggest))
if option != nil {
return option.Short
}
return ""
}
if argIsPositional(command, suggest) {
option := command.ArgSpecs.GetPositionalArg()
if option != nil {
return option.Short
}
return ""
}
// Should be a command, just use command short
return command.Short
}
// sortOptions sorts options, putting required first then order alphabetically
func sortOptions(meta *Meta, args []string, toSuggest string, suggestions []string) []string {
command := getCommand(meta, args, toSuggest)
if command == nil {
return suggestions
}
argSpecs := []ShellSuggestion(nil)
for _, suggest := range suggestions {
argSpec := command.ArgSpecs.GetByName(OptionToArgSpecName(suggest))
argSpecs = append(argSpecs, ShellSuggestion{
Text: suggest,
Arg: argSpec,
})
}
sort.Slice(argSpecs, func(i, j int) bool {
if argSpecs[i].Arg != nil && argSpecs[j].Arg != nil && argSpecs[i].Arg.Required != argSpecs[j].Arg.Required {
return argSpecs[i].Arg.Required
}
return argSpecs[i].Text < argSpecs[j].Text
})
suggests := []string(nil)
for _, argSpec := range argSpecs {
suggests = append(suggests, argSpec.Text)
}
return suggests
}
// Complete returns the list of suggestion based on prompt content
func (c *Completer) Complete(d prompt.Document) []prompt.Suggest {
// shell lib can request duplicate Complete request with empty strings as text
// skipping to avoid cache reset
if d.Text == "" {
return nil
}
meta := extractMeta(c.ctx)
argsBeforeCursor := meta.CliConfig.Alias.ResolveAliases(strings.Split(d.TextBeforeCursor(), " "))
argsAfterCursor := meta.CliConfig.Alias.ResolveAliases(strings.Split(d.TextAfterCursor(), " "))
currentArg := lastArg(argsBeforeCursor) + firstArg(argsAfterCursor)
// leftArgs contains all arguments before the one with the cursor
leftArgs := trimLastArg(argsBeforeCursor)
// rightWords contains all words after the selected one
rightWords := trimFirstArg(argsAfterCursor)
leftWords := append([]string{"scw"}, leftArgs...)
acr := AutoComplete(c.ctx, leftWords, currentArg, rightWords)
suggestions := []prompt.Suggest(nil)
rawSuggestions := []string(acr.Suggestions)
// if first suggestion is an option, all suggestions should be options
// we sort them
if len(rawSuggestions) > 0 && ArgIsOption(rawSuggestions[0]) {
rawSuggestions = sortOptions(meta, leftArgs, rawSuggestions[0], rawSuggestions)
}
for _, suggest := range rawSuggestions {
suggestions = append(suggestions, prompt.Suggest{
Text: suggest,
Description: getSuggestDescription(meta, leftArgs, suggest),
})
}
return prompt.FilterHasPrefix(suggestions, currentArg, true)
}
func NewShellCompleter(ctx context.Context) *Completer {
return &Completer{
ctx: ctx,
}
}
// shellExecutor returns the function that will execute command entered in shell
func shellExecutor(rootCmd *cobra.Command, printer *Printer, meta *Meta) func(s string) {
return func(s string) {
args := strings.Fields(s)
sentry.AddCommandContext(strings.Join(removeOptions(args), " "))
rootCmd.SetArgs(meta.CliConfig.Alias.ResolveAliases(args))
err := rootCmd.Execute()
if err != nil {
if _, ok := err.(*interactive.InterruptError); ok {
return
}
printErr := printer.Print(err, nil)
if printErr != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
return
}
// command is nil if it does not have a Run function
// ex: instance -h
if meta.command == nil {
return
}
autoCompleteCache.Update(meta.command.Namespace)
printErr := printer.Print(meta.result, meta.command.getHumanMarshalerOpt())
if printErr != nil {
_, _ = fmt.Fprintln(os.Stderr, printErr)
}
}
}
// Return the shell subcommand
func getShellCommand(rootCmd *cobra.Command) *cobra.Command {
subcommands := rootCmd.Commands()
for _, command := range subcommands {
if command.Name() == "shell" {
return command
}
}
return nil
}
// RunShell will run an interactive shell that runs cobra commands
func RunShell(ctx context.Context, printer *Printer, meta *Meta, rootCmd *cobra.Command, args []string) {
autoCompleteCache = cache.New()
completer := NewShellCompleter(ctx)
shellCobraCommand := getShellCommand(rootCmd)
shellCobraCommand.InitDefaultHelpFlag()
_ = shellCobraCommand.ParseFlags(args)
if isHelp, _ := shellCobraCommand.Flags().GetBool("help"); isHelp {
shellCobraCommand.HelpFunc()(shellCobraCommand, args)
return
}
// remove shell command so it cannot be called from shell
rootCmd.RemoveCommand(shellCobraCommand)
meta.Commands.Remove("shell", "")
executor := shellExecutor(rootCmd, printer, meta)
quitMessage := terminal.Style("- Type Ctrl+d to quit.", color.Bold, color.FgCyan)
fmt.Println(quitMessage)
p := prompt.New(
executor,
completer.Complete,
prompt.OptionPrefix(">>> "),
prompt.OptionSuggestionBGColor(prompt.Purple),
prompt.OptionSelectedSuggestionBGColor(prompt.Fuchsia),
prompt.OptionSelectedSuggestionTextColor(prompt.White),
prompt.OptionDescriptionBGColor(prompt.Purple),
prompt.OptionSelectedDescriptionBGColor(prompt.Fuchsia),
prompt.OptionSelectedDescriptionTextColor(prompt.White),
)
p.Run()
}