virtualenvwrapper.plugin.zsh 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. virtualenvwrapper='virtualenvwrapper.sh'
  2. if (( $+commands[$virtualenvwrapper] )); then
  3. source ${${virtualenvwrapper}:c}
  4. if [[ ! $DISABLE_VENV_CD -eq 1 ]]; then
  5. # Automatically activate Git projects's virtual environments based on the
  6. # directory name of the project. Virtual environment name can be overridden
  7. # by placing a .venv file in the project root with a virtualenv name in it
  8. function workon_cwd {
  9. if [ ! $WORKON_CWD ]; then
  10. WORKON_CWD=1
  11. # Check if this is a Git repo
  12. PROJECT_ROOT=`git rev-parse --show-toplevel 2> /dev/null`
  13. if (( $? != 0 )); then
  14. PROJECT_ROOT="."
  15. fi
  16. # Check for virtualenv name override
  17. if [[ -f "$PROJECT_ROOT/.venv" ]]; then
  18. ENV_NAME=`cat "$PROJECT_ROOT/.venv"`
  19. elif [[ -f "$PROJECT_ROOT/.venv/bin/activate" ]];then
  20. ENV_NAME="$PROJECT_ROOT/.venv"
  21. elif [[ "$PROJECT_ROOT" != "." ]]; then
  22. ENV_NAME=`basename "$PROJECT_ROOT"`
  23. else
  24. ENV_NAME=""
  25. fi
  26. if [[ "$ENV_NAME" != "" ]]; then
  27. # Activate the environment only if it is not already active
  28. if [[ "$VIRTUAL_ENV" != "$WORKON_HOME/$ENV_NAME" ]]; then
  29. if [[ -e "$WORKON_HOME/$ENV_NAME/bin/activate" ]]; then
  30. workon "$ENV_NAME" && export CD_VIRTUAL_ENV="$ENV_NAME"
  31. elif [[ -e "$ENV_NAME/bin/activate" ]]; then
  32. source $ENV_NAME/bin/activate && export CD_VIRTUAL_ENV="$ENV_NAME"
  33. fi
  34. fi
  35. elif [ $CD_VIRTUAL_ENV ]; then
  36. # We've just left the repo, deactivate the environment
  37. # Note: this only happens if the virtualenv was activated automatically
  38. deactivate && unset CD_VIRTUAL_ENV
  39. fi
  40. unset PROJECT_ROOT
  41. unset WORKON_CWD
  42. fi
  43. }
  44. # Append workon_cwd to the chpwd_functions array, so it will be called on cd
  45. # http://zsh.sourceforge.net/Doc/Release/Functions.html
  46. # TODO: replace with 'add-zsh-hook chpwd workon_cwd' when oh-my-zsh min version is raised above 4.3.4
  47. if (( ${+chpwd_functions} )); then
  48. if (( $chpwd_functions[(I)workon_cwd] == 0 )); then
  49. set -A chpwd_functions $chpwd_functions workon_cwd
  50. fi
  51. else
  52. set -A chpwd_functions workon_cwd
  53. fi
  54. fi
  55. else
  56. print "zsh virtualenvwrapper plugin: Cannot find ${virtualenvwrapper}. Please install with \`pip install virtualenvwrapper\`."
  57. fi