app.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. // Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to
  80. // function as a default, so this is optional.
  81. ExitErrHandler ExitErrHandlerFunc
  82. // Other custom info
  83. Metadata map[string]interface{}
  84. // Carries a function which returns app specific info.
  85. ExtraInfo func() map[string]string
  86. // CustomAppHelpTemplate the text template for app help topic.
  87. // cli.go uses text/template to render templates. You can
  88. // render custom help text by setting this variable.
  89. CustomAppHelpTemplate string
  90. didSetup bool
  91. }
  92. // Tries to find out when this binary was compiled.
  93. // Returns the current time if it fails to find it.
  94. func compileTime() time.Time {
  95. info, err := os.Stat(os.Args[0])
  96. if err != nil {
  97. return time.Now()
  98. }
  99. return info.ModTime()
  100. }
  101. // NewApp creates a new cli Application with some reasonable defaults for Name,
  102. // Usage, Version and Action.
  103. func NewApp() *App {
  104. return &App{
  105. Name: filepath.Base(os.Args[0]),
  106. HelpName: filepath.Base(os.Args[0]),
  107. Usage: "A new cli application",
  108. UsageText: "",
  109. Version: "0.0.0",
  110. BashComplete: DefaultAppComplete,
  111. Action: helpCommand.Action,
  112. Compiled: compileTime(),
  113. Writer: os.Stdout,
  114. }
  115. }
  116. // Setup runs initialization code to ensure all data structures are ready for
  117. // `Run` or inspection prior to `Run`. It is internally called by `Run`, but
  118. // will return early if setup has already happened.
  119. func (a *App) Setup() {
  120. if a.didSetup {
  121. return
  122. }
  123. a.didSetup = true
  124. if a.Author != "" || a.Email != "" {
  125. a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
  126. }
  127. newCmds := []Command{}
  128. for _, c := range a.Commands {
  129. if c.HelpName == "" {
  130. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  131. }
  132. newCmds = append(newCmds, c)
  133. }
  134. a.Commands = newCmds
  135. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  136. a.Commands = append(a.Commands, helpCommand)
  137. if (HelpFlag != BoolFlag{}) {
  138. a.appendFlag(HelpFlag)
  139. }
  140. }
  141. if !a.HideVersion {
  142. a.appendFlag(VersionFlag)
  143. }
  144. a.categories = CommandCategories{}
  145. for _, command := range a.Commands {
  146. a.categories = a.categories.AddCommand(command.Category, command)
  147. }
  148. sort.Sort(a.categories)
  149. if a.Metadata == nil {
  150. a.Metadata = make(map[string]interface{})
  151. }
  152. if a.Writer == nil {
  153. a.Writer = os.Stdout
  154. }
  155. }
  156. // Run is the entry point to the cli app. Parses the arguments slice and routes
  157. // to the proper flag/args combination
  158. func (a *App) Run(arguments []string) (err error) {
  159. a.Setup()
  160. // handle the completion flag separately from the flagset since
  161. // completion could be attempted after a flag, but before its value was put
  162. // on the command line. this causes the flagset to interpret the completion
  163. // flag name as the value of the flag before it which is undesirable
  164. // note that we can only do this because the shell autocomplete function
  165. // always appends the completion flag at the end of the command
  166. shellComplete, arguments := checkShellCompleteFlag(a, arguments)
  167. // parse flags
  168. set, err := flagSet(a.Name, a.Flags)
  169. if err != nil {
  170. return err
  171. }
  172. set.SetOutput(ioutil.Discard)
  173. err = set.Parse(arguments[1:])
  174. nerr := normalizeFlags(a.Flags, set)
  175. context := NewContext(a, set, nil)
  176. if nerr != nil {
  177. fmt.Fprintln(a.Writer, nerr)
  178. ShowAppHelp(context)
  179. return nerr
  180. }
  181. context.shellComplete = shellComplete
  182. if checkCompletions(context) {
  183. return nil
  184. }
  185. if err != nil {
  186. if a.OnUsageError != nil {
  187. err := a.OnUsageError(context, err, false)
  188. a.handleExitCoder(context, err)
  189. return err
  190. }
  191. fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
  192. ShowAppHelp(context)
  193. return err
  194. }
  195. if !a.HideHelp && checkHelp(context) {
  196. ShowAppHelp(context)
  197. return nil
  198. }
  199. if !a.HideVersion && checkVersion(context) {
  200. ShowVersion(context)
  201. return nil
  202. }
  203. if a.After != nil {
  204. defer func() {
  205. if afterErr := a.After(context); afterErr != nil {
  206. if err != nil {
  207. err = NewMultiError(err, afterErr)
  208. } else {
  209. err = afterErr
  210. }
  211. }
  212. }()
  213. }
  214. if a.Before != nil {
  215. beforeErr := a.Before(context)
  216. if beforeErr != nil {
  217. fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
  218. ShowAppHelp(context)
  219. a.handleExitCoder(context, beforeErr)
  220. err = beforeErr
  221. return err
  222. }
  223. }
  224. args := context.Args()
  225. if args.Present() {
  226. name := args.First()
  227. c := a.Command(name)
  228. if c != nil {
  229. return c.Run(context)
  230. }
  231. }
  232. if a.Action == nil {
  233. a.Action = helpCommand.Action
  234. }
  235. // Run default Action
  236. err = HandleAction(a.Action, context)
  237. a.handleExitCoder(context, err)
  238. return err
  239. }
  240. // RunAndExitOnError calls .Run() and exits non-zero if an error was returned
  241. //
  242. // Deprecated: instead you should return an error that fulfills cli.ExitCoder
  243. // to cli.App.Run. This will cause the application to exit with the given eror
  244. // code in the cli.ExitCoder
  245. func (a *App) RunAndExitOnError() {
  246. if err := a.Run(os.Args); err != nil {
  247. fmt.Fprintln(a.errWriter(), err)
  248. OsExiter(1)
  249. }
  250. }
  251. // RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to
  252. // generate command-specific flags
  253. func (a *App) RunAsSubcommand(ctx *Context) (err error) {
  254. // append help to commands
  255. if len(a.Commands) > 0 {
  256. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  257. a.Commands = append(a.Commands, helpCommand)
  258. if (HelpFlag != BoolFlag{}) {
  259. a.appendFlag(HelpFlag)
  260. }
  261. }
  262. }
  263. newCmds := []Command{}
  264. for _, c := range a.Commands {
  265. if c.HelpName == "" {
  266. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  267. }
  268. newCmds = append(newCmds, c)
  269. }
  270. a.Commands = newCmds
  271. // parse flags
  272. set, err := flagSet(a.Name, a.Flags)
  273. if err != nil {
  274. return err
  275. }
  276. set.SetOutput(ioutil.Discard)
  277. err = set.Parse(ctx.Args().Tail())
  278. nerr := normalizeFlags(a.Flags, set)
  279. context := NewContext(a, set, ctx)
  280. if nerr != nil {
  281. fmt.Fprintln(a.Writer, nerr)
  282. fmt.Fprintln(a.Writer)
  283. if len(a.Commands) > 0 {
  284. ShowSubcommandHelp(context)
  285. } else {
  286. ShowCommandHelp(ctx, context.Args().First())
  287. }
  288. return nerr
  289. }
  290. if checkCompletions(context) {
  291. return nil
  292. }
  293. if err != nil {
  294. if a.OnUsageError != nil {
  295. err = a.OnUsageError(context, err, true)
  296. a.handleExitCoder(context, err)
  297. return err
  298. }
  299. fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
  300. ShowSubcommandHelp(context)
  301. return err
  302. }
  303. if len(a.Commands) > 0 {
  304. if checkSubcommandHelp(context) {
  305. return nil
  306. }
  307. } else {
  308. if checkCommandHelp(ctx, context.Args().First()) {
  309. return nil
  310. }
  311. }
  312. if a.After != nil {
  313. defer func() {
  314. afterErr := a.After(context)
  315. if afterErr != nil {
  316. a.handleExitCoder(context, err)
  317. if err != nil {
  318. err = NewMultiError(err, afterErr)
  319. } else {
  320. err = afterErr
  321. }
  322. }
  323. }()
  324. }
  325. if a.Before != nil {
  326. beforeErr := a.Before(context)
  327. if beforeErr != nil {
  328. a.handleExitCoder(context, beforeErr)
  329. err = beforeErr
  330. return err
  331. }
  332. }
  333. args := context.Args()
  334. if args.Present() {
  335. name := args.First()
  336. c := a.Command(name)
  337. if c != nil {
  338. return c.Run(context)
  339. }
  340. }
  341. // Run default Action
  342. err = HandleAction(a.Action, context)
  343. a.handleExitCoder(context, err)
  344. return err
  345. }
  346. // Command returns the named command on App. Returns nil if the command does not exist
  347. func (a *App) Command(name string) *Command {
  348. for _, c := range a.Commands {
  349. if c.HasName(name) {
  350. return &c
  351. }
  352. }
  353. return nil
  354. }
  355. // Categories returns a slice containing all the categories with the commands they contain
  356. func (a *App) Categories() CommandCategories {
  357. return a.categories
  358. }
  359. // VisibleCategories returns a slice of categories and commands that are
  360. // Hidden=false
  361. func (a *App) VisibleCategories() []*CommandCategory {
  362. ret := []*CommandCategory{}
  363. for _, category := range a.categories {
  364. if visible := func() *CommandCategory {
  365. for _, command := range category.Commands {
  366. if !command.Hidden {
  367. return category
  368. }
  369. }
  370. return nil
  371. }(); visible != nil {
  372. ret = append(ret, visible)
  373. }
  374. }
  375. return ret
  376. }
  377. // VisibleCommands returns a slice of the Commands with Hidden=false
  378. func (a *App) VisibleCommands() []Command {
  379. ret := []Command{}
  380. for _, command := range a.Commands {
  381. if !command.Hidden {
  382. ret = append(ret, command)
  383. }
  384. }
  385. return ret
  386. }
  387. // VisibleFlags returns a slice of the Flags with Hidden=false
  388. func (a *App) VisibleFlags() []Flag {
  389. return visibleFlags(a.Flags)
  390. }
  391. func (a *App) hasFlag(flag Flag) bool {
  392. for _, f := range a.Flags {
  393. if flag == f {
  394. return true
  395. }
  396. }
  397. return false
  398. }
  399. func (a *App) errWriter() io.Writer {
  400. // When the app ErrWriter is nil use the package level one.
  401. if a.ErrWriter == nil {
  402. return ErrWriter
  403. }
  404. return a.ErrWriter
  405. }
  406. func (a *App) appendFlag(flag Flag) {
  407. if !a.hasFlag(flag) {
  408. a.Flags = append(a.Flags, flag)
  409. }
  410. }
  411. func (a *App) handleExitCoder(context *Context, err error) {
  412. if a.ExitErrHandler != nil {
  413. a.ExitErrHandler(context, err)
  414. } else {
  415. HandleExitCoder(err)
  416. }
  417. }
  418. // Author represents someone who has contributed to a cli project.
  419. type Author struct {
  420. Name string // The Authors name
  421. Email string // The Authors email
  422. }
  423. // String makes Author comply to the Stringer interface, to allow an easy print in the templating process
  424. func (a Author) String() string {
  425. e := ""
  426. if a.Email != "" {
  427. e = " <" + a.Email + ">"
  428. }
  429. return fmt.Sprintf("%v%v", a.Name, e)
  430. }
  431. // HandleAction attempts to figure out which Action signature was used. If
  432. // it's an ActionFunc or a func with the legacy signature for Action, the func
  433. // is run!
  434. func HandleAction(action interface{}, context *Context) (err error) {
  435. if a, ok := action.(ActionFunc); ok {
  436. return a(context)
  437. } else if a, ok := action.(func(*Context) error); ok {
  438. return a(context)
  439. } else if a, ok := action.(func(*Context)); ok { // deprecated function signature
  440. a(context)
  441. return nil
  442. }
  443. return errInvalidActionType
  444. }