From e41bfab17e0ebf8f372fce84b29c6fa869d7313f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Morosi?= Date: Fri, 22 Sep 2023 11:33:53 +0200 Subject: [PATCH] Use Specifier class to check version constraints Package.add_constraint implements its own way to check for version constraints, while packaging.specifiers.Specifier can be used --- src/e3/python/pypi.py | 36 +++++++----------------------- tests/tests_e3/python/main_test.py | 1 + 2 files changed, 9 insertions(+), 28 deletions(-) diff --git a/src/e3/python/pypi.py b/src/e3/python/pypi.py index 3969a420..994f8cd7 100644 --- a/src/e3/python/pypi.py +++ b/src/e3/python/pypi.py @@ -7,6 +7,7 @@ import time import packaging.version import packaging.tags +import packaging.specifiers from typing import TYPE_CHECKING from e3.error import E3Error from e3.python.wheel import Wheel @@ -332,34 +333,13 @@ def add_constraint(self, requirement: Requirement) -> None: # Apply version constraints for spec in requirement.specs: - if spec[1].endswith(".*") and spec[0] == "!=": - # Handle requirements ending with * apart as it is not covered by - # packaging.version - self.versions = [ - v for v in self.versions if not str(v).startswith(spec[1][:-2]) - ] - else: - target_version = packaging.version.parse(spec[1]) - if spec[0] == ">=": - self.versions = [v for v in self.versions if v >= target_version] - elif spec[0] == ">": - self.versions = [v for v in self.versions if v > target_version] - elif spec[0] == "!=": - self.versions = [v for v in self.versions if v != target_version] - elif spec[0] == "<": - self.versions = [v for v in self.versions if v < target_version] - elif spec[0] == "<=": - self.versions = [v for v in self.versions if v <= target_version] - elif spec[0] == "==": - self.versions = [v for v in self.versions if v == target_version] - elif spec[0] == "~=": - self.versions = [ - v - for v in self.versions - if str(v).startswith(str(target_version) + ".") - ] - else: - raise PyPIError(f"Unknown constraint operator {spec[0]}") + self.versions = [ + v + for v in self.versions + if packaging.specifiers.Specifier(f"{spec[0]}{spec[1]}").contains( + str(v) + ) + ] if len(self.versions) != current_length: logging.debug( diff --git a/tests/tests_e3/python/main_test.py b/tests/tests_e3/python/main_test.py index 069f796b..f219ea6a 100644 --- a/tests/tests_e3/python/main_test.py +++ b/tests/tests_e3/python/main_test.py @@ -59,6 +59,7 @@ def test_wheel(): pypi.add_requirement("src1>0.5.0") pypi.add_requirement("src1>=0.6.0") pypi.add_requirement("src1!=0.4.2") + pypi.add_requirement("src1~=1.0.0") assert len(pypi.file_closure()) == 2 assert len(pypi.closure_as_requirements()) == 2 assert len(pypi.closure()) == 2