import subprocess from pathlib import Path from afk_developer.scheduler.tools.codebase import grep_codebase def _make_rg_missing(monkeypatch) -> None: """Simulate the 'rg' binary not being installed, regardless of the host machine.""" def _raise_not_found(*_args, **_kwargs): raise FileNotFoundError("rg not found") monkeypatch.setattr(subprocess, "run", _raise_not_found) def test_grep_codebase_falls_back_to_pure_python_search_when_rg_is_missing( tmp_path: Path, monkeypatch ) -> None: _make_rg_missing(monkeypatch) (tmp_path / "app.py").write_text("def handler():\n return call_mixer()\n", encoding="utf-8") (tmp_path / "other.py").write_text("value = 1\n", encoding="utf-8") result = grep_codebase("call_mixer", str(tmp_path)) assert "app.py:2: return call_mixer()" in result assert "other.py" not in result def test_grep_codebase_fallback_respects_include_glob_and_skips_cache_and_binary_files( tmp_path: Path, monkeypatch ) -> None: _make_rg_missing(monkeypatch) (tmp_path / "src").mkdir() (tmp_path / "src" / "main.py").write_text("needle_pattern = 1\n", encoding="utf-8") (tmp_path / "notes.txt").write_text("needle_pattern mentioned in notes\n", encoding="utf-8") cache_dir = tmp_path / "__pycache__" cache_dir.mkdir() (cache_dir / "main.py").write_text("needle_pattern = 1\n", encoding="utf-8") (tmp_path / "asset.png").write_bytes(b"needle_pattern") result = grep_codebase("needle_pattern", str(tmp_path), include="*.py") assert "src/main.py:1:needle_pattern = 1" in result assert "__pycache__" not in result assert "notes.txt" not in result assert "asset.png" not in result def test_grep_codebase_fallback_reports_invalid_regex_as_an_error_not_a_crash( tmp_path: Path, monkeypatch ) -> None: _make_rg_missing(monkeypatch) (tmp_path / "app.py").write_text("value = 1\n", encoding="utf-8") result = grep_codebase("(unclosed", str(tmp_path)) assert "Error:" in result def test_grep_codebase_fallback_reports_no_matches_like_the_rg_path_does( tmp_path: Path, monkeypatch ) -> None: _make_rg_missing(monkeypatch) (tmp_path / "app.py").write_text("value = 1\n", encoding="utf-8") result = grep_codebase("nothing_matches_this", str(tmp_path)) assert result == "No matches for: nothing_matches_this"