virtualenvwrapper.plugin.zsh 2.6 KB

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