251
|
1 |
// Package gotenv provides functionality to dynamically load the environment variables |
|
2 |
package gotenv |
|
3 |
|
|
4 |
import ( |
|
5 |
"bufio" |
|
6 |
"fmt" |
|
7 |
"io" |
|
8 |
"os" |
260
|
9 |
"path/filepath" |
251
|
10 |
"regexp" |
260
|
11 |
"sort" |
|
12 |
"strconv" |
251
|
13 |
"strings" |
|
14 |
) |
|
15 |
|
|
16 |
const ( |
|
17 |
// Pattern for detecting valid line format |
|
18 |
linePattern = `\A\s*(?:export\s+)?([\w\.]+)(?:\s*=\s*|:\s+?)('(?:\'|[^'])*'|"(?:\"|[^"])*"|[^#\n]+)?\s*(?:\s*\#.*)?\z` |
|
19 |
|
|
20 |
// Pattern for detecting valid variable within a value |
|
21 |
variablePattern = `(\\)?(\$)(\{?([A-Z0-9_]+)?\}?)` |
260
|
22 |
|
|
23 |
// Byte order mark character |
|
24 |
bom = "\xef\xbb\xbf" |
251
|
25 |
) |
|
26 |
|
|
27 |
// Env holds key/value pair of valid environment variable |
|
28 |
type Env map[string]string |
|
29 |
|
260
|
30 |
// 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. |
|
31 |
// When it's called with no argument, it will load `.env` file on the current path and set the environment variables. |
|
32 |
// Otherwise, it will loop over the filenames parameter and set the proper environment variables. |
251
|
33 |
func Load(filenames ...string) error { |
|
34 |
return loadenv(false, filenames...) |
|
35 |
} |
|
36 |
|
260
|
37 |
// OverLoad is a function to load a file or multiple files and then export and override the valid variables into environment variables. |
251
|
38 |
func OverLoad(filenames ...string) error { |
|
39 |
return loadenv(true, filenames...) |
|
40 |
} |
|
41 |
|
260
|
42 |
// Must is wrapper function that will panic when supplied function returns an error. |
251
|
43 |
func Must(fn func(filenames ...string) error, filenames ...string) { |
|
44 |
if err := fn(filenames...); err != nil { |
|
45 |
panic(err.Error()) |
|
46 |
} |
|
47 |
} |
|
48 |
|
260
|
49 |
// Apply is a function to load an io Reader then export the valid variables into environment variables if they do not exist. |
251
|
50 |
func Apply(r io.Reader) error { |
|
51 |
return parset(r, false) |
|
52 |
} |
|
53 |
|
260
|
54 |
// OverApply is a function to load an io Reader then export and override the valid variables into environment variables. |
251
|
55 |
func OverApply(r io.Reader) error { |
|
56 |
return parset(r, true) |
|
57 |
} |
|
58 |
|
|
59 |
func loadenv(override bool, filenames ...string) error { |
|
60 |
if len(filenames) == 0 { |
|
61 |
filenames = []string{".env"} |
|
62 |
} |
|
63 |
|
|
64 |
for _, filename := range filenames { |
|
65 |
f, err := os.Open(filename) |
|
66 |
if err != nil { |
|
67 |
return err |
|
68 |
} |
|
69 |
|
|
70 |
err = parset(f, override) |
260
|
71 |
f.Close() |
251
|
72 |
if err != nil { |
|
73 |
return err |
|
74 |
} |
|
75 |
} |
|
76 |
|
|
77 |
return nil |
|
78 |
} |
|
79 |
|
|
80 |
// parse and set :) |
|
81 |
func parset(r io.Reader, override bool) error { |
260
|
82 |
env, err := strictParse(r, override) |
251
|
83 |
if err != nil { |
|
84 |
return err |
|
85 |
} |
|
86 |
|
|
87 |
for key, val := range env { |
|
88 |
setenv(key, val, override) |
|
89 |
} |
|
90 |
|
|
91 |
return nil |
|
92 |
} |
|
93 |
|
|
94 |
func setenv(key, val string, override bool) { |
|
95 |
if override { |
|
96 |
os.Setenv(key, val) |
|
97 |
} else { |
|
98 |
if _, present := os.LookupEnv(key); !present { |
|
99 |
os.Setenv(key, val) |
|
100 |
} |
|
101 |
} |
|
102 |
} |
|
103 |
|
|
104 |
// Parse is a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables. |
|
105 |
// It expands the value of a variable from the environment variable but does not set the value to the environment itself. |
|
106 |
// This function is skipping any invalid lines and only processing the valid one. |
|
107 |
func Parse(r io.Reader) Env { |
260
|
108 |
env, _ := strictParse(r, false) |
251
|
109 |
return env |
|
110 |
} |
|
111 |
|
|
112 |
// StrictParse is a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables. |
|
113 |
// It expands the value of a variable from the environment variable but does not set the value to the environment itself. |
|
114 |
// This function is returning an error if there are any invalid lines. |
|
115 |
func StrictParse(r io.Reader) (Env, error) { |
260
|
116 |
return strictParse(r, false) |
|
117 |
} |
|
118 |
|
|
119 |
// Read is a function to parse a file line by line and returns the valid Env key/value pair of valid variables. |
|
120 |
// It expands the value of a variable from the environment variable but does not set the value to the environment itself. |
|
121 |
// This function is skipping any invalid lines and only processing the valid one. |
|
122 |
func Read(filename string) (Env, error) { |
|
123 |
f, err := os.Open(filename) |
|
124 |
if err != nil { |
|
125 |
return nil, err |
|
126 |
} |
|
127 |
defer f.Close() |
|
128 |
return strictParse(f, false) |
|
129 |
} |
|
130 |
|
|
131 |
// Unmarshal reads a string line by line and returns the valid Env key/value pair of valid variables. |
|
132 |
// It expands the value of a variable from the environment variable but does not set the value to the environment itself. |
|
133 |
// This function is returning an error if there are any invalid lines. |
|
134 |
func Unmarshal(str string) (Env, error) { |
|
135 |
return strictParse(strings.NewReader(str), false) |
|
136 |
} |
|
137 |
|
|
138 |
// Marshal outputs the given environment as a env file. |
|
139 |
// Variables will be sorted by name. |
|
140 |
func Marshal(env Env) (string, error) { |
|
141 |
lines := make([]string, 0, len(env)) |
|
142 |
for k, v := range env { |
|
143 |
if d, err := strconv.Atoi(v); err == nil { |
|
144 |
lines = append(lines, fmt.Sprintf(`%s=%d`, k, d)) |
|
145 |
} else { |
|
146 |
lines = append(lines, fmt.Sprintf(`%s=%q`, k, v)) |
|
147 |
} |
|
148 |
} |
|
149 |
sort.Strings(lines) |
|
150 |
return strings.Join(lines, "\n"), nil |
|
151 |
} |
|
152 |
|
|
153 |
// Write serializes the given environment and writes it to a file |
|
154 |
func Write(env Env, filename string) error { |
|
155 |
content, err := Marshal(env) |
|
156 |
if err != nil { |
|
157 |
return err |
|
158 |
} |
|
159 |
// ensure the path exists |
|
160 |
if err := os.MkdirAll(filepath.Dir(filename), 0o775); err != nil { |
|
161 |
return err |
|
162 |
} |
|
163 |
// create or truncate the file |
|
164 |
file, err := os.Create(filename) |
|
165 |
if err != nil { |
|
166 |
return err |
|
167 |
} |
|
168 |
defer file.Close() |
|
169 |
_, err = file.WriteString(content + "\n") |
|
170 |
if err != nil { |
|
171 |
return err |
|
172 |
} |
|
173 |
|
|
174 |
return file.Sync() |
|
175 |
} |
|
176 |
|
|
177 |
func strictParse(r io.Reader, override bool) (Env, error) { |
251
|
178 |
env := make(Env) |
|
179 |
scanner := bufio.NewScanner(r) |
|
180 |
|
260
|
181 |
firstLine := true |
251
|
182 |
|
|
183 |
for scanner.Scan() { |
260
|
184 |
line := strings.TrimSpace(scanner.Text()) |
251
|
185 |
|
260
|
186 |
if firstLine { |
251
|
187 |
line = strings.TrimPrefix(line, bom) |
260
|
188 |
firstLine = false |
|
189 |
} |
|
190 |
|
|
191 |
if line == "" || line[0] == '#' { |
|
192 |
continue |
251
|
193 |
} |
|
194 |
|
260
|
195 |
quote := "" |
|
196 |
// look for the delimiter character |
|
197 |
idx := strings.Index(line, "=") |
|
198 |
if idx == -1 { |
|
199 |
idx = strings.Index(line, ":") |
|
200 |
} |
|
201 |
// look for a quote character |
|
202 |
if idx > 0 && idx < len(line)-1 { |
|
203 |
val := strings.TrimSpace(line[idx+1:]) |
|
204 |
if val[0] == '"' || val[0] == '\'' { |
|
205 |
quote = val[:1] |
|
206 |
// look for the closing quote character within the same line |
|
207 |
idx = strings.LastIndex(strings.TrimSpace(val[1:]), quote) |
|
208 |
if idx >= 0 && val[idx] != '\\' { |
|
209 |
quote = "" |
|
210 |
} |
|
211 |
} |
|
212 |
} |
|
213 |
// look for the closing quote character |
|
214 |
for quote != "" && scanner.Scan() { |
|
215 |
l := scanner.Text() |
|
216 |
line += "\n" + l |
|
217 |
idx := strings.LastIndex(l, quote) |
|
218 |
if idx > 0 && l[idx-1] == '\\' { |
|
219 |
// foud a matching quote character but it's escaped |
|
220 |
continue |
|
221 |
} |
|
222 |
if idx >= 0 { |
|
223 |
// foud a matching quote |
|
224 |
quote = "" |
|
225 |
} |
|
226 |
} |
251
|
227 |
|
260
|
228 |
if quote != "" { |
|
229 |
return env, fmt.Errorf("missing quotes") |
|
230 |
} |
|
231 |
|
|
232 |
err := parseLine(line, env, override) |
251
|
233 |
if err != nil { |
|
234 |
return env, err |
|
235 |
} |
|
236 |
} |
|
237 |
|
|
238 |
return env, nil |
|
239 |
} |
|
240 |
|
260
|
241 |
var ( |
|
242 |
lineRgx = regexp.MustCompile(linePattern) |
|
243 |
unescapeRgx = regexp.MustCompile(`\\([^$])`) |
|
244 |
varRgx = regexp.MustCompile(variablePattern) |
|
245 |
) |
|
246 |
|
|
247 |
func parseLine(s string, env Env, override bool) error { |
|
248 |
rm := lineRgx.FindStringSubmatch(s) |
251
|
249 |
|
|
250 |
if len(rm) == 0 { |
|
251 |
return checkFormat(s, env) |
|
252 |
} |
|
253 |
|
260
|
254 |
key := strings.TrimSpace(rm[1]) |
|
255 |
val := strings.TrimSpace(rm[2]) |
251
|
256 |
|
260
|
257 |
var hsq, hdq bool |
251
|
258 |
|
260
|
259 |
// check if the value is quoted |
|
260 |
if l := len(val); l >= 2 { |
|
261 |
l -= 1 |
|
262 |
// has double quotes |
|
263 |
hdq = val[0] == '"' && val[l] == '"' |
|
264 |
// has single quotes |
|
265 |
hsq = val[0] == '\'' && val[l] == '\'' |
251
|
266 |
|
260
|
267 |
// remove quotes '' or "" |
|
268 |
if hsq || hdq { |
|
269 |
val = val[1:l] |
|
270 |
} |
|
271 |
} |
251
|
272 |
|
|
273 |
if hdq { |
260
|
274 |
val = strings.ReplaceAll(val, `\n`, "\n") |
|
275 |
val = strings.ReplaceAll(val, `\r`, "\r") |
251
|
276 |
|
|
277 |
// Unescape all characters except $ so variables can be escaped properly |
260
|
278 |
val = unescapeRgx.ReplaceAllString(val, "$1") |
251
|
279 |
} |
|
280 |
|
260
|
281 |
if !hsq { |
|
282 |
fv := func(s string) string { |
|
283 |
return varReplacement(s, hsq, env, override) |
|
284 |
} |
|
285 |
val = varRgx.ReplaceAllStringFunc(val, fv) |
|
286 |
val = parseVal(val, env, hdq, override) |
251
|
287 |
} |
|
288 |
|
|
289 |
env[key] = val |
|
290 |
return nil |
|
291 |
} |
|
292 |
|
|
293 |
func parseExport(st string, env Env) error { |
|
294 |
if strings.HasPrefix(st, "export") { |
|
295 |
vs := strings.SplitN(st, " ", 2) |
|
296 |
|
|
297 |
if len(vs) > 1 { |
|
298 |
if _, ok := env[vs[1]]; !ok { |
|
299 |
return fmt.Errorf("line `%s` has an unset variable", st) |
|
300 |
} |
|
301 |
} |
|
302 |
} |
|
303 |
|
|
304 |
return nil |
|
305 |
} |
|
306 |
|
260
|
307 |
var varNameRgx = regexp.MustCompile(`(\$)(\{?([A-Z0-9_]+)\}?)`) |
|
308 |
|
|
309 |
func varReplacement(s string, hsq bool, env Env, override bool) string { |
|
310 |
if s == "" { |
|
311 |
return s |
|
312 |
} |
|
313 |
|
|
314 |
if s[0] == '\\' { |
|
315 |
// the dollar sign is escaped |
|
316 |
return s[1:] |
251
|
317 |
} |
|
318 |
|
|
319 |
if hsq { |
|
320 |
return s |
|
321 |
} |
|
322 |
|
260
|
323 |
mn := varNameRgx.FindStringSubmatch(s) |
251
|
324 |
|
|
325 |
if len(mn) == 0 { |
|
326 |
return s |
|
327 |
} |
|
328 |
|
|
329 |
v := mn[3] |
|
330 |
|
260
|
331 |
if replace, ok := os.LookupEnv(v); ok && !override { |
|
332 |
return replace |
251
|
333 |
} |
|
334 |
|
260
|
335 |
if replace, ok := env[v]; ok { |
|
336 |
return replace |
|
337 |
} |
|
338 |
|
|
339 |
return os.Getenv(v) |
251
|
340 |
} |
|
341 |
|
|
342 |
func checkFormat(s string, env Env) error { |
|
343 |
st := strings.TrimSpace(s) |
|
344 |
|
260
|
345 |
if st == "" || st[0] == '#' { |
251
|
346 |
return nil |
|
347 |
} |
|
348 |
|
|
349 |
if err := parseExport(st, env); err != nil { |
|
350 |
return err |
|
351 |
} |
|
352 |
|
|
353 |
return fmt.Errorf("line `%s` doesn't match format", s) |
|
354 |
} |
|
355 |
|
260
|
356 |
func parseVal(val string, env Env, ignoreNewlines bool, override bool) string { |
|
357 |
if strings.Contains(val, "=") && !ignoreNewlines { |
|
358 |
kv := strings.Split(val, "\r") |
251
|
359 |
|
260
|
360 |
if len(kv) > 1 { |
|
361 |
val = kv[0] |
|
362 |
for _, l := range kv[1:] { |
|
363 |
_ = parseLine(l, env, override) |
251
|
364 |
} |
|
365 |
} |
|
366 |
} |
|
367 |
|
|
368 |
return val |
|
369 |
} |