75 lines
1.5 KiB
Go
75 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"github.com/fsnotify/fsnotify"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func watchFiles(dir string, changes chan<- FileChange) {
|
|
watcher, err := fsnotify.NewWatcher()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer watcher.Close()
|
|
|
|
// Add all directories recursively
|
|
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if info.IsDir() {
|
|
err = watcher.Add(path)
|
|
if err != nil {
|
|
log.Printf("Error watching %s: %v\n", path, err)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case event, ok := <-watcher.Events:
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
// Handle different types of events
|
|
var operation string
|
|
switch {
|
|
case event.Op&fsnotify.Write == fsnotify.Write:
|
|
operation = "MODIFIED"
|
|
case event.Op&fsnotify.Create == fsnotify.Create:
|
|
operation = "CREATED"
|
|
// If a new directory is created, start watching it
|
|
if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
|
|
watcher.Add(event.Name)
|
|
}
|
|
case event.Op&fsnotify.Remove == fsnotify.Remove:
|
|
operation = "REMOVED"
|
|
case event.Op&fsnotify.Rename == fsnotify.Rename:
|
|
operation = "RENAMED"
|
|
case event.Op&fsnotify.Chmod == fsnotify.Chmod:
|
|
operation = "CHMOD"
|
|
default:
|
|
operation = "UNKNOWN"
|
|
}
|
|
|
|
changes <- FileChange{
|
|
Path: event.Name,
|
|
Operation: operation,
|
|
}
|
|
|
|
case err, ok := <-watcher.Errors:
|
|
if !ok {
|
|
return
|
|
}
|
|
log.Printf("Watcher error: %v\n", err)
|
|
}
|
|
}
|
|
}
|