PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/pymode/libs/pkg_resources/_vendor/packaging/specifiers.py

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