context.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. // Tail returns the rest of the arguments (not the first one)
  162. // or else an empty string slice
  163. func (a Args) Tail() []string {
  164. if len(a) >= 2 {
  165. return []string(a)[1:]
  166. }
  167. return []string{}
  168. }
  169. // Present checks if there are any arguments present
  170. func (a Args) Present() bool {
  171. return len(a) != 0
  172. }
  173. // Swap swaps arguments at the given indexes
  174. func (a Args) Swap(from, to int) error {
  175. if from >= len(a) || to >= len(a) {
  176. return errors.New("index out of range")
  177. }
  178. a[from], a[to] = a[to], a[from]
  179. return nil
  180. }
  181. func globalContext(ctx *Context) *Context {
  182. if ctx == nil {
  183. return nil
  184. }
  185. for {
  186. if ctx.parentContext == nil {
  187. return ctx
  188. }
  189. ctx = ctx.parentContext
  190. }
  191. }
  192. func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
  193. if ctx.parentContext != nil {
  194. ctx = ctx.parentContext
  195. }
  196. for ; ctx != nil; ctx = ctx.parentContext {
  197. if f := ctx.flagSet.Lookup(name); f != nil {
  198. return ctx.flagSet
  199. }
  200. }
  201. return nil
  202. }
  203. func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
  204. switch ff.Value.(type) {
  205. case *StringSlice:
  206. default:
  207. set.Set(name, ff.Value.String())
  208. }
  209. }
  210. func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
  211. visited := make(map[string]bool)
  212. set.Visit(func(f *flag.Flag) {
  213. visited[f.Name] = true
  214. })
  215. for _, f := range flags {
  216. parts := strings.Split(f.GetName(), ",")
  217. if len(parts) == 1 {
  218. continue
  219. }
  220. var ff *flag.Flag
  221. for _, name := range parts {
  222. name = strings.Trim(name, " ")
  223. if visited[name] {
  224. if ff != nil {
  225. return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
  226. }
  227. ff = set.Lookup(name)
  228. }
  229. }
  230. if ff == nil {
  231. continue
  232. }
  233. for _, name := range parts {
  234. name = strings.Trim(name, " ")
  235. if !visited[name] {
  236. copyFlag(name, ff, set)
  237. }
  238. }
  239. }
  240. return nil
  241. }