virtualenvwrapper.plugin.zsh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. virtualenvwrapper='virtualenvwrapper_lazy.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 [[ "$PROJECT_ROOT" != "." ]]; then
  20. ENV_NAME=`basename "$PROJECT_ROOT"`
  21. else
  22. ENV_NAME=""
  23. fi
  24. if [[ "$ENV_NAME" != "" ]]; then
  25. # Activate the environment only if it is not already active
  26. if [[ "$VIRTUAL_ENV" != "$WORKON_HOME/$ENV_NAME" ]]; then
  27. if [[ -e "$WORKON_HOME/$ENV_NAME/bin/activate" ]]; then
  28. workon "$ENV_NAME" && export CD_VIRTUAL_ENV="$ENV_NAME"
  29. fi
  30. fi
  31. elif [ $CD_VIRTUAL_ENV ]; then
  32. # We've just left the repo, deactivate the environment
  33. # Note: this only happens if the virtualenv was activated automatically
  34. deactivate && unset CD_VIRTUAL_ENV
  35. fi
  36. unset PROJECT_ROOT
  37. unset WORKON_CWD
  38. fi
  39. }
  40. # Append workon_cwd to the chpwd_functions array, so it will be called on cd
  41. # http://zsh.sourceforge.net/Doc/Release/Functions.html
  42. # TODO: replace with 'add-zsh-hook chpwd workon_cwd' when oh-my-zsh min version is raised above 4.3.4
  43. if (( ${+chpwd_functions} )); then
  44. if (( $chpwd_functions[(I)workon_cwd] == 0 )); then
  45. set -A chpwd_functions $chpwd_functions workon_cwd
  46. fi
  47. else
  48. set -A chpwd_functions workon_cwd
  49. fi
  50. fi
  51. else
  52. print "zsh virtualenvwrapper plugin: Cannot find ${virtualenvwrapper}. Please install with \`pip install virtualenvwrapper\`."
  53. fi