-
-
Save defrank/9c513056f7246d70758cb8ae1c90e823 to your computer and use it in GitHub Desktop.
Override builtin cd to source closest virtual environment
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
# Source closest virtual environment, ``venv``, if exists in any parent | |
# directory. | |
cd () { | |
local venv_dir="venv" prevpwd="$PWD" | |
builtin cd "$@" | |
if [ "$prevpwd" != "$PWD" ]; then | |
local base_dir="$PWD" | |
# Always try to deactivate for nested virtual environments. | |
deactivate &>/dev/null | |
# Find the closest parent directory with ``venv``. | |
while [[ ! -d "$base_dir/$venv_dir" ]] && [[ "$base_dir" != '/' ]]; do | |
base_dir="$(dirname "$base_dir")" | |
done | |
# Source virtual environment if it exists. | |
if [[ -f "$base_dir/$venv_dir/bin/activate" ]]; then | |
source "$base_dir/$venv_dir/bin/activate" | |
fi | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment