src: rewrite pyenv-check-reqs as a usable CLI

The 91-line script hardcoded the 3.8-3.14 range, required pip-tools to be
installed *inside every* pyenv interpreter (it is not, on Arch or anywhere
else that keeps pip-tools outside pyenv), left PYENV_VERSION set in the
caller's shell through 'pyenv shell', only knew one input file, had a typo
in its warning ([WARNGING]) and gave no usable exit status.

- src/pyenv-check-reqs: --help/--version/-f|--file/--versions/--quiet/
  --verbose, 'set -euo pipefail' and '#!/usr/bin/env bash'; versions come
  from 'pyenv versions --bare' instead of a fixed regex, with optional
  filtering by exact version, minor series or range (3.8-3.14);
  pyenv work happens inside a subshell so PYENV_VERSION is never exported.
- When pip-tools is missing from an interpreter it is installed into a
  throwaway venv under  and the whole work directory is removed by
  an EXIT/INT/TERM/HUP trap; an unreachable PyPI is reported as such.
- Missing pyenv, missing requirements file and bad usage now exit 2 with
  an explanation (what to install), a resolution failure exits 1, all
  versions resolving exits 0.
This commit is contained in:
aneto
2026-10-08 12:58:03 +01:00
parent e16e8029b7
commit 941fe9d85c
2 changed files with 366 additions and 71 deletions
+16
View File
@@ -0,0 +1,16 @@
# Generated by pyenv-check-reqs itself
pyenv-check-reqs.*/
*.compile.log
*.pip.log
# Python build artifacts
__pycache__/
*.py[cod]
.venv/
venv/
# Editors / OS
.vscode/
.idea/
*.swp
.DS_Store
+362 -83
View File
@@ -1,91 +1,370 @@
#!/bin/bash
#!/usr/bin/env bash
#
# pyenv-check-reqs — resolve a requirements file against every Python version
# installed with pyenv, so you know which interpreters your pin set supports.
#
# Copyright (c) 2026 Andre Neto (ags-neto)
# SPDX-License-Identifier: MIT
set -e
set -euo pipefail
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
PROGRAM="${0##*/}"
VERSION='1.0.0'
REQUIREMENTS_FILE="requirements.txt"
PYENV_BIN='pyenv'
DEFAULT_REQUIREMENTS='requirements.txt'
# --- Pre-requesites ---
REQUIREMENTS_FILE=''
VERSION_SPEC=''
QUIET=0
VERBOSE=0
WORK_DIR=''
WORK_DIR_CREATED=0
# ---------------------------------------------------------------- utilities --
usage() {
cat <<EOF
$PROGRAM $VERSION — check a requirements file against the Python versions of pyenv
Usage:
$PROGRAM [options] [requirements-file]
Options:
-f, --file PATH requirements file to compile (default: $DEFAULT_REQUIREMENTS)
--versions SPEC comma-separated list of versions and/or ranges to test,
e.g. 3.11,3.12 or 3.8-3.14
(default: every base version pyenv knows about)
-q, --quiet print only the summary and the failures
-v, --verbose print every command and the full output of the tools
-V, --version print the version and exit
-h, --help print this help and exit
Exit status:
0 every selected version resolved the requirements
1 at least one selected version failed to resolve
2 usage error: bad option, missing requirements file, no usable pyenv
Requirements:
pyenv on PATH with at least one base interpreter installed
(https://github.com/pyenv/pyenv#installation · Arch: pacman -S pyenv pyenv-virtualenv)
pip-tools does not have to be installed in every interpreter: if it is missing,
$PROGRAM installs it into a throwaway venv under \$TMPDIR and removes it on
exit, so your pyenv installations are never modified.
EOF
}
log() {
[ "$QUIET" -eq 1 ] && return 0
printf '%s\n' "$*"
}
verbose() {
[ "$VERBOSE" -eq 1 ] || return 0
printf '%s\n' "$*" >&2
}
error() {
printf '%s: %s\n' "$PROGRAM" "$*" >&2
}
die_usage() {
error "$1"
printf "Try '%s --help'.\n" "$PROGRAM" >&2
exit 2
}
cleanup() {
local rc=$?
if [ "$WORK_DIR_CREATED" -eq 1 ] && [ -n "$WORK_DIR" ] && [ -d "$WORK_DIR" ]; then
rm -rf -- "$WORK_DIR"
fi
exit "$rc"
}
# The scratch directory holds the generated outputs, the pip logs and the
# temporary virtualenvs; it always goes away, however we leave.
make_work_dir() {
WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/pyenv-check-reqs.XXXXXXXX") || {
error "cannot create a temporary directory under ${TMPDIR:-/tmp}"
exit 2
}
WORK_DIR_CREATED=1
trap cleanup EXIT INT TERM HUP
}
# is_between LO MID HI — MID is inside the [LO, HI] range, compared version-wise.
is_between() {
local mid
mid=$(printf '%s\n' "$1" "$2" "$3" | sort -V | sed -n '2p')
[ "$mid" = "$2" ]
}
# select_versions ALL_VERSIONS SPEC — SPEC is a comma-separated list of exact
# versions (3.11.13), minor series (3.11) and ranges (3.8-3.14). An empty SPEC
# selects everything. Returns 2 on a malformed SPEC.
select_versions() {
local all=$1 spec=$2 v item lo hi mm
local items=() want=''
if [ -z "$spec" ]; then
printf '%s\n' "$all"
return 0
fi
IFS=',' read -r -a items <<< "$spec"
for item in "${items[@]}"; do
item=$(printf '%s' "$item" | tr -d '[:space:]')
[ -n "$item" ] || continue
if [[ $item =~ ^[0-9]+\.[0-9]+-[0-9]+\.[0-9]+$ ]]; then
lo=${item%%-*}
hi=${item##*-}
while IFS= read -r v; do
[ -n "$v" ] || continue
mm=${v%.*}
if is_between "$lo" "$mm" "$hi"; then
want+="$v"$'\n'
fi
done <<< "$all"
elif [[ $item =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then
while IFS= read -r v; do
[ -n "$v" ] || continue
if [ "$v" = "$item" ] || [[ $v == "$item".* ]]; then
want+="$v"$'\n'
fi
done <<< "$all"
else
return 2
fi
done
printf '%s' "$want" | sed '/^$/d' | sort -V -u
}
# ------------------------------------------------------------ argument parse --
while [ $# -gt 0 ]; do
case "$1" in
-h | --help)
usage
exit 0
;;
-V | --version)
printf '%s %s\n' "$PROGRAM" "$VERSION"
exit 0
;;
-f | --file)
[ $# -ge 2 ] || die_usage "option '$1' needs a path"
REQUIREMENTS_FILE=$2
shift 2
;;
--file=*)
REQUIREMENTS_FILE=${1#*=}
shift
;;
--versions)
[ $# -ge 2 ] || die_usage "option '$1' needs a value"
VERSION_SPEC=$2
shift 2
;;
--versions=*)
VERSION_SPEC=${1#*=}
shift
;;
-q | --quiet)
QUIET=1
shift
;;
-v | --verbose)
VERBOSE=1
shift
;;
--)
shift
break
;;
-*)
die_usage "unknown option '$1'"
;;
*)
break
;;
esac
done
if [ $# -gt 0 ]; then
[ -z "$REQUIREMENTS_FILE" ] || die_usage "the requirements file was given more than once"
REQUIREMENTS_FILE=$1
shift
fi
[ $# -eq 0 ] || die_usage "unexpected argument '$1'"
REQUIREMENTS_FILE=${REQUIREMENTS_FILE:-$DEFAULT_REQUIREMENTS}
if [ -n "$VERSION_SPEC" ] && ! [[ $VERSION_SPEC =~ ^[0-9.,[:space:]-]+$ ]]; then
die_usage "invalid --versions value '$VERSION_SPEC'"
fi
# Check if the requirements.txt file exists in the current directory
if [ ! -f "$REQUIREMENTS_FILE" ]; then
echo "[ERROR] '$REQUIREMENTS_FILE' not found in the current directory."
error "requirements file not found: $REQUIREMENTS_FILE"
exit 2
fi
if [ ! -r "$REQUIREMENTS_FILE" ]; then
error "requirements file is not readable: $REQUIREMENTS_FILE"
exit 2
fi
if ! command -v "$PYENV_BIN" > /dev/null 2>&1; then
cat >&2 <<EOF
$PROGRAM: pyenv was not found on your PATH, so there is no interpreter to check against.
Install pyenv first:
Arch Linux sudo pacman -S pyenv pyenv-virtualenv
Debian/Ubuntu curl -fsSL https://pyenv.run | bash
macOS brew install pyenv
Then install at least one interpreter, e.g. pyenv install 3.12
Documentation: https://github.com/pyenv/pyenv#installation
EOF
exit 2
fi
if ! PYENV_RAW=$("$PYENV_BIN" versions --bare 2>&1); then
error "pyenv is on PATH but 'pyenv versions --bare' failed:"
printf '%s\n' "$PYENV_RAW" | sed 's/^/ /' >&2
exit 2
fi
# Base interpreters only: virtualenvs ("3.12.11/envs/x") and aliases are skipped.
ALL_VERSIONS=$(printf '%s\n' "$PYENV_RAW" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' || true)
if [ -z "$ALL_VERSIONS" ]; then
error "pyenv has no base interpreter installed (found: $(printf '%s' "$PYENV_RAW" | tr '\n' ' '))"
printf "Install one with 'pyenv install <version>' and run again.\n" >&2
exit 2
fi
if ! SELECTED=$(select_versions "$ALL_VERSIONS" "$VERSION_SPEC"); then
die_usage "invalid --versions value '$VERSION_SPEC' (use e.g. 3.11,3.12 or 3.8-3.14)"
fi
if [ -z "$SELECTED" ]; then
error "no installed pyenv version matches '$VERSION_SPEC'"
printf 'Installed base versions: %s\n' "$(printf '%s' "$ALL_VERSIONS" | tr '\n' ' ')" >&2
exit 2
fi
VERSION_LIST=$(printf '%s' "$SELECTED" | tr '\n' ' ')
read -r -a VERSIONS <<< "$VERSION_LIST"
make_work_dir
# ------------------------------------------------------------------- checks --
SUCCESS=()
FAILED=()
log "$PROGRAM $VERSION"
log "Requirements file : $REQUIREMENTS_FILE"
log "Versions to test : ${#VERSIONS[@]} (${VERSION_LIST% })"
log ''
if [ "$VERBOSE" -eq 1 ]; then
printf ' %s\n' "work directory: $WORK_DIR" \
"pip-tools is installed into a temporary venv when a version is missing it" >&2
fi
for version in "${VERSIONS[@]}"; do
output_file="$WORK_DIR/$version.txt"
compile_log="$WORK_DIR/$version.compile.log"
pip_log="$WORK_DIR/$version.pip.log"
venv_dir="$WORK_DIR/venv-$version"
runner=("$PYENV_BIN" exec python)
runner_desc="$PYENV_BIN exec python ($version)"
used_venv=0
log "==> $version"
# Fast path: pip-tools is already importable in this interpreter.
if PYENV_VERSION="$version" "${runner[@]}" -c 'import piptools' > /dev/null 2>&1; then
verbose " using the pip-tools already installed in $version"
else
# Slow path: throwaway venv with pip-tools inside.
log " pip-tools not found in $version, building a temporary venv"
verbose " PYENV_VERSION=$version $PYENV_BIN exec python -m venv $venv_dir"
if ! PYENV_VERSION="$version" "${runner[@]}" -m venv "$venv_dir" > "$pip_log" 2>&1; then
error "$version: could not create a virtualenv"
sed 's/^/ /' "$pip_log" >&2
FAILED+=("$version (venv creation failed)")
log ''
continue
fi
if ! PIP_DISABLE_PIP_VERSION_CHECK=1 PIP_NO_INPUT=1 \
"$venv_dir/bin/python" -m pip install --quiet pip-tools > "$pip_log" 2>&1; then
error "$version: could not install pip-tools into a temporary venv"
sed 's/^/ /' "$pip_log" | tail -n 5 >&2
if grep -qiE 'network is unreachable|temporary failure in name resolution|failed to establish a new connection|no matching distribution|proxy|timed out|could not find a version' "$pip_log"; then
printf ' This looks like a network/DNS problem: PyPI is unreachable.\n' >&2
printf ' Install pip-tools offline for this version, or set PIP_INDEX_URL to a mirror.\n' >&2
fi
FAILED+=("$version (pip-tools could not be installed)")
log ''
continue
fi
runner=("$venv_dir/bin/python")
runner_desc="$venv_dir/bin/python (temporary venv)"
used_venv=1
fi
verbose " compile: $runner_desc -m piptools compile $REQUIREMENTS_FILE --output-file $output_file"
if "${runner[@]}" -m piptools compile "$REQUIREMENTS_FILE" \
--output-file "$output_file" > "$compile_log" 2>&1; then
if [ "$used_venv" -eq 1 ]; then
log " resolved (pip-tools from a temporary venv)"
else
log " resolved"
fi
SUCCESS+=("$version")
else
FAILED+=("$version (resolution failed)")
error " $version: pip-tools could not resolve $REQUIREMENTS_FILE"
sed 's/^/ /' "$compile_log" | tail -n 3 >&2
if [ "$VERBOSE" -eq 1 ]; then
printf ' full output: %s\n' "$compile_log" >&2
fi
fi
log ''
done
# ------------------------------------------------------------------ summary --
printf '\n--- Summary ---\n'
printf 'Requirements file : %s\n' "$REQUIREMENTS_FILE"
printf 'Versions tested : %s\n' "${VERSION_LIST% }"
printf '\nSuccessfully resolved dependencies for:\n'
if [ ${#SUCCESS[@]} -eq 0 ]; then
printf ' None\n'
else
printf ' - %s\n' "${SUCCESS[@]}"
fi
printf '\nFailed to resolve dependencies for:\n'
if [ ${#FAILED[@]} -eq 0 ]; then
printf ' None\n'
else
printf ' - %s\n' "${FAILED[@]}"
fi
printf '\n'
if [ ${#FAILED[@]} -gt 0 ]; then
exit 1
fi
echo "[INFO] Starting Python environment compatibility check for '$REQUIREMENTS_FILE'"
# Get a list of all installed pyenv versions.
# Filter to only include BASE Python versions from 3.8 to 3.14.
# The regex now specifically matches versions like "3.8.x", "3.9.x", ..., "3.14.x"
# and excludes virtual environments (which typically contain '/envs/' or are aliases).
PYENV_VERSIONS=$(pyenv versions --bare | grep -E "^3\.(8|9|1[0-4])(\.[0-9]+)?$")
# Check if any pyenv versions are found after filtering
if [ -z "$PYENV_VERSIONS" ]; then
echo "[WARNGING] No base pyenv versions found matching the 3.8-3.14 range. Please ensure you have them installed with pyenv."
exit 1
fi
# Initialize arrays to store successful and failed versions
SUCCESS_VERSIONS=()
FAILED_VERSIONS=()
# --- Main Loop: Iterate through each pyenv version ---
for VERSION in $PYENV_VERSIONS; do
# Temporarily set the pyenv version for the current shell session.
# Redirect all output to /dev/null to keep the loop silent.
if ! pyenv shell "$VERSION" &> /dev/null; then
FAILED_VERSIONS+=("$VERSION (activation failed)")
continue # Move to the next version
fi
# Verify that 'pip-tools' is available in this environment.
# Redirect all output to /dev/null.
if ! python -c "import piptools" &> /dev/null; then
FAILED_VERSIONS+=("$VERSION (pip-tools not found)")
pyenv shell --unset &> /dev/null
continue # Move to the next version
fi
# Attempt to resolve dependencies using 'python -m piptools compile'.
# Redirect all output (both stdout and stderr) to /dev/null.
# We only care about the exit status for success/failure.
TEMP_OUTPUT_FILE=$(mktemp) # Create a temporary file for --output-file
if python -m piptools compile "$REQUIREMENTS_FILE" --output-file "$TEMP_OUTPUT_FILE" &> /dev/null; then
SUCCESS_VERSIONS+=("$VERSION")
else
FAILED_VERSIONS+=("$VERSION (Resolution failed)") # Only store a simple message
fi
rm -f "$TEMP_OUTPUT_FILE" # Clean up the temporary file
# Unset the pyenv shell version. Redirect all output to /dev/null.
pyenv shell --unset &> /dev/null
done
# --- Summary Report ---
echo "" # Add a newline for better separation from the start message
echo "--- Summary ---"
echo "Successfully resolved dependencies for:"
if [ ${#SUCCESS_VERSIONS[@]} -eq 0 ]; then
echo " None"
else
for v in "${SUCCESS_VERSIONS[@]}"; do
echo " - $v"
done
fi
echo ""
echo "Failed to resolve dependencies for:"
if [ ${#FAILED_VERSIONS[@]} -eq 0 ]; then
echo " None"
else
for v in "${FAILED_VERSIONS[@]}"; do
echo " - $v" # Print the simple failure message
done
fi
echo ""
echo "--- Script Finished ---"
exit 0