You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.go 12KB

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