Debian Codegraph @

display.go

raw symbols SCIP
1 package main
2
3 import (
4 "encoding/json"
5 "fmt"
6 "regexp"
7 "strings"
8
9 "github.com/fatih/color"
10 colorable "github.com/mattn/go-colorable"
11 "golang.org/x/net/html"
12 "golang.org/x/net/html/atom"
13 )
14
15 func init() {
16 color.Output = colorable.NewColorableStdout()
17 }
18
19 type Displayer interface {
20 Display([]*html.Node)
21 }
22
23 func ParseDisplayer(cmd string) error {
24 attrRe := regexp.MustCompile(`attr\{([a-zA-Z\-]+)\}`)
25 if cmd == "text{}" {
26 pupDisplayer = TextDisplayer{}
27 } else if cmd == "json{}" {
28 pupDisplayer = JSONDisplayer{}
29 } else if match := attrRe.FindAllStringSubmatch(cmd, -1); len(match) == 1 {
30 pupDisplayer = AttrDisplayer{
31 Attr: match[0][1],
32 }
33 } else {
34 return fmt.Errorf("Unknown displayer")
35 }
36 return nil
37 }
38
39 // Is this node a tag with no end tag such as <meta> or <br>?
40 // http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
41 func isVoidElement(n *html.Node) bool {
42 switch n.DataAtom {
43 case atom.Area, atom.Base, atom.Br, atom.Col, atom.Command, atom.Embed,
44 atom.Hr, atom.Img, atom.Input, atom.Keygen, atom.Link,
45 atom.Meta, atom.Param, atom.Source, atom.Track, atom.Wbr:
46 return true
47 }
48 return false
49 }
50
51 var (
52 // Colors
53 tagColor *color.Color = color.New(color.FgCyan)
54 tokenColor = color.New(color.FgCyan)
55 attrKeyColor = color.New(color.FgMagenta)
56 quoteColor = color.New(color.FgBlue)
57 commentColor = color.New(color.FgYellow)
58 )
59
60 type TreeDisplayer struct {
61 }
62
63 func (t TreeDisplayer) Display(nodes []*html.Node) {
64 for _, node := range nodes {
65 t.printNode(node, 0)
66 }
67 }
68
69 // The <pre> tag indicates that the text within it should always be formatted
70 // as is. See https://github.com/ericchiang/pup/issues/33
71 func (t TreeDisplayer) printPre(n *html.Node) {
72 switch n.Type {
73 case html.TextNode:
74 s := n.Data
75 if pupEscapeHTML {
76 // don't escape javascript
77 if n.Parent == nil || n.Parent.DataAtom != atom.Script {
78 s = html.EscapeString(s)
79 }
80 }
81 fmt.Print(s)
82 for c := n.FirstChild; c != nil; c = c.NextSibling {
83 t.printPre(c)
84 }
85 case html.ElementNode:
86 fmt.Printf("<%s", n.Data)
87 for _, a := range n.Attr {
88 val := a.Val
89 if pupEscapeHTML {
90 val = html.EscapeString(val)
91 }
92 fmt.Printf(` %s="%s"`, a.Key, val)
93 }
94 fmt.Print(">")
95 if !isVoidElement(n) {
96 for c := n.FirstChild; c != nil; c = c.NextSibling {
97 t.printPre(c)
98 }
99 fmt.Printf("</%s>", n.Data)
100 }
101 case html.CommentNode:
102 data := n.Data
103 if pupEscapeHTML {
104 data = html.EscapeString(data)
105 }
106 fmt.Printf("<!--%s-->\n", data)
107 for c := n.FirstChild; c != nil; c = c.NextSibling {
108 t.printPre(c)
109 }
110 case html.DoctypeNode, html.DocumentNode:
111 for c := n.FirstChild; c != nil; c = c.NextSibling {
112 t.printPre(c)
113 }
114 }
115 }
116
117 // Print a node and all of it's children to `maxlevel`.
118 func (t TreeDisplayer) printNode(n *html.Node, level int) {
119 switch n.Type {
120 case html.TextNode:
121 s := n.Data
122 if pupEscapeHTML {
123 // don't escape javascript
124 if n.Parent == nil || n.Parent.DataAtom != atom.Script {
125 s = html.EscapeString(s)
126 }
127 }
128 s = strings.TrimSpace(s)
129 if s != "" {
130 t.printIndent(level)
131 fmt.Println(s)
132 }
133 case html.ElementNode:
134 t.printIndent(level)
135 // TODO: allow pre with color
136 if n.DataAtom == atom.Pre && !pupPrintColor && pupPreformatted {
137 t.printPre(n)
138 fmt.Println()
139 return
140 }
141 if pupPrintColor {
142 tokenColor.Print("<")
143 tagColor.Printf("%s", n.Data)
144 } else {
145 fmt.Printf("<%s", n.Data)
146 }
147 for _, a := range n.Attr {
148 val := a.Val
149 if pupEscapeHTML {
150 val = html.EscapeString(val)
151 }
152 if pupPrintColor {
153 fmt.Print(" ")
154 attrKeyColor.Printf("%s", a.Key)
155 tokenColor.Print("=")
156 quoteColor.Printf(`"%s"`, val)
157 } else {
158 fmt.Printf(` %s="%s"`, a.Key, val)
159 }
160 }
161 if pupPrintColor {
162 tokenColor.Println(">")
163 } else {
164 fmt.Println(">")
165 }
166 if !isVoidElement(n) {
167 t.printChildren(n, level+1)
168 t.printIndent(level)
169 if pupPrintColor {
170 tokenColor.Print("</")
171 tagColor.Printf("%s", n.Data)
172 tokenColor.Println(">")
173 } else {
174 fmt.Printf("</%s>\n", n.Data)
175 }
176 }
177 case html.CommentNode:
178 t.printIndent(level)
179 data := n.Data
180 if pupEscapeHTML {
181 data = html.EscapeString(data)
182 }
183 if pupPrintColor {
184 commentColor.Printf("<!--%s-->\n", data)
185 } else {
186 fmt.Printf("<!--%s-->\n", data)
187 }
188 t.printChildren(n, level)
189 case html.DoctypeNode, html.DocumentNode:
190 t.printChildren(n, level)
191 }
192 }
193
194 func (t TreeDisplayer) printChildren(n *html.Node, level int) {
195 if pupMaxPrintLevel > -1 {
196 if level >= pupMaxPrintLevel {
197 t.printIndent(level)
198 fmt.Println("...")
199 return
200 }
201 }
202 child := n.FirstChild
203 for child != nil {
204 t.printNode(child, level)
205 child = child.NextSibling
206 }
207 }
208
209 func (t TreeDisplayer) printIndent(level int) {
210 for ; level > 0; level-- {
211 fmt.Print(pupIndentString)
212 }
213 }
214
215 // Print the text of a node
216 type TextDisplayer struct{}
217
218 func (t TextDisplayer) Display(nodes []*html.Node) {
219 for _, node := range nodes {
220 if node.Type == html.TextNode {
221 data := node.Data
222 if pupEscapeHTML {
223 // don't escape javascript
224 if node.Parent == nil || node.Parent.DataAtom != atom.Script {
225 data = html.EscapeString(data)
226 }
227 }
228 fmt.Println(data)
229 }
230 children := []*html.Node{}
231 child := node.FirstChild
232 for child != nil {
233 children = append(children, child)
234 child = child.NextSibling
235 }
236 t.Display(children)
237 }
238 }
239
240 // Print the attribute of a node
241 type AttrDisplayer struct {
242 Attr string
243 }
244
245 func (a AttrDisplayer) Display(nodes []*html.Node) {
246 for _, node := range nodes {
247 attributes := node.Attr
248 for _, attr := range attributes {
249 if attr.Key == a.Attr {
250 val := attr.Val
251 if pupEscapeHTML {
252 val = html.EscapeString(val)
253 }
254 fmt.Printf("%s\n", val)
255 }
256 }
257 }
258 }
259
260 // Print nodes as a JSON list
261 type JSONDisplayer struct{}
262
263 // returns a jsonifiable struct
264 func jsonify(node *html.Node) map[string]interface{} {
265 vals := map[string]interface{}{}
266 if len(node.Attr) > 0 {
267 for _, attr := range node.Attr {
268 if pupEscapeHTML {
269 vals[attr.Key] = html.EscapeString(attr.Val)
270 } else {
271 vals[attr.Key] = attr.Val
272 }
273 }
274 }
275 vals["tag"] = node.DataAtom.String()
276 children := []interface{}{}
277 for child := node.FirstChild; child != nil; child = child.NextSibling {
278 switch child.Type {
279 case html.ElementNode:
280 children = append(children, jsonify(child))
281 case html.TextNode:
282 text := strings.TrimSpace(child.Data)
283 if text != "" {
284 if pupEscapeHTML {
285 // don't escape javascript
286 if node.DataAtom != atom.Script {
287 text = html.EscapeString(text)
288 }
289 }
290 // if there is already text we'll append it
291 currText, ok := vals["text"]
292 if ok {
293 text = fmt.Sprintf("%s %s", currText, text)
294 }
295 vals["text"] = text
296 }
297 case html.CommentNode:
298 comment := strings.TrimSpace(child.Data)
299 if pupEscapeHTML {
300 comment = html.EscapeString(comment)
301 }
302 currComment, ok := vals["comment"]
303 if ok {
304 comment = fmt.Sprintf("%s %s", currComment, comment)
305 }
306 vals["comment"] = comment
307 }
308 }
309 if len(children) > 0 {
310 vals["children"] = children
311 }
312 return vals
313 }
314
315 func (j JSONDisplayer) Display(nodes []*html.Node) {
316 var data []byte
317 var err error
318 jsonNodes := []map[string]interface{}{}
319 for _, node := range nodes {
320 jsonNodes = append(jsonNodes, jsonify(node))
321 }
322 data, err = json.MarshalIndent(&jsonNodes, "", pupIndentString)
323 if err != nil {
324 panic("Could not jsonify nodes")
325 }
326 fmt.Printf("%s\n", data)
327 }
328
329 // Print the number of features returned
330 type NumDisplayer struct{}
331
332 func (d NumDisplayer) Display(nodes []*html.Node) {
333 fmt.Println(len(nodes))
334 }