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
|
package blog
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/bmatcuk/doublestar/v4"
"github.com/pelletier/go-toml/v2"
"gopkg.in/yaml.v3"
)
// Blog is a collection of [Article]
type Blog struct {
indexTemplate *template.Template
articleTemplate *template.Template
Articles []Article
Author Author
}
// Article is a blog post/article
type Article struct {
Filename string
Content template.HTML
ArticleMeta
}
// ArticleMeta is the metadata of an [Article]
// The meta is parsed from frontmatter in an article
type ArticleMeta struct {
Title string
Subtitle string
Summary string
Time time.Time
Author Author
Tags []string
Category string
}
// Author is an author of a blog/post
type Author struct {
Name string
Job string
Email string
Links []Link
}
// Link is a link name and URL
type Link struct {
Name string
URL LinkURL
}
// LinkURL is a URL
type LinkURL url.URL
func (l *LinkURL) UnmarshalText(data []byte) error {
u, err := url.Parse(string(data))
if err != nil {
return err
}
*l = LinkURL(*u)
return nil
}
// NewBlog constructs a new blog from articles in articleDir and templates in templateDir
func NewBlog(articleDir, templateDir string, author Author) (*Blog, error) {
tmpl, err := parseTemplates(os.DirFS(templateDir))
if err != nil {
return nil, fmt.Errorf("could not parse templates in %q: %w", templateDir, err)
}
indexTmpl := tmpl.Lookup("index.tmpl")
if indexTmpl == nil {
indexTmpl = tmpl.Lookup("index")
if indexTmpl == nil {
return nil, errors.New("`index` template is required but was not found")
}
}
articleTmpl := tmpl.Lookup("article.tmpl")
if articleTmpl == nil {
articleTmpl = tmpl.Lookup("article")
if articleTmpl == nil {
return nil, errors.New("`article` template is required but was not found")
}
}
articles, err := parseArticles(os.DirFS(articleDir))
if err != nil {
return nil, fmt.Errorf("could not parse articles in %q: %w", articleDir, err)
}
return &Blog{
indexTemplate: indexTmpl,
articleTemplate: articleTmpl,
Articles: articles,
Author: author,
}, nil
}
// Index renders the blog index to w
func (b *Blog) Index(w io.Writer) error {
byCat := make(map[string][]Article)
for _, article := range b.Articles {
byCat[article.Category] = append(byCat[article.Category], article)
}
return b.indexTemplate.Execute(w, map[string]any{
"Articles": b.Articles,
"ArticlesByCategory": byCat,
"Author": b.Author,
})
}
// Article renders an article to w
func (b *Blog) Article(w io.Writer, a Article) error {
return b.articleTemplate.Execute(w, map[string]any{
"Article": a,
"Author": b.Author,
})
}
func parseTemplates(fs fs.FS) (*template.Template, error) {
matches, err := doublestar.Glob(fs, "**/*.{tmpl,gohtml}")
if err != nil {
return nil, fmt.Errorf("could not glob templates: %w", err)
}
tmpl, err := template.New("").ParseFS(fs, matches...)
if err != nil {
return nil, fmt.Errorf("could not parse templates: %w", err)
}
return tmpl, nil
}
func parseArticles(fs fs.FS) ([]Article, error) {
matches, err := doublestar.Glob(fs, "**/*.md")
if err != nil {
return nil, fmt.Errorf("could not glob articles: %w", err)
}
articles := make([]Article, 0, len(matches))
for _, match := range matches {
if err := func() error {
fi, err := fs.Open(match)
if err != nil {
return err
}
defer fi.Close()
content, err := io.ReadAll(fi)
if err != nil {
return err
}
article, err := parseArticle(string(content))
if err != nil {
return err
}
article.Filename = strings.TrimSuffix(filepath.Base(match), filepath.Ext(match))
articles = append(articles, article)
return nil
}(); err != nil {
return nil, err
}
}
sort.SliceStable(articles, func(i, j int) bool {
return articles[i].Time.After(articles[j].Time)
})
return articles, nil
}
func parseArticle(content string) (Article, error) {
lines := strings.Split(content, "\n")
start, end := -1, -1
var isSep func(string) bool
var decoder func([]byte, any) error
for idx, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
if isSep != nil && isSep(line) {
end = idx
break
}
if isTOMLSeparator(line) {
start = idx
isSep = isTOMLSeparator
decoder = toml.Unmarshal
continue
}
if isYAMLSeparator(line) {
start = idx
isSep = isYAMLSeparator
decoder = yaml.Unmarshal
continue
}
}
var meta ArticleMeta
body := content
if start != -1 && end != -1 {
body = strings.Join(lines[end+1:], "\n")
if err := decoder([]byte(strings.Join(lines[start+1:end], "\n")), &meta); err != nil {
return Article{}, fmt.Errorf("could not parse frontmatter: %w", err)
}
}
var buf bytes.Buffer
err := Markdown.Convert([]byte(body), &buf)
if err != nil {
return Article{}, fmt.Errorf("could not convert article: %w", err)
}
return Article{
Content: template.HTML(buf.String()),
ArticleMeta: meta,
}, nil
}
func isTOMLSeparator(line string) bool {
for _, char := range line {
if char != '+' {
return false
}
}
return true
}
func isYAMLSeparator(line string) bool {
for _, char := range line {
if char != '-' {
return false
}
}
return true
}
|