diff options
author | Thomas Voss <mail@thomasvoss.com> | 2025-06-14 00:40:55 +0200 |
---|---|---|
committer | Thomas Voss <mail@thomasvoss.com> | 2025-06-14 00:40:55 +0200 |
commit | 604cac8c0ab26a43d28341ff6f6e58e969eec925 (patch) | |
tree | b15ccb9ca705dd34ec50713e8e743b43e7e455d0 /src | |
parent | 197686a72cd464417d2e5afce1214a973d253946 (diff) |
Implement the ‘watch’ package
Diffstat (limited to 'src')
-rw-r--r-- | src/templates.go | 39 | ||||
-rw-r--r-- | src/watch/watch.go | 41 |
2 files changed, 65 insertions, 15 deletions
diff --git a/src/templates.go b/src/templates.go index 8479759..de1f081 100644 --- a/src/templates.go +++ b/src/templates.go @@ -8,6 +8,8 @@ import ( "strings" "git.thomasvoss.com/euro-cash.eu/src/dbx" + . "git.thomasvoss.com/euro-cash.eu/src/try" + "git.thomasvoss.com/euro-cash.eu/src/watch" ) type templateData struct { @@ -31,29 +33,36 @@ var ( } ) -func BuildTemplates(dir fs.FS) { - ents, err := fs.ReadDir(dir, ".") - if err != nil { - log.Fatal(err) - } - +func BuildTemplates(dir fs.FS, debugp bool) { + ents := Try2(fs.ReadDir(dir, ".")) notFoundTmpl = buildTemplate(dir, "-404") errorTmpl = buildTemplate(dir, "-error") - templates = make(map[string]*template.Template, len(ents)) + for _, e := range ents { - path := "/" - name := strings.TrimSuffix(e.Name(), ".html.tmpl") - switch { - case name[0] == '-': - continue - case name != "index": - path += strings.ReplaceAll(name, "-", "/") + name := e.Name() + buildAndSetTemplate(dir, name) + if debugp { + go watch.FileFS(dir, name, func() { + buildAndSetTemplate(dir, name) + log.Printf("Template ‘%s’ updated\n", name) + }) } - templates[path] = buildTemplate(dir, name) } } +func buildAndSetTemplate(dir fs.FS, name string) { + path := "/" + name = strings.TrimSuffix(name, ".html.tmpl") + switch { + case name[0] == '-': + return + case name != "index": + path += strings.ReplaceAll(name, "-", "/") + } + templates[path] = buildTemplate(dir, name) +} + func buildTemplate(dir fs.FS, name string) *template.Template { names := [...]string{"-base", "-navbar", name} for i, s := range names { diff --git a/src/watch/watch.go b/src/watch/watch.go new file mode 100644 index 0000000..84f9ed9 --- /dev/null +++ b/src/watch/watch.go @@ -0,0 +1,41 @@ +package watch + +import ( + "errors" + "io/fs" + "log" + "os" + "time" + + . "git.thomasvoss.com/euro-cash.eu/src/try" +) + +func File(path string, f func()) { + impl(path, os.Stat, f) +} + +func FileFS(dir fs.FS, path string, f func()) { + impl(path, func(path string) (os.FileInfo, error) { + return fs.Stat(dir, path) + }, f) +} + +func impl(path string, statfn func(string) (os.FileInfo, error), f func()) { + ostat := Try2(statfn(path)) + + for { + nstat, err := statfn(path) + switch { + case errors.Is(err, os.ErrNotExist): + return + case err != nil: + log.Println(err) + } + + if nstat.ModTime() != ostat.ModTime() { + f() + ostat = nstat + } + time.Sleep(1 * time.Second) + } +} |