/
registry.go
89 lines (73 loc) · 2.25 KB
/
registry.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 action
import (
"sort"
"strings"
"sync"
)
type ActionRegistry struct {
m map[string]*Action
}
var (
defaultRegistry *ActionRegistry
registryOnce sync.Once
)
var all = []Action{
upperAction, lowerAction, titleAction, trimSpaceAction, quoteAction, unquoteAction,
md5HashAction, sha1HashAction, sha256HashAction, sha512HashAction,
toHexStringAction, fromHexStringAction, toBase64StringAction, fromBase64StringAction,
parseJSONDateStringAction, epochTimeAction,
estTimeAction, etTimeAction, utcTimeAction, isoTimeAction, timeEpochAction,
commaTextListAction, jwtTextListAction, textListJoinCommaAction, jsonCompactAction,
textListFirstAction, textListLastAction,
}
func DefaultRegistry() *ActionRegistry {
registryOnce.Do(func() {
defaultRegistry = NewRegistry()
})
return defaultRegistry
}
func NewRegistry() *ActionRegistry {
m := make(map[string]*Action)
r := &ActionRegistry{
m: m,
}
r.RegisterActions(all...)
return r
}
// RegisterActions registers multiple actions by their input format, names
func (r *ActionRegistry) RegisterActions(actions ...Action) {
for _, a := range actions {
r.RegisterAction(a)
}
}
// RegisterAction registers an action by its input , names
func (r *ActionRegistry) RegisterAction(a Action) {
for _, name := range a.Names {
key := a.InputFormat.Prefix + "," + name
r.m[key] = &a
}
}
// ActionsForText returns a list of actions, prefix by search, all if search is empty
// ordered alphabetically
func (r *ActionRegistry) ActionsForText(search string) (actions []*Action) {
for k, a := range r.m {
if strings.HasPrefix(k, textFormat.Prefix+",") {
actions = append(actions, a)
}
sort.Slice(actions, func(i, j int) bool { return actions[i].Names[0] < actions[j].Names[0] })
}
return
}
func (r *ActionRegistry) ActionsForData(data *Data) (actions []*Action) {
for k, a := range r.m {
if strings.HasPrefix(k, data.Format.Prefix+",") {
actions = append(actions, a)
}
// in case we have a textList we also want to apply text filter, that can output text
if data.Format == textListFormat && a.InputFormat == textFormat && a.OutputFormat == textFormat {
actions = append(actions, a)
}
sort.Slice(actions, func(i, j int) bool { return actions[i].Names[0] < actions[j].Names[0] })
}
return
}