Sub topic 11
Enforcing formatting and lints in CI
This chapter assumes you can run cargo fmt and cargo clippy locally, and that you know how lint levels (allow, warn, deny) work. It also assumes you have used Cargo to build a project and have seen a basic CI configuration file. The goal is a pipeline that rejects unformatted code and Clippy warnings before they reach your main branch.
Why local checks are not enough
Running the tools by hand depends on every contributor remembering to do it. Editor integration helps, but editors differ in settings and some contributors don't use one. CI (continuous integration) is a server that runs the same commands on every push and pull request. It is the one place where the rules are applied to everyone in the same way.
CI should check, not change. A CI job that rewrites files would modify a temporary checkout that is thrown away, so the fix never reaches the repository. Instead, the job reports a failure and the author fixes the problem locally.
Checking formatting without changing files
The --check flag makes rustfmt report differences and exit with a non-zero status when any file is not formatted. It does not rewrite files.
cargo fmt
cargo fmt --all -- --checkThe first command rewrites files in place and is for local use. The second is the CI form. Two details matter here:
--allformats every package in a workspace. Without it,cargo fmtonly handles the package in the current directory.- The lone
--separates Cargo's arguments from rustfmt's.--checkbelongs to rustfmt, so it goes after the separator.
When the check fails, rustfmt prints a diff of what it would change. The CI log then shows the author exactly which lines to fix.
Here is a file that would fail the check:
fn main(){
let numbers=vec![1,2,3];
let total:i32=numbers.iter().sum();
println!("total = {}",total);
}Running cargo fmt rewrites it to the standard style, and the check then passes.
Making Clippy fail the build
By default, Clippy reports lints as warnings, and warnings do not change the exit status. A pipeline that only runs cargo clippy will stay green even when Clippy finds problems. To fail the build, promote all warnings to errors with the -D warnings flag.
cargo clippy --all-targets --all-features -- -D warnings
cargo clippy --fix --allow-dirtyThe first command is the strict form for CI. The second is a local convenience: it applies machine-applicable suggestions even when the working tree has uncommitted changes. You would not run --fix in CI.
Each part of the strict command has a purpose:
| Part | Effect |
|---|---|
| `--all-targets` | Lints tests, benchmarks, examples, and binaries, not only the library or main target. |
| `--all-features` | Compiles with every Cargo feature enabled, so code behind `#[cfg(feature = "...")]` is linted. |
| `--` | Separates Cargo's arguments from the ones passed to Clippy and the compiler. |
| `-D warnings` | Treats every warning as an error, including ordinary compiler warnings such as unused variables. |
The last row is a point that surprises people. -D warnings applies to rustc warnings as well as Clippy lints. An unused import that was previously ignored will now fail the build.
Gotchas with `--all-features`
--all-features is not always what you want. If your crate has mutually exclusive features, or a feature that needs a system library that the CI image lacks, the build will fail for reasons unrelated to linting. In that case, run Clippy once per meaningful feature combination, or use --no-default-features in a second step. For a workspace, add --workspace so every member is checked.
cargo clippy --workspace --all-targets --all-features -- -D warningsA complete GitHub Actions workflow
The following workflow runs both checks on every push and pull request. It uses the dtolnay/rust-toolchain action to install a Rust toolchain together with the rustfmt and clippy components.
name: lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- run: cargo fmt --all -- --check
- run: cargo clippy --all-targets --all-features -- -D warningsSteps in a job run in order, and a failing step stops the job. The cheap formatting check runs first, so a style mistake fails in seconds without waiting for a compile.
The components line matters. Without it, cargo fmt or cargo clippy may fail with a message that the subcommand is not installed. The rustup profile used by some runners does not include these components by default.
Toolchain versions and reproducibility
A strict CI gate has a known weakness. Each Rust release can add new Clippy lints, and some of them fire on existing code. If CI uses the stable channel, a routine toolchain update can turn a green build red without any change to your code.
You have a few options:
- Track stable and fix new lints as they appear. This keeps the code current and spreads the work out. It does mean unrelated pull requests can suddenly fail.
- Pin the toolchain. A
rust-toolchain.tomlfile in the repository root fixes the version for everyone, including CI, and you upgrade deliberately in a dedicated pull request. - Run Clippy on stable but not as a required check. This is the weakest option, since warnings tend to accumulate.
A pinned toolchain looks like this:
# rust-toolchain.toml
[toolchain]
channel = "1.82.0"
components = ["rustfmt", "clippy"]With this file present, rustup installs the listed version and components automatically when a command runs in the repository. Contributors and CI then use the same formatter and the same lint set.
Pinning also helps with formatting. Rustfmt's output can change slightly between releases, so two people on different versions can disagree about what is "formatted". The --check step would then fail for one of them even though neither made a mistake.
The msrv setting in clippy.toml is a separate concern. It tells Clippy the oldest Rust version your crate supports, so it does not suggest APIs newer than that. It does not choose which compiler runs.
# clippy.toml
msrv = "1.70"
too-many-arguments-threshold = 8Keeping policy in the repository, not in the pipeline
You can pass lint levels as command-line flags in the CI file, as with -D warnings. A better habit is to keep the lasting policy in files committed to the repository, and keep the CI command short. That way a developer running cargo clippy locally sees the same lint set that CI enforces.
The [lints] table in Cargo.toml is the usual place for this:
# Cargo.toml
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "warn"
module_name_repetitions = "allow"Here the entries are set to warn, not deny. CI then turns those warnings into errors with -D warnings. Locally, developers see warnings while they work and are not blocked from compiling. This split gives you strict CI and a forgiving local experience from a single policy.
If you prefer the policy to block even local builds, set levels to deny in the table. Be aware that this can interrupt development with errors for work in progress, such as a temporary unwrap.
Formatting policy follows the same idea. A rustfmt.toml in the repository root applies to local runs and to CI:
# rustfmt.toml
max_width = 100
edition = "2021"
use_field_init_shorthand = trueBecause CI runs cargo fmt --all -- --check and reads this file, the configured style is enforced. Stick to stable options. Unstable rustfmt options only work on a nightly toolchain and print warnings elsewhere, which breaks the stable CI job.
Handling code that must stay as written
Some code should keep its hand-made layout. Add #[rustfmt::skip] to that item, and the formatting check will ignore it.
#[rustfmt::skip]
const IDENTITY: [[u8; 3]; 3] = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];For a single Clippy lint, use a narrow allow attribute on the item, not a crate-wide setting. This keeps the exception visible in review:
#[allow(clippy::too_many_arguments)]
fn draw(x: i32, y: i32, w: i32, h: i32, r: u8, g: u8, b: u8, a: u8) {
let _ = (x, y, w, h, r, g, b, a);
}Every allow should have a reason. A short comment above it helps reviewers decide whether the exception is justified.
Common errors
- The check passes locally but fails in CI. The usual causes are different toolchain versions, a missing
--allor--all-targets, or a feature enabled only in CI. Pin the toolchain and run the exact CI commands locally. - Clippy never fails the build. The
-D warningsflag is missing, or it is placed before the--separator. It must come after the separator. - "cargo-clippy is not installed". The CI image lacks the component. Add
components: rustfmt, clippyor runrustup component add clippy rustfmt. - A new Rust release breaks an unrelated pull request. A new lint appeared. Pin the toolchain, or fix the lint in a separate pull request.
- Formatting differs between contributors. Editors use their own settings or versions. Commit
rustfmt.tomlandrust-toolchain.toml. - Generated code fails the check. Mark the generated module with
#[rustfmt::skip]or exclude it from linting with a narrowallow, since you cannot fix it by hand.
Reproducing CI locally
Before pushing, run the same two commands that the pipeline runs:
cargo fmt --all -- --check
cargo clippy --all-targets --all-features -- -D warningsIf you want a safeguard, put them in a Git pre-push hook or a task runner recipe. The hook is optional and is not a substitute for CI, because hooks can be skipped with --no-verify.
Exercise
A project's CI job runs cargo clippy --all-targets --all-features and always passes, even though developers see Clippy warnings locally. What change makes the job fail on warnings, and where must it go in the command?
Show answer
Add -D warnings after the -- separator: cargo clippy --all-targets --all-features -- -D warnings. Without it, warnings do not change the exit status. The flag must come after -- so that it is passed to Clippy and the compiler, not interpreted by Cargo.
Exercise
Your CI uses the stable toolchain. After a Rust release, an unrelated pull request fails on a lint nobody touched. Name two ways to prevent this kind of surprise, and say what each costs.
Show answer
Pin the toolchain with rust-toolchain.toml, which gives reproducible results but means you must upgrade the version deliberately. Alternatively, keep tracking stable and fix new lints as they appear, which keeps code current but can block unrelated pull requests until the lint is fixed.
Exercise
Why does the workflow run cargo fmt --all -- --check before cargo clippy, and why should CI use --check instead of plain cargo fmt?
Show answer
The formatting check is fast and needs no full compile, so style errors fail early. --check reports differences and exits non-zero without writing files. Plain cargo fmt would only rewrite the temporary CI checkout, and the job would pass without the fix ever reaching the repository.