This repository has been archived by the owner on Mar 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_watcher.go
95 lines (78 loc) · 1.66 KB
/
file_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type Watcher struct {
C chan string
cancelled bool
root string
observation time.Duration
}
// pushes new files onto c when they've stopped getting bigger after observation time
func NewWatcher(path string, observation time.Duration) *Watcher {
return &Watcher{
C: make(chan string, 0),
root: path,
observation: observation,
}
}
func (w *Watcher) Watch() {
var wg sync.WaitGroup
w.loop(&wg)
wg.Wait()
close(w.C)
}
func (w *Watcher) Cancel() {
w.cancelled = true
}
func (w *Watcher) loop(wg *sync.WaitGroup) {
files := make(map[string]bool)
for !w.cancelled {
w.walk(wg, files)
time.Sleep(100 * time.Millisecond)
}
w.walk(wg, files)
}
func (w *Watcher) walk(wg *sync.WaitGroup, files map[string]bool) {
filepath.Walk(w.root,
func(path string, info os.FileInfo, err error) error {
lower := strings.ToLower(path) // multiple filewalks return files with different case...
if !info.IsDir() {
if _, exists := files[lower]; !exists {
files[lower] = true
wg.Add(1)
go pushWhenWriteStops(w.C, wg, path, w.observation)
}
}
return nil
})
}
func pushWhenWriteStops(c chan string, wg *sync.WaitGroup, path string, observation time.Duration) {
fi, err := os.Stat(path)
if err != nil {
return
}
size := fi.Size()
mtime := time.Now()
for {
time.Sleep(100 * time.Millisecond)
fi, err := os.Stat(path)
if err != nil {
return
}
age := time.Now().Sub(mtime)
if age > observation && size == fi.Size() {
c <- path
wg.Done()
return
}
if fi.Size() != size {
mtime = time.Now()
size = fi.Size()
}
}
}