Skip to main content

indigo_core/
path.rs

1use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
2use pathdiff::diff_utf8_paths;
3
4#[must_use]
5pub fn display_path(home: &Utf8Path, pwd: &Utf8Path, path: &Utf8Path) -> String {
6    // If we're under `$PWD`, use a relative path.
7    let absolute = normalize(&pwd.join(path));
8    if let Ok(relative) = absolute.strip_prefix(pwd) {
9        return relative.to_string();
10    }
11    // If we're outside `$PWD`, use the shortest option (preferring absolute, then `~`, on ties).
12    let mut shortest = absolute.clone();
13    if let Ok(relative) = absolute.strip_prefix(home) {
14        let tilde = Utf8Path::new("~").join(relative);
15        if tilde.as_str().len() < shortest.as_str().len() {
16            shortest = tilde;
17        }
18    }
19    if let Some(relative) = diff_utf8_paths(&absolute, pwd)
20        && relative.as_str().len() < shortest.as_str().len()
21    {
22        shortest = relative;
23    }
24    shortest.into_string()
25}
26
27#[must_use]
28pub fn absolute_path(home: &Utf8Path, pwd: &Utf8Path, path: &Utf8Path) -> Utf8PathBuf {
29    // If the path starts with `~`, join it onto `$HOME`.
30    if let Ok(relative) = path.strip_prefix("~") {
31        return home.join(relative);
32    }
33    // Otherwise join it onto `$PWD`, which does nothing to absolute paths. Don't resolve `..`
34    // components, because that requires following symlinks to get right.
35    pwd.join(path)
36}
37
38/// Resolve `.` and `..` components without touching the filesystem, preserving symlinks.
39fn normalize(path: &Utf8Path) -> Utf8PathBuf {
40    let mut normalized = Utf8PathBuf::new();
41    for component in path.components() {
42        match component {
43            Utf8Component::CurDir => {}
44            Utf8Component::ParentDir => _ = normalized.pop(),
45            component => normalized.push(component),
46        }
47    }
48    normalized
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use hegel::generators as gs;
55
56    #[test]
57    fn test_display_path() {
58        for (pwd, path, expected) in [
59            // Paths under `$PWD` are shown relative to it.
60            ("/me/src/indigo", "/me/src/indigo/Cargo.toml", "Cargo.toml"),
61            ("/me/src/indigo", "./src/../Cargo.toml", "Cargo.toml"),
62            ("/me/src/indigo", "../indigo/Cargo.toml", "Cargo.toml"),
63            // Paths outside `$PWD` are shown as whichever is shortest: relative to `$PWD`,
64            // relative to `~`, or absolute (preferring absolute, then `~`, on ties).
65            ("/me/src/indigo", "/etc/shells", "/etc/shells"),
66            ("/me/src/indigo", "../../../etc/shells", "/etc/shells"),
67            ("/me/src/indigo", "/me/src/kak/README", "../kak/README"),
68            ("/me/src/indigo", "../kak/README", "../kak/README"),
69            ("/me/src/indigo", "../../Library/foo", "~/Library/foo"),
70            ("/", "me/foo", "me/foo"),
71        ] {
72            let display_path = display_path("/me".into(), pwd.into(), path.into());
73            assert_eq!(display_path, expected, "{path} in {pwd}");
74        }
75    }
76
77    #[test]
78    fn test_absolute_path() {
79        for (path, expected) in [
80            ("~/foo", "/me/foo"),
81            ("~user/foo", "/me/src/indigo/~user/foo"),
82            ("foo/~", "/me/src/indigo/foo/~"),
83            ("../foo", "/me/src/indigo/../foo"),
84            ("/etc/shells", "/etc/shells"),
85        ] {
86            let absolute_path = absolute_path("/me".into(), "/me/src/indigo".into(), path.into());
87            assert_eq!(absolute_path, expected, "{path}");
88        }
89    }
90
91    #[hegel::composite]
92    fn gen_path(tc: &hegel::TestCase, root: &'static str) -> String {
93        let components = gs::vecs(gs::sampled_from(vec!["a", "b", ".", ".."])).max_size(6);
94        root.to_owned() + &tc.draw(components).join("/")
95    }
96
97    #[hegel::test(test_cases = 5_000)]
98    fn display_path_points_to_same_place(tc: hegel::TestCase) {
99        let home = normalize(Utf8Path::new(&tc.draw(gen_path("/"))));
100        let pwd = normalize(Utf8Path::new(&tc.draw(gen_path("/"))));
101        let path = tc.draw(gen_path(tc.draw(gs::sampled_from(vec!["", "/"]))));
102        let absolute = normalize(&pwd.join(&path));
103
104        let display_path = display_path(&home, &pwd, path.as_str().into());
105
106        let resolved = absolute_path(&home, &pwd, display_path.as_str().into());
107        assert_eq!(normalize(&resolved), absolute);
108        assert!(display_path.len() <= absolute.as_str().len());
109        if absolute.starts_with(&pwd) {
110            assert!(!display_path.starts_with(['/', '~']) && !display_path.contains(".."));
111        }
112    }
113}