|
| 1 | +#!/bin/bash |
| 2 | +# pre-commit.sh: Run the same checks as CI (see .github/workflows/ci.yml) |
| 3 | +# Usage: |
| 4 | +# ./pre-commit.sh # Run checks |
| 5 | +# ./pre-commit.sh install # Install as .git/hooks/pre-commit |
| 6 | + |
| 7 | +set -euo pipefail |
| 8 | + |
| 9 | +if [[ "${1:-}" == "install" ]]; then |
| 10 | + hook_path=".git/hooks/pre-commit" |
| 11 | + cp -- "$0" "$hook_path" |
| 12 | + chmod +x "$hook_path" |
| 13 | + echo "Installed pre-commit hook to $hook_path" |
| 14 | + exit 0 |
| 15 | +fi |
| 16 | + |
| 17 | +# 1. Find the project root |
| 18 | +PROJECT_ROOT="$(git rev-parse --show-toplevel)" |
| 19 | + |
| 20 | +# 2. Define standard virtual environment names |
| 21 | +VENV_NAMES=(".venv" "venv") |
| 22 | + |
| 23 | +# 3. Locate the virtual environment directory |
| 24 | +VENV_DIR="" |
| 25 | +for name in "${VENV_NAMES[@]}"; do |
| 26 | + CANDIDATE="$PROJECT_ROOT/$name" |
| 27 | + if [ -d "$CANDIDATE" ]; then |
| 28 | + VENV_DIR="$CANDIDATE" |
| 29 | + break |
| 30 | + fi |
| 31 | +done |
| 32 | + |
| 33 | +# 4. Check if a virtual environment was found |
| 34 | +if [ -z "$VENV_DIR" ]; then |
| 35 | + echo "🚨 Error: Virtual environment not found. Please create one (e.g., 'python3 -m venv .venv') and run the hook again." |
| 36 | + exit 1 |
| 37 | +fi |
| 38 | + |
| 39 | +# 5. Define the full path to the Python interpreter within the found VENV |
| 40 | +PYTHON_EXEC="$VENV_DIR/bin/python" |
| 41 | + |
| 42 | +# 6. Check if the interpreter exists |
| 43 | +if [ ! -x "$PYTHON_EXEC" ]; then |
| 44 | + echo "🚨 Error: Python executable not found at $PYTHON_EXEC" |
| 45 | + exit 1 |
| 46 | +fi |
| 47 | + |
| 48 | +# --- Use the specific Python executable for all commands --- |
| 49 | + |
| 50 | +# Run all examples |
| 51 | +"$PYTHON_EXEC" runner.py |
| 52 | + |
| 53 | +# Lint and format checks (ruff and isort are installed in the venv) |
| 54 | +"$PYTHON_EXEC" -m ruff check |
| 55 | +"$PYTHON_EXEC" -m isort --check --diff . |
| 56 | + |
| 57 | +# Coverage |
| 58 | +"$PYTHON_EXEC" -m coverage run runner.py |
| 59 | +"$PYTHON_EXEC" -m coverage report --fail-under=80 |
0 commit comments