diff --git a/crontabd/main.go b/crontabd/main.go index b01d8c8..82dad49 100644 --- a/crontabd/main.go +++ b/crontabd/main.go @@ -31,18 +31,14 @@ func main() { } logger.Info("Crontab file resolved as: %s", crontabFile) - watcher, err := fsnotify.NewWatcher() + events, err := watchCrontabFile(crontabFile) if err != nil { - logger.Error("Failed to create watcher: %v", err) + logger.Error("Failed to watch crontab file: %v", err) return } - - err = watcher.Add(crontabFile) - if err != nil { - logger.Error("Failed to add crontab file to watcher: %v", err) - return + for event := range events { + logger.Info("Crontab file updated: %s", event.Name) } - logger.Info("Watching crontab file: %s", crontabFile) } func resolveCrontabPath() (string, error) { @@ -79,3 +75,37 @@ func ensureExists(path string) error { defer file.Close() return nil } + +func watchCrontabFile(path string) (<-chan fsnotify.Event, error) { + watcher, err := fsnotify.NewWatcher() + if err != nil { + return nil, fmt.Errorf("failed to create watcher: %v", err) + } + + err = watcher.Add(path) + if err != nil { + return nil, fmt.Errorf("failed to add crontab file to watcher: %v", err) + } + + filteredChan := make(chan fsnotify.Event) + go func() { + defer close(filteredChan) + for { + select { + case event, ok := <-watcher.Events: + if !ok { + return + } + if event.Op&fsnotify.Write == fsnotify.Write { + filteredChan <- event + } + case err, ok := <-watcher.Errors: + if !ok { + return + } + logger.Error("Error watching crontab file: %v", err) + } + } + }() + return filteredChan, nil +}