checkforge 0.1.8__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.
Files changed (33) hide show
  1. checkforge-0.1.8/LICENSE +21 -0
  2. checkforge-0.1.8/PKG-INFO +170 -0
  3. checkforge-0.1.8/README.md +137 -0
  4. checkforge-0.1.8/checkforge/__init__.py +3 -0
  5. checkforge-0.1.8/checkforge/__main__.py +6 -0
  6. checkforge-0.1.8/checkforge/checks/__init__.py +0 -0
  7. checkforge-0.1.8/checkforge/checks/dead_files.py +208 -0
  8. checkforge-0.1.8/checkforge/checks/git_hotspots.py +131 -0
  9. checkforge-0.1.8/checkforge/checks/readme_drift.py +110 -0
  10. checkforge-0.1.8/checkforge/checks/secrets.py +154 -0
  11. checkforge-0.1.8/checkforge/checks/stale_deps.py +218 -0
  12. checkforge-0.1.8/checkforge/cli.py +100 -0
  13. checkforge-0.1.8/checkforge/plugin.py +56 -0
  14. checkforge-0.1.8/checkforge/report.py +72 -0
  15. checkforge-0.1.8/checkforge/runner.py +58 -0
  16. checkforge-0.1.8/checkforge.egg-info/PKG-INFO +170 -0
  17. checkforge-0.1.8/checkforge.egg-info/SOURCES.txt +31 -0
  18. checkforge-0.1.8/checkforge.egg-info/dependency_links.txt +1 -0
  19. checkforge-0.1.8/checkforge.egg-info/entry_points.txt +9 -0
  20. checkforge-0.1.8/checkforge.egg-info/requires.txt +6 -0
  21. checkforge-0.1.8/checkforge.egg-info/top_level.txt +1 -0
  22. checkforge-0.1.8/pyproject.toml +77 -0
  23. checkforge-0.1.8/setup.cfg +4 -0
  24. checkforge-0.1.8/tests/test_cli.py +87 -0
  25. checkforge-0.1.8/tests/test_dead_files.py +128 -0
  26. checkforge-0.1.8/tests/test_git_hotspots.py +69 -0
  27. checkforge-0.1.8/tests/test_plugin.py +19 -0
  28. checkforge-0.1.8/tests/test_readme_drift.py +79 -0
  29. checkforge-0.1.8/tests/test_report.py +54 -0
  30. checkforge-0.1.8/tests/test_runner.py +42 -0
  31. checkforge-0.1.8/tests/test_secrets.py +131 -0
  32. checkforge-0.1.8/tests/test_stale_deps.py +124 -0
  33. checkforge-0.1.8/tests/test_version.py +11 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 José Luis Segura Yuste
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -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
+ [![PyPI](https://img.shields.io/pypi/v/checkforge.svg)](https://pypi.org/project/checkforge/)
37
+ [![CI](https://github.com/jl-segurayuste/checkforge/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/checkforge/actions/workflows/ci.yml)
38
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/checkforge/blob/main/pyproject.toml)
39
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](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
+ ![Salida de checkforge sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/checkforge/main/docs/img/demo.svg)
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.
@@ -0,0 +1,137 @@
1
+ # checkforge
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/checkforge.svg)](https://pypi.org/project/checkforge/)
4
+ [![CI](https://github.com/jl-segurayuste/checkforge/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/checkforge/actions/workflows/ci.yml)
5
+ [![Python 3.11–3.15](https://img.shields.io/badge/python-3.11%20%E2%80%93%203.15-blue.svg)](https://github.com/jl-segurayuste/checkforge/blob/main/pyproject.toml)
6
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/checkforge/blob/main/LICENSE)
7
+
8
+ Un único comando que agrega varias auditorías de un repositorio —
9
+ dependencias, secretos, código muerto, historial de git — en un solo
10
+ informe, en vez de tener que ejecutar y leer media docena de herramientas
11
+ sueltas por separado.
12
+
13
+ ```
14
+ $ checkforge analyze .
15
+
16
+ checkforge — /ruta/al/repo
17
+
18
+ ── secrets ──────────────────────────────
19
+ 53 fichero(s) analizados, 2 hallazgo(s).
20
+ [HIGH ] Posible secreto: AWS Access Key ID (config/settings.py:14)
21
+ Revisar y revocar si es real antes de publicar.
22
+
23
+ ── stale_deps ───────────────────────────
24
+ 12 dependencia(s) declarada(s), 1 hallazgo(s).
25
+ [LOW ] Dependencia declarada pero no importada en ningún fichero: requests
26
+ Heurística -- puede usarse indirectamente (plugin, entry point, CLI de terceros).
27
+
28
+ Total: 3 hallazgo(s) — 1 high, 2 low
29
+ ```
30
+
31
+ ## Así se ve
32
+
33
+ ![Salida de checkforge sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/checkforge/main/docs/img/demo.svg)
34
+
35
+ <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>
36
+
37
+ ## Por qué existe
38
+
39
+ Hoy existen muchas herramientas excelentes que resuelven un problema cada
40
+ una — un detector de secretos, un linter de dependencias, un analizador de
41
+ churn de git — pero ninguna las normaliza en un único informe accionable.
42
+ `checkforge` no compite con ellas: es un agregador. El núcleo no sabe
43
+ nada de ningún lenguaje ni de ningún tipo de análisis concreto; cada check
44
+ es un plugin independiente.
45
+
46
+ ## Instalación
47
+
48
+ ```bash
49
+ pipx install checkforge # recomendado para herramientas de línea de comandos
50
+ # o bien
51
+ pip install checkforge
52
+ ```
53
+
54
+ ## Uso
55
+
56
+ ```bash
57
+ checkforge analyze . # informe en consola
58
+ checkforge analyze . --json # informe en JSON
59
+ checkforge analyze . --only secrets # solo un check
60
+ checkforge analyze . --skip git_hotspots
61
+ checkforge analyze . --fail-on high # código de salida 1 si hay algo "high" (para CI)
62
+ # código 2 si algún check no se pudo ejecutar (análisis incompleto)
63
+ checkforge list-checks # que checks estan instalados
64
+ ```
65
+
66
+ ## Checks incluidos (v0.1)
67
+
68
+ | Check | Qué mira |
69
+ |---|---|
70
+ | `secrets` | Claves privadas, tokens de proveedores conocidos, asignaciones con aspecto de secreto, IPs privadas |
71
+ | `dead_files` | Ficheros Python que ningún otro fichero del repo importa |
72
+ | `git_hotspots` | Ficheros que cambian con mucha frecuencia, ramas obsoletas, ficheros enormes |
73
+ | `stale_deps` | Dependencias Python declaradas sin usar, o usadas sin declarar |
74
+ | `readme_drift` | Versión de Python y comandos de CLI del README frente a `pyproject.toml` |
75
+
76
+ Todo es análisis estático: nada de esto ejecuta el código del repo que se
77
+ analiza. `dead_files` y `stale_deps` son heurísticas y hoy solo entienden
78
+ Python — lo dicen explícitamente en cada hallazgo, porque un falso
79
+ positivo silencioso es peor que no tener el check.
80
+
81
+ ## Arquitectura: cada check es un plugin
82
+
83
+ El núcleo (`checkforge.runner`) descubre los checks instalados vía
84
+ [entry points](https://packaging.python.org/en/latest/specifications/entry-points/)
85
+ del grupo `checkforge.checks` — exactamente igual para los cuatro checks
86
+ que trae este paquete que para uno que instale un tercero. No hace falta
87
+ tocar este repositorio para añadir un check nuevo.
88
+
89
+ Un check es cualquier clase con este contrato:
90
+
91
+ ```python
92
+ from pathlib import Path
93
+ from checkforge.plugin import CheckResult, Finding
94
+
95
+ class MiCheck:
96
+ name = "mi_check"
97
+ description = "Qué hace, en una frase."
98
+
99
+ def run(self, repo_path: Path) -> CheckResult:
100
+ findings = [
101
+ Finding(severity="medium", title="...", detail="...", path="...", line=1),
102
+ ]
103
+ return CheckResult(check_name=self.name, summary="...", findings=findings)
104
+ ```
105
+
106
+ Y en el `pyproject.toml` de tu propio paquete:
107
+
108
+ ```toml
109
+ [project.entry-points."checkforge.checks"]
110
+ mi_check = "mi_paquete.checks:MiCheck"
111
+ ```
112
+
113
+ Con tu paquete instalado, `checkforge list-checks` ya lo verá. Ejemplo
114
+ real y funcional, no solo el fragmento de arriba:
115
+ [`examples/js-stale-deps-plugin`](examples/js-stale-deps-plugin) — puerto
116
+ a JavaScript/TypeScript del check `stale_deps`, con sus propios tests.
117
+
118
+ Otras ideas obvias para un plugin de terceros: soporte a más lenguajes en
119
+ `dead_files`/`stale_deps` (Go/Rust/Java), comprobación de versiones
120
+ desactualizadas contra el índice real de paquetes (`stale_deps` de este
121
+ repo es deliberadamente offline), un check de cobertura de tests.
122
+
123
+ ## Desarrollo
124
+
125
+ ```bash
126
+ python -m venv .venv && source .venv/bin/activate
127
+ pip install -e ".[dev]"
128
+ pytest
129
+ ruff check .
130
+ ```
131
+
132
+ Ver [CONTRIBUTING.md](CONTRIBUTING.md) antes de mandar un check nuevo o
133
+ un cambio al núcleo.
134
+
135
+ ## Licencia
136
+
137
+ MIT.
@@ -0,0 +1,3 @@
1
+ """checkforge — agregador de auditorías de repositorios, arquitectura de plugins."""
2
+
3
+ __version__ = "0.1.8"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
File without changes
@@ -0,0 +1,208 @@
1
+ """Ficheros Python que ningún otro fichero del repo importa.
2
+
3
+ Heurística estática basada en `import`/`from ... import` (con `ast`, así
4
+ que resuelve los imports relativos y `from paquete import submodulo`), sin
5
+ ejecutar código. También cuentan como uso los puntos de entrada de
6
+ `[project.scripts]`, los `python -m modulo` que aparezcan en el repo y los
7
+ directorios que Ansible carga por convención (`library/`, `module_utils/`). **Solo Python por ahora** (el soporte a otros lenguajes es el
8
+ caso de uso ideal para un plugin de terceros -- ver `plugin.py`). Como
9
+ toda heurística estática, puede haber falsos positivos (import dinámico,
10
+ entry points, ficheros cargados por un framework por convención) -- por
11
+ eso la severidad es baja y el mensaje lo deja claro.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import re
17
+ import subprocess
18
+ import tomllib
19
+ from pathlib import Path
20
+
21
+ from ..plugin import CheckResult, Finding
22
+
23
+ _IMPORT_RE = re.compile(
24
+ r"^\s*(?:from\s+([.\w]+)\s+import|import\s+([.\w]+(?:\s*,\s*[.\w]+)*))",
25
+ re.MULTILINE,
26
+ )
27
+
28
+ # Ficheros que un import no referenciaria nunca pero que sí "se usan":
29
+ # puntos de entrada, convenciones de framework/test-runner, config.
30
+ _SPECIAL_NAMES = {
31
+ "setup.py", "conftest.py", "manage.py", "__init__.py", "__main__.py",
32
+ }
33
+ _SPECIAL_DIR_PREFIXES = ("tests/", "test/", "scripts/", "bin/", "examples/", "docs/")
34
+ # Directorios cuyos .py carga una herramienta por convención, no un import (en cualquier nivel)
35
+ _CONVENTION_DIRS = {"library", "module_utils", "filter_plugins", "lookup_plugins", "callback_plugins"}
36
+ _PYTHON_M = re.compile(r"python[\d.]*\s+-m\s+([A-Za-z_][\w.]*)")
37
+ _TEXT_SUFFIXES = {".md", ".rst", ".txt", ".py", ".sh", ".toml", ".yml", ".yaml", ".cfg", ".ini", ".service", ""}
38
+
39
+
40
+ def _tracked_py_files(repo_path: Path) -> list[Path] | None:
41
+ try:
42
+ out = subprocess.run(
43
+ ["git", "-c", "core.quotePath=false", "ls-files", "*.py"], cwd=repo_path, capture_output=True,
44
+ text=True, check=True, timeout=30,
45
+ )
46
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
47
+ return None
48
+ return [repo_path / line for line in out.stdout.splitlines() if line]
49
+
50
+
51
+ def _module_candidates(repo_path: Path, file_path: Path) -> set[str]:
52
+ """Nombres por los que se podría importar `file_path` desde el repo."""
53
+ rel = file_path.relative_to(repo_path)
54
+ parts = list(rel.parts)
55
+ if parts[-1] == "__init__.py":
56
+ parts = parts[:-1]
57
+ else:
58
+ parts[-1] = parts[-1].removesuffix(".py")
59
+ if not parts:
60
+ return set()
61
+ # Todos los sufijos: con la estructura src/ (o un directorio que se mete en sys.path) el módulo
62
+ # src/pkg/mod.py se importa como «pkg.mod»; antes solo contaban «src.pkg.mod» y «mod», y
63
+ # todo el paquete salía como huérfano.
64
+ return {".".join(parts[i:]) for i in range(len(parts))}
65
+
66
+
67
+ def _is_script(file_path: Path) -> bool:
68
+ """Un .py con guion en el nombre no se puede importar; con shebang se ejecuta directamente."""
69
+ if "-" in file_path.stem:
70
+ return True
71
+ try:
72
+ with file_path.open("rb") as f:
73
+ return f.read(2) == b"#!"
74
+ except OSError:
75
+ return False
76
+
77
+
78
+ def _is_special(repo_path: Path, file_path: Path) -> bool:
79
+ rel = file_path.relative_to(repo_path)
80
+ if file_path.name in _SPECIAL_NAMES or _is_script(file_path):
81
+ return True
82
+ if file_path.name.startswith("test_") or file_path.name.endswith("_test.py"): # tests fuera de tests/
83
+ return True
84
+ if _CONVENTION_DIRS & set(rel.parts[:-1]):
85
+ return True
86
+ return any(str(rel).startswith(prefix) for prefix in _SPECIAL_DIR_PREFIXES)
87
+
88
+
89
+ def _with_prefixes(names: set[str], dotted: str) -> None:
90
+ """Añade "a.b.c" y sus prefijos ("a", "a.b"): importar un submódulo usa sus paquetes."""
91
+ segs = [s for s in dotted.split(".") if s]
92
+ for i in range(1, len(segs) + 1):
93
+ names.add(".".join(segs[:i]))
94
+
95
+
96
+ def _package_of(repo_path: Path, file_path: Path) -> list[str]:
97
+ """Paquete al que pertenece el fichero (base de sus imports relativos)."""
98
+ return list(file_path.relative_to(repo_path).parts[:-1])
99
+
100
+
101
+ def _imports_from_source(repo_path: Path, file_path: Path, text: str) -> set[str]:
102
+ """Nombres de módulo que importa el fichero, con los relativos ya resueltos."""
103
+ names: set[str] = set()
104
+ try:
105
+ tree = ast.parse(text)
106
+ except (SyntaxError, ValueError):
107
+ for match in _IMPORT_RE.finditer(text): # Python que no parsea: la heurística de siempre
108
+ for token in (match.group(1) or match.group(2) or "").split(","):
109
+ _with_prefixes(names, token.strip().lstrip("."))
110
+ return names
111
+ package = _package_of(repo_path, file_path)
112
+ for node in ast.walk(tree):
113
+ if isinstance(node, ast.Import):
114
+ for alias in node.names:
115
+ _with_prefixes(names, alias.name)
116
+ elif isinstance(node, ast.ImportFrom):
117
+ if node.level:
118
+ base = package[:len(package) - (node.level - 1)] if node.level > 1 else package
119
+ module = ".".join(base + ([node.module] if node.module else []))
120
+ else:
121
+ module = node.module or ""
122
+ _with_prefixes(names, module)
123
+ for alias in node.names: # "from paquete import submodulo"
124
+ if alias.name != "*":
125
+ _with_prefixes(names, f"{module}.{alias.name}" if module else alias.name)
126
+ names.add(alias.name)
127
+ return names
128
+
129
+
130
+ def _entry_point_modules(repo_path: Path) -> set[str]:
131
+ names: set[str] = set()
132
+ pyproject = repo_path / "pyproject.toml"
133
+ if pyproject.is_file():
134
+ try:
135
+ project = tomllib.loads(pyproject.read_text(encoding="utf-8", errors="ignore")).get("project", {})
136
+ except tomllib.TOMLDecodeError:
137
+ project = {}
138
+ groups = [project.get("scripts", {}), project.get("gui-scripts", {}), *project.get("entry-points", {}).values()]
139
+ for group in groups:
140
+ for target in group.values():
141
+ _with_prefixes(names, str(target).split(":")[0].strip())
142
+ return names
143
+
144
+
145
+ def _python_m_modules(repo_path: Path, tracked: list[str]) -> set[str]:
146
+ names: set[str] = set()
147
+ for rel in tracked:
148
+ path = repo_path / rel
149
+ if path.suffix not in _TEXT_SUFFIXES:
150
+ continue
151
+ try:
152
+ text = path.read_text(encoding="utf-8", errors="ignore")
153
+ except OSError:
154
+ continue
155
+ for match in _PYTHON_M.finditer(text):
156
+ _with_prefixes(names, match.group(1).rstrip("."))
157
+ return names
158
+
159
+
160
+ def _tracked_files(repo_path: Path) -> list[str]:
161
+ try:
162
+ out = subprocess.run(["git", "-c", "core.quotePath=false", "ls-files"], cwd=repo_path, capture_output=True, text=True,
163
+ check=True, timeout=30)
164
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
165
+ return []
166
+ return [line for line in out.stdout.splitlines() if line]
167
+
168
+
169
+ class DeadFilesCheck:
170
+ name = "dead_files"
171
+ description = "Ficheros Python que ningún otro fichero del repo importa (heurística)."
172
+
173
+ def run(self, repo_path: Path) -> CheckResult:
174
+ py_files = _tracked_py_files(repo_path)
175
+ if py_files is None:
176
+ return CheckResult(
177
+ check_name=self.name,
178
+ summary="No aplica: no es un repositorio git.",
179
+ error="not_a_git_repo",
180
+ )
181
+ if not py_files:
182
+ return CheckResult(check_name=self.name, summary="No hay ficheros .py en el repo.")
183
+
184
+ imported_names = _entry_point_modules(repo_path) | _python_m_modules(repo_path, _tracked_files(repo_path))
185
+ for file_path in py_files:
186
+ try:
187
+ text = file_path.read_text(encoding="utf-8", errors="ignore")
188
+ except OSError:
189
+ continue
190
+ imported_names |= _imports_from_source(repo_path, file_path, text)
191
+
192
+ findings: list[Finding] = []
193
+ for file_path in py_files:
194
+ if _is_special(repo_path, file_path):
195
+ continue
196
+ candidates = _module_candidates(repo_path, file_path)
197
+ if candidates & imported_names:
198
+ continue
199
+ findings.append(Finding(
200
+ severity="low",
201
+ title="Fichero Python no importado por ningún otro fichero del repo",
202
+ detail="Heurística estática (sin ejecutar código) -- puede ser un falso "
203
+ "positivo si se carga dinámicamente o es un punto de entrada.",
204
+ path=str(file_path.relative_to(repo_path)),
205
+ ))
206
+
207
+ summary = f"{len(py_files)} fichero(s) .py analizados, {len(findings)} posible(s) huérfano(s)."
208
+ return CheckResult(check_name=self.name, summary=summary, findings=findings)
@@ -0,0 +1,131 @@
1
+ """Métricas basadas en el historial de git: hotspots de cambio, ramas
2
+ obsoletas, ficheros enormes en el repo.
3
+
4
+ Todo se calcula con un puñado de invocaciones a `git` (sin librerías
5
+ externas) -- si el directorio no es un repo git, el check lo señala como
6
+ no aplicable en vez de fallar.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import subprocess
11
+ import time
12
+ from collections import Counter
13
+ from pathlib import Path
14
+
15
+ from ..plugin import CheckResult, Finding
16
+
17
+ _STALE_BRANCH_DAYS = 180
18
+ _TOP_HOTSPOTS = 10
19
+ _LARGE_FILE_BYTES = 1 * 1024 * 1024
20
+
21
+
22
+ def _git(repo_path: Path, *args: str) -> str | None:
23
+ try:
24
+ out = subprocess.run(
25
+ # quotePath=false: sin esto git escapa las rutas no ASCII ("v\303\255deo.bin") y no se
26
+ # podían abrir: un fichero grande con tildes en el nombre se saltaba en silencio
27
+ ["git", "-c", "core.quotePath=false", *args], cwd=repo_path, capture_output=True, text=True,
28
+ check=True, timeout=60,
29
+ )
30
+ return out.stdout
31
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
32
+ return None
33
+
34
+
35
+ def _is_git_repo(repo_path: Path) -> bool:
36
+ return _git(repo_path, "rev-parse", "--is-inside-work-tree") is not None
37
+
38
+
39
+ def _churn_hotspots(repo_path: Path) -> list[Finding]:
40
+ log = _git(repo_path, "log", "--pretty=format:__COMMIT__", "--name-only")
41
+ if not log:
42
+ return []
43
+ counts: Counter[str] = Counter()
44
+ for line in log.splitlines():
45
+ if line and line != "__COMMIT__":
46
+ counts[line] += 1
47
+ findings: list[Finding] = []
48
+ current = set((_git(repo_path, "ls-files") or "").splitlines())
49
+ counts = Counter({p: c for p, c in counts.items() if p in current}) # sin ficheros ya borrados
50
+ for path, count in counts.most_common(_TOP_HOTSPOTS):
51
+ if count < 5: # no merece la pena senalar ficheros con pocos cambios
52
+ continue
53
+ findings.append(Finding(
54
+ severity="info",
55
+ title=f"Hotspot de cambios: {count} commits lo tocan",
56
+ detail="Cambia con mucha frecuencia -- candidato a revisar cobertura de tests y complejidad.",
57
+ path=path,
58
+ ))
59
+ return findings
60
+
61
+
62
+ def _stale_branches(repo_path: Path) -> list[Finding]:
63
+ out = _git(
64
+ repo_path, "for-each-ref", "--format=%(refname)|%(committerdate:unix)|%(symref)",
65
+ "refs/heads", "refs/remotes",
66
+ )
67
+ if not out:
68
+ return []
69
+ # La rama actual y la rama por defecto del remoto (destino de origin/HEAD) no son «candidatas
70
+ # a borrar» aunque lleven tiempo sin commits: en un proyecto estable main salía como obsoleta.
71
+ current = (_git(repo_path, "symbolic-ref", "-q", "HEAD") or "").strip()
72
+ rows = [line.split("|") for line in out.splitlines() if line.count("|") == 2]
73
+ protected = {current} | {symref for _, _, symref in rows if symref}
74
+ now = time.time()
75
+ findings: list[Finding] = []
76
+ for ref, ts, symref in rows:
77
+ if symref or ref in protected or not ts.strip().isdigit():
78
+ continue
79
+ age_days = (now - int(ts)) / 86400
80
+ if age_days > _STALE_BRANCH_DAYS:
81
+ name = ref.removeprefix("refs/heads/").removeprefix("refs/remotes/")
82
+ findings.append(Finding(
83
+ severity="info",
84
+ title=f"Rama sin commits desde hace {int(age_days)} días: {name}",
85
+ detail="Candidata a borrar si ya no está en uso.",
86
+ ))
87
+ return findings
88
+
89
+
90
+ def _large_tracked_files(repo_path: Path) -> list[Finding]:
91
+ out = _git(repo_path, "ls-files")
92
+ if out is None:
93
+ return []
94
+ findings: list[Finding] = []
95
+ for rel in out.splitlines():
96
+ if not rel:
97
+ continue
98
+ full = repo_path / rel
99
+ try:
100
+ size = full.stat().st_size
101
+ except OSError:
102
+ continue
103
+ if size > _LARGE_FILE_BYTES:
104
+ findings.append(Finding(
105
+ severity="low",
106
+ title=f"Fichero grande en el repo: {size / (1024 * 1024):.1f} MB",
107
+ detail="Considera Git LFS o excluirlo si es un artefacto generado/binario.",
108
+ path=rel,
109
+ ))
110
+ return findings
111
+
112
+
113
+ class GitHotspotsCheck:
114
+ name = "git_hotspots"
115
+ description = "Hotspots de cambio, ramas obsoletas y ficheros enormes según el historial de git."
116
+
117
+ def run(self, repo_path: Path) -> CheckResult:
118
+ if not _is_git_repo(repo_path):
119
+ return CheckResult(
120
+ check_name=self.name,
121
+ summary="No aplica: no es un repositorio git.",
122
+ error="not_a_git_repo",
123
+ )
124
+
125
+ findings = [
126
+ *_churn_hotspots(repo_path),
127
+ *_stale_branches(repo_path),
128
+ *_large_tracked_files(repo_path),
129
+ ]
130
+ summary = f"{len(findings)} hallazgo(s) sobre el historial de git."
131
+ return CheckResult(check_name=self.name, summary=summary, findings=findings)