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.
 
 
 

291 lines
6.6 KiB

  1. package cli
  2. import (
  3. "errors"
  4. "flag"
  5. "reflect"
  6. "strings"
  7. "syscall"
  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. shellComplete bool
  17. flagSet *flag.FlagSet
  18. setFlags 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. c := &Context{App: app, flagSet: set, parentContext: parentCtx}
  24. if parentCtx != nil {
  25. c.shellComplete = parentCtx.shellComplete
  26. }
  27. return c
  28. }
  29. // NumFlags returns the number of flags set
  30. func (c *Context) NumFlags() int {
  31. return c.flagSet.NFlag()
  32. }
  33. // Set sets a context flag to a value.
  34. func (c *Context) Set(name, value string) error {
  35. return c.flagSet.Set(name, value)
  36. }
  37. // GlobalSet sets a context flag to a value on the global flagset
  38. func (c *Context) GlobalSet(name, value string) error {
  39. return globalContext(c).flagSet.Set(name, value)
  40. }
  41. // IsSet determines if the flag was actually set
  42. func (c *Context) IsSet(name string) bool {
  43. if c.setFlags == nil {
  44. c.setFlags = make(map[string]bool)
  45. c.flagSet.Visit(func(f *flag.Flag) {
  46. c.setFlags[f.Name] = true
  47. })
  48. c.flagSet.VisitAll(func(f *flag.Flag) {
  49. if _, ok := c.setFlags[f.Name]; ok {
  50. return
  51. }
  52. c.setFlags[f.Name] = false
  53. })
  54. // XXX hack to support IsSet for flags with EnvVar
  55. //
  56. // There isn't an easy way to do this with the current implementation since
  57. // whether a flag was set via an environment variable is very difficult to
  58. // determine here. Instead, we intend to introduce a backwards incompatible
  59. // change in version 2 to add `IsSet` to the Flag interface to push the
  60. // responsibility closer to where the information required to determine
  61. // whether a flag is set by non-standard means such as environment
  62. // variables is avaliable.
  63. //
  64. // See https://github.com/urfave/cli/issues/294 for additional discussion
  65. flags := c.Command.Flags
  66. if c.Command.Name == "" { // cannot == Command{} since it contains slice types
  67. if c.App != nil {
  68. flags = c.App.Flags
  69. }
  70. }
  71. for _, f := range flags {
  72. eachName(f.GetName(), func(name string) {
  73. if isSet, ok := c.setFlags[name]; isSet || !ok {
  74. return
  75. }
  76. val := reflect.ValueOf(f)
  77. if val.Kind() == reflect.Ptr {
  78. val = val.Elem()
  79. }
  80. envVarValue := val.FieldByName("EnvVar")
  81. if !envVarValue.IsValid() {
  82. return
  83. }
  84. eachName(envVarValue.String(), func(envVar string) {
  85. envVar = strings.TrimSpace(envVar)
  86. if _, ok := syscall.Getenv(envVar); ok {
  87. c.setFlags[name] = true
  88. return
  89. }
  90. })
  91. })
  92. }
  93. }
  94. return c.setFlags[name]
  95. }
  96. // GlobalIsSet determines if the global flag was actually set
  97. func (c *Context) GlobalIsSet(name string) bool {
  98. ctx := c
  99. if ctx.parentContext != nil {
  100. ctx = ctx.parentContext
  101. }
  102. for ; ctx != nil; ctx = ctx.parentContext {
  103. if ctx.IsSet(name) {
  104. return true
  105. }
  106. }
  107. return false
  108. }
  109. // FlagNames returns a slice of flag names used in this context.
  110. func (c *Context) FlagNames() (names []string) {
  111. for _, flag := range c.Command.Flags {
  112. name := strings.Split(flag.GetName(), ",")[0]
  113. if name == "help" {
  114. continue
  115. }
  116. names = append(names, name)
  117. }
  118. return
  119. }
  120. // GlobalFlagNames returns a slice of global flag names used by the app.
  121. func (c *Context) GlobalFlagNames() (names []string) {
  122. for _, flag := range c.App.Flags {
  123. name := strings.Split(flag.GetName(), ",")[0]
  124. if name == "help" || name == "version" {
  125. continue
  126. }
  127. names = append(names, name)
  128. }
  129. return
  130. }
  131. // Parent returns the parent context, if any
  132. func (c *Context) Parent() *Context {
  133. return c.parentContext
  134. }
  135. // value returns the value of the flag coressponding to `name`
  136. func (c *Context) value(name string) interface{} {
  137. return c.flagSet.Lookup(name).Value.(flag.Getter).Get()
  138. }
  139. // Args contains apps console arguments
  140. type Args []string
  141. // Args returns the command line arguments associated with the context.
  142. func (c *Context) Args() Args {
  143. args := Args(c.flagSet.Args())
  144. return args
  145. }
  146. // NArg returns the number of the command line arguments.
  147. func (c *Context) NArg() int {
  148. return len(c.Args())
  149. }
  150. // Get returns the nth argument, or else a blank string
  151. func (a Args) Get(n int) string {
  152. if len(a) > n {
  153. return a[n]
  154. }
  155. return ""
  156. }
  157. // First returns the first argument, or else a blank string
  158. func (a Args) First() string {
  159. return a.Get(0)
  160. }
  161. // Last - Return the last argument, or else a blank string
  162. func (a Args) Last() string {
  163. return a.Get(len(a) - 1)
  164. }
  165. // Head - Return the rest of the arguments (not the last one)
  166. // or else an empty string slice
  167. func (a Args) Head() Args {
  168. if len(a) == 1 {
  169. return a
  170. }
  171. return []string(a)[:len(a)-1]
  172. }
  173. // Tail returns the rest of the arguments (not the first one)
  174. // or else an empty string slice
  175. func (a Args) Tail() Args {
  176. if len(a) >= 2 {
  177. return []string(a)[1:]
  178. }
  179. return []string{}
  180. }
  181. // Present checks if there are any arguments present
  182. func (a Args) Present() bool {
  183. return len(a) != 0
  184. }
  185. // Swap swaps arguments at the given indexes
  186. func (a Args) Swap(from, to int) error {
  187. if from >= len(a) || to >= len(a) {
  188. return errors.New("index out of range")
  189. }
  190. a[from], a[to] = a[to], a[from]
  191. return nil
  192. }
  193. func globalContext(ctx *Context) *Context {
  194. if ctx == nil {
  195. return nil
  196. }
  197. for {
  198. if ctx.parentContext == nil {
  199. return ctx
  200. }
  201. ctx = ctx.parentContext
  202. }
  203. }
  204. func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
  205. if ctx.parentContext != nil {
  206. ctx = ctx.parentContext
  207. }
  208. for ; ctx != nil; ctx = ctx.parentContext {
  209. if f := ctx.flagSet.Lookup(name); f != nil {
  210. return ctx.flagSet
  211. }
  212. }
  213. return nil
  214. }
  215. func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
  216. switch ff.Value.(type) {
  217. case *StringSlice:
  218. default:
  219. set.Set(name, ff.Value.String())
  220. }
  221. }
  222. func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
  223. visited := make(map[string]bool)
  224. set.Visit(func(f *flag.Flag) {
  225. visited[f.Name] = true
  226. })
  227. for _, f := range flags {
  228. parts := strings.Split(f.GetName(), ",")
  229. if len(parts) == 1 {
  230. continue
  231. }
  232. var ff *flag.Flag
  233. for _, name := range parts {
  234. name = strings.Trim(name, " ")
  235. if visited[name] {
  236. if ff != nil {
  237. return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
  238. }
  239. ff = set.Lookup(name)
  240. }
  241. }
  242. if ff == nil {
  243. continue
  244. }
  245. for _, name := range parts {
  246. name = strings.Trim(name, " ")
  247. if !visited[name] {
  248. copyFlag(name, ff, set)
  249. }
  250. }
  251. }
  252. return nil
  253. }