-
Notifications
You must be signed in to change notification settings - Fork 38
/
env_store.go
117 lines (98 loc) · 2.17 KB
/
env_store.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package command
import (
"strings"
"sync"
"golang.org/x/exp/slices"
)
// func envPairSize(k, v string) int {
// // +2 for the '=' and '\0' separators
// return len(k) + len(v) + 2
// }
type envStore struct {
mu sync.RWMutex
items map[string]string
}
func newEnvStore() *envStore {
return &envStore{items: make(map[string]string)}
}
func (s *envStore) Merge(envs ...string) (*envStore, error) {
for _, env := range envs {
if _, err := s.Set(splitEnv(env)); err != nil {
return s, err
}
}
return s, nil
}
func (s *envStore) Get(k string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
v, ok := s.items[k]
return v, ok
}
func (s *envStore) Set(k, v string) (*envStore, error) {
s.mu.Lock()
defer s.mu.Unlock()
// environSize := envPairSize(k, v)
// for key, value := range s.items {
// if key == k {
// continue
// }
// environSize += envPairSize(key, value)
// }
// if environSize > MaxEnvironSizeInBytes {
// return s, errors.New("could not set environment variable, environment size limit exceeded")
// }
s.items[k] = v
return s, nil
}
func (s *envStore) Delete(k string) *envStore {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.items, k)
return s
}
func (s *envStore) Items() []string {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]string, 0, len(s.items))
for k, v := range s.items {
result = append(result, k+"="+v)
}
slices.Sort(result)
return result
}
func diffEnvStores(initial, updated *envStore) (newOrUpdated, unchanged, deleted []string) {
initial.mu.RLock()
defer initial.mu.RUnlock()
updated.mu.RLock()
defer updated.mu.RUnlock()
for k, v := range initial.items {
uVal, ok := updated.items[k]
if !ok {
deleted = append(deleted, k)
} else if v != uVal {
newOrUpdated = append(newOrUpdated, k+"="+uVal)
} else {
unchanged = append(unchanged, k)
}
}
for k, v := range updated.items {
_, ok := initial.items[k]
if ok {
continue
}
newOrUpdated = append(newOrUpdated, k+"="+v)
}
return
}
func splitEnv(str string) (string, string) {
parts := strings.SplitN(str, "=", 2)
switch len(parts) {
case 0:
return "", ""
case 1:
return parts[0], ""
default:
return parts[0], parts[1]
}
}