isitbroken 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.
@@ -0,0 +1,284 @@
1
+ """Run each repo's test suite — cached so unchanged repos are instant.
2
+
3
+ The cache key is (commit hash, deps mtime, worktree fingerprint): any edit
4
+ to tracked content, untracked source files, or dependency manifests
5
+ invalidates it, so a stale pass can never mask a real failure.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ import time
16
+ from itertools import islice
17
+ from pathlib import Path
18
+
19
+ from ..cache import Cache
20
+ from .base import Check, CheckResult, Repo, Status
21
+
22
+ # Bump when run commands or result semantics change (invalidates all cache).
23
+ # v2: --tb=short (classification needs exception text), deps-not-installed and
24
+ # no-tests-collected became WARN instead of FAIL
25
+ CACHE_VERSION = "tests-v2"
26
+
27
+ # Manifests whose mtime participates in the cache key.
28
+ DEPS_FILES = (
29
+ "uv.lock",
30
+ "poetry.lock",
31
+ "Pipfile.lock",
32
+ "requirements.txt",
33
+ "requirements-dev.txt",
34
+ "pyproject.toml",
35
+ "setup.py",
36
+ "setup.cfg",
37
+ "tox.ini",
38
+ )
39
+
40
+ # Test-run artifacts that must not perturb the worktree fingerprint.
41
+ ARTIFACT_DIRS = frozenset(
42
+ {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".nox"}
43
+ )
44
+ ARTIFACT_SUFFIXES = (".pyc", ".pyo")
45
+
46
+ TEST_TIMEOUT = 120.0
47
+ _COUNT_RE = re.compile(r"(\d+)\s+(passed|failed|errors?|skipped|xfailed|xpassed)")
48
+ _MISSING_MODULE_RE = re.compile(r"No module named ['\"]([^'\"]+)['\"]")
49
+ _PYTEST_MISSING = "No module named pytest"
50
+
51
+
52
+ class TestsCheck(Check):
53
+ """Detect and run a repo's declared test suite (tox / make test / pytest)."""
54
+
55
+ name = "tests"
56
+ __test__ = False # not a pytest test class
57
+
58
+ def __init__(self, cache: Cache | None = None, timeout: float = TEST_TIMEOUT) -> None:
59
+ self.cache = cache
60
+ self.timeout = timeout
61
+
62
+ def run(self, repo: Repo) -> CheckResult:
63
+ commit = self._head(repo)
64
+ if commit is None:
65
+ # Unborn repo: no key to cache on; detection is cheap anyway.
66
+ return self._detect_and_run(repo)
67
+
68
+ key = self._cache_key(repo, commit)
69
+ if self.cache is not None:
70
+ hit = self.cache.get(str(repo.path), key)
71
+ if hit is not None:
72
+ return CheckResult(
73
+ self.name,
74
+ Status(hit.status),
75
+ hit.summary,
76
+ {**hit.details, "cached": True},
77
+ )
78
+
79
+ result = self._detect_and_run(repo)
80
+ if self.cache is not None:
81
+ self.cache.put(
82
+ str(repo.path), key, result.status.value, result.summary, result.details
83
+ )
84
+ return result
85
+
86
+ # -- suite detection ---------------------------------------------------
87
+
88
+ def _detect(self, root: Path) -> tuple[str, list[str]] | None:
89
+ if (root / "tox.ini").exists():
90
+ return "tox", ["tox"]
91
+ makefile = next(
92
+ (root / n for n in ("Makefile", "makefile", "GNUmakefile") if (root / n).is_file()),
93
+ None,
94
+ )
95
+ if makefile is not None and _make_test_target(makefile):
96
+ return "make", ["make", "test"]
97
+ if _pytest_detectable(root):
98
+ return "pytest", [
99
+ *_pytest_python(root),
100
+ "-m",
101
+ "pytest",
102
+ "-q",
103
+ "--tb=short", # need the exception text to classify failures
104
+ "-p",
105
+ "no:cacheprovider",
106
+ ]
107
+ return None
108
+
109
+ def _detect_and_run(self, repo: Repo) -> CheckResult:
110
+ started = time.monotonic()
111
+ plan = self._detect(repo.path)
112
+ if plan is None:
113
+ return CheckResult(self.name, Status.SKIP, "no tests detected", {"cached": False})
114
+ runner, cmd = plan
115
+ details: dict = {"runner": runner, "cached": False}
116
+
117
+ try:
118
+ proc = subprocess.run(
119
+ cmd,
120
+ cwd=repo.path,
121
+ capture_output=True,
122
+ text=True,
123
+ errors="replace",
124
+ timeout=self.timeout,
125
+ )
126
+ except FileNotFoundError:
127
+ return CheckResult(
128
+ self.name, Status.WARN, f"{runner} not installed", details
129
+ )
130
+ except subprocess.TimeoutExpired:
131
+ details["timeout"] = True
132
+ return CheckResult(
133
+ self.name,
134
+ Status.FAIL,
135
+ f"timed out after {self.timeout:g}s",
136
+ details,
137
+ )
138
+ except OSError as exc:
139
+ return CheckResult(
140
+ self.name, Status.ERROR, f"cannot run {runner}: {exc}"[:160], details
141
+ )
142
+
143
+ output = (proc.stdout or "") + (proc.stderr or "")
144
+ details.update(
145
+ exit_code=proc.returncode,
146
+ duration_s=round(time.monotonic() - started, 2),
147
+ output_tail=output[-4000:],
148
+ )
149
+ if runner == "pytest" and _PYTEST_MISSING in output:
150
+ return CheckResult(self.name, Status.WARN, "pytest not installed", details)
151
+ # A fresh clone whose deps aren't installed dies at collection with
152
+ # ModuleNotFoundError — that's "can't verify", not "tests are broken".
153
+ missing = _MISSING_MODULE_RE.search(output)
154
+ if missing and proc.returncode != 0:
155
+ module = missing.group(1).split(".")[0]
156
+ return CheckResult(
157
+ self.name,
158
+ Status.WARN,
159
+ f"deps not installed (missing {module})",
160
+ details,
161
+ )
162
+ if proc.returncode == 0:
163
+ return CheckResult(self.name, Status.PASS, _counts(output) or "passed", details)
164
+ if proc.returncode == 5:
165
+ # pytest's "no tests collected" — nothing failed, nothing verified
166
+ return CheckResult(
167
+ self.name, Status.WARN, "no tests collected", details
168
+ )
169
+ return CheckResult(
170
+ self.name,
171
+ Status.FAIL,
172
+ _counts(output) or f"failed (exit {proc.returncode})",
173
+ details,
174
+ )
175
+
176
+ # -- cache key ---------------------------------------------------------
177
+
178
+ def _head(self, repo: Repo) -> str | None:
179
+ proc = subprocess.run(
180
+ ["git", "-C", str(repo.path), "rev-parse", "HEAD"],
181
+ capture_output=True,
182
+ text=True,
183
+ timeout=15,
184
+ )
185
+ return proc.stdout.strip() if proc.returncode == 0 else None
186
+
187
+ def _cache_key(self, repo: Repo, commit: str) -> str:
188
+ digest = hashlib.sha256()
189
+ digest.update(
190
+ f"{CACHE_VERSION}\0{commit}\0{self._deps_mtime(repo.path)}\0".encode()
191
+ )
192
+ digest.update(self._fingerprint(repo).encode())
193
+ return digest.hexdigest()
194
+
195
+ @staticmethod
196
+ def _deps_mtime(root: Path) -> int:
197
+ newest = 0
198
+ for name in DEPS_FILES:
199
+ try:
200
+ newest = max(newest, int((root / name).stat().st_mtime))
201
+ except OSError:
202
+ continue
203
+ return newest
204
+
205
+ @staticmethod
206
+ def _fingerprint(repo: Repo) -> str:
207
+ """Hash of tracked changes + untracked source files (path/size/mtime)."""
208
+ digest = hashlib.sha256()
209
+ diff = subprocess.run(
210
+ ["git", "-C", str(repo.path), "diff", "HEAD", "--no-ext-diff", "--no-color"],
211
+ capture_output=True,
212
+ timeout=15,
213
+ )
214
+ if diff.returncode == 0:
215
+ digest.update(diff.stdout)
216
+ others = subprocess.run(
217
+ ["git", "-C", str(repo.path), "ls-files", "--others", "--exclude-standard", "-z"],
218
+ capture_output=True,
219
+ timeout=15,
220
+ )
221
+ if others.returncode == 0:
222
+ for raw in sorted(others.stdout.split(b"\0")):
223
+ if not raw:
224
+ continue
225
+ rel = os.fsdecode(raw)
226
+ parts = Path(rel).parts
227
+ if any(p in ARTIFACT_DIRS for p in parts):
228
+ continue
229
+ if rel.endswith(ARTIFACT_SUFFIXES):
230
+ continue
231
+ try:
232
+ stat = (repo.path / rel).stat()
233
+ except OSError:
234
+ continue
235
+ digest.update(f"{rel}\0{stat.st_size}\0{stat.st_mtime_ns}\0".encode())
236
+ return digest.hexdigest()
237
+
238
+
239
+ # -- detection helpers ------------------------------------------------------
240
+
241
+
242
+ def _make_test_target(path: Path) -> bool:
243
+ try:
244
+ text = path.read_text(errors="replace")
245
+ except OSError:
246
+ return False
247
+ return any(re.match(r"^[ \t]*test[ \t]*::?", line) for line in text.splitlines())
248
+
249
+
250
+ def _pytest_detectable(root: Path) -> bool:
251
+ if (root / "pytest.ini").exists() or (root / "conftest.py").exists():
252
+ return True
253
+ pyproject = root / "pyproject.toml"
254
+ if pyproject.is_file() and "[tool.pytest" in pyproject.read_text(errors="replace"):
255
+ return True
256
+ setup_cfg = root / "setup.cfg"
257
+ if setup_cfg.is_file() and "[tool:pytest]" in setup_cfg.read_text(errors="replace"):
258
+ return True
259
+ for pattern in ("test_*.py", "*_test.py"):
260
+ if any(root.glob(pattern)):
261
+ return True
262
+ for dirname in ("tests", "test"):
263
+ directory = root / dirname
264
+ if directory.is_dir() and any(islice(directory.rglob(pattern), 5)):
265
+ return True
266
+ return False
267
+
268
+
269
+ def _pytest_python(root: Path) -> list[str]:
270
+ for candidate in (root / ".venv/bin/python", root / ".venv/bin/python3"):
271
+ if candidate.exists():
272
+ return [str(candidate)]
273
+ return [sys.executable]
274
+
275
+
276
+ def _counts(output: str) -> str:
277
+ """Extract '3 failed, 10 passed' style counts from the tail of the output."""
278
+ found = _COUNT_RE.findall(output[-2000:])
279
+ parts: list[str] = []
280
+ for number, label in found:
281
+ item = f"{number} {label}"
282
+ if item not in parts:
283
+ parts.append(item)
284
+ return ", ".join(parts)
isitbroken/cli.py ADDED
@@ -0,0 +1,164 @@
1
+ """Command line interface for isitbroken."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import __version__
10
+ from .cache import Cache
11
+ from .checks import DepsCheck, GapsCheck, GitCheck, TestsCheck
12
+ from .checks.base import Check, Status
13
+ from .discover import discover
14
+ from .render import render_json, render_table
15
+ from .runner import run_all
16
+
17
+ COMMANDS = frozenset({"doctor", "check"})
18
+ _NO_INJECT = frozenset({"-h", "--help", "--version"})
19
+
20
+
21
+ def build_parser() -> argparse.ArgumentParser:
22
+ parser = argparse.ArgumentParser(
23
+ prog="isitbroken",
24
+ description=(
25
+ "One command that tells you which of your side projects are "
26
+ "actually broken \u2014 not just dirty."
27
+ ),
28
+ )
29
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
30
+ sub = parser.add_subparsers(dest="command")
31
+
32
+ doctor = sub.add_parser("doctor", help="scan repos under a path and report health (default)")
33
+ _add_scan_args(doctor, default_path=".")
34
+
35
+ check = sub.add_parser("check", help="check a single repo (or a folder of them)")
36
+ _add_scan_args(check, default_path=None)
37
+
38
+ return parser
39
+
40
+
41
+ def _add_scan_args(parser: argparse.ArgumentParser, default_path: str | None) -> None:
42
+ if default_path is not None:
43
+ parser.add_argument(
44
+ "path",
45
+ nargs="?",
46
+ default=default_path,
47
+ help="directory to scan (default: current directory)",
48
+ )
49
+ else:
50
+ parser.add_argument("path", help="repo or directory to check")
51
+ parser.add_argument("--json", action="store_true", help="machine-readable JSON output")
52
+ parser.add_argument(
53
+ "--stale-days",
54
+ type=int,
55
+ default=30,
56
+ metavar="N",
57
+ help="days since last commit before a repo is stale (default: 30)",
58
+ )
59
+ parser.add_argument(
60
+ "--strict",
61
+ action="store_true",
62
+ help="exit 1 on warnings too, not just failures",
63
+ )
64
+ parser.add_argument("--jobs", type=int, default=None, metavar="N", help="parallel workers (default: auto)")
65
+ parser.add_argument(
66
+ "--timeout",
67
+ type=float,
68
+ default=120,
69
+ metavar="S",
70
+ help="per-check timeout in seconds (default: 120)",
71
+ )
72
+ parser.add_argument(
73
+ "--attention",
74
+ action="store_true",
75
+ help="only show repos that need attention (warn/fail/error)",
76
+ )
77
+ parser.add_argument(
78
+ "--no-tests",
79
+ action="store_true",
80
+ help="skip running test suites",
81
+ )
82
+ parser.add_argument(
83
+ "--no-deps",
84
+ action="store_true",
85
+ help="skip the dependency audit (pip-audit / outdated)",
86
+ )
87
+ parser.add_argument(
88
+ "--no-cache",
89
+ action="store_true",
90
+ help="ignore the result cache and re-run everything",
91
+ )
92
+
93
+
94
+ def _normalize_argv(argv: list[str]) -> list[str]:
95
+ """Allow flag-first usage: `isitbroken --json ~/code` -> `doctor --json ~/code`."""
96
+ if not argv:
97
+ return ["doctor"]
98
+ if argv[0] in COMMANDS or argv[0] in _NO_INJECT:
99
+ return argv
100
+ return ["doctor", *argv]
101
+
102
+
103
+ def main(argv: list[str] | None = None) -> int:
104
+ raw = list(sys.argv[1:]) if argv is None else list(argv)
105
+ args = build_parser().parse_args(_normalize_argv(raw))
106
+
107
+ if (err := _validate(args)) is not None:
108
+ print(f"error: {err}", file=sys.stderr)
109
+ return 2
110
+
111
+ path = Path(args.path).expanduser()
112
+ if path.exists() and not path.is_dir():
113
+ print(f"error: not a directory: {path}", file=sys.stderr)
114
+ return 2
115
+ try:
116
+ repos = discover([path])
117
+ except FileNotFoundError as exc:
118
+ print(f"error: {exc}", file=sys.stderr)
119
+ return 2
120
+
121
+ if not repos:
122
+ if args.json:
123
+ print(render_json([], root=str(path.resolve())))
124
+ else:
125
+ print(f"no git repositories found under {path}", file=sys.stderr)
126
+ return 0
127
+
128
+ cache = None if args.no_cache else Cache() # one store, both checks
129
+ checks: list[Check] = [GitCheck(stale_days=args.stale_days)]
130
+ if not args.no_tests:
131
+ checks.append(TestsCheck(cache=cache, timeout=args.timeout))
132
+ if not args.no_deps:
133
+ checks.append(DepsCheck(cache=cache, timeout=args.timeout))
134
+ checks.append(GapsCheck())
135
+ # batch timeout gets slack over the per-check timeout so checks classify
136
+ # their own timeouts (FAIL) instead of the runner (ERROR)
137
+ reports = run_all(repos, checks, jobs=args.jobs, timeout=args.timeout + 10)
138
+
139
+ if args.attention:
140
+ reports = [r for r in reports if r.status.rank >= Status.WARN.rank]
141
+
142
+ if args.json:
143
+ print(render_json(reports, root=str(path.resolve())))
144
+ else:
145
+ render_table(reports, title=f"isitbroken \u00b7 {path.resolve()}")
146
+
147
+ failed = any(r.status in (Status.FAIL, Status.ERROR) for r in reports)
148
+ warned = any(r.status is Status.WARN for r in reports)
149
+ return 1 if (failed or (args.strict and warned)) else 0
150
+
151
+
152
+ def _validate(args: argparse.Namespace) -> str | None:
153
+ """Reject hostile/accidental flag values with a usage error (rc=2)."""
154
+ if args.jobs is not None and args.jobs < 1:
155
+ return f"--jobs must be >= 1 (got {args.jobs})"
156
+ if args.timeout <= 0:
157
+ return f"--timeout must be > 0 (got {args.timeout:g})"
158
+ if args.stale_days < 0:
159
+ return f"--stale-days must be >= 0 (got {args.stale_days})"
160
+ return None
161
+
162
+
163
+ if __name__ == "__main__":
164
+ raise SystemExit(main())
isitbroken/discover.py ADDED
@@ -0,0 +1,80 @@
1
+ """Locate git repositories under one or more root paths."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from .checks.base import Repo
9
+
10
+ # Directories never worth descending into when hunting for repos.
11
+ SKIP_DIRS = frozenset(
12
+ {
13
+ ".git",
14
+ ".hg",
15
+ ".svn",
16
+ ".venv",
17
+ "venv",
18
+ "env",
19
+ ".tox",
20
+ ".nox",
21
+ "__pycache__",
22
+ ".mypy_cache",
23
+ ".pytest_cache",
24
+ ".ruff_cache",
25
+ "node_modules",
26
+ "vendor",
27
+ "target",
28
+ "build",
29
+ "dist",
30
+ "site-packages",
31
+ ".cache",
32
+ ".next",
33
+ ".nuxt",
34
+ }
35
+ )
36
+
37
+
38
+ def discover(roots: list[Path]) -> list[Repo]:
39
+ """Return repos found under roots.
40
+
41
+ - A root that is itself a repo yields just that repo.
42
+ - Repos are not descended into, so nested clones and submodules
43
+ don't double-count.
44
+ - Junk directories in SKIP_DIRS are pruned.
45
+ """
46
+ found: list[Repo] = []
47
+ seen: set[Path] = set()
48
+
49
+ for root in roots:
50
+ root = Path(root).expanduser().resolve()
51
+ if not root.exists():
52
+ raise FileNotFoundError(f"path does not exist: {root}")
53
+ if (root / ".git").exists():
54
+ _add(found, seen, root)
55
+ continue
56
+ for dirpath, dirnames, _filenames in os.walk(root, followlinks=False):
57
+ current = Path(dirpath)
58
+ if (current / ".git").exists():
59
+ _add(found, seen, current)
60
+ dirnames[:] = [] # never descend into a repo (submodules, nested clones)
61
+ continue
62
+ # current is not a repo: prune junk and catch repo children that
63
+ # os.walk would skip — notably symlinked repos (followlinks=False)
64
+ kept: list[str] = []
65
+ for d in dirnames:
66
+ if d in SKIP_DIRS:
67
+ continue
68
+ if (current / d / ".git").exists():
69
+ _add(found, seen, current / d)
70
+ else:
71
+ kept.append(d)
72
+ dirnames[:] = kept
73
+ return sorted(found, key=lambda r: r.name.lower())
74
+
75
+
76
+ def _add(found: list[Repo], seen: set[Path], path: Path) -> None:
77
+ if path in seen:
78
+ return
79
+ seen.add(path)
80
+ found.append(Repo(path=path, name=path.name))