2022-04-29 11:16:39 +02:00
|
|
|
mkvenv(){
|
2023-11-11 18:54:40 +01:00
|
|
|
local source_venv force_create venv_name
|
|
|
|
while getopts "sf" opt; do
|
|
|
|
case $opt in
|
|
|
|
s|source) source_venv=y ;;
|
|
|
|
f|force) force_create=y ;;
|
|
|
|
*) echo "Unknown option: $opt"; return 1 ;;
|
|
|
|
esac
|
|
|
|
done
|
|
|
|
|
|
|
|
echo "force=$force_create"
|
|
|
|
return
|
|
|
|
shift $(($OPTIND-1))
|
|
|
|
if [[ -n $1 ]]; then
|
|
|
|
venv_name=$1
|
2022-05-03 10:16:05 +02:00
|
|
|
shift
|
2022-04-29 11:16:39 +02:00
|
|
|
fi
|
2023-11-11 18:54:40 +01:00
|
|
|
# any other arguments are passed on to the `venv` module as flags/arguments
|
|
|
|
echo ${venv_name}
|
|
|
|
if [[ -e ${venv_name} ]]; then
|
|
|
|
if [[ -n ${force_create} ]]; then
|
|
|
|
if [[ -n $VIRTUAL_ENV ]]; then # deactivate venv if enabled
|
|
|
|
deactivate && info "Deactivated existing virtualenv" || red "Could not run deactivate";
|
|
|
|
fi
|
|
|
|
rm -rf ${venv_name} && info "Deleted existing virtualenv"
|
|
|
|
else
|
|
|
|
echo "$(color $RED Error:) $(color $BOLD .venv) already exists. Run with -f to recreate it." >&2
|
|
|
|
return 1
|
|
|
|
fi
|
2022-04-29 11:16:39 +02:00
|
|
|
fi
|
2022-05-03 10:16:05 +02:00
|
|
|
|
2023-11-11 18:54:40 +01:00
|
|
|
info "Creating virtualenv ${venv_name}... " && python -m virtualenv $@ ${venv_name}|| echo -e "Failed to create virtualenv. Is virtualenv installed? Try:\n $ pip install virtualenv"
|
2022-04-29 11:16:39 +02:00
|
|
|
if [[ -z ${source_venv} ]]; then
|
2023-11-11 18:54:40 +01:00
|
|
|
echo -n " done. Enable? [Y/n] "
|
2022-04-29 11:16:39 +02:00
|
|
|
read source_venv
|
2022-05-03 10:16:05 +02:00
|
|
|
else
|
|
|
|
echo ""
|
2022-04-29 11:16:39 +02:00
|
|
|
fi
|
|
|
|
|
|
|
|
if [[ $source_venv != "n" ]]; then
|
2023-11-11 18:54:40 +01:00
|
|
|
source ${venv_name}/bin/activate && echo -e " → $(color $BOLD Enabled!) 🐍 $(color $BOLD$PURPLE $(python --version | cut -d " " -f2 )) ($(color $BOLD$GREEN $(pip --version | cut -d " " -f -2)))"
|
2022-04-29 11:16:39 +02:00
|
|
|
fi
|
|
|
|
}
|
2023-09-14 22:57:38 +02:00
|
|
|
|
|
|
|
function enable_venv() {
|
|
|
|
local root
|
|
|
|
local activate
|
|
|
|
|
|
|
|
root=$(git rev-parse --show-toplevel 2>/dev/null)
|
|
|
|
if [[ -z $root ]]; then root=$PWD; fi
|
|
|
|
activate="$root/.venv/bin/activate"
|
|
|
|
if [[ -f "$activate" ]]; then
|
|
|
|
source "$activate"
|
|
|
|
fi
|
|
|
|
}
|
|
|
|
|
|
|
|
function disable_venv() {
|
|
|
|
if [[ -z ${VIRTUAL_ENV} ]]; then
|
|
|
|
return
|
|
|
|
fi
|
|
|
|
|
|
|
|
if [[ ! "$PWD" =~ $(dirname $VIRTUAL_ENV)}* ]]; then
|
|
|
|
echo "Deactivating venv..."
|
|
|
|
deactivate
|
|
|
|
fi
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if [[ -n $DOTFILES_AUTOSWITCH_VIRTUALENV ]]; then
|
|
|
|
add-zsh-hook chpwd enable_venv
|
|
|
|
add-zsh-hook chpwd disable_venv
|
|
|
|
|
|
|
|
enable_venv
|
|
|
|
fi
|