Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@akheron
Last active September 19, 2015 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akheron/777e2c991a788e3e7ee5 to your computer and use it in GitHub Desktop.
Save akheron/777e2c991a788e3e7ee5 to your computer and use it in GitHub Desktop.
Automatically activate Git projects' virtual environments
# Automatically activate Git projects' virtual environments based on the
# directory name of the project. Virtual environment name can be overridden
# by placing a .venv file in the project root with a virtualenv name in it
function workon_cwd {
# Check that this is a Git repo
GIT_DIR=`git rev-parse --git-dir 2> /dev/null`
if [ $? == 0 ]; then
# Find the repo root and check for virtualenv name override
GIT_DIR=`\cd $GIT_DIR; pwd`
PROJECT_ROOT=`dirname "$GIT_DIR"`
ENV_NAME=`basename "$PROJECT_ROOT"`
if [ -f "$PROJECT_ROOT/.venv" ]; then
ENV_NAME=`cat "$PROJECT_ROOT/.venv"`
fi
# Activate the environment only if it is not already active
if [ "$VIRTUAL_ENV" != "$WORKON_HOME/$ENV_NAME" -a -e "$WORKON_HOME/$ENV_NAME/bin/activate" ]; then
workon "$ENV_NAME" && export CD_VIRTUAL_ENV="$ENV_NAME"
elif [ "$VIRTUAL_ENV" != "$PROJECT_ROOT/venv" -a -e "$PROJECT_ROOT/venv/bin/activate" ]; then
. "$PROJECT_ROOT/venv/bin/activate" && export CD_VIRTUAL_ENV="$PROJECT_ROOT/venv"
fi
elif [ $CD_VIRTUAL_ENV ]; then
# We've just left the repo, deactivate the environment
# Note: this only happens if the virtualenv was activated automatically
deactivate && unset CD_VIRTUAL_ENV
fi
}
# New cd function that does the virtualenv magic
function venv_cd {
if [ ! $IN_VENV_CD ]; then
# Prevent recursion
export IN_VENV_CD=1
cd "$@" && workon_cwd
unset IN_VENV_CD
fi
}
alias cd="venv_cd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment