Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(virtualenv): improve virtual environment activation logic #204

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions autoswitch_virtualenv.plugin.zsh
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,19 @@ function _get_venv_name() {
printf "%s" "$venv_name"
}

# Function to ensure virtualenv bin is at the start of PATH
function _ensure_virtualenv_path() {
# Remove the current virtualenv from PATH if it exists
if [[ -n "$VIRTUAL_ENV" ]]; then
PATH=:$PATH:
PATH=${PATH//:$VIRTUAL_ENV\/bin:/:}
PATH=${PATH#:}
PATH=${PATH%:}
fi
# Add the new virtualenv to the start of PATH
PATH="$venv_dir/bin:$PATH"
}


function _maybeworkon() {
local venv_dir="$1"
Expand All @@ -86,9 +99,8 @@ function _maybeworkon() {
DEFAULT_MESSAGE_FORMAT="${DEFAULT_MESSAGE_FORMAT/🐍/}"
fi

# Don't reactivate an already activated virtual environment
if [[ -z "$VIRTUAL_ENV" || "$venv_name" != "$(_get_venv_name $VIRTUAL_ENV $venv_type)" ]]; then

# Check if we need to activate or reactivate the virtualenv
if [[ -z "$VIRTUAL_ENV" || "$venv_name" != "$(_get_venv_name $VIRTUAL_ENV $venv_type)" || "$PATH" != "$venv_dir/bin"* ]]; then
if [[ ! -d "$venv_dir" ]]; then
printf "Unable to find ${AUTOSWITCH_PURPLE}$venv_name${AUTOSWITCH_NORMAL} virtualenv\n"
printf "If the issue persists run ${AUTOSWITCH_PURPLE}rmvenv && mkvenv${AUTOSWITCH_NORMAL} in this directory\n"
Expand All @@ -110,8 +122,10 @@ function _maybeworkon() {

# Much faster to source the activate file directly rather than use the `workon` command
local activate_script="$venv_dir/bin/activate"

_validated_source "$activate_script"

# Ensure the virtualenv's bin directory is at the start of PATH
_ensure_virtualenv_path
fi
}

Expand Down