Merge pull request #367 from codegangsta/bryanl-bryanl-set-context-values

Merging #234 set context values
This commit is contained in:
Dan Buch 2016-04-30 12:31:31 -04:00
commit 9f8c5004f2
3 changed files with 53 additions and 0 deletions

View File

@ -8,6 +8,8 @@
- This file! - This file!
- Support for placeholders in flag usage strings - Support for placeholders in flag usage strings
- `App.Metadata` map for arbitrary data/state management - `App.Metadata` map for arbitrary data/state management
- `Set` and `GlobalSet` methods on `*cli.Context` for altering values after
parsing.
### Changed ### Changed
- The `App.Action` and `Command.Action` now prefer a return signature of - The `App.Action` and `Command.Action` now prefer a return signature of

View File

@ -141,6 +141,16 @@ func (c *Context) NumFlags() int {
return c.flagSet.NFlag() return c.flagSet.NFlag()
} }
// Set sets a context flag to a value.
func (c *Context) Set(name, value string) error {
return c.flagSet.Set(name, value)
}
// GlobalSet sets a context flag to a value on the global flagset
func (c *Context) GlobalSet(name, value string) error {
return globalContext(c).flagSet.Set(name, value)
}
// Determines if the flag was actually set // Determines if the flag was actually set
func (c *Context) IsSet(name string) bool { func (c *Context) IsSet(name string) bool {
if c.setFlags == nil { if c.setFlags == nil {
@ -247,6 +257,19 @@ func (a Args) Swap(from, to int) error {
return nil return nil
} }
func globalContext(ctx *Context) *Context {
if ctx == nil {
return nil
}
for {
if ctx.parentContext == nil {
return ctx
}
ctx = ctx.parentContext
}
}
func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet { func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
if ctx.parentContext != nil { if ctx.parentContext != nil {
ctx = ctx.parentContext ctx = ctx.parentContext

View File

@ -202,3 +202,31 @@ func TestContext_GlobalFlagsInSubcommands(t *testing.T) {
expect(t, subcommandRun, true) expect(t, subcommandRun, true)
expect(t, parentFlag, true) expect(t, parentFlag, true)
} }
func TestContext_Set(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("int", 5, "an int")
c := NewContext(nil, set, nil)
c.Set("int", "1")
expect(t, c.Int("int"), 1)
}
func TestContext_GlobalSet(t *testing.T) {
gSet := flag.NewFlagSet("test", 0)
gSet.Int("int", 5, "an int")
set := flag.NewFlagSet("sub", 0)
set.Int("int", 3, "an int")
pc := NewContext(nil, gSet, nil)
c := NewContext(nil, set, pc)
c.Set("int", "1")
expect(t, c.Int("int"), 1)
expect(t, c.GlobalInt("int"), 5)
c.GlobalSet("int", "1")
expect(t, c.Int("int"), 1)
expect(t, c.GlobalInt("int"), 1)
}