Refactor HistoryMonitor to be customisable

This commit is contained in:
Kristóf Tóth 2018-03-29 11:23:38 +02:00
parent e832059526
commit c973b17141
2 changed files with 28 additions and 5 deletions

View File

@ -1,22 +1,26 @@
from os.path import dirname
from re import compile, findall
from abc import ABC, abstractmethod
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from tfw.components.mixins.callback_mixin import CallbackMixin
from tfw.components.decorators.rate_limiter import RateLimiter
class CallbackEventHandler(PatternMatchingEventHandler):
class CallbackEventHandler(PatternMatchingEventHandler, ABC):
def __init__(self, files, *callbacks):
super().__init__(files)
self.callbacks = callbacks
@RateLimiter(rate_per_second=2)
def on_modified(self, event):
for callback in self.callbacks:
callback()
class HistoryMonitor(CallbackMixin):
class HistoryMonitor(CallbackMixin, ABC):
def __init__(self, histfile):
CallbackMixin.__init__(self)
self.histfile = histfile
@ -35,7 +39,17 @@ class HistoryMonitor(CallbackMixin):
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()]
pattern = compile(self.command_pattern)
data = ifile.read()
self._history = [self.sanitize_command(command) for command in findall(pattern, data)]
@property
@abstractmethod
def command_pattern(self):
raise NotImplementedError
def sanitize_command(self, command):
return command
def _invoke_callbacks(self):
if self._last_length < len(self._history):
@ -47,3 +61,12 @@ class HistoryMonitor(CallbackMixin):
def stop(self):
self.observer.stop()
self.observer.join()
class BashMonitor(HistoryMonitor):
@property
def command_pattern(self):
return r'.+'
def sanitize_command(self, command):
return command.strip()

View File

@ -1,5 +1,5 @@
from tfw.components.terminado_mini_server import TerminadoMiniServer
from tfw.components.history_monitor import HistoryMonitor
from tfw.components.history_monitor import BashMonitor
from tfw.event_handler_base import TriggerlessEventHandler
from tfw.config import TFWENV
from tfw.config.logs import logging
@ -11,7 +11,7 @@ class TerminadoEventHandler(TriggerlessEventHandler):
def __init__(self, key):
super().__init__(key)
self.working_directory = TFWENV.TERMINADO_DIR
self._historymonitor = HistoryMonitor(TFWENV.HISTFILE)
self._historymonitor = BashMonitor(TFWENV.HISTFILE)
self.terminado_server = TerminadoMiniServer('/terminal', TFWENV.TERMINADO_PORT, TFWENV.TERMINADO_WD, ['bash'])
self.commands = {'write': self.write,
'read': self.read}