|
| 1 | +package core |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "sort" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/c-bata/go-prompt" |
| 12 | + "github.com/scaleway/scaleway-cli/v2/internal/interactive" |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +type Completer struct { |
| 17 | + ctx context.Context |
| 18 | +} |
| 19 | + |
| 20 | +type ShellSuggestion struct { |
| 21 | + Text string |
| 22 | + Arg *ArgSpec |
| 23 | + Cmd *Command |
| 24 | +} |
| 25 | + |
| 26 | +// lastArg returns last element of string or empty string |
| 27 | +func lastArg(args []string) string { |
| 28 | + l := len(args) |
| 29 | + if l >= 2 { |
| 30 | + return args[l-1] |
| 31 | + } |
| 32 | + if l == 1 { |
| 33 | + return args[0] |
| 34 | + } |
| 35 | + return "" |
| 36 | +} |
| 37 | + |
| 38 | +// firstArg returns first element of list or empty string |
| 39 | +func firstArg(args []string) string { |
| 40 | + l := len(args) |
| 41 | + if l >= 1 { |
| 42 | + return args[0] |
| 43 | + } |
| 44 | + return "" |
| 45 | +} |
| 46 | + |
| 47 | +// trimLastArg returns all arguments but the last one |
| 48 | +// return a nil slice if there is no previous arguments |
| 49 | +func trimLastArg(args []string) []string { |
| 50 | + l := len(args) |
| 51 | + if l > 1 { |
| 52 | + return args[:l-1] |
| 53 | + } |
| 54 | + return []string(nil) |
| 55 | +} |
| 56 | + |
| 57 | +// argIsOption returns if an argument is an option |
| 58 | +func argIsOption(arg string) bool { |
| 59 | + return strings.Contains(arg, "=") || strings.Contains(arg, ".") |
| 60 | +} |
| 61 | + |
| 62 | +// removeOptions removes options from a list of argument |
| 63 | +// ex: scw instance create name=myserver |
| 64 | +// will be changed to: scw instance server create |
| 65 | +func removeOptions(args []string) []string { |
| 66 | + filteredArgs := []string(nil) |
| 67 | + for _, arg := range args { |
| 68 | + if !argIsOption(arg) { |
| 69 | + filteredArgs = append(filteredArgs, arg) |
| 70 | + } |
| 71 | + } |
| 72 | + return filteredArgs |
| 73 | +} |
| 74 | + |
| 75 | +// optionToArgSpecName convert option to arg spec name |
| 76 | +// from additional-volumes.0=hello to additional-volumes.{index} |
| 77 | +// also with multiple indexes pools.0.kubelet-args. to pools.{index}.kubelet-args.{key} |
| 78 | +func optionToArgSpecName(option string) string { |
| 79 | + optionName := strings.Split(option, "=")[0] |
| 80 | + |
| 81 | + if strings.Contains(optionName, ".") { |
| 82 | + // If option is formatted like "additional-volumes.0" |
| 83 | + // it should be converted to "additional-volumes.{index} |
| 84 | + elems := strings.Split(optionName, ".") |
| 85 | + for i := range elems { |
| 86 | + _, err := strconv.Atoi(elems[i]) |
| 87 | + if err == nil { |
| 88 | + elems[i] = "{index}" |
| 89 | + } |
| 90 | + } |
| 91 | + if elems[len(elems)-1] == "" { |
| 92 | + elems[len(elems)-1] = "{key}" |
| 93 | + } |
| 94 | + optionName = strings.Join(elems, ".") |
| 95 | + } |
| 96 | + return optionName |
| 97 | +} |
| 98 | + |
| 99 | +// getCommand return command object from args and suggest |
| 100 | +func getCommand(meta *meta, args []string, suggest string) *Command { |
| 101 | + rawCommand := removeOptions(args) |
| 102 | + suggestIsOption := argIsOption(suggest) |
| 103 | + |
| 104 | + if !suggestIsOption { |
| 105 | + rawCommand = append(rawCommand, suggest) |
| 106 | + } |
| 107 | + |
| 108 | + command, foundCommand := meta.Commands.find(rawCommand...) |
| 109 | + if foundCommand { |
| 110 | + return command |
| 111 | + } |
| 112 | + return nil |
| 113 | +} |
| 114 | + |
| 115 | +// getSuggestDescription will return suggest description |
| 116 | +// it will return command description if it is a command |
| 117 | +// or option description if suggest is an option of a command |
| 118 | +func getSuggestDescription(meta *meta, args []string, suggest string) string { |
| 119 | + isOption := argIsOption(suggest) |
| 120 | + |
| 121 | + command := getCommand(meta, args, suggest) |
| 122 | + if command == nil { |
| 123 | + return "command not found" |
| 124 | + } |
| 125 | + |
| 126 | + if isOption { |
| 127 | + option := command.ArgSpecs.GetByName(optionToArgSpecName(suggest)) |
| 128 | + if option != nil { |
| 129 | + return option.Short |
| 130 | + } |
| 131 | + } else { |
| 132 | + return command.Short |
| 133 | + } |
| 134 | + |
| 135 | + return "" |
| 136 | +} |
| 137 | + |
| 138 | +// sortOptions sorts options, putting required first then order alphabetically |
| 139 | +func sortOptions(meta *meta, args []string, toSuggest string, suggestions []string) []string { |
| 140 | + command := getCommand(meta, args, toSuggest) |
| 141 | + if command == nil { |
| 142 | + return suggestions |
| 143 | + } |
| 144 | + |
| 145 | + argSpecs := []ShellSuggestion(nil) |
| 146 | + for _, suggest := range suggestions { |
| 147 | + argSpec := command.ArgSpecs.GetByName(optionToArgSpecName(suggest)) |
| 148 | + argSpecs = append(argSpecs, ShellSuggestion{ |
| 149 | + Text: suggest, |
| 150 | + Arg: argSpec, |
| 151 | + }) |
| 152 | + } |
| 153 | + |
| 154 | + sort.Slice(argSpecs, func(i, j int) bool { |
| 155 | + if argSpecs[i].Arg.Required != argSpecs[j].Arg.Required { |
| 156 | + return argSpecs[i].Arg.Required |
| 157 | + } |
| 158 | + return argSpecs[i].Text < argSpecs[j].Text |
| 159 | + }) |
| 160 | + |
| 161 | + suggests := []string(nil) |
| 162 | + for _, argSpec := range argSpecs { |
| 163 | + suggests = append(suggests, argSpec.Text) |
| 164 | + } |
| 165 | + |
| 166 | + return suggests |
| 167 | +} |
| 168 | + |
| 169 | +// Complete returns the list of suggestion based on prompt content |
| 170 | +func (c *Completer) Complete(d prompt.Document) []prompt.Suggest { |
| 171 | + argsBeforeCursor := strings.Split(d.TextBeforeCursor(), " ") |
| 172 | + argsAfterCursor := strings.Split(d.TextAfterCursor(), " ") |
| 173 | + currentArg := lastArg(argsBeforeCursor) + firstArg(argsAfterCursor) |
| 174 | + |
| 175 | + // args contains all arguments before the one with the cursor |
| 176 | + args := trimLastArg(argsBeforeCursor) |
| 177 | + |
| 178 | + acr := AutoComplete(c.ctx, append([]string{"scw"}, args...), currentArg, argsAfterCursor) |
| 179 | + |
| 180 | + suggestions := []prompt.Suggest(nil) |
| 181 | + |
| 182 | + meta := extractMeta(c.ctx) |
| 183 | + rawSuggestions := []string(acr.Suggestions) |
| 184 | + |
| 185 | + // if first suggestion is an option, all suggestions should be options |
| 186 | + // we sort them |
| 187 | + if len(rawSuggestions) > 0 && argIsOption(rawSuggestions[0]) { |
| 188 | + rawSuggestions = sortOptions(meta, args, rawSuggestions[0], rawSuggestions) |
| 189 | + } |
| 190 | + |
| 191 | + for _, suggest := range rawSuggestions { |
| 192 | + suggestions = append(suggestions, prompt.Suggest{ |
| 193 | + Text: suggest, |
| 194 | + Description: getSuggestDescription(meta, args, suggest), |
| 195 | + }) |
| 196 | + } |
| 197 | + |
| 198 | + return prompt.FilterHasPrefix(suggestions, currentArg, true) |
| 199 | +} |
| 200 | + |
| 201 | +func NewShellCompleter(ctx context.Context) *Completer { |
| 202 | + return &Completer{ |
| 203 | + ctx: ctx, |
| 204 | + } |
| 205 | +} |
| 206 | + |
| 207 | +// shellExecutor returns the function that will execute command entered in shell |
| 208 | +func shellExecutor(rootCmd *cobra.Command, printer *Printer, meta *meta) func(s string) { |
| 209 | + return func(s string) { |
| 210 | + args := strings.Fields(s) |
| 211 | + rootCmd.SetArgs(args) |
| 212 | + |
| 213 | + err := rootCmd.Execute() |
| 214 | + if err != nil { |
| 215 | + if _, ok := err.(*interactive.InterruptError); ok { |
| 216 | + return |
| 217 | + } |
| 218 | + |
| 219 | + printErr := printer.Print(err, nil) |
| 220 | + if printErr != nil { |
| 221 | + _, _ = fmt.Fprintln(os.Stderr, err) |
| 222 | + } |
| 223 | + |
| 224 | + return |
| 225 | + } |
| 226 | + |
| 227 | + printErr := printer.Print(meta.result, meta.command.getHumanMarshalerOpt()) |
| 228 | + if printErr != nil { |
| 229 | + _, _ = fmt.Fprintln(os.Stderr, printErr) |
| 230 | + } |
| 231 | + } |
| 232 | +} |
| 233 | + |
| 234 | +// Return the shell subcommand |
| 235 | +func getShellCommand(rootCmd *cobra.Command) *cobra.Command { |
| 236 | + subcommands := rootCmd.Commands() |
| 237 | + for _, command := range subcommands { |
| 238 | + if command.Name() == "shell" { |
| 239 | + return command |
| 240 | + } |
| 241 | + } |
| 242 | + return nil |
| 243 | +} |
| 244 | + |
| 245 | +// RunShell will run an interactive shell that runs cobra commands |
| 246 | +func RunShell(ctx context.Context, printer *Printer, meta *meta, rootCmd *cobra.Command, args []string) { |
| 247 | + completer := NewShellCompleter(ctx) |
| 248 | + |
| 249 | + shellCobraCommand := getShellCommand(rootCmd) |
| 250 | + shellCobraCommand.InitDefaultHelpFlag() |
| 251 | + _ = shellCobraCommand.ParseFlags(args) |
| 252 | + if isHelp, _ := shellCobraCommand.Flags().GetBool("help"); isHelp { |
| 253 | + shellCobraCommand.HelpFunc()(shellCobraCommand, args) |
| 254 | + return |
| 255 | + } |
| 256 | + |
| 257 | + // remove shell command so it cannot be called from shell |
| 258 | + rootCmd.RemoveCommand(shellCobraCommand) |
| 259 | + meta.Commands.Remove("shell", "") |
| 260 | + |
| 261 | + executor := shellExecutor(rootCmd, printer, meta) |
| 262 | + p := prompt.New( |
| 263 | + executor, |
| 264 | + completer.Complete, |
| 265 | + prompt.OptionPrefix(">>>"), |
| 266 | + prompt.OptionSuggestionBGColor(prompt.Purple), |
| 267 | + prompt.OptionSelectedSuggestionBGColor(prompt.Fuchsia), |
| 268 | + prompt.OptionSelectedSuggestionTextColor(prompt.White), |
| 269 | + prompt.OptionDescriptionBGColor(prompt.Purple), |
| 270 | + prompt.OptionSelectedDescriptionBGColor(prompt.Fuchsia), |
| 271 | + prompt.OptionSelectedDescriptionTextColor(prompt.White), |
| 272 | + ) |
| 273 | + p.Run() |
| 274 | +} |
0 commit comments