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