Represent relative paths using a dedicated, separator-agnostic type (#38744)

Closes https://github.com/zed-industries/zed/issues/38690
Closes #37353

### Background

On Windows, paths are normally separated by `\`, unlike mac and linux
where they are separated by `/`. When editing code in a project that
uses a different path style than your local system (e.g. remoting from
Windows to Linux, using WSL, and collaboration between windows and unix
users), the correct separator for a path may differ from the "native"
separator.

Previously, to work around this, Zed converted paths' separators in
numerous places. This was applied to both absolute and relative paths,
leading to incorrect conversions in some cases.

### Solution

Many code paths in Zed use paths that are *relative* to either a
worktree root or a git repository. This PR introduces a dedicated type
for these paths called `RelPath`, which stores the path in the same way
regardless of host platform, and offers `Path`-like manipulation APIs.
RelPath supports *displaying* the path using either separator, so that
we can display paths in a style that is determined at runtime based on
the current project.

The representation of absolute paths is left untouched, for now.
Absolute paths are different from relative paths because (except in
contexts where we know that the path refers to the local filesystem)
they should generally be treated as opaque strings. Currently we use a
mix of types for these paths (std::path::Path, String, SanitizedPath).

Release Notes:

- N/A

---------

Co-authored-by: Cole Miller <cole@zed.dev>
Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
Co-authored-by: Peter Tripp <petertripp@gmail.com>
Co-authored-by: Smit Barmase <heysmitbarmase@gmail.com>
Co-authored-by: Lukas Wirth <me@lukaswirth.dev>
This commit is contained in:
Max Brunsfeld
2025-09-24 18:57:33 -04:00
committed by GitHub
co-authored by Cole Miller Piotr Osiewicz Peter Tripp Smit Barmase Lukas Wirth
parent 3c626f3758
commit 03f9cf4414
216 changed files with 5873 additions and 5257 deletions
+22 -80
View File
@@ -1,5 +1,5 @@
use std::{
borrow::{Borrow, Cow},
borrow::Borrow,
collections::BTreeMap,
sync::atomic::{self, AtomicBool},
};
@@ -27,7 +27,7 @@ pub struct Matcher<'a> {
pub trait MatchCandidate {
fn has_chars(&self, bag: CharBag) -> bool;
fn to_string(&self) -> Cow<'_, str>;
fn candidate_chars(&self) -> impl Iterator<Item = char>;
}
impl<'a> Matcher<'a> {
@@ -83,7 +83,7 @@ impl<'a> Matcher<'a> {
candidate_chars.clear();
lowercase_candidate_chars.clear();
extra_lowercase_chars.clear();
for (i, c) in candidate.borrow().to_string().chars().enumerate() {
for (i, c) in candidate.borrow().candidate_chars().enumerate() {
candidate_chars.push(c);
let mut char_lowercased = c.to_lowercase().collect::<Vec<_>>();
if char_lowercased.len() > 1 {
@@ -202,8 +202,6 @@ impl<'a> Matcher<'a> {
cur_score: f64,
extra_lowercase_chars: &BTreeMap<usize, usize>,
) -> f64 {
use std::path::MAIN_SEPARATOR;
if query_idx == self.query.len() {
return 1.0;
}
@@ -245,17 +243,11 @@ impl<'a> Matcher<'a> {
None => continue,
}
};
let is_path_sep = path_char == MAIN_SEPARATOR;
let is_path_sep = path_char == '/';
if query_idx == 0 && is_path_sep {
last_slash = j_regular;
}
#[cfg(not(target_os = "windows"))]
let need_to_score =
query_char == path_char || (is_path_sep && query_char == '_' || query_char == '\\');
// `query_char == '\\'` breaks `test_match_path_entries` on Windows, `\` is only used as a path separator on Windows.
#[cfg(target_os = "windows")]
let need_to_score = query_char == path_char || (is_path_sep && query_char == '_');
if need_to_score {
let curr = match prefix.get(j_regular) {
@@ -270,7 +262,7 @@ impl<'a> Matcher<'a> {
None => path[j_regular - 1 - prefix.len()],
};
if last == MAIN_SEPARATOR {
if last == '/' {
char_score = 0.9;
} else if (last == '-' || last == '_' || last == ' ' || last.is_numeric())
|| (last.is_lowercase() && curr.is_uppercase())
@@ -291,7 +283,7 @@ impl<'a> Matcher<'a> {
// Apply a severe penalty if the case doesn't match.
// This will make the exact matches have higher score than the case-insensitive and the
// path insensitive matches.
if (self.smart_case || curr == MAIN_SEPARATOR) && self.query[query_idx] != curr {
if (self.smart_case || curr == '/') && self.query[query_idx] != curr {
char_score *= 0.001;
}
@@ -348,13 +340,12 @@ impl<'a> Matcher<'a> {
#[cfg(test)]
mod tests {
use util::rel_path::{RelPath, rel_path};
use crate::{PathMatch, PathMatchCandidate};
use super::*;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use std::sync::Arc;
#[test]
fn test_get_last_positions() {
@@ -376,7 +367,6 @@ mod tests {
assert_eq!(matcher.last_positions, vec![0, 3, 4, 8]);
}
#[cfg(not(target_os = "windows"))]
#[test]
fn test_match_path_entries() {
let paths = vec![
@@ -388,9 +378,9 @@ mod tests {
"alphabravocharlie",
"AlphaBravoCharlie",
"thisisatestdir",
"/////ThisIsATestDir",
"/this/is/a/test/dir",
"/test/tiatd",
"ThisIsATestDir",
"this/is/a/test/dir",
"test/tiatd",
];
assert_eq!(
@@ -404,63 +394,15 @@ mod tests {
);
assert_eq!(
match_single_path_query("t/i/a/t/d", false, &paths),
vec![("/this/is/a/test/dir", vec![1, 5, 6, 8, 9, 10, 11, 15, 16]),]
vec![("this/is/a/test/dir", vec![0, 4, 5, 7, 8, 9, 10, 14, 15]),]
);
assert_eq!(
match_single_path_query("tiatd", false, &paths),
vec![
("/test/tiatd", vec![6, 7, 8, 9, 10]),
("/this/is/a/test/dir", vec![1, 6, 9, 11, 16]),
("/////ThisIsATestDir", vec![5, 9, 11, 12, 16]),
("thisisatestdir", vec![0, 2, 6, 7, 11]),
]
);
}
/// todo(windows)
/// Now, on Windows, users can only use the backslash as a path separator.
/// I do want to support both the backslash and the forward slash as path separators on Windows.
#[cfg(target_os = "windows")]
#[test]
fn test_match_path_entries() {
let paths = vec![
"",
"a",
"ab",
"abC",
"abcd",
"alphabravocharlie",
"AlphaBravoCharlie",
"thisisatestdir",
"\\\\\\\\\\ThisIsATestDir",
"\\this\\is\\a\\test\\dir",
"\\test\\tiatd",
];
assert_eq!(
match_single_path_query("abc", false, &paths),
vec![
("abC", vec![0, 1, 2]),
("abcd", vec![0, 1, 2]),
("AlphaBravoCharlie", vec![0, 5, 10]),
("alphabravocharlie", vec![4, 5, 10]),
]
);
assert_eq!(
match_single_path_query("t\\i\\a\\t\\d", false, &paths),
vec![(
"\\this\\is\\a\\test\\dir",
vec![1, 5, 6, 8, 9, 10, 11, 15, 16]
),]
);
assert_eq!(
match_single_path_query("tiatd", false, &paths),
vec![
("\\test\\tiatd", vec![6, 7, 8, 9, 10]),
("\\this\\is\\a\\test\\dir", vec![1, 6, 9, 11, 16]),
("\\\\\\\\\\ThisIsATestDir", vec![5, 9, 11, 12, 16]),
("test/tiatd", vec![5, 6, 7, 8, 9]),
("ThisIsATestDir", vec![0, 4, 6, 7, 11]),
("this/is/a/test/dir", vec![0, 5, 8, 10, 15]),
("thisisatestdir", vec![0, 2, 6, 7, 11]),
]
);
@@ -491,7 +433,7 @@ mod tests {
"aαbβ/cγdδ",
"αβγδ/bcde",
"c1️⃣2️⃣3️⃣/d4️⃣5️⃣6️⃣/e7️⃣8️⃣9️⃣/f",
"/d/🆒/h",
"d/🆒/h",
];
assert_eq!("1️⃣".len(), 7);
assert_eq!(
@@ -602,9 +544,9 @@ mod tests {
let query = query.chars().collect::<Vec<_>>();
let query_chars = CharBag::from(&lowercase_query[..]);
let path_arcs: Vec<Arc<Path>> = paths
let path_arcs: Vec<Arc<RelPath>> = paths
.iter()
.map(|path| Arc::from(PathBuf::from(path)))
.map(|path| Arc::from(rel_path(path)))
.collect::<Vec<_>>();
let mut path_entries = Vec::new();
for (i, path) in paths.iter().enumerate() {
@@ -632,8 +574,8 @@ mod tests {
score,
worktree_id: 0,
positions: positions.clone(),
path: Arc::from(candidate.path),
path_prefix: "".into(),
path: candidate.path.into(),
path_prefix: RelPath::empty().into(),
distance_to_relative_ancestor: usize::MAX,
is_dir: false,
},
@@ -647,7 +589,7 @@ mod tests {
paths
.iter()
.copied()
.find(|p| result.path.as_ref() == Path::new(p))
.find(|p| result.path.as_ref() == rel_path(p))
.unwrap(),
result.positions,
)
+39 -19
View File
@@ -1,13 +1,12 @@
use gpui::BackgroundExecutor;
use std::{
borrow::Cow,
cmp::{self, Ordering},
path::Path,
sync::{
Arc,
atomic::{self, AtomicBool},
},
};
use util::{paths::PathStyle, rel_path::RelPath};
use crate::{
CharBag,
@@ -17,7 +16,7 @@ use crate::{
#[derive(Clone, Debug)]
pub struct PathMatchCandidate<'a> {
pub is_dir: bool,
pub path: &'a Path,
pub path: &'a RelPath,
pub char_bag: CharBag,
}
@@ -26,8 +25,8 @@ pub struct PathMatch {
pub score: f64,
pub positions: Vec<usize>,
pub worktree_id: usize,
pub path: Arc<Path>,
pub path_prefix: Arc<str>,
pub path: Arc<RelPath>,
pub path_prefix: Arc<RelPath>,
pub is_dir: bool,
/// Number of steps removed from a shared parent with the relative path
/// Used to order closer paths first in the search list
@@ -41,8 +40,10 @@ pub trait PathMatchCandidateSet<'a>: Send + Sync {
fn is_empty(&self) -> bool {
self.len() == 0
}
fn prefix(&self) -> Arc<str>;
fn root_is_file(&self) -> bool;
fn prefix(&self) -> Arc<RelPath>;
fn candidates(&'a self, start: usize) -> Self::Candidates;
fn path_style(&self) -> PathStyle;
}
impl<'a> MatchCandidate for PathMatchCandidate<'a> {
@@ -50,8 +51,8 @@ impl<'a> MatchCandidate for PathMatchCandidate<'a> {
self.char_bag.is_superset(bag)
}
fn to_string(&self) -> Cow<'a, str> {
self.path.to_string_lossy()
fn candidate_chars(&self) -> impl Iterator<Item = char> {
self.path.as_str().chars()
}
}
@@ -109,8 +110,8 @@ pub fn match_fixed_path_set(
worktree_id,
positions: positions.clone(),
is_dir: candidate.is_dir,
path: Arc::from(candidate.path),
path_prefix: Arc::default(),
path: candidate.path.into(),
path_prefix: RelPath::empty().into(),
distance_to_relative_ancestor: usize::MAX,
},
);
@@ -121,7 +122,7 @@ pub fn match_fixed_path_set(
pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
candidate_sets: &'a [Set],
query: &str,
relative_to: &Option<Arc<Path>>,
relative_to: &Option<Arc<RelPath>>,
smart_case: bool,
max_results: usize,
cancel_flag: &AtomicBool,
@@ -132,12 +133,27 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
return Vec::new();
}
let lowercase_query = query.to_lowercase().chars().collect::<Vec<_>>();
let query = query.chars().collect::<Vec<_>>();
let path_style = candidate_sets[0].path_style();
let query = query
.chars()
.map(|char| {
if path_style.is_windows() && char == '\\' {
'/'
} else {
char
}
})
.collect::<Vec<_>>();
let lowercase_query = query
.iter()
.map(|query| query.to_ascii_lowercase())
.collect::<Vec<_>>();
let lowercase_query = &lowercase_query;
let query = &query;
let query_char_bag = CharBag::from(&lowercase_query[..]);
let lowercase_query = &lowercase_query;
let query_char_bag = CharBag::from_iter(lowercase_query.iter().copied());
let num_cpus = executor.num_cpus().min(path_count);
let segment_size = path_count.div_ceil(num_cpus);
@@ -168,7 +184,11 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
let candidates = candidate_set.candidates(start).take(end - start);
let worktree_id = candidate_set.id();
let prefix = candidate_set.prefix().chars().collect::<Vec<_>>();
let mut prefix =
candidate_set.prefix().as_str().chars().collect::<Vec<_>>();
if !candidate_set.root_is_file() && !prefix.is_empty() {
prefix.push('/');
}
let lowercase_prefix = prefix
.iter()
.map(|c| c.to_ascii_lowercase())
@@ -219,7 +239,7 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
/// Compute the distance from a given path to some other path
/// If there is no shared path, returns usize::MAX
fn distance_between_paths(path: &Path, relative_to: &Path) -> usize {
fn distance_between_paths(path: &RelPath, relative_to: &RelPath) -> usize {
let mut path_components = path.components();
let mut relative_components = relative_to.components();
@@ -234,12 +254,12 @@ fn distance_between_paths(path: &Path, relative_to: &Path) -> usize {
#[cfg(test)]
mod tests {
use std::path::Path;
use util::rel_path::RelPath;
use super::distance_between_paths;
#[test]
fn test_distance_between_paths_empty() {
distance_between_paths(Path::new(""), Path::new(""));
distance_between_paths(RelPath::empty(), RelPath::empty());
}
}
+4 -4
View File
@@ -4,7 +4,7 @@ use crate::{
};
use gpui::BackgroundExecutor;
use std::{
borrow::{Borrow, Cow},
borrow::Borrow,
cmp::{self, Ordering},
iter,
ops::Range,
@@ -28,13 +28,13 @@ impl StringMatchCandidate {
}
}
impl<'a> MatchCandidate for &'a StringMatchCandidate {
impl MatchCandidate for &StringMatchCandidate {
fn has_chars(&self, bag: CharBag) -> bool {
self.char_bag.is_superset(bag)
}
fn to_string(&self) -> Cow<'a, str> {
self.string.as_str().into()
fn candidate_chars(&self) -> impl Iterator<Item = char> {
self.string.chars()
}
}