-
Notifications
You must be signed in to change notification settings - Fork 0
/
with.go
47 lines (40 loc) · 973 Bytes
/
with.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
// SPDX-License-Identifier: MIT
package with
import (
"fmt"
"reflect"
"runtime"
"strings"
)
type Defaulted interface {
SetDefaults()
}
type Validated interface {
Validate() error
}
type Func[O any] func(options *O) (err error)
func Nop[O any]() Func[O] {
return func(options *O) error {
return nil
}
}
func DefaultThenAddWith[O any](options *O, withOptions []Func[O]) (err error) {
if i, ok := any(options).(Defaulted); ok {
i.SetDefaults()
}
return AddWith(options, withOptions)
}
func AddWith[O any](options *O, withOptions []Func[O]) (err error) {
for _, option := range withOptions {
if err = option(options); err != nil {
frame, _ := runtime.CallersFrames([]uintptr{reflect.ValueOf(option).Pointer()}).Next()
withNames := strings.Split(frame.Function, ".")
err = fmt.Errorf("cannot apply %v: %w", withNames[len(withNames)-2], err)
return
}
}
if v, ok := interface{}(options).(Validated); ok {
err = v.Validate()
}
return
}