-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfg.go
179 lines (154 loc) · 3.65 KB
/
cfg.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
package conf
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/davidmdm/x/xerr"
)
type LookupFunc func(string) (string, bool)
type field struct {
value value
opts options
}
type Parser struct {
fields map[string]field
lookup LookupFunc
}
func MakeParser(funcs ...LookupFunc) Parser {
lookupFuncs := make([]LookupFunc, 0, len(funcs))
for _, fn := range funcs {
if fn == nil {
continue
}
lookupFuncs = append(lookupFuncs, fn)
}
lookup := os.LookupEnv
if len(lookupFuncs) > 0 {
lookup = joinLookupFuncs(lookupFuncs...)
}
return Parser{
fields: make(map[string]field),
lookup: lookup,
}
}
func (parser Parser) Parse() error {
errs := make([]error, 0, len(parser.fields))
for name, field := range parser.fields {
if err := func() (err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = fmt.Errorf("%v", recovered)
}
}()
text, ok := parser.lookup(name)
if ok && text == "" {
switch {
case field.opts.nonEmpty:
return fmt.Errorf("field is declared but empty: cannot be empty")
case field.opts.skipEmpty:
return
}
}
if !ok {
if field.opts.required {
return errors.New("field is required")
}
if field.opts.fallback != nil {
field.value.Set(field.opts.fallback)
}
return nil
}
return field.value.Parse(text)
}(); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", name, err))
}
}
return xerr.MultiErrOrderedFrom("failed to parse variable(s)", errs...)
}
// MustParse is like Parse but panics if an error occurs
func (parser Parser) MustParse() {
if err := parser.Parse(); err != nil {
panic(err)
}
}
func Var[T any](parser Parser, p *T, name string, opts ...Option[T]) {
var options options
for _, apply := range opts {
apply(&options)
}
parser.fields[name] = field{
value: genericValue[T]{p},
opts: options,
}
}
// CommandLineArgs returns a lookup function that will search the provided args for flags.
// Since we often want our EnvironmentVariable name declarations to be reusable for command line args
// the lookup is case-insensitive and all underscores are changes to dashes.
// For example, a variable mapped to DATABASE_URL can be found using the --database-url flag when working with CommandLineArgs.
func CommandLineArgs(args ...string) LookupFunc {
if len(args) == 0 {
args = os.Args[1:]
}
var (
m = map[string][]string{}
flag = ""
)
for _, arg := range args {
switch {
case strings.HasPrefix(arg, "-"):
if flag != "" && len(m[flag]) == 0 {
m[flag] = []string{"true"}
}
flag = strings.ToLower(strings.TrimLeft(arg, "-"))
if key, value, ok := strings.Cut(flag, "="); ok {
m[key] = append(m[key], value)
flag = ""
}
case flag == "":
// skip positional args
default:
m[flag] = append(m[flag], arg)
flag = ""
}
}
return func(name string) (string, bool) {
name = strings.ReplaceAll(strings.ToLower(name), "_", "-")
value, ok := m[name]
return strings.Join(value, ","), ok
}
}
type FileSystemOptions struct {
Base string
}
func FileSystem(opts FileSystemOptions) LookupFunc {
if opts.Base == "" {
opts.Base = "."
}
return func(path string) (string, bool) {
if !filepath.IsAbs(path) {
path = filepath.Join(opts.Base, path)
}
data, err := os.ReadFile(path)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
panic(err)
}
return "", false
}
return string(data), true
}
}
func joinLookupFuncs(fns ...LookupFunc) LookupFunc {
return func(key string) (value string, ok bool) {
for _, fn := range fns {
value, ok = fn(key)
if ok {
return
}
}
return
}
}
var Environ = MakeParser(os.LookupEnv)