-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathoption.go
85 lines (69 loc) · 1.62 KB
/
option.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
package seed
import (
"reflect"
)
//Option can be used to modify a seed.
type Option interface {
AddTo(Seed)
}
//Options is a multiple of Option.
type Options []Option
//AddTo implements Option, Options are a type of Option.
func (options Options) AddTo(c Seed) {
for _, o := range options {
if o != nil {
o.AddTo(c)
}
}
}
//OptionFunc can be used to create an Option.
type OptionFunc func(c Seed)
//NewOption can be used to create options.
type NewOption = OptionFunc
//AddTo implements Option.AddTo
func (o OptionFunc) AddTo(c Seed) {
o(c)
}
//And implements Option.And
func (o OptionFunc) And(more ...Option) Option {
return And(o, more...)
}
//And implements Option.And
func And(o Option, more ...Option) Option {
return NewOption(func(c Seed) {
o.AddTo(c)
for _, o = range more {
o.AddTo(c)
}
})
}
//If applies the options if the condition is true.
func If(condition bool, options ...Option) Option {
return NewOption(func(c Seed) {
if condition {
for _, o := range options {
o.AddTo(c)
}
}
})
}
//Mutate a seed with the given data.
//panics on illegal arguments.
func Mutate(f interface{}) Option {
T := reflect.TypeOf(f)
if T.Kind() != reflect.Func || T.In(0).Kind() != reflect.Ptr || T.NumIn() > 2 ||
(T.NumIn() == 2 && T.In(1) != reflect.TypeOf(Seed{})) {
panic("illegal argument to seed.Mutate")
}
V := reflect.ValueOf(f)
data := reflect.New(T.In(0).Elem())
return NewOption(func(c Seed) {
c.Load(data.Interface())
if T.NumIn() == 2 {
V.Call([]reflect.Value{data, reflect.ValueOf(c)})
} else {
V.Call([]reflect.Value{data})
}
c.Save(data.Elem().Interface())
})
}