paths.rs

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