simple-path 0.4.1

Simplify Windows UNC path for `fs::canonicalize`
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
#![cfg_attr(not(target_os = "windows"), allow(unused))]
use crate::Display;
#[cfg(windows)]
use crate::{PathExt, UncPath, Volumes};
use std::{
    borrow::Cow,
    fs, io,
    path::{Path, PathBuf, StripPrefixError},
};

/// Simplifies [Win32 File Namespaces] paths (the "`\\?\`" prefix)
/// for better readability and compatibility.
///
/// The following code is a snap-in replacement of [`fs::canonicalize`].
/// ```no_run
/// # use simple_path::SimplePath;
/// # let path = "";
/// SimplePath::default().canonicalize(path);
/// ```
///
/// If you have `net use Z: \\server\share`:
/// | | `C:\dir` | `Z:\x` |
/// | --- | --- | --- |
/// | [`fs::canonicalize`] | `\\?\C:\dir` | `\\?\UNC\server\share\x` |
/// | `SimplePath` | `C:\dir` | `\\server\share\x` |
/// | `SimplePath` with [`map_to_drive`] | `C:\dir` | `Z:\x` |
///
/// [`map_to_drive`]: `SimplePath::map_to_drive`
/// [Win32 File Namespaces]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#win32-file-namespaces
#[derive(Clone, Debug, Default)]
pub struct SimplePath {
    /// Disallow simplifications
    /// if the result is a "long path" (longer than 260 characters).
    /// Initially `false`.
    ///
    /// Long paths may not be supported by some programs and APIs.
    /// In such cases, using the [Win32 File Namespaces] (the "`\\?\`" prefix)
    /// can often work around the limitation.
    /// Setting this option to `true` can improve
    /// the compatibility with such cases.
    ///
    /// On the other hand, some other programs such as PowerShell v7
    /// can handle long paths,
    /// but they can't handle the "`\\?\`" prefix.
    /// They work best with `false`.
    ///
    /// Please also see the [Maximum Path Length Limitation].
    ///
    /// [Maximum Path Length Limitation]: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
    /// [Win32 File Namespaces]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#win32-file-namespaces
    pub disallow_long: bool,

    /// Disallow simplifications
    /// if the path is not connected.
    /// Initially `false`.
    ///
    /// Technically speaking,
    /// since the "`\\?\`" prefix ([Win32 File Namespaces])
    /// disables all string parsing and
    /// sends the following string directly to the file system,
    /// simplifying the path is not always guaranteed to be safe or equivalent.
    ///
    /// Enable this option
    /// to restrict simplification to verified paths,
    /// providing an extra layer of safety.
    ///
    /// Please also see the [safety] note.
    ///
    /// # Examples
    /// ```
    /// # use simple_path::SimplePath;
    /// # use std::path::Path;
    /// let path = Path::new(r"\\?\UNC\server\share\dir");
    /// let simple = SimplePath { disallow_unknown_unc: true, ..Default::default() };
    /// #[cfg(windows)]
    /// assert!(simple.simplify(path).unwrap().is_none());
    /// ```
    ///
    /// [safety]: https://github.com/kojiishi/simple-path#safety-and-equivalence
    /// [Win32 File Namespaces]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#win32-file-namespaces
    pub disallow_unknown_unc: bool,

    /// Map to network share drive names when possible.
    /// Initially `false`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use simple_path::SimplePath;
    /// # fn test() -> std::io::Result<()> {
    /// let path = "file.txt";
    /// let simple = SimplePath { map_to_drive: true, ..Default::default() };
    /// let canonicalized = simple.canonicalize(path)?;
    /// # Ok(())
    /// # }
    /// ```
    /// If the `file.txt` is in a network drive,
    /// the result is `Z:\dir\file.txt`
    /// instead of `\\server\share\dir\file.txt`.
    ///
    /// The following code tries to preserve the original form of the `path`.
    /// ```
    /// # use simple_path::SimplePath;
    /// # fn test(path: &std::path::Path) -> std::io::Result<()> {
    /// SimplePath {
    ///     map_to_drive: !SimplePath::is_unc(path),
    ///     ..Default::default()
    /// }.canonicalize(path)?;
    /// # Ok(())
    /// # }
    /// ```
    pub map_to_drive: bool,

    /// Skip the [`dunce`] simplification.
    /// Initially `false`.
    ///
    /// [`dunce`]: https://crates.io/crates/dunce
    pub skip_dunce: bool,

    /// It is highly recommended to always use `, ..Default::default()`.
    /// Otherwise builds fail when new fields are added.
    ///
    /// This field is not used in any ways,
    /// but exists to allow using `, ..Default::default()`
    /// even when all other fields are specified.
    pub _unused: bool,

    #[cfg(all(test, windows))]
    volumes: Option<Volumes>,
}

impl SimplePath {
    #[cfg(all(test, windows))]
    pub(crate) fn mock() -> SimplePath {
        SimplePath {
            volumes: Some(Volumes::mock()),
            ..Default::default()
        }
    }

