-
Notifications
You must be signed in to change notification settings - Fork 5
/
readattr.go
238 lines (202 loc) · 6.24 KB
/
readattr.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package fir
import (
"bytes"
"fmt"
"regexp"
"strings"
"github.com/sourcegraph/conc/pool"
"golang.org/x/exp/slices"
"golang.org/x/net/html"
"k8s.io/klog/v2"
)
func readAttributes(fi fileInfo) fileInfo {
doc, err := html.Parse(bytes.NewReader(fi.content))
if err != nil {
panic(err)
}
attributes := firAttributes(doc)
resultPool := pool.NewWithResults[eventTemplates]()
for _, attr := range attributes {
attr := attr
resultPool.Go(func() eventTemplates {
return eventTemplatesFromAttr(attr)
})
}
evtArr := resultPool.Wait()
evt := make(eventTemplates)
for _, evtMap := range evtArr {
evt = deepMergeEventTemplates(evt, evtMap)
}
return fileInfo{
name: fi.name,
content: fi.content,
err: fi.err,
eventTemplates: evt,
}
}
func eventTemplatesFromAttr(attr html.Attribute) eventTemplates {
evt := make(eventTemplates)
eventns := strings.TrimPrefix(attr.Key, "@fir:")
eventns = strings.TrimPrefix(eventns, "x-on:fir:")
// eventns might have modifiers like .prevent, .stop, .self, .once, .window, .document etc. remove them
eventnsParts := strings.SplitN(eventns, ".", -1)
if len(eventnsParts) > 0 {
eventns = eventnsParts[0]
}
// eventns might have a filter:[e1:ok,e2:ok] containing multiple event:state separated by comma
eventnsList, _ := getEventNsList(eventns)
for _, eventns := range eventnsList {
eventns = strings.TrimSpace(eventns)
// set @fir|x-on:fir:eventns attribute to the node
// myevent:ok::myblock
eventnsParts = strings.SplitN(eventns, "::", -1)
if len(eventnsParts) == 0 {
continue
}
// [myevent:ok, myblock]
if len(eventnsParts) > 2 {
klog.Errorf(eventFormatError(eventns))
continue
}
// myevent:ok
eventID := eventnsParts[0]
// [myevent, ok]
eventIDParts := strings.SplitN(eventID, ":", -1)
if len(eventIDParts) != 2 {
klog.Errorf(eventFormatError(eventns))
continue
}
// event name can only be followed by ok, error, pending, done
if !slices.Contains([]string{"ok", "error", "pending", "done"}, eventIDParts[1]) {
klog.Errorf(eventFormatError(eventns))
continue
}
// assert myevent:ok::myblock or myevent:error::myblock
if len(eventnsParts) == 2 && !slices.Contains([]string{"ok", "error"}, eventIDParts[1]) {
klog.Errorf(eventFormatError(eventns))
continue
}
// template name is declared for event state i.e. myevent:ok::myblock
templateName := "-"
if len(eventnsParts) == 2 {
templateName = eventnsParts[1]
}
templates, ok := evt[eventID]
if !ok {
templates = make(eventTemplate)
}
if !templateNameRegex.MatchString(templateName) {
klog.Errorf("error: invalid template name in event binding: only hyphen(-) and colon(:) are allowed: %v\n", templateName)
continue
}
templates[templateName] = struct{}{}
// fmt.Printf("eventID: %s, templateName: %s\n", eventID, templateName)
evt[eventID] = templates
}
return evt
}
// checks if the event string is of the format [event1:ok,event2:ok]:tmpl1 and returns the unbundled list of event strings
// event1:ok:tmpl1,event2:ok:tmpl1. if not, returns original event string
func getEventNsList(input string) ([]string, bool) {
ef, err := getEventFilter(input)
if err != nil {
klog.Warningf("error parsing event filter: %v", err)
return []string{input}, false
}
if ef == nil {
return []string{input}, false
}
if len(ef.Values) == 0 {
return []string{input}, false
}
var eventnsList []string
for _, v := range ef.Values {
eventnsList = append(eventnsList, ef.BeforeBracket+v+ef.AfterBracket)
}
return eventnsList, true
}
var ErrorEventFilterFormat = fmt.Errorf("error parsing event filter. must match ^[a-zA-Z0-9-]+:(ok|pending|error|done)$")
type eventFilter struct {
BeforeBracket string
Values []string
AfterBracket string
}
func getEventFilter(input string) (*eventFilter, error) {
// Extract the part of the string before the open square bracket
beforeRe := regexp.MustCompile(`^(.*?)\[`)
beforeMatch := beforeRe.FindStringSubmatch(input)
var beforeBracket string
if len(beforeMatch) == 2 {
beforeBracket = beforeMatch[1]
}
// Extract the part of the string after the closed square bracket
afterRe := regexp.MustCompile(`\](.*)$`)
afterMatch := afterRe.FindStringSubmatch(input)
var afterBracket string
if len(afterMatch) == 2 {
afterBracket = afterMatch[1]
}
// Extract the contents of a closed square bracket
re := regexp.MustCompile(`\[(.*?)\]`)
matches := re.FindStringSubmatch(input)
if len(matches) < 2 {
return nil, nil
}
// Remove whitespace and split the contents by comma
contents := strings.ReplaceAll(matches[1], " ", "")
values := strings.Split(contents, ",")
// Validate and format each value
validValues := make([]string, 0)
for _, value := range values {
if !isValidValue(value) {
return nil, ErrorEventFilterFormat
}
validValues = append(validValues, formatValue(value))
}
extractedValues := &eventFilter{
BeforeBracket: beforeBracket,
Values: validValues,
AfterBracket: afterBracket,
}
return extractedValues, nil
}
func isValidValue(value string) bool {
re := regexp.MustCompile(`^[a-zA-Z0-9-]+:(ok|pending|error|done)$`)
return re.MatchString(value)
}
func formatValue(value string) string {
parts := strings.Split(value, ":")
return fmt.Sprintf("%s:%s", parts[0], parts[1])
}
func getClassNameWithKey(eventns string, key *string) string {
cls := getClassName(eventns)
if key != nil && *key != "" {
cls = cls + "--" + strings.ReplaceAll(*key, " ", "-")
}
return cls
}
func getClassName(eventns string) string {
return strings.ReplaceAll(eventns, ":", "-")
}
func firAttributes(n *html.Node) []html.Attribute {
var attributes []html.Attribute
if n.Type == html.ElementNode {
for _, attr := range n.Attr {
if !strings.HasPrefix(attr.Key, "@fir:") && !strings.HasPrefix(attr.Key, "x-on:fir:") {
continue
}
attributes = append(attributes, attr)
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
attributes = append(firAttributes(c), attributes...)
}
return attributes
}
func eventFormatError(eventns string) string {
return fmt.Sprintf(`
error: invalid event namespace: %s. must be of either of the three formats =>
1. @fir:<event>:<state:ok|error|pending|done>::<block-name(optional)>
2. @fir:[event1:state,event2:state]::<block-name(optional)>
`, eventns)
}