`cargo fmt --check` in CI

I would like to automatically check that the commits in a Rust project on GitHub are well-formatted.
Thus, I added the following lines in the step field of the rust.yml file of the repo.

- name: Format check
  run: cargo fmt --check

However, CI fails because cargo-fmt is not installed on the toolchain. Here is some excerpt from the error log:

error: 'cargo-fmt' is not installed for the toolchain 'nightly-2023-01-01-x86_64-unknown-linux-gnu'
To install, run `rustup component add rustfmt --toolchain nightly-2023-01-01-x86_64-unknown-linux-gnu`
Error: Process completed with exit code 1.

I installed rustfmt as per GitHub - rust-lang/rustfmt: Format Rust code and
cargo search rustfmt gave me, among other results:

rustfmt = "0.10.0"            
rustfmt-nightly = "1.4.21" 

I updated the Cargo.toml file with

rustfmt-nightly = "1.4.21"

and trying other version numbers suggested by Vscode, but nothing works.
How can I make cargo fmt work in my CI?

The error message tells you exactly how to install rustfmt for your current toolchain. If you execute this before the cargo fmt --check the CI should have rustfmt available and everything should work.

You are using a specific nightly version, though. That must come from somewhere. You can probably add rustfmt as a required component there. How exactly you do that depends on the installation step, which you didn't provide. If you use a rust-toolchain.toml you can list it under components: Overrides - The rustup book.

The linked repository does not tell you any of the steps you took. In general, tools you need are never listed in the Cargo.toml. The Cargo.toml file only contains dependencies your code needs to compile, run, and/or test. Tools around that, for example to check formatting, benchmarking, or code coverage analysis, are not listed in the Cargo.toml.

1 Like

Thanks a lot! I just removed any reference to rustfmt in the Cargo.toml and put it in the components field of the toolchain file, and this now compiles.
Putting the rustup instruction in the yml file didn't work though

FYI, on GitHub I quite often use the the actions defined in the organization actions-rs.

Edit: dtolnay also made an action GitHub - dtolnay/rust-toolchain: Concise GitHub Action for installing a Rust toolchain

1 Like

I like this setup-rust-toolchain if you need support for toolchain files.
The actions-rs organization is effectively abandoned and dtolnay made it clear that there will never be support for toolchain files in rust-toolchain.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.