    /// A snap-in replacement for [`fs::canonicalize`].
    /// It calls [`fs::canonicalize`] and [`simplify`].
    ///
    /// On other platforms than Windows,
    /// this is equivalent to [`fs::canonicalize`].
    ///
    /// # Examples
    /// ```
    /// # fn test(path: &std::path::Path) -> std::io::Result<()> {
    /// use simple_path::SimplePath;
    /// let canonicalized = SimplePath::default().canonicalize(path)?;
    /// println!("{}", canonicalized.display());
    /// # Ok(()) }
    /// ```
    ///
    /// [`fs::canonicalize`]: https://doc.rust-lang.org/std/fs/fn.canonicalize.html
    /// [`simplify`]: SimplePath::simplify
    #[inline]
    pub fn canonicalize(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
        let canonicalized = fs::canonicalize(path)?;
        #[cfg(windows)]
        if let Some(simplified) = self.simplify(&canonicalized)? {
            return Ok(simplified.into_owned());
        }
        Ok(canonicalized)
    }

    /// Try to simplify the given `path`.
    ///
    /// Returns `Ok(None)`
    /// if no simplification is applied,
    /// or on other platforms than Windows.
    #[inline]
    pub fn simplify<'a>(&self, path: &'a Path) -> io::Result<Option<Cow<'a, Path>>> {
        #[cfg(windows)]
        return self._simplify(path).map_err(io_error_from_anyhow);
        #[cfg(not(windows))]
        Ok(None)
    }

    #[cfg(windows)]
    fn _simplify<'a>(&self, path: &'a Path) -> anyhow::Result<Option<Cow<'a, Path>>> {
        // If it starts with the `\\?\UNC\` prefix.
        if let Ok(unc) = UncPath::try_from(path)
            && unc.is_file_namespace_unc()
        {
            // Try mapped network drives.
            let drive_path = if self.disallow_unknown_unc || self.map_to_drive {
                self.drive_path(path)?
            } else {
                None
            };
            if self.map_to_drive
                && let Some(drive_path) = &drive_path
                && drive_path.has_drive()
                && !drive_path.has_invalid_chars()
                && (!self.disallow_long || !drive_path.is_longer_than_max_path())
            {
                return Ok(Some(Cow::Owned(drive_path.to_path_buf())));
            }

            // Try short UNC (`\\server\share`).
            if (!self.disallow_unknown_unc || drive_path.is_some())
                && let Some(short_unc) = unc.to_short_unc()
                && !short_unc.has_invalid_chars()
                && (!self.disallow_long || !short_unc.is_longer_than_win_max_path())
            {
                return Ok(Some(Cow::Owned(short_unc)));
            }
        }

        // Try `dunce::simplified`.
        if !self.skip_dunce {
            let simplified = dunce::simplified(path);
            if !std::ptr::eq(path, simplified) {
                return Ok(Some(Cow::Borrowed(simplified)));
            }
        }
        Ok(None)
    }

    #[cfg(windows)]
    #[inline]
    fn drive_path<'a>(&self, path: &'a Path) -> anyhow::Result<Option<crate::DrivePath<'a>>> {
        #[cfg(test)]
        if let Some(volumes) = &self.volumes {
            return Ok(volumes._drive_path(path));
        }
        Volumes::drive_path(path)
    }

    /// Refresh the cached information.
    pub fn refresh() -> io::Result<()> {
        #[cfg(windows)]
        Volumes::refresh().map_err(io_error_from_anyhow)?;
        Ok(())
    }

    /// Return an object that implements [`Display`][`core::fmt::Display`]
    /// for printing simplified paths.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::path::Path;
    /// # use simple_path::SimplePath;
    /// # fn test() -> std::io::Result<()> {
    /// let path = Path::new("file").canonicalize()?;
    /// println!("{}", SimplePath::default().display(&path));
    /// # Ok(())
    /// # }
    /// ```
    pub fn display<'a>(&'a self, path: &'a Path) -> Display<'a> {
        Display::new(self, path)
    }

    /// Return `true` if the given `path` is a UNC path.
    /// A UNC path starts with a "`\\`" prefix.
    ///
    /// Always `false` on non-Windows platforms.
    ///
    /// # Examples
    /// ```
    /// # use simple_path::SimplePath;
    /// #[cfg(windows)]
    /// {
    ///     assert!(SimplePath::is_unc(r"\\unc"));
    ///     assert!(SimplePath::is_unc(r"//unc"));
    ///     assert!(!SimplePath::is_unc(r"\not-unc"));
    /// }
    /// assert!(!SimplePath::is_unc("/not-unc"));
    /// assert!(!SimplePath::is_unc("not-unc"));
    /// ```
    #[inline]
    pub fn is_unc(path: impl AsRef<Path>) -> bool {
        #[cfg(windows)]
        return UncPath::is_unc(path);
        #[cfg(not(windows))]
        false
    }

    /// A snap-in replacement for [`Path::strip_prefix`]
    /// with a fix for [a leading directory separator "`\`" left for UNC paths
    /// on Windows](https://github.com/rust-lang/rust/issues/155183).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::path::{Path, StripPrefixError};
    /// # use simple_path::SimplePath;
    /// # fn t<'a>(path: &'a Path, base: &'a Path) -> Result<&'a Path, StripPrefixError> {
    /// SimplePath::strip_prefix(path, base)
    /// # }
    /// ```
    #[inline]
    pub fn strip_prefix(path: &Path, base: impl AsRef<Path>) -> Result<&Path, StripPrefixError> {
        #[cfg(windows)]
        return PathExt::strip_prefix_fix(path, base);
        #[cfg(not(windows))]
        path.strip_prefix(base)
    }
}

