Skip to content

Instantly share code, notes, and snippets.

@howeyc
Created February 12, 2013 12:56
Show Gist options
  • Save howeyc/4762676 to your computer and use it in GitHub Desktop.
Save howeyc/4762676 to your computer and use it in GitHub Desktop.
Watch for created directories.
package main
import (
"log"
"os"
"path/filepath"
"github.com/howeyc/fsnotify"
)
func watchAllDirs(watcher *fsnotify.Watcher, root string) (err error) {
walkFn := func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
watcher.Watch(path)
log.Println("Added Watch: ", path)
}
return nil
}
return filepath.Walk(root, walkFn)
}
func main() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
done := make(chan bool)
go func() {
for {
select {
case ev := <-watcher.Event:
log.Println("event:", ev)
if ev.IsCreate() {
if finfo, err := os.Stat(ev.Name); err == nil && finfo.IsDir() {
watcher.Watch(ev.Name)
log.Println("Added Watch: ", ev.Name)
}
}
case err := <-watcher.Error:
log.Println("error:", err)
}
}
done <- true
}()
err = watchAllDirs(watcher, "test")
if err != nil {
log.Fatal(err)
}
<-done
watcher.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment