app.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package cli
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "time"
  8. )
  9. // App is the main structure of a cli application. It is recomended that
  10. // an app be created with the cli.NewApp() function
  11. type App struct {
  12. // The name of the program. Defaults to os.Args[0]
  13. Name string
  14. // Full name of command for help, defaults to Name
  15. HelpName string
  16. // Description of the program.
  17. Usage string
  18. // Description of the program argument format.
  19. ArgsUsage string
  20. // Version of the program
  21. Version string
  22. // List of commands to execute
  23. Commands []Command
  24. // List of flags to parse
  25. Flags []Flag
  26. // Boolean to enable bash completion commands
  27. EnableBashCompletion bool
  28. // Boolean to hide built-in help command
  29. HideHelp bool
  30. // Boolean to hide built-in version flag
  31. HideVersion bool
  32. // An action to execute when the bash-completion flag is set
  33. BashComplete func(context *Context)
  34. // An action to execute before any subcommands are run, but after the context is ready
  35. // If a non-nil error is returned, no subcommands are run
  36. Before func(context *Context) error
  37. // An action to execute after any subcommands are run, but after the subcommand has finished
  38. // It is run even if Action() panics
  39. After func(context *Context) error
  40. // The action to execute when no subcommands are specified
  41. Action func(context *Context)
  42. // Execute this function if the proper command cannot be found
  43. CommandNotFound func(context *Context, command string)
  44. // Compilation date
  45. Compiled time.Time
  46. // List of all authors who contributed
  47. Authors []Author
  48. // Copyright of the binary if any
  49. Copyright string
  50. // Name of Author (Note: Use App.Authors, this is deprecated)
  51. Author string
  52. // Email of Author (Note: Use App.Authors, this is deprecated)
  53. Email string
  54. // Writer writer to write output to
  55. Writer io.Writer
  56. }
  57. // Tries to find out when this binary was compiled.
  58. // Returns the current time if it fails to find it.
  59. func compileTime() time.Time {
  60. info, err := os.Stat(os.Args[0])
  61. if err != nil {
  62. return time.Now()
  63. }
  64. return info.ModTime()
  65. }
  66. // Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
  67. func NewApp() *App {
  68. return &App{
  69. Name: os.Args[0],
  70. HelpName: os.Args[0],
  71. Usage: "A new cli application",
  72. Version: "0.0.0",
  73. BashComplete: DefaultAppComplete,
  74. Action: helpCommand.Action,
  75. Compiled: compileTime(),
  76. Writer: os.Stdout,
  77. }
  78. }
  79. // Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
  80. func (a *App) Run(arguments []string) (err error) {
  81. if a.Author != "" || a.Email != "" {
  82. a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
  83. }
  84. newCmds := []Command{}
  85. for _, c := range a.Commands {
  86. if c.HelpName == "" {
  87. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  88. }
  89. newCmds = append(newCmds, c)
  90. }
  91. a.Commands = newCmds
  92. // append help to commands
  93. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  94. a.Commands = append(a.Commands, helpCommand)
  95. if (HelpFlag != BoolFlag{}) {
  96. a.appendFlag(HelpFlag)
  97. }
  98. }
  99. //append version/help flags
  100. if a.EnableBashCompletion {
  101. a.appendFlag(BashCompletionFlag)
  102. }
  103. if !a.HideVersion {
  104. a.appendFlag(VersionFlag)
  105. }
  106. // parse flags
  107. set := flagSet(a.Name, a.Flags)
  108. set.SetOutput(ioutil.Discard)
  109. err = set.Parse(arguments[1:])
  110. nerr := normalizeFlags(a.Flags, set)
  111. if nerr != nil {
  112. fmt.Fprintln(a.Writer, nerr)
  113. context := NewContext(a, set, nil)
  114. ShowAppHelp(context)
  115. return nerr
  116. }
  117. context := NewContext(a, set, nil)
  118. if checkCompletions(context) {
  119. return nil
  120. }
  121. if err != nil {
  122. fmt.Fprintln(a.Writer, "Incorrect Usage.")
  123. fmt.Fprintln(a.Writer)
  124. ShowAppHelp(context)
  125. return err
  126. }
  127. if !a.HideHelp && checkHelp(context) {
  128. ShowAppHelp(context)
  129. return nil
  130. }
  131. if !a.HideVersion && checkVersion(context) {
  132. ShowVersion(context)
  133. return nil
  134. }
  135. if a.After != nil {
  136. defer func() {
  137. afterErr := a.After(context)
  138. if afterErr != nil {
  139. if err != nil {
  140. err = NewMultiError(err, afterErr)
  141. } else {
  142. err = afterErr
  143. }
  144. }
  145. }()
  146. }
  147. if a.Before != nil {
  148. err := a.Before(context)
  149. if err != nil {
  150. return err
  151. }
  152. }
  153. args := context.Args()
  154. if args.Present() {
  155. name := args.First()
  156. c := a.Command(name)
  157. if c != nil {
  158. return c.Run(context)
  159. }
  160. }
  161. // Run default Action
  162. a.Action(context)
  163. return nil
  164. }
  165. // Another entry point to the cli app, takes care of passing arguments and error handling
  166. func (a *App) RunAndExitOnError() {
  167. if err := a.Run(os.Args); err != nil {
  168. fmt.Fprintln(os.Stderr, err)
  169. os.Exit(1)
  170. }
  171. }
  172. // Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
  173. func (a *App) RunAsSubcommand(ctx *Context) (err error) {
  174. // append help to commands
  175. if len(a.Commands) > 0 {
  176. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  177. a.Commands = append(a.Commands, helpCommand)
  178. if (HelpFlag != BoolFlag{}) {
  179. a.appendFlag(HelpFlag)
  180. }
  181. }
  182. }
  183. newCmds := []Command{}
  184. for _, c := range a.Commands {
  185. if c.HelpName == "" {
  186. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  187. }
  188. newCmds = append(newCmds, c)
  189. }
  190. a.Commands = newCmds
  191. // append flags
  192. if a.EnableBashCompletion {
  193. a.appendFlag(BashCompletionFlag)
  194. }
  195. // parse flags
  196. set := flagSet(a.Name, a.Flags)
  197. set.SetOutput(ioutil.Discard)
  198. err = set.Parse(ctx.Args().Tail())
  199. nerr := normalizeFlags(a.Flags, set)
  200. context := NewContext(a, set, ctx)
  201. if nerr != nil {
  202. fmt.Fprintln(a.Writer, nerr)
  203. fmt.Fprintln(a.Writer)
  204. if len(a.Commands) > 0 {
  205. ShowSubcommandHelp(context)
  206. } else {
  207. ShowCommandHelp(ctx, context.Args().First())
  208. }
  209. return nerr
  210. }
  211. if checkCompletions(context) {
  212. return nil
  213. }
  214. if err != nil {
  215. fmt.Fprintln(a.Writer, "Incorrect Usage.")
  216. fmt.Fprintln(a.Writer)
  217. ShowSubcommandHelp(context)
  218. return err
  219. }
  220. if len(a.Commands) > 0 {
  221. if checkSubcommandHelp(context) {
  222. return nil
  223. }
  224. } else {
  225. if checkCommandHelp(ctx, context.Args().First()) {
  226. return nil
  227. }
  228. }
  229. if a.After != nil {
  230. defer func() {
  231. afterErr := a.After(context)
  232. if afterErr != nil {
  233. if err != nil {
  234. err = NewMultiError(err, afterErr)
  235. } else {
  236. err = afterErr
  237. }
  238. }
  239. }()
  240. }
  241. if a.Before != nil {
  242. err := a.Before(context)
  243. if err != nil {
  244. return err
  245. }
  246. }
  247. args := context.Args()
  248. if args.Present() {
  249. name := args.First()
  250. c := a.Command(name)
  251. if c != nil {
  252. return c.Run(context)
  253. }
  254. }
  255. // Run default Action
  256. a.Action(context)
  257. return nil
  258. }
  259. // Returns the named command on App. Returns nil if the command does not exist
  260. func (a *App) Command(name string) *Command {
  261. for _, c := range a.Commands {
  262. if c.HasName(name) {
  263. return &c
  264. }
  265. }
  266. return nil
  267. }
  268. func (a *App) hasFlag(flag Flag) bool {
  269. for _, f := range a.Flags {
  270. if flag == f {
  271. return true
  272. }
  273. }
  274. return false
  275. }
  276. func (a *App) appendFlag(flag Flag) {
  277. if !a.hasFlag(flag) {
  278. a.Flags = append(a.Flags, flag)
  279. }
  280. }
  281. // Author represents someone who has contributed to a cli project.
  282. type Author struct {
  283. Name string // The Authors name
  284. Email string // The Authors email
  285. }
  286. // String makes Author comply to the Stringer interface, to allow an easy print in the templating process
  287. func (a Author) String() string {
  288. e := ""
  289. if a.Email != "" {
  290. e = "<" + a.Email + "> "
  291. }
  292. return fmt.Sprintf("%v %v", a.Name, e)
  293. }