depweight 0.1.5__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.
- depweight-0.1.5/LICENSE +21 -0
- depweight-0.1.5/PKG-INFO +101 -0
- depweight-0.1.5/README.md +67 -0
- depweight-0.1.5/depweight/__init__.py +3 -0
- depweight-0.1.5/depweight/__main__.py +6 -0
- depweight-0.1.5/depweight/analyze.py +116 -0
- depweight-0.1.5/depweight/cli.py +58 -0
- depweight-0.1.5/depweight/deps.py +128 -0
- depweight-0.1.5/depweight/report.py +31 -0
- depweight-0.1.5/depweight/usage.py +46 -0
- depweight-0.1.5/depweight.egg-info/PKG-INFO +101 -0
- depweight-0.1.5/depweight.egg-info/SOURCES.txt +22 -0
- depweight-0.1.5/depweight.egg-info/dependency_links.txt +1 -0
- depweight-0.1.5/depweight.egg-info/entry_points.txt +2 -0
- depweight-0.1.5/depweight.egg-info/requires.txt +7 -0
- depweight-0.1.5/depweight.egg-info/top_level.txt +1 -0
- depweight-0.1.5/pyproject.toml +60 -0
- depweight-0.1.5/setup.cfg +4 -0
- depweight-0.1.5/tests/test_analyze.py +115 -0
- depweight-0.1.5/tests/test_cli.py +44 -0
- depweight-0.1.5/tests/test_deps.py +70 -0
- depweight-0.1.5/tests/test_report.py +30 -0
- depweight-0.1.5/tests/test_usage.py +58 -0
- depweight-0.1.5/tests/test_version.py +11 -0
depweight-0.1.5/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.
|
depweight-0.1.5/PKG-INFO
ADDED
|
@@ -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,67 @@
|
|
|
1
|
+
# depweight
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/depweight/)
|
|
4
|
+
[](https://github.com/jl-segurayuste/depweight/actions/workflows/ci.yml)
|
|
5
|
+
[](https://github.com/jl-segurayuste/depweight/blob/main/pyproject.toml)
|
|
6
|
+
[](https://github.com/jl-segurayuste/depweight/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
No solo el grafo de dependencias — cuánto se usa *realmente* cada una, para
|
|
9
|
+
saber si de verdad la necesitas entera o solo hace falta una función suelta.
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
$ depweight analyze .
|
|
13
|
+
|
|
14
|
+
[NARROW] requests -- 1 uso(s) en 1 fichero(s)
|
|
15
|
+
Revisa si de verdad necesitas requests entera: scripts/ping.py
|
|
16
|
+
[NARROW] pandas -- 0 uso(s) en 0 fichero(s)
|
|
17
|
+
Declarada pero no se encontró ningún uso real.
|
|
18
|
+
|
|
19
|
+
Total: 2 dependencia(s) de uso estrecho de 8 analizada(s).
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Así se ve
|
|
23
|
+
|
|
24
|
+

|
|
25
|
+
|
|
26
|
+
<sub>Ejecución real sobre una pequeña API con dependencias que apenas se usan (todos los datos son ficticios).</sub>
|
|
27
|
+
|
|
28
|
+
## Por qué existe
|
|
29
|
+
|
|
30
|
+
Un grafo de dependencias te dice *qué* depende de *qué*, pero no *cuánto* de
|
|
31
|
+
verdad se usa. Es habitual arrastrar una librería entera (con su propio árbol
|
|
32
|
+
de subdependencias) para una sola llamada — `depweight` cuenta los usos
|
|
33
|
+
reales de cada dependencia declarada (vía AST, no regex) y señala las que
|
|
34
|
+
tienen un uso tan estrecho que merece la pena preguntarse si compensa.
|
|
35
|
+
|
|
36
|
+
## Instalación
|
|
37
|
+
|
|
38
|
+
Todavía no está en PyPI:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pipx install depweight # recomendado para herramientas de línea de comandos
|
|
42
|
+
# o bien
|
|
43
|
+
pip install depweight
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Uso
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
depweight analyze . # solo las de uso estrecho
|
|
50
|
+
depweight analyze . --all # todas, incluidas las normales
|
|
51
|
+
depweight analyze . --threshold 5 # umbral de "estrecho" (por defecto 3)
|
|
52
|
+
depweight analyze . --json
|
|
53
|
+
depweight analyze . --fail-on-narrow # código de salida 1 si hay alguna
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Lee `requirements.txt`/`pyproject.toml` para las dependencias declaradas, y
|
|
57
|
+
recorre los ficheros `.py` rastreados por git (vía `git ls-files`, respeta
|
|
58
|
+
`.gitignore`) contando referencias reales a cada una vía `ast` — nunca
|
|
59
|
+
ejecuta el código analizado.
|
|
60
|
+
|
|
61
|
+
## Desarrollo
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install -e ".[dev]"
|
|
65
|
+
ruff check .
|
|
66
|
+
pytest
|
|
67
|
+
```
|
|
@@ -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
|
|
@@ -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())
|
|
@@ -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]
|
|
@@ -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)
|
|
@@ -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,22 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
depweight/__init__.py
|
|
5
|
+
depweight/__main__.py
|
|
6
|
+
depweight/analyze.py
|
|
7
|
+
depweight/cli.py
|
|
8
|
+
depweight/deps.py
|
|
9
|
+
depweight/report.py
|
|
10
|
+
depweight/usage.py
|
|
11
|
+
depweight.egg-info/PKG-INFO
|
|
12
|
+
depweight.egg-info/SOURCES.txt
|
|
13
|
+
depweight.egg-info/dependency_links.txt
|
|
14
|
+
depweight.egg-info/entry_points.txt
|
|
15
|
+
depweight.egg-info/requires.txt
|
|
16
|
+
depweight.egg-info/top_level.txt
|
|
17
|
+
tests/test_analyze.py
|
|
18
|
+
tests/test_cli.py
|
|
19
|
+
tests/test_deps.py
|
|
20
|
+
tests/test_report.py
|
|
21
|
+
tests/test_usage.py
|
|
22
|
+
tests/test_version.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
depweight
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "depweight"
|
|
3
|
+
version = "0.1.5"
|
|
4
|
+
description = "No solo el grafo de dependencias: cuanto se usa realmente cada una, para saber si de verdad la necesitas entera."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
authors = [{ name = "José Luis Segura Yuste" }]
|
|
8
|
+
keywords = ["developer-tools", "dependencies", "static-analysis"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 4 - Beta",
|
|
11
|
+
"Environment :: Console",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Natural Language :: Spanish",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Programming Language :: Python :: 3.11",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Programming Language :: Python :: 3.14",
|
|
20
|
+
"Programming Language :: Python :: 3.15",
|
|
21
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
22
|
+
]
|
|
23
|
+
requires-python = ">=3.11"
|
|
24
|
+
dependencies = ["pydantic>=2.6", "packaging>=23.0"]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = ["pytest>=7.4", "pytest-cov>=5", "ruff==0.17.6"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/jl-segurayuste/depweight"
|
|
31
|
+
Source = "https://github.com/jl-segurayuste/depweight"
|
|
32
|
+
Issues = "https://github.com/jl-segurayuste/depweight/issues"
|
|
33
|
+
Changelog = "https://github.com/jl-segurayuste/depweight/releases"
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
depweight = "depweight.cli:main"
|
|
37
|
+
|
|
38
|
+
[tool.setuptools.packages.find]
|
|
39
|
+
include = ["depweight*"]
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
line-length = 100
|
|
43
|
+
target-version = "py311"
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
testpaths = ["tests"]
|
|
47
|
+
|
|
48
|
+
[build-system]
|
|
49
|
+
requires = ["setuptools>=77"]
|
|
50
|
+
build-backend = "setuptools.build_meta"
|
|
51
|
+
|
|
52
|
+
[tool.coverage.run]
|
|
53
|
+
branch = true
|
|
54
|
+
source = ["depweight"]
|
|
55
|
+
|
|
56
|
+
[tool.coverage.report]
|
|
57
|
+
# Mínimo exigido en el CI: la cobertura medida al añadirlo (93 %) menos un margen.
|
|
58
|
+
fail_under = 90
|
|
59
|
+
show_missing = true
|
|
60
|
+
skip_covered = true
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from conftest import commit_all, write
|
|
2
|
+
|
|
3
|
+
from depweight.analyze import analyze_repo
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_dependencia_usada_mucho_no_es_narrow(git_repo):
|
|
7
|
+
write(git_repo, "requirements.txt", "click\n")
|
|
8
|
+
write(
|
|
9
|
+
git_repo,
|
|
10
|
+
"app.py",
|
|
11
|
+
"import click\n"
|
|
12
|
+
"click.echo('a')\n"
|
|
13
|
+
"click.echo('b')\n"
|
|
14
|
+
"click.echo('c')\n"
|
|
15
|
+
"click.echo('d')\n",
|
|
16
|
+
)
|
|
17
|
+
commit_all(git_repo)
|
|
18
|
+
results = analyze_repo(git_repo, threshold=3)
|
|
19
|
+
click_usage = next(r for r in results if r.package == "click")
|
|
20
|
+
assert click_usage.usage_count == 4
|
|
21
|
+
assert click_usage.narrow is False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_dependencia_usada_poco_es_narrow(git_repo):
|
|
25
|
+
write(git_repo, "requirements.txt", "requests\n")
|
|
26
|
+
write(git_repo, "app.py", "import requests\nrequests.get('x')\n")
|
|
27
|
+
commit_all(git_repo)
|
|
28
|
+
results = analyze_repo(git_repo, threshold=3)
|
|
29
|
+
req_usage = next(r for r in results if r.package == "requests")
|
|
30
|
+
assert req_usage.usage_count == 1
|
|
31
|
+
assert req_usage.narrow is True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_dependencia_declarada_sin_ningun_uso(git_repo):
|
|
35
|
+
write(git_repo, "requirements.txt", "unused-pkg\n")
|
|
36
|
+
write(git_repo, "app.py", "x = 1\n")
|
|
37
|
+
commit_all(git_repo)
|
|
38
|
+
results = analyze_repo(git_repo, threshold=3)
|
|
39
|
+
usage = next(r for r in results if r.package == "unused-pkg")
|
|
40
|
+
assert usage.usage_count == 0
|
|
41
|
+
assert usage.files == []
|
|
42
|
+
assert usage.narrow is True
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_uso_repartido_en_varios_ficheros_se_suma(git_repo):
|
|
46
|
+
write(git_repo, "requirements.txt", "click\n")
|
|
47
|
+
write(git_repo, "a.py", "import click\nclick.echo('a')\n")
|
|
48
|
+
write(git_repo, "b.py", "import click\nclick.echo('b')\nclick.echo('c')\n")
|
|
49
|
+
commit_all(git_repo)
|
|
50
|
+
results = analyze_repo(git_repo, threshold=3)
|
|
51
|
+
click_usage = next(r for r in results if r.package == "click")
|
|
52
|
+
assert click_usage.usage_count == 3
|
|
53
|
+
assert set(click_usage.files) == {"a.py", "b.py"}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_mapeo_pyyaml_a_yaml_funciona(git_repo):
|
|
57
|
+
write(git_repo, "requirements.txt", "pyyaml\n")
|
|
58
|
+
write(git_repo, "app.py", "import yaml\nyaml.safe_load('x')\n")
|
|
59
|
+
commit_all(git_repo)
|
|
60
|
+
results = analyze_repo(git_repo, threshold=3)
|
|
61
|
+
usage = next(r for r in results if r.package == "pyyaml")
|
|
62
|
+
assert usage.usage_count == 1
|
|
63
|
+
assert usage.import_names == ["yaml"]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_paquete_declarado_capitalizado_no_da_falso_cero_usos(git_repo):
|
|
67
|
+
# Bug real encontrado 2026-08-09: "Django" (así, capitalizado, como se
|
|
68
|
+
# escribe habitualmente en requirements.txt) se comparaba tal cual contra
|
|
69
|
+
# el import real "django" (minúsculas) sin normalizar mayúsculas, así que
|
|
70
|
+
# una dependencia usada por todo el proyecto aparecía con 0 usos --
|
|
71
|
+
# justo el falso positivo que esta herramienta existe para evitar.
|
|
72
|
+
write(git_repo, "requirements.txt", "Django==4.2\n")
|
|
73
|
+
write(
|
|
74
|
+
git_repo,
|
|
75
|
+
"app.py",
|
|
76
|
+
"import django\ndjango.setup()\ndjango.setup()\ndjango.setup()\ndjango.setup()\n",
|
|
77
|
+
)
|
|
78
|
+
commit_all(git_repo)
|
|
79
|
+
results = analyze_repo(git_repo, threshold=3)
|
|
80
|
+
usage = next(r for r in results if r.package == "Django")
|
|
81
|
+
assert usage.usage_count == 4
|
|
82
|
+
assert usage.narrow is False
|
|
83
|
+
assert usage.files == ["app.py"]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_sin_dependencias_declaradas_devuelve_none(git_repo):
|
|
87
|
+
write(git_repo, "app.py", "x = 1\n")
|
|
88
|
+
commit_all(git_repo)
|
|
89
|
+
assert analyze_repo(git_repo) is None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_sin_repo_git_devuelve_none_no_falsos_cero_usos(tmp_path):
|
|
93
|
+
# requirements.txt existe pero no hay .git -- no se puede determinar que
|
|
94
|
+
# ficheros mirar, y NO debe reportarse como "0 usos" (falso positivo).
|
|
95
|
+
write(tmp_path, "requirements.txt", "requests\n")
|
|
96
|
+
write(tmp_path, "app.py", "import requests\nrequests.get('x')\n")
|
|
97
|
+
assert analyze_repo(tmp_path) is None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_dependencia_que_carga_otra_por_dentro_no_es_narrow(git_repo):
|
|
101
|
+
"""Sin itsdangerous no hay SessionMiddleware: nunca se importa, pero quitarla rompe la app."""
|
|
102
|
+
write(git_repo, "pyproject.toml",
|
|
103
|
+
'[project]\nname = "x"\ndependencies = ["fastapi", "itsdangerous", "segno"]\n')
|
|
104
|
+
write(git_repo, "app.py", "import fastapi\n" + "fastapi.FastAPI()\n" * 5)
|
|
105
|
+
commit_all(git_repo)
|
|
106
|
+
by_name = {r.package: r for r in analyze_repo(git_repo)}
|
|
107
|
+
assert not by_name["itsdangerous"].narrow and by_name["itsdangerous"].implied_by == ["fastapi"]
|
|
108
|
+
assert by_name["segno"].narrow # la tabla no tapa dependencias sin uso de verdad
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_dependencia_implicita_sin_su_framework_sigue_marcandose(git_repo):
|
|
112
|
+
write(git_repo, "pyproject.toml", '[project]\nname = "x"\ndependencies = ["itsdangerous"]\n')
|
|
113
|
+
write(git_repo, "app.py", "x = 1\n")
|
|
114
|
+
commit_all(git_repo)
|
|
115
|
+
assert analyze_repo(git_repo)[0].narrow
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from conftest import commit_all, write
|
|
2
|
+
|
|
3
|
+
from depweight.cli import main
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_analyze_sin_dependencias_exit_0(git_repo, capsys):
|
|
7
|
+
write(git_repo, "app.py", "x = 1\n")
|
|
8
|
+
commit_all(git_repo)
|
|
9
|
+
rc = main(["analyze", str(git_repo)])
|
|
10
|
+
assert rc == 0
|
|
11
|
+
assert "No aplica" in capsys.readouterr().out
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_analyze_con_narrow_exit_1_si_fail_on_narrow(git_repo, capsys):
|
|
15
|
+
write(git_repo, "requirements.txt", "requests\n")
|
|
16
|
+
write(git_repo, "app.py", "import requests\nrequests.get('x')\n")
|
|
17
|
+
commit_all(git_repo)
|
|
18
|
+
rc = main(["analyze", str(git_repo), "--fail-on-narrow"])
|
|
19
|
+
assert rc == 1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_analyze_sin_narrow_exit_0(git_repo, capsys):
|
|
23
|
+
write(git_repo, "requirements.txt", "click\n")
|
|
24
|
+
write(git_repo, "app.py", "import click\n" + "click.echo('x')\n" * 5)
|
|
25
|
+
commit_all(git_repo)
|
|
26
|
+
rc = main(["analyze", str(git_repo), "--fail-on-narrow"])
|
|
27
|
+
assert rc == 0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_analyze_json(git_repo, capsys):
|
|
31
|
+
write(git_repo, "requirements.txt", "click\n")
|
|
32
|
+
write(git_repo, "app.py", "import click\nclick.echo('x')\n")
|
|
33
|
+
commit_all(git_repo)
|
|
34
|
+
main(["analyze", str(git_repo), "--json"])
|
|
35
|
+
out = capsys.readouterr().out
|
|
36
|
+
assert '"package"' in out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_analyze_threshold_personalizado(git_repo, capsys):
|
|
40
|
+
write(git_repo, "requirements.txt", "click\n")
|
|
41
|
+
write(git_repo, "app.py", "import click\n" + "click.echo('x')\n" * 5)
|
|
42
|
+
commit_all(git_repo)
|
|
43
|
+
rc = main(["analyze", str(git_repo), "--threshold", "10", "--fail-on-narrow"])
|
|
44
|
+
assert rc == 1 # con threshold=10, 5 usos SI es narrow
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from conftest import write
|
|
2
|
+
|
|
3
|
+
from depweight.deps import declared_packages, import_candidates
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_declared_packages_requirements_txt(git_repo):
|
|
7
|
+
write(git_repo, "requirements.txt", "requests>=2.31\nclick\n")
|
|
8
|
+
assert declared_packages(git_repo) == ["requests", "click"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_declared_packages_pyproject_toml(git_repo):
|
|
12
|
+
write(git_repo, "pyproject.toml", '[project]\nname="x"\ndependencies = ["pydantic>=2.6"]\n')
|
|
13
|
+
assert declared_packages(git_repo) == ["pydantic"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_declared_packages_combina_y_deduplica(git_repo):
|
|
17
|
+
write(git_repo, "requirements.txt", "click\n")
|
|
18
|
+
write(git_repo, "pyproject.toml", '[project]\nname="x"\ndependencies = ["click", "requests"]\n')
|
|
19
|
+
assert declared_packages(git_repo) == ["click", "requests"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_declared_packages_ninguno(git_repo):
|
|
23
|
+
assert declared_packages(git_repo) == []
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_import_candidates_mapeo_conocido():
|
|
27
|
+
assert import_candidates("pyyaml") == ["yaml"]
|
|
28
|
+
assert import_candidates("beautifulsoup4") == ["bs4"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_import_candidates_normaliza_guiones():
|
|
32
|
+
assert import_candidates("some-package") == ["some_package"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_import_candidates_sin_mapeo_usa_nombre_normalizado():
|
|
36
|
+
assert import_candidates("requests") == ["requests"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_import_candidates_mapeo_conocido_ignora_mayusculas():
|
|
40
|
+
# Bug real encontrado 2026-08-09: requirements.txt/pyproject.toml suelen
|
|
41
|
+
# declarar el nombre tal como aparece en PyPI ("PyYAML", "Pillow"), pero
|
|
42
|
+
# el mapa usa claves en minúsculas -- comparar sin normalizar hacía que
|
|
43
|
+
# NINGUNA de estas entradas mapeadas coincidiera nunca al declararse con
|
|
44
|
+
# su capitalización real.
|
|
45
|
+
assert import_candidates("PyYAML") == ["yaml"]
|
|
46
|
+
assert import_candidates("Pillow") == ["PIL"]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_import_candidates_sin_mapeo_prueba_tambien_minusculas():
|
|
50
|
+
# Bug real encontrado 2026-08-09: la inmensa mayoría de paquetes sin
|
|
51
|
+
# mapeo explícito también importan en minúsculas aunque se declaren
|
|
52
|
+
# capitalizados ("Django" -> "django") -- sin esto, Django aparecía con
|
|
53
|
+
# 0 usos pese a estar fuertemente usado, el falso positivo exacto que
|
|
54
|
+
# esta herramienta existe para evitar.
|
|
55
|
+
assert import_candidates("Django") == ["Django", "django"]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_import_candidates_sin_mapeo_ya_en_minusculas_no_duplica():
|
|
59
|
+
assert import_candidates("requests") == ["requests"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_import_candidates_nombre_normalizado_como_pypi():
|
|
63
|
+
from depweight.deps import import_candidates
|
|
64
|
+
|
|
65
|
+
assert import_candidates("python_dateutil") == ["dateutil"]
|
|
66
|
+
assert import_candidates("Python.Dateutil") == ["dateutil"]
|
|
67
|
+
assert import_candidates("psycopg2-binary") == ["psycopg2"]
|
|
68
|
+
assert import_candidates("opencv-python-headless") == ["cv2"]
|
|
69
|
+
assert import_candidates("ruamel.yaml") == ["ruamel.yaml"]
|
|
70
|
+
assert import_candidates("zope.interface") == ["zope.interface"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from depweight.analyze import DependencyUsage
|
|
2
|
+
from depweight.report import to_console, to_json
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def test_to_console_sin_narrow_mensaje_limpio():
|
|
6
|
+
results = [DependencyUsage(package="click", import_names=["click"], usage_count=10, files=["a.py"], narrow=False)]
|
|
7
|
+
out = to_console(results, only_narrow=True)
|
|
8
|
+
assert "No hay dependencias" in out
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_to_console_muestra_narrow():
|
|
12
|
+
results = [
|
|
13
|
+
DependencyUsage(package="requests", import_names=["requests"], usage_count=1, files=["a.py"], narrow=True)
|
|
14
|
+
]
|
|
15
|
+
out = to_console(results)
|
|
16
|
+
assert "[NARROW]" in out
|
|
17
|
+
assert "requests" in out
|
|
18
|
+
assert "🔧" not in out and "⚠" not in out
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_to_console_cero_usos_mensaje_especifico():
|
|
22
|
+
results = [DependencyUsage(package="unused", import_names=["unused"], usage_count=0, files=[], narrow=True)]
|
|
23
|
+
out = to_console(results)
|
|
24
|
+
assert "no se encontró ningún uso real" in out
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_to_json_valido():
|
|
28
|
+
results = [DependencyUsage(package="click", import_names=["click"], usage_count=5, files=[], narrow=False)]
|
|
29
|
+
out = to_json(results)
|
|
30
|
+
assert '"package": "click"' in out
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
|
|
3
|
+
from depweight.usage import analyze_file, bound_names, count_usages_per_name
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_bound_names_import_simple():
|
|
7
|
+
tree = ast.parse("import requests\n")
|
|
8
|
+
assert bound_names(tree) == {"requests": "requests"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_bound_names_import_con_alias():
|
|
12
|
+
tree = ast.parse("import numpy as np\n")
|
|
13
|
+
assert bound_names(tree) == {"np": "numpy"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_bound_names_from_import():
|
|
17
|
+
tree = ast.parse("from pathlib import Path\n")
|
|
18
|
+
assert bound_names(tree) == {"Path": "pathlib"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_bound_names_ignora_imports_relativos():
|
|
22
|
+
tree = ast.parse("from .mod import algo\n")
|
|
23
|
+
assert bound_names(tree) == {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_bound_names_submodulo_usa_top_level():
|
|
27
|
+
tree = ast.parse("import os.path\n")
|
|
28
|
+
assert bound_names(tree) == {"os": "os"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_count_usages_per_name_cuenta_usos_reales():
|
|
32
|
+
tree = ast.parse("import requests\nrequests.get('x')\nrequests.post('y')\n")
|
|
33
|
+
counts = count_usages_per_name(tree, {"requests"})
|
|
34
|
+
assert counts["requests"] == 2
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_count_usages_per_name_cero_si_no_se_usa():
|
|
38
|
+
tree = ast.parse("import requests\n")
|
|
39
|
+
counts = count_usages_per_name(tree, {"requests"})
|
|
40
|
+
assert counts["requests"] == 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_analyze_file_devuelve_bindings_y_counts(tmp_path):
|
|
44
|
+
p = tmp_path / "mod.py"
|
|
45
|
+
p.write_text("import click\nclick.echo('hola')\n", encoding="utf-8")
|
|
46
|
+
bindings, counts = analyze_file(p)
|
|
47
|
+
assert bindings == {"click": "click"}
|
|
48
|
+
assert counts == {"click": 1}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_analyze_file_codigo_invalido_devuelve_none(tmp_path):
|
|
52
|
+
p = tmp_path / "bad.py"
|
|
53
|
+
p.write_text("esto no es python [[[", encoding="utf-8")
|
|
54
|
+
assert analyze_file(p) is None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_analyze_file_inexistente_devuelve_none(tmp_path):
|
|
58
|
+
assert analyze_file(tmp_path / "no-existe.py") is None
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from depweight import __version__
|
|
4
|
+
from depweight.cli import main
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_version(capsys):
|
|
8
|
+
with pytest.raises(SystemExit) as exc:
|
|
9
|
+
main(["--version"])
|
|
10
|
+
assert exc.value.code == 0
|
|
11
|
+
assert capsys.readouterr().out.strip() == f"depweight {__version__}"
|