depweight 0.1.5__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.
- depweight/__init__.py +3 -0
- depweight/__main__.py +6 -0
- depweight/analyze.py +116 -0
- depweight/cli.py +58 -0
- depweight/deps.py +128 -0
- depweight/report.py +31 -0
- depweight/usage.py +46 -0
- depweight-0.1.5.dist-info/METADATA +101 -0
- depweight-0.1.5.dist-info/RECORD +13 -0
- depweight-0.1.5.dist-info/WHEEL +5 -0
- depweight-0.1.5.dist-info/entry_points.txt +2 -0
- depweight-0.1.5.dist-info/licenses/LICENSE +21 -0
- depweight-0.1.5.dist-info/top_level.txt +1 -0
depweight/__init__.py
ADDED
depweight/__main__.py
ADDED
depweight/analyze.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from packaging.utils import canonicalize_name
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from depweight.deps import declared_packages, import_candidates
|
|
10
|
+
from depweight.usage import analyze_file
|
|
11
|
+
|
|
12
|
+
# Las carga otra dependencia por dentro: no se importan nunca y aun así hacen falta. Antes salían
|
|
13
|
+
# con "0 usos" y quitarlas rompía la aplicación (sin itsdangerous no hay SessionMiddleware, sin
|
|
14
|
+
# python-multipart no hay Form()).
|
|
15
|
+
IMPLIED_BY: dict[str, set[str]] = {
|
|
16
|
+
"python-multipart": {"fastapi", "starlette"}, # formularios y subidas
|
|
17
|
+
"itsdangerous": {"fastapi", "starlette", "flask"}, # sesiones firmadas
|
|
18
|
+
"jinja2": {"fastapi", "starlette", "flask"}, # plantillas
|
|
19
|
+
"uvicorn": {"fastapi", "starlette"}, # servidor ASGI
|
|
20
|
+
"gunicorn": {"flask", "django", "fastapi"},
|
|
21
|
+
"psycopg2": {"sqlalchemy", "django"},
|
|
22
|
+
"psycopg2-binary": {"sqlalchemy", "django"},
|
|
23
|
+
"psycopg": {"sqlalchemy", "django"},
|
|
24
|
+
"asyncpg": {"sqlalchemy"},
|
|
25
|
+
"pymysql": {"sqlalchemy"},
|
|
26
|
+
"aiosqlite": {"sqlalchemy"},
|
|
27
|
+
"email-validator": {"pydantic"}, # EmailStr
|
|
28
|
+
"pyyaml": {"uvicorn"},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DependencyUsage(BaseModel):
|
|
33
|
+
package: str
|
|
34
|
+
import_names: list[str]
|
|
35
|
+
usage_count: int
|
|
36
|
+
files: list[str]
|
|
37
|
+
narrow: bool
|
|
38
|
+
implied_by: list[str] = []
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _tracked_python_files(repo_path: Path) -> list[Path] | None:
|
|
42
|
+
"""None si `git ls-files` no pudo ejecutarse (no es un repo git) --
|
|
43
|
+
distinto de una lista vacía real, para no confundir "no pude mirar" con
|
|
44
|
+
"no hay ningún .py", que llevaría a marcar cualquier dependencia como
|
|
45
|
+
"0 usos" de forma enganosa.
|
|
46
|
+
"""
|
|
47
|
+
result = subprocess.run(
|
|
48
|
+
["git", "-c", "core.quotePath=false", "ls-files", "*.py"], cwd=repo_path, capture_output=True, text=True, check=False
|
|
49
|
+
)
|
|
50
|
+
if result.returncode != 0:
|
|
51
|
+
return None
|
|
52
|
+
return [repo_path / line for line in result.stdout.splitlines() if line]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def analyze_repo(repo_path: Path, *, threshold: int = 3) -> list[DependencyUsage] | None:
|
|
56
|
+
"""Para cada dependencia declarada, cuántos sitios reales del código la usan.
|
|
57
|
+
|
|
58
|
+
threshold: si el nº total de usos es <= threshold, se marca "narrow" --
|
|
59
|
+
candidata a revisar si de verdad hace falta la dependencia entera.
|
|
60
|
+
None: no aplica (no hay dependencias declaradas, o repo_path no es un
|
|
61
|
+
repo git y no se pudo determinar qué ficheros mirar).
|
|
62
|
+
"""
|
|
63
|
+
packages = declared_packages(repo_path)
|
|
64
|
+
if not packages:
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
files = _tracked_python_files(repo_path)
|
|
68
|
+
if files is None:
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
# módulo top-level -> {fichero relativo: nº de usos en ese fichero}
|
|
72
|
+
module_usage: dict[str, dict[str, int]] = {}
|
|
73
|
+
for path in files:
|
|
74
|
+
analyzed = analyze_file(path)
|
|
75
|
+
if analyzed is None:
|
|
76
|
+
continue
|
|
77
|
+
bindings, counts = analyzed
|
|
78
|
+
rel = str(path.relative_to(repo_path))
|
|
79
|
+
for local, module in bindings.items():
|
|
80
|
+
per_file = module_usage.setdefault(module, {})
|
|
81
|
+
per_file[rel] = per_file.get(rel, 0) + counts.get(local, 0)
|
|
82
|
+
|
|
83
|
+
results: list[DependencyUsage] = []
|
|
84
|
+
for package in packages:
|
|
85
|
+
candidates = import_candidates(package)
|
|
86
|
+
total = 0
|
|
87
|
+
files_using: dict[str, int] = {}
|
|
88
|
+
matched: list[str] = []
|
|
89
|
+
|
|
90
|
+
for candidate in candidates:
|
|
91
|
+
top = candidate.split(".")[0]
|
|
92
|
+
per_file = module_usage.get(top)
|
|
93
|
+
if per_file is None:
|
|
94
|
+
continue
|
|
95
|
+
matched.append(candidate)
|
|
96
|
+
for rel, count in per_file.items():
|
|
97
|
+
files_using[rel] = files_using.get(rel, 0) + count
|
|
98
|
+
total += count
|
|
99
|
+
|
|
100
|
+
results.append(
|
|
101
|
+
DependencyUsage(
|
|
102
|
+
package=package,
|
|
103
|
+
import_names=matched or candidates,
|
|
104
|
+
usage_count=total,
|
|
105
|
+
files=sorted(f for f, c in files_using.items() if c > 0),
|
|
106
|
+
narrow=total <= threshold,
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
used = {canonicalize_name(r.package) for r in results if r.usage_count > 0}
|
|
111
|
+
for r in results:
|
|
112
|
+
implied = sorted(IMPLIED_BY.get(canonicalize_name(r.package), set()) & used)
|
|
113
|
+
if implied:
|
|
114
|
+
r.implied_by = implied
|
|
115
|
+
r.narrow = False
|
|
116
|
+
return results
|
depweight/cli.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from depweight import __version__
|
|
8
|
+
from depweight.analyze import analyze_repo
|
|
9
|
+
from depweight.report import to_console, to_json
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _cmd_analyze(args: argparse.Namespace) -> int:
|
|
13
|
+
repo_path = Path(args.path).resolve()
|
|
14
|
+
results = analyze_repo(repo_path, threshold=args.threshold)
|
|
15
|
+
|
|
16
|
+
if not results:
|
|
17
|
+
print("No aplica: no se encontró requirements.txt ni pyproject.toml, o no declara dependencias.")
|
|
18
|
+
return 0
|
|
19
|
+
|
|
20
|
+
if args.json:
|
|
21
|
+
print(to_json(results))
|
|
22
|
+
else:
|
|
23
|
+
print(to_console(results, only_narrow=not args.all))
|
|
24
|
+
|
|
25
|
+
if args.fail_on_narrow and any(r.narrow for r in results):
|
|
26
|
+
return 1
|
|
27
|
+
return 0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
31
|
+
parser = argparse.ArgumentParser(prog="depweight")
|
|
32
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
33
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
34
|
+
|
|
35
|
+
p_analyze = sub.add_parser("analyze", help="Cuánto se usa realmente cada dependencia declarada")
|
|
36
|
+
p_analyze.add_argument("path", nargs="?", default=".")
|
|
37
|
+
p_analyze.add_argument(
|
|
38
|
+
"--threshold",
|
|
39
|
+
type=int,
|
|
40
|
+
default=3,
|
|
41
|
+
help="Nº de usos máximo para considerar una dependencia de uso 'estrecho' (por defecto 3)",
|
|
42
|
+
)
|
|
43
|
+
p_analyze.add_argument("--all", action="store_true", help="Muestra también las que tienen uso normal")
|
|
44
|
+
p_analyze.add_argument("--json", action="store_true")
|
|
45
|
+
p_analyze.add_argument("--fail-on-narrow", action="store_true")
|
|
46
|
+
p_analyze.set_defaults(func=_cmd_analyze)
|
|
47
|
+
|
|
48
|
+
return parser
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def main(argv: list[str] | None = None) -> int:
|
|
52
|
+
parser = build_parser()
|
|
53
|
+
args = parser.parse_args(argv)
|
|
54
|
+
return args.func(args)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
sys.exit(main())
|
depweight/deps.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import tomllib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from packaging.requirements import InvalidRequirement, Requirement
|
|
7
|
+
from packaging.utils import canonicalize_name
|
|
8
|
+
|
|
9
|
+
# Nombre de paquete en PyPI -> nombre(s) de import mas probable(s), para los
|
|
10
|
+
# casos donde no coinciden simplemente normalizando guiones/mayusculas.
|
|
11
|
+
PACKAGE_TO_IMPORT: dict[str, list[str]] = {
|
|
12
|
+
"pyyaml": ["yaml"],
|
|
13
|
+
"beautifulsoup4": ["bs4"],
|
|
14
|
+
"pillow": ["PIL"],
|
|
15
|
+
"opencv-python": ["cv2"],
|
|
16
|
+
"scikit-learn": ["sklearn"],
|
|
17
|
+
"python-dotenv": ["dotenv"],
|
|
18
|
+
"pyjwt": ["jwt"],
|
|
19
|
+
"python-dateutil": ["dateutil"],
|
|
20
|
+
"pycryptodome": ["Crypto"],
|
|
21
|
+
"pyopenssl": ["OpenSSL"],
|
|
22
|
+
"python-docx": ["docx"],
|
|
23
|
+
"python-pptx": ["pptx"],
|
|
24
|
+
"pyserial": ["serial"],
|
|
25
|
+
"pyusb": ["usb"],
|
|
26
|
+
"markdown-it-py": ["markdown_it"],
|
|
27
|
+
"protobuf": ["google.protobuf"],
|
|
28
|
+
"grpcio": ["grpc"],
|
|
29
|
+
"psycopg2-binary": ["psycopg2"],
|
|
30
|
+
"psycopg-binary": ["psycopg"],
|
|
31
|
+
"opencv-python-headless": ["cv2"],
|
|
32
|
+
"opencv-contrib-python": ["cv2"],
|
|
33
|
+
"opencv-contrib-python-headless": ["cv2"],
|
|
34
|
+
"mysqlclient": ["MySQLdb"],
|
|
35
|
+
"pyzmq": ["zmq"],
|
|
36
|
+
"websocket-client": ["websocket"],
|
|
37
|
+
"pygobject": ["gi"],
|
|
38
|
+
"msgpack-python": ["msgpack"],
|
|
39
|
+
"pymupdf": ["fitz", "pymupdf"],
|
|
40
|
+
"scikit-image": ["skimage"],
|
|
41
|
+
"discord-py": ["discord"],
|
|
42
|
+
"pywin32": ["win32api", "win32con", "win32com", "pythoncom", "pywintypes"],
|
|
43
|
+
"pycryptodomex": ["Cryptodome"],
|
|
44
|
+
"python-jose": ["jose"],
|
|
45
|
+
"python-magic": ["magic"],
|
|
46
|
+
"python-ldap": ["ldap"],
|
|
47
|
+
"dnspython": ["dns"],
|
|
48
|
+
"pyinstaller": ["PyInstaller"],
|
|
49
|
+
"python-multipart": ["multipart", "python_multipart"],
|
|
50
|
+
"attrs": ["attr", "attrs"],
|
|
51
|
+
"ruamel-yaml": ["ruamel.yaml"],
|
|
52
|
+
"google-cloud-storage": ["google.cloud.storage"],
|
|
53
|
+
"beautifulsoup": ["BeautifulSoup"],
|
|
54
|
+
"pyserial-asyncio": ["serial_asyncio"],
|
|
55
|
+
"paho-mqtt": ["paho.mqtt"],
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _parse_requirement_line(line: str) -> Requirement | None:
|
|
60
|
+
line = line.split("#", 1)[0].strip()
|
|
61
|
+
if not line or line.startswith("-"):
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
return Requirement(line)
|
|
65
|
+
except InvalidRequirement:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _declared_names_from_requirements_txt(path: Path) -> list[str]:
|
|
70
|
+
if not path.exists():
|
|
71
|
+
return []
|
|
72
|
+
names = []
|
|
73
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
74
|
+
req = _parse_requirement_line(line)
|
|
75
|
+
if req is not None:
|
|
76
|
+
names.append(req.name)
|
|
77
|
+
return names
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _declared_names_from_pyproject_toml(path: Path) -> list[str]:
|
|
81
|
+
if not path.exists():
|
|
82
|
+
return []
|
|
83
|
+
try:
|
|
84
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
85
|
+
except tomllib.TOMLDecodeError:
|
|
86
|
+
return []
|
|
87
|
+
project = data.get("project", {})
|
|
88
|
+
names = []
|
|
89
|
+
for line in project.get("dependencies", []):
|
|
90
|
+
req = _parse_requirement_line(line)
|
|
91
|
+
if req is not None:
|
|
92
|
+
names.append(req.name)
|
|
93
|
+
return names
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def declared_packages(repo_path: Path) -> list[str]:
|
|
97
|
+
names = _declared_names_from_requirements_txt(repo_path / "requirements.txt")
|
|
98
|
+
names += _declared_names_from_pyproject_toml(repo_path / "pyproject.toml")
|
|
99
|
+
seen = set()
|
|
100
|
+
ordered = []
|
|
101
|
+
for name in names:
|
|
102
|
+
if name not in seen:
|
|
103
|
+
seen.add(name)
|
|
104
|
+
ordered.append(name)
|
|
105
|
+
return ordered
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def import_candidates(package: str) -> list[str]:
|
|
109
|
+
# PACKAGE_TO_IMPORT usa claves en minúsculas, pero los ficheros de
|
|
110
|
+
# dependencias reales suelen declarar el nombre tal como aparece en PyPI
|
|
111
|
+
# ("Django", "Pillow", "PyYAML") -- comparar sin normalizar mayúsculas
|
|
112
|
+
# hacía que ninguna de esas entradas del mapa (¡ni el propio "Pillow"!)
|
|
113
|
+
# coincidiera nunca, así que se le atribuían 0 usos a dependencias muy
|
|
114
|
+
# usadas de verdad.
|
|
115
|
+
# Normalizado como PyPI (PEP 503): «python_dateutil» o «Python.Dateutil» son «python-dateutil».
|
|
116
|
+
key = canonicalize_name(package)
|
|
117
|
+
if key in PACKAGE_TO_IMPORT:
|
|
118
|
+
return PACKAGE_TO_IMPORT[key]
|
|
119
|
+
# Mismo problema para el resto: la inmensa mayoría de paquetes no
|
|
120
|
+
# mapeados también importan en minúsculas aunque se declaren capitalizados
|
|
121
|
+
# ("Django" -> "django", "Requests" -> "requests"). Se prueban ambas
|
|
122
|
+
# formas -- la literal (por si el import realmente usa mayúsculas, como
|
|
123
|
+
# "PyQt5") y la normalizada -- en vez de adivinar solo una.
|
|
124
|
+
default = package.replace("-", "_")
|
|
125
|
+
lowered = default.lower()
|
|
126
|
+
if lowered == default:
|
|
127
|
+
return [default]
|
|
128
|
+
return [default, lowered]
|
depweight/report.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from depweight.analyze import DependencyUsage
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def to_console(results: list[DependencyUsage], *, only_narrow: bool = False) -> str:
|
|
9
|
+
shown = [r for r in results if r.narrow] if only_narrow else results
|
|
10
|
+
if not shown:
|
|
11
|
+
return "No hay dependencias con uso estrecho -- todo parece justificado."
|
|
12
|
+
|
|
13
|
+
lines = []
|
|
14
|
+
for r in sorted(shown, key=lambda x: x.usage_count):
|
|
15
|
+
label = "[NARROW]" if r.narrow else "[OK ]"
|
|
16
|
+
lines.append(f"{label} {r.package} -- {r.usage_count} uso(s) en {len(r.files)} fichero(s)")
|
|
17
|
+
if r.implied_by:
|
|
18
|
+
lines.append(f" Hace falta para {', '.join(r.implied_by)} (la carga o la usa por dentro), aunque apenas se importe.")
|
|
19
|
+
elif r.usage_count == 0:
|
|
20
|
+
lines.append(" Declarada pero no se encontró ningún uso real.")
|
|
21
|
+
elif r.narrow:
|
|
22
|
+
lines.append(f" Revisa si de verdad necesitas {r.package} entera: {', '.join(r.files[:3])}")
|
|
23
|
+
|
|
24
|
+
narrow_count = sum(1 for r in results if r.narrow)
|
|
25
|
+
lines.append("")
|
|
26
|
+
lines.append(f"Total: {narrow_count} dependencia(s) de uso estrecho de {len(results)} analizada(s).")
|
|
27
|
+
return "\n".join(lines)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def to_json(results: list[DependencyUsage]) -> str:
|
|
31
|
+
return json.dumps([r.model_dump() for r in results], ensure_ascii=False, indent=2)
|
depweight/usage.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def bound_names(tree: ast.Module) -> dict[str, str]:
|
|
8
|
+
"""Nombre local (tras import/alias) -> nombre de módulo top-level."""
|
|
9
|
+
bindings: dict[str, str] = {}
|
|
10
|
+
for node in ast.walk(tree):
|
|
11
|
+
if isinstance(node, ast.Import):
|
|
12
|
+
for alias in node.names:
|
|
13
|
+
top = alias.name.split(".")[0]
|
|
14
|
+
local = alias.asname or alias.name.split(".")[0]
|
|
15
|
+
bindings[local] = top
|
|
16
|
+
elif isinstance(node, ast.ImportFrom):
|
|
17
|
+
if node.module is None or node.level > 0:
|
|
18
|
+
continue # import relativo -- no es un paquete externo
|
|
19
|
+
top = node.module.split(".")[0]
|
|
20
|
+
for alias in node.names:
|
|
21
|
+
local = alias.asname or alias.name
|
|
22
|
+
bindings[local] = top
|
|
23
|
+
return bindings
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def count_usages_per_name(tree: ast.Module, local_names: set[str]) -> dict[str, int]:
|
|
27
|
+
"""Cuenta referencias reales (no la propia línea de import) a cada nombre."""
|
|
28
|
+
counts: dict[str, int] = dict.fromkeys(local_names, 0)
|
|
29
|
+
for node in ast.walk(tree):
|
|
30
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id in counts:
|
|
31
|
+
counts[node.id] += 1
|
|
32
|
+
return counts
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def analyze_file(path: Path) -> tuple[dict[str, str], dict[str, int]] | None:
|
|
36
|
+
"""(nombre local -> módulo, nombre local -> nº de usos) o None si no se pudo leer/parsear."""
|
|
37
|
+
try:
|
|
38
|
+
source = path.read_text(encoding="utf-8")
|
|
39
|
+
tree = ast.parse(source)
|
|
40
|
+
except (OSError, UnicodeDecodeError, SyntaxError):
|
|
41
|
+
return None
|
|
42
|
+
bindings = bound_names(tree)
|
|
43
|
+
if not bindings:
|
|
44
|
+
return ({}, {})
|
|
45
|
+
counts = count_usages_per_name(tree, set(bindings))
|
|
46
|
+
return (bindings, counts)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: depweight
|
|
3
|
+
Version: 0.1.5
|
|
4
|
+
Summary: No solo el grafo de dependencias: cuanto se usa realmente cada una, para saber si de verdad la necesitas entera.
|
|
5
|
+
Author: José Luis Segura Yuste
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jl-segurayuste/depweight
|
|
8
|
+
Project-URL: Source, https://github.com/jl-segurayuste/depweight
|
|
9
|
+
Project-URL: Issues, https://github.com/jl-segurayuste/depweight/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/jl-segurayuste/depweight/releases
|
|
11
|
+
Keywords: developer-tools,dependencies,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
|
+
Requires-Dist: packaging>=23.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
32
|
+
Requires-Dist: ruff==0.17.6; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# depweight
|
|
36
|
+
|
|
37
|
+
[](https://pypi.org/project/depweight/)
|
|
38
|
+
[](https://github.com/jl-segurayuste/depweight/actions/workflows/ci.yml)
|
|
39
|
+
[](https://github.com/jl-segurayuste/depweight/blob/main/pyproject.toml)
|
|
40
|
+
[](https://github.com/jl-segurayuste/depweight/blob/main/LICENSE)
|
|
41
|
+
|
|
42
|
+
No solo el grafo de dependencias — cuánto se usa *realmente* cada una, para
|
|
43
|
+
saber si de verdad la necesitas entera o solo hace falta una función suelta.
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
$ depweight analyze .
|
|
47
|
+
|
|
48
|
+
[NARROW] requests -- 1 uso(s) en 1 fichero(s)
|
|
49
|
+
Revisa si de verdad necesitas requests entera: scripts/ping.py
|
|
50
|
+
[NARROW] pandas -- 0 uso(s) en 0 fichero(s)
|
|
51
|
+
Declarada pero no se encontró ningún uso real.
|
|
52
|
+
|
|
53
|
+
Total: 2 dependencia(s) de uso estrecho de 8 analizada(s).
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Así se ve
|
|
57
|
+
|
|
58
|
+

|
|
59
|
+
|
|
60
|
+
<sub>Ejecución real sobre una pequeña API con dependencias que apenas se usan (todos los datos son ficticios).</sub>
|
|
61
|
+
|
|
62
|
+
## Por qué existe
|
|
63
|
+
|
|
64
|
+
Un grafo de dependencias te dice *qué* depende de *qué*, pero no *cuánto* de
|
|
65
|
+
verdad se usa. Es habitual arrastrar una librería entera (con su propio árbol
|
|
66
|
+
de subdependencias) para una sola llamada — `depweight` cuenta los usos
|
|
67
|
+
reales de cada dependencia declarada (vía AST, no regex) y señala las que
|
|
68
|
+
tienen un uso tan estrecho que merece la pena preguntarse si compensa.
|
|
69
|
+
|
|
70
|
+
## Instalación
|
|
71
|
+
|
|
72
|
+
Todavía no está en PyPI:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pipx install depweight # recomendado para herramientas de línea de comandos
|
|
76
|
+
# o bien
|
|
77
|
+
pip install depweight
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Uso
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
depweight analyze . # solo las de uso estrecho
|
|
84
|
+
depweight analyze . --all # todas, incluidas las normales
|
|
85
|
+
depweight analyze . --threshold 5 # umbral de "estrecho" (por defecto 3)
|
|
86
|
+
depweight analyze . --json
|
|
87
|
+
depweight analyze . --fail-on-narrow # código de salida 1 si hay alguna
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Lee `requirements.txt`/`pyproject.toml` para las dependencias declaradas, y
|
|
91
|
+
recorre los ficheros `.py` rastreados por git (vía `git ls-files`, respeta
|
|
92
|
+
`.gitignore`) contando referencias reales a cada una vía `ast` — nunca
|
|
93
|
+
ejecuta el código analizado.
|
|
94
|
+
|
|
95
|
+
## Desarrollo
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
pip install -e ".[dev]"
|
|
99
|
+
ruff check .
|
|
100
|
+
pytest
|
|
101
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
depweight/__init__.py,sha256=csDYilDxm2mTXxvSCvkxRRtzqiT8vbqEIozI42IvKn4,104
|
|
2
|
+
depweight/__main__.py,sha256=JkNxDocRJNxr5056bnWCo7Uw8y1sGctf8BKW4FpUlC0,92
|
|
3
|
+
depweight/analyze.py,sha256=O5Z4roWo1YBqll7GQVcTc67PSsS3wZguPzN0-wKuLVc,4314
|
|
4
|
+
depweight/cli.py,sha256=rRhNLCkkQvPul87RmqurEXskS4IfwJQQz6ZYLzVu7KU,1839
|
|
5
|
+
depweight/deps.py,sha256=IQvFvc8PzEa1c5PzHuxTTRjIbvoUzTCmxhKG-wpSGd0,4511
|
|
6
|
+
depweight/report.py,sha256=inAAGQuKZO-8XA_y_NWcfp4YizEyVB7OWVygupm2GEU,1353
|
|
7
|
+
depweight/usage.py,sha256=rGWBFkU8ut4EHU5UxCHGtUJZiPCvxMyTj4LJ54SnqJc,1779
|
|
8
|
+
depweight-0.1.5.dist-info/licenses/LICENSE,sha256=70acRqGbi12E-RBHctB4yHLzZOoCFayZUXlhAUvwaAM,1080
|
|
9
|
+
depweight-0.1.5.dist-info/METADATA,sha256=8TgM2PzOTPsyjvr3o6Nfd6wqn0iC18df1qipsOpiYgE,4023
|
|
10
|
+
depweight-0.1.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
depweight-0.1.5.dist-info/entry_points.txt,sha256=dRE1wTVmkf-Oy9xdHJyYMocWW0SyHDQFJ1Z3iwdNWJw,49
|
|
12
|
+
depweight-0.1.5.dist-info/top_level.txt,sha256=PKLCO5iP8p8tVxQxr0B8il7QIzbpdW4Lm-xi_Yyb5pk,10
|
|
13
|
+
depweight-0.1.5.dist-info/RECORD,,
|
|
@@ -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
|
+
depweight
|