Skip to main content
hooksSource-backedReview first Safety Privacy

Rust Cargo Check - Hooks

Automatically runs cargo check and clippy when Rust files are modified.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://doc.rust-lang.org/cargo/commands/cargo-check.html, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/rust-cargo-check.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
4 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://doc.rust-lang.org/cargo/commands/cargo-check.htmlhttps://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/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
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/rust-cargo-check.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

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

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/rust-cargo-check.sh
  3. Make executable: chmod +x .claude/hooks/rust-cargo-check.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. 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.

Source citations

Add this badge to your README

Show that Rust Cargo Check - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/rust-cargo-check.svg)](https://heyclau.de/entry/hooks/rust-cargo-check)

How it compares

Rust Cargo Check - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Automatically runs cargo check and clippy when Rust files are modified.

Open dossier

Lints Vue 3 components for Composition API best practices and common issues.

Open dossier

Automated accessibility testing and compliance checking for web applications following WCAG 2.1 and WCAG 2.2 guidelines. This hook automatically runs accessibility scans on HTML files after they are written or edited, using axe-core for comprehensive WCAG compliance testing.

Open dossier

Automatically creates timestamped backups of files before modification to prevent data loss. This hook runs before file editing operations (Edit, Write, Multiedit) and creates versioned backups in a centralized .backups directory with ISO 8601-compliant timestamps including nanoseconds for collision prevention.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-09-192025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/rust-cargo-check.sh && chmod +x .claude/hooks/rust-cargo-check.sh
mkdir -p .claude/hooks && touch .claude/hooks/vue-composition-api-linter.sh && chmod +x .claude/hooks/vue-composition-api-linter.sh
mkdir -p .claude/hooks && touch .claude/hooks/accessibility-checker.sh && chmod +x .claude/hooks/accessibility-checker.sh
mkdir -p .claude/hooks && touch .claude/hooks/auto-save-backup.sh && chmod +x .claude/hooks/auto-save-backup.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/rust-cargo-check.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/vue-composition-api-linter.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/accessibility-checker.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "preToolUse": {
      "script": "./.claude/hooks/auto-save-backup.sh",
      "matchers": [
        "edit",
        "write",
        "multiedit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.