Allow context value to be set after parse

This change allows a context value to be set after parsing. The use case is updating default settings in a Before func.

An example usage:

```
		f, err := os.Open(configPath)
		if err == nil {
			config, err := docli.NewConfig(f)
			if err != nil {
                       panic(err)
			}

			c.Set("token", config.APIKey)
		}
```
This commit is contained in:
bryanl 2015-06-08 16:21:26 -04:00
parent 616b730509
commit a3b93076ff
2 changed files with 14 additions and 0 deletions

View File

@ -132,6 +132,11 @@ 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)
}
// 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 {

View File

@ -113,3 +113,12 @@ func TestContext_NumFlags(t *testing.T) {
globalSet.Parse([]string{"--myflagGlobal"}) globalSet.Parse([]string{"--myflagGlobal"})
expect(t, c.NumFlags(), 2) expect(t, c.NumFlags(), 2)
} }
func TestContext_Set(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("int", 5, "an int")
c := cli.NewContext(nil, set, nil)
c.Set("int", "1")
expect(t, c.Int("int"), 1)
}