This commit is contained in:
Mats Tornberg
2025-11-22 17:35:24 +01:00
parent 0596fe60fa
commit 87660c7d1d
12 changed files with 34 additions and 39 deletions

View File

@@ -0,0 +1,63 @@
package daemon
import (
"log"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
// Watcher watches for configuration file changes
type Watcher struct {
configPath string
onReloadFunc func() error
}
// NewWatcher creates a new config file watcher
func NewWatcher(configPath string, onReload func() error) *Watcher {
return &Watcher{
configPath: configPath,
onReloadFunc: onReload,
}
}
// Watch starts watching for changes to the configuration file
func (w *Watcher) Watch() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// Watch the parent directory since file operations might replace the file
configDir := filepath.Dir(w.configPath)
if err := watcher.Add(configDir); err != nil {
return err
}
log.Printf("Watching for changes to %s", w.configPath)
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return nil
}
// Check if the event is for our config file
if event.Name == w.configPath && (event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create) {
log.Printf("Configuration file changed: %s", event.Op.String())
// Call reload callback if provided
if w.onReloadFunc != nil {
if err := w.onReloadFunc(); err != nil {
log.Printf("Failed to reload devices: %v", err)
}
}
}
case err, ok := <-watcher.Errors:
if !ok {
return nil
}
log.Printf("File watcher error: %v", err)
}
}
}