-
Notifications
You must be signed in to change notification settings - Fork 2
/
env.go
68 lines (57 loc) · 1.45 KB
/
env.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"os"
"strings"
"github.com/samber/lo"
)
// EnvMap represents a map for environment variables
type EnvMap struct {
env Dict
}
// NewEnvMap returns a new EnvMap
func NewEnvMap() *EnvMap {
return &EnvMap{env: make(Dict)}
}
// Merge adds the given map to the existing values, overwriting any existing values
func (e *EnvMap) Merge(kv map[string]string) {
for k, v := range kv {
e.Add(k, v)
}
}
// Add adds the given value to the map, overwriting any existing values
func (e *EnvMap) Add(key, value string) {
e.env[key] = value
}
// Environ returns the map in the format of "key=value", skipping any already set,
// non-empty environment variables, and expanding variables
func (e *EnvMap) Environ() []string {
// Remove anything already set as an env var
env := lo.OmitBy(e.env, func(k, _ string) bool {
return os.Getenv(k) != ""
})
// Remove blank keys
env = lo.OmitBy(env, func(k, _ string) bool {
return strings.TrimSpace(k) == ""
})
// Expand variables
env = lo.MapValues(env, func(v string, _ string) string {
return os.Expand(v, func(s string) string {
if l := os.Getenv(s); l != "" {
return l
}
if v, ok := e.env[s]; ok {
return v
}
return ""
})
})
return lo.MapToSlice(env, func(k string, v string) string {
return fmt.Sprintf("%s=%s", k, v)
})
}
// Has returns true if the given key is set and not empty
func (e *EnvMap) Has(key string) bool {
v, ok := e.env[key]
return ok && v != ""
}