depexplain 0.1.4__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.
- depexplain/__init__.py +3 -0
- depexplain/__main__.py +6 -0
- depexplain/cli.py +87 -0
- depexplain/deps.py +92 -0
- depexplain/diagnose.py +99 -0
- depexplain/environment.py +60 -0
- depexplain/explain.py +94 -0
- depexplain/report.py +28 -0
- depexplain-0.1.4.dist-info/METADATA +106 -0
- depexplain-0.1.4.dist-info/RECORD +14 -0
- depexplain-0.1.4.dist-info/WHEEL +5 -0
- depexplain-0.1.4.dist-info/entry_points.txt +2 -0
- depexplain-0.1.4.dist-info/licenses/LICENSE +21 -0
- depexplain-0.1.4.dist-info/top_level.txt +1 -0
depexplain/__init__.py
ADDED
depexplain/__main__.py
ADDED
depexplain/cli.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from depexplain import __version__
|
|
8
|
+
from depexplain.diagnose import diagnose_project, diagnose_project_by_import_name
|
|
9
|
+
from depexplain.explain import explain_undeclared, extract_module_name
|
|
10
|
+
from depexplain.report import to_console, to_json
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _cmd_diagnose(args: argparse.Namespace) -> int:
|
|
14
|
+
repo_path = Path(args.path).resolve()
|
|
15
|
+
diagnoses = diagnose_project(repo_path, include_extras=args.include_extras)
|
|
16
|
+
if diagnoses is None:
|
|
17
|
+
print("No aplica: no se encontró requirements.txt ni pyproject.toml.")
|
|
18
|
+
return 0
|
|
19
|
+
|
|
20
|
+
if args.json:
|
|
21
|
+
print(to_json(diagnoses))
|
|
22
|
+
else:
|
|
23
|
+
print(to_console(diagnoses, only_problems=not args.all))
|
|
24
|
+
|
|
25
|
+
if args.fail_on_problems and any(d.status != "ok" for d in diagnoses):
|
|
26
|
+
return 1
|
|
27
|
+
return 0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _cmd_explain(args: argparse.Namespace) -> int:
|
|
31
|
+
if args.file:
|
|
32
|
+
error_text = Path(args.file).read_text(encoding="utf-8")
|
|
33
|
+
elif args.text:
|
|
34
|
+
error_text = args.text
|
|
35
|
+
else:
|
|
36
|
+
error_text = sys.stdin.read()
|
|
37
|
+
|
|
38
|
+
module_name = extract_module_name(error_text)
|
|
39
|
+
if module_name is None:
|
|
40
|
+
print("No he reconocido ningún ModuleNotFoundError/ImportError en ese texto.")
|
|
41
|
+
return 1
|
|
42
|
+
|
|
43
|
+
repo_path = Path(args.path).resolve()
|
|
44
|
+
diagnosis = diagnose_project_by_import_name(repo_path, module_name)
|
|
45
|
+
if diagnosis is None:
|
|
46
|
+
for line in explain_undeclared(module_name):
|
|
47
|
+
print(line)
|
|
48
|
+
return 1
|
|
49
|
+
|
|
50
|
+
print(diagnosis.explanation)
|
|
51
|
+
if diagnosis.fix_command:
|
|
52
|
+
print(f"Fix: {diagnosis.fix_command}")
|
|
53
|
+
return 0 if diagnosis.status == "ok" else 1
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
57
|
+
parser = argparse.ArgumentParser(prog="depexplain")
|
|
58
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
59
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
60
|
+
|
|
61
|
+
p_diagnose = sub.add_parser("diagnose", help="Compara lo instalado contra lo declarado")
|
|
62
|
+
p_diagnose.add_argument("path", nargs="?", default=".")
|
|
63
|
+
p_diagnose.add_argument("--all", action="store_true", help="Muestra también los que están OK")
|
|
64
|
+
p_diagnose.add_argument(
|
|
65
|
+
"--include-extras", action="store_true", help="Incluye también optional-dependencies (dev, test...)"
|
|
66
|
+
)
|
|
67
|
+
p_diagnose.add_argument("--json", action="store_true")
|
|
68
|
+
p_diagnose.add_argument("--fail-on-problems", action="store_true")
|
|
69
|
+
p_diagnose.set_defaults(func=_cmd_diagnose)
|
|
70
|
+
|
|
71
|
+
p_explain = sub.add_parser("explain", help="Explica un ModuleNotFoundError/ImportError concreto")
|
|
72
|
+
p_explain.add_argument("text", nargs="?", default=None, help="El error, como texto")
|
|
73
|
+
p_explain.add_argument("--file", default=None, help="Leer el error de un fichero")
|
|
74
|
+
p_explain.add_argument("--path", default=".", help="Directorio del proyecto")
|
|
75
|
+
p_explain.set_defaults(func=_cmd_explain)
|
|
76
|
+
|
|
77
|
+
return parser
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def main(argv: list[str] | None = None) -> int:
|
|
81
|
+
parser = build_parser()
|
|
82
|
+
args = parser.parse_args(argv)
|
|
83
|
+
return args.func(args)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
sys.exit(main())
|
depexplain/deps.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import tomllib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from packaging.markers import UndefinedEnvironmentName
|
|
7
|
+
from packaging.requirements import InvalidRequirement, Requirement
|
|
8
|
+
from packaging.specifiers import SpecifierSet
|
|
9
|
+
from packaging.utils import canonicalize_name
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _parse_requirement_line(line: str) -> Requirement | None:
|
|
13
|
+
line = line.split("#", 1)[0].strip()
|
|
14
|
+
if not line or line.startswith("-"):
|
|
15
|
+
return None
|
|
16
|
+
try:
|
|
17
|
+
return Requirement(line)
|
|
18
|
+
except InvalidRequirement:
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _marker_applies(req: Requirement) -> bool:
|
|
23
|
+
assert req.marker is not None
|
|
24
|
+
try:
|
|
25
|
+
return req.marker.evaluate({"extra": ""})
|
|
26
|
+
except UndefinedEnvironmentName:
|
|
27
|
+
return True # marcador raro: mejor revisarlo que callarlo
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _add(declared: dict[str, SpecifierSet], req: Requirement) -> None:
|
|
31
|
+
# Un marcador que no aplica aquí (`; sys_platform == "win32"`, `; python_version < "3.11"`)
|
|
32
|
+
# significa que el paquete no hace falta en este entorno: antes salía como «falta instalar».
|
|
33
|
+
if req.marker is not None and not _marker_applies(req):
|
|
34
|
+
return
|
|
35
|
+
# El mismo paquete en dos sitios («Django» y «django») se une y se suman las restricciones.
|
|
36
|
+
key = next((k for k in declared if canonicalize_name(k) == canonicalize_name(req.name)), req.name)
|
|
37
|
+
declared[key] = declared[key] & req.specifier if key in declared else req.specifier
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_requirements_txt(path: Path) -> dict[str, SpecifierSet]:
|
|
41
|
+
if not path.exists():
|
|
42
|
+
return {}
|
|
43
|
+
declared: dict[str, SpecifierSet] = {}
|
|
44
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
45
|
+
req = _parse_requirement_line(line)
|
|
46
|
+
if req is not None:
|
|
47
|
+
_add(declared, req)
|
|
48
|
+
return declared
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_pyproject_toml(path: Path, *, include_extras: bool = False) -> dict[str, SpecifierSet]:
|
|
52
|
+
if not path.exists():
|
|
53
|
+
return {}
|
|
54
|
+
try:
|
|
55
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
56
|
+
except tomllib.TOMLDecodeError:
|
|
57
|
+
return {}
|
|
58
|
+
|
|
59
|
+
project = data.get("project", {})
|
|
60
|
+
lines: list[str] = list(project.get("dependencies", []))
|
|
61
|
+
if include_extras:
|
|
62
|
+
for extra_deps in project.get("optional-dependencies", {}).values():
|
|
63
|
+
lines.extend(extra_deps)
|
|
64
|
+
|
|
65
|
+
declared: dict[str, SpecifierSet] = {}
|
|
66
|
+
for line in lines:
|
|
67
|
+
req = _parse_requirement_line(line)
|
|
68
|
+
if req is not None:
|
|
69
|
+
_add(declared, req)
|
|
70
|
+
return declared
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def declared_dependencies(
|
|
74
|
+
repo_path: Path, *, include_extras: bool = False
|
|
75
|
+
) -> dict[str, SpecifierSet] | None:
|
|
76
|
+
"""None si no hay ni requirements.txt ni pyproject.toml -- no aplica.
|
|
77
|
+
Diccionario (posiblemente vacío) si al menos uno de los dos existe.
|
|
78
|
+
|
|
79
|
+
Por defecto solo mira dependencias obligatorias: las de
|
|
80
|
+
`[project.optional-dependencies]` (dev, test...) no tienen por qué estar
|
|
81
|
+
instaladas en un entorno normal (p.ej. producción), así que exigirlas
|
|
82
|
+
por defecto generaría falsos "falta instalar".
|
|
83
|
+
"""
|
|
84
|
+
req_path = repo_path / "requirements.txt"
|
|
85
|
+
pyproject_path = repo_path / "pyproject.toml"
|
|
86
|
+
if not req_path.exists() and not pyproject_path.exists():
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
declared = parse_requirements_txt(req_path)
|
|
90
|
+
for name, spec in parse_pyproject_toml(pyproject_path, include_extras=include_extras).items():
|
|
91
|
+
_add(declared, Requirement(f"{name}{spec}"))
|
|
92
|
+
return declared
|
depexplain/diagnose.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from packaging.specifiers import SpecifierSet
|
|
7
|
+
from packaging.utils import canonicalize_name
|
|
8
|
+
from packaging.version import InvalidVersion, Version
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from depexplain.deps import declared_dependencies
|
|
12
|
+
from depexplain.environment import installed_version
|
|
13
|
+
|
|
14
|
+
Status = Literal["ok", "missing", "version_mismatch"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Diagnosis(BaseModel):
|
|
18
|
+
package: str
|
|
19
|
+
declared_constraint: str
|
|
20
|
+
installed_version: str | None
|
|
21
|
+
status: Status
|
|
22
|
+
fix_command: str | None = None
|
|
23
|
+
explanation: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _fix_command(package: str, constraint: SpecifierSet) -> str:
|
|
27
|
+
spec = str(constraint)
|
|
28
|
+
if spec:
|
|
29
|
+
return f'pip install "{package}{spec}"'
|
|
30
|
+
return f"pip install {package}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def diagnose_package(package: str, constraint: SpecifierSet) -> Diagnosis:
|
|
34
|
+
installed = installed_version(package)
|
|
35
|
+
spec_str = str(constraint) or "(sin versión fijada)"
|
|
36
|
+
|
|
37
|
+
if installed is None:
|
|
38
|
+
return Diagnosis(
|
|
39
|
+
package=package,
|
|
40
|
+
declared_constraint=spec_str,
|
|
41
|
+
installed_version=None,
|
|
42
|
+
status="missing",
|
|
43
|
+
fix_command=_fix_command(package, constraint),
|
|
44
|
+
explanation=f"'{package}' no está instalado, pero el proyecto lo declara ({spec_str}).",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
satisfied = Version(installed) in constraint
|
|
49
|
+
except InvalidVersion:
|
|
50
|
+
satisfied = True # version no estandar (p.ej. de un VCS) -- no se puede comparar, no forzar
|
|
51
|
+
|
|
52
|
+
if not satisfied:
|
|
53
|
+
return Diagnosis(
|
|
54
|
+
package=package,
|
|
55
|
+
declared_constraint=spec_str,
|
|
56
|
+
installed_version=installed,
|
|
57
|
+
status="version_mismatch",
|
|
58
|
+
fix_command=_fix_command(package, constraint),
|
|
59
|
+
explanation=(
|
|
60
|
+
f"tienes '{package}' {installed} instalado, pero el proyecto pide {spec_str}."
|
|
61
|
+
),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
return Diagnosis(
|
|
65
|
+
package=package,
|
|
66
|
+
declared_constraint=spec_str,
|
|
67
|
+
installed_version=installed,
|
|
68
|
+
status="ok",
|
|
69
|
+
explanation=f"'{package}' {installed} cumple lo que pide el proyecto ({spec_str}).",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def diagnose_project(repo_path: Path, *, include_extras: bool = False) -> list[Diagnosis] | None:
|
|
74
|
+
declared = declared_dependencies(repo_path, include_extras=include_extras)
|
|
75
|
+
if declared is None:
|
|
76
|
+
return None
|
|
77
|
+
return [diagnose_package(pkg, spec) for pkg, spec in sorted(declared.items())]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def diagnose_project_by_import_name(
|
|
81
|
+
repo_path: Path, module_name: str, *, include_extras: bool = True
|
|
82
|
+
) -> Diagnosis | None:
|
|
83
|
+
"""Busca en las dependencias declaradas la que probablemente corresponde
|
|
84
|
+
a `module_name` (normalizando nombre de import vs. nombre de paquete),
|
|
85
|
+
para el flujo `depexplain explain`. Aquí sí se incluyen los extras por
|
|
86
|
+
defecto: si el error ya ocurrió, lo relevante es si el paquete que lo
|
|
87
|
+
causó está declarado en algún sitio, sea obligatorio u opcional.
|
|
88
|
+
"""
|
|
89
|
+
declared = declared_dependencies(repo_path, include_extras=include_extras)
|
|
90
|
+
if not declared:
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
from depexplain.environment import module_to_package
|
|
94
|
+
|
|
95
|
+
candidate = canonicalize_name(module_to_package(module_name))
|
|
96
|
+
for pkg, spec in declared.items():
|
|
97
|
+
if canonicalize_name(pkg) == candidate:
|
|
98
|
+
return diagnose_package(pkg, spec)
|
|
99
|
+
return None
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
# Nombre de import -> nombre de paquete en PyPI, para los casos donde no
|
|
6
|
+
# coinciden (lo que de verdad hace falta para traducir un ModuleNotFoundError
|
|
7
|
+
# en un "pip install <esto>" correcto).
|
|
8
|
+
IMPORT_TO_PACKAGE: dict[str, str] = {
|
|
9
|
+
"yaml": "pyyaml",
|
|
10
|
+
"PIL": "pillow",
|
|
11
|
+
"bs4": "beautifulsoup4",
|
|
12
|
+
"cv2": "opencv-python",
|
|
13
|
+
"sklearn": "scikit-learn",
|
|
14
|
+
"google.protobuf": "protobuf",
|
|
15
|
+
"dotenv": "python-dotenv",
|
|
16
|
+
"jwt": "pyjwt",
|
|
17
|
+
"dateutil": "python-dateutil",
|
|
18
|
+
"Crypto": "pycryptodome",
|
|
19
|
+
"OpenSSL": "pyopenssl",
|
|
20
|
+
"docx": "python-docx",
|
|
21
|
+
"pptx": "python-pptx",
|
|
22
|
+
"serial": "pyserial",
|
|
23
|
+
"usb": "pyusb",
|
|
24
|
+
"markdown_it": "markdown-it-py",
|
|
25
|
+
"pkg_resources": "setuptools",
|
|
26
|
+
"attr": "attrs",
|
|
27
|
+
"magic": "python-magic",
|
|
28
|
+
"MySQLdb": "mysqlclient",
|
|
29
|
+
"git": "gitpython",
|
|
30
|
+
"jose": "python-jose",
|
|
31
|
+
"multipart": "python-multipart",
|
|
32
|
+
"socks": "pysocks",
|
|
33
|
+
"win32api": "pywin32",
|
|
34
|
+
"win32con": "pywin32",
|
|
35
|
+
"skimage": "scikit-image",
|
|
36
|
+
"fitz": "pymupdf",
|
|
37
|
+
"ldap": "python-ldap",
|
|
38
|
+
"nacl": "pynacl",
|
|
39
|
+
"gi": "pygobject",
|
|
40
|
+
"zmq": "pyzmq",
|
|
41
|
+
"telegram": "python-telegram-bot",
|
|
42
|
+
"Bio": "biopython",
|
|
43
|
+
"googleapiclient": "google-api-python-client",
|
|
44
|
+
"dns": "dnspython",
|
|
45
|
+
"kafka": "kafka-python",
|
|
46
|
+
"slugify": "python-slugify",
|
|
47
|
+
"ruamel": "ruamel.yaml",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def module_to_package(module_name: str) -> str:
|
|
52
|
+
top_level = module_name.split(".")[0]
|
|
53
|
+
return IMPORT_TO_PACKAGE.get(module_name, IMPORT_TO_PACKAGE.get(top_level, top_level))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def installed_version(package_name: str) -> str | None:
|
|
57
|
+
try:
|
|
58
|
+
return version(package_name)
|
|
59
|
+
except PackageNotFoundError:
|
|
60
|
+
return None
|
depexplain/explain.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
_MODULE_NOT_FOUND = re.compile(r"ModuleNotFoundError: No module named ['\"]([\w.]+)['\"]")
|
|
6
|
+
_IMPORT_ERROR_FROM = re.compile(r"ImportError: cannot import name ['\"][\w.]+['\"] from ['\"]([\w.]+)['\"]")
|
|
7
|
+
_IMPORT_ERROR_PLAIN = re.compile(r"ImportError: No module named ['\"]?([\w.]+)['\"]?")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def extract_module_name(error_text: str) -> str | None:
|
|
11
|
+
for pattern in (_MODULE_NOT_FOUND, _IMPORT_ERROR_FROM, _IMPORT_ERROR_PLAIN):
|
|
12
|
+
m = pattern.search(error_text)
|
|
13
|
+
if m:
|
|
14
|
+
return m.group(1)
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# Módulos que se quitaron de la biblioteca estándar y qué usar en su lugar (PEP 632 y PEP 594).
|
|
19
|
+
REMOVED_FROM_STDLIB: dict[str, tuple[str, str]] = {
|
|
20
|
+
"distutils": ("3.12", "instala setuptools (trae un distutils compatible) o pasa a packaging/setuptools"),
|
|
21
|
+
"imp": ("3.12", "usa importlib"),
|
|
22
|
+
"asyncore": ("3.12", "usa asyncio"),
|
|
23
|
+
"asynchat": ("3.12", "usa asyncio"),
|
|
24
|
+
"smtpd": ("3.12", "usa aiosmtpd (pip install aiosmtpd)"),
|
|
25
|
+
"cgi": ("3.13", "usa email.message o multipart; para salir del paso, pip install legacy-cgi"),
|
|
26
|
+
"cgitb": ("3.13", "usa el módulo traceback"),
|
|
27
|
+
"imghdr": ("3.13", "usa filetype o puremagic (pip install filetype)"),
|
|
28
|
+
"sndhdr": ("3.13", "usa filetype (pip install filetype)"),
|
|
29
|
+
"telnetlib": ("3.13", "usa telnetlib3 (pip install telnetlib3)"),
|
|
30
|
+
"pipes": ("3.13", "usa shlex.quote"),
|
|
31
|
+
"crypt": ("3.13", "usa hashlib o passlib (pip install passlib)"),
|
|
32
|
+
"uu": ("3.13", "usa base64"),
|
|
33
|
+
"xdrlib": ("3.13", "no tiene sustituto directo en la biblioteca estándar"),
|
|
34
|
+
"nntplib": ("3.13", "no tiene sustituto directo en la biblioteca estándar"),
|
|
35
|
+
"mailcap": ("3.13", "usa mimetypes"),
|
|
36
|
+
"aifc": ("3.13", "usa soundfile (pip install soundfile)"),
|
|
37
|
+
"audioop": ("3.13", "pip install audioop-lts"),
|
|
38
|
+
"chunk": ("3.13", "no tiene sustituto directo en la biblioteca estándar"),
|
|
39
|
+
"sunau": ("3.13", "usa soundfile (pip install soundfile)"),
|
|
40
|
+
"spwd": ("3.13", "usa python-pam o lee /etc/shadow con permisos"),
|
|
41
|
+
"nis": ("3.13", "no tiene sustituto directo en la biblioteca estándar"),
|
|
42
|
+
"ossaudiodev": ("3.13", "usa pyalsaaudio o sounddevice"),
|
|
43
|
+
"msilib": ("3.13", "no tiene sustituto directo en la biblioteca estándar"),
|
|
44
|
+
"lib2to3": ("3.13", "usa libcst o parso"),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
# Módulos de la biblioteca estándar que dependen de una librería del sistema al compilar Python:
|
|
48
|
+
# si faltan, no es un problema de pip.
|
|
49
|
+
_STDLIB_SYSTEM_LIBS: dict[str, str] = {
|
|
50
|
+
"_ctypes": "libffi-dev", "ctypes": "libffi-dev",
|
|
51
|
+
"_sqlite3": "libsqlite3-dev", "sqlite3": "libsqlite3-dev",
|
|
52
|
+
"_tkinter": "tk-dev (o el paquete python3-tk)", "tkinter": "tk-dev (o el paquete python3-tk)",
|
|
53
|
+
"_ssl": "libssl-dev", "ssl": "libssl-dev", "_hashlib": "libssl-dev",
|
|
54
|
+
"_bz2": "libbz2-dev", "bz2": "libbz2-dev",
|
|
55
|
+
"_lzma": "liblzma-dev", "lzma": "liblzma-dev",
|
|
56
|
+
"zlib": "zlib1g-dev", "readline": "libreadline-dev",
|
|
57
|
+
"_uuid": "uuid-dev", "_curses": "libncurses-dev", "curses": "libncurses-dev",
|
|
58
|
+
"_dbm": "libgdbm-dev", "_gdbm": "libgdbm-dev",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def explain_undeclared(module_name: str) -> list[str]:
|
|
63
|
+
"""Qué hacer con un módulo que el proyecto no declara.
|
|
64
|
+
|
|
65
|
+
Antes solo decía «añade '<módulo>' a requirements.txt»: con yaml, cv2 o sklearn eso es instalar
|
|
66
|
+
un paquete que no es (los buenos son PyYAML, opencv-python y scikit-learn), y con distutils o
|
|
67
|
+
_ctypes ni siquiera es cosa de pip."""
|
|
68
|
+
import sys
|
|
69
|
+
|
|
70
|
+
from depexplain.environment import module_to_package
|
|
71
|
+
|
|
72
|
+
top = module_name.split(".")[0]
|
|
73
|
+
if top in REMOVED_FROM_STDLIB:
|
|
74
|
+
since, instead = REMOVED_FROM_STDLIB[top]
|
|
75
|
+
return [
|
|
76
|
+
f"'{top}' era de la biblioteca estándar y se quitó en Python {since}.",
|
|
77
|
+
f"Solución: {instead}.",
|
|
78
|
+
]
|
|
79
|
+
if top in _STDLIB_SYSTEM_LIBS:
|
|
80
|
+
return [
|
|
81
|
+
(f"'{top}' es de la biblioteca estándar, pero este Python se compiló sin la librería del "
|
|
82
|
+
f"sistema que necesita ({_STDLIB_SYSTEM_LIBS[top]})."),
|
|
83
|
+
("Solución: instala esa librería y vuelve a compilar o instalar Python (pyenv, uv python "
|
|
84
|
+
"install…), o usa el Python de la distribución."),
|
|
85
|
+
]
|
|
86
|
+
if top in getattr(sys, "stdlib_module_names", ()):
|
|
87
|
+
return [(f"'{top}' es de la biblioteca estándar: revisa si el nombre está bien escrito o si "
|
|
88
|
+
"un fichero local con el mismo nombre lo está tapando.")]
|
|
89
|
+
package = module_to_package(module_name)
|
|
90
|
+
lines = [f"'{module_name}' no está declarado como dependencia en este proyecto."]
|
|
91
|
+
if package.lower() != top.lower():
|
|
92
|
+
lines.append(f"Ojo: el paquete que lo instala se llama '{package}', no '{top}'.")
|
|
93
|
+
lines.append(f"Solución: añade '{package}' a requirements.txt/pyproject.toml (pip install {package}).")
|
|
94
|
+
return lines
|
depexplain/report.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from depexplain.diagnose import Diagnosis
|
|
6
|
+
|
|
7
|
+
_LABELS = {"ok": "OK ", "missing": "FALTA ", "version_mismatch": "VERSION"}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def to_console(diagnoses: list[Diagnosis], *, only_problems: bool = True) -> str:
|
|
11
|
+
shown = [d for d in diagnoses if d.status != "ok"] if only_problems else diagnoses
|
|
12
|
+
if not shown:
|
|
13
|
+
return "Todo en orden: lo instalado cumple con lo que declara el proyecto."
|
|
14
|
+
|
|
15
|
+
lines = []
|
|
16
|
+
for d in shown:
|
|
17
|
+
label = f"[{_LABELS[d.status]:<8}]"
|
|
18
|
+
lines.append(f"{label} {d.explanation}")
|
|
19
|
+
if d.fix_command:
|
|
20
|
+
lines.append(f" Fix: {d.fix_command}")
|
|
21
|
+
problems = sum(1 for d in diagnoses if d.status != "ok")
|
|
22
|
+
lines.append("")
|
|
23
|
+
lines.append(f"Total: {problems} problema(s) de {len(diagnoses)} dependencia(s) revisada(s).")
|
|
24
|
+
return "\n".join(lines)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def to_json(diagnoses: list[Diagnosis]) -> str:
|
|
28
|
+
return json.dumps([d.model_dump() for d in diagnoses], ensure_ascii=False, indent=2)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: depexplain
|
|
3
|
+
Version: 0.1.4
|
|
4
|
+
Summary: Traduce ImportError/ModuleNotFoundError a un diagnóstico claro: qué tienes instalado, qué pide el proyecto, y el comando exacto para arreglarlo.
|
|
5
|
+
Author: José Luis Segura Yuste
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jl-segurayuste/depexplain
|
|
8
|
+
Project-URL: Source, https://github.com/jl-segurayuste/depexplain
|
|
9
|
+
Project-URL: Issues, https://github.com/jl-segurayuste/depexplain/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/jl-segurayuste/depexplain/releases
|
|
11
|
+
Keywords: developer-tools,dependencies,troubleshooting
|
|
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
|
+
# depexplain
|
|
36
|
+
|
|
37
|
+
[](https://pypi.org/project/depexplain/)
|
|
38
|
+
[](https://github.com/jl-segurayuste/depexplain/actions/workflows/ci.yml)
|
|
39
|
+
[](https://github.com/jl-segurayuste/depexplain/blob/main/pyproject.toml)
|
|
40
|
+
[](https://github.com/jl-segurayuste/depexplain/blob/main/LICENSE)
|
|
41
|
+
|
|
42
|
+
Traduce un `ImportError`/`ModuleNotFoundError` a un diagnóstico claro: qué
|
|
43
|
+
tienes instalado, qué pide el proyecto, y el comando exacto para arreglarlo —
|
|
44
|
+
en vez de tener que averiguarlo tú mismo comparando versiones a mano.
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
$ python3 app.py
|
|
48
|
+
...
|
|
49
|
+
ImportError: cannot import name 'BaseSettings' from 'pydantic'
|
|
50
|
+
|
|
51
|
+
$ echo "$ERROR" | depexplain explain
|
|
52
|
+
tienes 'pydantic' 2.13.4 instalado, pero el proyecto pide ==1.10.0.
|
|
53
|
+
Fix: pip install "pydantic==1.10.0"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Así se ve
|
|
57
|
+
|
|
58
|
+

|
|
59
|
+
|
|
60
|
+
<sub>Ejecución real sobre un proyecto con una dependencia sin instalar y otra con versión incompatible (todos los datos son ficticios).</sub>
|
|
61
|
+
|
|
62
|
+
## Por qué existe
|
|
63
|
+
|
|
64
|
+
"Tengo numpy 2 pero el proyecto necesita 1.26" es uno de los errores más
|
|
65
|
+
comunes y a la vez más tediosos de diagnosticar a mano: hay que mirar el
|
|
66
|
+
traceback, adivinar qué paquete lo causó (no siempre coincide con el nombre
|
|
67
|
+
del módulo — `yaml` es `pyyaml`, `cv2` es `opencv-python`...), comprobar qué
|
|
68
|
+
versión tienes instalada, y qué versión pide realmente el proyecto.
|
|
69
|
+
`depexplain` hace esas tres comprobaciones por ti.
|
|
70
|
+
|
|
71
|
+
## Instalación
|
|
72
|
+
|
|
73
|
+
Todavía no está en PyPI:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pipx install depexplain # recomendado para herramientas de línea de comandos
|
|
77
|
+
# o bien
|
|
78
|
+
pip install depexplain
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Uso
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
depexplain diagnose . # compara todo lo declarado vs. lo instalado
|
|
85
|
+
depexplain diagnose . --all # incluye también lo que está OK
|
|
86
|
+
depexplain diagnose . --json
|
|
87
|
+
depexplain diagnose . --fail-on-problems # código de salida 1 si hay algo mal (para CI)
|
|
88
|
+
|
|
89
|
+
depexplain explain "ModuleNotFoundError: No module named 'yaml'"
|
|
90
|
+
echo "$ERROR" | depexplain explain # o por stdin, pegando el traceback completo
|
|
91
|
+
depexplain explain --file traceback.txt
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Lee `requirements.txt` y/o `pyproject.toml` (`[project.dependencies]` y
|
|
95
|
+
`[project.optional-dependencies]`), usando `packaging` para interpretar
|
|
96
|
+
correctamente los especificadores de versión (`>=`, `<`, `==`, `~=`...).
|
|
97
|
+
Nunca ejecuta el código del proyecto — solo introspecciona el entorno de
|
|
98
|
+
Python actual (`importlib.metadata`) y los ficheros de dependencias.
|
|
99
|
+
|
|
100
|
+
## Desarrollo
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
pip install -e ".[dev]"
|
|
104
|
+
ruff check .
|
|
105
|
+
pytest
|
|
106
|
+
```
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
depexplain/__init__.py,sha256=AwLnoadoW0M7c4OjdxaSkbRDDpq9h017bZu0G7fZJDE,113
|
|
2
|
+
depexplain/__main__.py,sha256=z3kZx_aMGvDS05uBCiQzWmQpsOi3okl3zEWZe-B6wgU,93
|
|
3
|
+
depexplain/cli.py,sha256=wwCLWgb25femTrsFeKXa3L_9P2NY-lF03Y6pPD5Sp3U,3125
|
|
4
|
+
depexplain/deps.py,sha256=Jlg1G8cTKCR-mvQac8aXjayUeJszVHCxifX9Dipsg2o,3413
|
|
5
|
+
depexplain/diagnose.py,sha256=91exg3o-7Xarn-5dhqUQmQuRBH8Rd2xlDQn0TOzwhgc,3397
|
|
6
|
+
depexplain/environment.py,sha256=9POb4daTT42QX3cH_PQwqwbHbpQey1LTSOs6h-Hq_rU,1772
|
|
7
|
+
depexplain/explain.py,sha256=7atRjTXY5f5D415cBOFL-eaBS9PDCCnYASYKLrLgG_c,4824
|
|
8
|
+
depexplain/report.py,sha256=NqMg1zraM35gi7JGVKomwVJqzOhP0efyXPGo7u92zh0,1008
|
|
9
|
+
depexplain-0.1.4.dist-info/licenses/LICENSE,sha256=70acRqGbi12E-RBHctB4yHLzZOoCFayZUXlhAUvwaAM,1080
|
|
10
|
+
depexplain-0.1.4.dist-info/METADATA,sha256=a11nx4hvcnryTJZmp_p3VXmCPirsCMxVwa9Ze2Pb8cE,4392
|
|
11
|
+
depexplain-0.1.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
depexplain-0.1.4.dist-info/entry_points.txt,sha256=wIEB_JsbPxKi8CsomwUWoLuq-HzmTm6sKeGdkuzf1t0,51
|
|
13
|
+
depexplain-0.1.4.dist-info/top_level.txt,sha256=fb_z6_mFD_LAVikli2QqO6NPMA9rXV3wg-00Z9Tb-TI,11
|
|
14
|
+
depexplain-0.1.4.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
|
+
depexplain
|