Debian Codegraph @

watcher/watcher.go

raw symbols SCIP
1 // Package watcher implements filesystem notification,.
2 package watcher
3
4 import (
5 //"fmt"
6
7 "os"
8 "path/filepath"
9 "strings"
10 "sync"
11 "time"
12
13 "github.com/mgutz/str"
14 "gopkg.in/godo.v2/watcher/fswatch"
15 )
16
17 const (
18 // IgnoreThresholdRange is the amount of time in ns to ignore when
19 // receiving watch events for the same file
20 IgnoreThresholdRange = 50 * 1000000 // convert to ms
21 )
22
23 // SetWatchDelay sets the watch delay
24 func SetWatchDelay(delay time.Duration) {
25 fswatch.WatchDelay = delay
26 }
27
28 // Watcher is a wrapper around which adds some additional features:
29 //
30 // - recursive directory watch
31 // - buffer to even chan
32 // - even time
33 //
34 // Original work from https://github.com/bronze1man/kmg
35 type Watcher struct {
36 *fswatch.Watcher
37 Event chan *FileEvent
38 Error chan error
39 //default ignore all file start with "."
40 IgnorePathFn func(path string) bool
41 //default is nil,if is nil ,error send through Error chan,if is not nil,error handle by this func
42 ErrorHandler func(err error)
43 isClosed bool
44 quit chan bool
45 cache map[string]*os.FileInfo
46 mu sync.Mutex
47 }
48
49 // NewWatcher creates an instance of watcher.
50 func NewWatcher(bufferSize int) (watcher *Watcher, err error) {
51
52 fswatcher := fswatch.NewAutoWatcher()
53
54 if err != nil {
55 return nil, err
56 }
57 watcher = &Watcher{
58 Watcher: fswatcher,
59 Error: make(chan error, 10),
60 Event: make(chan *FileEvent, bufferSize),
61 IgnorePathFn: DefaultIgnorePathFn,
62 cache: map[string]*os.FileInfo{},
63 }
64 return
65 }
66
67 // Close closes the watcher channels.
68 func (w *Watcher) Close() error {
69 if w.isClosed {
70 return nil
71 }
72 w.Watcher.Stop()
73 w.quit <- true
74 w.isClosed = true
75 return nil
76 }
77
78 func (w *Watcher) eventLoop() {
79 // cache := map[string]*os.FileInfo{}
80 // mu := &sync.Mutex{}
81
82 coutput := w.Watcher.Start()
83 for {
84 event, ok := <-coutput
85 if !ok {
86 return
87 }
88
89 // fmt.Printf("event %+v\n", event)
90 if w.IgnorePathFn(event.Path) {
91 continue
92 }
93
94 // you can not stat a delete file...
95 if event.Event == fswatch.DELETED || event.Event == fswatch.NOEXIST {
96 // adjust with arbitrary value because it was deleted
97 // before it got here
98 //fmt.Println("sending fi wevent", event)
99 w.Event <- newFileEvent(event.Event, event.Path, time.Now().UnixNano()-10)
100 continue
101 }
102
103 fi, err := os.Stat(event.Path)
104 if os.IsNotExist(err) {
105 //fmt.Println("not exists", event)
106 continue
107 }
108
109 // fsnotify is sending multiple MODIFY events for the same
110 // file which is likely OS related. The solution here is to
111 // compare the current stats of a file against its last stats
112 // (if any) and if it falls within a nanoseconds threshold,
113 // ignore it.
114 w.mu.Lock()
115 oldFI := w.cache[event.Path]
116 w.cache[event.Path] = &fi
117
118 // if oldFI != nil {
119 // fmt.Println("new FI", fi.ModTime().UnixNano())
120 // fmt.Println("old FI", (*oldFI).ModTime().UnixNano()+IgnoreThresholdRange)
121 // }
122
123 if oldFI != nil && fi.ModTime().UnixNano() < (*oldFI).ModTime().UnixNano()+IgnoreThresholdRange {
124 w.mu.Unlock()
125 continue
126 }
127 w.mu.Unlock()
128
129 //fmt.Println("sending Event", fi.Name())
130
131 //fmt.Println("sending fi wevent", event)
132 w.Event <- newFileEvent(event.Event, event.Path, fi.ModTime().UnixNano())
133
134 if err != nil {
135 //rename send two events,one old file,one new file,here ignore old one
136 if os.IsNotExist(err) {
137 continue
138 }
139 w.errorHandle(err)
140 continue
141 }
142 // case err := <-w.Watcher.Errors:
143 // w.errorHandle(err)
144 // case _ = <-w.quit:
145 // break
146 // }
147 }
148 }
149 func (w *Watcher) errorHandle(err error) {
150 if w.ErrorHandler == nil {
151 w.Error <- err
152 return
153 }
154 w.ErrorHandler(err)
155 }
156
157 // GetErrorChan gets error chan.
158 func (w *Watcher) GetErrorChan() chan error {
159 return w.Error
160 }
161
162 // GetEventChan gets event chan.
163 func (w *Watcher) GetEventChan() chan *FileEvent {
164 return w.Event
165 }
166
167 // WatchRecursive watches a directory recursively. If a dir is created
168 // within directory it is also watched.
169 func (w *Watcher) WatchRecursive(path string) error {
170 path, err := filepath.Abs(path)
171 if err != nil {
172 return err
173 }
174
175 _, err = os.Stat(path)
176 if err != nil {
177 return err
178 }
179
180 w.Watcher.Add(path)
181
182 //util.Debug("watcher", "watching %s %s\n", path, time.Now())
183 return nil
184 }
185
186 // Start starts the watcher
187 func (w *Watcher) Start() {
188 go w.eventLoop()
189 }
190
191 // func (w *Watcher) getSubFolders(path string) (paths []string, err error) {
192 // err = filepath.Walk(path, func(newPath string, info os.FileInfo, err error) error {
193 // if err != nil {
194 // return err
195 // }
196
197 // if !info.IsDir() {
198 // return nil
199 // }
200 // if w.IgnorePathFn(newPath) {
201 // return filepath.SkipDir
202 // }
203 // paths = append(paths, newPath)
204 // return nil
205 // })
206 // return paths, err
207 // }
208
209 // DefaultIgnorePathFn checks whether a path is ignored. Currently defaults
210 // to hidden files on *nix systems, ie they start with a ".".
211 func DefaultIgnorePathFn(path string) bool {
212 if strings.HasPrefix(path, ".") || strings.Contains(path, "/.") {
213 return true
214 }
215
216 // ignore node
217 if strings.HasPrefix(path, "node_modules") || strings.Contains(path, "/node_modules") {
218 return true
219 }
220
221 // vim creates random numeric files
222 base := filepath.Base(path)
223 if str.IsNumeric(base) {
224 return true
225 }
226 return false
227 }
228
229 // SetIgnorePathFn sets the function which determines if a path should be
230 // skipped when watching.
231 func (w *Watcher) SetIgnorePathFn(fn func(string) bool) {
232 w.Watcher.IgnorePathFn = fn
233 }