Skip to content

Instantly share code, notes, and snippets.

@awbacker
Created March 24, 2023 09:12
Show Gist options
  • Save awbacker/e7a99a2b2a4604d0e00324c37590f9fb to your computer and use it in GitHub Desktop.
Save awbacker/e7a99a2b2a4604d0e00324c37590f9fb to your computer and use it in GitHub Desktop.
Shell function to enable the "logical" virtualenv based on your current directory
function venvnow() {
GREEN="\033[0;32m"
NC='\033[0m' # No Color
venv_default_root=~/dev/venvs
function try_dotvenv {
if [ -d '.venv' ]; then
echo -e " - found ${GREEN}.venv${NC} directory"
if [ -f ".venv/bin/activate" ]; then
source .venv/bin/activate
echo -e " - success (${GREEN}.venv${NC})"
return 0
fi
fi
if [ -f '.venv' ]; then
venv_name=$(<.venv)
echo -e " - found .venv file (${GREEN}$venv_name${NC})"
if [ -f "$venv_default_root/$venv_name/bin/activate" ]; then
source $venv_default_root/$venv_name/bin/activate
echo -e " - success ($venv_default_root/${GREEN}$venv_name${NC})"
return 0
fi
if [ -f "./$venv_name/bin/activate/" ]; then
source ./$venv_name/bin/activate
echo -e " - success (./${GREEN}$venv_name${NC})"
return 0
fi
fi
return 1
}
function try_pipenv {
if [ -f "Pipfile" ]; then
source $(pipenv --venv)/bin/activate
echo -e " - success (${GREEN}pipenv${NC})"
return 0
fi
return 1
}
function try_local_venv {
if [ -d venv ]; then
echo -e " - found local ${GREEN}./venv/${NC}, using that"
source ./venv/bin/activate
return 0
fi
return 1
}
function try_dirname {
cur_dir=`pwd`
venv_name=$(basename "$cur_dir")
if [ -d $venv_default_root/$venv_name ]; then
echo " - using current directory name: $venv_name"
echo " - $venv_default_root/${GREEN}$venv_name${NC}"
source $venv_default_root/$venv_name/bin/activate
return 0
fi
return 1
}
if try_pipenv ; then return 0; fi
if try_dotvenv ; then return 0; fi
if try_local_venv ; then return 0; fi
if try_dirname ; then return 0; fi
echo " - unable to set venv"
return 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment