diff --git a/README.md b/README.md index 65956155e5..833c9df80f 100644 --- a/README.md +++ b/README.md @@ -916,6 +916,7 @@ Development in progress #### Features +* Support of `_completion` command (shell completion helper) ([#45](https://github.com/scaleway/scaleway-cli/issues/45)) * Returing more resource fields on `scw inspect` ([#50](https://github.com/scaleway/scaleway-cli/issues/50)) * Show public ip address in PORTS field in `scw ps` ([#54](https://github.com/scaleway/scaleway-cli/issues/54)) * Support of `inspect --format` option diff --git a/cli.go b/cli.go index 4f25071d10..c5eb24f6c0 100644 --- a/cli.go +++ b/cli.go @@ -233,6 +233,7 @@ func (c *Command) GetBootscript(needle string) string { var commands = []*Command{ cmdAttach, cmdCommit, + cmdCompletion, cmdCp, cmdCreate, cmdEvents, diff --git a/completion.go b/completion.go new file mode 100644 index 0000000000..9494a9913a --- /dev/null +++ b/completion.go @@ -0,0 +1,71 @@ +package main + +import ( + "fmt" + "log" + "sort" + "strings" +) + +var cmdCompletion = &Command{ + Exec: runCompletion, + UsageLine: "_completion [OPTIONS] CATEGORY", + Description: "Completion helper", + Help: "Completion helper.", + Hidden: true, + Examples: ` + $ scw _completion servers-all + $ scw _completion images-all + $ scw _completion snapshots-all + $ scw _completion volumes-all + $ scw _completion bootscripts-all +`, +} + +func init() { + cmdCompletion.Flag.BoolVar(&completionHelp, []string{"h", "-help"}, false, "Print usage") +} + +// Flags +var completionHelp bool // -h, --help flag + +func runCompletion(cmd *Command, args []string) { + if completionHelp { + cmd.PrintUsage() + } + if len(args) != 1 { + cmd.PrintShortUsage() + } + + category := args[0] + + elements := []string{} + + switch category { + case "servers-all": + for identifier, name := range cmd.API.Cache.Servers { + elements = append(elements, identifier, wordify(name)) + } + case "images-all": + for identifier, name := range cmd.API.Cache.Images { + elements = append(elements, identifier, wordify(name)) + } + case "volumes-all": + for identifier, name := range cmd.API.Cache.Volumes { + elements = append(elements, identifier, wordify(name)) + } + case "snapshots-all": + for identifier, name := range cmd.API.Cache.Snapshots { + elements = append(elements, identifier, wordify(name)) + } + case "bootscripts-all": + for identifier, name := range cmd.API.Cache.Bootscripts { + elements = append(elements, identifier, wordify(name)) + } + default: + log.Fatalf("Unhandled category of completion: %s", category) + } + + sort.Strings(elements) + fmt.Println(strings.Join(RemoveDuplicates(elements), "\n")) +}