From d078fc78b8bf2ac39a262f60da2915e964f9d391 Mon Sep 17 00:00:00 2001 From: Brandon Rodriguez <brodriguez8774@gmail.com> Date: Tue, 30 Apr 2019 12:05:05 -0400 Subject: [PATCH] Create helper bash script --- helper_script.sh | 99 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 helper_script.sh diff --git a/helper_script.sh b/helper_script.sh new file mode 100644 index 0000000..fdcaaad --- /dev/null +++ b/helper_script.sh @@ -0,0 +1,99 @@ + +### + # Modified "cd" command to automatically load/unload Python ".venv" environments. + # :$1: The standard path to pass into the "cd" command. + ## +function cd() { + + # Check if .venv folder exists in path to final location. + local cd_string=$1 + local cd_path="" + local checked_current=false + + + # Check all sections of provided path. + for index in $(echo $cd_string | tr "/" "\n") + do + + # Check if we've looked at any paths yet. + if [[ "$cd_path" ]] + then + # Not first part of path. Simply concat index and prev path info. + cd_path="$cd_path/$index" + else + # First part of path. Check current folder, before anything else. + cd_path="$index" + + # Deactivate if backing out and .venv folder exists in current folder. + if [[ "$index" == ".." ]] + then + if [[ -d .venv ]] + then + cd_venv_deactivate + fi + fi + fi + + + # Check if current path equals home folder. If so, assume fresh start and deactivate. + if [[ "/$cd_path" == "$HOME" ]] + then + cd_venv_deactivate + fi + + + # If backing up, check for .venv in parent folder. + if [[ "$index" == ".." ]] + then + # Check for venv folder. + if [[ -d "$cd_path/.venv" ]] + then + cd_venv_deactivate + fi + else + # Otherwise, check if we're going into a new .venv. + if [[ -d "$cd_path/.venv" ]] + then + cd_venv_activate "./$cd_path/.venv" + fi + fi + + done + + + # Execute normal cd command. + builtin cd $1 + + + # Check for .venv folder in new directory. + if [[ -d ./.venv ]] + then + cd_venv_activate "./.venv" + fi +} + + +### + # Attempts to activate Python virtual environment. + # :$1: Path of folder for virtual environment (excluding the "/bin/activate" part). + ## +cd_venv_activate() { + + # First make sure no other environment is loaded. + cd_venv_deactivate + + # Load environment. + . "$1/bin/activate" +} + + +### + # Deactivates current Python virtual environment, if present. + ## +cd_venv_deactivate() { + # Check if environment is currently active. + if [[ -n "$VIRTUAL_ENV" ]] + then + deactivate + fi +} -- GitLab