Skip to content

Commit

Permalink
rename option virtualenvs.prefer-active-python and move whole logic…
Browse files Browse the repository at this point in the history
… to EnvManager.create_venv()
  • Loading branch information
finswimmer committed Dec 30, 2021
1 parent 411dc49 commit 5c65efd
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 51 deletions.
4 changes: 2 additions & 2 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ virtualenvs.in-project = null
virtualenvs.options.always-copy = true
virtualenvs.options.system-site-packages = false
virtualenvs.path = "{cache-dir}/virtualenvs" # /path/to/cache/directory/virtualenvs
virtualenvs.prefer-shell-python = false
virtualenvs.prefer-active-python = false
```

## Displaying a single configuration setting
Expand Down Expand Up @@ -189,7 +189,7 @@ Give the virtual environment access to the system site-packages directory.
Applies on virtualenv creation.
Defaults to `false`.

### `virtualenvs.prefer-shell-python`
### `virtualenvs.prefer-active-python`

**Type**: boolean

Expand Down
2 changes: 1 addition & 1 deletion docs/managing-environments.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pyenv install 3.9.8
pyenv local 3.9.8 # Activate Python 3.9 for the current project
poetry install
```
This requires setting the `virtualenvs.prefer-shell-python` option to `true`.
This requires setting the `virtualenvs.prefer-active-python` option to `true`.
{{% /note %}}

## Switching between environments
Expand Down
4 changes: 2 additions & 2 deletions src/poetry/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class Config:
"in-project": None,
"path": os.path.join("{cache-dir}", "virtualenvs"),
"options": {"always-copy": False, "system-site-packages": False},
"prefer-shell-python": False,
"prefer-active-python": False,
},
"experimental": {"new-installer": True},
"installer": {"parallel": True, "max-workers": None},
Expand Down Expand Up @@ -139,7 +139,7 @@ def _get_normalizer(name: str) -> Callable:
"virtualenvs.in-project",
"virtualenvs.options.always-copy",
"virtualenvs.options.system-site-packages",
"virtualenvs.options.prefer-shell-python",
"virtualenvs.options.prefer-active-python",
"experimental.new-installer",
"installer.parallel",
}:
Expand Down
41 changes: 1 addition & 40 deletions src/poetry/console/application.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import logging
import re
import subprocess

from contextlib import suppress
from importlib import import_module
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
Expand All @@ -18,14 +16,11 @@
from cleo.exceptions import CleoException
from cleo.formatters.style import Style
from cleo.io.inputs.argv_input import ArgvInput
from cleo.io.outputs.output import Verbosity
from poetry.core.utils._compat import PY37

from poetry.__version__ import __version__
from poetry.console.command_loader import CommandLoader
from poetry.console.commands.command import Command
from poetry.utils._compat import decode
from poetry.utils._compat import list_to_shell_command


if TYPE_CHECKING:
Expand Down Expand Up @@ -229,30 +224,6 @@ def _configure_io(self, io: "IO") -> None:

return super()._configure_io(io)

def _detect_active_python(self, io: "IO") -> str:
executable = None

try:
io.write_line(
"Trying to detect current active python executable as specified in the config.",
verbosity=Verbosity.VERBOSE,
)
executable = decode(
subprocess.check_output(
list_to_shell_command(
["python", "-c", '"import sys; print(sys.executable)"']
),
shell=True,
).strip()
)
io.write_line(f"Found: {executable}", verbosity=Verbosity.VERBOSE)
except CalledProcessError:
io.write_line(
"Unable to detect the current active python executable. Falling back to default.",
verbosity=Verbosity.VERBOSE,
)
return executable

