1package interpolate
2
3import (
4 "runtime"
5 "strings"
6)
7
8// Env is an interface for getting environment variables by name and returning a boolean indicating
9// whether the variable was found.
10type Env interface {
11 Get(key string) (string, bool)
12}
13
14// NewSliceEnv creates an Env from a slice of environment variables in the form "key=value".
15//
16// This can be used with [os.Environ] to create an Env.
17func NewSliceEnv(env []string) Env {
18 envMap := mapEnv{}
19 for _, l := range env {
20 parts := strings.SplitN(l, "=", 2)
21 if len(parts) == 2 {
22 envMap[normalizeKeyName(parts[0])] = parts[1]
23 }
24 }
25 return envMap
26}
27
28// NewMapEnv creates an Env from a map of environment variables.
29func NewMapEnv(env map[string]string) Env {
30 envMap := mapEnv{}
31 for k, v := range env {
32 envMap[normalizeKeyName(k)] = v
33 }
34 return envMap
35}
36
37type mapEnv map[string]string
38
39func (m mapEnv) Get(key string) (string, bool) {
40 if m == nil {
41 return "", false
42 }
43 val, ok := m[normalizeKeyName(key)]
44 return val, ok
45}
46
47// Windows isn't case sensitive for env
48func normalizeKeyName(key string) string {
49 if runtime.GOOS == "windows" {
50 return strings.ToUpper(key)
51 }
52 return key
53}