Skip to main content

boltz_util/
paths.rs

1use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
2use itertools::Itertools;
3use regex::Regex;
4use serde::{Deserialize, Serialize};
5use std::borrow::Cow;
6use std::cmp::Ordering;
7use std::error::Error;
8use std::fmt::{Display, Formatter};
9use std::mem;
10use std::path::StripPrefixError;
11use std::sync::Arc;
12use std::{
13    ffi::OsStr,
14    path::{Path, PathBuf},
15    sync::LazyLock,
16};
17
18use crate::rel_path::RelPath;
19use crate::rel_path::RelPathBuf;
20
21/// Returns the path to the user's home directory.
22pub fn home_dir() -> &'static PathBuf {
23    static HOME_DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
24    HOME_DIR.get_or_init(|| {
25        if cfg!(any(test, feature = "test-support")) {
26            if cfg!(target_os = "macos") {
27                PathBuf::from("/Users/user")
28            } else if cfg!(target_os = "windows") {
29                PathBuf::from("C:\\Users\\user")
30            } else {
31                PathBuf::from("/home/user")
32            }
33        } else {
34            dirs::home_dir().expect("failed to determine home directory")
35        }
36    })
37}
38
39pub trait PathExt {
40    /// Compacts a given file path by replacing the user's home directory
41    /// prefix with a tilde (`~`).
42    ///
43    /// # Returns
44    ///
45    /// * A `PathBuf` containing the compacted file path. If the input path
46    ///   does not have the user's home directory prefix, or if we are not on
47    ///   Linux or macOS, the original path is returned unchanged.
48    fn compact(&self) -> PathBuf;
49
50    /// Returns a file's extension or, if the file is hidden, its name without the leading dot
51    fn extension_or_hidden_file_name(&self) -> Option<&str>;
52
53    fn try_from_bytes<'a>(bytes: &'a [u8]) -> anyhow::Result<Self>
54    where
55        Self: From<&'a Path>,
56    {
57        #[cfg(target_family = "wasm")]
58        {
59            std::str::from_utf8(bytes)
60                .map(Path::new)
61                .map(Into::into)
62                .map_err(Into::into)
63        }
64        #[cfg(unix)]
65        {
66            use std::os::unix::prelude::OsStrExt;
67            Ok(Self::from(Path::new(OsStr::from_bytes(bytes))))
68        }
69        #[cfg(windows)]
70        {
71            use anyhow::Context;
72            use tendril::fmt::{Format, WTF8};
73            WTF8::validate(bytes)
74                .then(|| {
75                    // Safety: bytes are valid WTF-8 sequence.
76                    Self::from(Path::new(unsafe {
77                        OsStr::from_encoded_bytes_unchecked(bytes)
78                    }))
79                })
80                .with_context(|| format!("Invalid WTF-8 sequence: {bytes:?}"))
81        }
82    }
83
84    /// Converts a local path to one that can be used inside of WSL.
85    /// Returns `None` if the path cannot be converted into a WSL one (network share).
86    fn local_to_wsl(&self) -> Option<PathBuf>;
87
88    /// Returns a file's "full" joined collection of extensions, in the case where a file does not
89    /// just have a singular extension but instead has multiple (e.g File.tar.gz, Component.stories.tsx)
90    ///
91    /// Will provide back the extensions joined together such as tar.gz or stories.tsx
92    fn multiple_extensions(&self) -> Option<String>;
93
94    /// Try to make a shell-safe representation of the path.
95    #[cfg(not(target_family = "wasm"))]
96    fn try_shell_safe(&self, shell_kind: crate::shell::ShellKind) -> anyhow::Result<String>;
97}
98
99impl<T: AsRef<Path>> PathExt for T {
100    fn compact(&self) -> PathBuf {
101        #[cfg(target_family = "wasm")]
102        {
103            self.as_ref().to_path_buf()
104        }
105        #[cfg(not(target_family = "wasm"))]
106        if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
107            match self.as_ref().strip_prefix(home_dir().as_path()) {
108                Ok(relative_path) => {
109                    let mut shortened_path = PathBuf::new();
110                    shortened_path.push("~");
111                    shortened_path.push(relative_path);
112                    shortened_path
113                }
114                Err(_) => self.as_ref().to_path_buf(),
115            }
116        } else {
117            self.as_ref().to_path_buf()
118        }
119    }
120
121    fn extension_or_hidden_file_name(&self) -> Option<&str> {
122        let path = self.as_ref();
123        let file_name = path.file_name()?.to_str()?;
124        if file_name.starts_with('.') {
125            return file_name.strip_prefix('.');
126        }
127
128        path.extension()
129            .and_then(|e| e.to_str())
130            .or_else(|| path.file_stem()?.to_str())
131    }
132
133    fn local_to_wsl(&self) -> Option<PathBuf> {
134        // quite sketchy to convert this back to path at the end, but a lot of functions only accept paths
135        // todo: ideally rework them..?
136        let mut new_path = std::ffi::OsString::new();
137        for component in self.as_ref().components() {
138            match component {
139                std::path::Component::Prefix(prefix) => {
140                    let drive_letter = prefix.as_os_str().to_string_lossy().to_lowercase();
141                    let drive_letter = drive_letter.strip_suffix(':')?;
142
143                    new_path.push(format!("/mnt/{}", drive_letter));
144                }
145                std::path::Component::RootDir => {}
146                std::path::Component::CurDir => {
147                    new_path.push("/.");
148                }
149                std::path::Component::ParentDir => {
150                    new_path.push("/..");
151                }
152                std::path::Component::Normal(os_str) => {
153                    new_path.push("/");
154                    new_path.push(os_str);
155                }
156            }
157        }
158
159        Some(new_path.into())
160    }
161
162    fn multiple_extensions(&self) -> Option<String> {
163        let path = self.as_ref();
164        let file_name = path.file_name()?.to_str()?;
165
166        let parts: Vec<&str> = file_name
167            .split('.')
168            // Skip the part with the file name extension
169            .skip(1)
170            .collect();
171
172        if parts.len() < 2 {
173            return None;
174        }
175
176        Some(parts.into_iter().join("."))
177    }
178
179    #[cfg(not(target_family = "wasm"))]
180    fn try_shell_safe(&self, shell_kind: crate::shell::ShellKind) -> anyhow::Result<String> {
181        use anyhow::Context;
182        let path_str = self
183            .as_ref()
184            .to_str()
185            .with_context(|| "Path contains invalid UTF-8")?;
186        shell_kind
187            .try_quote(path_str)
188            .as_deref()
189            .map(ToOwned::to_owned)
190            .context("Failed to quote path")
191    }
192}
193
194pub fn path_ends_with(base: &Path, suffix: &Path) -> bool {
195    strip_path_suffix(base, suffix).is_some()
196}
197
198pub fn strip_path_suffix<'a>(base: &'a Path, suffix: &Path) -> Option<&'a Path> {
199    if let Some(remainder) = base
200        .as_os_str()
201        .as_encoded_bytes()
202        .strip_suffix(suffix.as_os_str().as_encoded_bytes())
203    {
204        if remainder
205            .last()
206            .is_none_or(|last_byte| std::path::is_separator(*last_byte as char))
207        {
208            let os_str = unsafe {
209                OsStr::from_encoded_bytes_unchecked(
210                    &remainder[0..remainder.len().saturating_sub(1)],
211                )
212            };
213            return Some(Path::new(os_str));
214        }
215    }
216    None
217}
218
219/// In memory, this is identical to `Path`. On non-Windows conversions to this type are no-ops. On
220/// windows, these conversions sanitize UNC paths by removing the `\\\\?\\` prefix.
221#[derive(Eq, PartialEq, Hash, Ord, PartialOrd)]
222#[repr(transparent)]
223pub struct SanitizedPath(Path);
224
225impl SanitizedPath {
226    pub fn new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
227        #[cfg(not(target_os = "windows"))]
228        return Self::unchecked_new(path.as_ref());
229
230        #[cfg(target_os = "windows")]
231        return Self::unchecked_new(dunce::simplified(path.as_ref()));
232    }
233
234    pub fn unchecked_new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
235        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
236        unsafe { mem::transmute::<&Path, &Self>(path.as_ref()) }
237    }
238
239    pub fn from_arc(path: Arc<Path>) -> Arc<Self> {
240        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
241        #[cfg(not(target_os = "windows"))]
242        return unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) };
243
244        #[cfg(target_os = "windows")]
245        {
246            let simplified = dunce::simplified(path.as_ref());
247            if simplified == path.as_ref() {
248                // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
249                unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) }
250            } else {
251                Self::unchecked_new(simplified).into()
252            }
253        }
254    }
255
256    pub fn new_arc<T: AsRef<Path> + ?Sized>(path: &T) -> Arc<Self> {
257        Self::new(path).into()
258    }
259
260    pub fn cast_arc(path: Arc<Self>) -> Arc<Path> {
261        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
262        unsafe { mem::transmute::<Arc<Self>, Arc<Path>>(path) }
263    }
264
265    pub fn cast_arc_ref(path: &Arc<Self>) -> &Arc<Path> {
266        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
267        unsafe { mem::transmute::<&Arc<Self>, &Arc<Path>>(path) }
268    }
269
270    pub fn starts_with(&self, prefix: &Self) -> bool {
271        self.0.starts_with(&prefix.0)
272    }
273
274    pub fn as_path(&self) -> &Path {
275        &self.0
276    }
277
278    pub fn file_name(&self) -> Option<&std::ffi::OsStr> {
279        self.0.file_name()
280    }
281
282    pub fn extension(&self) -> Option<&std::ffi::OsStr> {
283        self.0.extension()
284    }
285
286    pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
287        self.0.join(path)
288    }
289
290    pub fn parent(&self) -> Option<&Self> {
291        self.0.parent().map(Self::unchecked_new)
292    }
293
294    pub fn strip_prefix(&self, base: &Self) -> Result<&Path, StripPrefixError> {
295        self.0.strip_prefix(base.as_path())
296    }
297
298    pub fn to_str(&self) -> Option<&str> {
299        self.0.to_str()
300    }
301
302    pub fn to_path_buf(&self) -> PathBuf {
303        self.0.to_path_buf()
304    }
305}
306
307impl std::fmt::Debug for SanitizedPath {
308    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
309        std::fmt::Debug::fmt(&self.0, formatter)
310    }
311}
312
313impl Display for SanitizedPath {
314    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
315        write!(f, "{}", self.0.display())
316    }
317}
318
319impl From<&SanitizedPath> for Arc<SanitizedPath> {
320    fn from(sanitized_path: &SanitizedPath) -> Self {
321        let path: Arc<Path> = sanitized_path.0.into();
322        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
323        unsafe { mem::transmute(path) }
324    }
325}
326
327impl From<&SanitizedPath> for PathBuf {
328    fn from(sanitized_path: &SanitizedPath) -> Self {
329        sanitized_path.as_path().into()
330    }
331}
332
333impl AsRef<Path> for SanitizedPath {
334    fn as_ref(&self) -> &Path {
335        &self.0
336    }
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
340pub enum PathStyle {
341    Posix,
342    Windows,
343}
344
345impl PathStyle {
346    #[cfg(target_os = "windows")]
347    pub const fn local() -> Self {
348        PathStyle::Windows
349    }
350
351    #[cfg(not(target_os = "windows"))]
352    pub const fn local() -> Self {
353        PathStyle::Posix
354    }
355
356    #[inline]
357    pub fn primary_separator(&self) -> &'static str {
358        match self {
359            PathStyle::Posix => "/",
360            PathStyle::Windows => "\\",
361        }
362    }
363
364    pub fn separators(&self) -> &'static [&'static str] {
365        match self {
366            PathStyle::Posix => &["/"],
367            PathStyle::Windows => &["\\", "/"],
368        }
369    }
370
371    pub fn separators_ch(&self) -> &'static [char] {
372        match self {
373            PathStyle::Posix => &['/'],
374            PathStyle::Windows => &['\\', '/'],
375        }
376    }
377
378    pub fn is_absolute(&self, path_like: &str) -> bool {
379        path_like.starts_with('/')
380            || *self == PathStyle::Windows
381                && (path_like.starts_with('\\')
382                    || path_like
383                        .chars()
384                        .next()
385                        .is_some_and(|c| c.is_ascii_alphabetic())
386                        && path_like[1..]
387                            .strip_prefix(':')
388                            .is_some_and(|path| path.starts_with('/') || path.starts_with('\\')))
389    }
390
391    pub fn is_windows(&self) -> bool {
392        *self == PathStyle::Windows
393    }
394
395    pub fn is_posix(&self) -> bool {
396        *self == PathStyle::Posix
397    }
398
399    pub fn join(self, left: impl AsRef<Path>, right: impl AsRef<Path>) -> Option<String> {
400        let right = right.as_ref().to_str()?;
401        if is_absolute(right, self) {
402            return None;
403        }
404        let left = left.as_ref().to_str()?;
405        if left.is_empty() {
406            Some(right.into())
407        } else {
408            Some(format!(
409                "{left}{}{right}",
410                if left.ends_with(self.primary_separator()) {
411                    ""
412                } else {
413                    self.primary_separator()
414                }
415            ))
416        }
417    }
418
419    pub fn split(self, path_like: &str) -> (Option<&str>, &str) {
420        let Some(pos) = path_like.rfind(self.primary_separator()) else {
421            return (None, path_like);
422        };
423        let filename_start = pos + self.primary_separator().len();
424        (
425            Some(&path_like[..filename_start]),
426            &path_like[filename_start..],
427        )
428    }
429
430    pub fn strip_prefix<'a>(
431        &self,
432        child: &'a Path,
433        parent: &'a Path,
434    ) -> Option<std::borrow::Cow<'a, RelPath>> {
435        let parent = parent.to_str()?;
436        if parent.is_empty() {
437            return RelPath::new(child, *self).ok();
438        }
439        let parent = self
440            .separators()
441            .iter()
442            .find_map(|sep| parent.strip_suffix(sep))
443            .unwrap_or(parent);
444        let child = child.to_str()?;
445
446        // Match behavior of std::path::Path, which is case-insensitive for drive letters (e.g., "C:" == "c:")
447        let stripped = if self.is_windows()
448            && child.as_bytes().get(1) == Some(&b':')
449            && parent.as_bytes().get(1) == Some(&b':')
450            && child.as_bytes()[0].eq_ignore_ascii_case(&parent.as_bytes()[0])
451        {
452            child[2..].strip_prefix(&parent[2..])?
453        } else {
454            child.strip_prefix(parent)?
455        };
456        if let Some(relative) = self
457            .separators()
458            .iter()
459            .find_map(|sep| stripped.strip_prefix(sep))
460        {
461            RelPath::new(relative.as_ref(), *self).ok()
462        } else if stripped.is_empty() {
463            Some(Cow::Borrowed(RelPath::empty()))
464        } else {
465            None
466        }
467    }
468}
469
470#[derive(Debug, Clone)]
471pub struct RemotePathBuf {
472    style: PathStyle,
473    string: String,
474}
475
476impl RemotePathBuf {
477    pub fn new(string: String, style: PathStyle) -> Self {
478        Self { style, string }
479    }
480
481    pub fn from_str(path: &str, style: PathStyle) -> Self {
482        Self::new(path.to_string(), style)
483    }
484
485    pub fn path_style(&self) -> PathStyle {
486        self.style
487    }
488
489    pub fn to_proto(self) -> String {
490        self.string
491    }
492}
493
494impl Display for RemotePathBuf {
495    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496        write!(f, "{}", self.string)
497    }
498}
499
500pub fn is_absolute(path_like: &str, path_style: PathStyle) -> bool {
501    path_like.starts_with('/')
502        || path_style == PathStyle::Windows
503            && (path_like.starts_with('\\')
504                || path_like
505                    .chars()
506                    .next()
507                    .is_some_and(|c| c.is_ascii_alphabetic())
508                    && path_like[1..]
509                        .strip_prefix(':')
510                        .is_some_and(|path| path.starts_with('/') || path.starts_with('\\')))
511}
512
513#[derive(Debug, PartialEq)]
514#[non_exhaustive]
515pub struct NormalizeError;
516
517impl Error for NormalizeError {}
518
519impl std::fmt::Display for NormalizeError {
520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521        f.write_str("parent reference `..` points outside of base directory")
522    }
523}
524
525/// Copied from stdlib where it's unstable.
526///
527/// Normalize a path, including `..` without traversing the filesystem.
528///
529/// Returns an error if normalization would leave leading `..` components.
530///
531/// <div class="warning">
532///
533/// This function always resolves `..` to the "lexical" parent.
534/// That is "a/b/../c" will always resolve to `a/c` which can change the meaning of the path.
535/// In particular, `a/c` and `a/b/../c` are distinct on many systems because `b` may be a symbolic link, so its parent isn't `a`.
536///
537/// </div>
538///
539/// [`path::absolute`](absolute) is an alternative that preserves `..`.
540/// Or [`Path::canonicalize`] can be used to resolve any `..` by querying the filesystem.
541pub fn normalize_lexically(path: &Path) -> Result<PathBuf, NormalizeError> {
542    use std::path::Component;
543
544    let mut lexical = PathBuf::new();
545    let mut iter = path.components().peekable();
546
547    // Find the root, if any, and add it to the lexical path.
548    // Here we treat the Windows path "C:\" as a single "root" even though
549    // `components` splits it into two: (Prefix, RootDir).
550    let root = match iter.peek() {
551        Some(Component::ParentDir) => return Err(NormalizeError),
552        Some(p @ Component::RootDir) | Some(p @ Component::CurDir) => {
553            lexical.push(p);
554            iter.next();
555            lexical.as_os_str().len()
556        }
557        Some(Component::Prefix(prefix)) => {
558            lexical.push(prefix.as_os_str());
559            iter.next();
560            if let Some(p @ Component::RootDir) = iter.peek() {
561                lexical.push(p);
562                iter.next();
563            }
564            lexical.as_os_str().len()
565        }
566        None => return Ok(PathBuf::new()),
567        Some(Component::Normal(_)) => 0,
568    };
569
570    for component in iter {
571        match component {
572            Component::RootDir => unreachable!(),
573            Component::Prefix(_) => return Err(NormalizeError),
574            Component::CurDir => continue,
575            Component::ParentDir => {
576                // It's an error if ParentDir causes us to go above the "root".
577                if lexical.as_os_str().len() == root {
578                    return Err(NormalizeError);
579                } else {
580                    lexical.pop();
581                }
582            }
583            Component::Normal(path) => lexical.push(path),
584        }
585    }
586    Ok(lexical)
587}
588
589/// A delimiter to use in `path_query:row_number:column_number` strings parsing.
590pub const FILE_ROW_COLUMN_DELIMITER: char = ':';
591
592const ROW_COL_CAPTURE_REGEX: &str = r"(?xs)
593    ([^\(]+)\:(?:
594        \((\d+)[,:](\d+)\) # filename:(row,column), filename:(row:column)
595        |
596        \((\d+)\)()     # filename:(row)
597    )
598    |
599    ([^\(]+)(?:
600        \((\d+)[,:](\d+)\) # filename(row,column), filename(row:column)
601        |
602        \((\d+)\)()     # filename(row)
603    )
604    \:*$
605    |
606    (.+?)(?:
607        \:+(\d+)\:(\d+)\:*$  # filename:row:column
608        |
609        \:+(\d+)\:*()$       # filename:row
610        |
611        \:+()()$
612    )";
613
614/// A representation of a path-like string with optional row and column numbers.
615/// Matching values example: `te`, `test.rs:22`, `te:22:5`, `test.c(22)`, `test.c(22,5)`etc.
616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
617pub struct PathWithPosition {
618    pub path: PathBuf,
619    pub row: Option<u32>,
620    // Absent if row is absent.
621    pub column: Option<u32>,
622}
623
624impl PathWithPosition {
625    /// Returns a PathWithPosition from a path.
626    pub fn from_path(path: PathBuf) -> Self {
627        Self {
628            path,
629            row: None,
630            column: None,
631        }
632    }
633
634    /// Parses a string that possibly has `:row:column` or `(row, column)` suffix.
635    /// Parenthesis format is used by [MSBuild](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks) compatible tools
636    /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`.
637    /// If the suffix parsing fails, the whole string is parsed as a path.
638    ///
639    /// Be mindful that `test_file:10:1:` is a valid posix filename.
640    /// `PathWithPosition` class assumes that the ending position-like suffix is **not** part of the filename.
641    ///
642    /// # Examples
643    ///
644    /// ```
645    /// # use util::paths::PathWithPosition;
646    /// # use std::path::PathBuf;
647    /// assert_eq!(PathWithPosition::parse_str("test_file"), PathWithPosition {
648    ///     path: PathBuf::from("test_file"),
649    ///     row: None,
650    ///     column: None,
651    /// });
652    /// assert_eq!(PathWithPosition::parse_str("test_file:10"), PathWithPosition {
653    ///     path: PathBuf::from("test_file"),
654    ///     row: Some(10),
655    ///     column: None,
656    /// });
657    /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
658    ///     path: PathBuf::from("test_file.rs"),
659    ///     row: None,
660    ///     column: None,
661    /// });
662    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1"), PathWithPosition {
663    ///     path: PathBuf::from("test_file.rs"),
664    ///     row: Some(1),
665    ///     column: None,
666    /// });
667    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2"), PathWithPosition {
668    ///     path: PathBuf::from("test_file.rs"),
669    ///     row: Some(1),
670    ///     column: Some(2),
671    /// });
672    /// ```
673    ///
674    /// # Expected parsing results when encounter ill-formatted inputs.
675    /// ```
676    /// # use util::paths::PathWithPosition;
677    /// # use std::path::PathBuf;
678    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a"), PathWithPosition {
679    ///     path: PathBuf::from("test_file.rs:a"),
680    ///     row: None,
681    ///     column: None,
682    /// });
683    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a:b"), PathWithPosition {
684    ///     path: PathBuf::from("test_file.rs:a:b"),
685    ///     row: None,
686    ///     column: None,
687    /// });
688    /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
689    ///     path: PathBuf::from("test_file.rs"),
690    ///     row: None,
691    ///     column: None,
692    /// });
693    /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1"), PathWithPosition {
694    ///     path: PathBuf::from("test_file.rs"),
695    ///     row: Some(1),
696    ///     column: None,
697    /// });
698    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::"), PathWithPosition {
699    ///     path: PathBuf::from("test_file.rs"),
700    ///     row: Some(1),
701    ///     column: None,
702    /// });
703    /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1:2"), PathWithPosition {
704    ///     path: PathBuf::from("test_file.rs"),
705    ///     row: Some(1),
706    ///     column: Some(2),
707    /// });
708    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::2"), PathWithPosition {
709    ///     path: PathBuf::from("test_file.rs:1"),
710    ///     row: Some(2),
711    ///     column: None,
712    /// });
713    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2:3"), PathWithPosition {
714    ///     path: PathBuf::from("test_file.rs:1"),
715    ///     row: Some(2),
716    ///     column: Some(3),
717    /// });
718    /// ```
719    pub fn parse_str(s: &str) -> Self {
720        let trimmed = s.trim();
721        let path = Path::new(trimmed);
722        let Some(maybe_file_name_with_row_col) = path.file_name().unwrap_or_default().to_str()
723        else {
724            return Self {
725                path: Path::new(s).to_path_buf(),
726                row: None,
727                column: None,
728            };
729        };
730        if maybe_file_name_with_row_col.is_empty() {
731            return Self {
732                path: Path::new(s).to_path_buf(),
733                row: None,
734                column: None,
735            };
736        }
737
738        // Let's avoid repeated init cost on this. It is subject to thread contention, but
739        // so far this code isn't called from multiple hot paths. Getting contention here
740        // in the future seems unlikely.
741        static SUFFIX_RE: LazyLock<Regex> =
742            LazyLock::new(|| Regex::new(ROW_COL_CAPTURE_REGEX).unwrap());
743        match SUFFIX_RE
744            .captures(maybe_file_name_with_row_col)
745            .map(|caps| caps.extract())
746        {
747            Some((_, [file_name, maybe_row, maybe_column])) => {
748                let row = maybe_row.parse::<u32>().ok();
749                let column = maybe_column.parse::<u32>().ok();
750
751                let (_, suffix) = trimmed.split_once(file_name).unwrap();
752                let path_without_suffix = &trimmed[..trimmed.len() - suffix.len()];
753
754                Self {
755                    path: Path::new(path_without_suffix).to_path_buf(),
756                    row,
757                    column,
758                }
759            }
760            None => {
761                // The `ROW_COL_CAPTURE_REGEX` deals with separated digits only,
762                // but in reality there could be `foo/bar.py:22:in` inputs which we want to match too.
763                // The regex mentioned is not very extendable with "digit or random string" checks, so do this here instead.
764                let delimiter = ':';
765                let mut path_parts = s
766                    .rsplitn(3, delimiter)
767                    .collect::<Vec<_>>()
768                    .into_iter()
769                    .rev()
770                    .fuse();
771                let mut path_string = path_parts.next().expect("rsplitn should have the rest of the string as its last parameter that we reversed").to_owned();
772                let mut row = None;
773                let mut column = None;
774                if let Some(maybe_row) = path_parts.next() {
775                    if let Ok(parsed_row) = maybe_row.parse::<u32>() {
776                        row = Some(parsed_row);
777                        if let Some(parsed_column) = path_parts
778                            .next()
779                            .and_then(|maybe_col| maybe_col.parse::<u32>().ok())
780                        {
781                            column = Some(parsed_column);
782                        }
783                    } else {
784                        path_string.push(delimiter);
785                        path_string.push_str(maybe_row);
786                    }
787                }
788                for split in path_parts {
789                    path_string.push(delimiter);
790                    path_string.push_str(split);
791                }
792
793                Self {
794                    path: PathBuf::from(path_string),
795                    row,
796                    column,
797                }
798            }
799        }
800    }
801
802    pub fn map_path<E>(
803        self,
804        mapping: impl FnOnce(PathBuf) -> Result<PathBuf, E>,
805    ) -> Result<PathWithPosition, E> {
806        Ok(PathWithPosition {
807            path: mapping(self.path)?,
808            row: self.row,
809            column: self.column,
810        })
811    }
812
813    pub fn to_string(&self, path_to_string: &dyn Fn(&PathBuf) -> String) -> String {
814        let path_string = path_to_string(&self.path);
815        if let Some(row) = self.row {
816            if let Some(column) = self.column {
817                format!("{path_string}:{row}:{column}")
818            } else {
819                format!("{path_string}:{row}")
820            }
821        } else {
822            path_string
823        }
824    }
825}
826
827#[derive(Clone)]
828pub struct PathMatcher {
829    sources: Vec<(String, RelPathBuf, /*trailing separator*/ bool)>,
830    glob: GlobSet,
831    path_style: PathStyle,
832}
833
834impl std::fmt::Debug for PathMatcher {
835    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
836        f.debug_struct("PathMatcher")
837            .field("sources", &self.sources)
838            .field("path_style", &self.path_style)
839            .finish()
840    }
841}
842
843impl PartialEq for PathMatcher {
844    fn eq(&self, other: &Self) -> bool {
845        self.sources.eq(&other.sources)
846    }
847}
848
849impl Eq for PathMatcher {}
850
851impl PathMatcher {
852    pub fn new(
853        globs: impl IntoIterator<Item = impl AsRef<str>>,
854        path_style: PathStyle,
855    ) -> Result<Self, globset::Error> {
856        let globs = globs
857            .into_iter()
858            .map(|as_str| {
859                GlobBuilder::new(as_str.as_ref())
860                    .backslash_escape(path_style.is_posix())
861                    .build()
862            })
863            .collect::<Result<Vec<_>, _>>()?;
864        let sources = globs
865            .iter()
866            .filter_map(|glob| {
867                let glob = glob.glob();
868                Some((
869                    glob.to_string(),
870                    RelPath::new(&glob.as_ref(), path_style)
871                        .ok()
872                        .map(std::borrow::Cow::into_owned)?,
873                    glob.ends_with(path_style.separators_ch()),
874                ))
875            })
876            .collect();
877        let mut glob_builder = GlobSetBuilder::new();
878        for single_glob in globs {
879            glob_builder.add(single_glob);
880        }
881        let glob = glob_builder.build()?;
882        Ok(PathMatcher {
883            glob,
884            sources,
885            path_style,
886        })
887    }
888
889    pub fn sources(&self) -> impl Iterator<Item = &str> + Clone {
890        self.sources.iter().map(|(source, ..)| source.as_str())
891    }
892
893    pub fn is_match<P: AsRef<RelPath>>(&self, other: P) -> bool {
894        let other = other.as_ref();
895        if self
896            .sources
897            .iter()
898            .any(|(_, source, _)| other.starts_with(source) || other.ends_with(source))
899        {
900            return true;
901        }
902        let other_path = other.display(self.path_style);
903
904        if self.glob.is_match(&*other_path) {
905            return true;
906        }
907
908        self.glob
909            .is_match(other_path.into_owned() + self.path_style.primary_separator())
910    }
911
912    pub fn is_match_std_path<P: AsRef<Path>>(&self, other: P) -> bool {
913        let other = other.as_ref();
914        if self.sources.iter().any(|(_, source, _)| {
915            other.starts_with(source.as_std_path()) || other.ends_with(source.as_std_path())
916        }) {
917            return true;
918        }
919        self.glob.is_match(other)
920    }
921}
922
923impl Default for PathMatcher {
924    fn default() -> Self {
925        Self {
926            path_style: PathStyle::local(),
927            glob: GlobSet::empty(),
928            sources: vec![],
929        }
930    }
931}
932
933/// Compares two sequences of consecutive digits for natural sorting.
934///
935/// This function is a core component of natural sorting that handles numeric comparison
936/// in a way that feels natural to humans. It extracts and compares consecutive digit
937/// sequences from two iterators, handling various cases like leading zeros and very large numbers.
938///
939/// # Behavior
940///
941/// The function implements the following comparison rules:
942/// 1. Different numeric values: Compares by actual numeric value (e.g., "2" < "10")
943/// 2. Leading zeros: When values are equal, longer sequence wins (e.g., "002" > "2")
944/// 3. Large numbers: Falls back to string comparison for numbers that would overflow u128
945///
946/// # Examples
947///
948/// ```text
949/// "1" vs "2"      -> Less       (different values)
950/// "2" vs "10"     -> Less       (numeric comparison)
951/// "002" vs "2"    -> Greater    (leading zeros)
952/// "10" vs "010"   -> Less       (leading zeros)
953/// "999..." vs "1000..." -> Less (large number comparison)
954/// ```
955///
956/// # Implementation Details
957///
958/// 1. Extracts consecutive digits into strings
959/// 2. Compares sequence lengths for leading zero handling
960/// 3. For equal lengths, compares digit by digit
961/// 4. For different lengths:
962///    - Attempts numeric comparison first (for numbers up to 2^128 - 1)
963///    - Falls back to string comparison if numbers would overflow
964///
965/// The function advances both iterators past their respective numeric sequences,
966/// regardless of the comparison result.
967fn compare_numeric_segments<I>(
968    a_iter: &mut std::iter::Peekable<I>,
969    b_iter: &mut std::iter::Peekable<I>,
970) -> Ordering
971where
972    I: Iterator<Item = char>,
973{
974    // Collect all consecutive digits into strings
975    let mut a_num_str = String::new();
976    let mut b_num_str = String::new();
977
978    while let Some(&c) = a_iter.peek() {
979        if !c.is_ascii_digit() {
980            break;
981        }
982
983        a_num_str.push(c);
984        a_iter.next();
985    }
986
987    while let Some(&c) = b_iter.peek() {
988        if !c.is_ascii_digit() {
989            break;
990        }
991
992        b_num_str.push(c);
993        b_iter.next();
994    }
995
996    // First compare lengths (handle leading zeros)
997    match a_num_str.len().cmp(&b_num_str.len()) {
998        Ordering::Equal => {
999            // Same length, compare digit by digit
1000            match a_num_str.cmp(&b_num_str) {
1001                Ordering::Equal => Ordering::Equal,
1002                ordering => ordering,
1003            }
1004        }
1005
1006        // Different lengths but same value means leading zeros
1007        ordering => {
1008            // Try parsing as numbers first
1009            if let (Ok(a_val), Ok(b_val)) = (a_num_str.parse::<u128>(), b_num_str.parse::<u128>()) {
1010                match a_val.cmp(&b_val) {
1011                    Ordering::Equal => ordering, // Same value, longer one is greater (leading zeros)
1012                    ord => ord,
1013                }
1014            } else {
1015                // If parsing fails (overflow), compare as strings
1016                a_num_str.cmp(&b_num_str)
1017            }
1018        }
1019    }
1020}
1021
1022/// Performs natural sorting comparison between two strings.
1023///
1024/// Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations.
1025/// For example, "file2" comes before "file10" (unlike standard lexicographic sorting).
1026///
1027/// # Characteristics
1028///
1029/// * Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase
1030/// * Numbers are compared by numeric value, not character by character
1031/// * Leading zeros affect ordering when numeric values are equal
1032/// * Can handle numbers larger than u128::MAX (falls back to string comparison)
1033/// * When strings are equal case-insensitively, lowercase is prioritized (lowercase < uppercase)
1034///
1035/// # Algorithm
1036///
1037/// The function works by:
1038/// 1. Processing strings character by character in a case-insensitive manner
1039/// 2. When encountering digits, treating consecutive digits as a single number
1040/// 3. Comparing numbers by their numeric value rather than lexicographically
1041/// 4. For non-numeric characters, using case-insensitive comparison
1042/// 5. If everything is equal case-insensitively, using case-sensitive comparison as final tie-breaker
1043pub fn natural_sort(a: &str, b: &str) -> Ordering {
1044    let mut a_iter = a.chars().peekable();
1045    let mut b_iter = b.chars().peekable();
1046
1047    loop {
1048        match (a_iter.peek(), b_iter.peek()) {
1049            (None, None) => {
1050                return b.cmp(a);
1051            }
1052            (None, _) => return Ordering::Less,
1053            (_, None) => return Ordering::Greater,
1054            (Some(&a_char), Some(&b_char)) => {
1055                if a_char.is_ascii_digit() && b_char.is_ascii_digit() {
1056                    match compare_numeric_segments(&mut a_iter, &mut b_iter) {
1057                        Ordering::Equal => continue,
1058                        ordering => return ordering,
1059                    }
1060                } else {
1061                    match a_char
1062                        .to_ascii_lowercase()
1063                        .cmp(&b_char.to_ascii_lowercase())
1064                    {
1065                        Ordering::Equal => {
1066                            a_iter.next();
1067                            b_iter.next();
1068                        }
1069                        ordering => return ordering,
1070                    }
1071                }
1072            }
1073        }
1074    }
1075}
1076
1077/// Case-insensitive natural sort without applying the final lowercase/uppercase tie-breaker.
1078/// This is useful when comparing individual path components where we want to keep walking
1079/// deeper components before deciding on casing.
1080fn natural_sort_no_tiebreak(a: &str, b: &str) -> Ordering {
1081    if a.eq_ignore_ascii_case(b) {
1082        Ordering::Equal
1083    } else {
1084        natural_sort(a, b)
1085    }
1086}
1087
1088fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) {
1089    if filename.is_empty() {
1090        return (None, None);
1091    }
1092
1093    match filename.rsplit_once('.') {
1094        // Case 1: No dot was found. The entire name is the stem.
1095        None => (Some(filename), None),
1096
1097        // Case 2: A dot was found.
1098        Some((before, after)) => {
1099            // This is the crucial check for dotfiles like ".bashrc".
1100            // If `before` is empty, the dot was the first character.
1101            // In that case, we revert to the "whole name is the stem" logic.
1102            if before.is_empty() {
1103                (Some(filename), None)
1104            } else {
1105                // Otherwise, we have a standard stem and extension.
1106                (Some(before), Some(after))
1107            }
1108        }
1109    }
1110}
1111
1112/// Controls the lexicographic sorting of file and folder names.
1113#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1114pub enum SortOrder {
1115    /// Case-insensitive natural sort with lowercase preferred in ties.
1116    /// Numbers in file names are compared by value (e.g., `file2` before `file10`).
1117    #[default]
1118    Default,
1119    /// Uppercase names are grouped before lowercase names, with case-insensitive
1120    /// natural sort within each group. Dot-prefixed names sort before both groups.
1121    Upper,
1122    /// Lowercase names are grouped before uppercase names, with case-insensitive
1123    /// natural sort within each group. Dot-prefixed names sort before both groups.
1124    Lower,
1125    /// Pure Unicode codepoint comparison. No case folding, no natural number sorting.
1126    /// Uppercase ASCII sorts before lowercase. Accented characters sort after ASCII.
1127    Unicode,
1128}
1129
1130/// Controls how files and directories are ordered relative to each other.
1131#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1132pub enum SortMode {
1133    /// Directories are listed before files at each level.
1134    #[default]
1135    DirectoriesFirst,
1136    /// Files and directories are interleaved alphabetically.
1137    Mixed,
1138    /// Files are listed before directories at each level.
1139    FilesFirst,
1140}
1141
1142fn case_group_key(name: &str, order: SortOrder) -> u8 {
1143    let first = match name.chars().next() {
1144        Some(c) => c,
1145        None => return 0,
1146    };
1147    match order {
1148        SortOrder::Upper => {
1149            if first.is_lowercase() {
1150                1
1151            } else {
1152                0
1153            }
1154        }
1155        SortOrder::Lower => {
1156            if first.is_uppercase() {
1157                1
1158            } else {
1159                0
1160            }
1161        }
1162        _ => 0,
1163    }
1164}
1165
1166fn compare_strings(a: &str, b: &str, order: SortOrder) -> Ordering {
1167    match order {
1168        SortOrder::Unicode => a.cmp(b),
1169        _ => natural_sort(a, b),
1170    }
1171}
1172
1173fn compare_strings_no_tiebreak(a: &str, b: &str, order: SortOrder) -> Ordering {
1174    match order {
1175        SortOrder::Unicode => a.cmp(b),
1176        _ => natural_sort_no_tiebreak(a, b),
1177    }
1178}
1179
1180pub fn compare_rel_paths(
1181    (path_a, a_is_file): (&RelPath, bool),
1182    (path_b, b_is_file): (&RelPath, bool),
1183) -> Ordering {
1184    compare_rel_paths_by(
1185        (path_a, a_is_file),
1186        (path_b, b_is_file),
1187        SortMode::DirectoriesFirst,
1188        SortOrder::Default,
1189    )
1190}
1191
1192pub fn compare_rel_paths_by(
1193    (path_a, a_is_file): (&RelPath, bool),
1194    (path_b, b_is_file): (&RelPath, bool),
1195    mode: SortMode,
1196    order: SortOrder,
1197) -> Ordering {
1198    let needs_final_tiebreak =
1199        mode != SortMode::DirectoriesFirst && !(std::ptr::eq(path_a, path_b) || path_a == path_b);
1200
1201    let mut components_a = path_a.components();
1202    let mut components_b = path_b.components();
1203
1204    loop {
1205        match (components_a.next(), components_b.next()) {
1206            (Some(component_a), Some(component_b)) => {
1207                let a_leaf_file = a_is_file && components_a.rest().is_empty();
1208                let b_leaf_file = b_is_file && components_b.rest().is_empty();
1209
1210                let file_dir_ordering = match mode {
1211                    SortMode::DirectoriesFirst => a_leaf_file.cmp(&b_leaf_file),
1212                    SortMode::FilesFirst => b_leaf_file.cmp(&a_leaf_file),
1213                    SortMode::Mixed => Ordering::Equal,
1214                };
1215
1216                if !file_dir_ordering.is_eq() {
1217                    return file_dir_ordering;
1218                }
1219
1220                let (a_stem, a_ext) = a_leaf_file
1221                    .then(|| stem_and_extension(component_a))
1222                    .unwrap_or_default();
1223                let (b_stem, b_ext) = b_leaf_file
1224                    .then(|| stem_and_extension(component_b))
1225                    .unwrap_or_default();
1226                let a_key = if a_leaf_file {
1227                    a_stem
1228                } else {
1229                    Some(component_a)
1230                };
1231                let b_key = if b_leaf_file {
1232                    b_stem
1233                } else {
1234                    Some(component_b)
1235                };
1236
1237                let ordering = match (a_key, b_key) {
1238                    (Some(a), Some(b)) => {
1239                        let name_cmp = case_group_key(a, order)
1240                            .cmp(&case_group_key(b, order))
1241                            .then_with(|| match mode {
1242                                SortMode::DirectoriesFirst => compare_strings(a, b, order),
1243                                _ => compare_strings_no_tiebreak(a, b, order),
1244                            });
1245
1246                        let name_cmp = if mode == SortMode::Mixed {
1247                            name_cmp.then_with(|| match (a_leaf_file, b_leaf_file) {
1248                                (true, false) if a.eq_ignore_ascii_case(b) => Ordering::Greater,
1249                                (false, true) if a.eq_ignore_ascii_case(b) => Ordering::Less,
1250                                _ => Ordering::Equal,
1251                            })
1252                        } else {
1253                            name_cmp
1254                        };
1255
1256                        name_cmp.then_with(|| {
1257                            if a_leaf_file && b_leaf_file {
1258                                match order {
1259                                    SortOrder::Unicode => {
1260                                        a_ext.unwrap_or_default().cmp(b_ext.unwrap_or_default())
1261                                    }
1262                                    _ => {
1263                                        let a_ext_str = a_ext.unwrap_or_default().to_lowercase();
1264                                        let b_ext_str = b_ext.unwrap_or_default().to_lowercase();
1265                                        a_ext_str.cmp(&b_ext_str)
1266                                    }
1267                                }
1268                            } else {
1269                                Ordering::Equal
1270                            }
1271                        })
1272                    }
1273                    (Some(_), None) => Ordering::Greater,
1274                    (None, Some(_)) => Ordering::Less,
1275                    (None, None) => Ordering::Equal,
1276                };
1277
1278                if !ordering.is_eq() {
1279                    return ordering;
1280                }
1281            }
1282            (Some(_), None) => return Ordering::Greater,
1283            (None, Some(_)) => return Ordering::Less,
1284            (None, None) => {
1285                if needs_final_tiebreak {
1286                    return compare_strings(path_a.as_unix_str(), path_b.as_unix_str(), order);
1287                }
1288                return Ordering::Equal;
1289            }
1290        }
1291    }
1292}
1293
1294pub fn compare_paths(
1295    (path_a, a_is_file): (&Path, bool),
1296    (path_b, b_is_file): (&Path, bool),
1297) -> Ordering {
1298    let mut components_a = path_a.components().peekable();
1299    let mut components_b = path_b.components().peekable();
1300
1301    loop {
1302        match (components_a.next(), components_b.next()) {
1303            (Some(component_a), Some(component_b)) => {
1304                let a_is_file = components_a.peek().is_none() && a_is_file;
1305                let b_is_file = components_b.peek().is_none() && b_is_file;
1306
1307                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
1308                    let path_a = Path::new(component_a.as_os_str());
1309                    let path_string_a = if a_is_file {
1310                        path_a.file_stem()
1311                    } else {
1312                        path_a.file_name()
1313                    }
1314                    .map(|s| s.to_string_lossy());
1315
1316                    let path_b = Path::new(component_b.as_os_str());
1317                    let path_string_b = if b_is_file {
1318                        path_b.file_stem()
1319                    } else {
1320                        path_b.file_name()
1321                    }
1322                    .map(|s| s.to_string_lossy());
1323
1324                    let compare_components = match (path_string_a, path_string_b) {
1325                        (Some(a), Some(b)) => natural_sort(&a, &b),
1326                        (Some(_), None) => Ordering::Greater,
1327                        (None, Some(_)) => Ordering::Less,
1328                        (None, None) => Ordering::Equal,
1329                    };
1330
1331                    compare_components.then_with(|| {
1332                        if a_is_file && b_is_file {
1333                            let ext_a = path_a.extension().unwrap_or_default();
1334                            let ext_b = path_b.extension().unwrap_or_default();
1335                            ext_a.cmp(ext_b)
1336                        } else {
1337                            Ordering::Equal
1338                        }
1339                    })
1340                });
1341
1342                if !ordering.is_eq() {
1343                    return ordering;
1344                }
1345            }
1346            (Some(_), None) => break Ordering::Greater,
1347            (None, Some(_)) => break Ordering::Less,
1348            (None, None) => break Ordering::Equal,
1349        }
1350    }
1351}
1352
1353#[derive(Debug, Clone, PartialEq, Eq)]
1354pub struct WslPath {
1355    pub distro: String,
1356
1357    // the reason this is an OsString and not any of the path types is that it needs to
1358    // represent a unix path (with '/' separators) on windows. `from_path` does this by
1359    // manually constructing it from the path components of a given windows path.
1360    pub path: std::ffi::OsString,
1361}
1362
1363impl WslPath {
1364    pub fn from_path<P: AsRef<Path>>(path: P) -> Option<WslPath> {
1365        if cfg!(not(target_os = "windows")) {
1366            return None;
1367        }
1368        use std::{
1369            ffi::OsString,
1370            path::{Component, Prefix},
1371        };
1372
1373        let mut components = path.as_ref().components();
1374        let Some(Component::Prefix(prefix)) = components.next() else {
1375            return None;
1376        };
1377        let (server, distro) = match prefix.kind() {
1378            Prefix::UNC(server, distro) => (server, distro),
1379            Prefix::VerbatimUNC(server, distro) => (server, distro),
1380            _ => return None,
1381        };
1382        let Some(Component::RootDir) = components.next() else {
1383            return None;
1384        };
1385
1386        let server_str = server.to_string_lossy();
1387        if server_str == "wsl.localhost" || server_str == "wsl$" {
1388            let mut result = OsString::from("");
1389            for c in components {
1390                use Component::*;
1391                match c {
1392                    Prefix(p) => unreachable!("got {p:?}, but already stripped prefix"),
1393                    RootDir => unreachable!("got root dir, but already stripped root"),
1394                    CurDir => continue,
1395                    ParentDir => result.push("/.."),
1396                    Normal(s) => {
1397                        result.push("/");
1398                        result.push(s);
1399                    }
1400                }
1401            }
1402            if result.is_empty() {
1403                result.push("/");
1404            }
1405            Some(WslPath {
1406                distro: distro.to_string_lossy().to_string(),
1407                path: result,
1408            })
1409        } else {
1410            None
1411        }
1412    }
1413}
1414
1415pub trait UrlExt {
1416    /// A version of `url::Url::to_file_path` that does platform handling based on the provided `PathStyle` instead of the host platform.
1417    ///
1418    /// Prefer using this over `url::Url::to_file_path` when you need to handle paths in a cross-platform way as is the case for remoting interactions.
1419    fn to_file_path_ext(&self, path_style: PathStyle) -> Result<PathBuf, ()>;
1420}
1421
1422impl UrlExt for url::Url {
1423    // Copied from `url::Url::to_file_path`, but the `cfg` handling is replaced with runtime branching on `PathStyle`
1424    fn to_file_path_ext(&self, source_path_style: PathStyle) -> Result<PathBuf, ()> {
1425        if let Some(segments) = self.path_segments() {
1426            let host = match self.host() {
1427                None | Some(url::Host::Domain("localhost")) => None,
1428                Some(_) if source_path_style.is_windows() && self.scheme() == "file" => {
1429                    self.host_str()
1430                }
1431                _ => return Err(()),
1432            };
1433
1434            let str_len = self.as_str().len();
1435            let estimated_capacity = if source_path_style.is_windows() {
1436                // remove scheme: - has possible \\ for hostname
1437                str_len.saturating_sub(self.scheme().len() + 1)
1438            } else {
1439                // remove scheme://
1440                str_len.saturating_sub(self.scheme().len() + 3)
1441            };
1442            return match source_path_style {
1443                PathStyle::Posix => {
1444                    file_url_segments_to_pathbuf_posix(estimated_capacity, host, segments)
1445                }
1446                PathStyle::Windows => {
1447                    file_url_segments_to_pathbuf_windows(estimated_capacity, host, segments)
1448                }
1449            };
1450        }
1451
1452        fn file_url_segments_to_pathbuf_posix(
1453            estimated_capacity: usize,
1454            host: Option<&str>,
1455            segments: std::str::Split<'_, char>,
1456        ) -> Result<PathBuf, ()> {
1457            use percent_encoding::percent_decode;
1458
1459            if host.is_some() {
1460                return Err(());
1461            }
1462
1463            let mut bytes = Vec::new();
1464            bytes.try_reserve(estimated_capacity).map_err(|_| ())?;
1465
1466            for segment in segments {
1467                bytes.push(b'/');
1468                bytes.extend(percent_decode(segment.as_bytes()));
1469            }
1470
1471            // A windows drive letter must end with a slash.
1472            if bytes.len() > 2
1473                && bytes[bytes.len() - 2].is_ascii_alphabetic()
1474                && matches!(bytes[bytes.len() - 1], b':' | b'|')
1475            {
1476                bytes.push(b'/');
1477            }
1478
1479            let path = String::from_utf8(bytes).map_err(|_| ())?;
1480            debug_assert!(
1481                PathStyle::Posix.is_absolute(&path),
1482                "to_file_path() failed to produce an absolute Path"
1483            );
1484
1485            Ok(PathBuf::from(path))
1486        }
1487
1488        fn file_url_segments_to_pathbuf_windows(
1489            estimated_capacity: usize,
1490            host: Option<&str>,
1491            mut segments: std::str::Split<'_, char>,
1492        ) -> Result<PathBuf, ()> {
1493            use percent_encoding::percent_decode_str;
1494            let mut string = String::new();
1495            string.try_reserve(estimated_capacity).map_err(|_| ())?;
1496            if let Some(host) = host {
1497                string.push_str(r"\\");
1498                string.push_str(host);
1499            } else {
1500                let first = segments.next().ok_or(())?;
1501
1502                match first.len() {
1503                    2 => {
1504                        if !first.starts_with(|c| char::is_ascii_alphabetic(&c))
1505                            || first.as_bytes()[1] != b':'
1506                        {
1507                            return Err(());
1508                        }
1509
1510                        string.push_str(first);
1511                    }
1512
1513                    4 => {
1514                        if !first.starts_with(|c| char::is_ascii_alphabetic(&c)) {
1515                            return Err(());
1516                        }
1517                        let bytes = first.as_bytes();
1518                        if bytes[1] != b'%'
1519                            || bytes[2] != b'3'
1520                            || (bytes[3] != b'a' && bytes[3] != b'A')
1521                        {
1522                            return Err(());
1523                        }
1524
1525                        string.push_str(&first[0..1]);
1526                        string.push(':');
1527                    }
1528
1529                    _ => return Err(()),
1530                }
1531            };
1532
1533            for segment in segments {
1534                string.push('\\');
1535
1536                // Currently non-unicode windows paths cannot be represented
1537                match percent_decode_str(segment).decode_utf8() {
1538                    Ok(s) => string.push_str(&s),
1539                    Err(..) => return Err(()),
1540                }
1541            }
1542            // ensure our estimated capacity was good
1543            if cfg!(test) {
1544                debug_assert!(
1545                    string.len() <= estimated_capacity,
1546                    "len: {}, capacity: {}",
1547                    string.len(),
1548                    estimated_capacity
1549                );
1550            }
1551            debug_assert!(
1552                PathStyle::Windows.is_absolute(&string),
1553                "to_file_path() failed to produce an absolute Path"
1554            );
1555            let path = PathBuf::from(string);
1556            Ok(path)
1557        }
1558        Err(())
1559    }
1560}
1561
1562#[cfg(test)]
1563mod tests {
1564    use crate::rel_path::rel_path;
1565
1566    use super::*;
1567
1568    fn rel_path_entry(path: &'static str, is_file: bool) -> (&'static RelPath, bool) {
1569        (RelPath::unix(path).unwrap(), is_file)
1570    }
1571
1572    fn sorted_rel_paths(
1573        mut paths: Vec<(&'static RelPath, bool)>,
1574        mode: SortMode,
1575        order: SortOrder,
1576    ) -> Vec<(&'static RelPath, bool)> {
1577        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, mode, order));
1578        paths
1579    }
1580
1581    #[test]
1582    fn compare_paths_with_dots() {
1583        let mut paths = vec![
1584            (Path::new("test_dirs"), false),
1585            (Path::new("test_dirs/1.46"), false),
1586            (Path::new("test_dirs/1.46/bar_1"), true),
1587            (Path::new("test_dirs/1.46/bar_2"), true),
1588            (Path::new("test_dirs/1.45"), false),
1589            (Path::new("test_dirs/1.45/foo_2"), true),
1590            (Path::new("test_dirs/1.45/foo_1"), true),
1591        ];
1592        paths.sort_by(|&a, &b| compare_paths(a, b));
1593        assert_eq!(
1594            paths,
1595            vec![
1596                (Path::new("test_dirs"), false),
1597                (Path::new("test_dirs/1.45"), false),
1598                (Path::new("test_dirs/1.45/foo_1"), true),
1599                (Path::new("test_dirs/1.45/foo_2"), true),
1600                (Path::new("test_dirs/1.46"), false),
1601                (Path::new("test_dirs/1.46/bar_1"), true),
1602                (Path::new("test_dirs/1.46/bar_2"), true),
1603            ]
1604        );
1605        let mut paths = vec![
1606            (Path::new("root1/one.txt"), true),
1607            (Path::new("root1/one.two.txt"), true),
1608        ];
1609        paths.sort_by(|&a, &b| compare_paths(a, b));
1610        assert_eq!(
1611            paths,
1612            vec![
1613                (Path::new("root1/one.txt"), true),
1614                (Path::new("root1/one.two.txt"), true),
1615            ]
1616        );
1617    }
1618
1619    #[test]
1620    fn compare_paths_with_same_name_different_extensions() {
1621        let mut paths = vec![
1622            (Path::new("test_dirs/file.rs"), true),
1623            (Path::new("test_dirs/file.txt"), true),
1624            (Path::new("test_dirs/file.md"), true),
1625            (Path::new("test_dirs/file"), true),
1626            (Path::new("test_dirs/file.a"), true),
1627        ];
1628        paths.sort_by(|&a, &b| compare_paths(a, b));
1629        assert_eq!(
1630            paths,
1631            vec![
1632                (Path::new("test_dirs/file"), true),
1633                (Path::new("test_dirs/file.a"), true),
1634                (Path::new("test_dirs/file.md"), true),
1635                (Path::new("test_dirs/file.rs"), true),
1636                (Path::new("test_dirs/file.txt"), true),
1637            ]
1638        );
1639    }
1640
1641    #[test]
1642    fn compare_paths_case_semi_sensitive() {
1643        let mut paths = vec![
1644            (Path::new("test_DIRS"), false),
1645            (Path::new("test_DIRS/foo_1"), true),
1646            (Path::new("test_DIRS/foo_2"), true),
1647            (Path::new("test_DIRS/bar"), true),
1648            (Path::new("test_DIRS/BAR"), true),
1649            (Path::new("test_dirs"), false),
1650            (Path::new("test_dirs/foo_1"), true),
1651            (Path::new("test_dirs/foo_2"), true),
1652            (Path::new("test_dirs/bar"), true),
1653            (Path::new("test_dirs/BAR"), true),
1654        ];
1655        paths.sort_by(|&a, &b| compare_paths(a, b));
1656        assert_eq!(
1657            paths,
1658            vec![
1659                (Path::new("test_dirs"), false),
1660                (Path::new("test_dirs/bar"), true),
1661                (Path::new("test_dirs/BAR"), true),
1662                (Path::new("test_dirs/foo_1"), true),
1663                (Path::new("test_dirs/foo_2"), true),
1664                (Path::new("test_DIRS"), false),
1665                (Path::new("test_DIRS/bar"), true),
1666                (Path::new("test_DIRS/BAR"), true),
1667                (Path::new("test_DIRS/foo_1"), true),
1668                (Path::new("test_DIRS/foo_2"), true),
1669            ]
1670        );
1671    }
1672
1673    #[test]
1674    fn compare_paths_mixed_case_numeric_ordering() {
1675        let mut entries = [
1676            (Path::new(".config"), false),
1677            (Path::new("Dir1"), false),
1678            (Path::new("dir01"), false),
1679            (Path::new("dir2"), false),
1680            (Path::new("Dir02"), false),
1681            (Path::new("dir10"), false),
1682            (Path::new("Dir10"), false),
1683        ];
1684
1685        entries.sort_by(|&a, &b| compare_paths(a, b));
1686
1687        let ordered: Vec<&str> = entries
1688            .iter()
1689            .map(|(path, _)| path.to_str().unwrap())
1690            .collect();
1691
1692        assert_eq!(
1693            ordered,
1694            vec![
1695                ".config", "Dir1", "dir01", "dir2", "Dir02", "dir10", "Dir10"
1696            ]
1697        );
1698    }
1699
1700    #[test]
1701    fn compare_rel_paths_mixed_case_insensitive() {
1702        // Test that mixed mode is case-insensitive
1703        let mut paths = vec![
1704            (RelPath::unix("zebra.txt").unwrap(), true),
1705            (RelPath::unix("Apple").unwrap(), false),
1706            (RelPath::unix("banana.rs").unwrap(), true),
1707            (RelPath::unix("Carrot").unwrap(), false),
1708            (RelPath::unix("aardvark.txt").unwrap(), true),
1709        ];
1710        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1711        // Case-insensitive: aardvark < Apple < banana < Carrot < zebra
1712        assert_eq!(
1713            paths,
1714            vec![
1715                (RelPath::unix("aardvark.txt").unwrap(), true),
1716                (RelPath::unix("Apple").unwrap(), false),
1717                (RelPath::unix("banana.rs").unwrap(), true),
1718                (RelPath::unix("Carrot").unwrap(), false),
1719                (RelPath::unix("zebra.txt").unwrap(), true),
1720            ]
1721        );
1722    }
1723
1724    #[test]
1725    fn compare_rel_paths_files_first_basic() {
1726        // Test that files come before directories
1727        let mut paths = vec![
1728            (RelPath::unix("zebra.txt").unwrap(), true),
1729            (RelPath::unix("Apple").unwrap(), false),
1730            (RelPath::unix("banana.rs").unwrap(), true),
1731            (RelPath::unix("Carrot").unwrap(), false),
1732            (RelPath::unix("aardvark.txt").unwrap(), true),
1733        ];
1734        paths
1735            .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1736        // Files first (case-insensitive), then directories (case-insensitive)
1737        assert_eq!(
1738            paths,
1739            vec![
1740                (RelPath::unix("aardvark.txt").unwrap(), true),
1741                (RelPath::unix("banana.rs").unwrap(), true),
1742                (RelPath::unix("zebra.txt").unwrap(), true),
1743                (RelPath::unix("Apple").unwrap(), false),
1744                (RelPath::unix("Carrot").unwrap(), false),
1745            ]
1746        );
1747    }
1748
1749    #[test]
1750    fn compare_rel_paths_files_first_case_insensitive() {
1751        // Test case-insensitive sorting within files and directories
1752        let mut paths = vec![
1753            (RelPath::unix("Zebra.txt").unwrap(), true),
1754            (RelPath::unix("apple").unwrap(), false),
1755            (RelPath::unix("Banana.rs").unwrap(), true),
1756            (RelPath::unix("carrot").unwrap(), false),
1757            (RelPath::unix("Aardvark.txt").unwrap(), true),
1758        ];
1759        paths
1760            .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1761        assert_eq!(
1762            paths,
1763            vec![
1764                (RelPath::unix("Aardvark.txt").unwrap(), true),
1765                (RelPath::unix("Banana.rs").unwrap(), true),
1766                (RelPath::unix("Zebra.txt").unwrap(), true),
1767                (RelPath::unix("apple").unwrap(), false),
1768                (RelPath::unix("carrot").unwrap(), false),
1769            ]
1770        );
1771    }
1772
1773    #[test]
1774    fn compare_rel_paths_files_first_numeric() {
1775        // Test natural number sorting with files first
1776        let mut paths = vec![
1777            (RelPath::unix("file10.txt").unwrap(), true),
1778            (RelPath::unix("dir2").unwrap(), false),
1779            (RelPath::unix("file2.txt").unwrap(), true),
1780            (RelPath::unix("dir10").unwrap(), false),
1781            (RelPath::unix("file1.txt").unwrap(), true),
1782        ];
1783        paths
1784            .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1785        assert_eq!(
1786            paths,
1787            vec![
1788                (RelPath::unix("file1.txt").unwrap(), true),
1789                (RelPath::unix("file2.txt").unwrap(), true),
1790                (RelPath::unix("file10.txt").unwrap(), true),
1791                (RelPath::unix("dir2").unwrap(), false),
1792                (RelPath::unix("dir10").unwrap(), false),
1793            ]
1794        );
1795    }
1796
1797    #[test]
1798    fn compare_rel_paths_mixed_case() {
1799        // Test case-insensitive sorting with varied capitalization
1800        let mut paths = vec![
1801            (RelPath::unix("README.md").unwrap(), true),
1802            (RelPath::unix("readme.txt").unwrap(), true),
1803            (RelPath::unix("ReadMe.rs").unwrap(), true),
1804        ];
1805        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1806        // All "readme" variants should group together, sorted by extension
1807        assert_eq!(
1808            paths,
1809            vec![
1810                (RelPath::unix("README.md").unwrap(), true),
1811                (RelPath::unix("ReadMe.rs").unwrap(), true),
1812                (RelPath::unix("readme.txt").unwrap(), true),
1813            ]
1814        );
1815    }
1816
1817    #[test]
1818    fn compare_rel_paths_mixed_files_and_dirs() {
1819        // Verify directories and files are still mixed
1820        let mut paths = vec![
1821            (RelPath::unix("file2.txt").unwrap(), true),
1822            (RelPath::unix("Dir1").unwrap(), false),
1823            (RelPath::unix("file1.txt").unwrap(), true),
1824            (RelPath::unix("dir2").unwrap(), false),
1825        ];
1826        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1827        // Case-insensitive: dir1, dir2, file1, file2 (all mixed)
1828        assert_eq!(
1829            paths,
1830            vec![
1831                (RelPath::unix("Dir1").unwrap(), false),
1832                (RelPath::unix("dir2").unwrap(), false),
1833                (RelPath::unix("file1.txt").unwrap(), true),
1834                (RelPath::unix("file2.txt").unwrap(), true),
1835            ]
1836        );
1837    }
1838
1839    #[test]
1840    fn compare_rel_paths_mixed_same_name_different_case_file_and_dir() {
1841        let mut paths = vec![
1842            (RelPath::unix("Hello.txt").unwrap(), true),
1843            (RelPath::unix("hello").unwrap(), false),
1844        ];
1845        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1846        assert_eq!(
1847            paths,
1848            vec![
1849                (RelPath::unix("hello").unwrap(), false),
1850                (RelPath::unix("Hello.txt").unwrap(), true),
1851            ]
1852        );
1853
1854        let mut paths = vec![
1855            (RelPath::unix("hello").unwrap(), false),
1856            (RelPath::unix("Hello.txt").unwrap(), true),
1857        ];
1858        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1859        assert_eq!(
1860            paths,
1861            vec![
1862                (RelPath::unix("hello").unwrap(), false),
1863                (RelPath::unix("Hello.txt").unwrap(), true),
1864            ]
1865        );
1866    }
1867
1868    #[test]
1869    fn compare_rel_paths_mixed_with_nested_paths() {
1870        // Test that nested paths still work correctly
1871        let mut paths = vec![
1872            (RelPath::unix("src/main.rs").unwrap(), true),
1873            (RelPath::unix("Cargo.toml").unwrap(), true),
1874            (RelPath::unix("src").unwrap(), false),
1875            (RelPath::unix("target").unwrap(), false),
1876        ];
1877        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1878        assert_eq!(
1879            paths,
1880            vec![
1881                (RelPath::unix("Cargo.toml").unwrap(), true),
1882                (RelPath::unix("src").unwrap(), false),
1883                (RelPath::unix("src/main.rs").unwrap(), true),
1884                (RelPath::unix("target").unwrap(), false),
1885            ]
1886        );
1887    }
1888
1889    #[test]
1890    fn compare_rel_paths_files_first_with_nested() {
1891        // Files come before directories, even with nested paths
1892        let mut paths = vec![
1893            (RelPath::unix("src/lib.rs").unwrap(), true),
1894            (RelPath::unix("README.md").unwrap(), true),
1895            (RelPath::unix("src").unwrap(), false),
1896            (RelPath::unix("tests").unwrap(), false),
1897        ];
1898        paths
1899            .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1900        assert_eq!(
1901            paths,
1902            vec![
1903                (RelPath::unix("README.md").unwrap(), true),
1904                (RelPath::unix("src").unwrap(), false),
1905                (RelPath::unix("src/lib.rs").unwrap(), true),
1906                (RelPath::unix("tests").unwrap(), false),
1907            ]
1908        );
1909    }
1910
1911    #[test]
1912    fn compare_rel_paths_mixed_dotfiles() {
1913        // Test that dotfiles are handled correctly in mixed mode
1914        let mut paths = vec![
1915            (RelPath::unix(".gitignore").unwrap(), true),
1916            (RelPath::unix("README.md").unwrap(), true),
1917            (RelPath::unix(".github").unwrap(), false),
1918            (RelPath::unix("src").unwrap(), false),
1919        ];
1920        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1921        assert_eq!(
1922            paths,
1923            vec![
1924                (RelPath::unix(".github").unwrap(), false),
1925                (RelPath::unix(".gitignore").unwrap(), true),
1926                (RelPath::unix("README.md").unwrap(), true),
1927                (RelPath::unix("src").unwrap(), false),
1928            ]
1929        );
1930    }
1931
1932    #[test]
1933    fn compare_rel_paths_files_first_dotfiles() {
1934        // Test that dotfiles come first when they're files
1935        let mut paths = vec![
1936            (RelPath::unix(".gitignore").unwrap(), true),
1937            (RelPath::unix("README.md").unwrap(), true),
1938            (RelPath::unix(".github").unwrap(), false),
1939            (RelPath::unix("src").unwrap(), false),
1940        ];
1941        paths
1942            .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1943        assert_eq!(
1944            paths,
1945            vec![
1946                (RelPath::unix(".gitignore").unwrap(), true),
1947                (RelPath::unix("README.md").unwrap(), true),
1948                (RelPath::unix(".github").unwrap(), false),
1949                (RelPath::unix("src").unwrap(), false),
1950            ]
1951        );
1952    }
1953
1954    #[test]
1955    fn compare_rel_paths_mixed_same_stem_different_extension() {
1956        // Files with same stem but different extensions should sort by extension
1957        let mut paths = vec![
1958            (RelPath::unix("file.rs").unwrap(), true),
1959            (RelPath::unix("file.md").unwrap(), true),
1960            (RelPath::unix("file.txt").unwrap(), true),
1961        ];
1962        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1963        assert_eq!(
1964            paths,
1965            vec![
1966                (RelPath::unix("file.md").unwrap(), true),
1967                (RelPath::unix("file.rs").unwrap(), true),
1968                (RelPath::unix("file.txt").unwrap(), true),
1969            ]
1970        );
1971    }
1972
1973    #[test]
1974    fn compare_rel_paths_files_first_same_stem() {
1975        // Same stem files should still sort by extension with files_first
1976        let mut paths = vec![
1977            (RelPath::unix("main.rs").unwrap(), true),
1978            (RelPath::unix("main.c").unwrap(), true),
1979            (RelPath::unix("main").unwrap(), false),
1980        ];
1981        paths
1982            .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1983        assert_eq!(
1984            paths,
1985            vec![
1986                (RelPath::unix("main.c").unwrap(), true),
1987                (RelPath::unix("main.rs").unwrap(), true),
1988                (RelPath::unix("main").unwrap(), false),
1989            ]
1990        );
1991    }
1992
1993    #[test]
1994    fn compare_rel_paths_mixed_deep_nesting() {
1995        // Test sorting with deeply nested paths
1996        let mut paths = vec![
1997            (RelPath::unix("a/b/c.txt").unwrap(), true),
1998            (RelPath::unix("A/B.txt").unwrap(), true),
1999            (RelPath::unix("a.txt").unwrap(), true),
2000            (RelPath::unix("A.txt").unwrap(), true),
2001        ];
2002        paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
2003        assert_eq!(
2004            paths,
2005            vec![
2006                (RelPath::unix("a/b/c.txt").unwrap(), true),
2007                (RelPath::unix("A/B.txt").unwrap(), true),
2008                (RelPath::unix("a.txt").unwrap(), true),
2009                (RelPath::unix("A.txt").unwrap(), true),
2010            ]
2011        );
2012    }
2013
2014    #[test]
2015    fn compare_rel_paths_upper() {
2016        let directories_only_paths = vec![
2017            rel_path_entry("mixedCase", false),
2018            rel_path_entry("Zebra", false),
2019            rel_path_entry("banana", false),
2020            rel_path_entry("ALLCAPS", false),
2021            rel_path_entry("Apple", false),
2022            rel_path_entry("dog", false),
2023            rel_path_entry(".hidden", false),
2024            rel_path_entry("Carrot", false),
2025        ];
2026        assert_eq!(
2027            sorted_rel_paths(
2028                directories_only_paths,
2029                SortMode::DirectoriesFirst,
2030                SortOrder::Upper,
2031            ),
2032            vec![
2033                rel_path_entry(".hidden", false),
2034                rel_path_entry("ALLCAPS", false),
2035                rel_path_entry("Apple", false),
2036                rel_path_entry("Carrot", false),
2037                rel_path_entry("Zebra", false),
2038                rel_path_entry("banana", false),
2039                rel_path_entry("dog", false),
2040                rel_path_entry("mixedCase", false),
2041            ]
2042        );
2043
2044        let file_and_directory_paths = vec![
2045            rel_path_entry("banana", false),
2046            rel_path_entry("Apple.txt", true),
2047            rel_path_entry("dog.md", true),
2048            rel_path_entry("ALLCAPS", false),
2049            rel_path_entry("file1.txt", true),
2050            rel_path_entry("File2.txt", true),
2051            rel_path_entry(".hidden", false),
2052        ];
2053        assert_eq!(
2054            sorted_rel_paths(
2055                file_and_directory_paths.clone(),
2056                SortMode::DirectoriesFirst,
2057                SortOrder::Upper,
2058            ),
2059            vec![
2060                rel_path_entry(".hidden", false),
2061                rel_path_entry("ALLCAPS", false),
2062                rel_path_entry("banana", false),
2063                rel_path_entry("Apple.txt", true),
2064                rel_path_entry("File2.txt", true),
2065                rel_path_entry("dog.md", true),
2066                rel_path_entry("file1.txt", true),
2067            ]
2068        );
2069        assert_eq!(
2070            sorted_rel_paths(
2071                file_and_directory_paths.clone(),
2072                SortMode::Mixed,
2073                SortOrder::Upper,
2074            ),
2075            vec![
2076                rel_path_entry(".hidden", false),
2077                rel_path_entry("ALLCAPS", false),
2078                rel_path_entry("Apple.txt", true),
2079                rel_path_entry("File2.txt", true),
2080                rel_path_entry("banana", false),
2081                rel_path_entry("dog.md", true),
2082                rel_path_entry("file1.txt", true),
2083            ]
2084        );
2085        assert_eq!(
2086            sorted_rel_paths(
2087                file_and_directory_paths,
2088                SortMode::FilesFirst,
2089                SortOrder::Upper,
2090            ),
2091            vec![
2092                rel_path_entry("Apple.txt", true),
2093                rel_path_entry("File2.txt", true),
2094                rel_path_entry("dog.md", true),
2095                rel_path_entry("file1.txt", true),
2096                rel_path_entry(".hidden", false),
2097                rel_path_entry("ALLCAPS", false),
2098                rel_path_entry("banana", false),
2099            ]
2100        );
2101
2102        let natural_sort_paths = vec![
2103            rel_path_entry("file10.txt", true),
2104            rel_path_entry("file1.txt", true),
2105            rel_path_entry("file20.txt", true),
2106            rel_path_entry("file2.txt", true),
2107        ];
2108        assert_eq!(
2109            sorted_rel_paths(natural_sort_paths, SortMode::Mixed, SortOrder::Upper,),
2110            vec![
2111                rel_path_entry("file1.txt", true),
2112                rel_path_entry("file2.txt", true),
2113                rel_path_entry("file10.txt", true),
2114                rel_path_entry("file20.txt", true),
2115            ]
2116        );
2117
2118        let accented_paths = vec![
2119            rel_path_entry("\u{00C9}something.txt", true),
2120            rel_path_entry("zebra.txt", true),
2121            rel_path_entry("Apple.txt", true),
2122        ];
2123        assert_eq!(
2124            sorted_rel_paths(accented_paths, SortMode::Mixed, SortOrder::Upper),
2125            vec![
2126                rel_path_entry("Apple.txt", true),
2127                rel_path_entry("\u{00C9}something.txt", true),
2128                rel_path_entry("zebra.txt", true),
2129            ]
2130        );
2131    }
2132
2133    #[test]
2134    fn compare_rel_paths_lower() {
2135        let directories_only_paths = vec![
2136            rel_path_entry("mixedCase", false),
2137            rel_path_entry("Zebra", false),
2138            rel_path_entry("banana", false),
2139            rel_path_entry("ALLCAPS", false),
2140            rel_path_entry("Apple", false),
2141            rel_path_entry("dog", false),
2142            rel_path_entry(".hidden", false),
2143            rel_path_entry("Carrot", false),
2144        ];
2145        assert_eq!(
2146            sorted_rel_paths(
2147                directories_only_paths,
2148                SortMode::DirectoriesFirst,
2149                SortOrder::Lower,
2150            ),
2151            vec![
2152                rel_path_entry(".hidden", false),
2153                rel_path_entry("banana", false),
2154                rel_path_entry("dog", false),
2155                rel_path_entry("mixedCase", false),
2156                rel_path_entry("ALLCAPS", false),
2157                rel_path_entry("Apple", false),
2158                rel_path_entry("Carrot", false),
2159                rel_path_entry("Zebra", false),
2160            ]
2161        );
2162
2163        let file_and_directory_paths = vec![
2164            rel_path_entry("banana", false),
2165            rel_path_entry("Apple.txt", true),
2166            rel_path_entry("dog.md", true),
2167            rel_path_entry("ALLCAPS", false),
2168            rel_path_entry("file1.txt", true),
2169            rel_path_entry("File2.txt", true),
2170            rel_path_entry(".hidden", false),
2171        ];
2172        assert_eq!(
2173            sorted_rel_paths(
2174                file_and_directory_paths.clone(),
2175                SortMode::DirectoriesFirst,
2176                SortOrder::Lower,
2177            ),
2178            vec![
2179                rel_path_entry(".hidden", false),
2180                rel_path_entry("banana", false),
2181                rel_path_entry("ALLCAPS", false),
2182                rel_path_entry("dog.md", true),
2183                rel_path_entry("file1.txt", true),
2184                rel_path_entry("Apple.txt", true),
2185                rel_path_entry("File2.txt", true),
2186            ]
2187        );
2188        assert_eq!(
2189            sorted_rel_paths(
2190                file_and_directory_paths.clone(),
2191                SortMode::Mixed,
2192                SortOrder::Lower,
2193            ),
2194            vec![
2195                rel_path_entry(".hidden", false),
2196                rel_path_entry("banana", false),
2197                rel_path_entry("dog.md", true),
2198                rel_path_entry("file1.txt", true),
2199                rel_path_entry("ALLCAPS", false),
2200                rel_path_entry("Apple.txt", true),
2201                rel_path_entry("File2.txt", true),
2202            ]
2203        );
2204        assert_eq!(
2205            sorted_rel_paths(
2206                file_and_directory_paths,
2207                SortMode::FilesFirst,
2208                SortOrder::Lower,
2209            ),
2210            vec![
2211                rel_path_entry("dog.md", true),
2212                rel_path_entry("file1.txt", true),
2213                rel_path_entry("Apple.txt", true),
2214                rel_path_entry("File2.txt", true),
2215                rel_path_entry(".hidden", false),
2216                rel_path_entry("banana", false),
2217                rel_path_entry("ALLCAPS", false),
2218            ]
2219        );
2220    }
2221
2222    #[test]
2223    fn compare_rel_paths_unicode() {
2224        let directories_only_paths = vec![
2225            rel_path_entry("mixedCase", false),
2226            rel_path_entry("Zebra", false),
2227            rel_path_entry("banana", false),
2228            rel_path_entry("ALLCAPS", false),
2229            rel_path_entry("Apple", false),
2230            rel_path_entry("dog", false),
2231            rel_path_entry(".hidden", false),
2232            rel_path_entry("Carrot", false),
2233        ];
2234        assert_eq!(
2235            sorted_rel_paths(
2236                directories_only_paths,
2237                SortMode::DirectoriesFirst,
2238                SortOrder::Unicode,
2239            ),
2240            vec![
2241                rel_path_entry(".hidden", false),
2242                rel_path_entry("ALLCAPS", false),
2243                rel_path_entry("Apple", false),
2244                rel_path_entry("Carrot", false),
2245                rel_path_entry("Zebra", false),
2246                rel_path_entry("banana", false),
2247                rel_path_entry("dog", false),
2248                rel_path_entry("mixedCase", false),
2249            ]
2250        );
2251
2252        let file_and_directory_paths = vec![
2253            rel_path_entry("banana", false),
2254            rel_path_entry("Apple.txt", true),
2255            rel_path_entry("dog.md", true),
2256            rel_path_entry("ALLCAPS", false),
2257            rel_path_entry("file1.txt", true),
2258            rel_path_entry("File2.txt", true),
2259            rel_path_entry(".hidden", false),
2260        ];
2261        assert_eq!(
2262            sorted_rel_paths(
2263                file_and_directory_paths.clone(),
2264                SortMode::DirectoriesFirst,
2265                SortOrder::Unicode,
2266            ),
2267            vec![
2268                rel_path_entry(".hidden", false),
2269                rel_path_entry("ALLCAPS", false),
2270                rel_path_entry("banana", false),
2271                rel_path_entry("Apple.txt", true),
2272                rel_path_entry("File2.txt", true),
2273                rel_path_entry("dog.md", true),
2274                rel_path_entry("file1.txt", true),
2275            ]
2276        );
2277        assert_eq!(
2278            sorted_rel_paths(
2279                file_and_directory_paths.clone(),
2280                SortMode::Mixed,
2281                SortOrder::Unicode,
2282            ),
2283            vec![
2284                rel_path_entry(".hidden", false),
2285                rel_path_entry("ALLCAPS", false),
2286                rel_path_entry("Apple.txt", true),
2287                rel_path_entry("File2.txt", true),
2288                rel_path_entry("banana", false),
2289                rel_path_entry("dog.md", true),
2290                rel_path_entry("file1.txt", true),
2291            ]
2292        );
2293        assert_eq!(
2294            sorted_rel_paths(
2295                file_and_directory_paths,
2296                SortMode::FilesFirst,
2297                SortOrder::Unicode,
2298            ),
2299            vec![
2300                rel_path_entry("Apple.txt", true),
2301                rel_path_entry("File2.txt", true),
2302                rel_path_entry("dog.md", true),
2303                rel_path_entry("file1.txt", true),
2304                rel_path_entry(".hidden", false),
2305                rel_path_entry("ALLCAPS", false),
2306                rel_path_entry("banana", false),
2307            ]
2308        );
2309
2310        let numeric_paths = vec![
2311            rel_path_entry("file10.txt", true),
2312            rel_path_entry("file1.txt", true),
2313            rel_path_entry("file2.txt", true),
2314            rel_path_entry("file20.txt", true),
2315        ];
2316        assert_eq!(
2317            sorted_rel_paths(numeric_paths, SortMode::Mixed, SortOrder::Unicode,),
2318            vec![
2319                rel_path_entry("file1.txt", true),
2320                rel_path_entry("file10.txt", true),
2321                rel_path_entry("file2.txt", true),
2322                rel_path_entry("file20.txt", true),
2323            ]
2324        );
2325
2326        let accented_paths = vec![
2327            rel_path_entry("\u{00C9}something.txt", true),
2328            rel_path_entry("zebra.txt", true),
2329            rel_path_entry("Apple.txt", true),
2330        ];
2331        assert_eq!(
2332            sorted_rel_paths(accented_paths, SortMode::Mixed, SortOrder::Unicode),
2333            vec![
2334                rel_path_entry("Apple.txt", true),
2335                rel_path_entry("zebra.txt", true),
2336                rel_path_entry("\u{00C9}something.txt", true),
2337            ]
2338        );
2339    }
2340
2341    #[test]
2342    fn path_with_position_parse_posix_path() {
2343        // Test POSIX filename edge cases
2344        // Read more at https://en.wikipedia.org/wiki/Filename
2345        assert_eq!(
2346            PathWithPosition::parse_str("test_file"),
2347            PathWithPosition {
2348                path: PathBuf::from("test_file"),
2349                row: None,
2350                column: None
2351            }
2352        );
2353
2354        assert_eq!(
2355            PathWithPosition::parse_str("a:bc:.zip:1"),
2356            PathWithPosition {
2357                path: PathBuf::from("a:bc:.zip"),
2358                row: Some(1),
2359                column: None
2360            }
2361        );
2362
2363        assert_eq!(
2364            PathWithPosition::parse_str("one.second.zip:1"),
2365            PathWithPosition {
2366                path: PathBuf::from("one.second.zip"),
2367                row: Some(1),
2368                column: None
2369            }
2370        );
2371
2372        // Trim off trailing `:`s for otherwise valid input.
2373        assert_eq!(
2374            PathWithPosition::parse_str("test_file:10:1:"),
2375            PathWithPosition {
2376                path: PathBuf::from("test_file"),
2377                row: Some(10),
2378                column: Some(1)
2379            }
2380        );
2381
2382        assert_eq!(
2383            PathWithPosition::parse_str("test_file.rs:"),
2384            PathWithPosition {
2385                path: PathBuf::from("test_file.rs"),
2386                row: None,
2387                column: None
2388            }
2389        );
2390
2391        assert_eq!(
2392            PathWithPosition::parse_str("test_file.rs:1:"),
2393            PathWithPosition {
2394                path: PathBuf::from("test_file.rs"),
2395                row: Some(1),
2396                column: None
2397            }
2398        );
2399
2400        assert_eq!(
2401            PathWithPosition::parse_str("ab\ncd"),
2402            PathWithPosition {
2403                path: PathBuf::from("ab\ncd"),
2404                row: None,
2405                column: None
2406            }
2407        );
2408
2409        assert_eq!(
2410            PathWithPosition::parse_str("👋\nab"),
2411            PathWithPosition {
2412                path: PathBuf::from("👋\nab"),
2413                row: None,
2414                column: None
2415            }
2416        );
2417
2418        assert_eq!(
2419            PathWithPosition::parse_str("Types.hs:(617,9)-(670,28):"),
2420            PathWithPosition {
2421                path: PathBuf::from("Types.hs"),
2422                row: Some(617),
2423                column: Some(9),
2424            }
2425        );
2426
2427        assert_eq!(
2428            PathWithPosition::parse_str("main (1).log"),
2429            PathWithPosition {
2430                path: PathBuf::from("main (1).log"),
2431                row: None,
2432                column: None
2433            }
2434        );
2435    }
2436
2437    #[test]
2438    #[cfg(not(target_os = "windows"))]
2439    fn path_with_position_parse_posix_path_with_suffix() {
2440        assert_eq!(
2441            PathWithPosition::parse_str("foo/bar:34:in"),
2442            PathWithPosition {
2443                path: PathBuf::from("foo/bar"),
2444                row: Some(34),
2445                column: None,
2446            }
2447        );
2448        assert_eq!(
2449            PathWithPosition::parse_str("foo/bar.rs:1902:::15:"),
2450            PathWithPosition {
2451                path: PathBuf::from("foo/bar.rs:1902"),
2452                row: Some(15),
2453                column: None
2454            }
2455        );
2456
2457        assert_eq!(
2458            PathWithPosition::parse_str("app-editors:app-0.143.6:20240710-201212.log:34:"),
2459            PathWithPosition {
2460                path: PathBuf::from("app-editors:app-0.143.6:20240710-201212.log"),
2461                row: Some(34),
2462                column: None,
2463            }
2464        );
2465
2466        assert_eq!(
2467            PathWithPosition::parse_str("crates/file_finder/src/file_finder.rs:1902:13:"),
2468            PathWithPosition {
2469                path: PathBuf::from("crates/file_finder/src/file_finder.rs"),
2470                row: Some(1902),
2471                column: Some(13),
2472            }
2473        );
2474
2475        assert_eq!(
2476            PathWithPosition::parse_str("crate/utils/src/test:today.log:34"),
2477            PathWithPosition {
2478                path: PathBuf::from("crate/utils/src/test:today.log"),
2479                row: Some(34),
2480                column: None,
2481            }
2482        );
2483        assert_eq!(
2484            PathWithPosition::parse_str("/testing/out/src/file_finder.odin(7:15)"),
2485            PathWithPosition {
2486                path: PathBuf::from("/testing/out/src/file_finder.odin"),
2487                row: Some(7),
2488                column: Some(15),
2489            }
2490        );
2491    }
2492
2493    #[test]
2494    #[cfg(target_os = "windows")]
2495    fn path_with_position_parse_windows_path() {
2496        assert_eq!(
2497            PathWithPosition::parse_str("crates\\utils\\paths.rs"),
2498            PathWithPosition {
2499                path: PathBuf::from("crates\\utils\\paths.rs"),
2500                row: None,
2501                column: None
2502            }
2503        );
2504
2505        assert_eq!(
2506            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs"),
2507            PathWithPosition {
2508                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2509                row: None,
2510                column: None
2511            }
2512        );
2513
2514        assert_eq!(
2515            PathWithPosition::parse_str("C:\\Users\\someone\\main (1).log"),
2516            PathWithPosition {
2517                path: PathBuf::from("C:\\Users\\someone\\main (1).log"),
2518                row: None,
2519                column: None
2520            }
2521        );
2522    }
2523
2524    #[test]
2525    #[cfg(target_os = "windows")]
2526    fn path_with_position_parse_windows_path_with_suffix() {
2527        assert_eq!(
2528            PathWithPosition::parse_str("crates\\utils\\paths.rs:101"),
2529            PathWithPosition {
2530                path: PathBuf::from("crates\\utils\\paths.rs"),
2531                row: Some(101),
2532                column: None
2533            }
2534        );
2535
2536        assert_eq!(
2537            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1:20"),
2538            PathWithPosition {
2539                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2540                row: Some(1),
2541                column: Some(20)
2542            }
2543        );
2544
2545        assert_eq!(
2546            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13)"),
2547            PathWithPosition {
2548                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2549                row: Some(1902),
2550                column: Some(13)
2551            }
2552        );
2553
2554        // Trim off trailing `:`s for otherwise valid input.
2555        assert_eq!(
2556            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:"),
2557            PathWithPosition {
2558                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2559                row: Some(1902),
2560                column: Some(13)
2561            }
2562        );
2563
2564        assert_eq!(
2565            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:15:"),
2566            PathWithPosition {
2567                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
2568                row: Some(13),
2569                column: Some(15)
2570            }
2571        );
2572
2573        assert_eq!(
2574            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:::15:"),
2575            PathWithPosition {
2576                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
2577                row: Some(15),
2578                column: None
2579            }
2580        );
2581
2582        assert_eq!(
2583            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902,13):"),
2584            PathWithPosition {
2585                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2586                row: Some(1902),
2587                column: Some(13),
2588            }
2589        );
2590
2591        assert_eq!(
2592            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902):"),
2593            PathWithPosition {
2594                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2595                row: Some(1902),
2596                column: None,
2597            }
2598        );
2599
2600        assert_eq!(
2601            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs:1902:13:"),
2602            PathWithPosition {
2603                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2604                row: Some(1902),
2605                column: Some(13),
2606            }
2607        );
2608
2609        assert_eq!(
2610            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13):"),
2611            PathWithPosition {
2612                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2613                row: Some(1902),
2614                column: Some(13),
2615            }
2616        );
2617
2618        assert_eq!(
2619            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902):"),
2620            PathWithPosition {
2621                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2622                row: Some(1902),
2623                column: None,
2624            }
2625        );
2626
2627        assert_eq!(
2628            PathWithPosition::parse_str("crates/utils/paths.rs:101"),
2629            PathWithPosition {
2630                path: PathBuf::from("crates\\utils\\paths.rs"),
2631                row: Some(101),
2632                column: None,
2633            }
2634        );
2635    }
2636
2637    #[test]
2638    fn test_path_compact() {
2639        let path: PathBuf = [
2640            home_dir().to_string_lossy().into_owned(),
2641            "some_file.txt".to_string(),
2642        ]
2643        .iter()
2644        .collect();
2645        if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
2646            assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
2647        } else {
2648            assert_eq!(path.compact().to_str(), path.to_str());
2649        }
2650    }
2651
2652    #[test]
2653    fn test_extension_or_hidden_file_name() {
2654        // No dots in name
2655        let path = Path::new("/a/b/c/file_name.rs");
2656        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2657
2658        // Single dot in name
2659        let path = Path::new("/a/b/c/file.name.rs");
2660        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2661
2662        // Multiple dots in name
2663        let path = Path::new("/a/b/c/long.file.name.rs");
2664        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2665
2666        // Hidden file, no extension
2667        let path = Path::new("/a/b/c/.gitignore");
2668        assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
2669
2670        // Hidden file, with extension
2671        let path = Path::new("/a/b/c/.eslintrc.js");
2672        assert_eq!(path.extension_or_hidden_file_name(), Some("eslintrc.js"));
2673    }
2674
2675    #[test]
2676    // fn edge_of_glob() {
2677    //     let path = Path::new("/work/node_modules");
2678    //     let path_matcher =
2679    //         PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
2680    //     assert!(
2681    //         path_matcher.is_match(path),
2682    //         "Path matcher should match {path:?}"
2683    //     );
2684    // }
2685
2686    // #[perf]
2687    // fn file_in_dirs() {
2688    //     let path = Path::new("/work/.env");
2689    //     let path_matcher = PathMatcher::new(&["**/.env".to_owned()], PathStyle::Posix).unwrap();
2690    //     assert!(
2691    //         path_matcher.is_match(path),
2692    //         "Path matcher should match {path:?}"
2693    //     );
2694    //     let path = Path::new("/work/package.json");
2695    //     assert!(
2696    //         !path_matcher.is_match(path),
2697    //         "Path matcher should not match {path:?}"
2698    //     );
2699    // }
2700
2701    // #[perf]
2702    // fn project_search() {
2703    //     let path = Path::new("/Users/someonetoignore/work/app/app.dev/node_modules");
2704    //     let path_matcher =
2705    //         PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
2706    //     assert!(
2707    //         path_matcher.is_match(path),
2708    //         "Path matcher should match {path:?}"
2709    //     );
2710    // }
2711    #[test]
2712    #[cfg(target_os = "windows")]
2713    fn test_sanitized_path() {
2714        let path = Path::new("C:\\Users\\someone\\test_file.rs");
2715        let sanitized_path = SanitizedPath::new(path);
2716        assert_eq!(
2717            sanitized_path.to_string(),
2718            "C:\\Users\\someone\\test_file.rs"
2719        );
2720
2721        let path = Path::new("\\\\?\\C:\\Users\\someone\\test_file.rs");
2722        let sanitized_path = SanitizedPath::new(path);
2723        assert_eq!(
2724            sanitized_path.to_string(),
2725            "C:\\Users\\someone\\test_file.rs"
2726        );
2727    }
2728
2729    #[test]
2730    fn test_compare_numeric_segments() {
2731        // Helper function to create peekable iterators and test
2732        fn compare(a: &str, b: &str) -> Ordering {
2733            let mut a_iter = a.chars().peekable();
2734            let mut b_iter = b.chars().peekable();
2735
2736            let result = compare_numeric_segments(&mut a_iter, &mut b_iter);
2737
2738            // Verify iterators advanced correctly
2739            assert!(
2740                !a_iter.next().is_some_and(|c| c.is_ascii_digit()),
2741                "Iterator a should have consumed all digits"
2742            );
2743            assert!(
2744                !b_iter.next().is_some_and(|c| c.is_ascii_digit()),
2745                "Iterator b should have consumed all digits"
2746            );
2747
2748            result
2749        }
2750
2751        // Basic numeric comparisons
2752        assert_eq!(compare("0", "0"), Ordering::Equal);
2753        assert_eq!(compare("1", "2"), Ordering::Less);
2754        assert_eq!(compare("9", "10"), Ordering::Less);
2755        assert_eq!(compare("10", "9"), Ordering::Greater);
2756        assert_eq!(compare("99", "100"), Ordering::Less);
2757
2758        // Leading zeros
2759        assert_eq!(compare("0", "00"), Ordering::Less);
2760        assert_eq!(compare("00", "0"), Ordering::Greater);
2761        assert_eq!(compare("01", "1"), Ordering::Greater);
2762        assert_eq!(compare("001", "1"), Ordering::Greater);
2763        assert_eq!(compare("001", "01"), Ordering::Greater);
2764
2765        // Same value different representation
2766        assert_eq!(compare("000100", "100"), Ordering::Greater);
2767        assert_eq!(compare("100", "0100"), Ordering::Less);
2768        assert_eq!(compare("0100", "00100"), Ordering::Less);
2769
2770        // Large numbers
2771        assert_eq!(compare("9999999999", "10000000000"), Ordering::Less);
2772        assert_eq!(
2773            compare(
2774                "340282366920938463463374607431768211455", // u128::MAX
2775                "340282366920938463463374607431768211456"
2776            ),
2777            Ordering::Less
2778        );
2779        assert_eq!(
2780            compare(
2781                "340282366920938463463374607431768211456", // > u128::MAX
2782                "340282366920938463463374607431768211455"
2783            ),
2784            Ordering::Greater
2785        );
2786
2787        // Iterator advancement verification
2788        let mut a_iter = "123abc".chars().peekable();
2789        let mut b_iter = "456def".chars().peekable();
2790
2791        compare_numeric_segments(&mut a_iter, &mut b_iter);
2792
2793        assert_eq!(a_iter.collect::<String>(), "abc");
2794        assert_eq!(b_iter.collect::<String>(), "def");
2795    }
2796
2797    #[test]
2798    fn test_natural_sort() {
2799        // Basic alphanumeric
2800        assert_eq!(natural_sort("a", "b"), Ordering::Less);
2801        assert_eq!(natural_sort("b", "a"), Ordering::Greater);
2802        assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2803
2804        // Case sensitivity
2805        assert_eq!(natural_sort("a", "A"), Ordering::Less);
2806        assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2807        assert_eq!(natural_sort("aA", "aa"), Ordering::Greater);
2808        assert_eq!(natural_sort("aa", "aA"), Ordering::Less);
2809
2810        // Numbers
2811        assert_eq!(natural_sort("1", "2"), Ordering::Less);
2812        assert_eq!(natural_sort("2", "10"), Ordering::Less);
2813        assert_eq!(natural_sort("02", "10"), Ordering::Less);
2814        assert_eq!(natural_sort("02", "2"), Ordering::Greater);
2815
2816        // Mixed alphanumeric
2817        assert_eq!(natural_sort("a1", "a2"), Ordering::Less);
2818        assert_eq!(natural_sort("a2", "a10"), Ordering::Less);
2819        assert_eq!(natural_sort("a02", "a2"), Ordering::Greater);
2820        assert_eq!(natural_sort("a1b", "a1c"), Ordering::Less);
2821
2822        // Multiple numeric segments
2823        assert_eq!(natural_sort("1a2", "1a10"), Ordering::Less);
2824        assert_eq!(natural_sort("1a10", "1a2"), Ordering::Greater);
2825        assert_eq!(natural_sort("2a1", "10a1"), Ordering::Less);
2826
2827        // Special characters
2828        assert_eq!(natural_sort("a-1", "a-2"), Ordering::Less);
2829        assert_eq!(natural_sort("a_1", "a_2"), Ordering::Less);
2830        assert_eq!(natural_sort("a.1", "a.2"), Ordering::Less);
2831
2832        // Unicode
2833        assert_eq!(natural_sort("文1", "文2"), Ordering::Less);
2834        assert_eq!(natural_sort("文2", "文10"), Ordering::Less);
2835        assert_eq!(natural_sort("🔤1", "🔤2"), Ordering::Less);
2836
2837        // Empty and special cases
2838        assert_eq!(natural_sort("", ""), Ordering::Equal);
2839        assert_eq!(natural_sort("", "a"), Ordering::Less);
2840        assert_eq!(natural_sort("a", ""), Ordering::Greater);
2841        assert_eq!(natural_sort(" ", "  "), Ordering::Less);
2842
2843        // Mixed everything
2844        assert_eq!(natural_sort("File-1.txt", "File-2.txt"), Ordering::Less);
2845        assert_eq!(natural_sort("File-02.txt", "File-2.txt"), Ordering::Greater);
2846        assert_eq!(natural_sort("File-2.txt", "File-10.txt"), Ordering::Less);
2847        assert_eq!(natural_sort("File_A1", "File_A2"), Ordering::Less);
2848        assert_eq!(natural_sort("File_a1", "File_A1"), Ordering::Less);
2849    }
2850
2851    #[test]
2852    fn test_compare_paths() {
2853        // Helper function for cleaner tests
2854        fn compare(a: &str, is_a_file: bool, b: &str, is_b_file: bool) -> Ordering {
2855            compare_paths((Path::new(a), is_a_file), (Path::new(b), is_b_file))
2856        }
2857
2858        // Basic path comparison
2859        assert_eq!(compare("a", true, "b", true), Ordering::Less);
2860        assert_eq!(compare("b", true, "a", true), Ordering::Greater);
2861        assert_eq!(compare("a", true, "a", true), Ordering::Equal);
2862
2863        // Files vs Directories
2864        assert_eq!(compare("a", true, "a", false), Ordering::Greater);
2865        assert_eq!(compare("a", false, "a", true), Ordering::Less);
2866        assert_eq!(compare("b", false, "a", true), Ordering::Less);
2867
2868        // Extensions
2869        assert_eq!(compare("a.txt", true, "a.md", true), Ordering::Greater);
2870        assert_eq!(compare("a.md", true, "a.txt", true), Ordering::Less);
2871        assert_eq!(compare("a", true, "a.txt", true), Ordering::Less);
2872
2873        // Nested paths
2874        assert_eq!(compare("dir/a", true, "dir/b", true), Ordering::Less);
2875        assert_eq!(compare("dir1/a", true, "dir2/a", true), Ordering::Less);
2876        assert_eq!(compare("dir/sub/a", true, "dir/a", true), Ordering::Less);
2877
2878        // Case sensitivity in paths
2879        assert_eq!(
2880            compare("Dir/file", true, "dir/file", true),
2881            Ordering::Greater
2882        );
2883        assert_eq!(
2884            compare("dir/File", true, "dir/file", true),
2885            Ordering::Greater
2886        );
2887        assert_eq!(compare("dir/file", true, "Dir/File", true), Ordering::Less);
2888
2889        // Hidden files and special names
2890        assert_eq!(compare(".hidden", true, "visible", true), Ordering::Less);
2891        assert_eq!(compare("_special", true, "normal", true), Ordering::Less);
2892        assert_eq!(compare(".config", false, ".data", false), Ordering::Less);
2893
2894        // Mixed numeric paths
2895        assert_eq!(
2896            compare("dir1/file", true, "dir2/file", true),
2897            Ordering::Less
2898        );
2899        assert_eq!(
2900            compare("dir2/file", true, "dir10/file", true),
2901            Ordering::Less
2902        );
2903        assert_eq!(
2904            compare("dir02/file", true, "dir2/file", true),
2905            Ordering::Greater
2906        );
2907
2908        // Root paths
2909        assert_eq!(compare("/a", true, "/b", true), Ordering::Less);
2910        assert_eq!(compare("/", false, "/a", true), Ordering::Less);
2911
2912        // Complex real-world examples
2913        assert_eq!(
2914            compare("project/src/main.rs", true, "project/src/lib.rs", true),
2915            Ordering::Greater
2916        );
2917        assert_eq!(
2918            compare(
2919                "project/tests/test_1.rs",
2920                true,
2921                "project/tests/test_2.rs",
2922                true
2923            ),
2924            Ordering::Less
2925        );
2926        assert_eq!(
2927            compare(
2928                "project/v1.0.0/README.md",
2929                true,
2930                "project/v1.10.0/README.md",
2931                true
2932            ),
2933            Ordering::Less
2934        );
2935    }
2936
2937    #[test]
2938    fn test_natural_sort_case_sensitivity() {
2939        std::thread::sleep(std::time::Duration::from_millis(100));
2940        // Same letter different case - lowercase should come first
2941        assert_eq!(natural_sort("a", "A"), Ordering::Less);
2942        assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2943        assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2944        assert_eq!(natural_sort("A", "A"), Ordering::Equal);
2945
2946        // Mixed case strings
2947        assert_eq!(natural_sort("aaa", "AAA"), Ordering::Less);
2948        assert_eq!(natural_sort("AAA", "aaa"), Ordering::Greater);
2949        assert_eq!(natural_sort("aAa", "AaA"), Ordering::Less);
2950
2951        // Different letters
2952        assert_eq!(natural_sort("a", "b"), Ordering::Less);
2953        assert_eq!(natural_sort("A", "b"), Ordering::Less);
2954        assert_eq!(natural_sort("a", "B"), Ordering::Less);
2955    }
2956
2957    #[test]
2958    fn test_natural_sort_with_numbers() {
2959        // Basic number ordering
2960        assert_eq!(natural_sort("file1", "file2"), Ordering::Less);
2961        assert_eq!(natural_sort("file2", "file10"), Ordering::Less);
2962        assert_eq!(natural_sort("file10", "file2"), Ordering::Greater);
2963
2964        // Numbers in different positions
2965        assert_eq!(natural_sort("1file", "2file"), Ordering::Less);
2966        assert_eq!(natural_sort("file1text", "file2text"), Ordering::Less);
2967        assert_eq!(natural_sort("text1file", "text2file"), Ordering::Less);
2968
2969        // Multiple numbers in string
2970        assert_eq!(natural_sort("file1-2", "file1-10"), Ordering::Less);
2971        assert_eq!(natural_sort("2-1file", "10-1file"), Ordering::Less);
2972
2973        // Leading zeros
2974        assert_eq!(natural_sort("file002", "file2"), Ordering::Greater);
2975        assert_eq!(natural_sort("file002", "file10"), Ordering::Less);
2976
2977        // Very large numbers
2978        assert_eq!(
2979            natural_sort("file999999999999999999999", "file999999999999999999998"),
2980            Ordering::Greater
2981        );
2982
2983        // u128 edge cases
2984
2985        // Numbers near u128::MAX (340,282,366,920,938,463,463,374,607,431,768,211,455)
2986        assert_eq!(
2987            natural_sort(
2988                "file340282366920938463463374607431768211454",
2989                "file340282366920938463463374607431768211455"
2990            ),
2991            Ordering::Less
2992        );
2993
2994        // Equal length numbers that overflow u128
2995        assert_eq!(
2996            natural_sort(
2997                "file340282366920938463463374607431768211456",
2998                "file340282366920938463463374607431768211455"
2999            ),
3000            Ordering::Greater
3001        );
3002
3003        // Different length numbers that overflow u128
3004        assert_eq!(
3005            natural_sort(
3006                "file3402823669209384634633746074317682114560",
3007                "file340282366920938463463374607431768211455"
3008            ),
3009            Ordering::Greater
3010        );
3011
3012        // Leading zeros with numbers near u128::MAX
3013        assert_eq!(
3014            natural_sort(
3015                "file0340282366920938463463374607431768211455",
3016                "file340282366920938463463374607431768211455"
3017            ),
3018            Ordering::Greater
3019        );
3020
3021        // Very large numbers with different lengths (both overflow u128)
3022        assert_eq!(
3023            natural_sort(
3024                "file999999999999999999999999999999999999999999999999",
3025                "file9999999999999999999999999999999999999999999999999"
3026            ),
3027            Ordering::Less
3028        );
3029    }
3030
3031    #[test]
3032    fn test_natural_sort_case_sensitive() {
3033        // Numerically smaller values come first.
3034        assert_eq!(natural_sort("File1", "file2"), Ordering::Less);
3035        assert_eq!(natural_sort("file1", "File2"), Ordering::Less);
3036
3037        // Numerically equal values: the case-insensitive comparison decides first.
3038        // Case-sensitive comparison only occurs when both are equal case-insensitively.
3039        assert_eq!(natural_sort("Dir1", "dir01"), Ordering::Less);
3040        assert_eq!(natural_sort("dir2", "Dir02"), Ordering::Less);
3041        assert_eq!(natural_sort("dir2", "dir02"), Ordering::Less);
3042
3043        // Numerically equal and case-insensitively equal:
3044        // the lexicographically smaller (case-sensitive) one wins.
3045        assert_eq!(natural_sort("dir1", "Dir1"), Ordering::Less);
3046        assert_eq!(natural_sort("dir02", "Dir02"), Ordering::Less);
3047        assert_eq!(natural_sort("dir10", "Dir10"), Ordering::Less);
3048    }
3049
3050    #[test]
3051    fn test_natural_sort_edge_cases() {
3052        // Empty strings
3053        assert_eq!(natural_sort("", ""), Ordering::Equal);
3054        assert_eq!(natural_sort("", "a"), Ordering::Less);
3055        assert_eq!(natural_sort("a", ""), Ordering::Greater);
3056
3057        // Special characters
3058        assert_eq!(natural_sort("file-1", "file_1"), Ordering::Less);
3059        assert_eq!(natural_sort("file.1", "file_1"), Ordering::Less);
3060        assert_eq!(natural_sort("file 1", "file_1"), Ordering::Less);
3061
3062        // Unicode characters
3063        // 9312 vs 9313
3064        assert_eq!(natural_sort("file①", "file②"), Ordering::Less);
3065        // 9321 vs 9313
3066        assert_eq!(natural_sort("file⑩", "file②"), Ordering::Greater);
3067        // 28450 vs 23383
3068        assert_eq!(natural_sort("file漢", "file字"), Ordering::Greater);
3069
3070        // Mixed alphanumeric with special chars
3071        assert_eq!(natural_sort("file-1a", "file-1b"), Ordering::Less);
3072        assert_eq!(natural_sort("file-1.2", "file-1.10"), Ordering::Less);
3073        assert_eq!(natural_sort("file-1.10", "file-1.2"), Ordering::Greater);
3074    }
3075
3076    #[test]
3077    fn test_multiple_extensions() {
3078        // No extensions
3079        let path = Path::new("/a/b/c/file_name");
3080        assert_eq!(path.multiple_extensions(), None);
3081
3082        // Only one extension
3083        let path = Path::new("/a/b/c/file_name.tsx");
3084        assert_eq!(path.multiple_extensions(), None);
3085
3086        // Stories sample extension
3087        let path = Path::new("/a/b/c/file_name.stories.tsx");
3088        assert_eq!(path.multiple_extensions(), Some("stories.tsx".to_string()));
3089
3090        // Longer sample extension
3091        let path = Path::new("/a/b/c/long.app.tar.gz");
3092        assert_eq!(path.multiple_extensions(), Some("app.tar.gz".to_string()));
3093    }
3094
3095    #[test]
3096    fn test_strip_path_suffix() {
3097        let base = Path::new("/a/b/c/file_name");
3098        let suffix = Path::new("file_name");
3099        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
3100
3101        let base = Path::new("/a/b/c/file_name.tsx");
3102        let suffix = Path::new("file_name.tsx");
3103        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
3104
3105        let base = Path::new("/a/b/c/file_name.stories.tsx");
3106        let suffix = Path::new("c/file_name.stories.tsx");
3107        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b")));
3108
3109        let base = Path::new("/a/b/c/long.app.tar.gz");
3110        let suffix = Path::new("b/c/long.app.tar.gz");
3111        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a")));
3112
3113        let base = Path::new("/a/b/c/long.app.tar.gz");
3114        let suffix = Path::new("/a/b/c/long.app.tar.gz");
3115        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("")));
3116
3117        let base = Path::new("/a/b/c/long.app.tar.gz");
3118        let suffix = Path::new("/a/b/c/no_match.app.tar.gz");
3119        assert_eq!(strip_path_suffix(base, suffix), None);
3120
3121        let base = Path::new("/a/b/c/long.app.tar.gz");
3122        let suffix = Path::new("app.tar.gz");
3123        assert_eq!(strip_path_suffix(base, suffix), None);
3124    }
3125
3126    #[test]
3127    fn test_strip_prefix() {
3128        let expected = [
3129            (
3130                PathStyle::Posix,
3131                "/a/b/c",
3132                "/a/b",
3133                Some(rel_path("c").into_arc()),
3134            ),
3135            (
3136                PathStyle::Posix,
3137                "/a/b/c",
3138                "/a/b/",
3139                Some(rel_path("c").into_arc()),
3140            ),
3141            (
3142                PathStyle::Posix,
3143                "/a/b/c",
3144                "/",
3145                Some(rel_path("a/b/c").into_arc()),
3146            ),
3147            (PathStyle::Posix, "/a/b/c", "", None),
3148            (PathStyle::Posix, "/a/b//c", "/a/b/", None),
3149            (PathStyle::Posix, "/a/bc", "/a/b", None),
3150            (
3151                PathStyle::Posix,
3152                "/a/b/c",
3153                "/a/b/c",
3154                Some(rel_path("").into_arc()),
3155            ),
3156            (
3157                PathStyle::Windows,
3158                "C:\\a\\b\\c",
3159                "C:\\a\\b",
3160                Some(rel_path("c").into_arc()),
3161            ),
3162            (
3163                PathStyle::Windows,
3164                "C:\\a\\b\\c",
3165                "C:\\a\\b\\",
3166                Some(rel_path("c").into_arc()),
3167            ),
3168            (
3169                PathStyle::Windows,
3170                "C:\\a\\b\\c",
3171                "C:\\",
3172                Some(rel_path("a/b/c").into_arc()),
3173            ),
3174            (PathStyle::Windows, "C:\\a\\b\\c", "", None),
3175            (PathStyle::Windows, "C:\\a\\b\\\\c", "C:\\a\\b\\", None),
3176            (PathStyle::Windows, "C:\\a\\bc", "C:\\a\\b", None),
3177            (
3178                PathStyle::Windows,
3179                "C:\\a\\b/c",
3180                "C:\\a\\b",
3181                Some(rel_path("c").into_arc()),
3182            ),
3183            (
3184                PathStyle::Windows,
3185                "C:\\a\\b/c",
3186                "C:\\a\\b\\",
3187                Some(rel_path("c").into_arc()),
3188            ),
3189            (
3190                PathStyle::Windows,
3191                "C:\\a\\b/c",
3192                "C:\\a\\b/",
3193                Some(rel_path("c").into_arc()),
3194            ),
3195        ];
3196        let actual = expected.clone().map(|(style, child, parent, _)| {
3197            (
3198                style,
3199                child,
3200                parent,
3201                style
3202                    .strip_prefix(child.as_ref(), parent.as_ref())
3203                    .map(|rel_path| rel_path.into_arc()),
3204            )
3205        });
3206        pretty_assertions::assert_eq!(actual, expected);
3207    }
3208
3209    #[cfg(target_os = "windows")]
3210    #[test]
3211    fn test_wsl_path() {
3212        use super::WslPath;
3213        let path = "/a/b/c";
3214        assert_eq!(WslPath::from_path(&path), None);
3215
3216        let path = r"\\wsl.localhost";
3217        assert_eq!(WslPath::from_path(&path), None);
3218
3219        let path = r"\\wsl.localhost\Distro";
3220        assert_eq!(
3221            WslPath::from_path(&path),
3222            Some(WslPath {
3223                distro: "Distro".to_owned(),
3224                path: "/".into(),
3225            })
3226        );
3227
3228        let path = r"\\wsl.localhost\Distro\blue";
3229        assert_eq!(
3230            WslPath::from_path(&path),
3231            Some(WslPath {
3232                distro: "Distro".to_owned(),
3233                path: "/blue".into()
3234            })
3235        );
3236
3237        let path = r"\\wsl$\archlinux\tomato\.\paprika\..\aubergine.txt";
3238        assert_eq!(
3239            WslPath::from_path(&path),
3240            Some(WslPath {
3241                distro: "archlinux".to_owned(),
3242                path: "/tomato/paprika/../aubergine.txt".into()
3243            })
3244        );
3245
3246        let path = r"\\windows.localhost\Distro\foo";
3247        assert_eq!(WslPath::from_path(&path), None);
3248    }
3249
3250    #[test]
3251    fn test_url_to_file_path_ext_posix_basic() {
3252        use super::UrlExt;
3253
3254        let url = url::Url::parse("file:///home/user/file.txt").unwrap();
3255        assert_eq!(
3256            url.to_file_path_ext(PathStyle::Posix),
3257            Ok(PathBuf::from("/home/user/file.txt"))
3258        );
3259
3260        let url = url::Url::parse("file:///").unwrap();
3261        assert_eq!(
3262            url.to_file_path_ext(PathStyle::Posix),
3263            Ok(PathBuf::from("/"))
3264        );
3265
3266        let url = url::Url::parse("file:///a/b/c/d/e").unwrap();
3267        assert_eq!(
3268            url.to_file_path_ext(PathStyle::Posix),
3269            Ok(PathBuf::from("/a/b/c/d/e"))
3270        );
3271    }
3272
3273    #[test]
3274    fn test_url_to_file_path_ext_posix_percent_encoding() {
3275        use super::UrlExt;
3276
3277        let url = url::Url::parse("file:///home/user/file%20with%20spaces.txt").unwrap();
3278        assert_eq!(
3279            url.to_file_path_ext(PathStyle::Posix),
3280            Ok(PathBuf::from("/home/user/file with spaces.txt"))
3281        );
3282
3283        let url = url::Url::parse("file:///path%2Fwith%2Fencoded%2Fslashes").unwrap();
3284        assert_eq!(
3285            url.to_file_path_ext(PathStyle::Posix),
3286            Ok(PathBuf::from("/path/with/encoded/slashes"))
3287        );
3288
3289        let url = url::Url::parse("file:///special%23chars%3F.txt").unwrap();
3290        assert_eq!(
3291            url.to_file_path_ext(PathStyle::Posix),
3292            Ok(PathBuf::from("/special#chars?.txt"))
3293        );
3294    }
3295
3296    #[test]
3297    fn test_url_to_file_path_ext_posix_localhost() {
3298        use super::UrlExt;
3299
3300        let url = url::Url::parse("file://localhost/home/user/file.txt").unwrap();
3301        assert_eq!(
3302            url.to_file_path_ext(PathStyle::Posix),
3303            Ok(PathBuf::from("/home/user/file.txt"))
3304        );
3305    }
3306
3307    #[test]
3308    fn test_url_to_file_path_ext_posix_rejects_host() {
3309        use super::UrlExt;
3310
3311        let url = url::Url::parse("file://somehost/home/user/file.txt").unwrap();
3312        assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(()));
3313    }
3314
3315    #[test]
3316    fn test_url_to_file_path_ext_posix_windows_drive_letter() {
3317        use super::UrlExt;
3318
3319        let url = url::Url::parse("file:///C:").unwrap();
3320        assert_eq!(
3321            url.to_file_path_ext(PathStyle::Posix),
3322            Ok(PathBuf::from("/C:/"))
3323        );
3324
3325        let url = url::Url::parse("file:///D|").unwrap();
3326        assert_eq!(
3327            url.to_file_path_ext(PathStyle::Posix),
3328            Ok(PathBuf::from("/D|/"))
3329        );
3330    }
3331
3332    #[test]
3333    fn test_url_to_file_path_ext_windows_basic() {
3334        use super::UrlExt;
3335
3336        let url = url::Url::parse("file:///C:/Users/user/file.txt").unwrap();
3337        assert_eq!(
3338            url.to_file_path_ext(PathStyle::Windows),
3339            Ok(PathBuf::from("C:\\Users\\user\\file.txt"))
3340        );
3341
3342        let url = url::Url::parse("file:///D:/folder/subfolder/file.rs").unwrap();
3343        assert_eq!(
3344            url.to_file_path_ext(PathStyle::Windows),
3345            Ok(PathBuf::from("D:\\folder\\subfolder\\file.rs"))
3346        );
3347
3348        let url = url::Url::parse("file:///C:/").unwrap();
3349        assert_eq!(
3350            url.to_file_path_ext(PathStyle::Windows),
3351            Ok(PathBuf::from("C:\\"))
3352        );
3353    }
3354
3355    #[test]
3356    fn test_url_to_file_path_ext_windows_encoded_drive_letter() {
3357        use super::UrlExt;
3358
3359        let url = url::Url::parse("file:///C%3A/Users/file.txt").unwrap();
3360        assert_eq!(
3361            url.to_file_path_ext(PathStyle::Windows),
3362            Ok(PathBuf::from("C:\\Users\\file.txt"))
3363        );
3364
3365        let url = url::Url::parse("file:///c%3a/Users/file.txt").unwrap();
3366        assert_eq!(
3367            url.to_file_path_ext(PathStyle::Windows),
3368            Ok(PathBuf::from("c:\\Users\\file.txt"))
3369        );
3370
3371        let url = url::Url::parse("file:///D%3A/folder/file.txt").unwrap();
3372        assert_eq!(
3373            url.to_file_path_ext(PathStyle::Windows),
3374            Ok(PathBuf::from("D:\\folder\\file.txt"))
3375        );
3376
3377        let url = url::Url::parse("file:///d%3A/folder/file.txt").unwrap();
3378        assert_eq!(
3379            url.to_file_path_ext(PathStyle::Windows),
3380            Ok(PathBuf::from("d:\\folder\\file.txt"))
3381        );
3382    }
3383
3384    #[test]
3385    fn test_url_to_file_path_ext_windows_unc_path() {
3386        use super::UrlExt;
3387
3388        let url = url::Url::parse("file://server/share/path/file.txt").unwrap();
3389        assert_eq!(
3390            url.to_file_path_ext(PathStyle::Windows),
3391            Ok(PathBuf::from("\\\\server\\share\\path\\file.txt"))
3392        );
3393
3394        let url = url::Url::parse("file://server/share").unwrap();
3395        assert_eq!(
3396            url.to_file_path_ext(PathStyle::Windows),
3397            Ok(PathBuf::from("\\\\server\\share"))
3398        );
3399    }
3400
3401    #[test]
3402    fn test_url_to_file_path_ext_windows_percent_encoding() {
3403        use super::UrlExt;
3404
3405        let url = url::Url::parse("file:///C:/Users/user/file%20with%20spaces.txt").unwrap();
3406        assert_eq!(
3407            url.to_file_path_ext(PathStyle::Windows),
3408            Ok(PathBuf::from("C:\\Users\\user\\file with spaces.txt"))
3409        );
3410
3411        let url = url::Url::parse("file:///C:/special%23chars%3F.txt").unwrap();
3412        assert_eq!(
3413            url.to_file_path_ext(PathStyle::Windows),
3414            Ok(PathBuf::from("C:\\special#chars?.txt"))
3415        );
3416    }
3417
3418    #[test]
3419    fn test_url_to_file_path_ext_windows_invalid_drive() {
3420        use super::UrlExt;
3421
3422        let url = url::Url::parse("file:///1:/path/file.txt").unwrap();
3423        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3424
3425        let url = url::Url::parse("file:///CC:/path/file.txt").unwrap();
3426        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3427
3428        let url = url::Url::parse("file:///C/path/file.txt").unwrap();
3429        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3430
3431        let url = url::Url::parse("file:///invalid").unwrap();
3432        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3433    }
3434
3435    #[test]
3436    fn test_url_to_file_path_ext_non_file_scheme() {
3437        use super::UrlExt;
3438
3439        let url = url::Url::parse("http://example.com/path").unwrap();
3440        assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(()));
3441        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3442
3443        let url = url::Url::parse("https://example.com/path").unwrap();
3444        assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(()));
3445        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3446    }
3447
3448    #[test]
3449    fn test_url_to_file_path_ext_windows_localhost() {
3450        use super::UrlExt;
3451
3452        let url = url::Url::parse("file://localhost/C:/Users/file.txt").unwrap();
3453        assert_eq!(
3454            url.to_file_path_ext(PathStyle::Windows),
3455            Ok(PathBuf::from("C:\\Users\\file.txt"))
3456        );
3457    }
3458}