diff --git a/docs/changelog/+unnameable-working-directory.bugfix.rst b/docs/changelog/+unnameable-working-directory.bugfix.rst new file mode 100644 index 0000000..578af01 --- /dev/null +++ b/docs/changelog/+unnameable-working-directory.bugfix.rst @@ -0,0 +1,2 @@ +:func:`~python_discovery.get_interpreter` no longer raises while resolving a ``pyenv`` shim when the working +directory was removed, or on illumos sits below an unreadable directory; it reads ``$PWD`` instead, as ``pyenv`` does. diff --git a/src/python_discovery/_discovery.py b/src/python_discovery/_discovery.py index 6e58f7f..5a8abbd 100644 --- a/src/python_discovery/_discovery.py +++ b/src/python_discovery/_discovery.py @@ -285,7 +285,12 @@ def _active_versions(env: Mapping[str, str]) -> Generator[str, None, None]: if pyenv_version := env.get("PYENV_VERSION"): yield from pyenv_version.split(":") return - if versions := _read_python_version_file(Path.cwd()): + cwd: str | Path | None + try: + cwd = Path.cwd() + except OSError: # removed, or on illumos below an unreadable directory; pyenv reads $PWD as well + cwd = env.get("PWD") + if cwd and (versions := _read_python_version_file(cwd)): yield from versions return if (pyenv_root := env.get("PYENV_ROOT")) and ( diff --git a/tests/python_discovery/test_discovery.py b/tests/python_discovery/test_discovery.py index 0d5de82..f754846 100644 --- a/tests/python_discovery/test_discovery.py +++ b/tests/python_discovery/test_discovery.py @@ -698,6 +698,24 @@ def test_shim_unreadable_python_version_file_is_skipped( assert pyenv_probed() == ("versions", "2.7.18") +@pytest.mark.parametrize("error", [FileNotFoundError, PermissionError]) +def test_shim_unnameable_working_directory_reads_pwd( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + pyenv_probed: Callable[[], tuple[str, ...]], + error: type[OSError], +) -> None: + root = Path(os.environ["PYENV_ROOT"]) + _create_versioned_binary(root, ("versions",), "2.7.15", "python2.7") + (root / "version").write_text("2.7.15\n", encoding="utf-8") + (tmp_path / ".python-version").write_text("2.7.18\n", encoding="utf-8") + monkeypatch.setenv("PWD", str(tmp_path / "removed")) + mocker.patch.object(Path, "cwd", autospec=True, side_effect=error) + + assert pyenv_probed() == ("versions", "2.7.18") + + @_POSIX_PERMISSIONS def test_shim_unsearchable_directory_is_skipped( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, pyenv_probed: Callable[[], tuple[str, ...]] @@ -705,6 +723,7 @@ def test_shim_unsearchable_directory_is_skipped( (tmp_path / ".python-version").write_text("2.7.18\n", encoding="utf-8") (work := tmp_path / "locked" / "work").mkdir(parents=True) monkeypatch.chdir(work) + monkeypatch.setenv("PWD", str(work)) work.parent.chmod(0o600) try: assert pyenv_probed() == ("versions", "2.7.18")