Last active
July 19, 2024 16:18
-
-
Save fictorial/e56e1ad465a8be64f01c6e0b4c783e42 to your computer and use it in GitHub Desktop.
cd hook for zsh to activate a venv in the cwd
This file contains 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
function create-venv() { | |
name=$(basename $PWD) | |
venv_path="$HOME/.venvs/$name" | |
if [ -d "$venv_path" ]; then | |
echo "$venv_path already exists" | |
return | |
fi | |
python3 -m venv "$venv_path" | |
source "$venv_path/bin/activate" | |
pip install --upgrade pip | |
if [ -e "requirements.txt" ]; then | |
pip install -r requirements.txt | |
fi | |
} | |
function activate-closest-venv() { | |
declare -f deactivate > /dev/null && deactivate | |
check="$PWD" | |
while [ "$check" != "/" ]; do | |
base=$(basename $check) | |
[ -f "$HOME/.venvs/$base/bin/activate" ] && source "$HOME/.venvs/$base/bin/activate" && return | |
check=$(realpath "$check/..") | |
done | |
} | |
add-zsh-hook chpwd activate-closest-venv | |
cd $PWD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment