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/runner.py ADDED
@@ -0,0 +1,271 @@
1
+ """Run the affected tests, and tell NEW failures from pre-existing ones.
2
+
3
+ Failures found in the working tree are re-run against the pre-diff baseline
4
+ in a temporary git worktree (checked out at the base ref). A failure that
5
+ also occurs there was already broken; only NEW failures are reported as
6
+ problems.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ import time
16
+ from dataclasses import dataclass, field
17
+
18
+ from .mapper import AffectedTests
19
+
20
+
21
+ @dataclass
22
+ class TestResult:
23
+ test_id: str # "tests/test_auth.py::test_token_refresh"
24
+ passed: bool
25
+ duration: float = 0.0
26
+ error_message: str | None = None
27
+ pre_existing: bool = False
28
+
29
+
30
+ @dataclass
31
+ class RunResult:
32
+ results: list[TestResult] = field(default_factory=list)
33
+ total_passed: int = 0
34
+ total_failed: int = 0
35
+ duration: float = 0.0
36
+ new_failures: list[TestResult] = field(default_factory=list)
37
+ pre_existing_failures: list[TestResult] = field(default_factory=list)
38
+ no_tests: bool = False
39
+ error: str | None = None
40
+
41
+
42
+ _RESULT_RE = re.compile(
43
+ r"^(\S+?)\s+(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)\s*(?:\[\s*\d+%\])?$"
44
+ )
45
+ _SUMMARY_RE = re.compile(r"^(FAILED|ERROR)\s+(\S+?)\s+-\s+(.*)$")
46
+ _SUMMARY_BARE_RE = re.compile(r"^(FAILED|ERROR)\s+(\S+?)$")
47
+ _SECTION_RE = re.compile(r"^_{3,}\s+(.+?)\s+_{3,}$")
48
+ _DURATION_RE = re.compile(r"^([\d.]+)s\s+(call|setup|teardown)\s+(\S+)$")
49
+
50
+ _PASS_STATUSES = {"PASSED", "XFAIL", "SKIPPED"}
51
+
52
+
53
+ def _run_pytest(targets: list[str], cwd: str,
54
+ extra_env: dict[str, str] | None = None,
55
+ timeout: int = 300) -> tuple[dict[str, str], dict[str, str],
56
+ dict[str, float], int, str]:
57
+ """Run pytest, return (statuses, error_messages, durations, rc, raw)."""
58
+ cmd = [
59
+ sys.executable, "-m", "pytest", *targets,
60
+ "-v", "--tb=short", "--no-header", "--color=no",
61
+ "-p", "no:cacheprovider", "--durations=0",
62
+ "--continue-on-collection-errors",
63
+ ]
64
+ env = dict(os.environ)
65
+ env.pop("PYTEST_ADDOPTS", None)
66
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
67
+ env["COLUMNS"] = "240" # stop pytest truncating summary lines to tty width
68
+ if extra_env:
69
+ env.update(extra_env)
70
+ try:
71
+ proc = subprocess.run(
72
+ cmd, cwd=cwd, capture_output=True, text=True,
73
+ timeout=timeout, env=env,
74
+ )
75
+ except subprocess.TimeoutExpired:
76
+ return {}, {}, {}, -1, "pytest timed out"
77
+ except FileNotFoundError:
78
+ return {}, {}, {}, -1, "pytest is not installed"
79
+
80
+ statuses: dict[str, str] = {}
81
+ errors: dict[str, str] = {}
82
+ durations: dict[str, float] = {}
83
+ in_summary = False
84
+ section: str | None = None # current FAILURES section test
85
+ for line in proc.stdout.splitlines():
86
+ line = line.rstrip()
87
+ if line.startswith("=") and "short test summary" in line:
88
+ in_summary = True
89
+ continue
90
+ if in_summary:
91
+ m = _SUMMARY_RE.match(line)
92
+ if m:
93
+ if m.group(2) not in errors:
94
+ errors[m.group(2)] = m.group(3).strip()[:500]
95
+ statuses.setdefault(m.group(2), m.group(1))
96
+ continue
97
+ m = _SUMMARY_BARE_RE.match(line)
98
+ if m:
99
+ statuses.setdefault(m.group(2), m.group(1))
100
+ continue
101
+ m = _SECTION_RE.match(line)
102
+ if m:
103
+ section = m.group(1)
104
+ if section.startswith("ERROR collecting "):
105
+ # key is a file path, not a dotted test name
106
+ section = section[len("ERROR collecting "):]
107
+ else:
108
+ section = section.replace(".", "::")
109
+ continue
110
+ if section and line.startswith("E "):
111
+ errors[section] = line[2:].strip()[:500]
112
+ section = None
113
+ continue
114
+ m = _RESULT_RE.match(line.strip())
115
+ if m and "::" in m.group(1):
116
+ statuses[m.group(1)] = m.group(2)
117
+ continue
118
+ m = _DURATION_RE.match(line.strip())
119
+ if m:
120
+ durations[m.group(3)] = durations.get(m.group(3), 0.0) + float(m.group(1))
121
+ return statuses, errors, durations, proc.returncode, proc.stdout + proc.stderr
122
+
123
+
124
+ def _collect_targets(targets: list[str], cwd: str,
125
+ extra_env: dict[str, str] | None = None
126
+ ) -> tuple[dict[str, str], dict[str, str], dict[str, float], int, str]:
127
+ """Run pytest over targets; if a fatal collection error (e.g. a broken
128
+ conftest) kills the whole batch, fall back to per-target runs so one
129
+ bad file can't hide the rest."""
130
+ statuses, errors, durations, rc, raw = _run_pytest(targets, cwd, extra_env)
131
+ if statuses or rc in (0, 5, -1) or len(targets) <= 1:
132
+ return statuses, errors, durations, rc, raw
133
+ for t in targets:
134
+ s, e, d, rc2, raw2 = _run_pytest([t], cwd, extra_env)
135
+ statuses.update(s)
136
+ errors.update(e)
137
+ for k, v in d.items():
138
+ durations[k] = durations.get(k, 0.0) + v
139
+ if not s and rc2 not in (0, 5):
140
+ statuses[t] = "ERROR"
141
+ errors.setdefault(t, _tail(raw2, 3))
142
+ return statuses, errors, durations, 0 if statuses else rc, raw
143
+
144
+
145
+ def _git_ok(args: list[str], cwd: str) -> bool:
146
+ return subprocess.run(
147
+ ["git", *args], cwd=cwd,
148
+ capture_output=True, text=True,
149
+ ).returncode == 0
150
+
151
+
152
+ def _baseline_failures(failed_ids: list[str], cwd: str, base_ref: str) -> set[str] | None:
153
+ """Re-run failed tests against the pre-diff code in a temp worktree.
154
+
155
+ Returns the set of test ids that ALSO fail at baseline (= pre-existing),
156
+ or None if a baseline run wasn't possible.
157
+ """
158
+ if not _git_ok(["rev-parse", "--verify", base_ref], cwd):
159
+ return None
160
+ tmp = tempfile.mkdtemp(prefix="catch-baseline-")
161
+ try:
162
+ if not _git_ok(["worktree", "add", "--detach", tmp, base_ref], cwd):
163
+ return None
164
+ # make the baseline importable: flat layout lives at the root,
165
+ # src-layout lives in <root>/src — put both ahead of any
166
+ # editable install of the *modified* code.
167
+ paths = [tmp]
168
+ if os.path.isdir(os.path.join(tmp, "src")):
169
+ paths.insert(0, os.path.join(tmp, "src"))
170
+ paths.append(os.environ.get("PYTHONPATH", ""))
171
+ env_path = os.pathsep.join(p for p in paths if p)
172
+ statuses, _, _, rc, raw = _collect_targets(
173
+ failed_ids, cwd=tmp, extra_env={"PYTHONPATH": env_path}
174
+ )
175
+ if rc == -1 or not statuses:
176
+ return None
177
+ return {tid for tid, st in statuses.items() if st not in _PASS_STATUSES}
178
+ finally:
179
+ subprocess.run(["git", "worktree", "remove", "--force", tmp],
180
+ cwd=cwd, capture_output=True)
181
+ subprocess.run(["git", "worktree", "prune"],
182
+ cwd=cwd, capture_output=True)
183
+
184
+
185
+ def run_tests(affected: AffectedTests, all_tests: bool = False,
186
+ cwd: str = ".", base_ref: str = "HEAD") -> RunResult:
187
+ if all_tests:
188
+ targets = ["."]
189
+ else:
190
+ # run pinpointed test functions, PLUS whole files where we only
191
+ # have file-level confidence
192
+ func_files = {t.split("::")[0] for t in affected.test_functions}
193
+ targets = list(affected.test_functions) + [
194
+ f for f in affected.test_files if f not in func_files
195
+ ]
196
+
197
+ result = RunResult()
198
+ if not targets:
199
+ result.no_tests = True
200
+ return result
201
+
202
+ start = time.monotonic()
203
+ statuses, errors, durations, rc, raw = _collect_targets(targets, cwd)
204
+ result.duration = time.monotonic() - start
205
+
206
+ if rc == -1:
207
+ result.error = raw.strip()
208
+ return result
209
+ if rc == 5 or (not statuses and rc != 0):
210
+ # pytest collected nothing / failed at collection
211
+ if not statuses:
212
+ result.no_tests = rc == 5
213
+ if rc != 0 and rc != 5:
214
+ result.error = _tail(raw)
215
+ return result
216
+
217
+ for tid, status in sorted(statuses.items()):
218
+ passed = status in _PASS_STATUSES
219
+ result.results.append(TestResult(
220
+ test_id=tid,
221
+ passed=passed,
222
+ duration=durations.get(tid, 0.0),
223
+ error_message=None if passed else _error_for(tid, status, errors),
224
+ ))
225
+
226
+ failures = [r for r in result.results if not r.passed]
227
+ if failures:
228
+ baseline = _baseline_failures([f.test_id for f in failures], cwd, base_ref)
229
+ for f in failures:
230
+ if baseline is not None and _in_baseline(f.test_id, baseline):
231
+ f.pre_existing = True
232
+ result.pre_existing_failures.append(f)
233
+ else:
234
+ result.new_failures.append(f)
235
+
236
+ result.total_passed = sum(1 for r in result.results if r.passed)
237
+ result.total_failed = sum(1 for r in result.results if not r.passed)
238
+ return result
239
+
240
+
241
+ def _in_baseline(test_id: str, baseline: set[str]) -> bool:
242
+ """Did this test also fail at baseline?
243
+
244
+ Handles id shape mismatches: a collection error is keyed by file path
245
+ ('tests/test_x.py') while a collected run keys by node id
246
+ ('tests/test_x.py::test_y').
247
+ """
248
+ if test_id in baseline:
249
+ return True
250
+ return any(
251
+ b.startswith(test_id + "::") or test_id.startswith(b + "::")
252
+ for b in baseline
253
+ )
254
+
255
+
256
+ def _error_for(test_id: str, status: str, errors: dict[str, str]) -> str:
257
+ """Best error message for a failed test id.
258
+
259
+ FAILURES-section entries are keyed by 'Class::test[x]' (no file part),
260
+ summary entries by full nodeid — try both.
261
+ """
262
+ if test_id in errors:
263
+ return errors[test_id]
264
+ for key, msg in errors.items():
265
+ if test_id.endswith(key):
266
+ return msg
267
+ return status
268
+
269
+
270
+ def _tail(text: str, lines: int = 15) -> str:
271
+ return "\n".join(text.strip().splitlines()[-lines:])
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: catchdev
3
+ Version: 0.1.0
4
+ Summary: Tells you what your AI coding agent just broke
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: httpx
10
+ Requires-Dist: rich
11
+ Requires-Dist: click
12
+ Dynamic: license-file
13
+
14
+ # catchdev
15
+
16
+ **Tells you what your AI coding agent just broke.**
17
+
18
+ ![catch flags a real 4-month Flask regression in 2 seconds](demo/demo.gif)
19
+
20
+ That GIF is real: it's catch flagging the `SECRET_KEY_FALLBACKS` session bug
21
+ that lived in Flask 3.1.0 for ~4 months before anyone noticed. catch ran the
22
+ affected tests, re-ran the failures against the pre-diff baseline, and pointed
23
+ at the exact regression. [Reproduce it yourself.](demo/README.md)
24
+
25
+ ## 10-second install
26
+
27
+ ```bash
28
+ pip install catchdev
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ```bash
34
+ cd some-ai-generated-project
35
+ # make some changes (or let an agent make them)
36
+ git add .
37
+ catch # check staged changes
38
+ catch --commit HEAD~1 # check the last commit
39
+ catch --all-tests # run the full suite instead of affected tests
40
+ catch --skip-deps # skip PyPI dependency risk checks
41
+ catch --fail-on-suspicious # also block on suspicious (not just dangerous) deps
42
+ catch --output report.md # write a markdown report (for PR comments)
43
+ echo $? # 1 = problems found, 0 = clean
44
+ ```
45
+
46
+ In a GitHub Actions PR, catch automatically diffs against
47
+ `origin/$GITHUB_BASE_REF` instead of `HEAD~1` (squash merges break `HEAD~1`).
48
+
49
+ ## How it works
50
+
51
+ 1. **differ** — parses `git diff --unified=0` into changed files, changed line
52
+ numbers, and newly added imports / dependency entries.
53
+ 2. **mapper** — builds (and caches in `.catch_cache.json`) an AST import graph
54
+ of the project, then walks it backwards from each changed file until it hits
55
+ test files. When possible it narrows down to the specific test functions
56
+ that call the functions your diff touched.
57
+ 3. **runner** — runs the affected tests with pytest, then re-runs any failures
58
+ against the pre-diff baseline in a temporary git worktree to distinguish
59
+ NEW failures from pre-existing ones.
60
+ 4. **depcheck** — queries PyPI for every new dependency: does it exist, how old
61
+ is it, how many downloads, and did you mean a similarly-named popular
62
+ package? (Hallucinated package names — "slopsquatting" — are a real supply
63
+ chain risk with AI-generated code.)
64
+ 5. **report** — pretty terminal output and an exit code you can wire into a
65
+ hook or CI.
66
+
67
+ ## Why not just...?
68
+
69
+ | | catch | LLM review (CodeRabbit etc.) | static gates (dont-break, Solumbe) |
70
+ |---|---|---|---|
71
+ | Actually runs your tests | ✓ | ✗ | ✗ |
72
+ | Tells new failures from pre-existing | ✓ | ✗ | ✗ |
73
+ | Deterministic (same answer every run) | ✓ | ✗ | ✓ |
74
+ | Catches hallucinated packages | ✓ (live registry check) | unreliable | partial |
75
+ | Cost per run | free | tokens/subscription | free |
76
+ | Works as a hard CI gate | ✓ exit code | ✗ | ✓ |
77
+
78
+ ## Use it everywhere
79
+
80
+ **GitHub Action** (posts the report as a PR comment):
81
+
82
+ ```yaml
83
+ # .github/workflows/catch.yml
84
+ name: Catch
85
+ on: [pull_request]
86
+ jobs:
87
+ catch:
88
+ runs-on: ubuntu-latest
89
+ permissions:
90
+ issues: write
91
+ pull-requests: write
92
+ steps:
93
+ - uses: actions/checkout@v4
94
+ with:
95
+ fetch-depth: 0
96
+ - uses: actions/setup-python@v5
97
+ with:
98
+ python-version: "3.12"
99
+ - run: pip install -e .
100
+ - uses: yourusername/catchdev@v1
101
+ ```
102
+
103
+ catch runs catch on its own PRs — see
104
+ [.github/workflows/catch.yml](.github/workflows/catch.yml) in this repo.
105
+
106
+ **Pre-commit / pre-push hook** — add to `.pre-commit-config.yaml`:
107
+
108
+ ```yaml
109
+ - repo: https://github.com/yourusername/catchdev
110
+ rev: v0.1.0
111
+ hooks:
112
+ - id: catch
113
+ ```
114
+
115
+ Running tests on every commit annoys people; pre-push is the sweet spot:
116
+
117
+ ```yaml
118
+ - id: catch
119
+ stages: [pre-push]
120
+ ```
121
+
122
+ **Claude Code skill** — your agent checks its own work before committing.
123
+ Copy [skills/catch/SKILL.md](skills/catch/SKILL.md) into
124
+ `~/.claude/skills/catch/` (or drop the packaged `catch.skill` from Releases
125
+ into your skills directory). After that, Claude runs `catch --staged` before
126
+ every commit and fixes what it breaks instead of shipping it.
127
+
128
+ ## Exit codes
129
+
130
+ - `0` — all affected tests pass, no dangerous dependencies
131
+ - `1` — new test failures OR dangerous dependencies
132
+ - `2` — catch itself couldn't run (not a git repo, etc.)
133
+
134
+ ## License
135
+
136
+ MIT
@@ -0,0 +1,13 @@
1
+ catchdev/__init__.py,sha256=agaDdw5K_mq_8S15RgO0naL4pTmkKpg5dXG7AHLqxp8,90
2
+ catchdev/cli.py,sha256=jLzN_Xn4RTKTYCXcqm9P7tdoeNyJOjcDDSRC8qLlIhQ,2770
3
+ catchdev/depcheck.py,sha256=9OjQiUMY8J14oYs633M9ERtnEstlW2irbaub8OEktNI,4879
4
+ catchdev/differ.py,sha256=AUGXeHO3PuYOFN5klg5nTRIzcZ2qa6OEJUJK_acMPmM,8210
5
+ catchdev/mapper.py,sha256=xuxTrdJCWBwTmc8mv-kD5O139Wdkdfs-gR1O2HtlBhU,12430
6
+ catchdev/report.py,sha256=QPvugz0lKFeoMfDIcP0BUtHBrYDxaiGydfCPersw28U,6974
7
+ catchdev/runner.py,sha256=B3acWCWIHJJ6M2nyo3BKSAYwyOgSwuScSl8DmCEnwJ4,9891
8
+ catchdev-0.1.0.dist-info/licenses/LICENSE,sha256=le8U08j8BaZTFk-2slgZfT3VbScI3mgzY2kTBUd7nFI,1078
9
+ catchdev-0.1.0.dist-info/METADATA,sha256=7IN29hK5xrUM2zhqD3sYY-_KF46ENKHkvuV4vNLifLo,4546
10
+ catchdev-0.1.0.dist-info/WHEEL,sha256=a-udL2m4V_6Yn8b-uKzWb12RjRxwwMo6ohYFM24tpaY,91
11
+ catchdev-0.1.0.dist-info/entry_points.txt,sha256=TeY8NfEFgd6ymLAkpMqa-7Ti4cokSEXxc-5GcNn9Xsk,44
12
+ catchdev-0.1.0.dist-info/top_level.txt,sha256=GoHQF3DLSQ7MAe7lqUO5j4CxN2nkOSMBD66ILyqYkt4,9
13
+ catchdev-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ catch = catchdev.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 catchdev contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ catchdev