Files
claude-howto/06-hooks/pre-commit.sh
Luong NGUYENandBenjamin Kincses e2fd4ed6dc fix(hooks): harden hook templates and the auto-mode baseline (#263)
Harden the hook templates in `06-hooks/` and the auto-mode permission baseline in `09-advanced-features/`, in every locale copy that exists. Consolidates #205, #206 and #207 by Benjamin Kincses and fixes the gaps their reviews found.

Closes #258

Co-authored-by: Benjamin Kincses <4175097+benjaminkincses@users.noreply.github.com>
2026-11-13 13:24:52 +01:00

64 lines
1.8 KiB
Bash

#!/bin/bash
# Run tests before commit
# Hook: PreToolUse (matcher: Bash) - checks if the command is a git commit
# Note: There is no "PreCommit" hook event. Use PreToolUse with a Bash matcher
# and inspect the command to detect git commit operations.
#
# Exit codes: 2 blocks the tool call and surfaces stderr as the block reason.
# Any other non-zero value is a NON-blocking error — the commit would proceed.
# Source: https://code.claude.com/docs/en/hooks
# Read the hook JSON from stdin; only run the tests for git commit commands
INPUT=$(cat)
# Extract tool_input.command. The pattern skips escaped quotes (\"), so a command
# like `cd "app" && git commit` is read in full instead of stopping at the first \"
COMMAND=$(echo "$INPUT" | sed -nE 's/.*"command"[[:space:]]*:[[:space:]]*"(([^"\\]|\\.)*)".*/\1/p' | head -1)
if ! echo "$COMMAND" | grep -q 'git commit'; then
exit 0
fi
echo "🧪 Running tests before commit..."
# Check if package.json exists (Node.js project)
if [ -f "package.json" ]; then
if grep -q "\"test\":" package.json; then
npm test
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked." >&2
exit 2
fi
fi
fi
# Check if pytest is available (Python project)
if [ -f "pytest.ini" ] || [ -f "setup.py" ]; then
if command -v pytest &> /dev/null; then
pytest
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked." >&2
exit 2
fi
fi
fi
# Check if go.mod exists (Go project)
if [ -f "go.mod" ]; then
go test ./...
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked." >&2
exit 2
fi
fi
# Check if Cargo.toml exists (Rust project)
if [ -f "Cargo.toml" ]; then
cargo test
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked." >&2
exit 2
fi
fi
echo "✅ All tests passed! Proceeding with commit."
exit 0