-
Notifications
You must be signed in to change notification settings - Fork 8
/
env.go
59 lines (54 loc) · 1.12 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
// Package osutil implements some OS utility functions.
package osutil
import (
"os"
"regexp"
"strings"
)
type EnvVar struct {
Key string
Value string
}
func Env() []EnvVar {
envs := []EnvVar{}
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if len(pair) > 0 {
key := strings.TrimSpace(pair[0])
if len(key) > 0 {
env := EnvVar{Key: key}
if len(pair) > 1 {
env.Value = strings.Join(pair[1:], "=")
}
envs = append(envs, env)
}
}
}
return envs
}
// EnvFiltered returns a map[string]string of environment
// variables that match a regular expression.
func EnvFiltered(rx *regexp.Regexp) map[string]string {
res := map[string]string{}
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if rx.MatchString(pair[0]) {
res[pair[0]] = pair[1]
}
}
return res
}
func EnvExists(fields ...string) (missing []string, haveAll bool) {
missing = []string{}
for _, field := range fields {
val := strings.TrimSpace(os.Getenv(field))
if len(val) == 0 {
missing = append(missing, field)
}
}
haveAll = true
if len(missing) > 0 {
haveAll = false
}
return
}