Normalize a filesystem path by collapsing redundant separators and removing trailing slashes, without requiring the path to exist on disk. This is a lexical normalization only — it does NOT resolve symlinks or check the filesystem. `..` components are preserved verbatim; callers that need to reject parent traversal must validate separately.
(path: &str)
| 135 | /// check the filesystem. `..` components are preserved verbatim; callers that |
| 136 | /// need to reject parent traversal must validate separately. |
| 137 | pub fn normalize_path(path: &str) -> String { |
| 138 | use std::path::Component; |
| 139 | |
| 140 | let p = Path::new(path); |
| 141 | let mut normalized = PathBuf::new(); |
| 142 | for component in p.components() { |
| 143 | match component { |
| 144 | Component::Prefix(prefix) => normalized.push(prefix.as_os_str()), |
| 145 | #[allow(clippy::path_buf_push_overwrite)] |
| 146 | Component::RootDir => normalized.push("/"), |
| 147 | Component::CurDir => {} // skip "." |
| 148 | Component::ParentDir => { |
| 149 | // Keep ".." — validation will catch it separately |
| 150 | normalized.push(".."); |
| 151 | } |
| 152 | Component::Normal(c) => normalized.push(c), |
| 153 | } |
| 154 | } |
| 155 | normalized.to_string_lossy().to_string() |
| 156 | } |
| 157 | |
| 158 | #[cfg(test)] |
| 159 | mod tests { |