+
+# Gets a directory named .env or .venv if it exists in the currend directory or any of its parents
+get_env() {
+ if [ -d "$1/.env" ] ; then
+ echo "$1/.env"
+ else
+ if [ -d "$1/.venv" ] ; then
+ echo "$1/.venv"
+ else
+ if [ -d "$1/.." ] ; then
+ get_env "$1/.."
+ fi
+ fi
+ fi
+}
+
+get_absolute_path() {
+ python3 -c "import os; print(os.path.realpath('$1'))"
+}
+
+on_prompt() {
+ # Load a virtualenv environment if it exists in a file named .env
+ env_folder=$(get_env $(pwd))
+
+ if [ -d "$env_folder" ] ; then
+ if [[ $VIRTUAL_ENV != $(get_absolute_path $env_folder) ]] ; then
+ echo "Activating env '$env_folder'"
+ source "$env_folder/bin/activate"
+ fi
+ else
+ if [ -d "$VIRTUAL_ENV" ] ; then
+ deactivate
+ fi
+ fi
+}
+
+# Call on_prompt() every time the command prompt executes
+PROMPT_COMMAND=on_prompt
+
+# Set vi keybindings
+set -o vi
+
+# pip should only run if there is a virtualenv currently activated
+export PIP_REQUIRE_VIRTUALENV=true