app.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package cli
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "sort"
  9. "time"
  10. )
  11. var (
  12. changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md"
  13. appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
  14. runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL)
  15. contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you."
  16. errInvalidActionType = NewExitError("ERROR invalid Action type. "+
  17. fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+
  18. fmt.Sprintf("See %s", appActionDeprecationURL), 2)
  19. )
  20. // App is the main structure of a cli application. It is recommended that
  21. // an app be created with the cli.NewApp() function
  22. type App struct {
  23. // The name of the program. Defaults to path.Base(os.Args[0])
  24. Name string
  25. // Full name of command for help, defaults to Name
  26. HelpName string
  27. // Description of the program.
  28. Usage string
  29. // Text to override the USAGE section of help
  30. UsageText string
  31. // Description of the program argument format.
  32. ArgsUsage string
  33. // Version of the program
  34. Version string
  35. // Description of the program
  36. Description string
  37. // List of commands to execute
  38. Commands []Command
  39. // List of flags to parse
  40. Flags []Flag
  41. // Boolean to enable bash completion commands
  42. EnableBashCompletion bool
  43. // Boolean to hide built-in help command
  44. HideHelp bool
  45. // Boolean to hide built-in version flag and the VERSION section of help
  46. HideVersion bool
  47. // Populate on app startup, only gettable through method Categories()
  48. categories CommandCategories
  49. // An action to execute when the bash-completion flag is set
  50. BashComplete BashCompleteFunc
  51. // An action to execute before any subcommands are run, but after the context is ready
  52. // If a non-nil error is returned, no subcommands are run
  53. Before BeforeFunc
  54. // An action to execute after any subcommands are run, but after the subcommand has finished
  55. // It is run even if Action() panics
  56. After AfterFunc
  57. // The action to execute when no subcommands are specified
  58. // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
  59. // *Note*: support for the deprecated `Action` signature will be removed in a future version
  60. Action interface{}
  61. // Execute this function if the proper command cannot be found
  62. CommandNotFound CommandNotFoundFunc
  63. // Execute this function if an usage error occurs
  64. OnUsageError OnUsageErrorFunc
  65. // Compilation date
  66. Compiled time.Time
  67. // List of all authors who contributed
  68. Authors []Author
  69. // Copyright of the binary if any
  70. Copyright string
  71. // Name of Author (Note: Use App.Authors, this is deprecated)
  72. Author string
  73. // Email of Author (Note: Use App.Authors, this is deprecated)
  74. Email string
  75. // Writer writer to write output to
  76. Writer io.Writer
  77. // ErrWriter writes error output
  78. ErrWriter io.Writer
  79. // Other custom info
  80. Metadata map[string]interface{}
  81. didSetup bool
  82. }
  83. // Tries to find out when this binary was compiled.
  84. // Returns the current time if it fails to find it.
  85. func compileTime() time.Time {
  86. info, err := os.Stat(os.Args[0])
  87. if err != nil {
  88. return time.Now()
  89. }
  90. return info.ModTime()
  91. }
  92. // NewApp creates a new cli Application with some reasonable defaults for Name,
  93. // Usage, Version and Action.
  94. func NewApp() *App {
  95. return &App{
  96. Name: filepath.Base(os.Args[0]),
  97. HelpName: filepath.Base(os.Args[0]),
  98. Usage: "A new cli application",
  99. UsageText: "",
  100. Version: "0.0.0",
  101. BashComplete: DefaultAppComplete,
  102. Action: helpCommand.Action,
  103. Compiled: compileTime(),
  104. Writer: os.Stdout,
  105. }
  106. }
  107. // Setup runs initialization code to ensure all data structures are ready for
  108. // `Run` or inspection prior to `Run`. It is internally called by `Run`, but
  109. // will return early if setup has already happened.
  110. func (a *App) Setup() {
  111. if a.didSetup {
  112. return
  113. }
  114. a.didSetup = true
  115. if a.Author != "" || a.Email != "" {
  116. a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
  117. }
  118. newCmds := []Command{}
  119. for _, c := range a.Commands {
  120. if c.HelpName == "" {
  121. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  122. }
  123. newCmds = append(newCmds, c)
  124. }
  125. a.Commands = newCmds
  126. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  127. a.Commands = append(a.Commands, helpCommand)
  128. if (HelpFlag != BoolFlag{}) {
  129. a.appendFlag(HelpFlag)
  130. }
  131. }
  132. if !a.HideVersion {
  133. a.appendFlag(VersionFlag)
  134. }
  135. a.categories = CommandCategories{}
  136. for _, command := range a.Commands {
  137. a.categories = a.categories.AddCommand(command.Category, command)
  138. }
  139. sort.Sort(a.categories)
  140. if a.Metadata == nil {
  141. a.Metadata = make(map[string]interface{})
  142. }
  143. if a.Writer == nil {
  144. a.Writer = os.Stdout
  145. }
  146. }
  147. // Run is the entry point to the cli app. Parses the arguments slice and routes
  148. // to the proper flag/args combination
  149. func (a *App) Run(arguments []string) (err error) {
  150. a.Setup()
  151. // handle the completion flag separately from the flagset since
  152. // completion could be attempted after a flag, but before its value was put
  153. // on the command line. this causes the flagset to interpret the completion
  154. // flag name as the value of the flag before it which is undesirable
  155. // note that we can only do this because the shell autocomplete function
  156. // always appends the completion flag at the end of the command
  157. shellComplete, arguments := checkShellCompleteFlag(a, arguments)
  158. // parse flags
  159. set, err := flagSet(a.Name, a.Flags)
  160. if err != nil {
  161. return err
  162. }
  163. set.SetOutput(ioutil.Discard)
  164. err = set.Parse(arguments[1:])
  165. nerr := normalizeFlags(a.Flags, set)
  166. context := NewContext(a, set, nil)
  167. if nerr != nil {
  168. fmt.Fprintln(a.Writer, nerr)
  169. ShowAppHelp(context)
  170. return nerr
  171. }
  172. context.shellComplete = shellComplete
  173. if checkCompletions(context) {
  174. return nil
  175. }
  176. if err != nil {
  177. if a.OnUsageError != nil {
  178. err := a.OnUsageError(context, err, false)
  179. HandleExitCoder(err)
  180. return err
  181. }
  182. fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
  183. ShowAppHelp(context)
  184. return err
  185. }
  186. if !a.HideHelp && checkHelp(context) {
  187. ShowAppHelp(context)
  188. return nil
  189. }
  190. if !a.HideVersion && checkVersion(context) {
  191. ShowVersion(context)
  192. return nil
  193. }
  194. if a.After != nil {
  195. defer func() {
  196. if afterErr := a.After(context); afterErr != nil {
  197. if err != nil {
  198. err = NewMultiError(err, afterErr)
  199. } else {
  200. err = afterErr
  201. }
  202. }
  203. }()
  204. }
  205. if a.Before != nil {
  206. beforeErr := a.Before(context)
  207. if beforeErr != nil {
  208. fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
  209. ShowAppHelp(context)
  210. HandleExitCoder(beforeErr)
  211. err = beforeErr
  212. return err
  213. }
  214. }
  215. args := context.Args()
  216. if args.Present() {
  217. name := args.First()
  218. c := a.Command(name)
  219. if c != nil {
  220. return c.Run(context)
  221. }
  222. }
  223. if a.Action == nil {
  224. a.Action = helpCommand.Action
  225. }
  226. // Run default Action
  227. err = HandleAction(a.Action, context)
  228. HandleExitCoder(err)
  229. return err
  230. }
  231. // RunAndExitOnError calls .Run() and exits non-zero if an error was returned
  232. //
  233. // Deprecated: instead you should return an error that fulfills cli.ExitCoder
  234. // to cli.App.Run. This will cause the application to exit with the given eror
  235. // code in the cli.ExitCoder
  236. func (a *App) RunAndExitOnError() {
  237. if err := a.Run(os.Args); err != nil {
  238. fmt.Fprintln(a.errWriter(), err)
  239. OsExiter(1)
  240. }
  241. }
  242. // RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to
  243. // generate command-specific flags
  244. func (a *App) RunAsSubcommand(ctx *Context) (err error) {
  245. // append help to commands
  246. if len(a.Commands) > 0 {
  247. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  248. a.Commands = append(a.Commands, helpCommand)
  249. if (HelpFlag != BoolFlag{}) {
  250. a.appendFlag(HelpFlag)
  251. }
  252. }
  253. }
  254. newCmds := []Command{}
  255. for _, c := range a.Commands {
  256. if c.HelpName == "" {
  257. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  258. }
  259. newCmds = append(newCmds, c)
  260. }
  261. a.Commands = newCmds
  262. // parse flags
  263. set, err := flagSet(a.Name, a.Flags)
  264. if err != nil {
  265. return err
  266. }
  267. set.SetOutput(ioutil.Discard)
  268. err = set.Parse(ctx.Args().Tail())
  269. nerr := normalizeFlags(a.Flags, set)
  270. context := NewContext(a, set, ctx)
  271. if nerr != nil {
  272. fmt.Fprintln(a.Writer, nerr)
  273. fmt.Fprintln(a.Writer)
  274. if len(a.Commands) > 0 {
  275. ShowSubcommandHelp(context)
  276. } else {
  277. ShowCommandHelp(ctx, context.Args().First())
  278. }
  279. return nerr
  280. }
  281. if checkCompletions(context) {
  282. return nil
  283. }
  284. if err != nil {
  285. if a.OnUsageError != nil {
  286. err = a.OnUsageError(context, err, true)
  287. HandleExitCoder(err)
  288. return err
  289. }
  290. fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
  291. ShowSubcommandHelp(context)
  292. return err
  293. }
  294. if len(a.Commands) > 0 {
  295. if checkSubcommandHelp(context) {
  296. return nil
  297. }
  298. } else {
  299. if checkCommandHelp(ctx, context.Args().First()) {
  300. return nil
  301. }
  302. }
  303. if a.After != nil {
  304. defer func() {
  305. afterErr := a.After(context)
  306. if afterErr != nil {
  307. HandleExitCoder(err)
  308. if err != nil {
  309. err = NewMultiError(err, afterErr)
  310. } else {
  311. err = afterErr
  312. }
  313. }
  314. }()
  315. }
  316. if a.Before != nil {
  317. beforeErr := a.Before(context)
  318. if beforeErr != nil {
  319. HandleExitCoder(beforeErr)
  320. err = beforeErr
  321. return err
  322. }
  323. }
  324. args := context.Args()
  325. if args.Present() {
  326. name := args.First()
  327. c := a.Command(name)
  328. if c != nil {
  329. return c.Run(context)
  330. }
  331. }
  332. // Run default Action
  333. err = HandleAction(a.Action, context)
  334. HandleExitCoder(err)
  335. return err
  336. }
  337. // Command returns the named command on App. Returns nil if the command does not exist
  338. func (a *App) Command(name string) *Command {
  339. for _, c := range a.Commands {
  340. if c.HasName(name) {
  341. return &c
  342. }
  343. }
  344. return nil
  345. }
  346. // Categories returns a slice containing all the categories with the commands they contain
  347. func (a *App) Categories() CommandCategories {
  348. return a.categories
  349. }
  350. // VisibleCategories returns a slice of categories and commands that are
  351. // Hidden=false
  352. func (a *App) VisibleCategories() []*CommandCategory {
  353. ret := []*CommandCategory{}
  354. for _, category := range a.categories {
  355. if visible := func() *CommandCategory {
  356. for _, command := range category.Commands {
  357. if !command.Hidden {
  358. return category
  359. }
  360. }
  361. return nil
  362. }(); visible != nil {
  363. ret = append(ret, visible)
  364. }
  365. }
  366. return ret
  367. }
  368. // VisibleCommands returns a slice of the Commands with Hidden=false
  369. func (a *App) VisibleCommands() []Command {
  370. ret := []Command{}
  371. for _, command := range a.Commands {
  372. if !command.Hidden {
  373. ret = append(ret, command)
  374. }
  375. }
  376. return ret
  377. }
  378. // VisibleFlags returns a slice of the Flags with Hidden=false
  379. func (a *App) VisibleFlags() []Flag {
  380. return visibleFlags(a.Flags)
  381. }
  382. func (a *App) hasFlag(flag Flag) bool {
  383. for _, f := range a.Flags {
  384. if flag == f {
  385. return true
  386. }
  387. }
  388. return false
  389. }
  390. func (a *App) errWriter() io.Writer {
  391. // When the app ErrWriter is nil use the package level one.
  392. if a.ErrWriter == nil {
  393. return ErrWriter
  394. }
  395. return a.ErrWriter
  396. }
  397. func (a *App) appendFlag(flag Flag) {
  398. if !a.hasFlag(flag) {
  399. a.Flags = append(a.Flags, flag)
  400. }
  401. }
  402. // Author represents someone who has contributed to a cli project.
  403. type Author struct {
  404. Name string // The Authors name
  405. Email string // The Authors email
  406. }
  407. // String makes Author comply to the Stringer interface, to allow an easy print in the templating process
  408. func (a Author) String() string {
  409. e := ""
  410. if a.Email != "" {
  411. e = " <" + a.Email + ">"
  412. }
  413. return fmt.Sprintf("%v%v", a.Name, e)
  414. }
  415. // HandleAction attempts to figure out which Action signature was used. If
  416. // it's an ActionFunc or a func with the legacy signature for Action, the func
  417. // is run!
  418. func HandleAction(action interface{}, context *Context) (err error) {
  419. if a, ok := action.(func(*Context) error); ok {
  420. return a(context)
  421. } else if a, ok := action.(func(*Context)); ok { // deprecated function signature
  422. a(context)
  423. return nil
  424. } else {
  425. return errInvalidActionType
  426. }
  427. }