diskwhy 0.1.7__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 (34) hide show
  1. diskwhy-0.1.7/LICENSE +21 -0
  2. diskwhy-0.1.7/PKG-INFO +121 -0
  3. diskwhy-0.1.7/README.md +86 -0
  4. diskwhy-0.1.7/diskwhy/__init__.py +3 -0
  5. diskwhy-0.1.7/diskwhy/__main__.py +6 -0
  6. diskwhy-0.1.7/diskwhy/checks/__init__.py +0 -0
  7. diskwhy-0.1.7/diskwhy/checks/docker_reclaimable.py +76 -0
  8. diskwhy-0.1.7/diskwhy/checks/duplicate_lockfiles.py +64 -0
  9. diskwhy-0.1.7/diskwhy/checks/orphaned_envs.py +57 -0
  10. diskwhy-0.1.7/diskwhy/checks/reclaimable_dirs.py +63 -0
  11. diskwhy-0.1.7/diskwhy/cli.py +75 -0
  12. diskwhy-0.1.7/diskwhy/fs.py +41 -0
  13. diskwhy-0.1.7/diskwhy/patterns.py +61 -0
  14. diskwhy-0.1.7/diskwhy/plugin.py +34 -0
  15. diskwhy-0.1.7/diskwhy/report.py +59 -0
  16. diskwhy-0.1.7/diskwhy/runner.py +41 -0
  17. diskwhy-0.1.7/diskwhy.egg-info/PKG-INFO +121 -0
  18. diskwhy-0.1.7/diskwhy.egg-info/SOURCES.txt +32 -0
  19. diskwhy-0.1.7/diskwhy.egg-info/dependency_links.txt +1 -0
  20. diskwhy-0.1.7/diskwhy.egg-info/entry_points.txt +8 -0
  21. diskwhy-0.1.7/diskwhy.egg-info/requires.txt +6 -0
  22. diskwhy-0.1.7/diskwhy.egg-info/top_level.txt +1 -0
  23. diskwhy-0.1.7/pyproject.toml +68 -0
  24. diskwhy-0.1.7/setup.cfg +4 -0
  25. diskwhy-0.1.7/tests/test_cli.py +48 -0
  26. diskwhy-0.1.7/tests/test_docker_reclaimable.py +66 -0
  27. diskwhy-0.1.7/tests/test_duplicate_lockfiles.py +33 -0
  28. diskwhy-0.1.7/tests/test_fs.py +51 -0
  29. diskwhy-0.1.7/tests/test_orphaned_envs.py +48 -0
  30. diskwhy-0.1.7/tests/test_plugin.py +18 -0
  31. diskwhy-0.1.7/tests/test_reclaimable_dirs.py +59 -0
  32. diskwhy-0.1.7/tests/test_report.py +55 -0
  33. diskwhy-0.1.7/tests/test_runner.py +39 -0
  34. diskwhy-0.1.7/tests/test_version.py +11 -0
