6ecd55ef3303447058d8f620e3e16dd48f0f892c5b2e5629d63d26665792166bd25167529804d94006aa9a2570cdc7006e5a56f96d45c54849208e032bfdc3 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. import logging
  5. import platform
  6. import struct
  7. import subprocess
  8. import sys
  9. import sysconfig
  10. from importlib.machinery import EXTENSION_SUFFIXES
  11. from typing import (
  12. Dict,
  13. FrozenSet,
  14. Iterable,
  15. Iterator,
  16. List,
  17. Optional,
  18. Sequence,
  19. Tuple,
  20. Union,
  21. cast,
  22. )
  23. from . import _manylinux, _musllinux
  24. logger = logging.getLogger(__name__)
  25. PythonVersion = Sequence[int]
  26. MacVersion = Tuple[int, int]
  27. INTERPRETER_SHORT_NAMES: Dict[str, str] = {
  28. "python": "py", # Generic.
  29. "cpython": "cp",
  30. "pypy": "pp",
  31. "ironpython": "ip",
  32. "jython": "jy",
  33. }
  34. _32_BIT_INTERPRETER = struct.calcsize("P") == 4
  35. class Tag:
  36. """
  37. A representation of the tag triple for a wheel.
  38. Instances are considered immutable and thus are hashable. Equality checking
  39. is also supported.
  40. """
  41. __slots__ = ["_interpreter", "_abi", "_platform", "_hash"]
  42. def __init__(self, interpreter: str, abi: str, platform: str) -> None:
  43. self._interpreter = interpreter.lower()
  44. self._abi = abi.lower()
  45. self._platform = platform.lower()
  46. # The __hash__ of every single element in a Set[Tag] will be evaluated each time
  47. # that a set calls its `.disjoint()` method, which may be called hundreds of
  48. # times when scanning a page of links for packages with tags matching that
  49. # Set[Tag]. Pre-computing the value here produces significant speedups for
  50. # downstream consumers.
  51. self._hash = hash((self._interpreter, self._abi, self._platform))
  52. @property
  53. def interpreter(self) -> str:
  54. return self._interpreter
  55. @property
  56. def abi(self) -> str:
  57. return self._abi
  58. @property
  59. def platform(self) -> str:
  60. return self._platform
  61. def __eq__(self, other: object) -> bool:
  62. if not isinstance(other, Tag):
  63. return NotImplemented
  64. return (
  65. (self._hash == other._hash) # Short-circuit ASAP for perf reasons.
  66. and (self._platform == other._platform)
  67. and (self._abi == other._abi)
  68. and (self._interpreter == other._interpreter)
  69. )
  70. def __hash__(self) -> int:
  71. return self._hash
  72. def __str__(self) -> str:
  73. return f"{self._interpreter}-{self._abi}-{self._platform}"
  74. def __repr__(self) -> str:
  75. return f"<{self} @ {id(self)}>"
  76. def parse_tag(tag: str) -> FrozenSet[Tag]:
  77. """
  78. Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
  79. Returning a set is required due to the possibility that the tag is a
  80. compressed tag set.
  81. """
  82. tags = set()
  83. interpreters, abis, platforms = tag.split("-")
  84. for interpreter in interpreters.split("."):
  85. for abi in abis.split("."):
  86. for platform_ in platforms.split("."):
  87. tags.add(Tag(interpreter, abi, platform_))
  88. return frozenset(tags)
  89. def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:
  90. value: Union[int, str, None] = sysconfig.get_config_var(name)
  91. if value is None and warn:
  92. logger.debug(
  93. "Config variable '%s' is unset, Python ABI tag may be incorrect", name
  94. )
  95. return value
  96. def _normalize_string(string: str) -> str:
  97. return string.replace(".", "_").replace("-", "_").replace(" ", "_")
  98. def _abi3_applies(python_version: PythonVersion) -> bool:
  99. """
  100. Determine if the Python version supports abi3.
  101. PEP 384 was first implemented in Python 3.2.
  102. """
  103. return len(python_version) > 1 and tuple(python_version) >= (3, 2)
  104. def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
  105. py_version = tuple(py_version) # To allow for version comparison.
  106. abis = []
  107. version = _version_nodot(py_version[:2])
  108. debug = pymalloc = ucs4 = ""
  109. with_debug = _get_config_var("Py_DEBUG", warn)
  110. has_refcount = hasattr(sys, "gettotalrefcount")
  111. # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
  112. # extension modules is the best option.
  113. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
  114. has_ext = "_d.pyd" in EXTENSION_SUFFIXES
  115. if with_debug or (with_debug is None and (has_refcount or has_ext)):
  116. debug = "d"
  117. if py_version < (3, 8):
  118. with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
  119. if with_pymalloc or with_pymalloc is None:
  120. pymalloc = "m"
  121. if py_version < (3, 3):
  122. unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
  123. if unicode_size == 4 or (
  124. unicode_size is None and sys.maxunicode == 0x10FFFF
  125. ):
  126. ucs4 = "u"
  127. elif debug:
  128. # Debug builds can also load "normal" extension modules.
  129. # We can also assume no UCS-4 or pymalloc requirement.
  130. abis.append(f"cp{version}")
  131. abis.insert(
  132. 0,
  133. "cp{version}{debug}{pymalloc}{ucs4}".format(
  134. version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4
  135. ),
  136. )
  137. return abis
  138. def cpython_tags(
  139. python_version: Optional[PythonVersion] = None,
  140. abis: Optional[Iterable[str]] = None,
  141. platforms: Optional[Iterable[str]] = None,
  142. *,
  143. warn: bool = False,
  144. ) -> Iterator[Tag]:
  145. """
  146. Yields the tags for a CPython interpreter.
  147. The tags consist of:
  148. - cp<python_version>-<abi>-<platform>
  149. - cp<python_version>-abi3-<platform>
  150. - cp<python_version>-none-<platform>
  151. - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
  152. If python_version only specifies a major version then user-provided ABIs and
  153. the 'none' ABItag will be used.
  154. If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
  155. their normal position and not at the beginning.
  156. """
  157. if not python_version:
  158. python_version = sys.version_info[:2]
  159. interpreter = f"cp{_version_nodot(python_version[:2])}"
  160. if abis is None:
  161. if len(python_version) > 1:
  162. abis = _cpython_abis(python_version, warn)
  163. else:
  164. abis = []
  165. abis = list(abis)
  166. # 'abi3' and 'none' are explicitly handled later.
  167. for explicit_abi in ("abi3", "none"):
  168. try:
  169. abis.remove(explicit_abi)
  170. except ValueError:
  171. pass
  172. platforms = list(platforms or platform_tags())
  173. for abi in abis:
  174. for platform_ in platforms:
  175. yield Tag(interpreter, abi, platform_)
  176. if _abi3_applies(python_version):
  177. yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
  178. yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
  179. if _abi3_applies(python_version):
  180. for minor_version in range(python_version[1] - 1, 1, -1):
  181. for platform_ in platforms:
  182. interpreter = "cp{version}".format(
  183. version=_version_nodot((python_version[0], minor_version))
  184. )
  185. yield Tag(interpreter, "abi3", platform_)
  186. def _generic_abi() -> List[str]:
  187. """
  188. Return the ABI tag based on EXT_SUFFIX.
  189. """
  190. # The following are examples of `EXT_SUFFIX`.
  191. # We want to keep the parts which are related to the ABI and remove the
  192. # parts which are related to the platform:
  193. # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310
  194. # - mac: '.cpython-310-darwin.so' => cp310
  195. # - win: '.cp310-win_amd64.pyd' => cp310
  196. # - win: '.pyd' => cp37 (uses _cpython_abis())
  197. # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
  198. # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
  199. # => graalpy_38_native
  200. ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
  201. if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
  202. raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
  203. parts = ext_suffix.split(".")
  204. if len(parts) < 3:
  205. # CPython3.7 and earlier uses ".pyd" on Windows.
  206. return _cpython_abis(sys.version_info[:2])
  207. soabi = parts[1]
  208. if soabi.startswith("cpython"):
  209. # non-windows
  210. abi = "cp" + soabi.split("-")[1]
  211. elif soabi.startswith("cp"):
  212. # windows
  213. abi = soabi.split("-")[0]
  214. elif soabi.startswith("pypy"):
  215. abi = "-".join(soabi.split("-")[:2])
  216. elif soabi.startswith("graalpy"):
  217. abi = "-".join(soabi.split("-")[:3])
  218. elif soabi:
  219. # pyston, ironpython, others?
  220. abi = soabi
  221. else:
  222. return []
  223. return [_normalize_string(abi)]
  224. def generic_tags(
  225. interpreter: Optional[str] = None,
  226. abis: Optional[Iterable[str]] = None,
  227. platforms: Optional[Iterable[str]] = None,
  228. *,
  229. warn: bool = False,
  230. ) -> Iterator[Tag]:
  231. """
  232. Yields the tags for a generic interpreter.
  233. The tags consist of:
  234. - <interpreter>-<abi>-<platform>
  235. The "none" ABI will be added if it was not explicitly provided.
  236. """
  237. if not interpreter:
  238. interp_name = interpreter_name()
  239. interp_version = interpreter_version(warn=warn)
  240. interpreter = "".join([interp_name, interp_version])
  241. if abis is None:
  242. abis = _generic_abi()
  243. else:
  244. abis = list(abis)
  245. platforms = list(platforms or platform_tags())
  246. if "none" not in abis:
  247. abis.append("none")
  248. for abi in abis:
  249. for platform_ in platforms:
  250. yield Tag(interpreter, abi, platform_)
  251. def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
  252. """
  253. Yields Python versions in descending order.
  254. After the latest version, the major-only version will be yielded, and then
  255. all previous versions of that major version.
  256. """
  257. if len(py_version) > 1:
  258. yield f"py{_version_nodot(py_version[:2])}"
  259. yield f"py{py_version[0]}"
  260. if len(py_version) > 1:
  261. for minor in range(py_version[1] - 1, -1, -1):
  262. yield f"py{_version_nodot((py_version[0], minor))}"
  263. def compatible_tags(
  264. python_version: Optional[PythonVersion] = None,
  265. interpreter: Optional[str] = None,
  266. platforms: Optional[Iterable[str]] = None,
  267. ) -> Iterator[Tag]:
  268. """
  269. Yields the sequence of tags that are compatible with a specific version of Python.
  270. The tags consist of:
  271. - py*-none-<platform>
  272. - <interpreter>-none-any # ... if `interpreter` is provided.
  273. - py*-none-any
  274. """
  275. if not python_version:
  276. python_version = sys.version_info[:2]
  277. platforms = list(platforms or platform_tags())
  278. for version in _py_interpreter_range(python_version):
  279. for platform_ in platforms:
  280. yield Tag(version, "none", platform_)
  281. if interpreter:
  282. yield Tag(interpreter, "none", "any")
  283. for version in _py_interpreter_range(python_version):
  284. yield Tag(version, "none", "any")
  285. def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
  286. if not is_32bit:
  287. return arch
  288. if arch.startswith("ppc"):
  289. return "ppc"
  290. return "i386"
  291. def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:
  292. formats = [cpu_arch]
  293. if cpu_arch == "x86_64":
  294. if version < (10, 4):
  295. return []
  296. formats.extend(["intel", "fat64", "fat32"])
  297. elif cpu_arch == "i386":
  298. if version < (10, 4):
  299. return []
  300. formats.extend(["intel", "fat32", "fat"])
  301. elif cpu_arch == "ppc64":
  302. # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
  303. if version > (10, 5) or version < (10, 4):
  304. return []
  305. formats.append("fat64")
  306. elif cpu_arch == "ppc":
  307. if version > (10, 6):
  308. return []
  309. formats.extend(["fat32", "fat"])
  310. if cpu_arch in {"arm64", "x86_64"}:
  311. formats.append("universal2")
  312. if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
  313. formats.append("universal")
  314. return formats
  315. def mac_platforms(
  316. version: Optional[MacVersion] = None, arch: Optional[str] = None
  317. ) -> Iterator[str]:
  318. """
  319. Yields the platform tags for a macOS system.
  320. The `version` parameter is a two-item tuple specifying the macOS version to
  321. generate platform tags for. The `arch` parameter is the CPU architecture to
  322. generate platform tags for. Both parameters default to the appropriate value
  323. for the current system.
  324. """
  325. version_str, _, cpu_arch = platform.mac_ver()
  326. if version is None:
  327. version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
  328. if version == (10, 16):
  329. # When built against an older macOS SDK, Python will report macOS 10.16
  330. # instead of the real version.
  331. version_str = subprocess.run(
  332. [
  333. sys.executable,
  334. "-sS",
  335. "-c",
  336. "import platform; print(platform.mac_ver()[0])",
  337. ],
  338. check=True,
  339. env={"SYSTEM_VERSION_COMPAT": "0"},
  340. stdout=subprocess.PIPE,
  341. text=True,
  342. ).stdout
  343. version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
  344. else:
  345. version = version
  346. if arch is None:
  347. arch = _mac_arch(cpu_arch)
  348. else:
  349. arch = arch
  350. if (10, 0) <= version and version < (11, 0):
  351. # Prior to Mac OS 11, each yearly release of Mac OS bumped the
  352. # "minor" version number. The major version was always 10.
  353. for minor_version in range(version[1], -1, -1):
  354. compat_version = 10, minor_version
  355. binary_formats = _mac_binary_formats(compat_version, arch)
  356. for binary_format in binary_formats:
  357. yield "macosx_{major}_{minor}_{binary_format}".format(
  358. major=10, minor=minor_version, binary_format=binary_format
  359. )
  360. if version >= (11, 0):
  361. # Starting with Mac OS 11, each yearly release bumps the major version
  362. # number. The minor versions are now the midyear updates.
  363. for major_version in range(version[0], 10, -1):
  364. compat_version = major_version, 0
  365. binary_formats = _mac_binary_formats(compat_version, arch)
  366. for binary_format in binary_formats:
  367. yield "macosx_{major}_{minor}_{binary_format}".format(
  368. major=major_version, minor=0, binary_format=binary_format
  369. )
  370. if version >= (11, 0):
  371. # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
  372. # Arm64 support was introduced in 11.0, so no Arm binaries from previous
  373. # releases exist.
  374. #
  375. # However, the "universal2" binary format can have a
  376. # macOS version earlier than 11.0 when the x86_64 part of the binary supports
  377. # that version of macOS.
  378. if arch == "x86_64":
  379. for minor_version in range(16, 3, -1):
  380. compat_version = 10, minor_version
  381. binary_formats = _mac_binary_formats(compat_version, arch)
  382. for binary_format in binary_formats:
  383. yield "macosx_{major}_{minor}_{binary_format}".format(
  384. major=compat_version[0],
  385. minor=compat_version[1],
  386. binary_format=binary_format,
  387. )
  388. else:
  389. for minor_version in range(16, 3, -1):
  390. compat_version = 10, minor_version
  391. binary_format = "universal2"
  392. yield "macosx_{major}_{minor}_{binary_format}".format(
  393. major=compat_version[0],
  394. minor=compat_version[1],
  395. binary_format=binary_format,
  396. )
  397. def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
  398. linux = _normalize_string(sysconfig.get_platform())
  399. if not linux.startswith("linux_"):
  400. # we should never be here, just yield the sysconfig one and return
  401. yield linux
  402. return
  403. if is_32bit:
  404. if linux == "linux_x86_64":
  405. linux = "linux_i686"
  406. elif linux == "linux_aarch64":
  407. linux = "linux_armv8l"
  408. _, arch = linux.split("_", 1)
  409. archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch])
  410. yield from _manylinux.platform_tags(archs)
  411. yield from _musllinux.platform_tags(archs)
  412. for arch in archs:
  413. yield f"linux_{arch}"
  414. def _generic_platforms() -> Iterator[str]:
  415. yield _normalize_string(sysconfig.get_platform())
  416. def platform_tags() -> Iterator[str]:
  417. """
  418. Provides the platform tags for this installation.
  419. """
  420. if platform.system() == "Darwin":
  421. return mac_platforms()
  422. elif platform.system() == "Linux":
  423. return _linux_platforms()
  424. else:
  425. return _generic_platforms()
  426. def interpreter_name() -> str:
  427. """
  428. Returns the name of the running interpreter.
  429. Some implementations have a reserved, two-letter abbreviation which will
  430. be returned when appropriate.
  431. """
  432. name = sys.implementation.name
  433. return INTERPRETER_SHORT_NAMES.get(name) or name
  434. def interpreter_version(*, warn: bool = False) -> str:
  435. """
  436. Returns the version of the running interpreter.
  437. """
  438. version = _get_config_var("py_version_nodot", warn=warn)
  439. if version:
  440. version = str(version)
  441. else:
  442. version = _version_nodot(sys.version_info[:2])
  443. return version
  444. def _version_nodot(version: PythonVersion) -> str:
  445. return "".join(map(str, version))
  446. def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
  447. """
  448. Returns the sequence of tag triples for the running interpreter.
  449. The order of the sequence corresponds to priority order for the
  450. interpreter, from most to least important.
  451. """
  452. interp_name = interpreter_name()
  453. if interp_name == "cp":
  454. yield from cpython_tags(warn=warn)
  455. else:
  456. yield from generic_tags()
  457. if interp_name == "pp":
  458. interp = "pp3"
  459. elif interp_name == "cp":
  460. interp = "cp" + interpreter_version(warn=warn)
  461. else:
  462. interp = None
  463. yield from compatible_tags(interpreter=interp)