context.go 6.6 KB

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