From 12a6ce7e42f1c05001c42190bad95410fe64104f Mon Sep 17 00:00:00 2001 From: kang Date: Thu, 26 Nov 2026 23:20:36 +0800 Subject: [PATCH] feat(python): add recursive parent directory search for auto_vrun (#13523) --- plugins/python/README.md | 2 ++ plugins/python/python.plugin.zsh | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/plugins/python/README.md b/plugins/python/README.md index ca424ea55..beab84a01 100644 --- a/plugins/python/README.md +++ b/plugins/python/README.md @@ -34,6 +34,8 @@ 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 search stops before `$HOME`, so a venv in your home directory is not activated in every folder under it. - 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 e96363b9b..562b19e78 100644 --- a/plugins/python/python.plugin.zsh +++ b/plugins/python/python.plugin.zsh @@ -113,8 +113,23 @@ 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, stopping before $HOME + if [[ "$PYTHON_AUTO_VRUN_RECURSIVE" == "true" ]]; then + local search_dir="$PWD:h" + while [[ "$search_dir" != "/" && "$search_dir" != "." && "$search_dir" != "$HOME" ]]; do + for file in "${search_dir}/"${^PYTHON_VENV_NAMES[@]}"/bin/activate"(N.); do + # the venv found is already active + [[ "${file:h:h:A}" == "${VIRTUAL_ENV:A}" ]] && return + (( $+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