| 1 |
// Copyright 2020 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package publisher |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"regexp" |
| 19 |
"sort" |
| 20 |
"strings" |
| 21 |
"sync" |
| 22 |
"unicode" |
| 23 |
"unicode/utf8" |
| 24 |
|
| 25 |
"golang.org/x/net/html" |
| 26 |
|
| 27 |
"github.com/gohugoio/hugo/common/hstrings" |
| 28 |
"github.com/gohugoio/hugo/config" |
| 29 |
) |
| 30 |
|
| 31 |
const eof = -1 |
| 32 |
|
| 33 |
var ( |
| 34 |
htmlJsonFixer = strings.NewReplacer(", ", "\n") |
| 35 |
jsonAttrRe = regexp.MustCompile(`'?(.*?)'?:\s.*`) |
| 36 |
classAttrRe = regexp.MustCompile(`(?i)^class$|transition`) |
| 37 |
|
| 38 |
skipInnerElementRe = regexp.MustCompile(`(?i)^(pre|textarea|script|style)`) |
| 39 |
skipAllElementRe = regexp.MustCompile(`(?i)^!DOCTYPE`) |
| 40 |
|
| 41 |
exceptionList = map[string]bool{ |
| 42 |
"thead": true, |
| 43 |
"tbody": true, |
| 44 |
"tfoot": true, |
| 45 |
"td": true, |
| 46 |
"tr": true, |
| 47 |
} |
| 48 |
) |
| 49 |
|
| 50 |
func newHTMLElementsCollector(conf config.BuildStats) *htmlElementsCollector { |
| 51 |
return &htmlElementsCollector{ |
| 52 |
conf: conf, |
| 53 |
elementSet: make(map[string]bool), |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
func newHTMLElementsCollectorWriter(collector *htmlElementsCollector) *htmlElementsCollectorWriter { |
| 58 |
w := &htmlElementsCollectorWriter{ |
| 59 |
collector: collector, |
| 60 |
state: htmlLexStart, |
| 61 |
} |
| 62 |
|
| 63 |
w.defaultLexElementInside = w.lexElementInside(htmlLexStart) |
| 64 |
|
| 65 |
return w |
| 66 |
} |
| 67 |
|
| 68 |
// HTMLElements holds lists of tags and attribute values for classes and id. |
| 69 |
type HTMLElements struct { |
| 70 |
Tags []string `json:"tags"` |
| 71 |
Classes []string `json:"classes"` |
| 72 |
IDs []string `json:"ids"` |
| 73 |
} |
| 74 |
|
| 75 |
func (h *HTMLElements) Merge(other HTMLElements) { |
| 76 |
h.Tags = append(h.Tags, other.Tags...) |
| 77 |
h.Classes = append(h.Classes, other.Classes...) |
| 78 |
h.IDs = append(h.IDs, other.IDs...) |
| 79 |
|
| 80 |
h.Tags = hstrings.UniqueStringsReuse(h.Tags) |
| 81 |
h.Classes = hstrings.UniqueStringsReuse(h.Classes) |
| 82 |
h.IDs = hstrings.UniqueStringsReuse(h.IDs) |
| 83 |
} |
| 84 |
|
| 85 |
func (h *HTMLElements) Sort() { |
| 86 |
sort.Strings(h.Tags) |
| 87 |
sort.Strings(h.Classes) |
| 88 |
sort.Strings(h.IDs) |
| 89 |
} |
| 90 |
|
| 91 |
type htmlElement struct { |
| 92 |
Tag string |
| 93 |
Classes []string |
| 94 |
IDs []string |
| 95 |
} |
| 96 |
|
| 97 |
type htmlElementsCollector struct { |
| 98 |
conf config.BuildStats |
| 99 |
|
| 100 |
// Contains the raw HTML string. We will get the same element |
| 101 |
// several times, and want to avoid costly reparsing when this |
| 102 |
// is used for aggregated data only. |
| 103 |
elementSet map[string]bool |
| 104 |
|
| 105 |
elements []htmlElement |
| 106 |
|
| 107 |
mu sync.RWMutex |
| 108 |
} |
| 109 |
|
| 110 |
func (c *htmlElementsCollector) getHTMLElements() HTMLElements { |
| 111 |
var ( |
| 112 |
classes []string |
| 113 |
ids []string |
| 114 |
tags []string |
| 115 |
) |
| 116 |
|
| 117 |
for _, el := range c.elements { |
| 118 |
classes = append(classes, el.Classes...) |
| 119 |
ids = append(ids, el.IDs...) |
| 120 |
if !c.conf.DisableTags { |
| 121 |
tags = append(tags, el.Tag) |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
classes = hstrings.UniqueStringsSorted(classes) |
| 126 |
ids = hstrings.UniqueStringsSorted(ids) |
| 127 |
tags = hstrings.UniqueStringsSorted(tags) |
| 128 |
|
| 129 |
els := HTMLElements{ |
| 130 |
Classes: classes, |
| 131 |
IDs: ids, |
| 132 |
Tags: tags, |
| 133 |
} |
| 134 |
|
| 135 |
return els |
| 136 |
} |
| 137 |
|
| 138 |
type htmlElementsCollectorWriter struct { |
| 139 |
collector *htmlElementsCollector |
| 140 |
|
| 141 |
r rune // Current rune |
| 142 |
width int // The width in bytes of r |
| 143 |
input []byte // The current slice written to Write |
| 144 |
pos int // The current position in input |
| 145 |
|
| 146 |
err error |
| 147 |
|
| 148 |
inQuote rune |
| 149 |
|
| 150 |
buff bytes.Buffer |
| 151 |
|
| 152 |
// Current state |
| 153 |
state htmlCollectorStateFunc |
| 154 |
|
| 155 |
// Precompiled state funcs |
| 156 |
defaultLexElementInside htmlCollectorStateFunc |
| 157 |
} |
| 158 |
|
| 159 |
// Write collects HTML elements from p, which must contain complete runes. |
| 160 |
func (w *htmlElementsCollectorWriter) Write(p []byte) (int, error) { |
| 161 |
if p == nil { |
| 162 |
return 0, nil |
| 163 |
} |
| 164 |
|
| 165 |
w.input = p |
| 166 |
|
| 167 |
for { |
| 168 |
w.r = w.next() |
| 169 |
if w.r == eof || w.r == utf8.RuneError { |
| 170 |
break |
| 171 |
} |
| 172 |
w.state = w.state(w) |
| 173 |
} |
| 174 |
|
| 175 |
w.pos = 0 |
| 176 |
w.input = nil |
| 177 |
|
| 178 |
return len(p), nil |
| 179 |
} |
| 180 |
|
| 181 |
func (l *htmlElementsCollectorWriter) backup() { |
| 182 |
l.pos -= l.width |
| 183 |
l.r, _ = utf8.DecodeRune(l.input[l.pos:]) |
| 184 |
} |
| 185 |
|
| 186 |
func (w *htmlElementsCollectorWriter) consumeBuffUntil(condition func() bool, resolve htmlCollectorStateFunc) htmlCollectorStateFunc { |
| 187 |
var s htmlCollectorStateFunc |
| 188 |
s = func(*htmlElementsCollectorWriter) htmlCollectorStateFunc { |
| 189 |
w.buff.WriteRune(w.r) |
| 190 |
if condition() { |
| 191 |
w.buff.Reset() |
| 192 |
return resolve |
| 193 |
} |
| 194 |
return s |
| 195 |
} |
| 196 |
return s |
| 197 |
} |
| 198 |
|
| 199 |
func (w *htmlElementsCollectorWriter) consumeRuneUntil(condition func(r rune) bool, resolve htmlCollectorStateFunc) htmlCollectorStateFunc { |
| 200 |
var s htmlCollectorStateFunc |
| 201 |
s = func(*htmlElementsCollectorWriter) htmlCollectorStateFunc { |
| 202 |
if condition(w.r) { |
| 203 |
return resolve |
| 204 |
} |
| 205 |
return s |
| 206 |
} |
| 207 |
return s |
| 208 |
} |
| 209 |
|
| 210 |
// Starts with e.g. "<body " or "<div" |
| 211 |
func (w *htmlElementsCollectorWriter) lexElementInside(resolve htmlCollectorStateFunc) htmlCollectorStateFunc { |
| 212 |
var s htmlCollectorStateFunc |
| 213 |
s = func(w *htmlElementsCollectorWriter) htmlCollectorStateFunc { |
| 214 |
w.buff.WriteRune(w.r) |
| 215 |
|
| 216 |
// Skip any text inside a quote. |
| 217 |
if w.r == '\'' || w.r == '"' { |
| 218 |
if w.inQuote == w.r { |
| 219 |
w.inQuote = 0 |
| 220 |
} else if w.inQuote == 0 { |
| 221 |
w.inQuote = w.r |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
if w.inQuote != 0 { |
| 226 |
return s |
| 227 |
} |
| 228 |
|
| 229 |
if w.r == '>' { |
| 230 |
|
| 231 |
// Work with the bytes slice as long as it's practical, |
| 232 |
// to save memory allocations. |
| 233 |
b := w.buff.Bytes() |
| 234 |
|
| 235 |
defer func() { |
| 236 |
w.buff.Reset() |
| 237 |
}() |
| 238 |
|
| 239 |
// First check if we have processed this element before. |
| 240 |
w.collector.mu.RLock() |
| 241 |
|
| 242 |
seen := w.collector.elementSet[string(b)] |
| 243 |
w.collector.mu.RUnlock() |
| 244 |
if seen { |
| 245 |
return resolve |
| 246 |
} |
| 247 |
|
| 248 |
s := w.buff.String() |
| 249 |
|
| 250 |
if s == "" { |
| 251 |
return resolve |
| 252 |
} |
| 253 |
|
| 254 |
// Parse each collected element. |
| 255 |
el, err := w.parseHTMLElement(s) |
| 256 |
if err != nil { |
| 257 |
w.err = err |
| 258 |
return resolve |
| 259 |
} |
| 260 |
|
| 261 |
// Write this tag to the element set. |
| 262 |
w.collector.mu.Lock() |
| 263 |
w.collector.elementSet[s] = true |
| 264 |
w.collector.elements = append(w.collector.elements, el) |
| 265 |
w.collector.mu.Unlock() |
| 266 |
|
| 267 |
return resolve |
| 268 |
|
| 269 |
} |
| 270 |
|
| 271 |
return s |
| 272 |
} |
| 273 |
|
| 274 |
return s |
| 275 |
} |
| 276 |
|
| 277 |
func (l *htmlElementsCollectorWriter) next() rune { |
| 278 |
if l.pos >= len(l.input) { |
| 279 |
l.width = 0 |
| 280 |
return eof |
| 281 |
} |
| 282 |
|
| 283 |
runeValue, runeWidth := utf8.DecodeRune(l.input[l.pos:]) |
| 284 |
|
| 285 |
l.width = runeWidth |
| 286 |
l.pos += l.width |
| 287 |
return runeValue |
| 288 |
} |
| 289 |
|
| 290 |
// returns the next state in HTML element scanner. |
| 291 |
type htmlCollectorStateFunc func(*htmlElementsCollectorWriter) htmlCollectorStateFunc |
| 292 |
|
| 293 |
// At "<", buffer empty. |
| 294 |
// Potentially starting a HTML element. |
| 295 |
func htmlLexElementStart(w *htmlElementsCollectorWriter) htmlCollectorStateFunc { |
| 296 |
if w.r == '>' || unicode.IsSpace(w.r) { |
| 297 |
if w.buff.Len() < 2 || bytes.HasPrefix(w.buff.Bytes(), []byte("</")) { |
| 298 |
w.buff.Reset() |
| 299 |
return htmlLexStart |
| 300 |
} |
| 301 |
|
| 302 |
tagName := w.buff.Bytes()[1:] |
| 303 |
isSelfClosing := tagName[len(tagName)-1] == '/' |
| 304 |
|
| 305 |
switch { |
| 306 |
case !isSelfClosing && skipInnerElementRe.Match(tagName): |
| 307 |
// pre, script etc. We collect classes etc. on the surrounding |
| 308 |
// element, but skip the inner content. |
| 309 |
w.backup() |
| 310 |
|
| 311 |
// tagName will be overwritten, so make a copy. |
| 312 |
tagNameCopy := make([]byte, len(tagName)) |
| 313 |
copy(tagNameCopy, tagName) |
| 314 |
|
| 315 |
return w.lexElementInside( |
| 316 |
w.consumeBuffUntil( |
| 317 |
func() bool { |
| 318 |
if w.r != '>' { |
| 319 |
return false |
| 320 |
} |
| 321 |
return isClosedByTag(w.buff.Bytes(), tagNameCopy) |
| 322 |
}, |
| 323 |
htmlLexStart, |
| 324 |
)) |
| 325 |
case skipAllElementRe.Match(tagName): |
| 326 |
// E.g. "<!DOCTYPE ..." |
| 327 |
w.buff.Reset() |
| 328 |
return w.consumeRuneUntil(func(r rune) bool { |
| 329 |
return r == '>' |
| 330 |
}, htmlLexStart) |
| 331 |
default: |
| 332 |
w.backup() |
| 333 |
return w.defaultLexElementInside |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
w.buff.WriteRune(w.r) |
| 338 |
|
| 339 |
// If it's a comment, skip to its end. |
| 340 |
if w.r == '-' && bytes.Equal(w.buff.Bytes(), []byte("<!--")) { |
| 341 |
w.buff.Reset() |
| 342 |
return htmlLexToEndOfComment |
| 343 |
} |
| 344 |
|
| 345 |
return htmlLexElementStart |
| 346 |
} |
| 347 |
|
| 348 |
// Entry state func. |
| 349 |
// Looks for a opening bracket, '<'. |
| 350 |
func htmlLexStart(w *htmlElementsCollectorWriter) htmlCollectorStateFunc { |
| 351 |
if w.r == '<' { |
| 352 |
w.backup() |
| 353 |
w.buff.Reset() |
| 354 |
return htmlLexElementStart |
| 355 |
} |
| 356 |
|
| 357 |
return htmlLexStart |
| 358 |
} |
| 359 |
|
| 360 |
// After "<!--", buff empty. |
| 361 |
func htmlLexToEndOfComment(w *htmlElementsCollectorWriter) htmlCollectorStateFunc { |
| 362 |
w.buff.WriteRune(w.r) |
| 363 |
|
| 364 |
if w.r == '>' && bytes.HasSuffix(w.buff.Bytes(), []byte("-->")) { |
| 365 |
// Done, start looking for HTML elements again. |
| 366 |
return htmlLexStart |
| 367 |
} |
| 368 |
|
| 369 |
return htmlLexToEndOfComment |
| 370 |
} |
| 371 |
|
| 372 |
func (w *htmlElementsCollectorWriter) parseHTMLElement(elStr string) (el htmlElement, err error) { |
| 373 |
conf := w.collector.conf |
| 374 |
|
| 375 |
tagName := parseStartTag(elStr) |
| 376 |
|
| 377 |
el.Tag = strings.ToLower(tagName) |
| 378 |
tagNameToParse := el.Tag |
| 379 |
|
| 380 |
// The net/html parser does not handle single table elements as input, e.g. tbody. |
| 381 |
// We only care about the element/class/ids, so just store away the original tag name |
| 382 |
// and pretend it's a <div>. |
| 383 |
if exceptionList[el.Tag] { |
| 384 |
elStr = strings.Replace(elStr, tagName, "div", 1) |
| 385 |
tagNameToParse = "div" |
| 386 |
} |
| 387 |
|
| 388 |
n, err := html.Parse(strings.NewReader(elStr)) |
| 389 |
if err != nil { |
| 390 |
return |
| 391 |
} |
| 392 |
|
| 393 |
var walk func(*html.Node) |
| 394 |
walk = func(n *html.Node) { |
| 395 |
if n.Type == html.ElementNode && n.Data == tagNameToParse { |
| 396 |
for _, a := range n.Attr { |
| 397 |
switch { |
| 398 |
case strings.EqualFold(a.Key, "id"): |
| 399 |
// There should be only one, but one never knows... |
| 400 |
if !conf.DisableIDs { |
| 401 |
el.IDs = append(el.IDs, a.Val) |
| 402 |
} |
| 403 |
default: |
| 404 |
if conf.DisableClasses { |
| 405 |
continue |
| 406 |
} |
| 407 |
|
| 408 |
if classAttrRe.MatchString(a.Key) { |
| 409 |
el.Classes = append(el.Classes, strings.Fields(a.Val)...) |
| 410 |
} else { |
| 411 |
key := strings.ToLower(a.Key) |
| 412 |
val := strings.TrimSpace(a.Val) |
| 413 |
|
| 414 |
if strings.Contains(key, ":class") { |
| 415 |
if strings.HasPrefix(val, "{") { |
| 416 |
// This looks like a Vue or AlpineJS class binding. |
| 417 |
val = htmlJsonFixer.Replace(strings.Trim(val, "{}")) |
| 418 |
lines := strings.Split(val, "\n") |
| 419 |
for i, l := range lines { |
| 420 |
lines[i] = strings.TrimSpace(l) |
| 421 |
} |
| 422 |
val = strings.Join(lines, "\n") |
| 423 |
|
| 424 |
val = jsonAttrRe.ReplaceAllString(val, "$1") |
| 425 |
|
| 426 |
el.Classes = append(el.Classes, strings.Fields(val)...) |
| 427 |
} |
| 428 |
// Also add single quoted strings. |
| 429 |
// This may introduce some false positives, but it covers some missing cases in the above. |
| 430 |
// E.g. AlpinesJS' :class="isTrue 'class1' : 'class2'" |
| 431 |
el.Classes = append(el.Classes, extractSingleQuotedStrings(val)...) |
| 432 |
} |
| 433 |
} |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
for c := n.FirstChild; c != nil; c = c.NextSibling { |
| 439 |
walk(c) |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
walk(n) |
| 444 |
|
| 445 |
return |
| 446 |
} |
| 447 |
|
| 448 |
// Variants of s |
| 449 |
// |
| 450 |
// <body class="b a"> |
| 451 |
// <div> |
| 452 |
func parseStartTag(s string) string { |
| 453 |
spaceIndex := strings.IndexFunc(s, func(r rune) bool { |
| 454 |
return unicode.IsSpace(r) |
| 455 |
}) |
| 456 |
|
| 457 |
if spaceIndex == -1 { |
| 458 |
s = s[1 : len(s)-1] |
| 459 |
} else { |
| 460 |
s = s[1:spaceIndex] |
| 461 |
} |
| 462 |
|
| 463 |
if s[len(s)-1] == '/' { |
| 464 |
// Self closing. |
| 465 |
s = s[:len(s)-1] |
| 466 |
} |
| 467 |
|
| 468 |
return s |
| 469 |
} |
| 470 |
|
| 471 |
// isClosedByTag reports whether b ends with a closing tag for tagName. |
| 472 |
func isClosedByTag(b, tagName []byte) bool { |
| 473 |
if len(b) == 0 { |
| 474 |
return false |
| 475 |
} |
| 476 |
|
| 477 |
if b[len(b)-1] != '>' { |
| 478 |
return false |
| 479 |
} |
| 480 |
|
| 481 |
var ( |
| 482 |
lo int |
| 483 |
hi int |
| 484 |
|
| 485 |
state int |
| 486 |
inWord bool |
| 487 |
) |
| 488 |
|
| 489 |
LOOP: |
| 490 |
for i := len(b) - 2; i >= 0; i-- { |
| 491 |
switch { |
| 492 |
case b[i] == '<': |
| 493 |
if state != 1 { |
| 494 |
return false |
| 495 |
} |
| 496 |
state = 2 |
| 497 |
break LOOP |
| 498 |
case b[i] == '/': |
| 499 |
if state != 0 { |
| 500 |
return false |
| 501 |
} |
| 502 |
state++ |
| 503 |
if inWord { |
| 504 |
lo = i + 1 |
| 505 |
inWord = false |
| 506 |
} |
| 507 |
case isSpace(b[i]): |
| 508 |
if inWord { |
| 509 |
lo = i + 1 |
| 510 |
inWord = false |
| 511 |
} |
| 512 |
default: |
| 513 |
if !inWord { |
| 514 |
hi = i + 1 |
| 515 |
inWord = true |
| 516 |
} |
| 517 |
} |
| 518 |
} |
| 519 |
|
| 520 |
if state != 2 || lo >= hi { |
| 521 |
return false |
| 522 |
} |
| 523 |
|
| 524 |
return bytes.EqualFold(tagName, b[lo:hi]) |
| 525 |
} |
| 526 |
|
| 527 |
func isSpace(b byte) bool { |
| 528 |
return b == ' ' || b == '\t' || b == '\n' |
| 529 |
} |
| 530 |
|
| 531 |
func extractSingleQuotedStrings(s string) []string { |
| 532 |
var ( |
| 533 |
inQuote bool |
| 534 |
lo int |
| 535 |
hi int |
| 536 |
) |
| 537 |
|
| 538 |
var words []string |
| 539 |
|
| 540 |
for i, r := range s { |
| 541 |
switch { |
| 542 |
case r == '\'': |
| 543 |
if !inQuote { |
| 544 |
inQuote = true |
| 545 |
lo = i + 1 |
| 546 |
} else { |
| 547 |
inQuote = false |
| 548 |
hi = i |
| 549 |
words = append(words, strings.Fields(s[lo:hi])...) |
| 550 |
} |
| 551 |
} |
| 552 |
} |
| 553 |
|
| 554 |
return words |
| 555 |
} |