app.go 12 KB

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