update-python-env: add --local flag for local virtualenv

- Add shebang and proper quoting for variable checks ($1 → "$1")
- Fix version detection to use exact match (grep ^VERSION$ not substring)
- Implement --local flag to create project-local .venv instead of pyenv-virtualenv
- Automatically upgrades pip/setuptools/wheel and installs requirements.txt
This commit is contained in:
Maxim Shulga
2026-06-23 20:38:20 -07:00
parent 7009457ac2
commit 7ac03bbc52

View File

@@ -1,5 +1,19 @@
if [ -z $1 ]; then #!/usr/bin/env bash
echo "Usage: $0 <python version> [ENV_NAME]"
if [ -z "$1" ]; then
echo "Usage: $0 [--local] <python version> [ENV_NAME]"
echo " --local create .venv in the current project instead of pyenv-virtualenv"
exit 1
fi
LOCAL_VENV=false
if [ "$1" = "--local" ]; then
LOCAL_VENV=true
shift
fi
if [ -z "$1" ]; then
echo "Usage: $0 [--local] <python version> [ENV_NAME]"
exit 1 exit 1
fi fi
@@ -15,13 +29,31 @@ if [[ $PROJECT == "" ]]; then
fi fi
echo "[*] Checking if required python version $PY_VER is installed" echo "[*] Checking if required python version $PY_VER is installed"
pyenv versions | grep $PY_VER > /dev/null pyenv versions --bare | grep "^$PY_VER$" > /dev/null
res=$? res=$?
if [ $res -eq 1 ]; then if [ $res -eq 1 ]; then
echo "Python $PY_VER is not installed. Run \"pyenv install $PY_VER\"" echo "Python $PY_VER is not installed. Run \"pyenv install $PY_VER\""
exit 1 exit 1
fi fi
if [ "$LOCAL_VENV" = true ]; then
echo "[*] Creating local virtualenv (.venv)"
rm -rf .venv
echo "$PY_VER" > .python-version
"$(pyenv prefix "$PY_VER")/bin/python" -m venv .venv || exit 1
echo "[*] Updating pip, setuptools and wheel"
.venv/bin/python -m pip install -U pip setuptools wheel || exit 1
if [ -f requirements.txt ]; then
echo "[*] Installing packets from requirements.txt"
.venv/bin/python -m pip install -Ur requirements.txt || exit 1
fi
echo "[*] Local virtualenv is ready. Activate it with: source .venv/bin/activate"
exit 0
fi
CUR_VENV=$(cat .python-version) CUR_VENV=$(cat .python-version)
echo "[*] Removing current virtualenv ($CUR_VENV)" echo "[*] Removing current virtualenv ($CUR_VENV)"
pyenv virtualenv-delete -f $CUR_VENV || true pyenv virtualenv-delete -f $CUR_VENV || true