poetry-env.plugin.zsh
1277 bytes
1_togglePoetryShell() {
2 # Determine if currently in a Poetry-managed directory
3 local in_poetry_dir=0
4 if [[ -f "$PWD/pyproject.toml" && -f "$PWD/poetry.lock" ]]; then
5 in_poetry_dir=1
6 fi
7
8 # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory
9 if [[ $poetry_active -eq 1 ]] && { [[ $in_poetry_dir -eq 0 ]] || [[ "$PWD" != "$poetry_dir"* ]]; }; then
10 export poetry_active=0
11 unset poetry_dir
12 (( $+functions[deactivate] )) && deactivate
13 fi
14
15 # Activate the environment if in a Poetry directory and no environment is currently active
16 if [[ $in_poetry_dir -eq 1 ]] && [[ $poetry_active -ne 1 ]]; then
17 venv_dir=$(poetry env info --path 2>/dev/null)
18 # Handle case where poetry returns "." for in-project virtual environments
19 if [[ "$venv_dir" == "." ]]; then
20 venv_dir="$PWD/.venv"
21 fi
22 # Only proceed if venv_dir is set and the activate script exists
23 if [[ -n "$venv_dir" && -f "${venv_dir}/bin/activate" ]]; then
24 export poetry_active=1
25 export poetry_dir="$PWD"
26 source "${venv_dir}/bin/activate"
27 fi
28 fi
29}
30autoload -U add-zsh-hook
31add-zsh-hook chpwd _togglePoetryShell
32_togglePoetryShell # Initial call to check the current directory at shell startup