-
Notifications
You must be signed in to change notification settings - Fork 1
/
goe.go
353 lines (277 loc) · 8.56 KB
/
goe.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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Package goe provide helpers to load environment variables.
package goe
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/compose-spec/compose-go/dotenv"
"github.com/ysmood/goe/pkg/utils"
"golang.org/x/exp/constraints"
)
// AutoLoad file and return informative message about what this function has done.
func AutoLoad(file string) error {
err := Load(false, true, file)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
utils.Println(Prefix, "env file not found, skipped loading.")
return nil
}
return err //nolint:wrapcheck
}
path, _ := LookupFile(file)
utils.Println(Prefix, "Loaded environment variables from:", path)
return nil
}
// Load .env file and return informative message about what this function has done.
// It will recursively search for the file in parent folders until it finds one.
// It uses [LoadDotEnv] to parse and load the content.
func Load(override, expand bool, file string) error {
path, err := LookupFile(file)
if err != nil {
return fmt.Errorf("failed to find .env file: %w", err)
}
content, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to open .env file: %w", err)
}
err = LoadContent(override, expand, string(content))
if err != nil {
return fmt.Errorf("failed to load .env content: %w", err)
}
return nil
}
// LoadContent load the .env content.
// If override is true, it will override the existing env vars.
// If expand is true, it will expand the env vars via [os.ExpandEnv].
func LoadContent(override, expand bool, content string) error {
doc, err := dotenv.ParseWithLookup(bytes.NewBufferString(content), os.LookupEnv)
if err != nil {
return fmt.Errorf("failed to parse env content: %w", err)
}
for k, v := range doc {
if !override {
if _, has := os.LookupEnv(k); has {
continue
}
}
if expand {
v = os.ExpandEnv(v)
}
err = os.Setenv(k, v)
if err != nil {
return fmt.Errorf("failed to set env variable: %w", err)
}
}
return nil
}
// LookupFile file recursively.
func LookupFile(file string) (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get current working directory: %w", err)
}
prev := ""
for dir != prev {
p := filepath.Join(dir, file)
if _, err := os.Stat(p); err == nil {
return p, nil
}
prev = dir
dir = filepath.Dir(dir)
}
return "", fmt.Errorf("%w: %s", os.ErrNotExist, file)
}
type EnvType interface {
EnvKeyType | ~[]byte
}
type EnvKeyType interface {
~bool | ~string | time.Duration | constraints.Float | constraints.Integer
}
// Is checks if the env var with the name is equal to the val.
func Is(name string, val string) bool {
return Get(name, "") == val
}
// Has checks if the env var with the name exists.
func Has(name string) bool {
_, has := os.LookupEnv(name)
return has
}
// Get env var with the name. It will return the defaultVal if it's not found.
// If the env var is found, it will use [Require] to parse the value.
func Get[T EnvType](name string, defaultVal T) T {
if _, has := os.LookupEnv(name); has {
return Require[T](name)
}
return defaultVal
}
// GetList is a shortcut for [GetListWithSep] with separator set to ",".
func GetList[T EnvType](name string, defaultVal []T) []T {
l, err := GetListWithSep(name, ",", defaultVal)
if err != nil {
panic("failed to parse list: " + err.Error())
}
return l
}
// GetListWithSep returns env var with the name. It will return the defaultVal if it's not found.
// It will parse the value as a list of type T with separator.
func GetListWithSep[T EnvType](name, separator string, defaultVal []T) ([]T, error) {
if _, has := os.LookupEnv(name); !has {
return defaultVal, nil
}
var out []T //nolint: prealloc
for _, s := range strings.Split(Get(name, ""), separator) {
v, err := Parse[T](s)
if err != nil {
return nil, fmt.Errorf("failed to parse list: %w", err)
}
out = append(out, v)
}
return out, nil
}
// GetMap is a shortcut for [GetMapWithSep] with pairSep set to "," and kvSep set to ":".
func GetMap[K EnvKeyType, V EnvType](name string, defaultVal map[K]V) map[K]V {
m, err := GetMapWithSep(name, ",", ":", defaultVal)
if err != nil {
panic("failed to parse map: " + err.Error())
}
return m
}
var ErrInvalidMapFormat = errors.New("invalid map format")
// GetMapWithSep returns env var with the name.
// It will override the key-value pairs in defaultVal with the parsed pairs.
// It will parse the value as a map of type K, V with two types of separators,
// the pairSep is for key-value pairs, and the kvSep is for key and value.
func GetMapWithSep[K EnvKeyType, V EnvType](name, pairSep, kvSep string, defaultVal map[K]V) (map[K]V, error) {
str := Get(name, "")
for _, s := range strings.Split(str, pairSep) {
kv := strings.Split(s, kvSep)
if len(kv) != 2 { //nolint: mnd
return nil, fmt.Errorf("%w: %s", ErrInvalidMapFormat, str)
}
k, err := Parse[K](kv[0])
if err != nil {
return nil, fmt.Errorf("failed to parse map key: %w", err)
}
v, err := Parse[V](kv[1])
if err != nil {
return nil, fmt.Errorf("failed to parse map value: %w", err)
}
defaultVal[k] = v
}
return defaultVal, nil
}
func GetWithParser[T any](name string, parser func(string) (T, error), defaultVal T) T {
if _, has := os.LookupEnv(name); has {
return RequireWithParser(name, parser)
}
return defaultVal
}
// Require load and parse the env var with the name.
// It will panic if the env var is not found or failed to parse.
// It uses [Parse] to parse the env var.
func Require[T EnvType](name string) T {
envStr, has := os.LookupEnv(name)
if !has {
panic("required env variable not found: " + name)
}
v, err := Parse[T](envStr)
if err != nil {
panic(err)
}
return v
}
// RequireWithParser load and parse the env var with the name.
func RequireWithParser[T any](name string, parser func(string) (T, error)) T {
v, err := parser(Require[string](name))
if err != nil {
panic("failed to parse env variable: " + name + ": " + err.Error())
}
return v
}
var ErrUnsupportedSliceType = errors.New("unsupported slice type")
// Parse the str to the type T.
// It will auto detect the type of the env var and parse it.
// If T is []byte and str is a existing file path, the file content will be the env var,
// or the str will be parsed as base64 and used as the env var.
func Parse[T EnvType](str string) (T, error) { //nolint: funlen,cyclop
v := reflect.ValueOf(new(T)).Elem()
empty := v.Interface().(T)
switch v.Interface().(type) { //nolint: gocritic
case time.Duration:
d, err := time.ParseDuration(str)
if err != nil {
return empty, fmt.Errorf("failed to parse duration: %w", err)
}
v.Set(reflect.ValueOf(d))
return v.Interface().(T), nil
}
switch v.Kind() { //nolint: exhaustive
case reflect.Bool:
b, err := strconv.ParseBool(str)
if err != nil {
return empty, fmt.Errorf("failed to parse bool: %w", err)
}
v.Set(reflect.ValueOf(b))
case reflect.String:
v = convert(str, v)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return empty, fmt.Errorf("failed to parse int: %w", err)
}
v = convert(i, v)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
i, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return empty, fmt.Errorf("failed to parse uint: %w", err)
}
v = convert(i, v)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(str, 64)
if err != nil {
return empty, fmt.Errorf("failed to parse float: %w", err)
}
v = convert(f, v)
case reflect.Slice:
if v.Type().Elem().Kind() != reflect.Uint8 {
return empty, fmt.Errorf("%w: %s", ErrUnsupportedSliceType, v.Type().String())
}
b, err := os.ReadFile(str)
if err == nil {
return convert(b, v).Interface().(T), nil
}
b, err = base64.StdEncoding.DecodeString(str)
if err != nil {
return empty, fmt.Errorf("failed to parse base64: %w", err)
}
v = convert(b, v)
}
return v.Interface().(T), nil
}
// Unset env var with [os.Unsetenv].
// Useful for secret unset to prevent leaking by other packages.
func Unset(name string) struct{} {
err := os.Unsetenv(name)
if err != nil {
panic("failed to unset env variable: " + name)
}
return struct{}{}
}
// Time parse the str to time.Time.
func Time(str string) (time.Time, error) {
t, err := time.Parse(time.RFC3339, str)
if err != nil {
return time.Time{}, fmt.Errorf("failed to parse time: %w", err)
}
return t, nil
}
func convert(from any, to reflect.Value) reflect.Value {
return reflect.ValueOf(from).Convert(to.Type())
}