Better more reliable path normalization

This commit is contained in:
Jeremy Wall 2021-03-10 20:45:06 -05:00
parent 04a97a7002
commit 5a20012fcb

View File

@ -692,30 +692,23 @@ impl Rewriter {
} }
} }
fn normalize_path(p: PathBuf) -> PathBuf {
let mut normalized = PathBuf::new();
for segment in p.components() {
normalized.push(segment);
}
return normalized;
}
impl walk::Walker for Rewriter { impl walk::Walker for Rewriter {
fn visit_expression(&mut self, expr: &mut Expression) { fn visit_expression(&mut self, expr: &mut Expression) {
// Rewrite all paths except for stdlib paths to absolute. // Rewrite all paths except for stdlib paths to absolute.
let main_separator = format!("{}", std::path::MAIN_SEPARATOR); let main_separator = format!("{}", std::path::MAIN_SEPARATOR);
if let Expression::Include(ref mut def) = expr { if let Expression::Include(ref mut def) = expr {
let path = PathBuf::from(&def.path.fragment); let path = PathBuf::from(&def.path.fragment);
#[cfg(not(windows))] def.path.fragment = normalize_path(self.base.join(path))
{ .to_string_lossy()
if path.is_relative() { .to_string();
def.path.fragment = self
.base
.join(path)
.canonicalize()
.unwrap()
.to_string_lossy()
.to_string();
}
}
#[cfg(windows)]
{
if path.is_relative() {
def.path.fragment = self.base.join(path).to_string_lossy().to_string();
}
}
} }
if let Expression::Import(ref mut def) = expr { if let Expression::Import(ref mut def) = expr {
let path = PathBuf::from( let path = PathBuf::from(
@ -728,24 +721,9 @@ impl walk::Walker for Rewriter {
if path.starts_with(format!("std{}", main_separator)) { if path.starts_with(format!("std{}", main_separator)) {
return; return;
} }
#[cfg(not(windows))] def.path.fragment = normalize_path(self.base.join(path))
{ .to_string_lossy()
if path.is_relative() { .to_string();
def.path.fragment = self
.base
.join(path)
.canonicalize()
.unwrap()
.to_string_lossy()
.to_string();
}
}
#[cfg(windows)]
{
if path.is_relative() {
def.path.fragment = self.base.join(path).to_string_lossy().to_string();
}
}
} }
} }
} }