forked from fsnotify/fsnotify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fen.go
334 lines (296 loc) · 7.98 KB
/
fen.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build solaris
// +build solaris
package fsnotify
import (
"errors"
"fmt"
"golang.org/x/sys/unix"
"io/ioutil"
"os"
"path/filepath"
"sync"
)
var (
eventBits = unix.FILE_MODIFIED | unix.FILE_ATTRIB | unix.FILE_NOFOLLOW
)
// Watcher watches a set of files, delivering events to a channel.
type Watcher struct {
Events chan Event
Errors chan error
done chan struct{} // Channel for sending a "quit message" to the reader goroutine
mu sync.Mutex
port *unix.EventPort
}
// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
func NewWatcher() (*Watcher, error) {
var err error
w := new(Watcher)
w.Events = make(chan Event)
w.Errors = make(chan error)
w.port, err = unix.NewEventPort()
if err != nil {
return nil, err
}
w.done = make(chan struct{})
go w.readEvents()
return w, nil
}
// sendEvent attempts to send an event to the user, returning true if the event
// was put in the channel successfully and false if the watcher has been closed.
func (w *Watcher) sendEvent(e Event) (sent bool) {
select {
case w.Events <- e:
return true
case <-w.done:
return false
}
}
// sendError attempts to send an error to the user, returning true if the error
// was put in the channel successfully and false if the watcher has been closed.
func (w *Watcher) sendError(err error) (sent bool) {
select {
case w.Errors <- err:
return true
case <-w.done:
return false
}
}
func (w *Watcher) isClosed() bool {
select {
case <-w.done:
return true
default:
return false
}
}
// Close removes all watches and closes the events channel.
func (w *Watcher) Close() error {
if w.isClosed() {
return nil
}
close(w.done)
w.port.Close()
return nil
}
// Add starts watching the named file or directory (non-recursively).
func (w *Watcher) Add(name string) error {
if w.isClosed() {
return errors.New("FEN watcher already closed")
}
if w.port.PathIsWatched(name) {
return nil
}
stat, err := os.Stat(name)
switch {
case err != nil:
return err
case stat.IsDir():
return w.handleDirectory(name, stat, w.associateFile)
default:
return w.associateFile(name, stat)
}
}
// Remove stops watching the the named file or directory (non-recursively).
func (w *Watcher) Remove(name string) error {
if w.isClosed() {
return errors.New("FEN watcher already closed")
}
if !w.port.PathIsWatched(name) {
return fmt.Errorf("can't remove non-existent FEN watch for: %s", name)
}
stat, err := os.Stat(name)
switch {
case err != nil:
return err
case stat.IsDir():
return w.handleDirectory(name, stat, w.dissociateFile)
default:
return w.port.DissociatePath(name)
}
}
// readEvents contains the main loop that runs in a goroutine watching for events.
func (w *Watcher) readEvents() {
// If this function returns, the watcher has been closed and we can
// close these channels
defer close(w.Errors)
defer close(w.Events)
pevents := make([]unix.PortEvent, 8, 8)
for {
count, err := w.port.Get(pevents, 1, nil)
if err != nil && err != unix.ETIME {
// Interrupted system call (count should be 0) ignore and continue
if err == unix.EINTR && count == 0 {
continue
}
// Get failed because we called w.Close()
if err == unix.EBADF && w.isClosed() {
return
}
// There was an error not caused by calling w.Close()
if !w.sendError(err) {
return
}
}
p := pevents[:count]
for _, pevent := range p {
if pevent.Source != unix.PORT_SOURCE_FILE {
// Event from unexpected source received; should never happen.
if !w.sendError(errors.New("Event from unexpected source received")) {
return
}
continue
}
err = w.handleEvent(&pevent)
if err != nil {
if !w.sendError(err) {
return
}
}
}
}
}
func (w *Watcher) handleDirectory(path string, stat os.FileInfo, handler func(string, os.FileInfo) error) error {
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
// Handle all children of the directory.
for _, finfo := range files {
if !finfo.IsDir() {
err := handler(filepath.Join(path, finfo.Name()), finfo)
if err != nil {
return err
}
}
}
// And finally handle the directory itself.
return handler(path, stat)
}
// handleEvent might need to emit more than one fsnotify event
// if the events bitmap matches more than one event type
// (e.g. the file was both modified and had the
// attributes changed between when the association
// was created and the when event was returned)
func (w *Watcher) handleEvent(event *unix.PortEvent) error {
events := event.Events
path := event.Path
fmode := event.Cookie.(os.FileMode)
var toSend *Event
reRegister := true
if events&unix.FILE_DELETE == unix.FILE_DELETE {
toSend = &Event{path, Remove}
if !w.sendEvent(*toSend) {
return nil
}
reRegister = false
}
if events&unix.FILE_RENAME_FROM == unix.FILE_RENAME_FROM {
toSend = &Event{path, Rename}
if !w.sendEvent(*toSend) {
return nil
}
// Don't keep watching the new file name
reRegister = false
}
if events&unix.FILE_RENAME_TO == unix.FILE_RENAME_TO {
// We don't report a Rename event for this case, because
// Rename events are interpreted as referring to the _old_ name
// of the file, and in this case the event would refer to the
// new name of the file. This type of rename event is not
// supported by fsnotify.
// inotify reports a Remove event in this case, so we simulate
// this here.
toSend = &Event{path, Remove}
if !w.sendEvent(*toSend) {
return nil
}
// Don't keep watching the file that was removed
reRegister = false
}
// The file is gone, nothing left to do.
if !reRegister {
return nil
}
// If we didn't get a deletion the file still exists and we're going to have to watch it again.
// Let's Stat it now so that we can compare permissions and have what we need
// to continue watching the file
stat, err := os.Stat(path)
if err != nil {
return err
}
if events&unix.FILE_MODIFIED == unix.FILE_MODIFIED {
if fmode.IsDir() {
if err := w.updateDirectory(path); err != nil {
return err
}
} else {
toSend = &Event{path, Write}
if !w.sendEvent(*toSend) {
return nil
}
}
}
if events&unix.FILE_ATTRIB == unix.FILE_ATTRIB {
// Only send Chmod if perms changed
if stat.Mode().Perm() != fmode.Perm() {
toSend = &Event{path, Chmod}
if !w.sendEvent(*toSend) {
return nil
}
}
}
// If we get here, it means we've hit an event above that requires us to
// continue watching the file or directory
return w.associateFile(path, stat)
}
func (w *Watcher) updateDirectory(path string) error {
// The directory was modified, so we must find unwatched entites and
// watch them. If something was removed from the directory, nothing will
// happen, as everything else should still be watched.
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for _, finfo := range files {
path := filepath.Join(path, finfo.Name())
if w.port.PathIsWatched(path) {
continue
}
err := w.associateFile(path, finfo)
if err != nil {
if !w.sendError(err) {
return nil
}
}
if !w.sendEvent(Event{path, Create}) {
return nil
}
}
return nil
}
func (w *Watcher) associateFile(path string, stat os.FileInfo) error {
// This is primarily protecting the call to AssociatePath
// but it is important and intentional that the call to
// PathIsWatched is also protected by this mutex.
// Without this mutex, AssociatePath has been seen
// to error out that the path is already associated.
w.mu.Lock()
defer w.mu.Unlock()
if w.port.PathIsWatched(path) {
// Remove the old association in favor of this one
if err := w.port.DissociatePath(path); err != nil {
return err
}
}
fmode := stat.Mode()
return w.port.AssociatePath(path, stat, eventBits, fmode)
}
func (w *Watcher) dissociateFile(path string, stat os.FileInfo) error {
if !w.port.PathIsWatched(path) {
return nil
}
return w.port.DissociatePath(path)
}