-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvironment.go
More file actions
203 lines (178 loc) · 4.81 KB
/
environment.go
File metadata and controls
203 lines (178 loc) · 4.81 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package env
import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"regexp"
"strconv"
"github.com/taybart/log"
)
var (
keyRE = regexp.MustCompile(`([[:word:]]+)([=?])?(.*)?`)
// Optional keys that should be set to zero value
optionalKeys map[string]bool
defaults map[string]string
)
func init() {
optionalKeys = make(map[string]bool)
defaults = make(map[string]string)
}
/* Add : environment variables for use later. This is global to the project
* requred -> NAME
* with_default -> NAME=taybart
* optional -> NAME? // defaults to zero value
*/
func Add(keys []string) {
err := Ensure(keys)
if err != nil {
panic(err)
}
}
// Ensure : check that env vars are defined, set default, mark optional
func Ensure(keys []string) error {
if len(keys) == 0 {
return nil
}
missingKeys := []string{}
optionalKeys = GetOptional(keys)
for _, key := range keys {
fkey, val := GetDefault(key) // formatted key and default value
if _, found := os.LookupEnv(fkey); !found {
if optionalKeys[fkey] {
log.Warnf("%s marked optional and not defined\n", fkey)
continue
}
if val != "" { // is there a default value?
log.Warnf("Setting %s to default value of %s\n", fkey, val)
os.Setenv(fkey, val)
defaults[fkey] = val
continue
}
missingKeys = append(missingKeys, key)
}
// was this previously set to something different?
if defaults[fkey] != "" && defaults[fkey] != val {
panic(fmt.Sprintf("Differing default value for %s [ %s!=%s ]\n", fkey, defaults[fkey], val))
}
}
for _, key := range missingKeys {
log.Errorf("Missing environment variable: %s%s%s\n", log.Red, key, log.Reset)
}
if len(missingKeys) > 0 {
return fmt.Errorf("set all required environment variables: %v", missingKeys)
}
return nil
}
// Has : see if env var defined
func Has(key string) bool {
_, b := os.LookupEnv(key)
return b
}
// Is : returns if the variable _is_ the string
func Is(key, compare string) bool {
if val, found := os.LookupEnv(key); found {
return val == compare
}
return false
}
// Get : returns the environment value as a string
func Get(key string) string {
if val, found := os.LookupEnv(key); found {
return val
}
log.Warnf("checking optional value %v\n", key)
if _, found := optionalKeys[key]; found {
return ""
}
log.Fatal("Trying to retrieve uninitialized environment variable:", key)
return ""
}
// Decode : returns the environment value as base64 decoded bytes
func Decode(key string) ([]byte, error) {
if val, found := os.LookupEnv(key); found {
decoded, err := base64.StdEncoding.DecodeString(val)
if err != nil {
return nil, err
}
return decoded, nil
}
log.Warnf("checking for optional %v\n", key)
if _, found := optionalKeys[key]; found {
return nil, nil
}
log.Fatal("Trying to retrieve/decode uninitialized environment variable:", key)
return nil, nil
}
// Int : returns the key as an int or panics
func Int(key string) int {
if val, found := os.LookupEnv(key); found {
converted, err := strconv.Atoi(val)
if err != nil {
log.Fatalf("An error occurred in converting the value [%s] retrieved with key [%s] to an int: %s", val, key, err)
}
return converted
}
if _, found := optionalKeys[key]; found {
return 0
}
log.Fatal("Trying to retrieve uninitialized environment variable:", key)
return 0
}
// Bool : returns the env var as its value, or false if it doesn't exist
func Bool(key string) bool {
if val, found := os.LookupEnv(key); found {
return val == "true"
}
if _, found := optionalKeys[key]; found {
return false
}
log.Fatal("Trying to retrieve uninitialized environment variable:", key)
return false
}
// IsSet : returns if the environment variable is set including a blank string
func IsSet(key string) bool {
value, found := os.LookupEnv(key)
if found {
return value != ""
}
return found
}
// JSON : returns the environment value marshalled to input
func JSON(key string, input any) error {
if val, found := os.LookupEnv(key); found {
err := json.Unmarshal([]byte(val), input)
if err != nil {
return fmt.Errorf("could not unmarshal %s: (value: %+v) %v", key, val, err)
}
return nil
}
if _, found := optionalKeys[key]; found {
return nil
}
log.Fatalf("Trying to retrieve uninitialized environment variable: %s, found (should show nothing) %s\n", key, os.Getenv(key))
return nil
}
func GetDefault(entry string) (key string, defaultValue string) {
res := keyRE.FindAllStringSubmatch(entry, -1)
return res[0][1], res[0][3]
}
func GetOptional(keys []string) map[string]bool {
optionals := make(map[string]bool)
if len(keys) == 0 {
return optionals
}
for _, key := range keys {
res := keyRE.FindAllStringSubmatch(key, -1)
optionals[res[0][1]] = res[0][2] == "?"
}
return optionals
}
// NoWarn : remove warning logs
func NoWarn() {
log.SetLevel(log.ERROR)
}
// NoLog : disable logging
func NoLog() {
log.SetLevel(log.NONE)
}