Skip to content

Commit

Permalink
Replace pkg_resources with packaging & importlib
Browse files Browse the repository at this point in the history
It's not perfect; in the long run we may want to use a tool like uv or
pixi instead.
  • Loading branch information
stefanv committed Jan 17, 2025
1 parent 8f6d1dc commit 7e04229
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions tools/pip_install_requirements.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import subprocess
import sys

import pkg_resources
from pkg_resources import DistributionNotFound, Requirement, VersionConflict
from packaging.requirements import Requirement
import importlib
import importlib.metadata

from status import status

if len(sys.argv) < 2:
Expand Down Expand Up @@ -38,12 +40,25 @@ def pip(req_files):
sys.exit(retcode)


class IncompatibleVersionError(Exception):
pass

try:
with status("Verifying Python package dependencies"):
pkg_resources.working_set.resolve(
[Requirement.parse(r.split("#egg=")[-1]) for r in requirements]
)
for rspec in requirements:
req = Requirement(rspec.strip().split("#egg=")[-1].replace('==', '~='))
name = req.name
version_specifier = req.specifier
version_installed = importlib.metadata.version(name)

if not version_specifier.contains(version_installed):
raise IncompatibleVersionError(f'Need {name} {version_specifier} but found {version_installed}')

except importlib.metadata.PackageNotFoundError: #
print(f'[!] Package `{name}` not found; refreshing dependencies')
except IncompatibleVersionError as e:
print(f'[!] {e}')
else:
sys.exit(0)

except (DistributionNotFound, VersionConflict) as e:
print(e.report())
pip(all_req_files)
pip(all_req_files)

0 comments on commit 7e04229

Please sign in to comment.