app.go 12 KB

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