Skip to main content

surjection_core/remote/
unc.rs

1//! Mapped drive letters as UNC paths (SPEC 9.6): a folder remote typed as
2//! `Z:\Backups\surjection` is kept as typed, but each push resolves it to
3//! `\\server\share\Backups\surjection`, so pushes work from processes that
4//! lack the mapping (elevated shells, scheduled tasks).
5//!
6//! [`UncResolver`] is the seam; tests fake it. [`SystemUnc`] asks Windows
7//! through `std::fs::canonicalize` (`GetFinalPathNameByHandleW`), which
8//! returns `\\?\UNC\server\share\...` for a mapped network drive, instead
9//! of calling `WNetGetUniversalNameW` (no `unsafe` in this workspace). A
10//! local drive, an unmapped letter or another OS keeps the path as typed.
11
12use std::path::{Path, PathBuf};
13
14use crate::env::Os;
15
16/// Resolves a typed remote path before a push or pull.
17pub trait UncResolver: Send + Sync {
18    /// The UNC form of `path` when it is on a mapped network drive.
19    fn universal_name(&self, path: &Path) -> Option<PathBuf>;
20}
21
22/// No resolution (Linux, macOS, tests).
23#[derive(Debug, Clone, Copy, Default)]
24pub struct NoUnc;
25
26impl UncResolver for NoUnc {
27    fn universal_name(&self, _path: &Path) -> Option<PathBuf> {
28        None
29    }
30}
31
32/// Windows: the path the drive letter maps to.
33#[derive(Debug, Clone, Copy, Default)]
34pub struct SystemUnc;
35
36impl UncResolver for SystemUnc {
37    fn universal_name(&self, path: &Path) -> Option<PathBuf> {
38        if !cfg!(windows) || !is_drive_path(path) {
39            return None;
40        }
41        let resolved = std::fs::canonicalize(path).ok()?;
42        let text = resolved.to_str()?;
43        text.strip_prefix(r"\\?\UNC\")
44            .map(|rest| PathBuf::from(format!(r"\\{rest}")))
45    }
46}
47
48/// `X:\...` or `X:/...`.
49pub fn is_drive_path(path: &Path) -> bool {
50    let bytes = path.as_os_str().as_encoded_bytes();
51    bytes.len() >= 3
52        && bytes[0].is_ascii_alphabetic()
53        && bytes[1] == b':'
54        && matches!(bytes[2], b'\\' | b'/')
55}
56
57/// The path a push or pull uses for `typed`: its UNC form on Windows when
58/// the drive is mapped, else as typed.
59pub fn resolve(os: Os, resolver: &dyn UncResolver, typed: &Path) -> PathBuf {
60    if os == Os::Windows && is_drive_path(typed) {
61        resolver
62            .universal_name(typed)
63            .unwrap_or_else(|| typed.to_path_buf())
64    } else {
65        typed.to_path_buf()
66    }
67}