Skip to content

Commit 7d9e4fc

Browse files
fix: do not assume rustup is installed in xtask codegen
When formatting generated code the xtask crate attempts to run `rustup run stable rustfmt`, which fails if `rustup` is not installed. This results in test failures when another source manages the compiler toolchain, for example when using Nix (or any other distro-specific packaging solution): * xtask::codegen::grammar::test * xtask::codegen::assists_doc_tests::test With this commit xtask will first attempt to run `rustup run stable rustfmt`, and if that fails just plain `rustfmt`. It still validates a stable version is being used. This allows `cargo test` to pass on systems that do not use `rustup`.
1 parent 0f7f68d commit 7d9e4fc

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

xtask/src/codegen.rs

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -126,27 +126,31 @@ impl fmt::Display for Location {
126126
}
127127
}
128128

129-
fn ensure_rustfmt(sh: &Shell) {
130-
let version = cmd!(sh, "rustup run stable rustfmt --version").read().unwrap_or_default();
131-
if !version.contains("stable") {
132-
panic!(
133-
"Failed to run rustfmt from toolchain 'stable'. \
134-
Please run `rustup component add rustfmt --toolchain stable` to install it.",
135-
);
129+
fn rustfmt_executable(sh: &Shell) -> &str {
130+
// First try explicitly requesting the stable channel via rustup in case nightly is being used by default,
131+
// then plain rustfmt in case rustup isn't being used to manage the compiler (e.g. when using Nix).
132+
for executable in ["rustup run stable rustfmt", "rustfmt"] {
133+
let version = cmd!(sh, "{executable} --version").read().unwrap_or_default();
134+
if version.contains("stable") {
135+
return executable;
136+
}
136137
}
138+
139+
panic!(
140+
"Failed to run rustfmt from toolchain 'stable'. \
141+
Please run `rustup component add rustfmt --toolchain stable` to install it.",
142+
);
137143
}
138144

139145
fn reformat(text: String) -> String {
140146
let sh = Shell::new().unwrap();
141-
ensure_rustfmt(&sh);
147+
let rustfmt_exe = rustfmt_executable(&sh);
142148
let rustfmt_toml = project_root().join("rustfmt.toml");
143-
let mut stdout = cmd!(
144-
sh,
145-
"rustup run stable rustfmt --config-path {rustfmt_toml} --config fn_single_line=true"
146-
)
147-
.stdin(text)
148-
.read()
149-
.unwrap();
149+
let mut stdout =
150+
cmd!(sh, "{rustfmt_exe} --config-path {rustfmt_toml} --config fn_single_line=true")
151+
.stdin(text)
152+
.read()
153+
.unwrap();
150154
if !stdout.ends_with('\n') {
151155
stdout.push('\n');
152156
}

0 commit comments

Comments
 (0)