diskwhy-0.1.7/LICENSE ADDED
@@ -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.
diskwhy-0.1.7/PKG-INFO ADDED
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: diskwhy
3
+ Version: 0.1.7
4
+ Summary: Explica por qué una carpeta pesa tanto y qué es seguro borrar: node_modules/venvs regenerables, entornos huérfanos, lockfiles duplicados, espacio reclamable de Docker.
5
+ Author: José Luis Segura Yuste
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/jl-segurayuste/diskwhy
8
+ Project-URL: Source, https://github.com/jl-segurayuste/diskwhy
9
+ Project-URL: Issues, https://github.com/jl-segurayuste/diskwhy/issues
10
+ Project-URL: Changelog, https://github.com/jl-segurayuste/diskwhy/releases
11
+ Keywords: developer-tools,disk-usage,sysadmin
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: Natural Language :: Spanish
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Topic :: System :: Filesystems
25
+ Classifier: Topic :: System :: Systems Administration
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: pydantic>=2.6
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.4; extra == "dev"
32
+ Requires-Dist: pytest-cov>=5; extra == "dev"
33
+ Requires-Dist: ruff==0.17.6; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # diskwhy
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/diskwhy.svg)](https://pypi.org/project/diskwhy/)
39
+ [![CI](https://github.com/jl-segurayuste/diskwhy/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/diskwhy/actions/workflows/ci.yml)
40
+ [![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/diskwhy/blob/main/pyproject.toml)
41
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/diskwhy/blob/main/LICENSE)
42
+
43
+ Un `du` que explica *por qué* una carpeta pesa tanto y qué es seguro borrar —
44
+ en vez de solo mostrarte números y dejarte adivinar.
45
+
46
+ ```
47
+ $ diskwhy scan ~/projects
48
+
49
+ diskwhy — /home/usuario/projects
50
+
51
+ ── reclaimable_dirs ─────────────────────
52
+ 4 carpeta(s) regenerables, 3.2 GB recuperables en total.
53
+ [INFO ] node_modules (1.8 GB) (/home/usuario/projects/app/node_modules)
54
+ Regenerable -- seguro borrar y reinstalar/reconstruir cuando haga falta.
55
+ [INFO ] .venv (900 MB) (/home/usuario/projects/api/.venv)
56
+ Regenerable -- seguro borrar y reinstalar/reconstruir cuando haga falta.
57
+
58
+ ── orphaned_envs ────────────────────────
59
+ 3 entorno(s) virtual(es) revisado(s), 1 huérfano(s).
60
+ [HIGH ] Entorno huérfano (400 MB) (/home/usuario/projects/old-script/.venv)
61
+ No hay pyproject.toml/requirements.txt/setup.py junto a este venv --
62
+ el proyecto probablemente ya no existe.
63
+
64
+ Total: 6 hallazgo(s).
65
+ ```
66
+
67
+ ## Así se ve
68
+
69
+ ![Salida de diskwhy sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/diskwhy/main/docs/img/demo.svg)
70
+
71
+ <sub>Ejecución real sobre una carpeta de proyectos con `node_modules`, entornos virtuales (uno huérfano) y lockfiles duplicados (todos los datos son ficticios).</sub>
72
+
73
+ ## Por qué existe
74
+
75
+ `du -sh */` te dice qué carpeta pesa más, pero no te dice si es seguro
76
+ borrarla. `diskwhy` sí: distingue entre "esto es regenerable" (node_modules,
77
+ venvs, cachés de build), "esto es un venv sin proyecto detrás" (candidato de
78
+ alta confianza para borrar del todo) y "esto son dependencias duplicadas
79
+ entre proyectos" — sin borrar nada por su cuenta, solo diagnostica.
80
+
81
+ ## Instalación
82
+
83
+ Todavía no está en PyPI:
84
+
85
+ ```bash
86
+ pipx install diskwhy # recomendado para herramientas de línea de comandos
87
+ # o bien
88
+ pip install diskwhy
89
+ ```
90
+
91
+ ## Uso
92
+
93
+ ```bash
94
+ diskwhy scan . # informe en consola
95
+ diskwhy scan . --only reclaimable_dirs # solo un check
96
+ diskwhy scan . --json
97
+ diskwhy scan . --fail-on high # código de salida 1 si hay algo "high"
98
+ # código 2 si algún check no se pudo ejecutar (análisis incompleto)
99
+ diskwhy list-checks
100
+ ```
101
+
102
+ ## Checks incluidos
103
+
104
+ | Check | Qué detecta |
105
+ |---|---|
106
+ | `reclaimable_dirs` | `node_modules`, `__pycache__`, `.venv`/`venv`, cachés de build (`dist`, `.next`, `.tox`...) — regenerables, seguro borrar |
107
+ | `orphaned_envs` | Un `.venv`/`venv` sin ningún fichero de dependencias al lado — el proyecto probablemente ya no existe |
108
+ | `duplicate_lockfiles` | Lockfiles idénticos en proyectos distintos — candidatos a compartir cache de paquetes en vez de duplicar `node_modules` |
109
+ | `docker_reclaimable` | Espacio reclamable de Docker (`docker system df`) — solo lee, nunca ejecuta `docker system prune` |
110
+
111
+ Ningún check borra nada ni ejecuta código de lo que analiza — solo lee el
112
+ árbol de ficheros e introspecciona tamaños. Cada check es un plugin
113
+ independiente (`importlib.metadata.entry_points`, grupo `diskwhy.checks`).
114
+
115
+ ## Desarrollo
116
+
117
+ ```bash
118
+ pip install -e ".[dev]"
119
+ ruff check .
120
+ pytest
121
+ ```
@@ -0,0 +1,86 @@
1
+ # diskwhy
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/diskwhy.svg)](https://pypi.org/project/diskwhy/)
4
+ [![CI](https://github.com/jl-segurayuste/diskwhy/actions/workflows/ci.yml/badge.svg)](https://github.com/jl-segurayuste/diskwhy/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/diskwhy/blob/main/pyproject.toml)
6
+ [![Licencia MIT](https://img.shields.io/badge/licencia-MIT-green.svg)](https://github.com/jl-segurayuste/diskwhy/blob/main/LICENSE)
7
+
8
+ Un `du` que explica *por qué* una carpeta pesa tanto y qué es seguro borrar —
9
+ en vez de solo mostrarte números y dejarte adivinar.
10
+
11
+ ```
12
+ $ diskwhy scan ~/projects
13
+
14
+ diskwhy — /home/usuario/projects
15
+
16
+ ── reclaimable_dirs ─────────────────────
17
+ 4 carpeta(s) regenerables, 3.2 GB recuperables en total.
18
+ [INFO ] node_modules (1.8 GB) (/home/usuario/projects/app/node_modules)
19
+ Regenerable -- seguro borrar y reinstalar/reconstruir cuando haga falta.
20
+ [INFO ] .venv (900 MB) (/home/usuario/projects/api/.venv)
21
+ Regenerable -- seguro borrar y reinstalar/reconstruir cuando haga falta.
22
+
23
+ ── orphaned_envs ────────────────────────
24
+ 3 entorno(s) virtual(es) revisado(s), 1 huérfano(s).
25
+ [HIGH ] Entorno huérfano (400 MB) (/home/usuario/projects/old-script/.venv)
26
+ No hay pyproject.toml/requirements.txt/setup.py junto a este venv --
27
+ el proyecto probablemente ya no existe.
28
+
29
+ Total: 6 hallazgo(s).
30
+ ```
31
+
32
+ ## Así se ve
33
+
34
+ ![Salida de diskwhy sobre un proyecto de ejemplo](https://raw.githubusercontent.com/jl-segurayuste/diskwhy/main/docs/img/demo.svg)
35
+
36
+ <sub>Ejecución real sobre una carpeta de proyectos con `node_modules`, entornos virtuales (uno huérfano) y lockfiles duplicados (todos los datos son ficticios).</sub>
37
+
38
+ ## Por qué existe
39
+
40
+ `du -sh */` te dice qué carpeta pesa más, pero no te dice si es seguro
41
+ borrarla. `diskwhy` sí: distingue entre "esto es regenerable" (node_modules,
42
+ venvs, cachés de build), "esto es un venv sin proyecto detrás" (candidato de
43
+ alta confianza para borrar del todo) y "esto son dependencias duplicadas
44
+ entre proyectos" — sin borrar nada por su cuenta, solo diagnostica.
45
+
46
+ ## Instalación
47
+
48
+ Todavía no está en PyPI:
49
+
50
+ ```bash
51
+ pipx install diskwhy # recomendado para herramientas de línea de comandos
52
+ # o bien
53
+ pip install diskwhy
54
+ ```
55
+
56
+ ## Uso
57
+
58
+ ```bash
59
+ diskwhy scan . # informe en consola
60
+ diskwhy scan . --only reclaimable_dirs # solo un check
61
+ diskwhy scan . --json
62
+ diskwhy scan . --fail-on high # código de salida 1 si hay algo "high"
63
+ # código 2 si algún check no se pudo ejecutar (análisis incompleto)
64
+ diskwhy list-checks
65
+ ```
66
+
67
+ ## Checks incluidos
68
+
69
+ | Check | Qué detecta |
70
+ |---|---|
71
+ | `reclaimable_dirs` | `node_modules`, `__pycache__`, `.venv`/`venv`, cachés de build (`dist`, `.next`, `.tox`...) — regenerables, seguro borrar |
72
+ | `orphaned_envs` | Un `.venv`/`venv` sin ningún fichero de dependencias al lado — el proyecto probablemente ya no existe |
73
+ | `duplicate_lockfiles` | Lockfiles idénticos en proyectos distintos — candidatos a compartir cache de paquetes en vez de duplicar `node_modules` |
74
+ | `docker_reclaimable` | Espacio reclamable de Docker (`docker system df`) — solo lee, nunca ejecuta `docker system prune` |
75
+
76
+ Ningún check borra nada ni ejecuta código de lo que analiza — solo lee el
77
+ árbol de ficheros e introspecciona tamaños. Cada check es un plugin
78
+ independiente (`importlib.metadata.entry_points`, grupo `diskwhy.checks`).
79
+
80
+ ## Desarrollo
81
+
82
+ ```bash
83
+ pip install -e ".[dev]"
84
+ ruff check .
85
+ pytest
86
+ ```
@@ -0,0 +1,3 @@
1
+ """diskwhy — explica por qué una carpeta pesa tanto y qué es seguro borrar."""
2
+
3
+ __version__ = "0.1.7"
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from diskwhy.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
File without changes
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import shutil
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from diskwhy.plugin import CheckResult, Finding
9
+
10
+
11
+ class DockerReclaimableCheck:
12
+ """Espacio reclamable de Docker (imágenes sin usar, cache de build, contenedores parados) vía `docker system df` -- solo lee, nunca ejecuta `docker system prune` por su cuenta."""
13
+
14
+ name = "docker_reclaimable"
15
+
16
+ def run(self, root: Path) -> CheckResult:
17
+ del root # no depende del árbol de ficheros, solo consulta al daemon de Docker
18
+ if shutil.which("docker") is None:
19
+ return CheckResult(
20
+ check_name=self.name,
21
+ summary="No aplica: docker no está instalado o no está en el PATH.",
22
+ )
23
+
24
+ try:
25
+ result = subprocess.run(
26
+ ["docker", "system", "df", "--format", "{{json .}}"],
27
+ capture_output=True,
28
+ text=True,
29
+ timeout=15,
30
+ check=False,
31
+ )
32
+ except (OSError, subprocess.TimeoutExpired):
33
+ return CheckResult(
34
+ check_name=self.name,
35
+ summary="No aplica: no se pudo ejecutar 'docker system df'.",
36
+ )
37
+
38
+ if result.returncode != 0:
39
+ return CheckResult(
40
+ check_name=self.name,
41
+ summary="No aplica: 'docker system df' falló (¿el daemon de Docker está corriendo?).",
42
+ )
43
+
44
+ findings: list[Finding] = []
45
+ for line in result.stdout.splitlines():
46
+ line = line.strip()
47
+ if not line:
48
+ continue
49
+ try:
50
+ row = json.loads(line)
51
+ except json.JSONDecodeError:
52
+ continue
53
+ reclaimable = row.get("Reclaimable", "")
54
+ # OJO: no usar `.startswith("0")` -- un valor real como "0.5GB (10%)"
55
+ # también empieza por "0" y se descartaría como si fuera cero. Docker
56
+ # solo representa el cero exacto como "0B" (no hay unidad más pequeña
57
+ # que el byte, así que nunca hay un "0.xxx B"), con o sin porcentaje
58
+ # detrás -- ese es el único prefijo que de verdad significa "nada".
59
+ if not reclaimable or reclaimable.strip().startswith("0B"):
60
+ continue
61
+ findings.append(
62
+ Finding(
63
+ severity="info",
64
+ title=f"{row.get('Type', '?')}: {reclaimable} reclamable",
65
+ detail=(
66
+ f"Total: {row.get('Size', '?')}. "
67
+ "Revisar con 'docker system df -v' antes de un 'docker system prune'."
68
+ ),
69
+ )
70
+ )
71
+
72
+ return CheckResult(
73
+ check_name=self.name,
74
+ summary=f"{len(findings)} categoría(s) de Docker con espacio reclamable.",
75
+ findings=findings,
76
+ )
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+
8
+ from diskwhy.patterns import LOCKFILE_NAMES
9
+ from diskwhy.plugin import CheckResult, Finding
10
+
11
+
12
+ def _find_lockfiles(root: Path):
13
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
14
+ if "node_modules" in dirnames:
15
+ dirnames.remove("node_modules") # nunca hay lockfiles utiles ahi dentro
16
+ for name in filenames:
17
+ if name in LOCKFILE_NAMES:
18
+ yield Path(dirpath) / name
19
+
20
+
21
+ def _hash_file(path: Path) -> str | None:
22
+ try:
23
+ return hashlib.sha256(path.read_bytes()).hexdigest()
24
+ except OSError:
25
+ return None
26
+
27
+
28
+ class DuplicateLockfilesCheck:
29
+ """Lockfiles (package-lock.json/yarn.lock/pnpm-lock.yaml) con contenido idéntico en proyectos distintos -- candidatos a compartir un cache global del gestor de paquetes en vez de duplicar node_modules por completo."""
30
+
31
+ name = "duplicate_lockfiles"
32
+
33
+ def run(self, root: Path) -> CheckResult:
34
+ by_hash: dict[str, list[Path]] = defaultdict(list)
35
+ scanned = 0
36
+ for lockfile in _find_lockfiles(root):
37
+ digest = _hash_file(lockfile)
38
+ if digest is None:
39
+ continue
40
+ scanned += 1
41
+ by_hash[digest].append(lockfile)
42
+
43
+ findings: list[Finding] = []
44
+ for digest, paths in by_hash.items():
45
+ if len(paths) < 2:
46
+ continue
47
+ paths_str = ", ".join(str(p) for p in paths)
48
+ findings.append(
49
+ Finding(
50
+ severity="info",
51
+ title=f"{len(paths)} lockfiles idénticos ({paths[0].name})",
52
+ detail=(
53
+ f"Mismas dependencias exactas en: {paths_str}. "
54
+ "Considera un gestor de paquetes con cache global (pnpm) "
55
+ "para no duplicar node_modules por completo."
56
+ ),
57
+ )
58
+ )
59
+
60
+ return CheckResult(
61
+ check_name=self.name,
62
+ summary=f"{scanned} lockfile(s) analizados, {len(findings)} grupo(s) duplicado(s).",
63
+ findings=findings,
64
+ )
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ from diskwhy.fs import dir_size, human_size
7
+ from diskwhy.patterns import PROJECT_MARKER_FILES, PROJECT_MARKER_GLOBS, VENV_DIR_NAMES
8
+ from diskwhy.plugin import CheckResult, Finding
9
+
10
+
11
+ def _find_venv_dirs(root: Path):
12
+ for dirpath, dirnames, _filenames in os.walk(root, followlinks=False):
13
+ keep = []
14
+ for name in dirnames:
15
+ if name in VENV_DIR_NAMES:
16
+ yield Path(dirpath) / name
17
+ else:
18
+ keep.append(name)
19
+ dirnames[:] = keep
20
+
21
+
22
+ def _has_project_markers(parent: Path) -> bool:
23
+ # Antes solo los nombres fijos: un proyecto con requirements-dev.txt, uv.lock o solo scripts
24
+ # salía como huérfano con gravedad alta.
25
+ if any((parent / marker).exists() for marker in PROJECT_MARKER_FILES):
26
+ return True
27
+ return any(next(parent.glob(pattern), None) is not None for pattern in PROJECT_MARKER_GLOBS)
28
+
29
+
30
+ class OrphanedEnvsCheck:
31
+ """Entornos virtuales (.venv/venv) cuyo proyecto ya no tiene ningún fichero de dependencias al lado -- probablemente el proyecto se borró y el venv se quedó atrás."""
32
+
33
+ name = "orphaned_envs"
34
+
35
+ def run(self, root: Path) -> CheckResult:
36
+ findings: list[Finding] = []
37
+ scanned = 0
38
+ for venv_dir in _find_venv_dirs(root):
39
+ scanned += 1
40
+ if not _has_project_markers(venv_dir.parent):
41
+ size = dir_size(venv_dir)
42
+ findings.append(
43
+ Finding(
44
+ severity="high",
45
+ title=f"Entorno huérfano ({human_size(size)})",
46
+ detail="No hay pyproject.toml/requirements.txt/setup.py junto a este venv -- el proyecto probablemente ya no existe.",
47
+ path=str(venv_dir),
48
+ size_bytes=size,
49
+ )
50
+ )
51
+
52
+ findings.sort(key=lambda f: f.size_bytes or 0, reverse=True)
53
+ return CheckResult(
54
+ check_name=self.name,
55
+ summary=f"{scanned} entorno(s) virtual(es) revisado(s), {len(findings)} huérfano(s).",
56
+ findings=findings,
57
+ )
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ from diskwhy.fs import dir_size, human_size
8
+ from diskwhy.patterns import AMBIGUOUS_DIR_NAMES, RECLAIMABLE_DIR_NAMES
9
+ from diskwhy.plugin import CheckResult, Finding
10
+
11
+
12
+ def _has_tracked_files(path: Path) -> bool:
13
+ """True si git tiene ficheros versionados dentro: entonces es código, no algo regenerable."""
14
+ try:
15
+ out = subprocess.run(
16
+ ["git", "-c", "core.quotePath=false", "ls-files", "--", "."], cwd=path, capture_output=True, text=True, timeout=30, check=False
17
+ )
18
+ except (OSError, subprocess.TimeoutExpired):
19
+ return False
20
+ return out.returncode == 0 and bool(out.stdout.strip())
21
+
22
+
23
+ def _find_junk_dirs(root: Path):
24
+ for dirpath, dirnames, _filenames in os.walk(root, followlinks=False):
25
+ keep = []
26
+ for name in dirnames:
27
+ if name in AMBIGUOUS_DIR_NAMES and _has_tracked_files(Path(dirpath) / name):
28
+ keep.append(name) # carpeta de código: se recorre como cualquier otra
29
+ elif name in RECLAIMABLE_DIR_NAMES:
30
+ yield Path(dirpath) / name
31
+ # no descender dentro -- evita contar cachés anidadas dos veces
32
+ else:
33
+ keep.append(name)
34
+ dirnames[:] = keep
35
+
36
+
37
+ class ReclaimableDirsCheck:
38
+ """Carpetas regenerables (node_modules, __pycache__, venvs, cachés de build...) -- seguro borrar y reinstalar/reconstruir cuando haga falta."""
39
+
40
+ name = "reclaimable_dirs"
41
+
42
+ def run(self, root: Path) -> CheckResult:
43
+ findings: list[Finding] = []
44
+ total = 0
45
+ for junk_dir in _find_junk_dirs(root):
46
+ size = dir_size(junk_dir)
47
+ total += size
48
+ findings.append(
49
+ Finding(
50
+ severity="info",
51
+ title=f"{junk_dir.name} ({human_size(size)})",
52
+ detail="Regenerable -- seguro borrar y reinstalar/reconstruir cuando haga falta.",
53
+ path=str(junk_dir),
54
+ size_bytes=size,
55
+ )
56
+ )
57
+
58
+ findings.sort(key=lambda f: f.size_bytes or 0, reverse=True)
59
+ return CheckResult(
60
+ check_name=self.name,
61
+ summary=f"{len(findings)} carpeta(s) regenerables, {human_size(total)} recuperables en total.",
62
+ findings=findings,
63
+ )
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from diskwhy import __version__
8
+ from diskwhy.plugin import SEVERITIES
9
+ from diskwhy.report import build_report, write_json
10
+ from diskwhy.runner import discover_checks, run_checks
11
+
12
+ _SEVERITY_ORDER = {sev: idx for idx, sev in enumerate(SEVERITIES)}
13
+
14
+
15
+ def _cmd_scan(args: argparse.Namespace) -> int:
16
+ root = Path(args.path).resolve()
17
+ only = set(args.only) if args.only else None
18
+ skip = set(args.skip) if args.skip else None
19
+
20
+ results = run_checks(root, only=only, skip=skip)
21
+ report = build_report(root, results)
22
+
23
+ if args.json:
24
+ print(write_json(report))
25
+ else:
26
+ print(report.to_console())
27
+
28
+ # Un check que revienta deja el análisis incompleto: antes solo se avisaba y salía 0 (o 1 según
29
+ # --fail-on), y en un CI pasaba por verde sin haber mirado lo que ese check mira.
30
+ failed = [r.check_name for r in results if r.error]
31
+ if failed:
32
+ print(f"error: no se pudieron ejecutar: {', '.join(failed)} (análisis incompleto)", file=sys.stderr)
33
+ return 2
34
+
35
+ if args.fail_on:
36
+ worst = report.worst_severity()
37
+ if worst is not None and _SEVERITY_ORDER[worst] >= _SEVERITY_ORDER[args.fail_on]:
38
+ return 1
39
+ return 0
40
+
41
+
42
+ def _cmd_list_checks(args: argparse.Namespace) -> int:
43
+ for name, cls in sorted(discover_checks().items()):
44
+ doc = (cls.__doc__ or "").strip().splitlines()[0] if cls.__doc__ else ""
45
+ print(f"{name}: {doc}")
46
+ return 0
47
+
48
+
49
+ def build_parser() -> argparse.ArgumentParser:
50
+ parser = argparse.ArgumentParser(prog="diskwhy")
51
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
52
+ sub = parser.add_subparsers(dest="command", required=True)
53
+
54
+ p_scan = sub.add_parser("scan", help="Analiza una carpeta en busca de espacio recuperable")
55
+ p_scan.add_argument("path", nargs="?", default=".")
56
+ p_scan.add_argument("--only", action="append", help="Ejecutar solo este check (repetible)")
57
+ p_scan.add_argument("--skip", action="append", help="Saltar este check (repetible)")
58
+ p_scan.add_argument("--json", action="store_true")
59
+ p_scan.add_argument("--fail-on", choices=SEVERITIES, default=None)
60
+ p_scan.set_defaults(func=_cmd_scan)
61
+
62
+ p_list = sub.add_parser("list-checks", help="Lista los checks instalados")
63
+ p_list.set_defaults(func=_cmd_list_checks)
64
+
65
+ return parser
66
+
67
+
68
+ def main(argv: list[str] | None = None) -> int:
69
+ parser = build_parser()
70
+ args = parser.parse_args(argv)
71
+ return args.func(args)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ sys.exit(main())
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import stat
5
+ from pathlib import Path
6
+
7
+
8
+ def dir_size(path: Path) -> int:
9
+ """Espacio que ocupa de verdad en disco, como `du`.
10
+
11
+ Se cuentan los bloques asignados (no `st_size`: un disco de VM disperso de 10 GB que ocupa
12
+ 4 KB salía como 10 GB) y cada inodo una sola vez (los enlaces duros de pnpm, ccache o
13
+ `cp -al` se sumaban una vez por enlace).
14
+ """
15
+ total = 0
16
+ seen: set[tuple[int, int]] = set()
17
+ for dirpath, _dirnames, filenames in os.walk(path, followlinks=False):
18
+ for name in filenames:
19
+ try:
20
+ st = os.lstat(os.path.join(dirpath, name))
21
+ except OSError:
22
+ continue
23
+ if stat.S_ISLNK(st.st_mode):
24
+ continue
25
+ if st.st_nlink > 1:
26
+ key = (st.st_dev, st.st_ino)
27
+ if key in seen:
28
+ continue
29
+ seen.add(key)
30
+ blocks = getattr(st, "st_blocks", None) # no existe en Windows
31
+ total += blocks * 512 if blocks is not None else st.st_size
32
+ return total
33
+
34
+
35
+ def human_size(num_bytes: int) -> str:
36
+ size = float(num_bytes)
37
+ for unit in ("B", "KB", "MB", "GB", "TB"):
38
+ if size < 1024 or unit == "TB":
39
+ return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} {unit}"
40
+ size /= 1024
41
+ return f"{size:.1f} TB"