-
Notifications
You must be signed in to change notification settings - Fork 176
/
env.go
72 lines (58 loc) · 1.18 KB
/
env.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
package main
import (
"fmt"
"os"
"regexp"
"github.com/subosito/gotenv"
)
var envEntryRegexp = regexp.MustCompile("^([A-Za-z_0-9]+)=(.*)$")
type Env map[string]string
type envFiles []string
func (e *envFiles) String() string {
return fmt.Sprintf("%s", *e)
}
func (e *envFiles) Set(value string) error {
*e = append(*e, value)
return nil
}
func loadEnvs(files []string) (Env, error) {
if len(files) == 0 {
files = []string{".env"}
}
env := make(Env)
for _, file := range files {
tmpEnv, err := ReadEnv(file)
if err != nil {
return nil, err
}
// Merge the file I just read into the env.
for k, v := range tmpEnv {
env[k] = v
}
}
return env, nil
}
func ReadEnv(filename string) (Env, error) {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return make(Env), nil
}
fd, err := os.Open(filename)
if err != nil {
return nil, err
}
defer fd.Close()
env := make(Env)
for key, val := range gotenv.Parse(fd) {
env[key] = val
}
return env, nil
}
func (e *Env) asArray() (env []string) {
for _, pair := range os.Environ() {
env = append(env, pair)
}
for name, val := range *e {
env = append(env, fmt.Sprintf("%s=%s", name, val))
}
return
}