From 2974416a81a64d75e0dc1c394b75fecd96230713 Mon Sep 17 00:00:00 2001 From: David Barsky Date: Tue, 12 Sep 2023 14:35:24 -0400 Subject: [PATCH] fix: ensure `rustfmt` runs when configured with `./` --- crates/rust-analyzer/src/handlers/request.rs | 41 +++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs index b8a1a39be19..ad6319586cf 100644 --- a/crates/rust-analyzer/src/handlers/request.rs +++ b/crates/rust-analyzer/src/handlers/request.rs @@ -4,6 +4,7 @@ use std::{ fs, io::Write as _, + path::PathBuf, process::{self, Stdio}, }; @@ -1995,7 +1996,43 @@ fn run_rustfmt( cmd } RustfmtConfig::CustomCommand { command, args } => { - let mut cmd = process::Command::new(command); + let cmd = PathBuf::from(&command); + let mut components = cmd.components(); + + // to support rustc's suggested, default configuration + let mut cmd = match components.next() { + Some(std::path::Component::CurDir) => { + let rest = components.as_path(); + + let roots = snap + .workspaces + .iter() + .flat_map(|ws| ws.workspace_definition_path()) + .collect::>(); + + let abs: Option = roots.into_iter().find_map(|base| { + let abs = base.join(rest); + std::fs::metadata(&abs).ok().map(|_| abs) + }); + + let command = match abs { + Some(cmd) => cmd, + None => { + tracing::error!( + rustfmt = ?command, + "Unable to make the format command an absolute path" + ); + anyhow::bail!( + "Unable to make the format command an absolute path: {}", + command + ); + } + }; + + process::Command::new(&command.as_os_str()) + } + _ => process::Command::new(command), + }; cmd.envs(snap.config.extra_env()); cmd.args(args); @@ -2003,6 +2040,8 @@ fn run_rustfmt( } }; + tracing::debug!(?command, "created format command"); + // try to chdir to the file so we can respect `rustfmt.toml` // FIXME: use `rustfmt --config-path` once // https://github.com/rust-lang/rustfmt/issues/4660 gets fixed