From 5b5265d677c7c25b880f3792bbb3d80af5ee2d8f Mon Sep 17 00:00:00 2001 From: FazleArefin <1625934+FazleArefin@users.noreply.github.com> Date: Sun, 6 Sep 2026 04:13:45 +1000 Subject: [PATCH] feat(uv-env): add plugin for Astral's uv (#13914) * feat(uv-env): create plugin This plugin automatically activates/deactivates a uv-managed virtual environment when you cd into or out of a project directory. It looks for pyproject.toml and uv.lock to detect a uv project, and reads UV_PROJECT_ENVIRONMENT to support custom venv locations. * fix(uv-env): address review feedback from robbyrussell - Add `local` to venv_dir to prevent leaking into user's shell - Replace `export` with `typeset -g` for uv_active and uv_dir - Use `autoload -Uz` to match the style guide --- plugins/uv-env/README.md | 10 ++++++++++ plugins/uv-env/uv-env.plugin.zsh | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 plugins/uv-env/README.md create mode 100644 plugins/uv-env/uv-env.plugin.zsh diff --git a/plugins/uv-env/README.md b/plugins/uv-env/README.md new file mode 100644 index 000000000..8502e80a9 --- /dev/null +++ b/plugins/uv-env/README.md @@ -0,0 +1,10 @@ +# uv Environment Plugin + +This plugin automatically activates the uv virtual environment when you cd into a project directory, and deactivates it when you cd out. +Note: Script looks for pyproject.toml and uv.lock files to determine if it's a uv project + +To use it, add `uv-env` to the plugins array in your zshrc file: + +```zsh +plugins=(... uv-env) +``` diff --git a/plugins/uv-env/uv-env.plugin.zsh b/plugins/uv-env/uv-env.plugin.zsh new file mode 100644 index 000000000..dad589ecf --- /dev/null +++ b/plugins/uv-env/uv-env.plugin.zsh @@ -0,0 +1,26 @@ +_toggleUvShell() { + local in_uv_dir=0 + if [[ -f "$PWD/pyproject.toml" && -f "$PWD/uv.lock" ]]; then + in_uv_dir=1 + fi + + if [[ $uv_active -eq 1 ]] && { [[ $in_uv_dir -eq 0 ]] || [[ "$PWD" != "$uv_dir" && "$PWD" != "$uv_dir"/* ]]; }; then + typeset -g uv_active=0 + unset uv_dir + (( $+functions[deactivate] )) && deactivate + fi + + if [[ $in_uv_dir -eq 1 ]] && [[ $uv_active -ne 1 ]]; then + local venv_dir="${UV_PROJECT_ENVIRONMENT:-$PWD/.venv}" + [[ "$venv_dir" != /* ]] && venv_dir="$PWD/$venv_dir" + + if [[ -f "${venv_dir}/bin/activate" ]]; then + typeset -g uv_active=1 + typeset -g uv_dir="$PWD" + source "${venv_dir}/bin/activate" + fi + fi +} +autoload -Uz add-zsh-hook +add-zsh-hook chpwd _toggleUvShell +_toggleUvShell