mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-09 02:07:17 +00:00
49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
from watchdog.observers import Observer
|
|
from watchdog.events import PatternMatchingEventHandler
|
|
from os.path import dirname
|
|
|
|
from tfw.components.mixins.callback_mixin import CallbackMixin
|
|
|
|
|
|
class CallbackEventHandler(PatternMatchingEventHandler):
|
|
def __init__(self, files, *callbacks):
|
|
super().__init__(files)
|
|
self.callbacks = callbacks
|
|
|
|
def on_modified(self, event):
|
|
for callback in self.callbacks:
|
|
callback()
|
|
|
|
|
|
class HistoryMonitor(CallbackMixin):
|
|
def __init__(self, histfile):
|
|
CallbackMixin.__init__(self)
|
|
self.histfile = histfile
|
|
self._history = []
|
|
self._last_length = len(self._history)
|
|
self.observer = Observer()
|
|
self.observer.schedule(CallbackEventHandler([self.histfile],
|
|
self._fetch_history,
|
|
self._invoke_callbacks),
|
|
dirname(self.histfile))
|
|
|
|
@property
|
|
def history(self):
|
|
return self._history
|
|
|
|
def _fetch_history(self):
|
|
self._last_length = len(self._history)
|
|
with open(self.histfile, 'r') as ifile:
|
|
self._history = [line.rstrip() for line in ifile.readlines()]
|
|
|
|
def _invoke_callbacks(self):
|
|
if self._last_length < len(self._history):
|
|
self._execute_callbacks(self.history)
|
|
|
|
def watch(self):
|
|
self.observer.start()
|
|
|
|
def stop(self):
|
|
self.observer.stop()
|
|
self.observer.join()
|