Created
March 15, 2018 11:46
-
-
Save husjon/0047e185485772c2b15246873903e26c to your computer and use it in GitHub Desktop.
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
# ~/.oh-my-zsh/custom/workon_cwd.zsh | |
function workon_cwd { | |
# Credits to: Harry Marr (https://hmarr.com/2010/jan/19/making-virtualenv-play-nice-with-git/) | |
cd $@ 2>/dev/null | |
# 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 | |
} | |
alias cd="workon_cwd" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment