Skip to main content

specfold_core/paths/
lexical.rs

1//! Slash-separated paths cleaned up as text: `.` and `..` resolved without the file system.
2
3/// `a/./b/../c` as `a/c`; `None` when it climbs above where it starts.
4pub fn normalize(path: &str) -> Option<String> {
5    let mut out: Vec<&str> = vec![];
6    for part in path.split('/') {
7        match part {
8            "" | "." => {}
9            ".." => {
10                out.pop()?;
11            }
12            p => out.push(p),
13        }
14    }
15    Some(out.join("/"))
16}
17
18/// A link read from the folder `dir`: `docs/adr` and `../x/./y.md` give `docs/x/y.md`; `None`
19/// when it climbs above the root. Only the link is cleaned up; `dir` is taken as given.
20pub fn join(dir: &str, link: &str) -> Option<String> {
21    let mut parts: Vec<&str> = dir.split('/').filter(|s| !s.is_empty()).collect();
22    for seg in link.split('/') {
23        match seg {
24            "" | "." => {}
25            ".." => {
26                parts.pop()?;
27            }
28            s => parts.push(s),
29        }
30    }
31    Some(parts.join("/"))
32}
33
34/// Like [`normalize`], for keys that must stay comparable when the path leaves its start: a `..`
35/// with nothing left to remove is kept, and `\` separates like `/`.
36pub fn normalize_keeping_up(path: &str) -> String {
37    let mut parts: Vec<&str> = vec![];
38    for c in path.split(['/', '\\']) {
39        match c {
40            "" | "." => {}
41            ".." if parts.last().is_some_and(|l| *l != "..") => {
42                parts.pop();
43            }
44            other => parts.push(other),
45        }
46    }
47    parts.join("/")
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn normalize_resolves_dots_and_refuses_climbing_out() {
56        let cases: &[(&str, Option<&str>)] = &[
57            ("a/b/../c", Some("a/c")),
58            ("a/./b/../c", Some("a/c")),
59            ("./a//b/", Some("a/b")),
60            ("a/..", Some("")),
61            ("", Some("")),
62            ("../x", None),
63            ("a/../../x", None),
64        ];
65        for (input, want) in cases {
66            assert_eq!(normalize(input).as_deref(), *want, "{input}");
67        }
68    }
69
70    #[test]
71    fn join_reads_the_link_from_the_folder() {
72        let cases: &[(&str, &str, Option<&str>)] = &[
73            ("doc/adr", "../x/./y.md", Some("doc/x/y.md")),
74            ("", "../y.md", None),
75            ("", "a.md", Some("a.md")),
76            ("docs/", "./a.md", Some("docs/a.md")),
77            ("a/b", "../../c.md", Some("c.md")),
78            ("a/b", "../../../c.md", None),
79        ];
80        for (dir, link, want) in cases {
81            assert_eq!(join(dir, link).as_deref(), *want, "{dir} + {link}");
82        }
83    }
84
85    #[test]
86    fn normalize_keeping_up_keeps_leading_parents() {
87        let cases: &[(&str, &str)] = &[
88            ("./b.json", "b.json"),
89            ("x/../b.json", "b.json"),
90            ("../b.json", "../b.json"),
91            ("../../a/../b", "../../b"),
92            ("a\\b\\..\\c", "a/c"),
93            ("", ""),
94        ];
95        for (input, want) in cases {
96            assert_eq!(normalize_keeping_up(input), *want, "{input}");
97        }
98    }
99}