requirements.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 annotations
  5. from typing import Iterator
  6. from ._parser import parse_requirement as _parse_requirement
  7. from ._tokenizer import ParserSyntaxError
  8. from .markers import Marker, _normalize_extra_values
  9. from .specifiers import SpecifierSet
  10. from .utils import canonicalize_name
  11. __all__ = [
  12. "InvalidRequirement",
  13. "Requirement",
  14. ]
  15. def __dir__() -> list[str]:
  16. return __all__
  17. class InvalidRequirement(ValueError):
  18. """
  19. An invalid requirement was found, users should refer to PEP 508.
  20. """
  21. class Requirement:
  22. """Parse a requirement.
  23. Parse a given requirement string into its parts, such as name, specifier,
  24. URL, and extras. Raises InvalidRequirement on a badly-formed requirement
  25. string.
  26. Instances are safe to serialize with :mod:`pickle`. They use a stable
  27. format so the same pickle can be loaded in future packaging releases.
  28. .. versionchanged:: 26.2
  29. Added a stable pickle format. Pickles created with packaging 26.2+ can
  30. be unpickled with future releases. Backward compatibility with pickles
  31. from packaging < 26.2 is supported but may be removed in a future
  32. release.
  33. """
  34. # TODO: Can we test whether something is contained within a requirement?
  35. # If so how do we do that? Do we need to test against the _name_ of
  36. # the thing as well as the version? What about the markers?
  37. # TODO: Can we normalize the name and extra name?
  38. def __init__(self, requirement_string: str) -> None:
  39. try:
  40. parsed = _parse_requirement(requirement_string)
  41. except ParserSyntaxError as e:
  42. raise InvalidRequirement(str(e)) from e
  43. self.name: str = parsed.name
  44. self.url: str | None = parsed.url or None
  45. self.extras: set[str] = set(parsed.extras or [])
  46. self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
  47. self.marker: Marker | None = None
  48. if parsed.marker is not None:
  49. self.marker = Marker.__new__(Marker)
  50. self.marker._markers = _normalize_extra_values(parsed.marker)
  51. def _iter_parts(self, name: str) -> Iterator[str]:
  52. yield name
  53. if self.extras:
  54. formatted_extras = ",".join(sorted(self.extras))
  55. yield f"[{formatted_extras}]"
  56. if self.specifier:
  57. yield str(self.specifier)
  58. if self.url:
  59. yield f" @ {self.url}"
  60. if self.marker:
  61. yield " "
  62. if self.marker:
  63. yield f"; {self.marker}"
  64. def __getstate__(self) -> str:
  65. # Return the requirement string for compactness and stability.
  66. # Re-parsed on load to reconstruct all fields.
  67. return str(self)
  68. def __setstate__(self, state: object) -> None:
  69. if isinstance(state, str):
  70. # New format (26.2+): just the requirement string.
  71. try:
  72. tmp = Requirement(state)
  73. except InvalidRequirement as exc:
  74. raise TypeError(f"Cannot restore Requirement from {state!r}") from exc
  75. self.name = tmp.name
  76. self.url = tmp.url
  77. self.extras = tmp.extras
  78. self.specifier = tmp.specifier
  79. self.marker = tmp.marker
  80. return
  81. if isinstance(state, dict):
  82. # Old format (packaging <= 26.1, no __slots__): plain __dict__.
  83. self.__dict__.update(state)
  84. return
  85. raise TypeError(f"Cannot restore Requirement from {state!r}")
  86. def __str__(self) -> str:
  87. return "".join(self._iter_parts(self.name))
  88. def __repr__(self) -> str:
  89. return f"<{self.__class__.__name__}({str(self)!r})>"
  90. def __hash__(self) -> int:
  91. return hash(tuple(self._iter_parts(canonicalize_name(self.name))))
  92. def __eq__(self, other: object) -> bool:
  93. if not isinstance(other, Requirement):
  94. return NotImplemented
  95. return (
  96. canonicalize_name(self.name) == canonicalize_name(other.name)
  97. and self.extras == other.extras
  98. and self.specifier == other.specifier
  99. and self.url == other.url
  100. and self.marker == other.marker
  101. )