pub fn normal_path(text: &str) -> String {
let absolute = text.starts_with('/');
let parts: Vec<&str> = text
.split('/')
.filter(|part| !part.is_empty() && *part != ".")
.collect();
let joined = parts.join("/");
match (absolute, joined.is_empty()) {
(true, _) => format!("/{joined}"),
(false, true) => ".".to_owned(),
(false, false) => joined,
}
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
#[test]
fn the_normal_form_drops_empty_and_dot_components_and_keeps_every_dot_dot() {
for (text, normal) in [
("a//b/./c/", "a/b/c"),
("", "."),
(".", "."),
("/", "/"),
("//./", "/"),
("/../x", "/../x"),
("a/../b", "a/../b"),
("a\0b", "a\0b"),
] {
assert_eq!(normal_path(text), normal, "{text:?}");
assert_eq!(normal_path(normal), normal, "{normal:?}");
}
for spelled in ["a//b", "", "a/"] {
assert_ne!(normal_path(spelled), spelled, "{spelled:?}");
}
}
}