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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """catchdev — tells you what your AI coding agent just broke."""
2
+
3
+ __version__ = "0.1.0"
catchdev/cli.py ADDED
@@ -0,0 +1,75 @@
1
+ """catch — Tells you what your AI coding agent just broke."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import sys
6
+
7
+ import click
8
+
9
+ from . import depcheck, differ, mapper, report, runner
10
+
11
+
12
+ @click.command()
13
+ @click.option("--staged", is_flag=True, default=False,
14
+ help="Check staged changes (default)")
15
+ @click.option("--commit", default=None,
16
+ help="Check changes since a specific commit (e.g., HEAD~1)")
17
+ @click.option("--all-tests", is_flag=True, default=False,
18
+ help="Run all tests, not just affected ones")
19
+ @click.option("--skip-deps", is_flag=True, default=False,
20
+ help="Skip dependency checking")
21
+ @click.option("--fail-on-suspicious", is_flag=True, default=False,
22
+ help="Exit 1 on suspicious (not just dangerous) dependencies")
23
+ @click.option("--output", default=None, metavar="FILE",
24
+ help="Also write the report as markdown to FILE "
25
+ "(e.g. report.md for PR comments)")
26
+ def main(staged: bool, commit: str | None, all_tests: bool, skip_deps: bool,
27
+ fail_on_suspicious: bool, output: str | None) -> None:
28
+ """Tells you what your AI coding agent just broke."""
29
+ # In CI pull requests, diff against the PR base, not HEAD~1
30
+ # (squash merges break HEAD~1). GITHUB_BASE_REF is set by GitHub Actions.
31
+ base_ref_env = os.environ.get("GITHUB_BASE_REF")
32
+ if commit is None and base_ref_env and not staged:
33
+ commit = f"origin/{base_ref_env}"
34
+
35
+ # 1. Get the diff
36
+ try:
37
+ diff = differ.get_diff(staged=staged or not commit, commit=commit)
38
+ except differ.GitError as e:
39
+ report.err_console.print(f"[red]✗ {e}[/red]")
40
+ sys.exit(2)
41
+
42
+ if not diff.files:
43
+ report.console.print("[green]✓ no changes detected[/green]")
44
+ sys.exit(0)
45
+
46
+ # 2. Map to affected tests
47
+ affected = mapper.find_affected_tests(diff)
48
+
49
+ # 3. Run tests (baseline = the ref we diffed against)
50
+ results = runner.run_tests(
51
+ affected, all_tests=all_tests, base_ref=commit or "HEAD"
52
+ )
53
+
54
+ # 4. Check dependencies
55
+ dep_risks = [] if skip_deps else depcheck.check_dependencies(
56
+ diff.new_dependencies
57
+ )
58
+
59
+ # 5. Report (terminal + optional markdown file)
60
+ report.print_report(diff, affected, results, dep_risks,
61
+ fail_on_suspicious=fail_on_suspicious)
62
+ if output:
63
+ with open(output, "w", encoding="utf-8") as f:
64
+ f.write(report.render_markdown(
65
+ diff, affected, results, dep_risks,
66
+ fail_on_suspicious=fail_on_suspicious,
67
+ ))
68
+
69
+ # 6. Exit code
70
+ sys.exit(report.get_exit_code(results, dep_risks,
71
+ fail_on_suspicious=fail_on_suspicious))
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
catchdev/depcheck.py ADDED
@@ -0,0 +1,122 @@
1
+ """Check new dependencies against PyPI.
2
+
3
+ Catches hallucinated packages (404 on PyPI), brand-new low-usage packages
4
+ (typosquat risk), and suggests the popular package you probably meant.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import difflib
9
+ from dataclasses import dataclass, field
10
+ from datetime import datetime, timezone
11
+
12
+ import httpx
13
+
14
+ PYPI_URL = "https://pypi.org/pypi/{package}/json"
15
+ STATS_URL = "https://pypistats.org/api/packages/{package}/recent"
16
+
17
+ POPULAR_PACKAGES = [
18
+ "requests", "numpy", "pandas", "flask", "django", "pyjwt", "sqlalchemy",
19
+ "click", "rich", "httpx", "pytest", "boto3", "scipy", "matplotlib",
20
+ "pillow", "beautifulsoup4", "cryptography", "paramiko", "aiohttp",
21
+ "fastapi", "pydantic", "urllib3", "certifi", "setuptools", "wheel",
22
+ "torch", "tensorflow", "scikit-learn", "transformers", "openai",
23
+ "anthropic", "redis", "celery", "gunicorn", "uvicorn", "starlette",
24
+ "jinja2", "pyyaml", "lxml", "psycopg2", "pymysql", "pymongo",
25
+ "python-dateutil", "tqdm", "six", "attrs", "packaging",
26
+ "typing-extensions", "colorama", "toml", "pytest-cov", "mock",
27
+ "responses", "faker", "factory-boy", "django-rest-framework",
28
+ "djangorestframework", "arrow", "pendulum", "typer", "fire",
29
+ ]
30
+
31
+
32
+ @dataclass
33
+ class DepRisk:
34
+ package: str
35
+ exists: bool | None # None = couldn't verify (network error)
36
+ age_days: int | None = None
37
+ weekly_downloads: int | None = None
38
+ risk_level: str = "safe" # "safe" | "suspicious" | "dangerous"
39
+ similar_packages: list[str] = field(default_factory=list)
40
+ reason: str = ""
41
+
42
+
43
+ def _classify(exists: bool | None, age_days: int | None,
44
+ weekly_downloads: int | None) -> tuple[str, str]:
45
+ if exists is False:
46
+ return "dangerous", "package does not exist on PyPI (likely hallucinated)"
47
+ if exists is None:
48
+ return "suspicious", "could not verify package on PyPI (network error)"
49
+ if age_days is not None and weekly_downloads is not None:
50
+ if age_days < 30 and weekly_downloads < 100:
51
+ return ("dangerous",
52
+ f"registered {age_days} days ago with "
53
+ f"{weekly_downloads} weekly downloads")
54
+ if age_days < 90 and weekly_downloads < 1000:
55
+ return ("suspicious",
56
+ f"registered {age_days} days ago with "
57
+ f"{weekly_downloads} weekly downloads")
58
+ parts = []
59
+ if age_days is not None:
60
+ parts.append(f"on PyPI for {age_days} days")
61
+ if weekly_downloads is not None:
62
+ parts.append(f"{weekly_downloads} weekly downloads")
63
+ return "safe", ", ".join(parts) or "established package"
64
+
65
+
66
+ def _similar(package: str) -> list[str]:
67
+ return difflib.get_close_matches(
68
+ package.lower(), POPULAR_PACKAGES, n=3, cutoff=0.72
69
+ )
70
+
71
+
72
+ def _parse_time(value: str) -> datetime | None:
73
+ try:
74
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
75
+ except ValueError:
76
+ return None
77
+
78
+
79
+ def check_dependencies(packages: list[str], timeout: float = 10.0) -> list[DepRisk]:
80
+ risks: list[DepRisk] = []
81
+ if not packages:
82
+ return risks
83
+ with httpx.Client(timeout=timeout, follow_redirects=True) as client:
84
+ for pkg in packages:
85
+ risk = DepRisk(package=pkg, exists=None)
86
+ try:
87
+ resp = client.get(PYPI_URL.format(package=pkg))
88
+ if resp.status_code == 404:
89
+ risk.exists = False
90
+ elif resp.status_code == 200:
91
+ risk.exists = True
92
+ data = resp.json()
93
+ earliest: datetime | None = None
94
+ for releases in data.get("releases", {}).values():
95
+ for f in releases:
96
+ t = _parse_time(f.get("upload_time", ""))
97
+ if t and (earliest is None or t < earliest):
98
+ earliest = t
99
+ if earliest:
100
+ risk.age_days = max(
101
+ 0, (datetime.now(timezone.utc) - earliest).days
102
+ )
103
+ except httpx.HTTPError:
104
+ risk.exists = None
105
+
106
+ if risk.exists:
107
+ try:
108
+ sresp = client.get(STATS_URL.format(package=pkg.lower()))
109
+ if sresp.status_code == 200:
110
+ risk.weekly_downloads = (
111
+ sresp.json().get("data", {}).get("last_week")
112
+ )
113
+ except (httpx.HTTPError, ValueError):
114
+ pass
115
+
116
+ risk.risk_level, risk.reason = _classify(
117
+ risk.exists, risk.age_days, risk.weekly_downloads
118
+ )
119
+ if risk.risk_level != "safe" or risk.exists is False:
120
+ risk.similar_packages = _similar(pkg)
121
+ risks.append(risk)
122
+ return risks
catchdev/differ.py ADDED
@@ -0,0 +1,242 @@
1
+ """Parse git diffs into structured change data.
2
+
3
+ Input: `git diff` (staged changes, or `git diff <commit>` for a commit range)
4
+ Output: DiffResult — which files changed, which lines, and which new
5
+ third-party dependencies were introduced.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+
16
+ @dataclass
17
+ class ChangedFile:
18
+ path: str # "src/auth/token.py"
19
+ changed_lines: list[int] = field(default_factory=list) # [45, 46, 47, 89]
20
+ is_new_file: bool = False
21
+ is_deleted: bool = False
22
+ is_python: bool = True
23
+
24
+
25
+ @dataclass
26
+ class DiffResult:
27
+ files: list[ChangedFile] = field(default_factory=list)
28
+ new_dependencies: list[str] = field(default_factory=list) # ["py-token-utils"]
29
+
30
+
31
+ _HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
32
+ _HEADER_RE = re.compile(r"^diff --git a/(.*?) b/(.*)$")
33
+ _IMPORT_RE = re.compile(
34
+ r"^\s*(?:from\s+([A-Za-z_][\w.]*)\s+import\s|import\s+([A-Za-z_][\w.]*))"
35
+ )
36
+ _REQ_LINE_RE = re.compile(r"^\s*([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)\s*(?:[<>=!~;\[ ]|$)")
37
+ _TOML_DEP_RE = re.compile(r"""["']([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)""")
38
+
39
+ # import name -> PyPI package name for common mismatches
40
+ _IMPORT_TO_PACKAGE = {
41
+ "yaml": "pyyaml",
42
+ "PIL": "pillow",
43
+ "cv2": "opencv-python",
44
+ "sklearn": "scikit-learn",
45
+ "bs4": "beautifulsoup4",
46
+ "jwt": "PyJWT",
47
+ "Crypto": "pycryptodome",
48
+ "dateutil": "python-dateutil",
49
+ "magic": "python-magic",
50
+ "serial": "pyserial",
51
+ "usb": "pyusb",
52
+ "dns": "dnspython",
53
+ "ldap": "python-ldap",
54
+ "gi": "PyGObject",
55
+ }
56
+
57
+
58
+ class GitError(RuntimeError):
59
+ """Raised when git can't give us a diff (not a repo, bad ref, ...)."""
60
+
61
+
62
+ def _git(args: list[str], cwd: str) -> str:
63
+ proc = subprocess.run(
64
+ ["git", *args], cwd=cwd, capture_output=True, text=True
65
+ )
66
+ if proc.returncode != 0:
67
+ raise GitError(proc.stderr.strip() or f"git {' '.join(args)} failed")
68
+ return proc.stdout
69
+
70
+
71
+ def get_diff(staged: bool = True, commit: str | None = None, cwd: str = ".") -> DiffResult:
72
+ """Get the diff to analyse.
73
+
74
+ staged=True (default): staged changes, falling back to unstaged if the
75
+ index is empty.
76
+ commit="HEAD~1": changes introduced since that commit.
77
+ """
78
+ if commit:
79
+ text = _git(["diff", "--unified=0", commit], cwd)
80
+ elif staged:
81
+ text = _git(["diff", "--cached", "--unified=0"], cwd)
82
+ if not text.strip():
83
+ text = _git(["diff", "--unified=0"], cwd)
84
+ else:
85
+ text = _git(["diff", "--unified=0"], cwd)
86
+ return parse_diff(text, cwd=cwd)
87
+
88
+
89
+ def parse_diff(text: str, cwd: str = ".") -> DiffResult:
90
+ """Parse `git diff --unified=0` output into a DiffResult."""
91
+ result = DiffResult()
92
+ current: ChangedFile | None = None
93
+ added_lines: list[str] = []
94
+ old_path = ""
95
+
96
+ def flush():
97
+ nonlocal current, added_lines
98
+ if current is None:
99
+ return
100
+ current.changed_lines = sorted(set(current.changed_lines))
101
+ result.files.append(current)
102
+ deps = _extract_deps(current, added_lines, cwd)
103
+ for d in deps:
104
+ if d not in result.new_dependencies:
105
+ result.new_dependencies.append(d)
106
+ current = None
107
+ added_lines = []
108
+
109
+ for line in text.splitlines():
110
+ if line.startswith("diff --git "):
111
+ flush()
112
+ m = _HEADER_RE.match(line)
113
+ # fallback path for binary files (no +++ line follows)
114
+ current = ChangedFile(path=m.group(2) if m else "")
115
+ current.is_python = current.path.endswith(".py")
116
+ old_path = ""
117
+ elif current is None:
118
+ continue
119
+ elif line.startswith("new file mode"):
120
+ current.is_new_file = True
121
+ elif line.startswith("deleted file mode"):
122
+ current.is_deleted = True
123
+ elif line.startswith("rename to "):
124
+ current.path = line[len("rename to "):].strip()
125
+ elif line.startswith("--- "):
126
+ target = line[4:].strip()
127
+ old_path = target[2:] if target.startswith("a/") else target
128
+ elif line.startswith("+++ "):
129
+ target = line[4:].strip()
130
+ if target == "/dev/null":
131
+ current.is_deleted = True
132
+ current.path = old_path
133
+ current.is_python = current.path.endswith(".py")
134
+ else:
135
+ current.path = target[2:] if target.startswith("b/") else target
136
+ current.is_python = current.path.endswith(".py")
137
+ elif line.startswith("@@ "):
138
+ m = _HUNK_RE.match(line)
139
+ if m:
140
+ start = int(m.group(1))
141
+ count = int(m.group(2)) if m.group(2) else 1
142
+ if count > 0:
143
+ current.changed_lines.extend(range(start, start + count))
144
+ elif line.startswith("+") and not line.startswith("+++"):
145
+ added_lines.append(line[1:])
146
+
147
+ flush()
148
+ return result
149
+
150
+
151
+ def _extract_deps(cf: ChangedFile, added_lines: list[str], cwd: str) -> list[str]:
152
+ """Pull new third-party dependency names out of added lines."""
153
+ if cf.is_deleted:
154
+ return []
155
+ name = cf.path
156
+ if name.endswith(".py"):
157
+ return _extract_python_imports(added_lines, cwd)
158
+ if name.endswith("requirements.txt") or "requirements" in Path(name).name:
159
+ return _extract_requirements(added_lines)
160
+ if name.endswith("pyproject.toml"):
161
+ return _extract_pyproject_deps(added_lines)
162
+ return []
163
+
164
+
165
+ def _extract_python_imports(lines: list[str], cwd: str) -> list[str]:
166
+ local = _local_top_level_modules(cwd)
167
+ deps: list[str] = []
168
+ for line in lines:
169
+ m = _IMPORT_RE.match(line)
170
+ if not m:
171
+ continue
172
+ module = (m.group(1) or m.group(2)).split(".")[0]
173
+ if module in _stdlib_names() or module in local:
174
+ continue
175
+ package = _IMPORT_TO_PACKAGE.get(module, module)
176
+ if package not in deps:
177
+ deps.append(package)
178
+ return deps
179
+
180
+
181
+ def _extract_requirements(lines: list[str]) -> list[str]:
182
+ deps: list[str] = []
183
+ for line in lines:
184
+ line = line.strip()
185
+ if not line or line.startswith("#") or line.startswith("-"):
186
+ continue
187
+ m = _REQ_LINE_RE.match(line)
188
+ if m and m.group(1) not in deps:
189
+ deps.append(m.group(1))
190
+ return deps
191
+
192
+
193
+ def _extract_pyproject_deps(lines: list[str]) -> list[str]:
194
+ deps: list[str] = []
195
+ for line in lines:
196
+ stripped = line.strip()
197
+ if not stripped.startswith(('"', "'")) and "=" in stripped:
198
+ # a key = ... line (e.g. dependencies = ["a", "b"]) — still parse quotes
199
+ pass
200
+ for m in _TOML_DEP_RE.finditer(stripped):
201
+ token = m.group(1)
202
+ # skip version numbers and obvious non-packages
203
+ if token[0].isdigit() or token in ("toml",):
204
+ continue
205
+ if token not in deps:
206
+ deps.append(token)
207
+ return deps
208
+
209
+
210
+ _STDLIB: frozenset[str] | None = None
211
+
212
+
213
+ def _stdlib_names() -> frozenset[str]:
214
+ global _STDLIB
215
+ if _STDLIB is None:
216
+ _STDLIB = frozenset(sys.stdlib_module_names)
217
+ return _STDLIB
218
+
219
+
220
+ def _local_top_level_modules(root: str) -> set[str]:
221
+ """Top-level importable names that live in this project (not PyPI)."""
222
+ mods: set[str] = set()
223
+ root_path = Path(root)
224
+ if not root_path.is_dir():
225
+ return mods
226
+ for child in root_path.iterdir():
227
+ if child.name.startswith("."):
228
+ continue
229
+ if child.is_dir():
230
+ if (child / "__init__.py").exists() or any(child.glob("*.py")):
231
+ mods.add(child.name)
232
+ if child.name in ("src", "lib"): # src-layout
233
+ for sub in child.iterdir():
234
+ if sub.is_dir() and (
235
+ (sub / "__init__.py").exists() or any(sub.glob("*.py"))
236
+ ):
237
+ mods.add(sub.name)
238
+ elif sub.suffix == ".py":
239
+ mods.add(sub.stem)
240
+ elif child.suffix == ".py":
241
+ mods.add(child.stem)
242
+ return mods