From d7dd980970fd8d4abeeb66e25caef2ee96bab0b2 Mon Sep 17 00:00:00 2001 From: kang Date: Sun, 18 Jan 2026 20:15:31 +0800 Subject: [PATCH] feat(python): add recursive parent directory search for auto_vrun Add PYTHON_AUTO_VRUN_RECURSIVE option to search parent directories for virtual environments, useful for monorepos where venv is at project root but you work in subdirectories. --- plugins/python/README.md | 1 + plugins/python/python.plugin.zsh | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/plugins/python/README.md b/plugins/python/README.md index ca424ea55..2727e81cd 100644 --- a/plugins/python/README.md +++ b/plugins/python/README.md @@ -34,6 +34,7 @@ virtual environments: `/bin/activate`, and automatically deactivate it when navigating out of it (keeps venv activated in subdirectories). - To enable the feature, set `PYTHON_AUTO_VRUN=true` before sourcing oh-my-zsh. + - To also search parent directories (useful for monorepos), set `PYTHON_AUTO_VRUN_RECURSIVE=true` as well. - The plugin activates the first existing virtual environment, in order, appearing in `$PYTHON_VENV_NAMES`. The default virtual environment name is `venv`. To use a different name, set `PYTHON_VENV_NAME=`. For example: `PYTHON_VENV_NAME=".venv"` diff --git a/plugins/python/python.plugin.zsh b/plugins/python/python.plugin.zsh index 2b139ddf0..b2ca11f2f 100644 --- a/plugins/python/python.plugin.zsh +++ b/plugins/python/python.plugin.zsh @@ -113,8 +113,21 @@ if [[ "$PYTHON_AUTO_VRUN" == "true" ]]; then # make sure we're not in a venv already (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1 source $file > /dev/null 2>&1 - break + return done + + # Search parent directories if recursive mode is enabled + if [[ "$PYTHON_AUTO_VRUN_RECURSIVE" == "true" ]]; then + local search_dir="$PWD:h" + while [[ "$search_dir" != "/" && "$search_dir" != "." ]]; do + for file in "${search_dir}/"${^PYTHON_VENV_NAMES[@]}"/bin/activate"(N.); do + (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1 + source $file > /dev/null 2>&1 + return + done + search_dir="${search_dir:h}" + done + fi fi } add-zsh-hook chpwd auto_vrun