1use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder};
2use itertools::Itertools;
3use regex::Regex;
4use serde::{Deserialize, Serialize};
5use std::cmp::Ordering;
6use std::error::Error;
7use std::fmt::{Display, Formatter};
8use std::mem;
9use std::path::StripPrefixError;
10use std::sync::Arc;
11use std::{
12 ffi::OsStr,
13 path::{Path, PathBuf},
14 sync::LazyLock,
15};
16
17use path::rel_path::RelPath;
18use path::rel_path::RelPathBuf;
19
20pub use path::PathStyle;
21
22#[cfg(not(target_family = "wasm"))]
27pub fn home_dir() -> &'static PathBuf {
28 static HOME_DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
29 HOME_DIR.get_or_init(|| {
30 if cfg!(test) {
31 if cfg!(target_os = "macos") {
32 PathBuf::from("/Users/zed")
33 } else if cfg!(target_os = "windows") {
34 PathBuf::from("C:\\Users\\zed")
35 } else {
36 PathBuf::from("/home/zed")
37 }
38 } else {
39 dirs::home_dir().expect("failed to determine home directory")
40 }
41 })
42}
43
44pub trait PathExt {
45 fn compact(&self) -> PathBuf;
54
55 fn extension_or_hidden_file_name(&self) -> Option<&str>;
57
58 fn try_from_bytes<'a>(bytes: &'a [u8]) -> anyhow::Result<Self>
59 where
60 Self: From<&'a Path>,
61 {
62 path::try_from_bytes::<Self>(bytes)
63 }
64
65 fn local_to_wsl(&self) -> Option<PathBuf>;
68
69 fn multiple_extensions(&self) -> Option<String>;
74
75 #[cfg(not(target_family = "wasm"))]
77 fn try_shell_safe(&self, shell_kind: crate::shell::ShellKind) -> anyhow::Result<String>;
78}
79
80impl<T: AsRef<Path>> PathExt for T {
81 fn compact(&self) -> PathBuf {
82 #[cfg(target_family = "wasm")]
83 {
84 self.as_ref().to_path_buf()
85 }
86 #[cfg(not(target_family = "wasm"))]
87 if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
88 match self.as_ref().strip_prefix(home_dir().as_path()) {
89 Ok(relative_path) => {
90 let mut shortened_path = PathBuf::new();
91 shortened_path.push("~");
92 shortened_path.push(relative_path);
93 shortened_path
94 }
95 Err(_) => self.as_ref().to_path_buf(),
96 }
97 } else {
98 self.as_ref().to_path_buf()
99 }
100 }
101
102 fn extension_or_hidden_file_name(&self) -> Option<&str> {
103 let path = self.as_ref();
104 let file_name = path.file_name()?.to_str()?;
105 if file_name.starts_with('.') {
106 return file_name.strip_prefix('.');
107 }
108
109 path.extension()
110 .and_then(|e| e.to_str())
111 .or_else(|| path.file_stem()?.to_str())
112 }
113
114 fn local_to_wsl(&self) -> Option<PathBuf> {
115 let mut new_path = std::ffi::OsString::new();
118 for component in self.as_ref().components() {
119 match component {
120 std::path::Component::Prefix(prefix) => {
121 let drive_letter = prefix.as_os_str().to_string_lossy().to_lowercase();
122 let drive_letter = drive_letter.strip_suffix(':')?;
123
124 new_path.push(format!("/mnt/{}", drive_letter));
125 }
126 std::path::Component::RootDir => {}
127 std::path::Component::CurDir => {
128 new_path.push("/.");
129 }
130 std::path::Component::ParentDir => {
131 new_path.push("/..");
132 }
133 std::path::Component::Normal(os_str) => {
134 new_path.push("/");
135 new_path.push(os_str);
136 }
137 }
138 }
139
140 Some(new_path.into())
141 }
142
143 fn multiple_extensions(&self) -> Option<String> {
144 let path = self.as_ref();
145 let file_name = path.file_name()?.to_str()?;
146
147 let parts: Vec<&str> = file_name
148 .split('.')
149 .skip(1)
151 .collect();
152
153 if parts.len() < 2 {
154 return None;
155 }
156
157 Some(parts.into_iter().join("."))
158 }
159
160 #[cfg(not(target_family = "wasm"))]
161 fn try_shell_safe(&self, shell_kind: crate::shell::ShellKind) -> anyhow::Result<String> {
162 use anyhow::Context;
163 let path_str = self
164 .as_ref()
165 .to_str()
166 .with_context(|| "Path contains invalid UTF-8")?;
167 shell_kind
168 .try_quote(path_str)
169 .as_deref()
170 .map(ToOwned::to_owned)
171 .context("Failed to quote path")
172 }
173}
174
175pub fn path_ends_with(base: &Path, suffix: &Path) -> bool {
176 strip_path_suffix(base, suffix).is_some()
177}
178
179pub fn component_matches_ignore_ascii_case(component: &OsStr, name: &str) -> bool {
187 component
188 .to_str()
189 .is_some_and(|s| s.eq_ignore_ascii_case(name))
190}
191
192pub fn strip_path_suffix<'a>(base: &'a Path, suffix: &Path) -> Option<&'a Path> {
193 if let Some(remainder) = base
194 .as_os_str()
195 .as_encoded_bytes()
196 .strip_suffix(suffix.as_os_str().as_encoded_bytes())
197 {
198 if remainder
199 .last()
200 .is_none_or(|last_byte| std::path::is_separator(*last_byte as char))
201 {
202 let os_str = unsafe {
203 OsStr::from_encoded_bytes_unchecked(
204 &remainder[0..remainder.len().saturating_sub(1)],
205 )
206 };
207 return Some(Path::new(os_str));
208 }
209 }
210 None
211}
212
213#[derive(Eq, PartialEq, Hash, Ord, PartialOrd)]
216#[repr(transparent)]
217pub struct SanitizedPath(Path);
218
219impl SanitizedPath {
220 pub fn new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
221 #[cfg(not(target_os = "windows"))]
222 return Self::unchecked_new(path.as_ref());
223
224 #[cfg(target_os = "windows")]
225 return Self::unchecked_new(dunce::simplified(path.as_ref()));
226 }
227
228 pub fn unchecked_new<T: AsRef<Path> + ?Sized>(path: &T) -> &Self {
229 unsafe { mem::transmute::<&Path, &Self>(path.as_ref()) }
231 }
232
233 pub fn from_arc(path: Arc<Path>) -> Arc<Self> {
234 #[cfg(not(target_os = "windows"))]
236 return unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) };
237
238 #[cfg(target_os = "windows")]
239 {
240 let path = match path.to_str().and_then(|s| s.strip_prefix(r"\\?\UNC\")) {
241 Some(rest) => PathBuf::from(format!(r"\\{rest}")).into(),
242 None => path,
243 };
244 let simplified = dunce::simplified(path.as_ref());
245 if simplified == path.as_ref() {
246 unsafe { mem::transmute::<Arc<Path>, Arc<Self>>(path) }
248 } else {
249 Self::unchecked_new(simplified).into()
250 }
251 }
252 }
253
254 pub fn new_arc<T: AsRef<Path> + ?Sized>(path: &T) -> Arc<Self> {
255 Self::new(path).into()
256 }
257
258 pub fn cast_arc(path: Arc<Self>) -> Arc<Path> {
259 unsafe { mem::transmute::<Arc<Self>, Arc<Path>>(path) }
261 }
262
263 pub fn cast_arc_ref(path: &Arc<Self>) -> &Arc<Path> {
264 unsafe { mem::transmute::<&Arc<Self>, &Arc<Path>>(path) }
266 }
267
268 pub fn starts_with(&self, prefix: &Self) -> bool {
269 self.0.starts_with(&prefix.0)
270 }
271
272 pub fn as_path(&self) -> &Path {
273 &self.0
274 }
275
276 pub fn file_name(&self) -> Option<&std::ffi::OsStr> {
277 self.0.file_name()
278 }
279
280 pub fn extension(&self) -> Option<&std::ffi::OsStr> {
281 self.0.extension()
282 }
283
284 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
285 self.0.join(path)
286 }
287
288 pub fn parent(&self) -> Option<&Self> {
289 self.0.parent().map(Self::unchecked_new)
290 }
291
292 pub fn strip_prefix(&self, base: &Self) -> Result<&Path, StripPrefixError> {
293 self.0.strip_prefix(base.as_path())
294 }
295
296 pub fn to_str(&self) -> Option<&str> {
297 self.0.to_str()
298 }
299
300 pub fn to_path_buf(&self) -> PathBuf {
301 self.0.to_path_buf()
302 }
303}
304
305impl std::fmt::Debug for SanitizedPath {
306 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
307 std::fmt::Debug::fmt(&self.0, formatter)
308 }
309}
310
311impl Display for SanitizedPath {
312 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
313 write!(f, "{}", self.0.display())
314 }
315}
316
317impl From<&SanitizedPath> for Arc<SanitizedPath> {
318 fn from(sanitized_path: &SanitizedPath) -> Self {
319 let path: Arc<Path> = sanitized_path.0.into();
320 unsafe { mem::transmute(path) }
322 }
323}
324
325impl From<&SanitizedPath> for PathBuf {
326 fn from(sanitized_path: &SanitizedPath) -> Self {
327 sanitized_path.as_path().into()
328 }
329}
330
331impl AsRef<Path> for SanitizedPath {
332 fn as_ref(&self) -> &Path {
333 &self.0
334 }
335}
336
337#[derive(Debug, Clone)]
338pub struct RemotePathBuf {
339 style: PathStyle,
340 string: String,
341}
342
343impl RemotePathBuf {
344 pub fn new(string: String, style: PathStyle) -> Self {
345 Self { style, string }
346 }
347
348 pub fn from_str(path: &str, style: PathStyle) -> Self {
349 Self::new(path.to_string(), style)
350 }
351
352 pub fn path_style(&self) -> PathStyle {
353 self.style
354 }
355
356 pub fn to_proto(self) -> String {
357 self.string
358 }
359}
360
361impl Display for RemotePathBuf {
362 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
363 write!(f, "{}", self.string)
364 }
365}
366
367#[derive(Debug, PartialEq)]
368#[non_exhaustive]
369pub struct NormalizeError;
370
371impl Error for NormalizeError {}
372
373impl std::fmt::Display for NormalizeError {
374 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
375 f.write_str("parent reference `..` points outside of base directory")
376 }
377}
378
379pub fn normalize_lexically(path: &Path) -> Result<PathBuf, NormalizeError> {
396 use std::path::Component;
397
398 let mut lexical = PathBuf::new();
399 let mut iter = path.components().peekable();
400
401 let root = match iter.peek() {
405 Some(Component::ParentDir) => return Err(NormalizeError),
406 Some(p @ Component::RootDir) | Some(p @ Component::CurDir) => {
407 lexical.push(p);
408 iter.next();
409 lexical.as_os_str().len()
410 }
411 Some(Component::Prefix(prefix)) => {
412 lexical.push(prefix.as_os_str());
413 iter.next();
414 if let Some(p @ Component::RootDir) = iter.peek() {
415 lexical.push(p);
416 iter.next();
417 }
418 lexical.as_os_str().len()
419 }
420 None => return Ok(PathBuf::new()),
421 Some(Component::Normal(_)) => 0,
422 };
423
424 for component in iter {
425 match component {
426 Component::RootDir => unreachable!(),
427 Component::Prefix(_) => return Err(NormalizeError),
428 Component::CurDir => continue,
429 Component::ParentDir => {
430 if lexical.as_os_str().len() == root {
432 return Err(NormalizeError);
433 } else {
434 lexical.pop();
435 }
436 }
437 Component::Normal(path) => lexical.push(path),
438 }
439 }
440 Ok(lexical)
441}
442
443pub fn insert_subtree(subtrees: &mut Vec<PathBuf>, path: PathBuf) {
452 if subtrees.iter().any(|existing| path.starts_with(existing)) {
453 return;
454 }
455 subtrees.retain(|existing| !existing.starts_with(&path));
456 subtrees.push(path);
457}
458
459pub fn path_within_subtree<'a>(path: &Path, mut subtrees: impl Iterator<Item = &'a Path>) -> bool {
463 subtrees.any(|granted| path.starts_with(granted))
464}
465
466pub const FILE_ROW_COLUMN_DELIMITER: char = ':';
468
469const ROW_COL_CAPTURE_REGEX: &str = r"(?xs)
470 ([^\(]+)\:(?:
471 \((\d+)[,:](\d+)\) # filename:(row,column), filename:(row:column)
472 |
473 \((\d+)\)() # filename:(row)
474 )
475 |
476 ([^\(]+)(?:
477 \((\d+)[,:](\d+)\) # filename(row,column), filename(row:column)
478 |
479 \((\d+)\)() # filename(row)
480 )
481 \:*$
482 |
483 (.+?)(?:
484 \:+(\d+)\:(\d+)\:*$ # filename:row:column
485 |
486 \:+(\d+)\:*()$ # filename:row
487 |
488 \:+()()$
489 )";
490
491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
494pub struct PathWithPosition {
495 pub path: PathBuf,
496 pub row: Option<u32>,
497 pub column: Option<u32>,
499}
500
501impl PathWithPosition {
502 pub fn from_path(path: PathBuf) -> Self {
504 Self {
505 path,
506 row: None,
507 column: None,
508 }
509 }
510
511 pub fn parse_str(s: &str) -> Self {
597 let trimmed = s.trim();
598 let path = Path::new(trimmed);
599 let Some(maybe_file_name_with_row_col) = path.file_name().unwrap_or_default().to_str()
600 else {
601 return Self {
602 path: Path::new(s).to_path_buf(),
603 row: None,
604 column: None,
605 };
606 };
607 if maybe_file_name_with_row_col.is_empty() {
608 return Self {
609 path: Path::new(s).to_path_buf(),
610 row: None,
611 column: None,
612 };
613 }
614
615 static SUFFIX_RE: LazyLock<Regex> =
619 LazyLock::new(|| Regex::new(ROW_COL_CAPTURE_REGEX).unwrap());
620 match SUFFIX_RE
621 .captures(maybe_file_name_with_row_col)
622 .and_then(|captures| {
623 let file_name_end = captures.iter().skip(1).flatten().next()?.end();
624 let (_, [_, row, column]) = captures.extract();
625 Some((file_name_end, row, column))
626 }) {
627 Some((file_name_end, maybe_row, maybe_column)) => {
628 let row = maybe_row.parse::<u32>().ok();
629 let column = maybe_column.parse::<u32>().ok();
630
631 Self {
632 path: path.with_file_name(&maybe_file_name_with_row_col[..file_name_end]),
633 row,
634 column,
635 }
636 }
637 None => {
638 let path = Path::new(s);
642 let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
643 return Self::from_path(path.to_path_buf());
644 };
645 let delimiter = ':';
646 let mut path_parts = file_name
647 .rsplitn(3, delimiter)
648 .collect::<Vec<_>>()
649 .into_iter()
650 .rev()
651 .fuse();
652 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();
653 let mut row = None;
654 let mut column = None;
655 if let Some(maybe_row) = path_parts.next() {
656 if let Ok(parsed_row) = maybe_row.parse::<u32>() {
657 row = Some(parsed_row);
658 if let Some(parsed_column) = path_parts
659 .next()
660 .and_then(|maybe_col| maybe_col.parse::<u32>().ok())
661 {
662 column = Some(parsed_column);
663 }
664 } else {
665 path_string.push(delimiter);
666 path_string.push_str(maybe_row);
667 }
668 }
669 for split in path_parts {
670 path_string.push(delimiter);
671 path_string.push_str(split);
672 }
673
674 Self {
675 path: if row.is_some() {
676 path.with_file_name(path_string)
677 } else {
678 path.to_path_buf()
679 },
680 row,
681 column,
682 }
683 }
684 }
685 }
686
687 pub fn map_path<E>(
688 self,
689 mapping: impl FnOnce(PathBuf) -> Result<PathBuf, E>,
690 ) -> Result<PathWithPosition, E> {
691 Ok(PathWithPosition {
692 path: mapping(self.path)?,
693 row: self.row,
694 column: self.column,
695 })
696 }
697
698 pub fn to_string(&self, path_to_string: &dyn Fn(&PathBuf) -> String) -> String {
699 let path_string = path_to_string(&self.path);
700 if let Some(row) = self.row {
701 if let Some(column) = self.column {
702 format!("{path_string}:{row}:{column}")
703 } else {
704 format!("{path_string}:{row}")
705 }
706 } else {
707 path_string
708 }
709 }
710}
711
712#[derive(Clone)]
713pub struct PathMatcher {
714 sources: Vec<(String, RelPathBuf, bool)>,
715 glob: GlobSet,
716 path_style: PathStyle,
717}
718
719impl std::fmt::Debug for PathMatcher {
720 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
721 f.debug_struct("PathMatcher")
722 .field("sources", &self.sources)
723 .field("path_style", &self.path_style)
724 .finish()
725 }
726}
727
728impl PartialEq for PathMatcher {
729 fn eq(&self, other: &Self) -> bool {
730 self.sources.eq(&other.sources)
731 }
732}
733
734impl Eq for PathMatcher {}
735
736impl PathMatcher {
737 pub fn new(
738 globs: impl IntoIterator<Item = impl AsRef<str>>,
739 path_style: PathStyle,
740 ) -> Result<Self, globset::Error> {
741 let globs = globs
742 .into_iter()
743 .map(|as_str| {
744 GlobBuilder::new(as_str.as_ref())
745 .backslash_escape(path_style.is_posix())
746 .build()
747 })
748 .collect::<Result<Vec<_>, _>>()?;
749 Self::from_globs(globs, path_style)
750 }
751
752 pub fn new_lenient(
755 globs: impl IntoIterator<Item = impl AsRef<str>>,
756 path_style: PathStyle,
757 mut on_error: impl FnMut(globset::Error),
758 ) -> Self {
759 let globs = globs
760 .into_iter()
761 .filter_map(|pattern| {
762 match GlobBuilder::new(pattern.as_ref())
763 .backslash_escape(path_style.is_posix())
764 .build()
765 {
766 Ok(glob) => Some(glob),
767 Err(error) => {
768 on_error(error);
769 None
770 }
771 }
772 })
773 .collect();
774 match Self::from_globs(globs, path_style) {
775 Ok(matcher) => matcher,
776 Err(error) => {
777 on_error(error);
778 Self {
779 path_style,
780 ..Self::default()
781 }
782 }
783 }
784 }
785
786 fn from_globs(globs: Vec<Glob>, path_style: PathStyle) -> Result<Self, globset::Error> {
787 let sources = globs
788 .iter()
789 .filter_map(|glob| {
790 let glob = glob.glob();
791 Some((
792 glob.to_string(),
793 RelPath::new(&glob.as_ref(), path_style)
794 .ok()
795 .map(std::borrow::Cow::into_owned)?,
796 glob.ends_with(path_style.separators_ch()),
797 ))
798 })
799 .collect();
800 let mut glob_builder = GlobSetBuilder::new();
801 for single_glob in globs {
802 glob_builder.add(single_glob);
803 }
804 let glob = glob_builder.build()?;
805 Ok(PathMatcher {
806 glob,
807 sources,
808 path_style,
809 })
810 }
811
812 pub fn sources(&self) -> impl Iterator<Item = &str> + Clone {
813 self.sources.iter().map(|(source, ..)| source.as_str())
814 }
815
816 pub fn is_match<P: AsRef<RelPath>>(&self, other: P) -> bool {
817 let other = other.as_ref();
818 if self
819 .sources
820 .iter()
821 .any(|(_, source, _)| other.starts_with(source) || other.ends_with(source))
822 {
823 return true;
824 }
825 let other_path = other.display(self.path_style);
826
827 if self.glob.is_match(&*other_path) {
828 return true;
829 }
830
831 self.glob
832 .is_match(other_path.into_owned() + self.path_style.primary_separator())
833 }
834
835 pub fn is_match_std_path<P: AsRef<Path>>(&self, other: P) -> bool {
836 let other = other.as_ref();
837 if self.sources.iter().any(|(_, source, _)| {
838 other.starts_with(source.as_std_path()) || other.ends_with(source.as_std_path())
839 }) {
840 return true;
841 }
842 self.glob.is_match(other)
843 }
844}
845
846impl Default for PathMatcher {
847 fn default() -> Self {
848 Self {
849 path_style: PathStyle::local(),
850 glob: GlobSet::empty(),
851 sources: vec![],
852 }
853 }
854}
855
856fn compare_numeric_segments<I>(
891 a_iter: &mut std::iter::Peekable<I>,
892 b_iter: &mut std::iter::Peekable<I>,
893) -> Ordering
894where
895 I: Iterator<Item = char>,
896{
897 let mut a_num_str = String::new();
899 let mut b_num_str = String::new();
900
901 while let Some(&c) = a_iter.peek() {
902 if !c.is_ascii_digit() {
903 break;
904 }
905
906 a_num_str.push(c);
907 a_iter.next();
908 }
909
910 while let Some(&c) = b_iter.peek() {
911 if !c.is_ascii_digit() {
912 break;
913 }
914
915 b_num_str.push(c);
916 b_iter.next();
917 }
918
919 match a_num_str.len().cmp(&b_num_str.len()) {
921 Ordering::Equal => {
922 match a_num_str.cmp(&b_num_str) {
924 Ordering::Equal => Ordering::Equal,
925 ordering => ordering,
926 }
927 }
928
929 ordering => {
931 if let (Ok(a_val), Ok(b_val)) = (a_num_str.parse::<u128>(), b_num_str.parse::<u128>()) {
933 match a_val.cmp(&b_val) {
934 Ordering::Equal => ordering, ord => ord,
936 }
937 } else {
938 a_num_str.cmp(&b_num_str)
940 }
941 }
942 }
943}
944
945pub fn natural_sort(a: &str, b: &str) -> Ordering {
967 let mut a_iter = a.chars().peekable();
968 let mut b_iter = b.chars().peekable();
969
970 loop {
971 match (a_iter.peek(), b_iter.peek()) {
972 (None, None) => {
973 return b.cmp(a);
974 }
975 (None, _) => return Ordering::Less,
976 (_, None) => return Ordering::Greater,
977 (Some(&a_char), Some(&b_char)) => {
978 if a_char.is_ascii_digit() && b_char.is_ascii_digit() {
979 match compare_numeric_segments(&mut a_iter, &mut b_iter) {
980 Ordering::Equal => continue,
981 ordering => return ordering,
982 }
983 } else {
984 match a_char
985 .to_ascii_lowercase()
986 .cmp(&b_char.to_ascii_lowercase())
987 {
988 Ordering::Equal => {
989 a_iter.next();
990 b_iter.next();
991 }
992 ordering => return ordering,
993 }
994 }
995 }
996 }
997 }
998}
999
1000fn natural_sort_no_tiebreak(a: &str, b: &str) -> Ordering {
1004 if a.eq_ignore_ascii_case(b) {
1005 Ordering::Equal
1006 } else {
1007 natural_sort(a, b)
1008 }
1009}
1010
1011fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) {
1012 if filename.is_empty() {
1013 return (None, None);
1014 }
1015
1016 match filename.rsplit_once('.') {
1017 None => (Some(filename), None),
1019
1020 Some((before, after)) => {
1022 if before.is_empty() {
1026 (Some(filename), None)
1027 } else {
1028 (Some(before), Some(after))
1030 }
1031 }
1032 }
1033}
1034
1035#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1037pub enum SortOrder {
1038 #[default]
1041 Default,
1042 Upper,
1045 Lower,
1048 Unicode,
1051}
1052
1053#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1055pub enum SortMode {
1056 #[default]
1058 DirectoriesFirst,
1059 Mixed,
1061 FilesFirst,
1063}
1064
1065fn case_group_key(name: &str, order: SortOrder) -> u8 {
1066 let first = match name.chars().next() {
1067 Some(c) => c,
1068 None => return 0,
1069 };
1070 match order {
1071 SortOrder::Upper => {
1072 if first.is_lowercase() {
1073 1
1074 } else {
1075 0
1076 }
1077 }
1078 SortOrder::Lower => {
1079 if first.is_uppercase() {
1080 1
1081 } else {
1082 0
1083 }
1084 }
1085 _ => 0,
1086 }
1087}
1088
1089fn compare_strings(a: &str, b: &str, order: SortOrder) -> Ordering {
1090 match order {
1091 SortOrder::Unicode => a.cmp(b),
1092 _ => natural_sort(a, b),
1093 }
1094}
1095
1096fn compare_strings_no_tiebreak(a: &str, b: &str, order: SortOrder) -> Ordering {
1097 match order {
1098 SortOrder::Unicode => a.cmp(b),
1099 _ => natural_sort_no_tiebreak(a, b),
1100 }
1101}
1102
1103pub fn compare_rel_paths(
1104 (path_a, a_is_file): (&RelPath, bool),
1105 (path_b, b_is_file): (&RelPath, bool),
1106) -> Ordering {
1107 compare_rel_paths_by(
1108 (path_a, a_is_file),
1109 (path_b, b_is_file),
1110 SortMode::DirectoriesFirst,
1111 SortOrder::Default,
1112 )
1113}
1114
1115pub fn compare_rel_paths_by(
1116 (path_a, a_is_file): (&RelPath, bool),
1117 (path_b, b_is_file): (&RelPath, bool),
1118 mode: SortMode,
1119 order: SortOrder,
1120) -> Ordering {
1121 let needs_final_tiebreak =
1122 mode != SortMode::DirectoriesFirst && !(std::ptr::eq(path_a, path_b) || path_a == path_b);
1123
1124 let mut components_a = path_a.components();
1125 let mut components_b = path_b.components();
1126
1127 loop {
1128 match (components_a.next(), components_b.next()) {
1129 (Some(component_a), Some(component_b)) => {
1130 let a_leaf_file = a_is_file && components_a.rest().is_empty();
1131 let b_leaf_file = b_is_file && components_b.rest().is_empty();
1132
1133 let file_dir_ordering = match mode {
1134 SortMode::DirectoriesFirst => a_leaf_file.cmp(&b_leaf_file),
1135 SortMode::FilesFirst => b_leaf_file.cmp(&a_leaf_file),
1136 SortMode::Mixed => Ordering::Equal,
1137 };
1138
1139 if !file_dir_ordering.is_eq() {
1140 return file_dir_ordering;
1141 }
1142
1143 let (a_stem, a_ext) = a_leaf_file
1144 .then(|| stem_and_extension(component_a))
1145 .unwrap_or_default();
1146 let (b_stem, b_ext) = b_leaf_file
1147 .then(|| stem_and_extension(component_b))
1148 .unwrap_or_default();
1149 let a_key = if a_leaf_file {
1150 a_stem
1151 } else {
1152 Some(component_a)
1153 };
1154 let b_key = if b_leaf_file {
1155 b_stem
1156 } else {
1157 Some(component_b)
1158 };
1159
1160 let ordering = match (a_key, b_key) {
1161 (Some(a), Some(b)) => {
1162 let name_cmp = case_group_key(a, order)
1163 .cmp(&case_group_key(b, order))
1164 .then_with(|| match mode {
1165 SortMode::DirectoriesFirst => compare_strings(a, b, order),
1166 _ => compare_strings_no_tiebreak(a, b, order),
1167 });
1168
1169 let name_cmp = if mode == SortMode::Mixed {
1170 name_cmp.then_with(|| match (a_leaf_file, b_leaf_file) {
1171 (true, false) if a.eq_ignore_ascii_case(b) => Ordering::Greater,
1172 (false, true) if a.eq_ignore_ascii_case(b) => Ordering::Less,
1173 _ => Ordering::Equal,
1174 })
1175 } else {
1176 name_cmp
1177 };
1178
1179 name_cmp.then_with(|| {
1180 if a_leaf_file && b_leaf_file {
1181 match order {
1182 SortOrder::Unicode => {
1183 a_ext.unwrap_or_default().cmp(b_ext.unwrap_or_default())
1184 }
1185 _ => {
1186 let a_ext_str = a_ext.unwrap_or_default().to_lowercase();
1187 let b_ext_str = b_ext.unwrap_or_default().to_lowercase();
1188 a_ext_str.cmp(&b_ext_str)
1189 }
1190 }
1191 } else {
1192 Ordering::Equal
1193 }
1194 })
1195 }
1196 (Some(_), None) => Ordering::Greater,
1197 (None, Some(_)) => Ordering::Less,
1198 (None, None) => Ordering::Equal,
1199 };
1200
1201 if !ordering.is_eq() {
1202 return ordering;
1203 }
1204 }
1205 (Some(_), None) => return Ordering::Greater,
1206 (None, Some(_)) => return Ordering::Less,
1207 (None, None) => {
1208 if needs_final_tiebreak {
1209 return compare_strings(path_a.as_unix_str(), path_b.as_unix_str(), order);
1210 }
1211 return Ordering::Equal;
1212 }
1213 }
1214 }
1215}
1216
1217pub fn compare_paths(
1218 (path_a, a_is_file): (&Path, bool),
1219 (path_b, b_is_file): (&Path, bool),
1220) -> Ordering {
1221 let mut components_a = path_a.components().peekable();
1222 let mut components_b = path_b.components().peekable();
1223
1224 loop {
1225 match (components_a.next(), components_b.next()) {
1226 (Some(component_a), Some(component_b)) => {
1227 let a_is_file = components_a.peek().is_none() && a_is_file;
1228 let b_is_file = components_b.peek().is_none() && b_is_file;
1229
1230 let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
1231 let path_a = Path::new(component_a.as_os_str());
1232 let path_string_a = if a_is_file {
1233 path_a.file_stem()
1234 } else {
1235 path_a.file_name()
1236 }
1237 .map(|s| s.to_string_lossy());
1238
1239 let path_b = Path::new(component_b.as_os_str());
1240 let path_string_b = if b_is_file {
1241 path_b.file_stem()
1242 } else {
1243 path_b.file_name()
1244 }
1245 .map(|s| s.to_string_lossy());
1246
1247 let compare_components = match (path_string_a, path_string_b) {
1248 (Some(a), Some(b)) => natural_sort(&a, &b),
1249 (Some(_), None) => Ordering::Greater,
1250 (None, Some(_)) => Ordering::Less,
1251 (None, None) => Ordering::Equal,
1252 };
1253
1254 compare_components.then_with(|| {
1255 if a_is_file && b_is_file {
1256 let ext_a = path_a.extension().unwrap_or_default();
1257 let ext_b = path_b.extension().unwrap_or_default();
1258 ext_a.cmp(ext_b)
1259 } else {
1260 Ordering::Equal
1261 }
1262 })
1263 });
1264
1265 if !ordering.is_eq() {
1266 return ordering;
1267 }
1268 }
1269 (Some(_), None) => break Ordering::Greater,
1270 (None, Some(_)) => break Ordering::Less,
1271 (None, None) => break Ordering::Equal,
1272 }
1273 }
1274}
1275
1276#[derive(Debug, Clone, PartialEq, Eq)]
1277pub struct WslPath {
1278 pub distro: String,
1279
1280 pub path: std::ffi::OsString,
1284}
1285
1286impl WslPath {
1287 pub fn from_path<P: AsRef<Path>>(path: P) -> Option<WslPath> {
1288 if cfg!(not(target_os = "windows")) {
1289 return None;
1290 }
1291 use std::{
1292 ffi::OsString,
1293 path::{Component, Prefix},
1294 };
1295
1296 let mut components = path.as_ref().components();
1297 let Some(Component::Prefix(prefix)) = components.next() else {
1298 return None;
1299 };
1300 let (server, distro) = match prefix.kind() {
1301 Prefix::UNC(server, distro) => (server, distro),
1302 Prefix::VerbatimUNC(server, distro) => (server, distro),
1303 _ => return None,
1304 };
1305 let Some(Component::RootDir) = components.next() else {
1306 return None;
1307 };
1308
1309 let server_str = server.to_string_lossy();
1310 if server_str == "wsl.localhost" || server_str == "wsl$" {
1311 let mut result = OsString::from("");
1312 for c in components {
1313 use Component::*;
1314 match c {
1315 Prefix(p) => unreachable!("got {p:?}, but already stripped prefix"),
1316 RootDir => unreachable!("got root dir, but already stripped root"),
1317 CurDir => continue,
1318 ParentDir => result.push("/.."),
1319 Normal(s) => {
1320 result.push("/");
1321 result.push(s);
1322 }
1323 }
1324 }
1325 if result.is_empty() {
1326 result.push("/");
1327 }
1328 Some(WslPath {
1329 distro: distro.to_string_lossy().to_string(),
1330 path: result,
1331 })
1332 } else {
1333 None
1334 }
1335 }
1336}
1337
1338pub trait UrlExt {
1339 fn to_file_path_ext(&self, path_style: PathStyle) -> Result<PathBuf, ()>;
1343}
1344
1345impl UrlExt for url::Url {
1346 fn to_file_path_ext(&self, source_path_style: PathStyle) -> Result<PathBuf, ()> {
1348 if let Some(segments) = self.path_segments() {
1349 let host = match self.host() {
1350 None | Some(url::Host::Domain("localhost")) => None,
1351 Some(_) if source_path_style.is_windows() && self.scheme() == "file" => {
1352 self.host_str()
1353 }
1354 _ => return Err(()),
1355 };
1356
1357 let str_len = self.as_str().len();
1358 let estimated_capacity = if source_path_style.is_windows() {
1359 str_len.saturating_sub(self.scheme().len() + 1)
1361 } else {
1362 str_len.saturating_sub(self.scheme().len() + 3)
1364 };
1365 return match source_path_style {
1366 PathStyle::Unix => {
1367 file_url_segments_to_pathbuf_posix(estimated_capacity, host, segments)
1368 }
1369 PathStyle::Windows => {
1370 file_url_segments_to_pathbuf_windows(estimated_capacity, host, segments)
1371 }
1372 };
1373 }
1374
1375 fn file_url_segments_to_pathbuf_posix(
1376 estimated_capacity: usize,
1377 host: Option<&str>,
1378 segments: std::str::Split<'_, char>,
1379 ) -> Result<PathBuf, ()> {
1380 use percent_encoding::percent_decode;
1381
1382 if host.is_some() {
1383 return Err(());
1384 }
1385
1386 let mut bytes = Vec::new();
1387 bytes.try_reserve(estimated_capacity).map_err(|_| ())?;
1388
1389 for segment in segments {
1390 bytes.push(b'/');
1391 bytes.extend(percent_decode(segment.as_bytes()));
1392 }
1393
1394 if bytes.len() > 2
1396 && bytes[bytes.len() - 2].is_ascii_alphabetic()
1397 && matches!(bytes[bytes.len() - 1], b':' | b'|')
1398 {
1399 bytes.push(b'/');
1400 }
1401
1402 let path = String::from_utf8(bytes).map_err(|_| ())?;
1403 debug_assert!(
1404 PathStyle::Unix.is_absolute(Path::new(&path)),
1405 "to_file_path() failed to produce an absolute Path"
1406 );
1407
1408 Ok(PathBuf::from(path))
1409 }
1410
1411 fn file_url_segments_to_pathbuf_windows(
1412 estimated_capacity: usize,
1413 host: Option<&str>,
1414 mut segments: std::str::Split<'_, char>,
1415 ) -> Result<PathBuf, ()> {
1416 use percent_encoding::percent_decode_str;
1417 let mut string = String::new();
1418 string.try_reserve(estimated_capacity).map_err(|_| ())?;
1419 if let Some(host) = host {
1420 string.push_str(r"\\");
1421 string.push_str(host);
1422 } else {
1423 let first = segments.next().ok_or(())?;
1424
1425 match first.len() {
1426 2 => {
1427 if !first.starts_with(|c| char::is_ascii_alphabetic(&c))
1428 || first.as_bytes()[1] != b':'
1429 {
1430 return Err(());
1431 }
1432
1433 string.push_str(first);
1434 }
1435
1436 4 => {
1437 if !first.starts_with(|c| char::is_ascii_alphabetic(&c)) {
1438 return Err(());
1439 }
1440 let bytes = first.as_bytes();
1441 if bytes[1] != b'%'
1442 || bytes[2] != b'3'
1443 || (bytes[3] != b'a' && bytes[3] != b'A')
1444 {
1445 return Err(());
1446 }
1447
1448 string.push_str(&first[0..1]);
1449 string.push(':');
1450 }
1451
1452 _ => return Err(()),
1453 }
1454 };
1455
1456 for segment in segments {
1457 string.push('\\');
1458
1459 match percent_decode_str(segment).decode_utf8() {
1461 Ok(s) => string.push_str(&s),
1462 Err(..) => return Err(()),
1463 }
1464 }
1465 if cfg!(test) {
1467 debug_assert!(
1468 string.len() <= estimated_capacity,
1469 "len: {}, capacity: {}",
1470 string.len(),
1471 estimated_capacity
1472 );
1473 }
1474 debug_assert!(
1475 PathStyle::Windows.is_absolute(Path::new(&string)),
1476 "to_file_path() failed to produce an absolute Path"
1477 );
1478 let path = PathBuf::from(string);
1479 Ok(path)
1480 }
1481 Err(())
1482 }
1483}
1484
1485#[cfg(test)]
1486mod tests {
1487 use super::*;
1488 use util_macros::perf;
1489
1490 #[test]
1491 fn test_lenient_path_matcher() {
1492 for path_style in [PathStyle::Unix, PathStyle::Windows] {
1493 let patterns = ["**/.git", "[", "target/**", "{"];
1494 let mut errors = Vec::new();
1495 let matcher =
1496 PathMatcher::new_lenient(patterns, path_style, |error| errors.push(error));
1497 let expected = PathMatcher::new(["**/.git", "target/**"], path_style).unwrap();
1498 assert_eq!(matcher, expected);
1499 assert_eq!(errors.len(), 2);
1500 assert_eq!(errors[0].glob(), Some("["));
1501 assert_eq!(errors[1].glob(), Some("{"));
1502 for path in ["nested/.git", "src/file.rs", "target/file.rs"] {
1503 let path = RelPath::from_unix_str(path).unwrap();
1504 assert_eq!(matcher.is_match(path), expected.is_match(path));
1505 }
1506 if path_style == PathStyle::local() {
1507 assert!(matcher.is_match(RelPath::from_unix_str("nested/.git").unwrap()));
1508 assert!(matcher.is_match(RelPath::from_unix_str("target/file.rs").unwrap()));
1509 }
1510 assert!(PathMatcher::new(patterns, path_style).is_err());
1511
1512 let mut errors = Vec::new();
1513 let matcher =
1514 PathMatcher::new_lenient(["[", "{"], path_style, |error| errors.push(error));
1515 assert_eq!(errors.len(), 2);
1516 assert_eq!(matcher.path_style, path_style);
1517 assert_eq!(matcher.sources().count(), 0);
1518 assert!(!matcher.is_match(RelPath::from_unix_str("file.rs").unwrap()));
1519 assert!(!matcher.is_match_std_path("file.rs"));
1520
1521 let matcher = PathMatcher::new_lenient([] as [&str; 0], path_style, |_| {
1522 panic!("empty patterns are valid")
1523 });
1524 assert_eq!(matcher.path_style, path_style);
1525 assert_eq!(matcher.sources().count(), 0);
1526 assert!(!matcher.is_match(RelPath::from_unix_str("file.rs").unwrap()));
1527 }
1528 }
1529
1530 #[test]
1531 fn test_lenient_path_matcher_preserves_escaping() {
1532 for path_style in [PathStyle::Unix, PathStyle::Windows] {
1533 let patterns = [r"directory\file.rs", r"literal\*", r"literal\[name]"];
1534 let strict = PathMatcher::new(patterns, path_style).unwrap();
1535 let lenient = PathMatcher::new_lenient(patterns, path_style, |_| {
1536 panic!("valid patterns are preserved")
1537 });
1538 assert_eq!(lenient, strict);
1539 for path in [
1540 "directory/file.rs",
1541 "literal*",
1542 "literal/file.rs",
1543 "literal[name]",
1544 ] {
1545 let path = RelPath::from_unix_str(path).unwrap();
1546 assert_eq!(lenient.is_match(path), strict.is_match(path));
1547 }
1548 }
1549 }
1550
1551 #[test]
1552 fn test_parse_str_treats_paren_suffix_as_position() {
1553 let parsed = PathWithPosition::parse_str("/root/Test (3)");
1557 assert_eq!(parsed.path, PathBuf::from("/root/Test "));
1558 assert_eq!(parsed.row, Some(3));
1559 }
1560
1561 fn rel_path_entry(path: &'static str, is_file: bool) -> (&'static RelPath, bool) {
1562 (RelPath::from_unix_str(path).unwrap(), is_file)
1563 }
1564
1565 fn sorted_rel_paths(
1566 mut paths: Vec<(&'static RelPath, bool)>,
1567 mode: SortMode,
1568 order: SortOrder,
1569 ) -> Vec<(&'static RelPath, bool)> {
1570 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, mode, order));
1571 paths
1572 }
1573
1574 #[perf]
1575 fn compare_paths_with_dots() {
1576 let mut paths = vec![
1577 (Path::new("test_dirs"), false),
1578 (Path::new("test_dirs/1.46"), false),
1579 (Path::new("test_dirs/1.46/bar_1"), true),
1580 (Path::new("test_dirs/1.46/bar_2"), true),
1581 (Path::new("test_dirs/1.45"), false),
1582 (Path::new("test_dirs/1.45/foo_2"), true),
1583 (Path::new("test_dirs/1.45/foo_1"), true),
1584 ];
1585 paths.sort_by(|&a, &b| compare_paths(a, b));
1586 assert_eq!(
1587 paths,
1588 vec![
1589 (Path::new("test_dirs"), false),
1590 (Path::new("test_dirs/1.45"), false),
1591 (Path::new("test_dirs/1.45/foo_1"), true),
1592 (Path::new("test_dirs/1.45/foo_2"), true),
1593 (Path::new("test_dirs/1.46"), false),
1594 (Path::new("test_dirs/1.46/bar_1"), true),
1595 (Path::new("test_dirs/1.46/bar_2"), true),
1596 ]
1597 );
1598 let mut paths = vec![
1599 (Path::new("root1/one.txt"), true),
1600 (Path::new("root1/one.two.txt"), true),
1601 ];
1602 paths.sort_by(|&a, &b| compare_paths(a, b));
1603 assert_eq!(
1604 paths,
1605 vec![
1606 (Path::new("root1/one.txt"), true),
1607 (Path::new("root1/one.two.txt"), true),
1608 ]
1609 );
1610 }
1611
1612 #[perf]
1613 fn compare_paths_with_same_name_different_extensions() {
1614 let mut paths = vec![
1615 (Path::new("test_dirs/file.rs"), true),
1616 (Path::new("test_dirs/file.txt"), true),
1617 (Path::new("test_dirs/file.md"), true),
1618 (Path::new("test_dirs/file"), true),
1619 (Path::new("test_dirs/file.a"), true),
1620 ];
1621 paths.sort_by(|&a, &b| compare_paths(a, b));
1622 assert_eq!(
1623 paths,
1624 vec![
1625 (Path::new("test_dirs/file"), true),
1626 (Path::new("test_dirs/file.a"), true),
1627 (Path::new("test_dirs/file.md"), true),
1628 (Path::new("test_dirs/file.rs"), true),
1629 (Path::new("test_dirs/file.txt"), true),
1630 ]
1631 );
1632 }
1633
1634 #[perf]
1635 fn compare_paths_case_semi_sensitive() {
1636 let mut paths = vec![
1637 (Path::new("test_DIRS"), false),
1638 (Path::new("test_DIRS/foo_1"), true),
1639 (Path::new("test_DIRS/foo_2"), true),
1640 (Path::new("test_DIRS/bar"), true),
1641 (Path::new("test_DIRS/BAR"), true),
1642 (Path::new("test_dirs"), false),
1643 (Path::new("test_dirs/foo_1"), true),
1644 (Path::new("test_dirs/foo_2"), true),
1645 (Path::new("test_dirs/bar"), true),
1646 (Path::new("test_dirs/BAR"), true),
1647 ];
1648 paths.sort_by(|&a, &b| compare_paths(a, b));
1649 assert_eq!(
1650 paths,
1651 vec![
1652 (Path::new("test_dirs"), false),
1653 (Path::new("test_dirs/bar"), true),
1654 (Path::new("test_dirs/BAR"), true),
1655 (Path::new("test_dirs/foo_1"), true),
1656 (Path::new("test_dirs/foo_2"), true),
1657 (Path::new("test_DIRS"), false),
1658 (Path::new("test_DIRS/bar"), true),
1659 (Path::new("test_DIRS/BAR"), true),
1660 (Path::new("test_DIRS/foo_1"), true),
1661 (Path::new("test_DIRS/foo_2"), true),
1662 ]
1663 );
1664 }
1665
1666 #[perf]
1667 fn compare_paths_mixed_case_numeric_ordering() {
1668 let mut entries = [
1669 (Path::new(".config"), false),
1670 (Path::new("Dir1"), false),
1671 (Path::new("dir01"), false),
1672 (Path::new("dir2"), false),
1673 (Path::new("Dir02"), false),
1674 (Path::new("dir10"), false),
1675 (Path::new("Dir10"), false),
1676 ];
1677
1678 entries.sort_by(|&a, &b| compare_paths(a, b));
1679
1680 let ordered: Vec<&str> = entries
1681 .iter()
1682 .map(|(path, _)| path.to_str().unwrap())
1683 .collect();
1684
1685 assert_eq!(
1686 ordered,
1687 vec![
1688 ".config", "Dir1", "dir01", "dir2", "Dir02", "dir10", "Dir10"
1689 ]
1690 );
1691 }
1692
1693 #[perf]
1694 fn compare_rel_paths_mixed_case_insensitive() {
1695 let mut paths = vec![
1697 (RelPath::from_unix_str("zebra.txt").unwrap(), true),
1698 (RelPath::from_unix_str("Apple").unwrap(), false),
1699 (RelPath::from_unix_str("banana.rs").unwrap(), true),
1700 (RelPath::from_unix_str("Carrot").unwrap(), false),
1701 (RelPath::from_unix_str("aardvark.txt").unwrap(), true),
1702 ];
1703 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1704 assert_eq!(
1706 paths,
1707 vec![
1708 (RelPath::from_unix_str("aardvark.txt").unwrap(), true),
1709 (RelPath::from_unix_str("Apple").unwrap(), false),
1710 (RelPath::from_unix_str("banana.rs").unwrap(), true),
1711 (RelPath::from_unix_str("Carrot").unwrap(), false),
1712 (RelPath::from_unix_str("zebra.txt").unwrap(), true),
1713 ]
1714 );
1715 }
1716
1717 #[perf]
1718 fn compare_rel_paths_files_first_basic() {
1719 let mut paths = vec![
1721 (RelPath::from_unix_str("zebra.txt").unwrap(), true),
1722 (RelPath::from_unix_str("Apple").unwrap(), false),
1723 (RelPath::from_unix_str("banana.rs").unwrap(), true),
1724 (RelPath::from_unix_str("Carrot").unwrap(), false),
1725 (RelPath::from_unix_str("aardvark.txt").unwrap(), true),
1726 ];
1727 paths
1728 .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1729 assert_eq!(
1731 paths,
1732 vec![
1733 (RelPath::from_unix_str("aardvark.txt").unwrap(), true),
1734 (RelPath::from_unix_str("banana.rs").unwrap(), true),
1735 (RelPath::from_unix_str("zebra.txt").unwrap(), true),
1736 (RelPath::from_unix_str("Apple").unwrap(), false),
1737 (RelPath::from_unix_str("Carrot").unwrap(), false),
1738 ]
1739 );
1740 }
1741
1742 #[perf]
1743 fn compare_rel_paths_files_first_case_insensitive() {
1744 let mut paths = vec![
1746 (RelPath::from_unix_str("Zebra.txt").unwrap(), true),
1747 (RelPath::from_unix_str("apple").unwrap(), false),
1748 (RelPath::from_unix_str("Banana.rs").unwrap(), true),
1749 (RelPath::from_unix_str("carrot").unwrap(), false),
1750 (RelPath::from_unix_str("Aardvark.txt").unwrap(), true),
1751 ];
1752 paths
1753 .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1754 assert_eq!(
1755 paths,
1756 vec![
1757 (RelPath::from_unix_str("Aardvark.txt").unwrap(), true),
1758 (RelPath::from_unix_str("Banana.rs").unwrap(), true),
1759 (RelPath::from_unix_str("Zebra.txt").unwrap(), true),
1760 (RelPath::from_unix_str("apple").unwrap(), false),
1761 (RelPath::from_unix_str("carrot").unwrap(), false),
1762 ]
1763 );
1764 }
1765
1766 #[perf]
1767 fn compare_rel_paths_files_first_numeric() {
1768 let mut paths = vec![
1770 (RelPath::from_unix_str("file10.txt").unwrap(), true),
1771 (RelPath::from_unix_str("dir2").unwrap(), false),
1772 (RelPath::from_unix_str("file2.txt").unwrap(), true),
1773 (RelPath::from_unix_str("dir10").unwrap(), false),
1774 (RelPath::from_unix_str("file1.txt").unwrap(), true),
1775 ];
1776 paths
1777 .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1778 assert_eq!(
1779 paths,
1780 vec![
1781 (RelPath::from_unix_str("file1.txt").unwrap(), true),
1782 (RelPath::from_unix_str("file2.txt").unwrap(), true),
1783 (RelPath::from_unix_str("file10.txt").unwrap(), true),
1784 (RelPath::from_unix_str("dir2").unwrap(), false),
1785 (RelPath::from_unix_str("dir10").unwrap(), false),
1786 ]
1787 );
1788 }
1789
1790 #[perf]
1791 fn compare_rel_paths_mixed_case() {
1792 let mut paths = vec![
1794 (RelPath::from_unix_str("README.md").unwrap(), true),
1795 (RelPath::from_unix_str("readme.txt").unwrap(), true),
1796 (RelPath::from_unix_str("ReadMe.rs").unwrap(), true),
1797 ];
1798 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1799 assert_eq!(
1801 paths,
1802 vec![
1803 (RelPath::from_unix_str("README.md").unwrap(), true),
1804 (RelPath::from_unix_str("ReadMe.rs").unwrap(), true),
1805 (RelPath::from_unix_str("readme.txt").unwrap(), true),
1806 ]
1807 );
1808 }
1809
1810 #[perf]
1811 fn compare_rel_paths_mixed_files_and_dirs() {
1812 let mut paths = vec![
1814 (RelPath::from_unix_str("file2.txt").unwrap(), true),
1815 (RelPath::from_unix_str("Dir1").unwrap(), false),
1816 (RelPath::from_unix_str("file1.txt").unwrap(), true),
1817 (RelPath::from_unix_str("dir2").unwrap(), false),
1818 ];
1819 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1820 assert_eq!(
1822 paths,
1823 vec![
1824 (RelPath::from_unix_str("Dir1").unwrap(), false),
1825 (RelPath::from_unix_str("dir2").unwrap(), false),
1826 (RelPath::from_unix_str("file1.txt").unwrap(), true),
1827 (RelPath::from_unix_str("file2.txt").unwrap(), true),
1828 ]
1829 );
1830 }
1831
1832 #[perf]
1833 fn compare_rel_paths_mixed_same_name_different_case_file_and_dir() {
1834 let mut paths = vec![
1835 (RelPath::from_unix_str("Hello.txt").unwrap(), true),
1836 (RelPath::from_unix_str("hello").unwrap(), false),
1837 ];
1838 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1839 assert_eq!(
1840 paths,
1841 vec![
1842 (RelPath::from_unix_str("hello").unwrap(), false),
1843 (RelPath::from_unix_str("Hello.txt").unwrap(), true),
1844 ]
1845 );
1846
1847 let mut paths = vec![
1848 (RelPath::from_unix_str("hello").unwrap(), false),
1849 (RelPath::from_unix_str("Hello.txt").unwrap(), true),
1850 ];
1851 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1852 assert_eq!(
1853 paths,
1854 vec![
1855 (RelPath::from_unix_str("hello").unwrap(), false),
1856 (RelPath::from_unix_str("Hello.txt").unwrap(), true),
1857 ]
1858 );
1859 }
1860
1861 #[perf]
1862 fn compare_rel_paths_mixed_with_nested_paths() {
1863 let mut paths = vec![
1865 (RelPath::from_unix_str("src/main.rs").unwrap(), true),
1866 (RelPath::from_unix_str("Cargo.toml").unwrap(), true),
1867 (RelPath::from_unix_str("src").unwrap(), false),
1868 (RelPath::from_unix_str("target").unwrap(), false),
1869 ];
1870 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1871 assert_eq!(
1872 paths,
1873 vec![
1874 (RelPath::from_unix_str("Cargo.toml").unwrap(), true),
1875 (RelPath::from_unix_str("src").unwrap(), false),
1876 (RelPath::from_unix_str("src/main.rs").unwrap(), true),
1877 (RelPath::from_unix_str("target").unwrap(), false),
1878 ]
1879 );
1880 }
1881
1882 #[perf]
1883 fn compare_rel_paths_files_first_with_nested() {
1884 let mut paths = vec![
1886 (RelPath::from_unix_str("src/lib.rs").unwrap(), true),
1887 (RelPath::from_unix_str("README.md").unwrap(), true),
1888 (RelPath::from_unix_str("src").unwrap(), false),
1889 (RelPath::from_unix_str("tests").unwrap(), false),
1890 ];
1891 paths
1892 .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1893 assert_eq!(
1894 paths,
1895 vec![
1896 (RelPath::from_unix_str("README.md").unwrap(), true),
1897 (RelPath::from_unix_str("src").unwrap(), false),
1898 (RelPath::from_unix_str("src/lib.rs").unwrap(), true),
1899 (RelPath::from_unix_str("tests").unwrap(), false),
1900 ]
1901 );
1902 }
1903
1904 #[perf]
1905 fn compare_rel_paths_mixed_dotfiles() {
1906 let mut paths = vec![
1908 (RelPath::from_unix_str(".gitignore").unwrap(), true),
1909 (RelPath::from_unix_str("README.md").unwrap(), true),
1910 (RelPath::from_unix_str(".github").unwrap(), false),
1911 (RelPath::from_unix_str("src").unwrap(), false),
1912 ];
1913 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1914 assert_eq!(
1915 paths,
1916 vec![
1917 (RelPath::from_unix_str(".github").unwrap(), false),
1918 (RelPath::from_unix_str(".gitignore").unwrap(), true),
1919 (RelPath::from_unix_str("README.md").unwrap(), true),
1920 (RelPath::from_unix_str("src").unwrap(), false),
1921 ]
1922 );
1923 }
1924
1925 #[perf]
1926 fn compare_rel_paths_files_first_dotfiles() {
1927 let mut paths = vec![
1929 (RelPath::from_unix_str(".gitignore").unwrap(), true),
1930 (RelPath::from_unix_str("README.md").unwrap(), true),
1931 (RelPath::from_unix_str(".github").unwrap(), false),
1932 (RelPath::from_unix_str("src").unwrap(), false),
1933 ];
1934 paths
1935 .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1936 assert_eq!(
1937 paths,
1938 vec![
1939 (RelPath::from_unix_str(".gitignore").unwrap(), true),
1940 (RelPath::from_unix_str("README.md").unwrap(), true),
1941 (RelPath::from_unix_str(".github").unwrap(), false),
1942 (RelPath::from_unix_str("src").unwrap(), false),
1943 ]
1944 );
1945 }
1946
1947 #[perf]
1948 fn compare_rel_paths_mixed_same_stem_different_extension() {
1949 let mut paths = vec![
1951 (RelPath::from_unix_str("file.rs").unwrap(), true),
1952 (RelPath::from_unix_str("file.md").unwrap(), true),
1953 (RelPath::from_unix_str("file.txt").unwrap(), true),
1954 ];
1955 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1956 assert_eq!(
1957 paths,
1958 vec![
1959 (RelPath::from_unix_str("file.md").unwrap(), true),
1960 (RelPath::from_unix_str("file.rs").unwrap(), true),
1961 (RelPath::from_unix_str("file.txt").unwrap(), true),
1962 ]
1963 );
1964 }
1965
1966 #[perf]
1967 fn compare_rel_paths_files_first_same_stem() {
1968 let mut paths = vec![
1970 (RelPath::from_unix_str("main.rs").unwrap(), true),
1971 (RelPath::from_unix_str("main.c").unwrap(), true),
1972 (RelPath::from_unix_str("main").unwrap(), false),
1973 ];
1974 paths
1975 .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default));
1976 assert_eq!(
1977 paths,
1978 vec![
1979 (RelPath::from_unix_str("main.c").unwrap(), true),
1980 (RelPath::from_unix_str("main.rs").unwrap(), true),
1981 (RelPath::from_unix_str("main").unwrap(), false),
1982 ]
1983 );
1984 }
1985
1986 #[perf]
1987 fn compare_rel_paths_mixed_deep_nesting() {
1988 let mut paths = vec![
1990 (RelPath::from_unix_str("a/b/c.txt").unwrap(), true),
1991 (RelPath::from_unix_str("A/B.txt").unwrap(), true),
1992 (RelPath::from_unix_str("a.txt").unwrap(), true),
1993 (RelPath::from_unix_str("A.txt").unwrap(), true),
1994 ];
1995 paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default));
1996 assert_eq!(
1997 paths,
1998 vec![
1999 (RelPath::from_unix_str("a/b/c.txt").unwrap(), true),
2000 (RelPath::from_unix_str("A/B.txt").unwrap(), true),
2001 (RelPath::from_unix_str("a.txt").unwrap(), true),
2002 (RelPath::from_unix_str("A.txt").unwrap(), true),
2003 ]
2004 );
2005 }
2006
2007 #[perf]
2008 fn compare_rel_paths_upper() {
2009 let directories_only_paths = vec![
2010 rel_path_entry("mixedCase", false),
2011 rel_path_entry("Zebra", false),
2012 rel_path_entry("banana", false),
2013 rel_path_entry("ALLCAPS", false),
2014 rel_path_entry("Apple", false),
2015 rel_path_entry("dog", false),
2016 rel_path_entry(".hidden", false),
2017 rel_path_entry("Carrot", false),
2018 ];
2019 assert_eq!(
2020 sorted_rel_paths(
2021 directories_only_paths,
2022 SortMode::DirectoriesFirst,
2023 SortOrder::Upper,
2024 ),
2025 vec![
2026 rel_path_entry(".hidden", false),
2027 rel_path_entry("ALLCAPS", false),
2028 rel_path_entry("Apple", false),
2029 rel_path_entry("Carrot", false),
2030 rel_path_entry("Zebra", false),
2031 rel_path_entry("banana", false),
2032 rel_path_entry("dog", false),
2033 rel_path_entry("mixedCase", false),
2034 ]
2035 );
2036
2037 let file_and_directory_paths = vec![
2038 rel_path_entry("banana", false),
2039 rel_path_entry("Apple.txt", true),
2040 rel_path_entry("dog.md", true),
2041 rel_path_entry("ALLCAPS", false),
2042 rel_path_entry("file1.txt", true),
2043 rel_path_entry("File2.txt", true),
2044 rel_path_entry(".hidden", false),
2045 ];
2046 assert_eq!(
2047 sorted_rel_paths(
2048 file_and_directory_paths.clone(),
2049 SortMode::DirectoriesFirst,
2050 SortOrder::Upper,
2051 ),
2052 vec![
2053 rel_path_entry(".hidden", false),
2054 rel_path_entry("ALLCAPS", false),
2055 rel_path_entry("banana", false),
2056 rel_path_entry("Apple.txt", true),
2057 rel_path_entry("File2.txt", true),
2058 rel_path_entry("dog.md", true),
2059 rel_path_entry("file1.txt", true),
2060 ]
2061 );
2062 assert_eq!(
2063 sorted_rel_paths(
2064 file_and_directory_paths.clone(),
2065 SortMode::Mixed,
2066 SortOrder::Upper,
2067 ),
2068 vec![
2069 rel_path_entry(".hidden", false),
2070 rel_path_entry("ALLCAPS", false),
2071 rel_path_entry("Apple.txt", true),
2072 rel_path_entry("File2.txt", true),
2073 rel_path_entry("banana", false),
2074 rel_path_entry("dog.md", true),
2075 rel_path_entry("file1.txt", true),
2076 ]
2077 );
2078 assert_eq!(
2079 sorted_rel_paths(
2080 file_and_directory_paths,
2081 SortMode::FilesFirst,
2082 SortOrder::Upper,
2083 ),
2084 vec![
2085 rel_path_entry("Apple.txt", true),
2086 rel_path_entry("File2.txt", true),
2087 rel_path_entry("dog.md", true),
2088 rel_path_entry("file1.txt", true),
2089 rel_path_entry(".hidden", false),
2090 rel_path_entry("ALLCAPS", false),
2091 rel_path_entry("banana", false),
2092 ]
2093 );
2094
2095 let natural_sort_paths = vec![
2096 rel_path_entry("file10.txt", true),
2097 rel_path_entry("file1.txt", true),
2098 rel_path_entry("file20.txt", true),
2099 rel_path_entry("file2.txt", true),
2100 ];
2101 assert_eq!(
2102 sorted_rel_paths(natural_sort_paths, SortMode::Mixed, SortOrder::Upper,),
2103 vec![
2104 rel_path_entry("file1.txt", true),
2105 rel_path_entry("file2.txt", true),
2106 rel_path_entry("file10.txt", true),
2107 rel_path_entry("file20.txt", true),
2108 ]
2109 );
2110
2111 let accented_paths = vec![
2112 rel_path_entry("\u{00C9}something.txt", true),
2113 rel_path_entry("zebra.txt", true),
2114 rel_path_entry("Apple.txt", true),
2115 ];
2116 assert_eq!(
2117 sorted_rel_paths(accented_paths, SortMode::Mixed, SortOrder::Upper),
2118 vec![
2119 rel_path_entry("Apple.txt", true),
2120 rel_path_entry("\u{00C9}something.txt", true),
2121 rel_path_entry("zebra.txt", true),
2122 ]
2123 );
2124 }
2125
2126 #[perf]
2127 fn compare_rel_paths_lower() {
2128 let directories_only_paths = vec![
2129 rel_path_entry("mixedCase", false),
2130 rel_path_entry("Zebra", false),
2131 rel_path_entry("banana", false),
2132 rel_path_entry("ALLCAPS", false),
2133 rel_path_entry("Apple", false),
2134 rel_path_entry("dog", false),
2135 rel_path_entry(".hidden", false),
2136 rel_path_entry("Carrot", false),
2137 ];
2138 assert_eq!(
2139 sorted_rel_paths(
2140 directories_only_paths,
2141 SortMode::DirectoriesFirst,
2142 SortOrder::Lower,
2143 ),
2144 vec![
2145 rel_path_entry(".hidden", false),
2146 rel_path_entry("banana", false),
2147 rel_path_entry("dog", false),
2148 rel_path_entry("mixedCase", false),
2149 rel_path_entry("ALLCAPS", false),
2150 rel_path_entry("Apple", false),
2151 rel_path_entry("Carrot", false),
2152 rel_path_entry("Zebra", false),
2153 ]
2154 );
2155
2156 let file_and_directory_paths = vec![
2157 rel_path_entry("banana", false),
2158 rel_path_entry("Apple.txt", true),
2159 rel_path_entry("dog.md", true),
2160 rel_path_entry("ALLCAPS", false),
2161 rel_path_entry("file1.txt", true),
2162 rel_path_entry("File2.txt", true),
2163 rel_path_entry(".hidden", false),
2164 ];
2165 assert_eq!(
2166 sorted_rel_paths(
2167 file_and_directory_paths.clone(),
2168 SortMode::DirectoriesFirst,
2169 SortOrder::Lower,
2170 ),
2171 vec![
2172 rel_path_entry(".hidden", false),
2173 rel_path_entry("banana", false),
2174 rel_path_entry("ALLCAPS", false),
2175 rel_path_entry("dog.md", true),
2176 rel_path_entry("file1.txt", true),
2177 rel_path_entry("Apple.txt", true),
2178 rel_path_entry("File2.txt", true),
2179 ]
2180 );
2181 assert_eq!(
2182 sorted_rel_paths(
2183 file_and_directory_paths.clone(),
2184 SortMode::Mixed,
2185 SortOrder::Lower,
2186 ),
2187 vec![
2188 rel_path_entry(".hidden", false),
2189 rel_path_entry("banana", false),
2190 rel_path_entry("dog.md", true),
2191 rel_path_entry("file1.txt", true),
2192 rel_path_entry("ALLCAPS", false),
2193 rel_path_entry("Apple.txt", true),
2194 rel_path_entry("File2.txt", true),
2195 ]
2196 );
2197 assert_eq!(
2198 sorted_rel_paths(
2199 file_and_directory_paths,
2200 SortMode::FilesFirst,
2201 SortOrder::Lower,
2202 ),
2203 vec![
2204 rel_path_entry("dog.md", true),
2205 rel_path_entry("file1.txt", true),
2206 rel_path_entry("Apple.txt", true),
2207 rel_path_entry("File2.txt", true),
2208 rel_path_entry(".hidden", false),
2209 rel_path_entry("banana", false),
2210 rel_path_entry("ALLCAPS", false),
2211 ]
2212 );
2213 }
2214
2215 #[perf]
2216 fn compare_rel_paths_unicode() {
2217 let directories_only_paths = vec![
2218 rel_path_entry("mixedCase", false),
2219 rel_path_entry("Zebra", false),
2220 rel_path_entry("banana", false),
2221 rel_path_entry("ALLCAPS", false),
2222 rel_path_entry("Apple", false),
2223 rel_path_entry("dog", false),
2224 rel_path_entry(".hidden", false),
2225 rel_path_entry("Carrot", false),
2226 ];
2227 assert_eq!(
2228 sorted_rel_paths(
2229 directories_only_paths,
2230 SortMode::DirectoriesFirst,
2231 SortOrder::Unicode,
2232 ),
2233 vec![
2234 rel_path_entry(".hidden", false),
2235 rel_path_entry("ALLCAPS", false),
2236 rel_path_entry("Apple", false),
2237 rel_path_entry("Carrot", false),
2238 rel_path_entry("Zebra", false),
2239 rel_path_entry("banana", false),
2240 rel_path_entry("dog", false),
2241 rel_path_entry("mixedCase", false),
2242 ]
2243 );
2244
2245 let file_and_directory_paths = vec![
2246 rel_path_entry("banana", false),
2247 rel_path_entry("Apple.txt", true),
2248 rel_path_entry("dog.md", true),
2249 rel_path_entry("ALLCAPS", false),
2250 rel_path_entry("file1.txt", true),
2251 rel_path_entry("File2.txt", true),
2252 rel_path_entry(".hidden", false),
2253 ];
2254 assert_eq!(
2255 sorted_rel_paths(
2256 file_and_directory_paths.clone(),
2257 SortMode::DirectoriesFirst,
2258 SortOrder::Unicode,
2259 ),
2260 vec![
2261 rel_path_entry(".hidden", false),
2262 rel_path_entry("ALLCAPS", false),
2263 rel_path_entry("banana", false),
2264 rel_path_entry("Apple.txt", true),
2265 rel_path_entry("File2.txt", true),
2266 rel_path_entry("dog.md", true),
2267 rel_path_entry("file1.txt", true),
2268 ]
2269 );
2270 assert_eq!(
2271 sorted_rel_paths(
2272 file_and_directory_paths.clone(),
2273 SortMode::Mixed,
2274 SortOrder::Unicode,
2275 ),
2276 vec![
2277 rel_path_entry(".hidden", false),
2278 rel_path_entry("ALLCAPS", false),
2279 rel_path_entry("Apple.txt", true),
2280 rel_path_entry("File2.txt", true),
2281 rel_path_entry("banana", false),
2282 rel_path_entry("dog.md", true),
2283 rel_path_entry("file1.txt", true),
2284 ]
2285 );
2286 assert_eq!(
2287 sorted_rel_paths(
2288 file_and_directory_paths,
2289 SortMode::FilesFirst,
2290 SortOrder::Unicode,
2291 ),
2292 vec![
2293 rel_path_entry("Apple.txt", true),
2294 rel_path_entry("File2.txt", true),
2295 rel_path_entry("dog.md", true),
2296 rel_path_entry("file1.txt", true),
2297 rel_path_entry(".hidden", false),
2298 rel_path_entry("ALLCAPS", false),
2299 rel_path_entry("banana", false),
2300 ]
2301 );
2302
2303 let numeric_paths = vec![
2304 rel_path_entry("file10.txt", true),
2305 rel_path_entry("file1.txt", true),
2306 rel_path_entry("file2.txt", true),
2307 rel_path_entry("file20.txt", true),
2308 ];
2309 assert_eq!(
2310 sorted_rel_paths(numeric_paths, SortMode::Mixed, SortOrder::Unicode,),
2311 vec![
2312 rel_path_entry("file1.txt", true),
2313 rel_path_entry("file10.txt", true),
2314 rel_path_entry("file2.txt", true),
2315 rel_path_entry("file20.txt", true),
2316 ]
2317 );
2318
2319 let accented_paths = vec![
2320 rel_path_entry("\u{00C9}something.txt", true),
2321 rel_path_entry("zebra.txt", true),
2322 rel_path_entry("Apple.txt", true),
2323 ];
2324 assert_eq!(
2325 sorted_rel_paths(accented_paths, SortMode::Mixed, SortOrder::Unicode),
2326 vec![
2327 rel_path_entry("Apple.txt", true),
2328 rel_path_entry("zebra.txt", true),
2329 rel_path_entry("\u{00C9}something.txt", true),
2330 ]
2331 );
2332 }
2333
2334 #[test]
2335 fn path_with_position_preserves_paths_without_positions() {
2336 for input in [
2337 "",
2338 "/",
2339 "thf/",
2340 "/test/cool/",
2341 "/test/Ῥόδος/",
2342 "parent//file.rs",
2343 "parent/./file.rs",
2344 "parent/file.rs/.",
2345 "parent:12:3/file.rs/",
2346 "file.rs:invalid/",
2347 " parent/file.rs ",
2348 r"C:\test\cool\",
2349 r"C:\test\Ῥόδος\",
2350 r"\\server\share\cool\",
2351 ] {
2352 let parsed = PathWithPosition::parse_str(input);
2353 assert_eq!(parsed.path.as_os_str(), Path::new(input).as_os_str());
2354 assert_eq!(parsed.row, None, "{input}");
2355 assert_eq!(parsed.column, None, "{input}");
2356 }
2357 }
2358
2359 #[test]
2360 fn path_with_position_preserves_repeated_filename() {
2361 for (input, expected_path) in [
2362 ("file.rs/file.rs:12:3", "file.rs/file.rs"),
2363 ("file.rs-backups/file.rs(12,3)", "file.rs-backups/file.rs"),
2364 ("😀.rs/😀.rs:12:3", "😀.rs/😀.rs"),
2365 ("parent/a(b).rs(12,3)", "parent/a(b).rs"),
2366 ("parent/😀(b).rs(12,3)", "parent/😀(b).rs"),
2367 ("parent/a(b).rs:(12,3)", "parent/a(b).rs"),
2368 (r"src\file.rs\file.rs:12:3", r"src\file.rs\file.rs"),
2369 ] {
2370 assert_eq!(
2371 PathWithPosition::parse_str(input),
2372 PathWithPosition {
2373 path: PathBuf::from(expected_path),
2374 row: Some(12),
2375 column: Some(3),
2376 },
2377 "{input}",
2378 );
2379 }
2380 }
2381
2382 #[test]
2383 fn path_with_position_preserves_parent_position_like_components() {
2384 for (input, expected_path, row) in [
2385 ("parent:12:3/file.rs", "parent:12:3/file.rs", None),
2386 ("parent:12:3/file.rs:4:in", "parent:12:3/file.rs", Some(4)),
2387 (" parent/file.rs ", " parent/file.rs ", None),
2388 (" parent/file.rs:4:in ", " parent/file.rs", Some(4)),
2389 ] {
2390 assert_eq!(
2391 PathWithPosition::parse_str(input),
2392 PathWithPosition {
2393 path: PathBuf::from(expected_path),
2394 row,
2395 column: None,
2396 },
2397 "{input}",
2398 );
2399 }
2400 }
2401
2402 #[perf]
2403 fn path_with_position_parse_posix_path() {
2404 assert_eq!(
2407 PathWithPosition::parse_str("test_file"),
2408 PathWithPosition {
2409 path: PathBuf::from("test_file"),
2410 row: None,
2411 column: None
2412 }
2413 );
2414
2415 assert_eq!(
2416 PathWithPosition::parse_str("a:bc:.zip:1"),
2417 PathWithPosition {
2418 path: PathBuf::from("a:bc:.zip"),
2419 row: Some(1),
2420 column: None
2421 }
2422 );
2423
2424 assert_eq!(
2425 PathWithPosition::parse_str("one.second.zip:1"),
2426 PathWithPosition {
2427 path: PathBuf::from("one.second.zip"),
2428 row: Some(1),
2429 column: None
2430 }
2431 );
2432
2433 assert_eq!(
2435 PathWithPosition::parse_str("test_file:10:1:"),
2436 PathWithPosition {
2437 path: PathBuf::from("test_file"),
2438 row: Some(10),
2439 column: Some(1)
2440 }
2441 );
2442
2443 assert_eq!(
2444 PathWithPosition::parse_str("test_file.rs:"),
2445 PathWithPosition {
2446 path: PathBuf::from("test_file.rs"),
2447 row: None,
2448 column: None
2449 }
2450 );
2451
2452 assert_eq!(
2453 PathWithPosition::parse_str("test_file.rs:1:"),
2454 PathWithPosition {
2455 path: PathBuf::from("test_file.rs"),
2456 row: Some(1),
2457 column: None
2458 }
2459 );
2460
2461 assert_eq!(
2462 PathWithPosition::parse_str("ab\ncd"),
2463 PathWithPosition {
2464 path: PathBuf::from("ab\ncd"),
2465 row: None,
2466 column: None
2467 }
2468 );
2469
2470 assert_eq!(
2471 PathWithPosition::parse_str("👋\nab"),
2472 PathWithPosition {
2473 path: PathBuf::from("👋\nab"),
2474 row: None,
2475 column: None
2476 }
2477 );
2478
2479 assert_eq!(
2480 PathWithPosition::parse_str("Types.hs:(617,9)-(670,28):"),
2481 PathWithPosition {
2482 path: PathBuf::from("Types.hs"),
2483 row: Some(617),
2484 column: Some(9),
2485 }
2486 );
2487
2488 assert_eq!(
2489 PathWithPosition::parse_str("main (1).log"),
2490 PathWithPosition {
2491 path: PathBuf::from("main (1).log"),
2492 row: None,
2493 column: None
2494 }
2495 );
2496 }
2497
2498 #[perf]
2499 #[cfg(not(target_os = "windows"))]
2500 fn path_with_position_parse_posix_path_with_suffix() {
2501 assert_eq!(
2502 PathWithPosition::parse_str("foo/bar:34:in"),
2503 PathWithPosition {
2504 path: PathBuf::from("foo/bar"),
2505 row: Some(34),
2506 column: None,
2507 }
2508 );
2509 assert_eq!(
2510 PathWithPosition::parse_str("foo/bar.rs:1902:::15:"),
2511 PathWithPosition {
2512 path: PathBuf::from("foo/bar.rs:1902"),
2513 row: Some(15),
2514 column: None
2515 }
2516 );
2517
2518 assert_eq!(
2519 PathWithPosition::parse_str("app-editors:zed-0.143.6:20240710-201212.log:34:"),
2520 PathWithPosition {
2521 path: PathBuf::from("app-editors:zed-0.143.6:20240710-201212.log"),
2522 row: Some(34),
2523 column: None,
2524 }
2525 );
2526
2527 assert_eq!(
2528 PathWithPosition::parse_str("crates/file_finder/src/file_finder.rs:1902:13:"),
2529 PathWithPosition {
2530 path: PathBuf::from("crates/file_finder/src/file_finder.rs"),
2531 row: Some(1902),
2532 column: Some(13),
2533 }
2534 );
2535
2536 assert_eq!(
2537 PathWithPosition::parse_str("crate/utils/src/test:today.log:34"),
2538 PathWithPosition {
2539 path: PathBuf::from("crate/utils/src/test:today.log"),
2540 row: Some(34),
2541 column: None,
2542 }
2543 );
2544 assert_eq!(
2545 PathWithPosition::parse_str("/testing/out/src/file_finder.odin(7:15)"),
2546 PathWithPosition {
2547 path: PathBuf::from("/testing/out/src/file_finder.odin"),
2548 row: Some(7),
2549 column: Some(15),
2550 }
2551 );
2552 }
2553
2554 #[perf]
2555 #[cfg(target_os = "windows")]
2556 fn path_with_position_parse_windows_path() {
2557 assert_eq!(
2558 PathWithPosition::parse_str("crates\\utils\\paths.rs"),
2559 PathWithPosition {
2560 path: PathBuf::from("crates\\utils\\paths.rs"),
2561 row: None,
2562 column: None
2563 }
2564 );
2565
2566 assert_eq!(
2567 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs"),
2568 PathWithPosition {
2569 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2570 row: None,
2571 column: None
2572 }
2573 );
2574
2575 assert_eq!(
2576 PathWithPosition::parse_str("C:\\Users\\someone\\main (1).log"),
2577 PathWithPosition {
2578 path: PathBuf::from("C:\\Users\\someone\\main (1).log"),
2579 row: None,
2580 column: None
2581 }
2582 );
2583 }
2584
2585 #[perf]
2586 #[cfg(target_os = "windows")]
2587 fn path_with_position_parse_windows_path_with_suffix() {
2588 assert_eq!(
2589 PathWithPosition::parse_str("crates\\utils\\paths.rs:101"),
2590 PathWithPosition {
2591 path: PathBuf::from("crates\\utils\\paths.rs"),
2592 row: Some(101),
2593 column: None
2594 }
2595 );
2596
2597 assert_eq!(
2598 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1:20"),
2599 PathWithPosition {
2600 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2601 row: Some(1),
2602 column: Some(20)
2603 }
2604 );
2605
2606 assert_eq!(
2607 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13)"),
2608 PathWithPosition {
2609 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2610 row: Some(1902),
2611 column: Some(13)
2612 }
2613 );
2614
2615 assert_eq!(
2617 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:"),
2618 PathWithPosition {
2619 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2620 row: Some(1902),
2621 column: Some(13)
2622 }
2623 );
2624
2625 assert_eq!(
2626 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:15:"),
2627 PathWithPosition {
2628 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
2629 row: Some(13),
2630 column: Some(15)
2631 }
2632 );
2633
2634 assert_eq!(
2635 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:::15:"),
2636 PathWithPosition {
2637 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"),
2638 row: Some(15),
2639 column: None
2640 }
2641 );
2642
2643 assert_eq!(
2644 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902,13):"),
2645 PathWithPosition {
2646 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2647 row: Some(1902),
2648 column: Some(13),
2649 }
2650 );
2651
2652 assert_eq!(
2653 PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902):"),
2654 PathWithPosition {
2655 path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"),
2656 row: Some(1902),
2657 column: None,
2658 }
2659 );
2660
2661 assert_eq!(
2662 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs:1902:13:"),
2663 PathWithPosition {
2664 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2665 row: Some(1902),
2666 column: Some(13),
2667 }
2668 );
2669
2670 assert_eq!(
2671 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13):"),
2672 PathWithPosition {
2673 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2674 row: Some(1902),
2675 column: Some(13),
2676 }
2677 );
2678
2679 assert_eq!(
2680 PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902):"),
2681 PathWithPosition {
2682 path: PathBuf::from("C:\\Users\\someone\\test_file.rs"),
2683 row: Some(1902),
2684 column: None,
2685 }
2686 );
2687
2688 assert_eq!(
2689 PathWithPosition::parse_str("crates/utils/paths.rs:101"),
2690 PathWithPosition {
2691 path: PathBuf::from("crates\\utils\\paths.rs"),
2692 row: Some(101),
2693 column: None,
2694 }
2695 );
2696 }
2697
2698 #[perf]
2699 fn test_path_compact() {
2700 let path: PathBuf = [
2701 home_dir().to_string_lossy().into_owned(),
2702 "some_file.txt".to_string(),
2703 ]
2704 .iter()
2705 .collect();
2706 if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") {
2707 assert_eq!(path.compact().to_str(), Some("~/some_file.txt"));
2708 } else {
2709 assert_eq!(path.compact().to_str(), path.to_str());
2710 }
2711 }
2712
2713 #[perf]
2714 fn test_extension_or_hidden_file_name() {
2715 let path = Path::new("/a/b/c/file_name.rs");
2717 assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2718
2719 let path = Path::new("/a/b/c/file.name.rs");
2721 assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2722
2723 let path = Path::new("/a/b/c/long.file.name.rs");
2725 assert_eq!(path.extension_or_hidden_file_name(), Some("rs"));
2726
2727 let path = Path::new("/a/b/c/.gitignore");
2729 assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore"));
2730
2731 let path = Path::new("/a/b/c/.eslintrc.js");
2733 assert_eq!(path.extension_or_hidden_file_name(), Some("eslintrc.js"));
2734 }
2735
2736 #[perf]
2737 #[perf]
2773 #[cfg(target_os = "windows")]
2774 fn test_sanitized_path() {
2775 let path = Path::new("C:\\Users\\someone\\test_file.rs");
2776 let sanitized_path = SanitizedPath::new(path);
2777 assert_eq!(
2778 sanitized_path.to_string(),
2779 "C:\\Users\\someone\\test_file.rs"
2780 );
2781
2782 let path = Path::new("\\\\?\\C:\\Users\\someone\\test_file.rs");
2783 let sanitized_path = SanitizedPath::new(path);
2784 assert_eq!(
2785 sanitized_path.to_string(),
2786 "C:\\Users\\someone\\test_file.rs"
2787 );
2788 }
2789
2790 #[perf]
2791 #[cfg(target_os = "windows")]
2792 fn test_sanitized_path_verbatim_unc() {
2793 let path: Arc<Path> = PathBuf::from("\\\\?\\UNC\\server\\share\\file.txt").into();
2794 let sanitized_path = SanitizedPath::from_arc(path);
2795 assert_eq!(sanitized_path.to_string(), "\\\\server\\share\\file.txt");
2796 }
2797
2798 #[perf]
2799 fn test_compare_numeric_segments() {
2800 fn compare(a: &str, b: &str) -> Ordering {
2802 let mut a_iter = a.chars().peekable();
2803 let mut b_iter = b.chars().peekable();
2804
2805 let result = compare_numeric_segments(&mut a_iter, &mut b_iter);
2806
2807 assert!(
2809 !a_iter.next().is_some_and(|c| c.is_ascii_digit()),
2810 "Iterator a should have consumed all digits"
2811 );
2812 assert!(
2813 !b_iter.next().is_some_and(|c| c.is_ascii_digit()),
2814 "Iterator b should have consumed all digits"
2815 );
2816
2817 result
2818 }
2819
2820 assert_eq!(compare("0", "0"), Ordering::Equal);
2822 assert_eq!(compare("1", "2"), Ordering::Less);
2823 assert_eq!(compare("9", "10"), Ordering::Less);
2824 assert_eq!(compare("10", "9"), Ordering::Greater);
2825 assert_eq!(compare("99", "100"), Ordering::Less);
2826
2827 assert_eq!(compare("0", "00"), Ordering::Less);
2829 assert_eq!(compare("00", "0"), Ordering::Greater);
2830 assert_eq!(compare("01", "1"), Ordering::Greater);
2831 assert_eq!(compare("001", "1"), Ordering::Greater);
2832 assert_eq!(compare("001", "01"), Ordering::Greater);
2833
2834 assert_eq!(compare("000100", "100"), Ordering::Greater);
2836 assert_eq!(compare("100", "0100"), Ordering::Less);
2837 assert_eq!(compare("0100", "00100"), Ordering::Less);
2838
2839 assert_eq!(compare("9999999999", "10000000000"), Ordering::Less);
2841 assert_eq!(
2842 compare(
2843 "340282366920938463463374607431768211455", "340282366920938463463374607431768211456"
2845 ),
2846 Ordering::Less
2847 );
2848 assert_eq!(
2849 compare(
2850 "340282366920938463463374607431768211456", "340282366920938463463374607431768211455"
2852 ),
2853 Ordering::Greater
2854 );
2855
2856 let mut a_iter = "123abc".chars().peekable();
2858 let mut b_iter = "456def".chars().peekable();
2859
2860 compare_numeric_segments(&mut a_iter, &mut b_iter);
2861
2862 assert_eq!(a_iter.collect::<String>(), "abc");
2863 assert_eq!(b_iter.collect::<String>(), "def");
2864 }
2865
2866 #[perf]
2867 fn test_natural_sort() {
2868 assert_eq!(natural_sort("a", "b"), Ordering::Less);
2870 assert_eq!(natural_sort("b", "a"), Ordering::Greater);
2871 assert_eq!(natural_sort("a", "a"), Ordering::Equal);
2872
2873 assert_eq!(natural_sort("a", "A"), Ordering::Less);
2875 assert_eq!(natural_sort("A", "a"), Ordering::Greater);
2876 assert_eq!(natural_sort("aA", "aa"), Ordering::Greater);
2877 assert_eq!(natural_sort("aa", "aA"), Ordering::Less);
2878
2879 assert_eq!(natural_sort("1", "2"), Ordering::Less);
2881 assert_eq!(natural_sort("2", "10"), Ordering::Less);
2882 assert_eq!(natural_sort("02", "10"), Ordering::Less);
2883 assert_eq!(natural_sort("02", "2"), Ordering::Greater);
2884
2885 assert_eq!(natural_sort("a1", "a2"), Ordering::Less);
2887 assert_eq!(natural_sort("a2", "a10"), Ordering::Less);
2888 assert_eq!(natural_sort("a02", "a2"), Ordering::Greater);
2889 assert_eq!(natural_sort("a1b", "a1c"), Ordering::Less);
2890
2891 assert_eq!(natural_sort("1a2", "1a10"), Ordering::Less);
2893 assert_eq!(natural_sort("1a10", "1a2"), Ordering::Greater);
2894 assert_eq!(natural_sort("2a1", "10a1"), Ordering::Less);
2895
2896 assert_eq!(natural_sort("a-1", "a-2"), Ordering::Less);
2898 assert_eq!(natural_sort("a_1", "a_2"), Ordering::Less);
2899 assert_eq!(natural_sort("a.1", "a.2"), Ordering::Less);
2900
2901 assert_eq!(natural_sort("文1", "文2"), Ordering::Less);
2903 assert_eq!(natural_sort("文2", "文10"), Ordering::Less);
2904 assert_eq!(natural_sort("🔤1", "🔤2"), Ordering::Less);
2905
2906 assert_eq!(natural_sort("", ""), Ordering::Equal);
2908 assert_eq!(natural_sort("", "a"), Ordering::Less);
2909 assert_eq!(natural_sort("a", ""), Ordering::Greater);
2910 assert_eq!(natural_sort(" ", " "), Ordering::Less);
2911
2912 assert_eq!(natural_sort("File-1.txt", "File-2.txt"), Ordering::Less);
2914 assert_eq!(natural_sort("File-02.txt", "File-2.txt"), Ordering::Greater);
2915 assert_eq!(natural_sort("File-2.txt", "File-10.txt"), Ordering::Less);
2916 assert_eq!(natural_sort("File_A1", "File_A2"), Ordering::Less);
2917 assert_eq!(natural_sort("File_a1", "File_A1"), Ordering::Less);
2918 }
2919
2920 #[perf]
2921 fn test_compare_paths() {
2922 fn compare(a: &str, is_a_file: bool, b: &str, is_b_file: bool) -> Ordering {
2924 compare_paths((Path::new(a), is_a_file), (Path::new(b), is_b_file))
2925 }
2926
2927 assert_eq!(compare("a", true, "b", true), Ordering::Less);
2929 assert_eq!(compare("b", true, "a", true), Ordering::Greater);
2930 assert_eq!(compare("a", true, "a", true), Ordering::Equal);
2931
2932 assert_eq!(compare("a", true, "a", false), Ordering::Greater);
2934 assert_eq!(compare("a", false, "a", true), Ordering::Less);
2935 assert_eq!(compare("b", false, "a", true), Ordering::Less);
2936
2937 assert_eq!(compare("a.txt", true, "a.md", true), Ordering::Greater);
2939 assert_eq!(compare("a.md", true, "a.txt", true), Ordering::Less);
2940 assert_eq!(compare("a", true, "a.txt", true), Ordering::Less);
2941
2942 assert_eq!(compare("dir/a", true, "dir/b", true), Ordering::Less);
2944 assert_eq!(compare("dir1/a", true, "dir2/a", true), Ordering::Less);
2945 assert_eq!(compare("dir/sub/a", true, "dir/a", true), Ordering::Less);
2946
2947 assert_eq!(
2949 compare("Dir/file", true, "dir/file", true),
2950 Ordering::Greater
2951 );
2952 assert_eq!(
2953 compare("dir/File", true, "dir/file", true),
2954 Ordering::Greater
2955 );
2956 assert_eq!(compare("dir/file", true, "Dir/File", true), Ordering::Less);
2957
2958 assert_eq!(compare(".hidden", true, "visible", true), Ordering::Less);
2960 assert_eq!(compare("_special", true, "normal", true), Ordering::Less);
2961 assert_eq!(compare(".config", false, ".data", false), Ordering::Less);
2962
2963 assert_eq!(
2965 compare("dir1/file", true, "dir2/file", true),
2966 Ordering::Less
2967 );
2968 assert_eq!(
2969 compare("dir2/file", true, "dir10/file", true),
2970 Ordering::Less
2971 );
2972 assert_eq!(
2973 compare("dir02/file", true, "dir2/file", true),
2974 Ordering::Greater
2975 );
2976
2977 assert_eq!(compare("/a", true, "/b", true), Ordering::Less);
2979 assert_eq!(compare("/", false, "/a", true), Ordering::Less);
2980
2981 assert_eq!(
2983 compare("project/src/main.rs", true, "project/src/lib.rs", true),
2984 Ordering::Greater
2985 );
2986 assert_eq!(
2987 compare(
2988 "project/tests/test_1.rs",
2989 true,
2990 "project/tests/test_2.rs",
2991 true
2992 ),
2993 Ordering::Less
2994 );
2995 assert_eq!(
2996 compare(
2997 "project/v1.0.0/README.md",
2998 true,
2999 "project/v1.10.0/README.md",
3000 true
3001 ),
3002 Ordering::Less
3003 );
3004 }
3005
3006 #[perf]
3007 fn test_natural_sort_case_sensitivity() {
3008 std::thread::sleep(std::time::Duration::from_millis(100));
3009 assert_eq!(natural_sort("a", "A"), Ordering::Less);
3011 assert_eq!(natural_sort("A", "a"), Ordering::Greater);
3012 assert_eq!(natural_sort("a", "a"), Ordering::Equal);
3013 assert_eq!(natural_sort("A", "A"), Ordering::Equal);
3014
3015 assert_eq!(natural_sort("aaa", "AAA"), Ordering::Less);
3017 assert_eq!(natural_sort("AAA", "aaa"), Ordering::Greater);
3018 assert_eq!(natural_sort("aAa", "AaA"), Ordering::Less);
3019
3020 assert_eq!(natural_sort("a", "b"), Ordering::Less);
3022 assert_eq!(natural_sort("A", "b"), Ordering::Less);
3023 assert_eq!(natural_sort("a", "B"), Ordering::Less);
3024 }
3025
3026 #[perf]
3027 fn test_natural_sort_with_numbers() {
3028 assert_eq!(natural_sort("file1", "file2"), Ordering::Less);
3030 assert_eq!(natural_sort("file2", "file10"), Ordering::Less);
3031 assert_eq!(natural_sort("file10", "file2"), Ordering::Greater);
3032
3033 assert_eq!(natural_sort("1file", "2file"), Ordering::Less);
3035 assert_eq!(natural_sort("file1text", "file2text"), Ordering::Less);
3036 assert_eq!(natural_sort("text1file", "text2file"), Ordering::Less);
3037
3038 assert_eq!(natural_sort("file1-2", "file1-10"), Ordering::Less);
3040 assert_eq!(natural_sort("2-1file", "10-1file"), Ordering::Less);
3041
3042 assert_eq!(natural_sort("file002", "file2"), Ordering::Greater);
3044 assert_eq!(natural_sort("file002", "file10"), Ordering::Less);
3045
3046 assert_eq!(
3048 natural_sort("file999999999999999999999", "file999999999999999999998"),
3049 Ordering::Greater
3050 );
3051
3052 assert_eq!(
3056 natural_sort(
3057 "file340282366920938463463374607431768211454",
3058 "file340282366920938463463374607431768211455"
3059 ),
3060 Ordering::Less
3061 );
3062
3063 assert_eq!(
3065 natural_sort(
3066 "file340282366920938463463374607431768211456",
3067 "file340282366920938463463374607431768211455"
3068 ),
3069 Ordering::Greater
3070 );
3071
3072 assert_eq!(
3074 natural_sort(
3075 "file3402823669209384634633746074317682114560",
3076 "file340282366920938463463374607431768211455"
3077 ),
3078 Ordering::Greater
3079 );
3080
3081 assert_eq!(
3083 natural_sort(
3084 "file0340282366920938463463374607431768211455",
3085 "file340282366920938463463374607431768211455"
3086 ),
3087 Ordering::Greater
3088 );
3089
3090 assert_eq!(
3092 natural_sort(
3093 "file999999999999999999999999999999999999999999999999",
3094 "file9999999999999999999999999999999999999999999999999"
3095 ),
3096 Ordering::Less
3097 );
3098 }
3099
3100 #[perf]
3101 fn test_natural_sort_case_sensitive() {
3102 assert_eq!(natural_sort("File1", "file2"), Ordering::Less);
3104 assert_eq!(natural_sort("file1", "File2"), Ordering::Less);
3105
3106 assert_eq!(natural_sort("Dir1", "dir01"), Ordering::Less);
3109 assert_eq!(natural_sort("dir2", "Dir02"), Ordering::Less);
3110 assert_eq!(natural_sort("dir2", "dir02"), Ordering::Less);
3111
3112 assert_eq!(natural_sort("dir1", "Dir1"), Ordering::Less);
3115 assert_eq!(natural_sort("dir02", "Dir02"), Ordering::Less);
3116 assert_eq!(natural_sort("dir10", "Dir10"), Ordering::Less);
3117 }
3118
3119 #[perf]
3120 fn test_natural_sort_edge_cases() {
3121 assert_eq!(natural_sort("", ""), Ordering::Equal);
3123 assert_eq!(natural_sort("", "a"), Ordering::Less);
3124 assert_eq!(natural_sort("a", ""), Ordering::Greater);
3125
3126 assert_eq!(natural_sort("file-1", "file_1"), Ordering::Less);
3128 assert_eq!(natural_sort("file.1", "file_1"), Ordering::Less);
3129 assert_eq!(natural_sort("file 1", "file_1"), Ordering::Less);
3130
3131 assert_eq!(natural_sort("file①", "file②"), Ordering::Less);
3134 assert_eq!(natural_sort("file⑩", "file②"), Ordering::Greater);
3136 assert_eq!(natural_sort("file漢", "file字"), Ordering::Greater);
3138
3139 assert_eq!(natural_sort("file-1a", "file-1b"), Ordering::Less);
3141 assert_eq!(natural_sort("file-1.2", "file-1.10"), Ordering::Less);
3142 assert_eq!(natural_sort("file-1.10", "file-1.2"), Ordering::Greater);
3143 }
3144
3145 #[test]
3146 fn test_multiple_extensions() {
3147 let path = Path::new("/a/b/c/file_name");
3149 assert_eq!(path.multiple_extensions(), None);
3150
3151 let path = Path::new("/a/b/c/file_name.tsx");
3153 assert_eq!(path.multiple_extensions(), None);
3154
3155 let path = Path::new("/a/b/c/file_name.stories.tsx");
3157 assert_eq!(path.multiple_extensions(), Some("stories.tsx".to_string()));
3158
3159 let path = Path::new("/a/b/c/long.app.tar.gz");
3161 assert_eq!(path.multiple_extensions(), Some("app.tar.gz".to_string()));
3162 }
3163
3164 #[test]
3165 fn test_strip_path_suffix() {
3166 let base = Path::new("/a/b/c/file_name");
3167 let suffix = Path::new("file_name");
3168 assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
3169
3170 let base = Path::new("/a/b/c/file_name.tsx");
3171 let suffix = Path::new("file_name.tsx");
3172 assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c")));
3173
3174 let base = Path::new("/a/b/c/file_name.stories.tsx");
3175 let suffix = Path::new("c/file_name.stories.tsx");
3176 assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b")));
3177
3178 let base = Path::new("/a/b/c/long.app.tar.gz");
3179 let suffix = Path::new("b/c/long.app.tar.gz");
3180 assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a")));
3181
3182 let base = Path::new("/a/b/c/long.app.tar.gz");
3183 let suffix = Path::new("/a/b/c/long.app.tar.gz");
3184 assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("")));
3185
3186 let base = Path::new("/a/b/c/long.app.tar.gz");
3187 let suffix = Path::new("/a/b/c/no_match.app.tar.gz");
3188 assert_eq!(strip_path_suffix(base, suffix), None);
3189
3190 let base = Path::new("/a/b/c/long.app.tar.gz");
3191 let suffix = Path::new("app.tar.gz");
3192 assert_eq!(strip_path_suffix(base, suffix), None);
3193 }
3194
3195 #[cfg(target_os = "windows")]
3196 #[test]
3197 fn test_wsl_path() {
3198 use super::WslPath;
3199 let path = "/a/b/c";
3200 assert_eq!(WslPath::from_path(&path), None);
3201
3202 let path = r"\\wsl.localhost";
3203 assert_eq!(WslPath::from_path(&path), None);
3204
3205 let path = r"\\wsl.localhost\Distro";
3206 assert_eq!(
3207 WslPath::from_path(&path),
3208 Some(WslPath {
3209 distro: "Distro".to_owned(),
3210 path: "/".into(),
3211 })
3212 );
3213
3214 let path = r"\\wsl.localhost\Distro\blue";
3215 assert_eq!(
3216 WslPath::from_path(&path),
3217 Some(WslPath {
3218 distro: "Distro".to_owned(),
3219 path: "/blue".into()
3220 })
3221 );
3222
3223 let path = r"\\wsl$\archlinux\tomato\.\paprika\..\aubergine.txt";
3224 assert_eq!(
3225 WslPath::from_path(&path),
3226 Some(WslPath {
3227 distro: "archlinux".to_owned(),
3228 path: "/tomato/paprika/../aubergine.txt".into()
3229 })
3230 );
3231
3232 let path = r"\\windows.localhost\Distro\foo";
3233 assert_eq!(WslPath::from_path(&path), None);
3234 }
3235
3236 #[test]
3237 fn test_url_to_file_path_ext_posix_basic() {
3238 use super::UrlExt;
3239
3240 let url = url::Url::parse("file:///home/user/file.txt").unwrap();
3241 assert_eq!(
3242 url.to_file_path_ext(PathStyle::Unix),
3243 Ok(PathBuf::from("/home/user/file.txt"))
3244 );
3245
3246 let url = url::Url::parse("file:///").unwrap();
3247 assert_eq!(
3248 url.to_file_path_ext(PathStyle::Unix),
3249 Ok(PathBuf::from("/"))
3250 );
3251
3252 let url = url::Url::parse("file:///a/b/c/d/e").unwrap();
3253 assert_eq!(
3254 url.to_file_path_ext(PathStyle::Unix),
3255 Ok(PathBuf::from("/a/b/c/d/e"))
3256 );
3257 }
3258
3259 #[test]
3260 fn test_url_to_file_path_ext_posix_percent_encoding() {
3261 use super::UrlExt;
3262
3263 let url = url::Url::parse("file:///home/user/file%20with%20spaces.txt").unwrap();
3264 assert_eq!(
3265 url.to_file_path_ext(PathStyle::Unix),
3266 Ok(PathBuf::from("/home/user/file with spaces.txt"))
3267 );
3268
3269 let url = url::Url::parse("file:///path%2Fwith%2Fencoded%2Fslashes").unwrap();
3270 assert_eq!(
3271 url.to_file_path_ext(PathStyle::Unix),
3272 Ok(PathBuf::from("/path/with/encoded/slashes"))
3273 );
3274
3275 let url = url::Url::parse("file:///special%23chars%3F.txt").unwrap();
3276 assert_eq!(
3277 url.to_file_path_ext(PathStyle::Unix),
3278 Ok(PathBuf::from("/special#chars?.txt"))
3279 );
3280 }
3281
3282 #[test]
3283 fn test_url_to_file_path_ext_posix_localhost() {
3284 use super::UrlExt;
3285
3286 let url = url::Url::parse("file://localhost/home/user/file.txt").unwrap();
3287 assert_eq!(
3288 url.to_file_path_ext(PathStyle::Unix),
3289 Ok(PathBuf::from("/home/user/file.txt"))
3290 );
3291 }
3292
3293 #[test]
3294 fn test_url_to_file_path_ext_posix_rejects_host() {
3295 use super::UrlExt;
3296
3297 let url = url::Url::parse("file://somehost/home/user/file.txt").unwrap();
3298 assert_eq!(url.to_file_path_ext(PathStyle::Unix), Err(()));
3299 }
3300
3301 #[test]
3302 fn test_url_to_file_path_ext_posix_windows_drive_letter() {
3303 use super::UrlExt;
3304
3305 let url = url::Url::parse("file:///C:").unwrap();
3306 assert_eq!(
3307 url.to_file_path_ext(PathStyle::Unix),
3308 Ok(PathBuf::from("/C:/"))
3309 );
3310
3311 let url = url::Url::parse("file:///D|").unwrap();
3312 assert_eq!(
3313 url.to_file_path_ext(PathStyle::Unix),
3314 Ok(PathBuf::from("/D|/"))
3315 );
3316 }
3317
3318 #[test]
3319 fn test_url_to_file_path_ext_windows_basic() {
3320 use super::UrlExt;
3321
3322 let url = url::Url::parse("file:///C:/Users/user/file.txt").unwrap();
3323 assert_eq!(
3324 url.to_file_path_ext(PathStyle::Windows),
3325 Ok(PathBuf::from("C:\\Users\\user\\file.txt"))
3326 );
3327
3328 let url = url::Url::parse("file:///D:/folder/subfolder/file.rs").unwrap();
3329 assert_eq!(
3330 url.to_file_path_ext(PathStyle::Windows),
3331 Ok(PathBuf::from("D:\\folder\\subfolder\\file.rs"))
3332 );
3333
3334 let url = url::Url::parse("file:///C:/").unwrap();
3335 assert_eq!(
3336 url.to_file_path_ext(PathStyle::Windows),
3337 Ok(PathBuf::from("C:\\"))
3338 );
3339 }
3340
3341 #[test]
3342 fn test_url_to_file_path_ext_windows_encoded_drive_letter() {
3343 use super::UrlExt;
3344
3345 let url = url::Url::parse("file:///C%3A/Users/file.txt").unwrap();
3346 assert_eq!(
3347 url.to_file_path_ext(PathStyle::Windows),
3348 Ok(PathBuf::from("C:\\Users\\file.txt"))
3349 );
3350
3351 let url = url::Url::parse("file:///c%3a/Users/file.txt").unwrap();
3352 assert_eq!(
3353 url.to_file_path_ext(PathStyle::Windows),
3354 Ok(PathBuf::from("c:\\Users\\file.txt"))
3355 );
3356
3357 let url = url::Url::parse("file:///D%3A/folder/file.txt").unwrap();
3358 assert_eq!(
3359 url.to_file_path_ext(PathStyle::Windows),
3360 Ok(PathBuf::from("D:\\folder\\file.txt"))
3361 );
3362
3363 let url = url::Url::parse("file:///d%3A/folder/file.txt").unwrap();
3364 assert_eq!(
3365 url.to_file_path_ext(PathStyle::Windows),
3366 Ok(PathBuf::from("d:\\folder\\file.txt"))
3367 );
3368 }
3369
3370 #[test]
3371 fn test_url_to_file_path_ext_windows_unc_path() {
3372 use super::UrlExt;
3373
3374 let url = url::Url::parse("file://server/share/path/file.txt").unwrap();
3375 assert_eq!(
3376 url.to_file_path_ext(PathStyle::Windows),
3377 Ok(PathBuf::from("\\\\server\\share\\path\\file.txt"))
3378 );
3379
3380 let url = url::Url::parse("file://server/share").unwrap();
3381 assert_eq!(
3382 url.to_file_path_ext(PathStyle::Windows),
3383 Ok(PathBuf::from("\\\\server\\share"))
3384 );
3385 }
3386
3387 #[test]
3388 fn test_url_to_file_path_ext_windows_percent_encoding() {
3389 use super::UrlExt;
3390
3391 let url = url::Url::parse("file:///C:/Users/user/file%20with%20spaces.txt").unwrap();
3392 assert_eq!(
3393 url.to_file_path_ext(PathStyle::Windows),
3394 Ok(PathBuf::from("C:\\Users\\user\\file with spaces.txt"))
3395 );
3396
3397 let url = url::Url::parse("file:///C:/special%23chars%3F.txt").unwrap();
3398 assert_eq!(
3399 url.to_file_path_ext(PathStyle::Windows),
3400 Ok(PathBuf::from("C:\\special#chars?.txt"))
3401 );
3402 }
3403
3404 #[test]
3405 fn test_url_to_file_path_ext_windows_invalid_drive() {
3406 use super::UrlExt;
3407
3408 let url = url::Url::parse("file:///1:/path/file.txt").unwrap();
3409 assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3410
3411 let url = url::Url::parse("file:///CC:/path/file.txt").unwrap();
3412 assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3413
3414 let url = url::Url::parse("file:///C/path/file.txt").unwrap();
3415 assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3416
3417 let url = url::Url::parse("file:///invalid").unwrap();
3418 assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3419 }
3420
3421 #[test]
3422 fn test_url_to_file_path_ext_non_file_scheme() {
3423 use super::UrlExt;
3424
3425 let url = url::Url::parse("http://example.com/path").unwrap();
3426 assert_eq!(url.to_file_path_ext(PathStyle::Unix), Err(()));
3427 assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3428
3429 let url = url::Url::parse("https://example.com/path").unwrap();
3430 assert_eq!(url.to_file_path_ext(PathStyle::Unix), Err(()));
3431 assert_eq!(url.to_file_path_ext(PathStyle::Windows), Err(()));
3432 }
3433
3434 #[test]
3435 fn test_url_to_file_path_ext_windows_localhost() {
3436 use super::UrlExt;
3437
3438 let url = url::Url::parse("file://localhost/C:/Users/file.txt").unwrap();
3439 assert_eq!(
3440 url.to_file_path_ext(PathStyle::Windows),
3441 Ok(PathBuf::from("C:\\Users\\file.txt"))
3442 );
3443 }
3444}