From d8eab422e10dec9ca441317985524d7cf09499ff Mon Sep 17 00:00:00 2001 From: Robert Crews Date: Fri, 1 Mar 2024 15:10:11 -0800 Subject: [PATCH] feat(python): Auto-activate venv when cd'ing into directory --- plugins/python/README.md | 12 +++++++++++- plugins/python/python.plugin.zsh | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/plugins/python/README.md b/plugins/python/README.md index 7bf1b34ac..c3b537f5d 100644 --- a/plugins/python/README.md +++ b/plugins/python/README.md @@ -22,8 +22,18 @@ plugins=(... python) ## Virtual environments -The plugin provides two utilities to manage Python venvs: +The plugin provides three utilities to manage Python venvs: - `mkv [name]`: make a new virtual environment called `name` (default: `venv`) in current directory. - `vrun [name]`: activate virtual environment called `name` (default: `venv`) in current directory. + +- `auto_vrun`: Automatically activate the venv virtual environment when + cd’ing into a directory containing `venv/bin/activate`, and + automatically deactivate the venv virtual environment when cd’ing into + any other directory. + - Set the environment variable `VENV_NAME` to auto-activate on a + different venv name. (Example: `VENV_NAME=.venv`). + - Set the environment variable `DISABLE_AUTO_VRUN` to anything to + deactivate `auto_vrun`. (Example: `DISABLE_AUTO_VRUN=true`) Unset + `DISABLE_AUTO_VRUN` to re-enable. diff --git a/plugins/python/python.plugin.zsh b/plugins/python/python.plugin.zsh index 77d4bf425..d36a75e00 100644 --- a/plugins/python/python.plugin.zsh +++ b/plugins/python/python.plugin.zsh @@ -81,3 +81,18 @@ function mkv() { echo >&2 "Created venv in '${venvpath}'" vrun "${name}" } + +# Virtual environment is assumed to be named "venv". +# Set VENV_NAME to another name if you use a different name, maybe ".venv". +# To disable, set DISABLE_AUTO_VRUN to anything. Unset to re-enable. +auto_vrun() { + [ $DISABLE_AUTO_VRUN ] && return 0 + local venvpath=${VENV_NAME:-'venv'} + if [ -e "${venvpath}/bin/activate" ]; then + source "${venvpath}/bin/activate" > /dev/null 2>&1 + else + [ -n "$(command -v deactivate)" ] && deactivate > /dev/null 2>&1 + fi +} +add-zsh-hook chpwd auto_vrun +auto_vrun