1
0
Fork 0
dotfiles/.config/zsh/plugins/autopyenv/autopyenv.zsh

35 lines
1.2 KiB
Bash
Raw Normal View History

2023-03-29 16:15:06 +02:00
# vim:set ft=zsh
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
2023-03-26 15:17:48 +02:00
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
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
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
2023-03-26 15:17:48 +02:00
[[ "$(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}"
2022-08-23 17:33:53 +02:00
source "$PYENV_DIR/${envdir}/bin/activate"
2022-08-02 14:46:25 +02:00
else
echo "A venv for this path already exists"
fi
}
autoload -U add-zsh-hook
add-zsh-hook chpwd chpwd_activate