-
Notifications
You must be signed in to change notification settings - Fork 3
/
gozer.go
530 lines (434 loc) · 12.4 KB
/
gozer.go
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package main
import (
"bytes"
_ "embed"
"encoding/xml"
"flag"
"fmt"
"html/template"
"io/fs"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/renderer/html"
)
var md = goldmark.New(
goldmark.WithRendererOptions(
html.WithUnsafe(),
),
goldmark.WithExtensions(extension.GFM, extension.Footnote))
var frontMatter = []byte("+++")
var templates *template.Template
//go:embed sitemap.xsl
var sitemapXSL []byte
type Site struct {
pages []Page
posts []Page
Title string `toml:"title"`
SiteUrl string `toml:"url"`
RootDir string
}
type Page struct {
// Title of this page
Title string
// Template this page uses for rendering. Defaults to "default.html".
Template string
// Time this page was published (parsed from file name).
DatePublished time.Time
// Time this page was last modified (from filesystem).
DateModified time.Time
// The full URL to this page (incl. site URL)
Permalink string
// URL path for this page, relative to site URL
UrlPath string
// Path to source file for this page, relative to content root
Filepath string
}
// parseFilename parses the URL path and optional date component from the given file path
func parseFilename(path string, rootDir string) (string, time.Time) {
path = filepath.ToSlash(path)
path = strings.TrimPrefix(path, rootDir+"content/")
path = strings.TrimSuffix(path, ".md")
path = strings.TrimSuffix(path, ".html")
path = strings.TrimSuffix(path, "index")
filename := filepath.Base(path)
if len(filename) > 11 && filename[4] == '-' && filename[7] == '-' && filename[10] == '-' {
date, err := time.Parse("2006-01-02", filename[0:10])
if err == nil {
return path[0:len(path)-len(filename)] + filename[11:] + "/", date
}
}
if path != "" && !strings.HasSuffix(path, "/") {
path += "/"
}
return path, time.Time{}
}
func parseFrontMatter(p *Page) error {
fh, err := os.Open(p.Filepath)
if err != nil {
return err
}
defer fh.Close()
buf := make([]byte, 1024)
n, err := fh.Read(buf)
if err != nil {
return err
}
buf = buf[:n]
if !bytes.HasPrefix(buf, frontMatter) {
return nil
}
// strip front matter prefix
buf = buf[3:]
// find pos of closing front matter
pos := bytes.Index(buf, frontMatter)
if pos == -1 {
return fmt.Errorf("missing closing front-matter identifier in %s", p.Filepath)
}
return toml.Unmarshal(buf[:pos], p)
}
func (p *Page) ParseContent() (string, error) {
fileContent, err := os.ReadFile(p.Filepath)
if err != nil {
return "", err
}
// Skip front matter
if len(fileContent) > 6 {
pos := bytes.Index(fileContent[3:], frontMatter)
if pos > -1 {
fileContent = fileContent[pos+6:]
}
}
// If source file has HTML extension, return content directly
if strings.HasSuffix(p.Filepath, ".html") {
return string(fileContent), nil
}
// Otherwise, parse as Markdown
var buf2 strings.Builder
if err := md.Convert(fileContent, &buf2); err != nil {
return "", err
}
return buf2.String(), nil
}
func (s *Site) buildPage(p *Page) error {
content, err := p.ParseContent()
if err != nil {
return err
}
dest := filepath.Join("build", p.UrlPath, "index.html")
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return err
}
fh, err := os.Create(dest)
if err != nil {
return err
}
defer fh.Close()
tmpl := templates.Lookup(p.Template)
if tmpl == nil {
return fmt.Errorf("invalid template name: %s", p.Template)
}
return tmpl.Execute(fh, map[string]any{
"Page": p,
"Posts": s.posts,
"Pages": s.pages,
"Site": map[string]string{
"Url": s.SiteUrl,
"Title": s.Title,
},
// Shorthand for accessing through .Page.Title / .Page.Content
"Title": p.Title,
"Content": template.HTML(content),
// Deprecated template variables, use .Site.Url instead
"SiteUrl": s.SiteUrl,
})
}
func (s *Site) AddPageFromFile(file string) error {
info, err := os.Stat(file)
if err != nil {
return err
}
urlPath, datePublished := parseFilename(file, s.RootDir)
p := Page{
Filepath: file,
UrlPath: urlPath,
Permalink: s.SiteUrl + urlPath,
DatePublished: datePublished,
DateModified: info.ModTime(),
Template: "default.html",
}
if err := parseFrontMatter(&p); err != nil {
return err
}
s.pages = append(s.pages, p)
// every page with a date is assumed to be a blog post
if !p.DatePublished.IsZero() {
s.posts = append(s.posts, p)
}
return nil
}
func (s *Site) readContent(dir string) error {
// walk over files in "content" directory
err := filepath.WalkDir(dir, func(file string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}
return s.AddPageFromFile(file)
})
// sort posts by date
sort.Slice(s.posts, func(i int, j int) bool {
return s.posts[i].DatePublished.After(s.posts[j].DatePublished)
})
return err
}
func (s *Site) createSitemap() error {
type Url struct {
XMLName xml.Name `xml:"url"`
Loc string `xml:"loc"`
LastMod string `xml:"lastmod"`
}
type Envelope struct {
XMLName xml.Name `xml:"urlset"`
XMLNS string `xml:"xmlns,attr"`
SchemaLocation string `xml:"xsi:schemaLocation,attr"`
XSI string `xml:"xmlns:xsi,attr"`
Image string `xml:"xmlns:image,attr"`
Urls []Url `xml:""`
}
urls := make([]Url, 0, len(s.pages))
for _, p := range s.pages {
urls = append(urls, Url{
Loc: p.Permalink,
LastMod: p.DateModified.Format(time.RFC3339),
})
}
env := Envelope{
SchemaLocation: "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd",
XMLNS: "http://www.sitemaps.org/schemas/sitemap/0.9",
XSI: "http://www.w3.org/2001/XMLSchema-instance",
Image: "http://www.google.com/schemas/sitemap-image/1.1",
Urls: urls,
}
sitemapFilename := filepath.Join("build", "sitemap.xml")
wr, err := os.Create(sitemapFilename)
if err != nil {
return err
}
defer wr.Close()
if _, err := wr.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>`)); err != nil {
return err
}
if err := xml.NewEncoder(wr).Encode(env); err != nil {
return err
}
// copy xml stylesheet
sitemapStylesheetFilename := filepath.Join("build", "sitemap.xsl")
if err := os.WriteFile(sitemapStylesheetFilename, sitemapXSL, 0655); err != nil {
return err
}
return nil
}
func (s *Site) createRSSFeed() error {
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
PubDate string `xml:"pubDate"`
GUID string `xml:"guid"`
}
type Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Generator string `xml:"generator"`
LastBuildDate string `xml:"lastBuildDate"`
Items []Item `xml:"item"`
}
type Feed struct {
XMLName xml.Name `xml:"rss"`
Version string `xml:"version,attr"`
Atom string `xml:"xmlns:atom,attr"`
Channel Channel `xml:"channel"`
}
// add 10 most recent posts to feed
n := len(s.posts)
if n > 10 {
n = 10
}
items := make([]Item, 0, n)
for _, p := range s.posts[0:n] {
pageContent, err := p.ParseContent()
if err != nil {
log.Warn("error parsing content of %s: %s", p.Filepath, err)
continue
}
items = append(items, Item{
Title: p.Title,
Link: p.Permalink,
Description: pageContent,
PubDate: p.DatePublished.Format(time.RFC1123Z),
GUID: p.Permalink,
})
}
feed := Feed{
Version: "2.0",
Atom: "http://www.w3.org/2005/Atom",
Channel: Channel{
Title: s.Title,
Link: s.SiteUrl,
Generator: "Gozer",
LastBuildDate: time.Now().Format(time.RFC1123Z),
Items: items,
},
}
rssFeedFilename := filepath.Join("build", "feed.xml")
wr, err := os.Create(rssFeedFilename)
if err != nil {
return err
}
defer wr.Close()
if _, err := wr.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?>`)); err != nil {
return err
}
if err := xml.NewEncoder(wr).Encode(feed); err != nil {
return err
}
return nil
}
// func to calculate and print execution time
func measure(name string) func() {
start := time.Now()
return func() {
log.Info("%s execution time: %v\n", name, time.Since(start))
}
}
func parseConfig(s *Site, file string) error {
_, err := toml.DecodeFile(file, s)
if err != nil {
return err
}
// ensure site url has trailing slash
if !strings.HasSuffix(s.SiteUrl, "/") {
s.SiteUrl += "/"
}
return nil
}
func main() {
configFile := "config.toml"
rootPath := ""
showHelp := false
// parse flags
flag.StringVar(&configFile, "config", configFile, "")
flag.StringVar(&configFile, "c", configFile, "")
flag.StringVar(&rootPath, "root", rootPath, "")
flag.StringVar(&rootPath, "r", rootPath, "")
flag.BoolVar(&showHelp, "help", showHelp, "")
flag.BoolVar(&showHelp, "h", showHelp, "")
flag.Parse()
command := os.Args[len(os.Args)-1]
if showHelp || (command != "build" && command != "serve" && command != "new") {
fmt.Printf(`Gozer - a fast & simple static site generator
Usage: gozer [OPTIONS] <COMMAND>
Commands:
build Deletes the output directory if there is one and builds the site
serve Builds the site and starts an HTTP server on http://localhost:8080
new Creates a new site structure in the given directory
Options:
-r, --root <ROOT> Directory to use as root of project (default: .)
-c, --config <CONFIG> Path to configuration file (default: config.toml)
`)
return
}
if command == "new" {
if err := createDirectoryStructure(rootPath); err != nil {
log.Fatal("Error creating site structure: ", err)
}
return
}
buildSite(rootPath, configFile)
if command == "serve" {
// setup fsnotify watcher
go watchDirs([]string{
filepath.Join(rootPath, "content"),
filepath.Join(rootPath, "public"),
filepath.Join(rootPath, "templates"),
}, func() {
buildSite(rootPath, configFile)
})
// serve site
log.Info("Listening on http://localhost:8080\n")
_ = http.ListenAndServe("localhost:8080", http.FileServer(http.Dir("build")))
}
}
func createDirectoryStructure(rootPath string) error {
for _, dir := range []string{"content", "templates", "public"} {
if err := os.Mkdir(filepath.Join(rootPath, dir), 0755); err != nil {
return err
}
}
files := []struct {
Name string
Content []byte
}{
{"config.toml", []byte("url = \"http://localhost:8080\"\ntitle = \"My website\"\n")},
{"templates/default.html", []byte("<!DOCTYPE html>\n<head>\n\t<title>{{ .Title }}</title>\n</head>\n<body>\n{{ .Content }}\n</body>\n</html>")},
{"content/index.md", []byte("+++\ntitle = \"Gozer!\"\n+++\n\nWelcome to my website.\n")},
}
for _, f := range files {
if err := os.WriteFile(filepath.Join(rootPath, f.Name), f.Content, 0655); err != nil {
return err
}
}
return nil
}
func buildSite(rootPath string, configFile string) {
var err error
timeStart := time.Now()
templates, err = template.ParseGlob(filepath.Join(rootPath, "templates/*.html"))
if err != nil {
log.Fatal("Error reading templates/ directory: %s", err)
}
// read config.xml
site := &Site{
RootDir: rootPath,
}
if err := parseConfig(site, filepath.Join(rootPath, configFile)); err != nil {
log.Fatal("Error reading configuration file at %s: %w\n", rootPath+configFile, err)
}
// read content
if err := site.readContent(filepath.Join(rootPath, "content")); err != nil {
log.Fatal("Error reading content/: %s", err)
}
var wg sync.WaitGroup
// build each individual page
for _, p := range site.pages {
wg.Add(1)
go func(p Page) {
if err := site.buildPage(&p); err != nil {
log.Warn("Error processing %s: %s\n", p.Filepath, err)
}
wg.Done()
}(p)
}
wg.Wait()
// create XML sitemap
if err := site.createSitemap(); err != nil {
log.Warn("Error creating sitemap: %s\n", err)
}
// create RSS feed
if err := site.createRSSFeed(); err != nil {
log.Warn("Error creating RSS feed: %s\n", err)
}
// static files
if err := copyDirRecursively(filepath.Join(rootPath, "public"), "build"); err != nil {
log.Fatal("Error copying public/ directory: %s", err)
}
log.Info("Built %d pages in %d ms\n", len(site.pages), time.Since(timeStart).Milliseconds())
}