This repository has been archived on 2024-05-02. You can view files and clone it, but cannot push or open issues or pull requests.
omni-ansible/resources/bash/pyenv.sh

77 lines
2.4 KiB
Bash
Raw Normal View History

#!/env/bash
function pyenv () {
usage="Custom Python virtualenv manager
sivenv [list, delete, load, new] [VENV]
Commands:
list List existing virtualenvs (alias: 'ls')
load VENV Activate the virtualenv named VENV (alias: 'source')
new VENV [VERSION] Create and load a new virtualenv named VENV. Optionally VERSION
can be a python version to use for creating the venv. Note that
only python3 versions are supported.
delete VENV Delete the virtualenv named VENV (alias: 'rm')";
if [ $# -eq 0 ]; then
echo "Error: no command specified" >&2;
echo "$usage";
return 1;
fi;
case $1 in
"-h"| "--help")
echo "$usage";
return 0;;
"ls"| "list")
lsvenv "$VIRTUALENV_DIR";;
"rm"| "delete")
if [ $# -ne 2 ]; then
echo "Error: no virtualenv specified" >&2;
return 1;
fi;
rm --recursive --force "${VIRTUALENV_DIR:?}/$2";;
"source" | "load")
if [ $# -ne 2 ]; then
echo "Error: no virtualenv specified" >&2;
return 1;
fi;
# shellcheck source=/dev/null
source "$VIRTUALENV_DIR/$2/bin/activate";;
"new")
if [ $# -lt 2 ]; then
echo "Error: no virtualenv specified" >&2;
return 1;
fi;
if [ $# -eq 3 ]; then
version="$3";
else
version="3";
fi
if ! command -v "python$version" &>/dev/null; then
echo "Error: no interpreter found for python version '$version'" >&2;
return 2;
fi
if python$version -m venv "$VIRTUALENV_DIR/$2"; then
echo "New virtualenv '$2' created using $(command -v python$version)" >&2;
# shellcheck source=/dev/null
source "$VIRTUALENV_DIR/$2/bin/activate"
else
return $?;
fi;;
*)
echo "Error: unknown command '$1'" >&2;
echo "$usage";
return 1;;
esac
}
function lsvenv () {
venvs=()
for item in /usr/bin/ls -d "$1"/*/; do
if stat "${item}/bin/activate" &>/dev/null; then
venvs+=("$(basename "$item")");
fi
done
echo "${venvs[*]}"
}