specifiers.py 39 KB

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