catchdev 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
catchdev/mapper.py ADDED
@@ -0,0 +1,328 @@
1
+ """Map changed source files to the tests they can break.
2
+
3
+ Builds an AST import graph of the whole project (cached in
4
+ .catch_cache.json — only files whose mtime/size changed are re-parsed),
5
+ then walks the *reverse* graph from each changed file until it reaches
6
+ test files. When possible it narrows the result to the specific test
7
+ functions that reference the functions your diff touched.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import fnmatch
13
+ import json
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from .differ import DiffResult
18
+
19
+ CACHE_NAME = ".catch_cache.json"
20
+ _IGNORE_DIRS = {
21
+ ".git", ".hg", ".svn", "__pycache__", ".venv", "venv", "env",
22
+ "node_modules", ".mypy_cache", ".pytest_cache", ".tox", ".idea",
23
+ "dist", "build", ".eggs",
24
+ }
25
+ _CACHE_VERSION = 3
26
+
27
+
28
+ @dataclass
29
+ class AffectedTests:
30
+ test_files: list[str] = field(default_factory=list) # ["tests/test_auth.py"]
31
+ test_functions: list[str] = field(default_factory=list) # ["tests/test_auth.py::test_x"]
32
+ confidence: str = "low" # "high" | "medium" | "low"
33
+ # test_file -> human-readable reasons it is affected
34
+ reasons: dict[str, list[str]] = field(default_factory=dict)
35
+
36
+
37
+ def is_test_file(path: str) -> bool:
38
+ name = Path(path).name
39
+ if fnmatch.fnmatch(name, "test_*.py") or fnmatch.fnmatch(name, "*_test.py"):
40
+ return True
41
+ return Path(path).parent.name in ("tests", "test") and name.endswith(".py")
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # import graph (with caching)
46
+ # ---------------------------------------------------------------------------
47
+
48
+ def _discover_python_files(root: Path) -> list[str]:
49
+ out: list[str] = []
50
+ for p in sorted(root.rglob("*.py")):
51
+ rel = p.relative_to(root)
52
+ if any(part in _IGNORE_DIRS or part.startswith(".") for part in rel.parts):
53
+ continue
54
+ out.append(str(rel))
55
+ return out
56
+
57
+
58
+ def _module_names(rel_path: str) -> list[str]:
59
+ """Candidate dotted module names for a file (handles src-layout)."""
60
+ parts = rel_path[:-3].split("/") # strip .py
61
+ if parts[-1] == "__init__":
62
+ parts = parts[:-1]
63
+ if not parts:
64
+ return []
65
+ names = [".".join(parts)]
66
+ if parts[0] in ("src", "lib") and len(parts) > 1:
67
+ names.append(".".join(parts[1:]))
68
+ return names
69
+
70
+
71
+ def _raw_imports(path: Path, rel_path: str) -> list[str]:
72
+ """Dotted module names this file imports (unresolved), including
73
+ relative imports resolved against the file's own package path."""
74
+ try:
75
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
76
+ except (SyntaxError, ValueError):
77
+ return []
78
+ # package context for resolving `from . import x` / `from .mod import x`
79
+ parts = rel_path[:-3].split("/")
80
+ if parts[-1] == "__init__":
81
+ parts = parts[:-1]
82
+ pkg = parts
83
+ else:
84
+ pkg = parts[:-1]
85
+ mods: list[str] = []
86
+ for node in ast.walk(tree):
87
+ if isinstance(node, ast.Import):
88
+ mods.extend(a.name for a in node.names)
89
+ elif isinstance(node, ast.ImportFrom):
90
+ if node.level == 0 and node.module:
91
+ base = node.module
92
+ elif node.level > 0 and node.level <= len(pkg):
93
+ anchor = ".".join(pkg[: len(pkg) - node.level + 1])
94
+ base = f"{anchor}.{node.module}" if node.module else anchor
95
+ else:
96
+ continue
97
+ if not base:
98
+ continue
99
+ mods.append(base)
100
+ for a in node.names: # `from pkg import mod` may import a module
101
+ mods.append(f"{base}.{a.name}")
102
+ return mods
103
+
104
+
105
+ def build_import_graph(root: str = ".") -> dict[str, set[str]]:
106
+ """Return {file: {internal files it imports}}, using the disk cache."""
107
+ root_path = Path(root).resolve()
108
+ cache_file = root_path / CACHE_NAME
109
+ cache: dict = {"version": _CACHE_VERSION, "entries": {}}
110
+ if cache_file.exists():
111
+ try:
112
+ loaded = json.loads(cache_file.read_text())
113
+ if loaded.get("version") == _CACHE_VERSION:
114
+ cache = loaded
115
+ except (json.JSONDecodeError, OSError):
116
+ pass
117
+
118
+ files = _discover_python_files(root_path)
119
+ entries: dict[str, dict] = cache.get("entries", {})
120
+ new_entries: dict[str, dict] = {}
121
+
122
+ # module index for resolution
123
+ index: dict[str, str] = {}
124
+ for rel in files:
125
+ for mod in _module_names(rel):
126
+ index.setdefault(mod, rel)
127
+
128
+ file_set = set(files)
129
+ for rel in files:
130
+ p = root_path / rel
131
+ try:
132
+ stat = p.stat()
133
+ except OSError:
134
+ continue
135
+ old = entries.get(rel)
136
+ if old and old.get("mtime") == stat.st_mtime and old.get("size") == stat.st_size:
137
+ new_entries[rel] = old
138
+ else:
139
+ new_entries[rel] = {
140
+ "mtime": stat.st_mtime,
141
+ "size": stat.st_size,
142
+ "imports": _raw_imports(p, rel),
143
+ }
144
+
145
+ graph: dict[str, set[str]] = {}
146
+ for rel, entry in new_entries.items():
147
+ resolved: set[str] = set()
148
+ for mod in entry["imports"]:
149
+ target = index.get(mod)
150
+ if target and target != rel and target in file_set:
151
+ resolved.add(target)
152
+ graph[rel] = resolved
153
+
154
+ try:
155
+ cache_file.write_text(json.dumps(
156
+ {"version": _CACHE_VERSION, "entries": new_entries}
157
+ ))
158
+ except OSError:
159
+ pass
160
+ return graph
161
+
162
+
163
+ # ---------------------------------------------------------------------------
164
+ # function-level precision
165
+ # ---------------------------------------------------------------------------
166
+
167
+ def _changed_function_names(path: Path, changed_lines: list[int]) -> list[str]:
168
+ """Names of functions whose body intersects the changed line numbers."""
169
+ if not changed_lines or not path.exists():
170
+ return []
171
+ try:
172
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
173
+ except (SyntaxError, ValueError):
174
+ return []
175
+ changed = set(changed_lines)
176
+ names: list[str] = []
177
+ for node in ast.walk(tree):
178
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
179
+ end = node.end_lineno or node.lineno
180
+ if any(node.lineno <= ln <= end for ln in changed):
181
+ names.append(node.name)
182
+ return names
183
+
184
+
185
+ def _test_functions_referencing(path: Path, names: set[str]) -> list[str]:
186
+ """Test functions in a file that reference any of the given names."""
187
+ if not names or not path.exists():
188
+ return []
189
+ try:
190
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
191
+ except (SyntaxError, ValueError):
192
+ return []
193
+ hits: list[str] = []
194
+ for node in tree.body if hasattr(tree, "body") else []:
195
+ targets = []
196
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
197
+ targets = [(node, "")]
198
+ elif isinstance(node, ast.ClassDef): # test classes
199
+ targets = [(n, f"{node.name}::") for n in node.body
200
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
201
+ for fn, prefix in targets:
202
+ if not fn.name.startswith("test"):
203
+ continue
204
+ for sub in ast.walk(fn):
205
+ if isinstance(sub, ast.Name) and sub.id in names:
206
+ hits.append(prefix + fn.name)
207
+ break
208
+ if isinstance(sub, ast.Attribute) and sub.attr in names:
209
+ hits.append(prefix + fn.name)
210
+ break
211
+ return hits
212
+
213
+
214
+ # ---------------------------------------------------------------------------
215
+ # main entry
216
+ # ---------------------------------------------------------------------------
217
+
218
+ def find_affected_tests(diff: DiffResult, root: str = ".") -> AffectedTests:
219
+ root_path = Path(root).resolve()
220
+ result = AffectedTests()
221
+
222
+ py_changes = [f for f in diff.files if f.is_python and not f.is_deleted]
223
+ deleted = [f for f in diff.files if f.is_python and f.is_deleted]
224
+ if not py_changes and not deleted:
225
+ return result
226
+
227
+ graph = build_import_graph(root)
228
+ reverse: dict[str, set[str]] = {}
229
+ for src, targets in graph.items():
230
+ for t in targets:
231
+ reverse.setdefault(t, set()).add(src)
232
+
233
+ affected: dict[str, list[str]] = {} # test file -> reasons
234
+ symbol_sources: dict[str, set[str]] = {} # test file -> changed symbols
235
+ changed_test_funcs: list[str] = [] # test functions that were edited directly
236
+
237
+ def note(test_file: str, reason: str, symbols: list[str]):
238
+ affected.setdefault(test_file, [])
239
+ if reason not in affected[test_file]:
240
+ affected[test_file].append(reason)
241
+ symbol_sources.setdefault(test_file, set()).update(symbols)
242
+
243
+ # BFS on the reverse import graph from every changed file
244
+ for cf in py_changes:
245
+ path = cf.path
246
+ symbols = _changed_function_names(root_path / path, cf.changed_lines)
247
+ sym_desc = f":{', '.join(symbols)}()" if symbols else ""
248
+ if is_test_file(path):
249
+ note(path, f"test file itself changed{sym_desc}", symbols)
250
+ # run the edited test functions directly, not the whole file
251
+ for fn in symbols:
252
+ if fn.startswith("test"):
253
+ changed_test_funcs.append(f"{path}::{fn}")
254
+ continue
255
+ if path not in graph and not cf.is_new_file:
256
+ # file isn't in the graph (unparseable / moved) — be conservative
257
+ continue
258
+ visited = {path}
259
+ # parent maps node -> the node that imported it (for chain display)
260
+ queue = [(path, [path])]
261
+ while queue:
262
+ node, chain = queue.pop(0)
263
+ for importer in reverse.get(node, ()):
264
+ if importer in visited:
265
+ continue
266
+ visited.add(importer)
267
+ new_chain = chain + [importer]
268
+ if is_test_file(importer):
269
+ if len(new_chain) > 2:
270
+ via = " → ".join(new_chain[1:-1])
271
+ reason = f"diff touches {path}{sym_desc} (via {via})"
272
+ else:
273
+ reason = f"diff touches {path}{sym_desc}"
274
+ note(importer, reason, symbols)
275
+ else:
276
+ queue.append((importer, new_chain))
277
+
278
+ # deleted files: any test still importing them will break
279
+ for cf in deleted:
280
+ mod_names = set(_module_names(cf.path))
281
+ for rel, entry_imports in _all_raw_imports(root_path).items():
282
+ if mod_names & set(entry_imports) and is_test_file(rel):
283
+ note(rel, f"imports deleted file {cf.path}", [])
284
+
285
+ if not affected:
286
+ return result
287
+
288
+ # function-level precision: which test functions call the changed symbols?
289
+ changed_test_funcs_set = set(changed_test_funcs)
290
+ test_functions: list[str] = []
291
+ file_level: list[str] = []
292
+ for test_file in sorted(affected):
293
+ direct = sorted(f for f in changed_test_funcs_set
294
+ if f.split("::")[0] == test_file)
295
+ if direct:
296
+ test_functions.extend(direct)
297
+ continue
298
+ funcs = _test_functions_referencing(root_path / test_file,
299
+ symbol_sources.get(test_file, set()))
300
+ if funcs:
301
+ test_functions.extend(f"{test_file}::{f}" for f in sorted(set(funcs)))
302
+ else:
303
+ file_level.append(test_file)
304
+
305
+ result.test_files = sorted(affected)
306
+ result.test_functions = sorted(set(test_functions))
307
+ result.reasons = affected
308
+ if test_functions and not file_level:
309
+ result.confidence = "high"
310
+ elif test_functions:
311
+ result.confidence = "medium"
312
+ else:
313
+ result.confidence = "medium"
314
+ return result
315
+
316
+
317
+ def _all_raw_imports(root_path: Path) -> dict[str, list[str]]:
318
+ cache_file = root_path / CACHE_NAME
319
+ if cache_file.exists():
320
+ try:
321
+ data = json.loads(cache_file.read_text())
322
+ if data.get("version") == _CACHE_VERSION:
323
+ return {rel: e.get("imports", [])
324
+ for rel, e in data.get("entries", {}).items()}
325
+ except (json.JSONDecodeError, OSError):
326
+ pass
327
+ return {rel: _raw_imports(root_path / rel, rel)
328
+ for rel in _discover_python_files(root_path)}
catchdev/report.py ADDED
@@ -0,0 +1,162 @@
1
+ """Pretty terminal output for catch, built on rich."""
2
+ from __future__ import annotations
3
+
4
+ from rich.console import Console
5
+ from rich.panel import Panel
6
+
7
+ from .depcheck import DepRisk
8
+ from .differ import DiffResult
9
+ from .mapper import AffectedTests
10
+ from .runner import RunResult
11
+
12
+ console = Console()
13
+ err_console = Console(stderr=True)
14
+
15
+
16
+ def _file_of(test_id: str) -> str:
17
+ return test_id.split("::")[0]
18
+
19
+
20
+ def print_report(diff: DiffResult, affected: AffectedTests,
21
+ results: RunResult, dep_risks: list[DepRisk],
22
+ fail_on_suspicious: bool = False) -> None:
23
+ n_files = len(diff.files)
24
+ n_tests = len(results.results) or len(affected.test_files)
25
+ console.print(Panel(
26
+ f"[bold]{n_files} file{'s' if n_files != 1 else ''} changed, "
27
+ f"{n_tests} test{'s' if n_tests != 1 else ''} affected[/bold]",
28
+ title="CATCH REPORT",
29
+ expand=False,
30
+ ))
31
+
32
+ if results.error:
33
+ err_console.print(f"[red]✗ could not run tests:[/red] {results.error}")
34
+
35
+ # --- new failures -----------------------------------------------------
36
+ if results.new_failures:
37
+ console.print(f"\n[bold red]✗ NEW FAILURES "
38
+ f"({len(results.new_failures)})[/bold red]")
39
+ seen_reasons: set[str] = set()
40
+ for f in results.new_failures:
41
+ console.print(f" [red]{f.test_id}[/red]")
42
+ reasons = affected.reasons.get(_file_of(f.test_id), [])
43
+ for r in reasons:
44
+ if (f.test_id, r) not in seen_reasons:
45
+ console.print(f" [dim]→ {r}[/dim]")
46
+ seen_reasons.add((f.test_id, r))
47
+ if f.error_message:
48
+ console.print(f" [dim]→ {f.error_message}[/dim]")
49
+
50
+ # --- pre-existing failures --------------------------------------------
51
+ if results.pre_existing_failures:
52
+ console.print(f"\n[dim]~ PRE-EXISTING FAILURES "
53
+ f"({len(results.pre_existing_failures)}) — "
54
+ f"already broken before your diff[/dim]")
55
+ for f in results.pre_existing_failures:
56
+ console.print(f" [dim]{f.test_id}[/dim]")
57
+
58
+ # --- dependency risks ---------------------------------------------------
59
+ risky = [d for d in dep_risks if d.risk_level != "safe"]
60
+ if risky:
61
+ console.print(f"\n[bold yellow]⚠ SUSPICIOUS DEPENDENCIES "
62
+ f"({len(risky)})[/bold yellow]")
63
+ for d in risky:
64
+ color = "red" if d.risk_level == "dangerous" else "yellow"
65
+ console.print(f" [{color}]{d.package}[/{color}] "
66
+ f"[dim]({d.risk_level})[/dim]")
67
+ console.print(f" [dim]→ {d.reason}[/dim]")
68
+ if d.similar_packages:
69
+ console.print(
70
+ f" [dim]→ did you mean: "
71
+ f"{', '.join(d.similar_packages)}?[/dim]"
72
+ )
73
+
74
+ # --- summary ------------------------------------------------------------
75
+ if results.no_tests:
76
+ console.print("\n[yellow]⚠ no tests found — can't verify anything, "
77
+ "commit at your own risk[/yellow]")
78
+ elif results.total_passed:
79
+ console.print(f"\n[green]✓ {results.total_passed} affected "
80
+ f"test{'s' if results.total_passed != 1 else ''} "
81
+ f"pass[/green]")
82
+
83
+ code = get_exit_code(results, dep_risks, fail_on_suspicious)
84
+ if results.no_tests:
85
+ console.print("\n[bold yellow]RESULT: UNKNOWN[/bold yellow] — "
86
+ "no tests to verify against")
87
+ elif code == 0:
88
+ console.print("\n[bold green]RESULT: PASS[/bold green] — safe to commit")
89
+ else:
90
+ console.print("\n[bold red]RESULT: FAIL[/bold red] — do not commit")
91
+
92
+
93
+ def get_exit_code(results: RunResult, dep_risks: list[DepRisk],
94
+ fail_on_suspicious: bool = False) -> int:
95
+ """0 = clean. 1 = new failures or dangerous deps. 2 = catch couldn't run."""
96
+ if results.error:
97
+ return 2
98
+ if results.new_failures:
99
+ return 1
100
+ blocking = {"dangerous"} | ({"suspicious"} if fail_on_suspicious else set())
101
+ if any(d.risk_level in blocking for d in dep_risks):
102
+ return 1
103
+ return 0
104
+
105
+
106
+ def render_markdown(diff: DiffResult, affected: AffectedTests,
107
+ results: RunResult, dep_risks: list[DepRisk],
108
+ fail_on_suspicious: bool = False) -> str:
109
+ """Markdown version of the report (for PR comments via --output)."""
110
+ n_files = len(diff.files)
111
+ n_tests = len(results.results) or len(affected.test_files)
112
+ lines = [
113
+ "## Catch report",
114
+ "",
115
+ f"**{n_files} file{'s' if n_files != 1 else ''} changed, "
116
+ f"{n_tests} test{'s' if n_tests != 1 else ''} affected**",
117
+ "",
118
+ ]
119
+ if results.error:
120
+ lines += [f"❌ could not run tests: `{results.error}`", ""]
121
+ if results.new_failures:
122
+ lines += [f"### ❌ New failures ({len(results.new_failures)})", ""]
123
+ for f in results.new_failures:
124
+ lines.append(f"- `{f.test_id}`")
125
+ for r in affected.reasons.get(_file_of(f.test_id), []):
126
+ lines.append(f" - {r}")
127
+ if f.error_message:
128
+ lines.append(f" - `{f.error_message}`")
129
+ lines.append("")
130
+ if results.pre_existing_failures:
131
+ lines += [f"<details><summary>~ Pre-existing failures "
132
+ f"({len(results.pre_existing_failures)}) — already broken "
133
+ f"before this diff</summary>", ""]
134
+ for f in results.pre_existing_failures:
135
+ lines.append(f"- `{f.test_id}`")
136
+ lines += ["", "</details>", ""]
137
+ risky = [d for d in dep_risks if d.risk_level != "safe"]
138
+ if risky:
139
+ lines += [f"### ⚠️ Suspicious dependencies ({len(risky)})", ""]
140
+ for d in risky:
141
+ lines.append(f"- **{d.package}** ({d.risk_level}) — {d.reason}")
142
+ if d.similar_packages:
143
+ lines.append(f" - did you mean: "
144
+ f"{', '.join(f'`{p}`' for p in d.similar_packages)}?")
145
+ lines.append("")
146
+ if results.no_tests:
147
+ lines += ["> ⚠️ No tests found — can't verify anything, "
148
+ "merge at your own risk.", ""]
149
+ elif results.total_passed:
150
+ lines += [f"✅ {results.total_passed} affected "
151
+ f"test{'s' if results.total_passed != 1 else ''} pass", ""]
152
+ code = get_exit_code(results, dep_risks, fail_on_suspicious)
153
+ if results.no_tests:
154
+ lines.append("**RESULT: UNKNOWN** — no tests to verify against")
155
+ elif code == 0:
156
+ lines.append("**RESULT: PASS** ✅ — safe to merge")
157
+ else:
158
+ lines.append("**RESULT: FAIL** ❌ — do not merge")
159
+ lines += ["", "---", "<sub>Posted by "
160
+ "[catch](https://github.com/yourusername/catchdev) — "
161
+ "tells you what your AI coding agent just broke</sub>"]
162
+ return "\n".join(lines) + "\n"