Skip to main content

util/
paths.rs

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