-
Notifications
You must be signed in to change notification settings - Fork 2
/
load.go
62 lines (55 loc) · 1.17 KB
/
load.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
package dolores
import (
"bytes"
"fmt"
"os"
"time"
"github.com/rs/zerolog/log"
)
type Variable struct {
Key []byte
Value []byte
}
func (v Variable) Data() []byte {
res := append(v.Key, byte('=')) //nolint:gocritic
res = append(res, v.Value...)
res = append(res, byte('\n'))
return res
}
type EnvFile struct {
data []byte
Variables []Variable
CreatedAt time.Time
}
func (ef *EnvFile) Parse() error {
for i, line := range bytes.Split(ef.data, []byte("\n")) {
line = bytes.TrimSpace(line)
if line == nil {
continue
}
if line[0] == '#' {
log.Debug().Msgf("parsing comment: %s", line)
continue
}
split := bytes.Split(line, []byte("="))
if len(split) != 2 {
return fmt.Errorf("error parsing line: %d %w", i, ErrInvalidFormat)
}
ef.Variables = append(ef.Variables, Variable{Key: split[0], Value: split[1]})
}
return nil
}
func LoadEnvFile(fn string) (*EnvFile, error) {
data, err := os.ReadFile(fn)
if err != nil {
return nil, fmt.Errorf("failed to read file: %s %w", fn, err)
}
envFile := &EnvFile{
data: data,
CreatedAt: time.Now().UTC(),
}
if err := envFile.Parse(); err != nil {
return nil, err
}
return envFile, nil
}