-
Notifications
You must be signed in to change notification settings - Fork 27
/
fsevents.py
352 lines (301 loc) · 9.74 KB
/
fsevents.py
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import os
import sys
import threading
import unicodedata
from _fsevents import (
FS_CFLAGFILEEVENTS,
FS_CFLAGNONE,
FS_EVENTIDSINCENOW,
FS_FLAGEVENTIDSWRAPPED,
FS_FLAGHISTORYDONE,
FS_FLAGKERNELDROPPED,
FS_FLAGMOUNT,
FS_FLAGMUSTSCANSUBDIRS,
FS_FLAGROOTCHANGED,
FS_FLAGUNMOUNT,
FS_FLAGUSERDROPPED,
FS_ITEMCHANGEOWNER,
FS_ITEMCREATED,
FS_ITEMFINDERINFOMOD,
FS_ITEMINODEMETAMOD,
FS_ITEMISDIR,
FS_ITEMISFILE,
FS_ITEMISSYMLINK,
FS_ITEMMODIFIED,
FS_ITEMREMOVED,
FS_ITEMRENAMED,
FS_ITEMXATTRMOD,
loop,
schedule,
stop,
unschedule
)
class Mask(int):
stringmap = {
FS_FLAGMUSTSCANSUBDIRS: "MustScanSubDirs",
FS_FLAGUSERDROPPED: "UserDropped",
FS_FLAGKERNELDROPPED: "KernelDropped",
FS_FLAGEVENTIDSWRAPPED: "EventIDsWrapped",
FS_FLAGHISTORYDONE: "HistoryDone",
FS_FLAGROOTCHANGED: "RootChanged",
FS_FLAGMOUNT: "Mount",
FS_FLAGUNMOUNT: "Unmount",
# Flags when creating the stream.
FS_ITEMCREATED: "ItemCreated",
FS_ITEMREMOVED: "ItemRemoved",
FS_ITEMINODEMETAMOD: "ItemInodeMetaMod",
FS_ITEMRENAMED: "ItemRenamed",
FS_ITEMMODIFIED: "ItemModified",
FS_ITEMFINDERINFOMOD: "ItemFinderInfoMod",
FS_ITEMCHANGEOWNER: "ItemChangedOwner",
FS_ITEMXATTRMOD: "ItemXAttrMod",
FS_ITEMISFILE: "ItemIsFile",
FS_ITEMISDIR: "ItemIsDir",
FS_ITEMISSYMLINK: "ItemIsSymlink",
}
_svals = list(stringmap.items())
_svals.sort()
del stringmap
def __str__(self):
vals = []
for k, s in self._svals:
if self & k:
vals.append(s)
return "[" + "|".join(vals) + "]"
# inotify event flags
IN_MODIFY = 0x00000002
IN_ATTRIB = 0x00000004
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
IN_MOVED_FROM = 0x00000040
IN_MOVED_TO = 0x00000080
if sys.version_info[0] >= 3:
unicode = str
def check_path_string_type(*paths):
for path in paths:
if not isinstance(path, str):
raise TypeError(
"Path must be string, not '%s'." % type(path).__name__
)
class Observer(threading.Thread):
event = None
runloop = None
def __init__(self):
self.streams = set()
self.schedulings = {}
self.lock = threading.Lock()
threading.Thread.__init__(self)
def run(self):
# wait until we have streams registered
while not self.streams:
self.event = threading.Event()
self.event.wait()
if self.event is None:
return
self.event = None
self.lock.acquire()
try:
# schedule all streams
for stream in self.streams:
self._schedule(stream)
self.streams = None
finally:
self.lock.release()
# start run-loop
loop(self)
def _schedule(self, stream):
if not stream.paths:
raise ValueError("No paths to observe.")
if stream.file_events:
callback = FileEventCallback(stream.callback, stream.raw_paths)
else:
def callback(paths, masks, ids):
for path, mask, id in zip(paths, masks, ids):
if sys.version_info[0] >= 3:
path = path.decode("utf-8")
if stream.ids is False:
stream.callback(path, mask)
elif stream.ids is True:
stream.callback(path, mask, id)
schedule(
self,
stream,
callback,
stream.paths,
stream.since,
stream.latency,
stream.cflags,
)
def schedule(self, stream):
self.lock.acquire()
try:
if self.streams is None:
self._schedule(stream)
elif stream in self.streams:
raise ValueError("Stream already scheduled.")
else:
self.streams.add(stream)
if self.event is not None:
self.event.set()
finally:
self.lock.release()
def unschedule(self, stream):
self.lock.acquire()
try:
if self.streams is None:
unschedule(stream)
else:
self.streams.remove(stream)
finally:
self.lock.release()
def stop(self):
if self.event is None:
stop(self)
else:
event = self.event
self.event = None
event.set()
class Stream(object):
def __init__(self, callback, *paths, **options):
file_events = options.pop("file_events", False)
since = options.pop("since", FS_EVENTIDSINCENOW)
cflags = options.pop("flags", FS_CFLAGNONE)
latency = options.pop("latency", 0.01)
ids = options.pop("ids", False)
assert len(options) == 0, "Invalid option(s): %s" % repr(
options.keys()
)
check_path_string_type(*paths)
self.callback = callback
self.raw_paths = paths
# The C-extension needs the path in 8-bit form.
self.paths = [
path if isinstance(path, bytes) else path.encode("utf-8")
for path in paths
]
self.file_events = file_events
self.since = since
self.cflags = cflags
self.latency = latency
self.ids = ids
class FileEvent(object):
__slots__ = "mask", "cookie", "name"
def __init__(self, mask, cookie, name):
self.mask = mask
self.cookie = cookie
self.name = name
def __repr__(self):
return repr((self.mask, self.cookie, self.name))
class FileEventCallback(object):
def __init__(self, callback, paths):
self.snapshots = {}
for path in paths:
check_path_string_type(path)
self.snapshot(path)
self.callback = callback
self.cookie = 0
def __call__(self, paths, masks, ids):
events = []
deleted = {}
created = {}
for path in sorted(paths):
# supports UTF-8-MAC(NFD)
if not isinstance(path, unicode):
path = path.decode("utf-8")
path = unicodedata.normalize("NFD", path).encode("utf-8")
if sys.version_info[0] >= 3:
path = path.decode("utf-8")
path = path.rstrip("/")
snapshot = self.snapshots[path]
current = {}
try:
for name in os.listdir(path):
try:
current[name] = os.lstat(os.path.join(path, name))
except OSError:
pass
except OSError:
# recursive delete causes problems with path being non-existent
pass
observed = set(current)
for name, snap_stat in snapshot.items():
filename = os.path.join(path, name)
if name in observed:
stat = current[name]
if stat.st_mtime > snap_stat.st_mtime:
events.append(FileEvent(IN_MODIFY, None, filename))
elif stat.st_ctime > snap_stat.st_ctime:
events.append(FileEvent(IN_ATTRIB, None, filename))
observed.discard(name)
else:
event = created.get(snap_stat.st_ino)
if event is not None:
self.cookie += 1
event.mask = IN_MOVED_FROM
event.cookie = self.cookie
tmp_filename = event.name
event.name = filename
events.append(
FileEvent(IN_MOVED_TO, self.cookie, tmp_filename)
)
else:
event = FileEvent(IN_DELETE, None, filename)
deleted[snap_stat.st_ino] = event
events.append(event)
for name in observed:
stat = current[name]
filename = os.path.join(path, name)
event = deleted.get(stat.st_ino)
if event is not None:
self.cookie += 1
event.mask = IN_MOVED_FROM
event.cookie = self.cookie
event = FileEvent(IN_MOVED_TO, self.cookie, filename)
else:
event = FileEvent(IN_CREATE, None, filename)
created[stat.st_ino] = event
if os.path.isdir(filename):
self.snapshot(filename)
events.append(event)
snapshot.clear()
snapshot.update(current)
for event in events:
self.callback(event)
def snapshot(self, path):
path = os.path.realpath(path)
refs = self.snapshots
for root, dirs, files in os.walk(path):
refs[root] = {}
entry = refs[root]
for obj in files + dirs:
try:
entry[obj] = os.lstat(os.path.join(root, obj))
except OSError:
continue
__all__ = (
FS_CFLAGFILEEVENTS,
FS_CFLAGNONE,
FS_EVENTIDSINCENOW,
FS_FLAGEVENTIDSWRAPPED,
FS_FLAGHISTORYDONE,
FS_FLAGKERNELDROPPED,
FS_FLAGMOUNT,
FS_FLAGMUSTSCANSUBDIRS,
FS_FLAGROOTCHANGED,
FS_FLAGUNMOUNT,
FS_FLAGUSERDROPPED,
FS_ITEMCHANGEOWNER,
FS_ITEMCREATED,
FS_ITEMFINDERINFOMOD,
FS_ITEMINODEMETAMOD,
FS_ITEMISDIR,
FS_ITEMISFILE,
FS_ITEMISSYMLINK,
FS_ITEMMODIFIED,
FS_ITEMREMOVED,
FS_ITEMRENAMED,
FS_ITEMXATTRMOD,
FileEvent,
Stream,
Observer,
)