-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
67 lines (57 loc) · 1.42 KB
/
Copy pathparser.go
File metadata and controls
67 lines (57 loc) · 1.42 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
package dotenv
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
type pair struct {
k string
v string
}
// Parse reads every line from r, empty lines and lines that starts with '#' are discarded.
//
// Value should not contain line breaks or quotes, all characters after the
// first equal sign up to the line break are considered. Values are not expanded.
func Parse(r io.Reader) (map[string]string, error) {
pairs, err := parse(r)
if err != nil {
return nil, err
}
kv := make(map[string]string, len(pairs))
for _, pair := range pairs {
kv[pair.k] = pair.v
}
return kv, nil
}
func parseFile(path string) (pairs []pair, err error) {
path = filepath.FromSlash(path)
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("dotenv: opening %q file: %w", path, err)
}
defer func() { err = file.Close() }()
pairs, err = parse(file)
if err != nil {
return nil, fmt.Errorf("dotenv: parsing %q file: %w", path, err)
}
return pairs, err
}
func parse(r io.Reader) ([]pair, error) {
scanner := bufio.NewScanner(r)
pairs := make([]pair, 0)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 || line[0] == '#' {
continue
}
k, v, ok := strings.Cut(line, "=")
if !ok {
return nil, fmt.Errorf("dotenv: invalid line %q: missing equal sign", line)
}
pairs = append(pairs, pair{strings.TrimSpace(k), strings.TrimSpace(v)})
}
return pairs, scanner.Err()
}