catchdev 0.1.2__tar.gz → 0.1.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: catchdev
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Tells you what your AI coding agent just broke
5
5
  License: MIT
6
6
  Requires-Python: >=3.9
@@ -11,9 +11,17 @@ Requires-Dist: rich
11
11
  Requires-Dist: click
12
12
  Dynamic: license-file
13
13
 
14
- # catchdev
14
+ <h1 align="center">catchdev</h1>
15
15
 
16
- **Tells you what your AI coding agent just broke.**
16
+ <p align="center">
17
+ <strong>Tells you what your AI coding agent just broke.</strong>
18
+ </p>
19
+
20
+ <p align="center">
21
+ <a href="https://github.com/sponsors/soham131345">
22
+ <img src="https://img.shields.io/badge/%E2%9D%A4-Sponsor-pink?style=for-the-badge&logo=github" alt="Sponsor soham131345">
23
+ </a>
24
+ </p>
17
25
 
18
26
  ![catch flags a real 4-month Flask regression in 2 seconds](demo/demo.gif)
19
27
 
@@ -1,6 +1,14 @@
1
- # catchdev
1
+ <h1 align="center">catchdev</h1>
2
2
 
3
- **Tells you what your AI coding agent just broke.**
3
+ <p align="center">
4
+ <strong>Tells you what your AI coding agent just broke.</strong>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/sponsors/soham131345">
9
+ <img src="https://img.shields.io/badge/%E2%9D%A4-Sponsor-pink?style=for-the-badge&logo=github" alt="Sponsor soham131345">
10
+ </a>
11
+ </p>
4
12
 
5
13
  ![catch flags a real 4-month Flask regression in 2 seconds](demo/demo.gif)
6
14
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "catchdev"
3
- version = "0.1.2"
3
+ version = "0.1.3"
4
4
  description = "Tells you what your AI coding agent just broke"
5
5
  readme = "README.md"
6
6
  license = {text = "MIT"}
@@ -1,83 +1,83 @@
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
- # Windows consoles default to cp1252; make every printable we emit
30
- # (✓, ✗, ⚠, ─, …) survive regardless of the terminal's codepage.
31
- for stream in (sys.stdout, sys.stderr):
32
- try:
33
- stream.reconfigure(encoding="utf-8", errors="replace")
34
- except Exception:
35
- pass
36
-
37
- # In CI pull requests, diff against the PR base, not HEAD~1
38
- # (squash merges break HEAD~1). GITHUB_BASE_REF is set by GitHub Actions.
39
- base_ref_env = os.environ.get("GITHUB_BASE_REF")
40
- if commit is None and base_ref_env and not staged:
41
- commit = f"origin/{base_ref_env}"
42
-
43
- # 1. Get the diff
44
- try:
45
- diff = differ.get_diff(staged=staged or not commit, commit=commit)
46
- except differ.GitError as e:
47
- report.err_console.print(f"[red]✗ {e}[/red]")
48
- sys.exit(2)
49
-
50
- if not diff.files:
51
- report.console.print("[green]✓ no changes detected[/green]")
52
- sys.exit(0)
53
-
54
- # 2. Map to affected tests
55
- affected = mapper.find_affected_tests(diff)
56
-
57
- # 3. Run tests (baseline = the ref we diffed against)
58
- results = runner.run_tests(
59
- affected, all_tests=all_tests, base_ref=commit or "HEAD"
60
- )
61
-
62
- # 4. Check dependencies
63
- dep_risks = [] if skip_deps else depcheck.check_dependencies(
64
- diff.new_dependencies
65
- )
66
-
67
- # 5. Report (terminal + optional markdown file)
68
- report.print_report(diff, affected, results, dep_risks,
69
- fail_on_suspicious=fail_on_suspicious)
70
- if output:
71
- with open(output, "w", encoding="utf-8") as f:
72
- f.write(report.render_markdown(
73
- diff, affected, results, dep_risks,
74
- fail_on_suspicious=fail_on_suspicious,
75
- ))
76
-
77
- # 6. Exit code
78
- sys.exit(report.get_exit_code(results, dep_risks,
79
- fail_on_suspicious=fail_on_suspicious))
80
-
81
-
82
- if __name__ == "__main__":
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
+ # Windows consoles default to cp1252; make every printable we emit
30
+ # (✓, ✗, ⚠, ─, …) survive regardless of the terminal's codepage.
31
+ for stream in (sys.stdout, sys.stderr):
32
+ try:
33
+ stream.reconfigure(encoding="utf-8", errors="replace")
34
+ except Exception:
35
+ pass
36
+
37
+ # In CI pull requests, diff against the PR base, not HEAD~1
38
+ # (squash merges break HEAD~1). GITHUB_BASE_REF is set by GitHub Actions.
39
+ base_ref_env = os.environ.get("GITHUB_BASE_REF")
40
+ if commit is None and base_ref_env and not staged:
41
+ commit = f"origin/{base_ref_env}"
42
+
43
+ # 1. Get the diff
44
+ try:
45
+ diff = differ.get_diff(staged=staged or not commit, commit=commit)
46
+ except differ.GitError as e:
47
+ report.err_console.print(f"[red]✗ {e}[/red]")
48
+ sys.exit(2)
49
+
50
+ if not diff.files:
51
+ report.console.print("[green]✓ no changes detected[/green]")
52
+ sys.exit(0)
53
+
54
+ # 2. Map to affected tests
55
+ affected = mapper.find_affected_tests(diff)
56
+
57
+ # 3. Run tests (baseline = the ref we diffed against)
58
+ results = runner.run_tests(
59
+ affected, all_tests=all_tests, base_ref=commit or "HEAD"
60
+ )
61
+
62
+ # 4. Check dependencies
63
+ dep_risks = [] if skip_deps else depcheck.check_dependencies(
64
+ diff.new_dependencies
65
+ )
66
+
67
+ # 5. Report (terminal + optional markdown file)
68
+ report.print_report(diff, affected, results, dep_risks,
69
+ fail_on_suspicious=fail_on_suspicious)
70
+ if output:
71
+ with open(output, "w", encoding="utf-8") as f:
72
+ f.write(report.render_markdown(
73
+ diff, affected, results, dep_risks,
74
+ fail_on_suspicious=fail_on_suspicious,
75
+ ))
76
+
77
+ # 6. Exit code
78
+ sys.exit(report.get_exit_code(results, dep_risks,
79
+ fail_on_suspicious=fail_on_suspicious))
80
+
81
+
82
+ if __name__ == "__main__":
83
83
  main()
@@ -1,122 +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
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