app.go 7.2 KB

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