Ensure that fn config_path returns canonicalized paths.

This commit ensures that `fn config_path` in `rustfmt/src/config/mod.rs`
always returns canonicalized paths.  This is achieved by canonicalizing
both: 1) paths received via `CliOptions` (after checking if the path
exists) as well as 2) paths returned via `get_toml_path` (canonicalizing
within `fn get_toml_path`).

Fixes https://github.com/rust-lang/rustfmt/issues/6178
This commit is contained in:
Lukasz Anforowicz 2024-08-07 23:35:33 +00:00 committed by Yacin Tmimi
parent 68dc912b99
commit caaa612a0b
2 changed files with 9 additions and 2 deletions

View File

@ -378,7 +378,7 @@ fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
match fs::metadata(&config_file) { match fs::metadata(&config_file) {
// Only return if it's a file to handle the unlikely situation of a directory named // Only return if it's a file to handle the unlikely situation of a directory named
// `rustfmt.toml`. // `rustfmt.toml`.
Ok(ref md) if md.is_file() => return Ok(Some(config_file)), Ok(ref md) if md.is_file() => return Ok(Some(config_file.canonicalize()?)),
// Return the error if it's something other than `NotFound`; otherwise we didn't // Return the error if it's something other than `NotFound`; otherwise we didn't
// find the project file yet, and continue searching. // find the project file yet, and continue searching.
Err(e) => { Err(e) => {
@ -417,7 +417,11 @@ fn config_path(options: &dyn CliOptions) -> Result<Option<PathBuf>, Error> {
config_path_not_found(path.to_str().unwrap()) config_path_not_found(path.to_str().unwrap())
} }
} }
path => Ok(path.map(ToOwned::to_owned)), Some(path) => Ok(Some(
// Canonicalize only after checking above that the `path.exists()`.
path.canonicalize()?,
)),
None => Ok(None),
} }
} }

View File

@ -415,6 +415,9 @@ fn from_str(_: &str) -> Result<Self, Self::Err> {
/// values in a config with values from the command line. /// values in a config with values from the command line.
pub trait CliOptions { pub trait CliOptions {
fn apply_to(self, config: &mut Config); fn apply_to(self, config: &mut Config);
/// It is ok if the returned path doesn't exist or is not canonicalized
/// (i.e. the callers are expected to handle such cases).
fn config_path(&self) -> Option<&Path>; fn config_path(&self) -> Option<&Path>;
} }