Skip to content

Instantly share code, notes, and snippets.

@markshust
Created December 10, 2025 20:10
Show Gist options
  • Select an option

  • Save markshust/dad924298ab13fd473a662bc9672b258 to your computer and use it in GitHub Desktop.

Select an option

Save markshust/dad924298ab13fd473a662bc9672b258 to your computer and use it in GitHub Desktop.
Git pre-commit hook to run Laravel unit tests and auto-correct failing test(s) with Claude Code CLI's -p flag
#!/bin/bash
# Configuration
MAX_ATTEMPTS=${CLAUDE_FIX_ATTEMPTS:-2}
AUTO_FIX=${CLAUDE_AUTO_FIX:-true}
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
attempt=1
while [ $attempt -le $MAX_ATTEMPTS ]; do
echo -e "${YELLOW}Running tests (attempt $attempt/$MAX_ATTEMPTS)...${NC}"
# Run tests and capture output
TEST_OUTPUT=$(php artisan test 2>&1)
TEST_EXIT_CODE=$?
if [ $TEST_EXIT_CODE -eq 0 ]; then
echo -e "${GREEN}All tests passed!${NC}"
exit 0
fi
echo -e "${RED}Tests failed.${NC}"
echo "$TEST_OUTPUT"
# Check if auto-fix is enabled and we haven't exceeded attempts
if [ "$AUTO_FIX" != "true" ] || [ $attempt -eq $MAX_ATTEMPTS ]; then
echo -e "${RED}Tests failed. Commit aborted.${NC}"
exit 1
fi
echo -e "${YELLOW}Attempting to fix with Claude Code...${NC}"
# Use Claude Code to fix the failing tests
# --allowedTools grants permission to edit files without prompting
echo "The following test(s) failed. Please analyze the error and fix the failing test(s). Only modify the necessary files to make the tests pass.
Test output:
$TEST_OUTPUT" | claude -p --allowedTools Edit,Write,Read
CLAUDE_EXIT_CODE=$?
if [ $CLAUDE_EXIT_CODE -ne 0 ]; then
echo -e "${RED}Claude Code failed to fix tests. Commit aborted.${NC}"
exit 1
fi
# Stage any modified files
git add -u
((attempt++))
done
echo -e "${RED}Could not fix tests after $MAX_ATTEMPTS attempts. Commit aborted.${NC}"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment