Skip to content

Commit

Permalink
Adds sherpa.ResolveBool for use in helpers
Browse files Browse the repository at this point in the history
Provide the method with an env variable name and it will resolve & attempt to validate in a consistent way if the variable is true or false.

The function returns true for 1, t, T, TRUE, true, True. It returns false for all other values (even invalid) and if the variable is not set.

Signed-off-by: Daniel Mikusa <dmikusa@vmware.com>
  • Loading branch information
Daniel Mikusa committed Oct 6, 2021
1 parent eb2c8cb commit b467887
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
17 changes: 17 additions & 0 deletions sherpa/env_var.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package sherpa
import (
"fmt"
"os"
"strconv"
"strings"
)

Expand Down Expand Up @@ -50,3 +51,19 @@ func GetEnvWithDefault(name string, def string) string {
}
return def
}

// ResolveBool resolves a boolean value for a configuration option. Returns true for 1, t, T, TRUE, true, True. Returns
// false for all other values or unset.
func ResolveBool(name string) bool {
s, ok := os.LookupEnv(name)
if !ok {
return false
}

t, err := strconv.ParseBool(s)
if err != nil {
return false
}

return t
}
49 changes: 49 additions & 0 deletions sherpa/env_var_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,53 @@ func testEnvVar(t *testing.T, context spec.G, it spec.S) {
Expect(sherpa.GetEnvWithDefault("ANOTHER_KEY", "default-value")).To(Equal("default-value"))
})
})

context("ResolveBool", func() {
context("variable not set", func() {
it("returns false if not set", func() {
Expect(sherpa.ResolveBool("TEST_KEY")).To(BeFalse())
})
})

context("variable is set to true value", func() {
it.After(func() {
Expect(os.Unsetenv("TEST_KEY")).To(Succeed())
})

it("returns true", func() {
for _, form := range []string{"1", "t", "T", "TRUE", "true", "True"} {
Expect(os.Setenv("TEST_KEY", form))
Expect(sherpa.ResolveBool("TEST_KEY")).To(BeTrue())
Expect(os.Unsetenv("TEST_KEY")).To(Succeed())
}
})
})

context("variable is set to non-true value", func() {
it.After(func() {
Expect(os.Unsetenv("TEST_KEY")).To(Succeed())
})

it("returns false", func() {
for _, form := range []string{"0", "f", "F", "FALSE", "false", "False"} {
Expect(os.Setenv("TEST_KEY", form))
Expect(sherpa.ResolveBool("TEST_KEY")).To(BeFalse())
Expect(os.Unsetenv("TEST_KEY")).To(Succeed())
}
})
})

context("variable is set to an invalid value", func() {
it.After(func() {
Expect(os.Unsetenv("TEST_KEY")).To(Succeed())
})

it("returns false", func() {
Expect(os.Setenv("TEST_KEY", "foo"))
Expect(sherpa.ResolveBool("TEST_KEY")).To(BeFalse())
Expect(os.Unsetenv("TEST_KEY")).To(Succeed())
})
})

})
}

0 comments on commit b467887

Please sign in to comment.