Skip to content

Instantly share code, notes, and snippets.

@pplante
Created September 4, 2014 23:26
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 pplante/81d4d40fadf3e205d1cf to your computer and use it in GitHub Desktop.
Save pplante/81d4d40fadf3e205d1cf to your computer and use it in GitHub Desktop.
# 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" ]; then
if [ -e "$WORKON_HOME/$ENV_NAME/bin/activate" ]; then
workon "$ENV_NAME" && export CD_VIRTUAL_ENV="$ENV_NAME"
fi
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 {
cd "$@" && workon_cwd
}
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
alias cd="venv_cd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment