22bbc233e90f18ad7a02625c66d1867a5486fcbb

Author
Michael Gonzo <feasuro@protonmail.com>
Committer
GitHub <noreply@github.com>
Date

Message

feat(python): autovenv keeps activated on subdirs (#12396)

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

Diff

 1diff --git a/plugins/python/README.md b/plugins/python/README.md
 2index c99697b22c1e1e4c2bd74df489722e0355619e31..b990a26b9c1dc3b1cf28c178b567584e84592f0f 100644
 3--- a/plugins/python/README.md
 4+++ b/plugins/python/README.md
 5@@ -32,8 +32,9 @@ virtual environments:
 6   `venv`) in the current directory.
 7 
 8 - `auto_vrun`: Automatically activate the venv virtual environment when entering a directory containing
 9-  `<venv-name>/bin/activate`, and automatically deactivate it when navigating out of it (including
10-  subdirectories!).
11+  `<venv-name>/bin/activate`, and automatically deactivate it when navigating out of it (keeps venv activated
12+  in subdirectories).
13   - To enable the feature, set `export PYTHON_AUTO_VRUN=true` before sourcing oh-my-zsh.
14-  - The default virtual environment name is `venv`. To use a different name, set
15+  - Plugin activates first virtual environment in lexicographic order whose name begins with `<venv-name>`.
16+    The default virtual environment name is `venv`. To use a different name, set
17     `export PYTHON_VENV_NAME=<venv-name>`. For example: `export PYTHON_VENV_NAME=".venv"`
18diff --git a/plugins/python/python.plugin.zsh b/plugins/python/python.plugin.zsh
19index f6ea85027cb4d8fe0969d15a718059a4910a896e..7256aa04f0379a8b7d67f4bd6ef45adc315060ef 100644
20--- a/plugins/python/python.plugin.zsh
21+++ b/plugins/python/python.plugin.zsh
22@@ -86,11 +86,20 @@ function mkv() {
23 
24 if [[ "$PYTHON_AUTO_VRUN" == "true" ]]; then
25   # Automatically activate venv when changing dir
26-  auto_vrun() {
27-    if [[ -f "${PYTHON_VENV_NAME}/bin/activate" ]]; then
28-      source "${PYTHON_VENV_NAME}/bin/activate" > /dev/null 2>&1
29-    else
30-      (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1
31+  function auto_vrun() {
32+    # deactivate if we're on a different dir than VIRTUAL_ENV states
33+    # we don't deactivate subdirectories!
34+    if (( $+functions[deactivate] )) && [[ $PWD != ${VIRTUAL_ENV:h}* ]]; then
35+      deactivate > /dev/null 2>&1
36+    fi
37+
38+    if [[ $PWD != ${VIRTUAL_ENV:h} ]]; then
39+      for _file in "${PYTHON_VENV_NAME}"*/bin/activate(N.); do
40+        # make sure we're not in a venv already
41+        (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1
42+        source $_file > /dev/null 2>&1
43+        break
44+      done
45     fi
46   }
47   add-zsh-hook chpwd auto_vrun