diff --git a/docs/changelog/+relative-exe-cache.bugfix.rst b/docs/changelog/+relative-exe-cache.bugfix.rst new file mode 100644 index 0000000..4578af9 --- /dev/null +++ b/docs/changelog/+relative-exe-cache.bugfix.rst @@ -0,0 +1,3 @@ +:meth:`~python_discovery.PythonInfo.from_exe` now keys its caches on the absolute executable path and copies cached +instances when ``executable`` differs, so relative paths follow working-directory changes and alternate path spellings +do not mutate previously returned :class:`~python_discovery.PythonInfo` objects. diff --git a/src/python_discovery/_cached_py_info.py b/src/python_discovery/_cached_py_info.py index d29dc43..44b50e9 100644 --- a/src/python_discovery/_cached_py_info.py +++ b/src/python_discovery/_cached_py_info.py @@ -3,6 +3,7 @@ from __future__ import annotations __lazy_modules__ = [ + "copy", "hashlib", "io", "pkgutil", @@ -17,6 +18,7 @@ f"{__spec__.parent}._windows", # ty: ignore[unresolved-attribute] # imported modules have a spec ] +import copy import hashlib import logging import os @@ -62,7 +64,7 @@ class CacheEntryMeta(TypedDict): _CACHE: Final[OrderedDict[tuple[Path, str | None], PythonInfo | Exception]] = OrderedDict() -_CACHE[Path(sys.executable), None] = PythonInfo() +_CACHE[Path(sys.executable).absolute(), None] = PythonInfo() _LOGGER: Final[logging.Logger] = logging.getLogger(__name__) _PY_INFO_SCRIPT: Final[Path] = Path(__file__).resolve().parent / "_py_info_collect.py" _MAX_QUERY_OUTPUT: Final[int] = 1 << 20 @@ -104,17 +106,19 @@ def _get_from_cache( # ruff:ignore[too-many-arguments] each argument is a separ ignore_cache: bool, executable_args: str | None, ) -> PythonInfo | Exception: - key = Path(exe), executable_args + path = Path(exe).absolute() + key = path, executable_args if not ignore_cache and key in _CACHE: result = _CACHE[key] else: - result = _get_via_file_cache(cls, cache, key[0], exe, env, executable_args=executable_args) - if _cacheable_result(key[0], result): + result = _get_via_file_cache(cls, cache, path, exe, env, executable_args=executable_args) + if _cacheable_result(path, result): _CACHE[key] = result else: _CACHE.pop(key, None) # with launcher arguments the queried binary is not the interpreter, so keep the one the query reported - if isinstance(result, PythonInfo) and executable_args is None: + if isinstance(result, PythonInfo) and executable_args is None and result.executable != exe: + result = copy.copy(result) result.executable = exe return result diff --git a/tests/python_discovery/test_cached_py_info.py b/tests/python_discovery/test_cached_py_info.py index 31306b1..881d0e2 100644 --- a/tests/python_discovery/test_cached_py_info.py +++ b/tests/python_discovery/test_cached_py_info.py @@ -8,7 +8,7 @@ from io import StringIO from os import read from pathlib import Path -from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired, list2cmdline +from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired, check_call, list2cmdline from threading import enumerate as active_threads from time import monotonic from typing import TYPE_CHECKING, Final @@ -773,3 +773,45 @@ def test_from_exe_timeout_with_inherited_pipes(tmp_path: Path) -> None: assert result is None assert monotonic() - started < 2.5 + + +@pytest.mark.parametrize("ignore_cache", [pytest.param(False, id="memory"), pytest.param(True, id="disk")]) +def test_from_exe_relative_path_follows_working_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ignore_cache: bool +) -> None: + rel_exe = Path("venv/Scripts/python.exe" if sys.platform == "win32" else "venv/bin/python") + first, second = tmp_path / "first", tmp_path / "second" + check_call([sys.executable, "-m", "venv", "--without-pip", str(first / "venv"), str(second / "venv")]) + if sys.platform == "win32": # pragma: win32 cover + mtime = (first / rel_exe).stat().st_mtime + os.utime(second / rel_exe, (mtime, mtime)) + cache = DiskCache(tmp_path / "cache") + + monkeypatch.chdir(first) + earlier = PythonInfo.from_exe(str(rel_exe), cache, ignore_cache=ignore_cache, resolve_to_host=False) + monkeypatch.chdir(second) + later = PythonInfo.from_exe(str(rel_exe), cache, ignore_cache=ignore_cache, resolve_to_host=False) + + assert earlier is not None + assert later is not None + assert (earlier.prefix, earlier.executable, later.prefix, later.executable) == ( + str(first / "venv"), + str(rel_exe), + str(second / "venv"), + str(rel_exe), + ) + + +def test_from_exe_leaves_cached_executable_untouched(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(PythonInfo, "_current", None) + current = PythonInfo.current() + exe_path = Path(sys.executable) + dotted = f"{exe_path.parent}{os.sep}.{os.sep}{exe_path.name}" + + via_dot = PythonInfo.from_exe(dotted, resolve_to_host=False) + monkeypatch.chdir(exe_path.parent) + via_rel = PythonInfo.from_exe(exe_path.name, resolve_to_host=False) + + assert via_dot is not None + assert via_rel is not None + assert (current.executable, via_dot.executable, via_rel.executable) == (sys.executable, dotted, exe_path.name)