-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdotenv.go
More file actions
153 lines (124 loc) · 3.41 KB
/
Copy pathdotenv.go
File metadata and controls
153 lines (124 loc) · 3.41 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
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
// Package dotenv provides simple utilities to load environment variables from local files.
package dotenv
import (
"errors"
"fmt"
"os"
"reflect"
"strings"
)
// FilenameVariables defines the default files the package searches for.
var FilenameVariables = []string{".env", ".env.local"}
// Collect iterates through the predefined filenames in FilenameVariables,
// parses their content, and sets the resulting key-value pairs as
// environment variables in the current process.
//
// It supports:
// - Standard KEY=VALUE pairs.
// - Lines starting with "export ".
// - Comments starting with "#".
// - Basic handling of quoted values (via the internal quotes function).
func Collect() {
for _, filename := range FilenameVariables {
content, err := os.ReadFile(filename)
if err != nil {
continue
}
if len(content) <= 1 {
continue
}
for _, line := range strings.Split(string(content), "\n") {
if strings.HasPrefix(line, "export ") {
line = strings.TrimPrefix(line, "export")
line = strings.TrimSpace(line)
}
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, found := strings.Cut(line, "=")
if !found {
continue
}
value = quotes(value)
os.Setenv(key, value)
}
}
}
// Unmarshal parses environment variables into the provided struct.
// The struct must have 'env' tags defining which variables to map.
func Unmarshal(dest interface{}) error {
rv := reflect.ValueOf(dest)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.New("dest must be a non-nil pointer")
}
rv = rv.Elem()
if rv.Kind() != reflect.Struct {
return errors.New("dest must be a pointer to a struct")
}
t := rv.Type()
for i := 0; i < rv.NumField(); i++ {
field := rv.Field(i)
fieldType := t.Field(i)
if !field.CanSet() {
continue
}
key := fieldType.Tag.Get("env")
required := fieldType.Tag.Get("required") == "true"
defaultValue := fieldType.Tag.Get("default")
if key == "" {
continue
}
value, exists := os.LookupEnv(key)
if !exists || value == "" {
if defaultValue != "" {
value = defaultValue
} else if required {
return fmt.Errorf("error %s tag needs to be filled in", fieldType.Name)
} else {
continue
}
}
if err := setField(field, value); err != nil {
return fmt.Errorf("error setting field %s: %w", fieldType.Name, err)
}
}
return nil
}
// Marshal converts a struct into a .env formatted byte slice.
// It uses 'env' tags to define the keys.
func Marshal(dest interface{}) ([]byte, error) {
rv := reflect.ValueOf(dest)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return nil, errors.New("dest must be a struct or a pointer to a struct")
}
var builder strings.Builder
t := rv.Type()
for i := 0; i < rv.NumField(); i++ {
field := rv.Field(i)
fieldType := t.Field(i)
if !field.CanInterface() {
continue
}
key := fieldType.Tag.Get("env")
if key == "" {
continue
}
value := fmt.Sprintf("%v", field.Interface())
if value == "" {
defaultValue := fieldType.Tag.Get("default")
if defaultValue != "" {
value = defaultValue
} else if fieldType.Tag.Get("required") == "true" {
return nil, fmt.Errorf("env %s for field %s is required", key, fieldType.Name)
}
}
if strings.Contains(value, " ") {
value = fmt.Sprintf(`"%s"`, value)
}
builder.WriteString(fmt.Sprintf("%s=%s\n", key, value))
}
return []byte(builder.String()), nil
}