-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrules.go
89 lines (73 loc) · 2.41 KB
/
rules.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
package rule
import (
"errors"
"gopkg.in/vinxi/vinxi.v0/config"
)
// ErrRuleNotFound is used when a rule does not exists.
var ErrRuleNotFound = errors.New("vinxi: rule does not exists")
// Rules is used to store the existent rules globally.
var Rules = make(map[string]Info)
// Factory represents the rule factory function interface.
type Factory func(config.Config) (Matcher, error)
// NewFunc represents the Rule constructor factory function interface.
type NewFunc func(config.Config) (Rule, error)
// Validator represents the rule config field validator function interface.
type Validator func(interface{}, config.Config) error
// Info represents the rule entity fields
// storing the name, description and factory function
// used to initialize the fields.
type Info struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Params Params `json:"params,omitempty"`
Factory Factory `json:"-"`
}
// Params represents the list of supported config fields by rules.
type Params []Field
// Field is used to declare specific config fields supported by rules.
type Field struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
Mandatory bool `json:"mandatory,omitempty"`
Examples []string `json:"examples,omitempty"`
Default interface{} `json:"default,omitempty"`
Validator Validator `json:"-"`
}
// Register registers the given rule in the current store.
func Register(rule Info) {
Rules[rule.Name] = rule
}
// Init is used to initialize a new rule by name identifier
// based on the given config options.
func Init(name string, opts config.Config) (Rule, error) {
if !Exists(name) {
return nil, ErrRuleNotFound
}
return NewWithConfig(Rules[name], opts)
}
// Get is used to find and retrieve a rule factory function.
func Get(name string) NewFunc {
rule, ok := Rules[name]
if ok {
return New(rule)
}
return nil
}
// GetFactory is used to find and retrieve a rule factory function.
func GetFactory(name string) Factory {
rule, ok := Rules[name]
if ok {
return rule.Factory
}
return nil
}
// GetInfo is used to find and retrieve a rule info struct, if exists.
func GetInfo(name string) Info {
return Rules[name]
}
// Exists is used to check if a given rule name exists.
func Exists(name string) bool {
_, ok := Rules[name]
return ok
}