pip_check.py 4.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """Which `uv pip check` incompatibilities the project's lock resolved on purpose.
  2. A `[tool.uv] override-dependencies` entry replaces a dependency's requirement
  3. during resolution, but the installed distribution still declares the original,
  4. so `uv pip check` reports the overridden package as incompatible. uv.lock records
  5. the overrides it applied (`[manifest] overrides`) and the version it resolved for
  6. each, so a report line is expected exactly when it names an overridden
  7. dependency installed at the locked version. Everything else still fails.
  8. Installs from the lock's requirements export (`uv pip install`) re-resolve, so they
  9. need the same overrides back (override_requirements) to reach the locked graph.
  10. Stdlib only: the bootstrap runner loads pm.environment on a system python that
  11. may predate tomllib.
  12. """
  13. from __future__ import annotations
  14. from pathlib import Path
  15. import re
  16. # The incompatibility lines uv prints, e.g.
  17. # The package `browser-harness` requires `pillow==12.3.0`, but `13.0.0` is installed
  18. _REPORT_LINE = re.compile(r"^The package `[^`]+` requires ")
  19. _VERSION_MISMATCH = re.compile(
  20. r"^The package `[^`]+` requires `([A-Za-z0-9][A-Za-z0-9._-]*)[^`]*`, but `([^`]+)` is installed$"
  21. )
  22. _FOUND = re.compile(r"^Found (\d+) incompatibilit(?:y|ies)$", re.MULTILINE)
  23. def _normalize(name: str) -> str:
  24. return re.sub(r"[-_.]+", "-", name).lower()
  25. def _parse_lock(text: str) -> tuple[list[dict[str, str]], list[tuple[str, str]]]:
  26. """Manifest overrides ({name, specifier?, marker?}) and (name, version) packages from uv.lock text."""
  27. try:
  28. import tomllib
  29. except ModuleNotFoundError:
  30. manifest = re.search(r"(?ms)^\[manifest\]\s*$(.*?)(?=^\[)", text + "\n[")
  31. overrides = re.search(r"(?ms)^overrides\s*=\s*\[(.*?)^\]", manifest.group(1)) if manifest else None
  32. tables = re.findall(r"\{([^}]*)\}", overrides.group(1)) if overrides else []
  33. entries = [dict(re.findall(r'(\w+)\s*=\s*"([^"]*)"', table)) for table in tables]
  34. packages = re.findall(r'(?m)^\[\[package\]\]\s*\nname = "([^"]+)"\s*\nversion = "([^"]+)"', text)
  35. return entries, packages
  36. data = tomllib.loads(text)
  37. entries = data.get("manifest", {}).get("overrides", [])
  38. packages = [(package["name"], package["version"]) for package in data.get("package", []) if "version" in package]
  39. return entries, packages
  40. def override_requirements(lock: Path) -> list[str]:
  41. """The lock's manifest overrides as requirement lines for `uv pip install --overrides`."""
  42. entries, _ = _parse_lock(lock.read_text(encoding="utf-8"))
  43. lines = []
  44. for entry in entries:
  45. if set(entry) - {"name", "specifier", "marker"}:
  46. # A source override (URL, path, git) has no requirement-line form here.
  47. raise ValueError(f"unsupported uv.lock override: {entry}")
  48. line = entry["name"] + entry.get("specifier", "")
  49. if entry.get("marker"):
  50. line += " ; " + entry["marker"]
  51. lines.append(line)
  52. return lines
  53. def overridden_versions(lock: Path) -> dict[str, set[str]]:
  54. """Locked versions of every dependency the lock's manifest overrides."""
  55. entries, packages = _parse_lock(lock.read_text(encoding="utf-8"))
  56. overridden = {_normalize(entry["name"]) for entry in entries}
  57. versions: dict[str, set[str]] = {}
  58. for name, version in packages:
  59. if _normalize(name) in overridden:
  60. versions.setdefault(_normalize(name), set()).add(version)
  61. return versions
  62. def unexpected_incompatibilities(report: str, lock: Path | None) -> list[str] | None:
  63. """The report lines *lock* does not account for.
  64. None when the report cannot be read line by line: no lines, or uv's "Found N"
  65. total missing or different from the lines recognised (a truncated report loses
  66. its head, and any failure printed there). The caller then fails on the raw output
  67. instead of trusting a partial parse.
  68. """
  69. lines = [line.strip() for line in report.splitlines() if _REPORT_LINE.match(line.strip())]
  70. found = _FOUND.search(report)
  71. if not lines or not found or int(found.group(1)) != len(lines):
  72. return None
  73. if lock is None or not lock.is_file():
  74. return lines
  75. expected = overridden_versions(lock)
  76. unexpected = []
  77. for line in lines:
  78. mismatch = _VERSION_MISMATCH.match(line)
  79. if not (mismatch and mismatch.group(2) in expected.get(_normalize(mismatch.group(1)), ())):
  80. unexpected.append(line)
  81. return unexpected