Created
July 4, 2025 02:56
-
-
Save ashwch/507c612cc31de5993ea4d82fb9af3daa to your computer and use it in GitHub Desktop.
auto_uv_env shell function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| command -v uv >/dev/null 2>&1 && { | |
| auto_uv_env() { | |
| # Early exit for performance - check if we're in a Python project | |
| if [[ -f "pyproject.toml" ]]; then | |
| local py_version="" | |
| # Parse Python version requirement from common pyproject.toml patterns | |
| # Supports: requires-python = ">=3.11", python_requires = ">=3.11.5", etc. | |
| if grep -q "requires-python" pyproject.toml; then | |
| py_version=$(grep "requires-python" pyproject.toml | sed -E 's/.*[">]=?([0-9]+\.[0-9]+(\.[0-9]+)?).*/\1/' | head -1) | |
| elif grep -q "python_requires" pyproject.toml; then | |
| py_version=$(grep "python_requires" pyproject.toml | sed -E 's/.*[">]=?([0-9]+\.[0-9]+(\.[0-9]+)?).*/\1/' | head -1) | |
| fi | |
| # Create virtual environment if it doesn't exist | |
| if [[ ! -d ".venv" ]]; then | |
| if [[ -n "$py_version" ]]; then | |
| echo "π Setting up Python $py_version environment with UV..." | |
| # Install Python version if needed (UV handles this efficiently) | |
| uv python install "$py_version" 2>/dev/null || echo "Python $py_version already available" | |
| # Create venv with specific Python version | |
| uv venv --python "$py_version" || { | |
| echo "β Failed to create venv with Python $py_version, using default" | |
| uv venv | |
| } | |
| else | |
| echo "π Creating default Python environment with UV..." | |
| uv venv | |
| fi | |
| echo "β Virtual environment created" | |
| fi | |
| # Activate venv if exists and we're not already in the correct one | |
| # Performance: Only activate if path doesn't match current VIRTUAL_ENV | |
| if [[ -f ".venv/bin/activate" ]] && [[ "$VIRTUAL_ENV" != "$PWD/.venv" ]]; then | |
| source .venv/bin/activate | |
| echo "π Activated Python environment ($(python --version 2>/dev/null || echo "unknown"))" | |
| fi | |
| elif [[ -n "$VIRTUAL_ENV" ]] && [[ ! -f "pyproject.toml" ]]; then | |
| # Deactivate when leaving Python projects (smart cleanup) | |
| deactivate 2>/dev/null | |
| echo "β¬οΈ Deactivated Python environment" | |
| fi | |
| } | |
| # Register directory change hook for automatic activation | |
| # This runs auto_uv_env every time you cd into a directory | |
| autoload -U add-zsh-hook | |
| add-zsh-hook chpwd auto_uv_env | |
| # Run on shell startup if already in a Python project | |
| auto_uv_env | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment