prefs: apply flake8 suggestions
[git-cola.git] / cola / inotify.py
blobba5745b958764f4d724322fde3ceeeeb65ae850b
1 from __future__ import absolute_import, division, unicode_literals
3 import ctypes
4 import ctypes.util
5 import errno
6 import os
8 # constant from Linux include/uapi/linux/limits.h
9 NAME_MAX = 255
11 # constants from Linux include/uapi/linux/inotify.h
12 IN_MODIFY = 0x00000002
13 IN_ATTRIB = 0x00000004
14 IN_CLOSE_WRITE = 0x00000008
15 IN_MOVED_FROM = 0x00000040
16 IN_MOVED_TO = 0x00000080
17 IN_CREATE = 0x00000100
18 IN_DELETE = 0x00000200
20 IN_Q_OVERFLOW = 0x00004000
22 IN_ONLYDIR = 0x01000000
23 IN_EXCL_UNLINK = 0x04000000
24 IN_ISDIR = 0x80000000
27 class inotify_event(ctypes.Structure):
28 _fields_ = [
29 ('wd', ctypes.c_int),
30 ('mask', ctypes.c_uint32),
31 ('cookie', ctypes.c_uint32),
32 ('len', ctypes.c_uint32),
35 MAX_EVENT_SIZE = ctypes.sizeof(inotify_event) + NAME_MAX + 1
38 def _errcheck(result, func, arguments):
39 if result >= 0:
40 return result
41 err = ctypes.get_errno()
42 if err == errno.EINTR:
43 return func(*arguments)
44 raise OSError(err, os.strerror(err))
47 try:
48 _libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
49 _read = _libc.read
50 init = _libc.inotify_init
51 add_watch = _libc.inotify_add_watch
52 rm_watch = _libc.inotify_rm_watch
53 except AttributeError:
54 raise ImportError('Could not load inotify functions from libc')
57 _read.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t]
58 _read.errcheck = _errcheck
60 init.argtypes = []
61 init.errcheck = _errcheck
63 add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
64 add_watch.errcheck = _errcheck
66 rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
67 rm_watch.errcheck = _errcheck
70 def read_events(inotify_fd, count=64):
71 buf = ctypes.create_string_buffer(MAX_EVENT_SIZE * count)
72 n = _read(inotify_fd, buf, ctypes.sizeof(buf))
74 addr = ctypes.addressof(buf)
75 while n:
76 assert n >= ctypes.sizeof(inotify_event)
77 event = inotify_event.from_address(addr)
78 addr += ctypes.sizeof(inotify_event)
79 n -= ctypes.sizeof(inotify_event)
80 if event.len:
81 assert n >= event.len
82 name = ctypes.string_at(addr)
83 addr += event.len
84 n -= event.len
85 else:
86 name = None
87 yield event.wd, event.mask, event.cookie, name