/
field.go
236 lines (197 loc) · 4.6 KB
/
field.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package env
import (
"encoding/hex"
"errors"
"fmt"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/simia-tech/env/v3/internal/parser"
)
var (
ErrMissingValue = errors.New("missing value")
ErrInvalidValue = errors.New("invalid value")
)
type FieldType interface {
bool | []byte | time.Duration | int | string | []string | map[string]string
}
type F[T FieldType] struct {
name string
location string
defaultValue T
options options
}
var nameRegexp = regexp.MustCompile("^[A-Z0-9_]+$")
func Field[T FieldType](name string, defaultValue T, opts ...Option) *F[T] {
if !nameRegexp.MatchString(name) {
panic(fmt.Sprintf("field name [%s] must only contain capital letters, numbers or underscores", name))
}
_, filename, line, _ := runtime.Caller(1)
f := &F[T]{
name: name,
location: fmt.Sprintf("%s:%d", filename, line),
defaultValue: defaultValue,
options: newOptions(opts),
}
registerField(f)
return f
}
func (f *F[T]) Name() string {
return f.name
}
func (f *F[T]) Description() string {
if f.options.description != "" {
return f.options.description
}
sentences := []string{label[T]() + " field."}
if f.options.required {
sentences = append(sentences, "Required field.")
}
if f.options.allowedValues != nil {
sentences = append(sentences, fmt.Sprintf("Allowed values are %s.", joinStringValues(f.options.allowedValues)))
}
sentences = append(sentences, "The default value is '"+formatValue[T](f.defaultValue)+"'.")
sentences = append(sentences, "Defined at "+f.location+".")
return strings.Join(sentences, " ")
}
func (f *F[T]) GetRaw() (string, error) {
text, ok := os.LookupEnv(f.name)
if !ok {
if f.options.required {
return formatValue[T](f.defaultValue), fmt.Errorf("field [%s]: %w", f.name, ErrMissingValue)
}
return formatValue[T](f.defaultValue), nil
}
text = strings.TrimSpace(text)
if !f.options.isAllowedValue(text) {
return formatValue[T](f.defaultValue), fmt.Errorf("field [%s]: value [%s]: %w", f.name, text, ErrInvalidValue)
}
return text, nil
}
func (f *F[T]) GetRawOrDefault() string {
value, _ := f.GetRaw()
return value
}
func (f *F[T]) MustGetRaw() string {
value, err := f.GetRaw()
if err != nil {
panic(err)
}
return value
}
func (f *F[T]) Get() (T, error) {
raw, err := f.GetRaw()
if err != nil {
return f.defaultValue, err
}
result, err := parseValue[T](raw)
if err != nil {
return f.defaultValue, fmt.Errorf("field [%s]: %w", f.name, err)
}
return result, nil
}
func (f *F[T]) GetOrDefault() T {
value, _ := f.Get()
return value
}
func (f *F[T]) MustGet() T {
value, err := f.Get()
if err != nil {
panic(err)
}
return value
}
func label[T FieldType]() string {
switch any(*new(T)).(type) {
case bool:
return "Boolean"
case []byte:
return "Bytes"
case time.Duration:
return "Duration"
case int:
return "Int"
case string:
return "String"
case []string:
return "StringArray"
case map[string]string:
return "StringStringMap"
default:
return "Unknown"
}
}
func parseValue[T FieldType](raw string) (T, error) {
value := *new(T)
result := any(nil)
switch any(value).(type) {
case bool:
switch raw {
case "1", "true", "yes":
result = true
case "0", "false", "no":
result = false
default:
return value, fmt.Errorf("parse bool [%s]: %w", raw, ErrInvalidValue)
}
case []byte:
v, err := hex.DecodeString(raw)
if err != nil {
return value, fmt.Errorf("parse hex [%s]: %w", raw, ErrInvalidValue)
}
result = v
case time.Duration:
v, err := time.ParseDuration(raw)
if err != nil {
return value, fmt.Errorf("parse duration [%s]: %w", raw, ErrInvalidValue)
}
result = v
case int:
v, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return value, fmt.Errorf("parse int [%s]: %w", raw, ErrInvalidValue)
}
result = int(v)
case string:
result = raw
case []string:
v, err := parser.ParseStrings(raw)
if err != nil {
return value, fmt.Errorf("parse string array [%s]: %w", raw, err)
}
result = v
case map[string]string:
m, err := parser.ParseStringMap(raw)
if err != nil {
return value, fmt.Errorf("parse string map [%s]: %w", raw, err)
}
result = m
}
return result.(T), nil
}
func formatValue[T FieldType](value T) string {
switch t := any(value).(type) {
case bool:
if t {
return "true"
}
return "false"
case []byte:
return hex.EncodeToString(t)
case time.Duration:
return t.String()
case int:
return strconv.FormatInt(int64(t), 10)
case string:
return t
case []string:
return parser.FormatStrings(t)
case map[string]string:
return parser.FormatStringMap(t)
default:
return ""
}
}