diff options
Diffstat (limited to 'srv/src')
-rw-r--r-- | srv/src/cfg/cfg.go | 21 | ||||
-rw-r--r-- | srv/src/cfg/cfg_test.go | 21 |
2 files changed, 42 insertions, 0 deletions
diff --git a/srv/src/cfg/cfg.go b/srv/src/cfg/cfg.go index 32fc3e7..d87c45b 100644 --- a/srv/src/cfg/cfg.go +++ b/srv/src/cfg/cfg.go @@ -211,6 +211,27 @@ func (c *Cfg) Int(name string, value int, usage string) *int { return p } +// BoolVar is equivalent to flag.FlagSet's BoolVar method, but will additionally +// set up an environment variable for the parameter. +func (c *Cfg) BoolVar(p *bool, name string, value bool, usage string) { + + envName := c.envifyName(name) + + c.flagSet.BoolVar(p, name, value, envifyUsage(envName, usage)) + + if valStr := c.params.Env[envName]; valStr != "" { + *p = valStr != "" && valStr != "0" && valStr != "false" + } +} + +// Bool is equivalent to flag.FlagSet's Bool method, but will additionally set +// up an environment variable for the parameter. +func (c *Cfg) Bool(name string, value bool, usage string) *bool { + p := new(bool) + c.BoolVar(p, name, value, usage) + return p +} + // SubCmd should be called _after_ Init. Init will have consumed all arguments // up until the first non-flag argument. This non-flag argument is a // sub-command, and is returned by this method. This method also resets Cfg's diff --git a/srv/src/cfg/cfg_test.go b/srv/src/cfg/cfg_test.go index 7ccf94a..8266c89 100644 --- a/srv/src/cfg/cfg_test.go +++ b/srv/src/cfg/cfg_test.go @@ -44,3 +44,24 @@ func TestIntVar(t *testing.T) { assert.Equal(t, 222, bar) assert.Equal(t, 333, baz) } + +func TestBoolVar(t *testing.T) { + + cfg := New(Params{ + Args: []string{"--foo=1"}, + Env: map[string]string{"FOO": "0", "BAR": "anything", "BIZ": "0"}, + }) + + var foo, bar, baz, biz bool + + cfg.BoolVar(&foo, "foo", false, "") + cfg.BoolVar(&bar, "bar", false, "") + cfg.BoolVar(&baz, "baz", false, "") + cfg.BoolVar(&biz, "biz", true, "") + + assert.NoError(t, cfg.Init(context.Background())) + assert.Equal(t, true, foo) + assert.Equal(t, true, bar) + assert.Equal(t, false, baz) + assert.Equal(t, false, biz) +} |