poetry-env.plugin.zsh 1012 B

123456789101112131415161718192021222324252627
  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 ]] && [[ "$PWD" != "$poetry_dir"* ]]; }; then
  9. export poetry_active=0
  10. unset poetry_dir
  11. deactivate
  12. fi
  13. # Activate the environment if in a Poetry directory and no environment is currently active
  14. if [[ $in_poetry_dir -eq 1 ]] && [[ $poetry_active -ne 1 ]]; then
  15. venv_dir=$(poetry env info --path 2>/dev/null)
  16. if [[ -n "$venv_dir" ]]; then
  17. export poetry_active=1
  18. export poetry_dir="$PWD"
  19. source "${venv_dir}/bin/activate"
  20. fi
  21. fi
  22. }
  23. autoload -U add-zsh-hook
  24. add-zsh-hook chpwd _togglePoetryShell
  25. _togglePoetryShell # Initial call to check the current directory at shell startup