1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
package main
import (
"os"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
)
const chmodMask fsnotify.Op = ^fsnotify.Op(0) ^ fsnotify.Chmod
// watch recursively watches changes in root and reports the filenames to names.
// It sends an error on the done chan.
// As an optimization, any dirs we encounter that meet the ExcludePrefix
// criteria of all reflexes can be ignored.
func watch(root string, watcher *fsnotify.Watcher, names chan<- string, done chan<- error, reflexes []*Reflex) {
if err := filepath.Walk(root, walker(watcher, reflexes)); err != nil {
infoPrintf(-1, "Error while walking path %s: %s", root, err)
}
for {
select {
case e := <-watcher.Events:
if verbose {
infoPrintln(-1, "fsnotify event:", e)
}
stat, err := os.Stat(e.Name)
if err != nil {
continue
}
path := normalize(e.Name, stat.IsDir())
if e.Op&chmodMask == 0 {
continue
}
names <- path
if e.Op&fsnotify.Create > 0 && stat.IsDir() {
if err := filepath.Walk(path, walker(watcher, reflexes)); err != nil {
infoPrintf(-1, "Error while walking path %s: %s", path, err)
}
}
// TODO: Cannot currently remove fsnotify watches
// recursively, or for deleted files. See:
// https://github.com/cespare/reflex/issues/13
// https://github.com/go-fsnotify/fsnotify/issues/40
// https://github.com/go-fsnotify/fsnotify/issues/41
case err := <-watcher.Errors:
done <- err
return
}
}
}
func walker(watcher *fsnotify.Watcher, reflexes []*Reflex) filepath.WalkFunc {
return func(path string, f os.FileInfo, err error) error {
if err != nil || !f.IsDir() {
return nil
}
path = normalize(path, f.IsDir())
ignore := true
for _, r := range reflexes {
if !r.matcher.ExcludePrefix(path) {
ignore = false
break
}
}
if ignore {
return filepath.SkipDir
}
if err := watcher.Add(path); err != nil {
infoPrintf(-1, "Error while watching new path %s: %s", path, err)
}
return nil
}
}
func normalize(path string, dir bool) string {
path = strings.TrimPrefix(path, "./")
if dir && !strings.HasSuffix(path, "/") {
path = path + "/"
}
return path
}
|