diff --git a/sherpa/env_var.go b/sherpa/env_var.go index ff2b7c2..91505b8 100644 --- a/sherpa/env_var.go +++ b/sherpa/env_var.go @@ -19,6 +19,7 @@ package sherpa import ( "fmt" "os" + "strconv" "strings" ) @@ -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 +} diff --git a/sherpa/env_var_test.go b/sherpa/env_var_test.go index 62c6db3..4b1e087 100644 --- a/sherpa/env_var_test.go +++ b/sherpa/env_var_test.go @@ -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()) + }) + }) + + }) }