forked from ericchiang/pup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
printing.go
106 lines (98 loc) · 2.45 KB
/
printing.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
package main
import (
"code.google.com/p/go.net/html"
"code.google.com/p/go.net/html/atom"
"fmt"
"github.com/fatih/color"
"regexp"
)
var (
// Colors
tagColor *color.Color = color.New(color.FgYellow).Add(color.Bold)
tokenColor = color.New(color.FgCyan).Add(color.Bold)
attrKeyColor = color.New(color.FgRed)
quoteColor = color.New(color.FgBlue)
// Regexp helpers
whitespaceRegexp *regexp.Regexp = regexp.MustCompile(`^\s*$`)
preWhitespace = regexp.MustCompile(`^\s+`)
postWhitespace = regexp.MustCompile(`\s+$`)
)
func printIndent(level int) {
for ; level > 0; level-- {
fmt.Print(indentString)
}
}
// Is this node a tag with no end tag such as <meta> or <br>?
// http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
func isVoidElement(n *html.Node) bool {
switch n.DataAtom {
case atom.Area, atom.Base, atom.Br, atom.Col, atom.Command, atom.Embed,
atom.Hr, atom.Img, atom.Input, atom.Keygen, atom.Link,
atom.Meta, atom.Param, atom.Source, atom.Track, atom.Wbr:
return true
}
return false
}
func printChildren(n *html.Node, level int) {
if maxPrintLevel > -1 {
if level >= maxPrintLevel {
printIndent(level)
fmt.Println("...")
return
}
}
child := n.FirstChild
for child != nil {
PrintNode(child, level)
child = child.NextSibling
}
}
// Print a node and all of it's children to `maxlevel`.
func PrintNode(n *html.Node, level int) {
switch n.Type {
case html.TextNode:
s := n.Data
if !whitespaceRegexp.MatchString(s) {
s = preWhitespace.ReplaceAllString(s, "")
s = postWhitespace.ReplaceAllString(s, "")
printIndent(level)
fmt.Println(s)
}
case html.ElementNode:
printIndent(level)
if printColor {
tokenColor.Print("<")
tagColor.Printf("%s", n.Data)
} else {
fmt.Printf("<%s", n.Data)
}
for _, a := range n.Attr {
if printColor {
fmt.Print(" ")
attrKeyColor.Printf("%s", a.Key)
tokenColor.Print("=")
quoteColor.Printf(`"%s"`, a.Val)
} else {
fmt.Printf(` %s="%s"`, a.Key, a.Val)
}
}
if printColor {
tokenColor.Println(">")
} else {
fmt.Print(">\n")
}
if !isVoidElement(n) {
printChildren(n, level+1)
printIndent(level)
if printColor {
tokenColor.Print("</")
tagColor.Printf("%s", n.Data)
tokenColor.Println(">")
} else {
fmt.Printf("</%s>\n", n.Data)
}
}
case html.CommentNode, html.DoctypeNode, html.DocumentNode:
printChildren(n, level)
}
}