Skip to content

Commit

Permalink
osutil.GetenvBool now takes an extra optional, argument
Browse files Browse the repository at this point in the history
  • Loading branch information
chipaca committed Jan 12, 2017
1 parent dea104c commit a6b25e6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
17 changes: 14 additions & 3 deletions osutil/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,27 @@ import (
"strconv"
)

// GetenvBool returns whether the given key may be considered "set" in the environment
// (i.e. it is set to one of "1", "true", etc)
func GetenvBool(key string) bool {
// GetenvBool returns whether the given key may be considered "set" in the
// environment (i.e. it is set to one of "1", "true", etc).
//
// An optional second argument can be provided, which determines how to
// treat missing or unparsable values; default is to treat them as false.
func GetenvBool(key string, dflt ...bool) bool {
val := os.Getenv(key)
if val == "" {
if len(dflt) > 0 {
return dflt[0]
}

return false
}

b, err := strconv.ParseBool(val)
if err != nil {
if len(dflt) > 0 {
return dflt[0]
}

return false
}

Expand Down
29 changes: 27 additions & 2 deletions osutil/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ func (s *envSuite) TestGetenvBoolTrue(c *check.C) {
os.Unsetenv(key)

for _, s := range []string{
"1", "t", "TRUE", // etc
"1", "t", "TRUE",
} {
os.Setenv(key, s)
c.Assert(os.Getenv(key), check.Equals, s)
c.Check(osutil.GetenvBool(key), check.Equals, true, check.Commentf(s))
c.Check(osutil.GetenvBool(key, false), check.Equals, true, check.Commentf(s))
c.Check(osutil.GetenvBool(key, true), check.Equals, true, check.Commentf(s))
}
}

Expand All @@ -50,10 +52,33 @@ func (s *envSuite) TestGetenvBoolFalse(c *check.C) {
c.Assert(osutil.GetenvBool(key), check.Equals, false)

for _, s := range []string{
"", "0", "f", "FALSE", // etc
"", "0", "f", "FALSE", "potato",
} {
os.Setenv(key, s)
c.Assert(os.Getenv(key), check.Equals, s)
c.Check(osutil.GetenvBool(key), check.Equals, false, check.Commentf(s))
c.Check(osutil.GetenvBool(key, false), check.Equals, false, check.Commentf(s))
}
}

func (s *envSuite) TestGetenvBoolFalseDefaultTrue(c *check.C) {
key := "__XYZZY__"
os.Unsetenv(key)
c.Assert(osutil.GetenvBool(key), check.Equals, false)

for _, s := range []string{
"0", "f", "FALSE",
} {
os.Setenv(key, s)
c.Assert(os.Getenv(key), check.Equals, s)
c.Check(osutil.GetenvBool(key, true), check.Equals, false, check.Commentf(s))
}

for _, s := range []string{
"", "potato", // etc
} {
os.Setenv(key, s)
c.Assert(os.Getenv(key), check.Equals, s)
c.Check(osutil.GetenvBool(key, true), check.Equals, true, check.Commentf(s))
}
}

0 comments on commit a6b25e6

Please sign in to comment.