1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//! Normalizes paths similarly to canonicalize, but without performing I/O.
//!
//! This is like Python's `os.path.normpath`.
//!
//! Initially adapted from [Cargo's implementation][cargo-paths].
//!
//! [cargo-paths]: https://github.com/rust-lang/cargo/blob/fede83ccf973457de319ba6fa0e36ead454d2e20/src/cargo/util/paths.rs#L61
//!
//! # Example
//!
//! ```
//! use normalize_path::NormalizePath;
//! use std::path::Path;
//!
//! assert_eq!(
//!     Path::new("/A/foo/../B/./").normalize(),
//!     Path::new("/A/B")
//! );
//! ```

use std::path::{Component, Path, PathBuf};

/// Extension trait to add `normalize_path` to std's [`Path`].
pub trait NormalizePath {
    /// Normalize a path without performing I/O.
    ///
    /// All redundant separator and up-level references are collapsed.
    ///
    /// However, this does not resolve links.
    fn normalize(&self) -> PathBuf;

    /// Same as [`NormalizePath::normalize`] except that if
    /// `Component::Prefix`/`Component::RootDir` is encountered,
    /// or if the path points outside of current dir, returns `None`.
    fn try_normalize(&self) -> Option<PathBuf>;

    /// Return `true` if the path is normalized.
    ///
    /// # Quirk
    ///
    /// If the path does not start with `./` but contains `./` in the middle,
    /// then this function might returns `true`.
    fn is_normalized(&self) -> bool;
}

impl NormalizePath for Path {
    fn normalize(&self) -> PathBuf {
        let mut components = self.components().peekable();
        let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek() {
            let buf = PathBuf::from(c.as_os_str());
            components.next();
            buf
        } 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
    }

    fn try_normalize(&self) -> Option<PathBuf> {
        let mut ret = PathBuf::new();

        for component in self.components() {
            match component {
                Component::Prefix(..) | Component::RootDir => return None,
                Component::CurDir => {}
                Component::ParentDir => {
                    if !ret.pop() {
                        return None;
                    }
                }
                Component::Normal(c) => {
                    ret.push(c);
                }
            }
        }

        Some(ret)
    }

    fn is_normalized(&self) -> bool {
        for component in self.components() {
            match component {
                Component::CurDir | Component::ParentDir => {
                    return false;
                }
                _ => continue,
            }
        }

        true
    }
}