From b467887746e9f446ccc93a718743788194eb72b8 Mon Sep 17 00:00:00 2001 From: Daniel Mikusa Date: Wed, 6 Oct 2021 12:12:50 -0400 Subject: [PATCH] Adds sherpa.ResolveBool for use in helpers 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 --- sherpa/env_var.go | 17 +++++++++++++++ sherpa/env_var_test.go | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) 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()) + }) + }) + + }) }