about summary refs log tree commit diff stats
path: root/internal/server/dev.go
diff options
context:
space:
mode:
authorAlan Pearce2024-06-11 10:07:25 +0200
committerAlan Pearce2024-06-11 10:07:25 +0200
commit66b66e6118dd43ccbd1e85e33d44a02de7a2b812 (patch)
tree32987723187ddac9d3a8aa8187aa20080aa5c91d /internal/server/dev.go
parente89fbd7ef3e418629ea2533cf4fa9707fe51950f (diff)
downloadwebsite-66b66e6118dd43ccbd1e85e33d44a02de7a2b812.tar.lz
website-66b66e6118dd43ccbd1e85e33d44a02de7a2b812.tar.zst
website-66b66e6118dd43ccbd1e85e33d44a02de7a2b812.zip
server: automatically build, re-build and reload in dev
Diffstat (limited to 'internal/server/dev.go')
-rw-r--r--internal/server/dev.go71
1 files changed, 71 insertions, 0 deletions
diff --git a/internal/server/dev.go b/internal/server/dev.go
new file mode 100644
index 0000000..f7ebb82
--- /dev/null
+++ b/internal/server/dev.go
@@ -0,0 +1,71 @@
+package server
+
+import (
+	"fmt"
+	"io/fs"
+	"log/slog"
+	"os"
+	"path/filepath"
+	"time"
+	"website/internal/log"
+
+	"github.com/fsnotify/fsnotify"
+	"github.com/pkg/errors"
+)
+
+type FileWatcher struct {
+	*fsnotify.Watcher
+}
+
+func NewFileWatcher() (*FileWatcher, error) {
+	watcher, err := fsnotify.NewWatcher()
+	if err != nil {
+		return nil, errors.WithMessage(err, "could not create watcher")
+	}
+
+	return &FileWatcher{watcher}, nil
+}
+
+func (watcher FileWatcher) AddRecursive(from string) error {
+	log.Debug("walking directory tree", "root", from)
+	err := filepath.WalkDir(from, func(path string, entry fs.DirEntry, err error) error {
+		if err != nil {
+			return errors.WithMessagef(err, "could not walk directory %s", path)
+		}
+		if entry.IsDir() {
+			log.Debug("adding directory to watcher", "path", path)
+			if err = watcher.Add(path); err != nil {
+				return errors.WithMessagef(err, "could not add directory %s to watcher", path)
+			}
+		}
+
+		return nil
+	})
+
+	return errors.WithMessage(err, "error walking directory tree")
+}
+
+func (watcher FileWatcher) Start(callback func(string)) {
+	for {
+		select {
+		case event := <-watcher.Events:
+			if event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) {
+				f, err := os.Stat(event.Name)
+				if err != nil {
+					slog.Error(fmt.Sprintf("error handling %s event: %v", event.Op.String(), err))
+				} else if f.IsDir() {
+					err = watcher.Add(event.Name)
+					if err != nil {
+						slog.Error(fmt.Sprintf("error adding new folder to watcher: %v", err))
+					}
+				}
+			}
+			if event.Has(fsnotify.Rename) || event.Has(fsnotify.Write) {
+				callback(event.Name)
+				time.Sleep(500 * time.Millisecond)
+			}
+		case err := <-watcher.Errors:
+			slog.Error(fmt.Sprintf("error in watcher: %v", err))
+		}
+	}
+}