poetry-env.plugin.zsh 1.0 KB

12345678910111213141516171819202122232425262728
  1. _togglePoetryShell() {
  2. # Determine if currently in a Poetry-managed directory
  3. local in_poetry_dir=0
  4. if [[ -f "$PWD/pyproject.toml" ]] && grep -q 'tool.poetry' "$PWD/pyproject.toml"; then
  5. in_poetry_dir=1
  6. fi
  7. # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory
  8. if [[ $poetry_active -eq 1 ]] && [[ $in_poetry_dir -eq 0 ]] \
  9. && [[ "$PWD" != "$poetry_dir"* ]]; then
  10. export poetry_active=0
  11. unset poetry_dir
  12. (( $+functions[deactivate] )) && deactivate
  13. fi
  14. # Activate the environment if in a Poetry directory and no environment is currently active
  15. if [[ $in_poetry_dir -eq 1 ]] && [[ $poetry_active -ne 1 ]]; then
  16. venv_dir=$(poetry env info --path 2>/dev/null)
  17. if [[ -n "$venv_dir" ]]; then
  18. export poetry_active=1
  19. export poetry_dir="$PWD"
  20. source "${venv_dir}/bin/activate"
  21. fi
  22. fi
  23. }
  24. autoload -U add-zsh-hook
  25. add-zsh-hook chpwd _togglePoetryShell
  26. _togglePoetryShell # Initial call to check the current directory at shell startup