checkforge 0.1.8__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.
- checkforge/__init__.py +3 -0
- checkforge/__main__.py +6 -0
- checkforge/checks/__init__.py +0 -0
- checkforge/checks/dead_files.py +208 -0
- checkforge/checks/git_hotspots.py +131 -0
- checkforge/checks/readme_drift.py +110 -0
- checkforge/checks/secrets.py +154 -0
- checkforge/checks/stale_deps.py +218 -0
- checkforge/cli.py +100 -0
- checkforge/plugin.py +56 -0
- checkforge/report.py +72 -0
- checkforge/runner.py +58 -0
- checkforge-0.1.8.dist-info/METADATA +170 -0
- checkforge-0.1.8.dist-info/RECORD +18 -0
- checkforge-0.1.8.dist-info/WHEEL +5 -0
- checkforge-0.1.8.dist-info/entry_points.txt +9 -0
- checkforge-0.1.8.dist-info/licenses/LICENSE +21 -0
- checkforge-0.1.8.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Dependencias Python declaradas pero nunca importadas, e imports sin declarar.
|
|
2
|
+
|
|
3
|
+
Todo estático y sin red (no consulta a PyPI en esta versión -- comprobar
|
|
4
|
+
versiones desactualizadas de verdad necesitaría red, y este check está
|
|
5
|
+
pensado para poder correr offline/en CI de forma fiable; queda como
|
|
6
|
+
posible plugin aparte el día que se quiera esa comprobación).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import tomllib
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from ..plugin import CheckResult, Finding
|
|
17
|
+
|
|
18
|
+
_REQ_LINE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)")
|
|
19
|
+
_IMPORT_RE = re.compile(
|
|
20
|
+
r"^\s*(?:from\s+([A-Za-z_][\w]*)|import\s+([A-Za-z_][\w]*))",
|
|
21
|
+
re.MULTILINE,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Casos donde el nombre del paquete (PyPI) y el nombre que se importa
|
|
25
|
+
# difieren -- las discrepancias mas comunes, no exhaustivo a proposito.
|
|
26
|
+
_PACKAGE_TO_IMPORT = {
|
|
27
|
+
"pyyaml": "yaml",
|
|
28
|
+
"beautifulsoup4": "bs4",
|
|
29
|
+
"pillow": "PIL",
|
|
30
|
+
"python-dotenv": "dotenv",
|
|
31
|
+
"scikit-learn": "sklearn",
|
|
32
|
+
"opencv-python": "cv2",
|
|
33
|
+
"python-dateutil": "dateutil",
|
|
34
|
+
"pyjwt": "jwt",
|
|
35
|
+
"protobuf": "google",
|
|
36
|
+
"grpcio": "grpc",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
_STDLIB = set(getattr(sys, "stdlib_module_names", ()))
|
|
40
|
+
|
|
41
|
+
# Se usan como programa o plugin, no con import: declararlas (normalmente en un extra "dev") es lo correcto
|
|
42
|
+
_TOOLS = {
|
|
43
|
+
"ruff", "black", "isort", "flake8", "pylint", "mypy", "pyright", "bandit", "pytest", "coverage",
|
|
44
|
+
"tox", "nox", "pre-commit", "build", "twine", "pip-tools", "sphinx", "mkdocs", "uv", "hatch",
|
|
45
|
+
}
|
|
46
|
+
_TOOL_PREFIXES = ("pytest-", "flake8-", "types-", "mkdocs-", "sphinx-")
|
|
47
|
+
# Las carga otra dependencia por su cuenta: si se usa esa, no son "declaradas sin usar"
|
|
48
|
+
_IMPLIED_BY = {
|
|
49
|
+
"python-multipart": {"fastapi", "starlette"}, # formularios
|
|
50
|
+
"itsdangerous": {"fastapi", "starlette", "flask"}, # SessionMiddleware / sesiones firmadas
|
|
51
|
+
"httpx": {"fastapi", "starlette"}, # TestClient
|
|
52
|
+
"uvicorn": {"fastapi", "starlette"},
|
|
53
|
+
"gunicorn": {"flask", "django", "fastapi"},
|
|
54
|
+
"psycopg2-binary": {"sqlalchemy", "django"},
|
|
55
|
+
"asyncpg": {"sqlalchemy"},
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _used_another_way(package: str, used: set[str]) -> bool:
|
|
60
|
+
name = package.lower()
|
|
61
|
+
if name in _TOOLS or name.startswith(_TOOL_PREFIXES):
|
|
62
|
+
return True
|
|
63
|
+
return bool(_IMPLIED_BY.get(name, set()) & used)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _parse_requirements_txt(path: Path) -> set[str]:
|
|
67
|
+
names: set[str] = set()
|
|
68
|
+
for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
|
|
69
|
+
line = line.strip()
|
|
70
|
+
if not line or line.startswith(("#", "-e", "-r", "--")):
|
|
71
|
+
continue
|
|
72
|
+
match = _REQ_LINE.match(line)
|
|
73
|
+
if match:
|
|
74
|
+
names.add(match.group(1).lower())
|
|
75
|
+
return names
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _parse_pyproject_toml(path: Path) -> set[str]:
|
|
79
|
+
try:
|
|
80
|
+
data = tomllib.loads(path.read_text(encoding="utf-8", errors="ignore"))
|
|
81
|
+
except tomllib.TOMLDecodeError:
|
|
82
|
+
return set()
|
|
83
|
+
names: set[str] = set()
|
|
84
|
+
project = data.get("project", {})
|
|
85
|
+
for dep in project.get("dependencies", []):
|
|
86
|
+
match = _REQ_LINE.match(dep)
|
|
87
|
+
if match:
|
|
88
|
+
names.add(match.group(1).lower())
|
|
89
|
+
for extra_deps in project.get("optional-dependencies", {}).values():
|
|
90
|
+
for dep in extra_deps:
|
|
91
|
+
match = _REQ_LINE.match(dep)
|
|
92
|
+
if match:
|
|
93
|
+
names.add(match.group(1).lower())
|
|
94
|
+
return names
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _declared_dependencies(repo_path: Path) -> set[str] | None:
|
|
98
|
+
"""None si no existe ni requirements.txt ni pyproject.toml (no aplica);
|
|
99
|
+
set() si existen pero no declaran ninguna dependencia -- son casos
|
|
100
|
+
distintos, el segundo sigue debiendo comprobar imports sin declarar.
|
|
101
|
+
"""
|
|
102
|
+
req = repo_path / "requirements.txt"
|
|
103
|
+
pyproject = repo_path / "pyproject.toml"
|
|
104
|
+
if not req.is_file() and not pyproject.is_file():
|
|
105
|
+
return None
|
|
106
|
+
names: set[str] = set()
|
|
107
|
+
if req.is_file():
|
|
108
|
+
names |= _parse_requirements_txt(req)
|
|
109
|
+
if pyproject.is_file():
|
|
110
|
+
names |= _parse_pyproject_toml(pyproject)
|
|
111
|
+
return names
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _to_import_name(package_name: str) -> str:
|
|
115
|
+
mapped = _PACKAGE_TO_IMPORT.get(package_name.lower())
|
|
116
|
+
if mapped:
|
|
117
|
+
return mapped
|
|
118
|
+
return package_name.replace("-", "_")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _local_package_names(repo_path: Path) -> set[str]:
|
|
122
|
+
"""Nombres de nivel superior que son del propio repo, no de PyPI.
|
|
123
|
+
|
|
124
|
+
Un paquete propio del repo (`import miproyecto`) no es una dependencia
|
|
125
|
+
sin declarar -- es el propio código que se está analizando. Se detecta
|
|
126
|
+
por convención: cualquier directorio de primer nivel con `__init__.py`,
|
|
127
|
+
más los ficheros .py sueltos en la raíz.
|
|
128
|
+
"""
|
|
129
|
+
names: set[str] = set()
|
|
130
|
+
for entry in repo_path.iterdir():
|
|
131
|
+
if entry.is_dir() and (entry / "__init__.py").is_file():
|
|
132
|
+
names.add(entry.name)
|
|
133
|
+
elif entry.is_file() and entry.suffix == ".py":
|
|
134
|
+
names.add(entry.stem)
|
|
135
|
+
# Módulos sueltos de subdirectorios que se importan por su nombre (pytest mete tests/ en el
|
|
136
|
+
# path: `from conftest import ...`; un script importa al de al lado) y paquetes bajo src/.
|
|
137
|
+
# Antes `conftest` salía como dependencia sin declarar.
|
|
138
|
+
# Solo ficheros versionados: un entorno virtual sin punto (env/) colaría sus paquetes.
|
|
139
|
+
try:
|
|
140
|
+
out = subprocess.run(
|
|
141
|
+
["git", "-c", "core.quotePath=false", "ls-files", "*.py"], cwd=repo_path, capture_output=True,
|
|
142
|
+
text=True, check=True, timeout=30,
|
|
143
|
+
)
|
|
144
|
+
except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
|
|
145
|
+
return names
|
|
146
|
+
for line in out.stdout.splitlines():
|
|
147
|
+
rel = Path(line)
|
|
148
|
+
if rel.name != "__init__.py":
|
|
149
|
+
names.add(rel.stem)
|
|
150
|
+
elif len(rel.parts) == 3 and rel.parts[0] == "src":
|
|
151
|
+
names.add(rel.parts[1])
|
|
152
|
+
return names
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _used_imports(repo_path: Path) -> set[str] | None:
|
|
156
|
+
try:
|
|
157
|
+
out = subprocess.run(
|
|
158
|
+
["git", "-c", "core.quotePath=false", "ls-files", "*.py"], cwd=repo_path, capture_output=True,
|
|
159
|
+
text=True, check=True, timeout=30,
|
|
160
|
+
)
|
|
161
|
+
except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
|
|
162
|
+
return None
|
|
163
|
+
used: set[str] = set()
|
|
164
|
+
for rel in out.stdout.splitlines():
|
|
165
|
+
if not rel:
|
|
166
|
+
continue
|
|
167
|
+
try:
|
|
168
|
+
text = (repo_path / rel).read_text(encoding="utf-8", errors="ignore")
|
|
169
|
+
except OSError:
|
|
170
|
+
continue
|
|
171
|
+
for match in _IMPORT_RE.finditer(text):
|
|
172
|
+
name = match.group(1) or match.group(2)
|
|
173
|
+
if name:
|
|
174
|
+
used.add(name.split(".")[0])
|
|
175
|
+
return used
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class StaleDepsCheck:
|
|
179
|
+
name = "stale_deps"
|
|
180
|
+
description = "Dependencias Python declaradas sin usar, o usadas sin declarar (requirements.txt/pyproject.toml)."
|
|
181
|
+
|
|
182
|
+
def run(self, repo_path: Path) -> CheckResult:
|
|
183
|
+
declared = _declared_dependencies(repo_path)
|
|
184
|
+
if declared is None:
|
|
185
|
+
return CheckResult(
|
|
186
|
+
check_name=self.name,
|
|
187
|
+
summary="No aplica: no se encontró requirements.txt ni pyproject.toml.",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
used = _used_imports(repo_path)
|
|
191
|
+
if used is None:
|
|
192
|
+
return CheckResult(
|
|
193
|
+
check_name=self.name,
|
|
194
|
+
summary="No aplica: no es un repositorio git.",
|
|
195
|
+
error="not_a_git_repo",
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
findings: list[Finding] = []
|
|
199
|
+
for package in sorted(declared):
|
|
200
|
+
import_name = _to_import_name(package)
|
|
201
|
+
if import_name not in used and not _used_another_way(package, used):
|
|
202
|
+
findings.append(Finding(
|
|
203
|
+
severity="low",
|
|
204
|
+
title=f"Dependencia declarada pero no importada en ningún fichero: {package}",
|
|
205
|
+
detail="Heurística -- puede usarse indirectamente (plugin, entry point, CLI de terceros).",
|
|
206
|
+
))
|
|
207
|
+
|
|
208
|
+
declared_import_names = {_to_import_name(p) for p in declared}
|
|
209
|
+
local_names = _local_package_names(repo_path)
|
|
210
|
+
for name in sorted(used - declared_import_names - _STDLIB - local_names):
|
|
211
|
+
findings.append(Finding(
|
|
212
|
+
severity="info",
|
|
213
|
+
title=f"Import de terceros sin declarar en requirements/pyproject: {name}",
|
|
214
|
+
detail="Puede ser un módulo local o una dependencia transitiva -- revisar.",
|
|
215
|
+
))
|
|
216
|
+
|
|
217
|
+
summary = f"{len(declared)} dependencia(s) declarada(s), {len(findings)} hallazgo(s)."
|
|
218
|
+
return CheckResult(check_name=self.name, summary=summary, findings=findings)
|
checkforge/cli.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""CLI: `checkforge analyze <ruta>`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import __version__
|
|
9
|
+
from .plugin import SEVERITIES
|
|
10
|
+
from .report import Report
|
|
11
|
+
from .runner import discover_checks, run_checks
|
|
12
|
+
|
|
13
|
+
_SEVERITY_RANK = {sev: i for i, sev in enumerate(SEVERITIES)}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
17
|
+
parser = argparse.ArgumentParser(
|
|
18
|
+
prog="checkforge",
|
|
19
|
+
description="Agregador de auditorías de repositorios (dependencias, secretos, "
|
|
20
|
+
"código muerto, hotspots de git...) en un único informe.",
|
|
21
|
+
)
|
|
22
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
23
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
24
|
+
|
|
25
|
+
analyze = sub.add_parser("analyze", help="Analiza un repositorio")
|
|
26
|
+
analyze.add_argument("path", nargs="?", default=".", help="Ruta al repositorio (por defecto: .)")
|
|
27
|
+
analyze.add_argument(
|
|
28
|
+
"--only", metavar="CHECK", action="append", default=None,
|
|
29
|
+
help="Ejecutar solo este check (repetible)",
|
|
30
|
+
)
|
|
31
|
+
analyze.add_argument(
|
|
32
|
+
"--skip", metavar="CHECK", action="append", default=None,
|
|
33
|
+
help="Excluir este check (repetible)",
|
|
34
|
+
)
|
|
35
|
+
analyze.add_argument("--json", action="store_true", help="Salida en JSON en vez de consola")
|
|
36
|
+
analyze.add_argument(
|
|
37
|
+
"--fail-on", metavar="SEVERITY", choices=SEVERITIES, default=None,
|
|
38
|
+
help="Salir con código != 0 si hay algún hallazgo de esta severidad o mayor",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
sub.add_parser("list-checks", help="Lista los checks instalados (propios y de terceros)")
|
|
42
|
+
|
|
43
|
+
return parser
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def main(argv: list[str] | None = None) -> int:
|
|
47
|
+
parser = _build_parser()
|
|
48
|
+
args = parser.parse_args(argv)
|
|
49
|
+
|
|
50
|
+
if args.command == "list-checks":
|
|
51
|
+
checks = discover_checks()
|
|
52
|
+
if not checks:
|
|
53
|
+
print("No hay ningún check instalado.")
|
|
54
|
+
return 0
|
|
55
|
+
for name, cls in sorted(checks.items()):
|
|
56
|
+
desc = getattr(cls, "description", "")
|
|
57
|
+
print(f"{name}: {desc}")
|
|
58
|
+
return 0
|
|
59
|
+
|
|
60
|
+
# analyze
|
|
61
|
+
repo_path = Path(args.path).resolve()
|
|
62
|
+
if not repo_path.is_dir():
|
|
63
|
+
print(f"error: {repo_path} no es un directorio", file=sys.stderr)
|
|
64
|
+
return 2
|
|
65
|
+
|
|
66
|
+
only = set(args.only) if args.only else None
|
|
67
|
+
skip = set(args.skip) if args.skip else None
|
|
68
|
+
# Un nombre mal escrito en --only no ejecutaba nada y salía 0: verde falso en CI con --fail-on.
|
|
69
|
+
unknown = ((only or set()) | (skip or set())) - set(discover_checks())
|
|
70
|
+
if unknown:
|
|
71
|
+
print(f"error: check(s) desconocido(s): {', '.join(sorted(unknown))} "
|
|
72
|
+
"(ver `checkforge list-checks`)", file=sys.stderr)
|
|
73
|
+
return 2
|
|
74
|
+
results = run_checks(repo_path, only=only, skip=skip)
|
|
75
|
+
report = Report(repo_path=str(repo_path), results=results)
|
|
76
|
+
|
|
77
|
+
if args.json:
|
|
78
|
+
print(report.to_json())
|
|
79
|
+
else:
|
|
80
|
+
print(report.to_console())
|
|
81
|
+
|
|
82
|
+
# Un check que revienta deja el análisis incompleto: antes solo se avisaba y salía 0 (o 1 según
|
|
83
|
+
# --fail-on), y en un CI pasaba por verde sin haber mirado lo que ese check mira.
|
|
84
|
+
# «not_a_git_repo» no es un fallo: es «no aplica» (carpeta sin git).
|
|
85
|
+
failed = [r.check_name for r in results if r.error and r.error != "not_a_git_repo"]
|
|
86
|
+
if failed:
|
|
87
|
+
print(f"error: no se pudieron ejecutar: {', '.join(failed)} (análisis incompleto)", file=sys.stderr)
|
|
88
|
+
return 2
|
|
89
|
+
|
|
90
|
+
if args.fail_on is not None:
|
|
91
|
+
threshold = _SEVERITY_RANK[args.fail_on]
|
|
92
|
+
for result in results:
|
|
93
|
+
for finding in result.findings:
|
|
94
|
+
if _SEVERITY_RANK.get(finding.severity, 0) >= threshold:
|
|
95
|
+
return 1
|
|
96
|
+
return 0
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__":
|
|
100
|
+
sys.exit(main())
|
checkforge/plugin.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Contrato que debe cumplir cualquier check, propio o de terceros.
|
|
2
|
+
|
|
3
|
+
El núcleo no distingue entre los checks incorporados y los de un plugin
|
|
4
|
+
externo: ambos se descubren y ejecutan exactamente igual (ver `runner.py`).
|
|
5
|
+
Un check de terceros solo necesita publicar su propio paquete instalable
|
|
6
|
+
con una entrada en el grupo de entry points `checkforge.checks` — no hace
|
|
7
|
+
falta tocar este repositorio para añadir uno nuevo.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Protocol, runtime_checkable
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, Field
|
|
15
|
+
|
|
16
|
+
Severity = str # "info" | "low" | "medium" | "high" -- str simple a proposito,
|
|
17
|
+
# un plugin de terceros no deberia depender de un enum interno nuestro.
|
|
18
|
+
|
|
19
|
+
SEVERITIES: tuple[Severity, ...] = ("info", "low", "medium", "high")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Finding(BaseModel):
|
|
23
|
+
"""Un hallazgo concreto de un check."""
|
|
24
|
+
|
|
25
|
+
severity: Severity
|
|
26
|
+
title: str
|
|
27
|
+
detail: str = ""
|
|
28
|
+
path: str | None = None
|
|
29
|
+
line: int | None = None
|
|
30
|
+
|
|
31
|
+
def model_post_init(self, context: object, /) -> None:
|
|
32
|
+
if self.severity not in SEVERITIES:
|
|
33
|
+
raise ValueError(
|
|
34
|
+
f"severity {self.severity!r} no es una de {SEVERITIES}"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CheckResult(BaseModel):
|
|
39
|
+
"""Resultado de ejecutar un check contra un repo."""
|
|
40
|
+
|
|
41
|
+
check_name: str
|
|
42
|
+
summary: str
|
|
43
|
+
findings: list[Finding] = Field(default_factory=list)
|
|
44
|
+
# Si el check no pudo completarse (no aplica a este repo, herramienta
|
|
45
|
+
# externa que falta, etc.) -- no es lo mismo que "sin hallazgos".
|
|
46
|
+
error: str | None = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@runtime_checkable
|
|
50
|
+
class Check(Protocol):
|
|
51
|
+
"""Un check independiente. Instanciable sin argumentos."""
|
|
52
|
+
|
|
53
|
+
name: str
|
|
54
|
+
description: str
|
|
55
|
+
|
|
56
|
+
def run(self, repo_path: Path) -> CheckResult: ...
|
checkforge/report.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Agrega los CheckResult de una ejecución y los presenta: consola o JSON."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from .plugin import SEVERITIES, CheckResult
|
|
8
|
+
|
|
9
|
+
_SEVERITY_ORDER = {sev: i for i, sev in enumerate(reversed(SEVERITIES))} # high primero
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Report:
|
|
14
|
+
repo_path: str
|
|
15
|
+
results: list[CheckResult] = field(default_factory=list)
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def total_findings(self) -> int:
|
|
19
|
+
return sum(len(r.findings) for r in self.results)
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def counts_by_severity(self) -> dict[str, int]:
|
|
23
|
+
counts = dict.fromkeys(SEVERITIES, 0)
|
|
24
|
+
for r in self.results:
|
|
25
|
+
for f in r.findings:
|
|
26
|
+
counts[f.severity] += 1
|
|
27
|
+
return counts
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def failed_checks(self) -> list[CheckResult]:
|
|
31
|
+
return [r for r in self.results if r.error is not None]
|
|
32
|
+
|
|
33
|
+
def to_json(self) -> str:
|
|
34
|
+
payload = {
|
|
35
|
+
"repo_path": self.repo_path,
|
|
36
|
+
"total_findings": self.total_findings,
|
|
37
|
+
"counts_by_severity": self.counts_by_severity,
|
|
38
|
+
"checks": [r.model_dump() for r in self.results],
|
|
39
|
+
}
|
|
40
|
+
return json.dumps(payload, indent=2, ensure_ascii=False)
|
|
41
|
+
|
|
42
|
+
def to_console(self) -> str:
|
|
43
|
+
lines: list[str] = [f"checkforge — {self.repo_path}", ""]
|
|
44
|
+
|
|
45
|
+
for result in self.results:
|
|
46
|
+
lines.append(f"── {result.check_name} " + "─" * max(0, 40 - len(result.check_name)))
|
|
47
|
+
if result.error is not None:
|
|
48
|
+
lines.append(f" aviso: el check falló ({result.summary})")
|
|
49
|
+
lines.append("")
|
|
50
|
+
continue
|
|
51
|
+
lines.append(f" {result.summary}")
|
|
52
|
+
findings_sorted = sorted(
|
|
53
|
+
result.findings, key=lambda f: _SEVERITY_ORDER.get(f.severity, 0)
|
|
54
|
+
)
|
|
55
|
+
for f in findings_sorted:
|
|
56
|
+
label = f"[{f.severity.upper():<6}]"
|
|
57
|
+
loc = f" ({f.path})" if f.path else ""
|
|
58
|
+
if f.line is not None:
|
|
59
|
+
loc = f" ({f.path}:{f.line})" if f.path else f" (línea {f.line})"
|
|
60
|
+
lines.append(f" {label} {f.title}{loc}")
|
|
61
|
+
if f.detail:
|
|
62
|
+
lines.append(f" {f.detail}")
|
|
63
|
+
lines.append("")
|
|
64
|
+
|
|
65
|
+
counts = self.counts_by_severity
|
|
66
|
+
summary_parts = [f"{counts[s]} {s}" for s in reversed(SEVERITIES) if counts[s]]
|
|
67
|
+
summary = ", ".join(summary_parts) if summary_parts else "sin hallazgos"
|
|
68
|
+
lines.append(f"Total: {self.total_findings} hallazgo(s) — {summary}")
|
|
69
|
+
if self.failed_checks:
|
|
70
|
+
names = ", ".join(r.check_name for r in self.failed_checks)
|
|
71
|
+
lines.append(f"aviso: {len(self.failed_checks)} check(s) no se pudieron ejecutar: {names}")
|
|
72
|
+
return "\n".join(lines)
|
checkforge/runner.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Descubre los checks instalados (propios y de terceros) y los ejecuta.
|
|
2
|
+
|
|
3
|
+
Descubrimiento vía entry points (`checkforge.checks`) -- funciona igual
|
|
4
|
+
para un check incorporado en este paquete que para uno instalado desde un
|
|
5
|
+
paquete de terceros. Un check que falle con una excepción no tira abajo la
|
|
6
|
+
ejecución entera: se recoge como `CheckResult(error=...)` y se sigue con
|
|
7
|
+
el resto (un plugin de la comunidad no debería poder romper la ejecución
|
|
8
|
+
completa por un bug suyo).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import traceback
|
|
13
|
+
from importlib.metadata import entry_points
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .plugin import Check, CheckResult
|
|
17
|
+
|
|
18
|
+
ENTRY_POINT_GROUP = "checkforge.checks"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def discover_checks() -> dict[str, type[Check]]:
|
|
22
|
+
"""Devuelve {nombre: clase} de todos los checks instalados."""
|
|
23
|
+
found: dict[str, type[Check]] = {}
|
|
24
|
+
for ep in entry_points(group=ENTRY_POINT_GROUP):
|
|
25
|
+
found[ep.name] = ep.load()
|
|
26
|
+
return found
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run_checks(
|
|
30
|
+
repo_path: Path,
|
|
31
|
+
*,
|
|
32
|
+
only: set[str] | None = None,
|
|
33
|
+
skip: set[str] | None = None,
|
|
34
|
+
) -> list[CheckResult]:
|
|
35
|
+
"""Ejecuta los checks aplicables sobre `repo_path`.
|
|
36
|
+
|
|
37
|
+
`only`: si se da, solo ejecuta esos nombres de check.
|
|
38
|
+
`skip`: nombres a excluir (se aplica después de `only`).
|
|
39
|
+
"""
|
|
40
|
+
checks = discover_checks()
|
|
41
|
+
names = set(checks) if only is None else (set(checks) & only)
|
|
42
|
+
if skip:
|
|
43
|
+
names -= skip
|
|
44
|
+
|
|
45
|
+
results: list[CheckResult] = []
|
|
46
|
+
for name in sorted(names):
|
|
47
|
+
check_cls = checks[name]
|
|
48
|
+
try:
|
|
49
|
+
check = check_cls()
|
|
50
|
+
result = check.run(repo_path)
|
|
51
|
+
except Exception as exc: # noqa: BLE001 -- un plugin de terceros puede fallar de cualquier forma
|
|
52
|
+
result = CheckResult(
|
|
53
|
+
check_name=name,
|
|
54
|
+
summary=f"El check falló al ejecutarse: {exc}",
|
|
55
|
+
error=traceback.format_exc(),
|
|
56
|
+
)
|
|
57
|
+
results.append(result)
|
|
58
|
+
return results
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: checkforge
|
|
3
|
+
Version: 0.1.8
|
|
4
|
+
Summary: Agregador de auditorías de repositorios: dependencias, secretos, código muerto, hotspots de git — un informe, arquitectura de plugins.
|
|
5
|
+
Author: José Luis Segura Yuste
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jl-segurayuste/checkforge
|
|
8
|
+
Project-URL: Source, https://github.com/jl-segurayuste/checkforge
|
|
9
|
+
Project-URL: Issues, https://github.com/jl-segurayuste/checkforge/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/jl-segurayuste/checkforge/releases
|
|
11
|
+
Keywords: code-quality,developer-tools,static-analysis
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Natural Language :: Spanish
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
23
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: pydantic>=2.6
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
31
|
+
Requires-Dist: ruff==0.17.6; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# checkforge
|
|
35
|
+
|
|
36
|
+
[](https://pypi.org/project/checkforge/)
|
|
37
|
+
[](https://github.com/jl-segurayuste/checkforge/actions/workflows/ci.yml)
|
|
38
|
+
[](https://github.com/jl-segurayuste/checkforge/blob/main/pyproject.toml)
|
|
39
|
+
[](https://github.com/jl-segurayuste/checkforge/blob/main/LICENSE)
|
|
40
|
+
|
|
41
|
+
Un único comando que agrega varias auditorías de un repositorio —
|
|
42
|
+
dependencias, secretos, código muerto, historial de git — en un solo
|
|
43
|
+
informe, en vez de tener que ejecutar y leer media docena de herramientas
|
|
44
|
+
sueltas por separado.
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
$ checkforge analyze .
|
|
48
|
+
|
|
49
|
+
checkforge — /ruta/al/repo
|
|
50
|
+
|
|
51
|
+
── secrets ──────────────────────────────
|
|
52
|
+
53 fichero(s) analizados, 2 hallazgo(s).
|
|
53
|
+
[HIGH ] Posible secreto: AWS Access Key ID (config/settings.py:14)
|
|
54
|
+
Revisar y revocar si es real antes de publicar.
|
|
55
|
+
|
|
56
|
+
── stale_deps ───────────────────────────
|
|
57
|
+
12 dependencia(s) declarada(s), 1 hallazgo(s).
|
|
58
|
+
[LOW ] Dependencia declarada pero no importada en ningún fichero: requests
|
|
59
|
+
Heurística -- puede usarse indirectamente (plugin, entry point, CLI de terceros).
|
|
60
|
+
|
|
61
|
+
Total: 3 hallazgo(s) — 1 high, 2 low
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Así se ve
|
|
65
|
+
|
|
66
|
+

|
|
67
|
+
|
|
68
|
+
<sub>Ejecución real sobre un proyecto Python de ejemplo con un secreto, un fichero huérfano y el README desfasado (todos los datos son ficticios).</sub>
|
|
69
|
+
|
|
70
|
+
## Por qué existe
|
|
71
|
+
|
|
72
|
+
Hoy existen muchas herramientas excelentes que resuelven un problema cada
|
|
73
|
+
una — un detector de secretos, un linter de dependencias, un analizador de
|
|
74
|
+
churn de git — pero ninguna las normaliza en un único informe accionable.
|
|
75
|
+
`checkforge` no compite con ellas: es un agregador. El núcleo no sabe
|
|
76
|
+
nada de ningún lenguaje ni de ningún tipo de análisis concreto; cada check
|
|
77
|
+
es un plugin independiente.
|
|
78
|
+
|
|
79
|
+
## Instalación
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
pipx install checkforge # recomendado para herramientas de línea de comandos
|
|
83
|
+
# o bien
|
|
84
|
+
pip install checkforge
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Uso
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
checkforge analyze . # informe en consola
|
|
91
|
+
checkforge analyze . --json # informe en JSON
|
|
92
|
+
checkforge analyze . --only secrets # solo un check
|
|
93
|
+
checkforge analyze . --skip git_hotspots
|
|
94
|
+
checkforge analyze . --fail-on high # código de salida 1 si hay algo "high" (para CI)
|
|
95
|
+
# código 2 si algún check no se pudo ejecutar (análisis incompleto)
|
|
96
|
+
checkforge list-checks # que checks estan instalados
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Checks incluidos (v0.1)
|
|
100
|
+
|
|
101
|
+
| Check | Qué mira |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `secrets` | Claves privadas, tokens de proveedores conocidos, asignaciones con aspecto de secreto, IPs privadas |
|
|
104
|
+
| `dead_files` | Ficheros Python que ningún otro fichero del repo importa |
|
|
105
|
+
| `git_hotspots` | Ficheros que cambian con mucha frecuencia, ramas obsoletas, ficheros enormes |
|
|
106
|
+
| `stale_deps` | Dependencias Python declaradas sin usar, o usadas sin declarar |
|
|
107
|
+
| `readme_drift` | Versión de Python y comandos de CLI del README frente a `pyproject.toml` |
|
|
108
|
+
|
|
109
|
+
Todo es análisis estático: nada de esto ejecuta el código del repo que se
|
|
110
|
+
analiza. `dead_files` y `stale_deps` son heurísticas y hoy solo entienden
|
|
111
|
+
Python — lo dicen explícitamente en cada hallazgo, porque un falso
|
|
112
|
+
positivo silencioso es peor que no tener el check.
|
|
113
|
+
|
|
114
|
+
## Arquitectura: cada check es un plugin
|
|
115
|
+
|
|
116
|
+
El núcleo (`checkforge.runner`) descubre los checks instalados vía
|
|
117
|
+
[entry points](https://packaging.python.org/en/latest/specifications/entry-points/)
|
|
118
|
+
del grupo `checkforge.checks` — exactamente igual para los cuatro checks
|
|
119
|
+
que trae este paquete que para uno que instale un tercero. No hace falta
|
|
120
|
+
tocar este repositorio para añadir un check nuevo.
|
|
121
|
+
|
|
122
|
+
Un check es cualquier clase con este contrato:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from pathlib import Path
|
|
126
|
+
from checkforge.plugin import CheckResult, Finding
|
|
127
|
+
|
|
128
|
+
class MiCheck:
|
|
129
|
+
name = "mi_check"
|
|
130
|
+
description = "Qué hace, en una frase."
|
|
131
|
+
|
|
132
|
+
def run(self, repo_path: Path) -> CheckResult:
|
|
133
|
+
findings = [
|
|
134
|
+
Finding(severity="medium", title="...", detail="...", path="...", line=1),
|
|
135
|
+
]
|
|
136
|
+
return CheckResult(check_name=self.name, summary="...", findings=findings)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Y en el `pyproject.toml` de tu propio paquete:
|
|
140
|
+
|
|
141
|
+
```toml
|
|
142
|
+
[project.entry-points."checkforge.checks"]
|
|
143
|
+
mi_check = "mi_paquete.checks:MiCheck"
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Con tu paquete instalado, `checkforge list-checks` ya lo verá. Ejemplo
|
|
147
|
+
real y funcional, no solo el fragmento de arriba:
|
|
148
|
+
[`examples/js-stale-deps-plugin`](examples/js-stale-deps-plugin) — puerto
|
|
149
|
+
a JavaScript/TypeScript del check `stale_deps`, con sus propios tests.
|
|
150
|
+
|
|
151
|
+
Otras ideas obvias para un plugin de terceros: soporte a más lenguajes en
|
|
152
|
+
`dead_files`/`stale_deps` (Go/Rust/Java), comprobación de versiones
|
|
153
|
+
desactualizadas contra el índice real de paquetes (`stale_deps` de este
|
|
154
|
+
repo es deliberadamente offline), un check de cobertura de tests.
|
|
155
|
+
|
|
156
|
+
## Desarrollo
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
python -m venv .venv && source .venv/bin/activate
|
|
160
|
+
pip install -e ".[dev]"
|
|
161
|
+
pytest
|
|
162
|
+
ruff check .
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Ver [CONTRIBUTING.md](CONTRIBUTING.md) antes de mandar un check nuevo o
|
|
166
|
+
un cambio al núcleo.
|
|
167
|
+
|
|
168
|
+
## Licencia
|
|
169
|
+
|
|
170
|
+
MIT.
|