cli.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package cli
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "strings"
  8. flag "github.com/docker/docker/pkg/mflag"
  9. )
  10. // Cli represents a command line interface.
  11. type Cli struct {
  12. Stderr io.Writer
  13. handlers []Handler
  14. Usage func()
  15. }
  16. // Handler holds the different commands Cli will call
  17. // It should have methods with names starting with `Cmd` like:
  18. // func (h myHandler) CmdFoo(args ...string) error
  19. type Handler interface {
  20. Command(name string) func(...string) error
  21. }
  22. // Initializer can be optionally implemented by a Handler to
  23. // initialize before each call to one of its commands.
  24. type Initializer interface {
  25. Initialize() error
  26. }
  27. // New instantiates a ready-to-use Cli.
  28. func New(handlers ...Handler) *Cli {
  29. // make the generic Cli object the first cli handler
  30. // in order to handle `docker help` appropriately
  31. cli := new(Cli)
  32. cli.handlers = append([]Handler{cli}, handlers...)
  33. return cli
  34. }
  35. var errCommandNotFound = errors.New("command not found")
  36. func (cli *Cli) command(args ...string) (func(...string) error, error) {
  37. for _, c := range cli.handlers {
  38. if c == nil {
  39. continue
  40. }
  41. if cmd := c.Command(strings.Join(args, " ")); cmd != nil {
  42. if ci, ok := c.(Initializer); ok {
  43. if err := ci.Initialize(); err != nil {
  44. return nil, err
  45. }
  46. }
  47. return cmd, nil
  48. }
  49. }
  50. return nil, errCommandNotFound
  51. }
  52. // Run executes the specified command.
  53. func (cli *Cli) Run(args ...string) error {
  54. if len(args) > 1 {
  55. command, err := cli.command(args[:2]...)
  56. if err == nil {
  57. return command(args[2:]...)
  58. }
  59. if err != errCommandNotFound {
  60. return err
  61. }
  62. }
  63. if len(args) > 0 {
  64. command, err := cli.command(args[0])
  65. if err != nil {
  66. if err == errCommandNotFound {
  67. cli.noSuchCommand(args[0])
  68. return nil
  69. }
  70. return err
  71. }
  72. return command(args[1:]...)
  73. }
  74. return cli.CmdHelp()
  75. }
  76. func (cli *Cli) noSuchCommand(command string) {
  77. if cli.Stderr == nil {
  78. cli.Stderr = os.Stderr
  79. }
  80. fmt.Fprintf(cli.Stderr, "docker: '%s' is not a docker command.\nSee 'docker --help'.\n", command)
  81. os.Exit(1)
  82. }
  83. // Command returns a command handler, or nil if the command does not exist
  84. func (cli *Cli) Command(name string) func(...string) error {
  85. return map[string]func(...string) error{
  86. "help": cli.CmdHelp,
  87. }[name]
  88. }
  89. // CmdHelp displays information on a Docker command.
  90. //
  91. // If more than one command is specified, information is only shown for the first command.
  92. //
  93. // Usage: docker help COMMAND or docker COMMAND --help
  94. func (cli *Cli) CmdHelp(args ...string) error {
  95. if len(args) > 1 {
  96. command, err := cli.command(args[:2]...)
  97. if err == nil {
  98. command("--help")
  99. return nil
  100. }
  101. if err != errCommandNotFound {
  102. return err
  103. }
  104. }
  105. if len(args) > 0 {
  106. command, err := cli.command(args[0])
  107. if err != nil {
  108. if err == errCommandNotFound {
  109. cli.noSuchCommand(args[0])
  110. return nil
  111. }
  112. return err
  113. }
  114. command("--help")
  115. return nil
  116. }
  117. if cli.Usage == nil {
  118. flag.Usage()
  119. } else {
  120. cli.Usage()
  121. }
  122. return nil
  123. }
  124. // Subcmd is a subcommand of the main "docker" command.
  125. // A subcommand represents an action that can be performed
  126. // from the Docker command line client.
  127. //
  128. // To see all available subcommands, run "docker --help".
  129. func Subcmd(name string, synopses []string, description string, exitOnError bool) *flag.FlagSet {
  130. var errorHandling flag.ErrorHandling
  131. if exitOnError {
  132. errorHandling = flag.ExitOnError
  133. } else {
  134. errorHandling = flag.ContinueOnError
  135. }
  136. flags := flag.NewFlagSet(name, errorHandling)
  137. flags.Usage = func() {
  138. flags.ShortUsage()
  139. flags.PrintDefaults()
  140. }
  141. flags.ShortUsage = func() {
  142. if len(synopses) == 0 {
  143. synopses = []string{""}
  144. }
  145. // Allow for multiple command usage synopses.
  146. for i, synopsis := range synopses {
  147. lead := "\t"
  148. if i == 0 {
  149. // First line needs the word 'Usage'.
  150. lead = "Usage:\t"
  151. }
  152. if synopsis != "" {
  153. synopsis = " " + synopsis
  154. }
  155. fmt.Fprintf(flags.Out(), "\n%sdocker %s%s", lead, name, synopsis)
  156. }
  157. fmt.Fprintf(flags.Out(), "\n\n%s\n", description)
  158. }
  159. return flags
  160. }
  161. // StatusError reports an unsuccessful exit by a command.
  162. type StatusError struct {
  163. Status string
  164. StatusCode int
  165. }
  166. func (e StatusError) Error() string {
  167. return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
  168. }