Skip to content

Instantly share code, notes, and snippets.

@znorris
Created February 14, 2017 01:02
Show Gist options
  • Save znorris/a77ea0b8bb7c8c7601672a754690be76 to your computer and use it in GitHub Desktop.
Save znorris/a77ea0b8bb7c8c7601672a754690be76 to your computer and use it in GitHub Desktop.
[WIP] nearby auto-virtualenv plugin for oh my zsh.
##
## Looks for python virtualenv directories and activates them.
## If you've left a project directory where there is no
## virtualenv folder, the env will be disabled.
##
VENV_DIR=".venv"
CLOSEST_VENV=""
function closest_venv(){
# Requires `setopt extended_glob`
NEARBY_VENV=((../)#.venv(/Y1:a)) 2>/dev/null
if [[ -d $VENV_DIR ]]; then
echo "Found .venv in current dir"
CLOSEST_VENV="${PWD}/${VENV_DIR}"
elif $NEARBY_VENV; then
# Virtual env not in current dir
# There is a nearby virtual env
echo "Found .venv nearby"
CLOSEST_VENV=$NEARBY_VENV
else
echo "Did not find .venv"
CLOSEST_VENV=""
fi
echo ${CLOSEST_VENV}
}
clear_vars(){
NEARBY_VENV=""
CLOSEST_VENV=""
}
manage_venv() {
echo "Running manage_venv"
if [[ ! $CLOSEST_VENV && $VIRTUAL_ENV ]]; then
# We don't have a closest virtual env
# We have an active virtual env
echo "Deactivating"
deactivate
elif [[ ${CLOSEST_VENV} && ${VIRTUAL_ENV} && "${CLOSEST_VENV}" != "${VIRTUAL_ENV}" ]]; then
# We have a closest virtual env
# We have an active virtual env
# The closest virtual env is not active
echo "Deactivating to activate closer venv"
deactivate
source ${CLOSEST_VENV}/bin/activate
elif [[ ${CLOSEST_VENV} && ! ${VIRTUAL_ENV} ]]; then
# We have a closest virtual env
# We do not have an active virtual env
echo "Activating new venv"
source ${CLOSEST_VENV}/bin/activate
else
# Virtual env does not need to be changed
fi
}
function zach_workon_cwd() {
clear_vars
setopt extended_glob
closest_venv
manage_venv
}
# Append workon_cwd to the chpwd_functions array, so it will be called on cd
# http://zsh.sourceforge.net/Doc/Release/Functions.html
if ! (( $chpwd_functions[(I)zach_workon_cwd] )); then
chpwd_functions+=(zach_workon_cwd)
fi
# Using extended_glob
# setopt extended_glob
# get_opt(){
# # could be used to manage the `extended_glob` option
# }
@znorris
Copy link
Author

znorris commented Feb 14, 2017

Need to determine what's wrong with the conditional logic.
Notes [WIP]:
1a. We have no .venv in current directory
1b. We have no .venv nearby

2a. We have a .venv in current directory
2b. We don't care if a .venv is nearby

3a. We have no .venv in current directory
3b.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment