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.
 
 
 

505 lines
12 KiB

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