diff --git a/envconfig/config.go b/envconfig/config.go index f4bd4aa6b..0aee21f9f 100644 --- a/envconfig/config.go +++ b/envconfig/config.go @@ -179,7 +179,8 @@ func BoolWithDefault(k string) func(defaultValue bool) bool { if s := Var(k); s != "" { b, err := strconv.ParseBool(s) if err != nil { - return true + slog.Warn("invalid boolean value, using default", "key", k, "value", s, "default", defaultValue) + return defaultValue } return b diff --git a/envconfig/config_test.go b/envconfig/config_test.go index 1a9d77f07..d135f1a84 100644 --- a/envconfig/config_test.go +++ b/envconfig/config_test.go @@ -1,6 +1,7 @@ package envconfig import ( + "fmt" "log/slog" "math" "os" @@ -188,9 +189,12 @@ func TestBool(t *testing.T) { "false": false, "1": true, "0": false, - // invalid values - "random": true, - "something": true, + // invalid values fall back to default (false for Bool) + "random": false, + "something": false, + "yes": false, + "on": false, + "enabled": false, } for k, v := range cases { @@ -203,6 +207,42 @@ func TestBool(t *testing.T) { } } +func TestBoolWithDefault(t *testing.T) { + cases := []struct { + value string + defaultValue bool + expect bool + }{ + // valid values override the default + {"true", false, true}, + {"false", true, false}, + {"1", false, true}, + {"0", true, false}, + // empty value returns the default unchanged + {"", true, true}, + {"", false, false}, + // invalid values fall back to the default, not hardcoded true + {"yes", false, false}, + {"yes", true, true}, + {"on", false, false}, + {"on", true, true}, + {"enabled", false, false}, + {"enabled", true, true}, + {"random", false, false}, + {"random", true, true}, + } + + for _, tt := range cases { + name := fmt.Sprintf("value=%q default=%v", tt.value, tt.defaultValue) + t.Run(name, func(t *testing.T) { + t.Setenv("OLLAMA_BOOL_WITH_DEFAULT", tt.value) + if b := BoolWithDefault("OLLAMA_BOOL_WITH_DEFAULT")(tt.defaultValue); b != tt.expect { + t.Errorf("%s: expected %v, got %v", name, tt.expect, b) + } + }) + } +} + func TestUint(t *testing.T) { cases := map[string]uint{ "0": 0,