|
| 1 | +#!/usr/bin/env bash |
| 2 | +# Pre-commit hook: catch common mistakes before they're committed |
| 3 | +set -euo pipefail |
| 4 | + |
| 5 | +RED='\033[0;31m' |
| 6 | +YELLOW='\033[0;33m' |
| 7 | +NC='\033[0m' # No Color |
| 8 | + |
| 9 | +echo "Running pre-commit checks..." |
| 10 | + |
| 11 | +# 1. Block commits of sensitive files |
| 12 | +SENSITIVE_PATTERNS=('.env' '.env.local' '.env.production' 'credentials.json' '*.pem' '*.key') |
| 13 | +STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM) |
| 14 | + |
| 15 | +for pattern in "${SENSITIVE_PATTERNS[@]}"; do |
| 16 | + while IFS= read -r file; do |
| 17 | + if [[ -n "$file" ]]; then |
| 18 | + echo -e "${RED}BLOCKED:${NC} Refusing to commit sensitive file: $file" |
| 19 | + echo "If this is intentional, use: git commit --no-verify" |
| 20 | + exit 1 |
| 21 | + fi |
| 22 | + done < <(echo "$STAGED_FILES" | grep -E "^${pattern//\*/.*}$" 2>/dev/null || true) |
| 23 | +done |
| 24 | + |
| 25 | +# 2. Check for debug/console statements in staged JS/TS/Python files |
| 26 | +CODE_FILES=$(echo "$STAGED_FILES" | grep -E '\.(js|ts|py)$' || true) |
| 27 | +if [ -n "$CODE_FILES" ]; then |
| 28 | + ISSUES=0 |
| 29 | + while IFS= read -r file; do |
| 30 | + if git diff --cached "$file" | grep -E '^\+.*console\.(log|debug|warn)\(' | grep -v '// keep' > /dev/null 2>&1; then |
| 31 | + echo -e "${YELLOW}WARNING:${NC} console.log/debug/warn found in $file" |
| 32 | + ISSUES=$((ISSUES + 1)) |
| 33 | + fi |
| 34 | + if git diff --cached "$file" | grep -E '^\+.*(debugger|breakpoint\(\))' > /dev/null 2>&1; then |
| 35 | + echo -e "${RED}BLOCKED:${NC} debugger statement found in $file" |
| 36 | + exit 1 |
| 37 | + fi |
| 38 | + done <<< "$CODE_FILES" |
| 39 | + if [ $ISSUES -gt 0 ]; then |
| 40 | + echo -e "${YELLOW}Found $ISSUES file(s) with console statements. Consider removing them.${NC}" |
| 41 | + fi |
| 42 | +fi |
| 43 | + |
| 44 | +# 3. Check for merge conflict markers |
| 45 | +if [ -n "$STAGED_FILES" ]; then |
| 46 | + while IFS= read -r file; do |
| 47 | + if [ -f "$file" ] && grep -rn '<<<<<<<\|=======\|>>>>>>>' "$file" > /dev/null 2>&1; then |
| 48 | + echo -e "${RED}BLOCKED:${NC} Merge conflict markers found in $file" |
| 49 | + exit 1 |
| 50 | + fi |
| 51 | + done <<< "$STAGED_FILES" |
| 52 | +fi |
| 53 | + |
| 54 | +# 4. Warn on large files (> 500KB) |
| 55 | +while IFS= read -r file; do |
| 56 | + if [ -f "$file" ]; then |
| 57 | + SIZE=$(wc -c < "$file") |
| 58 | + if [ "$SIZE" -gt 512000 ]; then |
| 59 | + SIZE_KB=$((SIZE / 1024)) |
| 60 | + echo -e "${YELLOW}WARNING:${NC} Large file (${SIZE_KB}KB): $file" |
| 61 | + fi |
| 62 | + fi |
| 63 | +done <<< "$STAGED_FILES" |
| 64 | + |
| 65 | +echo "Pre-commit checks passed." |
0 commit comments