specifiers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import abc
  5. import functools
  6. import itertools
  7. import re
  8. import warnings
  9. from typing import (
  10. Callable,
  11. Dict,
  12. Iterable,
  13. Iterator,
  14. List,
  15. Optional,
  16. Pattern,
  17. Set,
  18. Tuple,
  19. TypeVar,
  20. Union,
  21. )
  22. from .utils import canonicalize_version
  23. from .version import LegacyVersion, Version, parse
  24. ParsedVersion = Union[Version, LegacyVersion]
  25. UnparsedVersion = Union[Version, LegacyVersion, str]
  26. VersionTypeVar = TypeVar("VersionTypeVar", bound=UnparsedVersion)
  27. CallableOperator = Callable[[ParsedVersion, str], bool]
  28. class InvalidSpecifier(ValueError):
  29. """
  30. An invalid specifier was found, users should refer to PEP 440.
  31. """
  32. class BaseSpecifier(metaclass=abc.ABCMeta):
  33. @abc.abstractmethod
  34. def __str__(self) -> str:
  35. """
  36. Returns the str representation of this Specifier like object. This
  37. should be representative of the Specifier itself.
  38. """
  39. @abc.abstractmethod
  40. def __hash__(self) -> int:
  41. """
  42. Returns a hash value for this Specifier like object.
  43. """
  44. @abc.abstractmethod
  45. def __eq__(self, other: object) -> bool:
  46. """
  47. Returns a boolean representing whether or not the two Specifier like
  48. objects are equal.
  49. """
  50. @abc.abstractproperty
  51. def prereleases(self) -> Optional[bool]:
  52. """
  53. Returns whether or not pre-releases as a whole are allowed by this
  54. specifier.
  55. """
  56. @prereleases.setter
  57. def prereleases(self, value: bool) -> None:
  58. """
  59. Sets whether or not pre-releases as a whole are allowed by this
  60. specifier.
  61. """
  62. @abc.abstractmethod
  63. def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
  64. """
  65. Determines if the given item is contained within this specifier.
  66. """
  67. @abc.abstractmethod
  68. def filter(
  69. self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None
  70. ) -> Iterable[VersionTypeVar]:
  71. """
  72. Takes an iterable of items and filters them so that only items which
  73. are contained within this specifier are allowed in it.
  74. """
  75. class _IndividualSpecifier(BaseSpecifier):
  76. _operators: Dict[str, str] = {}
  77. _regex: Pattern[str]
  78. def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
  79. match = self._regex.search(spec)
  80. if not match:
  81. raise InvalidSpecifier(f"Invalid specifier: '{spec}'")
  82. self._spec: Tuple[str, str] = (
  83. match.group("operator").strip(),
  84. match.group("version").strip(),
  85. )
  86. # Store whether or not this Specifier should accept prereleases
  87. self._prereleases = prereleases
  88. def __repr__(self) -> str:
  89. pre = (
  90. f", prereleases={self.prereleases!r}"
  91. if self._prereleases is not None
  92. else ""
  93. )
  94. return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
  95. def __str__(self) -> str:
  96. return "{}{}".format(*self._spec)
  97. @property
  98. def _canonical_spec(self) -> Tuple[str, str]:
  99. return self._spec[0], canonicalize_version(self._spec[1])
  100. def __hash__(self) -> int:
  101. return hash(self._canonical_spec)
  102. def __eq__(self, other: object) -> bool:
  103. if isinstance(other, str):
  104. try:
  105. other = self.__class__(str(other))
  106. except InvalidSpecifier:
  107. return NotImplemented
  108. elif not isinstance(other, self.__class__):
  109. return NotImplemented
  110. return self._canonical_spec == other._canonical_spec
  111. def _get_operator(self, op: str) -> CallableOperator:
  112. operator_callable: CallableOperator = getattr(
  113. self, f"_compare_{self._operators[op]}"
  114. )
  115. return operator_callable
  116. def _coerce_version(self, version: UnparsedVersion) -> ParsedVersion:
  117. if not isinstance(version, (LegacyVersion, Version)):
  118. version = parse(version)
  119. return version
  120. @property
  121. def operator(self) -> str:
  122. return self._spec[0]
  123. @property
  124. def version(self) -> str:
  125. return self._spec[1]
  126. @property
  127. def prereleases(self) -> Optional[bool]:
  128. return self._prereleases
  129. @prereleases.setter
  130. def prereleases(self, value: bool) -> None:
  131. self._prereleases = value
  132. def __contains__(self, item: str) -> bool:
  133. return self.contains(item)
  134. def contains(
  135. self, item: UnparsedVersion, prereleases: Optional[bool] = None
  136. ) -> bool:
  137. # Determine if prereleases are to be allowed or not.
  138. if prereleases is None:
  139. prereleases = self.prereleases
  140. # Normalize item to a Version or LegacyVersion, this allows us to have
  141. # a shortcut for ``"2.0" in Specifier(">=2")
  142. normalized_item = self._coerce_version(item)
  143. # Determine if we should be supporting prereleases in this specifier
  144. # or not, if we do not support prereleases than we can short circuit
  145. # logic if this version is a prereleases.
  146. if normalized_item.is_prerelease and not prereleases:
  147. return False
  148. # Actually do the comparison to determine if this item is contained
  149. # within this Specifier or not.
  150. operator_callable: CallableOperator = self._get_operator(self.operator)
  151. return operator_callable(normalized_item, self.version)
  152. def filter(
  153. self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None
  154. ) -> Iterable[VersionTypeVar]:
  155. yielded = False
  156. found_prereleases = []
  157. kw = {"prereleases": prereleases if prereleases is not None else True}
  158. # Attempt to iterate over all the values in the iterable and if any of
  159. # them match, yield them.
  160. for version in iterable:
  161. parsed_version = self._coerce_version(version)
  162. if self.contains(parsed_version, **kw):
  163. # If our version is a prerelease, and we were not set to allow
  164. # prereleases, then we'll store it for later in case nothing
  165. # else matches this specifier.
  166. if parsed_version.is_prerelease and not (
  167. prereleases or self.prereleases
  168. ):
  169. found_prereleases.append(version)
  170. # Either this is not a prerelease, or we should have been
  171. # accepting prereleases from the beginning.
  172. else:
  173. yielded = True
  174. yield version
  175. # Now that we've iterated over everything, determine if we've yielded
  176. # any values, and if we have not and we have any prereleases stored up
  177. # then we will go ahead and yield the prereleases.
  178. if not yielded and found_prereleases:
  179. for version in found_prereleases:
  180. yield version
  181. class LegacySpecifier(_IndividualSpecifier):
  182. _regex_str = r"""
  183. (?P<operator>(==|!=|<=|>=|<|>))
  184. \s*
  185. (?P<version>
  186. [^,;\s)]* # Since this is a "legacy" specifier, and the version
  187. # string can be just about anything, we match everything
  188. # except for whitespace, a semi-colon for marker support,
  189. # a closing paren since versions can be enclosed in
  190. # them, and a comma since it's a version separator.
  191. )
  192. """
  193. _regex = re.compile(r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)
  194. _operators = {
  195. "==": "equal",
  196. "!=": "not_equal",
  197. "<=": "less_than_equal",
  198. ">=": "greater_than_equal",
  199. "<": "less_than",
  200. ">": "greater_than",
  201. }
  202. def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
  203. super().__init__(spec, prereleases)
  204. warnings.warn(
  205. "Creating a LegacyVersion has been deprecated and will be "
  206. "removed in the next major release",
  207. DeprecationWarning,
  208. )
  209. def _coerce_version(self, version: UnparsedVersion) -> LegacyVersion:
  210. if not isinstance(version, LegacyVersion):
  211. version = LegacyVersion(str(version))
  212. return version
  213. def _compare_equal(self, prospective: LegacyVersion, spec: str) -> bool:
  214. return prospective == self._coerce_version(spec)
  215. def _compare_not_equal(self, prospective: LegacyVersion, spec: str) -> bool:
  216. return prospective != self._coerce_version(spec)
  217. def _compare_less_than_equal(self, prospective: LegacyVersion, spec: str) -> bool:
  218. return prospective <= self._coerce_version(spec)
  219. def _compare_greater_than_equal(
  220. self, prospective: LegacyVersion, spec: str
  221. ) -> bool:
  222. return prospective >= self._coerce_version(spec)
  223. def _compare_less_than(self, prospective: LegacyVersion, spec: str) -> bool:
  224. return prospective < self._coerce_version(spec)
  225. def _compare_greater_than(self, prospective: LegacyVersion, spec: str) -> bool:
  226. return prospective > self._coerce_version(spec)
  227. def _require_version_compare(
  228. fn: Callable[["Specifier", ParsedVersion, str], bool]
  229. ) -> Callable[["Specifier", ParsedVersion, str], bool]:
  230. @functools.wraps(fn)
  231. def wrapped(self: "Specifier", prospective: ParsedVersion, spec: str) -> bool:
  232. if not isinstance(prospective, Version):
  233. return False
  234. return fn(self, prospective, spec)
  235. return wrapped
  236. class Specifier(_IndividualSpecifier):
  237. _regex_str = r"""
  238. (?P<operator>(~=|==|!=|<=|>=|<|>|===))
  239. (?P<version>
  240. (?:
  241. # The identity operators allow for an escape hatch that will
  242. # do an exact string match of the version you wish to install.
  243. # This will not be parsed by PEP 440 and we cannot determine
  244. # any semantic meaning from it. This operator is discouraged
  245. # but included entirely as an escape hatch.
  246. (?<====) # Only match for the identity operator
  247. \s*
  248. [^\s]* # We just match everything, except for whitespace
  249. # since we are only testing for strict identity.
  250. )
  251. |
  252. (?:
  253. # The (non)equality operators allow for wild card and local
  254. # versions to be specified so we have to define these two
  255. # operators separately to enable that.
  256. (?<===|!=) # Only match for equals and not equals
  257. \s*
  258. v?
  259. (?:[0-9]+!)? # epoch
  260. [0-9]+(?:\.[0-9]+)* # release
  261. (?: # pre release
  262. [-_\.]?
  263. (a|b|c|rc|alpha|beta|pre|preview)
  264. [-_\.]?
  265. [0-9]*
  266. )?
  267. (?: # post release
  268. (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
  269. )?
  270. # You cannot use a wild card and a dev or local version
  271. # together so group them with a | and make them optional.
  272. (?:
  273. (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
  274. (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
  275. |
  276. \.\* # Wild card syntax of .*
  277. )?
  278. )
  279. |
  280. (?:
  281. # The compatible operator requires at least two digits in the
  282. # release segment.
  283. (?<=~=) # Only match for the compatible operator
  284. \s*
  285. v?
  286. (?:[0-9]+!)? # epoch
  287. [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *)
  288. (?: # pre release
  289. [-_\.]?
  290. (a|b|c|rc|alpha|beta|pre|preview)
  291. [-_\.]?
  292. [0-9]*
  293. )?
  294. (?: # post release
  295. (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
  296. )?
  297. (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
  298. )
  299. |
  300. (?:
  301. # All other operators only allow a sub set of what the
  302. # (non)equality operators do. Specifically they do not allow
  303. # local versions to be specified nor do they allow the prefix
  304. # matching wild cards.
  305. (?<!==|!=|~=) # We have special cases for these
  306. # operators so we want to make sure they
  307. # don't match here.
  308. \s*
  309. v?
  310. (?:[0-9]+!)? # epoch
  311. [0-9]+(?:\.[0-9]+)* # release
  312. (?: # pre release
  313. [-_\.]?
  314. (a|b|c|rc|alpha|beta|pre|preview)
  315. [-_\.]?
  316. [0-9]*
  317. )?
  318. (?: # post release
  319. (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
  320. )?
  321. (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release
  322. )
  323. )
  324. """
  325. _regex = re.compile(r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)
  326. _operators = {
  327. "~=": "compatible",
  328. "==": "equal",
  329. "!=": "not_equal",
  330. "<=": "less_than_equal",
  331. ">=": "greater_than_equal",
  332. "<": "less_than",
  333. ">": "greater_than",
  334. "===": "arbitrary",
  335. }
  336. @_require_version_compare
  337. def _compare_compatible(self, prospective: ParsedVersion, spec: str) -> bool:
  338. # Compatible releases have an equivalent combination of >= and ==. That
  339. # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
  340. # implement this in terms of the other specifiers instead of
  341. # implementing it ourselves. The only thing we need to do is construct
  342. # the other specifiers.
  343. # We want everything but the last item in the version, but we want to
  344. # ignore suffix segments.
  345. prefix = ".".join(
  346. list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
  347. )
  348. # Add the prefix notation to the end of our string
  349. prefix += ".*"
  350. return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
  351. prospective, prefix
  352. )
  353. @_require_version_compare
  354. def _compare_equal(self, prospective: ParsedVersion, spec: str) -> bool:
  355. # We need special logic to handle prefix matching
  356. if spec.endswith(".*"):
  357. # In the case of prefix matching we want to ignore local segment.
  358. prospective = Version(prospective.public)
  359. # Split the spec out by dots, and pretend that there is an implicit
  360. # dot in between a release segment and a pre-release segment.
  361. split_spec = _version_split(spec[:-2]) # Remove the trailing .*
  362. # Split the prospective version out by dots, and pretend that there
  363. # is an implicit dot in between a release segment and a pre-release
  364. # segment.
  365. split_prospective = _version_split(str(prospective))
  366. # Shorten the prospective version to be the same length as the spec
  367. # so that we can determine if the specifier is a prefix of the
  368. # prospective version or not.
  369. shortened_prospective = split_prospective[: len(split_spec)]
  370. # Pad out our two sides with zeros so that they both equal the same
  371. # length.
  372. padded_spec, padded_prospective = _pad_version(
  373. split_spec, shortened_prospective
  374. )
  375. return padded_prospective == padded_spec
  376. else:
  377. # Convert our spec string into a Version
  378. spec_version = Version(spec)
  379. # If the specifier does not have a local segment, then we want to
  380. # act as if the prospective version also does not have a local
  381. # segment.
  382. if not spec_version.local:
  383. prospective = Version(prospective.public)
  384. return prospective == spec_version
  385. @_require_version_compare
  386. def _compare_not_equal(self, prospective: ParsedVersion, spec: str) -> bool:
  387. return not self._compare_equal(prospective, spec)
  388. @_require_version_compare
  389. def _compare_less_than_equal(self, prospective: ParsedVersion, spec: str) -> bool:
  390. # NB: Local version identifiers are NOT permitted in the version
  391. # specifier, so local version labels can be universally removed from
  392. # the prospective version.
  393. return Version(prospective.public) <= Version(spec)
  394. @_require_version_compare
  395. def _compare_greater_than_equal(
  396. self, prospective: ParsedVersion, spec: str
  397. ) -> bool:
  398. # NB: Local version identifiers are NOT permitted in the version
  399. # specifier, so local version labels can be universally removed from
  400. # the prospective version.
  401. return Version(prospective.public) >= Version(spec)
  402. @_require_version_compare
  403. def _compare_less_than(self, prospective: ParsedVersion, spec_str: str) -> bool:
  404. # Convert our spec to a Version instance, since we'll want to work with
  405. # it as a version.
  406. spec = Version(spec_str)
  407. # Check to see if the prospective version is less than the spec
  408. # version. If it's not we can short circuit and just return False now
  409. # instead of doing extra unneeded work.
  410. if not prospective < spec:
  411. return False
  412. # This special case is here so that, unless the specifier itself
  413. # includes is a pre-release version, that we do not accept pre-release
  414. # versions for the version mentioned in the specifier (e.g. <3.1 should
  415. # not match 3.1.dev0, but should match 3.0.dev0).
  416. if not spec.is_prerelease and prospective.is_prerelease:
  417. if Version(prospective.base_version) == Version(spec.base_version):
  418. return False
  419. # If we've gotten to here, it means that prospective version is both
  420. # less than the spec version *and* it's not a pre-release of the same
  421. # version in the spec.
  422. return True
  423. @_require_version_compare
  424. def _compare_greater_than(self, prospective: ParsedVersion, spec_str: str) -> bool:
  425. # Convert our spec to a Version instance, since we'll want to work with
  426. # it as a version.
  427. spec = Version(spec_str)
  428. # Check to see if the prospective version is greater than the spec
  429. # version. If it's not we can short circuit and just return False now
  430. # instead of doing extra unneeded work.
  431. if not prospective > spec:
  432. return False
  433. # This special case is here so that, unless the specifier itself
  434. # includes is a post-release version, that we do not accept
  435. # post-release versions for the version mentioned in the specifier
  436. # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
  437. if not spec.is_postrelease and prospective.is_postrelease:
  438. if Version(prospective.base_version) == Version(spec.base_version):
  439. return False
  440. # Ensure that we do not allow a local version of the version mentioned
  441. # in the specifier, which is technically greater than, to match.
  442. if prospective.local is not None:
  443. if Version(prospective.base_version) == Version(spec.base_version):
  444. return False
  445. # If we've gotten to here, it means that prospective version is both
  446. # greater than the spec version *and* it's not a pre-release of the
  447. # same version in the spec.
  448. return True
  449. def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
  450. return str(prospective).lower() == str(spec).lower()
  451. @property
  452. def prereleases(self) -> bool:
  453. # If there is an explicit prereleases set for this, then we'll just
  454. # blindly use that.
  455. if self._prereleases is not None:
  456. return self._prereleases
  457. # Look at all of our specifiers and determine if they are inclusive
  458. # operators, and if they are if they are including an explicit
  459. # prerelease.
  460. operator, version = self._spec
  461. if operator in ["==", ">=", "<=", "~=", "==="]:
  462. # The == specifier can include a trailing .*, if it does we
  463. # want to remove before parsing.
  464. if operator == "==" and version.endswith(".*"):
  465. version = version[:-2]
  466. # Parse the version, and if it is a pre-release than this
  467. # specifier allows pre-releases.
  468. if parse(version).is_prerelease:
  469. return True
  470. return False
  471. @prereleases.setter
  472. def prereleases(self, value: bool) -> None:
  473. self._prereleases = value
  474. _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")
  475. def _version_split(version: str) -> List[str]:
  476. result: List[str] = []
  477. for item in version.split("."):
  478. match = _prefix_regex.search(item)
  479. if match:
  480. result.extend(match.groups())
  481. else:
  482. result.append(item)
  483. return result
  484. def _is_not_suffix(segment: str) -> bool:
  485. return not any(
  486. segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
  487. )
  488. def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:
  489. left_split, right_split = [], []
  490. # Get the release segment of our versions
  491. left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
  492. right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))
  493. # Get the rest of our versions
  494. left_split.append(left[len(left_split[0]) :])
  495. right_split.append(right[len(right_split[0]) :])
  496. # Insert our padding
  497. left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
  498. right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))
  499. return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))
  500. class SpecifierSet(BaseSpecifier):
  501. def __init__(
  502. self, specifiers: str = "", prereleases: Optional[bool] = None
  503. ) -> None:
  504. # Split on , to break each individual specifier into it's own item, and
  505. # strip each item to remove leading/trailing whitespace.
  506. split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
  507. # Parsed each individual specifier, attempting first to make it a
  508. # Specifier and falling back to a LegacySpecifier.
  509. parsed: Set[_IndividualSpecifier] = set()
  510. for specifier in split_specifiers:
  511. try:
  512. parsed.add(Specifier(specifier))
  513. except InvalidSpecifier:
  514. parsed.add(LegacySpecifier(specifier))
  515. # Turn our parsed specifiers into a frozen set and save them for later.
  516. self._specs = frozenset(parsed)
  517. # Store our prereleases value so we can use it later to determine if
  518. # we accept prereleases or not.
  519. self._prereleases = prereleases
  520. def __repr__(self) -> str:
  521. pre = (
  522. f", prereleases={self.prereleases!r}"
  523. if self._prereleases is not None
  524. else ""
  525. )
  526. return f"<SpecifierSet({str(self)!r}{pre})>"
  527. def __str__(self) -> str:
  528. return ",".join(sorted(str(s) for s in self._specs))
  529. def __hash__(self) -> int:
  530. return hash(self._specs)
  531. def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
  532. if isinstance(other, str):
  533. other = SpecifierSet(other)
  534. elif not isinstance(other, SpecifierSet):
  535. return NotImplemented
  536. specifier = SpecifierSet()
  537. specifier._specs = frozenset(self._specs | other._specs)
  538. if self._prereleases is None and other._prereleases is not None:
  539. specifier._prereleases = other._prereleases
  540. elif self._prereleases is not None and other._prereleases is None:
  541. specifier._prereleases = self._prereleases
  542. elif self._prereleases == other._prereleases:
  543. specifier._prereleases = self._prereleases
  544. else:
  545. raise ValueError(
  546. "Cannot combine SpecifierSets with True and False prerelease "
  547. "overrides."
  548. )
  549. return specifier
  550. def __eq__(self, other: object) -> bool:
  551. if isinstance(other, (str, _IndividualSpecifier)):
  552. other = SpecifierSet(str(other))
  553. elif not isinstance(other, SpecifierSet):
  554. return NotImplemented
  555. return self._specs == other._specs
  556. def __len__(self) -> int:
  557. return len(self._specs)
  558. def __iter__(self) -> Iterator[_IndividualSpecifier]:
  559. return iter(self._specs)
  560. @property
  561. def prereleases(self) -> Optional[bool]:
  562. # If we have been given an explicit prerelease modifier, then we'll
  563. # pass that through here.
  564. if self._prereleases is not None:
  565. return self._prereleases
  566. # If we don't have any specifiers, and we don't have a forced value,
  567. # then we'll just return None since we don't know if this should have
  568. # pre-releases or not.
  569. if not self._specs:
  570. return None
  571. # Otherwise we'll see if any of the given specifiers accept
  572. # prereleases, if any of them do we'll return True, otherwise False.
  573. return any(s.prereleases for s in self._specs)
  574. @prereleases.setter
  575. def prereleases(self, value: bool) -> None:
  576. self._prereleases = value
  577. def __contains__(self, item: UnparsedVersion) -> bool:
  578. return self.contains(item)
  579. def contains(
  580. self, item: UnparsedVersion, prereleases: Optional[bool] = None
  581. ) -> bool:
  582. # Ensure that our item is a Version or LegacyVersion instance.
  583. if not isinstance(item, (LegacyVersion, Version)):
  584. item = parse(item)
  585. # Determine if we're forcing a prerelease or not, if we're not forcing
  586. # one for this particular filter call, then we'll use whatever the
  587. # SpecifierSet thinks for whether or not we should support prereleases.
  588. if prereleases is None:
  589. prereleases = self.prereleases
  590. # We can determine if we're going to allow pre-releases by looking to
  591. # see if any of the underlying items supports them. If none of them do
  592. # and this item is a pre-release then we do not allow it and we can
  593. # short circuit that here.
  594. # Note: This means that 1.0.dev1 would not be contained in something
  595. # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
  596. if not prereleases and item.is_prerelease:
  597. return False
  598. # We simply dispatch to the underlying specs here to make sure that the
  599. # given version is contained within all of them.
  600. # Note: This use of all() here means that an empty set of specifiers
  601. # will always return True, this is an explicit design decision.
  602. return all(s.contains(item, prereleases=prereleases) for s in self._specs)
  603. def filter(
  604. self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None
  605. ) -> Iterable[VersionTypeVar]:
  606. # Determine if we're forcing a prerelease or not, if we're not forcing
  607. # one for this particular filter call, then we'll use whatever the
  608. # SpecifierSet thinks for whether or not we should support prereleases.
  609. if prereleases is None:
  610. prereleases = self.prereleases
  611. # If we have any specifiers, then we want to wrap our iterable in the
  612. # filter method for each one, this will act as a logical AND amongst
  613. # each specifier.
  614. if self._specs:
  615. for spec in self._specs:
  616. iterable = spec.filter(iterable, prereleases=bool(prereleases))
  617. return iterable
  618. # If we do not have any specifiers, then we need to have a rough filter
  619. # which will filter out any pre-releases, unless there are no final
  620. # releases, and which will filter out LegacyVersion in general.
  621. else:
  622. filtered: List[VersionTypeVar] = []
  623. found_prereleases: List[VersionTypeVar] = []
  624. item: UnparsedVersion
  625. parsed_version: Union[Version, LegacyVersion]
  626. for item in iterable:
  627. # Ensure that we some kind of Version class for this item.
  628. if not isinstance(item, (LegacyVersion, Version)):
  629. parsed_version = parse(item)
  630. else:
  631. parsed_version = item
  632. # Filter out any item which is parsed as a LegacyVersion
  633. if isinstance(parsed_version, LegacyVersion):
  634. continue
  635. # Store any item which is a pre-release for later unless we've
  636. # already found a final version or we are accepting prereleases
  637. if parsed_version.is_prerelease and not prereleases:
  638. if not filtered:
  639. found_prereleases.append(item)
  640. else:
  641. filtered.append(item)
  642. # If we've found no items except for pre-releases, then we'll go
  643. # ahead and use the pre-releases
  644. if not filtered and found_prereleases and prereleases is None:
  645. return found_prereleases
  646. return filtered