-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.go
112 lines (103 loc) · 2.17 KB
/
filter.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
package sniffy
import (
"path/filepath"
"strings"
"sync"
"time"
"gopkg.in/fsnotify.v1"
)
// This factory will concatinate multiple filters into
// one
func FilterChain(fs ...Filter) Filter {
m := &sync.Mutex{}
return func(e fsnotify.Event) bool {
m.Lock()
defer m.Unlock()
for _, f := range fs {
if !f(e) {
return false
}
}
return true
}
}
// If Event was triggered by provided operation this factory
// will return Filter that will pass
func OpFilter(ops ...fsnotify.Op) Filter {
return func(e fsnotify.Event) bool {
for _, op := range ops {
if op == e.Op {
return true
}
}
return false
}
}
// Returns true only if event occured on files with
// provided extensions
func ExtFilter(exts ...string) Filter {
return func(e fsnotify.Event) bool {
for _, ext := range exts {
if filepath.Ext(e.Name) == ext {
return true
}
}
return false
}
}
// Returns true only if event occured on a child
// of provided paths
// paths must be absolute
func ChildFilter(paths ...string) Filter {
return func(e fsnotify.Event) bool {
for _, p := range paths {
if strings.HasPrefix(e.Name+"/", p) {
return true
}
}
return false
}
}
// Returns false if Event path is one of the provided paths
// paths must be absolute
func ExcludePathFilter(paths ...string) Filter {
return func(e fsnotify.Event) bool {
for _, p := range paths {
if p == e.Name {
return false
}
}
return true
}
}
// Returns false if last event occured
// within the specified duration
// It can be used to filter out simultaneous events
func TooSoonFilter(d time.Duration) Filter {
var (
lastTime time.Time
)
return func(_ fsnotify.Event) bool {
now := time.Now()
if !lastTime.IsZero() {
if now.Sub(lastTime) <= d {
return false
}
}
lastTime = now
return true
}
}
// Returns false if event occured on file with provided
// shell filename patterns, pattern will be matched against
// filename not the absolute path
func IgnoreFnPatternFilter(pats ...string) Filter {
return func(e fsnotify.Event) bool {
for _, p := range pats {
if ok, _ := filepath.Match(p, filepath.Base(e.Name)); ok {
return false
}
}
return true
}
}