|
| 1 | +"""Filesystem watcher that rebuilds ctxeng context on changes.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import threading |
| 6 | +import time |
| 7 | +from dataclasses import dataclass |
| 8 | +from pathlib import Path |
| 9 | +from typing import Callable |
| 10 | + |
| 11 | +from ctxeng.models import Context |
| 12 | + |
| 13 | + |
| 14 | +@dataclass(frozen=True) |
| 15 | +class WatchConfig: |
| 16 | + """Configuration for watching and rebuilding context.""" |
| 17 | + |
| 18 | + debounce_seconds: float = 0.5 |
| 19 | + interval_seconds: float = 1.0 |
| 20 | + |
| 21 | + |
| 22 | +class ContextWatcher: |
| 23 | + """ |
| 24 | + Watch a project for file changes and rebuild context automatically. |
| 25 | +
|
| 26 | + This is an optional feature that requires the ``watchdog`` dependency: |
| 27 | +
|
| 28 | + pip install "ctxeng[watch]" |
| 29 | +
|
| 30 | + Args: |
| 31 | + query: Query to build context for. |
| 32 | + engine: A configured :class:`~ctxeng.core.ContextEngine` instance. |
| 33 | + output_file: If set, write context output to this file on rebuild. |
| 34 | + callback: If set, called with the freshly built :class:`~ctxeng.models.Context`. |
| 35 | + fmt: Output format passed to ``Context.to_string()`` when writing to file. |
| 36 | + config: Watch timing configuration (debounce + polling interval). |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + query: str, |
| 42 | + *, |
| 43 | + engine, |
| 44 | + output_file: str | Path | None = None, |
| 45 | + callback: Callable[[Context], None] | None = None, |
| 46 | + fmt: str = "xml", |
| 47 | + config: WatchConfig | None = None, |
| 48 | + ) -> None: |
| 49 | + self.query = query |
| 50 | + self.engine = engine |
| 51 | + self.root = Path(engine.root).resolve() |
| 52 | + self.output_file = Path(output_file) if output_file else None |
| 53 | + self.callback = callback |
| 54 | + self.fmt = fmt |
| 55 | + self.config = config or WatchConfig() |
| 56 | + |
| 57 | + self._changed: set[Path] = set() |
| 58 | + self._lock = threading.Lock() |
| 59 | + self._timer: threading.Timer | None = None |
| 60 | + |
| 61 | + def run(self) -> None: |
| 62 | + """ |
| 63 | + Block forever, rebuilding context when files change. |
| 64 | +
|
| 65 | + Gracefully exits on Ctrl+C. |
| 66 | + """ |
| 67 | + try: |
| 68 | + from watchdog.events import FileSystemEventHandler |
| 69 | + from watchdog.observers.polling import PollingObserver |
| 70 | + except ImportError as e: # pragma: no cover |
| 71 | + raise ImportError( |
| 72 | + "watch mode requires watchdog. Install with: pip install \"ctxeng[watch]\"" |
| 73 | + ) from e |
| 74 | + |
| 75 | + watcher = self |
| 76 | + |
| 77 | + class Handler(FileSystemEventHandler): |
| 78 | + def on_any_event(self, event) -> None: # type: ignore[override] |
| 79 | + # event has .is_directory and .src_path; moved events also have .dest_path |
| 80 | + if getattr(event, "is_directory", False): |
| 81 | + return |
| 82 | + src = getattr(event, "src_path", None) |
| 83 | + if src: |
| 84 | + watcher.notify_change(Path(src)) |
| 85 | + dest = getattr(event, "dest_path", None) |
| 86 | + if dest: |
| 87 | + watcher.notify_change(Path(dest)) |
| 88 | + |
| 89 | + obs = PollingObserver(timeout=self.config.interval_seconds) |
| 90 | + obs.schedule(Handler(), str(self.root), recursive=True) |
| 91 | + obs.start() |
| 92 | + |
| 93 | + try: |
| 94 | + while True: |
| 95 | + time.sleep(0.2) |
| 96 | + except KeyboardInterrupt: |
| 97 | + pass |
| 98 | + finally: |
| 99 | + obs.stop() |
| 100 | + obs.join(timeout=5) |
| 101 | + |
| 102 | + def notify_change(self, abs_path: Path) -> None: |
| 103 | + """Record a changed path and schedule a debounced rebuild.""" |
| 104 | + rel = self._to_rel(abs_path) |
| 105 | + ts = self._timestamp() |
| 106 | + print(f"[{ts}] File changed: {rel.as_posix()}") |
| 107 | + with self._lock: |
| 108 | + self._changed.add(rel) |
| 109 | + if self._timer is not None: |
| 110 | + self._timer.cancel() |
| 111 | + self._timer = threading.Timer(self.config.debounce_seconds, self._rebuild) |
| 112 | + self._timer.daemon = True |
| 113 | + self._timer.start() |
| 114 | + |
| 115 | + def _rebuild(self) -> None: |
| 116 | + changed: list[Path] |
| 117 | + with self._lock: |
| 118 | + changed = sorted(self._changed) |
| 119 | + self._changed.clear() |
| 120 | + self._timer = None |
| 121 | + |
| 122 | + ts = self._timestamp() |
| 123 | + print(f"[{ts}] Rebuilding context...") |
| 124 | + ctx = self.engine.build(self.query, fmt=self.fmt) |
| 125 | + |
| 126 | + done_ts = self._timestamp() |
| 127 | + cost = f", ~${ctx.cost_estimate:.3f}" if ctx.cost_estimate is not None else "" |
| 128 | + print(f"[{done_ts}] Done. {len(ctx.files)} files, {ctx.total_tokens:,} tokens{cost}") |
| 129 | + |
| 130 | + if self.output_file: |
| 131 | + out = self.output_file |
| 132 | + out.write_text(ctx.to_string(self.fmt), encoding="utf-8") |
| 133 | + print(f"[{self._timestamp()}] Written to: {out}") |
| 134 | + |
| 135 | + if self.callback: |
| 136 | + self.callback(ctx) |
| 137 | + |
| 138 | + # changed is currently only printed as individual lines on notify; keep for future hooks |
| 139 | + _ = changed |
| 140 | + |
| 141 | + def _to_rel(self, abs_path: Path) -> Path: |
| 142 | + try: |
| 143 | + return abs_path.resolve().relative_to(self.root) |
| 144 | + except Exception: |
| 145 | + return abs_path |
| 146 | + |
| 147 | + @staticmethod |
| 148 | + def _timestamp() -> str: |
| 149 | + return time.strftime("%H:%M:%S", time.localtime()) |
| 150 | + |
0 commit comments