hswg: separate rendering from link expansion

This commit is contained in:
Přemysl Eric Janouch 2021-06-22 02:08:56 +02:00
parent 8276f6bcb9
commit d763ce619d
Signed by: p
GPG Key ID: A0420B94F92B9493

View File

@ -138,6 +138,7 @@ type Entry struct {
PathSource string // path to source AsciiDoc
PathDestination string // path to destination HTML
mtime time.Time // modification time
raw []byte // raw inner document
Content template.HTML // inner document with expanded LinkWords
backlinks map[string]bool // what documents link back here
Backlinks []template.HTML
@ -189,9 +190,7 @@ func expand(m *map[string]*Entry, name string, chunk []byte) []byte {
var tagRE = regexp.MustCompile(`<[^<>]+>`)
func renderEntry(name string, entries *map[string]*Entry) error {
e := (*entries)[name]
func renderEntry(name string, e *Entry) error {
f, err := os.Open(e.PathSource)
if err != nil {
return err
@ -216,16 +215,7 @@ func renderEntry(name string, entries *map[string]*Entry) error {
e.Title = name
}
// 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.Content = template.HTML(expanded.String())
e.raw = html.Bytes()
return nil
}
@ -251,8 +241,8 @@ func loadEntries(globs []string) (map[string]*Entry, error) {
}
}
for name := range entries {
if err := renderEntry(name, &entries); err != nil {
for name, e := range entries {
if err := renderEntry(name, e); err != nil {
return nil, err
}
}
@ -279,6 +269,21 @@ func writeEntry(e *Entry, t *template.Template,
return t.Execute(f, e)
}
func finalizeEntries(entries *map[string]*Entry) {
for name, e := range *entries {
// Expand LinkWords anywhere between <tags>.
// We want something like the inverse of Regexp.ReplaceAllStringFunc.
raw, last, expanded := e.raw, 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.Content = template.HTML(expanded.String())
}
}
func writeIndex(t *template.Template, entries *map[string]*Entry) error {
// Reorder entries reversely, primarily by date, secondarily by filename.
ordered := []*Entry{}
@ -344,6 +349,8 @@ func main() {
if err != nil {
log.Fatalln(err)
}
finalizeEntries(&entries)
for _, e := range entries {
if err := writeEntry(e, t, &entries); err != nil {
log.Fatalln(err)