|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import functools |
| 4 | +import platform |
| 5 | +import struct |
| 6 | +import sys |
| 7 | +from enum import Enum |
| 8 | + |
| 9 | + |
| 10 | +class Architecture(Enum): |
| 11 | + value: str |
| 12 | + |
| 13 | + aarch64 = "aarch64" |
| 14 | + armv7l = "armv7l" |
| 15 | + i686 = "i686" |
| 16 | + loongarch64 = "loongarch64" |
| 17 | + ppc64 = "ppc64" |
| 18 | + ppc64le = "ppc64le" |
| 19 | + riscv64 = "riscv64" |
| 20 | + s390x = "s390x" |
| 21 | + x86_64 = "x86_64" |
| 22 | + x86_64_v2 = "x86_64_v2" |
| 23 | + x86_64_v3 = "x86_64_v3" |
| 24 | + x86_64_v4 = "x86_64_v4" |
| 25 | + |
| 26 | + def __str__(self): |
| 27 | + return self.value |
| 28 | + |
| 29 | + @property |
| 30 | + def baseline(self): |
| 31 | + if self.value.startswith("x86_64"): |
| 32 | + return Architecture.x86_64 |
| 33 | + return self |
| 34 | + |
| 35 | + @classmethod |
| 36 | + @functools.lru_cache(None) |
| 37 | + def _member_list(cls) -> list[Architecture]: |
| 38 | + return list(cls) |
| 39 | + |
| 40 | + def is_subset(self, other: Architecture) -> bool: |
| 41 | + if self.baseline != other.baseline: |
| 42 | + return False |
| 43 | + member_list = Architecture._member_list() |
| 44 | + return member_list.index(self) <= member_list.index(other) |
| 45 | + |
| 46 | + def is_superset(self, other: Architecture) -> bool: |
| 47 | + if self.baseline != other.baseline: |
| 48 | + return False |
| 49 | + return other.is_subset(self) |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def get_native_architecture(*, bits: int | None = None) -> Architecture: |
| 53 | + machine = platform.machine() |
| 54 | + if sys.platform.startswith("win"): |
| 55 | + machine = {"AMD64": "x86_64", "ARM64": "aarch64", "x86": "i686"}.get( |
| 56 | + machine, machine |
| 57 | + ) |
| 58 | + elif sys.platform.startswith("darwin"): |
| 59 | + machine = {"arm64": "aarch64"}.get(machine, machine) |
| 60 | + |
| 61 | + if bits is None: |
| 62 | + # c.f. https://github.com/pypa/packaging/pull/711 |
| 63 | + bits = 8 * struct.calcsize("P") |
| 64 | + |
| 65 | + if machine in {"x86_64", "i686"}: |
| 66 | + machine = {64: "x86_64", 32: "i686"}[bits] |
| 67 | + elif machine in {"aarch64", "armv8l"}: |
| 68 | + # use armv7l policy for 64-bit arm kernel in 32-bit mode (armv8l) |
| 69 | + machine = {64: "aarch64", 32: "armv7l"}[bits] |
| 70 | + |
| 71 | + return Architecture(machine) |
0 commit comments