-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
98 lines (73 loc) · 1.95 KB
/
options.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
package call
import (
"fmt"
"reflect"
"strings"
"sync"
)
// Options is enable to modify arguments when calling functions.
//
// Use options like this first value name after that `:` seperated and pass option arguments with `=`.
//
// `hababam:option1=1,2,3;option2=value2`.
type Options struct {
option map[string]func([]reflect.Value, ...string) ([]reflect.Value, error)
mutex sync.RWMutex
}
var _ Option = (*Options)(nil)
func NewOptions() Option {
return &Options{
option: make(map[string]func([]reflect.Value, ...string) ([]reflect.Value, error)),
}
}
// GetDelimeter returns delimeter for options.
func (o *Options) GetDelimeter() string {
return ":"
}
// ParseOptions parses options from string with delimeter.
func (o *Options) ParseOption(name string) []string {
o.mutex.RLock()
defer o.mutex.RUnlock()
sName := strings.SplitN(name, ":", 2)
if len(sName) == 1 {
return nil
}
return strings.Split(sName[1], ";")
}
func (o *Options) AddOption(name string, fn func([]reflect.Value, ...string) ([]reflect.Value, error)) Option {
o.mutex.Lock()
defer o.mutex.Unlock()
o.option[name] = fn
return o
}
func (o *Options) GetOption(name string) (func([]reflect.Value, ...string) ([]reflect.Value, error), bool) {
o.mutex.RLock()
defer o.mutex.RUnlock()
fn, ok := o.option[name]
return fn, ok
}
func (o *Options) VisitOptions(arg string, v any) ([]reflect.Value, error) {
var err error
vValue := []reflect.Value{reflect.ValueOf(v)}
options := o.ParseOption(arg)
for _, option := range options {
opt := strings.SplitN(option, "=", 2)
optName := opt[0]
var optVariables []string
if len(opt) > 1 {
optVariables = strings.Split(opt[1], ",")
}
optionFn, ok := o.GetOption(optName)
if !ok {
return nil, fmt.Errorf("option %s not found", optName)
}
vValue, err = optionFn(vValue, optVariables...)
if err != nil {
return nil, fmt.Errorf("%s; %w", optName, err)
}
if vValue == nil {
break
}
}
return vValue, nil
}