app.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. package cli
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "sort"
  10. "time"
  11. )
  12. var (
  13. changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md"
  14. appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
  15. runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL)
  16. contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you."
  17. errNonFuncAction = NewExitError("ERROR invalid Action type. "+
  18. fmt.Sprintf("Must be a func of type `cli.ActionFunc`. %s", contactSysadmin)+
  19. fmt.Sprintf("See %s", appActionDeprecationURL), 2)
  20. errInvalidActionSignature = NewExitError("ERROR invalid Action signature. "+
  21. fmt.Sprintf("Must be `cli.ActionFunc`. %s", contactSysadmin)+
  22. fmt.Sprintf("See %s", appActionDeprecationURL), 2)
  23. )
  24. // App is the main structure of a cli application. It is recommended that
  25. // an app be created with the cli.NewApp() function
  26. type App struct {
  27. // The name of the program. Defaults to path.Base(os.Args[0])
  28. Name string
  29. // Full name of command for help, defaults to Name
  30. HelpName string
  31. // Description of the program.
  32. Usage string
  33. // Text to override the USAGE section of help
  34. UsageText string
  35. // Description of the program argument format.
  36. ArgsUsage string
  37. // Version of the program
  38. Version 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. Action interface{}
  61. // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind
  62. // of deprecation period has passed, maybe?
  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. a.categories = CommandCategories{}
  129. for _, command := range a.Commands {
  130. a.categories = a.categories.AddCommand(command.Category, command)
  131. }
  132. sort.Sort(a.categories)
  133. // append help to commands
  134. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  135. a.Commands = append(a.Commands, helpCommand)
  136. if (HelpFlag != BoolFlag{}) {
  137. a.appendFlag(HelpFlag)
  138. }
  139. }
  140. //append version/help flags
  141. if a.EnableBashCompletion {
  142. a.appendFlag(BashCompletionFlag)
  143. }
  144. if !a.HideVersion {
  145. a.appendFlag(VersionFlag)
  146. }
  147. }
  148. // Run is the entry point to the cli app. Parses the arguments slice and routes
  149. // to the proper flag/args combination
  150. func (a *App) Run(arguments []string) (err error) {
  151. a.Setup()
  152. // parse flags
  153. set := flagSet(a.Name, a.Flags)
  154. set.SetOutput(ioutil.Discard)
  155. err = set.Parse(arguments[1:])
  156. nerr := normalizeFlags(a.Flags, set)
  157. context := NewContext(a, set, nil)
  158. if nerr != nil {
  159. fmt.Fprintln(a.Writer, nerr)
  160. ShowAppHelp(context)
  161. return nerr
  162. }
  163. if checkCompletions(context) {
  164. return nil
  165. }
  166. if err != nil {
  167. if a.OnUsageError != nil {
  168. err := a.OnUsageError(context, err, false)
  169. HandleExitCoder(err)
  170. return err
  171. }
  172. fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
  173. ShowAppHelp(context)
  174. return err
  175. }
  176. if !a.HideHelp && checkHelp(context) {
  177. ShowAppHelp(context)
  178. return nil
  179. }
  180. if !a.HideVersion && checkVersion(context) {
  181. ShowVersion(context)
  182. return nil
  183. }
  184. if a.After != nil {
  185. defer func() {
  186. if afterErr := a.After(context); afterErr != nil {
  187. if err != nil {
  188. err = NewMultiError(err, afterErr)
  189. } else {
  190. err = afterErr
  191. }
  192. }
  193. }()
  194. }
  195. if a.Before != nil {
  196. beforeErr := a.Before(context)
  197. if beforeErr != nil {
  198. fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
  199. ShowAppHelp(context)
  200. HandleExitCoder(beforeErr)
  201. err = beforeErr
  202. return err
  203. }
  204. }
  205. args := context.Args()
  206. if args.Present() {
  207. name := args.First()
  208. c := a.Command(name)
  209. if c != nil {
  210. return c.Run(context)
  211. }
  212. }
  213. // Run default Action
  214. err = HandleAction(a.Action, context)
  215. HandleExitCoder(err)
  216. return err
  217. }
  218. // DEPRECATED: Another entry point to the cli app, takes care of passing arguments and error handling
  219. func (a *App) RunAndExitOnError() {
  220. if err := a.Run(os.Args); err != nil {
  221. fmt.Fprintln(a.errWriter(), err)
  222. OsExiter(1)
  223. }
  224. }
  225. // RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to
  226. // generate command-specific flags
  227. func (a *App) RunAsSubcommand(ctx *Context) (err error) {
  228. // append help to commands
  229. if len(a.Commands) > 0 {
  230. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  231. a.Commands = append(a.Commands, helpCommand)
  232. if (HelpFlag != BoolFlag{}) {
  233. a.appendFlag(HelpFlag)
  234. }
  235. }
  236. }
  237. newCmds := []Command{}
  238. for _, c := range a.Commands {
  239. if c.HelpName == "" {
  240. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  241. }
  242. newCmds = append(newCmds, c)
  243. }
  244. a.Commands = newCmds
  245. // append flags
  246. if a.EnableBashCompletion {
  247. a.appendFlag(BashCompletionFlag)
  248. }
  249. // parse flags
  250. set := flagSet(a.Name, a.Flags)
  251. set.SetOutput(ioutil.Discard)
  252. err = set.Parse(ctx.Args().Tail())
  253. nerr := normalizeFlags(a.Flags, set)
  254. context := NewContext(a, set, ctx)
  255. if nerr != nil {
  256. fmt.Fprintln(a.Writer, nerr)
  257. fmt.Fprintln(a.Writer)
  258. if len(a.Commands) > 0 {
  259. ShowSubcommandHelp(context)
  260. } else {
  261. ShowCommandHelp(ctx, context.Args().First())
  262. }
  263. return nerr
  264. }
  265. if checkCompletions(context) {
  266. return nil
  267. }
  268. if err != nil {
  269. if a.OnUsageError != nil {
  270. err = a.OnUsageError(context, err, true)
  271. HandleExitCoder(err)
  272. return err
  273. }
  274. fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
  275. ShowSubcommandHelp(context)
  276. return err
  277. }
  278. if len(a.Commands) > 0 {
  279. if checkSubcommandHelp(context) {
  280. return nil
  281. }
  282. } else {
  283. if checkCommandHelp(ctx, context.Args().First()) {
  284. return nil
  285. }
  286. }
  287. if a.After != nil {
  288. defer func() {
  289. afterErr := a.After(context)
  290. if afterErr != nil {
  291. HandleExitCoder(err)
  292. if err != nil {
  293. err = NewMultiError(err, afterErr)
  294. } else {
  295. err = afterErr
  296. }
  297. }
  298. }()
  299. }
  300. if a.Before != nil {
  301. beforeErr := a.Before(context)
  302. if beforeErr != nil {
  303. HandleExitCoder(beforeErr)
  304. err = beforeErr
  305. return err
  306. }
  307. }
  308. args := context.Args()
  309. if args.Present() {
  310. name := args.First()
  311. c := a.Command(name)
  312. if c != nil {
  313. return c.Run(context)
  314. }
  315. }
  316. // Run default Action
  317. err = HandleAction(a.Action, context)
  318. HandleExitCoder(err)
  319. return err
  320. }
  321. // Command returns the named command on App. Returns nil if the command does not exist
  322. func (a *App) Command(name string) *Command {
  323. for _, c := range a.Commands {
  324. if c.HasName(name) {
  325. return &c
  326. }
  327. }
  328. return nil
  329. }
  330. // Categories returns a slice containing all the categories with the commands they contain
  331. func (a *App) Categories() CommandCategories {
  332. return a.categories
  333. }
  334. // VisibleCategories returns a slice of categories and commands that are
  335. // Hidden=false
  336. func (a *App) VisibleCategories() []*CommandCategory {
  337. ret := []*CommandCategory{}
  338. for _, category := range a.categories {
  339. if visible := func() *CommandCategory {
  340. for _, command := range category.Commands {
  341. if !command.Hidden {
  342. return category
  343. }
  344. }
  345. return nil
  346. }(); visible != nil {
  347. ret = append(ret, visible)
  348. }
  349. }
  350. return ret
  351. }
  352. // VisibleCommands returns a slice of the Commands with Hidden=false
  353. func (a *App) VisibleCommands() []Command {
  354. ret := []Command{}
  355. for _, command := range a.Commands {
  356. if !command.Hidden {
  357. ret = append(ret, command)
  358. }
  359. }
  360. return ret
  361. }
  362. // VisibleFlags returns a slice of the Flags with Hidden=false
  363. func (a *App) VisibleFlags() []Flag {
  364. return visibleFlags(a.Flags)
  365. }
  366. func (a *App) hasFlag(flag Flag) bool {
  367. for _, f := range a.Flags {
  368. if flag == f {
  369. return true
  370. }
  371. }
  372. return false
  373. }
  374. func (a *App) errWriter() io.Writer {
  375. // When the app ErrWriter is nil use the package level one.
  376. if a.ErrWriter == nil {
  377. return ErrWriter
  378. }
  379. return a.ErrWriter
  380. }
  381. func (a *App) appendFlag(flag Flag) {
  382. if !a.hasFlag(flag) {
  383. a.Flags = append(a.Flags, flag)
  384. }
  385. }
  386. // Author represents someone who has contributed to a cli project.
  387. type Author struct {
  388. Name string // The Authors name
  389. Email string // The Authors email
  390. }
  391. // String makes Author comply to the Stringer interface, to allow an easy print in the templating process
  392. func (a Author) String() string {
  393. e := ""
  394. if a.Email != "" {
  395. e = "<" + a.Email + "> "
  396. }
  397. return fmt.Sprintf("%v %v", a.Name, e)
  398. }
  399. // HandleAction uses ✧✧✧reflection✧✧✧ to figure out if the given Action is an
  400. // ActionFunc, a func with the legacy signature for Action, or some other
  401. // invalid thing. If it's an ActionFunc or a func with the legacy signature for
  402. // Action, the func is run!
  403. func HandleAction(action interface{}, context *Context) (err error) {
  404. defer func() {
  405. if r := recover(); r != nil {
  406. switch r.(type) {
  407. case error:
  408. err = r.(error)
  409. default:
  410. err = NewExitError(fmt.Sprintf("ERROR unknown Action error: %v. See %s", r, appActionDeprecationURL), 2)
  411. }
  412. }
  413. }()
  414. if reflect.TypeOf(action).Kind() != reflect.Func {
  415. return errNonFuncAction
  416. }
  417. vals := reflect.ValueOf(action).Call([]reflect.Value{reflect.ValueOf(context)})
  418. if len(vals) == 0 {
  419. return nil
  420. }
  421. if len(vals) > 1 {
  422. return errInvalidActionSignature
  423. }
  424. if retErr, ok := vals[0].Interface().(error); vals[0].IsValid() && ok {
  425. return retErr
  426. }
  427. return err
  428. }