forked from agrinman/chasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
77 lines (65 loc) · 1.3 KB
/
watcher.go
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
package main
import (
"log"
"os"
"gopkg.in/fsnotify.v1"
)
// StartWatching a path indefinitely.
func StartWatching(path string, subDirs map[string]bool) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
err = watcher.Add(path)
if err != nil {
log.Fatal(err)
}
for sub, _ := range subDirs {
watcher.Add(sub)
}
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
log.Println("event:", event)
isDir := isDir(event.Name)
if event.Op&fsnotify.Create == fsnotify.Create {
AddFile(event.Name)
if isDir {
watcher.Add(event.Name)
}
} else if event.Op&fsnotify.Write == fsnotify.Write {
AddFile(event.Name)
if isDir {
watcher.Add(event.Name)
}
} else if event.Op&fsnotify.Rename == fsnotify.Rename {
DeleteFile(event.Name)
} else if event.Op&fsnotify.Remove == fsnotify.Remove {
DeleteFile(event.Name)
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
<-done
}
func isDir(filePath string) bool {
file, err := os.Open(filePath)
if err != nil {
return false
}
fi, err := file.Stat()
if err != nil {
return false
}
switch mode := fi.Mode(); {
case mode.IsDir():
return true
default:
return false
}
}