Coverage for src/governed_harness/profiles/interpreter.py: 95%

28 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""The project's Python interpreter (``toolchain.interpreter: auto``, since 2.0). 

2 

3The built-in Python validators run ``python -m pytest`` with the ``python`` on ``PATH``, which 

4in a project managed by uv or Poetry, or with a local virtual environment, is not the one that 

5has the project's dependencies. Discovery, in order: 

6 

71. ``.venv`` or ``venv`` in the workspace (``bin/python``, or ``Scripts/python.exe`` on 

8 Windows): the interpreter itself, by absolute path; 

92. ``uv.lock`` with ``uv`` on ``PATH``: ``uv run --no-sync python`` (uses the project 

10 environment without installing anything); 

113. ``poetry.lock`` with ``poetry`` on ``PATH``: ``poetry run python``. 

12 

13Nothing found keeps ``python``.""" 

14 

15from __future__ import annotations 

16 

17import shutil 

18from dataclasses import dataclass 

19from pathlib import Path 

20 

21PYTHON_NAMES = frozenset({"python", "python3"}) 

22 

23 

24@dataclass(frozen=True) 

25class DiscoveredInterpreter: 

26 argv: tuple[str, ...] 

27 source: str 

28 

29 @property 

30 def grant_scope(self) -> str: 

31 """The ``process.execute`` scope that authorizes exactly this interpreter prefix.""" 

32 return " ".join(self.argv) 

33 

34 

35def discover_python(workspace: Path) -> DiscoveredInterpreter | None: 

36 root = workspace.resolve() 

37 for directory in (".venv", "venv"): 

38 for relative in (("bin", "python"), ("Scripts", "python.exe")): 

39 candidate = root.joinpath(directory, *relative) 

40 if candidate.is_file(): 

41 return DiscoveredInterpreter((str(candidate),), f"{directory}/{'/'.join(relative)}") 

42 if (root / "uv.lock").is_file() and shutil.which("uv"): 

43 return DiscoveredInterpreter(("uv", "run", "--no-sync", "python"), "uv.lock") 

44 if (root / "poetry.lock").is_file() and shutil.which("poetry"): 44 ↛ 45line 44 didn't jump to line 45 because the condition on line 44 was never true

45 return DiscoveredInterpreter(("poetry", "run", "python"), "poetry.lock") 

46 return None 

47 

48 

49def with_interpreter( 

50 command: tuple[str, ...] | None, interpreter: DiscoveredInterpreter | None 

51) -> tuple[str, ...] | None: 

52 """``command`` with a leading ``python``/``python3`` replaced by the interpreter.""" 

53 if not command or interpreter is None or command[0] not in PYTHON_NAMES: 

54 return command 

55 return (*interpreter.argv, *command[1:])