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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
|
// Program hswg is a static website generator employing libasciidoc with added
// support for two-line/underlined titles, and postprocessing "wiki" InterLinks.
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/bytesparadise/libasciidoc"
"github.com/bytesparadise/libasciidoc/pkg/configuration"
"github.com/bytesparadise/libasciidoc/pkg/types"
)
// isTitle returns the title level if the lines seem to form a title,
// zero otherwise. Input lines may inclide trailing newlines.
func isTitle(line1, line2 []byte) int {
// This is a very naïve method, we should target graphemes (thus at least
// NFC normalize the lines first) and account for wide characters.
diff := utf8.RuneCount(line1) - utf8.RuneCount(line2)
if len(line2) < 2 || diff < -1 || diff > 1 {
return 0
}
// "Don't be fooled by back-to-back delimited blocks."
// Still gets fooled by other things, though.
if bytes.IndexFunc(line1, func(r rune) bool {
return unicode.IsLetter(r) || unicode.IsNumber(r)
}) < 0 {
return 0
}
// The underline must be homogenous.
for _, r := range bytes.TrimRight(line2, "\r\n") {
if r != line2[0] {
return 0
}
}
return 1 + strings.IndexByte("=-~^+", line2[0])
}
func writeLine(w *io.PipeWriter, cur, next []byte) []byte {
if level := isTitle(cur, next); level > 0 {
w.Write(append(bytes.Repeat([]byte{'='}, level), ' '))
next = nil
}
w.Write(cur)
return next
}
// ConvertTitles converts AsciiDoc two-line (underlined) titles to single-line.
func ConvertTitles(w *io.PipeWriter, input []byte) {
var last []byte
for _, cur := range bytes.SplitAfter(input, []byte{'\n'}) {
last = writeLine(w, last, cur)
}
writeLine(w, last, nil)
}
// Render converts an io.Reader with an AsciiDoc document to HTML. So long as
// the file could be read at all, it will always return a non-empty document.
func Render(doc io.Reader, config configuration.Configuration) (
html *bytes.Buffer, meta types.Metadata, err error) {
html = bytes.NewBuffer(nil)
var input []byte
if input, err = ioutil.ReadAll(doc); err != nil {
return
}
pr, pw := io.Pipe()
go func() {
defer pw.Close()
ConvertTitles(pw, input)
}()
// io.Copy(os.Stdout, pr)
// return
meta, err = libasciidoc.ConvertToHTML(pr, html, config)
if err != nil {
// Fallback: output all the text sanitized for direct inclusion.
html.Reset()
_, _ = html.WriteString("<pre>")
for _, line := range bytes.Split(input, []byte{'\n'}) {
_ = xml.EscapeText(html, line)
_, _ = html.WriteString("\n")
}
_, _ = html.WriteString("</pre>")
}
return
}
// entry contains all context information about a single page.
type entry struct {
path string // path
mtime time.Time // modification time
metadata types.Metadata // metadata
document []byte // inner document with expanded LinkWords
backlinks []string // what documents link back here
}
var extRE = regexp.MustCompile(`\.[^/.]*$`)
func stripExtension(path string) string {
return extRE.ReplaceAllString(path, "")
}
func resultPath(path string) string {
if m := extRE.FindStringIndex(path); m != nil {
return path[:m[0]] + ".html"
}
return path + ".html"
}
func makeLink(m *map[string]*entry, name string) string {
e := (*m)[name]
return fmt.Sprintf("<a href='%s'>%s</a>", resultPath(e.path), name)
}
var linkWordRE = regexp.MustCompile(`\b\p{Lu}\p{L}*\b`)
func expand(m *map[string]*entry, name string, chunk []byte) []byte {
return linkWordRE.ReplaceAllFunc(chunk, func(match []byte) []byte {
if link, ok := (*m)[string(match)]; ok {
link.backlinks = append(link.backlinks, name)
return []byte(makeLink(m, string(match)))
}
return match
})
}
func singleFile() {
html, meta, err := Render(os.Stdin, configuration.NewConfiguration())
if err != nil {
log.Println(err)
} else if meta.Title != "" {
_, _ = os.Stdout.WriteString("<h1>")
_ = xml.EscapeText(os.Stdout, []byte(meta.Title))
_, _ = os.Stdout.WriteString("</h1>\n")
}
_, _ = io.Copy(os.Stdout, html)
}
func main() {
if len(os.Args) < 2 {
singleFile()
return
}
if len(os.Args) < 3 {
log.Fatalf("usage: %s TEMPLATE GLOB...\n", os.Args[0])
}
// Read the common page header.
header, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatalln(err)
}
// Create a map from document names to their page entries.
entries := map[string]*entry{}
for _, glob := range os.Args[2:] {
matches, err := filepath.Glob(glob)
if err != nil {
log.Fatalf("%s: %s\n", glob, err)
}
for _, path := range matches {
name := stripExtension(filepath.Base(path))
if conflict, ok := entries[name]; ok {
log.Fatalf("%s: conflicts with %s\n", name, conflict.path)
}
entries[name] = &entry{path: path}
}
}
tagRE := regexp.MustCompile(`<[^<>]+>`)
for name, e := range entries {
f, err := os.Open(e.path)
if err != nil {
log.Fatalln(err)
}
if i, err := f.Stat(); err != nil {
log.Fatalln(err)
} else {
e.mtime = i.ModTime()
}
var html *bytes.Buffer
if html, e.metadata, err = Render(f, configuration.NewConfiguration(
configuration.WithFilename(e.path),
configuration.WithLastUpdated(e.mtime),
)); err != nil {
log.Fatalln(err)
}
// Expand LinkWords anywhere between <tags>.
// We want something like the inverse of Regexp.ReplaceAllStringFunc.
raw, last, expanded := html.Bytes(), 0, bytes.NewBuffer(nil)
for _, where := range tagRE.FindAllIndex(raw, -1) {
_, _ = expanded.Write(expand(&entries, name, raw[last:where[0]]))
_, _ = expanded.Write(raw[where[0]:where[1]])
last = where[1]
}
_, _ = expanded.Write(expand(&entries, name, raw[last:]))
e.document = expanded.Bytes()
}
for name, e := range entries {
f, err := os.Create(resultPath(e.path))
if err != nil {
log.Fatalln(err)
}
_, _ = f.Write(header)
title := e.metadata.Title
if title == "" {
title = name
}
_, _ = f.WriteString(fmt.Sprintf("<title>%s</title>\n", title))
_, _ = f.WriteString(fmt.Sprintf("<h1>%s</h1>\n", title))
sort.Strings(e.backlinks)
backlinks, last := []string{}, ""
for _, name := range e.backlinks {
if name != last {
backlinks = append(backlinks, makeLink(&entries, name))
}
last = name
}
if len(backlinks) > 0 {
_, _ = f.WriteString(fmt.Sprintf("<p id=links>Links here: %s</p>\n",
strings.Join(backlinks, ", ")))
}
_, _ = f.Write(e.document)
_, _ = f.WriteString(fmt.Sprintf("<p id=footer>Last updated: %s"+
" — <a href='%s'>Source</p>\n",
e.metadata.LastUpdated, e.path))
}
}
|