Features
- Fast compilation checking with cargo check including cargo check integration (cargo check command execution with fast compilation validation, incremental compilation with target directory caching, compilation error detection with detailed error reporting, compilation warning detection with warning messages), compilation optimization (incremental compilation optimization with caching, parallel compilation with job scheduling, compilation performance with build optimization, compilation caching with target directory), compilation validation (compilation syntax validation, compilation type checking, compilation borrow checking, compilation lifetime checking), and compilation reporting (compilation error reporting with detailed errors, compilation warning reporting with warnings, compilation success reporting with success messages, compilation statistics with build statistics)
- Code linting with clippy including clippy integration (clippy command execution with comprehensive linting, clippy rule enforcement with configurable rules, clippy warning detection with detailed warnings, clippy suggestion detection with code suggestions), clippy configuration (clippy rule configuration with clippy.toml, clippy allow/deny attributes with code annotations, clippy lint groups with pedantic/nursery/cargo, clippy custom rules with custom lints), clippy analysis (clippy code analysis with comprehensive checking, clippy pattern detection with common patterns, clippy optimization suggestions with performance tips, clippy best practices with Rust idioms), and clippy reporting (clippy warning reporting with detailed warnings, clippy suggestion reporting with code suggestions, clippy error reporting with errors, clippy statistics with lint statistics)
- Rust best practices enforcement including best practices (Rust best practices enforcement with clippy, Rust idiom enforcement with idiomatic code, Rust style enforcement with consistent style, Rust pattern enforcement with common patterns), code quality (Rust code quality checking with quality metrics, Rust code maintainability with maintainable code, Rust code readability with readable code, Rust code safety with safe code), performance optimization (Rust performance optimization with performance tips, Rust memory optimization with efficient memory, Rust algorithm optimization with efficient algorithms, Rust resource optimization with efficient resources), and Rust standards (Rust coding standards with standard practices, Rust documentation standards with documentation, Rust testing standards with testing practices, Rust error handling standards with error handling)
- Dependency validation including dependency checking (Cargo.toml dependency validation, dependency version checking with version constraints, dependency compatibility checking with compatibility validation, dependency security checking with security audits), dependency management (dependency resolution with Cargo resolver, dependency update checking with outdated dependencies, dependency conflict detection with conflict resolution, dependency optimization with dependency optimization), dependency security (dependency vulnerability scanning with cargo-audit, dependency license checking with license validation, dependency supply chain security with supply chain validation, dependency update recommendations with update suggestions), and dependency reporting (dependency validation reporting with validation results, dependency security reporting with security issues, dependency update reporting with update recommendations, dependency statistics with dependency metrics)
- Performance optimization suggestions including performance analysis (Rust performance analysis with performance profiling, Rust performance bottlenecks with bottleneck detection, Rust performance optimization with optimization suggestions, Rust performance benchmarking with benchmarking), optimization suggestions (Rust optimization suggestions with performance tips, Rust memory optimization with memory efficiency, Rust algorithm optimization with algorithm efficiency, Rust resource optimization with resource efficiency), performance monitoring (Rust performance monitoring with performance metrics, Rust performance tracking with performance tracking, Rust performance regression detection with regression detection, Rust performance reporting with performance reports), and performance best practices (Rust performance best practices with performance guidelines, Rust memory best practices with memory guidelines, Rust concurrency best practices with concurrency guidelines, Rust I/O best practices with I/O guidelines)
- Security vulnerability detection including security scanning (Rust security vulnerability scanning with cargo-audit, Rust dependency vulnerability detection with vulnerability scanning, Rust code vulnerability detection with code analysis, Rust supply chain security with supply chain validation), security analysis (Rust security analysis with comprehensive analysis, Rust vulnerability assessment with vulnerability assessment, Rust security recommendations with security suggestions, Rust security best practices with security guidelines), security reporting (Rust security reporting with security reports, Rust vulnerability reporting with vulnerability reports, Rust security recommendations with security suggestions, Rust security statistics with security metrics), and security best practices (Rust security best practices with security guidelines, Rust memory safety with memory safety, Rust concurrency safety with concurrency safety, Rust I/O safety with I/O safety)
- Code formatting and style checking including formatting checking (rustfmt code formatting checking with cargo fmt --check, code style validation with consistent style, code formatting validation with formatting rules, code indentation checking with indentation rules), formatting configuration (rustfmt configuration with rustfmt.toml, formatting rules with configurable rules, formatting options with formatting options, formatting standards with style standards), formatting reporting (formatting issue reporting with formatting issues, formatting suggestions with format suggestions, formatting statistics with format statistics, formatting compliance with style compliance), and formatting automation (automatic formatting with cargo fmt, formatting integration with development workflow, formatting consistency with consistent formatting, formatting best practices with formatting guidelines)
- Development workflow integration including continuous validation (real-time compilation checking on Rust file changes, immediate clippy linting on file updates, automatic code validation on file modifications, seamless Rust integration with development workflow), workflow automation (automated Rust validation without manual intervention, compilation checking automation with automatic checking, linting automation with automatic linting), and workflow optimization (Rust change detection with change tracking, incremental compilation with optimization, Rust code consistency maintenance with consistency checks)
Use Cases
- Validate Rust code compilation before commits automatically running cargo check on file changes, detecting compilation errors early, and ensuring code compiles successfully
- Catch common Rust programming errors early automatically running clippy linting, detecting common Rust mistakes, and providing code improvement suggestions
- Enforce Rust coding standards with clippy automatically enforcing Rust best practices, ensuring idiomatic Rust code, and maintaining code quality standards
- Check dependency compatibility automatically validating Cargo.toml dependencies, checking dependency versions, and ensuring dependency compatibility
- Identify performance improvement opportunities automatically analyzing Rust code for performance issues, providing optimization suggestions, and recommending performance improvements
- Development workflow integration seamlessly integrating Rust code validation into development workflows without manual compilation checking or linting
Installation
- Create hooks directory: mkdir -p .claude/hooks
- Create hook file: touch .claude/hooks/rust-cargo-check.sh
- Make executable: chmod +x .claude/hooks/rust-cargo-check.sh
- Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
- Alternative: Use the interactive /hooks command in Claude Code
Config paths
- Local (not committed):
.claude/settings.local.json
- User settings (global):
~/.claude/settings.json
- Project-wide (committed):
.claude/settings.json
Requirements
- Claude Code CLI installed
- Project directory initialized
- Bash shell available
- Rust toolchain installed (rustup, cargo)
- Clippy installed (rustup component add clippy, optional)
- rustfmt installed (rustup component add rustfmt, optional)
- cargo-audit installed (cargo install cargo-audit, optional)
- jq (optional, for JSON parsing)
- flock (optional, for file locking on Linux)
Hook Configuration
{
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/rust-cargo-check.sh",
"matchers": ["write", "edit"]
}
}
}
Hook Script
#!/bin/bash
# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
exit 0
fi
# Check if this is a Rust file or Cargo configuration
if [[ "$FILE_PATH" == *.rs ]] || [[ "$FILE_PATH" == *Cargo.toml ]] || [[ "$FILE_PATH" == *Cargo.lock ]]; then
echo "🦀 Rust Cargo Check - Analyzing Rust code..."
echo "📄 File: $FILE_PATH"
# Check if cargo is available
if ! command -v cargo >/dev/null 2>&1; then
echo "⚠️ Cargo not found - please install Rust toolchain"
echo "💡 Install from: https://rustup.rs/"
exit 1
fi
# Check if we're in a Rust project
if [ ! -f "Cargo.toml" ]; then
echo "⚠️ No Cargo.toml found - not a Rust project"
exit 0
fi
echo "🔍 Running Rust toolchain checks..."
# Step 1: Run cargo check for fast compilation validation
echo "⚡ Running cargo check (fast compilation check)..."
if cargo check --message-format=short; then
echo "✅ Cargo check passed - code compiles successfully"
else
echo "❌ Cargo check failed - compilation errors found"
echo "💡 Fix compilation errors before proceeding"
exit 1
fi
# Step 2: Run clippy for linting (if available)
echo ""
echo "📋 Running clippy (Rust linter)..."
if command -v cargo-clippy >/dev/null 2>&1 || cargo clippy --version >/dev/null 2>&1; then
if cargo clippy --message-format=short -- -W clippy::pedantic -W clippy::nursery; then
echo "✅ Clippy analysis passed - no linting issues"
else
echo "⚠️ Clippy found linting issues (non-blocking)"
fi
else
echo "ℹ️ Clippy not available - install with: rustup component add clippy"
fi
# Step 3: Check formatting (if rustfmt is available)
echo ""
echo "🎨 Checking code formatting..."
if command -v rustfmt >/dev/null 2>&1; then
if cargo fmt -- --check; then
echo "✅ Code formatting is correct"
else
echo "⚠️ Code formatting issues found"
echo "💡 Run 'cargo fmt' to fix formatting"
fi
else
echo "ℹ️ rustfmt not available - install with: rustup component add rustfmt"
fi
# Step 4: Security audit (if cargo-audit is available)
echo ""
echo "🔒 Running security audit..."
if command -v cargo-audit >/dev/null 2>&1; then
if cargo audit; then
echo "✅ No known security vulnerabilities found"
else
echo "⚠️ Security vulnerabilities detected - review dependencies"
fi
else
echo "ℹ️ cargo-audit not available - install with: cargo install cargo-audit"
fi
# Step 5: Project analysis
echo ""
echo "📊 Project Analysis:"
# Count Rust files
RUST_FILES=$(find . -name "*.rs" -not -path "./target/*" | wc -l)
echo " • Rust files: $RUST_FILES"
# Check for tests
TEST_FILES=$(find . -name "*.rs" -not -path "./target/*" -exec grep -l "#\[test\]\|#\[cfg(test)\]" {} \; | wc -l)
echo " • Files with tests: $TEST_FILES"
# Check dependencies
DEPENDENCIES=$(grep -c '^[a-zA-Z].*=' Cargo.toml 2>/dev/null || echo 0)
echo " • Dependencies: $DEPENDENCIES"
# Check for unsafe blocks
if find . -name "*.rs" -not -path "./target/*" -exec grep -l "unsafe" {} \; | head -1 >/dev/null 2>&1; then
UNSAFE_COUNT=$(find . -name "*.rs" -not -path "./target/*" -exec grep -c "unsafe" {} \; | awk '{sum+=$1} END {print sum}')
echo " • ⚠️ Unsafe blocks found: $UNSAFE_COUNT"
fi
echo ""
echo "💡 Rust Development Tips:"
echo " • Use 'cargo test' to run all tests"
echo " • Use 'cargo build --release' for optimized builds"
echo " • Use 'cargo doc --open' to generate and view documentation"
echo " • Use 'cargo bench' for benchmarking (if available)"
echo " • Consider using 'cargo watch' for continuous testing"
echo ""
echo "🎯 Rust code analysis complete!"
else
echo "ℹ️ File is not a Rust file: $FILE_PATH"
fi
exit 0
Examples
Rust Cargo Check Hook Script
Complete hook script that runs cargo check on Rust file changes
#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
exit 0
fi
if [[ "$FILE_PATH" == *.rs ]] || [[ "$FILE_PATH" == *Cargo.toml ]]; then
if command -v cargo >/dev/null 2>&1 && [ -f "Cargo.toml" ]; then
echo "🦀 Running cargo check..."
if cargo check --message-format=short; then
echo "✅ Cargo check passed"
else
echo "❌ Cargo check failed"
exit 1
fi
fi
fi
exit 0
Hook Configuration
Complete hook configuration for .claude/settings.json to enable Rust cargo check
{
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/rust-cargo-check.sh",
"matchers": ["write", "edit"]
}
}
}
Comprehensive Rust Validation
Enhanced hook script with cargo check, clippy, and rustfmt
#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.rs ]] || [[ "$FILE_PATH" == *Cargo.toml ]]; then
if command -v cargo >/dev/null 2>&1 && [ -f "Cargo.toml" ]; then
echo "🦀 Running cargo check..."
cargo check --message-format=short
if command -v cargo-clippy >/dev/null 2>&1 || cargo clippy --version >/dev/null 2>&1; then
echo "📋 Running clippy..."
cargo clippy --message-format=short -- -W clippy::pedantic
fi
if command -v rustfmt >/dev/null 2>&1; then
echo "🎨 Checking formatting..."
cargo fmt -- --check
fi
fi
fi
exit 0
Thread-Safe Cargo Check with File Locking
Enhanced hook script with file locking to prevent concurrent cargo check executions
#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.rs ]]; then
if command -v cargo >/dev/null 2>&1 && [ -f "Cargo.toml" ]; then
{ flock -n 200 || exit 0; cargo check --message-format=short; } 200>/tmp/cargo-check.lock
fi
fi
exit 0
Clippy Configuration Example
Example clippy.toml configuration for strict linting
[clippy]
denied-warnings = ["clippy::all"]
warn-on-all-lints = true
[clippy::pedantic]
[clippy::nursery]
Troubleshooting
Cargo check fails with 'No Cargo.toml found' in monorepos
Hook searches from file directory upward but may fail in nested workspaces. Add cd logic to find workspace root: while [ ! -f Cargo.toml ] && [ $(pwd) != / ]; do cd ..; done before running cargo commands. Verify workspace structure. Test with various workspace configurations.
Target directory compilation artifacts cause slow check times
Cargo check reuses incremental compilation from target/. Ensure .gitignore excludes target/ but preserve it locally. Use cargo clean selectively or CARGO_TARGET_DIR to separate hook builds from development builds. Verify target directory. Test with various build configurations.
Cargo audit fails when offline or network restricted environments
Script treats cargo-audit as optional but doesn't handle network errors. Add CARGO_NET_OFFLINE=true check or wrap in: timeout 5s cargo audit || echo 'Audit skipped (offline)' to prevent hanging on network unavailable. Verify network connectivity. Test with various network configurations.
Multiple Rust files changed simultaneously trigger concurrent checks
PostToolUse fires per operation causing parallel cargo check processes. Add flock-based locking: { flock -n 200 || exit 0; cargo check; } 200>/tmp/cargo-check.lock to serialize executions and prevent resource contention. Verify file locking. Test with various concurrent scenarios.
Hook executes before file write completes showing stale errors
PostToolUse hooks fire after tool completion but file system may buffer writes. Add small delay: sleep 0.1 before cargo check, or verify file timestamp: [ "$FILE_PATH" -nt /tmp/last-check ] to ensure fresh content is analyzed. Verify file timestamps. Test with various file write scenarios.
Clippy shows too many warnings or false positives
Configure clippy with clippy.toml to customize lint levels. Use #[allow(clippy::lint_name)] for specific suppressions. Adjust clippy lint groups (pedantic, nursery) based on project needs. Verify clippy configuration. Test with various clippy configurations.
Cargo check is slow on large Rust projects
Use incremental compilation with target directory caching. Consider using cargo check --workspace for workspace projects. Use CARGO_TARGET_DIR for separate build directories. Optimize Cargo.toml dependencies. Verify compilation settings. Test with various project sizes.
rustfmt formatting conflicts with project style
Configure rustfmt with rustfmt.toml to match project style. Use #[rustfmt::skip] for specific code sections. Customize formatting rules to match project standards. Verify rustfmt configuration. Test with various formatting configurations.