wiki/backref.go
Peter Stuifzand 725f1b8adb
All checks were successful
continuous-integration/drone/push Build is passing
Don't decode ID's
2020-05-30 23:31:34 +02:00

103 lines
1.8 KiB
Go

package main
import (
"encoding/json"
"html/template"
"os"
"path/filepath"
"strings"
)
type Reference struct {
Link ParsedLink
Name string
}
type Refs map[string][]Reference
func processBackrefs(fp *FilePages) error {
pages, err := fp.AllPages()
refs := make(Refs)
if err != nil {
return err
}
for _, page := range pages {
content := page.Content
var listItems []struct {
Indented int
Text string
}
err = json.NewDecoder(strings.NewReader(content)).Decode(&listItems)
if err == nil {
pageText := ""
for _, item := range listItems {
pageText += strings.Repeat(" ", item.Indented) + "* " + item.Text + "\n"
}
content = pageText
}
links, err := ParseLinks(content)
if err != nil {
return err
}
for _, link := range links {
refs[link.PageName] = append(refs[link.PageName], Reference{link, page.Name})
}
}
f, err := os.Create(filepath.Join(fp.dirname, "backrefs.json"))
if err != nil {
return err
}
defer f.Close()
err = json.NewEncoder(f).Encode(&refs)
return err
}
func loadBackrefs(fp *FilePages, p string) (map[string][]Backref, error) {
refs := make(Refs)
p = strings.Replace(p, " ", "_", -1)
f, err := os.Open(filepath.Join(fp.dirname, "backrefs.json"))
if err != nil {
return nil, err
}
defer f.Close()
err = json.NewDecoder(f).Decode(&refs)
if err != nil {
return nil, err
}
result := make(map[string][]Backref)
for _, ref := range refs[p] {
title := strings.Replace(ref.Name, "_", " ", -1)
if _, e := result[ref.Name]; !e {
result[ref.Name] = nil
}
links := renderLinks(strings.TrimLeft(ref.Link.Line, " *"))
pageText := renderMarkdown2(links)
result[ref.Name] = append(result[ref.Name], Backref{
Name: ref.Name,
Title: title,
Line: template.HTML(pageText),
})
}
return result, nil
}