]> Sergey Matveev's repositories - zsh-autoenv.git/commitdiff
README: add Recipes section with .venv activation (#58)
authorDaniel Hahler <github@thequod.de>
Sun, 23 Apr 2017 22:41:27 +0000 (00:41 +0200)
committerGitHub <noreply@github.com>
Sun, 23 Apr 2017 22:41:27 +0000 (00:41 +0200)
README.md

index 8bb95cbbfa84f03ad47fd47d484d0f4e448ac735..519e0faa5ef89ad1bdb81371f2dbda1effe151e5 100644 (file)
--- a/README.md
+++ b/README.md
@@ -128,6 +128,54 @@ Enable debugging. Multiple levels are supported (max 2).
 
 Default: `0`
 
+## Recipes
+
+### Automatically activate Python virtualenvs
+
+Given `AUTOENV_FILE_ENTER=.autoenv.zsh`, `AUTOENV_FILE_LEAVE=.autoenv.zsh` and
+`AUTOENV_HANDLE_LEAVE=1` the following script will activate Python virtualenvs
+automatically in all subdirectories (`.venv` directories get used by
+[pipenv](https://github.com/kennethreitz/pipenv) with
+`PIPENV_VENV_IN_PROJECT=1`):
+
+```zsh
+# Environment file for all projects.
+#  - (de)activates Python virtualenvs (.venv) from pipenv
+
+if [[ $autoenv_event == 'enter' ]]; then
+  autoenv_source_parent
+
+  _my_autoenv_venv_chpwd() {
+    if [[ -z "$_ZSH_ACTIVATED_VIRTUALENV" && -n "$VIRTUAL_ENV" ]]; then
+      return
+    fi
+
+    local -a venv
+    venv=(./(../)#.venv(NY1:A))
+
+    if [[ -n "$_ZSH_ACTIVATED_VIRTUALENV" ]]; then
+      if ! (( $#venv )) || [[ "$_ZSH_ACTIVATED_VIRTUALENV" != "$venv[1]" ]]; then
+        echo "De-activating virtualenv: $VIRTUAL_ENV" >&2
+        deactivate
+        unset _ZSH_ACTIVATED_VIRTUALENV
+      fi
+    fi
+
+    if [[ -z "$VIRTUAL_ENV" ]]; then
+      if (( $#venv )); then
+        echo "Activating virtualenv: $venv" >&2
+        source $venv[1]/bin/activate
+        _ZSH_ACTIVATED_VIRTUALENV="$venv[1]"
+      fi
+    fi
+  }
+  autoload -U add-zsh-hook
+  add-zsh-hook chpwd _my_autoenv_venv_chpwd
+  _my_autoenv_venv_chpwd
+else
+  add-zsh-hook -d chpwd _my_autoenv_venv_chpwd
+fi
+```
 
 ## Related projects
 - https://github.com/direnv/direnv