context.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. // Duration looks up the value of a local time.Duration flag, returns 0 if no
  30. // time.Duration flag exists
  31. func (c *Context) Duration(name string) time.Duration {
  32. return lookupDuration(name, c.flagSet)
  33. }
  34. // Float64 looks up the value of a local float64 flag, returns 0 if no float64
  35. // flag exists
  36. func (c *Context) Float64(name string) float64 {
  37. return lookupFloat64(name, c.flagSet)
  38. }
  39. // Bool looks up the value of a local bool flag, returns false if no bool flag exists
  40. func (c *Context) Bool(name string) bool {
  41. return lookupBool(name, c.flagSet)
  42. }
  43. // BoolT looks up the value of a local boolT flag, returns false if no bool flag exists
  44. func (c *Context) BoolT(name string) bool {
  45. return lookupBoolT(name, c.flagSet)
  46. }
  47. // String looks up the value of a local string flag, returns "" if no string flag exists
  48. func (c *Context) String(name string) string {
  49. return lookupString(name, c.flagSet)
  50. }
  51. // StringSlice looks up the value of a local string slice flag, returns nil if no
  52. // string slice flag exists
  53. func (c *Context) StringSlice(name string) []string {
  54. return lookupStringSlice(name, c.flagSet)
  55. }
  56. // IntSlice looks up the value of a local int slice flag, returns nil if no int
  57. // slice flag exists
  58. func (c *Context) IntSlice(name string) []int {
  59. return lookupIntSlice(name, c.flagSet)
  60. }
  61. // Generic looks up the value of a local generic flag, returns nil if no generic
  62. // flag exists
  63. func (c *Context) Generic(name string) interface{} {
  64. return lookupGeneric(name, c.flagSet)
  65. }
  66. // GlobalInt looks up the value of a global int flag, returns 0 if no int flag exists
  67. func (c *Context) GlobalInt(name string) int {
  68. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  69. return lookupInt(name, fs)
  70. }
  71. return 0
  72. }
  73. // GlobalFloat64 looks up the value of a global float64 flag, returns float64(0)
  74. // if no float64 flag exists
  75. func (c *Context) GlobalFloat64(name string) float64 {
  76. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  77. return lookupFloat64(name, fs)
  78. }
  79. return float64(0)
  80. }
  81. // GlobalDuration looks up the value of a global time.Duration flag, returns 0
  82. // if no time.Duration flag exists
  83. func (c *Context) GlobalDuration(name string) time.Duration {
  84. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  85. return lookupDuration(name, fs)
  86. }
  87. return 0
  88. }
  89. // GlobalBool looks up the value of a global bool flag, returns false if no bool
  90. // flag exists
  91. func (c *Context) GlobalBool(name string) bool {
  92. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  93. return lookupBool(name, fs)
  94. }
  95. return false
  96. }
  97. // GlobalBoolT looks up the value of a global bool flag, returns true if no bool
  98. // flag exists
  99. func (c *Context) GlobalBoolT(name string) bool {
  100. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  101. return lookupBoolT(name, fs)
  102. }
  103. return false
  104. }
  105. // GlobalString looks up the value of a global string flag, returns "" if no
  106. // string flag exists
  107. func (c *Context) GlobalString(name string) string {
  108. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  109. return lookupString(name, fs)
  110. }
  111. return ""
  112. }
  113. // GlobalStringSlice looks up the value of a global string slice flag, returns
  114. // nil if no string slice flag exists
  115. func (c *Context) GlobalStringSlice(name string) []string {
  116. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  117. return lookupStringSlice(name, fs)
  118. }
  119. return nil
  120. }
  121. // GlobalIntSlice looks up the value of a global int slice flag, returns nil if
  122. // no int slice flag exists
  123. func (c *Context) GlobalIntSlice(name string) []int {
  124. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  125. return lookupIntSlice(name, fs)
  126. }
  127. return nil
  128. }
  129. // GlobalGeneric looks up the value of a global generic flag, returns nil if no
  130. // generic flag exists
  131. func (c *Context) GlobalGeneric(name string) interface{} {
  132. if fs := lookupGlobalFlagSet(name, c); fs != nil {
  133. return lookupGeneric(name, fs)
  134. }
  135. return nil
  136. }
  137. // NumFlags returns the number of flags set
  138. func (c *Context) NumFlags() int {
  139. return c.flagSet.NFlag()
  140. }
  141. // Set sets a context flag to a value.
  142. func (c *Context) Set(name, value string) error {
  143. return c.flagSet.Set(name, value)
  144. }
  145. // GlobalSet sets a context flag to a value on the global flagset
  146. func (c *Context) GlobalSet(name, value string) error {
  147. return globalContext(c).flagSet.Set(name, value)
  148. }
  149. // IsSet determines if the flag was actually set
  150. func (c *Context) IsSet(name string) bool {
  151. if c.setFlags == nil {
  152. c.setFlags = make(map[string]bool)
  153. c.flagSet.Visit(func(f *flag.Flag) {
  154. c.setFlags[f.Name] = true
  155. })
  156. }
  157. return c.setFlags[name] == true
  158. }
  159. // GlobalIsSet determines if the global flag was actually set
  160. func (c *Context) GlobalIsSet(name string) bool {
  161. if c.globalSetFlags == nil {
  162. c.globalSetFlags = make(map[string]bool)
  163. ctx := c
  164. if ctx.parentContext != nil {
  165. ctx = ctx.parentContext
  166. }
  167. for ; ctx != nil && c.globalSetFlags[name] == false; ctx = ctx.parentContext {
  168. ctx.flagSet.Visit(func(f *flag.Flag) {
  169. c.globalSetFlags[f.Name] = true
  170. })
  171. }
  172. }
  173. return c.globalSetFlags[name]
  174. }
  175. // FlagNames returns a slice of flag names used in this context.
  176. func (c *Context) FlagNames() (names []string) {
  177. for _, flag := range c.Command.Flags {
  178. name := strings.Split(flag.GetName(), ",")[0]
  179. if name == "help" {
  180. continue
  181. }
  182. names = append(names, name)
  183. }
  184. return
  185. }
  186. // GlobalFlagNames returns a slice of global flag names used by the app.
  187. func (c *Context) GlobalFlagNames() (names []string) {
  188. for _, flag := range c.App.Flags {
  189. name := strings.Split(flag.GetName(), ",")[0]
  190. if name == "help" || name == "version" {
  191. continue
  192. }
  193. names = append(names, name)
  194. }
  195. return
  196. }
  197. // Parent returns the parent context, if any
  198. func (c *Context) Parent() *Context {
  199. return c.parentContext
  200. }
  201. // Args contains apps console arguments
  202. type Args []string
  203. // Args returns the command line arguments associated with the context.
  204. func (c *Context) Args() Args {
  205. args := Args(c.flagSet.Args())
  206. return args
  207. }
  208. // NArg returns the number of the command line arguments.
  209. func (c *Context) NArg() int {
  210. return len(c.Args())
  211. }
  212. // Get returns the nth argument, or else a blank string
  213. func (a Args) Get(n int) string {
  214. if len(a) > n {
  215. return a[n]
  216. }
  217. return ""
  218. }
  219. // First returns the first argument, or else a blank string
  220. func (a Args) First() string {
  221. return a.Get(0)
  222. }
  223. // Tail returns the rest of the arguments (not the first one)
  224. // or else an empty string slice
  225. func (a Args) Tail() []string {
  226. if len(a) >= 2 {
  227. return []string(a)[1:]
  228. }
  229. return []string{}
  230. }
  231. // Present checks if there are any arguments present
  232. func (a Args) Present() bool {
  233. return len(a) != 0
  234. }
  235. // Swap swaps arguments at the given indexes
  236. func (a Args) Swap(from, to int) error {
  237. if from >= len(a) || to >= len(a) {
  238. return errors.New("index out of range")
  239. }
  240. a[from], a[to] = a[to], a[from]
  241. return nil
  242. }
  243. func globalContext(ctx *Context) *Context {
  244. if ctx == nil {
  245. return nil
  246. }
  247. for {
  248. if ctx.parentContext == nil {
  249. return ctx
  250. }
  251. ctx = ctx.parentContext
  252. }
  253. }
  254. func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
  255. if ctx.parentContext != nil {
  256. ctx = ctx.parentContext
  257. }
  258. for ; ctx != nil; ctx = ctx.parentContext {
  259. if f := ctx.flagSet.Lookup(name); f != nil {
  260. return ctx.flagSet
  261. }
  262. }
  263. return nil
  264. }
  265. func lookupInt(name string, set *flag.FlagSet) int {
  266. f := set.Lookup(name)
  267. if f != nil {
  268. val, err := strconv.Atoi(f.Value.String())
  269. if err != nil {
  270. return 0
  271. }
  272. return val
  273. }
  274. return 0
  275. }
  276. func lookupDuration(name string, set *flag.FlagSet) time.Duration {
  277. f := set.Lookup(name)
  278. if f != nil {
  279. val, err := time.ParseDuration(f.Value.String())
  280. if err == nil {
  281. return val
  282. }
  283. }
  284. return 0
  285. }
  286. func lookupFloat64(name string, set *flag.FlagSet) float64 {
  287. f := set.Lookup(name)
  288. if f != nil {
  289. val, err := strconv.ParseFloat(f.Value.String(), 64)
  290. if err != nil {
  291. return 0
  292. }
  293. return val
  294. }
  295. return 0
  296. }
  297. func lookupString(name string, set *flag.FlagSet) string {
  298. f := set.Lookup(name)
  299. if f != nil {
  300. return f.Value.String()
  301. }
  302. return ""
  303. }
  304. func lookupStringSlice(name string, set *flag.FlagSet) []string {
  305. f := set.Lookup(name)
  306. if f != nil {
  307. return (f.Value.(*StringSlice)).Value()
  308. }
  309. return nil
  310. }
  311. func lookupIntSlice(name string, set *flag.FlagSet) []int {
  312. f := set.Lookup(name)
  313. if f != nil {
  314. return (f.Value.(*IntSlice)).Value()
  315. }
  316. return nil
  317. }
  318. func lookupGeneric(name string, set *flag.FlagSet) interface{} {
  319. f := set.Lookup(name)
  320. if f != nil {
  321. return f.Value
  322. }
  323. return nil
  324. }
  325. func lookupBool(name string, set *flag.FlagSet) bool {
  326. f := set.Lookup(name)
  327. if f != nil {
  328. val, err := strconv.ParseBool(f.Value.String())
  329. if err != nil {
  330. return false
  331. }
  332. return val
  333. }
  334. return false
  335. }
  336. func lookupBoolT(name string, set *flag.FlagSet) bool {
  337. f := set.Lookup(name)
  338. if f != nil {
  339. val, err := strconv.ParseBool(f.Value.String())
  340. if err != nil {
  341. return true
  342. }
  343. return val
  344. }
  345. return false
  346. }
  347. func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
  348. switch ff.Value.(type) {
  349. case *StringSlice:
  350. default:
  351. set.Set(name, ff.Value.String())
  352. }
  353. }
  354. func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
  355. visited := make(map[string]bool)
  356. set.Visit(func(f *flag.Flag) {
  357. visited[f.Name] = true
  358. })
  359. for _, f := range flags {
  360. parts := strings.Split(f.GetName(), ",")
  361. if len(parts) == 1 {
  362. continue
  363. }
  364. var ff *flag.Flag
  365. for _, name := range parts {
  366. name = strings.Trim(name, " ")
  367. if visited[name] {
  368. if ff != nil {
  369. return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
  370. }
  371. ff = set.Lookup(name)
  372. }
  373. }
  374. if ff == nil {
  375. continue
  376. }
  377. for _, name := range parts {
  378. name = strings.Trim(name, " ")
  379. if !visited[name] {
  380. copyFlag(name, ff, set)
  381. }
  382. }
  383. }
  384. return nil
  385. }