From 593e8ed6c8b4686654e1ff059d1e8e345082c848 Mon Sep 17 00:00:00 2001 From: Ting-An Chen <73953029+nrps9909@users.noreply.github.com> Date: Sun, 6 Sep 2026 03:41:40 +0800 Subject: [PATCH] fix(poetry-env): preserve venv in project subdirectories (#13932) * fix(poetry-env): preserve venv in project subdirectories Keep the active environment while navigating ordinary project children, but switch when entering a nested Poetry project. Use a path-component boundary so similarly named sibling projects are not mistaken for subdirectories. Fixes #12377 * fix(poetry-env): normalize active project root --- plugins/poetry-env/README.md | 6 ++++-- plugins/poetry-env/poetry-env.plugin.zsh | 19 ++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/plugins/poetry-env/README.md b/plugins/poetry-env/README.md index bd99d2a91..03c50809b 100644 --- a/plugins/poetry-env/README.md +++ b/plugins/poetry-env/README.md @@ -1,7 +1,9 @@ # Poetry Environment Plugin -This plugin automatically changes poetry environment when you cd into or out of the project directory. -Note: Script looks for pyproject.toml file to determine poetry if its a poetry environment +This plugin automatically activates a Poetry environment when you enter a +directory containing both `pyproject.toml` and `poetry.lock`. It keeps the +environment active in project subdirectories, switches to nested Poetry +projects, and deactivates it when you leave the project tree. To use it, add `poetry-env` to the plugins array in your zshrc file: diff --git a/plugins/poetry-env/poetry-env.plugin.zsh b/plugins/poetry-env/poetry-env.plugin.zsh index 5f6fd4511..5949a048e 100644 --- a/plugins/poetry-env/poetry-env.plugin.zsh +++ b/plugins/poetry-env/poetry-env.plugin.zsh @@ -1,15 +1,24 @@ _togglePoetryShell() { # Determine if currently in a Poetry-managed directory local in_poetry_dir=0 + local in_active_poetry_dir=0 if [[ -f "$PWD/pyproject.toml" && -f "$PWD/poetry.lock" ]]; then in_poetry_dir=1 fi - # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory - if [[ $poetry_active -eq 1 ]] && { [[ $in_poetry_dir -eq 0 ]] || [[ "$PWD" != "$poetry_dir"* ]]; }; then - export poetry_active=0 - unset poetry_dir - (( $+functions[deactivate] )) && deactivate + # Deactivate when leaving the active project or entering a nested project + if [[ $poetry_active -eq 1 ]]; then + local project_dir="${poetry_dir%/}" + if [[ "$PWD" == "$project_dir" || "$PWD" == "$project_dir"/* ]]; then + in_active_poetry_dir=1 + fi + + if [[ $in_active_poetry_dir -eq 0 ]] || + { [[ $in_poetry_dir -eq 1 ]] && [[ "$PWD" != "$poetry_dir" ]]; }; then + export poetry_active=0 + unset poetry_dir + (( $+functions[deactivate] )) && deactivate + fi fi # Activate the environment if in a Poetry directory and no environment is currently active