diskwhy 0.1.7__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.
diskwhy/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """diskwhy — explica por qué una carpeta pesa tanto y qué es seguro borrar."""
2
+
3
+ __version__ = "0.1.7"
diskwhy/__main__.py ADDED
@@ -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
+ )
diskwhy/cli.py ADDED
@@ -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())
diskwhy/fs.py ADDED
@@ -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"
diskwhy/patterns.py ADDED
@@ -0,0 +1,61 @@
1
+ RECLAIMABLE_DIR_NAMES: frozenset[str] = frozenset(
2
+ {
3
+ "node_modules",
4
+ "__pycache__",
5
+ ".venv",
6
+ "venv",
7
+ ".pytest_cache",
8
+ ".ruff_cache",
9
+ ".mypy_cache",
10
+ "dist",
11
+ "build",
12
+ ".tox",
13
+ "target",
14
+ ".next",
15
+ ".nuxt",
16
+ ".cache",
17
+ ".parcel-cache",
18
+ "coverage",
19
+ "htmlcov",
20
+ ".gradle",
21
+ ".terraform",
22
+ }
23
+ )
24
+
25
+ # Ficheros que, si están junto a un .venv/venv, indican que el proyecto
26
+ # sigue existiendo (el venv no está huérfano).
27
+ PROJECT_MARKER_FILES: frozenset[str] = frozenset(
28
+ {
29
+ "pyproject.toml",
30
+ "requirements.txt",
31
+ "setup.py",
32
+ "setup.cfg",
33
+ "Pipfile",
34
+ "Pipfile.lock",
35
+ "poetry.lock",
36
+ "uv.lock",
37
+ "pdm.lock",
38
+ "pixi.toml",
39
+ "environment.yml",
40
+ "environment.yaml",
41
+ "tox.ini",
42
+ "hatch.toml",
43
+ "requirements", # directorio requirements/base.txt, dev.txt...
44
+ }
45
+ )
46
+ # Además de los anteriores: requirements-dev.txt, código o notebooks sueltos junto al venv.
47
+ PROJECT_MARKER_GLOBS: tuple[str, ...] = ("requirements*.txt", "*.py", "*.ipynb")
48
+
49
+ # Nombres que también se usan para carpetas de código (el build/ de un proyecto Go, un dist/ que
50
+ # se publica...): solo son regenerables si git no tiene ficheros dentro.
51
+ AMBIGUOUS_DIR_NAMES: frozenset[str] = frozenset({"build", "dist", "target", "coverage", ".cache"})
52
+
53
+ VENV_DIR_NAMES: frozenset[str] = frozenset({".venv", "venv"})
54
+
55
+ LOCKFILE_NAMES: frozenset[str] = frozenset(
56
+ {
57
+ "package-lock.json",
58
+ "yarn.lock",
59
+ "pnpm-lock.yaml",
60
+ }
61
+ )
diskwhy/plugin.py ADDED
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Protocol
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+ Severity = str
9
+ SEVERITIES: tuple[Severity, ...] = ("info", "low", "medium", "high")
10
+
11
+
12
+ class Finding(BaseModel):
13
+ severity: Severity
14
+ title: str
15
+ detail: str = ""
16
+ path: str | None = None
17
+ size_bytes: int | None = None
18
+
19
+ def model_post_init(self, context: object, /) -> None:
20
+ if self.severity not in SEVERITIES:
21
+ raise ValueError(f"severity {self.severity!r} no es una de {SEVERITIES}")
22
+
23
+
24
+ class CheckResult(BaseModel):
25
+ check_name: str
26
+ summary: str
27
+ findings: list[Finding] = Field(default_factory=list)
28
+ error: str | None = None
29
+
30
+
31
+ class Check(Protocol):
32
+ name: str
33
+
34
+ def run(self, root: Path) -> CheckResult: ...
diskwhy/report.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from pydantic import BaseModel
7
+
8
+ from diskwhy.plugin import SEVERITIES, CheckResult
9
+
10
+ _SEVERITY_ORDER = {sev: idx for idx, sev in enumerate(SEVERITIES)}
11
+
12
+
13
+ class Report(BaseModel):
14
+ root: str
15
+ results: list[CheckResult]
16
+
17
+ def all_findings(self) -> list[tuple[str, object]]:
18
+ return [(r.check_name, f) for r in self.results for f in r.findings]
19
+
20
+ def worst_severity(self) -> str | None:
21
+ sevs = [f.severity for _, f in self.all_findings()]
22
+ if not sevs:
23
+ return None
24
+ return max(sevs, key=lambda s: _SEVERITY_ORDER[s])
25
+
26
+ def total_reclaimable_bytes(self) -> int:
27
+ return sum(f.size_bytes or 0 for _, f in self.all_findings())
28
+
29
+ def to_json(self) -> str:
30
+ return self.model_dump_json(indent=2)
31
+
32
+ def to_console(self) -> str:
33
+ lines = [f"diskwhy — {self.root}", ""]
34
+ for result in self.results:
35
+ lines.append(f"── {result.check_name} " + "─" * max(0, 40 - len(result.check_name)))
36
+ if result.error:
37
+ lines.append(f" ERROR: {result.summary}")
38
+ lines.append("")
39
+ continue
40
+ lines.append(f" {result.summary}")
41
+ for f in result.findings:
42
+ loc = f" ({f.path})" if f.path else ""
43
+ label = f"[{f.severity.upper():<6}]"
44
+ lines.append(f" {label} {f.title}{loc}")
45
+ if f.detail:
46
+ lines.append(f" {f.detail}")
47
+ lines.append("")
48
+
49
+ total = len(self.all_findings())
50
+ lines.append(f"Total: {total} hallazgo(s).")
51
+ return "\n".join(lines)
52
+
53
+
54
+ def build_report(root: Path, results: list[CheckResult]) -> Report:
55
+ return Report(root=str(root), results=results)
56
+
57
+
58
+ def write_json(report: Report) -> str:
59
+ return json.dumps(json.loads(report.to_json()), ensure_ascii=False, indent=2)
diskwhy/runner.py ADDED
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ import traceback
4
+ from importlib.metadata import entry_points
5
+ from pathlib import Path
6
+
7
+ from diskwhy.plugin import Check, CheckResult
8
+
9
+ ENTRY_POINT_GROUP = "diskwhy.checks"
10
+
11
+
12
+ def discover_checks() -> dict[str, type[Check]]:
13
+ found: dict[str, type[Check]] = {}
14
+ for ep in entry_points(group=ENTRY_POINT_GROUP):
15
+ found[ep.name] = ep.load()
16
+ return found
17
+
18
+
19
+ def run_checks(
20
+ root: Path,
21
+ *,
22
+ only: set[str] | None = None,
23
+ skip: set[str] | None = None,
24
+ ) -> list[CheckResult]:
25
+ checks = discover_checks()
26
+ names = set(checks) if only is None else (set(checks) & only)
27
+ if skip:
28
+ names -= skip
29
+
30
+ results = []
31
+ for name in sorted(names):
32
+ try:
33
+ result = checks[name]().run(root)
34
+ except Exception as exc: # noqa: BLE001 -- aislar un check roto del resto de la ejecucion
35
+ result = CheckResult(
36
+ check_name=name,
37
+ summary=f"El check falló al ejecutarse: {exc}",
38
+ error=traceback.format_exc(),
39
+ )
40
+ results.append(result)
41
+ return results
@@ -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,19 @@
1
+ diskwhy/__init__.py,sha256=dMbpEqJtlojDIJIxc7M9kL5_CM4uSOp6w6VVT38O1Qk,106
2
+ diskwhy/__main__.py,sha256=odpdgxjqwxCM0QNrQZkE2TPfsp8SOGPyCFhMQjMzAdg,90
3
+ diskwhy/cli.py,sha256=71Us4TYOCl4D-TPUcpc-UdUYvCALgc6Y-pxtoTY6biA,2620
4
+ diskwhy/fs.py,sha256=49MOGLzwkV95k0SPu3IKE3wQtBPMEEb90WNfOact86I,1388
5
+ diskwhy/patterns.py,sha256=P7bEm1Sz4JOPjU0v5bViPodGCgjdhILTMQTseCDlbU8,1662
6
+ diskwhy/plugin.py,sha256=bvHvzK0fTsux5gB6VqSRvAgpzeaLZNNDC7tt9iVjcLA,798
7
+ diskwhy/report.py,sha256=jbhv-A40Ekyj_8FGuoyV132W8PPRqzRTXzwRTekgpxk,1942
8
+ diskwhy/runner.py,sha256=oirkVwpurK7FCcpGibgIkZNnXsCjKbzWbsAl2ttoVRU,1116
9
+ diskwhy/checks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ diskwhy/checks/docker_reclaimable.py,sha256=qoDTR_0IJg_I_AsLPv2chRnOlsQ9DdREPopEM6gs_vo,2906
11
+ diskwhy/checks/duplicate_lockfiles.py,sha256=HHvt1c-mw-c4ANCI9EFC21T13kxeUblX_jJxBrbsUsY,2227
12
+ diskwhy/checks/orphaned_envs.py,sha256=iTtbHWtdgLpSrWDyXHEJcez0n4UUCN3OoH0U6oikyM0,2180
13
+ diskwhy/checks/reclaimable_dirs.py,sha256=h57uKgwv4zp6sw1_znEM_DPy2cID7YnhQ6ltWHDQfLo,2379
14
+ diskwhy-0.1.7.dist-info/licenses/LICENSE,sha256=70acRqGbi12E-RBHctB4yHLzZOoCFayZUXlhAUvwaAM,1080
15
+ diskwhy-0.1.7.dist-info/METADATA,sha256=N7aYmvlmp7Bd0_39JiBwevyA6YfUHJe_-cyfuVjzLak,5316
16
+ diskwhy-0.1.7.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
+ diskwhy-0.1.7.dist-info/entry_points.txt,sha256=JoDlFa6Pkzya_KAaaw9eszkPm4WUQ3on-RRT-kwe2-o,357
18
+ diskwhy-0.1.7.dist-info/top_level.txt,sha256=k5Pfpmsly-KghcvpCHQrl8ihTH01yKQJW0cJLV_6Xnk,8
19
+ diskwhy-0.1.7.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,8 @@
1
+ [console_scripts]
2
+ diskwhy = diskwhy.cli:main
3
+
4
+ [diskwhy.checks]
5
+ docker_reclaimable = diskwhy.checks.docker_reclaimable:DockerReclaimableCheck
6
+ duplicate_lockfiles = diskwhy.checks.duplicate_lockfiles:DuplicateLockfilesCheck
7
+ orphaned_envs = diskwhy.checks.orphaned_envs:OrphanedEnvsCheck
8
+ reclaimable_dirs = diskwhy.checks.reclaimable_dirs:ReclaimableDirsCheck
@@ -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 @@
1
+ diskwhy