31f2025e0fa963788655fe197e0179c47588b175

Author
Kate Sullivan <75387802+katesullivan@users.noreply.github.com>
Committer
GitHub <noreply@github.com>
Date

Message

feat(poetry-env): support changing between two venv dirs (#12346)

Co-authored-by: Carlo Sala <carlosalag@protonmail.com>

Diff

 1diff --git a/plugins/poetry-env/poetry-env.plugin.zsh b/plugins/poetry-env/poetry-env.plugin.zsh
 2index 97ca524921919680554036006de251af6840a40a..f98c177b4eaff11e50ad5f933b34e15694bba6c3 100644
 3--- a/plugins/poetry-env/poetry-env.plugin.zsh
 4+++ b/plugins/poetry-env/poetry-env.plugin.zsh
 5@@ -1,27 +1,27 @@
 6-# Automatic poetry environment activation/deactivation
 7 _togglePoetryShell() {
 8-  # deactivate environment if pyproject.toml doesn't exist and not in a subdir
 9-  if [[ ! -f "$PWD/pyproject.toml" ]] ; then
10-    if [[ "$poetry_active" == 1 ]]; then
11-      if [[ "$PWD" != "$poetry_dir"* ]]; then
12-        export poetry_active=0
13-        deactivate
14-        return
15-      fi
16-    fi
17+  # Determine if currently in a Poetry-managed directory
18+  local in_poetry_dir=0
19+  if [[ -f "$PWD/pyproject.toml" ]] && grep -q 'tool.poetry' "$PWD/pyproject.toml"; then
20+    in_poetry_dir=1
21+  fi
22+
23+  # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory
24+  if [[ $poetry_active -eq 1 ]] && { [[ $in_poetry_dir -eq 0 ]] || [[ "$PWD" != "$poetry_dir"* ]]; }; then
25+    export poetry_active=0
26+    unset poetry_dir
27+    deactivate
28   fi
29 
30-  # activate the environment if pyproject.toml exists
31-  if [[ "$poetry_active" != 1 ]]; then
32-    if [[ -f "$PWD/pyproject.toml" ]]; then
33-      if grep -q 'tool.poetry' "$PWD/pyproject.toml" && venv_dir=$(poetry env info --path); then
34-        export poetry_active=1
35-        export poetry_dir="$PWD"
36-        source "${venv_dir}/bin/activate"
37-      fi
38+  # Activate the environment if in a Poetry directory and no environment is currently active
39+  if [[ $in_poetry_dir -eq 1 ]] && [[ $poetry_active -ne 1 ]]; then
40+    venv_dir=$(poetry env info --path 2>/dev/null)
41+    if [[ -n "$venv_dir" ]]; then
42+      export poetry_active=1
43+      export poetry_dir="$PWD"
44+      source "${venv_dir}/bin/activate"
45     fi
46   fi
47 }
48 autoload -U add-zsh-hook
49 add-zsh-hook chpwd _togglePoetryShell
50-_togglePoetryShell
51+_togglePoetryShell # Initial call to check the current directory at shell startup