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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
|
// Package gotenv provides functionality to dynamically load the environment variables
package gotenv
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
)
const (
// Pattern for detecting valid line format
linePattern = `\A\s*(?:export\s+)?([\w\.]+)(?:\s*=\s*|:\s+?)('(?:\'|[^'])*'|"(?:\"|[^"])*"|[^#\n]+)?\s*(?:\s*\#.*)?\z`
// Pattern for detecting valid variable within a value
variablePattern = `(\\)?(\$)(\{?([A-Z0-9_]+)?\}?)`
// Byte order mark character
bom = "\xef\xbb\xbf"
)
// Env holds key/value pair of valid environment variable
type Env map[string]string
// Load is a function to load a file or multiple files and then export the valid variables into environment variables if they do not exist.
// When it's called with no argument, it will load `.env` file on the current path and set the environment variables.
// Otherwise, it will loop over the filenames parameter and set the proper environment variables.
func Load(filenames ...string) error {
return loadenv(false, filenames...)
}
// OverLoad is a function to load a file or multiple files and then export and override the valid variables into environment variables.
func OverLoad(filenames ...string) error {
return loadenv(true, filenames...)
}
// Must is wrapper function that will panic when supplied function returns an error.
func Must(fn func(filenames ...string) error, filenames ...string) {
if err := fn(filenames...); err != nil {
panic(err.Error())
}
}
// Apply is a function to load an io Reader then export the valid variables into environment variables if they do not exist.
func Apply(r io.Reader) error {
return parset(r, false)
}
// OverApply is a function to load an io Reader then export and override the valid variables into environment variables.
func OverApply(r io.Reader) error {
return parset(r, true)
}
func loadenv(override bool, filenames ...string) error {
if len(filenames) == 0 {
filenames = []string{".env"}
}
for _, filename := range filenames {
f, err := os.Open(filename)
if err != nil {
return err
}
err = parset(f, override)
f.Close()
if err != nil {
return err
}
}
return nil
}
// parse and set :)
func parset(r io.Reader, override bool) error {
env, err := strictParse(r, override)
if err != nil {
return err
}
for key, val := range env {
setenv(key, val, override)
}
return nil
}
func setenv(key, val string, override bool) {
if override {
os.Setenv(key, val)
} else {
if _, present := os.LookupEnv(key); !present {
os.Setenv(key, val)
}
}
}
// Parse is a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables.
// It expands the value of a variable from the environment variable but does not set the value to the environment itself.
// This function is skipping any invalid lines and only processing the valid one.
func Parse(r io.Reader) Env {
env, _ := strictParse(r, false)
return env
}
// StrictParse is a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables.
// It expands the value of a variable from the environment variable but does not set the value to the environment itself.
// This function is returning an error if there are any invalid lines.
func StrictParse(r io.Reader) (Env, error) {
return strictParse(r, false)
}
// Read is a function to parse a file line by line and returns the valid Env key/value pair of valid variables.
// It expands the value of a variable from the environment variable but does not set the value to the environment itself.
// This function is skipping any invalid lines and only processing the valid one.
func Read(filename string) (Env, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return strictParse(f, false)
}
// Unmarshal reads a string line by line and returns the valid Env key/value pair of valid variables.
// It expands the value of a variable from the environment variable but does not set the value to the environment itself.
// This function is returning an error if there are any invalid lines.
func Unmarshal(str string) (Env, error) {
return strictParse(strings.NewReader(str), false)
}
// Marshal outputs the given environment as a env file.
// Variables will be sorted by name.
func Marshal(env Env) (string, error) {
lines := make([]string, 0, len(env))
for k, v := range env {
if d, err := strconv.Atoi(v); err == nil {
lines = append(lines, fmt.Sprintf(`%s=%d`, k, d))
} else {
lines = append(lines, fmt.Sprintf(`%s=%q`, k, v))
}
}
sort.Strings(lines)
return strings.Join(lines, "\n"), nil
}
// Write serializes the given environment and writes it to a file
func Write(env Env, filename string) error {
content, err := Marshal(env)
if err != nil {
return err
}
// ensure the path exists
if err := os.MkdirAll(filepath.Dir(filename), 0o775); err != nil {
return err
}
// create or truncate the file
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(content + "\n")
if err != nil {
return err
}
return file.Sync()
}
// splitLines is a valid SplitFunc for a bufio.Scanner. It will split lines on CR ('\r'), LF ('\n') or CRLF (any of the three sequences).
// If a CR is immediately followed by a LF, it is treated as a CRLF (one single line break).
func splitLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, bufio.ErrFinalToken
}
idx := bytes.IndexAny(data, "\r\n")
switch {
case atEOF && idx < 0:
return len(data), data, bufio.ErrFinalToken
case idx < 0:
return 0, nil, nil
}
// consume CR or LF
eol := idx + 1
// detect CRLF
if len(data) > eol && data[eol-1] == '\r' && data[eol] == '\n' {
eol++
}
return eol, data[:idx], nil
}
func strictParse(r io.Reader, override bool) (Env, error) {
env := make(Env)
scanner := bufio.NewScanner(r)
scanner.Split(splitLines)
firstLine := true
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if firstLine {
line = strings.TrimPrefix(line, bom)
firstLine = false
}
if line == "" || line[0] == '#' {
continue
}
quote := ""
// look for the delimiter character
idx := strings.Index(line, "=")
if idx == -1 {
idx = strings.Index(line, ":")
}
// look for a quote character
if idx > 0 && idx < len(line)-1 {
val := strings.TrimSpace(line[idx+1:])
if val[0] == '"' || val[0] == '\'' {
quote = val[:1]
// look for the closing quote character within the same line
idx = strings.LastIndex(strings.TrimSpace(val[1:]), quote)
if idx >= 0 && val[idx] != '\\' {
quote = ""
}
}
}
// look for the closing quote character
for quote != "" && scanner.Scan() {
l := scanner.Text()
line += "\n" + l
idx := strings.LastIndex(l, quote)
if idx > 0 && l[idx-1] == '\\' {
// foud a matching quote character but it's escaped
continue
}
if idx >= 0 {
// foud a matching quote
quote = ""
}
}
if quote != "" {
return env, fmt.Errorf("missing quotes")
}
err := parseLine(line, env, override)
if err != nil {
return env, err
}
}
return env, nil
}
var (
lineRgx = regexp.MustCompile(linePattern)
unescapeRgx = regexp.MustCompile(`\\([^$])`)
varRgx = regexp.MustCompile(variablePattern)
)
func parseLine(s string, env Env, override bool) error {
rm := lineRgx.FindStringSubmatch(s)
if len(rm) == 0 {
return checkFormat(s, env)
}
key := strings.TrimSpace(rm[1])
val := strings.TrimSpace(rm[2])
var hsq, hdq bool
// check if the value is quoted
if l := len(val); l >= 2 {
l -= 1
// has double quotes
hdq = val[0] == '"' && val[l] == '"'
// has single quotes
hsq = val[0] == '\'' && val[l] == '\''
// remove quotes '' or ""
if hsq || hdq {
val = val[1:l]
}
}
if hdq {
val = strings.ReplaceAll(val, `\n`, "\n")
val = strings.ReplaceAll(val, `\r`, "\r")
// Unescape all characters except $ so variables can be escaped properly
val = unescapeRgx.ReplaceAllString(val, "$1")
}
if !hsq {
fv := func(s string) string {
return varReplacement(s, hsq, env, override)
}
val = varRgx.ReplaceAllStringFunc(val, fv)
}
env[key] = val
return nil
}
func parseExport(st string, env Env) error {
if strings.HasPrefix(st, "export") {
vs := strings.SplitN(st, " ", 2)
if len(vs) > 1 {
if _, ok := env[vs[1]]; !ok {
return fmt.Errorf("line `%s` has an unset variable", st)
}
}
}
return nil
}
var varNameRgx = regexp.MustCompile(`(\$)(\{?([A-Z0-9_]+)\}?)`)
func varReplacement(s string, hsq bool, env Env, override bool) string {
if s == "" {
return s
}
if s[0] == '\\' {
// the dollar sign is escaped
return s[1:]
}
if hsq {
return s
}
mn := varNameRgx.FindStringSubmatch(s)
if len(mn) == 0 {
return s
}
v := mn[3]
if replace, ok := os.LookupEnv(v); ok && !override {
return replace
}
if replace, ok := env[v]; ok {
return replace
}
return os.Getenv(v)
}
func checkFormat(s string, env Env) error {
st := strings.TrimSpace(s)
if st == "" || st[0] == '#' {
return nil
}
if err := parseExport(st, env); err != nil {
return err
}
return fmt.Errorf("line `%s` doesn't match format", s)
}
|