Skip to content

Commit 783ab57

Browse files
committed
Feat: Use watchdog instead of inotify
`watchdog` is much more portable. Fixes: #46.
1 parent 7f99bcd commit 783ab57

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

native/textern.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,8 @@
1515
import time
1616
import urllib.parse
1717

18-
try:
19-
from inotify_simple import INotify, flags
20-
except ImportError:
21-
# fall-back to the old import pattern for git-submodule use-case (PR#57)
22-
from inotify_simple.inotify_simple import INotify, flags
23-
18+
from watchdog.events import FileSystemEventHandler
19+
from watchdog.observers import Observer
2420

2521
BACKUP_RETENTION_SECS = 24 * 60 * 60
2622

@@ -97,14 +93,28 @@ def get(self, relfn):
9793
return f.read(), self._tmpfiles[relfn]
9894

9995

96+
class CloseEventHandler(FileSystemEventHandler):
97+
def __init__(self, tmp_mgr):
98+
super(CloseEventHandler, self).__init__()
99+
self.tmp_mgr = tmp_mgr
100+
101+
def on_closed(self, event):
102+
super(CloseEventHandler, self).on_closed(event)
103+
handle_close_event(os.path.basename(event.src_path), self.tmp_mgr)
104+
105+
100106
def main():
101-
with INotify() as ino, TmpManager() as tmp_mgr:
102-
ino.add_watch(tmp_mgr.tmpdir, flags.CLOSE_WRITE)
107+
with TmpManager() as tmp_mgr:
108+
event_handler = CloseEventHandler(tmp_mgr)
109+
observer = Observer()
110+
observer.schedule(event_handler, tmp_mgr.tmpdir)
111+
observer.start()
103112
loop = asyncio.get_event_loop()
104113
loop.add_reader(sys.stdin.buffer, handle_stdin, tmp_mgr)
105-
loop.add_reader(ino.fd, handle_inotify_event, ino, tmp_mgr)
106114
loop.run_forever()
107115
loop.close()
116+
observer.stop()
117+
observer.join()
108118

109119

110120
def handle_stdin(tmp_mgr):
@@ -201,15 +211,14 @@ async def handle_message_new_text(tmp_mgr, msg):
201211
}
202212

203213

204-
def handle_inotify_event(ino, tmp_mgr):
205-
for event in ino.read():
206-
# this check is relevant in the case where we're handling the inotify
207-
# event caused by tmp_mgr.new(), but then an exception occurred in
208-
# handle_message() which caused the tmpfile to already be deleted
209-
if event.name in tmp_mgr:
210-
text, id = tmp_mgr.get(event.name)
211-
send_text_update(id, text)
212-
tmp_mgr.backup(event.name)
214+
def handle_close_event(relfn, tmp_mgr):
215+
# this check is relevant in the case where we're handling the inotify
216+
# event caused by tmp_mgr.new(), but then an exception occurred in
217+
# handle_message() which caused the tmpfile to already be deleted
218+
if relfn in tmp_mgr:
219+
text, id = tmp_mgr.get(relfn)
220+
send_text_update(id, text)
221+
tmp_mgr.backup(relfn)
213222

214223

215224
def send_text_update(id, text):

0 commit comments

Comments
 (0)