Skip to content

Commit

Permalink
Implement *Context.GlobalSet + relevant CHANGELOG entry
Browse files Browse the repository at this point in the history
  • Loading branch information
meatballhat committed Apr 30, 2016
1 parent 4edb5c9 commit e059dc8
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
- This file!
- Support for placeholders in flag usage strings
- `App.Metadata` map for arbitrary data/state management
- `Set` and `GlobalSet` methods on `*cli.Context` for altering values after
parsing.

### Changed
- The `App.Action` and `Command.Action` now prefer a return signature of
Expand Down
20 changes: 20 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ 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
func (c *Context) IsSet(name string) bool {
if c.setFlags == nil {
Expand Down Expand Up @@ -252,6 +257,21 @@ func (a Args) Swap(from, to int) error {
return nil
}

func globalContext(ctx *Context) *Context {
if ctx == nil {
return nil
}

for {
if ctx.parentContext == nil {
return ctx
}
ctx = ctx.parentContext
}

return nil
}

func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
if ctx.parentContext != nil {
ctx = ctx.parentContext
Expand Down
19 changes: 19 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,22 @@ func TestContext_Set(t *testing.T) {
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)
}

0 comments on commit e059dc8

Please sign in to comment.