-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
1083 lines (899 loc) · 24.2 KB
/
main.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"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
textTmpl "text/template"
"io"
"io/fs"
"log"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
_ "embed"
"github.com/barelyhuman/go/env"
"github.com/barelyhuman/go/poller"
ghttp "github.com/cjoudrey/gluahttp"
"github.com/barelyhuman/go/color"
stringsLib "github.com/vadv/gopher-lua-libs/strings"
yamlLib "github.com/vadv/gopher-lua-libs/yaml"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
highlighting "github.com/yuin/goldmark-highlighting"
lua "github.com/yuin/gopher-lua"
"gopkg.in/yaml.v3"
luaAlvu "github.com/barelyhuman/alvu/lua/alvu"
"golang.org/x/net/websocket"
luajson "layeh.com/gopher-json"
)
const logPrefix = "[alvu] "
var mdProcessor goldmark.Markdown
var baseurl string
var basePath string
var outPath string
var hardWraps bool
var hookCollection HookCollection
var reloadCh = []chan bool{}
var serveFlag *bool
var notFoundPageExists bool
//go:embed .commitlog.release
var release string
var layoutFiles []string = []string{"_head.html", "_tail.html", "_layout.html"}
type SiteMeta struct {
BaseURL string
}
type PageRenderData struct {
Meta SiteMeta
Data map[string]interface{}
Extras map[string]interface{}
}
type LayoutRenderData struct {
PageRenderData
Content template.HTML
}
// TODO: move stuff into the alvu struct type
// on each newly added feature or during improving
// older features.
type Alvu struct {
publicPath string
files []*AlvuFile
filesIndex []string
}
func (al *Alvu) AddFile(file *AlvuFile) {
al.files = append(al.files, file)
al.filesIndex = append(al.filesIndex, file.sourcePath)
}
func (al *Alvu) IsAlvuFile(filePath string) bool {
for _, af := range al.filesIndex {
if af == filePath {
return true
}
}
return false
}
func (al *Alvu) Build() {
for ind := range al.files {
alvuFile := al.files[ind]
alvuFile.Build()
}
onDebug(func() {
debugInfo("Run all OnFinish Hooks")
memuse()
})
// right before completion run all hooks again but for the onFinish
hookCollection.RunAll("OnFinish")
}
func (al *Alvu) CopyPublic() {
onDebug(func() {
debugInfo("Before copying files")
memuse()
})
// copy public to out
_, err := os.Stat(al.publicPath)
if err == nil {
err = copyDir(al.publicPath, outPath)
if err != nil {
bail(err)
}
}
onDebug(func() {
debugInfo("After copying files")
memuse()
})
}
func main() {
onDebug(func() {
debugInfo("Before Exec")
memuse()
})
var versionFlag bool
flag.BoolVar(&versionFlag, "version", false, "version info")
flag.BoolVar(&versionFlag, "v", false, "version info")
basePathFlag := flag.String("path", ".", "`DIR` to search for the needed folders in")
outPathFlag := flag.String("out", "./dist", "`DIR` to output the compiled files to")
baseurlFlag := flag.String("baseurl", "/", "`URL` to be used as the root of the project")
hooksPathFlag := flag.String("hooks", "./hooks", "`DIR` that contains hooks for the content")
enableHighlightingFlag := flag.Bool("highlight", false, "enable highlighting for markdown files")
highlightThemeFlag := flag.String("highlight-theme", "bw", "`THEME` to use for highlighting (supports most themes from pygments)")
serveFlag = flag.Bool("serve", false, "start a local server")
hardWrapsFlag := flag.Bool("hard-wrap", true, "enable hard wrapping of elements with `<br>`")
portFlag := flag.String("port", "3000", "`PORT` to start the server on")
pollDurationFlag := flag.Int("poll", 350, "Polling duration for file changes in milliseconds")
flag.Parse()
// Show version and exit
if versionFlag {
println(release)
os.Exit(0)
}
baseurl = *baseurlFlag
basePath = path.Join(*basePathFlag)
pagesPath := path.Join(*basePathFlag, "pages")
publicPath := path.Join(*basePathFlag, "public")
headFilePath := path.Join(pagesPath, "_head.html")
baseFilePath := path.Join(pagesPath, "_layout.html")
tailFilePath := path.Join(pagesPath, "_tail.html")
notFoundFilePath := path.Join(pagesPath, "404.html")
outPath = path.Join(*outPathFlag)
hooksPath := path.Join(*basePathFlag, *hooksPathFlag)
hardWraps = *hardWrapsFlag
headTailDeprecationWarning := color.ColorString{}
headTailDeprecationWarning.Yellow(logPrefix).Yellow("[WARN] use of _tail.html and _head.html is deprecated, please use _layout.html instead")
os.MkdirAll(publicPath, os.ModePerm)
alvuApp := &Alvu{
publicPath: publicPath,
}
watcher := NewWatcher(alvuApp, *pollDurationFlag)
if *serveFlag {
watcher.AddDir(pagesPath)
watcher.AddDir(publicPath)
}
onDebug(func() {
debugInfo("Opening _head")
memuse()
})
headFileFd, err := os.Open(headFilePath)
if err != nil {
if err == fs.ErrNotExist {
log.Println("no _head.html found,skipping")
}
} else {
fmt.Println(headTailDeprecationWarning.String())
}
onDebug(func() {
debugInfo("Opening _layout")
memuse()
})
baseFileFd, err := os.Open(baseFilePath)
if err != nil {
if err == fs.ErrNotExist {
log.Println("no _layout.html found,skipping")
}
}
onDebug(func() {
debugInfo("Opening _tail")
memuse()
})
tailFileFd, err := os.Open(tailFilePath)
if err != nil {
if err == fs.ErrNotExist {
log.Println("no _tail.html found, skipping")
}
} else {
fmt.Println(headTailDeprecationWarning.String())
}
onDebug(func() {
debugInfo("Checking if 404.html exists")
memuse()
})
if _, err := os.Stat(notFoundFilePath); errors.Is(err, os.ErrNotExist) {
notFoundPageExists = false
log.Println("no 404.html found, skipping")
} else {
notFoundPageExists = true
}
alvuApp.CopyPublic()
onDebug(func() {
debugInfo("Reading hook and to process files")
memuse()
})
CollectHooks(basePath, hooksPath)
toProcess := CollectFilesToProcess(pagesPath)
onDebug(func() {
log.Println("printing files to process")
log.Println(toProcess)
})
initMDProcessor(*enableHighlightingFlag, *highlightThemeFlag)
onDebug(func() {
debugInfo("Running all OnStart hooks")
memuse()
})
hookCollection.RunAll("OnStart")
prefixSlashPath := regexp.MustCompile(`^\/`)
onDebug(func() {
debugInfo("Creating Alvu Files")
memuse()
})
for _, toProcessItem := range toProcess {
fileName := strings.Replace(toProcessItem, pagesPath, "", 1)
fileName = prefixSlashPath.ReplaceAllString(fileName, "")
destFilePath := strings.Replace(toProcessItem, pagesPath, outPath, 1)
isHTML := strings.HasSuffix(fileName, ".html")
alvuFile := &AlvuFile{
lock: &sync.Mutex{},
sourcePath: toProcessItem,
hooks: hookCollection,
destPath: destFilePath,
name: fileName,
isHTML: isHTML,
headFile: headFileFd,
tailFile: tailFileFd,
baseTemplate: baseFileFd,
data: map[string]interface{}{},
extras: map[string]interface{}{},
}
alvuApp.AddFile(alvuFile)
// If serving, also add the nested path into it
if *serveFlag {
watcher.AddDir(path.Dir(alvuFile.sourcePath))
}
}
alvuApp.Build()
onDebug(func() {
runtime.GC()
debugInfo("On Completions")
memuse()
})
cs := &color.ColorString{}
fmt.Println(cs.Blue(logPrefix).Green("Compiled ").Cyan("\"" + basePath + "\"").Green(" to ").Cyan("\"" + outPath + "\"").String())
if *serveFlag {
watcher.StartWatching()
runServer(*portFlag)
}
hookCollection.Shutdown()
}
func runServer(port string) {
normalizedPort := port
if !strings.HasPrefix(normalizedPort, ":") {
normalizedPort = ":" + normalizedPort
}
cs := &color.ColorString{}
cs.Blue(logPrefix).Green("Serving on").Reset(" ").Cyan(normalizedPort)
fmt.Println(cs.String())
http.Handle("/", http.HandlerFunc(ServeHandler))
AddWebsocketHandler()
err := http.ListenAndServe(normalizedPort, nil)
if strings.Contains(err.Error(), "address already in use") {
bail(errors.New("port already in use, use another port with the `-port` flag instead"))
}
}
func CollectFilesToProcess(basepath string) []string {
files := []string{}
pathstoprocess, err := os.ReadDir(basepath)
if err != nil {
panic(err)
}
for _, pathInfo := range pathstoprocess {
_path := path.Join(basepath, pathInfo.Name())
if Contains(layoutFiles, pathInfo.Name()) {
continue
}
if pathInfo.IsDir() {
files = append(files, CollectFilesToProcess(_path)...)
} else {
files = append(files, _path)
}
}
return files
}
func CollectHooks(basePath, hooksBasePath string) {
if _, err := os.Stat(hooksBasePath); err != nil {
return
}
pathsToProcess, err := os.ReadDir(hooksBasePath)
if err != nil {
panic(err)
}
for _, pathInfo := range pathsToProcess {
if !strings.HasSuffix(pathInfo.Name(), ".lua") {
continue
}
hook := NewHook()
hookPath := path.Join(hooksBasePath, pathInfo.Name())
if err := hook.DoFile(hookPath); err != nil {
panic(err)
}
hookCollection = append(hookCollection, &Hook{
path: hookPath,
state: hook,
})
}
}
func initMDProcessor(highlight bool, theme string) {
rendererOptions := []renderer.Option{
html.WithXHTML(),
html.WithUnsafe(),
}
if hardWraps {
rendererOptions = append(rendererOptions, html.WithHardWraps())
}
gmPlugins := []goldmark.Option{
goldmark.WithExtensions(extension.GFM, extension.Footnote),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
rendererOptions...,
),
}
if highlight {
gmPlugins = append(gmPlugins, goldmark.WithExtensions(
highlighting.NewHighlighting(
highlighting.WithStyle(theme),
),
))
}
mdProcessor = goldmark.New(gmPlugins...)
}
type Hook struct {
path string
state *lua.LState
}
type HookCollection []*Hook
func (hc HookCollection) Shutdown() {
for _, hook := range hc {
hook.state.Close()
}
}
func (hc HookCollection) RunAll(funcName string) {
for _, hook := range hc {
hookFunc := hook.state.GetGlobal(funcName)
if hookFunc == lua.LNil {
continue
}
if err := hook.state.CallByParam(lua.P{
Fn: hookFunc,
NRet: 0,
Protect: true,
}); err != nil {
bail(err)
}
}
}
type AlvuFile struct {
lock *sync.Mutex
hooks HookCollection
name string
sourcePath string
isHTML bool
destPath string
meta map[string]interface{}
content []byte
writeableContent []byte
headFile *os.File
tailFile *os.File
baseTemplate *os.File
targetName []byte
data map[string]interface{}
extras map[string]interface{}
}
func (alvuFile *AlvuFile) Build() {
bail(alvuFile.ReadFile())
bail(alvuFile.ParseMeta())
if len(alvuFile.hooks) == 0 {
alvuFile.ProcessFile(nil)
}
for _, hook := range hookCollection {
isForSpecificFile := hook.state.GetGlobal("ForFile")
if isForSpecificFile != lua.LNil {
if alvuFile.name == isForSpecificFile.String() {
alvuFile.ProcessFile(hook.state)
} else {
bail(alvuFile.ProcessFile(nil))
}
} else {
bail(alvuFile.ProcessFile(hook.state))
}
}
alvuFile.FlushFile()
}
func (af *AlvuFile) ReadFile() error {
filecontent, err := os.ReadFile(af.sourcePath)
if err != nil {
return fmt.Errorf("error reading file, error: %v", err)
}
af.content = filecontent
return nil
}
func (af *AlvuFile) ParseMeta() error {
sep := []byte("---")
if !bytes.HasPrefix(af.content, sep) {
af.writeableContent = af.content
return nil
}
metaParts := bytes.SplitN(af.content, sep, 3)
var meta map[string]interface{}
err := yaml.Unmarshal([]byte(metaParts[1]), &meta)
if err != nil {
return err
}
af.meta = meta
af.writeableContent = []byte(metaParts[2])
return nil
}
func (af *AlvuFile) ProcessFile(hook *lua.LState) error {
// pre process hook => should return back json with `content` and `data`
af.lock.Lock()
defer af.lock.Unlock()
af.targetName = regexp.MustCompile(`\.md$`).ReplaceAll([]byte(af.name), []byte(".html"))
onDebug(func() {
debugInfo(af.name + " will be changed to " + string(af.targetName))
})
buf := bytes.NewBuffer([]byte(""))
mdToHTML := ""
if filepath.Ext(af.name) == ".md" {
newName := strings.Replace(af.name, filepath.Ext(af.name), ".html", 1)
af.targetName = []byte(newName)
mdProcessor.Convert(af.writeableContent, buf)
mdToHTML = buf.String()
}
if hook == nil {
return nil
}
hookInput := struct {
Name string `json:"name"`
SourcePath string `json:"source_path"`
DestPath string `json:"dest_path"`
Meta map[string]interface{} `json:"meta"`
WriteableContent string `json:"content"`
HTMLContent string `json:"html"`
}{
Name: string(af.targetName),
SourcePath: af.sourcePath,
DestPath: af.destPath,
Meta: af.meta,
WriteableContent: string(af.writeableContent),
HTMLContent: mdToHTML,
}
hookJsonInput, err := json.Marshal(hookInput)
bail(err)
if err := hook.CallByParam(lua.P{
Fn: hook.GetGlobal("Writer"),
NRet: 1,
Protect: true,
}, lua.LString(hookJsonInput)); err != nil {
panic(err)
}
ret := hook.Get(-1)
var fromPlug map[string]interface{}
err = json.Unmarshal([]byte(ret.String()), &fromPlug)
bail(err)
if fromPlug["content"] != nil {
stringVal := fmt.Sprintf("%s", fromPlug["content"])
af.writeableContent = []byte(stringVal)
}
if fromPlug["name"] != nil {
af.targetName = []byte(fmt.Sprintf("%v", fromPlug["name"]))
}
if fromPlug["data"] != nil {
af.data = mergeMapWithCheck(af.data, fromPlug["data"])
}
if fromPlug["extras"] != nil {
af.extras = mergeMapWithCheck(af.extras, fromPlug["extras"])
}
hook.Pop(1)
return nil
}
func (af *AlvuFile) FlushFile() {
destFolder := filepath.Dir(af.destPath)
os.MkdirAll(destFolder, os.ModePerm)
targetFile := strings.Replace(path.Join(af.destPath), af.name, string(af.targetName), 1)
onDebug(func() {
debugInfo("flushing for file: " + af.name + string(af.targetName))
debugInfo("flusing file: " + targetFile)
})
f, err := os.Create(targetFile)
bail(err)
defer f.Sync()
writeHeadTail := false
if af.baseTemplate == nil && (filepath.Ext(af.sourcePath) == ".md" || filepath.Ext(af.sourcePath) == "html") {
writeHeadTail = true
}
if writeHeadTail && af.headFile != nil {
shouldCopyContentsWithReset(af.headFile, f)
}
renderData := PageRenderData{
Meta: SiteMeta{
BaseURL: baseurl,
},
Data: af.data,
Extras: af.extras,
}
// Run the Markdown file through the conversion
// process to be able to use template variables in
// the markdown instead of writing them in
// raw HTML
var preConvertHTML bytes.Buffer
preConvertTmpl := textTmpl.New("temporary_pre_template")
preConvertTmpl.Parse(string(af.writeableContent))
err = preConvertTmpl.Execute(&preConvertHTML, renderData)
bail(err)
var toHtml bytes.Buffer
if !af.isHTML {
err = mdProcessor.Convert(preConvertHTML.Bytes(), &toHtml)
bail(err)
} else {
toHtml = preConvertHTML
}
layoutData := LayoutRenderData{
PageRenderData: renderData,
Content: template.HTML(toHtml.Bytes()),
}
// If a layout file was found
// write the converted html content into the
// layout template file
layout := template.New("layout")
var layoutTemplateData string
if af.baseTemplate != nil {
layoutTemplateData = string(readFileToBytes(af.baseTemplate))
} else {
layoutTemplateData = `<body>{{.Content}}</body>`
}
layoutTemplateData = _injectLiveReload(&layoutTemplateData)
toHtml.Reset()
layout.Parse(layoutTemplateData)
layout.Execute(&toHtml, layoutData)
io.Copy(
f, &toHtml,
)
if writeHeadTail && af.tailFile != nil && af.baseTemplate == nil {
shouldCopyContentsWithReset(af.tailFile, f)
}
data, err := os.ReadFile(targetFile)
bail(err)
onDebug(func() {
debugInfo("template path: %v", af.sourcePath)
})
t := template.New(path.Join(af.sourcePath))
t.Parse(string(data))
f.Seek(0, 0)
err = t.Execute(f, renderData)
bail(err)
}
func NewHook() *lua.LState {
lState := lua.NewState()
luaAlvu.Preload(lState)
luajson.Preload(lState)
yamlLib.Preload(lState)
stringsLib.Preload(lState)
lState.PreloadModule("http", ghttp.NewHttpModule(&http.Client{}).Loader)
if basePath == "." {
lState.SetGlobal("workingdir", lua.LString(""))
} else {
lState.SetGlobal("workingdir", lua.LString(basePath))
}
return lState
}
// UTILS
func memuse() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("heap: %v MiB\n", bytesToMB(m.HeapAlloc))
}
func bytesToMB(inBytes uint64) uint64 {
return inBytes / 1024 / 1024
}
func bail(err error) {
if err == nil {
return
}
cs := &color.ColorString{}
fmt.Fprintln(os.Stderr, cs.Red(logPrefix).Red(": "+err.Error()).String())
panic("")
}
func debugInfo(msg string, a ...any) {
cs := &color.ColorString{}
prefix := logPrefix
baseMessage := cs.Reset("").Yellow(prefix).Reset(" ").Gray(msg).String()
fmt.Fprintf(os.Stdout, baseMessage+" \n", a...)
}
func showDebug() bool {
showInfo := env.Get("DEBUG_ALVU", "")
return len(showInfo) != 0
}
func onDebug(fn func()) {
if !showDebug() {
return
}
fn()
}
func mergeMapWithCheck(maps ...any) (source map[string]interface{}) {
source = map[string]interface{}{}
for _, toCheck := range maps {
if pairs, ok := toCheck.(map[string]interface{}); ok {
for k, v := range pairs {
source[k] = v
}
}
}
return source
}
func readFileToBytes(fd *os.File) []byte {
buf := &bytes.Buffer{}
fd.Seek(0, 0)
_, err := io.Copy(buf, fd)
bail(err)
return buf.Bytes()
}
func shouldCopyContentsWithReset(src *os.File, target *os.File) {
src.Seek(0, 0)
_, err := io.Copy(target, src)
bail(err)
}
func ServeHandler(rw http.ResponseWriter, req *http.Request) {
path := req.URL.Path
if path == "/" {
path = filepath.Join(outPath, "index.html")
http.ServeFile(rw, req, path)
return
}
// check if the requested file already exists
file := filepath.Join(outPath, path)
info, err := os.Stat(file)
// if not, check if it's a directory
// and if it's a directory, we look for
// a index.html inside the directory to return instead
if err == nil {
if info.Mode().IsDir() {
file = filepath.Join(outPath, path, "index.html")
_, err := os.Stat(file)
if err != nil {
notFoundHandler(rw, req)
return
}
}
http.ServeFile(rw, req, file)
return
}
// if neither a directory or file was found
// try a secondary case where the file might be missing
// a `.html` extension for cleaner url so append a .html
// to look for the file.
if err != nil {
file := filepath.Join(outPath, normalizeFilePath(path))
_, err := os.Stat(file)
if err != nil {
notFoundHandler(rw, req)
return
}
http.ServeFile(rw, req, file)
return
}
notFoundHandler(rw, req)
}
// _webSocketHandler Internal function to setup a listener loop
// for the live reload setup
func _webSocketHandler(ws *websocket.Conn) {
reloadCh = append(reloadCh, make(chan bool, 1))
currIndex := len(reloadCh) - 1
defer ws.Close()
for range reloadCh[currIndex] {
err := websocket.Message.Send(ws, "reload")
if err != nil {
// For debug only
// log.Printf("Error sending message: %s", err.Error())
break
}
onDebug(func() {
debugInfo("Reload message sent")
})
}
}
func AddWebsocketHandler() {
wsHandler := websocket.Handler(_webSocketHandler)
// Use a custom HTTP handler function to upgrade the HTTP request to WebSocket
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
// Check the request's 'Upgrade' header to see if it's a WebSocket request
if r.Header.Get("Upgrade") != "websocket" {
http.Error(w, "Not a WebSocket handshake request", http.StatusBadRequest)
return
}
// Upgrade the HTTP connection to a WebSocket connection
wsHandler.ServeHTTP(w, r)
})
}
// _clientNotifyReload Internal function to
// report changes to all possible reload channels
func _clientNotifyReload() {
for ind := range reloadCh {
reloadCh[ind] <- true
}
reloadCh = []chan bool{}
}
func normalizeFilePath(path string) string {
if strings.HasSuffix(path, ".html") {
return path
}
return path + ".html"
}
func notFoundHandler(w http.ResponseWriter, _ *http.Request) {
if notFoundPageExists {
compiledNotFoundFile := filepath.Join(outPath, "404.html")
notFoundFile, err := os.ReadFile(compiledNotFoundFile)
if err != nil {
http.Error(w, "404, Page not found....", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNotFound)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(notFoundFile)
return
}
http.Error(w, "404, Page not found....", http.StatusNotFound)
}
func Contains(collection []string, item string) bool {
for _, x := range collection {
if item == x {
return true
}
}
return false
}
// Watcher , create an interface over the fsnotify watcher
// to be able to run alvu compile processes again
// FIXME: redundant compile process for the files
type Watcher struct {
alvu *Alvu
poller *poller.Poller
dirs []string
}
func NewWatcher(alvu *Alvu, interval int) *Watcher {
watcher := &Watcher{
alvu: alvu,
poller: poller.NewPollWatcher(interval),
}
return watcher
}
func (w *Watcher) AddDir(dirPath string) {
for _, pth := range w.dirs {
if pth == dirPath {
return
}
}
w.dirs = append(w.dirs, dirPath)
w.poller.Add(dirPath)
}
func (w *Watcher) RebuildAlvu() {
onDebug(func() {
debugInfo("Rebuild Started")
})
w.alvu.CopyPublic()
w.alvu.Build()
onDebug(func() {
debugInfo("Build Completed")
})
}
func (w *Watcher) RebuildFile(filePath string) {
onDebug(func() {
debugInfo("RebuildFile Started")
})
for i, af := range w.alvu.files {
if af.sourcePath != filePath {
continue
}
w.alvu.files[i].Build()
break
}
onDebug(func() {
debugInfo("RebuildFile Completed")
})
}
func (w *Watcher) StartWatching() {
go w.poller.StartPoller()
go func() {
for {
select {
case evt := <-w.poller.Events:
onDebug(func() {
debugInfo("Events registered")
})
recompiledText := &color.ColorString{}
recompiledText.Blue(logPrefix).Green("Recompiled!").Reset(" ")
_, err := os.Stat(evt.Path)
// Do nothing if the file doesn't exit, just continue
if err != nil {
continue
}
// If alvu file then just build the file, else
// just rebuilt the whole folder since it could
// be a file from the public folder or the _layout file
if w.alvu.IsAlvuFile(evt.Path) {
recompilingText := &color.ColorString{}
recompilingText.Blue(logPrefix).Cyan("Recompiling: ").Gray(evt.Path).Reset(" ")
fmt.Println(recompilingText.String())
w.RebuildFile(evt.Path)