|
| 1 | +#!/usr/bin/env bash |
| 2 | +# |
| 3 | +# Pre-commit hook for Rust projects |
| 4 | +# |
| 5 | +# This hook runs cargo fmt on staged Rust files to catch formatting issues |
| 6 | +# before they reach CI. It's designed to be fast and non-intrusive. |
| 7 | +# |
| 8 | +# To skip this hook: git commit --no-verify |
| 9 | +# To skip only clippy: SKIP_CLIPPY=1 git commit |
| 10 | +# |
| 11 | + |
| 12 | +set -e |
| 13 | + |
| 14 | +# Colors for output |
| 15 | +RED='\033[0;31m' |
| 16 | +GREEN='\033[0;32m' |
| 17 | +YELLOW='\033[1;33m' |
| 18 | +NC='\033[0m' # No Color |
| 19 | + |
| 20 | +# Get list of staged Rust files |
| 21 | +STAGED_RS_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.rs$' || true) |
| 22 | + |
| 23 | +# If no Rust files are staged, exit early |
| 24 | +if [ -z "$STAGED_RS_FILES" ]; then |
| 25 | + exit 0 |
| 26 | +fi |
| 27 | + |
| 28 | +echo -e "${YELLOW}🔍 Checking staged Rust files...${NC}" |
| 29 | + |
| 30 | +# Run cargo fmt on the entire workspace |
| 31 | +# This is fast and fixes formatting issues automatically |
| 32 | +echo -e "${YELLOW}📝 Running cargo fmt...${NC}" |
| 33 | +if cargo fmt --all; then |
| 34 | + # Re-stage any files that were formatted |
| 35 | + for file in $STAGED_RS_FILES; do |
| 36 | + if [ -f "$file" ]; then |
| 37 | + git add "$file" |
| 38 | + fi |
| 39 | + done |
| 40 | + echo -e "${GREEN}✓ Formatting complete${NC}" |
| 41 | +else |
| 42 | + echo -e "${RED}✗ Formatting failed${NC}" |
| 43 | + exit 1 |
| 44 | +fi |
| 45 | + |
| 46 | +# Optional: Run clippy on changed files (can be slow on large projects) |
| 47 | +# Skip with: SKIP_CLIPPY=1 git commit |
| 48 | +if [ -z "$SKIP_CLIPPY" ]; then |
| 49 | + echo -e "${YELLOW}🔎 Running clippy on workspace...${NC}" |
| 50 | + echo -e "${YELLOW} (Skip with: SKIP_CLIPPY=1 git commit)${NC}" |
| 51 | + |
| 52 | + # Run clippy with --no-deps to only check workspace crates, not dependencies |
| 53 | + if cargo clippy --workspace --no-deps -- -D warnings; then |
| 54 | + echo -e "${GREEN}✓ Clippy checks passed${NC}" |
| 55 | + else |
| 56 | + echo -e "${RED}✗ Clippy found issues${NC}" |
| 57 | + echo -e "${YELLOW}💡 Fix the issues above or skip with: SKIP_CLIPPY=1 git commit${NC}" |
| 58 | + exit 1 |
| 59 | + fi |
| 60 | +fi |
| 61 | + |
| 62 | +echo -e "${GREEN}✓ Pre-commit checks passed!${NC}" |
| 63 | +exit 0 |
0 commit comments