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