2018-03-03 16:15:21 +00:00
|
|
|
from watchdog.observers import Observer
|
|
|
|
from watchdog.events import FileSystemEventHandler
|
|
|
|
from os.path import dirname
|
|
|
|
|
|
|
|
|
|
|
|
class CallbackEventHandler(FileSystemEventHandler):
|
|
|
|
def __init__(self, *callbacks):
|
|
|
|
super().__init__()
|
|
|
|
self.callbacks = callbacks
|
|
|
|
|
|
|
|
def on_modified(self, event):
|
|
|
|
for callback in self.callbacks:
|
|
|
|
callback()
|
|
|
|
|
|
|
|
|
|
|
|
class HistoryMonitor:
|
|
|
|
def __init__(self, histfile):
|
|
|
|
self.histfile = histfile
|
2018-03-03 21:44:05 +00:00
|
|
|
self._history = []
|
2018-03-05 15:23:01 +00:00
|
|
|
self._last_length = len(self._history)
|
|
|
|
self._callbacks = []
|
2018-03-03 16:15:21 +00:00
|
|
|
self.observer = Observer()
|
2018-03-05 15:23:01 +00:00
|
|
|
self.observer.schedule(CallbackEventHandler(self._fetch_history,
|
|
|
|
self._invoke_callbacks),
|
|
|
|
dirname(self.histfile))
|
2018-03-03 16:15:21 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def history(self):
|
|
|
|
return self._history
|
|
|
|
|
2018-03-05 15:23:01 +00:00
|
|
|
@property
|
|
|
|
def callbacks(self):
|
|
|
|
return self._callbacks
|
|
|
|
|
2018-03-03 16:15:21 +00:00
|
|
|
def _fetch_history(self):
|
2018-03-05 15:23:01 +00:00
|
|
|
self._last_length = len(self._history)
|
2018-03-03 16:15:21 +00:00
|
|
|
with open(self.histfile, 'r') as ifile:
|
2018-03-03 22:02:19 +00:00
|
|
|
self._history = [line.rstrip() for line in ifile.readlines()]
|
2018-03-03 16:15:21 +00:00
|
|
|
|
2018-03-05 15:23:01 +00:00
|
|
|
def _invoke_callbacks(self):
|
|
|
|
if self._last_length < len(self._history):
|
|
|
|
for callback in self.callbacks:
|
|
|
|
callback(self.history)
|
|
|
|
|
2018-03-03 16:15:21 +00:00
|
|
|
def watch(self):
|
|
|
|
self.observer.start()
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
self.observer.stop()
|
|
|
|
self.observer.join()
|