-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchanges.go
138 lines (108 loc) · 2.15 KB
/
changes.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
138
package changes
import (
"os"
"path/filepath"
"sort"
"time"
"github.com/docker/engine/pkg/fileutils"
)
type Change struct {
Operation string
Base string
Path string
}
type WatchOptions struct {
Ignores []string
}
func Files(cc []Change) []string {
files := make([]string, len(cc))
for i, c := range cc {
files[i] = c.Path
}
sort.Strings(files)
return files
}
func Partition(changes []Change) (adds []Change, removes []Change) {
for _, c := range changes {
switch c.Operation {
case "add":
adds = append(adds, c)
case "remove":
removes = append(removes, c)
}
}
return
}
func Watch(dir string, ch chan Change, opts WatchOptions) error {
abs, err := filepath.Abs(dir)
if err != nil {
return err
}
sym, err := filepath.EvalSymlinks(abs)
if err != nil {
return err
}
return watchForChanges(sym, opts.Ignores, ch)
}
func watchForChanges(dir string, ignore []string, ch chan Change) error {
defer close(ch)
cur, err := snapshot(dir)
if err != nil {
return err
}
startScanner(dir)
for {
snap, err := snapshot(dir)
if err != nil {
return err
}
notify(ch, cur, snap, dir, ignore)
cur = snap
waitForNextScan(dir)
}
}
func notify(ch chan Change, from, to map[string]time.Time, base string, ignore []string) {
for fk, ft := range from {
tt, ok := to[fk]
switch {
case !ok:
send(ch, "remove", fk, base, ignore)
case ft.Before(tt):
send(ch, "add", fk, base, ignore)
}
}
for tk := range to {
if _, ok := from[tk]; !ok {
send(ch, "add", tk, base, ignore)
}
}
}
func send(ch chan Change, op, file, base string, ignore []string) {
rel, err := filepath.Rel(base, file)
if err != nil {
return
}
if match, _ := fileutils.Matches(rel, ignore); match {
return
}
change := Change{
Operation: op,
Base: base,
Path: rel,
}
ch <- change
}
func snapshot(dir string) (map[string]time.Time, error) {
snap := map[string]time.Time{}
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info == nil || info.IsDir() {
return nil
}
snap[path] = info.ModTime()
return nil
})
if err != nil {
return nil, err
}
return snap, nil
}