app.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package cli
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "time"
  7. )
  8. // App is the main structure of a cli application. It is recomended that
  9. // and app be created with the cli.NewApp() function
  10. type App struct {
  11. // The name of the program. Defaults to os.Args[0]
  12. Name string
  13. // Description of the program.
  14. Usage string
  15. // Version of the program
  16. Version string
  17. // List of commands to execute
  18. Commands []Command
  19. // List of flags to parse
  20. Flags []Flag
  21. // Boolean to enable bash completion commands
  22. EnableBashCompletion bool
  23. // Boolean to hide built-in help command
  24. HideHelp bool
  25. // An action to execute when the bash-completion flag is set
  26. BashComplete func(context *Context)
  27. // An action to execute before any subcommands are run, but after the context is ready
  28. // If a non-nil error is returned, no subcommands are run
  29. Before func(context *Context) error
  30. // The action to execute when no subcommands are specified
  31. Action func(context *Context)
  32. // Execute this function if the proper command cannot be found
  33. CommandNotFound func(context *Context, command string)
  34. // Compilation date
  35. Compiled time.Time
  36. // Author
  37. Author string
  38. // Author e-mail
  39. Email string
  40. // Command argument requirements
  41. Requires *Requires
  42. }
  43. // Tries to find out when this binary was compiled.
  44. // Returns the current time if it fails to find it.
  45. func compileTime() time.Time {
  46. info, err := os.Stat(os.Args[0])
  47. if err != nil {
  48. return time.Now()
  49. }
  50. return info.ModTime()
  51. }
  52. // Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
  53. func NewApp() *App {
  54. return &App{
  55. Name: os.Args[0],
  56. Usage: "A new cli application",
  57. Version: "0.0.0",
  58. BashComplete: DefaultAppComplete,
  59. Action: helpCommand.Action,
  60. Compiled: compileTime(),
  61. }
  62. }
  63. // Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
  64. func (a *App) Run(arguments []string) error {
  65. // append help to commands
  66. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  67. a.Commands = append(a.Commands, helpCommand)
  68. a.appendFlag(HelpFlag)
  69. }
  70. //append version/help flags
  71. if a.EnableBashCompletion {
  72. a.appendFlag(BashCompletionFlag)
  73. }
  74. a.appendFlag(VersionFlag)
  75. // parse flags
  76. set := flagSet(a.Name, a.Flags)
  77. set.SetOutput(ioutil.Discard)
  78. err := set.Parse(arguments[1:])
  79. nerr := normalizeFlags(a.Flags, set)
  80. if nerr != nil {
  81. fmt.Println(nerr)
  82. context := NewContext(a, set, set)
  83. ShowAppHelp(context)
  84. fmt.Println("")
  85. return nerr
  86. }
  87. context := NewContext(a, set, set)
  88. if err != nil {
  89. fmt.Printf("Incorrect Usage.\n\n")
  90. ShowAppHelp(context)
  91. fmt.Println("")
  92. return err
  93. }
  94. if checkCompletions(context) {
  95. return nil
  96. }
  97. if checkHelp(context) {
  98. return nil
  99. }
  100. if checkVersion(context) {
  101. return nil
  102. }
  103. if err := context.Satisfies(a.Requires); err != nil {
  104. return err
  105. }
  106. if a.Before != nil {
  107. err := a.Before(context)
  108. if err != nil {
  109. return err
  110. }
  111. }
  112. args := context.Args()
  113. if args.Present() {
  114. name := args.First()
  115. c := a.Command(name)
  116. if c != nil {
  117. return c.Run(context)
  118. }
  119. }
  120. // Run default Action
  121. a.Action(context)
  122. return nil
  123. }
  124. // Another entry point to the cli app, takes care of passing arguments and error handling
  125. func (a *App) RunAndExitOnError() {
  126. if err := a.Run(os.Args); err != nil {
  127. os.Stderr.WriteString(fmt.Sprintln(err))
  128. os.Exit(1)
  129. }
  130. }
  131. // Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
  132. func (a *App) RunAsSubcommand(ctx *Context) error {
  133. // append help to commands
  134. if len(a.Commands) > 0 {
  135. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  136. a.Commands = append(a.Commands, helpCommand)
  137. a.appendFlag(HelpFlag)
  138. }
  139. }
  140. // append flags
  141. if a.EnableBashCompletion {
  142. a.appendFlag(BashCompletionFlag)
  143. }
  144. // parse flags
  145. set := flagSet(a.Name, a.Flags)
  146. set.SetOutput(ioutil.Discard)
  147. err := set.Parse(ctx.Args().Tail())
  148. nerr := normalizeFlags(a.Flags, set)
  149. context := NewContext(a, set, ctx.globalSet)
  150. if nerr != nil {
  151. fmt.Println(nerr)
  152. if len(a.Commands) > 0 {
  153. ShowSubcommandHelp(context)
  154. } else {
  155. ShowCommandHelp(ctx, context.Args().First())
  156. }
  157. fmt.Println("")
  158. return nerr
  159. }
  160. if err != nil {
  161. fmt.Printf("Incorrect Usage.\n\n")
  162. ShowSubcommandHelp(context)
  163. return err
  164. }
  165. if checkCompletions(context) {
  166. return nil
  167. }
  168. if len(a.Commands) > 0 {
  169. if checkSubcommandHelp(context) {
  170. return nil
  171. }
  172. } else {
  173. if checkCommandHelp(ctx, context.Args().First()) {
  174. return nil
  175. }
  176. }
  177. if err := context.Satisfies(a.Requires); err != nil {
  178. return err
  179. }
  180. if a.Before != nil {
  181. err := a.Before(context)
  182. if err != nil {
  183. return err
  184. }
  185. }
  186. args := context.Args()
  187. if args.Present() {
  188. name := args.First()
  189. c := a.Command(name)
  190. if c != nil {
  191. return c.Run(context)
  192. }
  193. }
  194. // Run default Action
  195. if len(a.Commands) > 0 {
  196. a.Action(context)
  197. } else {
  198. a.Action(ctx)
  199. }
  200. return nil
  201. }
  202. // Returns the named command on App. Returns nil if the command does not exist
  203. func (a *App) Command(name string) *Command {
  204. for _, c := range a.Commands {
  205. if c.HasName(name) {
  206. return &c
  207. }
  208. }
  209. return nil
  210. }
  211. func (a *App) hasFlag(flag Flag) bool {
  212. for _, f := range a.Flags {
  213. if flag == f {
  214. return true
  215. }
  216. }
  217. return false
  218. }
  219. func (a *App) appendFlag(flag Flag) {
  220. if !a.hasFlag(flag) {
  221. a.Flags = append(a.Flags, flag)
  222. }
  223. }