app.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. // Boolean to hide built-in version flag
  26. HideVersion bool
  27. // An action to execute when the bash-completion flag is set
  28. BashComplete func(context *Context)
  29. // An action to execute before any subcommands are run, but after the context is ready
  30. // If a non-nil error is returned, no subcommands are run
  31. Before func(context *Context) error
  32. // The action to execute when no subcommands are specified
  33. Action func(context *Context)
  34. // Execute this function if the proper command cannot be found
  35. CommandNotFound func(context *Context, command string)
  36. // Compilation date
  37. Compiled time.Time
  38. // Author
  39. Author string
  40. // Author e-mail
  41. Email string
  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. if !a.HideVersion {
  75. a.appendFlag(VersionFlag)
  76. }
  77. // parse flags
  78. set := flagSet(a.Name, a.Flags)
  79. set.SetOutput(ioutil.Discard)
  80. err := set.Parse(arguments[1:])
  81. nerr := normalizeFlags(a.Flags, set)
  82. if nerr != nil {
  83. fmt.Println(nerr)
  84. context := NewContext(a, set, set)
  85. ShowAppHelp(context)
  86. fmt.Println("")
  87. return nerr
  88. }
  89. context := NewContext(a, set, set)
  90. if err != nil {
  91. fmt.Printf("Incorrect Usage.\n\n")
  92. ShowAppHelp(context)
  93. fmt.Println("")
  94. return err
  95. }
  96. if checkCompletions(context) {
  97. return nil
  98. }
  99. if checkHelp(context) {
  100. return nil
  101. }
  102. if checkVersion(context) {
  103. return nil
  104. }
  105. if a.Before != nil {
  106. err := a.Before(context)
  107. if err != nil {
  108. return err
  109. }
  110. }
  111. args := context.Args()
  112. if args.Present() {
  113. name := args.First()
  114. c := a.Command(name)
  115. if c != nil {
  116. return c.Run(context)
  117. }
  118. }
  119. // Run default Action
  120. a.Action(context)
  121. return nil
  122. }
  123. // Another entry point to the cli app, takes care of passing arguments and error handling
  124. func (a *App) RunAndExitOnError() {
  125. if err := a.Run(os.Args); err != nil {
  126. os.Stderr.WriteString(fmt.Sprintln(err))
  127. os.Exit(1)
  128. }
  129. }
  130. // Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
  131. func (a *App) RunAsSubcommand(ctx *Context) error {
  132. // append help to commands
  133. if len(a.Commands) > 0 {
  134. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  135. a.Commands = append(a.Commands, helpCommand)
  136. a.appendFlag(HelpFlag)
  137. }
  138. }
  139. // append flags
  140. if a.EnableBashCompletion {
  141. a.appendFlag(BashCompletionFlag)
  142. }
  143. // parse flags
  144. set := flagSet(a.Name, a.Flags)
  145. set.SetOutput(ioutil.Discard)
  146. err := set.Parse(ctx.Args().Tail())
  147. nerr := normalizeFlags(a.Flags, set)
  148. context := NewContext(a, set, ctx.globalSet)
  149. if nerr != nil {
  150. fmt.Println(nerr)
  151. if len(a.Commands) > 0 {
  152. ShowSubcommandHelp(context)
  153. } else {
  154. ShowCommandHelp(ctx, context.Args().First())
  155. }
  156. fmt.Println("")
  157. return nerr
  158. }
  159. if err != nil {
  160. fmt.Printf("Incorrect Usage.\n\n")
  161. ShowSubcommandHelp(context)
  162. return err
  163. }
  164. if checkCompletions(context) {
  165. return nil
  166. }
  167. if len(a.Commands) > 0 {
  168. if checkSubcommandHelp(context) {
  169. return nil
  170. }
  171. } else {
  172. if checkCommandHelp(ctx, context.Args().First()) {
  173. return nil
  174. }
  175. }
  176. if a.Before != nil {
  177. err := a.Before(context)
  178. if err != nil {
  179. return err
  180. }
  181. }
  182. args := context.Args()
  183. if args.Present() {
  184. name := args.First()
  185. c := a.Command(name)
  186. if c != nil {
  187. return c.Run(context)
  188. }
  189. }
  190. // Run default Action
  191. if len(a.Commands) > 0 {
  192. a.Action(context)
  193. } else {
  194. a.Action(ctx)
  195. }
  196. return nil
  197. }
  198. // Returns the named command on App. Returns nil if the command does not exist
  199. func (a *App) Command(name string) *Command {
  200. for _, c := range a.Commands {
  201. if c.HasName(name) {
  202. return &c
  203. }
  204. }
  205. return nil
  206. }
  207. func (a *App) hasFlag(flag Flag) bool {
  208. for _, f := range a.Flags {
  209. if flag == f {
  210. return true
  211. }
  212. }
  213. return false
  214. }
  215. func (a *App) appendFlag(flag Flag) {
  216. if !a.hasFlag(flag) {
  217. a.Flags = append(a.Flags, flag)
  218. }
  219. }