util/def,cmd/containerboot: add LookupEnv, simplify env parsing (#20277)
Simplifies cmd/containerboot env var parsing. Most of the private helpers did not earn their abstraction: defaultEnv(name, "") is just os.Getenv(name), and the rest collapse into cmp.Or and the existing def.Bool. defaultEnv, defaultEnvs and defaultBool are gone. Adds def.LookupEnv, the env companion to def.Bool, for the one case that needs it: TS_KUBE_SECRET, where an explicit "" disables Kubernetes secret storage and must stay distinct from unset (cmp.Or cannot express that). Updates #20018 Signed-off-by: Nick Rossi <nrossi0530@gmail.com>
This commit is contained in:
+12
-1
@@ -1,10 +1,11 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Package def parses strings with fallback default values.
|
||||
// Package def parses strings and environment variables with fallback default values.
|
||||
package def
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
@@ -32,3 +33,13 @@ func Duration(s string, def time.Duration) time.Duration {
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// LookupEnv retrieves the value of the environment variable named by the key.
|
||||
// If the variable is present in the environment the value (which may be
|
||||
// empty) is returned. Otherwise, it returns def.
|
||||
func LookupEnv(key, def string) string {
|
||||
if v, ok := os.LookupEnv(key); ok {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package def_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -11,6 +12,32 @@ import (
|
||||
"tailscale.com/util/def"
|
||||
)
|
||||
|
||||
func TestLookupEnv(t *testing.T) {
|
||||
const key = "TS_DEF_TEST_LOOKUPENV"
|
||||
tests := []struct {
|
||||
name string
|
||||
unset bool
|
||||
value string
|
||||
def string
|
||||
want string
|
||||
}{
|
||||
{name: "unset", unset: true, def: "fallback", want: "fallback"},
|
||||
{name: "set", value: "value", def: "fallback", want: "value"},
|
||||
{name: "empty", value: "", def: "fallback", want: ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv(key, tt.value)
|
||||
if tt.unset {
|
||||
os.Unsetenv(key)
|
||||
}
|
||||
if got := def.LookupEnv(key, tt.def); got != tt.want {
|
||||
t.Errorf("LookupEnv(%q, %q) = %q; want %q", key, tt.def, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBool(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
Reference in New Issue
Block a user