Auto formatting with VS Code / rustfmt different from with `cargo fmt`

I'm trying to use an unstable version of rustfmt for some config options that aren't in stable yet.
When I run via cargo +nightly fmt things work as expected.
When I run via rustup run nightly -- rustfmt, I get a different (and incorrect) output.
I'm guessing there is a bug in the version of rustfmt invoked by rustup (I can describe later), but I really just want to figure out how to get VS Code to do the same thing that cargo +nightly fmt is doing but so far I haven't figured out how to do that. Any tips?

The (maybe) bug is that rustup run nightly -- rustfmt removes the leading double colon from a use line when it should not in a way that breaks the code. The use line is like use ::foo::bar, and there happens to be a submodule named foo as well, but it doesn't contain bar.
Should I try to report a bug about this? I searched briefly on GitHub and couldn't find anything.

I'm on MacOS:
➜ which cargo
/Users/garymm/.cargo/bin/cargo

➜ which rustup
/opt/homebrew/bin/rustup

➜ cargo +nightly fmt --version
rustfmt 1.8.0-nightly (28fc2ba714 2024-11-24)

➜ rustup run nightly -- rustfmt --version
rustfmt 1.8.0-nightly (28fc2ba714 2024-11-24)

Running verbose (-v) cargo fmt shows there’s an --edition argument you might be missing here; e.g. in an edition 2021 project, I do

$ cargo +nightly fmt -v
[bin (2021)] "/…path to project…/src/main.rs"
$ rustfmt --edition 2021 /…path to project…/src/main.rs

and see it passes --edition 2021, too. With that added to your command, the behavior should then hopefully be the same?

To skip the need to hardcode the 2021, it looks like another approach might be to skip the rust-analyzer.rustfmt.overrideCommand setting and instead just add something like

"rust-analyzer.rustfmt.extraArgs": [
    "+nightly"
],

at least according to this comment

1 Like