-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsite_generator.go
3311 lines (3209 loc) · 94.7 KB
/
site_generator.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package notebrew
import (
"bufio"
"bytes"
"context"
"database/sql"
"encoding/binary"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"math"
"net/url"
"path"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"text/template/parse"
"time"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/bokwoon95/notebrew/internal/highlighting"
"github.com/bokwoon95/notebrew/internal/markdownmath"
"github.com/bokwoon95/notebrew/sq"
"github.com/bokwoon95/notebrew/stacktrace"
"github.com/davecgh/go-spew/spew"
"github.com/jdkato/prose/transform"
fences "github.com/stefanfritsch/goldmark-fences"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
goldmarkhtml "github.com/yuin/goldmark/renderer/html"
"golang.org/x/net/html"
"golang.org/x/sync/errgroup"
)
// SiteGenerator is used to generate pages and posts for a particular site.
type SiteGenerator struct {
// Site information.
Site Site
// fsys is the FS to generate pages and posts in.
fsys FS
// sitePrefix is the site prefix.
sitePrefix string
// contentDomain is the domain that the site's generated content is served
// on.
contentDomain string
// contentDomainHTTPS indicates whether the content domain is served over
// HTTPS.
contentDomainHTTPS bool
// cdnDomain is the domain of the CDN that is used for hosting images.
cdnDomain string
// markdown is the goldmark parser and renderer used to generate from the
// site's markdown files.
markdown goldmark.Markdown
// funcMap stores the template funcMap used by the site's templates.
funcMap map[string]any
// mutex is used to guard access to templateCache, templateInProgress and
// imgFileIDs.
mutex sync.Mutex
// templateCache caches already-parsed templates, keyed by their file path
// (relative to the sitePrefix).
templateCache map[string]*template.Template
// templateInProgress stores wait channels of the templates whose parsing
// are currently in progress. If a wait channel is present, all code
// looking to parse a template should wait until the channel returns, then
// check the template cache for the already-parsed template. This ensures
// that goroutines do not parse the same template twice -- one goroutine
// will always parse the templates first, the rest will wait for the result
// and fetch it from the templateCache map.
templateInProgress map[string]chan struct{}
// imgFileIDs stores a mapping of image file paths to their file IDs. This
// is used for rewriting image URLs into their CDN links, which references
// images by their file IDs.
imgFileIDs map[string]ID
}
// NavigationLink represents a navigation link to be displayed in the site's
// navigation menu.
type NavigationLink struct {
// Name of the link.
Name string
// URL of the link.
URL string
}
// Site holds the global properties of a site.
type Site struct {
// Language code of the site.
LanguageCode string
// Title of the site.
Title string
// Tagline of the site.
Tagline string
// Favicon of the site.
Favicon template.URL
// The site's timezone offset in seconds.
TimezoneOffsetSeconds int
// Description of the site.
Description string
// NavigationLinks of the site.
NavigationLinks []NavigationLink
}
// SiteGeneratorConfig holds the parameters needed to construct a new SiteGenerator.
type SiteGeneratorConfig struct {
// FS is the filesystem that holds the site content.
FS FS
// ContentDomain is the domain that the site's generated content is served
// on.
ContentDomain string
// ContentDomainHTTPS indicates whether the content domain is served over
// HTTPS.
ContentDomainHTTPS bool
// CDNDomain is the domain of the CDN that is used for hosting images.
CDNDomain string
// SitePrefix is the site prefix of the site.
SitePrefix string
}
// NewSiteGenerator constructs a new SiteGenerator.
func NewSiteGenerator(ctx context.Context, siteGenConfig SiteGeneratorConfig) (*SiteGenerator, error) {
siteGen := &SiteGenerator{
fsys: siteGenConfig.FS,
sitePrefix: siteGenConfig.SitePrefix,
contentDomain: siteGenConfig.ContentDomain,
contentDomainHTTPS: siteGenConfig.ContentDomainHTTPS,
cdnDomain: siteGenConfig.CDNDomain,
funcMap: map[string]any{},
mutex: sync.Mutex{},
templateCache: make(map[string]*template.Template),
templateInProgress: make(map[string]chan struct{}),
}
var config struct {
LanguageCode string
Title string
Tagline string
Emoji string
Favicon string
CodeStyle string
TimezoneOffset string
Description string
NavigationLinks []NavigationLink
}
// Read from the site's site.json.
b, err := fs.ReadFile(siteGen.fsys, path.Join(siteGen.sitePrefix, "site.json"))
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, stacktrace.New(err)
}
if len(b) > 0 {
err := json.Unmarshal(b, &config)
if err != nil {
fmt.Printf("%s\n", string(b))
return nil, stacktrace.New(err)
}
} else {
config.Emoji = "☕"
config.NavigationLinks = []NavigationLink{
{Name: "Home", URL: "/"},
{Name: "Posts", URL: "/posts/"},
}
}
if config.LanguageCode == "" {
config.LanguageCode = "en"
}
if config.Favicon == "" {
emoji := config.Emoji
if emoji == "" {
emoji = "☕"
}
config.Favicon = "data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 10 10%22><text y=%221em%22 font-size=%228%22>" + emoji + "</text></svg>"
}
if config.CodeStyle == "" {
config.CodeStyle = "onedark"
}
// Prepare the site's markdown parser and renderer based on their code
// syntax highlighter style.
siteGen.markdown = goldmark.New(
goldmark.WithParserOptions(
parser.WithAttribute(),
),
goldmark.WithExtensions(
highlighting.NewHighlighting(
highlighting.WithStyle(config.CodeStyle),
highlighting.WithFormatOptions(chromahtml.TabWidth(2)),
),
extension.Footnote,
extension.CJK,
markdownmath.Extension,
&fences.Extender{},
),
goldmark.WithRendererOptions(
goldmarkhtml.WithHardWraps(),
goldmarkhtml.WithUnsafe(),
),
)
for name, fn := range baseFuncMap {
siteGen.funcMap[name] = fn
}
siteGen.funcMap["markdownToHTML"] = func(x any) (template.HTML, error) {
if s, ok := x.(string); ok {
var b strings.Builder
err := siteGen.markdown.Convert([]byte(s), &b)
if err != nil {
return "", err
}
return template.HTML(b.String()), nil
}
return "", fmt.Errorf("%#v is not a string", x)
}
siteGen.funcMap["markdownTextOnly"] = func(x any) (string, error) {
if s, ok := x.(string); ok {
return markdownTextOnly(siteGen.markdown.Parser(), []byte(s)), nil
}
return "", fmt.Errorf("%#v is not a string", x)
}
var timezoneOffsetSeconds int
if strings.HasPrefix(config.TimezoneOffset, "+") || strings.HasPrefix(config.TimezoneOffset, "-") {
before, after, ok := strings.Cut(config.TimezoneOffset, ":")
hours, err := strconv.Atoi(before)
if err == nil && hours >= -12 && hours <= 14 {
if ok {
minutes, err := strconv.Atoi(after)
if err == nil && minutes >= 0 && minutes <= 59 {
timezoneOffsetSeconds = ((hours * 60) + minutes) * 60
}
} else {
timezoneOffsetSeconds = hours * 60 * 60
}
}
}
siteGen.Site = Site{
LanguageCode: config.LanguageCode,
Title: config.Title,
Tagline: config.Tagline,
Favicon: template.URL(config.Favicon),
TimezoneOffsetSeconds: timezoneOffsetSeconds,
NavigationLinks: config.NavigationLinks,
}
if config.Description != "" {
siteGen.Site.Description = config.Description
}
if siteGen.cdnDomain == "" {
return siteGen, nil
}
databaseFS, isDatabaseFS := &DatabaseFS{}, false
switch v := siteGen.fsys.(type) {
case interface{ As(any) bool }:
isDatabaseFS = v.As(&databaseFS)
}
if !isDatabaseFS {
return siteGen, nil
}
extFilter := sq.Expr("1 = 1")
if len(imgExts) > 0 {
var b strings.Builder
args := make([]any, 0, len(imgExts))
b.WriteString("(")
for i, ext := range imgExts {
if i > 0 {
b.WriteString(" OR ")
}
b.WriteString("file_path LIKE {} ESCAPE '\\'")
args = append(args, "%"+wildcardReplacer.Replace(ext))
}
b.WriteString(")")
extFilter = sq.Expr(b.String(), args...)
}
cursor, err := sq.FetchCursor(ctx, databaseFS.DB, sq.Query{
Dialect: databaseFS.Dialect,
Format: "SELECT {*}" +
" FROM files" +
" WHERE file_path LIKE {pattern} ESCAPE '\\'" +
" AND {extFilter}",
Values: []any{
sq.StringParam("pattern", wildcardReplacer.Replace(path.Join(siteGen.sitePrefix, "output"))+"/%"),
sq.Param("extFilter", extFilter),
},
}, func(row *sq.Row) (result struct {
FileID ID
FilePath string
}) {
result.FileID = row.UUID("file_id")
result.FilePath = row.String("file_path")
return result
})
if err != nil {
return nil, stacktrace.New(err)
}
defer cursor.Close()
siteGen.imgFileIDs = make(map[string]ID)
for cursor.Next() {
result, err := cursor.Result()
if err != nil {
return nil, stacktrace.New(err)
}
siteGen.imgFileIDs[result.FilePath] = result.FileID
}
err = cursor.Close()
if err != nil {
return nil, stacktrace.New(err)
}
return siteGen, nil
}
// ParseTemplate parses text as a template body for name. Template references
// starting with "/themes/" and ending in ".html" will be looked for in the
// site's themes folder.
func (siteGen *SiteGenerator) ParseTemplate(ctx context.Context, name, text string) (*template.Template, error) {
return siteGen.parseTemplate(ctx, name, text, nil)
}
// parseTemplate is the auxiliary recursive function that ParseTemplate calls.
// The callers argument is used to keep track of the templates responsible for
// calling parseTemplate each time, so that we can detect if we are in a loop.
func (siteGen *SiteGenerator) parseTemplate(ctx context.Context, name, text string, callers []string) (*template.Template, error) {
currentTemplate, err := template.New(name).Funcs(siteGen.funcMap).Parse(text)
if err != nil {
return nil, NewTemplateError(err)
}
internalTemplates := currentTemplate.Templates()
slices.SortFunc(internalTemplates, func(a, b *template.Template) int {
return strings.Compare(a.Name(), b.Name())
})
for _, tmpl := range internalTemplates {
internalName := tmpl.Name()
if strings.HasSuffix(internalName, ".html") && internalName != name {
return nil, TemplateError{
Name: name,
ErrorMessage: "define " + strconv.Quote(internalName) + ": internal template name cannot end with .html",
}
}
}
// Get the list of external templates referenced by the current template.
var externalNames []string
var node parse.Node
var nodes []parse.Node
for _, tmpl := range internalTemplates {
if tmpl.Tree == nil || tmpl.Tree.Root == nil {
continue
}
nodes = append(nodes, tmpl.Tree.Root.Nodes...)
for len(nodes) > 0 {
node, nodes = nodes[len(nodes)-1], nodes[:len(nodes)-1]
switch node := node.(type) {
case *parse.ListNode:
if node == nil {
continue
}
nodes = append(nodes, node.Nodes...)
case *parse.BranchNode:
nodes = append(nodes, node.List, node.ElseList)
case *parse.RangeNode:
nodes = append(nodes, node.List, node.ElseList)
case *parse.TemplateNode:
if strings.HasSuffix(node.Name, ".html") {
if !strings.HasPrefix(node.Name, "/themes/") {
return nil, TemplateError{
Name: name,
ErrorMessage: "template " + strconv.Quote(node.Name) + ": external template name must start with /themes/",
}
}
externalNames = append(externalNames, node.Name)
}
}
}
}
// Sort the list of external template names so that looping through them
// becomes deterministic.
slices.Sort(externalNames)
externalNames = slices.Compact(externalNames)
group, groupctx := errgroup.WithContext(ctx)
externalTemplates := make([]*template.Template, len(externalNames))
for i, externalName := range externalNames {
i, externalName := i, externalName
group.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
n := slices.Index(callers, externalName)
if n >= 0 {
return TemplateError{
Name: externalName,
ErrorMessage: "circular template reference: " + strings.Join(callers[n:], "=>") + " => " + externalName,
}
}
// If a template is currently being parsed, wait for it to finish
// before checking the templateCache for the result.
siteGen.mutex.Lock()
wait := siteGen.templateInProgress[externalName]
siteGen.mutex.Unlock()
if wait != nil {
select {
case <-groupctx.Done():
return err
case <-wait:
break
}
}
siteGen.mutex.Lock()
cachedTemplate, ok := siteGen.templateCache[externalName]
siteGen.mutex.Unlock()
if ok {
// We found the template; add it to the slice and exit. Note
// that the cachedTemplate may be nil, if parsing that template
// had resulted in errors.
externalTemplates[i] = cachedTemplate
return nil
}
// We put a nil pointer into the templateCache first. This is to
// indicate that we have already seen this template. If parsing
// succeeds, we simply overwrite the nil entry with the parsed
// template. If we fail, the cachedTemplate pointer stays nil and
// should be treated as a signal by other goroutines that parsing
// this template has errors. Other goroutines are blocked from
// accessing the cachedTemplate pointer until the wait channel is
// closed by the defer function below (which is once this goroutine
// exits).
wait = make(chan struct{})
siteGen.mutex.Lock()
siteGen.templateCache[externalName] = nil
siteGen.templateInProgress[externalName] = wait
siteGen.mutex.Unlock()
defer func() {
siteGen.mutex.Lock()
siteGen.templateCache[externalName] = cachedTemplate
delete(siteGen.templateInProgress, externalName)
close(wait)
siteGen.mutex.Unlock()
}()
file, err := siteGen.fsys.WithContext(groupctx).Open(path.Join(siteGen.sitePrefix, "output", externalName))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return TemplateError{
Name: name,
ErrorMessage: "template " + strconv.Quote(externalName) + " does not exist",
}
}
return stacktrace.New(err)
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
return stacktrace.New(err)
}
if fileInfo.IsDir() {
return TemplateError{
Name: name,
ErrorMessage: strconv.Quote(externalName) + " is a folder",
}
}
var b strings.Builder
b.Grow(int(fileInfo.Size()))
_, err = io.Copy(&b, file)
if err != nil {
return stacktrace.New(err)
}
err = file.Close()
if err != nil {
return stacktrace.New(err)
}
newCallers := append(append(make([]string, 0, len(callers)+1), callers...), externalName)
externalTemplate, err := siteGen.parseTemplate(groupctx, externalName, b.String(), newCallers)
if err != nil {
return err
}
// Important! Before we execute any template, it must be cloned.
// This is because once a template has been executed it is no
// longer pristine i.e. it cannot be added to another template
// using AddParseTree (html/template has this restriction in order
// for its contextually auto-escaped HTML feature to work).
externalTemplates[i], err = externalTemplate.Clone()
if err != nil {
return stacktrace.New(err)
}
cachedTemplate = externalTemplate
return nil
})
}
err = group.Wait()
if err != nil {
return nil, err
}
finalTemplate := template.New(name).Funcs(siteGen.funcMap)
for i, externalTemplate := range externalTemplates {
if externalTemplate == nil {
// Got a nil pointer dereference one time (externalTemplate ==
// nil), could not replicate it. Should not be possible. If the
// errgroup returned no errors, every template pointer in the
// externalTemplates slice should be populated. If externalTemplate
// is somehow nil, return it as an error and include the context.
return nil, stacktrace.New(fmt.Errorf("for some reason, external template %q as mentioned in %q is nil", externalNames[i], name))
}
for _, tmpl := range externalTemplate.Templates() {
_, err = finalTemplate.AddParseTree(tmpl.Name(), tmpl.Tree)
if err != nil {
return nil, TemplateError{
Name: name,
ErrorMessage: fmt.Sprintf("%s: add %s: %s", externalNames[i], tmpl.Name(), err),
}
}
}
}
for _, tmpl := range internalTemplates {
_, err = finalTemplate.AddParseTree(tmpl.Name(), tmpl.Tree)
if err != nil {
return nil, TemplateError{
Name: name,
ErrorMessage: fmt.Sprintf("add %s: %s", tmpl.Name(), err),
}
}
}
return finalTemplate.Lookup(name), nil
}
// PageData is the data used to render a page.
type PageData struct {
// Site information.
Site Site
// Parent URL of the page.
Parent string
// Name of the page.
Name string
// Title of the page.
Title string
// ChildPages of the page.
ChildPages []Page
// ContentMap of markdown file names to their file contents. Convert it to
// HTML using the markdownToHTML template function.
ContentMap map[string]string
// Images belonging to the page.
Images []Image
// ModificationTime of the page.
ModificationTime time.Time
// CreationTime of the page.
CreationTime time.Time
}
// Page contains metadata about a page.
type Page struct {
// Parent URL of the page.
Parent string
// Name of the page.
Name string
// Title of the page.
Title string
}
// Image contains metadata about an image.
type Image struct {
// Parent URL of the image.
Parent string
// Name of the image.
Name string
// AltText of the image.
AltText string
// Caption of the image.
Caption string
}
var (
titleConverter = transform.NewTitleConverter(transform.APStyle)
urlSeparatorReplacer = strings.NewReplacer("-", " ", "_", " ")
)
// GeneratePage generates a page. filePath is the file path to the source .html
// page in the pages/ directory, text is the source text of the page, modTime
// and creationTime are when the page was modified and created.
func (siteGen *SiteGenerator) GeneratePage(ctx context.Context, filePath, text string, modTime, creationTime time.Time) error {
// urlPath is the URL of the resultant page.
urlPath := strings.TrimPrefix(filePath, "pages/")
if urlPath == "index.html" {
urlPath = ""
} else {
urlPath = strings.TrimSuffix(urlPath, path.Ext(urlPath))
}
// Sanity check: /posts/ and /themes/ are reserved for user posts and user
// themes, we absolutely do not want to generate any page here or else it
// might overwrite existing user posts and themes.
if urlPath == "posts" || urlPath == "themes" {
return stacktrace.New(fmt.Errorf("attempted to generate page in %s", path.Join(siteGen.sitePrefix, "output", urlPath)))
}
// outputDir is where we will render the page output to.
outputDir := path.Join(siteGen.sitePrefix, "output", urlPath)
pageData := PageData{
Site: siteGen.Site,
Parent: path.Dir(urlPath),
Name: path.Base(urlPath),
ChildPages: []Page{},
ContentMap: make(map[string]string),
Images: []Image{},
ModificationTime: modTime.UTC(),
CreationTime: creationTime.UTC(),
}
if pageData.Parent == "." {
pageData.Parent = ""
}
if pageData.Name == "." {
pageData.Name = ""
}
line, _, _ := strings.Cut(text, "\n")
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "<!--") && strings.HasSuffix(line, "-->") {
line := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "<!--"), "-->"))
if strings.HasPrefix(line, "#title ") {
pageData.Title = strings.TrimSpace(strings.TrimPrefix(line, "#title "))
}
} else if strings.HasPrefix(line, "<title>") && strings.HasSuffix(line, "</title>") {
pageData.Title = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "<title>"), "</title>"))
}
if pageData.Title == "" {
pageData.Title = titleConverter.Title(urlSeparatorReplacer.Replace(pageData.Name))
}
var err error
var tmpl *template.Template
group, groupctx := errgroup.WithContext(ctx)
// Parse the page template.
group.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
tmpl, err = siteGen.ParseTemplate(groupctx, "/"+filePath, text)
if err != nil {
return err
}
return nil
})
// Fetch all the images, videos and markdown files that belong to the page.
group.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
markdownMu := sync.Mutex{}
databaseFS, isDatabaseFS := &DatabaseFS{}, false
switch v := siteGen.fsys.(type) {
case interface{ As(any) bool }:
isDatabaseFS = v.As(&databaseFS)
}
if isDatabaseFS {
var b strings.Builder
args := make([]any, 0, len(imgExts)+1)
b.WriteString("(file_path LIKE '%.md' ESCAPE '\\'")
for _, ext := range imgExts {
b.WriteString(" OR file_path LIKE {} ESCAPE '\\'")
args = append(args, "%"+wildcardReplacer.Replace(ext))
}
b.WriteString(")")
extFilter := sq.Expr(b.String(), args...)
cursor, err := sq.FetchCursor(groupctx, databaseFS.DB, sq.Query{
Dialect: databaseFS.Dialect,
Format: "SELECT {*}" +
" FROM files" +
" WHERE parent_id = (SELECT file_id FROM files WHERE file_path = {outputDir})" +
" AND NOT is_dir" +
" AND {extFilter}" +
" ORDER BY file_path",
Values: []any{
sq.StringParam("outputDir", outputDir),
sq.Param("extFilter", extFilter),
},
}, func(row *sq.Row) (result struct {
FilePath string
Text []byte
}) {
result.FilePath = row.String("file_path")
result.Text = row.Bytes(bufPool.Get().(*bytes.Buffer).Bytes(), "text")
return result
})
if err != nil {
return stacktrace.New(err)
}
defer cursor.Close()
subgroup, subctx := errgroup.WithContext(groupctx)
for cursor.Next() {
result, err := cursor.Result()
if err != nil {
return stacktrace.New(err)
}
name := path.Base(result.FilePath)
fileType := AllowedFileTypes[strings.ToLower(path.Ext(result.FilePath))]
if fileType.Has(AttributeImg) {
pageData.Images = append(pageData.Images, Image{
Parent: urlPath,
Name: name,
})
i := len(pageData.Images) - 1
subgroup.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
defer func() {
result.Text = result.Text[:0]
bufPool.Put(bytes.NewBuffer(result.Text))
}()
err = subctx.Err()
if err != nil {
return stacktrace.New(err)
}
var altText []byte
result.Text = bytes.TrimSpace(result.Text)
if bytes.HasPrefix(result.Text, []byte("!alt ")) {
altText, result.Text, _ = bytes.Cut(result.Text, []byte("\n"))
altText = bytes.TrimSpace(bytes.TrimPrefix(altText, []byte("!alt ")))
result.Text = bytes.TrimSpace(result.Text)
}
pageData.Images[i].AltText = string(altText)
pageData.Images[i].Caption = string(result.Text)
return nil
})
} else {
subgroup.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
defer func() {
result.Text = result.Text[:0]
bufPool.Put(bytes.NewBuffer(result.Text))
}()
err = subctx.Err()
if err != nil {
return stacktrace.New(err)
}
markdownMu.Lock()
pageData.ContentMap[name] = string(result.Text)
markdownMu.Unlock()
return nil
})
}
}
err = cursor.Close()
if err != nil {
return stacktrace.New(err)
}
err = subgroup.Wait()
if err != nil {
return err
}
} else {
dirEntries, err := siteGen.fsys.WithContext(groupctx).ReadDir(outputDir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return stacktrace.New(err)
}
subgroup, subctx := errgroup.WithContext(groupctx)
for _, dirEntry := range dirEntries {
dirEntry := dirEntry
name := dirEntry.Name()
fileType := AllowedFileTypes[strings.ToLower(path.Ext(name))]
if fileType.Has(AttributeImg) {
pageData.Images = append(pageData.Images, Image{Parent: urlPath, Name: name})
} else if fileType.Ext == ".md" {
subgroup.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
file, err := siteGen.fsys.WithContext(subctx).Open(path.Join(outputDir, name))
if err != nil {
return stacktrace.New(err)
}
defer file.Close()
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
_, err = buf.ReadFrom(file)
if err != nil {
return stacktrace.New(err)
}
markdownMu.Lock()
pageData.ContentMap[name] = buf.String()
markdownMu.Unlock()
return nil
})
}
}
err = subgroup.Wait()
if err != nil {
return err
}
}
return nil
})
// Fetch the child pages of the page.
group.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
pageDir := path.Join(siteGen.sitePrefix, "pages", urlPath)
databaseFS, isDatabaseFS := &DatabaseFS{}, false
switch v := siteGen.fsys.(type) {
case interface{ As(any) bool }:
isDatabaseFS = v.As(&databaseFS)
}
if isDatabaseFS {
pageData.ChildPages, err = sq.FetchAll(groupctx, databaseFS.DB, sq.Query{
Dialect: databaseFS.Dialect,
Format: "SELECT {*}" +
" FROM files" +
" WHERE parent_id = (SELECT file_id FROM files WHERE file_path = {pageDir})" +
" AND NOT is_dir" +
" AND file_path LIKE '%.html' ESCAPE '\\'" +
" AND file_path NOT IN ({indexPage}, {notFoundPage})" +
" ORDER BY file_path",
Values: []any{
sq.StringParam("pageDir", pageDir),
sq.StringParam("indexPage", path.Join(pageDir, "index.html")),
sq.StringParam("notFoundPage", path.Join(pageDir, "404.html")),
},
}, func(row *sq.Row) Page {
page := Page{
Parent: urlPath,
Name: strings.TrimSuffix(path.Base(row.String("file_path")), ".html"),
}
line := strings.TrimSpace(row.String("{}", sq.DialectExpression{
Default: sq.Expr("substr(text, 1, instr(text, char(10))-1)"),
Cases: []sq.DialectCase{{
Dialect: "postgres",
Result: sq.Expr("split_part(text, chr(10), 1)"),
}, {
Dialect: "mysql",
Result: sq.Expr("substring_index(text, char(10), 1)"),
}},
}))
if strings.HasPrefix(line, "<!--") && strings.HasSuffix(line, "-->") {
line := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "<!--"), "-->"))
if strings.HasPrefix(line, "#title ") {
page.Title = strings.TrimSpace(strings.TrimPrefix(line, "#title "))
}
} else if strings.HasPrefix(line, "<title>") && strings.HasSuffix(line, "</title>") {
page.Title = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "<title>"), "</title>"))
}
if page.Title == "" {
page.Title = titleConverter.Title(urlSeparatorReplacer.Replace(page.Name))
}
return page
})
if err != nil {
return stacktrace.New(err)
}
} else {
dirEntries, err := siteGen.fsys.WithContext(groupctx).ReadDir(pageDir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return stacktrace.New(err)
}
pageData.ChildPages = make([]Page, len(dirEntries))
subgroup, subctx := errgroup.WithContext(groupctx)
for i, dirEntry := range dirEntries {
i, dirEntry := i, dirEntry
subgroup.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
name := dirEntry.Name()
if dirEntry.IsDir() || !strings.HasSuffix(name, ".html") {
return nil
}
if urlPath == "" {
if name == "index.html" || name == "404.html" {
return nil
}
}
pageData.ChildPages[i].Parent = urlPath
pageData.ChildPages[i].Name = strings.TrimSuffix(name, ".html")
file, err := siteGen.fsys.WithContext(subctx).Open(path.Join(pageDir, name))
if err != nil {
return stacktrace.New(err)
}
defer file.Close()
reader := readerPool.Get().(*bufio.Reader)
reader.Reset(file)
defer func() {
reader.Reset(bytes.NewReader(nil))
readerPool.Put(reader)
}()
done := false
for !done {
line, err := reader.ReadSlice('\n')
if err != nil {
if err != io.EOF {
return stacktrace.New(err)
}
done = true
}
line = bytes.TrimSpace(line)
if bytes.HasPrefix(line, []byte("<!--")) && bytes.HasSuffix(line, []byte("-->")) {
line := bytes.TrimSpace(bytes.TrimSuffix(bytes.TrimPrefix(line, []byte("<!--")), []byte("-->")))
if bytes.HasPrefix(line, []byte("#title ")) {
pageData.ChildPages[i].Title = string(bytes.TrimSpace(bytes.TrimPrefix(line, []byte("#title "))))
}
} else if bytes.HasPrefix(line, []byte("<title>")) && bytes.HasSuffix(line, []byte("</title>")) {
pageData.ChildPages[i].Title = string(bytes.TrimSpace(bytes.TrimSuffix(bytes.TrimPrefix(line, []byte("<title>")), []byte("</title>"))))
}
break
}
if pageData.ChildPages[i].Title == "" {
pageData.ChildPages[i].Title = titleConverter.Title(urlSeparatorReplacer.Replace(pageData.ChildPages[i].Name))
}
return nil
})
}
err = subgroup.Wait()
if err != nil {
return err
}
n := 0
for _, childPage := range pageData.ChildPages {
if childPage != (Page{}) {
pageData.ChildPages[n] = childPage
n++
}
}
pageData.ChildPages = pageData.ChildPages[:n]
}
return nil
})
err = group.Wait()
if err != nil {
return err
}
if pageData.ChildPages == nil {
pageData.ChildPages = []Page{}
}
// Prepare the writer.
writer, err := siteGen.fsys.WithContext(ctx).OpenWriter(path.Join(outputDir, "index.html"), 0644)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return stacktrace.New(err)
}
err := siteGen.fsys.WithContext(ctx).MkdirAll(outputDir, 0755)
if err != nil {
return stacktrace.New(err)
}
writer, err = siteGen.fsys.WithContext(ctx).OpenWriter(path.Join(outputDir, "index.html"), 0644)
if err != nil {
return stacktrace.New(err)
}
}
defer writer.Close()
// Write the necessary HTML boilerplate for every page.
_, err = io.Copy(writer, strings.NewReader("<!DOCTYPE html>\n"+
"<html lang='"+template.HTMLEscapeString(siteGen.Site.LanguageCode)+"'>\n"+
"<meta charset='utf-8'>\n"+
"<meta name='viewport' content='width=device-width, initial-scale=1'>\n"+
"<link rel='icon' href='"+template.HTMLEscapeString(string(siteGen.Site.Favicon))+"'>\n",
))
if err != nil {
return stacktrace.New(err)
}
var isDatabaseFS bool
switch v := siteGen.fsys.(type) {
case interface{ As(any) bool }:
isDatabaseFS = v.As(&DatabaseFS{})
}
// Execute the page template into the writer.
if siteGen.cdnDomain != "" && isDatabaseFS {
pipeReader, pipeWriter := io.Pipe()
result := make(chan error, 1)
go func() {
defer func() {
if v := recover(); v != nil {
result <- stacktrace.New(fmt.Errorf("panic: %v", v))
}
}()
result <- siteGen.rewriteURLs(writer, pipeReader, urlPath)
}()
err = tmpl.Execute(pipeWriter, pageData)