generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvarset_optional.go
81 lines (70 loc) · 1.96 KB
/
varset_optional.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
package ferrite
import (
"github.com/dogmatiq/ferrite/internal/variable"
)
// Optional is a VariableSet used to obtain a value that may be unavailable, due
// to the environment variables not being defined.
type Optional[T any] interface {
VariableSet
// Value returns the parsed and validated value.
//
// It returns a non-nil error if any of one of the environment variables in
// the set has an invalid value.
//
// If the environment variable(s) are not defined and there is no default
// value, ok is false; otherwise, ok is true and v is the value.
Value() (T, bool)
}
// OptionalOption is an option that configures an "optional" variable set. It
// may be passed to the Optional() method on each of the "builder" types.
type OptionalOption interface {
applyOptionalOptionToConfig(*variableSetConfig)
applyOptionalOptionToSpec(variable.SpecBuilder)
}
// required registers a variable that produces a value of type T and returns a
// Optional[T] that maps one-to-one to that variable.
func optional[T any, Schema variable.TypedSchema[T]](
s Schema,
b *variable.TypedSpecBuilder[T],
options ...OptionalOption,
) Optional[T] {
var cfg variableSetConfig
for _, opt := range options {
opt.applyOptionalOptionToConfig(&cfg)
opt.applyOptionalOptionToSpec(b)
}
v := variable.Register(
cfg.Registries,
b.Done(s),
)
return optionalFunc[T]{
[]variable.Any{v},
func() (T, bool, error) {
return v.NativeValue(),
v.Availability() == variable.AvailabilityOK,
v.Error()
},
}
}
// optionalFunc is an implementation of Optional[T] that obtains the value from
// an arbitrary function.
type optionalFunc[T any] struct {
vars []variable.Any
fn func() (T, bool, error)
}
func (s optionalFunc[T]) Value() (T, bool) {
n, ok, err := s.fn()
if err != nil {
panic(err.Error())
}
return n, ok
}
func (s optionalFunc[T]) value() any {
if n, ok, _ := s.fn(); ok {
return n
}
return nil
}
func (s optionalFunc[T]) variables() []variable.Any {
return s.vars
}