paths.rs

   1use anyhow::Context;
   2use globset::{Glob, GlobSet, GlobSetBuilder};
   3use itertools::Itertools;
   4use regex::Regex;
   5use serde::{Deserialize, Serialize};
   6use std::cmp::Ordering;
   7use std::error::Error;
   8use std::fmt::{Display, Formatter};
   9use std::mem;
  10use std::path::StripPrefixError;
  11use std::sync::{Arc, OnceLock};
  12use std::{
  13    ffi::OsStr,
  14    path::{Path, PathBuf},
  15    sync::LazyLock,
  16};
  17
  18use crate::{rel_path::RelPath, shell::ShellKind};
  19
  20static HOME_DIR: OnceLock<PathBuf> = OnceLock::new();
  21
  22/// Returns the path to the user's home directory.
  23pub fn home_dir() -> &'static PathBuf {
  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(unix)]
  58        {
  59            use std::os::unix::prelude::OsStrExt;
  60            Ok(Self::from(Path::new(OsStr::from_bytes(bytes))))
  61        }
  62        #[cfg(windows)]
  63        {
  64            use tendril::fmt::{Format, WTF8};
  65            WTF8::validate(bytes)
  66                .then(|| {
  67                    // Safety: bytes are valid WTF-8 sequence.
  68                    Self::from(Path::new(unsafe {
  69                        OsStr::from_encoded_bytes_unchecked(bytes)
  70                    }))
  71                })
  72                .with_context(|| format!("Invalid WTF-8 sequence: {bytes:?}"))
  73        }
  74    }
  75
  76    /// Converts a local path to one that can be used inside of WSL.
  77    /// Returns `None` if the path cannot be converted into a WSL one (network share).
  78    fn local_to_wsl(&self) -> Option<PathBuf>;
  79
  80    /// Returns a file's "full" joined collection of extensions, in the case where a file does not
  81    /// just have a singular extension but instead has multiple (e.g File.tar.gz, Component.stories.tsx)
  82    ///
  83    /// Will provide back the extensions joined together such as tar.gz or stories.tsx
  84    fn multiple_extensions(&self) -> Option<String>;
  85
  86    /// Try to make a shell-safe representation of the path.
  87    fn try_shell_safe(&self, shell_kind: ShellKind) -> anyhow::Result<String>;
  88}
  89
  90impl<T: AsRef<Path>> PathExt for T {
  91    fn compact(&self) -> PathBuf {
  92        if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
  93            match self.as_ref().strip_prefix(home_dir().as_path()) {
  94                Ok(relative_path) => {
  95                    let mut shortened_path = PathBuf::new();
  96                    shortened_path.push("~");
  97                    shortened_path.push(relative_path);
  98                    shortened_path
  99                }
 100                Err(_) => self.as_ref().to_path_buf(),
 101            }
 102        } else {
 103            self.as_ref().to_path_buf()
 104        }
 105    }
 106
 107    fn extension_or_hidden_file_name(&self) -> Option<&str> {
 108        let path = self.as_ref();
 109        let file_name = path.file_name()?.to_str()?;
 110        if file_name.starts_with('.') {
 111            return file_name.strip_prefix('.');
 112        }
 113
 114        path.extension()
 115            .and_then(|e| e.to_str())
 116            .or_else(|| path.file_stem()?.to_str())
 117    }
 118
 119    fn local_to_wsl(&self) -> Option<PathBuf> {
 120        // quite sketchy to convert this back to path at the end, but a lot of functions only accept paths
 121        // todo: ideally rework them..?
 122        let mut new_path = std::ffi::OsString::new();
 123        for component in self.as_ref().components() {
 124            match component {
 125                std::path::Component::Prefix(prefix) => {
 126                    let drive_letter = prefix.as_os_str().to_string_lossy().to_lowercase();
 127                    let drive_letter = drive_letter.strip_suffix(':')?;
 128
 129                    new_path.push(format!("/mnt/{}", drive_letter));
 130                }
 131                std::path::Component::RootDir => {}
 132                std::path::Component::CurDir => {
 133                    new_path.push("/.");
 134                }
 135                std::path::Component::ParentDir => {
 136                    new_path.push("/..");
 137                }
 138                std::path::Component::Normal(os_str) => {
 139                    new_path.push("/");
 140                    new_path.push(os_str);
 141                }
 142            }
 143        }
 144
 145        Some(new_path.into())
 146    }
 147
 148    fn multiple_extensions(&self) -> Option<String> {
 149        let path = self.as_ref();
 150        let file_name = path.file_name()?.to_str()?;
 151
 152        let parts: Vec<&str> = file_name
 153            .split('.')
 154            // Skip the part with the file name extension
 155            .skip(1)
 156            .collect();
 157
 158        if parts.len() < 2 {
 159            return None;
 160        }
 161
 162        Some(parts.into_iter().join("."))
 163    }
 164
 165    fn try_shell_safe(&self, shell_kind: ShellKind) -> anyhow::Result<String> {
 166        let path_str = self
 167            .as_ref()
 168            .to_str()
 169            .with_context(|| "Path contains invalid UTF-8")?;
 170        shell_kind
 171            .try_quote(path_str)
 172            .as_deref()
 173            .map(ToOwned::to_owned)
 174            .context("Failed to quote path")
 175    }
 176}
 177
 178pub fn path_ends_with(base: &Path, suffix: &Path) -> bool {
 179    strip_path_suffix(base, suffix).is_some()
 180}
 181
 182pub fn strip_path_suffix<'a>(base: &'a Path, suffix: &Path) -> Option<&'a Path> {
 183    if let Some(remainder) = base
 184        .as_os_str()
 185        .as_encoded_bytes()
 186        .strip_suffix(suffix.as_os_str().as_encoded_bytes())
 187    {
 188        if remainder
 189            .last()
 190            .is_none_or(|last_byte| std::path::is_separator(*last_byte as char))
 191        {
 192            let os_str = unsafe {
 193                OsStr::from_encoded_bytes_unchecked(
 194                    &remainder[0..remainder.len().saturating_sub(1)],
 195                )
 196            };
 197            return Some(Path::new(os_str));
 198        }
 199    }
 200    None
 201}
 202
 203/// In memory, this is identical to `Path`. On non-Windows conversions to this type are no-ops. On
 204/// windows, these conversions sanitize UNC paths by removing the `\\\\?\\` prefix.
 205#[derive(Eq, PartialEq, Hash, Ord, PartialOrd)]
 206#[repr(transparent)]
 207pub struct SanitizedPath(Path);
 208
 209impl SanitizedPath {
 210    pub fn new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
 211        #[cfg(not(target_os = "windows"))]
 212        return Self::unchecked_new(path.as_ref());
 213
 214        #[cfg(target_os = "windows")]
 215        return Self::unchecked_new(dunce::simplified(path.as_ref()));
 216    }
 217
 218    pub fn unchecked_new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
 219        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
 220        unsafe { mem::transmute::<&Path, &Self>(path.as_ref()) }
 221    }
 222
 223    pub fn from_arc(path: Arc<Path>) -> Arc<Self> {
 224        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
 225        #[cfg(not(target_os = "windows"))]
 226        return unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) };
 227
 228        // TODO: could avoid allocating here if dunce::simplified results in the same path
 229        #[cfg(target_os = "windows")]
 230        return Self::new(&path).into();
 231    }
 232
 233    pub fn new_arc<T: AsRef<Path> + ?Sized>(path: &T) -> Arc<Self> {
 234        Self::new(path).into()
 235    }
 236
 237    pub fn cast_arc(path: Arc<Self>) -> Arc<Path> {
 238        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
 239        unsafe { mem::transmute::<Arc<Self>, Arc<Path>>(path) }
 240    }
 241
 242    pub fn cast_arc_ref(path: &Arc<Self>) -> &Arc<Path> {
 243        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
 244        unsafe { mem::transmute::<&Arc<Self>, &Arc<Path>>(path) }
 245    }
 246
 247    pub fn starts_with(&self, prefix: &Self) -> bool {
 248        self.0.starts_with(&prefix.0)
 249    }
 250
 251    pub fn as_path(&self) -> &Path {
 252        &self.0
 253    }
 254
 255    pub fn file_name(&self) -> Option<&std::ffi::OsStr> {
 256        self.0.file_name()
 257    }
 258
 259    pub fn extension(&self) -> Option<&std::ffi::OsStr> {
 260        self.0.extension()
 261    }
 262
 263    pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
 264        self.0.join(path)
 265    }
 266
 267    pub fn parent(&self) -> Option<&Self> {
 268        self.0.parent().map(Self::unchecked_new)
 269    }
 270
 271    pub fn strip_prefix(&self, base: &Self) -> Result<&Path, StripPrefixError> {
 272        self.0.strip_prefix(base.as_path())
 273    }
 274
 275    pub fn to_str(&self) -> Option<&str> {
 276        self.0.to_str()
 277    }
 278
 279    pub fn to_path_buf(&self) -> PathBuf {
 280        self.0.to_path_buf()
 281    }
 282}
 283
 284impl std::fmt::Debug for SanitizedPath {
 285    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
 286        std::fmt::Debug::fmt(&self.0, formatter)
 287    }
 288}
 289
 290impl Display for SanitizedPath {
 291    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
 292        write!(f, "{}", self.0.display())
 293    }
 294}
 295
 296impl From<&SanitizedPath> for Arc<SanitizedPath> {
 297    fn from(sanitized_path: &SanitizedPath) -> Self {
 298        let path: Arc<Path> = sanitized_path.0.into();
 299        // safe because `Path` and `SanitizedPath` have the same repr and Drop impl
 300        unsafe { mem::transmute(path) }
 301    }
 302}
 303
 304impl From<&SanitizedPath> for PathBuf {
 305    fn from(sanitized_path: &SanitizedPath) -> Self {
 306        sanitized_path.as_path().into()
 307    }
 308}
 309
 310impl AsRef<Path> for SanitizedPath {
 311    fn as_ref(&self) -> &Path {
 312        &self.0
 313    }
 314}
 315
 316#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 317pub enum PathStyle {
 318    Posix,
 319    Windows,
 320}
 321
 322impl PathStyle {
 323    #[cfg(target_os = "windows")]
 324    pub const fn local() -> Self {
 325        PathStyle::Windows
 326    }
 327
 328    #[cfg(not(target_os = "windows"))]
 329    pub const fn local() -> Self {
 330        PathStyle::Posix
 331    }
 332
 333    #[inline]
 334    pub fn separator(&self) -> &'static str {
 335        match self {
 336            PathStyle::Posix => "/",
 337            PathStyle::Windows => "\\",
 338        }
 339    }
 340
 341    pub fn is_windows(&self) -> bool {
 342        *self == PathStyle::Windows
 343    }
 344
 345    pub fn join(self, left: impl AsRef<Path>, right: impl AsRef<Path>) -> Option<String> {
 346        let right = right.as_ref().to_str()?;
 347        if is_absolute(right, self) {
 348            return None;
 349        }
 350        let left = left.as_ref().to_str()?;
 351        if left.is_empty() {
 352            Some(right.into())
 353        } else {
 354            Some(format!(
 355                "{left}{}{right}",
 356                if left.ends_with(self.separator()) {
 357                    ""
 358                } else {
 359                    self.separator()
 360                }
 361            ))
 362        }
 363    }
 364
 365    pub fn split(self, path_like: &str) -> (Option<&str>, &str) {
 366        let Some(pos) = path_like.rfind(self.separator()) else {
 367            return (None, path_like);
 368        };
 369        let filename_start = pos + self.separator().len();
 370        (
 371            Some(&path_like[..filename_start]),
 372            &path_like[filename_start..],
 373        )
 374    }
 375}
 376
 377#[derive(Debug, Clone)]
 378pub struct RemotePathBuf {
 379    style: PathStyle,
 380    string: String,
 381}
 382
 383impl RemotePathBuf {
 384    pub fn new(string: String, style: PathStyle) -> Self {
 385        Self { style, string }
 386    }
 387
 388    pub fn from_str(path: &str, style: PathStyle) -> Self {
 389        Self::new(path.to_string(), style)
 390    }
 391
 392    pub fn path_style(&self) -> PathStyle {
 393        self.style
 394    }
 395
 396    pub fn to_proto(self) -> String {
 397        self.string
 398    }
 399}
 400
 401impl Display for RemotePathBuf {
 402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 403        write!(f, "{}", self.string)
 404    }
 405}
 406
 407pub fn is_absolute(path_like: &str, path_style: PathStyle) -> bool {
 408    path_like.starts_with('/')
 409        || path_style == PathStyle::Windows
 410            && (path_like.starts_with('\\')
 411                || path_like
 412                    .chars()
 413                    .next()
 414                    .is_some_and(|c| c.is_ascii_alphabetic())
 415                    && path_like[1..]
 416                        .strip_prefix(':')
 417                        .is_some_and(|path| path.starts_with('/') || path.starts_with('\\')))
 418}
 419
 420#[derive(Debug, PartialEq)]
 421#[non_exhaustive]
 422pub struct NormalizeError;
 423
 424impl Error for NormalizeError {}
 425
 426impl std::fmt::Display for NormalizeError {
 427    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 428        f.write_str("parent reference `..` points outside of base directory")
 429    }
 430}
 431
 432/// Copied from stdlib where it's unstable.
 433///
 434/// Normalize a path, including `..` without traversing the filesystem.
 435///
 436/// Returns an error if normalization would leave leading `..` components.
 437///
 438/// <div class="warning">
 439///
 440/// This function always resolves `..` to the "lexical" parent.
 441/// That is "a/b/../c" will always resolve to `a/c` which can change the meaning of the path.
 442/// 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`.
 443///
 444/// </div>
 445///
 446/// [`path::absolute`](absolute) is an alternative that preserves `..`.
 447/// Or [`Path::canonicalize`] can be used to resolve any `..` by querying the filesystem.
 448pub fn normalize_lexically(path: &Path) -> Result<PathBuf, NormalizeError> {
 449    use std::path::Component;
 450
 451    let mut lexical = PathBuf::new();
 452    let mut iter = path.components().peekable();
 453
 454    // Find the root, if any, and add it to the lexical path.
 455    // Here we treat the Windows path "C:\" as a single "root" even though
 456    // `components` splits it into two: (Prefix, RootDir).
 457    let root = match iter.peek() {
 458        Some(Component::ParentDir) => return Err(NormalizeError),
 459        Some(p @ Component::RootDir) | Some(p @ Component::CurDir) => {
 460            lexical.push(p);
 461            iter.next();
 462            lexical.as_os_str().len()
 463        }
 464        Some(Component::Prefix(prefix)) => {
 465            lexical.push(prefix.as_os_str());
 466            iter.next();
 467            if let Some(p @ Component::RootDir) = iter.peek() {
 468                lexical.push(p);
 469                iter.next();
 470            }
 471            lexical.as_os_str().len()
 472        }
 473        None => return Ok(PathBuf::new()),
 474        Some(Component::Normal(_)) => 0,
 475    };
 476
 477    for component in iter {
 478        match component {
 479            Component::RootDir => unreachable!(),
 480            Component::Prefix(_) => return Err(NormalizeError),
 481            Component::CurDir => continue,
 482            Component::ParentDir => {
 483                // It's an error if ParentDir causes us to go above the "root".
 484                if lexical.as_os_str().len() == root {
 485                    return Err(NormalizeError);
 486                } else {
 487                    lexical.pop();
 488                }
 489            }
 490            Component::Normal(path) => lexical.push(path),
 491        }
 492    }
 493    Ok(lexical)
 494}
 495
 496/// A delimiter to use in `path_query:row_number:column_number` strings parsing.
 497pub const FILE_ROW_COLUMN_DELIMITER: char = ':';
 498
 499const ROW_COL_CAPTURE_REGEX: &str = r"(?xs)
 500    ([^\(]+)\:(?:
 501        \((\d+)[,:](\d+)\) # filename:(row,column), filename:(row:column)
 502        |
 503        \((\d+)\)()     # filename:(row)
 504    )
 505    |
 506    ([^\(]+)(?:
 507        \((\d+)[,:](\d+)\) # filename(row,column), filename(row:column)
 508        |
 509        \((\d+)\)()     # filename(row)
 510    )
 511    |
 512    (.+?)(?:
 513        \:+(\d+)\:(\d+)\:*$  # filename:row:column
 514        |
 515        \:+(\d+)\:*()$       # filename:row
 516        |
 517        \:+()()$
 518    )";
 519
 520/// A representation of a path-like string with optional row and column numbers.
 521/// Matching values example: `te`, `test.rs:22`, `te:22:5`, `test.c(22)`, `test.c(22,5)`etc.
 522#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
 523pub struct PathWithPosition {
 524    pub path: PathBuf,
 525    pub row: Option<u32>,
 526    // Absent if row is absent.
 527    pub column: Option<u32>,
 528}
 529
 530impl PathWithPosition {
 531    /// Returns a PathWithPosition from a path.
 532    pub fn from_path(path: PathBuf) -> Self {
 533        Self {
 534            path,
 535            row: None,
 536            column: None,
 537        }
 538    }
 539
 540    /// Parses a string that possibly has `:row:column` or `(row, column)` suffix.
 541    /// Parenthesis format is used by [MSBuild](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks) compatible tools
 542    /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`.
 543    /// If the suffix parsing fails, the whole string is parsed as a path.
 544    ///
 545    /// Be mindful that `test_file:10:1:` is a valid posix filename.
 546    /// `PathWithPosition` class assumes that the ending position-like suffix is **not** part of the filename.
 547    ///
 548    /// # Examples
 549    ///
 550    /// ```
 551    /// # use util::paths::PathWithPosition;
 552    /// # use std::path::PathBuf;
 553    /// assert_eq!(PathWithPosition::parse_str("test_file"), PathWithPosition {
 554    ///     path: PathBuf::from("test_file"),
 555    ///     row: None,
 556    ///     column: None,
 557    /// });
 558    /// assert_eq!(PathWithPosition::parse_str("test_file:10"), PathWithPosition {
 559    ///     path: PathBuf::from("test_file"),
 560    ///     row: Some(10),
 561    ///     column: None,
 562    /// });
 563    /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
 564    ///     path: PathBuf::from("test_file.rs"),
 565    ///     row: None,
 566    ///     column: None,
 567    /// });
 568    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1"), PathWithPosition {
 569    ///     path: PathBuf::from("test_file.rs"),
 570    ///     row: Some(1),
 571    ///     column: None,
 572    /// });
 573    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2"), PathWithPosition {
 574    ///     path: PathBuf::from("test_file.rs"),
 575    ///     row: Some(1),
 576    ///     column: Some(2),
 577    /// });
 578    /// ```
 579    ///
 580    /// # Expected parsing results when encounter ill-formatted inputs.
 581    /// ```
 582    /// # use util::paths::PathWithPosition;
 583    /// # use std::path::PathBuf;
 584    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a"), PathWithPosition {
 585    ///     path: PathBuf::from("test_file.rs:a"),
 586    ///     row: None,
 587    ///     column: None,
 588    /// });
 589    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a:b"), PathWithPosition {
 590    ///     path: PathBuf::from("test_file.rs:a:b"),
 591    ///     row: None,
 592    ///     column: None,
 593    /// });
 594    /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition {
 595    ///     path: PathBuf::from("test_file.rs"),
 596    ///     row: None,
 597    ///     column: None,
 598    /// });
 599    /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1"), PathWithPosition {
 600    ///     path: PathBuf::from("test_file.rs"),
 601    ///     row: Some(1),
 602    ///     column: None,
 603    /// });
 604    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::"), PathWithPosition {
 605    ///     path: PathBuf::from("test_file.rs"),
 606    ///     row: Some(1),
 607    ///     column: None,
 608    /// });
 609    /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1:2"), PathWithPosition {
 610    ///     path: PathBuf::from("test_file.rs"),
 611    ///     row: Some(1),
 612    ///     column: Some(2),
 613    /// });
 614    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::2"), PathWithPosition {
 615    ///     path: PathBuf::from("test_file.rs:1"),
 616    ///     row: Some(2),
 617    ///     column: None,
 618    /// });
 619    /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2:3"), PathWithPosition {
 620    ///     path: PathBuf::from("test_file.rs:1"),
 621    ///     row: Some(2),
 622    ///     column: Some(3),
 623    /// });
 624    /// ```
 625    pub fn parse_str(s: &str) -> Self {
 626        let trimmed = s.trim();
 627        let path = Path::new(trimmed);
 628        let maybe_file_name_with_row_col = path.file_name().unwrap_or_default().to_string_lossy();
 629        if maybe_file_name_with_row_col.is_empty() {
 630            return Self {
 631                path: Path::new(s).to_path_buf(),
 632                row: None,
 633                column: None,
 634            };
 635        }
 636
 637        // Let's avoid repeated init cost on this. It is subject to thread contention, but
 638        // so far this code isn't called from multiple hot paths. Getting contention here
 639        // in the future seems unlikely.
 640        static SUFFIX_RE: LazyLock<Regex> =
 641            LazyLock::new(|| Regex::new(ROW_COL_CAPTURE_REGEX).unwrap());
 642        match SUFFIX_RE
 643            .captures(&maybe_file_name_with_row_col)
 644            .map(|caps| caps.extract())
 645        {
 646            Some((_, [file_name, maybe_row, maybe_column])) => {
 647                let row = maybe_row.parse::<u32>().ok();
 648                let column = maybe_column.parse::<u32>().ok();
 649
 650                let suffix_length = maybe_file_name_with_row_col.len() - file_name.len();
 651                let path_without_suffix = &trimmed[..trimmed.len() - suffix_length];
 652
 653                Self {
 654                    path: Path::new(path_without_suffix).to_path_buf(),
 655                    row,
 656                    column,
 657                }
 658            }
 659            None => {
 660                // The `ROW_COL_CAPTURE_REGEX` deals with separated digits only,
 661                // but in reality there could be `foo/bar.py:22:in` inputs which we want to match too.
 662                // The regex mentioned is not very extendable with "digit or random string" checks, so do this here instead.
 663                let delimiter = ':';
 664                let mut path_parts = s
 665                    .rsplitn(3, delimiter)
 666                    .collect::<Vec<_>>()
 667                    .into_iter()
 668                    .rev()
 669                    .fuse();
 670                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();
 671                let mut row = None;
 672                let mut column = None;
 673                if let Some(maybe_row) = path_parts.next() {
 674                    if let Ok(parsed_row) = maybe_row.parse::<u32>() {
 675                        row = Some(parsed_row);
 676                        if let Some(parsed_column) = path_parts
 677                            .next()
 678                            .and_then(|maybe_col| maybe_col.parse::<u32>().ok())
 679                        {
 680                            column = Some(parsed_column);
 681                        }
 682                    } else {
 683                        path_string.push(delimiter);
 684                        path_string.push_str(maybe_row);
 685                    }
 686                }
 687                for split in path_parts {
 688                    path_string.push(delimiter);
 689                    path_string.push_str(split);
 690                }
 691
 692                Self {
 693                    path: PathBuf::from(path_string),
 694                    row,
 695                    column,
 696                }
 697            }
 698        }
 699    }
 700
 701    pub fn map_path<E>(
 702        self,
 703        mapping: impl FnOnce(PathBuf) -> Result<PathBuf, E>,
 704    ) -> Result<PathWithPosition, E> {
 705        Ok(PathWithPosition {
 706            path: mapping(self.path)?,
 707            row: self.row,
 708            column: self.column,
 709        })
 710    }
 711
 712    pub fn to_string(&self, path_to_string: impl Fn(&PathBuf) -> String) -> String {
 713        let path_string = path_to_string(&self.path);
 714        if let Some(row) = self.row {
 715            if let Some(column) = self.column {
 716                format!("{path_string}:{row}:{column}")
 717            } else {
 718                format!("{path_string}:{row}")
 719            }
 720        } else {
 721            path_string
 722        }
 723    }
 724}
 725
 726#[derive(Clone, Debug)]
 727pub struct PathMatcher {
 728    sources: Vec<String>,
 729    glob: GlobSet,
 730    path_style: PathStyle,
 731}
 732
 733// impl std::fmt::Display for PathMatcher {
 734//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 735//         self.sources.fmt(f)
 736//     }
 737// }
 738
 739impl PartialEq for PathMatcher {
 740    fn eq(&self, other: &Self) -> bool {
 741        self.sources.eq(&other.sources)
 742    }
 743}
 744
 745impl Eq for PathMatcher {}
 746
 747impl PathMatcher {
 748    pub fn new(
 749        globs: impl IntoIterator<Item = impl AsRef<str>>,
 750        path_style: PathStyle,
 751    ) -> Result<Self, globset::Error> {
 752        let globs = globs
 753            .into_iter()
 754            .map(|as_str| Glob::new(as_str.as_ref()))
 755            .collect::<Result<Vec<_>, _>>()?;
 756        let sources = globs.iter().map(|glob| glob.glob().to_owned()).collect();
 757        let mut glob_builder = GlobSetBuilder::new();
 758        for single_glob in globs {
 759            glob_builder.add(single_glob);
 760        }
 761        let glob = glob_builder.build()?;
 762        Ok(PathMatcher {
 763            glob,
 764            sources,
 765            path_style,
 766        })
 767    }
 768
 769    pub fn sources(&self) -> &[String] {
 770        &self.sources
 771    }
 772
 773    pub fn is_match<P: AsRef<Path>>(&self, other: P) -> bool {
 774        let other_path = other.as_ref();
 775        self.sources.iter().any(|source| {
 776            let as_bytes = other_path.as_os_str().as_encoded_bytes();
 777            as_bytes.starts_with(source.as_bytes()) || as_bytes.ends_with(source.as_bytes())
 778        }) || self.glob.is_match(other_path)
 779            || self.check_with_end_separator(other_path)
 780    }
 781
 782    fn check_with_end_separator(&self, path: &Path) -> bool {
 783        let path_str = path.to_string_lossy();
 784        let separator = self.path_style.separator();
 785        if path_str.ends_with(separator) {
 786            false
 787        } else {
 788            self.glob.is_match(path_str.to_string() + separator)
 789        }
 790    }
 791}
 792
 793impl Default for PathMatcher {
 794    fn default() -> Self {
 795        Self {
 796            path_style: PathStyle::local(),
 797            glob: GlobSet::empty(),
 798            sources: vec![],
 799        }
 800    }
 801}
 802
 803/// Compares two sequences of consecutive digits for natural sorting.
 804///
 805/// This function is a core component of natural sorting that handles numeric comparison
 806/// in a way that feels natural to humans. It extracts and compares consecutive digit
 807/// sequences from two iterators, handling various cases like leading zeros and very large numbers.
 808///
 809/// # Behavior
 810///
 811/// The function implements the following comparison rules:
 812/// 1. Different numeric values: Compares by actual numeric value (e.g., "2" < "10")
 813/// 2. Leading zeros: When values are equal, longer sequence wins (e.g., "002" > "2")
 814/// 3. Large numbers: Falls back to string comparison for numbers that would overflow u128
 815///
 816/// # Examples
 817///
 818/// ```text
 819/// "1" vs "2"      -> Less       (different values)
 820/// "2" vs "10"     -> Less       (numeric comparison)
 821/// "002" vs "2"    -> Greater    (leading zeros)
 822/// "10" vs "010"   -> Less       (leading zeros)
 823/// "999..." vs "1000..." -> Less (large number comparison)
 824/// ```
 825///
 826/// # Implementation Details
 827///
 828/// 1. Extracts consecutive digits into strings
 829/// 2. Compares sequence lengths for leading zero handling
 830/// 3. For equal lengths, compares digit by digit
 831/// 4. For different lengths:
 832///    - Attempts numeric comparison first (for numbers up to 2^128 - 1)
 833///    - Falls back to string comparison if numbers would overflow
 834///
 835/// The function advances both iterators past their respective numeric sequences,
 836/// regardless of the comparison result.
 837fn compare_numeric_segments<I>(
 838    a_iter: &mut std::iter::Peekable<I>,
 839    b_iter: &mut std::iter::Peekable<I>,
 840) -> Ordering
 841where
 842    I: Iterator<Item = char>,
 843{
 844    // Collect all consecutive digits into strings
 845    let mut a_num_str = String::new();
 846    let mut b_num_str = String::new();
 847
 848    while let Some(&c) = a_iter.peek() {
 849        if !c.is_ascii_digit() {
 850            break;
 851        }
 852
 853        a_num_str.push(c);
 854        a_iter.next();
 855    }
 856
 857    while let Some(&c) = b_iter.peek() {
 858        if !c.is_ascii_digit() {
 859            break;
 860        }
 861
 862        b_num_str.push(c);
 863        b_iter.next();
 864    }
 865
 866    // First compare lengths (handle leading zeros)
 867    match a_num_str.len().cmp(&b_num_str.len()) {
 868        Ordering::Equal => {
 869            // Same length, compare digit by digit
 870            match a_num_str.cmp(&b_num_str) {
 871                Ordering::Equal => Ordering::Equal,
 872                ordering => ordering,
 873            }
 874        }
 875
 876        // Different lengths but same value means leading zeros
 877        ordering => {
 878            // Try parsing as numbers first
 879            if let (Ok(a_val), Ok(b_val)) = (a_num_str.parse::<u128>(), b_num_str.parse::<u128>()) {
 880                match a_val.cmp(&b_val) {
 881                    Ordering::Equal => ordering, // Same value, longer one is greater (leading zeros)
 882                    ord => ord,
 883                }
 884            } else {
 885                // If parsing fails (overflow), compare as strings
 886                a_num_str.cmp(&b_num_str)
 887            }
 888        }
 889    }
 890}
 891
 892/// Performs natural sorting comparison between two strings.
 893///
 894/// Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations.
 895/// For example, "file2" comes before "file10" (unlike standard lexicographic sorting).
 896///
 897/// # Characteristics
 898///
 899/// * Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase
 900/// * Numbers are compared by numeric value, not character by character
 901/// * Leading zeros affect ordering when numeric values are equal
 902/// * Can handle numbers larger than u128::MAX (falls back to string comparison)
 903/// * When strings are equal case-insensitively, lowercase is prioritized (lowercase < uppercase)
 904///
 905/// # Algorithm
 906///
 907/// The function works by:
 908/// 1. Processing strings character by character in a case-insensitive manner
 909/// 2. When encountering digits, treating consecutive digits as a single number
 910/// 3. Comparing numbers by their numeric value rather than lexicographically
 911/// 4. For non-numeric characters, using case-insensitive comparison
 912/// 5. If everything is equal case-insensitively, using case-sensitive comparison as final tie-breaker
 913pub fn natural_sort(a: &str, b: &str) -> Ordering {
 914    let mut a_iter = a.chars().peekable();
 915    let mut b_iter = b.chars().peekable();
 916
 917    loop {
 918        match (a_iter.peek(), b_iter.peek()) {
 919            (None, None) => {
 920                return b.cmp(a);
 921            }
 922            (None, _) => return Ordering::Less,
 923            (_, None) => return Ordering::Greater,
 924            (Some(&a_char), Some(&b_char)) => {
 925                if a_char.is_ascii_digit() && b_char.is_ascii_digit() {
 926                    match compare_numeric_segments(&mut a_iter, &mut b_iter) {
 927                        Ordering::Equal => continue,
 928                        ordering => return ordering,
 929                    }
 930                } else {
 931                    match a_char
 932                        .to_ascii_lowercase()
 933                        .cmp(&b_char.to_ascii_lowercase())
 934                    {
 935                        Ordering::Equal => {
 936                            a_iter.next();
 937                            b_iter.next();
 938                        }
 939                        ordering => return ordering,
 940                    }
 941                }
 942            }
 943        }
 944    }
 945}
 946
 947/// Case-insensitive natural sort without applying the final lowercase/uppercase tie-breaker.
 948/// This is useful when comparing individual path components where we want to keep walking
 949/// deeper components before deciding on casing.
 950fn natural_sort_no_tiebreak(a: &str, b: &str) -> Ordering {
 951    if a.eq_ignore_ascii_case(b) {
 952        Ordering::Equal
 953    } else {
 954        natural_sort(a, b)
 955    }
 956}
 957
 958fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) {
 959    if filename.is_empty() {
 960        return (None, None);
 961    }
 962
 963    match filename.rsplit_once('.') {
 964        // Case 1: No dot was found. The entire name is the stem.
 965        None => (Some(filename), None),
 966
 967        // Case 2: A dot was found.
 968        Some((before, after)) => {
 969            // This is the crucial check for dotfiles like ".bashrc".
 970            // If `before` is empty, the dot was the first character.
 971            // In that case, we revert to the "whole name is the stem" logic.
 972            if before.is_empty() {
 973                (Some(filename), None)
 974            } else {
 975                // Otherwise, we have a standard stem and extension.
 976                (Some(before), Some(after))
 977            }
 978        }
 979    }
 980}
 981
 982pub fn compare_rel_paths(
 983    (path_a, a_is_file): (&RelPath, bool),
 984    (path_b, b_is_file): (&RelPath, bool),
 985) -> Ordering {
 986    let mut components_a = path_a.components();
 987    let mut components_b = path_b.components();
 988    loop {
 989        match (components_a.next(), components_b.next()) {
 990            (Some(component_a), Some(component_b)) => {
 991                let a_is_file = a_is_file && components_a.rest().is_empty();
 992                let b_is_file = b_is_file && components_b.rest().is_empty();
 993
 994                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
 995                    let (a_stem, a_extension) = a_is_file
 996                        .then(|| stem_and_extension(component_a))
 997                        .unwrap_or_default();
 998                    let path_string_a = if a_is_file { a_stem } else { Some(component_a) };
 999
1000                    let (b_stem, b_extension) = b_is_file
1001                        .then(|| stem_and_extension(component_b))
1002                        .unwrap_or_default();
1003                    let path_string_b = if b_is_file { b_stem } else { Some(component_b) };
1004
1005                    let compare_components = match (path_string_a, path_string_b) {
1006                        (Some(a), Some(b)) => natural_sort(&a, &b),
1007                        (Some(_), None) => Ordering::Greater,
1008                        (None, Some(_)) => Ordering::Less,
1009                        (None, None) => Ordering::Equal,
1010                    };
1011
1012                    compare_components.then_with(|| {
1013                        if a_is_file && b_is_file {
1014                            let ext_a = a_extension.unwrap_or_default();
1015                            let ext_b = b_extension.unwrap_or_default();
1016                            ext_a.cmp(ext_b)
1017                        } else {
1018                            Ordering::Equal
1019                        }
1020                    })
1021                });
1022
1023                if !ordering.is_eq() {
1024                    return ordering;
1025                }
1026            }
1027            (Some(_), None) => break Ordering::Greater,
1028            (None, Some(_)) => break Ordering::Less,
1029            (None, None) => break Ordering::Equal,
1030        }
1031    }
1032}
1033
1034/// Compare two relative paths with mixed files and directories using
1035/// case-insensitive natural sorting. For example, "Apple", "aardvark.txt",
1036/// and "Zebra" would be sorted as: aardvark.txt, Apple, Zebra
1037/// (case-insensitive alphabetical).
1038pub fn compare_rel_paths_mixed(
1039    (path_a, a_is_file): (&RelPath, bool),
1040    (path_b, b_is_file): (&RelPath, bool),
1041) -> Ordering {
1042    let original_paths_equal = std::ptr::eq(path_a, path_b) || path_a == path_b;
1043    let mut components_a = path_a.components();
1044    let mut components_b = path_b.components();
1045
1046    loop {
1047        match (components_a.next(), components_b.next()) {
1048            (Some(component_a), Some(component_b)) => {
1049                let a_leaf_file = a_is_file && components_a.rest().is_empty();
1050                let b_leaf_file = b_is_file && components_b.rest().is_empty();
1051
1052                let (a_stem, a_ext) = a_leaf_file
1053                    .then(|| stem_and_extension(component_a))
1054                    .unwrap_or_default();
1055                let (b_stem, b_ext) = b_leaf_file
1056                    .then(|| stem_and_extension(component_b))
1057                    .unwrap_or_default();
1058                let a_key = if a_leaf_file {
1059                    a_stem
1060                } else {
1061                    Some(component_a)
1062                };
1063                let b_key = if b_leaf_file {
1064                    b_stem
1065                } else {
1066                    Some(component_b)
1067                };
1068
1069                let ordering = match (a_key, b_key) {
1070                    (Some(a), Some(b)) => natural_sort_no_tiebreak(a, b)
1071                        .then_with(|| match (a_leaf_file, b_leaf_file) {
1072                            (true, false) if a == b => Ordering::Greater,
1073                            (false, true) if a == b => Ordering::Less,
1074                            _ => Ordering::Equal,
1075                        })
1076                        .then_with(|| {
1077                            if a_leaf_file && b_leaf_file {
1078                                let a_ext_str = a_ext.unwrap_or_default().to_lowercase();
1079                                let b_ext_str = b_ext.unwrap_or_default().to_lowercase();
1080                                b_ext_str.cmp(&a_ext_str)
1081                            } else {
1082                                Ordering::Equal
1083                            }
1084                        }),
1085                    (Some(_), None) => Ordering::Greater,
1086                    (None, Some(_)) => Ordering::Less,
1087                    (None, None) => Ordering::Equal,
1088                };
1089
1090                if !ordering.is_eq() {
1091                    return ordering;
1092                }
1093            }
1094            (Some(_), None) => return Ordering::Greater,
1095            (None, Some(_)) => return Ordering::Less,
1096            (None, None) => {
1097                // Deterministic tie-break: use natural sort to prefer lowercase when paths
1098                // are otherwise equal but still differ in casing.
1099                if !original_paths_equal {
1100                    return natural_sort(path_a.as_unix_str(), path_b.as_unix_str());
1101                }
1102                return Ordering::Equal;
1103            }
1104        }
1105    }
1106}
1107
1108/// Compare two relative paths with files before directories using
1109/// case-insensitive natural sorting. At each directory level, all files
1110/// are sorted before all directories, with case-insensitive alphabetical
1111/// ordering within each group.
1112pub fn compare_rel_paths_files_first(
1113    (path_a, a_is_file): (&RelPath, bool),
1114    (path_b, b_is_file): (&RelPath, bool),
1115) -> Ordering {
1116    let original_paths_equal = std::ptr::eq(path_a, path_b) || path_a == path_b;
1117    let mut components_a = path_a.components();
1118    let mut components_b = path_b.components();
1119
1120    loop {
1121        match (components_a.next(), components_b.next()) {
1122            (Some(component_a), Some(component_b)) => {
1123                let a_leaf_file = a_is_file && components_a.rest().is_empty();
1124                let b_leaf_file = b_is_file && components_b.rest().is_empty();
1125
1126                let (a_stem, a_ext) = a_leaf_file
1127                    .then(|| stem_and_extension(component_a))
1128                    .unwrap_or_default();
1129                let (b_stem, b_ext) = b_leaf_file
1130                    .then(|| stem_and_extension(component_b))
1131                    .unwrap_or_default();
1132                let a_key = if a_leaf_file {
1133                    a_stem
1134                } else {
1135                    Some(component_a)
1136                };
1137                let b_key = if b_leaf_file {
1138                    b_stem
1139                } else {
1140                    Some(component_b)
1141                };
1142
1143                let ordering = match (a_key, b_key) {
1144                    (Some(a), Some(b)) => {
1145                        if a_leaf_file && !b_leaf_file {
1146                            Ordering::Less
1147                        } else if !a_leaf_file && b_leaf_file {
1148                            Ordering::Greater
1149                        } else {
1150                            natural_sort_no_tiebreak(a, b).then_with(|| {
1151                                if a_leaf_file && b_leaf_file {
1152                                    let a_ext_str = a_ext.unwrap_or_default().to_lowercase();
1153                                    let b_ext_str = b_ext.unwrap_or_default().to_lowercase();
1154                                    a_ext_str.cmp(&b_ext_str)
1155                                } else {
1156                                    Ordering::Equal
1157                                }
1158                            })
1159                        }
1160                    }
1161                    (Some(_), None) => Ordering::Greater,
1162                    (None, Some(_)) => Ordering::Less,
1163                    (None, None) => Ordering::Equal,
1164                };
1165
1166                if !ordering.is_eq() {
1167                    return ordering;
1168                }
1169            }
1170            (Some(_), None) => return Ordering::Greater,
1171            (None, Some(_)) => return Ordering::Less,
1172            (None, None) => {
1173                // Deterministic tie-break: use natural sort to prefer lowercase when paths
1174                // are otherwise equal but still differ in casing.
1175                if !original_paths_equal {
1176                    return natural_sort(path_a.as_unix_str(), path_b.as_unix_str());
1177                }
1178                return Ordering::Equal;
1179            }
1180        }
1181    }
1182}
1183
1184pub fn compare_paths(
1185    (path_a, a_is_file): (&Path, bool),
1186    (path_b, b_is_file): (&Path, bool),
1187) -> Ordering {
1188    let mut components_a = path_a.components().peekable();
1189    let mut components_b = path_b.components().peekable();
1190
1191    loop {
1192        match (components_a.next(), components_b.next()) {
1193            (Some(component_a), Some(component_b)) => {
1194                let a_is_file = components_a.peek().is_none() && a_is_file;
1195                let b_is_file = components_b.peek().is_none() && b_is_file;
1196
1197                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
1198                    let path_a = Path::new(component_a.as_os_str());
1199                    let path_string_a = if a_is_file {
1200                        path_a.file_stem()
1201                    } else {
1202                        path_a.file_name()
1203                    }
1204                    .map(|s| s.to_string_lossy());
1205
1206                    let path_b = Path::new(component_b.as_os_str());
1207                    let path_string_b = if b_is_file {
1208                        path_b.file_stem()
1209                    } else {
1210                        path_b.file_name()
1211                    }
1212                    .map(|s| s.to_string_lossy());
1213
1214                    let compare_components = match (path_string_a, path_string_b) {
1215                        (Some(a), Some(b)) => natural_sort(&a, &b),
1216                        (Some(_), None) => Ordering::Greater,
1217                        (None, Some(_)) => Ordering::Less,
1218                        (None, None) => Ordering::Equal,
1219                    };
1220
1221                    compare_components.then_with(|| {
1222                        if a_is_file && b_is_file {
1223                            let ext_a = path_a.extension().unwrap_or_default();
1224                            let ext_b = path_b.extension().unwrap_or_default();
1225                            ext_a.cmp(ext_b)
1226                        } else {
1227                            Ordering::Equal
1228                        }
1229                    })
1230                });
1231
1232                if !ordering.is_eq() {
1233                    return ordering;
1234                }
1235            }
1236            (Some(_), None) => break Ordering::Greater,
1237            (None, Some(_)) => break Ordering::Less,
1238            (None, None) => break Ordering::Equal,
1239        }
1240    }
1241}
1242
1243#[derive(Debug, Clone, PartialEq, Eq)]
1244pub struct WslPath {
1245    pub distro: String,
1246
1247    // the reason this is an OsString and not any of the path types is that it needs to
1248    // represent a unix path (with '/' separators) on windows. `from_path` does this by
1249    // manually constructing it from the path components of a given windows path.
1250    pub path: std::ffi::OsString,
1251}
1252
1253impl WslPath {
1254    pub fn from_path<P: AsRef<Path>>(path: P) -> Option<WslPath> {
1255        if cfg!(not(target_os = "windows")) {
1256            return None;
1257        }
1258        use std::{
1259            ffi::OsString,
1260            path::{Component, Prefix},
1261        };
1262
1263        let mut components = path.as_ref().components();
1264        let Some(Component::Prefix(prefix)) = components.next() else {
1265            return None;
1266        };
1267        let (server, distro) = match prefix.kind() {
1268            Prefix::UNC(server, distro) => (server, distro),
1269            Prefix::VerbatimUNC(server, distro) => (server, distro),
1270            _ => return None,
1271        };
1272        let Some(Component::RootDir) = components.next() else {
1273            return None;
1274        };
1275
1276        let server_str = server.to_string_lossy();
1277        if server_str == "wsl.localhost" || server_str == "wsl$" {
1278            let mut result = OsString::from("");
1279            for c in components {
1280                use Component::*;
1281                match c {
1282                    Prefix(p) => unreachable!("got {p:?}, but already stripped prefix"),
1283                    RootDir => unreachable!("got root dir, but already stripped root"),
1284                    CurDir => continue,
1285                    ParentDir => result.push("/.."),
1286                    Normal(s) => {
1287                        result.push("/");
1288                        result.push(s);
1289                    }
1290                }
1291            }
1292            if result.is_empty() {
1293                result.push("/");
1294            }
1295            Some(WslPath {
1296                distro: distro.to_string_lossy().to_string(),
1297                path: result,
1298            })
1299        } else {
1300            None
1301        }
1302    }
1303}
1304
1305#[cfg(test)]
1306mod tests {
1307    use super::*;
1308    use util_macros::perf;
1309
1310    #[perf]
1311    fn compare_paths_with_dots() {
1312        let mut paths = vec![
1313            (Path::new("test_dirs"), false),
1314            (Path::new("test_dirs/1.46"), false),
1315            (Path::new("test_dirs/1.46/bar_1"), true),
1316            (Path::new("test_dirs/1.46/bar_2"), true),
1317            (Path::new("test_dirs/1.45"), false),
1318            (Path::new("test_dirs/1.45/foo_2"), true),
1319            (Path::new("test_dirs/1.45/foo_1"), true),
1320        ];
1321        paths.sort_by(|&a, &b| compare_paths(a, b));
1322        assert_eq!(
1323            paths,
1324            vec![
1325                (Path::new("test_dirs"), false),
1326                (Path::new("test_dirs/1.45"), false),
1327                (Path::new("test_dirs/1.45/foo_1"), true),
1328                (Path::new("test_dirs/1.45/foo_2"), true),
1329                (Path::new("test_dirs/1.46"), false),
1330                (Path::new("test_dirs/1.46/bar_1"), true),
1331                (Path::new("test_dirs/1.46/bar_2"), true),
1332            ]
1333        );
1334        let mut paths = vec![
1335            (Path::new("root1/one.txt"), true),
1336            (Path::new("root1/one.two.txt"), true),
1337        ];
1338        paths.sort_by(|&a, &b| compare_paths(a, b));
1339        assert_eq!(
1340            paths,
1341            vec![
1342                (Path::new("root1/one.txt"), true),
1343                (Path::new("root1/one.two.txt"), true),
1344            ]
1345        );
1346    }
1347
1348    #[perf]
1349    fn compare_paths_with_same_name_different_extensions() {
1350        let mut paths = vec![
1351            (Path::new("test_dirs/file.rs"), true),
1352            (Path::new("test_dirs/file.txt"), true),
1353            (Path::new("test_dirs/file.md"), true),
1354            (Path::new("test_dirs/file"), true),
1355            (Path::new("test_dirs/file.a"), true),
1356        ];
1357        paths.sort_by(|&a, &b| compare_paths(a, b));
1358        assert_eq!(
1359            paths,
1360            vec![
1361                (Path::new("test_dirs/file"), true),
1362                (Path::new("test_dirs/file.a"), true),
1363                (Path::new("test_dirs/file.md"), true),
1364                (Path::new("test_dirs/file.rs"), true),
1365                (Path::new("test_dirs/file.txt"), true),
1366            ]
1367        );
1368    }
1369
1370    #[perf]
1371    fn compare_paths_case_semi_sensitive() {
1372        let mut paths = vec![
1373            (Path::new("test_DIRS"), false),
1374            (Path::new("test_DIRS/foo_1"), true),
1375            (Path::new("test_DIRS/foo_2"), true),
1376            (Path::new("test_DIRS/bar"), true),
1377            (Path::new("test_DIRS/BAR"), true),
1378            (Path::new("test_dirs"), false),
1379            (Path::new("test_dirs/foo_1"), true),
1380            (Path::new("test_dirs/foo_2"), true),
1381            (Path::new("test_dirs/bar"), true),
1382            (Path::new("test_dirs/BAR"), true),
1383        ];
1384        paths.sort_by(|&a, &b| compare_paths(a, b));
1385        assert_eq!(
1386            paths,
1387            vec![
1388                (Path::new("test_dirs"), false),
1389                (Path::new("test_dirs/bar"), true),
1390                (Path::new("test_dirs/BAR"), true),
1391                (Path::new("test_dirs/foo_1"), true),
1392                (Path::new("test_dirs/foo_2"), true),
1393                (Path::new("test_DIRS"), false),
1394                (Path::new("test_DIRS/bar"), true),
1395                (Path::new("test_DIRS/BAR"), true),
1396                (Path::new("test_DIRS/foo_1"), true),
1397                (Path::new("test_DIRS/foo_2"), true),
1398            ]
1399        );
1400    }
1401
1402    #[perf]
1403    fn compare_paths_mixed_case_numeric_ordering() {
1404        let mut entries = [
1405            (Path::new(".config"), false),
1406            (Path::new("Dir1"), false),
1407            (Path::new("dir01"), false),
1408            (Path::new("dir2"), false),
1409            (Path::new("Dir02"), false),
1410            (Path::new("dir10"), false),
1411            (Path::new("Dir10"), false),
1412        ];
1413
1414        entries.sort_by(|&a, &b| compare_paths(a, b));
1415
1416        let ordered: Vec<&str> = entries
1417            .iter()
1418            .map(|(path, _)| path.to_str().unwrap())
1419            .collect();
1420
1421        assert_eq!(
1422            ordered,
1423            vec![
1424                ".config", "Dir1", "dir01", "dir2", "Dir02", "dir10", "Dir10"
1425            ]
1426        );
1427    }
1428
1429    #[perf]
1430    fn compare_rel_paths_mixed_case_insensitive() {
1431        // Test that mixed mode is case-insensitive
1432        let mut paths = vec![
1433            (RelPath::unix("zebra.txt").unwrap(), true),
1434            (RelPath::unix("Apple").unwrap(), false),
1435            (RelPath::unix("banana.rs").unwrap(), true),
1436            (RelPath::unix("Carrot").unwrap(), false),
1437            (RelPath::unix("aardvark.txt").unwrap(), true),
1438        ];
1439        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1440        // Case-insensitive: aardvark < Apple < banana < Carrot < zebra
1441        assert_eq!(
1442            paths,
1443            vec![
1444                (RelPath::unix("aardvark.txt").unwrap(), true),
1445                (RelPath::unix("Apple").unwrap(), false),
1446                (RelPath::unix("banana.rs").unwrap(), true),
1447                (RelPath::unix("Carrot").unwrap(), false),
1448                (RelPath::unix("zebra.txt").unwrap(), true),
1449            ]
1450        );
1451    }
1452
1453    #[perf]
1454    fn compare_rel_paths_files_first_basic() {
1455        // Test that files come before directories
1456        let mut paths = vec![
1457            (RelPath::unix("zebra.txt").unwrap(), true),
1458            (RelPath::unix("Apple").unwrap(), false),
1459            (RelPath::unix("banana.rs").unwrap(), true),
1460            (RelPath::unix("Carrot").unwrap(), false),
1461            (RelPath::unix("aardvark.txt").unwrap(), true),
1462        ];
1463        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1464        // Files first (case-insensitive), then directories (case-insensitive)
1465        assert_eq!(
1466            paths,
1467            vec![
1468                (RelPath::unix("aardvark.txt").unwrap(), true),
1469                (RelPath::unix("banana.rs").unwrap(), true),
1470                (RelPath::unix("zebra.txt").unwrap(), true),
1471                (RelPath::unix("Apple").unwrap(), false),
1472                (RelPath::unix("Carrot").unwrap(), false),
1473            ]
1474        );
1475    }
1476
1477    #[perf]
1478    fn compare_rel_paths_files_first_case_insensitive() {
1479        // Test case-insensitive sorting within files and directories
1480        let mut paths = vec![
1481            (RelPath::unix("Zebra.txt").unwrap(), true),
1482            (RelPath::unix("apple").unwrap(), false),
1483            (RelPath::unix("Banana.rs").unwrap(), true),
1484            (RelPath::unix("carrot").unwrap(), false),
1485            (RelPath::unix("Aardvark.txt").unwrap(), true),
1486        ];
1487        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1488        assert_eq!(
1489            paths,
1490            vec![
1491                (RelPath::unix("Aardvark.txt").unwrap(), true),
1492                (RelPath::unix("Banana.rs").unwrap(), true),
1493                (RelPath::unix("Zebra.txt").unwrap(), true),
1494                (RelPath::unix("apple").unwrap(), false),
1495                (RelPath::unix("carrot").unwrap(), false),
1496            ]
1497        );
1498    }
1499
1500    #[perf]
1501    fn compare_rel_paths_files_first_numeric() {
1502        // Test natural number sorting with files first
1503        let mut paths = vec![
1504            (RelPath::unix("file10.txt").unwrap(), true),
1505            (RelPath::unix("dir2").unwrap(), false),
1506            (RelPath::unix("file2.txt").unwrap(), true),
1507            (RelPath::unix("dir10").unwrap(), false),
1508            (RelPath::unix("file1.txt").unwrap(), true),
1509        ];
1510        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1511        assert_eq!(
1512            paths,
1513            vec![
1514                (RelPath::unix("file1.txt").unwrap(), true),
1515                (RelPath::unix("file2.txt").unwrap(), true),
1516                (RelPath::unix("file10.txt").unwrap(), true),
1517                (RelPath::unix("dir2").unwrap(), false),
1518                (RelPath::unix("dir10").unwrap(), false),
1519            ]
1520        );
1521    }
1522
1523    #[perf]
1524    fn compare_rel_paths_mixed_case() {
1525        // Test case-insensitive sorting with varied capitalization
1526        let mut paths = vec![
1527            (RelPath::unix("README.md").unwrap(), true),
1528            (RelPath::unix("readme.txt").unwrap(), true),
1529            (RelPath::unix("ReadMe.rs").unwrap(), true),
1530        ];
1531        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1532        // All "readme" variants should group together, sorted by extension
1533        assert_eq!(
1534            paths,
1535            vec![
1536                (RelPath::unix("readme.txt").unwrap(), true),
1537                (RelPath::unix("ReadMe.rs").unwrap(), true),
1538                (RelPath::unix("README.md").unwrap(), true),
1539            ]
1540        );
1541    }
1542
1543    #[perf]
1544    fn compare_rel_paths_mixed_files_and_dirs() {
1545        // Verify directories and files are still mixed
1546        let mut paths = vec![
1547            (RelPath::unix("file2.txt").unwrap(), true),
1548            (RelPath::unix("Dir1").unwrap(), false),
1549            (RelPath::unix("file1.txt").unwrap(), true),
1550            (RelPath::unix("dir2").unwrap(), false),
1551        ];
1552        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1553        // Case-insensitive: dir1, dir2, file1, file2 (all mixed)
1554        assert_eq!(
1555            paths,
1556            vec![
1557                (RelPath::unix("Dir1").unwrap(), false),
1558                (RelPath::unix("dir2").unwrap(), false),
1559                (RelPath::unix("file1.txt").unwrap(), true),
1560                (RelPath::unix("file2.txt").unwrap(), true),
1561            ]
1562        );
1563    }
1564
1565    #[perf]
1566    fn compare_rel_paths_mixed_with_nested_paths() {
1567        // Test that nested paths still work correctly
1568        let mut paths = vec![
1569            (RelPath::unix("src/main.rs").unwrap(), true),
1570            (RelPath::unix("Cargo.toml").unwrap(), true),
1571            (RelPath::unix("src").unwrap(), false),
1572            (RelPath::unix("target").unwrap(), false),
1573        ];
1574        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1575        assert_eq!(
1576            paths,
1577            vec![
1578                (RelPath::unix("Cargo.toml").unwrap(), true),
1579                (RelPath::unix("src").unwrap(), false),
1580                (RelPath::unix("src/main.rs").unwrap(), true),
1581                (RelPath::unix("target").unwrap(), false),
1582            ]
1583        );
1584    }
1585
1586    #[perf]
1587    fn compare_rel_paths_files_first_with_nested() {
1588        // Files come before directories, even with nested paths
1589        let mut paths = vec![
1590            (RelPath::unix("src/lib.rs").unwrap(), true),
1591            (RelPath::unix("README.md").unwrap(), true),
1592            (RelPath::unix("src").unwrap(), false),
1593            (RelPath::unix("tests").unwrap(), false),
1594        ];
1595        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1596        assert_eq!(
1597            paths,
1598            vec![
1599                (RelPath::unix("README.md").unwrap(), true),
1600                (RelPath::unix("src").unwrap(), false),
1601                (RelPath::unix("src/lib.rs").unwrap(), true),
1602                (RelPath::unix("tests").unwrap(), false),
1603            ]
1604        );
1605    }
1606
1607    #[perf]
1608    fn compare_rel_paths_mixed_dotfiles() {
1609        // Test that dotfiles are handled correctly in mixed mode
1610        let mut paths = vec![
1611            (RelPath::unix(".gitignore").unwrap(), true),
1612            (RelPath::unix("README.md").unwrap(), true),
1613            (RelPath::unix(".github").unwrap(), false),
1614            (RelPath::unix("src").unwrap(), false),
1615        ];
1616        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1617        assert_eq!(
1618            paths,
1619            vec![
1620                (RelPath::unix(".github").unwrap(), false),
1621                (RelPath::unix(".gitignore").unwrap(), true),
1622                (RelPath::unix("README.md").unwrap(), true),
1623                (RelPath::unix("src").unwrap(), false),
1624            ]
1625        );
1626    }
1627
1628    #[perf]
1629    fn compare_rel_paths_files_first_dotfiles() {
1630        // Test that dotfiles come first when they're files
1631        let mut paths = vec![
1632            (RelPath::unix(".gitignore").unwrap(), true),
1633            (RelPath::unix("README.md").unwrap(), true),
1634            (RelPath::unix(".github").unwrap(), false),
1635            (RelPath::unix("src").unwrap(), false),
1636        ];
1637        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1638        assert_eq!(
1639            paths,
1640            vec![
1641                (RelPath::unix(".gitignore").unwrap(), true),
1642                (RelPath::unix("README.md").unwrap(), true),
1643                (RelPath::unix(".github").unwrap(), false),
1644                (RelPath::unix("src").unwrap(), false),
1645            ]
1646        );
1647    }
1648
1649    #[perf]
1650    fn compare_rel_paths_mixed_same_stem_different_extension() {
1651        // Files with same stem but different extensions should sort by extension
1652        let mut paths = vec![
1653            (RelPath::unix("file.rs").unwrap(), true),
1654            (RelPath::unix("file.md").unwrap(), true),
1655            (RelPath::unix("file.txt").unwrap(), true),
1656        ];
1657        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1658        assert_eq!(
1659            paths,
1660            vec![
1661                (RelPath::unix("file.txt").unwrap(), true),
1662                (RelPath::unix("file.rs").unwrap(), true),
1663                (RelPath::unix("file.md").unwrap(), true),
1664            ]
1665        );
1666    }
1667
1668    #[perf]
1669    fn compare_rel_paths_files_first_same_stem() {
1670        // Same stem files should still sort by extension with files_first
1671        let mut paths = vec![
1672            (RelPath::unix("main.rs").unwrap(), true),
1673            (RelPath::unix("main.c").unwrap(), true),
1674            (RelPath::unix("main").unwrap(), false),
1675        ];
1676        paths.sort_by(|&a, &b| compare_rel_paths_files_first(a, b));
1677        assert_eq!(
1678            paths,
1679            vec![
1680                (RelPath::unix("main.c").unwrap(), true),
1681                (RelPath::unix("main.rs").unwrap(), true),
1682                (RelPath::unix("main").unwrap(), false),
1683            ]
1684        );
1685    }
1686
1687    #[perf]
1688    fn compare_rel_paths_mixed_deep_nesting() {
1689        // Test sorting with deeply nested paths
1690        let mut paths = vec![
1691            (RelPath::unix("a/b/c.txt").unwrap(), true),
1692            (RelPath::unix("A/B.txt").unwrap(), true),
1693            (RelPath::unix("a.txt").unwrap(), true),
1694            (RelPath::unix("A.txt").unwrap(), true),
1695        ];
1696        paths.sort_by(|&a, &b| compare_rel_paths_mixed(a, b));
1697        assert_eq!(
1698            paths,
1699            vec![
1700                (RelPath::unix("A/B.txt").unwrap(), true),
1701                (RelPath::unix("a/b/c.txt").unwrap(), true),
1702                (RelPath::unix("a.txt").unwrap(), true),
1703                (RelPath::unix("A.txt").unwrap(), true),
1704            ]
1705        );
1706    }
1707
1708    #[perf]
1709    fn path_with_position_parse_posix_path() {
1710        // Test POSIX filename edge cases
1711        // Read more at https://en.wikipedia.org/wiki/Filename
1712        assert_eq!(
1713            PathWithPosition::parse_str("test_file"),
1714            PathWithPosition {
1715                path: PathBuf::from("test_file"),
1716                row: None,
1717                column: None
1718            }
1719        );
1720
1721        assert_eq!(
1722            PathWithPosition::parse_str("a:bc:.zip:1"),
1723            PathWithPosition {
1724                path: PathBuf::from("a:bc:.zip"),
1725                row: Some(1),
1726                column: None
1727            }
1728        );
1729
1730        assert_eq!(
1731            PathWithPosition::parse_str("one.second.zip:1"),
1732            PathWithPosition {
1733                path: PathBuf::from("one.second.zip"),
1734                row: Some(1),
1735                column: None
1736            }
1737        );
1738
1739        // Trim off trailing `:`s for otherwise valid input.
1740        assert_eq!(
1741            PathWithPosition::parse_str("test_file:10:1:"),
1742            PathWithPosition {
1743                path: PathBuf::from("test_file"),
1744                row: Some(10),
1745                column: Some(1)
1746            }
1747        );
1748
1749        assert_eq!(
1750            PathWithPosition::parse_str("test_file.rs:"),
1751            PathWithPosition {
1752                path: PathBuf::from("test_file.rs"),
1753                row: None,
1754                column: None
1755            }
1756        );
1757
1758        assert_eq!(
1759            PathWithPosition::parse_str("test_file.rs:1:"),
1760            PathWithPosition {
1761                path: PathBuf::from("test_file.rs"),
1762                row: Some(1),
1763                column: None
1764            }
1765        );
1766
1767        assert_eq!(
1768            PathWithPosition::parse_str("ab\ncd"),
1769            PathWithPosition {
1770                path: PathBuf::from("ab\ncd"),
1771                row: None,
1772                column: None
1773            }
1774        );
1775
1776        assert_eq!(
1777            PathWithPosition::parse_str("👋\nab"),
1778            PathWithPosition {
1779                path: PathBuf::from("👋\nab"),
1780                row: None,
1781                column: None
1782            }
1783        );
1784
1785        assert_eq!(
1786            PathWithPosition::parse_str("Types.hs:(617,9)-(670,28):"),
1787            PathWithPosition {
1788                path: PathBuf::from("Types.hs"),
1789                row: Some(617),
1790                column: Some(9),
1791            }
1792        );
1793    }
1794
1795    #[perf]
1796    #[cfg(not(target_os = "windows"))]
1797    fn path_with_position_parse_posix_path_with_suffix() {
1798        assert_eq!(
1799            PathWithPosition::parse_str("foo/bar:34:in"),
1800            PathWithPosition {
1801                path: PathBuf::from("foo/bar"),
1802                row: Some(34),
1803                column: None,
1804            }
1805        );
1806        assert_eq!(
1807            PathWithPosition::parse_str("foo/bar.rs:1902:::15:"),
1808            PathWithPosition {
1809                path: PathBuf::from("foo/bar.rs:1902"),
1810                row: Some(15),
1811                column: None
1812            }
1813        );
1814
1815        assert_eq!(
1816            PathWithPosition::parse_str("app-editors:zed-0.143.6:20240710-201212.log:34:"),
1817            PathWithPosition {
1818                path: PathBuf::from("app-editors:zed-0.143.6:20240710-201212.log"),
1819                row: Some(34),
1820                column: None,
1821            }
1822        );
1823
1824        assert_eq!(
1825            PathWithPosition::parse_str("crates/file_finder/src/file_finder.rs:1902:13:"),
1826            PathWithPosition {
1827                path: PathBuf::from("crates/file_finder/src/file_finder.rs"),
1828                row: Some(1902),
1829                column: Some(13),
1830            }
1831        );
1832
1833        assert_eq!(
1834            PathWithPosition::parse_str("crate/utils/src/test:today.log:34"),
1835            PathWithPosition {
1836                path: PathBuf::from("crate/utils/src/test:today.log"),
1837                row: Some(34),
1838                column: None,
1839            }
1840        );
1841        assert_eq!(
1842            PathWithPosition::parse_str("/testing/out/src/file_finder.odin(7:15)"),
1843            PathWithPosition {
1844                path: PathBuf::from("/testing/out/src/file_finder.odin"),
1845                row: Some(7),
1846                column: Some(15),
1847            }
1848        );
1849    }
1850
1851    #[perf]
1852    #[cfg(target_os = "windows")]
1853    fn path_with_position_parse_windows_path() {
1854        assert_eq!(
1855            PathWithPosition::parse_str("crates\\utils\\paths.rs"),
1856            PathWithPosition {
1857                path: PathBuf::from("crates\\utils\\paths.rs"),
1858                row: None,
1859                column: None
1860            }
1861        );
1862
1863        assert_eq!(
1864            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs"),
1865            PathWithPosition {
1866                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1867                row: None,
1868                column: None
1869            }
1870        );
1871    }
1872
1873    #[perf]
1874    #[cfg(target_os = "windows")]
1875    fn path_with_position_parse_windows_path_with_suffix() {
1876        assert_eq!(
1877            PathWithPosition::parse_str("crates\\utils\\paths.rs:101"),
1878            PathWithPosition {
1879                path: PathBuf::from("crates\\utils\\paths.rs"),
1880                row: Some(101),
1881                column: None
1882            }
1883        );
1884
1885        assert_eq!(
1886            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1:20"),
1887            PathWithPosition {
1888                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1889                row: Some(1),
1890                column: Some(20)
1891            }
1892        );
1893
1894        assert_eq!(
1895            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13)"),
1896            PathWithPosition {
1897                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1898                row: Some(1902),
1899                column: Some(13)
1900            }
1901        );
1902
1903        // Trim off trailing `:`s for otherwise valid input.
1904        assert_eq!(
1905            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:"),
1906            PathWithPosition {
1907                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1908                row: Some(1902),
1909                column: Some(13)
1910            }
1911        );
1912
1913        assert_eq!(
1914            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:15:"),
1915            PathWithPosition {
1916                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
1917                row: Some(13),
1918                column: Some(15)
1919            }
1920        );
1921
1922        assert_eq!(
1923            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:::15:"),
1924            PathWithPosition {
1925                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
1926                row: Some(15),
1927                column: None
1928            }
1929        );
1930
1931        assert_eq!(
1932            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902,13):"),
1933            PathWithPosition {
1934                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1935                row: Some(1902),
1936                column: Some(13),
1937            }
1938        );
1939
1940        assert_eq!(
1941            PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902):"),
1942            PathWithPosition {
1943                path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
1944                row: Some(1902),
1945                column: None,
1946            }
1947        );
1948
1949        assert_eq!(
1950            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs:1902:13:"),
1951            PathWithPosition {
1952                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1953                row: Some(1902),
1954                column: Some(13),
1955            }
1956        );
1957
1958        assert_eq!(
1959            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13):"),
1960            PathWithPosition {
1961                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1962                row: Some(1902),
1963                column: Some(13),
1964            }
1965        );
1966
1967        assert_eq!(
1968            PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902):"),
1969            PathWithPosition {
1970                path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
1971                row: Some(1902),
1972                column: None,
1973            }
1974        );
1975
1976        assert_eq!(
1977            PathWithPosition::parse_str("crates/utils/paths.rs:101"),
1978            PathWithPosition {
1979                path: PathBuf::from("crates\\utils\\paths.rs"),
1980                row: Some(101),
1981                column: None,
1982            }
1983        );
1984    }
1985
1986    #[perf]
1987    fn test_path_compact() {
1988        let path: PathBuf = [
1989            home_dir().to_string_lossy().into_owned(),
1990            "some_file.txt".to_string(),
1991        ]
1992        .iter()
1993        .collect();
1994        if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
1995            assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
1996        } else {
1997            assert_eq!(path.compact().to_str(), path.to_str());
1998        }
1999    }
2000
2001    #[perf]
2002    fn test_extension_or_hidden_file_name() {
2003        // No dots in name
2004        let path = Path::new("/a/b/c/file_name.rs");
2005        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2006
2007        // Single dot in name
2008        let path = Path::new("/a/b/c/file.name.rs");
2009        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2010
2011        // Multiple dots in name
2012        let path = Path::new("/a/b/c/long.file.name.rs");
2013        assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2014
2015        // Hidden file, no extension
2016        let path = Path::new("/a/b/c/.gitignore");
2017        assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
2018
2019        // Hidden file, with extension
2020        let path = Path::new("/a/b/c/.eslintrc.js");
2021        assert_eq!(path.extension_or_hidden_file_name(), Some("eslintrc.js"));
2022    }
2023
2024    #[perf]
2025    fn edge_of_glob() {
2026        let path = Path::new("/work/node_modules");
2027        let path_matcher =
2028            PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
2029        assert!(
2030            path_matcher.is_match(path),
2031            "Path matcher should match {path:?}"
2032        );
2033    }
2034
2035    #[perf]
2036    fn file_in_dirs() {
2037        let path = Path::new("/work/.env");
2038        let path_matcher = PathMatcher::new(&["**/.env".to_owned()], PathStyle::Posix).unwrap();
2039        assert!(
2040            path_matcher.is_match(path),
2041            "Path matcher should match {path:?}"
2042        );
2043        let path = Path::new("/work/package.json");
2044        assert!(
2045            !path_matcher.is_match(path),
2046            "Path matcher should not match {path:?}"
2047        );
2048    }
2049
2050    #[perf]
2051    fn project_search() {
2052        let path = Path::new("/Users/someonetoignore/work/zed/zed.dev/node_modules");
2053        let path_matcher =
2054            PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap();
2055        assert!(
2056            path_matcher.is_match(path),
2057            "Path matcher should match {path:?}"
2058        );
2059    }
2060
2061    #[perf]
2062    #[cfg(target_os = "windows")]
2063    fn test_sanitized_path() {
2064        let path = Path::new("C:\\Users\\someone\\test_file.rs");
2065        let sanitized_path = SanitizedPath::new(path);
2066        assert_eq!(
2067            sanitized_path.to_string(),
2068            "C:\\Users\\someone\\test_file.rs"
2069        );
2070
2071        let path = Path::new("\\\\?\\C:\\Users\\someone\\test_file.rs");
2072        let sanitized_path = SanitizedPath::new(path);
2073        assert_eq!(
2074            sanitized_path.to_string(),
2075            "C:\\Users\\someone\\test_file.rs"
2076        );
2077    }
2078
2079    #[perf]
2080    fn test_compare_numeric_segments() {
2081        // Helper function to create peekable iterators and test
2082        fn compare(a: &str, b: &str) -> Ordering {
2083            let mut a_iter = a.chars().peekable();
2084            let mut b_iter = b.chars().peekable();
2085
2086            let result = compare_numeric_segments(&mut a_iter, &mut b_iter);
2087
2088            // Verify iterators advanced correctly
2089            assert!(
2090                !a_iter.next().is_some_and(|c| c.is_ascii_digit()),
2091                "Iterator a should have consumed all digits"
2092            );
2093            assert!(
2094                !b_iter.next().is_some_and(|c| c.is_ascii_digit()),
2095                "Iterator b should have consumed all digits"
2096            );
2097
2098            result
2099        }
2100
2101        // Basic numeric comparisons
2102        assert_eq!(compare("0", "0"), Ordering::Equal);
2103        assert_eq!(compare("1", "2"), Ordering::Less);
2104        assert_eq!(compare("9", "10"), Ordering::Less);
2105        assert_eq!(compare("10", "9"), Ordering::Greater);
2106        assert_eq!(compare("99", "100"), Ordering::Less);
2107
2108        // Leading zeros
2109        assert_eq!(compare("0", "00"), Ordering::Less);
2110        assert_eq!(compare("00", "0"), Ordering::Greater);
2111        assert_eq!(compare("01", "1"), Ordering::Greater);
2112        assert_eq!(compare("001", "1"), Ordering::Greater);
2113        assert_eq!(compare("001", "01"), Ordering::Greater);
2114
2115        // Same value different representation
2116        assert_eq!(compare("000100", "100"), Ordering::Greater);
2117        assert_eq!(compare("100", "0100"), Ordering::Less);
2118        assert_eq!(compare("0100", "00100"), Ordering::Less);
2119
2120        // Large numbers
2121        assert_eq!(compare("9999999999", "10000000000"), Ordering::Less);
2122        assert_eq!(
2123            compare(
2124                "340282366920938463463374607431768211455", // u128::MAX
2125                "340282366920938463463374607431768211456"
2126            ),
2127            Ordering::Less
2128        );
2129        assert_eq!(
2130            compare(
2131                "340282366920938463463374607431768211456", // > u128::MAX
2132                "340282366920938463463374607431768211455"
2133            ),
2134            Ordering::Greater
2135        );
2136
2137        // Iterator advancement verification
2138        let mut a_iter = "123abc".chars().peekable();
2139        let mut b_iter = "456def".chars().peekable();
2140
2141        compare_numeric_segments(&mut a_iter, &mut b_iter);
2142
2143        assert_eq!(a_iter.collect::<String>(), "abc");
2144        assert_eq!(b_iter.collect::<String>(), "def");
2145    }
2146
2147    #[perf]
2148    fn test_natural_sort() {
2149        // Basic alphanumeric
2150        assert_eq!(natural_sort("a", "b"), Ordering::Less);
2151        assert_eq!(natural_sort("b", "a"), Ordering::Greater);
2152        assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2153
2154        // Case sensitivity
2155        assert_eq!(natural_sort("a", "A"), Ordering::Less);
2156        assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2157        assert_eq!(natural_sort("aA", "aa"), Ordering::Greater);
2158        assert_eq!(natural_sort("aa", "aA"), Ordering::Less);
2159
2160        // Numbers
2161        assert_eq!(natural_sort("1", "2"), Ordering::Less);
2162        assert_eq!(natural_sort("2", "10"), Ordering::Less);
2163        assert_eq!(natural_sort("02", "10"), Ordering::Less);
2164        assert_eq!(natural_sort("02", "2"), Ordering::Greater);
2165
2166        // Mixed alphanumeric
2167        assert_eq!(natural_sort("a1", "a2"), Ordering::Less);
2168        assert_eq!(natural_sort("a2", "a10"), Ordering::Less);
2169        assert_eq!(natural_sort("a02", "a2"), Ordering::Greater);
2170        assert_eq!(natural_sort("a1b", "a1c"), Ordering::Less);
2171
2172        // Multiple numeric segments
2173        assert_eq!(natural_sort("1a2", "1a10"), Ordering::Less);
2174        assert_eq!(natural_sort("1a10", "1a2"), Ordering::Greater);
2175        assert_eq!(natural_sort("2a1", "10a1"), Ordering::Less);
2176
2177        // Special characters
2178        assert_eq!(natural_sort("a-1", "a-2"), Ordering::Less);
2179        assert_eq!(natural_sort("a_1", "a_2"), Ordering::Less);
2180        assert_eq!(natural_sort("a.1", "a.2"), Ordering::Less);
2181
2182        // Unicode
2183        assert_eq!(natural_sort("文1", "文2"), Ordering::Less);
2184        assert_eq!(natural_sort("文2", "文10"), Ordering::Less);
2185        assert_eq!(natural_sort("🔤1", "🔤2"), Ordering::Less);
2186
2187        // Empty and special cases
2188        assert_eq!(natural_sort("", ""), Ordering::Equal);
2189        assert_eq!(natural_sort("", "a"), Ordering::Less);
2190        assert_eq!(natural_sort("a", ""), Ordering::Greater);
2191        assert_eq!(natural_sort(" ", "  "), Ordering::Less);
2192
2193        // Mixed everything
2194        assert_eq!(natural_sort("File-1.txt", "File-2.txt"), Ordering::Less);
2195        assert_eq!(natural_sort("File-02.txt", "File-2.txt"), Ordering::Greater);
2196        assert_eq!(natural_sort("File-2.txt", "File-10.txt"), Ordering::Less);
2197        assert_eq!(natural_sort("File_A1", "File_A2"), Ordering::Less);
2198        assert_eq!(natural_sort("File_a1", "File_A1"), Ordering::Less);
2199    }
2200
2201    #[perf]
2202    fn test_compare_paths() {
2203        // Helper function for cleaner tests
2204        fn compare(a: &str, is_a_file: bool, b: &str, is_b_file: bool) -> Ordering {
2205            compare_paths((Path::new(a), is_a_file), (Path::new(b), is_b_file))
2206        }
2207
2208        // Basic path comparison
2209        assert_eq!(compare("a", true, "b", true), Ordering::Less);
2210        assert_eq!(compare("b", true, "a", true), Ordering::Greater);
2211        assert_eq!(compare("a", true, "a", true), Ordering::Equal);
2212
2213        // Files vs Directories
2214        assert_eq!(compare("a", true, "a", false), Ordering::Greater);
2215        assert_eq!(compare("a", false, "a", true), Ordering::Less);
2216        assert_eq!(compare("b", false, "a", true), Ordering::Less);
2217
2218        // Extensions
2219        assert_eq!(compare("a.txt", true, "a.md", true), Ordering::Greater);
2220        assert_eq!(compare("a.md", true, "a.txt", true), Ordering::Less);
2221        assert_eq!(compare("a", true, "a.txt", true), Ordering::Less);
2222
2223        // Nested paths
2224        assert_eq!(compare("dir/a", true, "dir/b", true), Ordering::Less);
2225        assert_eq!(compare("dir1/a", true, "dir2/a", true), Ordering::Less);
2226        assert_eq!(compare("dir/sub/a", true, "dir/a", true), Ordering::Less);
2227
2228        // Case sensitivity in paths
2229        assert_eq!(
2230            compare("Dir/file", true, "dir/file", true),
2231            Ordering::Greater
2232        );
2233        assert_eq!(
2234            compare("dir/File", true, "dir/file", true),
2235            Ordering::Greater
2236        );
2237        assert_eq!(compare("dir/file", true, "Dir/File", true), Ordering::Less);
2238
2239        // Hidden files and special names
2240        assert_eq!(compare(".hidden", true, "visible", true), Ordering::Less);
2241        assert_eq!(compare("_special", true, "normal", true), Ordering::Less);
2242        assert_eq!(compare(".config", false, ".data", false), Ordering::Less);
2243
2244        // Mixed numeric paths
2245        assert_eq!(
2246            compare("dir1/file", true, "dir2/file", true),
2247            Ordering::Less
2248        );
2249        assert_eq!(
2250            compare("dir2/file", true, "dir10/file", true),
2251            Ordering::Less
2252        );
2253        assert_eq!(
2254            compare("dir02/file", true, "dir2/file", true),
2255            Ordering::Greater
2256        );
2257
2258        // Root paths
2259        assert_eq!(compare("/a", true, "/b", true), Ordering::Less);
2260        assert_eq!(compare("/", false, "/a", true), Ordering::Less);
2261
2262        // Complex real-world examples
2263        assert_eq!(
2264            compare("project/src/main.rs", true, "project/src/lib.rs", true),
2265            Ordering::Greater
2266        );
2267        assert_eq!(
2268            compare(
2269                "project/tests/test_1.rs",
2270                true,
2271                "project/tests/test_2.rs",
2272                true
2273            ),
2274            Ordering::Less
2275        );
2276        assert_eq!(
2277            compare(
2278                "project/v1.0.0/README.md",
2279                true,
2280                "project/v1.10.0/README.md",
2281                true
2282            ),
2283            Ordering::Less
2284        );
2285    }
2286
2287    #[perf]
2288    fn test_natural_sort_case_sensitivity() {
2289        std::thread::sleep(std::time::Duration::from_millis(100));
2290        // Same letter different case - lowercase should come first
2291        assert_eq!(natural_sort("a", "A"), Ordering::Less);
2292        assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2293        assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2294        assert_eq!(natural_sort("A", "A"), Ordering::Equal);
2295
2296        // Mixed case strings
2297        assert_eq!(natural_sort("aaa", "AAA"), Ordering::Less);
2298        assert_eq!(natural_sort("AAA", "aaa"), Ordering::Greater);
2299        assert_eq!(natural_sort("aAa", "AaA"), Ordering::Less);
2300
2301        // Different letters
2302        assert_eq!(natural_sort("a", "b"), Ordering::Less);
2303        assert_eq!(natural_sort("A", "b"), Ordering::Less);
2304        assert_eq!(natural_sort("a", "B"), Ordering::Less);
2305    }
2306
2307    #[perf]
2308    fn test_natural_sort_with_numbers() {
2309        // Basic number ordering
2310        assert_eq!(natural_sort("file1", "file2"), Ordering::Less);
2311        assert_eq!(natural_sort("file2", "file10"), Ordering::Less);
2312        assert_eq!(natural_sort("file10", "file2"), Ordering::Greater);
2313
2314        // Numbers in different positions
2315        assert_eq!(natural_sort("1file", "2file"), Ordering::Less);
2316        assert_eq!(natural_sort("file1text", "file2text"), Ordering::Less);
2317        assert_eq!(natural_sort("text1file", "text2file"), Ordering::Less);
2318
2319        // Multiple numbers in string
2320        assert_eq!(natural_sort("file1-2", "file1-10"), Ordering::Less);
2321        assert_eq!(natural_sort("2-1file", "10-1file"), Ordering::Less);
2322
2323        // Leading zeros
2324        assert_eq!(natural_sort("file002", "file2"), Ordering::Greater);
2325        assert_eq!(natural_sort("file002", "file10"), Ordering::Less);
2326
2327        // Very large numbers
2328        assert_eq!(
2329            natural_sort("file999999999999999999999", "file999999999999999999998"),
2330            Ordering::Greater
2331        );
2332
2333        // u128 edge cases
2334
2335        // Numbers near u128::MAX (340,282,366,920,938,463,463,374,607,431,768,211,455)
2336        assert_eq!(
2337            natural_sort(
2338                "file340282366920938463463374607431768211454",
2339                "file340282366920938463463374607431768211455"
2340            ),
2341            Ordering::Less
2342        );
2343
2344        // Equal length numbers that overflow u128
2345        assert_eq!(
2346            natural_sort(
2347                "file340282366920938463463374607431768211456",
2348                "file340282366920938463463374607431768211455"
2349            ),
2350            Ordering::Greater
2351        );
2352
2353        // Different length numbers that overflow u128
2354        assert_eq!(
2355            natural_sort(
2356                "file3402823669209384634633746074317682114560",
2357                "file340282366920938463463374607431768211455"
2358            ),
2359            Ordering::Greater
2360        );
2361
2362        // Leading zeros with numbers near u128::MAX
2363        assert_eq!(
2364            natural_sort(
2365                "file0340282366920938463463374607431768211455",
2366                "file340282366920938463463374607431768211455"
2367            ),
2368            Ordering::Greater
2369        );
2370
2371        // Very large numbers with different lengths (both overflow u128)
2372        assert_eq!(
2373            natural_sort(
2374                "file999999999999999999999999999999999999999999999999",
2375                "file9999999999999999999999999999999999999999999999999"
2376            ),
2377            Ordering::Less
2378        );
2379    }
2380
2381    #[perf]
2382    fn test_natural_sort_case_sensitive() {
2383        // Numerically smaller values come first.
2384        assert_eq!(natural_sort("File1", "file2"), Ordering::Less);
2385        assert_eq!(natural_sort("file1", "File2"), Ordering::Less);
2386
2387        // Numerically equal values: the case-insensitive comparison decides first.
2388        // Case-sensitive comparison only occurs when both are equal case-insensitively.
2389        assert_eq!(natural_sort("Dir1", "dir01"), Ordering::Less);
2390        assert_eq!(natural_sort("dir2", "Dir02"), Ordering::Less);
2391        assert_eq!(natural_sort("dir2", "dir02"), Ordering::Less);
2392
2393        // Numerically equal and case-insensitively equal:
2394        // the lexicographically smaller (case-sensitive) one wins.
2395        assert_eq!(natural_sort("dir1", "Dir1"), Ordering::Less);
2396        assert_eq!(natural_sort("dir02", "Dir02"), Ordering::Less);
2397        assert_eq!(natural_sort("dir10", "Dir10"), Ordering::Less);
2398    }
2399
2400    #[perf]
2401    fn test_natural_sort_edge_cases() {
2402        // Empty strings
2403        assert_eq!(natural_sort("", ""), Ordering::Equal);
2404        assert_eq!(natural_sort("", "a"), Ordering::Less);
2405        assert_eq!(natural_sort("a", ""), Ordering::Greater);
2406
2407        // Special characters
2408        assert_eq!(natural_sort("file-1", "file_1"), Ordering::Less);
2409        assert_eq!(natural_sort("file.1", "file_1"), Ordering::Less);
2410        assert_eq!(natural_sort("file 1", "file_1"), Ordering::Less);
2411
2412        // Unicode characters
2413        // 9312 vs 9313
2414        assert_eq!(natural_sort("file①", "file②"), Ordering::Less);
2415        // 9321 vs 9313
2416        assert_eq!(natural_sort("file⑩", "file②"), Ordering::Greater);
2417        // 28450 vs 23383
2418        assert_eq!(natural_sort("file漢", "file字"), Ordering::Greater);
2419
2420        // Mixed alphanumeric with special chars
2421        assert_eq!(natural_sort("file-1a", "file-1b"), Ordering::Less);
2422        assert_eq!(natural_sort("file-1.2", "file-1.10"), Ordering::Less);
2423        assert_eq!(natural_sort("file-1.10", "file-1.2"), Ordering::Greater);
2424    }
2425
2426    #[test]
2427    fn test_multiple_extensions() {
2428        // No extensions
2429        let path = Path::new("/a/b/c/file_name");
2430        assert_eq!(path.multiple_extensions(), None);
2431
2432        // Only one extension
2433        let path = Path::new("/a/b/c/file_name.tsx");
2434        assert_eq!(path.multiple_extensions(), None);
2435
2436        // Stories sample extension
2437        let path = Path::new("/a/b/c/file_name.stories.tsx");
2438        assert_eq!(path.multiple_extensions(), Some("stories.tsx".to_string()));
2439
2440        // Longer sample extension
2441        let path = Path::new("/a/b/c/long.app.tar.gz");
2442        assert_eq!(path.multiple_extensions(), Some("app.tar.gz".to_string()));
2443    }
2444
2445    #[test]
2446    fn test_strip_path_suffix() {
2447        let base = Path::new("/a/b/c/file_name");
2448        let suffix = Path::new("file_name");
2449        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
2450
2451        let base = Path::new("/a/b/c/file_name.tsx");
2452        let suffix = Path::new("file_name.tsx");
2453        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
2454
2455        let base = Path::new("/a/b/c/file_name.stories.tsx");
2456        let suffix = Path::new("c/file_name.stories.tsx");
2457        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b")));
2458
2459        let base = Path::new("/a/b/c/long.app.tar.gz");
2460        let suffix = Path::new("b/c/long.app.tar.gz");
2461        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a")));
2462
2463        let base = Path::new("/a/b/c/long.app.tar.gz");
2464        let suffix = Path::new("/a/b/c/long.app.tar.gz");
2465        assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("")));
2466
2467        let base = Path::new("/a/b/c/long.app.tar.gz");
2468        let suffix = Path::new("/a/b/c/no_match.app.tar.gz");
2469        assert_eq!(strip_path_suffix(base, suffix), None);
2470
2471        let base = Path::new("/a/b/c/long.app.tar.gz");
2472        let suffix = Path::new("app.tar.gz");
2473        assert_eq!(strip_path_suffix(base, suffix), None);
2474    }
2475
2476    #[cfg(target_os = "windows")]
2477    #[test]
2478    fn test_wsl_path() {
2479        use super::WslPath;
2480        let path = "/a/b/c";
2481        assert_eq!(WslPath::from_path(&path), None);
2482
2483        let path = r"\\wsl.localhost";
2484        assert_eq!(WslPath::from_path(&path), None);
2485
2486        let path = r"\\wsl.localhost\Distro";
2487        assert_eq!(
2488            WslPath::from_path(&path),
2489            Some(WslPath {
2490                distro: "Distro".to_owned(),
2491                path: "/".into(),
2492            })
2493        );
2494
2495        let path = r"\\wsl.localhost\Distro\blue";
2496        assert_eq!(
2497            WslPath::from_path(&path),
2498            Some(WslPath {
2499                distro: "Distro".to_owned(),
2500                path: "/blue".into()
2501            })
2502        );
2503
2504        let path = r"\\wsl$\archlinux\tomato\.\paprika\..\aubergine.txt";
2505        assert_eq!(
2506            WslPath::from_path(&path),
2507            Some(WslPath {
2508                distro: "archlinux".to_owned(),
2509                path: "/tomato/paprika/../aubergine.txt".into()
2510            })
2511        );
2512
2513        let path = r"\\windows.localhost\Distro\foo";
2514        assert_eq!(WslPath::from_path(&path), None);
2515    }
2516}