option_arguments.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package promputils
  15. import (
  16. "io/ioutil"
  17. "log"
  18. "path/filepath"
  19. "strings"
  20. prompt "github.com/c-bata/go-prompt"
  21. )
  22. func init() {
  23. fileListCache = map[string][]prompt.Suggest{}
  24. }
  25. func getPreviousOption(d prompt.Document) (cmd, option string, found bool) {
  26. args := strings.Split(d.TextBeforeCursor(), " ")
  27. l := len(args)
  28. if l >= 2 {
  29. option = args[l-2]
  30. }
  31. if strings.HasPrefix(option, "-") {
  32. return args[0], option, true
  33. }
  34. return "", "", false
  35. }
  36. func completeOptionArguments(d prompt.Document) ([]prompt.Suggest, bool) {
  37. cmd, option, found := getPreviousOption(d)
  38. if !found {
  39. return []prompt.Suggest{}, false
  40. }
  41. switch cmd {
  42. case "server-attach-disk", "describe", "create", "delete", "replace", "patch",
  43. "edit", "apply", "expose", "rolling-update", "rollout",
  44. "label", "annotate", "scale", "convert", "autoscale":
  45. switch option {
  46. case "-f", "--filename":
  47. return fileCompleter(d), true
  48. }
  49. }
  50. return []prompt.Suggest{}, false
  51. }
  52. /* file list */
  53. var fileListCache map[string][]prompt.Suggest
  54. func fileCompleter(d prompt.Document) []prompt.Suggest {
  55. path := d.GetWordBeforeCursor()
  56. if strings.HasPrefix(path, "./") {
  57. path = path[2:]
  58. }
  59. dir := filepath.Dir(path)
  60. if cached, ok := fileListCache[dir]; ok {
  61. return cached
  62. }
  63. files, err := ioutil.ReadDir(dir)
  64. if err != nil {
  65. log.Print("[ERROR] catch error " + err.Error())
  66. return []prompt.Suggest{}
  67. }
  68. suggests := make([]prompt.Suggest, 0, len(files))
  69. for _, f := range files {
  70. if !f.IsDir() &&
  71. !strings.HasSuffix(f.Name(), ".yml") &&
  72. !strings.HasSuffix(f.Name(), ".yaml") {
  73. continue
  74. }
  75. suggests = append(suggests, prompt.Suggest{Text: filepath.Join(dir, f.Name())})
  76. }
  77. return prompt.FilterHasPrefix(suggests, path, false)
  78. }