app.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. a.categories = CommandCategories{}
  130. for _, command := range a.Commands {
  131. a.categories = a.categories.AddCommand(command.Category, command)
  132. }
  133. sort.Sort(a.categories)
  134. // append help to commands
  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. //append version/help flags
  142. if a.EnableBashCompletion {
  143. a.appendFlag(BashCompletionFlag)
  144. }
  145. if !a.HideVersion {
  146. a.appendFlag(VersionFlag)
  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. // parse flags
  154. set := flagSet(a.Name, a.Flags)
  155. set.SetOutput(ioutil.Discard)
  156. err = set.Parse(arguments[1:])
  157. nerr := normalizeFlags(a.Flags, set)
  158. context := NewContext(a, set, nil)
  159. if nerr != nil {
  160. fmt.Fprintln(a.Writer, nerr)
  161. ShowAppHelp(context)
  162. return nerr
  163. }
  164. if checkCompletions(context) {
  165. return nil
  166. }
  167. if err != nil {
  168. if a.OnUsageError != nil {
  169. err := a.OnUsageError(context, err, false)
  170. HandleExitCoder(err)
  171. return err
  172. }
  173. fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
  174. ShowAppHelp(context)
  175. return err
  176. }
  177. if !a.HideHelp && checkHelp(context) {
  178. ShowAppHelp(context)
  179. return nil
  180. }
  181. if !a.HideVersion && checkVersion(context) {
  182. ShowVersion(context)
  183. return nil
  184. }
  185. if a.After != nil {
  186. defer func() {
  187. if afterErr := a.After(context); afterErr != nil {
  188. if err != nil {
  189. err = NewMultiError(err, afterErr)
  190. } else {
  191. err = afterErr
  192. }
  193. }
  194. }()
  195. }
  196. if a.Before != nil {
  197. beforeErr := a.Before(context)
  198. if beforeErr != nil {
  199. fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
  200. ShowAppHelp(context)
  201. HandleExitCoder(beforeErr)
  202. err = beforeErr
  203. return err
  204. }
  205. }
  206. args := context.Args()
  207. if args.Present() {
  208. name := args.First()
  209. c := a.Command(name)
  210. if c != nil {
  211. return c.Run(context)
  212. }
  213. }
  214. // Run default Action
  215. err = HandleAction(a.Action, context)
  216. HandleExitCoder(err)
  217. return err
  218. }
  219. // DEPRECATED: Another entry point to the cli app, takes care of passing arguments and error handling
  220. func (a *App) RunAndExitOnError() {
  221. fmt.Fprintf(a.errWriter(),
  222. "DEPRECATED cli.App.RunAndExitOnError. %s See %s\n",
  223. contactSysadmin, runAndExitOnErrorDeprecationURL)
  224. if err := a.Run(os.Args); err != nil {
  225. fmt.Fprintln(a.errWriter(), err)
  226. OsExiter(1)
  227. }
  228. }
  229. // RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to
  230. // generate command-specific flags
  231. func (a *App) RunAsSubcommand(ctx *Context) (err error) {
  232. // append help to commands
  233. if len(a.Commands) > 0 {
  234. if a.Command(helpCommand.Name) == nil && !a.HideHelp {
  235. a.Commands = append(a.Commands, helpCommand)
  236. if (HelpFlag != BoolFlag{}) {
  237. a.appendFlag(HelpFlag)
  238. }
  239. }
  240. }
  241. newCmds := []Command{}
  242. for _, c := range a.Commands {
  243. if c.HelpName == "" {
  244. c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
  245. }
  246. newCmds = append(newCmds, c)
  247. }
  248. a.Commands = newCmds
  249. // append flags
  250. if a.EnableBashCompletion {
  251. a.appendFlag(BashCompletionFlag)
  252. }
  253. // parse flags
  254. set := flagSet(a.Name, a.Flags)
  255. set.SetOutput(ioutil.Discard)
  256. err = set.Parse(ctx.Args().Tail())
  257. nerr := normalizeFlags(a.Flags, set)
  258. context := NewContext(a, set, ctx)
  259. if nerr != nil {
  260. fmt.Fprintln(a.Writer, nerr)
  261. fmt.Fprintln(a.Writer)
  262. if len(a.Commands) > 0 {
  263. ShowSubcommandHelp(context)
  264. } else {
  265. ShowCommandHelp(ctx, context.Args().First())
  266. }
  267. return nerr
  268. }
  269. if checkCompletions(context) {
  270. return nil
  271. }
  272. if err != nil {
  273. if a.OnUsageError != nil {
  274. err = a.OnUsageError(context, err, true)
  275. HandleExitCoder(err)
  276. return err
  277. }
  278. fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
  279. ShowSubcommandHelp(context)
  280. return err
  281. }
  282. if len(a.Commands) > 0 {
  283. if checkSubcommandHelp(context) {
  284. return nil
  285. }
  286. } else {
  287. if checkCommandHelp(ctx, context.Args().First()) {
  288. return nil
  289. }
  290. }
  291. if a.After != nil {
  292. defer func() {
  293. afterErr := a.After(context)
  294. if afterErr != nil {
  295. HandleExitCoder(err)
  296. if err != nil {
  297. err = NewMultiError(err, afterErr)
  298. } else {
  299. err = afterErr
  300. }
  301. }
  302. }()
  303. }
  304. if a.Before != nil {
  305. beforeErr := a.Before(context)
  306. if beforeErr != nil {
  307. HandleExitCoder(beforeErr)
  308. err = beforeErr
  309. return err
  310. }
  311. }
  312. args := context.Args()
  313. if args.Present() {
  314. name := args.First()
  315. c := a.Command(name)
  316. if c != nil {
  317. return c.Run(context)
  318. }
  319. }
  320. // Run default Action
  321. err = HandleAction(a.Action, context)
  322. HandleExitCoder(err)
  323. return err
  324. }
  325. // Command returns the named command on App. Returns nil if the command does not exist
  326. func (a *App) Command(name string) *Command {
  327. for _, c := range a.Commands {
  328. if c.HasName(name) {
  329. return &c
  330. }
  331. }
  332. return nil
  333. }
  334. // Categories returns a slice containing all the categories with the commands they contain
  335. func (a *App) Categories() CommandCategories {
  336. return a.categories
  337. }
  338. // VisibleCategories returns a slice of categories and commands that are
  339. // Hidden=false
  340. func (a *App) VisibleCategories() []*CommandCategory {
  341. ret := []*CommandCategory{}
  342. for _, category := range a.categories {
  343. if visible := func() *CommandCategory {
  344. for _, command := range category.Commands {
  345. if !command.Hidden {
  346. return category
  347. }
  348. }
  349. return nil
  350. }(); visible != nil {
  351. ret = append(ret, visible)
  352. }
  353. }
  354. return ret
  355. }
  356. // VisibleCommands returns a slice of the Commands with Hidden=false
  357. func (a *App) VisibleCommands() []Command {
  358. ret := []Command{}
  359. for _, command := range a.Commands {
  360. if !command.Hidden {
  361. ret = append(ret, command)
  362. }
  363. }
  364. return ret
  365. }
  366. // VisibleFlags returns a slice of the Flags with Hidden=false
  367. func (a *App) VisibleFlags() []Flag {
  368. return visibleFlags(a.Flags)
  369. }
  370. func (a *App) hasFlag(flag Flag) bool {
  371. for _, f := range a.Flags {
  372. if flag == f {
  373. return true
  374. }
  375. }
  376. return false
  377. }
  378. func (a *App) errWriter() io.Writer {
  379. // When the app ErrWriter is nil use the package level one.
  380. if a.ErrWriter == nil {
  381. return ErrWriter
  382. }
  383. return a.ErrWriter
  384. }
  385. func (a *App) appendFlag(flag Flag) {
  386. if !a.hasFlag(flag) {
  387. a.Flags = append(a.Flags, flag)
  388. }
  389. }
  390. // Author represents someone who has contributed to a cli project.
  391. type Author struct {
  392. Name string // The Authors name
  393. Email string // The Authors email
  394. }
  395. // String makes Author comply to the Stringer interface, to allow an easy print in the templating process
  396. func (a Author) String() string {
  397. e := ""
  398. if a.Email != "" {
  399. e = "<" + a.Email + "> "
  400. }
  401. return fmt.Sprintf("%v %v", a.Name, e)
  402. }
  403. // HandleAction uses ✧✧✧reflection✧✧✧ to figure out if the given Action is an
  404. // ActionFunc, a func with the legacy signature for Action, or some other
  405. // invalid thing. If it's an ActionFunc or a func with the legacy signature for
  406. // Action, the func is run!
  407. func HandleAction(action interface{}, context *Context) (err error) {
  408. defer func() {
  409. if r := recover(); r != nil {
  410. // Try to detect a known reflection error from *this scope*, rather than
  411. // swallowing all panics that may happen when calling an Action func.
  412. s := fmt.Sprintf("%v", r)
  413. if strings.HasPrefix(s, "reflect: ") && strings.Contains(s, "too many input arguments") {
  414. err = NewExitError(fmt.Sprintf("ERROR unknown Action error: %v. See %s", r, appActionDeprecationURL), 2)
  415. } else {
  416. panic(r)
  417. }
  418. }
  419. }()
  420. if reflect.TypeOf(action).Kind() != reflect.Func {
  421. return errNonFuncAction
  422. }
  423. vals := reflect.ValueOf(action).Call([]reflect.Value{reflect.ValueOf(context)})
  424. if len(vals) == 0 {
  425. fmt.Fprintf(ErrWriter,
  426. "DEPRECATED Action signature. Must be `cli.ActionFunc`. %s See %s\n",
  427. contactSysadmin, appActionDeprecationURL)
  428. return nil
  429. }
  430. if len(vals) > 1 {
  431. return errInvalidActionSignature
  432. }
  433. if retErr, ok := vals[0].Interface().(error); vals[0].IsValid() && ok {
  434. return retErr
  435. }
  436. return err
  437. }