-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.go
More file actions
348 lines (297 loc) · 8.48 KB
/
env.go
File metadata and controls
348 lines (297 loc) · 8.48 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
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
// Copyright CattleCloud LLC 2024, 2026
// SPDX-License-Identifier: BSD-3-Clause
package env
import (
"bufio"
"errors"
"fmt"
"maps"
"os"
"strconv"
"strings"
"github.com/shoenig/go-conceal"
)
// A Variable represents an environment variable.
type Variable string
func (v Variable) String() string {
return "{" + string(v) + "}"
}
func (v Variable) Name() string {
return string(v)
}
// Schema is used to describe how to parse a set of environment variables.
type Schema map[Variable]Parser
// ParseOS is a convenience function for parsing the given Schema of environment
// variables using the environment variables accessed by the standard libraray
// os package. If the values of environment variables do not match the schema,
// or required variables are missing, an error is returned.
func ParseOS(schema Schema) error {
return Parse(OS, schema)
}
// ParseFile is a convenience function for parsing the given Schema of environment
// variables using the given .env file path. The contents of the file are read
// and interpreted as key=value pairs, one per line. If the environment variable
// contents of the file do not match the schema, or required variables are missing,
// an error is returned.
func ParseFile(path string, schema Schema) error {
return Parse(File(path), schema)
}
// ParseMap is a convenience function for parsing the given Schema of environment
// variables using the given map. The contents of the map are inferred as
// key=value pairs. If the contents of the map do not match the schema, or
// required variables are missing, an error is returned.
func ParseMap(m map[string]string, schema Schema) error {
return Parse(Map(m), schema)
}
// Parse uses the given Schema to parse the environment variables in the given
// Environment. If the values of environment variables in Environment do not
// match the schema, or required variables are missing, an error is returned.
func Parse(environment Environment, schema Schema) error {
for key, parser := range schema {
value := environment.Getenv(key.Name())
if err := parser.Parse(value); err != nil {
return fmt.Errorf("failed to parse %q: %w", key, err)
}
}
return nil
}
// The Parser interface is what must be implemented to support decoding an
// environment variable into a custom type.
type Parser interface {
Parse(string) error
}
// StringType represents any type compatible with the Go string built-in type,
// to be used as a destination for writing the value of an environment variable.
type StringType interface {
~string
}
type stringParser[T StringType] struct {
required bool
destination *T
}
func (sp *stringParser[T]) Parse(s string) error {
if sp.required && s == "" {
return errors.New("missing")
} else if s == "" {
return nil
}
*sp.destination = T(s)
return nil
}
// String is used to extract an environment variable into a Go string. If
// required is true, then an error is returned if the environment variable is
// not set or is empty.
func String[T StringType](s *T, required bool) Parser {
return &stringParser[T]{
required: required,
destination: s,
}
}
// StringOr is used to extract an environment variable into a Go string. If
// the environment variable is not set or is empty, then the alt value is used
// instead.
func StringOr[T StringType](s *T, alt T) Parser {
*s = alt
return &stringParser[T]{
required: false,
destination: s,
}
}
type secretParser struct {
required bool
destination **conceal.Text
}
func (sp *secretParser) Parse(s string) error {
if sp.required && s == "" {
return errors.New("missing")
} else if s == "" {
return nil
}
text := conceal.New(s)
*sp.destination = text
return nil
}
// Secret is used to extract an environment variable into a Go concel.Text
// object. If required is true, then an error is returned if the environment
// variable is not set or is empty.
func Secret(s **conceal.Text, required bool) Parser {
return &secretParser{
required: required,
destination: s,
}
}
// IntType represents any type compatible with the Go integer built-in types,
// to be used as a destination for writing the value of an environment variable.
type IntType interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
type intParser[T IntType] struct {
required bool
destination *T
}
func (ip *intParser[T]) Parse(s string) error {
if ip.required && s == "" {
return errors.New("missing")
} else if s == "" {
return nil
}
i, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("unable to parse %q as int: %w", s, err)
}
*ip.destination = T(i)
return nil
}
// Int is used to extract an environment variable into a Go int. If required
// is true, then an error is returned if the environment variable is not set or
// is empty.
func Int[T IntType](i *T, required bool) Parser {
return &intParser[T]{
required: required,
destination: i,
}
}
// IntOr is used to extract an environment variable into a Go int. If the
// environment variable is not set or is empty, then the alt value is used
// instead.
func IntOr[T IntType](i *T, alt T) Parser {
*i = alt
return &intParser[T]{
required: false,
destination: i,
}
}
type floatParser struct {
required bool
destination *float64
}
func (fp *floatParser) Parse(s string) error {
if fp.required && s == "" {
return errors.New("missing")
} else if s == "" {
return nil
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return fmt.Errorf("unable to parse %q as float: %w", s, err)
}
*fp.destination = f
return nil
}
// Float is used to extract an environment variable into a Go float64. If
// required is true, then an error is returned if the environment variable is
// not set or is empty.
func Float(f *float64, required bool) Parser {
return &floatParser{
required: required,
destination: f,
}
}
// FloatOr is used to extract an environment variable into a Go float64. If
// the environment variable is not set or is emty, then the alt value is used
// instead.
func FloatOr(f *float64, alt float64) Parser {
*f = alt
return &floatParser{
required: false,
destination: f,
}
}
type boolParser struct {
required bool
destination *bool
}
func (bp *boolParser) Parse(s string) error {
if bp.required && s == "" {
return errors.New("missing")
} else if s == "" {
return nil
}
b, err := strconv.ParseBool(s)
if err != nil {
return fmt.Errorf("unable to parse %q as bool: %w", s, err)
}
*bp.destination = b
return nil
}
// Bool is used to extract an environment variable into a Go bool. If required
// is true, then an error is returned if the environment variable is not set or
// is empty.
func Bool(b *bool, required bool) Parser {
return &boolParser{
required: required,
destination: b,
}
}
// BoolOr is used to extract an environment variable into a Go bool. If the
// environment variable is not set or is empty, then the alt value is used
// instead.
func BoolOr(b *bool, alt bool) Parser {
*b = alt
return &boolParser{
required: false,
destination: b,
}
}
// Environment is something that implements Getenv().
//
// Most use cases can simply make use of the OS implementation which is backed
// by the standard library os package.
type Environment interface {
Getenv(string) string
}
type osEnv struct {
// defer to the os package
}
func (e *osEnv) Getenv(name string) string {
return os.Getenv(name)
}
// OS is an implementation of Environment that uses the standard library os
// package to retrieve actual environment variables.
var OS Environment = new(osEnv)
// File is an implementation of Environment that reads environment variables
// from a file.
//
// e.g. /etc/os-release
func File(filename string) Environment {
return &fileEnv{filename: filename}
}
type fileEnv struct {
filename string
}
func (e *fileEnv) Getenv(key string) string {
f, err := os.Open(e.filename)
if err != nil {
return ""
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
idx := strings.Index(line, "=")
if idx < 1 || idx >= len(line)-1 {
continue
}
if line[0:idx] == key {
return line[idx+1:]
}
}
return ""
}
// Map is an implementation of Environment that uses a given map[string]string
// to emulate a set of environment variables. Useful for testing.
//
// m := Map(map[string]string {...})
//
// func f(e env.Environment) {
// e.Getenv("FOOBAR")
// }
func Map(m map[string]string) Environment {
return &mapEnv{m: maps.Clone(m)}
}
type mapEnv struct {
m map[string]string
}
func (m *mapEnv) Getenv(key string) string {
return m.m[key]
}