1
0
Fork 0
dotfiles/.local/share/zsh/plugins/autopyenv/autopyenv.plugin.zsh

40 lines
1.3 KiB
Bash
Raw Normal View History

2022-08-03 00:31:29 +02:00
PYENV_DIR="${PYENVS_HOME:-${XDG_DATA_HOME:-$HOME/.local/share}/virtualenv}"
2022-08-02 14:46:25 +02:00
function chpwd_activate(){
2022-08-03 12:11:47 +02:00
[[ "$(pwd)" == "/" ]] && return 0
2022-08-02 14:46:25 +02:00
for pydir in $(ls $PYENV_DIR); do
if [[ "$(pwd|sed -e s@/@_@g|cut -c2-)" =~ "^$pydir$" ]] || [[ "r-$(pwd|sed -e s@/@_@g|cut -c2-)" =~ "^$pydir" ]]; then
2022-08-02 14:46:25 +02:00
if [ "x$VIRTUAL_ENV" != "x$PYENV_DIR/$pydir" ]; then
2022-08-03 13:12:28 +02:00
export PS1="$PS1"
export VIRTUAL_ENV_DISABLE_PROMPT=1
2022-08-02 14:46:25 +02:00
source "$PYENV_DIR/$pydir/bin/activate"
fi
return
2022-08-02 14:46:25 +02:00
fi
done
2022-08-03 13:12:28 +02:00
if [ "x$VIRTUAL_ENV" != "x" ]; then
unset VIRTUAL_ENV_DISABLE_PROMPT
export PS1="${PS1:3}"
deactivate
fi
2022-08-02 14:46:25 +02:00
}
function venv(){
2022-08-03 12:11:47 +02:00
[[ "$(pwd)" == "/" ]] && echo "Cannot create venv at root" && return 1
[[ "$(pwd)" != "/" ]] && envdir=$(pwd|sed -e s@/@_@g|cut -c2-)
[[ "$1" == "-r" ]] && envdir="r-$envdir" # create a venv that will be activated for all subdirectories as well
2022-08-02 14:46:25 +02:00
if [ ! -e "$PYENV_DIR/${envdir}" ]; then
echo "Creating python venv for ${envdir}.."
mkdir "$PYENV_DIR" -p
python3 -m venv "$PYENV_DIR/${envdir}"
echo "Activating virtual env ${envdir}"
[[ ! ${PS1:0:3} == "  " ]] && export PS1="$PS1"
export VIRTUAL_ENV_DISABLE_PROMPT=1
2022-08-02 14:46:25 +02:00
source "$PYENV_DIR/${envdir}/bin/activate"
else
echo "A venv for this path already exists"
fi
}
autoload -U add-zsh-hook
add-zsh-hook chpwd chpwd_activate