fn io_error_from_anyhow(error: anyhow::Error) -> io::Error {
    match error.downcast::<io::Error>() {
        Ok(io_error) => io_error,
        Err(other_error) => io::Error::other(other_error),
    }
}

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

    #[cfg(windows)]
    #[test]
    fn simplify_drive() {
        let mut simple = SimplePath::mock();
        assert_eq!(simple.simplify(Path::new(r"C:\foo")).unwrap(), None);
        simple.disallow_unknown_unc = true;
        assert_eq!(simple.simplify(Path::new(r"C:\foo")).unwrap(), None);
    }

    #[cfg(windows)]
    #[test]
    fn simplify_drive_unc() {
        let mut simple = SimplePath::mock();
        let path = Path::new(r"\\?\UNC\server\share\foo");
        let path2 = Path::new(r"\\?\UNC\server2\share2\foo2");
        assert_eq!(
            simple.simplify(path).unwrap(),
            Some(Cow::Owned(PathBuf::from(r"\\server\share\foo")))
        );
        assert_eq!(
            simple.simplify(path2).unwrap(),
            Some(Cow::Owned(PathBuf::from(r"\\server2\share2\foo2")))
        );

        simple.map_to_drive = true;
        assert_eq!(
            simple.simplify(path).unwrap(),
            Some(Cow::Owned(PathBuf::from(r"X:\foo")))
        );
        assert_eq!(
            simple.simplify(path2).unwrap(),
            Some(Cow::Owned(PathBuf::from(r"Z:\foo2")))
        );
    }

    #[cfg(windows)]
    #[test]
    fn simplify_dunce() {
        let simple = SimplePath::default();
        assert_eq!(
            simple.simplify(Path::new(r"\\?\C:\foo")).unwrap(),
            Some(Cow::Borrowed(Path::new(r"C:\foo")))
        );
    }

    #[cfg(windows)]
    #[test]
    fn simplify_dunce_skip() {
        let simple = SimplePath {
            skip_dunce: true,
            ..Default::default()
        };
        assert_eq!(simple.simplify(Path::new(r"\\?\C:\foo")).unwrap(), None);
    }

    #[cfg(windows)]
    #[test]
    fn simplify_unmapped_connected_share() {
        let mut simple = SimplePath::mock();
        let path = Path::new(r"\\?\UNC\server0\share0\foo");
        assert_eq!(
            simple.simplify(path).unwrap(),
            Some(Cow::Owned(PathBuf::from(r"\\server0\share0\foo")))
        );

        // Even with map_to_drive = true, it should simplify to the UNC path,
        // because the drive letter is '\0'.
        simple.map_to_drive = true;
        assert_eq!(
            simple.simplify(path).unwrap(),
            Some(Cow::Owned(PathBuf::from(r"\\server0\share0\foo")))
        );
    }

    #[cfg(windows)]
    #[test]
    fn simplify_unknown_unc() -> anyhow::Result<()> {
        let mut simple = SimplePath::mock();
        let unknown = Path::new(r"\\?\UNC\server\unknown\foo");
        let mapped = Path::new(r"\\?\UNC\server\share\foo");
        assert_eq!(
            simple.simplify(unknown)?,
            Some(Cow::Owned(PathBuf::from(r"\\server\unknown\foo")))
        );
        assert_eq!(
            simple.simplify(mapped)?,
            Some(Cow::Owned(PathBuf::from(r"\\server\share\foo")))
        );

        // `unknown` should not be simplified if `disallow_unknown_unc`.
        simple.disallow_unknown_unc = true;
        assert_eq!(simple.simplify(unknown)?, None);

        // `map_to_drive` should still be in effect.
        simple.map_to_drive = true;
        assert_eq!(
            simple.simplify(mapped)?,
            Some(Cow::Owned(PathBuf::from(r"X:\foo")))
        );

        // `disallow_unknown_unc` should simplify only for "`\\?\UNC\`".
        assert_eq!(simple.simplify(Path::new(r"\\.\COM1:"))?, None);
        simple.skip_dunce = true;
        assert_eq!(simple.simplify(Path::new(r"\\?\C:\foo"))?, None);
        Ok(())
    }
}