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.

context.go 6.3KB

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