about summary refs log tree commit diff stats
path: root/internal/builder/template.go
blob: 0be32141f9f78559b46392321b1f9194a4102972 (plain)
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
package builder

import (
	"encoding/xml"
	"io"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"website/internal/atom"
	"website/internal/config"
	"website/internal/content"

	"github.com/PuerkitoBio/goquery"
	"github.com/antchfx/xmlquery"
	"github.com/antchfx/xpath"
	"github.com/pkg/errors"
)

var (
	css           string
	templateFiles = make(map[string]*os.File)
	nsMap         = map[string]string{
		"xsl":   "http://www.w3.org/1999/XSL/Transform",
		"atom":  "http://www.w3.org/2005/Atom",
		"xhtml": "http://www.w3.org/1999/xhtml",
	}
)

func loadCSS(source string) {
	bytes, err := os.ReadFile(filepath.Join(source, "templates/style.css"))
	if err != nil {
		panic(err)
	}
	css = string(bytes)
}

func loadTemplate(path string) (file *os.File, err error) {
	if templateFiles[path] == nil {
		file, err = os.OpenFile(path, os.O_RDONLY, 0)
		if err != nil {
			return nil, errors.Wrapf(err, "could not load template at path %s", path)
		}
		templateFiles[path] = file
	}
	file = templateFiles[path]

	return
}

type QuerySelection struct {
	*goquery.Selection
}

type QueryDocument struct {
	*goquery.Document
}

func NewDocumentFromReader(r io.Reader) (*QueryDocument, error) {
	doc, err := goquery.NewDocumentFromReader(r)

	return &QueryDocument{doc}, errors.Wrap(err, "could not create query document")
}

func (q *QueryDocument) Find(selector string) *QuerySelection {
	return &QuerySelection{q.Document.Find(selector)}
}

func renderRobotsTXT(source string, config *config.Config) (io.Reader, error) {
	r, w := io.Pipe()
	tpl, err := template.ParseFiles(filepath.Join(source, "templates/robots.tmpl"))
	if err != nil {
		return nil, err
	}
	go func() {
		err = tpl.Execute(w, map[string]interface{}{
			"BaseURL": config.BaseURL,
		})
		if err != nil {
			w.CloseWithError(err)
		}
		w.Close()
	}()

	return r, nil
}

func renderFeed(
	source string,
	title string,
	config *config.Config,
	posts []content.Post,
	specific string,
) (io.Reader, error) {
	reader, err := loadTemplate(filepath.Join(source, "templates/feed.xml"))
	if err != nil {
		return nil, err
	}
	defer func() {
		_, err := reader.Seek(0, io.SeekStart)
		if err != nil {
			panic("could not reset reader: " + err.Error())
		}
	}()
	doc, err := xmlquery.Parse(reader)
	if err != nil {
		return nil, errors.Wrap(err, "could not parse XML")
	}
	feed := doc.SelectElement("feed")
	feed.SelectElement("title").FirstChild.Data = title
	feed.SelectElement("link").SetAttr("href", config.BaseURL.String())
	feed.SelectElement("id").FirstChild.Data = atom.MakeTagURI(config, specific)
	datetime, err := posts[0].Date.UTC().MarshalText()
	if err != nil {
		return nil, errors.Wrap(err, "could not convert post date to text")
	}
	feed.SelectElement("updated").FirstChild.Data = string(datetime)
	tpl := feed.SelectElement("entry")
	xmlquery.RemoveFromTree(tpl)

	for _, post := range posts {
		fullURL := config.BaseURL.JoinPath(post.URL).String()
		text, err := xml.MarshalIndent(&atom.FeedEntry{
			Title:   post.Title,
			Link:    atom.MakeLink(fullURL),
			ID:      atom.MakeTagURI(config, post.Basename),
			Updated: post.Date.UTC(),
			Summary: post.Description,
			Author:  config.Title,
			Content: atom.FeedContent{
				Content: post.Content,
				Type:    "html",
			},
		}, "  ", "    ")
		if err != nil {
			return nil, errors.Wrap(err, "could not marshal xml")
		}
		entry, err := xmlquery.ParseWithOptions(
			strings.NewReader(string(text)),
			xmlquery.ParserOptions{
				Decoder: &xmlquery.DecoderOptions{
					Strict:    false,
					AutoClose: xml.HTMLAutoClose,
					Entity:    xml.HTMLEntity,
				},
			},
		)
		if err != nil {
			return nil, errors.Wrap(err, "could not parse XML")
		}
		xmlquery.AddChild(feed, entry.SelectElement("entry"))
	}

	return strings.NewReader(doc.OutputXML(true)), nil
}

func renderFeedStyles(source string) (*strings.Reader, error) {
	tpl, err := template.ParseFiles(filepath.Join(source, "templates/feed-styles.xsl"))
	if err != nil {
		return nil, err
	}

	esc := &strings.Builder{}
	err = xml.EscapeText(esc, []byte(css))
	if err != nil {
		return nil, err
	}

	w := &strings.Builder{}
	err = tpl.Execute(w, map[string]interface{}{
		"css": esc.String(),
	})

	return strings.NewReader(w.String()), nil
}

func getFeedStylesHash(r io.Reader) (string, error) {
	doc, err := xmlquery.Parse(r)
	if err != nil {
		return "", err
	}
	expr, err := xpath.CompileWithNS("//xhtml:style", nsMap)
	if err != nil {
		return "", errors.Wrap(err, "could not parse XPath")
	}
	style := xmlquery.QuerySelector(doc, expr)

	return hash(style.InnerText()), nil
}

func getHTMLStyleHash(filenames ...string) (string, error) {
	fn := filepath.Join(filenames...)
	f, err := os.Open(fn)
	if err != nil {
		return "", err
	}
	defer f.Close()
	doc, err := NewDocumentFromReader(f)
	if err != nil {
		return "", err
	}
	html := doc.Find("head > style").Text()

	return hash(html), nil
}