registry.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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.
  36. func (r *Registry) Register(c *Command) {
  37. r.mu.Lock()
  38. defer r.mu.Unlock()
  39. r.commands[c.Name] = c
  40. }
  41. // Get returns the command registered under name, or nil if there is no such command.
  42. func (r *Registry) Get(name Name) *Command {
  43. r.mu.RLock()
  44. defer r.mu.RUnlock()
  45. return r.commands[name]
  46. }
  47. // Match returns the names of every command starting with prefix, sorted, as strings for
  48. // a prompt to complete and print.
  49. func (r *Registry) Match(prefix string) []string {
  50. cmds := make([]string, 0)
  51. r.mu.RLock()
  52. for n := range r.commands {
  53. if strings.HasPrefix(string(n), prefix) {
  54. cmds = append(cmds, string(n))
  55. }
  56. }
  57. r.mu.RUnlock()
  58. slices.Sort(cmds)
  59. return cmds
  60. }
  61. // All returns every registered command sorted by name, which is the order help lists them.
  62. func (r *Registry) All() []*Command {
  63. r.mu.RLock()
  64. defer r.mu.RUnlock()
  65. cmds := slices.Collect(maps.Values(r.commands))
  66. slices.SortFunc(cmds, func(a, b *Command) int { return cmp.Compare(a.Name, b.Name) })
  67. return cmds
  68. }
  69. // Clone returns a copy holding the same commands.
  70. func (r *Registry) Clone() *Registry {
  71. r.mu.RLock()
  72. defer r.mu.RUnlock()
  73. return &Registry{commands: maps.Clone(r.commands)}
  74. }
  75. // Dispatch parses a command line and runs it, reporting problems to w.
  76. func (r *Registry) Dispatch(line string, w StringWriter) {
  77. // A line shlex cannot split, an unbalanced quote, gets no answer. sshd was silent
  78. // here too; this is a relocation, so it stays silent.
  79. args, err := shlex.Split(line, true)
  80. if err != nil {
  81. return
  82. }
  83. _ = r.DispatchArgs(args, line, w)
  84. }
  85. // DispatchArgs runs an already tokenized command line. orig is what the user typed,
  86. // used only for the "did not understand" message; callers that have no raw line may
  87. // pass "" and the joined args are used instead.
  88. func (r *Registry) DispatchArgs(args []string, orig string, w StringWriter) error {
  89. if len(args) == 0 {
  90. r.dumpCommands(w)
  91. return nil
  92. }
  93. c := r.Get(Name(args[0]))
  94. if c == nil {
  95. if orig == "" {
  96. orig = strings.Join(args, " ")
  97. }
  98. if err := w.WriteLine(fmt.Sprintf("did not understand: %s", orig)); err != nil {
  99. return err
  100. }
  101. r.dumpCommands(w)
  102. return nil
  103. }
  104. if checkHelpArgs(args) {
  105. // Through the registered help command, so -h and `help <name>` are one path.
  106. return execCommand(r.Get(Help), []string{string(c.Name)}, w)
  107. }
  108. return execCommand(c, args[1:], w)
  109. }
  110. // dumpCommands writes the list of available commands to w.
  111. func (r *Registry) dumpCommands(w StringWriter) {
  112. err := w.WriteLine("Available commands:")
  113. if err != nil {
  114. return
  115. }
  116. // In the order All gives, which is the display order.
  117. cmds := make([]string, 0)
  118. for _, l := range r.All() {
  119. cmds = append(cmds, fmt.Sprintf("%s - %s", l.Name, l.ShortDescription))
  120. }
  121. _ = w.Write(strings.Join(cmds, "\n") + "\n\n")
  122. }
  123. // help writes the command list, or usage for the single command named in a.
  124. func (r *Registry) help(a []string, w StringWriter) error {
  125. // Just typed help
  126. if len(a) == 0 {
  127. r.dumpCommands(w)
  128. return nil
  129. }
  130. // We are printing a specific commands help text
  131. cmd := r.Get(Name(a[0]))
  132. if cmd == nil {
  133. return w.WriteLine("Command not available " + a[0])
  134. }
  135. if err := w.WriteLine(fmt.Sprintf("%s - %s", cmd.Name, cmd.ShortDescription)); err != nil {
  136. return err
  137. }
  138. if cmd.Help != "" {
  139. if err := w.WriteLine(fmt.Sprintf(" %s", cmd.Help)); err != nil {
  140. return err
  141. }
  142. }
  143. if cmd.Flags != nil {
  144. fs, _ := cmd.Flags()
  145. if fs != nil {
  146. fs.SetOutput(w.GetWriter())
  147. fs.PrintDefaults()
  148. }
  149. }
  150. return nil
  151. }