annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/site-packages/packaging/specifiers.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 # This file is dual licensed under the terms of the Apache License, Version
jpayne@69 2 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
jpayne@69 3 # for complete details.
jpayne@69 4 """
jpayne@69 5 .. testsetup::
jpayne@69 6
jpayne@69 7 from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
jpayne@69 8 from packaging.version import Version
jpayne@69 9 """
jpayne@69 10
jpayne@69 11 from __future__ import annotations
jpayne@69 12
jpayne@69 13 import abc
jpayne@69 14 import itertools
jpayne@69 15 import re
jpayne@69 16 from typing import Callable, Iterable, Iterator, TypeVar, Union
jpayne@69 17
jpayne@69 18 from .utils import canonicalize_version
jpayne@69 19 from .version import Version
jpayne@69 20
jpayne@69 21 UnparsedVersion = Union[Version, str]
jpayne@69 22 UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
jpayne@69 23 CallableOperator = Callable[[Version, str], bool]
jpayne@69 24
jpayne@69 25
jpayne@69 26 def _coerce_version(version: UnparsedVersion) -> Version:
jpayne@69 27 if not isinstance(version, Version):
jpayne@69 28 version = Version(version)
jpayne@69 29 return version
jpayne@69 30
jpayne@69 31
jpayne@69 32 class InvalidSpecifier(ValueError):
jpayne@69 33 """
jpayne@69 34 Raised when attempting to create a :class:`Specifier` with a specifier
jpayne@69 35 string that is invalid.
jpayne@69 36
jpayne@69 37 >>> Specifier("lolwat")
jpayne@69 38 Traceback (most recent call last):
jpayne@69 39 ...
jpayne@69 40 packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
jpayne@69 41 """
jpayne@69 42
jpayne@69 43
jpayne@69 44 class BaseSpecifier(metaclass=abc.ABCMeta):
jpayne@69 45 @abc.abstractmethod
jpayne@69 46 def __str__(self) -> str:
jpayne@69 47 """
jpayne@69 48 Returns the str representation of this Specifier-like object. This
jpayne@69 49 should be representative of the Specifier itself.
jpayne@69 50 """
jpayne@69 51
jpayne@69 52 @abc.abstractmethod
jpayne@69 53 def __hash__(self) -> int:
jpayne@69 54 """
jpayne@69 55 Returns a hash value for this Specifier-like object.
jpayne@69 56 """
jpayne@69 57
jpayne@69 58 @abc.abstractmethod
jpayne@69 59 def __eq__(self, other: object) -> bool:
jpayne@69 60 """
jpayne@69 61 Returns a boolean representing whether or not the two Specifier-like
jpayne@69 62 objects are equal.
jpayne@69 63
jpayne@69 64 :param other: The other object to check against.
jpayne@69 65 """
jpayne@69 66
jpayne@69 67 @property
jpayne@69 68 @abc.abstractmethod
jpayne@69 69 def prereleases(self) -> bool | None:
jpayne@69 70 """Whether or not pre-releases as a whole are allowed.
jpayne@69 71
jpayne@69 72 This can be set to either ``True`` or ``False`` to explicitly enable or disable
jpayne@69 73 prereleases or it can be set to ``None`` (the default) to use default semantics.
jpayne@69 74 """
jpayne@69 75
jpayne@69 76 @prereleases.setter
jpayne@69 77 def prereleases(self, value: bool) -> None:
jpayne@69 78 """Setter for :attr:`prereleases`.
jpayne@69 79
jpayne@69 80 :param value: The value to set.
jpayne@69 81 """
jpayne@69 82
jpayne@69 83 @abc.abstractmethod
jpayne@69 84 def contains(self, item: str, prereleases: bool | None = None) -> bool:
jpayne@69 85 """
jpayne@69 86 Determines if the given item is contained within this specifier.
jpayne@69 87 """
jpayne@69 88
jpayne@69 89 @abc.abstractmethod
jpayne@69 90 def filter(
jpayne@69 91 self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
jpayne@69 92 ) -> Iterator[UnparsedVersionVar]:
jpayne@69 93 """
jpayne@69 94 Takes an iterable of items and filters them so that only items which
jpayne@69 95 are contained within this specifier are allowed in it.
jpayne@69 96 """
jpayne@69 97
jpayne@69 98
jpayne@69 99 class Specifier(BaseSpecifier):
jpayne@69 100 """This class abstracts handling of version specifiers.
jpayne@69 101
jpayne@69 102 .. tip::
jpayne@69 103
jpayne@69 104 It is generally not required to instantiate this manually. You should instead
jpayne@69 105 prefer to work with :class:`SpecifierSet` instead, which can parse
jpayne@69 106 comma-separated version specifiers (which is what package metadata contains).
jpayne@69 107 """
jpayne@69 108
jpayne@69 109 _operator_regex_str = r"""
jpayne@69 110 (?P<operator>(~=|==|!=|<=|>=|<|>|===))
jpayne@69 111 """
jpayne@69 112 _version_regex_str = r"""
jpayne@69 113 (?P<version>
jpayne@69 114 (?:
jpayne@69 115 # The identity operators allow for an escape hatch that will
jpayne@69 116 # do an exact string match of the version you wish to install.
jpayne@69 117 # This will not be parsed by PEP 440 and we cannot determine
jpayne@69 118 # any semantic meaning from it. This operator is discouraged
jpayne@69 119 # but included entirely as an escape hatch.
jpayne@69 120 (?<====) # Only match for the identity operator
jpayne@69 121 \s*
jpayne@69 122 [^\s;)]* # The arbitrary version can be just about anything,
jpayne@69 123 # we match everything except for whitespace, a
jpayne@69 124 # semi-colon for marker support, and a closing paren
jpayne@69 125 # since versions can be enclosed in them.
jpayne@69 126 )
jpayne@69 127 |
jpayne@69 128 (?:
jpayne@69 129 # The (non)equality operators allow for wild card and local
jpayne@69 130 # versions to be specified so we have to define these two
jpayne@69 131 # operators separately to enable that.
jpayne@69 132 (?<===|!=) # Only match for equals and not equals
jpayne@69 133
jpayne@69 134 \s*
jpayne@69 135 v?
jpayne@69 136 (?:[0-9]+!)? # epoch
jpayne@69 137 [0-9]+(?:\.[0-9]+)* # release
jpayne@69 138
jpayne@69 139 # You cannot use a wild card and a pre-release, post-release, a dev or
jpayne@69 140 # local version together so group them with a | and make them optional.
jpayne@69 141 (?:
jpayne@69 142 \.\* # Wild card syntax of .*
jpayne@69 143 |
jpayne@69 144 (?: # pre release
jpayne@69 145 [-_\.]?
jpayne@69 146 (alpha|beta|preview|pre|a|b|c|rc)
jpayne@69 147 [-_\.]?
jpayne@69 148 [0-9]*
jpayne@69 149 )?
jpayne@69 150 (?: # post release
jpayne@69 151 (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
jpayne@69 152 )?
jpayne@69 153 (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
jpayne@69 154 (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
jpayne@69 155 )?
jpayne@69 156 )
jpayne@69 157 |
jpayne@69 158 (?:
jpayne@69 159 # The compatible operator requires at least two digits in the
jpayne@69 160 # release segment.
jpayne@69 161 (?<=~=) # Only match for the compatible operator
jpayne@69 162
jpayne@69 163 \s*
jpayne@69 164 v?
jpayne@69 165 (?:[0-9]+!)? # epoch
jpayne@69 166 [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *)
jpayne@69 167 (?: # pre release
jpayne@69 168 [-_\.]?
jpayne@69 169 (alpha|beta|preview|pre|a|b|c|rc)
jpayne@69 170 [-_\.]?
jpayne@69 171 [0-9]*
jpayne@69 172 )?
jpayne@69 173 (?: # post release
jpayne@69 174 (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
jpayne@69 175 )?
jpayne@69 176 (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
jpayne@69 177 )
jpayne@69 178 |
jpayne@69 179 (?:
jpayne@69 180 # All other operators only allow a sub set of what the
jpayne@69 181 # (non)equality operators do. Specifically they do not allow
jpayne@69 182 # local versions to be specified nor do they allow the prefix
jpayne@69 183 # matching wild cards.
jpayne@69 184 (?<!==|!=|~=) # We have special cases for these
jpayne@69 185 # operators so we want to make sure they
jpayne@69 186 # don't match here.
jpayne@69 187
jpayne@69 188 \s*
jpayne@69 189 v?
jpayne@69 190 (?:[0-9]+!)? # epoch
jpayne@69 191 [0-9]+(?:\.[0-9]+)* # release
jpayne@69 192 (?: # pre release
jpayne@69 193 [-_\.]?
jpayne@69 194 (alpha|beta|preview|pre|a|b|c|rc)
jpayne@69 195 [-_\.]?
jpayne@69 196 [0-9]*
jpayne@69 197 )?
jpayne@69 198 (?: # post release
jpayne@69 199 (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
jpayne@69 200 )?
jpayne@69 201 (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
jpayne@69 202 )
jpayne@69 203 )
jpayne@69 204 """
jpayne@69 205
jpayne@69 206 _regex = re.compile(
jpayne@69 207 r"^\s*" + _operator_regex_str + _version_regex_str + r"\s*$",
jpayne@69 208 re.VERBOSE | re.IGNORECASE,
jpayne@69 209 )
jpayne@69 210
jpayne@69 211 _operators = {
jpayne@69 212 "~=": "compatible",
jpayne@69 213 "==": "equal",
jpayne@69 214 "!=": "not_equal",
jpayne@69 215 "<=": "less_than_equal",
jpayne@69 216 ">=": "greater_than_equal",
jpayne@69 217 "<": "less_than",
jpayne@69 218 ">": "greater_than",
jpayne@69 219 "===": "arbitrary",
jpayne@69 220 }
jpayne@69 221
jpayne@69 222 def __init__(self, spec: str = "", prereleases: bool | None = None) -> None:
jpayne@69 223 """Initialize a Specifier instance.
jpayne@69 224
jpayne@69 225 :param spec:
jpayne@69 226 The string representation of a specifier which will be parsed and
jpayne@69 227 normalized before use.
jpayne@69 228 :param prereleases:
jpayne@69 229 This tells the specifier if it should accept prerelease versions if
jpayne@69 230 applicable or not. The default of ``None`` will autodetect it from the
jpayne@69 231 given specifiers.
jpayne@69 232 :raises InvalidSpecifier:
jpayne@69 233 If the given specifier is invalid (i.e. bad syntax).
jpayne@69 234 """
jpayne@69 235 match = self._regex.search(spec)
jpayne@69 236 if not match:
jpayne@69 237 raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
jpayne@69 238
jpayne@69 239 self._spec: tuple[str, str] = (
jpayne@69 240 match.group("operator").strip(),
jpayne@69 241 match.group("version").strip(),
jpayne@69 242 )
jpayne@69 243
jpayne@69 244 # Store whether or not this Specifier should accept prereleases
jpayne@69 245 self._prereleases = prereleases
jpayne@69 246
jpayne@69 247 # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515
jpayne@69 248 @property # type: ignore[override]
jpayne@69 249 def prereleases(self) -> bool:
jpayne@69 250 # If there is an explicit prereleases set for this, then we'll just
jpayne@69 251 # blindly use that.
jpayne@69 252 if self._prereleases is not None:
jpayne@69 253 return self._prereleases
jpayne@69 254
jpayne@69 255 # Look at all of our specifiers and determine if they are inclusive
jpayne@69 256 # operators, and if they are if they are including an explicit
jpayne@69 257 # prerelease.
jpayne@69 258 operator, version = self._spec
jpayne@69 259 if operator in ["==", ">=", "<=", "~=", "===", ">", "<"]:
jpayne@69 260 # The == specifier can include a trailing .*, if it does we
jpayne@69 261 # want to remove before parsing.
jpayne@69 262 if operator == "==" and version.endswith(".*"):
jpayne@69 263 version = version[:-2]
jpayne@69 264
jpayne@69 265 # Parse the version, and if it is a pre-release than this
jpayne@69 266 # specifier allows pre-releases.
jpayne@69 267 if Version(version).is_prerelease:
jpayne@69 268 return True
jpayne@69 269
jpayne@69 270 return False
jpayne@69 271
jpayne@69 272 @prereleases.setter
jpayne@69 273 def prereleases(self, value: bool) -> None:
jpayne@69 274 self._prereleases = value
jpayne@69 275
jpayne@69 276 @property
jpayne@69 277 def operator(self) -> str:
jpayne@69 278 """The operator of this specifier.
jpayne@69 279
jpayne@69 280 >>> Specifier("==1.2.3").operator
jpayne@69 281 '=='
jpayne@69 282 """
jpayne@69 283 return self._spec[0]
jpayne@69 284
jpayne@69 285 @property
jpayne@69 286 def version(self) -> str:
jpayne@69 287 """The version of this specifier.
jpayne@69 288
jpayne@69 289 >>> Specifier("==1.2.3").version
jpayne@69 290 '1.2.3'
jpayne@69 291 """
jpayne@69 292 return self._spec[1]
jpayne@69 293
jpayne@69 294 def __repr__(self) -> str:
jpayne@69 295 """A representation of the Specifier that shows all internal state.
jpayne@69 296
jpayne@69 297 >>> Specifier('>=1.0.0')
jpayne@69 298 <Specifier('>=1.0.0')>
jpayne@69 299 >>> Specifier('>=1.0.0', prereleases=False)
jpayne@69 300 <Specifier('>=1.0.0', prereleases=False)>
jpayne@69 301 >>> Specifier('>=1.0.0', prereleases=True)
jpayne@69 302 <Specifier('>=1.0.0', prereleases=True)>
jpayne@69 303 """
jpayne@69 304 pre = (
jpayne@69 305 f", prereleases={self.prereleases!r}"
jpayne@69 306 if self._prereleases is not None
jpayne@69 307 else ""
jpayne@69 308 )
jpayne@69 309
jpayne@69 310 return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
jpayne@69 311
jpayne@69 312 def __str__(self) -> str:
jpayne@69 313 """A string representation of the Specifier that can be round-tripped.
jpayne@69 314
jpayne@69 315 >>> str(Specifier('>=1.0.0'))
jpayne@69 316 '>=1.0.0'
jpayne@69 317 >>> str(Specifier('>=1.0.0', prereleases=False))
jpayne@69 318 '>=1.0.0'
jpayne@69 319 """
jpayne@69 320 return "{}{}".format(*self._spec)
jpayne@69 321
jpayne@69 322 @property
jpayne@69 323 def _canonical_spec(self) -> tuple[str, str]:
jpayne@69 324 canonical_version = canonicalize_version(
jpayne@69 325 self._spec[1],
jpayne@69 326 strip_trailing_zero=(self._spec[0] != "~="),
jpayne@69 327 )
jpayne@69 328 return self._spec[0], canonical_version
jpayne@69 329
jpayne@69 330 def __hash__(self) -> int:
jpayne@69 331 return hash(self._canonical_spec)
jpayne@69 332
jpayne@69 333 def __eq__(self, other: object) -> bool:
jpayne@69 334 """Whether or not the two Specifier-like objects are equal.
jpayne@69 335
jpayne@69 336 :param other: The other object to check against.
jpayne@69 337
jpayne@69 338 The value of :attr:`prereleases` is ignored.
jpayne@69 339
jpayne@69 340 >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
jpayne@69 341 True
jpayne@69 342 >>> (Specifier("==1.2.3", prereleases=False) ==
jpayne@69 343 ... Specifier("==1.2.3", prereleases=True))
jpayne@69 344 True
jpayne@69 345 >>> Specifier("==1.2.3") == "==1.2.3"
jpayne@69 346 True
jpayne@69 347 >>> Specifier("==1.2.3") == Specifier("==1.2.4")
jpayne@69 348 False
jpayne@69 349 >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
jpayne@69 350 False
jpayne@69 351 """
jpayne@69 352 if isinstance(other, str):
jpayne@69 353 try:
jpayne@69 354 other = self.__class__(str(other))
jpayne@69 355 except InvalidSpecifier:
jpayne@69 356 return NotImplemented
jpayne@69 357 elif not isinstance(other, self.__class__):
jpayne@69 358 return NotImplemented
jpayne@69 359
jpayne@69 360 return self._canonical_spec == other._canonical_spec
jpayne@69 361
jpayne@69 362 def _get_operator(self, op: str) -> CallableOperator:
jpayne@69 363 operator_callable: CallableOperator = getattr(
jpayne@69 364 self, f"_compare_{self._operators[op]}"
jpayne@69 365 )
jpayne@69 366 return operator_callable
jpayne@69 367
jpayne@69 368 def _compare_compatible(self, prospective: Version, spec: str) -> bool:
jpayne@69 369 # Compatible releases have an equivalent combination of >= and ==. That
jpayne@69 370 # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
jpayne@69 371 # implement this in terms of the other specifiers instead of
jpayne@69 372 # implementing it ourselves. The only thing we need to do is construct
jpayne@69 373 # the other specifiers.
jpayne@69 374
jpayne@69 375 # We want everything but the last item in the version, but we want to
jpayne@69 376 # ignore suffix segments.
jpayne@69 377 prefix = _version_join(
jpayne@69 378 list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
jpayne@69 379 )
jpayne@69 380
jpayne@69 381 # Add the prefix notation to the end of our string
jpayne@69 382 prefix += ".*"
jpayne@69 383
jpayne@69 384 return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
jpayne@69 385 prospective, prefix
jpayne@69 386 )
jpayne@69 387
jpayne@69 388 def _compare_equal(self, prospective: Version, spec: str) -> bool:
jpayne@69 389 # We need special logic to handle prefix matching
jpayne@69 390 if spec.endswith(".*"):
jpayne@69 391 # In the case of prefix matching we want to ignore local segment.
jpayne@69 392 normalized_prospective = canonicalize_version(
jpayne@69 393 prospective.public, strip_trailing_zero=False
jpayne@69 394 )
jpayne@69 395 # Get the normalized version string ignoring the trailing .*
jpayne@69 396 normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
jpayne@69 397 # Split the spec out by bangs and dots, and pretend that there is
jpayne@69 398 # an implicit dot in between a release segment and a pre-release segment.
jpayne@69 399 split_spec = _version_split(normalized_spec)
jpayne@69 400
jpayne@69 401 # Split the prospective version out by bangs and dots, and pretend
jpayne@69 402 # that there is an implicit dot in between a release segment and
jpayne@69 403 # a pre-release segment.
jpayne@69 404 split_prospective = _version_split(normalized_prospective)
jpayne@69 405
jpayne@69 406 # 0-pad the prospective version before shortening it to get the correct
jpayne@69 407 # shortened version.
jpayne@69 408 padded_prospective, _ = _pad_version(split_prospective, split_spec)
jpayne@69 409
jpayne@69 410 # Shorten the prospective version to be the same length as the spec
jpayne@69 411 # so that we can determine if the specifier is a prefix of the
jpayne@69 412 # prospective version or not.
jpayne@69 413 shortened_prospective = padded_prospective[: len(split_spec)]
jpayne@69 414
jpayne@69 415 return shortened_prospective == split_spec
jpayne@69 416 else:
jpayne@69 417 # Convert our spec string into a Version
jpayne@69 418 spec_version = Version(spec)
jpayne@69 419
jpayne@69 420 # If the specifier does not have a local segment, then we want to
jpayne@69 421 # act as if the prospective version also does not have a local
jpayne@69 422 # segment.
jpayne@69 423 if not spec_version.local:
jpayne@69 424 prospective = Version(prospective.public)
jpayne@69 425
jpayne@69 426 return prospective == spec_version
jpayne@69 427
jpayne@69 428 def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
jpayne@69 429 return not self._compare_equal(prospective, spec)
jpayne@69 430
jpayne@69 431 def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:
jpayne@69 432 # NB: Local version identifiers are NOT permitted in the version
jpayne@69 433 # specifier, so local version labels can be universally removed from
jpayne@69 434 # the prospective version.
jpayne@69 435 return Version(prospective.public) <= Version(spec)
jpayne@69 436
jpayne@69 437 def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:
jpayne@69 438 # NB: Local version identifiers are NOT permitted in the version
jpayne@69 439 # specifier, so local version labels can be universally removed from
jpayne@69 440 # the prospective version.
jpayne@69 441 return Version(prospective.public) >= Version(spec)
jpayne@69 442
jpayne@69 443 def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:
jpayne@69 444 # Convert our spec to a Version instance, since we'll want to work with
jpayne@69 445 # it as a version.
jpayne@69 446 spec = Version(spec_str)
jpayne@69 447
jpayne@69 448 # Check to see if the prospective version is less than the spec
jpayne@69 449 # version. If it's not we can short circuit and just return False now
jpayne@69 450 # instead of doing extra unneeded work.
jpayne@69 451 if not prospective < spec:
jpayne@69 452 return False
jpayne@69 453
jpayne@69 454 # This special case is here so that, unless the specifier itself
jpayne@69 455 # includes is a pre-release version, that we do not accept pre-release
jpayne@69 456 # versions for the version mentioned in the specifier (e.g. <3.1 should
jpayne@69 457 # not match 3.1.dev0, but should match 3.0.dev0).
jpayne@69 458 if not spec.is_prerelease and prospective.is_prerelease:
jpayne@69 459 if Version(prospective.base_version) == Version(spec.base_version):
jpayne@69 460 return False
jpayne@69 461
jpayne@69 462 # If we've gotten to here, it means that prospective version is both
jpayne@69 463 # less than the spec version *and* it's not a pre-release of the same
jpayne@69 464 # version in the spec.
jpayne@69 465 return True
jpayne@69 466
jpayne@69 467 def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:
jpayne@69 468 # Convert our spec to a Version instance, since we'll want to work with
jpayne@69 469 # it as a version.
jpayne@69 470 spec = Version(spec_str)
jpayne@69 471
jpayne@69 472 # Check to see if the prospective version is greater than the spec
jpayne@69 473 # version. If it's not we can short circuit and just return False now
jpayne@69 474 # instead of doing extra unneeded work.
jpayne@69 475 if not prospective > spec:
jpayne@69 476 return False
jpayne@69 477
jpayne@69 478 # This special case is here so that, unless the specifier itself
jpayne@69 479 # includes is a post-release version, that we do not accept
jpayne@69 480 # post-release versions for the version mentioned in the specifier
jpayne@69 481 # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
jpayne@69 482 if not spec.is_postrelease and prospective.is_postrelease:
jpayne@69 483 if Version(prospective.base_version) == Version(spec.base_version):
jpayne@69 484 return False
jpayne@69 485
jpayne@69 486 # Ensure that we do not allow a local version of the version mentioned
jpayne@69 487 # in the specifier, which is technically greater than, to match.
jpayne@69 488 if prospective.local is not None:
jpayne@69 489 if Version(prospective.base_version) == Version(spec.base_version):
jpayne@69 490 return False
jpayne@69 491
jpayne@69 492 # If we've gotten to here, it means that prospective version is both
jpayne@69 493 # greater than the spec version *and* it's not a pre-release of the
jpayne@69 494 # same version in the spec.
jpayne@69 495 return True
jpayne@69 496
jpayne@69 497 def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
jpayne@69 498 return str(prospective).lower() == str(spec).lower()
jpayne@69 499
jpayne@69 500 def __contains__(self, item: str | Version) -> bool:
jpayne@69 501 """Return whether or not the item is contained in this specifier.
jpayne@69 502
jpayne@69 503 :param item: The item to check for.
jpayne@69 504
jpayne@69 505 This is used for the ``in`` operator and behaves the same as
jpayne@69 506 :meth:`contains` with no ``prereleases`` argument passed.
jpayne@69 507
jpayne@69 508 >>> "1.2.3" in Specifier(">=1.2.3")
jpayne@69 509 True
jpayne@69 510 >>> Version("1.2.3") in Specifier(">=1.2.3")
jpayne@69 511 True
jpayne@69 512 >>> "1.0.0" in Specifier(">=1.2.3")
jpayne@69 513 False
jpayne@69 514 >>> "1.3.0a1" in Specifier(">=1.2.3")
jpayne@69 515 False
jpayne@69 516 >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
jpayne@69 517 True
jpayne@69 518 """
jpayne@69 519 return self.contains(item)
jpayne@69 520
jpayne@69 521 def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool:
jpayne@69 522 """Return whether or not the item is contained in this specifier.
jpayne@69 523
jpayne@69 524 :param item:
jpayne@69 525 The item to check for, which can be a version string or a
jpayne@69 526 :class:`Version` instance.
jpayne@69 527 :param prereleases:
jpayne@69 528 Whether or not to match prereleases with this Specifier. If set to
jpayne@69 529 ``None`` (the default), it uses :attr:`prereleases` to determine
jpayne@69 530 whether or not prereleases are allowed.
jpayne@69 531
jpayne@69 532 >>> Specifier(">=1.2.3").contains("1.2.3")
jpayne@69 533 True
jpayne@69 534 >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
jpayne@69 535 True
jpayne@69 536 >>> Specifier(">=1.2.3").contains("1.0.0")
jpayne@69 537 False
jpayne@69 538 >>> Specifier(">=1.2.3").contains("1.3.0a1")
jpayne@69 539 False
jpayne@69 540 >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1")
jpayne@69 541 True
jpayne@69 542 >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True)
jpayne@69 543 True
jpayne@69 544 """
jpayne@69 545
jpayne@69 546 # Determine if prereleases are to be allowed or not.
jpayne@69 547 if prereleases is None:
jpayne@69 548 prereleases = self.prereleases
jpayne@69 549
jpayne@69 550 # Normalize item to a Version, this allows us to have a shortcut for
jpayne@69 551 # "2.0" in Specifier(">=2")
jpayne@69 552 normalized_item = _coerce_version(item)
jpayne@69 553
jpayne@69 554 # Determine if we should be supporting prereleases in this specifier
jpayne@69 555 # or not, if we do not support prereleases than we can short circuit
jpayne@69 556 # logic if this version is a prereleases.
jpayne@69 557 if normalized_item.is_prerelease and not prereleases:
jpayne@69 558 return False
jpayne@69 559
jpayne@69 560 # Actually do the comparison to determine if this item is contained
jpayne@69 561 # within this Specifier or not.
jpayne@69 562 operator_callable: CallableOperator = self._get_operator(self.operator)
jpayne@69 563 return operator_callable(normalized_item, self.version)
jpayne@69 564
jpayne@69 565 def filter(
jpayne@69 566 self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
jpayne@69 567 ) -> Iterator[UnparsedVersionVar]:
jpayne@69 568 """Filter items in the given iterable, that match the specifier.
jpayne@69 569
jpayne@69 570 :param iterable:
jpayne@69 571 An iterable that can contain version strings and :class:`Version` instances.
jpayne@69 572 The items in the iterable will be filtered according to the specifier.
jpayne@69 573 :param prereleases:
jpayne@69 574 Whether or not to allow prereleases in the returned iterator. If set to
jpayne@69 575 ``None`` (the default), it will be intelligently decide whether to allow
jpayne@69 576 prereleases or not (based on the :attr:`prereleases` attribute, and
jpayne@69 577 whether the only versions matching are prereleases).
jpayne@69 578
jpayne@69 579 This method is smarter than just ``filter(Specifier().contains, [...])``
jpayne@69 580 because it implements the rule from :pep:`440` that a prerelease item
jpayne@69 581 SHOULD be accepted if no other versions match the given specifier.
jpayne@69 582
jpayne@69 583 >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
jpayne@69 584 ['1.3']
jpayne@69 585 >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
jpayne@69 586 ['1.2.3', '1.3', <Version('1.4')>]
jpayne@69 587 >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
jpayne@69 588 ['1.5a1']
jpayne@69 589 >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
jpayne@69 590 ['1.3', '1.5a1']
jpayne@69 591 >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
jpayne@69 592 ['1.3', '1.5a1']
jpayne@69 593 """
jpayne@69 594
jpayne@69 595 yielded = False
jpayne@69 596 found_prereleases = []
jpayne@69 597
jpayne@69 598 kw = {"prereleases": prereleases if prereleases is not None else True}
jpayne@69 599
jpayne@69 600 # Attempt to iterate over all the values in the iterable and if any of
jpayne@69 601 # them match, yield them.
jpayne@69 602 for version in iterable:
jpayne@69 603 parsed_version = _coerce_version(version)
jpayne@69 604
jpayne@69 605 if self.contains(parsed_version, **kw):
jpayne@69 606 # If our version is a prerelease, and we were not set to allow
jpayne@69 607 # prereleases, then we'll store it for later in case nothing
jpayne@69 608 # else matches this specifier.
jpayne@69 609 if parsed_version.is_prerelease and not (
jpayne@69 610 prereleases or self.prereleases
jpayne@69 611 ):
jpayne@69 612 found_prereleases.append(version)
jpayne@69 613 # Either this is not a prerelease, or we should have been
jpayne@69 614 # accepting prereleases from the beginning.
jpayne@69 615 else:
jpayne@69 616 yielded = True
jpayne@69 617 yield version
jpayne@69 618
jpayne@69 619 # Now that we've iterated over everything, determine if we've yielded
jpayne@69 620 # any values, and if we have not and we have any prereleases stored up
jpayne@69 621 # then we will go ahead and yield the prereleases.
jpayne@69 622 if not yielded and found_prereleases:
jpayne@69 623 for version in found_prereleases:
jpayne@69 624 yield version
jpayne@69 625
jpayne@69 626
jpayne@69 627 _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")
jpayne@69 628
jpayne@69 629
jpayne@69 630 def _version_split(version: str) -> list[str]:
jpayne@69 631 """Split version into components.
jpayne@69 632
jpayne@69 633 The split components are intended for version comparison. The logic does
jpayne@69 634 not attempt to retain the original version string, so joining the
jpayne@69 635 components back with :func:`_version_join` may not produce the original
jpayne@69 636 version string.
jpayne@69 637 """
jpayne@69 638 result: list[str] = []
jpayne@69 639
jpayne@69 640 epoch, _, rest = version.rpartition("!")
jpayne@69 641 result.append(epoch or "0")
jpayne@69 642
jpayne@69 643 for item in rest.split("."):
jpayne@69 644 match = _prefix_regex.search(item)
jpayne@69 645 if match:
jpayne@69 646 result.extend(match.groups())
jpayne@69 647 else:
jpayne@69 648 result.append(item)
jpayne@69 649 return result
jpayne@69 650
jpayne@69 651
jpayne@69 652 def _version_join(components: list[str]) -> str:
jpayne@69 653 """Join split version components into a version string.
jpayne@69 654
jpayne@69 655 This function assumes the input came from :func:`_version_split`, where the
jpayne@69 656 first component must be the epoch (either empty or numeric), and all other
jpayne@69 657 components numeric.
jpayne@69 658 """
jpayne@69 659 epoch, *rest = components
jpayne@69 660 return f"{epoch}!{'.'.join(rest)}"
jpayne@69 661
jpayne@69 662
jpayne@69 663 def _is_not_suffix(segment: str) -> bool:
jpayne@69 664 return not any(
jpayne@69 665 segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
jpayne@69 666 )
jpayne@69 667
jpayne@69 668
jpayne@69 669 def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]:
jpayne@69 670 left_split, right_split = [], []
jpayne@69 671
jpayne@69 672 # Get the release segment of our versions
jpayne@69 673 left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
jpayne@69 674 right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
jpayne@69 675
jpayne@69 676 # Get the rest of our versions
jpayne@69 677 left_split.append(left[len(left_split[0]) :])
jpayne@69 678 right_split.append(right[len(right_split[0]) :])
jpayne@69 679
jpayne@69 680 # Insert our padding
jpayne@69 681 left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
jpayne@69 682 right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
jpayne@69 683
jpayne@69 684 return (
jpayne@69 685 list(itertools.chain.from_iterable(left_split)),
jpayne@69 686 list(itertools.chain.from_iterable(right_split)),
jpayne@69 687 )
jpayne@69 688
jpayne@69 689
jpayne@69 690 class SpecifierSet(BaseSpecifier):
jpayne@69 691 """This class abstracts handling of a set of version specifiers.
jpayne@69 692
jpayne@69 693 It can be passed a single specifier (``>=3.0``), a comma-separated list of
jpayne@69 694 specifiers (``>=3.0,!=3.1``), or no specifier at all.
jpayne@69 695 """
jpayne@69 696
jpayne@69 697 def __init__(
jpayne@69 698 self,
jpayne@69 699 specifiers: str | Iterable[Specifier] = "",
jpayne@69 700 prereleases: bool | None = None,
jpayne@69 701 ) -> None:
jpayne@69 702 """Initialize a SpecifierSet instance.
jpayne@69 703
jpayne@69 704 :param specifiers:
jpayne@69 705 The string representation of a specifier or a comma-separated list of
jpayne@69 706 specifiers which will be parsed and normalized before use.
jpayne@69 707 May also be an iterable of ``Specifier`` instances, which will be used
jpayne@69 708 as is.
jpayne@69 709 :param prereleases:
jpayne@69 710 This tells the SpecifierSet if it should accept prerelease versions if
jpayne@69 711 applicable or not. The default of ``None`` will autodetect it from the
jpayne@69 712 given specifiers.
jpayne@69 713
jpayne@69 714 :raises InvalidSpecifier:
jpayne@69 715 If the given ``specifiers`` are not parseable than this exception will be
jpayne@69 716 raised.
jpayne@69 717 """
jpayne@69 718
jpayne@69 719 if isinstance(specifiers, str):
jpayne@69 720 # Split on `,` to break each individual specifier into its own item, and
jpayne@69 721 # strip each item to remove leading/trailing whitespace.
jpayne@69 722 split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
jpayne@69 723
jpayne@69 724 # Make each individual specifier a Specifier and save in a frozen set
jpayne@69 725 # for later.
jpayne@69 726 self._specs = frozenset(map(Specifier, split_specifiers))
jpayne@69 727 else:
jpayne@69 728 # Save the supplied specifiers in a frozen set.
jpayne@69 729 self._specs = frozenset(specifiers)
jpayne@69 730
jpayne@69 731 # Store our prereleases value so we can use it later to determine if
jpayne@69 732 # we accept prereleases or not.
jpayne@69 733 self._prereleases = prereleases
jpayne@69 734
jpayne@69 735 @property
jpayne@69 736 def prereleases(self) -> bool | None:
jpayne@69 737 # If we have been given an explicit prerelease modifier, then we'll
jpayne@69 738 # pass that through here.
jpayne@69 739 if self._prereleases is not None:
jpayne@69 740 return self._prereleases
jpayne@69 741
jpayne@69 742 # If we don't have any specifiers, and we don't have a forced value,
jpayne@69 743 # then we'll just return None since we don't know if this should have
jpayne@69 744 # pre-releases or not.
jpayne@69 745 if not self._specs:
jpayne@69 746 return None
jpayne@69 747
jpayne@69 748 # Otherwise we'll see if any of the given specifiers accept
jpayne@69 749 # prereleases, if any of them do we'll return True, otherwise False.
jpayne@69 750 return any(s.prereleases for s in self._specs)
jpayne@69 751
jpayne@69 752 @prereleases.setter
jpayne@69 753 def prereleases(self, value: bool) -> None:
jpayne@69 754 self._prereleases = value
jpayne@69 755
jpayne@69 756 def __repr__(self) -> str:
jpayne@69 757 """A representation of the specifier set that shows all internal state.
jpayne@69 758
jpayne@69 759 Note that the ordering of the individual specifiers within the set may not
jpayne@69 760 match the input string.
jpayne@69 761
jpayne@69 762 >>> SpecifierSet('>=1.0.0,!=2.0.0')
jpayne@69 763 <SpecifierSet('!=2.0.0,>=1.0.0')>
jpayne@69 764 >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
jpayne@69 765 <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=False)>
jpayne@69 766 >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
jpayne@69 767 <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=True)>
jpayne@69 768 """
jpayne@69 769 pre = (
jpayne@69 770 f", prereleases={self.prereleases!r}"
jpayne@69 771 if self._prereleases is not None
jpayne@69 772 else ""
jpayne@69 773 )
jpayne@69 774
jpayne@69 775 return f"<SpecifierSet({str(self)!r}{pre})>"
jpayne@69 776
jpayne@69 777 def __str__(self) -> str:
jpayne@69 778 """A string representation of the specifier set that can be round-tripped.
jpayne@69 779
jpayne@69 780 Note that the ordering of the individual specifiers within the set may not
jpayne@69 781 match the input string.
jpayne@69 782
jpayne@69 783 >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
jpayne@69 784 '!=1.0.1,>=1.0.0'
jpayne@69 785 >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
jpayne@69 786 '!=1.0.1,>=1.0.0'
jpayne@69 787 """
jpayne@69 788 return ",".join(sorted(str(s) for s in self._specs))
jpayne@69 789
jpayne@69 790 def __hash__(self) -> int:
jpayne@69 791 return hash(self._specs)
jpayne@69 792
jpayne@69 793 def __and__(self, other: SpecifierSet | str) -> SpecifierSet:
jpayne@69 794 """Return a SpecifierSet which is a combination of the two sets.
jpayne@69 795
jpayne@69 796 :param other: The other object to combine with.
jpayne@69 797
jpayne@69 798 >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
jpayne@69 799 <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>
jpayne@69 800 >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
jpayne@69 801 <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')>
jpayne@69 802 """
jpayne@69 803 if isinstance(other, str):
jpayne@69 804 other = SpecifierSet(other)
jpayne@69 805 elif not isinstance(other, SpecifierSet):
jpayne@69 806 return NotImplemented
jpayne@69 807
jpayne@69 808 specifier = SpecifierSet()
jpayne@69 809 specifier._specs = frozenset(self._specs | other._specs)
jpayne@69 810
jpayne@69 811 if self._prereleases is None and other._prereleases is not None:
jpayne@69 812 specifier._prereleases = other._prereleases
jpayne@69 813 elif self._prereleases is not None and other._prereleases is None:
jpayne@69 814 specifier._prereleases = self._prereleases
jpayne@69 815 elif self._prereleases == other._prereleases:
jpayne@69 816 specifier._prereleases = self._prereleases
jpayne@69 817 else:
jpayne@69 818 raise ValueError(
jpayne@69 819 "Cannot combine SpecifierSets with True and False prerelease "
jpayne@69 820 "overrides."
jpayne@69 821 )
jpayne@69 822
jpayne@69 823 return specifier
jpayne@69 824
jpayne@69 825 def __eq__(self, other: object) -> bool:
jpayne@69 826 """Whether or not the two SpecifierSet-like objects are equal.
jpayne@69 827
jpayne@69 828 :param other: The other object to check against.
jpayne@69 829
jpayne@69 830 The value of :attr:`prereleases` is ignored.
jpayne@69 831
jpayne@69 832 >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
jpayne@69 833 True
jpayne@69 834 >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
jpayne@69 835 ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
jpayne@69 836 True
jpayne@69 837 >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
jpayne@69 838 True
jpayne@69 839 >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
jpayne@69 840 False
jpayne@69 841 >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
jpayne@69 842 False
jpayne@69 843 """
jpayne@69 844 if isinstance(other, (str, Specifier)):
jpayne@69 845 other = SpecifierSet(str(other))
jpayne@69 846 elif not isinstance(other, SpecifierSet):
jpayne@69 847 return NotImplemented
jpayne@69 848
jpayne@69 849 return self._specs == other._specs
jpayne@69 850
jpayne@69 851 def __len__(self) -> int:
jpayne@69 852 """Returns the number of specifiers in this specifier set."""
jpayne@69 853 return len(self._specs)
jpayne@69 854
jpayne@69 855 def __iter__(self) -> Iterator[Specifier]:
jpayne@69 856 """
jpayne@69 857 Returns an iterator over all the underlying :class:`Specifier` instances
jpayne@69 858 in this specifier set.
jpayne@69 859
jpayne@69 860 >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
jpayne@69 861 [<Specifier('!=1.0.1')>, <Specifier('>=1.0.0')>]
jpayne@69 862 """
jpayne@69 863 return iter(self._specs)
jpayne@69 864
jpayne@69 865 def __contains__(self, item: UnparsedVersion) -> bool:
jpayne@69 866 """Return whether or not the item is contained in this specifier.
jpayne@69 867
jpayne@69 868 :param item: The item to check for.
jpayne@69 869
jpayne@69 870 This is used for the ``in`` operator and behaves the same as
jpayne@69 871 :meth:`contains` with no ``prereleases`` argument passed.
jpayne@69 872
jpayne@69 873 >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
jpayne@69 874 True
jpayne@69 875 >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
jpayne@69 876 True
jpayne@69 877 >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
jpayne@69 878 False
jpayne@69 879 >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
jpayne@69 880 False
jpayne@69 881 >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
jpayne@69 882 True
jpayne@69 883 """
jpayne@69 884 return self.contains(item)
jpayne@69 885
jpayne@69 886 def contains(
jpayne@69 887 self,
jpayne@69 888 item: UnparsedVersion,
jpayne@69 889 prereleases: bool | None = None,
jpayne@69 890 installed: bool | None = None,
jpayne@69 891 ) -> bool:
jpayne@69 892 """Return whether or not the item is contained in this SpecifierSet.
jpayne@69 893
jpayne@69 894 :param item:
jpayne@69 895 The item to check for, which can be a version string or a
jpayne@69 896 :class:`Version` instance.
jpayne@69 897 :param prereleases:
jpayne@69 898 Whether or not to match prereleases with this SpecifierSet. If set to
jpayne@69 899 ``None`` (the default), it uses :attr:`prereleases` to determine
jpayne@69 900 whether or not prereleases are allowed.
jpayne@69 901
jpayne@69 902 >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
jpayne@69 903 True
jpayne@69 904 >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
jpayne@69 905 True
jpayne@69 906 >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
jpayne@69 907 False
jpayne@69 908 >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
jpayne@69 909 False
jpayne@69 910 >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1")
jpayne@69 911 True
jpayne@69 912 >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
jpayne@69 913 True
jpayne@69 914 """
jpayne@69 915 # Ensure that our item is a Version instance.
jpayne@69 916 if not isinstance(item, Version):
jpayne@69 917 item = Version(item)
jpayne@69 918
jpayne@69 919 # Determine if we're forcing a prerelease or not, if we're not forcing
jpayne@69 920 # one for this particular filter call, then we'll use whatever the
jpayne@69 921 # SpecifierSet thinks for whether or not we should support prereleases.
jpayne@69 922 if prereleases is None:
jpayne@69 923 prereleases = self.prereleases
jpayne@69 924
jpayne@69 925 # We can determine if we're going to allow pre-releases by looking to
jpayne@69 926 # see if any of the underlying items supports them. If none of them do
jpayne@69 927 # and this item is a pre-release then we do not allow it and we can
jpayne@69 928 # short circuit that here.
jpayne@69 929 # Note: This means that 1.0.dev1 would not be contained in something
jpayne@69 930 # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
jpayne@69 931 if not prereleases and item.is_prerelease:
jpayne@69 932 return False
jpayne@69 933
jpayne@69 934 if installed and item.is_prerelease:
jpayne@69 935 item = Version(item.base_version)
jpayne@69 936
jpayne@69 937 # We simply dispatch to the underlying specs here to make sure that the
jpayne@69 938 # given version is contained within all of them.
jpayne@69 939 # Note: This use of all() here means that an empty set of specifiers
jpayne@69 940 # will always return True, this is an explicit design decision.
jpayne@69 941 return all(s.contains(item, prereleases=prereleases) for s in self._specs)
jpayne@69 942
jpayne@69 943 def filter(
jpayne@69 944 self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None
jpayne@69 945 ) -> Iterator[UnparsedVersionVar]:
jpayne@69 946 """Filter items in the given iterable, that match the specifiers in this set.
jpayne@69 947
jpayne@69 948 :param iterable:
jpayne@69 949 An iterable that can contain version strings and :class:`Version` instances.
jpayne@69 950 The items in the iterable will be filtered according to the specifier.
jpayne@69 951 :param prereleases:
jpayne@69 952 Whether or not to allow prereleases in the returned iterator. If set to
jpayne@69 953 ``None`` (the default), it will be intelligently decide whether to allow
jpayne@69 954 prereleases or not (based on the :attr:`prereleases` attribute, and
jpayne@69 955 whether the only versions matching are prereleases).
jpayne@69 956
jpayne@69 957 This method is smarter than just ``filter(SpecifierSet(...).contains, [...])``
jpayne@69 958 because it implements the rule from :pep:`440` that a prerelease item
jpayne@69 959 SHOULD be accepted if no other versions match the given specifier.
jpayne@69 960
jpayne@69 961 >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
jpayne@69 962 ['1.3']
jpayne@69 963 >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
jpayne@69 964 ['1.3', <Version('1.4')>]
jpayne@69 965 >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
jpayne@69 966 []
jpayne@69 967 >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
jpayne@69 968 ['1.3', '1.5a1']
jpayne@69 969 >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
jpayne@69 970 ['1.3', '1.5a1']
jpayne@69 971
jpayne@69 972 An "empty" SpecifierSet will filter items based on the presence of prerelease
jpayne@69 973 versions in the set.
jpayne@69 974
jpayne@69 975 >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
jpayne@69 976 ['1.3']
jpayne@69 977 >>> list(SpecifierSet("").filter(["1.5a1"]))
jpayne@69 978 ['1.5a1']
jpayne@69 979 >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
jpayne@69 980 ['1.3', '1.5a1']
jpayne@69 981 >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
jpayne@69 982 ['1.3', '1.5a1']
jpayne@69 983 """
jpayne@69 984 # Determine if we're forcing a prerelease or not, if we're not forcing
jpayne@69 985 # one for this particular filter call, then we'll use whatever the
jpayne@69 986 # SpecifierSet thinks for whether or not we should support prereleases.
jpayne@69 987 if prereleases is None:
jpayne@69 988 prereleases = self.prereleases
jpayne@69 989
jpayne@69 990 # If we have any specifiers, then we want to wrap our iterable in the
jpayne@69 991 # filter method for each one, this will act as a logical AND amongst
jpayne@69 992 # each specifier.
jpayne@69 993 if self._specs:
jpayne@69 994 for spec in self._specs:
jpayne@69 995 iterable = spec.filter(iterable, prereleases=bool(prereleases))
jpayne@69 996 return iter(iterable)
jpayne@69 997 # If we do not have any specifiers, then we need to have a rough filter
jpayne@69 998 # which will filter out any pre-releases, unless there are no final
jpayne@69 999 # releases.
jpayne@69 1000 else:
jpayne@69 1001 filtered: list[UnparsedVersionVar] = []
jpayne@69 1002 found_prereleases: list[UnparsedVersionVar] = []
jpayne@69 1003
jpayne@69 1004 for item in iterable:
jpayne@69 1005 parsed_version = _coerce_version(item)
jpayne@69 1006
jpayne@69 1007 # Store any item which is a pre-release for later unless we've
jpayne@69 1008 # already found a final version or we are accepting prereleases
jpayne@69 1009 if parsed_version.is_prerelease and not prereleases:
jpayne@69 1010 if not filtered:
jpayne@69 1011 found_prereleases.append(item)
jpayne@69 1012 else:
jpayne@69 1013 filtered.append(item)
jpayne@69 1014
jpayne@69 1015 # If we've found no items except for pre-releases, then we'll go
jpayne@69 1016 # ahead and use the pre-releases
jpayne@69 1017 if not filtered and found_prereleases and prereleases is None:
jpayne@69 1018 return iter(found_prereleases)
jpayne@69 1019
jpayne@69 1020 return iter(filtered)