Debian Codegraph @

cmd/html2article/conv.go

raw symbols SCIP
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // This program takes an HTML file and outputs a corresponding article file in
6 // present format. See: golang.org/x/tools/present
7 package main // import "golang.org/x/tools/cmd/html2article"
8
9 import (
10 "bytes"
11 "errors"
12 "flag"
13 "fmt"
14 "io"
15 "log"
16 "net/url"
17 "os"
18 "regexp"
19 "slices"
20 "strings"
21
22 "golang.org/x/net/html"
23 "golang.org/x/net/html/atom"
24 )
25
26 func main() {
27 flag.Parse()
28
29 err := convert(os.Stdout, os.Stdin)
30 if err != nil {
31 log.Fatal(err)
32 }
33 }
34
35 func convert(w io.Writer, r io.Reader) error {
36 root, err := html.Parse(r)
37 if err != nil {
38 return err
39 }
40
41 style := find(root, isTag(atom.Style))
42 if err := parseStyles(style); err != nil {
43 log.Printf("couldn't parse all styles: %v", err)
44 }
45
46 body := find(root, isTag(atom.Body))
47 if body == nil {
48 return errors.New("couldn't find body")
49 }
50 article := limitNewlineRuns(makeHeadings(strings.TrimSpace(text(body))))
51 _, err = fmt.Fprintf(w, "Title\n\n%s", article)
52 return err
53 }
54
55 type Style string
56
57 const (
58 Bold Style = "*"
59 Italic Style = "_"
60 Code Style = "`"
61 )
62
63 var cssRules = make(map[string]Style)
64
65 func parseStyles(style *html.Node) error {
66 if style == nil || style.FirstChild == nil {
67 return errors.New("couldn't find styles")
68 }
69
70 styles := style.FirstChild.Data
71 readUntil := func(end rune) (string, bool) {
72 i := strings.IndexRune(styles, end)
73 if i < 0 {
74 return "", false
75 }
76 s := styles[:i]
77 styles = styles[i:]
78 return s, true
79 }
80
81 for {
82 sel, ok := readUntil('{')
83 if !ok && sel == "" {
84 break
85 } else if !ok {
86 return fmt.Errorf("could not parse selector %q", styles)
87 }
88
89 value, ok := readUntil('}')
90 if !ok {
91 return fmt.Errorf("couldn't parse style body for %s", sel)
92 }
93 switch {
94 case strings.Contains(value, "italic"):
95 cssRules[sel] = Italic
96 case strings.Contains(value, "bold"):
97 cssRules[sel] = Bold
98 case strings.Contains(value, "Consolas") || strings.Contains(value, "Courier New"):
99 cssRules[sel] = Code
100 }
101 }
102 return nil
103 }
104
105 var newlineRun = regexp.MustCompile(`\n\n+`)
106
107 func limitNewlineRuns(s string) string {
108 return newlineRun.ReplaceAllString(s, "\n\n")
109 }
110
111 func makeHeadings(body string) string {
112 buf := new(bytes.Buffer)
113 lines := strings.Split(body, "\n")
114 for i, s := range lines {
115 if i == 0 && !isBoldTitle(s) {
116 buf.WriteString("* Introduction\n\n")
117 }
118 if isBoldTitle(s) {
119 s = strings.TrimSpace(strings.Replace(s, "*", " ", -1))
120 s = "* " + s
121 }
122 buf.WriteString(s)
123 buf.WriteByte('\n')
124 }
125 return buf.String()
126 }
127
128 func isBoldTitle(s string) bool {
129 return !strings.Contains(s, " ") &&
130 strings.HasPrefix(s, "*") &&
131 strings.HasSuffix(s, "*")
132 }
133
134 func indent(buf *bytes.Buffer, s string) {
135 for l := range strings.SplitSeq(s, "\n") {
136 if l != "" {
137 buf.WriteByte('\t')
138 buf.WriteString(l)
139 }
140 buf.WriteByte('\n')
141 }
142 }
143
144 func unwrap(buf *bytes.Buffer, s string) {
145 var cont bool
146 for l := range strings.SplitSeq(s, "\n") {
147 l = strings.TrimSpace(l)
148 if len(l) == 0 {
149 if cont {
150 buf.WriteByte('\n')
151 buf.WriteByte('\n')
152 }
153 cont = false
154 } else {
155 if cont {
156 buf.WriteByte(' ')
157 }
158 buf.WriteString(l)
159 cont = true
160 }
161 }
162 }
163
164 func text(n *html.Node) string {
165 var buf bytes.Buffer
166 walk(n, func(n *html.Node) bool {
167 switch n.Type {
168 case html.TextNode:
169 buf.WriteString(n.Data)
170 return false
171 case html.ElementNode:
172 // no-op
173 default:
174 return true
175 }
176 a := n.DataAtom
177 if a == atom.Span {
178 switch {
179 case hasStyle(Code)(n):
180 a = atom.Code
181 case hasStyle(Bold)(n):
182 a = atom.B
183 case hasStyle(Italic)(n):
184 a = atom.I
185 }
186 }
187 switch a {
188 case atom.Br:
189 buf.WriteByte('\n')
190 case atom.P:
191 unwrap(&buf, childText(n))
192 buf.WriteString("\n\n")
193 case atom.Li:
194 buf.WriteString("- ")
195 unwrap(&buf, childText(n))
196 buf.WriteByte('\n')
197 case atom.Pre:
198 indent(&buf, childText(n))
199 buf.WriteByte('\n')
200 case atom.A:
201 href, text := attr(n, "href"), childText(n)
202 // Skip links with no text.
203 if strings.TrimSpace(text) == "" {
204 break
205 }
206 // Don't emit empty links.
207 if strings.TrimSpace(href) == "" {
208 buf.WriteString(text)
209 break
210 }
211 // Use original url for Google Docs redirections.
212 if u, err := url.Parse(href); err != nil {
213 log.Printf("parsing url %q: %v", href, err)
214 } else if u.Host == "www.google.com" && u.Path == "/url" {
215 href = u.Query().Get("q")
216 }
217 fmt.Fprintf(&buf, "[[%s][%s]]", href, text)
218 case atom.Code:
219 buf.WriteString(highlight(n, "`"))
220 case atom.B:
221 buf.WriteString(highlight(n, "*"))
222 case atom.I:
223 buf.WriteString(highlight(n, "_"))
224 case atom.Img:
225 src := attr(n, "src")
226 fmt.Fprintf(&buf, ".image %s\n", src)
227 case atom.Iframe:
228 src, w, h := attr(n, "src"), attr(n, "width"), attr(n, "height")
229 fmt.Fprintf(&buf, "\n.iframe %s %s %s\n", src, h, w)
230 case atom.Param:
231 if attr(n, "name") == "movie" {
232 // Old style YouTube embed.
233 u := attr(n, "value")
234 u = strings.Replace(u, "/v/", "/embed/", 1)
235 if i := strings.Index(u, "&"); i >= 0 {
236 u = u[:i]
237 }
238 fmt.Fprintf(&buf, "\n.iframe %s 540 304\n", u)
239 }
240 case atom.Title:
241 default:
242 return true
243 }
244 return false
245 })
246 return buf.String()
247 }
248
249 func childText(node *html.Node) string {
250 var buf bytes.Buffer
251 for n := node.FirstChild; n != nil; n = n.NextSibling {
252 fmt.Fprint(&buf, text(n))
253 }
254 return buf.String()
255 }
256
257 func highlight(node *html.Node, char string) string {
258 t := strings.Replace(childText(node), " ", char, -1)
259 return fmt.Sprintf("%s%s%s", char, t, char)
260 }
261
262 type selector func(*html.Node) bool
263
264 func isTag(a atom.Atom) selector {
265 return func(n *html.Node) bool {
266 return n.DataAtom == a
267 }
268 }
269
270 func hasClass(name string) selector {
271 return func(n *html.Node) bool {
272 for _, a := range n.Attr {
273 if a.Key == "class" {
274 if slices.Contains(strings.Fields(a.Val), name) {
275 return true
276 }
277 }
278 }
279 return false
280 }
281 }
282
283 func hasStyle(s Style) selector {
284 return func(n *html.Node) bool {
285 for rule, s2 := range cssRules {
286 if s2 != s {
287 continue
288 }
289 if strings.HasPrefix(rule, ".") && hasClass(rule[1:])(n) {
290 return true
291 }
292 if n.DataAtom.String() == rule {
293 return true
294 }
295 }
296 return false
297 }
298 }
299
300 func attr(node *html.Node, key string) (value string) {
301 for _, attr := range node.Attr {
302 if attr.Key == key {
303 return attr.Val
304 }
305 }
306 return ""
307 }
308
309 func find(n *html.Node, fn selector) *html.Node {
310 var result *html.Node
311 walk(n, func(n *html.Node) bool {
312 if result != nil {
313 return false
314 }
315 if fn(n) {
316 result = n
317 return false
318 }
319 return true
320 })
321 return result
322 }
323
324 func walk(n *html.Node, fn selector) {
325 if fn(n) {
326 for c := n.FirstChild; c != nil; c = c.NextSibling {
327 walk(c, fn)
328 }
329 }
330 }