From a3b93076fffa81ce505c15d47e3f847d37a97382 Mon Sep 17 00:00:00 2001 From: bryanl Date: Mon, 8 Jun 2015 16:21:26 -0400 Subject: [PATCH] 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) } ``` --- context.go | 5 +++++ context_test.go | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/context.go b/context.go index 5b67129..3c8f468 100644 --- a/context.go +++ b/context.go @@ -132,6 +132,11 @@ func (c *Context) NumFlags() int { 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 func (c *Context) IsSet(name string) bool { if c.setFlags == nil { diff --git a/context_test.go b/context_test.go index 6c27d06..c3f2631 100644 --- a/context_test.go +++ b/context_test.go @@ -113,3 +113,12 @@ func TestContext_NumFlags(t *testing.T) { globalSet.Parse([]string{"--myflagGlobal"}) 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) +}