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