Skip to main content

cuno_core/
paths.rs

1//! Whether two paths are the same place, or one lies inside the other: the
2//! one answer every crate asks (`docs/en/specs/project-layout.md`, "Source
3//! collection and linking"; `docs/en/specs/architecture.md`, "What goes in
4//! `cuno-core`"). Only comparing uses where a path leads; the path a caller
5//! goes on to use or show stays as written, unless the caller normalizes it
6//! with [`lexical`] on purpose (the output directory is, once).
7
8use std::ffi::{OsStr, OsString};
9use std::path::{Component, Path, PathBuf, Prefix};
10
11use crate::NameCase;
12use crate::env::fold;
13
14/// `path` written without Windows' `\\?\` prefix: `\\?\C:\a` as `C:\a`,
15/// `\\?\UNC\server\share\a` as `\\server\share\a`, and any other path
16/// unchanged. `None` when the plain form would name another place: under
17/// `\\?\`, a `.` or `..` part, a name ending in `.` or a space, a `/` in a
18/// name and a device name (`CON`, `NUL`, `COM1`, ... with or without an
19/// extension) are taken literally. A verbatim prefix that is neither a
20/// drive with its root nor a share with a server and a name has no plain
21/// form either: `C:` alone is that drive's current directory, and `\\s\` a
22/// path on the current drive. See docs/en/specs/build.md, "Output
23/// directory". A `\\.\` path is not this rule's, and is left as it is.
24pub fn plain(path: &Path) -> Option<PathBuf> {
25    let mut parts = path.components().peekable();
26    let Some(Component::Prefix(prefix)) = parts.next() else {
27        return Some(path.to_owned());
28    };
29    let mut out = match prefix.kind() {
30        Prefix::VerbatimDisk(drive) if parts.peek() == Some(&Component::RootDir) => {
31            PathBuf::from(format!("{}:", char::from(drive)))
32        }
33        Prefix::VerbatimUNC(server, share) if !server.is_empty() && !share.is_empty() => {
34            let mut unc = OsString::from(r"\\");
35            unc.push(server);
36            unc.push(r"\");
37            unc.push(share);
38            PathBuf::from(unc)
39        }
40        Prefix::VerbatimDisk(_) | Prefix::VerbatimUNC(..) | Prefix::Verbatim(_) => return None,
41        Prefix::DeviceNS(_) | Prefix::Disk(_) | Prefix::UNC(..) => return Some(path.to_owned()),
42    };
43    for part in parts {
44        match part {
45            Component::RootDir => out.push(r"\"),
46            Component::Normal(name) if survives(name) => out.push(name),
47            _ => return None,
48        }
49    }
50    Some(out)
51}
52
53/// Whether `name`, a part of a `\\?\` path, names the same thing without
54/// the prefix.
55fn survives(name: &OsStr) -> bool {
56    let bytes = name.as_encoded_bytes();
57    if bytes.contains(&b'/') || bytes.ends_with(b".") || bytes.ends_with(b" ") {
58        return false;
59    }
60    // The part before the first `.`, as Windows matches device names.
61    let stem = bytes.split(|b| *b == b'.').next().unwrap_or(bytes);
62    let stem = stem.trim_ascii_end();
63    let device = |prefix: &[u8]| {
64        stem.len() == 4 && stem[..3].eq_ignore_ascii_case(prefix) && matches!(stem[3], b'1'..=b'9')
65    };
66    !([b"CON", b"PRN", b"AUX", b"NUL"]
67        .iter()
68        .any(|d| stem.eq_ignore_ascii_case(*d))
69        || device(b"COM")
70        || device(b"LPT"))
71}
72
73/// `path` with `.` dropped and each `..` taking the part before it away.
74pub fn lexical(path: &Path) -> PathBuf {
75    let mut out = PathBuf::new();
76    for part in path.components() {
77        match part {
78            Component::CurDir => {}
79            Component::ParentDir => {
80                out.pop();
81            }
82            other => out.push(other),
83        }
84    }
85    out
86}
87
88/// Where a path leads, ready to be compared many times: work out the
89/// [`Place`] of each path once, then ask it as often as needed.
90#[derive(Clone, Debug)]
91pub struct Place {
92    /// The path as the file system names it: see [`Place::of`].
93    real: PathBuf,
94    /// Each part of `real` as compared.
95    parts: Vec<String>,
96}
97
98impl Place {
99    /// Where `path` leads, whether or not it exists yet: `.` and `..`
100    /// resolved, and its longest existing part canonicalized, so a link or a
101    /// short name is where it leads; the part that does not exist yet is
102    /// kept as written. The existing part is compared as the file system
103    /// spells it, and only the rest is folded when `case` ignores case,
104    /// since no folding table cuno could hold is the file system's own. A
105    /// relative path is only resolved by name, since a library does not
106    /// read the process's current directory.
107    pub fn of(path: &Path, case: NameCase) -> Place {
108        let (real, exact) = resolve(path);
109        let parts = real
110            .components()
111            .enumerate()
112            .map(|(i, component)| part(component, if i < exact { None } else { Some(case) }))
113            .collect();
114        Place { real, parts }
115    }
116
117    /// Whether `self` and `other` are the same place.
118    pub fn same(&self, other: &Place) -> bool {
119        self.parts == other.parts
120    }
121
122    /// Whether `self` is `dir` or lies under it.
123    pub fn within(&self, dir: &Place) -> bool {
124        self.relative(dir).is_some()
125    }
126
127    /// Where `self` lies under `dir`, as the file system names it: empty
128    /// when the two are the same place, `None` when `self` is not inside.
129    pub fn relative(&self, dir: &Place) -> Option<PathBuf> {
130        self.parts
131            .starts_with(&dir.parts)
132            .then(|| self.real.components().skip(dir.parts.len()).collect())
133    }
134
135    /// The directory `self` is in.
136    pub fn parent(&self) -> Option<Place> {
137        let real = self.real.parent()?.to_owned();
138        let parts = self.parts[..self.parts.len() - 1].to_vec();
139        Some(Place { real, parts })
140    }
141}
142
143/// Whether `a` and `b` are the same place: see [`Place`].
144pub fn same(a: &Path, b: &Path, case: NameCase) -> bool {
145    Place::of(a, case).same(&Place::of(b, case))
146}
147
148/// Whether `path` is `dir` or lies under it: see [`Place`].
149pub fn within(path: &Path, dir: &Path, case: NameCase) -> bool {
150    Place::of(path, case).within(&Place::of(dir, case))
151}
152
153/// Where `path` lies under `dir`: see [`Place::relative`].
154pub fn relative(path: &Path, dir: &Path, case: NameCase) -> Option<PathBuf> {
155    Place::of(path, case).relative(&Place::of(dir, case))
156}
157
158/// `path` resolved as [`Place::of`] says, and how many of its leading
159/// components the file system spelled.
160fn resolve(path: &Path) -> (PathBuf, usize) {
161    let path = lexical(path);
162    if !path.is_absolute() {
163        return (path, 0);
164    }
165    let mut existing = path.as_path();
166    let mut rest = Vec::new();
167    loop {
168        if let Ok(canonical) = std::fs::canonicalize(existing) {
169            let exact = canonical.components().count();
170            let real = rest.iter().rev().fold(canonical, |p, part| p.join(part));
171            return (real, exact);
172        }
173        match (existing.parent(), existing.file_name()) {
174            (Some(parent), Some(name)) => {
175                rest.push(name.to_owned());
176                existing = parent;
177            }
178            _ => return (path, 0),
179        }
180    }
181}
182
183/// One component as compared: a drive or share prefix in its plain form
184/// (a drive letter in either case), the root as an empty part, and a name
185/// folded per `case`, or kept when `case` is `None` because the file
186/// system spelled it.
187fn part(component: Component<'_>, case: Option<NameCase>) -> String {
188    let folded = |name: &OsStr| match case {
189        Some(case) => fold(name, case),
190        None => name.to_owned(),
191    };
192    let part = match component {
193        Component::Prefix(prefix) => match prefix.kind() {
194            Prefix::VerbatimDisk(d) | Prefix::Disk(d) => {
195                OsString::from(format!("{}:", char::from(d.to_ascii_uppercase())))
196            }
197            Prefix::VerbatimUNC(server, share) | Prefix::UNC(server, share) => {
198                let mut unc = OsString::from("//");
199                unc.push(server);
200                unc.push("/");
201                unc.push(share);
202                fold(&unc, NameCase::Insensitive)
203            }
204            _ => folded(prefix.as_os_str()),
205        },
206        Component::RootDir => OsString::new(),
207        other => folded(other.as_os_str()),
208    };
209    part.to_string_lossy().into_owned()
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    /// A fresh, empty directory for one test.
217    fn scratch(name: &str) -> PathBuf {
218        let dir = std::env::temp_dir().join(format!("cuno-paths-{}-{name}", std::process::id()));
219        let _ = std::fs::remove_dir_all(&dir);
220        std::fs::create_dir_all(&dir).unwrap();
221        dir
222    }
223
224    /// Mutation: compare without folding case; this test fails.
225    #[test]
226    fn case_is_ignored_only_where_the_file_system_ignores_it() {
227        let a = Path::new("/project/Src/Main.cpp");
228        let b = Path::new("/project/src/main.cpp");
229        assert!(same(a, b, NameCase::Insensitive));
230        assert!(!same(a, b, NameCase::Sensitive));
231    }
232
233    /// Mutation: compare paths as written, without resolving `.` and `..`,
234    /// or resolve a relative path against the current directory; this test
235    /// fails.
236    #[test]
237    fn dot_and_dot_dot_are_resolved_by_name() {
238        let case = NameCase::Sensitive;
239        assert!(same(
240            Path::new("/p/./src/../src/a.c"),
241            Path::new("/p/src/a.c"),
242            case
243        ));
244        assert!(within(Path::new("/p/src/../target"), Path::new("/p"), case));
245        assert!(!within(Path::new("/p/../q"), Path::new("/p"), case));
246        // Relative, and resolved by name only: `src` exists in the current
247        // directory of a test run, and must not become absolute.
248        let relative_path = Path::new("no-such-dir/y/../z");
249        assert!(same(relative_path, Path::new("no-such-dir/z"), case));
250        assert!(within(relative_path, Path::new("no-such-dir/."), case));
251        assert!(!within(
252            Path::new("no-such-dir/y/out"),
253            Path::new("no-such-dir/z"),
254            case
255        ));
256        assert_eq!(resolve(Path::new("src/../src")).0, PathBuf::from("src"));
257    }
258
259    /// Mutation: compare by string prefix instead of by component; this
260    /// test fails.
261    #[test]
262    fn within_takes_whole_names() {
263        let case = NameCase::Sensitive;
264        let dir = Path::new("/a/b");
265        assert!(within(Path::new("/a/b"), dir, case));
266        assert!(within(Path::new("/a/b/c"), dir, case));
267        assert!(!within(Path::new("/a/bc"), dir, case));
268        assert!(!within(Path::new("/a"), dir, case));
269        assert_eq!(
270            relative(Path::new("/a/b/c/d"), dir, case),
271            Some(PathBuf::from("c/d"))
272        );
273        assert_eq!(relative(Path::new("/a/b"), dir, case), Some(PathBuf::new()));
274    }
275
276    /// A part that does not exist yet is kept as written after the part
277    /// that does, which is canonicalized.
278    ///
279    /// Mutation: drop the part that does not exist, or fall back to the
280    /// path as written when any of it is missing; this test fails.
281    #[test]
282    fn a_path_not_there_yet_continues_from_the_part_that_is() {
283        let dir = scratch("tail");
284        let case = NameCase::host();
285        let missing = dir.join("not").join("yet");
286        let (real, _) = resolve(&missing);
287        assert!(real.ends_with("not/yet"));
288        assert!(real.starts_with(std::fs::canonicalize(&dir).unwrap()));
289        assert!(!same(&missing, &dir.join("not"), case));
290        assert!(within(&missing, &dir, case));
291        std::fs::remove_dir_all(&dir).unwrap();
292    }
293
294    /// A path written with `\\?\` and the same path without it are one
295    /// place, even where nothing of it exists for `canonicalize` to
296    /// reconcile (here, a drive that is not there).
297    ///
298    /// Mutation: keep a `\\?\` drive prefix as written; this test fails.
299    #[cfg(windows)]
300    #[test]
301    fn a_verbatim_prefix_is_the_plain_one() {
302        let drive = (b'D'..=b'Z')
303            .map(char::from)
304            .find(|d| !Path::new(&format!("{d}:\\")).exists())
305            .expect("a free drive letter");
306        let verbatim = PathBuf::from(format!(r"\\?\{drive}:\nowhere"));
307        let plain = PathBuf::from(format!(r"{drive}:\nowhere"));
308        assert!(same(&verbatim, &plain, NameCase::Insensitive));
309    }
310
311    /// A junction compares as the directory it leads to, and what lies
312    /// under it as lying under that directory.
313    ///
314    /// Mutation: compare without following links (`real` returning
315    /// [`lexical`]); this test fails.
316    #[cfg(windows)]
317    #[test]
318    fn a_junction_is_where_it_leads() {
319        let dir = scratch("junction");
320        let target = dir.join("target");
321        let link = dir.join("link");
322        std::fs::create_dir(&target).unwrap();
323        let made = std::process::Command::new("cmd")
324            .args(["/C", "mklink", "/J"])
325            .arg(&link)
326            .arg(&target)
327            .output()
328            .unwrap();
329        assert!(made.status.success(), "{made:?}");
330        let case = NameCase::Insensitive;
331        assert!(same(&link, &target, case));
332        assert!(within(&link.join("debug"), &target, case));
333        assert!(!within(&link, &dir.join("elsewhere"), case));
334        std::fs::remove_dir(&link).unwrap();
335        std::fs::remove_dir_all(&dir).unwrap();
336    }
337
338    /// Names the file system holds are compared as it spells them: `σ` and
339    /// `ς` are two files on NTFS, though simple upper-casing makes both
340    /// `Σ`. Only a part not there yet is folded.
341    ///
342    /// Mutation: fold the existing part too, or fold nothing; this test
343    /// fails.
344    #[test]
345    fn existing_names_are_compared_as_the_file_system_spells_them() {
346        let dir = scratch("spelled");
347        let case = NameCase::Insensitive;
348        for name in ["tool_σ.cpp", "tool_ς.cpp"] {
349            std::fs::write(dir.join(name), "").unwrap();
350        }
351        assert!(!same(
352            &dir.join("tool_σ.cpp"),
353            &dir.join("tool_ς.cpp"),
354            case
355        ));
356        assert!(same(&dir.join("New/Out"), &dir.join("new/out"), case));
357        std::fs::remove_dir_all(&dir).unwrap();
358    }
359
360    /// A share written with `\\?\UNC\` and without it is one share, its
361    /// server and share names in either case; so is a drive.
362    ///
363    /// Mutation: keep a `\\?\` prefix as written, or compare the server,
364    /// share or drive letter with case; this test fails.
365    #[cfg(windows)]
366    #[test]
367    fn a_share_is_one_share_however_it_is_written() {
368        let prefix = |p: &'static str| part(Path::new(p).components().next().unwrap(), None);
369        assert_eq!(
370            prefix(r"\\?\UNC\Server\Share\x"),
371            prefix(r"\\server\share\x")
372        );
373        assert_eq!(prefix(r"\\?\c:\x"), prefix(r"C:\x"));
374    }
375
376    /// Mutation: give `parent` the place itself; this test fails.
377    #[test]
378    fn a_place_knows_its_directory() {
379        let case = NameCase::Sensitive;
380        let file = Place::of(Path::new("/p/src/a.c"), case);
381        let src = Place::of(Path::new("/p/src"), case);
382        assert!(file.parent().unwrap().same(&src));
383        assert!(!file.same(&src));
384    }
385
386    /// A `\\?\` drive or share path is written in its plain form, and any
387    /// other path is left as it is (`build.md`, "Output directory").
388    ///
389    /// Mutation: return the path as given, or slice the prefix off as a
390    /// string; this test fails.
391    #[cfg(windows)]
392    #[test]
393    fn a_verbatim_path_is_written_plain() {
394        let plain_of = |p: &str| plain(Path::new(p)).map(|p| p.to_string_lossy().into_owned());
395        assert_eq!(plain_of(r"\\?\C:\a\out").as_deref(), Some(r"C:\a\out"));
396        assert_eq!(plain_of(r"\\?\d:\x").as_deref(), Some(r"D:\x"));
397        assert_eq!(
398            plain_of(r"\\?\UNC\srv\share\out").as_deref(),
399            Some(r"\\srv\share\out")
400        );
401        assert_eq!(plain_of(r"C:\a\..\b").as_deref(), Some(r"C:\a\..\b"));
402        assert_eq!(
403            plain_of(r"\\srv\share\x").as_deref(),
404            Some(r"\\srv\share\x")
405        );
406        assert_eq!(plain_of("out").as_deref(), Some("out"));
407        // A device-namespace path is not this rule's: left as it is.
408        assert_eq!(plain_of(r"\\.\C:\x").as_deref(), Some(r"\\.\C:\x"));
409    }
410
411    /// A `\\?\` path whose plain form would name another place has none:
412    /// under the prefix each of these is a literal name.
413    ///
414    /// Mutation: drop any one of the rules in `plain` or `survives`; this
415    /// test fails, naming the path.
416    #[cfg(windows)]
417    #[test]
418    fn a_verbatim_path_that_means_something_else_plain_has_no_plain_form() {
419        for path in [
420            r"\\?\C:\a\..\b",
421            r"\\?\C:\a\.\b",
422            r"\\?\C:\out.",
423            r"\\?\C:\out ",
424            r"\\?\C:\a/b\out",
425            r"\\?\C:\nul",
426            r"\\?\C:\Con.txt",
427            r"\\?\C:\lpt9 .log",
428            r"\\?\C:\COM1",
429            r"\\?\C:\com3",
430            r"\\?\C:\prn",
431            r"\\?\C:\Aux.c",
432            r"\\?\GLOBALROOT\Device\x",
433            // A drive with no root is that drive's current directory, and
434            // a share with no name a path on the current drive: neither is
435            // the place the verbatim form names.
436            r"\\?\C:",
437            r"\\?\C:out",
438            r"\\?\UNC\srv",
439            r"\\?\UNC\srv\",
440            r"\\?\UNC\",
441        ] {
442            assert_eq!(plain(Path::new(path)), None, "{path}");
443        }
444        // Names that only look like those are plain.
445        for path in [
446            r"\\?\C:\console",
447            r"\\?\C:\com10",
448            r"\\?\C:\a.b\out",
449            r"\\?\C:\lpt0",
450        ] {
451            assert!(plain(Path::new(path)).is_some(), "{path}");
452        }
453    }
454}