Skip to content

Instantly share code, notes, and snippets.

@unlockedmutex
Last active February 7, 2022 07:18
Show Gist options
  • Save unlockedmutex/cd7cf0b1c57f7c95b4576d0c0fe1d22b to your computer and use it in GitHub Desktop.
Save unlockedmutex/cd7cf0b1c57f7c95b4576d0c0fe1d22b to your computer and use it in GitHub Desktop.
Automatically enter/exit/hop pipenv virtualenvironments
# This will enter any virtualenvironment when there is a pipfile
# to be found in the current directory or a directory higher up
# in the hierarchy. It will exit if none is found, and switch if
# You cd into a different pipenv.
# Append this to your bashrc and it will work whenever you cd around
function search_up_pipfile {
ORIG_DIRECTORY=$PWD
if ! [[ -z $VIRTUAL_ENV ]]; then
TEMP_=$(echo $VIRTUAL_ENV | rev | cut -c10- | rev)
CURR_PIPENV=${TEMP_##*/}
fi
while [ $PWD != "/" ]; do
if [ -f "Pipfile" ]; then
NEW_PIPENV=${PWD##*/}
if ! [[ -z $CURR_PIPENV ]]; then
if [[ $NEW_PIPENV != $CURR_PIPENV ]]; then
return 1
fi
fi
builtin cd "$ORIG_DIRECTORY"
return 0
fi
builtin cd ..
done
builtin cd "$ORIG_DIRECTORY"
return 1
}
function activate_or_leave_pipenv {
if search_up_pipfile; then
if [[ -z $PIPENV_ACTIVE ]] ; then
pipenv shell;
return
fi
elif [[ -z $PIPENV_ACTIVE ]] ; then
return;
elif [ $PIPENV_ACTIVE == 1 ] ; then
touch "/tmp/PIPENV_EXIT_DIRECTORY"
echo "$(pwd)" >> "/tmp/PIPENV_EXIT_DIRECTORY"
exit;
fi
}
function cd_if_exiting_pipenv {
if [ -f "/tmp/PIPENV_EXIT_DIRECTORY" ] ; then
PIPENV_DIR="$(cat /tmp/PIPENV_EXIT_DIRECTORY)"
builtin cd "$PIPENV_DIR"
rm "/tmp/PIPENV_EXIT_DIRECTORY"
fi
}
export PROMPT_COMMAND="cd_if_exiting_pipenv; activate_or_leave_pipenv; $PROMPT_COMMAND"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment