From 079deae8114abbf545323097be6e45b30f1b531b Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Tue, 25 Nov 2025 15:12:52 -0700 Subject: [PATCH] feat: Recursively watch directories and add watches for new subfolders Co-authored-by: aider (gemini/gemini-2.5-pro) --- main.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index f16220b..36f53ac 100644 --- a/main.py +++ b/main.py @@ -29,14 +29,27 @@ def trigger_scan(): logging.error(f"Failed to trigger scan: {e}") +def add_watch_recursive(inotify, path, watch_flags): + """Walk a directory path and add watches recursively.""" + try: + for root, _, _ in os.walk(path): + try: + logging.info(f"Watching {root}") + inotify.add_watch(root, watch_flags) + except OSError as e: + logging.error(f"Error adding watch for {root}: {e}") + except FileNotFoundError: + logging.warning(f"Could not scan {path} as it was not found.") + + def main(): global timer watch_flags = flags.MODIFY | flags.CREATE | flags.DELETE | flags.MOVED_FROM | flags.MOVED_TO with INotify() as inotify: for path in secrets.WATCH_PATHS: - logging.info(f"Watching {path}") - inotify.add_watch(path, watch_flags) + logging.info(f"Watching {path} and its subdirectories recursively.") + add_watch_recursive(inotify, path, watch_flags) try: while True: @@ -44,6 +57,13 @@ def main(): if events: for event in events: logging.debug(f"Event: {event!r}") + if event.mask & flags.ISDIR and (event.mask & flags.CREATE or event.mask & flags.MOVED_TO): + parent_dir_path_bytes = inotify.paths[event.wd] + new_dir_path_bytes = os.path.join(parent_dir_path_bytes, event.name) + new_dir_path = new_dir_path_bytes.decode('utf-8') + logging.info(f"New directory {new_dir_path} detected, adding watches.") + add_watch_recursive(inotify, new_dir_path, watch_flags) + if timer: timer.cancel() logging.info('Debounce cancelled timer.')