1
0

registry.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package commands
  2. import (
  3. "cmp"
  4. "fmt"
  5. "maps"
  6. "slices"
  7. "strings"
  8. "sync"
  9. "github.com/anmitsu/go-shlex"
  10. )
  11. // Registry holds a set of commands. New is the only way to make one.
  12. //
  13. // It is safe for concurrent use. Commands may be registered while a surface is serving
  14. // from the registry: the ssh server clones it per session, and a clone may overlap a
  15. // Register.
  16. type Registry struct {
  17. mu sync.RWMutex
  18. commands map[Name]*Command
  19. }
  20. // New returns an empty Registry with only `help` available.
  21. func New() *Registry {
  22. r := &Registry{commands: map[Name]*Command{}}
  23. r.registerHelp()
  24. return r
  25. }
  26. func (r *Registry) registerHelp() {
  27. r.Register(&Command{
  28. Name: Help,
  29. ShortDescription: "prints available commands or help <command> for specific usage info",
  30. Callback: func(a any, args []string, w StringWriter) error {
  31. return r.help(args, w)
  32. },
  33. })
  34. }
  35. // Register adds a command that can be run by a user. A command registered under a name
  36. // already held replaces it; see Clone for what that means for Help.
  37. func (r *Registry) Register(c *Command) {
  38. r.mu.Lock()
  39. defer r.mu.Unlock()
  40. r.commands[c.Name] = c
  41. }
  42. // Get returns the command registered under name, or nil if there is no such command.
  43. func (r *Registry) Get(name Name) *Command {
  44. r.mu.RLock()
  45. defer r.mu.RUnlock()
  46. return r.commands[name]
  47. }
  48. // Match returns the names of every command starting with prefix, sorted, as strings for
  49. // a prompt to complete and print.
  50. func (r *Registry) Match(prefix string) []string {
  51. cmds := make([]string, 0)
  52. r.mu.RLock()
  53. for n := range r.commands {
  54. if strings.HasPrefix(string(n), prefix) {
  55. cmds = append(cmds, string(n))
  56. }
  57. }
  58. r.mu.RUnlock()
  59. slices.Sort(cmds)
  60. return cmds
  61. }
  62. // All returns every registered command sorted by name, which is the order help lists them.
  63. func (r *Registry) All() []*Command {
  64. r.mu.RLock()
  65. defer r.mu.RUnlock()
  66. cmds := slices.Collect(maps.Values(r.commands))
  67. slices.SortFunc(cmds, func(a, b *Command) int { return cmp.Compare(a.Name, b.Name) })
  68. return cmds
  69. }
  70. // Clone returns a copy holding the same commands, with help bound to the copy: a
  71. // command registered on the clone alone is listed and described there, and one the
  72. // clone withholds is not. That rebinding replaces whatever was registered under Help on
  73. // the source, built-in or not.
  74. func (r *Registry) Clone() *Registry {
  75. r.mu.RLock()
  76. c := &Registry{commands: maps.Clone(r.commands)}
  77. r.mu.RUnlock()
  78. c.registerHelp()
  79. return c
  80. }
  81. // Dispatch parses a command line and runs it, reporting problems to w. The error is for
  82. // the caller to log, not to show; see CommandCallback.
  83. func (r *Registry) Dispatch(line string, w StringWriter) error {
  84. // A line shlex cannot split, an unbalanced quote.
  85. args, err := shlex.Split(line, true)
  86. if err != nil {
  87. return Fail(w, "could not parse the command line: "+err.Error())
  88. }
  89. return r.DispatchArgs(args, w)
  90. }
  91. // DispatchArgs runs an already tokenized command line. The error is as for Dispatch.
  92. func (r *Registry) DispatchArgs(args []string, w StringWriter) error {
  93. if len(args) == 0 {
  94. r.dumpCommands(w)
  95. return nil
  96. }
  97. c := r.Get(Name(args[0]))
  98. if c == nil {
  99. // Only the first word was looked up, so only it is named.
  100. msg := fmt.Sprintf("did not understand: %s", args[0])
  101. if err := w.WriteLine(msg); err != nil {
  102. return err
  103. }
  104. r.dumpCommands(w)
  105. return &Failure{Msg: msg}
  106. }
  107. if checkHelpArgs(args) {
  108. // Through the registered help command, so -h and `help <name>` are one path.
  109. return execCommand(r.Get(Help), []string{string(c.Name)}, w)
  110. }
  111. return execCommand(c, args[1:], w)
  112. }
  113. // dumpCommands writes the list of available commands to w.
  114. func (r *Registry) dumpCommands(w StringWriter) {
  115. err := w.WriteLine("Available commands:")
  116. if err != nil {
  117. return
  118. }
  119. // In the order All gives, which is the display order.
  120. cmds := make([]string, 0)
  121. for _, l := range r.All() {
  122. cmds = append(cmds, fmt.Sprintf("%s - %s", l.Name, l.ShortDescription))
  123. }
  124. _ = w.Write(strings.Join(cmds, "\n") + "\n\n")
  125. }
  126. // help writes the command list, or usage for the single command named in a.
  127. func (r *Registry) help(a []string, w StringWriter) error {
  128. // Just typed help
  129. if len(a) == 0 {
  130. r.dumpCommands(w)
  131. return nil
  132. }
  133. // We are printing a specific commands help text
  134. cmd := r.Get(Name(a[0]))
  135. if cmd == nil {
  136. return Fail(w, "Command not available "+a[0])
  137. }
  138. if err := w.WriteLine(fmt.Sprintf("%s - %s", cmd.Name, cmd.ShortDescription)); err != nil {
  139. return err
  140. }
  141. if cmd.Help != "" {
  142. if err := w.WriteLine(fmt.Sprintf(" %s", cmd.Help)); err != nil {
  143. return err
  144. }
  145. }
  146. if cmd.Flags != nil {
  147. fs, _ := cmd.Flags()
  148. if fs != nil {
  149. fs.SetOutput(w.GetWriter())
  150. fs.PrintDefaults()
  151. }
  152. }
  153. return nil
  154. }