markers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. import operator
  6. import os
  7. import platform
  8. import sys
  9. from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
  10. from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
  11. from ._parser import parse_marker as _parse_marker
  12. from ._tokenizer import ParserSyntaxError
  13. from .specifiers import InvalidSpecifier, Specifier
  14. from .utils import canonicalize_name
  15. __all__ = [
  16. "Environment",
  17. "EvaluateContext",
  18. "InvalidMarker",
  19. "Marker",
  20. "UndefinedComparison",
  21. "UndefinedEnvironmentName",
  22. "default_environment",
  23. ]
  24. def __dir__() -> list[str]:
  25. return __all__
  26. Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]
  27. EvaluateContext = Literal["metadata", "lock_file", "requirement"]
  28. """A ``typing.Literal`` enumerating valid marker evaluation contexts.
  29. Valid values for the ``context`` passed to :meth:`Marker.evaluate` are:
  30. * ``"metadata"`` (for core metadata; default)
  31. * ``"lock_file"`` (for lock files)
  32. * ``"requirement"`` (i.e. all other situations)
  33. """
  34. MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}
  35. MARKERS_REQUIRING_VERSION = {
  36. "implementation_version",
  37. "platform_release",
  38. "python_full_version",
  39. "python_version",
  40. }
  41. class InvalidMarker(ValueError):
  42. """Raised when attempting to create a :class:`Marker` from invalid input.
  43. This error indicates that the given marker string does not conform to the
  44. :ref:`specification of dependency specifiers <pypug:dependency-specifiers>`.
  45. """
  46. class UndefinedComparison(ValueError):
  47. """Raised when evaluating an unsupported marker comparison.
  48. This can happen when marker values are compared as versions but do not
  49. conform to the :ref:`specification of version specifiers
  50. <pypug:version-specifiers>`.
  51. """
  52. class UndefinedEnvironmentName(ValueError):
  53. """Raised when evaluating a marker that references a missing environment key."""
  54. class Environment(TypedDict):
  55. """
  56. A dictionary that represents a Python environment as captured by
  57. :func:`default_environment`. All fields are required.
  58. """
  59. implementation_name: str
  60. """The implementation's identifier, e.g. ``'cpython'``."""
  61. implementation_version: str
  62. """
  63. The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or
  64. ``'7.3.13'`` for PyPy3.10 v7.3.13.
  65. """
  66. os_name: str
  67. """
  68. The value of :py:data:`os.name`. The name of the operating system dependent module
  69. imported, e.g. ``'posix'``.
  70. """
  71. platform_machine: str
  72. """
  73. Returns the machine type, e.g. ``'i386'``.
  74. An empty string if the value cannot be determined.
  75. """
  76. platform_release: str
  77. """
  78. The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
  79. An empty string if the value cannot be determined.
  80. """
  81. platform_system: str
  82. """
  83. The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
  84. An empty string if the value cannot be determined.
  85. """
  86. platform_version: str
  87. """
  88. The system's release version, e.g. ``'#3 on degas'``.
  89. An empty string if the value cannot be determined.
  90. """
  91. python_full_version: str
  92. """
  93. The Python version as string ``'major.minor.patchlevel'``.
  94. Note that unlike the Python :py:data:`sys.version`, this value will always include
  95. the patchlevel (it defaults to 0).
  96. """
  97. platform_python_implementation: str
  98. """
  99. A string identifying the Python implementation, e.g. ``'CPython'``.
  100. """
  101. python_version: str
  102. """The Python version as string ``'major.minor'``."""
  103. sys_platform: str
  104. """
  105. This string contains a platform identifier that can be used to append
  106. platform-specific components to :py:data:`sys.path`, for instance.
  107. For Unix systems, except on Linux and AIX, this is the lowercased OS name as
  108. returned by ``uname -s`` with the first part of the version as returned by
  109. ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python
  110. was built.
  111. """
  112. def _normalize_extras(
  113. result: MarkerList | MarkerAtom | str,
  114. ) -> MarkerList | MarkerAtom | str:
  115. if not isinstance(result, tuple):
  116. return result
  117. lhs, op, rhs = result
  118. if isinstance(lhs, Variable) and lhs.value == "extra":
  119. normalized_extra = canonicalize_name(rhs.value)
  120. rhs = Value(normalized_extra)
  121. elif isinstance(rhs, Variable) and rhs.value == "extra":
  122. normalized_extra = canonicalize_name(lhs.value)
  123. lhs = Value(normalized_extra)
  124. return lhs, op, rhs
  125. def _normalize_extra_values(results: MarkerList) -> MarkerList:
  126. """
  127. Normalize extra values.
  128. """
  129. return [_normalize_extras(r) for r in results]
  130. def _format_marker(
  131. marker: list[str] | MarkerAtom | str, first: bool | None = True
  132. ) -> str:
  133. assert isinstance(marker, (list, tuple, str))
  134. # Sometimes we have a structure like [[...]] which is a single item list
  135. # where the single item is itself it's own list. In that case we want skip
  136. # the rest of this function so that we don't get extraneous () on the
  137. # outside.
  138. if (
  139. isinstance(marker, list)
  140. and len(marker) == 1
  141. and isinstance(marker[0], (list, tuple))
  142. ):
  143. return _format_marker(marker[0])
  144. if isinstance(marker, list):
  145. inner = (_format_marker(m, first=False) for m in marker)
  146. if first:
  147. return " ".join(inner)
  148. else:
  149. return "(" + " ".join(inner) + ")"
  150. elif isinstance(marker, tuple):
  151. return " ".join([m.serialize() for m in marker])
  152. else:
  153. return marker
  154. _operators: dict[str, Operator] = {
  155. "in": lambda lhs, rhs: lhs in rhs,
  156. "not in": lambda lhs, rhs: lhs not in rhs,
  157. "<": lambda _lhs, _rhs: False,
  158. "<=": operator.eq,
  159. "==": operator.eq,
  160. "!=": operator.ne,
  161. ">=": operator.eq,
  162. ">": lambda _lhs, _rhs: False,
  163. }
  164. def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool:
  165. op_str = op.serialize()
  166. if key in MARKERS_REQUIRING_VERSION:
  167. try:
  168. spec = Specifier(f"{op_str}{rhs}")
  169. except InvalidSpecifier:
  170. pass
  171. else:
  172. return spec.contains(lhs, prereleases=True)
  173. oper: Operator | None = _operators.get(op_str)
  174. if oper is None:
  175. raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
  176. return oper(lhs, rhs)
  177. def _normalize(
  178. lhs: str, rhs: str | AbstractSet[str], key: str
  179. ) -> tuple[str, str | AbstractSet[str]]:
  180. # PEP 685 - Comparison of extra names for optional distribution dependencies
  181. # https://peps.python.org/pep-0685/
  182. # > When comparing extra names, tools MUST normalize the names being
  183. # > compared using the semantics outlined in PEP 503 for names
  184. if key == "extra":
  185. assert isinstance(rhs, str), "extra value must be a string"
  186. # Both sides are normalized at this point already
  187. return (lhs, rhs)
  188. if key in MARKERS_ALLOWING_SET:
  189. if isinstance(rhs, str): # pragma: no cover
  190. return (canonicalize_name(lhs), canonicalize_name(rhs))
  191. else:
  192. return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
  193. # other environment markers don't have such standards
  194. return lhs, rhs
  195. def _evaluate_markers(
  196. markers: MarkerList, environment: dict[str, str | AbstractSet[str]]
  197. ) -> bool:
  198. groups: list[list[bool]] = [[]]
  199. for marker in markers:
  200. if isinstance(marker, list):
  201. groups[-1].append(_evaluate_markers(marker, environment))
  202. elif isinstance(marker, tuple):
  203. lhs, op, rhs = marker
  204. if isinstance(lhs, Variable):
  205. environment_key = lhs.value
  206. lhs_value = environment[environment_key]
  207. rhs_value = rhs.value
  208. else:
  209. lhs_value = lhs.value
  210. environment_key = rhs.value
  211. rhs_value = environment[environment_key]
  212. assert isinstance(lhs_value, str), "lhs must be a string"
  213. lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key)
  214. groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key))
  215. elif marker == "or":
  216. groups.append([])
  217. elif marker == "and":
  218. pass
  219. else: # pragma: nocover
  220. raise TypeError(f"Unexpected marker {marker!r}")
  221. return any(all(item) for item in groups)
  222. def _format_full_version(info: sys._version_info) -> str:
  223. version = f"{info.major}.{info.minor}.{info.micro}"
  224. kind = info.releaselevel
  225. if kind != "final":
  226. version += kind[0] + str(info.serial)
  227. return version
  228. def default_environment() -> Environment:
  229. """Return the default marker environment for the current Python process.
  230. This is the base environment used by :meth:`Marker.evaluate`.
  231. """
  232. iver = _format_full_version(sys.implementation.version)
  233. implementation_name = sys.implementation.name
  234. return {
  235. "implementation_name": implementation_name,
  236. "implementation_version": iver,
  237. "os_name": os.name,
  238. "platform_machine": platform.machine(),
  239. "platform_release": platform.release(),
  240. "platform_system": platform.system(),
  241. "platform_version": platform.version(),
  242. "python_full_version": platform.python_version(),
  243. "platform_python_implementation": platform.python_implementation(),
  244. "python_version": ".".join(platform.python_version_tuple()[:2]),
  245. "sys_platform": sys.platform,
  246. }
  247. class Marker:
  248. """Represents a parsed dependency marker expression.
  249. Marker expressions are parsed according to the
  250. :ref:`specification of dependency specifiers <pypug:dependency-specifiers>`.
  251. :param marker: The string representation of a marker expression.
  252. :raises InvalidMarker: If ``marker`` cannot be parsed.
  253. Instances are safe to serialize with :mod:`pickle`. They use a stable
  254. format so the same pickle can be loaded in future packaging releases.
  255. .. versionchanged:: 26.2
  256. Added a stable pickle format. Pickles created with packaging 26.2+ can
  257. be unpickled with future releases. Backward compatibility with pickles
  258. from packaging < 26.2 is supported but may be removed in a future
  259. release.
  260. """
  261. __slots__ = ("_markers",)
  262. def __init__(self, marker: str) -> None:
  263. # Note: We create a Marker object without calling this constructor in
  264. # packaging.requirements.Requirement. If any additional logic is
  265. # added here, make sure to mirror/adapt Requirement.
  266. # If this fails and throws an error, the repr still expects _markers to
  267. # be defined.
  268. self._markers: MarkerList = []
  269. try:
  270. self._markers = _normalize_extra_values(_parse_marker(marker))
  271. # The attribute `_markers` can be described in terms of a recursive type:
  272. # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
  273. #
  274. # For example, the following expression:
  275. # python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
  276. #
  277. # is parsed into:
  278. # [
  279. # (<Variable('python_version')>, <Op('>')>, <Value('3.6')>),
  280. # 'and',
  281. # [
  282. # (<Variable('python_version')>, <Op('==')>, <Value('3.6')>),
  283. # 'or',
  284. # (<Variable('os_name')>, <Op('==')>, <Value('unix')>)
  285. # ]
  286. # ]
  287. except ParserSyntaxError as e:
  288. raise InvalidMarker(str(e)) from e
  289. @classmethod
  290. def _from_markers(cls, markers: MarkerList) -> Marker:
  291. """Create a Marker instance from a pre-parsed marker tree.
  292. This avoids re-parsing serialised marker strings when combining markers.
  293. """
  294. new = cls.__new__(cls)
  295. new._markers = markers
  296. return new
  297. def __str__(self) -> str:
  298. return _format_marker(self._markers)
  299. def __repr__(self) -> str:
  300. return f"<{self.__class__.__name__}({str(self)!r})>"
  301. def __hash__(self) -> int:
  302. return hash(str(self))
  303. def __eq__(self, other: object) -> bool:
  304. if not isinstance(other, Marker):
  305. return NotImplemented
  306. return str(self) == str(other)
  307. def __getstate__(self) -> str:
  308. # Return the marker expression string for compactness and stability.
  309. # Internal Node objects are excluded; the string is re-parsed on load.
  310. return str(self)
  311. def __setstate__(self, state: object) -> None:
  312. if isinstance(state, str):
  313. # New format (26.2+): just the marker expression string.
  314. try:
  315. self._markers = _normalize_extra_values(_parse_marker(state))
  316. except ParserSyntaxError as exc:
  317. raise TypeError(f"Cannot restore Marker from {state!r}") from exc
  318. return
  319. if isinstance(state, dict) and "_markers" in state:
  320. # Old format (packaging <= 26.1, no __slots__): plain __dict__.
  321. markers = state["_markers"]
  322. if isinstance(markers, list):
  323. self._markers = markers
  324. return
  325. if isinstance(state, tuple) and len(state) == 2:
  326. # Old format (packaging <= 26.1, __slots__): (None, {slot: value}).
  327. _, slot_dict = state
  328. if isinstance(slot_dict, dict) and "_markers" in slot_dict:
  329. markers = slot_dict["_markers"]
  330. if isinstance(markers, list):
  331. self._markers = markers
  332. return
  333. raise TypeError(f"Cannot restore Marker from {state!r}")
  334. def __and__(self, other: Marker) -> Marker:
  335. if not isinstance(other, Marker):
  336. return NotImplemented
  337. return self._from_markers([self._markers, "and", other._markers])
  338. def __or__(self, other: Marker) -> Marker:
  339. if not isinstance(other, Marker):
  340. return NotImplemented
  341. return self._from_markers([self._markers, "or", other._markers])
  342. def evaluate(
  343. self,
  344. environment: Mapping[str, str | AbstractSet[str]] | None = None,
  345. context: EvaluateContext = "metadata",
  346. ) -> bool:
  347. """Evaluate a marker.
  348. Return the boolean from evaluating this marker against the environment.
  349. The environment is determined from the current Python process unless
  350. passed in explicitly.
  351. :param environment: Mapping containing keys and values to override the
  352. detected environment.
  353. :param EvaluateContext context: The context in which the marker is
  354. evaluated, which influences what marker names are considered valid.
  355. Accepted values are ``"metadata"`` (for core metadata; default),
  356. ``"lock_file"``, and ``"requirement"`` (i.e. all other situations).
  357. :raises UndefinedComparison: If the marker uses a comparison on values
  358. that are not valid versions per the :ref:`specification of version
  359. specifiers <pypug:version-specifiers>`.
  360. :raises UndefinedEnvironmentName: If the marker references a value that
  361. is missing from the evaluation environment.
  362. :returns: ``True`` if the marker matches, otherwise ``False``.
  363. """
  364. current_environment = cast(
  365. "dict[str, str | AbstractSet[str]]", default_environment()
  366. )
  367. if context == "lock_file":
  368. current_environment.update(
  369. extras=frozenset(), dependency_groups=frozenset()
  370. )
  371. elif context == "metadata":
  372. current_environment["extra"] = ""
  373. if environment is not None:
  374. current_environment.update(environment)
  375. if "extra" in current_environment:
  376. # The API used to allow setting extra to None. We need to handle
  377. # this case for backwards compatibility. Also skip running
  378. # normalize name if extra is empty.
  379. extra = cast("str | None", current_environment["extra"])
  380. current_environment["extra"] = canonicalize_name(extra) if extra else ""
  381. return _evaluate_markers(
  382. self._markers, _repair_python_full_version(current_environment)
  383. )
  384. def _repair_python_full_version(
  385. env: dict[str, str | AbstractSet[str]],
  386. ) -> dict[str, str | AbstractSet[str]]:
  387. """
  388. Work around platform.python_version() returning something that is not PEP 440
  389. compliant for non-tagged Python builds.
  390. """
  391. python_full_version = cast("str", env["python_full_version"])
  392. if python_full_version.endswith("+"):
  393. env["python_full_version"] = f"{python_full_version}local"
  394. return env