context.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package cli
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "strconv"
  7. "strings"
  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. globalSet *flag.FlagSet
  18. setFlags map[string]bool
  19. }
  20. type Requires []string
  21. // Creates a new context. For use in when invoking an App or Command action.
  22. func NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {
  23. return &Context{App: app, flagSet: set, globalSet: globalSet}
  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 float64 flag, returns 0 if no float64 flag exists
  30. func (c *Context) Float64(name string) float64 {
  31. return lookupFloat64(name, c.flagSet)
  32. }
  33. // Looks up the value of a local bool flag, returns false if no bool flag exists
  34. func (c *Context) Bool(name string) bool {
  35. return lookupBool(name, c.flagSet)
  36. }
  37. // Looks up the value of a local boolT flag, returns false if no bool flag exists
  38. func (c *Context) BoolT(name string) bool {
  39. return lookupBoolT(name, c.flagSet)
  40. }
  41. // Looks up the value of a local string flag, returns "" if no string flag exists
  42. func (c *Context) String(name string) string {
  43. return lookupString(name, c.flagSet)
  44. }
  45. // Looks up the value of a local string slice flag, returns nil if no string slice flag exists
  46. func (c *Context) StringSlice(name string) []string {
  47. return lookupStringSlice(name, c.flagSet)
  48. }
  49. // Looks up the value of a local int slice flag, returns nil if no int slice flag exists
  50. func (c *Context) IntSlice(name string) []int {
  51. return lookupIntSlice(name, c.flagSet)
  52. }
  53. // Looks up the value of a local generic flag, returns nil if no generic flag exists
  54. func (c *Context) Generic(name string) interface{} {
  55. return lookupGeneric(name, c.flagSet)
  56. }
  57. // Looks up the value of a global int flag, returns 0 if no int flag exists
  58. func (c *Context) GlobalInt(name string) int {
  59. return lookupInt(name, c.globalSet)
  60. }
  61. // Looks up the value of a global bool flag, returns false if no bool flag exists
  62. func (c *Context) GlobalBool(name string) bool {
  63. return lookupBool(name, c.globalSet)
  64. }
  65. // Looks up the value of a global string flag, returns "" if no string flag exists
  66. func (c *Context) GlobalString(name string) string {
  67. return lookupString(name, c.globalSet)
  68. }
  69. // Looks up the value of a global string slice flag, returns nil if no string slice flag exists
  70. func (c *Context) GlobalStringSlice(name string) []string {
  71. return lookupStringSlice(name, c.globalSet)
  72. }
  73. // Looks up the value of a global int slice flag, returns nil if no int slice flag exists
  74. func (c *Context) GlobalIntSlice(name string) []int {
  75. return lookupIntSlice(name, c.globalSet)
  76. }
  77. // Looks up the value of a global generic flag, returns nil if no generic flag exists
  78. func (c *Context) GlobalGeneric(name string) interface{} {
  79. return lookupGeneric(name, c.globalSet)
  80. }
  81. // Determines if the flag was actually set exists
  82. func (c *Context) IsSet(name string) bool {
  83. if c.setFlags == nil {
  84. c.setFlags = make(map[string]bool)
  85. c.flagSet.Visit(func(f *flag.Flag) {
  86. c.setFlags[f.Name] = true
  87. })
  88. }
  89. return c.setFlags[name] == true
  90. }
  91. type Args []string
  92. // Returns the command line arguments associated with the context.
  93. func (c *Context) Args() Args {
  94. args := Args(c.flagSet.Args())
  95. return args
  96. }
  97. // Returns an error if the context arguments do not satisfy the given requirements
  98. func (c *Context) Satisfies(req *Requires) error {
  99. if req != nil {
  100. optional := 0
  101. unlimited := false
  102. clean_args := []string{}
  103. for _, arg := range *req {
  104. if strings.Contains(arg, "...") {
  105. unlimited = true
  106. arg = strings.Replace(arg, "...", "", -1) + "..."
  107. }
  108. if strings.Contains(arg, "?") {
  109. optional++
  110. arg = "[" + strings.Replace(arg, "?", "", -1) + "]"
  111. } else {
  112. arg = "<" + arg + ">"
  113. }
  114. clean_args = append(clean_args, arg)
  115. }
  116. exactly, nomore, atleast := 0, 0, 0
  117. if optional == 0 && !unlimited {
  118. exactly = len(*req)
  119. } else {
  120. atleast = len(*req) - optional
  121. if !unlimited {
  122. nomore = len(*req)
  123. }
  124. }
  125. argc := len(c.Args())
  126. err := ""
  127. if atleast > 0 || nomore > 0 {
  128. if atleast > argc {
  129. err = fmtRequiresError("atleast", atleast)
  130. } else if nomore > 0 && argc > nomore {
  131. err = fmtRequiresError("no more than", nomore)
  132. }
  133. } else if argc != exactly {
  134. err = fmtRequiresError("exactly", exactly)
  135. }
  136. if err != "" {
  137. if len(clean_args) > 0 {
  138. err += ": " + strings.Join(clean_args, " ")
  139. }
  140. return fmt.Errorf(err)
  141. }
  142. }
  143. return nil
  144. }
  145. // Returns the nth argument, or else a blank string
  146. func (a Args) Get(n int) string {
  147. if len(a) > n {
  148. return a[n]
  149. }
  150. return ""
  151. }
  152. // Returns the first argument, or else a blank string
  153. func (a Args) First() string {
  154. return a.Get(0)
  155. }
  156. // Return the rest of the arguments (not the first one)
  157. // or else an empty string slice
  158. func (a Args) Tail() []string {
  159. if len(a) >= 2 {
  160. return []string(a)[1:]
  161. }
  162. return []string{}
  163. }
  164. // Checks if there are any arguments present
  165. func (a Args) Present() bool {
  166. return len(a) != 0
  167. }
  168. // Swaps arguments at the given indexes
  169. func (a Args) Swap(from, to int) error {
  170. if from >= len(a) || to >= len(a) {
  171. return errors.New("index out of range")
  172. }
  173. a[from], a[to] = a[to], a[from]
  174. return nil
  175. }
  176. // Formats the requirement error
  177. func fmtRequiresError(str string, count int) string {
  178. switch count {
  179. case 0:
  180. return "Command requires no arguments"
  181. case 1:
  182. return fmt.Sprintf("Command requires %s 1 argument", str)
  183. }
  184. return fmt.Sprintf("Command requires %s %d arguments", str, count)
  185. }
  186. func lookupInt(name string, set *flag.FlagSet) int {
  187. f := set.Lookup(name)
  188. if f != nil {
  189. val, err := strconv.Atoi(f.Value.String())
  190. if err != nil {
  191. return 0
  192. }
  193. return val
  194. }
  195. return 0
  196. }
  197. func lookupFloat64(name string, set *flag.FlagSet) float64 {
  198. f := set.Lookup(name)
  199. if f != nil {
  200. val, err := strconv.ParseFloat(f.Value.String(), 64)
  201. if err != nil {
  202. return 0
  203. }
  204. return val
  205. }
  206. return 0
  207. }
  208. func lookupString(name string, set *flag.FlagSet) string {
  209. f := set.Lookup(name)
  210. if f != nil {
  211. return f.Value.String()
  212. }
  213. return ""
  214. }
  215. func lookupStringSlice(name string, set *flag.FlagSet) []string {
  216. f := set.Lookup(name)
  217. if f != nil {
  218. return (f.Value.(*StringSlice)).Value()
  219. }
  220. return nil
  221. }
  222. func lookupIntSlice(name string, set *flag.FlagSet) []int {
  223. f := set.Lookup(name)
  224. if f != nil {
  225. return (f.Value.(*IntSlice)).Value()
  226. }
  227. return nil
  228. }
  229. func lookupGeneric(name string, set *flag.FlagSet) interface{} {
  230. f := set.Lookup(name)
  231. if f != nil {
  232. return f.Value
  233. }
  234. return nil
  235. }
  236. func lookupBool(name string, set *flag.FlagSet) bool {
  237. f := set.Lookup(name)
  238. if f != nil {
  239. val, err := strconv.ParseBool(f.Value.String())
  240. if err != nil {
  241. return false
  242. }
  243. return val
  244. }
  245. return false
  246. }
  247. func lookupBoolT(name string, set *flag.FlagSet) bool {
  248. f := set.Lookup(name)
  249. if f != nil {
  250. val, err := strconv.ParseBool(f.Value.String())
  251. if err != nil {
  252. return true
  253. }
  254. return val
  255. }
  256. return false
  257. }
  258. func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
  259. switch ff.Value.(type) {
  260. case *StringSlice:
  261. default:
  262. set.Set(name, ff.Value.String())
  263. }
  264. }
  265. func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
  266. visited := make(map[string]bool)
  267. set.Visit(func(f *flag.Flag) {
  268. visited[f.Name] = true
  269. })
  270. for _, f := range flags {
  271. parts := strings.Split(f.getName(), ",")
  272. if len(parts) == 1 {
  273. continue
  274. }
  275. var ff *flag.Flag
  276. for _, name := range parts {
  277. name = strings.Trim(name, " ")
  278. if visited[name] {
  279. if ff != nil {
  280. return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
  281. }
  282. ff = set.Lookup(name)
  283. }
  284. }
  285. if ff == nil {
  286. continue
  287. }
  288. for _, name := range parts {
  289. name = strings.Trim(name, " ")
  290. if !visited[name] {
  291. copyFlag(name, ff, set)
  292. }
  293. }
  294. }
  295. return nil
  296. }