This repository has been archived by the owner on Apr 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfg.go
153 lines (133 loc) · 3.17 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
package cfg
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
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 {
envvar, ok := parser.lookup(name)
if !ok && field.opts.required {
errs = append(errs, fmt.Errorf("%q is required but not found", name))
continue
}
if !ok {
field.value.Set(field.opts.fallback)
continue
}
if err := field.value.Parse(envvar); err != nil {
errs = append(errs, fmt.Errorf("failed to parse %s: %v", name, err))
continue
}
}
return errors.Join(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 ...Options[T]) {
parser.fields[name] = field{
value: genericValue[T]{p},
opts: multiOpts[T](opts).toOptions(),
}
}
// 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
}
}