forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpretty.go
125 lines (106 loc) · 2.11 KB
/
pretty.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
// ex5.7 pretty-prints html.
package main
import (
"fmt"
"io"
"log"
"os"
"strings"
"golang.org/x/net/html"
)
var depth int
type PrettyPrinter struct {
w io.Writer
err error
}
func NewPrettyPrinter() PrettyPrinter {
return PrettyPrinter{}
}
func (pp PrettyPrinter) Pretty(w io.Writer, n *html.Node) error {
pp.w = w
pp.err = nil
pp.forEachNode(n, pp.start, pp.end)
return pp.Err()
}
func (pp PrettyPrinter) Err() error {
return pp.err
}
func (pp PrettyPrinter) forEachNode(n *html.Node, pre, post func(n *html.Node)) {
if pre != nil {
pre(n)
}
if pp.Err() != nil {
return
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
pp.forEachNode(c, pre, post)
}
if post != nil {
post(n)
}
if pp.Err() != nil {
return
}
}
func (pp PrettyPrinter) printf(format string, args ...interface{}) {
_, err := fmt.Fprintf(pp.w, format, args...)
pp.err = err
}
func (pp PrettyPrinter) startElement(n *html.Node) {
end := ">"
if n.FirstChild == nil {
end = "/>"
}
attrs := make([]string, 0, len(n.Attr))
for _, a := range n.Attr {
attrs = append(attrs, fmt.Sprintf(`%s="%s"`, a.Key, a.Val))
}
attrStr := ""
if len(n.Attr) > 0 {
attrStr = " " + strings.Join(attrs, " ")
}
name := n.Data
pp.printf("%*s<%s%s%s\n", depth*2, "", name, attrStr, end)
depth++
}
func (pp PrettyPrinter) endElement(n *html.Node) {
depth--
if n.FirstChild == nil {
return
}
pp.printf("%*s</%s>\n", depth*2, "", n.Data)
}
func (pp PrettyPrinter) startText(n *html.Node) {
text := strings.TrimSpace(n.Data)
if len(text) == 0 {
return
}
pp.printf("%*s%s\n", depth*2, "", n.Data)
}
func (pp PrettyPrinter) startComment(n *html.Node) {
pp.printf("<!--%s-->\n", n.Data)
}
func (pp PrettyPrinter) start(n *html.Node) {
switch n.Type {
case html.ElementNode:
pp.startElement(n)
case html.TextNode:
pp.startText(n)
case html.CommentNode:
pp.startComment(n)
}
}
func (pp PrettyPrinter) end(n *html.Node) {
switch n.Type {
case html.ElementNode:
pp.endElement(n)
}
}
func main() {
doc, err := html.Parse(os.Stdin)
if err != nil {
log.Fatal(err)
}
pp := NewPrettyPrinter()
pp.Pretty(os.Stdout, doc)
}