virtualenvwrapper.plugin.zsh 2.6 KB

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