Skip to content

Commit

Permalink
port/file_watcher (#54)
Browse files Browse the repository at this point in the history
migrate FileWatcher class from ovos_config for reuse

authored-by: jarbasai <[email protected]>
  • Loading branch information
NeonJarbas authored Jul 6, 2022
1 parent 43e1ee8 commit 089669f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
42 changes: 42 additions & 0 deletions ovos_utils/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
from ovos_utils.bracket_expansion import expand_options
from ovos_utils.log import LOG
from ovos_utils.system import search_mycroft_core_location
import time
from os.path import dirname

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


def get_temp_path(*args):
Expand Down Expand Up @@ -257,3 +262,40 @@ def read_translated_file(filename, data):
return text.format(**data or {}).rstrip('\n').split('\n')
else:
return None


class FileWatcher:
def __init__(self, files, callback, recursive=False, ignore_creation=False):
self.observer = Observer()
self.handlers = []
for file_path in files:
watch_dir = dirname(file_path)
self.observer.schedule(FileEventHandler(file_path, callback, ignore_creation),
watch_dir, recursive=recursive)
self.observer.start()

def shutdown(self):
self.observer.unschedule_all()
self.observer.stop()


class FileEventHandler(FileSystemEventHandler):
def __init__(self, file_path, callback, ignore_creation=False):
super().__init__()
self._callback = callback
self._file_path = file_path
self._debounce = 1
self._last_update = 0
if ignore_creation:
self._events = ('modified')
else:
self._events = ('created', 'modified')

def on_any_event(self, event):
if event.is_directory:
return
elif event.event_type in self._events:
if event.src_path == self._file_path:
if time.time() - self._last_update >= self._debounce:
self._callback(event.src_path)
self._last_update = time.time()
1 change: 1 addition & 0 deletions requirements/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pexpect~=4.8
requests~=2.26
json_database~=0.7
kthread~=0.2
watchdog

0 comments on commit 089669f

Please sign in to comment.