You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

specifiers.py 27KB

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