-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfswatch.go
137 lines (112 loc) · 2.59 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package fswatch
import (
"fmt"
"os"
"path/filepath"
"time"
)
type FileInfo struct {
Path string
FileInfo os.FileInfo
}
type Watcher struct {
Changed chan FileInfo
stop chan int
}
func WatchFile(filename string, frequency time.Duration) *Watcher {
fw := &Watcher{make(chan FileInfo), make(chan int)}
lastFi, _ := os.Stat(filename)
go func() {
ticker := time.NewTicker(frequency)
changed := false
// send a change signal initially
if lastFi != nil {
fw.Changed <- FileInfo{filename, lastFi}
}
for {
select {
case <-ticker.C:
fi, err := os.Stat(filename)
if err != nil {
// If there's an error stating the file do nothing
break
}
// check if the file did not originally exist
if lastFi == nil {
lastFi = fi
changed = true
break
}
wasChanged := fi.ModTime() != lastFi.ModTime() || fi.Size() != lastFi.Size()
switch {
// The file was modified
case wasChanged:
changed = true
// The file was not modified since it was last changed
case changed && !wasChanged && !fi.IsDir():
// Send the newest stat to the channel
fw.Changed <- FileInfo{filename, fi}
// Reset the changed flag
changed = false
}
lastFi = fi
case _, ok := <-fw.stop:
if !ok {
ticker.Stop()
return
}
}
}
}()
return fw
}
func (fw *Watcher) Close() error {
close(fw.stop)
return nil
}
type dirFileInfo struct {
fileInfo os.FileInfo
changed bool
newFile bool
}
func WatchDirectory(dirname string, frequency time.Duration) *Watcher {
fw := &Watcher{make(chan FileInfo), make(chan int)}
fileList := make(map[string]*dirFileInfo)
go func() {
walkAction := func(path string, fi os.FileInfo, err error) error {
if dfi, ok := fileList[path]; ok && !fi.IsDir() && err == nil {
lastFi := dfi.fileInfo
wasChanged := fi.ModTime() != lastFi.ModTime() || fi.Size() != lastFi.Size()
switch {
case wasChanged:
dfi.fileInfo = fi
dfi.changed = true
case !wasChanged && dfi.changed:
dfi.changed = false
fw.Changed <- FileInfo{path, fi}
case !wasChanged && dfi.newFile:
dfi.newFile = false
fw.Changed <- FileInfo{path, fi}
}
} else {
fileList[path] = &dirFileInfo{fi, false, true}
}
return nil
}
// do a first walk of the directory immediately to get initial results
filepath.Walk(dirname, walkAction)
ticker := time.NewTicker(frequency)
for {
select {
case <-ticker.C:
filepath.Walk(dirname, walkAction)
case _, ok := <-fw.stop:
if !ok {
ticker.Stop()
return
}
}
}
}()
return fw
}