Files
go-telldus-matter/pkg/telldus-daemon/watcher.go
Mats Tornberg 87660c7d1d update
2025-11-22 17:35:24 +01:00

64 lines
1.4 KiB
Go

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)
}
}
}