-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathparsedotenv.go
165 lines (126 loc) · 3.63 KB
/
parsedotenv.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
package meli
/*
The functionality/code in this file is taken from: https://github.com/subosito/gotenv
Which is released by the author; Alif Rachmawadi(subosito) under MIT license.
*/
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/pkg/errors"
)
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_]+)?\}?)`
)
// env holds key/value pair of valid environment variable
// TODO: replace env with a []string since ComposeService.Environment is a []string
type env map[string]string
// parsedotenv 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 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 parsedotenv(r io.Reader) env {
e, _ := strictParse(r)
return e
}
// 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 environment variable, but does not set the value to the environment itself.
// This function is returning an error if there is any invalid lines.
func strictParse(r io.Reader) (env, error) {
e := make(env)
scanner := bufio.NewScanner(r)
i := 1
bom := string([]byte{239, 187, 191})
for scanner.Scan() {
line := scanner.Text()
if i == 1 {
line = strings.TrimPrefix(line, bom)
}
i++
err := parseLine(line, e)
if err != nil {
return e, err
}
}
return e, nil
}
func parseLine(s string, env env) error {
rl := regexp.MustCompile(linePattern)
rm := rl.FindStringSubmatch(s)
if len(rm) == 0 {
st := strings.TrimSpace(s)
if (st == "") || strings.HasPrefix(st, "#") {
return nil
}
if strings.HasPrefix(st, "export") {
vs := strings.SplitN(st, " ", 2)
if len(vs) > 1 {
if _, ok := env[vs[1]]; !ok {
return errors.New(fmt.Sprintf("Line `%s` has an unset variable", st))
}
}
}
return errors.New(fmt.Sprintf("Line `%s` doesn't match format", s))
}
key := rm[1]
val := rm[2]
// determine if string has quote prefix
hdq := strings.HasPrefix(val, `"`)
// determine if string has single quote prefix
hsq := strings.HasPrefix(val, `'`)
// trim whitespace
val = strings.Trim(val, " ")
// remove quotes '' or ""
rq := regexp.MustCompile(`\A(['"])(.*)(['"])\z`)
val = rq.ReplaceAllString(val, "$2")
if hdq {
val = strings.Replace(val, `\n`, "\n", -1)
val = strings.Replace(val, `\r`, "\r", -1)
// Unescape all characters except $ so variables can be escaped properly
re := regexp.MustCompile(`\\([^$])`)
val = re.ReplaceAllString(val, "$1")
}
rv := regexp.MustCompile(variablePattern)
fv := func(s string) string {
if strings.HasPrefix(s, "\\") {
return strings.TrimPrefix(s, "\\")
}
if hsq {
return s
}
sn := `(\$)(\{?([A-Z0-9_]+)\}?)`
rn := regexp.MustCompile(sn)
mn := rn.FindStringSubmatch(s)
if len(mn) == 0 {
return s
}
v := mn[3]
replace, ok := env[v]
if !ok {
replace = os.Getenv(v)
}
return replace
}
val = rv.ReplaceAllStringFunc(val, fv)
if strings.Contains(val, "=") {
if !(val == "\n" || val == "\r") {
kv := strings.Split(val, "\n")
if len(kv) == 1 {
kv = strings.Split(val, "\r")
}
if len(kv) > 1 {
val = kv[0]
for i := 1; i < len(kv); i++ {
parseLine(kv[i], env)
}
}
}
}
env[key] = val
return nil
}