Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodolphopivetta/d9b4513f30a0e00e282bd1e745e26324 to your computer and use it in GitHub Desktop.
Save rodolphopivetta/d9b4513f30a0e00e282bd1e745e26324 to your computer and use it in GitHub Desktop.
#!/bin/bash
# virtualenv-auto-activate.sh
#
# Installation:
# Add this line to your .bashrc or .bash-profile:
#
# source /path/to/virtualenv-auto-activate.sh
#
# Go to your project folder, run "virtualenv .venv", so your project folder
# has a .venv folder at the top level, next to your version control directory.
# For example:
# .
# ├── .git
# │   ├── HEAD
# │   ├── config
# │   ├── description
# │   ├── hooks
# │   ├── info
# │   ├── objects
# │   └── refs
# └── .venv
# ├── bin
# ├── include
# └── lib
#
# The virtualenv will be activated automatically when you enter the directory.
# If you use git as version control, maybe you'll want to activate the correct
# user/email for that repository, so you can add a bash script in .venv/bin
# directory to auto activate/change the user/email for git.
# For example:
# .
# ├── .git
# │   ├── HEAD
# │   ├── config
# │   ├── description
# │   ├── hooks
# │   ├── info
# │   ├── objects
# │   └── refs
# └── .venv
# ├── bin
# ├──── git_user.sh
# ├── include
# └── lib
_virtualenv_auto_activate() {
if [ -e ".venv" ]; then
# Check to see if already activated to avoid redundant activating
if [ "$VIRTUAL_ENV" != "$(pwd -P)/.venv" ]; then
_VENV_NAME=$(basename `pwd`)
echo Activating virtualenv \"$_VENV_NAME\"...
VIRTUAL_ENV_DISABLE_PROMPT=1
source .venv/bin/activate
if [ -e ".venv/bin/git_user.sh" ]; then
GIT_USER=$(cat .venv/bin/git_user.sh | grep -o -P '(?<=user.email ).*')
echo Activating git user for \"$GIT_USER\"
source .venv/bin/git_user.sh
fi
if [ -e ".git" ]; then
GIT_BRANCH=$(basename $(git symbolic-ref HEAD))
echo You are in branch $(tput setaf 2) $GIT_BRANCH $(tput sgr0)
fi
_OLD_VIRTUAL_PS1="$PS1"
PS1="($_VENV_NAME)$PS1"
export PS1
fi
fi
}
export PROMPT_COMMAND="_virtualenv_auto_activate; $PROMPT_COMMAND"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment