baseimage-tutorial-framework/lib/tfw/components/directory_monitor.py

79 lines
2.2 KiB
Python

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler as FileSystemWatchdogEventHandler
from functools import wraps
from tfw.networking.event_handlers.server_connector import ServerUplinkConnector
from tfw.components.decorators import RateLimiter
from tfw.config.logs import logging
log = logging.getLogger(__name__)
class DirectoryMonitor:
def __init__(self, directory):
self.observer = Observer()
self.eventhandler = WebideReloadWatchdogEventHandler()
self.observer.schedule(self.eventhandler, directory, recursive=True)
self.pause, self.resume = self.eventhandler.pause, self.eventhandler.resume
def watch(self):
self.observer.start()
def stop(self):
self.observer.stop()
self.observer.join()
@property
def ignore(self):
return self.eventhandler.ignore
@ignore.setter
def ignore(self, value):
self.eventhandler.ignore = value if value >= 0 else 0
@property
def pauser(self):
return DirectoryMonitor.Pauser(self)
class Pauser:
def __init__(self, directory_monitor):
self.directorymonitor = directory_monitor
def __enter__(self):
self.directorymonitor.pause()
def __exit__(self, exc_type, exc_val, exc_tb):
self.directorymonitor.resume()
class WebideReloadWatchdogEventHandler(FileSystemWatchdogEventHandler):
def __init__(self):
super().__init__()
self.uplink = ServerUplinkConnector()
self._paused = False
self.ignore = 0
def pause(self):
self._paused = True
def resume(self):
self._paused = False
@RateLimiter(rate_per_second=2)
def on_modified(self, event):
if self._paused: return
if self.ignore > 0:
self.ignore = self.ignore - 1
return
log.debug(event)
key = 'webide'
self.uplink.send(key, {'data': {'command': 'reload'}})
def with_monitor_paused(fun):
@wraps(fun)
def wrapper(self, *args, **kwargs):
if self.monitor:
with self.monitor.pauser:
return fun(self, *args, **kwargs)
return fun(self, *args, **kwargs)
return wrapper