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