Skip to content

Instantly share code, notes, and snippets.

@pprince
Last active March 28, 2016 18:19
Show Gist options
  • Save pprince/d01d6eabde888a798875 to your computer and use it in GitHub Desktop.
Save pprince/d01d6eabde888a798875 to your computer and use it in GitHub Desktop.
virtualenvwrapper hooks to cleanly set/restore some variables when activating/deactivating a venv
#!/bin/sh
# This hook is sourced after every virtualenv is activated.
__vew_is_in_env () {
awk 'BEGIN { exit ! ("'"$1"'" in ENVIRON) }'
}
__vew_set_and_preserve () {
if __vew_is_in_env "$1" && ! __vew_is_in_env "__VEW_OLD_$1"; then
eval "__VEW_OLD_$1=\$$1"
export "__VEW_OLD_$1"
fi
eval "$1=$2"
export "$1"
}
__vew_project_dir=$(cat "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_PROJECT_FILENAME")
if [ -d "$__vew_project_dir" ]; then
if [ -f "$VIRTUAL_ENV/.perl6" ]; then
__vew_set_and_preserve "PERL6LIB" "$__vew_project_dir/lib"
fi
if [ -f "$VIRTUAL_ENV/.perl5" ]; then
__vew_set_and_preserve "PERL5LIB" "$__vew_project_dir/lib"
fi
if [ -f "$VIRTUAL_ENV/.perl" ]; then
__vew_set_and_preserve "PERLLIB" "$__vew_project_dir/lib"
fi
fi
unset -v __vew_project_dir
unset -f __vew_set_and_preserve
unset -f __vew_is_in_env
#!/bin/sh
# This hook is sourced before a virtualenv is deactivated.
__vew_is_in_env () {
awk 'BEGIN { exit ! ("'"$1"'" in ENVIRON) }'
}
__vew_restore_and_unset () {
if __vew_is_in_env "__VEW_OLD_$1"; then
eval "$1=\$__VEW_OLD_$1"
export "$1"
unset "__VEW_OLD_$1"
export "__VEW_OLD_$1"
else
unset "$1"
export "$1"
fi
}
__vew_project_dir=$(cat "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_PROJECT_FILENAME")
if [ -d "$__vew_project_dir" ]; then
if [ -f "$VIRTUAL_ENV/.perl6" ]; then
__vew_restore_and_unset "PERL6LIB"
fi
if [ -f "$VIRTUAL_ENV/.perl5" ]; then
__vew_restore_and_unset "PERL5LIB"
fi
if [ -f "$VIRTUAL_ENV/.perl" ]; then
__vew_restore_and_unset "PERLLIB"
fi
fi
unset -v __vew_project_dir
unset -f __vew_set_and_preserve
unset -f __vew_is_in_env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment