-
Notifications
You must be signed in to change notification settings - Fork 0
/
fswatch.go
97 lines (88 loc) · 1.74 KB
/
fswatch.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package fswatch
import (
"fmt"
"io/ioutil"
"path"
"strings"
"github.com/fsnotify/fsnotify"
)
var baseIgnore = []string{"node_modules", ".git", ".vscode", ".idea", ".next"}
func Watch(paths, ignore []string, fn func(file string)) {
ignore = append(ignore, baseIgnore...)
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("watch error:", err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
// fmt.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
fn(event.Name)
// log.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("[error] watcher.Errors:", err)
}
}
}()
readedDirs := map[string]bool{}
var readDirs func([]string)
readDirs = func(dirs []string) {
var nextDirs []string
for _, p := range dirs {
var jump bool
for _, v := range ignore {
if strings.Contains(p, v) {
jump = true
break
}
}
if jump {
continue
}
err = watcher.Add(p)
if err != nil {
fmt.Println("[error] watcher.Add:", err)
}
files, err := ioutil.ReadDir(p)
if err != nil {
fmt.Println("[error] watcher.Add:", err)
}
for _, v := range files {
if readedDirs[v.Name()] {
continue
}
if v.IsDir() {
dir1 := path.Join(p, v.Name())
readedDirs[dir1] = true
var jump bool
for _, v := range ignore {
if strings.Contains(p, v) {
jump = true
break
}
}
if jump {
continue
}
nextDirs = append(nextDirs, dir1)
}
}
}
if len(nextDirs) > 0 {
readDirs(nextDirs)
}
}
readDirs(paths)
<-done
}