Skip to content

Commit

Permalink
Allow setup-env to specify Python version
Browse files Browse the repository at this point in the history
This commit is introducing 2 new flags
into the setup-env script. -l or
--list-versions will list available
Python versions and allow the user to
select a version interactively. The second
flag -v or --version will allow a user
to set the version if installed.
(e.g. ./setup-env -v 3.9.6)
  • Loading branch information
Michael Saki committed Jan 25, 2024
1 parent c0eed09 commit 48db3e3
Showing 1 changed file with 39 additions and 3 deletions.
42 changes: 39 additions & 3 deletions setup-env
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Options:
-h --help Show this message.
-i --install-hooks Install hook environments for all environments in the
pre-commit config file.
-v --version Specify the Python version for the virtual environment.
-l --list-versions List available Python versions and select interactively.
END_OF_LINE
)
Expand All @@ -35,6 +37,13 @@ FORCE=0
# Positional parameters
PARAMS=""

# Flags to allow a user to specify which version of Python they want to use
PYTHON_VERSION=""
LIST_VERSIONS=0

# Temp file that is used to search through available installed Python versions
TMPFILE=/tmp/versions.$$

# Parse command line arguments
while (("$#")); do
case "$1" in
Expand All @@ -50,6 +59,14 @@ while (("$#")); do
INSTALL_HOOKS=1
shift
;;
-v | --version)
PYTHON_VERSION=$2
shift 2
;;
-l | --list-versions)
LIST_VERSIONS=1
shift
;;
-*) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
Expand Down Expand Up @@ -111,6 +128,25 @@ else
fi
set -o nounset

# List Python versions and select one interactively
if [ $LIST_VERSIONS -ne 0 ]; then
echo Available Python versions:
pyenv versions --bare --skip-aliases --skip-envs
read -p -r "Enter the desired Python version: " PYTHON_VERSION
fi

# Check if PYTHON_VERSION isn't empty. If it is installed, set it locally.
pyenv versions --bare --skip-aliases --skip-envs > $TMPFILE
if [ -n "$PYTHON_VERSION" ]; then
if grep --fixed-strings --quiet "$PYTHON_VERSION" $TMPFILE; then
echo Using Python version "$PYTHON_VERSION"
pyenv local "$PYTHON_VERSION"
else
echo Error: Python version "$PYTHON_VERSION" is not installed.
fi
exit 1
fi

# Remove any lingering local configuration.
if [ $FORCE -ne 0 ]; then
rm -f .python-version
Expand All @@ -130,10 +166,10 @@ fi
# Create a new virtual environment for this project
if ! pyenv virtualenv "${env_name}"; then
cat << END_OF_LINE
An existing virtual environment named $env_name was found. Either delete this
environment yourself or re-run with --force option to have it deleted.
An existing virtual environment named $env_name was found. Either delete this
environment yourself or re-run with --force option to have it deleted.
pyenv virtualenv-delete ${env_name}
pyenv virtualenv-delete ${env_name}
END_OF_LINE
exit 1
Expand Down

0 comments on commit 48db3e3

Please sign in to comment.