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.
- isitbroken/__init__.py +3 -0
- isitbroken/__main__.py +6 -0
- isitbroken/cache.py +92 -0
- isitbroken/checks/__init__.py +18 -0
- isitbroken/checks/base.py +92 -0
- isitbroken/checks/deps.py +245 -0
- isitbroken/checks/gaps.py +61 -0
- isitbroken/checks/git.py +107 -0
- isitbroken/checks/tests.py +284 -0
- isitbroken/cli.py +164 -0
- isitbroken/discover.py +80 -0
- isitbroken/render.py +238 -0
- isitbroken/runner.py +67 -0
- isitbroken-0.1.0.dist-info/METADATA +113 -0
- isitbroken-0.1.0.dist-info/RECORD +19 -0
- isitbroken-0.1.0.dist-info/WHEEL +4 -0
- isitbroken-0.1.0.dist-info/entry_points.txt +3 -0
- isitbroken-0.1.0.dist-info/licenses/LICENSE +202 -0
- isitbroken-0.1.0.dist-info/licenses/NOTICE +2 -0
isitbroken/__init__.py
ADDED
isitbroken/__main__.py
ADDED
isitbroken/cache.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""SQLite result cache: unchanged repos skip their test suite entirely.
|
|
2
|
+
|
|
3
|
+
Key material lives in the checks (commit hash + deps mtime + worktree
|
|
4
|
+
fingerprint); this module only stores and retrieves verdicts.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sqlite3
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
SCHEMA = """
|
|
17
|
+
CREATE TABLE IF NOT EXISTS test_results (
|
|
18
|
+
repo TEXT NOT NULL,
|
|
19
|
+
cache_key TEXT NOT NULL,
|
|
20
|
+
status TEXT NOT NULL,
|
|
21
|
+
summary TEXT NOT NULL,
|
|
22
|
+
details TEXT NOT NULL,
|
|
23
|
+
created_at REAL NOT NULL,
|
|
24
|
+
PRIMARY KEY (repo, cache_key)
|
|
25
|
+
)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def default_cache_path() -> Path:
|
|
30
|
+
override = os.environ.get("ISITBROKEN_CACHE")
|
|
31
|
+
if override:
|
|
32
|
+
return Path(override).expanduser()
|
|
33
|
+
base = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
|
|
34
|
+
return base / "isitbroken" / "cache.sqlite3"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(slots=True)
|
|
38
|
+
class CachedResult:
|
|
39
|
+
status: str
|
|
40
|
+
summary: str
|
|
41
|
+
details: dict
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Cache:
|
|
45
|
+
def __init__(self, path: Path | str | None = None) -> None:
|
|
46
|
+
self.path = Path(path) if path is not None else default_cache_path()
|
|
47
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
conn = self._connect()
|
|
49
|
+
try:
|
|
50
|
+
with conn:
|
|
51
|
+
conn.executescript(SCHEMA)
|
|
52
|
+
finally:
|
|
53
|
+
conn.close()
|
|
54
|
+
|
|
55
|
+
def _connect(self) -> sqlite3.Connection:
|
|
56
|
+
conn = sqlite3.connect(self.path, timeout=10)
|
|
57
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
58
|
+
return conn
|
|
59
|
+
|
|
60
|
+
def get(self, repo: str, cache_key: str) -> CachedResult | None:
|
|
61
|
+
conn = self._connect()
|
|
62
|
+
try:
|
|
63
|
+
row = conn.execute(
|
|
64
|
+
"SELECT status, summary, details FROM test_results "
|
|
65
|
+
"WHERE repo = ? AND cache_key = ?",
|
|
66
|
+
(repo, cache_key),
|
|
67
|
+
).fetchone()
|
|
68
|
+
finally:
|
|
69
|
+
conn.close()
|
|
70
|
+
if row is None:
|
|
71
|
+
return None
|
|
72
|
+
return CachedResult(status=row[0], summary=row[1], details=json.loads(row[2]))
|
|
73
|
+
|
|
74
|
+
def put(
|
|
75
|
+
self,
|
|
76
|
+
repo: str,
|
|
77
|
+
cache_key: str,
|
|
78
|
+
status: str,
|
|
79
|
+
summary: str,
|
|
80
|
+
details: dict,
|
|
81
|
+
) -> None:
|
|
82
|
+
conn = self._connect()
|
|
83
|
+
try:
|
|
84
|
+
with conn:
|
|
85
|
+
conn.execute(
|
|
86
|
+
"INSERT OR REPLACE INTO test_results "
|
|
87
|
+
"(repo, cache_key, status, summary, details, created_at) "
|
|
88
|
+
"VALUES (?, ?, ?, ?, ?, ?)",
|
|
89
|
+
(repo, cache_key, status, summary, json.dumps(details), time.time()),
|
|
90
|
+
)
|
|
91
|
+
finally:
|
|
92
|
+
conn.close()
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from .base import Check, CheckResult, Repo, RepoReport, Status, worst
|
|
2
|
+
from .deps import DepsCheck
|
|
3
|
+
from .gaps import GapsCheck
|
|
4
|
+
from .git import GitCheck
|
|
5
|
+
from .tests import TestsCheck
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Check",
|
|
9
|
+
"CheckResult",
|
|
10
|
+
"DepsCheck",
|
|
11
|
+
"GapsCheck",
|
|
12
|
+
"GitCheck",
|
|
13
|
+
"Repo",
|
|
14
|
+
"RepoReport",
|
|
15
|
+
"Status",
|
|
16
|
+
"TestsCheck",
|
|
17
|
+
"worst",
|
|
18
|
+
]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Check plugin contract: every check is a small class returning a CheckResult."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Status(StrEnum):
|
|
12
|
+
"""Outcome of a single check. Severity ordering lives in `rank`."""
|
|
13
|
+
|
|
14
|
+
PASS = "pass"
|
|
15
|
+
SKIP = "skip"
|
|
16
|
+
WARN = "warn"
|
|
17
|
+
FAIL = "fail"
|
|
18
|
+
ERROR = "error"
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def rank(self) -> int:
|
|
22
|
+
return _RANK[self]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_RANK = {
|
|
26
|
+
Status.PASS: 0,
|
|
27
|
+
Status.SKIP: 1,
|
|
28
|
+
Status.WARN: 2,
|
|
29
|
+
Status.FAIL: 3,
|
|
30
|
+
Status.ERROR: 4,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(slots=True)
|
|
35
|
+
class CheckResult:
|
|
36
|
+
name: str
|
|
37
|
+
status: Status
|
|
38
|
+
summary: str = ""
|
|
39
|
+
details: dict = field(default_factory=dict)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def worst(results: list[CheckResult]) -> Status:
|
|
43
|
+
"""The most severe status among results (PASS when there are none).
|
|
44
|
+
|
|
45
|
+
SKIP never outranks a real verdict: a repo with passing tests and one
|
|
46
|
+
inapplicable check (e.g. no deps to audit) is *ok*, not "skipped".
|
|
47
|
+
Only when every check skipped is the overall status SKIP.
|
|
48
|
+
"""
|
|
49
|
+
if not results:
|
|
50
|
+
return Status.PASS
|
|
51
|
+
meaningful = [r.status for r in results if r.status is not Status.SKIP]
|
|
52
|
+
if not meaningful:
|
|
53
|
+
return Status.SKIP
|
|
54
|
+
return max(meaningful, key=lambda s: s.rank)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(slots=True, frozen=True)
|
|
58
|
+
class Repo:
|
|
59
|
+
path: Path
|
|
60
|
+
name: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(slots=True)
|
|
64
|
+
class RepoReport:
|
|
65
|
+
repo: Repo
|
|
66
|
+
results: list[CheckResult]
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def status(self) -> Status:
|
|
70
|
+
return worst(self.results)
|
|
71
|
+
|
|
72
|
+
def get(self, name: str) -> CheckResult | None:
|
|
73
|
+
for result in self.results:
|
|
74
|
+
if result.name == name:
|
|
75
|
+
return result
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def branch(self) -> str:
|
|
80
|
+
git = self.get("git")
|
|
81
|
+
if git is not None:
|
|
82
|
+
return str(git.details.get("branch") or "—")
|
|
83
|
+
return "—"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Check(ABC):
|
|
87
|
+
"""Inspect one repo and report a CheckResult. Implementations must not raise."""
|
|
88
|
+
|
|
89
|
+
name: str = "check"
|
|
90
|
+
|
|
91
|
+
@abstractmethod
|
|
92
|
+
def run(self, repo: Repo) -> CheckResult: ...
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Dependency audit: pip-audit vulnerabilities + outdated packages in the repo venv.
|
|
2
|
+
|
|
3
|
+
Supports requirements.txt (`-r`) and project-level audits (pip-audit reads
|
|
4
|
+
pyproject.toml / Pipfile / poetry.lock from the project path). The audit
|
|
5
|
+
result is cached (keyed on the content of every dependency manifest found)
|
|
6
|
+
so repeated scans don't re-hit the OSV database; the outdated scan is local
|
|
7
|
+
and cheap, so it always re-runs.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from ..cache import Cache
|
|
21
|
+
from .base import Check, CheckResult, Repo, Status
|
|
22
|
+
|
|
23
|
+
# Bump whenever key derivation or result semantics change.
|
|
24
|
+
# v3: multi-manifest key (pyproject/Pipfile/poetry included), audited-count
|
|
25
|
+
CACHE_VERSION = "deps-v3"
|
|
26
|
+
|
|
27
|
+
# pip-audit logs failures as "ERROR:pip_audit._cli:<message>"
|
|
28
|
+
_LOGGER_PREFIX = re.compile(r"^ERROR:pip_audit\.\w+:")
|
|
29
|
+
|
|
30
|
+
# Files that declare dependencies, in the order they are preferred.
|
|
31
|
+
MANIFESTS = (
|
|
32
|
+
"requirements.txt",
|
|
33
|
+
"pyproject.toml",
|
|
34
|
+
"Pipfile",
|
|
35
|
+
"poetry.lock",
|
|
36
|
+
"setup.py",
|
|
37
|
+
"setup.cfg",
|
|
38
|
+
)
|
|
39
|
+
AUDIT_TIMEOUT = 120.0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AuditError(RuntimeError):
|
|
43
|
+
"""pip-audit could not produce a parseable result."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DepsCheck(Check):
|
|
47
|
+
"""FAIL on known vulnerabilities, WARN on outdated packages."""
|
|
48
|
+
|
|
49
|
+
name = "deps"
|
|
50
|
+
|
|
51
|
+
def __init__(self, cache: Cache | None = None, timeout: float = AUDIT_TIMEOUT) -> None:
|
|
52
|
+
self.cache = cache
|
|
53
|
+
self.timeout = timeout
|
|
54
|
+
|
|
55
|
+
def run(self, repo: Repo) -> CheckResult:
|
|
56
|
+
manifests = [repo.path / n for n in MANIFESTS if (repo.path / n).is_file()]
|
|
57
|
+
outdated = self._outdated(repo)
|
|
58
|
+
details: dict = {}
|
|
59
|
+
if outdated is not None:
|
|
60
|
+
details["outdated"] = len(outdated)
|
|
61
|
+
|
|
62
|
+
if not manifests and outdated is None:
|
|
63
|
+
return CheckResult(self.name, Status.SKIP, "no Python deps detected", details)
|
|
64
|
+
|
|
65
|
+
vulns: list[str] | None = None
|
|
66
|
+
audited: int | None = None
|
|
67
|
+
audit_error: str | None = None
|
|
68
|
+
|
|
69
|
+
if manifests:
|
|
70
|
+
if not self._pip_audit_available():
|
|
71
|
+
audit_error = "pip-audit not installed"
|
|
72
|
+
else:
|
|
73
|
+
try:
|
|
74
|
+
vulns, audited = self._cached_audit(repo, manifests)
|
|
75
|
+
details["manifest"] = manifests[0].name
|
|
76
|
+
except AuditError as exc:
|
|
77
|
+
audit_error = str(exc)
|
|
78
|
+
if vulns is not None:
|
|
79
|
+
details["vulnerabilities"] = vulns
|
|
80
|
+
details["audited"] = audited
|
|
81
|
+
|
|
82
|
+
# Verdict: vulnerabilities beat everything; an empty audit is honest
|
|
83
|
+
# "we couldn't check", not "no known vulnerabilities".
|
|
84
|
+
if vulns:
|
|
85
|
+
return CheckResult(
|
|
86
|
+
self.name, Status.FAIL, f"{len(vulns)} vulnerabilities", details
|
|
87
|
+
)
|
|
88
|
+
empty = vulns is not None and not audited
|
|
89
|
+
if empty and outdated:
|
|
90
|
+
details["audit_note"] = "no auditable dependencies"
|
|
91
|
+
return CheckResult(
|
|
92
|
+
self.name, Status.WARN, f"{len(outdated)} outdated", details
|
|
93
|
+
)
|
|
94
|
+
if empty or (audit_error and not outdated):
|
|
95
|
+
reason = "no auditable dependencies" if empty else audit_error
|
|
96
|
+
return CheckResult(self.name, Status.SKIP, reason, details)
|
|
97
|
+
if outdated:
|
|
98
|
+
if audit_error:
|
|
99
|
+
details["audit_skipped"] = audit_error
|
|
100
|
+
return CheckResult(
|
|
101
|
+
self.name, Status.WARN, f"{len(outdated)} outdated", details
|
|
102
|
+
)
|
|
103
|
+
return CheckResult(self.name, Status.PASS, "no known vulnerabilities", details)
|
|
104
|
+
|
|
105
|
+
# -- vulnerability audit ----------------------------------------------
|
|
106
|
+
|
|
107
|
+
def _pip_audit_cmd(self) -> str | None:
|
|
108
|
+
"""Locate pip-audit: prefer the sibling of the running interpreter.
|
|
109
|
+
|
|
110
|
+
`uv tool install` / venv installs put pip-audit in the same bin dir
|
|
111
|
+
as the isitbroken script, but that dir is not necessarily on $PATH.
|
|
112
|
+
"""
|
|
113
|
+
# no .resolve(): venv pythons are symlinks to a base interpreter,
|
|
114
|
+
# and the sibling console scripts live next to the venv path
|
|
115
|
+
sibling = Path(sys.executable).parent / "pip-audit"
|
|
116
|
+
if sibling.exists():
|
|
117
|
+
return str(sibling)
|
|
118
|
+
return shutil.which("pip-audit")
|
|
119
|
+
|
|
120
|
+
def _pip_audit_available(self) -> bool:
|
|
121
|
+
return self._pip_audit_cmd() is not None
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def _key(manifests: list[Path]) -> str:
|
|
125
|
+
digest = hashlib.sha256(CACHE_VERSION.encode())
|
|
126
|
+
for manifest in manifests:
|
|
127
|
+
digest.update(b"\0" + manifest.name.encode() + b"\0")
|
|
128
|
+
try:
|
|
129
|
+
digest.update(manifest.read_bytes())
|
|
130
|
+
except OSError:
|
|
131
|
+
digest.update(b"unreadable")
|
|
132
|
+
return digest.hexdigest()
|
|
133
|
+
|
|
134
|
+
def _cached_audit(self, repo: Repo, manifests: list[Path]) -> tuple[list[str], int]:
|
|
135
|
+
key = self._key(manifests)
|
|
136
|
+
if self.cache is not None:
|
|
137
|
+
hit = self.cache.get(str(repo.path), key)
|
|
138
|
+
if hit is not None and "audited" in hit.details:
|
|
139
|
+
return list(hit.details.get("vulnerabilities") or []), int(
|
|
140
|
+
hit.details["audited"]
|
|
141
|
+
)
|
|
142
|
+
vulns, audited = self._audit(repo, manifests)
|
|
143
|
+
if self.cache is not None:
|
|
144
|
+
self.cache.put(
|
|
145
|
+
str(repo.path),
|
|
146
|
+
key,
|
|
147
|
+
"pass",
|
|
148
|
+
"audited",
|
|
149
|
+
{"vulnerabilities": vulns, "audited": audited},
|
|
150
|
+
)
|
|
151
|
+
return vulns, audited
|
|
152
|
+
|
|
153
|
+
def _audit(self, repo: Repo, manifests: list[Path]) -> tuple[list[str], int]:
|
|
154
|
+
cmd = self._pip_audit_cmd()
|
|
155
|
+
if cmd is None: # guarded by _pip_audit_available, but be safe
|
|
156
|
+
raise AuditError("pip-audit not installed")
|
|
157
|
+
primary = manifests[0]
|
|
158
|
+
if primary.name == "requirements.txt":
|
|
159
|
+
target = ["-r", str(primary)]
|
|
160
|
+
else:
|
|
161
|
+
# project mode: pip-audit reads pyproject.toml/Pipfile/poetry.lock
|
|
162
|
+
# (setup.py-only projects fall through to whatever it can parse)
|
|
163
|
+
target = [str(repo.path)]
|
|
164
|
+
proc = self._run(
|
|
165
|
+
cmd,
|
|
166
|
+
*target,
|
|
167
|
+
"--format",
|
|
168
|
+
"json",
|
|
169
|
+
"--progress-spinner",
|
|
170
|
+
"off",
|
|
171
|
+
cwd=repo.path,
|
|
172
|
+
)
|
|
173
|
+
# pip-audit may exit non-zero when vulns are found; trust stdout first.
|
|
174
|
+
try:
|
|
175
|
+
payload = json.loads(proc.stdout)
|
|
176
|
+
except json.JSONDecodeError:
|
|
177
|
+
err = (proc.stderr or proc.stdout or "no output").strip()
|
|
178
|
+
first = err.splitlines()[0] if err else "no output"
|
|
179
|
+
first = _LOGGER_PREFIX.sub("", first).strip() # ERROR:pip_audit._cli:
|
|
180
|
+
if "find a supported project file" in err:
|
|
181
|
+
first = f"pip-audit cannot read {primary.name}-only projects"
|
|
182
|
+
elif "does not contain" in first and "project" in first:
|
|
183
|
+
# tool-config-only root pyproject (monorepos, hatch workspaces)
|
|
184
|
+
first = "pyproject.toml has no [project] section"
|
|
185
|
+
raise AuditError(f"pip-audit failed: {first[:100]}") from None
|
|
186
|
+
names, audited = _vuln_names(payload)
|
|
187
|
+
return names, audited
|
|
188
|
+
|
|
189
|
+
# -- outdated packages -------------------------------------------------
|
|
190
|
+
|
|
191
|
+
def _outdated(self, repo: Repo) -> list[str] | None:
|
|
192
|
+
pip = repo.path / ".venv" / "bin" / "pip"
|
|
193
|
+
if not pip.exists():
|
|
194
|
+
return None
|
|
195
|
+
proc = self._run(
|
|
196
|
+
str(pip), "list", "--outdated", "--format=json", cwd=repo.path
|
|
197
|
+
)
|
|
198
|
+
if proc.returncode != 0:
|
|
199
|
+
return None
|
|
200
|
+
try:
|
|
201
|
+
data = json.loads(proc.stdout)
|
|
202
|
+
except json.JSONDecodeError:
|
|
203
|
+
return None
|
|
204
|
+
return sorted(str(item.get("name", "?")) for item in data)
|
|
205
|
+
|
|
206
|
+
# -- subprocess seam (tests override this) -----------------------------
|
|
207
|
+
|
|
208
|
+
def _run(self, *cmd: str, cwd: Path) -> subprocess.CompletedProcess[str]:
|
|
209
|
+
return subprocess.run(
|
|
210
|
+
list(cmd),
|
|
211
|
+
cwd=cwd,
|
|
212
|
+
capture_output=True,
|
|
213
|
+
text=True,
|
|
214
|
+
errors="replace",
|
|
215
|
+
timeout=self.timeout,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _vuln_names(payload: object) -> tuple[list[str], int]:
|
|
220
|
+
"""pip-audit JSON: a list of deps, or {"dependencies": [...]} in newer versions.
|
|
221
|
+
|
|
222
|
+
Each dep uses "vulnerabilities" (some versions) or "vulns" (others).
|
|
223
|
+
Returns (label list, number of dependencies audited).
|
|
224
|
+
"""
|
|
225
|
+
if isinstance(payload, dict):
|
|
226
|
+
deps = payload.get("dependencies", [])
|
|
227
|
+
elif isinstance(payload, list):
|
|
228
|
+
deps = payload
|
|
229
|
+
else:
|
|
230
|
+
raise AuditError("unexpected pip-audit JSON shape")
|
|
231
|
+
names: list[str] = []
|
|
232
|
+
for dep in deps:
|
|
233
|
+
if not isinstance(dep, dict):
|
|
234
|
+
continue
|
|
235
|
+
dep_name = dep.get("name", "?")
|
|
236
|
+
entries = dep.get("vulnerabilities") or dep.get("vulns") or []
|
|
237
|
+
for vuln in entries:
|
|
238
|
+
if not isinstance(vuln, dict):
|
|
239
|
+
continue
|
|
240
|
+
alias = vuln.get("aliases") or []
|
|
241
|
+
vid = vuln.get("id") or (alias[0] if alias else "?")
|
|
242
|
+
label = f"{dep_name}: {vid}"
|
|
243
|
+
if label not in names:
|
|
244
|
+
names.append(label)
|
|
245
|
+
return names, len(deps)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Project hygiene gaps: missing README / LICENSE / tests.
|
|
2
|
+
|
|
3
|
+
Pure file presence — cheap enough to run on every scan, no cache needed.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from fnmatch import fnmatch
|
|
10
|
+
|
|
11
|
+
from ..discover import SKIP_DIRS
|
|
12
|
+
from .base import Check, CheckResult, Repo, Status
|
|
13
|
+
|
|
14
|
+
README_NAMES = ("README.md", "README.rst", "README.txt", "README", "readme.md")
|
|
15
|
+
LICENSE_NAMES = (
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"LICENSE.md",
|
|
18
|
+
"LICENSE.txt",
|
|
19
|
+
"LICENCE",
|
|
20
|
+
"COPYING",
|
|
21
|
+
"COPYING.md",
|
|
22
|
+
)
|
|
23
|
+
TEST_GLOBS = ("test_*.py", "*_test.py")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class GapsCheck(Check):
|
|
27
|
+
"""WARN listing whatever standard files are missing; PASS when complete."""
|
|
28
|
+
|
|
29
|
+
name = "gaps"
|
|
30
|
+
|
|
31
|
+
def run(self, repo: Repo) -> CheckResult:
|
|
32
|
+
present = {
|
|
33
|
+
"readme": _any_exists(repo, README_NAMES),
|
|
34
|
+
"license": _any_exists(repo, LICENSE_NAMES),
|
|
35
|
+
"tests": _has_tests(repo),
|
|
36
|
+
}
|
|
37
|
+
missing = [key for key, ok in present.items() if not ok]
|
|
38
|
+
details = {"present": present, "missing": missing}
|
|
39
|
+
if missing:
|
|
40
|
+
return CheckResult(
|
|
41
|
+
self.name, Status.WARN, f"missing: {', '.join(missing)}", details
|
|
42
|
+
)
|
|
43
|
+
return CheckResult(self.name, Status.PASS, "complete", details)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _any_exists(repo: Repo, names: tuple[str, ...]) -> bool:
|
|
47
|
+
return any((repo.path / name).exists() for name in names)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _has_tests(repo: Repo) -> bool:
|
|
51
|
+
"""True only when actual test *files* exist — an empty tests/ dir doesn't count.
|
|
52
|
+
|
|
53
|
+
Walks with SKIP_DIRS pruning so caches/venvs are never searched; matches
|
|
54
|
+
any common layout (tests/, src/pkg/tests/, flat test_*.py at the root).
|
|
55
|
+
"""
|
|
56
|
+
for dirpath, dirnames, filenames in os.walk(repo.path, followlinks=False):
|
|
57
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
|
58
|
+
for filename in filenames:
|
|
59
|
+
if any(fnmatch(filename, pattern) for pattern in TEST_GLOBS):
|
|
60
|
+
return True
|
|
61
|
+
return False
|
isitbroken/checks/git.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Git state check: dirty / unpushed / behind / stale / no remote."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from .base import Check, CheckResult, Repo, Status
|
|
9
|
+
|
|
10
|
+
GIT_TIMEOUT = 15 # seconds; local git is fast — this is a hang guard
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GitCheck(Check):
|
|
14
|
+
"""Read-only snapshot of a repo's git health.
|
|
15
|
+
|
|
16
|
+
WARN for anything that needs attention (dirty, unpushed, behind,
|
|
17
|
+
no remote, stale, no commits); PASS when nothing is off.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
name = "git"
|
|
21
|
+
|
|
22
|
+
def __init__(self, stale_days: int = 30) -> None:
|
|
23
|
+
self.stale_days = stale_days
|
|
24
|
+
|
|
25
|
+
def _git(self, repo: Repo, *args: str) -> subprocess.CompletedProcess[str]:
|
|
26
|
+
return subprocess.run(
|
|
27
|
+
["git", "-C", str(repo.path), *args],
|
|
28
|
+
capture_output=True,
|
|
29
|
+
text=True,
|
|
30
|
+
timeout=GIT_TIMEOUT,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def run(self, repo: Repo) -> CheckResult:
|
|
34
|
+
try:
|
|
35
|
+
status = self._git(repo, "status", "--porcelain")
|
|
36
|
+
except FileNotFoundError:
|
|
37
|
+
return CheckResult(self.name, Status.ERROR, "git not found on PATH")
|
|
38
|
+
except subprocess.TimeoutExpired:
|
|
39
|
+
return CheckResult(
|
|
40
|
+
self.name, Status.ERROR, f"git status timed out after {GIT_TIMEOUT}s"
|
|
41
|
+
)
|
|
42
|
+
if status.returncode != 0:
|
|
43
|
+
msg = (status.stderr or status.stdout or "git status failed").strip()
|
|
44
|
+
return CheckResult(self.name, Status.ERROR, msg.splitlines()[0][:120])
|
|
45
|
+
|
|
46
|
+
details: dict = {}
|
|
47
|
+
problems: list[str] = []
|
|
48
|
+
|
|
49
|
+
# Working tree
|
|
50
|
+
dirty = sum(1 for line in status.stdout.splitlines() if line.strip())
|
|
51
|
+
details["dirty"] = dirty
|
|
52
|
+
if dirty:
|
|
53
|
+
problems.append(f"\u25cf{dirty}")
|
|
54
|
+
|
|
55
|
+
# Branch / HEAD
|
|
56
|
+
branch = self._git(repo, "branch", "--show-current").stdout.strip()
|
|
57
|
+
if not branch:
|
|
58
|
+
sha = self._git(repo, "rev-parse", "--short", "HEAD")
|
|
59
|
+
branch = sha.stdout.strip() if sha.returncode == 0 else "(detached)"
|
|
60
|
+
details["branch"] = branch
|
|
61
|
+
|
|
62
|
+
# Remotes & push state
|
|
63
|
+
remotes = self._git(repo, "remote").stdout.split()
|
|
64
|
+
details["has_remote"] = bool(remotes)
|
|
65
|
+
if not remotes:
|
|
66
|
+
problems.append("no remote")
|
|
67
|
+
else:
|
|
68
|
+
upstream = self._git(repo, "rev-parse", "--abbrev-ref", "@{upstream}")
|
|
69
|
+
if upstream.returncode != 0:
|
|
70
|
+
details["ahead"] = None
|
|
71
|
+
details["behind"] = None
|
|
72
|
+
problems.append("no upstream")
|
|
73
|
+
else:
|
|
74
|
+
counts = self._git(
|
|
75
|
+
repo, "rev-list", "--count", "--left-right", "@{upstream}...HEAD"
|
|
76
|
+
)
|
|
77
|
+
if counts.returncode == 0:
|
|
78
|
+
behind_s, ahead_s = counts.stdout.split()
|
|
79
|
+
behind, ahead = int(behind_s), int(ahead_s)
|
|
80
|
+
details["ahead"] = ahead
|
|
81
|
+
details["behind"] = behind
|
|
82
|
+
if ahead and behind:
|
|
83
|
+
problems.append(f"\u21c5 {ahead}\u2191/{behind}\u2193")
|
|
84
|
+
elif ahead:
|
|
85
|
+
problems.append(f"\u2191{ahead}")
|
|
86
|
+
elif behind:
|
|
87
|
+
problems.append(f"\u2193{behind}")
|
|
88
|
+
|
|
89
|
+
# Age / staleness
|
|
90
|
+
log = self._git(repo, "log", "-1", "--format=%ct")
|
|
91
|
+
if log.returncode == 0:
|
|
92
|
+
ts = int(log.stdout.strip())
|
|
93
|
+
age_days = (time.time() - ts) / 86400
|
|
94
|
+
details["last_commit_unix"] = ts
|
|
95
|
+
details["age_days"] = round(age_days, 1)
|
|
96
|
+
details["stale"] = age_days > self.stale_days
|
|
97
|
+
if details["stale"]:
|
|
98
|
+
problems.append(f"stale {int(age_days)}d")
|
|
99
|
+
else:
|
|
100
|
+
# Unborn branch: no commits yet
|
|
101
|
+
details["age_days"] = None
|
|
102
|
+
details["stale"] = False
|
|
103
|
+
problems.append("no commits")
|
|
104
|
+
|
|
105
|
+
summary = " ".join(problems) if problems else "clean"
|
|
106
|
+
result_status = Status.PASS if not problems else Status.WARN
|
|
107
|
+
return CheckResult(self.name, result_status, summary, details)
|