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
2023-04-11 10:30:27 +02:00
pydirs="${PYENVS_DIR:-$XDG_DATA_HOME/virtualenv}"
2022-08-02 14:46:25 +02:00
function chpwd_activate(){
2023-04-04 11:07:58 +02:00
[[ "$(pwd)" == "/" ]] && return 0
2023-04-11 10:30:27 +02:00
for pydir in $(ls $pydirs); do
if [[ "$(pwd | sed -e 's|/|~|g' | cut -c2-)" =~ "^${pydir}$" ]] || [[ "r-$(pwd | sed -e 's|/|~|g' | cut -c2-)" =~ "^${pydir}(~.+)?$" ]]; then
if [ "x$VIRTUAL_ENV" != "x$pydirs/$pydir" ]; then
source "$pydirs/$pydir/bin/activate"
2023-04-04 11:07:58 +02:00
fi
return
fi
done
if [ "x$VIRTUAL_ENV" != "x" ]; then
deactivate
2022-08-02 14:46:25 +02:00
fi
}
function venv(){
2023-04-04 11:07:58 +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
2023-04-11 10:30:27 +02:00
if [ ! -e "$pydirs/${envdir}" ]; then
2023-04-04 11:07:58 +02:00
echo "Creating python venv for ${envdir}.."
2023-04-11 10:30:27 +02:00
mkdir "$pydirs" -p
python3 -m venv "$pydirs/${envdir}"
2023-04-04 11:07:58 +02:00
echo "Activating virtual env ${envdir}"
2023-04-11 10:30:27 +02:00
source "$pydirs/${envdir}/bin/activate"
2023-04-04 11:07:58 +02:00
else
echo "A venv for this path already exists"
fi
2022-08-02 14:46:25 +02:00
}
autoload -U add-zsh-hook
add-zsh-hook chpwd chpwd_activate