Automatically run cargo fmt and cargo clippy before every commit. Catches issues before they reach the repo.
- Automatic formatting - Never commit unformatted code
- Catch issues early - Clippy warnings caught before commit
- Team consistency - Everyone's code meets the same standards
- No CI surprises - If it commits, it passes checks
Install pre-commit (Python tool):
# macOS
brew install pre-commit
# pip
pip install pre-commitCreate .pre-commit-config.yaml in your project root:
repos:
- repo: local
hooks:
- id: cargo-fmt
name: cargo fmt
entry: cargo fmt --manifest-path rust-json-parser/Cargo.toml --
language: system
types: [rust]
pass_filenames: false
- id: cargo-clippy
name: cargo clippy
entry: cargo clippy --manifest-path rust-json-parser/Cargo.toml -- -D warnings
language: system
types: [rust]
pass_filenames: false# Install the hooks (run once per repo clone)
pre-commit install
# Or use make if you have the Makefile
make pre-commit-installAfter setup, every git commit will:
- Run
cargo fmt- formats any changed Rust files - Run
cargo clippy- checks for warnings/errors - If either fails, commit is blocked
$ git commit -m "Add feature"
cargo fmt................................................................Passed
cargo clippy.............................................................Passed
[main abc1234] Add feature$ git commit -m "Add feature"
cargo fmt................................................................Failed
- hook id: cargo-fmt
- files were modified by this hook
# fmt modified files, need to re-stage and commit again
$ git add .
$ git commit -m "Add feature"| Field | Purpose |
|---|---|
repo: local |
Use local commands (not remote hook repos) |
entry |
The command to run |
--manifest-path |
Points to Cargo.toml location |
language: system |
Use system-installed cargo |
types: [rust] |
Only run on .rs files |
pass_filenames: false |
Run on whole project, not individual files |
# Run hooks manually (without committing)
pre-commit run --all-files
# Skip hooks for one commit (use sparingly!)
git commit --no-verify -m "WIP"
# Update hooks
pre-commit autoupdateIf your Cargo.toml is in the root (not a subdirectory), simplify to:
repos:
- repo: local
hooks:
- id: cargo-fmt
name: cargo fmt
entry: cargo fmt --
language: system
types: [rust]
pass_filenames: false
- id: cargo-clippy
name: cargo clippy
entry: cargo clippy -- -D warnings
language: system
types: [rust]
pass_filenames: false