context.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. package cli
  2. import (
  3. "errors"
  4. "flag"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. // Context is a type that is passed through to
  10. // each Handler action in a cli application. Context
  11. // can be used to retrieve context-specific Args and
  12. // parsed command-line options.
  13. type Context struct {
  14. App *App
  15. Command Command
  16. flagSet *flag.FlagSet
  17. setFlags map[string]bool
  18. globalSetFlags map[string]bool
  19. parentContext *Context
  20. }
  21. // NewContext creates a new context. For use in when invoking an App or Command action.
  22. func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
  23. return &Context{App: app, flagSet: set, parentContext: parentCtx}
  24. }
  25. // Int looks up the value of a local int flag, returns 0 if no int flag exists
  26. func (c *Context) Int(name string) int {
  27. return lookupInt(name, c.flagSet)
  28. }
  29. // Int64 looks up the value of a local int flag, returns 0 if no int flag exists
  30. func (c *Context) Int64(name string) int64 {
  31. return lookupInt64(name, c.flagSet)
  32. }
  33. // Uint looks up the value of a local int flag, returns 0 if no int flag exists
  34. func (c *Context) Uint(name string) uint {
  35. return lookupUint(name, c.flagSet)
  36. }
  37. // Uint64 looks up the value of a local int flag, returns 0 if no int flag exists
  38. func (c *Context) Uint64(name string) uint64 {
  39. return lookupUint64(name, c.flagSet)
  40. }
  41. // Duration looks up the value of a local time.Duration flag, returns 0 if no
  42. // time.Duration flag exists
  43. func (c *Context) Duration(name string) time.Duration {
  44. return lookupDuration(name, c.flagSet)
  45. }
  46. // Float64 looks up the value of a local float64 flag, returns 0 if no float64
  47. // flag exists
  48. func (c *Context) Float64(name string) float64 {
  49. return lookupFloat64(name, c.flagSet)
  50. }
  51. // Bool looks up the value of a local bool flag, returns false if no bool flag exists
  52. func (c *Context) Bool(name string) bool {
  53. return lookupBool(name, c.flagSet)
  54. }
  55. // BoolT looks up the value of a local boolT flag, returns false if no bool flag exists
  56. func (c *Context) BoolT(name string) bool {
  57. return lookupBoolT(name, c.flagSet)
  58. }
  59. // String looks up the value of a local string flag, returns "" if no string flag exists
  60. func (c *Context) String(name string) string {
  61. return lookupString(name, c.flagSet)
  62. }
  63. // StringSlice looks up the value of a local string slice flag, returns nil if no
  64. // string slice flag exists
  65. func (c *Context) StringSlice(name string) []string {
  66. return lookupStringSlice(name, c.flagSet)
  67. }
  68. // IntSlice looks up the value of a local int slice flag, returns nil if no int
  69. // slice flag exists
  70. func (c *Context) IntSlice(name string) []int {
  71. return lookupIntSlice(name, c.flagSet)
  72. }
  73. // Int64Slice looks up the value of a local int slice flag, returns nil if no int
  74. // slice flag exists
  75. func (c *Context) Int64Slice(name string) []int64 {
  76. return lookupInt64Slice(name, c.flagSet)
  77. }
  78. // Generic looks up the value of a local generic flag, returns nil if no generic
  79. // flag exists
  80. func (c *Context) Generic(name string) interface{} {
  81. return lookupGeneric(name, c.flagSet)
  82. }
  83. // GlobalInt looks up the value of a global int flag, returns 0 if no int flag exists
  84. func (c *Context) GlobalInt(name string) int {
  85. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  86. return lookupInt(name, fs)
  87. }
  88. return 0
  89. }
  90. // GlobalInt64 looks up the value of a global int flag, returns 0 if no int flag exists
  91. func (c *Context) GlobalInt64(name string) int64 {
  92. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  93. return lookupInt64(name, fs)
  94. }
  95. return 0
  96. }
  97. // GlobalUint looks up the value of a global int flag, returns 0 if no int flag exists
  98. func (c *Context) GlobalUint(name string) uint {
  99. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  100. return lookupUint(name, fs)
  101. }
  102. return 0
  103. }
  104. // GlobalUint64 looks up the value of a global int flag, returns 0 if no int flag exists
  105. func (c *Context) GlobalUint64(name string) uint64 {
  106. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  107. return lookupUint64(name, fs)
  108. }
  109. return 0
  110. }
  111. // GlobalFloat64 looks up the value of a global float64 flag, returns float64(0)
  112. // if no float64 flag exists
  113. func (c *Context) GlobalFloat64(name string) float64 {
  114. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  115. return lookupFloat64(name, fs)
  116. }
  117. return float64(0)
  118. }
  119. // GlobalDuration looks up the value of a global time.Duration flag, returns 0
  120. // if no time.Duration flag exists
  121. func (c *Context) GlobalDuration(name string) time.Duration {
  122. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  123. return lookupDuration(name, fs)
  124. }
  125. return 0
  126. }
  127. // GlobalBool looks up the value of a global bool flag, returns false if no bool
  128. // flag exists
  129. func (c *Context) GlobalBool(name string) bool {
  130. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  131. return lookupBool(name, fs)
  132. }
  133. return false
  134. }
  135. // GlobalBoolT looks up the value of a global bool flag, returns true if no bool
  136. // flag exists
  137. func (c *Context) GlobalBoolT(name string) bool {
  138. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  139. return lookupBoolT(name, fs)
  140. }
  141. return false
  142. }
  143. // GlobalString looks up the value of a global string flag, returns "" if no
  144. // string flag exists
  145. func (c *Context) GlobalString(name string) string {
  146. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  147. return lookupString(name, fs)
  148. }
  149. return ""
  150. }
  151. // GlobalStringSlice looks up the value of a global string slice flag, returns
  152. // nil if no string slice flag exists
  153. func (c *Context) GlobalStringSlice(name string) []string {
  154. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  155. return lookupStringSlice(name, fs)
  156. }
  157. return nil
  158. }
  159. // GlobalIntSlice looks up the value of a global int slice flag, returns nil if
  160. // no int slice flag exists
  161. func (c *Context) GlobalIntSlice(name string) []int {
  162. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  163. return lookupIntSlice(name, fs)
  164. }
  165. return nil
  166. }
  167. // GlobalInt64Slice looks up the value of a global int slice flag, returns nil if
  168. // no int slice flag exists
  169. func (c *Context) GlobalInt64Slice(name string) []int64 {
  170. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  171. return lookupInt64Slice(name, fs)
  172. }
  173. return nil
  174. }
  175. // GlobalGeneric looks up the value of a global generic flag, returns nil if no
  176. // generic flag exists
  177. func (c *Context) GlobalGeneric(name string) interface{} {
  178. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  179. return lookupGeneric(name, fs)
  180. }
  181. return nil
  182. }
  183. // NumFlags returns the number of flags set
  184. func (c *Context) NumFlags() int {
  185. return c.flagSet.NFlag()
  186. }
  187. // Set sets a context flag to a value.
  188. func (c *Context) Set(name, value string) error {
  189. return c.flagSet.Set(name, value)
  190. }
  191. // GlobalSet sets a context flag to a value on the global flagset
  192. func (c *Context) GlobalSet(name, value string) error {
  193. return globalContext(c).flagSet.Set(name, value)
  194. }
  195. // IsSet determines if the flag was actually set
  196. func (c *Context) IsSet(name string) bool {
  197. if c.setFlags == nil {
  198. c.setFlags = make(map[string]bool)
  199. c.flagSet.Visit(func(f *flag.Flag) {
  200. c.setFlags[f.Name] = true
  201. })
  202. }
  203. return c.setFlags[name] == true
  204. }
  205. // GlobalIsSet determines if the global flag was actually set
  206. func (c *Context) GlobalIsSet(name string) bool {
  207. if c.globalSetFlags == nil {
  208. c.globalSetFlags = make(map[string]bool)
  209. ctx := c
  210. if ctx.parentContext != nil {
  211. ctx = ctx.parentContext
  212. }
  213. for ; ctx != nil && c.globalSetFlags[name] == false; ctx = ctx.parentContext {
  214. ctx.flagSet.Visit(func(f *flag.Flag) {
  215. c.globalSetFlags[f.Name] = true
  216. })
  217. }
  218. }
  219. return c.globalSetFlags[name]
  220. }
  221. // FlagNames returns a slice of flag names used in this context.
  222. func (c *Context) FlagNames() (names []string) {
  223. for _, flag := range c.Command.Flags {
  224. name := strings.Split(flag.GetName(), ",")[0]
  225. if name == "help" {
  226. continue
  227. }
  228. names = append(names, name)
  229. }
  230. return
  231. }
  232. // GlobalFlagNames returns a slice of global flag names used by the app.
  233. func (c *Context) GlobalFlagNames() (names []string) {
  234. for _, flag := range c.App.Flags {
  235. name := strings.Split(flag.GetName(), ",")[0]
  236. if name == "help" || name == "version" {
  237. continue
  238. }
  239. names = append(names, name)
  240. }
  241. return
  242. }
  243. // Parent returns the parent context, if any
  244. func (c *Context) Parent() *Context {
  245. return c.parentContext
  246. }
  247. // Args contains apps console arguments
  248. type Args []string
  249. // Args returns the command line arguments associated with the context.
  250. func (c *Context) Args() Args {
  251. args := Args(c.flagSet.Args())
  252. return args
  253. }
  254. // NArg returns the number of the command line arguments.
  255. func (c *Context) NArg() int {
  256. return len(c.Args())
  257. }
  258. // Get returns the nth argument, or else a blank string
  259. func (a Args) Get(n int) string {
  260. if len(a) > n {
  261. return a[n]
  262. }
  263. return ""
  264. }
  265. // First returns the first argument, or else a blank string
  266. func (a Args) First() string {
  267. return a.Get(0)
  268. }
  269. // Tail returns the rest of the arguments (not the first one)
  270. // or else an empty string slice
  271. func (a Args) Tail() []string {
  272. if len(a) >= 2 {
  273. return []string(a)[1:]
  274. }
  275. return []string{}
  276. }
  277. // Present checks if there are any arguments present
  278. func (a Args) Present() bool {
  279. return len(a) != 0
  280. }
  281. // Swap swaps arguments at the given indexes
  282. func (a Args) Swap(from, to int) error {
  283. if from >= len(a) || to >= len(a) {
  284. return errors.New("index out of range")
  285. }
  286. a[from], a[to] = a[to], a[from]
  287. return nil
  288. }
  289. func globalContext(ctx *Context) *Context {
  290. if ctx == nil {
  291. return nil
  292. }
  293. for {
  294. if ctx.parentContext == nil {
  295. return ctx
  296. }
  297. ctx = ctx.parentContext
  298. }
  299. }
  300. func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
  301. if ctx.parentContext != nil {
  302. ctx = ctx.parentContext
  303. }
  304. for ; ctx != nil; ctx = ctx.parentContext {
  305. if f := ctx.flagSet.Lookup(name); f != nil {
  306. return ctx.flagSet
  307. }
  308. }
  309. return nil
  310. }
  311. func lookupInt(name string, set *flag.FlagSet) int {
  312. f := set.Lookup(name)
  313. if f != nil {
  314. val, err := strconv.ParseInt(f.Value.String(), 0, 64)
  315. if err != nil {
  316. return 0
  317. }
  318. return int(val)
  319. }
  320. return 0
  321. }
  322. func lookupInt64(name string, set *flag.FlagSet) int64 {
  323. f := set.Lookup(name)
  324. if f != nil {
  325. val, err := strconv.ParseInt(f.Value.String(), 0, 64)
  326. if err != nil {
  327. return 0
  328. }
  329. return val
  330. }
  331. return 0
  332. }
  333. func lookupUint(name string, set *flag.FlagSet) uint {
  334. f := set.Lookup(name)
  335. if f != nil {
  336. val, err := strconv.ParseUint(f.Value.String(), 0, 64)
  337. if err != nil {
  338. return 0
  339. }
  340. return uint(val)
  341. }
  342. return 0
  343. }
  344. func lookupUint64(name string, set *flag.FlagSet) uint64 {
  345. f := set.Lookup(name)
  346. if f != nil {
  347. val, err := strconv.ParseUint(f.Value.String(), 0, 64)
  348. if err != nil {
  349. return 0
  350. }
  351. return val
  352. }
  353. return 0
  354. }
  355. func lookupDuration(name string, set *flag.FlagSet) time.Duration {
  356. f := set.Lookup(name)
  357. if f != nil {
  358. val, err := time.ParseDuration(f.Value.String())
  359. if err == nil {
  360. return val
  361. }
  362. }
  363. return 0
  364. }
  365. func lookupFloat64(name string, set *flag.FlagSet) float64 {
  366. f := set.Lookup(name)
  367. if f != nil {
  368. val, err := strconv.ParseFloat(f.Value.String(), 64)
  369. if err != nil {
  370. return 0
  371. }
  372. return val
  373. }
  374. return 0
  375. }
  376. func lookupString(name string, set *flag.FlagSet) string {
  377. f := set.Lookup(name)
  378. if f != nil {
  379. return f.Value.String()
  380. }
  381. return ""
  382. }
  383. func lookupStringSlice(name string, set *flag.FlagSet) []string {
  384. f := set.Lookup(name)
  385. if f != nil {
  386. return (f.Value.(*StringSlice)).Value()
  387. }
  388. return nil
  389. }
  390. func lookupIntSlice(name string, set *flag.FlagSet) []int {
  391. f := set.Lookup(name)
  392. if f != nil {
  393. return (f.Value.(*IntSlice)).Value()
  394. }
  395. return nil
  396. }
  397. func lookupInt64Slice(name string, set *flag.FlagSet) []int64 {
  398. f := set.Lookup(name)
  399. if f != nil {
  400. return (f.Value.(*Int64Slice)).Value()
  401. }
  402. return nil
  403. }
  404. func lookupGeneric(name string, set *flag.FlagSet) interface{} {
  405. f := set.Lookup(name)
  406. if f != nil {
  407. return f.Value
  408. }
  409. return nil
  410. }
  411. func lookupBool(name string, set *flag.FlagSet) bool {
  412. f := set.Lookup(name)
  413. if f != nil {
  414. val, err := strconv.ParseBool(f.Value.String())
  415. if err != nil {
  416. return false
  417. }
  418. return val
  419. }
  420. return false
  421. }
  422. func lookupBoolT(name string, set *flag.FlagSet) bool {
  423. f := set.Lookup(name)
  424. if f != nil {
  425. val, err := strconv.ParseBool(f.Value.String())
  426. if err != nil {
  427. return true
  428. }
  429. return val
  430. }
  431. return false
  432. }
  433. func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
  434. switch ff.Value.(type) {
  435. case *StringSlice:
  436. default:
  437. set.Set(name, ff.Value.String())
  438. }
  439. }
  440. func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
  441. visited := make(map[string]bool)
  442. set.Visit(func(f *flag.Flag) {
  443. visited[f.Name] = true
  444. })
  445. for _, f := range flags {
  446. parts := strings.Split(f.GetName(), ",")
  447. if len(parts) == 1 {
  448. continue
  449. }
  450. var ff *flag.Flag
  451. for _, name := range parts {
  452. name = strings.Trim(name, " ")
  453. if visited[name] {
  454. if ff != nil {
  455. return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
  456. }
  457. ff = set.Lookup(name)
  458. }
  459. }
  460. if ff == nil {
  461. continue
  462. }
  463. for _, name := range parts {
  464. name = strings.Trim(name, " ")
  465. if !visited[name] {
  466. copyFlag(name, ff, set)
  467. }
  468. }
  469. }
  470. return nil
  471. }