Skip to main content

git_policy_cli/foundation/
lexical_path.rs

1//! What:
2//!  Lexical path normalization, the way Node's `path.resolve` does it.
3//! Why:
4//!  `git cli-git doctor` scans each hooks directory once, so one directory named two ways (`./hooks`, `hooks/`,
5//!  `a/../hooks`) must compare equal without touching the file system.
6//!
7//! In TS you'd write (pseudocode):
8//! ```ts
9//! path.resolve(path);
10//! ```
11
12/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
13use std::path::{Component, Path, PathBuf};
14
15/// What:
16///  Normalize a path lexically: drop `.`, fold `..` into the component before it, never above the root.
17/// Why:
18///   `PathBuf::join` keeps `.` and `..`, and a `..` above the root stays at the root, as Node clamps it.
19///
20/// In TS you'd write (pseudocode):
21/// ```ts
22/// path.resolve(path);
23/// ```
24pub fn normalized_path(path: &Path) -> PathBuf {
25    // `mut` lets the result grow and shrink as components arrive.
26    let mut result: PathBuf = PathBuf::new();
27    for component in path.components() {
28        match component {
29            Component::Prefix(_) | Component::RootDir => {
30                result.push(component.as_os_str());
31            }
32            Component::CurDir => {}
33            Component::ParentDir => {
34                let at_root: bool = result.parent().is_none();
35                if !at_root && result.file_name().is_some() {
36                    result.pop();
37                }
38            }
39            Component::Normal(name) => {
40                result.push(name);
41            }
42        }
43    }
44    return result;
45}
46
47/// Normalization is controlled in the test module.
48#[cfg(test)]
49#[path = "lexical_path_tests.rs"]
50mod tests;