cuno-core 0.3.0

Error classification, output, the cuno home, and the environment snapshot, shared by the other crates.
Documentation
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Whether two paths are the same place, or one lies inside the other: the
//! one answer every crate asks (`docs/en/specs/project-layout.md`, "Source
//! collection and linking"; `docs/en/specs/architecture.md`, "What goes in
//! `cuno-core`"). Only comparing uses where a path leads; the path a caller
//! goes on to use or show stays as written, unless the caller normalizes it
//! with [`lexical`] on purpose (the output directory is, once).

use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf, Prefix};

use crate::NameCase;
use crate::env::fold;

/// `path` written without Windows' `\\?\` prefix: `\\?\C:\a` as `C:\a`,
/// `\\?\UNC\server\share\a` as `\\server\share\a`, and any other path
/// unchanged. `None` when the plain form would name another place: under
/// `\\?\`, a `.` or `..` part, a name ending in `.` or a space, a `/` in a
/// name and a device name (`CON`, `NUL`, `COM1`, ... with or without an
/// extension) are taken literally. A verbatim prefix that is neither a
/// drive with its root nor a share with a server and a name has no plain
/// form either: `C:` alone is that drive's current directory, and `\\s\` a
/// path on the current drive. See docs/en/specs/build.md, "Output
/// directory". A `\\.\` path is not this rule's, and is left as it is.
pub fn plain(path: &Path) -> Option<PathBuf> {
    let mut parts = path.components().peekable();
    let Some(Component::Prefix(prefix)) = parts.next() else {
        return Some(path.to_owned());
    };
    let mut out = match prefix.kind() {
        Prefix::VerbatimDisk(drive) if parts.peek() == Some(&Component::RootDir) => {
            PathBuf::from(format!("{}:", char::from(drive)))
        }
        Prefix::VerbatimUNC(server, share) if !server.is_empty() && !share.is_empty() => {
            let mut unc = OsString::from(r"\\");
            unc.push(server);
            unc.push(r"\");
            unc.push(share);
            PathBuf::from(unc)
        }
        Prefix::VerbatimDisk(_) | Prefix::VerbatimUNC(..) | Prefix::Verbatim(_) => return None,
        Prefix::DeviceNS(_) | Prefix::Disk(_) | Prefix::UNC(..) => return Some(path.to_owned()),
    };
    for part in parts {
        match part {
            Component::RootDir => out.push(r"\"),
            Component::Normal(name) if survives(name) => out.push(name),
            _ => return None,
        }
    }
    Some(out)
}

/// Whether `name`, a part of a `\\?\` path, names the same thing without
/// the prefix.
fn survives(name: &OsStr) -> bool {
    let bytes = name.as_encoded_bytes();
    if bytes.contains(&b'/') || bytes.ends_with(b".") || bytes.ends_with(b" ") {
        return false;
    }
    // The part before the first `.`, as Windows matches device names.
    let stem = bytes.split(|b| *b == b'.').next().unwrap_or(bytes);
    let stem = stem.trim_ascii_end();
    let device = |prefix: &[u8]| {
        stem.len() == 4 && stem[..3].eq_ignore_ascii_case(prefix) && matches!(stem[3], b'1'..=b'9')
    };
    !([b"CON", b"PRN", b"AUX", b"NUL"]
        .iter()
        .any(|d| stem.eq_ignore_ascii_case(*d))
        || device(b"COM")
        || device(b"LPT"))
}

/// `path` with `.` dropped and each `..` taking the part before it away.
pub fn lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for part in path.components() {
        match part {
            Component::CurDir => {}
            Component::ParentDir => {
                out.pop();
            }
            other => out.push(other),
        }
    }
    out
}

/// Where a path leads, ready to be compared many times: work out the
/// [`Place`] of each path once, then ask it as often as needed.
#[derive(Clone, Debug)]
pub struct Place {
    /// The path as the file system names it: see [`Place::of`].
    real: PathBuf,
    /// Each part of `real` as compared.
    parts: Vec<String>,
}

impl Place {
    /// Where `path` leads, whether or not it exists yet: `.` and `..`
    /// resolved, and its longest existing part canonicalized, so a link or a
    /// short name is where it leads; the part that does not exist yet is
    /// kept as written. The existing part is compared as the file system
    /// spells it, and only the rest is folded when `case` ignores case,
    /// since no folding table cuno could hold is the file system's own. A
    /// relative path is only resolved by name, since a library does not
    /// read the process's current directory.
    pub fn of(path: &Path, case: NameCase) -> Place {
        let (real, exact) = resolve(path);
        let parts = real
            .components()
            .enumerate()
            .map(|(i, component)| part(component, if i < exact { None } else { Some(case) }))
            .collect();
        Place { real, parts }
    }

    /// Whether `self` and `other` are the same place.
    pub fn same(&self, other: &Place) -> bool {
        self.parts == other.parts
    }

    /// Whether `self` is `dir` or lies under it.
    pub fn within(&self, dir: &Place) -> bool {
        self.relative(dir).is_some()
    }

    /// Where `self` lies under `dir`, as the file system names it: empty
    /// when the two are the same place, `None` when `self` is not inside.
    pub fn relative(&self, dir: &Place) -> Option<PathBuf> {
        self.parts
            .starts_with(&dir.parts)
            .then(|| self.real.components().skip(dir.parts.len()).collect())
    }

    /// The directory `self` is in.
    pub fn parent(&self) -> Option<Place> {
        let real = self.real.parent()?.to_owned();
        let parts = self.parts[..self.parts.len() - 1].to_vec();
        Some(Place { real, parts })
    }
}

/// Whether `a` and `b` are the same place: see [`Place`].
pub fn same(a: &Path, b: &Path, case: NameCase) -> bool {
    Place::of(a, case).same(&Place::of(b, case))
}

/// Whether `path` is `dir` or lies under it: see [`Place`].
pub fn within(path: &Path, dir: &Path, case: NameCase) -> bool {
    Place::of(path, case).within(&Place::of(dir, case))
}

/// Where `path` lies under `dir`: see [`Place::relative`].
pub fn relative(path: &Path, dir: &Path, case: NameCase) -> Option<PathBuf> {
    Place::of(path, case).relative(&Place::of(dir, case))
}

/// `path` resolved as [`Place::of`] says, and how many of its leading
/// components the file system spelled.
fn resolve(path: &Path) -> (PathBuf, usize) {
    let path = lexical(path);
    if !path.is_absolute() {
        return (path, 0);
    }
    let mut existing = path.as_path();
    let mut rest = Vec::new();
    loop {
        if let Ok(canonical) = std::fs::canonicalize(existing) {
            let exact = canonical.components().count();
            let real = rest.iter().rev().fold(canonical, |p, part| p.join(part));
            return (real, exact);
        }
        match (existing.parent(), existing.file_name()) {
            (Some(parent), Some(name)) => {
                rest.push(name.to_owned());
                existing = parent;
            }
            _ => return (path, 0),
        }
    }
}

/// One component as compared: a drive or share prefix in its plain form
/// (a drive letter in either case), the root as an empty part, and a name
/// folded per `case`, or kept when `case` is `None` because the file
/// system spelled it.
fn part(component: Component<'_>, case: Option<NameCase>) -> String {
    let folded = |name: &OsStr| match case {
        Some(case) => fold(name, case),
        None => name.to_owned(),
    };
    let part = match component {
        Component::Prefix(prefix) => match prefix.kind() {
            Prefix::VerbatimDisk(d) | Prefix::Disk(d) => {
                OsString::from(format!("{}:", char::from(d.to_ascii_uppercase())))
            }
            Prefix::VerbatimUNC(server, share) | Prefix::UNC(server, share) => {
                let mut unc = OsString::from("//");
                unc.push(server);
                unc.push("/");
                unc.push(share);
                fold(&unc, NameCase::Insensitive)
            }
            _ => folded(prefix.as_os_str()),
        },
        Component::RootDir => OsString::new(),
        other => folded(other.as_os_str()),
    };
    part.to_string_lossy().into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A fresh, empty directory for one test.
    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("cuno-paths-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// Mutation: compare without folding case; this test fails.
    #[test]
    fn case_is_ignored_only_where_the_file_system_ignores_it() {
        let a = Path::new("/project/Src/Main.cpp");
        let b = Path::new("/project/src/main.cpp");
        assert!(same(a, b, NameCase::Insensitive));
        assert!(!same(a, b, NameCase::Sensitive));
    }

    /// Mutation: compare paths as written, without resolving `.` and `..`,
    /// or resolve a relative path against the current directory; this test
    /// fails.
    #[test]
    fn dot_and_dot_dot_are_resolved_by_name() {
        let case = NameCase::Sensitive;
        assert!(same(
            Path::new("/p/./src/../src/a.c"),
            Path::new("/p/src/a.c"),
            case
        ));
        assert!(within(Path::new("/p/src/../target"), Path::new("/p"), case));
        assert!(!within(Path::new("/p/../q"), Path::new("/p"), case));
        // Relative, and resolved by name only: `src` exists in the current
        // directory of a test run, and must not become absolute.
        let relative_path = Path::new("no-such-dir/y/../z");
        assert!(same(relative_path, Path::new("no-such-dir/z"), case));
        assert!(within(relative_path, Path::new("no-such-dir/."), case));
        assert!(!within(
            Path::new("no-such-dir/y/out"),
            Path::new("no-such-dir/z"),
            case
        ));
        assert_eq!(resolve(Path::new("src/../src")).0, PathBuf::from("src"));
    }

    /// Mutation: compare by string prefix instead of by component; this
    /// test fails.
    #[test]
    fn within_takes_whole_names() {
        let case = NameCase::Sensitive;
        let dir = Path::new("/a/b");
        assert!(within(Path::new("/a/b"), dir, case));
        assert!(within(Path::new("/a/b/c"), dir, case));
        assert!(!within(Path::new("/a/bc"), dir, case));
        assert!(!within(Path::new("/a"), dir, case));
        assert_eq!(
            relative(Path::new("/a/b/c/d"), dir, case),
            Some(PathBuf::from("c/d"))
        );
        assert_eq!(relative(Path::new("/a/b"), dir, case), Some(PathBuf::new()));
    }

    /// A part that does not exist yet is kept as written after the part
    /// that does, which is canonicalized.
    ///
    /// Mutation: drop the part that does not exist, or fall back to the
    /// path as written when any of it is missing; this test fails.
    #[test]
    fn a_path_not_there_yet_continues_from_the_part_that_is() {
        let dir = scratch("tail");
        let case = NameCase::host();
        let missing = dir.join("not").join("yet");
        let (real, _) = resolve(&missing);
        assert!(real.ends_with("not/yet"));
        assert!(real.starts_with(std::fs::canonicalize(&dir).unwrap()));
        assert!(!same(&missing, &dir.join("not"), case));
        assert!(within(&missing, &dir, case));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A path written with `\\?\` and the same path without it are one
    /// place, even where nothing of it exists for `canonicalize` to
    /// reconcile (here, a drive that is not there).
    ///
    /// Mutation: keep a `\\?\` drive prefix as written; this test fails.
    #[cfg(windows)]
    #[test]
    fn a_verbatim_prefix_is_the_plain_one() {
        let drive = (b'D'..=b'Z')
            .map(char::from)
            .find(|d| !Path::new(&format!("{d}:\\")).exists())
            .expect("a free drive letter");
        let verbatim = PathBuf::from(format!(r"\\?\{drive}:\nowhere"));
        let plain = PathBuf::from(format!(r"{drive}:\nowhere"));
        assert!(same(&verbatim, &plain, NameCase::Insensitive));
    }

    /// A junction compares as the directory it leads to, and what lies
    /// under it as lying under that directory.
    ///
    /// Mutation: compare without following links (`real` returning
    /// [`lexical`]); this test fails.
    #[cfg(windows)]
    #[test]
    fn a_junction_is_where_it_leads() {
        let dir = scratch("junction");
        let target = dir.join("target");
        let link = dir.join("link");
        std::fs::create_dir(&target).unwrap();
        let made = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(&link)
            .arg(&target)
            .output()
            .unwrap();
        assert!(made.status.success(), "{made:?}");
        let case = NameCase::Insensitive;
        assert!(same(&link, &target, case));
        assert!(within(&link.join("debug"), &target, case));
        assert!(!within(&link, &dir.join("elsewhere"), case));
        std::fs::remove_dir(&link).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Names the file system holds are compared as it spells them: `σ` and
    /// `Ï‚` are two files on NTFS, though simple upper-casing makes both
    /// `Σ`. Only a part not there yet is folded.
    ///
    /// Mutation: fold the existing part too, or fold nothing; this test
    /// fails.
    #[test]
    fn existing_names_are_compared_as_the_file_system_spells_them() {
        let dir = scratch("spelled");
        let case = NameCase::Insensitive;
        for name in ["tool_σ.cpp", "tool_ς.cpp"] {
            std::fs::write(dir.join(name), "").unwrap();
        }
        assert!(!same(
            &dir.join("tool_σ.cpp"),
            &dir.join("tool_Ï‚.cpp"),
            case
        ));
        assert!(same(&dir.join("New/Out"), &dir.join("new/out"), case));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A share written with `\\?\UNC\` and without it is one share, its
    /// server and share names in either case; so is a drive.
    ///
    /// Mutation: keep a `\\?\` prefix as written, or compare the server,
    /// share or drive letter with case; this test fails.
    #[cfg(windows)]
    #[test]
    fn a_share_is_one_share_however_it_is_written() {
        let prefix = |p: &'static str| part(Path::new(p).components().next().unwrap(), None);
        assert_eq!(
            prefix(r"\\?\UNC\Server\Share\x"),
            prefix(r"\\server\share\x")
        );
        assert_eq!(prefix(r"\\?\c:\x"), prefix(r"C:\x"));
    }

    /// Mutation: give `parent` the place itself; this test fails.
    #[test]
    fn a_place_knows_its_directory() {
        let case = NameCase::Sensitive;
        let file = Place::of(Path::new("/p/src/a.c"), case);
        let src = Place::of(Path::new("/p/src"), case);
        assert!(file.parent().unwrap().same(&src));
        assert!(!file.same(&src));
    }

    /// A `\\?\` drive or share path is written in its plain form, and any
    /// other path is left as it is (`build.md`, "Output directory").
    ///
    /// Mutation: return the path as given, or slice the prefix off as a
    /// string; this test fails.
    #[cfg(windows)]
    #[test]
    fn a_verbatim_path_is_written_plain() {
        let plain_of = |p: &str| plain(Path::new(p)).map(|p| p.to_string_lossy().into_owned());
        assert_eq!(plain_of(r"\\?\C:\a\out").as_deref(), Some(r"C:\a\out"));
        assert_eq!(plain_of(r"\\?\d:\x").as_deref(), Some(r"D:\x"));
        assert_eq!(
            plain_of(r"\\?\UNC\srv\share\out").as_deref(),
            Some(r"\\srv\share\out")
        );
        assert_eq!(plain_of(r"C:\a\..\b").as_deref(), Some(r"C:\a\..\b"));
        assert_eq!(
            plain_of(r"\\srv\share\x").as_deref(),
            Some(r"\\srv\share\x")
        );
        assert_eq!(plain_of("out").as_deref(), Some("out"));
        // A device-namespace path is not this rule's: left as it is.
        assert_eq!(plain_of(r"\\.\C:\x").as_deref(), Some(r"\\.\C:\x"));
    }

    /// A `\\?\` path whose plain form would name another place has none:
    /// under the prefix each of these is a literal name.
    ///
    /// Mutation: drop any one of the rules in `plain` or `survives`; this
    /// test fails, naming the path.
    #[cfg(windows)]
    #[test]
    fn a_verbatim_path_that_means_something_else_plain_has_no_plain_form() {
        for path in [
            r"\\?\C:\a\..\b",
            r"\\?\C:\a\.\b",
            r"\\?\C:\out.",
            r"\\?\C:\out ",
            r"\\?\C:\a/b\out",
            r"\\?\C:\nul",
            r"\\?\C:\Con.txt",
            r"\\?\C:\lpt9 .log",
            r"\\?\C:\COM1",
            r"\\?\C:\com3",
            r"\\?\C:\prn",
            r"\\?\C:\Aux.c",
            r"\\?\GLOBALROOT\Device\x",
            // A drive with no root is that drive's current directory, and
            // a share with no name a path on the current drive: neither is
            // the place the verbatim form names.
            r"\\?\C:",
            r"\\?\C:out",
            r"\\?\UNC\srv",
            r"\\?\UNC\srv\",
            r"\\?\UNC\",
        ] {
            assert_eq!(plain(Path::new(path)), None, "{path}");
        }
        // Names that only look like those are plain.
        for path in [
            r"\\?\C:\console",
            r"\\?\C:\com10",
            r"\\?\C:\a.b\out",
            r"\\?\C:\lpt0",
        ] {
            assert!(plain(Path::new(path)).is_some(), "{path}");
        }
    }
}