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        \:+(\d+)\:(\d+)\:*$  # filename:row:column
 607        |
 608        \:+(\d+)\:*()$       # filename:row
 609        |
 610        \:+()()$
 611    )";
 612
 613/// A representation of a path-like string with optional row and column numbers.
 614/// Matching values example: `te`, `test.rs:22`, `te:22:5`, `test.c(22)`, `test.c(22,5)`etc.
 615#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
 616pub struct PathWithPosition {
 617    pub path: PathBuf,
 618    pub row: Option<u32>,
 619    // Absent if row is absent.
 620    pub column: Option<u32>,
 621}
 622
 623impl PathWithPosition {
 624    /// Returns a PathWithPosition from a path.
 625    pub fn from_path(path: PathBuf) -> Self {
 626        Self {
 627            path,
 628            row: None,
 629            column: None,
 630        }
 631    }
 632
 633    /// Parses a string that possibly has `:row:column` or `(row, column)` suffix.
 634    /// Parenthesis format is used by [MSBuild](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks) compatible tools
 635    /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`.
 636    /// If the suffix parsing fails, the whole string is parsed as a path.
 637    ///
 638    /// Be mindful that `test_file:10:1:` is a valid posix filename.
 639    /// `PathWithPosition` class assumes that the ending position-like suffix is **not** part of the filename.
 640    ///
 641    /// # Examples
 642    ///
 643    /// ```
 644    /// # use util::paths::PathWithPosition;
 645    /// # use std::path::PathBuf;
 646    /// assert_eq!(PathWithPosition::parse_str("test_file"), PathWithPosition {
 647    ///     path: PathBuf::from("test_file"),
 648    ///     row: None,
 649    ///     column: None,
 650    /// });
 651    /// assert_eq!(PathWithPosition::parse_str("test_file:10"), PathWithPosition {
 652    ///     path: PathBuf::from("test_file"),
 653    ///     row: Some(10),
 654    ///     column: None,
 655    /// });
 656    /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
 657    ///     path: PathBuf::from("test_file.rs"),
 658    ///     row: None,
 659    ///     column: None,
 660    /// });
 661    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1"), PathWithPosition {
 662    ///     path: PathBuf::from("test_file.rs"),
 663    ///     row: Some(1),
 664    ///     column: None,
 665    /// });
 666    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2"), PathWithPosition {
 667    ///     path: PathBuf::from("test_file.rs"),
 668    ///     row: Some(1),
 669    ///     column: Some(2),
 670    /// });
 671    /// ```
 672    ///
 673    /// # Expected parsing results when encounter ill-formatted inputs.
 674    /// ```
 675    /// # use util::paths::PathWithPosition;
 676    /// # use std::path::PathBuf;
 677    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a"), PathWithPosition {
 678    ///     path: PathBuf::from("test_file.rs:a"),
 679    ///     row: None,
 680    ///     column: None,
 681    /// });
 682    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a:b"), PathWithPosition {
 683    ///     path: PathBuf::from("test_file.rs:a:b"),
 684    ///     row: None,
 685    ///     column: None,
 686    /// });
 687    /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
 688    ///     path: PathBuf::from("test_file.rs"),
 689    ///     row: None,
 690    ///     column: None,
 691    /// });
 692    /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1"), PathWithPosition {
 693    ///     path: PathBuf::from("test_file.rs"),
 694    ///     row: Some(1),
 695    ///     column: None,
 696    /// });
 697    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::"), PathWithPosition {
 698    ///     path: PathBuf::from("test_file.rs"),
 699    ///     row: Some(1),
 700    ///     column: None,
 701    /// });
 702    /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1:2"), PathWithPosition {
 703    ///     path: PathBuf::from("test_file.rs"),
 704    ///     row: Some(1),
 705    ///     column: Some(2),
 706    /// });
 707    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::2"), PathWithPosition {
 708    ///     path: PathBuf::from("test_file.rs:1"),
 709    ///     row: Some(2),
 710    ///     column: None,
 711    /// });
 712    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2:3"), PathWithPosition {
 713    ///     path: PathBuf::from("test_file.rs:1"),
 714    ///     row: Some(2),
 715    ///     column: Some(3),
 716    /// });
 717    /// ```
 718    pub fn parse_str(s: &str) -> Self {
 719        let trimmed = s.trim();
 720        let path = Path::new(trimmed);
 721        let Some(maybe_file_name_with_row_col) = path.file_name().unwrap_or_default().to_str()
 722        else {
 723            return Self {
 724                path: Path::new(s).to_path_buf(),
 725                row: None,
 726                column: None,
 727            };
 728        };
 729        if maybe_file_name_with_row_col.is_empty() {
 730            return Self {
 731                path: Path::new(s).to_path_buf(),
 732                row: None,
 733                column: None,
 734            };
 735        }
 736
 737        // Let's avoid repeated init cost on this. It is subject to thread contention, but
 738        // so far this code isn't called from multiple hot paths. Getting contention here
 739        // in the future seems unlikely.
 740        static SUFFIX_RE: LazyLock<Regex> =
 741            LazyLock::new(|| Regex::new(ROW_COL_CAPTURE_REGEX).unwrap());
 742        match SUFFIX_RE
 743            .captures(maybe_file_name_with_row_col)
 744            .map(|caps| caps.extract())
 745        {
 746            Some((_, [file_name, maybe_row, maybe_column])) => {
 747                let row = maybe_row.parse::<u32>().ok();
 748                let column = maybe_column.parse::<u32>().ok();
 749
 750                let (_, suffix) = trimmed.split_once(file_name).unwrap();
 751                let path_without_suffix = &trimmed[..trimmed.len() - suffix.len()];
 752
 753                Self {
 754                    path: Path::new(path_without_suffix).to_path_buf(),
 755                    row,
 756                    column,
 757                }
 758            }
 759            None => {
 760                // The `ROW_COL_CAPTURE_REGEX` deals with separated digits only,
 761                // but in reality there could be `foo/bar.py:22:in` inputs which we want to match too.
 762                // The regex mentioned is not very extendable with "digit or random string" checks, so do this here instead.
 763                let delimiter = ':';
 764                let mut path_parts = s
 765                    .rsplitn(3, delimiter)
 766                    .collect::<Vec<_>>()
 767                    .into_iter()
 768                    .rev()
 769                    .fuse();
 770                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();
 771                let mut row = None;
 772                let mut column = None;
 773                if let Some(maybe_row) = path_parts.next() {
 774                    if let Ok(parsed_row) = maybe_row.parse::<u32>() {
 775                        row = Some(parsed_row);
 776                        if let Some(parsed_column) = path_parts
 777                            .next()
 778                            .and_then(|maybe_col| maybe_col.parse::<u32>().ok())
 779                        {
 780                            column = Some(parsed_column);
 781                        }
 782                    } else {
 783                        path_string.push(delimiter);
 784                        path_string.push_str(maybe_row);
 785                    }
 786                }
 787                for split in path_parts {
 788                    path_string.push(delimiter);
 789                    path_string.push_str(split);
 790                }
 791
 792                Self {
 793                    path: PathBuf::from(path_string),
 794                    row,
 795                    column,
 796                }
 797            }
 798        }
 799    }
 800
 801    pub fn map_path<E>(
 802        self,
 803        mapping: impl FnOnce(PathBuf) -> Result<PathBuf, E>,
 804    ) -> Result<PathWithPosition, E> {
 805        Ok(PathWithPosition {
 806            path: mapping(self.path)?,
 807            row: self.row,
 808            column: self.column,
 809        })
 810    }
 811
 812    pub fn to_string(&self, path_to_string: &dyn Fn(&PathBuf) -> String) -> String {
 813        let path_string = path_to_string(&self.path);
 814        if let Some(row) = self.row {
 815            if let Some(column) = self.column {
 816                format!("{path_string}:{row}:{column}")
 817            } else {
 818                format!("{path_string}:{row}")
 819            }
 820        } else {
 821            path_string
 822        }
 823    }
 824}
 825
 826#[derive(Clone)]
 827pub struct PathMatcher {
 828    sources: Vec<(String, RelPathBuf, /*trailing separator*/ bool)>,
 829    glob: GlobSet,
 830    path_style: PathStyle,
 831}
 832
 833impl std::fmt::Debug for PathMatcher {
 834    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 835        f.debug_struct("PathMatcher")
 836            .field("sources", &self.sources)
 837            .field("path_style", &self.path_style)
 838            .finish()
 839    }
 840}
 841
 842impl PartialEq for PathMatcher {
 843    fn eq(&self, other: &Self) -> bool {
 844        self.sources.eq(&other.sources)
 845    }
 846}
 847
 848impl Eq for PathMatcher {}
 849
 850impl PathMatcher {
 851    pub fn new(
 852        globs: impl IntoIterator<Item = impl AsRef<str>>,
 853        path_style: PathStyle,
 854    ) -> Result<Self, globset::Error> {
 855        let globs = globs
 856            .into_iter()
 857            .map(|as_str| {
 858                GlobBuilder::new(as_str.as_ref())
 859                    .backslash_escape(path_style.is_posix())
 860                    .build()
 861            })
 862            .collect::<Result<Vec<_>, _>>()?;
 863        let sources = globs
 864            .iter()
 865            .filter_map(|glob| {
 866                let glob = glob.glob();
 867                Some((
 868                    glob.to_string(),
 869                    RelPath::new(&glob.as_ref(), path_style)
 870                        .ok()
 871                        .map(std::borrow::Cow::into_owned)?,
 872                    glob.ends_with(path_style.separators_ch()),
 873                ))
 874            })
 875            .collect();
 876        let mut glob_builder = GlobSetBuilder::new();
 877        for single_glob in globs {
 878            glob_builder.add(single_glob);
 879        }
 880        let glob = glob_builder.build()?;
 881        Ok(PathMatcher {
 882            glob,
 883            sources,
 884            path_style,
 885        })
 886    }
 887
 888    pub fn sources(&self) -> impl Iterator<Item = &str> + Clone {
 889        self.sources.iter().map(|(source, ..)| source.as_str())
 890    }
 891
 892    pub fn is_match<P: AsRef<RelPath>>(&self, other: P) -> bool {
 893        let other = other.as_ref();
 894        if self
 895            .sources
 896            .iter()
 897            .any(|(_, source, _)| other.starts_with(source) || other.ends_with(source))
 898        {
 899            return true;
 900        }
 901        let other_path = other.display(self.path_style);
 902
 903        if self.glob.is_match(&*other_path) {
 904            return true;
 905        }
 906
 907        self.glob
 908            .is_match(other_path.into_owned() + self.path_style.primary_separator())
 909    }
 910
 911    pub fn is_match_std_path<P: AsRef<Path>>(&self, other: P) -> bool {
 912        let other = other.as_ref();
 913        if self.sources.iter().any(|(_, source, _)| {
 914            other.starts_with(source.as_std_path()) || other.ends_with(source.as_std_path())
 915        }) {
 916            return true;
 917        }
 918        self.glob.is_match(other)
 919    }
 920}
 921
 922impl Default for PathMatcher {
 923    fn default() -> Self {
 924        Self {
 925            path_style: PathStyle::local(),
 926            glob: GlobSet::empty(),
 927            sources: vec![],
 928        }
 929    }
 930}
 931
 932/// Compares two sequences of consecutive digits for natural sorting.
 933///
 934/// This function is a core component of natural sorting that handles numeric comparison
 935/// in a way that feels natural to humans. It extracts and compares consecutive digit
 936/// sequences from two iterators, handling various cases like leading zeros and very large numbers.
 937///
 938/// # Behavior
 939///
 940/// The function implements the following comparison rules:
 941/// 1. Different numeric values: Compares by actual numeric value (e.g., "2" < "10")
 942/// 2. Leading zeros: When values are equal, longer sequence wins (e.g., "002" > "2")
 943/// 3. Large numbers: Falls back to string comparison for numbers that would overflow u128
 944///
 945/// # Examples
 946///
 947/// ```text
 948/// "1" vs "2"      -> Less       (different values)
 949/// "2" vs "10"     -> Less       (numeric comparison)
 950/// "002" vs "2"    -> Greater    (leading zeros)
 951/// "10" vs "010"   -> Less       (leading zeros)
 952/// "999..." vs "1000..." -> Less (large number comparison)
 953/// ```
 954///
 955/// # Implementation Details
 956///
 957/// 1. Extracts consecutive digits into strings
 958/// 2. Compares sequence lengths for leading zero handling
 959/// 3. For equal lengths, compares digit by digit
 960/// 4. For different lengths:
 961///    - Attempts numeric comparison first (for numbers up to 2^128 - 1)
 962///    - Falls back to string comparison if numbers would overflow
 963///
 964/// The function advances both iterators past their respective numeric sequences,
 965/// regardless of the comparison result.
 966fn compare_numeric_segments<I>(
 967    a_iter: &mut std::iter::Peekable<I>,
 968    b_iter: &mut std::iter::Peekable<I>,
 969) -> Ordering
 970where
 971    I: Iterator<Item = char>,
 972{
 973    // Collect all consecutive digits into strings
 974    let mut a_num_str = String::new();
 975    let mut b_num_str = String::new();
 976
 977    while let Some(&c) = a_iter.peek() {
 978        if !c.is_ascii_digit() {
 979            break;
 980        }
 981
 982        a_num_str.push(c);
 983        a_iter.next();
 984    }
 985
 986    while let Some(&c) = b_iter.peek() {
 987        if !c.is_ascii_digit() {
 988            break;
 989        }
 990
 991        b_num_str.push(c);
 992        b_iter.next();
 993    }
 994
 995    // First compare lengths (handle leading zeros)
 996    match a_num_str.len().cmp(&b_num_str.len()) {
 997        Ordering::Equal => {
 998            // Same length, compare digit by digit
 999            match a_num_str.cmp(&b_num_str) {
1000                Ordering::Equal => Ordering::Equal,
1001                ordering => ordering,
1002            }
1003        }
1004
1005        // Different lengths but same value means leading zeros
1006        ordering => {
1007            // Try parsing as numbers first
1008            if let (Ok(a_val), Ok(b_val)) = (a_num_str.parse::<u128>(), b_num_str.parse::<u128>()) {
1009                match a_val.cmp(&b_val) {
1010                    Ordering::Equal => ordering, // Same value, longer one is greater (leading zeros)
1011                    ord => ord,
1012                }
1013            } else {
1014                // If parsing fails (overflow), compare as strings
1015                a_num_str.cmp(&b_num_str)
1016            }
1017        }
1018    }
1019}
1020
1021/// Performs natural sorting comparison between two strings.
1022///
1023/// Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations.
1024/// For example, "file2" comes before "file10" (unlike standard lexicographic sorting).
1025///
1026/// # Characteristics
1027///
1028/// * Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase
1029/// * Numbers are compared by numeric value, not character by character
1030/// * Leading zeros affect ordering when numeric values are equal
1031/// * Can handle numbers larger than u128::MAX (falls back to string comparison)
1032/// * When strings are equal case-insensitively, lowercase is prioritized (lowercase < uppercase)
1033///
1034/// # Algorithm
1035///
1036/// The function works by:
1037/// 1. Processing strings character by character in a case-insensitive manner
1038/// 2. When encountering digits, treating consecutive digits as a single number
1039/// 3. Comparing numbers by their numeric value rather than lexicographically
1040/// 4. For non-numeric characters, using case-insensitive comparison
1041/// 5. If everything is equal case-insensitively, using case-sensitive comparison as final tie-breaker
1042pub fn natural_sort(a: &str, b: &str) -> Ordering {
1043    let mut a_iter = a.chars().peekable();
1044    let mut b_iter = b.chars().peekable();
1045
1046    loop {
1047        match (a_iter.peek(), b_iter.peek()) {
1048            (None, None) => {
1049                return b.cmp(a);
1050            }
1051            (None, _) => return Ordering::Less,
1052            (_, None) => return Ordering::Greater,
1053            (Some(&a_char), Some(&b_char)) => {
1054                if a_char.is_ascii_digit() && b_char.is_ascii_digit() {
1055                    match compare_numeric_segments(&mut a_iter, &mut b_iter) {
1056                        Ordering::Equal => continue,
1057                        ordering => return ordering,
1058                    }
1059                } else {
1060                    match a_char
1061                        .to_ascii_lowercase()
1062                        .cmp(&b_char.to_ascii_lowercase())
1063                    {
1064                        Ordering::Equal => {
1065                            a_iter.next();
1066                            b_iter.next();
1067                        }
1068                        ordering => return ordering,
1069                    }
1070                }
1071            }
1072        }
1073    }
1074}
1075
1076/// Case-insensitive natural sort without applying the final lowercase/uppercase tie-breaker.
1077/// This is useful when comparing individual path components where we want to keep walking
1078/// deeper components before deciding on casing.
1079fn natural_sort_no_tiebreak(a: &str, b: &str) -> Ordering {
1080    if a.eq_ignore_ascii_case(b) {
1081        Ordering::Equal
1082    } else {
1083        natural_sort(a, b)
1084    }
1085}
1086
1087fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) {
1088    if filename.is_empty() {
1089        return (None, None);
1090    }
1091
1092    match filename.rsplit_once('.') {
1093        // Case 1: No dot was found. The entire name is the stem.
1094        None => (Some(filename), None),
1095
1096        // Case 2: A dot was found.
1097        Some((before, after)) => {
1098            // This is the crucial check for dotfiles like ".bashrc".
1099            // If `before` is empty, the dot was the first character.
1100            // In that case, we revert to the "whole name is the stem" logic.
1101            if before.is_empty() {
1102                (Some(filename), None)
1103            } else {
1104                // Otherwise, we have a standard stem and extension.
1105                (Some(before), Some(after))
1106            }
1107        }
1108    }
1109}
1110
1111pub fn compare_rel_paths(
1112    (path_a, a_is_file): (&RelPath, bool),
1113    (path_b, b_is_file): (&RelPath, bool),
1114) -> Ordering {
1115    let mut components_a = path_a.components();
1116    let mut components_b = path_b.components();
1117    loop {
1118        match (components_a.next(), components_b.next()) {
1119            (Some(component_a), Some(component_b)) => {
1120                let a_is_file = a_is_file && components_a.rest().is_empty();
1121                let b_is_file = b_is_file && components_b.rest().is_empty();
1122
1123                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
1124                    let (a_stem, a_extension) = a_is_file
1125                        .then(|| stem_and_extension(component_a))
1126                        .unwrap_or_default();
1127                    let path_string_a = if a_is_file { a_stem } else { Some(component_a) };
1128
1129                    let (b_stem, b_extension) = b_is_file
1130                        .then(|| stem_and_extension(component_b))
1131                        .unwrap_or_default();
1132                    let path_string_b = if b_is_file { b_stem } else { Some(component_b) };
1133
1134                    let compare_components = match (path_string_a, path_string_b) {
1135                        (Some(a), Some(b)) => natural_sort(&a, &b),
1136                        (Some(_), None) => Ordering::Greater,
1137                        (None, Some(_)) => Ordering::Less,
1138                        (None, None) => Ordering::Equal,
1139                    };
1140
1141                    compare_components.then_with(|| {
1142                        if a_is_file && b_is_file {
1143                            let ext_a = a_extension.unwrap_or_default();
1144                            let ext_b = b_extension.unwrap_or_default();
1145                            ext_a.cmp(ext_b)
1146                        } else {
1147                            Ordering::Equal
1148                        }
1149                    })
1150                });
1151
1152                if !ordering.is_eq() {
1153                    return ordering;
1154                }
1155            }
1156            (Some(_), None) => break Ordering::Greater,
1157            (None, Some(_)) => break Ordering::Less,
1158            (None, None) => break Ordering::Equal,
1159        }
1160    }
1161}
1162
1163/// Compare two relative paths with mixed files and directories using
1164/// case-insensitive natural sorting. For example, "Apple", "aardvark.txt",
1165/// and "Zebra" would be sorted as: aardvark.txt, Apple, Zebra
1166/// (case-insensitive alphabetical).
1167pub fn compare_rel_paths_mixed(
1168    (path_a, a_is_file): (&RelPath, bool),
1169    (path_b, b_is_file): (&RelPath, bool),
1170) -> Ordering {
1171    let original_paths_equal = std::ptr::eq(path_a, path_b) || path_a == path_b;
1172    let mut components_a = path_a.components();
1173    let mut components_b = path_b.components();
1174
1175    loop {
1176        match (components_a.next(), components_b.next()) {
1177            (Some(component_a), Some(component_b)) => {
1178                let a_leaf_file = a_is_file && components_a.rest().is_empty();
1179                let b_leaf_file = b_is_file && components_b.rest().is_empty();
1180
1181                let (a_stem, a_ext) = a_leaf_file
1182                    .then(|| stem_and_extension(component_a))
1183                    .unwrap_or_default();
1184                let (b_stem, b_ext) = b_leaf_file
1185                    .then(|| stem_and_extension(component_b))
1186                    .unwrap_or_default();
1187                let a_key = if a_leaf_file {
1188                    a_stem
1189                } else {
1190                    Some(component_a)
1191                };
1192                let b_key = if b_leaf_file {
1193                    b_stem
1194                } else {
1195                    Some(component_b)
1196                };
1197
1198                let ordering = match (a_key, b_key) {
1199                    (Some(a), Some(b)) => natural_sort_no_tiebreak(a, b)
1200                        .then_with(|| match (a_leaf_file, b_leaf_file) {
1201                            (true, false) if a.eq_ignore_ascii_case(b) => Ordering::Greater,
1202                            (false, true) if a.eq_ignore_ascii_case(b) => Ordering::Less,
1203                            _ => Ordering::Equal,
1204                        })
1205                        .then_with(|| {
1206                            if a_leaf_file && b_leaf_file {
1207                                let a_ext_str = a_ext.unwrap_or_default().to_lowercase();
1208                                let b_ext_str = b_ext.unwrap_or_default().to_lowercase();
1209                                b_ext_str.cmp(&a_ext_str)
1210                            } else {
1211                                Ordering::Equal
1212                            }
1213                        }),
1214                    (Some(_), None) => Ordering::Greater,
1215                    (None, Some(_)) => Ordering::Less,
1216                    (None, None) => Ordering::Equal,
1217                };
1218
1219                if !ordering.is_eq() {
1220                    return ordering;
1221                }
1222            }
1223            (Some(_), None) => return Ordering::Greater,
1224            (None, Some(_)) => return Ordering::Less,
1225            (None, None) => {
1226                // Deterministic tie-break: use natural sort to prefer lowercase when paths
1227                // are otherwise equal but still differ in casing.
1228                if !original_paths_equal {
1229                    return natural_sort(path_a.as_unix_str(), path_b.as_unix_str());
1230                }
1231                return Ordering::Equal;
1232            }
1233        }
1234    }
1235}
1236
1237/// Compare two relative paths with files before directories using
1238/// case-insensitive natural sorting. At each directory level, all files
1239/// are sorted before all directories, with case-insensitive alphabetical
1240/// ordering within each group.
1241pub fn compare_rel_paths_files_first(
1242    (path_a, a_is_file): (&RelPath, bool),
1243    (path_b, b_is_file): (&RelPath, bool),
1244) -> Ordering {
1245    let original_paths_equal = std::ptr::eq(path_a, path_b) || path_a == path_b;
1246    let mut components_a = path_a.components();
1247    let mut components_b = path_b.components();
1248
1249    loop {
1250        match (components_a.next(), components_b.next()) {
1251            (Some(component_a), Some(component_b)) => {
1252                let a_leaf_file = a_is_file && components_a.rest().is_empty();
1253                let b_leaf_file = b_is_file && components_b.rest().is_empty();
1254
1255                let (a_stem, a_ext) = a_leaf_file
1256                    .then(|| stem_and_extension(component_a))
1257                    .unwrap_or_default();
1258                let (b_stem, b_ext) = b_leaf_file
1259                    .then(|| stem_and_extension(component_b))
1260                    .unwrap_or_default();
1261                let a_key = if a_leaf_file {
1262                    a_stem
1263                } else {
1264                    Some(component_a)
1265                };
1266                let b_key = if b_leaf_file {
1267                    b_stem
1268                } else {
1269                    Some(component_b)
1270                };
1271
1272                let ordering = match (a_key, b_key) {
1273                    (Some(a), Some(b)) => {
1274                        if a_leaf_file && !b_leaf_file {
1275                            Ordering::Less
1276                        } else if !a_leaf_file && b_leaf_file {
1277                            Ordering::Greater
1278                        } else {
1279                            natural_sort_no_tiebreak(a, b).then_with(|| {
1280                                if a_leaf_file && b_leaf_file {
1281                                    let a_ext_str = a_ext.unwrap_or_default().to_lowercase();
1282                                    let b_ext_str = b_ext.unwrap_or_default().to_lowercase();
1283                                    a_ext_str.cmp(&b_ext_str)
1284                                } else {
1285                                    Ordering::Equal
1286                                }
1287                            })
1288                        }
1289                    }
1290                    (Some(_), None) => Ordering::Greater,
1291                    (None, Some(_)) => Ordering::Less,
1292                    (None, None) => Ordering::Equal,
1293                };
1294
1295                if !ordering.is_eq() {
1296                    return ordering;
1297                }
1298            }
1299            (Some(_), None) => return Ordering::Greater,
1300            (None, Some(_)) => return Ordering::Less,
1301            (None, None) => {
1302                // Deterministic tie-break: use natural sort to prefer lowercase when paths
1303                // are otherwise equal but still differ in casing.
1304                if !original_paths_equal {
1305                    return natural_sort(path_a.as_unix_str(), path_b.as_unix_str());
1306                }
1307                return Ordering::Equal;
1308            }
1309        }
1310    }
1311}
1312
1313pub fn compare_paths(
1314    (path_a, a_is_file): (&Path, bool),
1315    (path_b, b_is_file): (&Path, bool),
1316) -> Ordering {
1317    let mut components_a = path_a.components().peekable();
1318    let mut components_b = path_b.components().peekable();
1319
1320    loop {
1321        match (components_a.next(), components_b.next()) {
1322            (Some(component_a), Some(component_b)) => {
1323                let a_is_file = components_a.peek().is_none() && a_is_file;
1324                let b_is_file = components_b.peek().is_none() && b_is_file;
1325
1326                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
1327                    let path_a = Path::new(component_a.as_os_str());
1328                    let path_string_a = if a_is_file {
1329                        path_a.file_stem()
1330                    } else {
1331                        path_a.file_name()
1332                    }
1333                    .map(|s| s.to_string_lossy());
1334
1335                    let path_b = Path::new(component_b.as_os_str());
1336                    let path_string_b = if b_is_file {
1337                        path_b.file_stem()
1338                    } else {
1339                        path_b.file_name()
1340                    }
1341                    .map(|s| s.to_string_lossy());
1342
1343                    let compare_components = match (path_string_a, path_string_b) {
1344                        (Some(a), Some(b)) => natural_sort(&a, &b),
1345                        (Some(_), None) => Ordering::Greater,
1346                        (None, Some(_)) => Ordering::Less,
1347                        (None, None) => Ordering::Equal,
1348                    };
1349
1350                    compare_components.then_with(|| {
1351                        if a_is_file && b_is_file {
1352                            let ext_a = path_a.extension().unwrap_or_default();
1353                            let ext_b = path_b.extension().unwrap_or_default();
1354                            ext_a.cmp(ext_b)
1355                        } else {
1356                            Ordering::Equal
1357                        }
1358                    })
1359                });
1360
1361                if !ordering.is_eq() {
1362                    return ordering;
1363                }
1364            }
1365            (Some(_), None) => break Ordering::Greater,
1366            (None, Some(_)) => break Ordering::Less,
1367            (None, None) => break Ordering::Equal,
1368        }
1369    }
1370}
1371
1372#[derive(Debug, Clone, PartialEq, Eq)]
1373pub struct WslPath {
1374    pub distro: String,
1375
1376    // the reason this is an OsString and not any of the path types is that it needs to
1377    // represent a unix path (with '/' separators) on windows. `from_path` does this by
1378    // manually constructing it from the path components of a given windows path.
1379    pub path: std::ffi::OsString,
1380}
1381
1382impl WslPath {
1383    pub fn from_path<P: AsRef<Path>>(path: P) -> Option<WslPath> {
1384        if cfg!(not(target_os = "windows")) {
1385            return None;
1386        }
1387        use std::{
1388            ffi::OsString,
1389            path::{Component, Prefix},
1390        };
1391
1392        let mut components = path.as_ref().components();
1393        let Some(Component::Prefix(prefix)) = components.next() else {
1394            return None;
1395        };
1396        let (server, distro) = match prefix.kind() {
1397            Prefix::UNC(server, distro) => (server, distro),
1398            Prefix::VerbatimUNC(server, distro) => (server, distro),
1399            _ => return None,
1400        };
1401        let Some(Component::RootDir) = components.next() else {
1402            return None;
1403        };
1404
1405        let server_str = server.to_string_lossy();
1406        if server_str == "wsl.localhost" || server_str == "wsl$" {
1407            let mut result = OsString::from("");
1408            for c in components {
1409                use Component::*;
1410                match c {
1411                    Prefix(p) => unreachable!("got {p:?}, but already stripped prefix"),
1412                    RootDir => unreachable!("got root dir, but already stripped root"),
1413                    CurDir => continue,
1414                    ParentDir => result.push("/.."),
1415                    Normal(s) => {
1416                        result.push("/");
1417                        result.push(s);
1418                    }
1419                }
1420            }
1421            if result.is_empty() {
1422                result.push("/");
1423            }
1424            Some(WslPath {
1425                distro: distro.to_string_lossy().to_string(),
1426                path: result,
1427            })
1428        } else {
1429            None
1430        }
1431    }
1432}
1433
1434pub trait UrlExt {
1435    /// A version of `url::Url::to_file_path` that does platform handling based on the provided `PathStyle` instead of the host platform.
1436    ///
1437    /// 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.
1438    fn to_file_path_ext(&self, path_style: PathStyle) -> Result<PathBuf, ()>;
1439}
1440
1441impl UrlExt for url::Url {
1442    // Copied from `url::Url::to_file_path`, but the `cfg` handling is replaced with runtime branching on `PathStyle`
1443    fn to_file_path_ext(&self, source_path_style: PathStyle) -> Result<PathBuf, ()> {
1444        if let Some(segments) = self.path_segments() {
1445            let host = match self.host() {
1446                None | Some(url::Host::Domain("localhost")) => None,
1447                Some(_) if source_path_style.is_windows() && self.scheme() == "file" => {
1448                    self.host_str()
1449                }
1450                _ => return Err(()),
1451            };
1452
1453            let str_len = self.as_str().len();
1454            let estimated_capacity = if source_path_style.is_windows() {
1455                // remove scheme: - has possible \\ for hostname
1456                str_len.saturating_sub(self.scheme().len() + 1)
1457            } else {
1458                // remove scheme://
1459                str_len.saturating_sub(self.scheme().len() + 3)
1460            };
1461            return match source_path_style {
1462                PathStyle::Posix => {
1463                    file_url_segments_to_pathbuf_posix(estimated_capacity, host, segments)
1464                }
1465                PathStyle::Windows => {
1466                    file_url_segments_to_pathbuf_windows(estimated_capacity, host, segments)
1467                }
1468            };
1469        }
1470
1471        fn file_url_segments_to_pathbuf_posix(
1472            estimated_capacity: usize,
1473            host: Option<&str>,
1474            segments: std::str::Split<'_, char>,
1475        ) -> Result<PathBuf, ()> {
1476            use percent_encoding::percent_decode;
1477
1478            if host.is_some() {
1479                return Err(());
1480            }
1481
1482            let mut bytes = Vec::new();
1483            bytes.try_reserve(estimated_capacity).map_err(|_| ())?;
1484
1485            for segment in segments {
1486                bytes.push(b'/');
1487                bytes.extend(percent_decode(segment.as_bytes()));
1488            }
1489
1490            // A windows drive letter must end with a slash.
1491            if bytes.len() > 2
1492                && bytes[bytes.len() - 2].is_ascii_alphabetic()
1493                && matches!(bytes[bytes.len() - 1], b':' | b'|')
1494            {
1495                bytes.push(b'/');
1496            }
1497
1498            let path = String::from_utf8(bytes).map_err(|_| ())?;
1499            debug_assert!(
1500                PathStyle::Posix.is_absolute(&path),
1501                "to_file_path() failed to produce an absolute Path"
1502            );
1503
1504            Ok(PathBuf::from(path))
1505        }
1506
1507        fn file_url_segments_to_pathbuf_windows(
1508            estimated_capacity: usize,
1509            host: Option<&str>,
1510            mut segments: std::str::Split<'_, char>,
1511        ) -> Result<PathBuf, ()> {
1512            use percent_encoding::percent_decode_str;
1513            let mut string = String::new();
1514            string.try_reserve(estimated_capacity).map_err(|_| ())?;
1515            if let Some(host) = host {
1516                string.push_str(r"\\");
1517                string.push_str(host);
1518            } else {
1519                let first = segments.next().ok_or(())?;
1520
1521                match first.len() {
1522                    2 => {
1523                        if !first.starts_with(|c| char::is_ascii_alphabetic(&c))
1524                            || first.as_bytes()[1] != b':'
1525                        {
1526                            return Err(());
1527                        }
1528
1529                        string.push_str(first);
1530                    }
1531
1532                    4 => {
1533                        if !first.starts_with(|c| char::is_ascii_alphabetic(&c)) {
1534                            return Err(());
1535                        }
1536                        let bytes = first.as_bytes();
1537                        if bytes[1] != b'%'
1538                            || bytes[2] != b'3'
1539                            || (bytes[3] != b'a' && bytes[3] != b'A')
1540                        {
1541                            return Err(());
1542                        }
1543
1544                        string.push_str(&first[0..1]);
1545                        string.push(':');
1546                    }
1547
1548                    _ => return Err(()),
1549                }
1550            };
1551
1552            for segment in segments {
1553                string.push('\\');
1554
1555                // Currently non-unicode windows paths cannot be represented
1556                match percent_decode_str(segment).decode_utf8() {
1557                    Ok(s) => string.push_str(&s),
1558                    Err(..) => return Err(()),
1559                }
1560            }
1561            // ensure our estimated capacity was good
1562            if cfg!(test) {
1563                debug_assert!(
1564                    string.len() <= estimated_capacity,
1565                    "len: {}, capacity: {}",
1566                    string.len(),
1567                    estimated_capacity
1568                );
1569            }
1570            debug_assert!(
1571                PathStyle::Windows.is_absolute(&string),
1572                "to_file_path() failed to produce an absolute Path"
1573            );
1574            let path = PathBuf::from(string);
1575            Ok(path)
1576        }
1577        Err(())
1578    }
1579}
1580
1581#[cfg(test)]
1582mod tests {
1583    use crate::rel_path::rel_path;
1584
1585    use super::*;
1586    use util_macros::perf;
1587
1588    #[perf]
1589    fn compare_paths_with_dots() {
1590        let mut paths = vec![
1591            (Path::new("test_dirs"), false),
1592            (Path::new("test_dirs/1.46"), false),
1593            (Path::new("test_dirs/1.46/bar_1"), true),
1594            (Path::new("test_dirs/1.46/bar_2"), true),
1595            (Path::new("test_dirs/1.45"), false),
1596            (Path::new("test_dirs/1.45/foo_2"), true),
1597            (Path::new("test_dirs/1.45/foo_1"), true),
1598        ];
1599        paths.sort_by(|&a, &b| compare_paths(a, b));
1600        assert_eq!(
1601            paths,
1602            vec![
1603                (Path::new("test_dirs"), false),
1604                (Path::new("test_dirs/1.45"), false),
1605                (Path::new("test_dirs/1.45/foo_1"), true),
1606                (Path::new("test_dirs/1.45/foo_2"), true),
1607                (Path::new("test_dirs/1.46"), false),
1608                (Path::new("test_dirs/1.46/bar_1"), true),
1609                (Path::new("test_dirs/1.46/bar_2"), true),
1610            ]
1611        );
1612        let mut paths = vec![
1613            (Path::new("root1/one.txt"), true),
1614            (Path::new("root1/one.two.txt"), true),
1615        ];
1616        paths.sort_by(|&a, &b| compare_paths(a, b));
1617        assert_eq!(
1618            paths,
1619            vec![
1620                (Path::new("root1/one.txt"), true),
1621                (Path::new("root1/one.two.txt"), true),
1622            ]
1623        );
1624    }
1625
1626    #[perf]
1627    fn compare_paths_with_same_name_different_extensions() {
1628        let mut paths = vec![
1629            (Path::new("test_dirs/file.rs"), true),
1630            (Path::new("test_dirs/file.txt"), true),
1631            (Path::new("test_dirs/file.md"), true),
1632            (Path::new("test_dirs/file"), true),
1633            (Path::new("test_dirs/file.a"), true),
1634        ];
1635        paths.sort_by(|&a, &b| compare_paths(a, b));
1636        assert_eq!(
1637            paths,
1638            vec![
1639                (Path::new("test_dirs/file"), true),
1640                (Path::new("test_dirs/file.a"), true),
1641                (Path::new("test_dirs/file.md"), true),
1642                (Path::new("test_dirs/file.rs"), true),
1643                (Path::new("test_dirs/file.txt"), true),
1644            ]
1645        );
1646    }
1647
1648    #[perf]
1649    fn compare_paths_case_semi_sensitive() {
1650        let mut paths = vec![
1651            (Path::new("test_DIRS"), false),
1652            (Path::new("test_DIRS/foo_1"), true),
1653            (Path::new("test_DIRS/foo_2"), true),
1654            (Path::new("test_DIRS/bar"), true),
1655            (Path::new("test_DIRS/BAR"), true),
1656            (Path::new("test_dirs"), false),
1657            (Path::new("test_dirs/foo_1"), true),
1658            (Path::new("test_dirs/foo_2"), true),
1659            (Path::new("test_dirs/bar"), true),
1660            (Path::new("test_dirs/BAR"), true),
1661        ];
1662        paths.sort_by(|&a, &b| compare_paths(a, b));
1663        assert_eq!(
1664            paths,
1665            vec![
1666                (Path::new("test_dirs"), false),
1667                (Path::new("test_dirs/bar"), true),
1668                (Path::new("test_dirs/BAR"), true),
1669                (Path::new("test_dirs/foo_1"), true),
1670                (Path::new("test_dirs/foo_2"), true),
1671                (Path::new("test_DIRS"), false),
1672                (Path::new("test_DIRS/bar"), true),
1673                (Path::new("test_DIRS/BAR"), true),
1674                (Path::new("test_DIRS/foo_1"), true),
1675                (Path::new("test_DIRS/foo_2"), true),
1676            ]
1677        );
1678    }
1679
1680    #[perf]
1681    fn compare_paths_mixed_case_numeric_ordering() {
1682        let mut entries = [
1683            (Path::new(".config"), false),
1684            (Path::new("Dir1"), false),
1685            (Path::new("dir01"), false),
1686            (Path::new("dir2"), false),
1687            (Path::new("Dir02"), false),
1688            (Path::new("dir10"), false),
1689            (Path::new("Dir10"), false),
1690        ];
1691
1692        entries.sort_by(|&a, &b| compare_paths(a, b));
1693
1694        let ordered: Vec<&str> = entries
1695            .iter()
1696            .map(|(path, _)| path.to_str().unwrap())
1697            .collect();
1698
1699        assert_eq!(
1700            ordered,
1701            vec![
1702                ".config", "Dir1", "dir01", "dir2", "Dir02", "dir10", "Dir10"
1703            ]
1704        );
1705    }
1706
1707    #[perf]
1708    fn compare_rel_paths_mixed_case_insensitive() {
1709        // Test that mixed mode is case-insensitive
1710        let mut paths = vec![
1711            (RelPath::unix("zebra.txt").unwrap(), true),
1712            (RelPath::unix("Apple").unwrap(), false),
1713            (RelPath::unix("banana.rs").unwrap(), true),
1714            (RelPath::unix("Carrot").unwrap(), false),
1715            (RelPath::unix("aardvark.txt").unwrap(), true),
1716        ];
1717        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1718        // Case-insensitive: aardvark < Apple < banana < Carrot < zebra
1719        assert_eq!(
1720            paths,
1721            vec![
1722                (RelPath::unix("aardvark.txt").unwrap(), true),
1723                (RelPath::unix("Apple").unwrap(), false),
1724                (RelPath::unix("banana.rs").unwrap(), true),
1725                (RelPath::unix("Carrot").unwrap(), false),
1726                (RelPath::unix("zebra.txt").unwrap(), true),
1727            ]
1728        );
1729    }
1730
1731    #[perf]
1732    fn compare_rel_paths_files_first_basic() {
1733        // Test that files come before directories
1734        let mut paths = vec![
1735            (RelPath::unix("zebra.txt").unwrap(), true),
1736            (RelPath::unix("Apple").unwrap(), false),
1737            (RelPath::unix("banana.rs").unwrap(), true),
1738            (RelPath::unix("Carrot").unwrap(), false),
1739            (RelPath::unix("aardvark.txt").unwrap(), true),
1740        ];
1741        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1742        // Files first (case-insensitive), then directories (case-insensitive)
1743        assert_eq!(
1744            paths,
1745            vec![
1746                (RelPath::unix("aardvark.txt").unwrap(), true),
1747                (RelPath::unix("banana.rs").unwrap(), true),
1748                (RelPath::unix("zebra.txt").unwrap(), true),
1749                (RelPath::unix("Apple").unwrap(), false),
1750                (RelPath::unix("Carrot").unwrap(), false),
1751            ]
1752        );
1753    }
1754
1755    #[perf]
1756    fn compare_rel_paths_files_first_case_insensitive() {
1757        // Test case-insensitive sorting within files and directories
1758        let mut paths = vec![
1759            (RelPath::unix("Zebra.txt").unwrap(), true),
1760            (RelPath::unix("apple").unwrap(), false),
1761            (RelPath::unix("Banana.rs").unwrap(), true),
1762            (RelPath::unix("carrot").unwrap(), false),
1763            (RelPath::unix("Aardvark.txt").unwrap(), true),
1764        ];
1765        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1766        assert_eq!(
1767            paths,
1768            vec![
1769                (RelPath::unix("Aardvark.txt").unwrap(), true),
1770                (RelPath::unix("Banana.rs").unwrap(), true),
1771                (RelPath::unix("Zebra.txt").unwrap(), true),
1772                (RelPath::unix("apple").unwrap(), false),
1773                (RelPath::unix("carrot").unwrap(), false),
1774            ]
1775        );
1776    }
1777
1778    #[perf]
1779    fn compare_rel_paths_files_first_numeric() {
1780        // Test natural number sorting with files first
1781        let mut paths = vec![
1782            (RelPath::unix("file10.txt").unwrap(), true),
1783            (RelPath::unix("dir2").unwrap(), false),
1784            (RelPath::unix("file2.txt").unwrap(), true),
1785            (RelPath::unix("dir10").unwrap(), false),
1786            (RelPath::unix("file1.txt").unwrap(), true),
1787        ];
1788        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1789        assert_eq!(
1790            paths,
1791            vec![
1792                (RelPath::unix("file1.txt").unwrap(), true),
1793                (RelPath::unix("file2.txt").unwrap(), true),
1794                (RelPath::unix("file10.txt").unwrap(), true),
1795                (RelPath::unix("dir2").unwrap(), false),
1796                (RelPath::unix("dir10").unwrap(), false),
1797            ]
1798        );
1799    }
1800
1801    #[perf]
1802    fn compare_rel_paths_mixed_case() {
1803        // Test case-insensitive sorting with varied capitalization
1804        let mut paths = vec![
1805            (RelPath::unix("README.md").unwrap(), true),
1806            (RelPath::unix("readme.txt").unwrap(), true),
1807            (RelPath::unix("ReadMe.rs").unwrap(), true),
1808        ];
1809        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1810        // All "readme" variants should group together, sorted by extension
1811        assert_eq!(
1812            paths,
1813            vec![
1814                (RelPath::unix("readme.txt").unwrap(), true),
1815                (RelPath::unix("ReadMe.rs").unwrap(), true),
1816                (RelPath::unix("README.md").unwrap(), true),
1817            ]
1818        );
1819    }
1820
1821    #[perf]
1822    fn compare_rel_paths_mixed_files_and_dirs() {
1823        // Verify directories and files are still mixed
1824        let mut paths = vec![
1825            (RelPath::unix("file2.txt").unwrap(), true),
1826            (RelPath::unix("Dir1").unwrap(), false),
1827            (RelPath::unix("file1.txt").unwrap(), true),
1828            (RelPath::unix("dir2").unwrap(), false),
1829        ];
1830        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1831        // Case-insensitive: dir1, dir2, file1, file2 (all mixed)
1832        assert_eq!(
1833            paths,
1834            vec![
1835                (RelPath::unix("Dir1").unwrap(), false),
1836                (RelPath::unix("dir2").unwrap(), false),
1837                (RelPath::unix("file1.txt").unwrap(), true),
1838                (RelPath::unix("file2.txt").unwrap(), true),
1839            ]
1840        );
1841    }
1842
1843    #[perf]
1844    fn compare_rel_paths_mixed_same_name_different_case_file_and_dir() {
1845        let mut paths = vec![
1846            (RelPath::unix("Hello.txt").unwrap(), true),
1847            (RelPath::unix("hello").unwrap(), false),
1848        ];
1849        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1850        assert_eq!(
1851            paths,
1852            vec![
1853                (RelPath::unix("hello").unwrap(), false),
1854                (RelPath::unix("Hello.txt").unwrap(), true),
1855            ]
1856        );
1857
1858        let mut paths = vec![
1859            (RelPath::unix("hello").unwrap(), false),
1860            (RelPath::unix("Hello.txt").unwrap(), true),
1861        ];
1862        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1863        assert_eq!(
1864            paths,
1865            vec![
1866                (RelPath::unix("hello").unwrap(), false),
1867                (RelPath::unix("Hello.txt").unwrap(), true),
1868            ]
1869        );
1870    }
1871
1872    #[perf]
1873    fn compare_rel_paths_mixed_with_nested_paths() {
1874        // Test that nested paths still work correctly
1875        let mut paths = vec![
1876            (RelPath::unix("src/main.rs").unwrap(), true),
1877            (RelPath::unix("Cargo.toml").unwrap(), true),
1878            (RelPath::unix("src").unwrap(), false),
1879            (RelPath::unix("target").unwrap(), false),
1880        ];
1881        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1882        assert_eq!(
1883            paths,
1884            vec![
1885                (RelPath::unix("Cargo.toml").unwrap(), true),
1886                (RelPath::unix("src").unwrap(), false),
1887                (RelPath::unix("src/main.rs").unwrap(), true),
1888                (RelPath::unix("target").unwrap(), false),
1889            ]
1890        );
1891    }
1892
1893    #[perf]
1894    fn compare_rel_paths_files_first_with_nested() {
1895        // Files come before directories, even with nested paths
1896        let mut paths = vec![
1897            (RelPath::unix("src/lib.rs").unwrap(), true),
1898            (RelPath::unix("README.md").unwrap(), true),
1899            (RelPath::unix("src").unwrap(), false),
1900            (RelPath::unix("tests").unwrap(), false),
1901        ];
1902        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1903        assert_eq!(
1904            paths,
1905            vec![
1906                (RelPath::unix("README.md").unwrap(), true),
1907                (RelPath::unix("src").unwrap(), false),
1908                (RelPath::unix("src/lib.rs").unwrap(), true),
1909                (RelPath::unix("tests").unwrap(), false),
1910            ]
1911        );
1912    }
1913
1914    #[perf]
1915    fn compare_rel_paths_mixed_dotfiles() {
1916        // Test that dotfiles are handled correctly in mixed mode
1917        let mut paths = vec![
1918            (RelPath::unix(".gitignore").unwrap(), true),
1919            (RelPath::unix("README.md").unwrap(), true),
1920            (RelPath::unix(".github").unwrap(), false),
1921            (RelPath::unix("src").unwrap(), false),
1922        ];
1923        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1924        assert_eq!(
1925            paths,
1926            vec![
1927                (RelPath::unix(".github").unwrap(), false),
1928                (RelPath::unix(".gitignore").unwrap(), true),
1929                (RelPath::unix("README.md").unwrap(), true),
1930                (RelPath::unix("src").unwrap(), false),
1931            ]
1932        );
1933    }
1934
1935    #[perf]
1936    fn compare_rel_paths_files_first_dotfiles() {
1937        // Test that dotfiles come first when they're files
1938        let mut paths = vec![
1939            (RelPath::unix(".gitignore").unwrap(), true),
1940            (RelPath::unix("README.md").unwrap(), true),
1941            (RelPath::unix(".github").unwrap(), false),
1942            (RelPath::unix("src").unwrap(), false),
1943        ];
1944        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1945        assert_eq!(
1946            paths,
1947            vec![
1948                (RelPath::unix(".gitignore").unwrap(), true),
1949                (RelPath::unix("README.md").unwrap(), true),
1950                (RelPath::unix(".github").unwrap(), false),
1951                (RelPath::unix("src").unwrap(), false),
1952            ]
1953        );
1954    }
1955
1956    #[perf]
1957    fn compare_rel_paths_mixed_same_stem_different_extension() {
1958        // Files with same stem but different extensions should sort by extension
1959        let mut paths = vec![
1960            (RelPath::unix("file.rs").unwrap(), true),
1961            (RelPath::unix("file.md").unwrap(), true),
1962            (RelPath::unix("file.txt").unwrap(), true),
1963        ];
1964        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1965        assert_eq!(
1966            paths,
1967            vec![
1968                (RelPath::unix("file.txt").unwrap(), true),
1969                (RelPath::unix("file.rs").unwrap(), true),
1970                (RelPath::unix("file.md").unwrap(), true),
1971            ]
1972        );
1973    }
1974
1975    #[perf]
1976    fn compare_rel_paths_files_first_same_stem() {
1977        // Same stem files should still sort by extension with files_first
1978        let mut paths = vec![
1979            (RelPath::unix("main.rs").unwrap(), true),
1980            (RelPath::unix("main.c").unwrap(), true),
1981            (RelPath::unix("main").unwrap(), false),
1982        ];
1983        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
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_mixed(a, b));
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 path_with_position_parse_posix_path() {
2017        // Test POSIX filename edge cases
2018        // Read more at https://en.wikipedia.org/wiki/Filename
2019        assert_eq!(
2020            PathWithPosition::parse_str("test_file"),
2021            PathWithPosition {
2022                path: PathBuf::from("test_file"),
2023                row: None,
2024                column: None
2025            }
2026        );
2027
2028        assert_eq!(
2029            PathWithPosition::parse_str("a:bc:.zip:1"),
2030            PathWithPosition {
2031                path: PathBuf::from("a:bc:.zip"),
2032                row: Some(1),
2033                column: None
2034            }
2035        );
2036
2037        assert_eq!(
2038            PathWithPosition::parse_str("one.second.zip:1"),
2039            PathWithPosition {
2040                path: PathBuf::from("one.second.zip"),
2041                row: Some(1),
2042                column: None
2043            }
2044        );
2045
2046        // Trim off trailing `:`s for otherwise valid input.
2047        assert_eq!(
2048            PathWithPosition::parse_str("test_file:10:1:"),
2049            PathWithPosition {
2050                path: PathBuf::from("test_file"),
2051                row: Some(10),
2052                column: Some(1)
2053            }
2054        );
2055
2056        assert_eq!(
2057            PathWithPosition::parse_str("test_file.rs:"),
2058            PathWithPosition {
2059                path: PathBuf::from("test_file.rs"),
2060                row: None,
2061                column: None
2062            }
2063        );
2064
2065        assert_eq!(
2066            PathWithPosition::parse_str("test_file.rs:1:"),
2067            PathWithPosition {
2068                path: PathBuf::from("test_file.rs"),
2069                row: Some(1),
2070                column: None
2071            }
2072        );
2073
2074        assert_eq!(
2075            PathWithPosition::parse_str("ab\ncd"),
2076            PathWithPosition {
2077                path: PathBuf::from("ab\ncd"),
2078                row: None,
2079                column: None
2080            }
2081        );
2082
2083        assert_eq!(
2084            PathWithPosition::parse_str("👋\nab"),
2085            PathWithPosition {
2086                path: PathBuf::from("👋\nab"),
2087                row: None,
2088                column: None
2089            }
2090        );
2091
2092        assert_eq!(
2093            PathWithPosition::parse_str("Types.hs:(617,9)-(670,28):"),
2094            PathWithPosition {
2095                path: PathBuf::from("Types.hs"),
2096                row: Some(617),
2097                column: Some(9),
2098            }
2099        );
2100    }
2101
2102    #[perf]
2103    #[cfg(not(target_os = "windows"))]
2104    fn path_with_position_parse_posix_path_with_suffix() {
2105        assert_eq!(
2106            PathWithPosition::parse_str("foo/bar:34:in"),
2107            PathWithPosition {
2108                path: PathBuf::from("foo/bar"),
2109                row: Some(34),
2110                column: None,
2111            }
2112        );
2113        assert_eq!(
2114            PathWithPosition::parse_str("foo/bar.rs:1902:::15:"),
2115            PathWithPosition {
2116                path: PathBuf::from("foo/bar.rs:1902"),
2117                row: Some(15),
2118                column: None
2119            }
2120        );
2121
2122        assert_eq!(
2123            PathWithPosition::parse_str("app-editors:zed-0.143.6:20240710-201212.log:34:"),
2124            PathWithPosition {
2125                path: PathBuf::from("app-editors:zed-0.143.6:20240710-201212.log"),
2126                row: Some(34),
2127                column: None,
2128            }
2129        );
2130
2131        assert_eq!(
2132            PathWithPosition::parse_str("crates/file_finder/src/file_finder.rs:1902:13:"),
2133            PathWithPosition {
2134                path: PathBuf::from("crates/file_finder/src/file_finder.rs"),
2135                row: Some(1902),
2136                column: Some(13),
2137            }
2138        );
2139
2140        assert_eq!(
2141            PathWithPosition::parse_str("crate/utils/src/test:today.log:34"),
2142            PathWithPosition {
2143                path: PathBuf::from("crate/utils/src/test:today.log"),
2144                row: Some(34),
2145                column: None,
2146            }
2147        );
2148        assert_eq!(
2149            PathWithPosition::parse_str("/testing/out/src/file_finder.odin(7:15)"),
2150            PathWithPosition {
2151                path: PathBuf::from("/testing/out/src/file_finder.odin"),
2152                row: Some(7),
2153                column: Some(15),
2154            }
2155        );
2156    }
2157
2158    #[perf]
2159    #[cfg(target_os = "windows")]
2160    fn path_with_position_parse_windows_path() {
2161        assert_eq!(
2162            PathWithPosition::parse_str("crates\\utils\\paths.rs"),
2163            PathWithPosition {
2164                path: PathBuf::from("crates\\utils\\paths.rs"),
2165                row: None,
2166                column: None
2167            }
2168        );
2169
2170        assert_eq!(
2171            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs"),
2172            PathWithPosition {
2173                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2174                row: None,
2175                column: None
2176            }
2177        );
2178    }
2179
2180    #[perf]
2181    #[cfg(target_os = "windows")]
2182    fn path_with_position_parse_windows_path_with_suffix() {
2183        assert_eq!(
2184            PathWithPosition::parse_str("crates\\utils\\paths.rs:101"),
2185            PathWithPosition {
2186                path: PathBuf::from("crates\\utils\\paths.rs"),
2187                row: Some(101),
2188                column: None
2189            }
2190        );
2191
2192        assert_eq!(
2193            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1:20"),
2194            PathWithPosition {
2195                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2196                row: Some(1),
2197                column: Some(20)
2198            }
2199        );
2200
2201        assert_eq!(
2202            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13)"),
2203            PathWithPosition {
2204                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2205                row: Some(1902),
2206                column: Some(13)
2207            }
2208        );
2209
2210        // Trim off trailing `:`s for otherwise valid input.
2211        assert_eq!(
2212            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:"),
2213            PathWithPosition {
2214                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2215                row: Some(1902),
2216                column: Some(13)
2217            }
2218        );
2219
2220        assert_eq!(
2221            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:15:"),
2222            PathWithPosition {
2223                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
2224                row: Some(13),
2225                column: Some(15)
2226            }
2227        );
2228
2229        assert_eq!(
2230            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:::15:"),
2231            PathWithPosition {
2232                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
2233                row: Some(15),
2234                column: None
2235            }
2236        );
2237
2238        assert_eq!(
2239            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902,13):"),
2240            PathWithPosition {
2241                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2242                row: Some(1902),
2243                column: Some(13),
2244            }
2245        );
2246
2247        assert_eq!(
2248            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902):"),
2249            PathWithPosition {
2250                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2251                row: Some(1902),
2252                column: None,
2253            }
2254        );
2255
2256        assert_eq!(
2257            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs:1902:13:"),
2258            PathWithPosition {
2259                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2260                row: Some(1902),
2261                column: Some(13),
2262            }
2263        );
2264
2265        assert_eq!(
2266            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13):"),
2267            PathWithPosition {
2268                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2269                row: Some(1902),
2270                column: Some(13),
2271            }
2272        );
2273
2274        assert_eq!(
2275            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902):"),
2276            PathWithPosition {
2277                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2278                row: Some(1902),
2279                column: None,
2280            }
2281        );
2282
2283        assert_eq!(
2284            PathWithPosition::parse_str("crates/utils/paths.rs:101"),
2285            PathWithPosition {
2286                path: PathBuf::from("crates\\utils\\paths.rs"),
2287                row: Some(101),
2288                column: None,
2289            }
2290        );
2291    }
2292
2293    #[perf]
2294    fn test_path_compact() {
2295        let path: PathBuf = [
2296            home_dir().to_string_lossy().into_owned(),
2297            "some_file.txt".to_string(),
2298        ]
2299        .iter()
2300        .collect();
2301        if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
2302            assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
2303        } else {
2304            assert_eq!(path.compact().to_str(), path.to_str());
2305        }
2306    }
2307
2308    #[perf]
2309    fn test_extension_or_hidden_file_name() {
2310        // No dots in name
2311        let path = Path::new("/a/b/c/file_name.rs");
2312        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2313
2314        // Single dot in name
2315        let path = Path::new("/a/b/c/file.name.rs");
2316        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2317
2318        // Multiple dots in name
2319        let path = Path::new("/a/b/c/long.file.name.rs");
2320        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2321
2322        // Hidden file, no extension
2323        let path = Path::new("/a/b/c/.gitignore");
2324        assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
2325
2326        // Hidden file, with extension
2327        let path = Path::new("/a/b/c/.eslintrc.js");
2328        assert_eq!(path.extension_or_hidden_file_name(), Some("eslintrc.js"));
2329    }
2330
2331    #[perf]
2332    // fn edge_of_glob() {
2333    //     let path = Path::new("/work/node_modules");
2334    //     let path_matcher =
2335    //         PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
2336    //     assert!(
2337    //         path_matcher.is_match(path),
2338    //         "Path matcher should match {path:?}"
2339    //     );
2340    // }
2341
2342    // #[perf]
2343    // fn file_in_dirs() {
2344    //     let path = Path::new("/work/.env");
2345    //     let path_matcher = PathMatcher::new(&["**/.env".to_owned()], PathStyle::Posix).unwrap();
2346    //     assert!(
2347    //         path_matcher.is_match(path),
2348    //         "Path matcher should match {path:?}"
2349    //     );
2350    //     let path = Path::new("/work/package.json");
2351    //     assert!(
2352    //         !path_matcher.is_match(path),
2353    //         "Path matcher should not match {path:?}"
2354    //     );
2355    // }
2356
2357    // #[perf]
2358    // fn project_search() {
2359    //     let path = Path::new("/Users/someonetoignore/work/zed/zed.dev/node_modules");
2360    //     let path_matcher =
2361    //         PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
2362    //     assert!(
2363    //         path_matcher.is_match(path),
2364    //         "Path matcher should match {path:?}"
2365    //     );
2366    // }
2367    #[perf]
2368    #[cfg(target_os = "windows")]
2369    fn test_sanitized_path() {
2370        let path = Path::new("C:\\Users\\someone\\test_file.rs");
2371        let sanitized_path = SanitizedPath::new(path);
2372        assert_eq!(
2373            sanitized_path.to_string(),
2374            "C:\\Users\\someone\\test_file.rs"
2375        );
2376
2377        let path = Path::new("\\\\?\\C:\\Users\\someone\\test_file.rs");
2378        let sanitized_path = SanitizedPath::new(path);
2379        assert_eq!(
2380            sanitized_path.to_string(),
2381            "C:\\Users\\someone\\test_file.rs"
2382        );
2383    }
2384
2385    #[perf]
2386    fn test_compare_numeric_segments() {
2387        // Helper function to create peekable iterators and test
2388        fn compare(a: &str, b: &str) -> Ordering {
2389            let mut a_iter = a.chars().peekable();
2390            let mut b_iter = b.chars().peekable();
2391
2392            let result = compare_numeric_segments(&mut a_iter, &mut b_iter);
2393
2394            // Verify iterators advanced correctly
2395            assert!(
2396                !a_iter.next().is_some_and(|c| c.is_ascii_digit()),
2397                "Iterator a should have consumed all digits"
2398            );
2399            assert!(
2400                !b_iter.next().is_some_and(|c| c.is_ascii_digit()),
2401                "Iterator b should have consumed all digits"
2402            );
2403
2404            result
2405        }
2406
2407        // Basic numeric comparisons
2408        assert_eq!(compare("0", "0"), Ordering::Equal);
2409        assert_eq!(compare("1", "2"), Ordering::Less);
2410        assert_eq!(compare("9", "10"), Ordering::Less);
2411        assert_eq!(compare("10", "9"), Ordering::Greater);
2412        assert_eq!(compare("99", "100"), Ordering::Less);
2413
2414        // Leading zeros
2415        assert_eq!(compare("0", "00"), Ordering::Less);
2416        assert_eq!(compare("00", "0"), Ordering::Greater);
2417        assert_eq!(compare("01", "1"), Ordering::Greater);
2418        assert_eq!(compare("001", "1"), Ordering::Greater);
2419        assert_eq!(compare("001", "01"), Ordering::Greater);
2420
2421        // Same value different representation
2422        assert_eq!(compare("000100", "100"), Ordering::Greater);
2423        assert_eq!(compare("100", "0100"), Ordering::Less);
2424        assert_eq!(compare("0100", "00100"), Ordering::Less);
2425
2426        // Large numbers
2427        assert_eq!(compare("9999999999", "10000000000"), Ordering::Less);
2428        assert_eq!(
2429            compare(
2430                "340282366920938463463374607431768211455", // u128::MAX
2431                "340282366920938463463374607431768211456"
2432            ),
2433            Ordering::Less
2434        );
2435        assert_eq!(
2436            compare(
2437                "340282366920938463463374607431768211456", // > u128::MAX
2438                "340282366920938463463374607431768211455"
2439            ),
2440            Ordering::Greater
2441        );
2442
2443        // Iterator advancement verification
2444        let mut a_iter = "123abc".chars().peekable();
2445        let mut b_iter = "456def".chars().peekable();
2446
2447        compare_numeric_segments(&mut a_iter, &mut b_iter);
2448
2449        assert_eq!(a_iter.collect::<String>(), "abc");
2450        assert_eq!(b_iter.collect::<String>(), "def");
2451    }
2452
2453    #[perf]
2454    fn test_natural_sort() {
2455        // Basic alphanumeric
2456        assert_eq!(natural_sort("a", "b"), Ordering::Less);
2457        assert_eq!(natural_sort("b", "a"), Ordering::Greater);
2458        assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2459
2460        // Case sensitivity
2461        assert_eq!(natural_sort("a", "A"), Ordering::Less);
2462        assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2463        assert_eq!(natural_sort("aA", "aa"), Ordering::Greater);
2464        assert_eq!(natural_sort("aa", "aA"), Ordering::Less);
2465
2466        // Numbers
2467        assert_eq!(natural_sort("1", "2"), Ordering::Less);
2468        assert_eq!(natural_sort("2", "10"), Ordering::Less);
2469        assert_eq!(natural_sort("02", "10"), Ordering::Less);
2470        assert_eq!(natural_sort("02", "2"), Ordering::Greater);
2471
2472        // Mixed alphanumeric
2473        assert_eq!(natural_sort("a1", "a2"), Ordering::Less);
2474        assert_eq!(natural_sort("a2", "a10"), Ordering::Less);
2475        assert_eq!(natural_sort("a02", "a2"), Ordering::Greater);
2476        assert_eq!(natural_sort("a1b", "a1c"), Ordering::Less);
2477
2478        // Multiple numeric segments
2479        assert_eq!(natural_sort("1a2", "1a10"), Ordering::Less);
2480        assert_eq!(natural_sort("1a10", "1a2"), Ordering::Greater);
2481        assert_eq!(natural_sort("2a1", "10a1"), Ordering::Less);
2482
2483        // Special characters
2484        assert_eq!(natural_sort("a-1", "a-2"), Ordering::Less);
2485        assert_eq!(natural_sort("a_1", "a_2"), Ordering::Less);
2486        assert_eq!(natural_sort("a.1", "a.2"), Ordering::Less);
2487
2488        // Unicode
2489        assert_eq!(natural_sort("文1", "文2"), Ordering::Less);
2490        assert_eq!(natural_sort("文2", "文10"), Ordering::Less);
2491        assert_eq!(natural_sort("🔤1", "🔤2"), Ordering::Less);
2492
2493        // Empty and special cases
2494        assert_eq!(natural_sort("", ""), Ordering::Equal);
2495        assert_eq!(natural_sort("", "a"), Ordering::Less);
2496        assert_eq!(natural_sort("a", ""), Ordering::Greater);
2497        assert_eq!(natural_sort(" ", "  "), Ordering::Less);
2498
2499        // Mixed everything
2500        assert_eq!(natural_sort("File-1.txt", "File-2.txt"), Ordering::Less);
2501        assert_eq!(natural_sort("File-02.txt", "File-2.txt"), Ordering::Greater);
2502        assert_eq!(natural_sort("File-2.txt", "File-10.txt"), Ordering::Less);
2503        assert_eq!(natural_sort("File_A1", "File_A2"), Ordering::Less);
2504        assert_eq!(natural_sort("File_a1", "File_A1"), Ordering::Less);
2505    }
2506
2507    #[perf]
2508    fn test_compare_paths() {
2509        // Helper function for cleaner tests
2510        fn compare(a: &str, is_a_file: bool, b: &str, is_b_file: bool) -> Ordering {
2511            compare_paths((Path::new(a), is_a_file), (Path::new(b), is_b_file))
2512        }
2513
2514        // Basic path comparison
2515        assert_eq!(compare("a", true, "b", true), Ordering::Less);
2516        assert_eq!(compare("b", true, "a", true), Ordering::Greater);
2517        assert_eq!(compare("a", true, "a", true), Ordering::Equal);
2518
2519        // Files vs Directories
2520        assert_eq!(compare("a", true, "a", false), Ordering::Greater);
2521        assert_eq!(compare("a", false, "a", true), Ordering::Less);
2522        assert_eq!(compare("b", false, "a", true), Ordering::Less);
2523
2524        // Extensions
2525        assert_eq!(compare("a.txt", true, "a.md", true), Ordering::Greater);
2526        assert_eq!(compare("a.md", true, "a.txt", true), Ordering::Less);
2527        assert_eq!(compare("a", true, "a.txt", true), Ordering::Less);
2528
2529        // Nested paths
2530        assert_eq!(compare("dir/a", true, "dir/b", true), Ordering::Less);
2531        assert_eq!(compare("dir1/a", true, "dir2/a", true), Ordering::Less);
2532        assert_eq!(compare("dir/sub/a", true, "dir/a", true), Ordering::Less);
2533
2534        // Case sensitivity in paths
2535        assert_eq!(
2536            compare("Dir/file", true, "dir/file", true),
2537            Ordering::Greater
2538        );
2539        assert_eq!(
2540            compare("dir/File", true, "dir/file", true),
2541            Ordering::Greater
2542        );
2543        assert_eq!(compare("dir/file", true, "Dir/File", true), Ordering::Less);
2544
2545        // Hidden files and special names
2546        assert_eq!(compare(".hidden", true, "visible", true), Ordering::Less);
2547        assert_eq!(compare("_special", true, "normal", true), Ordering::Less);
2548        assert_eq!(compare(".config", false, ".data", false), Ordering::Less);
2549
2550        // Mixed numeric paths
2551        assert_eq!(
2552            compare("dir1/file", true, "dir2/file", true),
2553            Ordering::Less
2554        );
2555        assert_eq!(
2556            compare("dir2/file", true, "dir10/file", true),
2557            Ordering::Less
2558        );
2559        assert_eq!(
2560            compare("dir02/file", true, "dir2/file", true),
2561            Ordering::Greater
2562        );
2563
2564        // Root paths
2565        assert_eq!(compare("/a", true, "/b", true), Ordering::Less);
2566        assert_eq!(compare("/", false, "/a", true), Ordering::Less);
2567
2568        // Complex real-world examples
2569        assert_eq!(
2570            compare("project/src/main.rs", true, "project/src/lib.rs", true),
2571            Ordering::Greater
2572        );
2573        assert_eq!(
2574            compare(
2575                "project/tests/test_1.rs",
2576                true,
2577                "project/tests/test_2.rs",
2578                true
2579            ),
2580            Ordering::Less
2581        );
2582        assert_eq!(
2583            compare(
2584                "project/v1.0.0/README.md",
2585                true,
2586                "project/v1.10.0/README.md",
2587                true
2588            ),
2589            Ordering::Less
2590        );
2591    }
2592
2593    #[perf]
2594    fn test_natural_sort_case_sensitivity() {
2595        std::thread::sleep(std::time::Duration::from_millis(100));
2596        // Same letter different case - lowercase should come first
2597        assert_eq!(natural_sort("a", "A"), Ordering::Less);
2598        assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2599        assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2600        assert_eq!(natural_sort("A", "A"), Ordering::Equal);
2601
2602        // Mixed case strings
2603        assert_eq!(natural_sort("aaa", "AAA"), Ordering::Less);
2604        assert_eq!(natural_sort("AAA", "aaa"), Ordering::Greater);
2605        assert_eq!(natural_sort("aAa", "AaA"), Ordering::Less);
2606
2607        // Different letters
2608        assert_eq!(natural_sort("a", "b"), Ordering::Less);
2609        assert_eq!(natural_sort("A", "b"), Ordering::Less);
2610        assert_eq!(natural_sort("a", "B"), Ordering::Less);
2611    }
2612
2613    #[perf]
2614    fn test_natural_sort_with_numbers() {
2615        // Basic number ordering
2616        assert_eq!(natural_sort("file1", "file2"), Ordering::Less);
2617        assert_eq!(natural_sort("file2", "file10"), Ordering::Less);
2618        assert_eq!(natural_sort("file10", "file2"), Ordering::Greater);
2619
2620        // Numbers in different positions
2621        assert_eq!(natural_sort("1file", "2file"), Ordering::Less);
2622        assert_eq!(natural_sort("file1text", "file2text"), Ordering::Less);
2623        assert_eq!(natural_sort("text1file", "text2file"), Ordering::Less);
2624
2625        // Multiple numbers in string
2626        assert_eq!(natural_sort("file1-2", "file1-10"), Ordering::Less);
2627        assert_eq!(natural_sort("2-1file", "10-1file"), Ordering::Less);
2628
2629        // Leading zeros
2630        assert_eq!(natural_sort("file002", "file2"), Ordering::Greater);
2631        assert_eq!(natural_sort("file002", "file10"), Ordering::Less);
2632
2633        // Very large numbers
2634        assert_eq!(
2635            natural_sort("file999999999999999999999", "file999999999999999999998"),
2636            Ordering::Greater
2637        );
2638
2639        // u128 edge cases
2640
2641        // Numbers near u128::MAX (340,282,366,920,938,463,463,374,607,431,768,211,455)
2642        assert_eq!(
2643            natural_sort(
2644                "file340282366920938463463374607431768211454",
2645                "file340282366920938463463374607431768211455"
2646            ),
2647            Ordering::Less
2648        );
2649
2650        // Equal length numbers that overflow u128
2651        assert_eq!(
2652            natural_sort(
2653                "file340282366920938463463374607431768211456",
2654                "file340282366920938463463374607431768211455"
2655            ),
2656            Ordering::Greater
2657        );
2658
2659        // Different length numbers that overflow u128
2660        assert_eq!(
2661            natural_sort(
2662                "file3402823669209384634633746074317682114560",
2663                "file340282366920938463463374607431768211455"
2664            ),
2665            Ordering::Greater
2666        );
2667
2668        // Leading zeros with numbers near u128::MAX
2669        assert_eq!(
2670            natural_sort(
2671                "file0340282366920938463463374607431768211455",
2672                "file340282366920938463463374607431768211455"
2673            ),
2674            Ordering::Greater
2675        );
2676
2677        // Very large numbers with different lengths (both overflow u128)
2678        assert_eq!(
2679            natural_sort(
2680                "file999999999999999999999999999999999999999999999999",
2681                "file9999999999999999999999999999999999999999999999999"
2682            ),
2683            Ordering::Less
2684        );
2685    }
2686
2687    #[perf]
2688    fn test_natural_sort_case_sensitive() {
2689        // Numerically smaller values come first.
2690        assert_eq!(natural_sort("File1", "file2"), Ordering::Less);
2691        assert_eq!(natural_sort("file1", "File2"), Ordering::Less);
2692
2693        // Numerically equal values: the case-insensitive comparison decides first.
2694        // Case-sensitive comparison only occurs when both are equal case-insensitively.
2695        assert_eq!(natural_sort("Dir1", "dir01"), Ordering::Less);
2696        assert_eq!(natural_sort("dir2", "Dir02"), Ordering::Less);
2697        assert_eq!(natural_sort("dir2", "dir02"), Ordering::Less);
2698
2699        // Numerically equal and case-insensitively equal:
2700        // the lexicographically smaller (case-sensitive) one wins.
2701        assert_eq!(natural_sort("dir1", "Dir1"), Ordering::Less);
2702        assert_eq!(natural_sort("dir02", "Dir02"), Ordering::Less);
2703        assert_eq!(natural_sort("dir10", "Dir10"), Ordering::Less);
2704    }
2705
2706    #[perf]
2707    fn test_natural_sort_edge_cases() {
2708        // Empty strings
2709        assert_eq!(natural_sort("", ""), Ordering::Equal);
2710        assert_eq!(natural_sort("", "a"), Ordering::Less);
2711        assert_eq!(natural_sort("a", ""), Ordering::Greater);
2712
2713        // Special characters
2714        assert_eq!(natural_sort("file-1", "file_1"), Ordering::Less);
2715        assert_eq!(natural_sort("file.1", "file_1"), Ordering::Less);
2716        assert_eq!(natural_sort("file 1", "file_1"), Ordering::Less);
2717
2718        // Unicode characters
2719        // 9312 vs 9313
2720        assert_eq!(natural_sort("file①", "file②"), Ordering::Less);
2721        // 9321 vs 9313
2722        assert_eq!(natural_sort("file⑩", "file②"), Ordering::Greater);
2723        // 28450 vs 23383
2724        assert_eq!(natural_sort("file漢", "file字"), Ordering::Greater);
2725
2726        // Mixed alphanumeric with special chars
2727        assert_eq!(natural_sort("file-1a", "file-1b"), Ordering::Less);
2728        assert_eq!(natural_sort("file-1.2", "file-1.10"), Ordering::Less);
2729        assert_eq!(natural_sort("file-1.10", "file-1.2"), Ordering::Greater);
2730    }
2731
2732    #[test]
2733    fn test_multiple_extensions() {
2734        // No extensions
2735        let path = Path::new("/a/b/c/file_name");
2736        assert_eq!(path.multiple_extensions(), None);
2737
2738        // Only one extension
2739        let path = Path::new("/a/b/c/file_name.tsx");
2740        assert_eq!(path.multiple_extensions(), None);
2741
2742        // Stories sample extension
2743        let path = Path::new("/a/b/c/file_name.stories.tsx");
2744        assert_eq!(path.multiple_extensions(), Some("stories.tsx".to_string()));
2745
2746        // Longer sample extension
2747        let path = Path::new("/a/b/c/long.app.tar.gz");
2748        assert_eq!(path.multiple_extensions(), Some("app.tar.gz".to_string()));
2749    }
2750
2751    #[test]
2752    fn test_strip_path_suffix() {
2753        let base = Path::new("/a/b/c/file_name");
2754        let suffix = Path::new("file_name");
2755        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
2756
2757        let base = Path::new("/a/b/c/file_name.tsx");
2758        let suffix = Path::new("file_name.tsx");
2759        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
2760
2761        let base = Path::new("/a/b/c/file_name.stories.tsx");
2762        let suffix = Path::new("c/file_name.stories.tsx");
2763        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b")));
2764
2765        let base = Path::new("/a/b/c/long.app.tar.gz");
2766        let suffix = Path::new("b/c/long.app.tar.gz");
2767        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a")));
2768
2769        let base = Path::new("/a/b/c/long.app.tar.gz");
2770        let suffix = Path::new("/a/b/c/long.app.tar.gz");
2771        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("")));
2772
2773        let base = Path::new("/a/b/c/long.app.tar.gz");
2774        let suffix = Path::new("/a/b/c/no_match.app.tar.gz");
2775        assert_eq!(strip_path_suffix(base, suffix), None);
2776
2777        let base = Path::new("/a/b/c/long.app.tar.gz");
2778        let suffix = Path::new("app.tar.gz");
2779        assert_eq!(strip_path_suffix(base, suffix), None);
2780    }
2781
2782    #[test]
2783    fn test_strip_prefix() {
2784        let expected = [
2785            (
2786                PathStyle::Posix,
2787                "/a/b/c",
2788                "/a/b",
2789                Some(rel_path("c").into_arc()),
2790            ),
2791            (
2792                PathStyle::Posix,
2793                "/a/b/c",
2794                "/a/b/",
2795                Some(rel_path("c").into_arc()),
2796            ),
2797            (
2798                PathStyle::Posix,
2799                "/a/b/c",
2800                "/",
2801                Some(rel_path("a/b/c").into_arc()),
2802            ),
2803            (PathStyle::Posix, "/a/b/c", "", None),
2804            (PathStyle::Posix, "/a/b//c", "/a/b/", None),
2805            (PathStyle::Posix, "/a/bc", "/a/b", None),
2806            (
2807                PathStyle::Posix,
2808                "/a/b/c",
2809                "/a/b/c",
2810                Some(rel_path("").into_arc()),
2811            ),
2812            (
2813                PathStyle::Windows,
2814                "C:\\a\\b\\c",
2815                "C:\\a\\b",
2816                Some(rel_path("c").into_arc()),
2817            ),
2818            (
2819                PathStyle::Windows,
2820                "C:\\a\\b\\c",
2821                "C:\\a\\b\\",
2822                Some(rel_path("c").into_arc()),
2823            ),
2824            (
2825                PathStyle::Windows,
2826                "C:\\a\\b\\c",
2827                "C:\\",
2828                Some(rel_path("a/b/c").into_arc()),
2829            ),
2830            (PathStyle::Windows, "C:\\a\\b\\c", "", None),
2831            (PathStyle::Windows, "C:\\a\\b\\\\c", "C:\\a\\b\\", None),
2832            (PathStyle::Windows, "C:\\a\\bc", "C:\\a\\b", None),
2833            (
2834                PathStyle::Windows,
2835                "C:\\a\\b/c",
2836                "C:\\a\\b",
2837                Some(rel_path("c").into_arc()),
2838            ),
2839            (
2840                PathStyle::Windows,
2841                "C:\\a\\b/c",
2842                "C:\\a\\b\\",
2843                Some(rel_path("c").into_arc()),
2844            ),
2845            (
2846                PathStyle::Windows,
2847                "C:\\a\\b/c",
2848                "C:\\a\\b/",
2849                Some(rel_path("c").into_arc()),
2850            ),
2851        ];
2852        let actual = expected.clone().map(|(style, child, parent, _)| {
2853            (
2854                style,
2855                child,
2856                parent,
2857                style
2858                    .strip_prefix(child.as_ref(), parent.as_ref())
2859                    .map(|rel_path| rel_path.into_arc()),
2860            )
2861        });
2862        pretty_assertions::assert_eq!(actual, expected);
2863    }
2864
2865    #[cfg(target_os = "windows")]
2866    #[test]
2867    fn test_wsl_path() {
2868        use super::WslPath;
2869        let path = "/a/b/c";
2870        assert_eq!(WslPath::from_path(&path), None);
2871
2872        let path = r"\\wsl.localhost";
2873        assert_eq!(WslPath::from_path(&path), None);
2874
2875        let path = r"\\wsl.localhost\Distro";
2876        assert_eq!(
2877            WslPath::from_path(&path),
2878            Some(WslPath {
2879                distro: "Distro".to_owned(),
2880                path: "/".into(),
2881            })
2882        );
2883
2884        let path = r"\\wsl.localhost\Distro\blue";
2885        assert_eq!(
2886            WslPath::from_path(&path),
2887            Some(WslPath {
2888                distro: "Distro".to_owned(),
2889                path: "/blue".into()
2890            })
2891        );
2892
2893        let path = r"\\wsl$\archlinux\tomato\.\paprika\..\aubergine.txt";
2894        assert_eq!(
2895            WslPath::from_path(&path),
2896            Some(WslPath {
2897                distro: "archlinux".to_owned(),
2898                path: "/tomato/paprika/../aubergine.txt".into()
2899            })
2900        );
2901
2902        let path = r"\\windows.localhost\Distro\foo";
2903        assert_eq!(WslPath::from_path(&path), None);
2904    }
2905
2906    #[test]
2907    fn test_url_to_file_path_ext_posix_basic() {
2908        use super::UrlExt;
2909
2910        let url = url::Url::parse("file:///home/user/file.txt").unwrap();
2911        assert_eq!(
2912            url.to_file_path_ext(PathStyle::Posix),
2913            Ok(PathBuf::from("/home/user/file.txt"))
2914        );
2915
2916        let url = url::Url::parse("file:///").unwrap();
2917        assert_eq!(
2918            url.to_file_path_ext(PathStyle::Posix),
2919            Ok(PathBuf::from("/"))
2920        );
2921
2922        let url = url::Url::parse("file:///a/b/c/d/e").unwrap();
2923        assert_eq!(
2924            url.to_file_path_ext(PathStyle::Posix),
2925            Ok(PathBuf::from("/a/b/c/d/e"))
2926        );
2927    }
2928
2929    #[test]
2930    fn test_url_to_file_path_ext_posix_percent_encoding() {
2931        use super::UrlExt;
2932
2933        let url = url::Url::parse("file:///home/user/file%20with%20spaces.txt").unwrap();
2934        assert_eq!(
2935            url.to_file_path_ext(PathStyle::Posix),
2936            Ok(PathBuf::from("/home/user/file with spaces.txt"))
2937        );
2938
2939        let url = url::Url::parse("file:///path%2Fwith%2Fencoded%2Fslashes").unwrap();
2940        assert_eq!(
2941            url.to_file_path_ext(PathStyle::Posix),
2942            Ok(PathBuf::from("/path/with/encoded/slashes"))
2943        );
2944
2945        let url = url::Url::parse("file:///special%23chars%3F.txt").unwrap();
2946        assert_eq!(
2947            url.to_file_path_ext(PathStyle::Posix),
2948            Ok(PathBuf::from("/special#chars?.txt"))
2949        );
2950    }
2951
2952    #[test]
2953    fn test_url_to_file_path_ext_posix_localhost() {
2954        use super::UrlExt;
2955
2956        let url = url::Url::parse("file://localhost/home/user/file.txt").unwrap();
2957        assert_eq!(
2958            url.to_file_path_ext(PathStyle::Posix),
2959            Ok(PathBuf::from("/home/user/file.txt"))
2960        );
2961    }
2962
2963    #[test]
2964    fn test_url_to_file_path_ext_posix_rejects_host() {
2965        use super::UrlExt;
2966
2967        let url = url::Url::parse("file://somehost/home/user/file.txt").unwrap();
2968        assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(()));
2969    }
2970
2971    #[test]
2972    fn test_url_to_file_path_ext_posix_windows_drive_letter() {
2973        use super::UrlExt;
2974
2975        let url = url::Url::parse("file:///C:").unwrap();
2976        assert_eq!(
2977            url.to_file_path_ext(PathStyle::Posix),
2978            Ok(PathBuf::from("/C:/"))
2979        );
2980
2981        let url = url::Url::parse("file:///D|").unwrap();
2982        assert_eq!(
2983            url.to_file_path_ext(PathStyle::Posix),
2984            Ok(PathBuf::from("/D|/"))
2985        );
2986    }
2987
2988    #[test]
2989    fn test_url_to_file_path_ext_windows_basic() {
2990        use super::UrlExt;
2991
2992        let url = url::Url::parse("file:///C:/Users/user/file.txt").unwrap();
2993        assert_eq!(
2994            url.to_file_path_ext(PathStyle::Windows),
2995            Ok(PathBuf::from("C:\\Users\\user\\file.txt"))
2996        );
2997
2998        let url = url::Url::parse("file:///D:/folder/subfolder/file.rs").unwrap();
2999        assert_eq!(
3000            url.to_file_path_ext(PathStyle::Windows),
3001            Ok(PathBuf::from("D:\\folder\\subfolder\\file.rs"))
3002        );
3003
3004        let url = url::Url::parse("file:///C:/").unwrap();
3005        assert_eq!(
3006            url.to_file_path_ext(PathStyle::Windows),
3007            Ok(PathBuf::from("C:\\"))
3008        );
3009    }
3010
3011    #[test]
3012    fn test_url_to_file_path_ext_windows_encoded_drive_letter() {
3013        use super::UrlExt;
3014
3015        let url = url::Url::parse("file:///C%3A/Users/file.txt").unwrap();
3016        assert_eq!(
3017            url.to_file_path_ext(PathStyle::Windows),
3018            Ok(PathBuf::from("C:\\Users\\file.txt"))
3019        );
3020
3021        let url = url::Url::parse("file:///c%3a/Users/file.txt").unwrap();
3022        assert_eq!(
3023            url.to_file_path_ext(PathStyle::Windows),
3024            Ok(PathBuf::from("c:\\Users\\file.txt"))
3025        );
3026
3027        let url = url::Url::parse("file:///D%3A/folder/file.txt").unwrap();
3028        assert_eq!(
3029            url.to_file_path_ext(PathStyle::Windows),
3030            Ok(PathBuf::from("D:\\folder\\file.txt"))
3031        );
3032
3033        let url = url::Url::parse("file:///d%3A/folder/file.txt").unwrap();
3034        assert_eq!(
3035            url.to_file_path_ext(PathStyle::Windows),
3036            Ok(PathBuf::from("d:\\folder\\file.txt"))
3037        );
3038    }
3039
3040    #[test]
3041    fn test_url_to_file_path_ext_windows_unc_path() {
3042        use super::UrlExt;
3043
3044        let url = url::Url::parse("file://server/share/path/file.txt").unwrap();
3045        assert_eq!(
3046            url.to_file_path_ext(PathStyle::Windows),
3047            Ok(PathBuf::from("\\\\server\\share\\path\\file.txt"))
3048        );
3049
3050        let url = url::Url::parse("file://server/share").unwrap();
3051        assert_eq!(
3052            url.to_file_path_ext(PathStyle::Windows),
3053            Ok(PathBuf::from("\\\\server\\share"))
3054        );
3055    }
3056
3057    #[test]
3058    fn test_url_to_file_path_ext_windows_percent_encoding() {
3059        use super::UrlExt;
3060
3061        let url = url::Url::parse("file:///C:/Users/user/file%20with%20spaces.txt").unwrap();
3062        assert_eq!(
3063            url.to_file_path_ext(PathStyle::Windows),
3064            Ok(PathBuf::from("C:\\Users\\user\\file with spaces.txt"))
3065        );
3066
3067        let url = url::Url::parse("file:///C:/special%23chars%3F.txt").unwrap();
3068        assert_eq!(
3069            url.to_file_path_ext(PathStyle::Windows),
3070            Ok(PathBuf::from("C:\\special#chars?.txt"))
3071        );
3072    }
3073
3074    #[test]
3075    fn test_url_to_file_path_ext_windows_invalid_drive() {
3076        use super::UrlExt;
3077
3078        let url = url::Url::parse("file:///1:/path/file.txt").unwrap();
3079        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3080
3081        let url = url::Url::parse("file:///CC:/path/file.txt").unwrap();
3082        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3083
3084        let url = url::Url::parse("file:///C/path/file.txt").unwrap();
3085        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3086
3087        let url = url::Url::parse("file:///invalid").unwrap();
3088        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3089    }
3090
3091    #[test]
3092    fn test_url_to_file_path_ext_non_file_scheme() {
3093        use super::UrlExt;
3094
3095        let url = url::Url::parse("http://example.com/path").unwrap();
3096        assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(()));
3097        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3098
3099        let url = url::Url::parse("https://example.com/path").unwrap();
3100        assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(()));
3101        assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3102    }
3103
3104    #[test]
3105    fn test_url_to_file_path_ext_windows_localhost() {
3106        use super::UrlExt;
3107
3108        let url = url::Url::parse("file://localhost/C:/Users/file.txt").unwrap();
3109        assert_eq!(
3110            url.to_file_path_ext(PathStyle::Windows),
3111            Ok(PathBuf::from("C:\\Users\\file.txt"))
3112        );
3113    }
3114}