#!/usr/bin/env python3 """ Watch script for Puercito Fiction site. Monitors markdown files in content/ directory and automatically rebuilds when changes are detected. """ import sys import time from pathlib import Path from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # Add parent directory to path so we can import build script sys.path.insert(0, str(Path(__file__).parent)) from build import convert_markdown_to_html, PAGE_COLORS class MarkdownChangeHandler(FileSystemEventHandler): """Handler for markdown file changes.""" def __init__(self, content_dir: Path, site_dir: Path): self.content_dir = content_dir self.site_dir = site_dir self.last_modified = {} def on_modified(self, event): """Called when a file is modified.""" if event.is_directory: return file_path = Path(event.src_path) # Only process .md files if file_path.suffix != '.md': return # Debounce: ignore if file was modified less than 0.5 seconds ago current_time = time.time() if file_path in self.last_modified: if current_time - self.last_modified[file_path] < 0.5: return self.last_modified[file_path] = current_time print(f"\nšŸ“ Change detected: {file_path.name}") self._rebuild_file(file_path) def on_created(self, event): """Called when a file is created.""" if event.is_directory: return file_path = Path(event.src_path) # Only process .md files if file_path.suffix != '.md': return print(f"\n✨ New file created: {file_path.name}") self._rebuild_file(file_path) def _rebuild_file(self, markdown_file: Path): """Rebuild a single markdown file.""" try: convert_markdown_to_html(markdown_file, self.site_dir) print(f"āœ… Build successful at {time.strftime('%H:%M:%S')}") except Exception as e: print(f"āŒ Build failed: {e}") def main(): """Main watch script.""" # Define directories script_dir = Path(__file__).parent project_dir = script_dir.parent content_dir = project_dir / 'content' site_dir = project_dir / 'site' # Ensure directories exist if not content_dir.exists(): print(f"āŒ Error: {content_dir} directory not found") return if not site_dir.exists(): print(f"Creating {site_dir} directory...") site_dir.mkdir(parents=True) # Initial build print("šŸ—ļø Running initial build...") print("-" * 50) md_files = list(content_dir.glob('*.md')) for md_file in md_files: convert_markdown_to_html(md_file, site_dir) print("-" * 50) print(f"āœ… Initial build complete! Built {len(md_files)} file(s)\n") # Setup file watcher event_handler = MarkdownChangeHandler(content_dir, site_dir) observer = Observer() observer.schedule(event_handler, str(content_dir), recursive=False) observer.start() print("šŸ‘€ Watching for changes in content/ directory...") print(" Press Ctrl+C to stop\n") try: while True: time.sleep(1) except KeyboardInterrupt: print("\n\nšŸ‘‹ Stopping watch script...") observer.stop() observer.join() print("āœ… Watch script stopped") if __name__ == '__main__': main()