context.go 8.9 KB

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