rw_deno_core/
normalize_path.rs

1// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
3use std::path::Component;
4use std::path::Path;
5use std::path::PathBuf;
6
7/// Normalize all intermediate components of the path (ie. remove "./" and "../" components).
8/// Similar to `fs::canonicalize()` but doesn't resolve symlinks.
9///
10/// Taken from Cargo
11/// <https://github.com/rust-lang/cargo/blob/af307a38c20a753ec60f0ad18be5abed3db3c9ac/src/cargo/util/paths.rs#L60-L85>
12#[inline]
13pub fn normalize_path<P: AsRef<Path>>(path: P) -> PathBuf {
14  let mut components = path.as_ref().components().peekable();
15  let mut ret =
16    if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
17      components.next();
18      PathBuf::from(c.as_os_str())
19    } else {
20      PathBuf::new()
21    };
22
23  for component in components {
24    match component {
25      Component::Prefix(..) => unreachable!(),
26      Component::RootDir => {
27        ret.push(component.as_os_str());
28      }
29      Component::CurDir => {}
30      Component::ParentDir => {
31        ret.pop();
32      }
33      Component::Normal(c) => {
34        ret.push(c);
35      }
36    }
37  }
38  ret
39}