paths.rs

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