2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2020-09-21 08:26:41 -04:00
|
|
|
|
2020-08-12 16:34:17 -04:00
|
|
|
use std::path::Component;
|
|
|
|
use std::path::Path;
|
|
|
|
use std::path::PathBuf;
|
|
|
|
|
2020-10-23 07:19:37 -04:00
|
|
|
/// Normalize all intermediate components of the path (ie. remove "./" and "../" components).
|
2020-08-12 16:34:17 -04:00
|
|
|
/// Similar to `fs::canonicalize()` but doesn't resolve symlinks.
|
|
|
|
///
|
|
|
|
/// Taken from Cargo
|
2021-09-05 10:22:45 -04:00
|
|
|
/// <https://github.com/rust-lang/cargo/blob/af307a38c20a753ec60f0ad18be5abed3db3c9ac/src/cargo/util/paths.rs#L60-L85>
|
2022-08-27 11:20:05 -04:00
|
|
|
#[inline]
|
2021-03-24 20:13:37 -04:00
|
|
|
pub fn normalize_path<P: AsRef<Path>>(path: P) -> PathBuf {
|
|
|
|
let mut components = path.as_ref().components().peekable();
|
2020-08-12 16:34:17 -04:00
|
|
|
let mut ret =
|
|
|
|
if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
|
|
|
|
components.next();
|
|
|
|
PathBuf::from(c.as_os_str())
|
|
|
|
} else {
|
|
|
|
PathBuf::new()
|
|
|
|
};
|
|
|
|
|
|
|
|
for component in components {
|
|
|
|
match component {
|
|
|
|
Component::Prefix(..) => unreachable!(),
|
|
|
|
Component::RootDir => {
|
|
|
|
ret.push(component.as_os_str());
|
|
|
|
}
|
|
|
|
Component::CurDir => {}
|
|
|
|
Component::ParentDir => {
|
|
|
|
ret.pop();
|
|
|
|
}
|
|
|
|
Component::Normal(c) => {
|
|
|
|
ret.push(c);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ret
|
|
|
|
}
|