-
Notifications
You must be signed in to change notification settings - Fork 0
/
envmap.go
93 lines (73 loc) · 1.53 KB
/
envmap.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package envparse
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
)
type envMap map[string]string
func newEnvMap(prefix string, envList []string) envMap {
env := make(map[string]string)
{
for _, envVar := range envList {
envVarParts := strings.SplitN(envVar, "=", 2)
if len(envVarParts) != 2 {
// Skip invalid envVar
continue
}
if strings.HasPrefix(envVarParts[0], prefix) {
env[envVarParts[0]] = envVarParts[1]
}
}
}
return env
}
func (env envMap) Exists(key string) bool {
if _, ok := env[key]; ok {
return true
}
return false
}
func (env envMap) PrefixExists(prefix string) bool {
for k := range env {
if strings.HasPrefix(k, prefix) {
return true
}
}
return false
}
func (env envMap) Get(key string) string {
return env[key]
}
func (env envMap) GetPrefix(prefix string) envMap {
result := make(map[string]string)
prefix = fmt.Sprintf("%s_", strings.TrimRight(prefix, "_"))
for k, v := range env {
if strings.HasPrefix(k, prefix) {
result[strings.TrimPrefix(k, prefix)] = v
}
}
return result
}
func (env envMap) GetSlicePrefixes() []string {
keys := make(map[int]string)
re := regexp.MustCompile(`^[0-9]+$`)
for k := range env {
kPart := strings.Split(k, "_")[0]
if re.MatchString(kPart) {
numValue, _ := strconv.Atoi(kPart)
keys[numValue] = kPart
}
}
result := make([]string, 0)
order := make([]int, 0)
for i := range keys {
order = append(order, i)
}
sort.Ints(order)
for _, i := range order {
result = append(result, keys[i])
}
return result
}