-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtmlcheck.go
More file actions
458 lines (393 loc) · 9.68 KB
/
htmlcheck.go
File metadata and controls
458 lines (393 loc) · 9.68 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package htmlcheck
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"regexp"
"strconv"
"strings"
//"golang.org/x/net/html"
html "github.com/mpfund/htmlcheck/htmlp"
)
type ErrorReason int
const (
InvTag ErrorReason = 0
InvAttribute ErrorReason = 1
InvClosedBeforeOpened ErrorReason = 2
InvNotProperlyClosed ErrorReason = 3
InvDuplicatedAttribute ErrorReason = 4
InvEOF ErrorReason = 5
)
type Span struct {
Start int
End int
}
type TextPos struct {
Line int
Column int
}
type ErrorCallback func(tagName string, attributeName string,
value string, reason ErrorReason) *ValidationError
type TagGroup struct {
Name string
Attrs []string
}
type ValidTag struct {
Name string
Attrs []string
AttrRegEx string
Groups []string
AttrStartsWith string
IsSelfClosing bool
}
type ValidationError struct {
TagName string
AttributeName string
Reason ErrorReason
Pos Span
TextPos *TextPos
}
type TagsFile struct {
Groups []*TagGroup
Tags []*ValidTag
}
type Validator struct {
validTagMap map[string]map[string]bool
validSelfClosingTags map[string]bool
errorCallback ErrorCallback
StopAfterFirstError bool
validTags map[string]*ValidTag
validGroups map[string]*TagGroup
}
func (e *ValidationError) Error() string {
text := ""
switch e.Reason {
case InvTag:
text = "tag '" + e.TagName + "' is not valid"
case InvAttribute:
text = "invalid attribute '" + e.AttributeName + "' in tag '" + e.TagName + "'"
case InvClosedBeforeOpened:
text = "'" + e.TagName + "' closed before opened."
case InvNotProperlyClosed:
text = "tag '" + e.TagName + "' is never closed"
case InvDuplicatedAttribute:
text = "duplicated attribute '" + e.AttributeName + "' in '" + e.TagName + "'"
}
pos := ""
start := strconv.Itoa(e.Pos.Start)
end := strconv.Itoa(e.Pos.End)
pos = " (" + start + ", " + end + ")"
if e.TextPos == nil {
} else {
line := strconv.Itoa(e.TextPos.Line)
column := strconv.Itoa(e.TextPos.Column)
pos = pos + " (L" + line + ", C" + column + ")"
}
return text + pos
}
func (v *Validator) AddValidTags(validTags []*ValidTag) {
if v.validSelfClosingTags == nil {
v.validSelfClosingTags = make(map[string]bool)
}
if v.validTagMap == nil {
v.validTagMap = make(map[string]map[string]bool)
}
if v.validTags == nil {
v.validTags = map[string]*ValidTag{}
}
for _, tag := range validTags {
if tag.IsSelfClosing {
v.validSelfClosingTags[tag.Name] = true
}
v.validTagMap[tag.Name] = make(map[string]bool)
for _, a := range tag.Attrs {
v.validTagMap[tag.Name][a] = true
}
if tag.Name == "" {
_, hasGlobalTag := v.validTags[""]
if hasGlobalTag {
log.Println("second global tag")
}
}
v.validTags[tag.Name] = tag
for _, groupName := range tag.Groups {
group := v.validGroups[groupName]
for _, attr := range group.Attrs {
v.validTagMap[tag.Name][attr] = true
}
}
}
}
func (v *Validator) AddValidTag(validTag ValidTag) {
v.AddValidTags([]*ValidTag{&validTag})
}
func (v *Validator) AddGroup(group *TagGroup) {
v.AddGroups([]*TagGroup{group})
}
func (v *Validator) AddGroups(groups []*TagGroup) {
if v.validGroups == nil {
v.validGroups = map[string]*TagGroup{}
}
for _, g := range groups {
v.validGroups[g.Name] = g
for _, t := range v.validTags {
if t.HasGroup(g.Name) {
for _, attr := range g.Attrs {
v.validTagMap[t.Name][attr] = true
}
}
}
}
}
func (tag *ValidTag) HasGroup(groupName string) bool {
for _, g := range tag.Groups {
if g == groupName {
return true
}
}
return false
}
func (v *Validator) RegisterCallback(f ErrorCallback) {
v.errorCallback = f
}
func (v *Validator) IsValidTag(tagName string) bool {
_, ok := v.validTagMap[tagName]
return ok
}
func (v *Validator) IsValidSelfClosingTag(tagName string) bool {
_, ok := v.validSelfClosingTags[tagName]
if !ok {
return false
}
return ok
}
func (v *Validator) LoadTagsFromFile(path string) error {
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
tagFile := TagsFile{}
err = json.Unmarshal(content, &tagFile)
if err != nil {
return err
}
v.AddGroups(tagFile.Groups)
v.AddValidTags(tagFile.Tags)
return nil
}
/*func (v *Validator) WriteTagsToFile(path string) error {
tagFile := TagsFile{v.validTags}
b, err := json.Marshal(tags)
if err != nil {
return err
}
ioutil.WriteFile(path, b, 755)
return nil
}*/
func (v *Validator) IsValidAttribute(tagName string, attrName string) bool {
attrs, hasTag := v.validTagMap[tagName]
gAttrs, hasGlobals := v.validTagMap[""] //check global attributes
if hasTag {
_, hasAttr := attrs[attrName]
if hasAttr {
return true
} else {
//test reg ex
ok := v.testAttribute(tagName, attrName)
if ok {
return true
}
}
}
if hasGlobals {
_, hasGlobalAttr := gAttrs[attrName]
if hasGlobalAttr {
return true
} else {
return v.testAttribute("", attrName)
}
}
return false
}
func (v *Validator) testAttribute(tagName string, attrName string) bool {
tag := v.validTags[tagName]
if tag.AttrStartsWith != "" {
return strings.HasPrefix(attrName, tag.AttrStartsWith)
}
if tag.AttrRegEx != "" {
matches, err := regexp.MatchString(tag.AttrRegEx, attrName)
if err == nil && matches {
return true
}
}
return false
}
func (v *Validator) ValidateHtmlString(str string) []*ValidationError {
buffer := strings.NewReader(str)
errors := v.ValidateHtml(buffer)
//updateLineColumns(str, errors)
return errors
}
func UpdateErrorLines(str string, errors []*ValidationError) {
updateLineColumns(str, errors)
}
func updateLineColumns(str string, errors []*ValidationError) {
lines := strings.Split(str, "\n")
for _, k := range errors {
charCount := 0
for i, l := range lines {
lineLen := len(l) + 1
if k.Pos.Start < (charCount + lineLen) {
tPos := TextPos{i + 1, k.Pos.Start - charCount + 1}
k.TextPos = &tPos
break
}
charCount += lineLen
}
}
}
func (v *Validator) checkErrorCallback(tagName string, attr string,
value string, span Span, reason ErrorReason) *ValidationError {
if v.errorCallback != nil {
return v.errorCallback(tagName, attr, value, reason)
}
return &ValidationError{tagName, attr, reason, span, nil}
}
func (v *Validator) ValidateHtml(r io.Reader) []*ValidationError {
d := html.NewTokenizer(r)
parents := []string{}
var err *ValidationError
errors := []*ValidationError{}
for {
parents, err = v.checkToken(d, parents)
if err != nil {
if err.Reason == InvEOF {
break
}
errors = append(errors, err)
if v.StopAfterFirstError {
return errors
}
}
}
err = v.checkParents(d, parents)
if err != nil {
errors = append(errors, err)
}
return errors
}
func indexOf(arr []string, val string) int {
for i, k := range arr {
if k == val {
return i
}
}
return -1
}
func (v *Validator) correctError(err *ValidationError, parents []string,
tokenType html.TokenType, token html.Token) []string {
if err.Reason == InvClosedBeforeOpened && tokenType == html.EndTagToken {
index := indexOf(parents, token.Data)
if index > -1 {
parents = parents[0:index]
}
}
fmt.Println("correct", parents, tokenType, token.Data)
return parents
}
func (v *Validator) checkParents(d *html.Tokenizer, parents []string) *ValidationError {
for _, tagName := range parents {
if v.IsValidSelfClosingTag(tagName) {
continue
}
pos := getPosition(d)
cError := v.checkErrorCallback(tagName, "", "", pos, InvNotProperlyClosed)
if cError != nil {
return cError
}
}
return nil
}
func popLast(list []string) []string {
if len(list) == 0 {
return list
}
return list[0 : len(list)-1]
}
func getPosition(d *html.Tokenizer) Span {
posStart, posEnd := d.GetRawPosition()
return Span{posStart, posEnd}
}
func (v *Validator) checkToken(d *html.Tokenizer,
parents []string) ([]string, *ValidationError) {
tokenType := d.Next()
if tokenType == html.ErrorToken {
return parents, &ValidationError{"", "", InvEOF, Span{0, 0}, nil}
}
pos := getPosition(d)
token := d.Token()
//pos := getPosition(d)
if tokenType == html.EndTagToken ||
tokenType == html.StartTagToken ||
tokenType == html.SelfClosingTagToken {
tagName := token.Data
if !v.IsValidTag(tagName) {
cError := v.checkErrorCallback(tagName, "", "", pos, InvTag)
if cError != nil {
return parents, cError
}
}
if token.Type == html.StartTagToken ||
token.Type == html.SelfClosingTagToken {
parents = append(parents, tagName)
}
attrs := map[string]bool{}
for _, attr := range token.Attr {
if !v.IsValidAttribute(tagName, attr.Key) {
cError := v.checkErrorCallback(tagName, attr.Key,
attr.Val, pos, InvAttribute)
if cError != nil {
return parents, cError
}
}
_, ok := attrs[attr.Key]
if !ok {
attrs[attr.Key] = true
} else {
cError := v.checkErrorCallback(tagName, attr.Key,
attr.Val, pos, InvDuplicatedAttribute)
if cError != nil {
return parents, cError
}
}
}
if token.Type == html.EndTagToken {
if len(parents) > 0 && parents[len(parents)-1] == tagName {
parents = popLast(parents)
} else if len(parents) == 0 ||
parents[len(parents)-1] != tagName {
index := indexOf(parents, tagName)
if index > -1 {
missingTagName := parents[len(parents)-1]
parents = parents[0:index]
if !v.IsValidSelfClosingTag(missingTagName) {
cError := v.checkErrorCallback(missingTagName,
"", "", pos, InvNotProperlyClosed)
if cError != nil {
return parents, cError
}
}
} else {
cError := v.checkErrorCallback(tagName,
"", "", pos, InvClosedBeforeOpened)
if cError != nil {
return parents, cError
}
}
}
}
}
return parents, nil
}