app.go 12 KB

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