Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ repos:
priority: 5
args: ["--fix", "--unsafe-fixes", "--exit-non-zero-on-fix"]
- repo: https://github.com/gaborbernat/simplint-pre-commit
rev: "5f12b15e1199c42bdeb3e13ea1c8b45952fbd802" # frozen: v0.11.0
rev: "a12d8eaac290be24041a3e2778c636c56453722e" # frozen: v0.12.2
hooks:
- id: simplint
priority: 6
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ lint.ignore = [
"undocumented-public-init", # undocumented-public-api (simplint) covers the public API instead
"undocumented-public-method", # undocumented-public-api (simplint) covers the public API instead
"undocumented-public-nested-class", # undocumented-public-api (simplint) covers the public API instead
"unnecessary-regular-expression-compile", # conflicts with simplint inline-regex
]
lint.per-file-ignores."docs/**/*.py" = [
"implicit-namespace-package", # no __init__.py in docs directory
Expand Down
38 changes: 19 additions & 19 deletions src/python_discovery/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,25 @@ def py_info_clear(self) -> None:
entry.unlink()


class NoOpContentStore(ContentStore):
# Content store that does nothing -- implements ContentStore protocol.
def exists(self) -> bool: # ruff:ignore[no-self-use] cache protocol
return False

def read(self) -> dict | None: # ruff:ignore[no-self-use] cache protocol
return None

def write(self, content: dict) -> None:
pass

def remove(self) -> None:
pass

@contextmanager
def locked(self) -> Generator[None]: # ruff:ignore[no-self-use] cache protocol
yield


class DiskContentStore:
# JSON file-based content store with file locking.
def __init__(self, folder: Path, key: str) -> None:
Expand Down Expand Up @@ -229,25 +248,6 @@ def locked(self) -> Generator[None]:
yield


class NoOpContentStore(ContentStore):
# Content store that does nothing -- implements ContentStore protocol.
def exists(self) -> bool: # ruff:ignore[no-self-use] cache protocol
return False

def read(self) -> dict | None: # ruff:ignore[no-self-use] cache protocol
return None

def write(self, content: dict) -> None:
pass

def remove(self) -> None:
pass

@contextmanager
def locked(self) -> Generator[None]: # ruff:ignore[no-self-use] cache protocol
yield


class NoOpCache(PyInfoCache):
# Cache that does nothing -- implements PyInfoCache protocol.
def py_info(self, path: Path) -> NoOpContentStore: # ruff:ignore[unused-method-argument, no-self-use] protocol
Expand Down
30 changes: 15 additions & 15 deletions src/python_discovery/_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,21 @@ def _parse_uv_install(path: Path) -> _UvInstall:
return _UvInstall(path=path, key=key)


@dataclass(**DC_KW)
class _UvInstall:
path: Path
key: _UvKey | None


@dataclass(**DC_KW)
class _UvKey:
# The ``<implementation>-<version>[+<variant>]-<os>-<arch>-<libc>`` name uv gives an install directory.
implementation: str
version: SimpleVersion
free_threaded: bool
debug: bool


def _uv_sort_key(install: _UvInstall) -> tuple[int, ...]:
# Rank like uv does: CPython first, newest version first, default build ahead of free-threaded and debug.
impl_order: Final[tuple[str, ...]] = ("cpython", "pypy", "graalpy", "pyodide")
Expand Down Expand Up @@ -560,21 +575,6 @@ def _iter_for_spec( # ruff:ignore[too-many-arguments, too-many-positional-argum
yield interpreter


@dataclass(**DC_KW)
class _UvKey:
# The ``<implementation>-<version>[+<variant>]-<os>-<arch>-<libc>`` name uv gives an install directory.
implementation: str
version: SimpleVersion
free_threaded: bool
debug: bool


@dataclass(**DC_KW)
class _UvInstall:
path: Path
key: _UvKey | None


__all__ = [
"LazyPathDump",
"get_interpreter",
Expand Down
66 changes: 33 additions & 33 deletions src/python_discovery/_py_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,6 @@
InfoValue = Union[str, int, bool, None, "tuple[int | str, ...]", "list[str]", "dict[str, str | int | None]"]


class VersionInfo(NamedTuple):
major: int
minor: int
micro: int
releaselevel: str
serial: int


_LOGGER: Final[logging.Logger] = logging.getLogger(__name__)


Expand Down Expand Up @@ -707,6 +699,39 @@ def sort_by(info: PythonInfo) -> int:
return sorted_discovered[0]


class VersionInfo(NamedTuple):
major: int
minor: int
micro: int
releaselevel: str
serial: int


def normalize_isa(isa: str) -> str:
"""
Normalize an ISA (instruction set architecture) string to a canonical form.

Known aliases are mapped (e.g. ``amd64`` → ``x86_64``, ``aarch64`` → ``arm64``).
Unrecognized values are lowercased and returned as-is.

:param isa: the architecture string as the platform reports it.
:returns: the normalized architecture name.
"""
low = isa.lower()
return {
"amd64": "x86_64",
"aarch64": "arm64",
"i386": "x86",
"i486": "x86",
"i586": "x86",
"i686": "x86",
"powerpc": "ppc",
"powerpc64": "ppc64",
"powerpc64le": "ppc64le",
"sparcv9": "sparc64",
}.get(low, low)


class MarkerEnvironment(TypedDict):
"""
Environment markers of an interpreter, as defined by PEP 508.
Expand Down Expand Up @@ -756,31 +781,6 @@ class MarkerEnvironment(TypedDict):
"""


def normalize_isa(isa: str) -> str:
"""
Normalize an ISA (instruction set architecture) string to a canonical form.

Known aliases are mapped (e.g. ``amd64`` → ``x86_64``, ``aarch64`` → ``arm64``).
Unrecognized values are lowercased and returned as-is.

:param isa: the architecture string as the platform reports it.
:returns: the normalized architecture name.
"""
low = isa.lower()
return {
"amd64": "x86_64",
"aarch64": "arm64",
"i386": "x86",
"i486": "x86",
"i586": "x86",
"i686": "x86",
"powerpc": "ppc",
"powerpc64": "ppc64",
"powerpc64le": "ppc64le",
"sparcv9": "sparc64",
}.get(low, low)


__all__ = [
"KNOWN_ARCHITECTURES",
"MarkerEnvironment",
Expand Down
3 changes: 2 additions & 1 deletion src/python_discovery/_py_info_collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
)


class PythonInfoCollector:
# Each attribute is a public PythonInfo field and a key of the cached JSON, so they stay flat.
class PythonInfoCollector: # simplint: ignore[too-many-attributes]
# Collects information about the currently running Python interpreter.
def __init__(self):
self._init_identity()
Expand Down
46 changes: 23 additions & 23 deletions src/python_discovery/_py_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,29 +112,6 @@ def _spec_from_match(
)


def _parse_specifier(string_spec: str) -> PythonSpec | None:
if not (match := _SPECIFIER_PATTERN.match(string_spec.strip())):
return None
spec_text = match["spec"].strip()
version_specifier = SpecifierSet.from_string(spec_text)
# the set never raises: it keeps an unparsable version as None and drops items without an operator
items = [item for item in spec_text.split(",") if item.strip()]
if len(items) != len(version_specifier.specifiers) or any(spec.version is None for spec in version_specifier):
msg = f"invalid version specifier {string_spec!r}"
raise ValueError(msg)
return _spec_from_match(
string_spec,
match,
(None, None, None),
# the version bounds say nothing about the build, so without a trailing t any build qualifies
threaded=True if match["threaded"] else None,
version_specifier=version_specifier,
)


_GET_REQUIRED_PRECISION_PATTERN: Final[re.Pattern[str]] = re.compile(r"a|b|rc")


class PythonSpec:
"""
Contains specification about a Python Interpreter.
Expand Down Expand Up @@ -317,6 +294,29 @@ def _get_required_precision(item: SimpleSpecifier) -> int | None:
return _GET_REQUIRED_PRECISION_PATTERN.split(item.version_str, maxsplit=1)[0].count(".") + 1


def _parse_specifier(string_spec: str) -> PythonSpec | None:
if not (match := _SPECIFIER_PATTERN.match(string_spec.strip())):
return None
spec_text = match["spec"].strip()
version_specifier = SpecifierSet.from_string(spec_text)
# the set never raises: it keeps an unparsable version as None and drops items without an operator
items = [item for item in spec_text.split(",") if item.strip()]
if len(items) != len(version_specifier.specifiers) or any(spec.version is None for spec in version_specifier):
msg = f"invalid version specifier {string_spec!r}"
raise ValueError(msg)
return _spec_from_match(
string_spec,
match,
(None, None, None),
# the version bounds say nothing about the build, so without a trailing t any build qualifies
threaded=True if match["threaded"] else None,
version_specifier=version_specifier,
)


_GET_REQUIRED_PRECISION_PATTERN: Final[re.Pattern[str]] = re.compile(r"a|b|rc")


__all__ = [
"KNOWN_IMPLEMENTATIONS",
"PythonSpec",
Expand Down
Loading