-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
1817 lines (1522 loc) · 44.8 KB
/
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 main
import (
"bytes"
"embed"
"errors"
"fmt"
"hash/crc32"
"html"
"io"
"io/fs"
"log"
"net/url"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/gomarkdown/markdown"
gitignore "github.com/sabhiram/go-gitignore"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
"github.com/alsosee/finder/structs"
)
var errExecutingTemplate = errors.New("error executing template")
var caser = cases.Title(language.English, cases.NoLower)
//go:embed functions/*
var functionsFS embed.FS
// Generator is a struct that generates a static site.
type Generator struct {
templates *template.Template
ignore *gitignore.GitIgnore
// config is a site configuration, e.g. title, description, etc.
// It is different from Config struct in main package,
// which is used to store command line flags.
config structs.Config
contents structs.Contents
// dirContents is a map where
// key is a directory path,
// value is a list of files and directories;
// used to build Panels
dirContents map[string][]structs.File
// Connections keep track of references from one file to another.
// key is a file path, where reference is pointing to.
// value is a list of files that are pointing to the key.
connections structs.Connections
mediaDirContents map[string][]structs.Media
// awardsMissingContent used to temporary hold awards
// that are for content that is not yet added.
awardsMissingContent map[string][]structs.Award
// chainPages used to keep track of next/prev pages in a series.
chainPages map[string]map[bool]string // from -> true(next)/false(prev) -> reference
renderedPanelsCache map[string]string
// hashes is map of CRC32 hashes for each file.
// key is a file path, value is a hash.
// Used by indexer to check if file was changed.
hashes map[string]string
awardPages []string
muContents sync.Mutex // protects writes to contents
muDir sync.Mutex // protects writes to dirContents
muConnections sync.Mutex // protects writes to connections
muMedia sync.Mutex // protects writes to mediaDirContents
muAwardPages sync.Mutex // protects writes to awardPages
muAwardsMissingContent sync.Mutex // protects writes to awardsMissingContent
muChainPages sync.Mutex // protects writes to chainPages
muRenderedPanels sync.Mutex // protects writes to renderedPanelsCache
muHashes sync.Mutex // protects writes to hashes
}
// NewGenerator creates a new Generator.
func NewGenerator(ignore *gitignore.GitIgnore) (*Generator, error) {
config, err := parseConfig(cfg.ConfigFile)
if err != nil {
return nil, fmt.Errorf("parsing site config: %w", err)
}
overrideConfig(&config)
return &Generator{
config: config,
ignore: ignore,
contents: structs.Contents{},
dirContents: map[string][]structs.File{},
connections: structs.Connections{},
mediaDirContents: map[string][]structs.Media{},
chainPages: map[string]map[bool]string{},
awardsMissingContent: map[string][]structs.Award{},
renderedPanelsCache: map[string]string{},
hashes: map[string]string{},
}, nil
}
func processIgnoreFile(ignoreFile string) (*gitignore.GitIgnore, error) {
ignore := &gitignore.GitIgnore{}
ignoreFilepath := filepath.Join(cfg.InfoDirectory, ignoreFile)
if _, err := os.Stat(ignoreFilepath); err == nil {
ignore, err = gitignore.CompileIgnoreFile(ignoreFilepath)
if err != nil {
return nil, fmt.Errorf("compiling ignore file: %w", err)
}
} else {
log.Printf("Ignore file %q not found, ignoring", ignoreFilepath)
}
return ignore, nil
}
func parseConfig(configFile string) (structs.Config, error) {
b, err := os.ReadFile(filepath.Join(cfg.InfoDirectory, configFile))
if err != nil {
return structs.Config{}, fmt.Errorf("reading config file: %w", err)
}
var config structs.Config
if err = yaml.Unmarshal(b, &config); err != nil {
return structs.Config{}, fmt.Errorf("unmarshaling config: %w", err)
}
return config, nil
}
func overrideConfig(config *structs.Config) {
if cfg.MediaHost != "" {
config.MediaHost = cfg.MediaHost
}
if cfg.SearchHost != "" {
config.SearchHost = cfg.SearchHost
}
if cfg.SearchIndexName != "" {
config.SearchIndexName = cfg.SearchIndexName
}
if cfg.SearchAPIKey != "" {
config.SearchAPIKey = cfg.SearchAPIKey
}
}
func (g *Generator) fm() template.FuncMap {
return template.FuncMap{
"config": func() structs.Config { return g.config },
"join": filepath.Join,
"dir": filepath.Dir,
"base": filepath.Base,
"hasPrefix": strings.HasPrefix,
"strjoin": strings.Join,
"isPerson": structs.IsPerson,
"personPrefix": structs.PersonPrefix,
"sum": func(ints ...int) int {
var sum int
for _, i := range ints {
sum += i
}
return sum
},
"in": in,
// "content" returns a Content struct for a given file path (without extension)
// It is used to render references.
"content": func(path, caller string) *structs.Content {
g.muContents.Lock()
defer g.muContents.Unlock()
if c, ok := g.contents[path]; ok {
return &c
}
return nil
},
// "connections" returns a list of connections for a given file path (no extension).
"connections": func(path string) map[string][]string {
g.muConnections.Lock()
defer g.muConnections.Unlock()
if m, ok := g.connections[path]; ok {
return m
}
return nil
},
"prev": func(id string) string {
g.muChainPages.Lock()
defer g.muChainPages.Unlock()
if m, ok := g.chainPages[id]; ok {
if prev, ok := m[false]; ok {
return prev
}
}
return ""
},
"next": func(id string) string {
g.muChainPages.Lock()
defer g.muChainPages.Unlock()
if m, ok := g.chainPages[id]; ok {
if next, ok := m[true]; ok {
return next
}
}
return ""
},
"crc32": crc32sum,
"div": func(a, b int) int {
return a / b
},
"initials": func(name string) string {
if name == "" {
return ""
}
var initials string
for _, s := range strings.Split(name, " ") {
initials += strings.ToUpper(s[:1]) + " " // thin space
}
return strings.TrimSpace(initials)
},
// "thumbStylePx" returns CSS styles for a thumbnail image,
// where background-size is in pixels.
// It's used for non-responsive images, and more reliable than "thumbStylePct".
"thumbStylePx": func(media structs.Media, max float64, opt ...string) string {
if media.ThumbPath == "" {
return ""
}
var (
backgroundWidth = float64(media.ThumbTotalWidth) * max / float64(media.ThumbWidth)
backgroundHeight = float64(media.ThumbTotalHeight) * max / float64(media.ThumbWidth)
positionX = float64(media.ThumbXOffset) * max / float64(media.ThumbWidth)
positionY = float64(media.ThumbYOffset) * max / float64(media.ThumbWidth)
width = max
height = float64(media.ThumbHeight) * max / float64(media.ThumbWidth)
)
p := ""
if len(opt) > 0 {
p = opt[0]
}
if media.Height > media.Width {
backgroundWidth = float64(media.ThumbTotalWidth) * max / float64(media.ThumbHeight)
backgroundHeight = float64(media.ThumbTotalHeight) * max / float64(media.ThumbHeight)
positionX = float64(media.ThumbXOffset) * max / float64(media.ThumbHeight)
positionY = float64(media.ThumbYOffset) * max / float64(media.ThumbHeight)
width = float64(media.ThumbWidth) * max / float64(media.ThumbHeight)
height = max
}
marginLeft := (max - width) / 2
marginRight := max - width - marginLeft
marginTop := (max - height) / 2
marginBottom := max - height - marginTop
// round down width to ceil number to avoid rounding errors
// that can cause image to have 1px of the next image on the right
width = float64(int(width))
style := fmt.Sprintf(
"%sbackground-size: %.2fpx %.2fpx; %swidth: %.2fpx; %sheight: %.2fpx",
p, backgroundWidth, backgroundHeight,
p, width,
p, height,
)
if marginLeft != 0 || marginRight != 0 {
style += fmt.Sprintf("; %scomp-margin-left: %.2fpx; %scomp-margin-right: %.2fpx", p, marginLeft, p, marginRight)
}
if marginTop != 0 || marginBottom != 0 {
style += fmt.Sprintf("; %scomp-margin-top: %.2fpx; %scomp-margin-bottom: %.2fpx", p, marginTop, p, marginBottom)
}
if positionX != 0 || positionY != 0 {
style += fmt.Sprintf("; %sbackground-position: -%.2fpx -%.2fpx", p, positionX, positionY)
}
return style
},
// "thumbStylePct" returns CSS styles for a thumbnail image,
// where background-size is in percents. It's used for responsive images.
// It can be used when last image in the sprite has the same width as the current one,
// which is the case for most people/characters images.
// Also, it doesn't add "comp-margin-left" and "comp-margin-right" styles,
// which are used to center the image in lists.
"thumbStylePct": func(media structs.Media, prefix ...string) string {
if media.ThumbPath == "" {
return ""
}
p := ""
if len(prefix) > 0 {
p = prefix[0]
}
// assume than image width is 100%
// how much bigger the whole sprite is?
width := float64(media.ThumbTotalWidth) * 100 / float64(media.ThumbWidth)
height := float64(media.ThumbTotalHeight) * 100 / float64(media.ThumbHeight)
positionX := 0.0
positionY := 0.0
if media.ThumbTotalWidth != media.ThumbWidth {
// position 100% is the right edge of the image
// assuming here that last image in the sprite has the same width as the current one
positionX = float64(media.ThumbXOffset) * 100 / float64(media.ThumbTotalWidth-media.ThumbWidth)
}
if media.ThumbTotalHeight != media.ThumbHeight {
positionY = float64(media.ThumbYOffset) * 100 / float64(media.ThumbTotalHeight-media.ThumbHeight)
}
arX := media.ThumbWidth
arY := media.ThumbHeight
if arX == arY {
arX = 1
arY = 1
}
if positionX == 0 && positionY == 0 {
return fmt.Sprintf(
"%sbackground-size: %.2f%% %.2f%%; %saspect-ratio: %d/%d;",
p, width, height,
p, arX, arY,
)
}
return fmt.Sprintf(
"%sbackground-size: %.2f%% %.2f%%; %sbackground-position: %.2f%% %.2f%%; %saspect-ratio: %d/%d;",
p, width, height,
p, positionX, positionY,
p, arX, arY,
)
},
// "isPNG" currenty not used
"isPNG": func(path string) bool {
return strings.HasSuffix(path, ".png")
},
// "isJPG" is used to add "jpg" class to links that have JPG image thumbnails
// (to add a shadow and border radius to them)
"isJPG": func(path string) bool {
return strings.HasSuffix(path, ".jpg") || strings.HasSuffix(path, ".jpeg")
},
"length": length,
// "either" returns true if any of the arguments is true-ish
// (bool true, string not empty, int not 0, time.Duration not 0, []string not empty, []Reference not empty)
// it's useful for checking if "either" of the fields is set in the template
// to avoid rendering empty HTML tags (e.g. ".labels" paragraph)
"either": func(args ...interface{}) bool {
for _, arg := range args {
switch v := arg.(type) {
case bool:
if v {
return true
}
case string:
if v != "" {
return true
}
case int:
if v != 0 {
return true
}
case time.Duration:
if v != 0 {
return true
}
case []string:
if len(v) != 0 {
return true
}
case []structs.Reference:
if len(v) != 0 {
return true
}
case []structs.Award:
if len(v) != 0 {
return true
}
}
}
return false
},
"character": func(content structs.Content, characterName string) *structs.Character {
for _, character := range content.Characters {
if character.Name == characterName {
return character
}
}
for _, episode := range content.Episodes {
for _, character := range episode.Characters {
if character.Name == characterName {
return character
}
}
}
return nil
},
"characterByActor": func(content *structs.Content, characterName string) *structs.Character {
// this function return a single character by actor or voice name
// todo: support multiple characters with the same actor/voice
if content == nil {
return nil
}
for _, character := range content.Characters {
if character.Actor == characterName {
return character
}
if character.Voice == characterName {
return character
}
}
return nil
},
// "dict" used to pass multiple key-value pairs to a template
// (e.g. {{ template "something" dict "Key1" "value1" "Key2" "value2" }})
"dict": func(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
},
"type": func(c structs.Content) string {
return c.Type()
},
"contentFieldName": func(field string) string {
return structs.ContentFieldName(field)
},
"series": series,
"isLast": func(i, total int) bool {
return i == total-1
},
"escape": func(s string) string {
return strings.ReplaceAll(s, `'`, `\'`)
},
"htmlEscape": html.EscapeString,
"value": newFileValue,
"missing": g.missing,
"missingAwardsLen": func(id string) int {
g.muAwardsMissingContent.Lock()
defer g.muAwardsMissingContent.Unlock()
return len(g.awardsMissingContent[id])
},
"image": g.getImageForPath,
"formatTitle": g.formatTitle,
"title": caser.String,
"awardYear": awardYear,
"prefix": prefix,
"columns": func() []structs.Column {
return structs.ColumnsList
},
"column": column,
"chooseColumns": chooseColumns,
"rootTypes": func() map[string]string { return structs.RootTypes },
"renderPanel": g.renderPanel,
"label": func(label string, list []string) string {
if len(list) == 1 && strings.HasSuffix(label, "s") {
return label[:len(label)-1]
}
return label
},
"fallback": func(args ...string) string {
for _, arg := range args {
if arg != "" {
return arg
}
}
return ""
},
"splitExtra": func(extra []string, content structs.Content) structs.Extra {
// turn list like
// ["a", "", "c", "a", "", "d"]
// into
// ["a"] and "c, d"
var (
roles = map[string]interface{}{}
addon []string
i int
collectAddon bool
)
for i < len(extra) {
if extra[i] == "" {
collectAddon = true
i++
continue
}
if collectAddon {
addon = append(addon, extra[i])
collectAddon = false
i++
continue
}
if _, ok := roles[extra[i]]; ok {
i++
continue
}
roles[extra[i]] = nil
i++
}
var primary []string
for role := range roles {
primary = append(primary, role)
}
if len(addon) > 0 && len(content.Episodes) == len(addon) {
addon = nil
}
return structs.Extra{
Primary: primary,
Addon: strings.Join(addon, ", "),
}
},
}
}
// Run runs the generator.
func (g *Generator) Run() error {
t, err := template.New("").Funcs(g.fm()).ParseGlob(cfg.TemplatesDirectory + "/*")
if err != nil {
return fmt.Errorf("parsing templates: %w", err)
}
g.templates = t
defer measureTime()()
// Go through all the files in the info directory
var (
files = make(chan string)
errorsChan = make(chan error)
done = make(chan struct{}, 1)
)
defer close(errorsChan)
g.copyStaticFiles()
g.copyFunctionsFiles()
go g.walkInfoDirectory(files, errorsChan)
g.walkMediaDirectory()
go g.processFiles(files, errorsChan, done)
FILE_PROCESSING:
for {
select {
case err := <-errorsChan:
close(done)
return fmt.Errorf("walking info directory: %w", err)
case <-done:
log.Printf("Done processing files")
close(done)
break FILE_PROCESSING
}
}
g.addAwards()
// Generate missing files
m := g.missing()
g.addMissingFilesToPanels(m)
// Render Go templates
if err := g.generateGoTemplates(); err != nil {
return fmt.Errorf("generating go templates: %w", err)
}
g.processPanels()
if err := g.generateMissing(m); err != nil {
return fmt.Errorf("rendering missing: %w", err)
}
// Generate file templates
if err := g.generateContentTemplates(); err != nil {
return fmt.Errorf("generating content templates: %w", err)
}
// Generate index for each directory
if err := g.generateIndexes(); err != nil {
return fmt.Errorf("generating indexes: %w", err)
}
return nil
}
func (g *Generator) copyStaticFiles() {
if cfg.StaticDirectory == "" {
log.Printf("No static files directory specified, skipping")
return
}
log.Printf("Copying static files from %q to %q", cfg.StaticDirectory, cfg.OutputDirectory)
if err := os.MkdirAll(cfg.OutputDirectory, 0o755); err != nil {
log.Fatalf("Error creating output directory %q: %v", cfg.OutputDirectory, err)
}
err := filepath.Walk(
cfg.StaticDirectory,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return os.MkdirAll(filepath.Join(cfg.OutputDirectory, strings.TrimPrefix(path, cfg.StaticDirectory)), 0o755)
}
relPath := strings.TrimPrefix(path, cfg.StaticDirectory+string(filepath.Separator))
outPath := filepath.Join(cfg.OutputDirectory, relPath)
if strings.HasSuffix(path, ".gojs") {
outPath = strings.TrimSuffix(outPath, ".gojs") + ".js"
log.Printf("Processing GoJS file %q to %q", path, outPath)
return g.processGoJSFile(path, outPath)
}
return copyFile(path, outPath)
},
)
if err != nil {
log.Fatalf("Error walking static directory %q: %v", cfg.StaticDirectory, err)
}
log.Printf("Done copying static files from %q to %q", cfg.StaticDirectory, cfg.OutputDirectory)
}
func (g *Generator) copyFunctionsFiles() {
log.Printf("Copying functions files")
// check if functions directory exists, if it does – exit
if _, err := os.Stat("functions"); err == nil {
log.Printf("Functions directory already exists, skipping")
return
}
// unline static files, functions directory has to the directory where app is running
// so we can't use cfg.OutputDirectory
if err := os.MkdirAll("functions", 0o755); err != nil {
log.Fatalf("Error creating functions directory: %v", err)
}
// copy embedded functionsFS files to the functions directory
err := fs.WalkDir(functionsFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return os.MkdirAll(path, 0o755)
}
outPath := filepath.Join(path)
outFile, err := os.Create(outPath)
if err != nil {
return fmt.Errorf("creating file %q: %w", outPath, err)
}
defer outFile.Close()
inFile, err := functionsFS.Open(path)
if err != nil {
return fmt.Errorf("opening file %q: %w", path, err)
}
_, err = io.Copy(outFile, inFile)
if err != nil {
return fmt.Errorf("copying file %q to %q: %w", path, outPath, err)
}
return nil
})
if err != nil {
log.Fatalf("Error walking functions directory: %v", err)
}
}
func (g *Generator) walkInfoDirectory(files chan<- string, errorsChan chan<- error) {
defer close(files)
infoDir, err := filepath.Abs(cfg.InfoDirectory)
if err != nil {
errorsChan <- fmt.Errorf("getting absolute path for %q: %w", cfg.InfoDirectory, err)
return
}
log.Printf("Walking info directory %q", infoDir)
err = filepath.Walk(
infoDir,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath := strings.TrimPrefix(path, infoDir+string(filepath.Separator))
if g.ignore.MatchesPath(relPath) {
return nil
}
if info.IsDir() {
g.addDir(relPath)
return nil
}
files <- relPath
return nil
},
)
if err != nil {
errorsChan <- err
} else {
log.Printf("Done walking info directory %q", cfg.InfoDirectory)
}
}
// walkMediaDirectory scans the media directory for .thumbs.yml files,
// parses them and adds to g.mediaDirContents.
// mediaDirContents is a map where key is a directory path, and value is a list of media files in that directory.
// Information from .thumbs.yml used later in template to build links to thumbnails.
func (g *Generator) walkMediaDirectory() {
if cfg.MediaDirectory == "" {
log.Printf("No media files directory specified, skipping")
return
}
mediaDir, err := filepath.Abs(cfg.MediaDirectory)
if err != nil {
log.Fatalf("Error getting absolute path for %q: %v", cfg.MediaDirectory, err)
}
log.Printf("Walking media directory %q", mediaDir)
err = filepath.Walk(
mediaDir,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath := strings.TrimPrefix(path, mediaDir+string(filepath.Separator))
if info.IsDir() {
return nil
}
if info.Name() != ".thumbs.yml" {
return nil
}
media, err := structs.ParseMediaFile(path)
if err != nil {
return fmt.Errorf("parsing media file %q: %w", path, err)
}
g.addMedia(relPath, media)
return nil
},
)
if err != nil {
log.Fatalf("Error walking media directory %q: %v", cfg.MediaDirectory, err)
}
log.Printf("Done walking media directory %q", cfg.MediaDirectory)
}
func (g *Generator) processFiles(files <-chan string, errorsChan chan<- error, done chan<- struct{}) {
wg := sync.WaitGroup{}
for i := 0; i < cfg.NumWorkers; i++ {
for path := range files {
wg.Add(1)
go func(path string) {
defer wg.Done()
if err := g.processFile(path); err != nil {
errorsChan <- fmt.Errorf("processing file %q: %w", path, err)
}
}(path)
}
}
wg.Wait()
done <- struct{}{}
}
// processFile processes a single file.
// For content files, like YAML and Markdown, it adds Content struct to g.contents.
func (g *Generator) processFile(file string) error {
switch filepath.Ext(file) {
case ".yml", ".yaml":
g.addFile(file)
return g.processYAMLFile(file)
case ".gomd":
g.addFile(file)
return g.processGoMarkdownFile(file)
case ".md":
g.addFile(file)
return g.processMarkdownFile(file)
case ".jpeg", ".jpg", ".png":
g.addFile(file)
return g.processImageFile(file)
case ".mp4":
g.addFile(file)
return g.processVideoFile(file)
default:
if file == "_redirects" {
return g.copyFileAsIs(file)
}
return fmt.Errorf("unknown file type: %q", file)
}
}
func (g *Generator) processYAMLFile(file string) error {
b, err := os.ReadFile(filepath.Join(cfg.InfoDirectory, file))
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
g.addHash(file, b)
var content structs.Content
if err = yaml.Unmarshal(b, &content); err != nil {
return fmt.Errorf("unmarshaling yaml: %w", err)
}
content.Source = file
content.GenerateID()
content.AddMedia(g.getImageForPath)
g.addContent(content)
g.addConnections(content)
return nil
}
func (g *Generator) processMarkdownFile(file string) error {
b, err := os.ReadFile(filepath.Join(cfg.InfoDirectory, file))
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
htmlBody := markdown.ToHTML(b, nil, nil)
// replace [ ] and [x] with checkboxes and break lines with <br> at the end of the line with checkbox
// except for the first line
htmlBody = bytes.ReplaceAll(htmlBody, []byte("[ ] "), []byte(`<br><input type="checkbox" disabled> `))
htmlBody = bytes.ReplaceAll(htmlBody, []byte("[x] "), []byte(`<br><input type="checkbox" disabled checked> `))
htmlBody = bytes.ReplaceAll(htmlBody, []byte("<p><br>"), []byte("<p>"))
g.addContent(structs.Content{
Source: file,
HTML: string(htmlBody),
})
return nil
}
func (g *Generator) processGoMarkdownFile(file string) error {
b, err := os.ReadFile(filepath.Join(cfg.InfoDirectory, file))
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
g.addContent(structs.Content{
Source: file,
HTML: string(b),
})
// conversion to HTML is done in generateGoTemplates()
// after all the files are processed
return nil
}
func (g *Generator) processGoJSFile(src, out string) error {
// treat file as a Go template
b, err := os.ReadFile(src)
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
t, err := template.New("").Funcs(g.fm()).Parse(string(b))
if err != nil {
return fmt.Errorf("parsing template: %w", err)
}
outFile, err := os.Create(out)
if err != nil {
return fmt.Errorf("creating file: %w", err)
}
defer outFile.Close()
if err = t.Execute(outFile, nil); err != nil {
return fmt.Errorf("%w for %q: %w", errExecutingTemplate, src, err)
}
return nil
}
func (g *Generator) processImageFile(_ string) error {
return nil
}
func (g *Generator) processVideoFile(_ string) error {
return nil
}
func (g *Generator) copyFileAsIs(file string) error {
return copyFile(
filepath.Join(cfg.InfoDirectory, file),
filepath.Join(cfg.OutputDirectory, file),
)
}
func (g *Generator) addContent(content structs.Content) {
content.GenerateID()
g.muContents.Lock()
g.contents[content.SourceNoExtention] = content
g.muContents.Unlock()
}
// addConnections adds a "connection" for a given content file.
func (g *Generator) addConnections(content structs.Content) {
content.GenerateID()
from := content.SourceNoExtention
connections := content.Connections()
for _, conn := range connections {
switch conn.Meta {
case structs.ConnectionPrevious:
g.addPrevious(from, conn.To)
case structs.ConnectionSeries:
g.addConnection(from, series(content), "Series")
case structs.ConnectionNone:
g.addConnection(from, conn.To, conn.Info...)
default:
g.addConnection(from, conn.To, append([]string{conn.Label}, conn.Info...)...)
}
}
// Prepare for adding Awards
if len(content.Categories) > 0 {
g.addAwardPage(from)
}
}
func (g *Generator) addConnection(from, to string, info ...string) {
g.muConnections.Lock()
defer g.muConnections.Unlock()
if _, ok := g.connections[to]; !ok {
g.connections[to] = map[string][]string{}
}
if _, ok := g.connections[to][from]; !ok {
g.connections[to][from] = info
return
}
g.connections[to][from] = append(g.connections[to][from], info...)