Skip to main content

cortexkit_paths/
lib.rs

1//! Shared path and user-directory primitives for CortexKit tooling.
2//!
3//! [`ProjectRootId`] resolves filesystem paths into canonical project identities.
4//! [`dirs`] resolves absolute user directories with injectable environment inputs.
5//! The crate does not perform workspace discovery, Git inspection, transport
6//! serialization, or operation-target fallback handling.
7
8#![forbid(unsafe_code)]
9
10pub mod dirs;
11pub use dirs::{
12    cache_home, config_home, connection_file_candidates, cortexkit_cache_dir, cortexkit_config_dir,
13    cortexkit_data_dir, cortexkit_run_dir, cortexkit_state_dir, data_home, env_absolute_path, home,
14    state_home, with_env, xdg_data_home, Dirs, EnvSource, PathsError, SystemEnv,
15};
16
17use std::{
18    error::Error,
19    fmt, fs, io,
20    path::{Path, PathBuf},
21};
22
23/// Stable canonical identity for a project root.
24///
25/// A `ProjectRootId` is represented by the canonical filesystem path of an
26/// existing project root. Construction uses [`std::fs::canonicalize`], so the
27/// stored path is absolute, has `.`/`..`/trailing separators collapsed, and has
28/// symlinks resolved.
29///
30/// Git worktrees are first-class roots: this crate does not ask Git for a
31/// repository common-dir and does not collapse linked worktrees back to their
32/// main checkout. Because a linked worktree has its own checkout directory, the
33/// canonical worktree path is a distinct id from the canonical main-checkout
34/// path while alternate spellings of either path still converge.
35/// A canonical project-root identity.
36///
37/// THE CANONICAL FORM THIS PRODUCES IS A CRYPTOGRAPHIC IDENTITY INPUT IN AT
38/// LEAST ONE CONSUMER, WHICH IS NOT VISIBLE FROM THIS CRATE. The vault hashes
39/// the canonical directory to derive the keychain service name holding its
40/// master key, and to derive the vault id that fences an admin-operation MAC to
41/// one vault. A change to canonicalization is therefore a BREAKING CHANGE to
42/// those identities.
43///
44/// It does not present as one. The vault looks up a keychain item that does not
45/// exist and reports a locked vault over an intact store, or two binaries derive
46/// different vault ids and every admin MAC fails verification. Nothing says
47/// "these two builds disagree about what this path is" -- so the usual
48/// reassurance for a path helper, that a mistake surfaces as a loud path
49/// mismatch, does not hold here.
50///
51/// The name is the trap: this reads as a path helper and is a canonicalizer for
52/// security identities. Route changes to the canonical form past the vault.
53#[derive(Clone, Debug, PartialEq, Eq, Hash)]
54pub struct ProjectRootId(PathBuf);
55
56impl ProjectRootId {
57    /// Resolve an existing filesystem path into a canonical project-root id.
58    ///
59    /// Non-existent paths are rejected with [`IdentityError::NonExistentPath`]
60    /// instead of being logically normalized. That policy avoids silently
61    /// aliasing roots whose future meaning could change when missing path
62    /// components or symlinks are later created.
63    ///
64    /// That rejection is load-bearing for callers who use it to DETECT a root
65    /// that has gone away, so this constructor keeps it. Callers that must still
66    /// address a vanished root -- ending or inspecting work that was admitted
67    /// while the root existed -- use [`Self::from_path_allowing_missing`], which
68    /// preserves the aliasing guarantee by a narrower means.
69    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, IdentityError> {
70        let requested_path = path.as_ref().to_path_buf();
71        match fs::canonicalize(path.as_ref()) {
72            Ok(canonical_path) => Ok(Self(platform_project_root_path(canonical_path))),
73            Err(err) if err.kind() == io::ErrorKind::NotFound => {
74                Err(IdentityError::NonExistentPath {
75                    path: requested_path,
76                })
77            }
78            Err(source) => Err(IdentityError::CanonicalizePath {
79                path: requested_path,
80                source,
81            }),
82        }
83    }
84
85    /// Resolve a path into a project-root id even when the path no longer exists.
86    ///
87    /// Resolves the longest prefix that still exists and re-appends the rest,
88    /// following any symlink encountered on the missing tail. This is the
89    /// behaviour of POSIX `realpath` on a non-existent path; [`fs::canonicalize`]
90    /// is the outlier in refusing partial resolution, so this matches a
91    /// documented reference rather than inventing a rule.
92    ///
93    /// WHY NOT LEXICAL NORMALIZATION: consumers key durable state on the
94    /// resolved string. On macOS every temporary directory is reached through a
95    /// symlink, so a lexically-normalized path is a DIFFERENT string from the id
96    /// minted while the root existed -- the caller would address an empty
97    /// lineage and receive a confident "no such thing" rather than an error.
98    /// That is one caller, one spelling, and two ids across time.
99    ///
100    /// WHAT THIS DOES NOT PROMISE: if a missing component later reappears as a
101    /// symlink pointing elsewhere, the id moves. [`Self::from_path`] does not
102    /// prevent that either -- it declines to answer while the component is
103    /// missing and then resolves through the new link exactly as this does, so
104    /// the hazard is shared rather than introduced here. The aliasing guarantee
105    /// the strict constructor exists for is preserved by refusing to create NEW
106    /// durable state under an id resolved this way; callers admit only
107    /// operations that read or end something already recorded.
108    pub fn from_path_allowing_missing(path: impl AsRef<Path>) -> Result<Self, IdentityError> {
109        let resolved = resolve_allowing_missing(path.as_ref(), 0)?;
110        Ok(Self(platform_project_root_path(resolved)))
111    }
112
113    /// Borrow the canonical path backing this identity.
114    pub fn as_path(&self) -> &Path {
115        &self.0
116    }
117
118    /// Consume the identity and return its canonical path representation.
119    pub fn into_path_buf(self) -> PathBuf {
120        self.0
121    }
122}
123
124impl AsRef<Path> for ProjectRootId {
125    fn as_ref(&self) -> &Path {
126        self.as_path()
127    }
128}
129
130impl fmt::Display for ProjectRootId {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        write!(f, "{}", self.0.display())
133    }
134}
135
136impl From<ProjectRootId> for PathBuf {
137    fn from(value: ProjectRootId) -> Self {
138        value.into_path_buf()
139    }
140}
141
142impl TryFrom<&Path> for ProjectRootId {
143    type Error = IdentityError;
144
145    fn try_from(value: &Path) -> Result<Self, Self::Error> {
146        Self::from_path(value)
147    }
148}
149
150impl TryFrom<PathBuf> for ProjectRootId {
151    type Error = IdentityError;
152
153    fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
154        Self::from_path(value)
155    }
156}
157
158impl TryFrom<&str> for ProjectRootId {
159    type Error = IdentityError;
160
161    fn try_from(value: &str) -> Result<Self, Self::Error> {
162        Self::from_path(Path::new(value))
163    }
164}
165
166impl TryFrom<String> for ProjectRootId {
167    type Error = IdentityError;
168
169    fn try_from(value: String) -> Result<Self, Self::Error> {
170        Self::from_path(PathBuf::from(value))
171    }
172}
173
174/// Typed identity-resolution failures.
175#[derive(Debug)]
176pub enum IdentityError {
177    /// The requested project root does not exist, or a path component cannot be
178    /// resolved through an existing symlink chain.
179    NonExistentPath { path: PathBuf },
180    /// The OS rejected canonicalization for a reason other than non-existence.
181    CanonicalizePath { path: PathBuf, source: io::Error },
182}
183
184impl fmt::Display for IdentityError {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        match self {
187            Self::NonExistentPath { path } => {
188                write!(f, "project root does not exist: {}", path.display())
189            }
190            Self::CanonicalizePath { path, source } => {
191                write!(
192                    f,
193                    "failed to canonicalize project root {}: {source}",
194                    path.display()
195                )
196            }
197        }
198    }
199}
200
201impl Error for IdentityError {
202    fn source(&self) -> Option<&(dyn Error + 'static)> {
203        match self {
204            Self::NonExistentPath { .. } => None,
205            Self::CanonicalizePath { source, .. } => Some(source),
206        }
207    }
208}
209
210#[cfg(not(windows))]
211fn platform_project_root_path(canonical_path: PathBuf) -> PathBuf {
212    canonical_path
213}
214
215/// The kernel's own ceiling on symlink hops is typically 40 (`ELOOP`); matching
216/// it means a chain this code refuses is one the OS would refuse too.
217const MAX_SYMLINK_HOPS: u32 = 40;
218
219/// Resolve the longest existing prefix of `path` and re-append the missing tail.
220///
221/// Recurses on the parent rather than looping so that following a symlink on the
222/// missing tail re-enters the same resolution from the link's target.
223fn resolve_allowing_missing(path: &Path, hops: u32) -> Result<PathBuf, IdentityError> {
224    match fs::canonicalize(path) {
225        Ok(canonical_path) => return Ok(canonical_path),
226        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
227        Err(source) => {
228            return Err(IdentityError::CanonicalizePath {
229                path: path.to_path_buf(),
230                source,
231            });
232        }
233    }
234
235    // `..` and `.` tails have no file name to re-append, so there is no honest
236    // way to reconstruct them once the path has stopped existing. Refuse rather
237    // than return a path that differs from what the caller named.
238    let (Some(parent), Some(tail)) = (path.parent(), path.file_name()) else {
239        return Err(IdentityError::NonExistentPath {
240            path: path.to_path_buf(),
241        });
242    };
243    // `Path::parent` yields an empty path for a bare relative name; that is the
244    // current directory, not the absence of a parent.
245    let parent = if parent.as_os_str().is_empty() {
246        Path::new(".")
247    } else {
248        parent
249    };
250
251    let resolved_parent = resolve_allowing_missing(parent, hops)?;
252    let candidate = resolved_parent.join(tail);
253
254    // A DANGLING symlink reads as absent to `canonicalize` and to `Path::exists`,
255    // because both follow links. `symlink_metadata` is the only predicate that
256    // sees the link itself, and following it is what `realpath` does -- keeping
257    // the link's own name instead would move the id the moment someone repairs
258    // the link, so ordinary maintenance would silently strand whatever was
259    // admitted under it.
260    match fs::symlink_metadata(&candidate) {
261        Ok(metadata) if metadata.file_type().is_symlink() => {
262            if hops >= MAX_SYMLINK_HOPS {
263                return Err(IdentityError::CanonicalizePath {
264                    path: path.to_path_buf(),
265                    source: io::Error::new(
266                        io::ErrorKind::InvalidData,
267                        format!("symbolic link chain exceeded {MAX_SYMLINK_HOPS} hops"),
268                    ),
269                });
270            }
271            let target =
272                fs::read_link(&candidate).map_err(|source| IdentityError::CanonicalizePath {
273                    path: candidate.clone(),
274                    source,
275                })?;
276            let target = if target.is_absolute() {
277                target
278            } else {
279                resolved_parent.join(target)
280            };
281            resolve_allowing_missing(&target, hops.saturating_add(1))
282        }
283        _ => Ok(candidate),
284    }
285}
286
287#[cfg(windows)]
288fn platform_project_root_path(canonical_path: PathBuf) -> PathBuf {
289    windows_non_verbatim_path(canonical_path)
290}
291
292#[cfg(windows)]
293fn windows_non_verbatim_path(path: PathBuf) -> PathBuf {
294    use std::{
295        ffi::OsString,
296        os::windows::ffi::{OsStrExt, OsStringExt},
297    };
298
299    const SEPARATOR: u16 = b'\\' as u16;
300    const DRIVE_SEPARATOR: u16 = b':' as u16;
301    const LOWER_A: u16 = b'a' as u16;
302    const LOWER_Z: u16 = b'z' as u16;
303    const ASCII_CASE_DELTA: u16 = (b'a' - b'A') as u16;
304    const VERBATIM_PREFIX: [u16; 4] = [SEPARATOR, SEPARATOR, b'?' as u16, SEPARATOR];
305    const VERBATIM_UNC_PREFIX: [u16; 8] = [
306        SEPARATOR,
307        SEPARATOR,
308        b'?' as u16,
309        SEPARATOR,
310        b'U' as u16,
311        b'N' as u16,
312        b'C' as u16,
313        SEPARATOR,
314    ];
315
316    let encoded: Vec<u16> = path.as_os_str().encode_wide().collect();
317    let mut normalized = if encoded.starts_with(&VERBATIM_UNC_PREFIX) {
318        let mut non_verbatim = Vec::with_capacity(encoded.len() - VERBATIM_UNC_PREFIX.len() + 2);
319        non_verbatim.extend_from_slice(&[SEPARATOR, SEPARATOR]);
320        non_verbatim.extend_from_slice(&encoded[VERBATIM_UNC_PREFIX.len()..]);
321        non_verbatim
322    } else if encoded.starts_with(&VERBATIM_PREFIX) {
323        encoded[VERBATIM_PREFIX.len()..].to_vec()
324    } else {
325        encoded
326    };
327
328    if normalized.len() >= 2
329        && normalized[1] == DRIVE_SEPARATOR
330        && (LOWER_A..=LOWER_Z).contains(&normalized[0])
331    {
332        normalized[0] -= ASCII_CASE_DELTA;
333    }
334
335    PathBuf::from(OsString::from_wide(&normalized))
336}
337
338#[cfg(test)]
339mod tests {
340    use std::{
341        collections::HashMap,
342        fs,
343        path::PathBuf,
344        sync::atomic::{AtomicUsize, Ordering},
345        time::{SystemTime, UNIX_EPOCH},
346    };
347
348    use super::*;
349
350    static NEXT_TEST_DIR: AtomicUsize = AtomicUsize::new(0);
351
352    #[cfg(unix)]
353    fn symlink_dir(target: &Path, link: &Path) -> io::Result<()> {
354        std::os::unix::fs::symlink(target, link)
355    }
356
357    #[cfg(windows)]
358    fn symlink_dir(target: &Path, link: &Path) -> io::Result<()> {
359        std::os::windows::fs::symlink_dir(target, link)
360    }
361
362    struct TestDir {
363        path: PathBuf,
364    }
365
366    impl TestDir {
367        fn new(label: &str) -> Self {
368            let unique = format!(
369                "cortexkit-paths-project-root-id-{label}-{}-{}-{}",
370                std::process::id(),
371                SystemTime::now()
372                    .duration_since(UNIX_EPOCH)
373                    .expect("system time should not be before the Unix epoch")
374                    .as_nanos(),
375                NEXT_TEST_DIR.fetch_add(1, Ordering::Relaxed)
376            );
377            let path = std::env::temp_dir().join(unique);
378            fs::create_dir(&path).expect("create temporary project-root-id test directory");
379            Self { path }
380        }
381
382        fn child(&self, name: &str) -> PathBuf {
383            self.path.join(name)
384        }
385    }
386
387    impl Drop for TestDir {
388        fn drop(&mut self) {
389            let _ = fs::remove_dir_all(&self.path);
390        }
391    }
392
393    /// The property the whole constructor exists for: an id minted while the root
394    /// existed must still be reachable after it is gone.
395    ///
396    /// Written as an EQUALITY against the strict constructor's output rather than
397    /// against a hand-written expected string, because a literal would encode
398    /// whatever this author believed canonicalization does. The equality fails if
399    /// the fallback and the strict path ever disagree, which is the only thing
400    /// consumers keying durable state on the result actually require.
401    #[test]
402    fn id_survives_the_root_being_deleted() {
403        let temp = TestDir::new("vanished");
404        let root = temp.child("project");
405        fs::create_dir(&root).expect("create project root");
406
407        let while_present = ProjectRootId::from_path(&root).expect("canonicalize live root");
408        fs::remove_dir(&root).expect("remove project root");
409
410        assert!(
411            ProjectRootId::from_path(&root).is_err(),
412            "the strict constructor must still refuse a vanished root, or callers that \
413             use the refusal to DETECT a dead root would silently keep it"
414        );
415        assert_eq!(
416            ProjectRootId::from_path_allowing_missing(&root).expect("resolve vanished root"),
417            while_present,
418            "a root deleted after admission must resolve to the id it was admitted \
419             under, or the caller addresses an empty lineage and is told no such thing \
420             exists rather than being given an error"
421        );
422    }
423
424    /// macOS reaches every temp directory through a symlink, so this is the case
425    /// that distinguishes resolving from lexical normalization on this host --
426    /// and the one a lexical implementation silently gets wrong.
427    #[test]
428    fn missing_tail_resolves_through_a_symlinked_ancestor() {
429        let temp = TestDir::new("symlinked-ancestor");
430        let real = temp.child("real");
431        let link = temp.child("link");
432        fs::create_dir(&real).expect("create real directory");
433        symlink_dir(&real, &link).expect("create ancestor symlink");
434
435        let through_link = ProjectRootId::from_path_allowing_missing(link.join("gone"))
436            .expect("resolve through symlinked ancestor");
437        let through_real = ProjectRootId::from_path_allowing_missing(real.join("gone"))
438            .expect("resolve through real ancestor");
439
440        assert_eq!(
441            through_link, through_real,
442            "a missing tail must resolve through a live symlinked ancestor, or two \
443             spellings of one location mint two different ids"
444        );
445        assert_ne!(
446            through_link.as_path(),
447            link.join("gone"),
448            "non-vacuity: if this equals the input the implementation is normalizing \
449             lexically and the test above would pass for the wrong reason"
450        );
451    }
452
453    /// A dangling link reads as absent to both `canonicalize` and `Path::exists`,
454    /// so the naive walk-up stops one component too high and keeps the link's own
455    /// name. Following it is what `realpath` does, and it is the choice that
456    /// SURVIVES REPAIR: if someone later creates the target, the strict
457    /// constructor produces this same id, so ordinary maintenance cannot strand
458    /// work admitted while the link dangled.
459    #[test]
460    fn dangling_link_resolves_to_its_target_and_survives_the_link_being_repaired() {
461        let temp = TestDir::new("dangling");
462        let target = temp.child("target");
463        let link = temp.child("link");
464        symlink_dir(&target, &link).expect("create dangling symlink");
465
466        let while_dangling = ProjectRootId::from_path_allowing_missing(link.join("session"))
467            .expect("resolve through dangling link");
468
469        fs::create_dir(&target).expect("create link target");
470        fs::create_dir(target.join("session")).expect("create session directory");
471        let after_repair =
472            ProjectRootId::from_path(link.join("session")).expect("canonicalize repaired path");
473
474        assert_eq!(
475            while_dangling, after_repair,
476            "repairing a dangling link must not move the id, or an act of maintenance \
477             silently strands whatever was admitted while it dangled"
478        );
479    }
480
481    /// A link chain long enough to be an error must fail rather than recurse until
482    /// the stack gives out. Asserting the ERROR VARIANT, not merely that it failed:
483    /// a stack overflow is not a refusal.
484    #[test]
485    fn symlink_chain_beyond_the_hop_ceiling_is_refused() {
486        let temp = TestDir::new("loop");
487        let first = temp.child("a");
488        let second = temp.child("b");
489        symlink_dir(&second, &first).expect("create first link");
490        symlink_dir(&first, &second).expect("create second link");
491
492        let error = ProjectRootId::from_path_allowing_missing(first.join("gone"))
493            .expect_err("a symlink cycle must be refused");
494        assert!(
495            matches!(error, IdentityError::CanonicalizePath { .. }),
496            "a cycle is an unresolvable path, not a missing one: {error:?}"
497        );
498    }
499
500    #[test]
501    fn path_spellings_to_same_root_have_equal_project_root_ids() {
502        let temp = TestDir::new("spellings");
503        let root = temp.child("project");
504        let nested = root.join("nested");
505        fs::create_dir(&root).expect("create project root");
506        fs::create_dir(&nested).expect("create nested directory");
507
508        let trailing = PathBuf::from(format!("{}{}", root.display(), std::path::MAIN_SEPARATOR));
509        let direct = ProjectRootId::from_path(&root).expect("canonicalize direct root");
510        let with_trailing = ProjectRootId::from_path(trailing).expect("canonicalize trailing root");
511        let with_dot = ProjectRootId::from_path(root.join(".")).expect("canonicalize dot root");
512        let round_trip =
513            ProjectRootId::from_path(nested.join("..")).expect("canonicalize round-trip root");
514
515        assert_eq!(direct, with_trailing);
516        assert_eq!(direct, with_dot);
517        assert_eq!(direct, round_trip);
518    }
519
520    #[cfg(unix)]
521    #[test]
522    fn symlinked_project_root_has_same_id_as_target() {
523        use std::os::unix::fs::symlink;
524
525        let temp = TestDir::new("symlink");
526        let target = temp.child("target");
527        let link = temp.child("link");
528        fs::create_dir(&target).expect("create symlink target");
529        symlink(&target, &link).expect("create symlink to project root");
530
531        let target_id = ProjectRootId::from_path(&target).expect("canonicalize target");
532        let link_id = ProjectRootId::from_path(&link).expect("canonicalize symlink");
533
534        assert_eq!(target_id, link_id);
535    }
536
537    #[test]
538    fn git_worktree_checkout_path_is_distinct_from_main_checkout_path() {
539        let temp = TestDir::new("worktree");
540        let main_checkout = temp.child("main-checkout");
541        let linked_worktree = temp.child("linked-worktree");
542        let main_gitdir = main_checkout.join(".git");
543        let worktree_gitdir = main_gitdir.join("worktrees").join("linked-worktree");
544
545        fs::create_dir(&main_checkout).expect("create main checkout");
546        fs::create_dir(&linked_worktree).expect("create linked worktree checkout");
547        fs::create_dir_all(&worktree_gitdir).expect("create simulated worktree gitdir");
548        fs::write(
549            linked_worktree.join(".git"),
550            format!("gitdir: {}\n", worktree_gitdir.display()),
551        )
552        .expect("write simulated linked-worktree .git file");
553
554        let main_id = ProjectRootId::from_path(&main_checkout).expect("canonicalize main checkout");
555        let worktree_id =
556            ProjectRootId::from_path(&linked_worktree).expect("canonicalize linked worktree");
557
558        assert_ne!(main_id, worktree_id);
559    }
560
561    #[test]
562    fn non_existent_project_root_returns_typed_error() {
563        let temp = TestDir::new("missing");
564        let missing_root = temp.child("missing-project");
565
566        match ProjectRootId::from_path(&missing_root) {
567            Err(IdentityError::NonExistentPath { path }) => assert_eq!(path, missing_root),
568            Err(other) => panic!("expected NonExistentPath error, got {other}"),
569            Ok(id) => panic!("expected missing project root to fail, got {id}"),
570        }
571    }
572
573    #[cfg(target_os = "macos")]
574    #[test]
575    fn macos_var_symlink_resolves_to_private_var() {
576        let id = ProjectRootId::from_path("/var").expect("canonicalize /var");
577
578        assert_eq!(id.as_path(), std::path::Path::new("/private/var"));
579    }
580
581    #[test]
582    fn realpath_preserves_stored_case_on_case_insensitive_filesystems() {
583        let temp = TestDir::new("stored-case");
584        let stored_case = temp.child("SUB");
585        let alternate_case = temp.child("sub");
586        fs::create_dir(&stored_case).expect("create stored-case project root");
587
588        let stored_id =
589            ProjectRootId::from_path(&stored_case).expect("canonicalize stored-case root");
590        match ProjectRootId::from_path(&alternate_case) {
591            Ok(alternate_id) => {
592                assert_eq!(stored_id, alternate_id);
593                assert!(alternate_id.as_path().ends_with("SUB"));
594            }
595            Err(IdentityError::NonExistentPath { path }) if path == alternate_case => {
596                // This filesystem is case-sensitive; the seed vector is not applicable here.
597            }
598            Err(other) => {
599                panic!("expected alternate case to canonicalize or be absent, got {other}")
600            }
601        }
602    }
603
604    #[test]
605    fn project_root_id_is_hashable_as_hash_map_key() {
606        let temp = TestDir::new("hashmap");
607        let root = temp.child("project");
608        let other_root = temp.child("other-project");
609        fs::create_dir(&root).expect("create project root");
610        fs::create_dir(&other_root).expect("create other project root");
611
612        let id = ProjectRootId::from_path(&root).expect("canonicalize project root");
613        let same_id =
614            ProjectRootId::from_path(root.join(".")).expect("canonicalize equivalent root");
615        let other_id = ProjectRootId::from_path(&other_root).expect("canonicalize different root");
616
617        let mut entries = HashMap::new();
618        entries.insert(id.clone(), "project state");
619
620        assert_eq!(entries.get(&same_id), Some(&"project state"));
621        assert_eq!(entries.get(&other_id), None);
622    }
623
624    #[cfg(windows)]
625    #[test]
626    fn windows_drive_verbatim_prefix_is_stripped() {
627        let path = windows_non_verbatim_path(PathBuf::from(r"\\?\C:\existing"));
628
629        assert_eq!(path, PathBuf::from(r"C:\existing"));
630    }
631
632    #[cfg(windows)]
633    #[test]
634    fn windows_unc_verbatim_prefix_is_stripped() {
635        let path = windows_non_verbatim_path(PathBuf::from(r"\\?\UNC\server\share\existing"));
636
637        assert_eq!(path, PathBuf::from(r"\\server\share\existing"));
638    }
639
640    #[cfg(windows)]
641    #[test]
642    fn windows_lowercase_drive_letter_is_uppercased() {
643        let path = windows_non_verbatim_path(PathBuf::from(r"c:\existing"));
644
645        assert_eq!(path, PathBuf::from(r"C:\existing"));
646    }
647}