Skip to content

Commit

Permalink
Merge pull request #91 from paketo-buildpacks/resolve-env
Browse files Browse the repository at this point in the history
Adds sherpa.ResolveBool for use in helpers
  • Loading branch information
Daniel Mikusa authored Oct 6, 2021
2 parents eb2c8cb + b467887 commit 5bedaab
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 5bedaab

Please sign in to comment.