Allow xtask::reformat to work without rustup

This commit is contained in:
Lukas Wirth 2024-08-30 16:17:45 +02:00
parent e69d57f16f
commit 6b15103152

View File

@ -126,27 +126,35 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
} }
} }
fn ensure_rustfmt(sh: &Shell) { fn reformat(text: String) -> String {
let sh = Shell::new().unwrap();
let rustfmt_toml = project_root().join("rustfmt.toml");
let version = cmd!(sh, "rustup run stable rustfmt --version").read().unwrap_or_default(); let version = cmd!(sh, "rustup run stable rustfmt --version").read().unwrap_or_default();
// First try explicitly requesting the stable channel via rustup in case nightly is being used by default,
// then plain rustfmt in case rustup isn't being used to manage the compiler (e.g. when using Nix).
let mut stdout = if !version.contains("stable") {
let version = cmd!(sh, "rustfmt --version").read().unwrap_or_default();
if !version.contains("stable") { if !version.contains("stable") {
panic!( panic!(
"Failed to run rustfmt from toolchain 'stable'. \ "Failed to run rustfmt from toolchain 'stable'. \
Please run `rustup component add rustfmt --toolchain stable` to install it.", Please run `rustup component add rustfmt --toolchain stable` to install it.",
); );
} else {
cmd!(sh, "rustfmt --config-path {rustfmt_toml} --config fn_single_line=true")
.stdin(text)
.read()
.unwrap()
} }
} } else {
cmd!(
fn reformat(text: String) -> String {
let sh = Shell::new().unwrap();
ensure_rustfmt(&sh);
let rustfmt_toml = project_root().join("rustfmt.toml");
let mut stdout = cmd!(
sh, sh,
"rustup run stable rustfmt --config-path {rustfmt_toml} --config fn_single_line=true" "rustup run stable rustfmt --config-path {rustfmt_toml} --config fn_single_line=true"
) )
.stdin(text) .stdin(text)
.read() .read()
.unwrap(); .unwrap()
};
if !stdout.ends_with('\n') { if !stdout.ends_with('\n') {
stdout.push('\n'); stdout.push('\n');
} }