def register_command_loggers(
self, event: "ConsoleCommandEvent", event_name: str, _: Any
) -> None:
Expand Down Expand Up @@ -311,18 +282,8 @@ def configure_env(
io = event.io
poetry = command.poetry

executable = (
self._detect_active_python(io)
if poetry.config.get("virtualenvs.prefer-shell-python")
else None
)

env_manager = EnvManager(poetry)
env = env_manager.create_venv(
io,
executable=executable,
find_compatible=True if executable else None,
)
env = env_manager.create_venv(io)

if env.is_venv() and io.is_verbose():
io.write_line(f"Using virtualenv: <comment>{env.path}</>")
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/console/commands/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def unique_config_values(self) -> Dict[str, Tuple[Any, Any, Any]]:
lambda val: str(Path(val)),
str(Path(CACHE_DIR) / "virtualenvs"),
),
"virtualenvs.prefer-shell-python": (
"virtualenvs.prefer-active-python": (
boolean_validator,
boolean_normalizer,
False,
Expand Down
34 changes: 32 additions & 2 deletions src/poetry/utils/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import tomlkit
import virtualenv

from cleo.io.outputs.output import Verbosity
from packaging.tags import Tag
from packaging.tags import interpreter_name
from packaging.tags import interpreter_version
Expand Down Expand Up @@ -456,6 +457,30 @@ class EnvManager:
def __init__(self, poetry: "Poetry") -> None:
self._poetry = poetry

def _detect_active_python(self, io: "IO") -> str:
executable = None

try:
io.write_line(
"Trying to detect current active python executable as specified in the config.",
verbosity=Verbosity.VERBOSE,
)
executable = decode(
subprocess.check_output(
list_to_shell_command(
["python", "-c", '"import sys; print(sys.executable)"']
),
shell=True,
).strip()
)
io.write_line(f"Found: {executable}", verbosity=Verbosity.VERBOSE)
except CalledProcessError:
io.write_line(
"Unable to detect the current active python executable. Falling back to default.",
verbosity=Verbosity.VERBOSE,
)
return executable

def activate(self, python: str, io: "IO") -> "Env":
venv_path = self._poetry.config.get("virtualenvs.path")
if venv_path is None:
Expand Down Expand Up @@ -767,7 +792,6 @@ def create_venv(
name: Optional[str] = None,
executable: Optional[str] = None,
force: bool = False,
find_compatible: Optional[bool] = None,
) -> Union["SystemEnv", "VirtualEnv"]:
if self._env is not None and not force:
return self._env
Expand All @@ -785,6 +809,12 @@ def create_venv(
create_venv = self._poetry.config.get("virtualenvs.create")
root_venv = self._poetry.config.get("virtualenvs.in-project")
venv_path = self._poetry.config.get("virtualenvs.path")
prefer_active_python = self._poetry.config.get(
"virtualenvs.prefer-active-python"
)

if not executable and prefer_active_python:
executable = self._detect_active_python(io)

if root_venv:
venv_path = cwd / ".venv"
Expand Down Expand Up @@ -821,7 +851,7 @@ def create_venv(
# If an executable has been specified, we stop there
# and notify the user of the incompatibility.
# Otherwise, we try to find a compatible Python version.
if executable and not find_compatible:
if executable and not prefer_active_python:
raise NoCompatiblePythonVersionFound(
self._poetry.package.python_versions, python_patch
)
Expand Down
6 changes: 3 additions & 3 deletions tests/console/commands/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_list_displays_default_value_if_not_set(
virtualenvs.options.always-copy = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = {venv_path} # {config_cache_dir / 'virtualenvs'}
virtualenvs.prefer-shell-python = false
virtualenvs.prefer-active-python = false
"""

assert expected == tester.io.fetch_output()
Expand All @@ -80,7 +80,7 @@ def test_list_displays_set_get_setting(
virtualenvs.options.always-copy = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = {venv_path} # {config_cache_dir / 'virtualenvs'}
virtualenvs.prefer-shell-python = false
virtualenvs.prefer-active-python = false
"""

assert config.set_config_source.call_count == 0
Expand Down Expand Up @@ -128,7 +128,7 @@ def test_list_displays_set_get_local_setting(
virtualenvs.options.always-copy = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = {venv_path} # {config_cache_dir / 'virtualenvs'}
virtualenvs.prefer-shell-python = false
virtualenvs.prefer-active-python = false
"""

assert config.set_config_source.call_count == 1
Expand Down

0 comments on commit 5c65efd

Please sign in to comment.