watcher.go: Automatically watch added subdirectories

This commit is contained in:
Aaron Lindsay 2013-02-12 09:11:38 -05:00
parent 61d5532e33
commit 5d3cd40195

View File

@ -2,6 +2,8 @@ package main
import ( import (
"github.com/howeyc/fsnotify" "github.com/howeyc/fsnotify"
"os"
"path/filepath"
) )
func StartWatching(watchDir string, fileUpdates chan *Event) { func StartWatching(watchDir string, fileUpdates chan *Event) {
@ -10,39 +12,58 @@ func StartWatching(watchDir string, fileUpdates chan *Event) {
panic("Failed to create fsnotify watcher") panic("Failed to create fsnotify watcher")
} }
err = watcher.Watch(watchDir) //function called by filepath.Walk to start watching a directory and all subdirectories
if err != nil { watchDirFn := func(path string, info os.FileInfo, err error) error {
panic("Failed to watch " + watchDir) if info.IsDir() {
err = watcher.Watch(path)
if err != nil {
panic("Failed to watch " + path)
}
}
return nil
} }
for { //processes all the fsnotify events into asink events
select { go func() {
case ev := <-watcher.Event: for {
event := new(Event) select {
if ev.IsCreate() || ev.IsModify() { case ev := <-watcher.Event:
event.Type = UPDATE //if a directory was created, begin recursively watching all its subdirectories
} else if ev.IsDelete() || ev.IsRename() { if fi, err := os.Stat(ev.Name); err == nil && fi.IsDir() {
event.Type = DELETE if ev.IsCreate() {
} else { filepath.Walk(ev.Name, watchDirFn)
panic("Unknown fsnotify event type") }
}
event.Path = ev.Name
if event.IsUpdate() {
event.Hash, err = HashFile(ev.Name)
if err != nil {
continue continue
} }
} else {
event.Hash = "" event := new(Event)
if ev.IsCreate() || ev.IsModify() {
event.Type = UPDATE
} else if ev.IsDelete() || ev.IsRename() {
event.Type = DELETE
} else {
panic("Unknown fsnotify event type")
}
event.Path = ev.Name
if event.IsUpdate() {
event.Hash, err = HashFile(ev.Name)
if err != nil {
panic("file deleted already?")
continue
}
} else {
event.Hash = ""
}
fileUpdates <- event
case err := <-watcher.Error:
panic(err)
} }
fileUpdates <- event
//TODO if creating a directory, start watching it (and then initiate a full scan of it so we're sure nothing slipped through the cracks)
case err := <-watcher.Error:
panic(err)
} }
} }()
//start watching the directory passed in
filepath.Walk(watchDir, watchDirFn)
} }