Skip to content

Instantly share code, notes, and snippets.

@sefk
Forked from swanson/.bashrc
Created August 15, 2013 08:02
Show Gist options
  • Save sefk/6239102 to your computer and use it in GitHub Desktop.
Save sefk/6239102 to your computer and use it in GitHub Desktop.
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
# 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"`
PROJECT_LANGUAGE=`sloccount . 2>/dev/null | grep '%' | head -n 1| cut -d : -f 1`
if [ "$PROJECT_LANGUAGE" != "python" ]; then
return
fi
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
}
alias cd="venv_cd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment