Aluode/PerceptionLabPortable
0
1"""PEP 656 support.2 3This module implements logic to detect if the currently running Python is4linked against musl, and what musl version is used.5"""6 7from __future__ import annotations8 9import functools10import re11import subprocess12import sys13from typing import Iterator, NamedTuple, Sequence14 15from ._elffile import ELFFile16 17 18class _MuslVersion(NamedTuple):19 major: int20 minor: int21 22 23def _parse_musl_version(output: str) -> _MuslVersion | None:24 lines = [n for n in (n.strip() for n in output.splitlines()) if n]25 if len(lines) < 2 or lines[0][:4] != "musl":26 return None27 m = re.match(r"Version (\d+)\.(\d+)", lines[1])28 if not m:29 return None30 return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))31 32 33@functools.lru_cache34def _get_musl_version(executable: str) -> _MuslVersion | None:35 """Detect currently-running musl runtime version.36 37 This is done by checking the specified executable's dynamic linking38 information, and invoking the loader to parse its output for a version39 string. If the loader is musl, the output would be something like::40 41 musl libc (x86_64)42 Version 1.2.243 Dynamic Program Loader44 """45 try:46 with open(executable, "rb") as f:47 ld = ELFFile(f).interpreter48 except (OSError, TypeError, ValueError):49 return None50 if ld is None or "musl" not in ld:51 return None52 proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True)53 return _parse_musl_version(proc.stderr)54 55 56def platform_tags(archs: Sequence[str]) -> Iterator[str]:57 """Generate musllinux tags compatible to the current platform.58 59 :param archs: Sequence of compatible architectures.60 The first one shall be the closest to the actual architecture and be the part of61 platform tag after the ``linux_`` prefix, e.g. ``x86_64``.62 The ``linux_`` prefix is assumed as a prerequisite for the current platform to63 be musllinux-compatible.64 65 :returns: An iterator of compatible musllinux tags.66 """67 sys_musl = _get_musl_version(sys.executable)68 if sys_musl is None: # Python not dynamically linked against musl.69 return70 for arch in archs:71 for minor in range(sys_musl.minor, -1, -1):72 yield f"musllinux_{sys_musl.major}_{minor}_{arch}"73 74 75if __name__ == "__main__": # pragma: no cover76 import sysconfig77 78 plat = sysconfig.get_platform()79 assert plat.startswith("linux-"), "not linux"80 81 print("plat:", plat)82 print("musl:", _get_musl_version(sys.executable))83 print("tags:", end=" ")84 for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])):85 print(t, end="\n ")86 