From 97b416f3cba0d07ead1a11da4d4b8e63e4600e94 Mon Sep 17 00:00:00 2001 From: Daniel Mikusa Date: Tue, 31 Dec 2024 17:41:21 -0500 Subject: [PATCH] Adds method ResolveBoolWithDefault This allows you to fetch a boolean configuration and change the default, like if you want the default to be true. Not used often, but it is helpful for a couple of buildpacks. Signed-off-by: Daniel Mikusa --- sherpa/env_var.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/sherpa/env_var.go b/sherpa/env_var.go index d41615c..8689529 100644 --- a/sherpa/env_var.go +++ b/sherpa/env_var.go @@ -69,8 +69,7 @@ func ResolveBoolErr(name string) (bool, error) { return false, nil } - t := strings.TrimSpace(s) - p, err := strconv.ParseBool(t) + p, err := strconv.ParseBool(strings.TrimSpace(s)) if err != nil { return false, fmt.Errorf( "invalid value '%s' for key '%s': expected one of [1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False]", @@ -81,3 +80,18 @@ func ResolveBoolErr(name string) (bool, error) { return p, nil } + +// ResolveBoolWithDefault resolves a boolean value for a configuration option or returns the default value +func ResolveBoolWithDefault(name string, defaultVal bool) bool { + s, ok := os.LookupEnv(name) + if !ok { + return defaultVal + } + + p, err := strconv.ParseBool(strings.TrimSpace(s)) + if err != nil { + return false + } + + return p +}