-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathobserver.py
More file actions
60 lines (46 loc) · 1.74 KB
/
observer.py
File metadata and controls
60 lines (46 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""File system observer.
Monitors source files and executes a callback function when any of them changes.
To be used with the --watch option.
"""
import logging
import time
from os import path
from typing import Callable, TypeAlias
from watchdog.events import DirModifiedEvent, FileModifiedEvent, FileSystemEventHandler
from watchdog.observers import Observer
POLL_TIME = 1
DEBOUNCE_TIME = 3
logger = logging.getLogger("Watch")
_most_recent_calls: dict[str, float] = {}
CallbackFunction: TypeAlias = Callable[[], None]
class _EventHandler(FileSystemEventHandler):
callback: CallbackFunction
extension: str
def __init__(self, extension: str, callback: CallbackFunction):
super().__init__()
self.callback = callback
self.extension = extension
def on_modified(self, event: FileModifiedEvent | DirModifiedEvent) -> None:
if event.event_type == "modified" and not event.is_directory:
_, ext = path.splitext(str(event.src_path))
if ext == self.extension and not _debounced(str(event.src_path)):
self.callback()
def _debounced(name: str) -> bool:
now = time.time()
if name in _most_recent_calls and now - _most_recent_calls[name] < DEBOUNCE_TIME:
return True
_most_recent_calls[name] = now
return False
def run_file_observer(dir: str, extension: str, callback: CallbackFunction) -> None:
observer = Observer()
observer.schedule(_EventHandler(extension, callback), dir, recursive=True)
observer.start()
logger.info("Waiting for changes in %s, CTRL+C to exit", dir)
try:
while observer.is_alive():
observer.join(POLL_TIME)
except KeyboardInterrupt:
pass
finally:
observer.stop()
observer.join()