Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

path: Reimplement `PathStyle::strip_prefix` based on std lib's implementation (#65503)

Xin Zhaof929b3f7ce00
diff --git a/Cargo.lock b/Cargo.lock
index 2d7a5aa9e1a..39b99bf26e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12554,7 +12554,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"dunce",
- "pretty_assertions",
"serde",
"tempfile",
"tendril",
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index 42026eda297..b0042fbdf95 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -3848,6 +3848,8 @@ pub fn skill_body_resolver_for_project(
worktree
.path_style()
.strip_prefix(&skill.skill_file_path, &worktree_root)
+ .ok()
+ .and_then(|path| RelPath::new(path, worktree.path_style()).ok())
.map(|relative_path| relative_path.into_arc())
.context("skill file is not inside its worktree")
})?;
diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs
index c1feb42d20c..253075d5bdc 100644
--- a/crates/agent/src/tools/terminal_tool.rs
+++ b/crates/agent/src/tools/terminal_tool.rs
@@ -1402,13 +1402,11 @@ fn resolve_cd_in_worktrees(
} else {
(*root_name).to_string()
};
- let subpath = path_style.strip_prefix(cd_path, Path::new(&prefix))?;
+ let subpath = path_style.strip_prefix(cd_path, Path::new(&prefix)).ok()?;
if subpath.is_empty() {
Some(abs_path.clone())
} else {
- path_style
- .join_path(abs_path, &*subpath.display(path_style))
- .ok()
+ path_style.join_path(abs_path, subpath).ok()
}
})
}
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 0bbabd69e39..3f8a0102b35 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -772,8 +772,9 @@ fn mention_path_for_terminal(
match (abs_path, working_directory) {
(Some(abs_path), Some(working_directory)) => path_style
.strip_prefix(&abs_path, working_directory)
- .map(|relative| relative.display(path_style).into_owned())
- .unwrap_or_else(|| abs_path.to_string_lossy().into_owned()),
+ .unwrap_or(&abs_path)
+ .to_string_lossy()
+ .into_owned(),
(Some(abs_path), None) => abs_path.to_string_lossy().into_owned(),
(None, _) => project_path.path.display(path_style).into_owned(),
}
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index a358a33884b..ee908087699 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -3915,6 +3915,8 @@ impl AgentCodeSpanResolver {
let relative_path: Option<Arc<RelPath>> = if path_style.is_absolute(path) {
path_style
.strip_prefix(path, worktree_abs_path)
+ .ok()
+ .and_then(|path| RelPath::new(path, path_style).ok())
.map(std::borrow::Cow::into_owned)
.map(Into::into)
} else {
diff --git a/crates/path/Cargo.toml b/crates/path/Cargo.toml
index 086d9d2159e..99f980aaa60 100644
--- a/crates/path/Cargo.toml
+++ b/crates/path/Cargo.toml
@@ -22,7 +22,6 @@ tendril.workspace = true
[dev-dependencies]
tempfile.workspace = true
-pretty_assertions.workspace = true
[lints]
workspace = true
diff --git a/crates/path/src/path.rs b/crates/path/src/path.rs
index ed911151710..58381bcdd9b 100644
--- a/crates/path/src/path.rs
+++ b/crates/path/src/path.rs
@@ -11,7 +11,6 @@ use anyhow::Context;
#[cfg(all(unix, not(target_family = "wasm")))]
use std::os::unix::prelude::OsStrExt;
use std::{
- borrow::Cow,
ffi::OsStr,
path::{Path, PathBuf},
};
@@ -19,7 +18,7 @@ use std::{
use tendril::fmt::{Format, WTF8};
use crate::path_component::{Component, Components, Prefix, PrefixExt, iter_after};
-use crate::rel_path::RelPath;
+use crate::rel_path::{RelPath, StripPrefixError};
pub mod abs_path;
mod path_component;
@@ -322,41 +321,15 @@ impl PathStyle {
pub fn strip_prefix<'a>(
&self,
- child: &'a Path,
- parent: &'a Path,
- ) -> Option<std::borrow::Cow<'a, RelPath>> {
- let parent = parent.to_str()?;
- if parent.is_empty() {
- return RelPath::new(child, *self).ok();
- }
- let parent = self
- .separators()
- .iter()
- .find_map(|sep| parent.strip_suffix(sep))
- .unwrap_or(parent);
- let child = child.to_str()?;
-
- // Match behavior of std::path::Path, which is case-insensitive for drive letters (e.g., "C:" == "c:")
- let stripped = if self.is_windows()
- && child.as_bytes().get(1) == Some(&b':')
- && parent.as_bytes().get(1) == Some(&b':')
- && child.as_bytes()[0].eq_ignore_ascii_case(&parent.as_bytes()[0])
- {
- child[2..].strip_prefix(&parent[2..])?
- } else {
- child.strip_prefix(parent)?
- };
- if let Some(relative) = self
- .separators()
- .iter()
- .find_map(|sep| stripped.strip_prefix(sep))
- {
- RelPath::new(relative.as_ref(), *self).ok()
- } else if stripped.is_empty() {
- Some(Cow::Borrowed(RelPath::empty()))
- } else {
- None
- }
+ path: &'a (impl AsRef<Path> + ?Sized),
+ prefix: impl AsRef<Path>,
+ ) -> Result<&'a Path, StripPrefixError> {
+ iter_after(
+ self.components(path.as_ref()),
+ self.components(prefix.as_ref()),
+ )
+ .map(|c| c.as_path())
+ .ok_or(StripPrefixError)
}
}
@@ -438,7 +411,6 @@ pub fn normalize_path(path: &Path) -> PathBuf {
#[cfg(test)]
mod tests {
use super::*;
- use crate::rel_path::rel_path;
#[test]
fn test_join_path_uses_path_style_separator() {
@@ -533,161 +505,127 @@ mod tests {
}
#[test]
- fn test_strip_prefix() {
- let expected = [
- (
- PathStyle::Unix,
- "/a/b/c",
- "/a/b",
- Some(rel_path("c").into_arc()),
- ),
- (
- PathStyle::Unix,
- "/a/b/c",
- "/a/b/",
- Some(rel_path("c").into_arc()),
- ),
- (
- PathStyle::Unix,
- "/a/b/c",
- "/",
- Some(rel_path("a/b/c").into_arc()),
- ),
- (PathStyle::Unix, "/a/b/c", "", None),
- (PathStyle::Unix, "/a/b//c", "/a/b/", None),
- (PathStyle::Unix, "/a/bc", "/a/b", None),
- (
- PathStyle::Unix,
- "/a/b/c",
- "/a/b/c",
- Some(rel_path("").into_arc()),
- ),
- (
- PathStyle::Windows,
- "C:\\a\\b\\c",
- "C:\\a\\b",
- Some(rel_path("c").into_arc()),
- ),
- (
- PathStyle::Windows,
- "C:\\a\\b\\c",
- "C:\\a\\b\\",
- Some(rel_path("c").into_arc()),
- ),
- (
- PathStyle::Windows,
- "C:\\a\\b\\c",
- "C:\\",
- Some(rel_path("a/b/c").into_arc()),
- ),
- (PathStyle::Windows, "C:\\a\\b\\c", "", None),
- (PathStyle::Windows, "C:\\a\\b\\\\c", "C:\\a\\b\\", None),
- (PathStyle::Windows, "C:\\a\\bc", "C:\\a\\b", None),
- (
- PathStyle::Windows,
- "C:\\a\\b/c",
- "C:\\a\\b",
- Some(rel_path("c").into_arc()),
- ),
- (
- PathStyle::Windows,
- "C:\\a\\b/c",
- "C:\\a\\b\\",
- Some(rel_path("c").into_arc()),
- ),
- (
- PathStyle::Windows,
- "C:\\a\\b/c",
- "C:\\a\\b/",
- Some(rel_path("c").into_arc()),
- ),
- ];
- let actual = expected.clone().map(|(style, child, parent, _)| {
- (
- style,
- child,
- parent,
- style
- .strip_prefix(child.as_ref(), parent.as_ref())
- .map(|rel_path| rel_path.into_arc()),
- )
- });
- pretty_assertions::assert_eq!(actual, expected);
- }
-
- #[test]
- fn test_unix_path_style_starts_with() {
+ fn test_unix_path_style_starts_with_and_strip_prefix() {
let unix_paths_and_prefixes = [
- ("", "", true),
- ("foo", "", true),
- ("", "foo", false),
- ("foo", "foo", true),
- ("foo/", "foo", true),
- ("foo//", "foo", true),
- ("foo///", "foo", true),
- ("foo/.", "foo", true),
- ("foo/./bar", "foo/bar", true),
- ("foo/.//bar", "foo/bar", true),
- ("foo//./bar", "foo/bar", true),
- ("foo/bar", "foo", true),
- ("foo/bar", "foobar", false),
- ("foo/bar/baz", "foo/bar", true),
- ("foo/bar", "foo/bar/baz", false),
- ("./foo/bar/", ".", true),
- ("/etc/passwd", "/etc", true),
- ("/etc/passwd", "/etc/", true),
- ("/etc/passwd", "/etc/passwd", true),
- ("/etc/passwd", "/etc/passwd/", true),
- ("/etc/passwd", "/etc/passwd///", true),
- ("/etc/passwd", "/e", false),
- ("/etc/passwd", "/etc/passwd.txt", false),
- ("/etc/foo.rs", "/etc/foo", false),
+ ("", "", true, Some("")),
+ ("foo", "", true, Some("foo")),
+ ("", "foo", false, None),
+ ("foo", "foo", true, Some("")),
+ ("foo/", "foo", true, Some("")),
+ ("foo//", "foo", true, Some("")),
+ ("foo///", "foo", true, Some("")),
+ ("foo/.", "foo", true, Some("")),
+ ("foo/./bar", "foo/bar", true, Some("")),
+ ("foo/.//bar", "foo/bar", true, Some("")),
+ ("foo//./bar", "foo/bar", true, Some("")),
+ ("foo/bar", "foo", true, Some("bar")),
+ ("foo/bar", "foobar", false, None),
+ ("foo/bar/baz", "foo/bar", true, Some("baz")),
+ ("foo/bar", "foo/bar/baz", false, None),
+ ("./foo/bar/", ".", true, Some("foo/bar")),
+ ("/etc/passwd", "/etc", true, Some("passwd")),
+ ("/etc/passwd", "/etc/", true, Some("passwd")),
+ ("/etc/passwd", "/etc/passwd", true, Some("")),
+ ("/etc/passwd", "/etc/passwd/", true, Some("")),
+ ("/etc/passwd", "/etc/passwd///", true, Some("")),
+ ("/etc/passwd", "/e", false, None),
+ ("/etc/passwd", "/etc/passwd.txt", false, None),
+ ("/etc/foo.rs", "/etc/foo", false, None),
+ ("/foo/bar/baz", "/", true, Some("foo/bar/baz")),
+ ("/foo/bar/baz", "", true, Some("/foo/bar/baz")),
+ ("/foo/bar//baz", "/foo/bar/", true, Some("baz")),
+ ("/foo/barbaz", "/foo/bar", false, None),
];
- for (path, prefix, expected) in unix_paths_and_prefixes {
+ for (path, prefix, expected_starts_with, expected_stripped) in unix_paths_and_prefixes {
assert_eq!(
PathStyle::Unix.starts_with(Path::new(path), Path::new(prefix)),
- expected,
+ expected_starts_with,
"{path:?}.starts_with({prefix:?})"
);
+ assert_eq!(
+ PathStyle::Unix
+ .strip_prefix(Path::new(path), Path::new(prefix))
+ .ok(),
+ expected_stripped.map(Path::new),
+ "{path:?}.strip_prefix({prefix:?})"
+ );
}
}
#[test]
- fn test_windows_path_style_starts_with() {
+ fn test_windows_path_style_starts_with_and_strip_prefix() {
let windows_paths_and_prefixes = [
(
r"C:\src\rust\cargo-test\test\Cargo.toml",
r"c:\src\rust\cargo-test\test",
true,
+ Some("Cargo.toml"),
),
- (r"C:\foo\.\bar.txt", r"C:\foo\bar.txt", true),
- (r"C:\foo\.", r"C:\foo", true),
- (r"\\server\share", r"\\server", false),
- (r"\\server\share\foo.txt", r"\\server", false),
- (r"\\server\share\foo.txt", r"\\server\share", true),
- (r"\\server\share\foo.txt", r"\\server\share\", true),
- (r"\\server\share\foo.txt", r"\\server\share/", true),
- (r"\\server\share\foo.txt", r"\\server\other", false),
- (r"\\server\share\foo.txt", r"\\SERVER\share", false),
- (r"\\?\C:\foo\.\bar.txt", r"\\?\C:\foo\bar.txt", false),
- (r"\\?\C:\foo.txt", r"\\?\C:\", true),
+ (r"C:\foo\.\bar.txt", r"C:\foo\bar.txt", true, Some("")),
+ (r"C:\foo\.", r"C:\foo", true, Some("")),
+ (r"\\server\share", r"\\server", false, None),
+ (r"\\server\share\foo.txt", r"\\server", false, None),
+ (
+ r"\\server\share\foo.txt",
+ r"\\server\share",
+ true,
+ Some("foo.txt"),
+ ),
+ (
+ r"\\server\share\foo.txt",
+ r"\\server\share\",
+ true,
+ Some("foo.txt"),
+ ),
+ (
+ r"\\server\share\foo.txt",
+ r"\\server\share/",
+ true,
+ Some("foo.txt"),
+ ),
+ (r"\\server\share\foo.txt", r"\\server\other", false, None),
+ (r"\\server\share\foo.txt", r"\\SERVER\share", false, None),
+ (r"\\?\C:\foo\.\bar.txt", r"\\?\C:\foo\bar.txt", false, None),
+ (r"\\?\C:\foo.txt", r"\\?\C:\", true, Some("foo.txt")),
(
r"\\?\UNC\server\share\foo.txt",
r"\\?\UNC\server\share",
true,
+ Some(r"\foo.txt"),
+ ),
+ (
+ r"\\?\UNC\server\share\foo.txt",
+ r"\\?\UNC\server\",
+ false,
+ None,
),
- (r"\\?\UNC\server\share\foo.txt", r"\\?\UNC\server\", false),
- (r"\\?\bar\foo.txt", r"\\?\bar", true),
- (r"\\?\C:\foo/bar.txt", r"\\?\C:\foo", false),
+ (r"\\?\bar\foo.txt", r"\\?\bar", true, Some(r"\foo.txt")),
+ (r"\\?\C:\foo/bar.txt", r"\\?\C:\foo", false, None),
+ (r"C:\foo\bar.txt", r"C:\foo", true, Some("bar.txt")),
+ (r"C:\foo\bar.txt", r"C:\foo\", true, Some("bar.txt")),
+ (r"C:\foo\bar.txt", r"C:\", true, Some(r"foo\bar.txt")),
+ (r"C:\foo\bar.txt", "", true, Some(r"C:\foo\bar.txt")),
+ (r"C:\foo\\bar.txt", r"C:\foo\", true, Some("bar.txt")),
+ (r"C:\foobar.txt", r"C:\foo", false, None),
+ (r"C:\foo/bar.txt", r"C:\foo", true, Some("bar.txt")),
+ (r"C:\foo/bar.txt", r"C:\foo\", true, Some("bar.txt")),
+ (r"C:\foo/bar.txt", r"C:\foo/", true, Some("bar.txt")),
];
- for (path, prefix, expected) in windows_paths_and_prefixes {
+ for (path, prefix, expected_starts_with, expected_stripped) in windows_paths_and_prefixes {
assert_eq!(
PathStyle::Windows.starts_with(Path::new(path), Path::new(prefix)),
- expected,
+ expected_starts_with,
"{path:?}.starts_with({prefix:?})"
);
+ assert_eq!(
+ PathStyle::Windows
+ .strip_prefix(Path::new(path), Path::new(prefix))
+ .ok(),
+ expected_stripped.map(Path::new),
+ "{path:?}.strip_prefix({prefix:?})"
+ );
}
}
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index 8144876b73b..33e4dce4087 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -6410,7 +6410,10 @@ impl RepositorySnapshot {
abs_path: &Path,
path_style: PathStyle,
) -> Option<RepoPath> {
- let rel_path = path_style.strip_prefix(abs_path, work_directory_abs_path)?;
+ let rel_path = path_style
+ .strip_prefix(abs_path, work_directory_abs_path)
+ .ok()
+ .and_then(|path| RelPath::new(path, path_style).ok())?;
Some(RepoPath::from_rel_path(&rel_path))
}
diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs
index 7f1f6f439da..fcbe245710a 100644
--- a/crates/project/src/project.rs
+++ b/crates/project/src/project.rs
@@ -2583,7 +2583,10 @@ impl Project {
.filter_map(|worktree| {
let worktree = worktree.read(cx);
let abs_path = worktree.abs_path();
- let relative_path = path_style.strip_prefix(path, abs_path.as_ref())?;
+ let relative_path = path_style
+ .strip_prefix(path, abs_path.as_ref())
+ .ok()
+ .and_then(|path| RelPath::new(path, path_style).ok())?;
// Don't exclude the worktree root itself, only actual subdirectories
let is_subpath = !relative_path.is_empty();
// Gitignored subtrees aren't scanned, so their contents don't
@@ -2617,7 +2620,10 @@ impl Project {
.filter_map(|worktree| {
let worktree = worktree.read(cx);
let abs_path = worktree.abs_path();
- let relative_path = path_style.strip_prefix(path, abs_path.as_ref())?;
+ let relative_path = path_style
+ .strip_prefix(path, abs_path.as_ref())
+ .ok()
+ .and_then(|path| RelPath::new(path, path_style).ok())?;
let is_subpath =
!relative_path.is_empty() && !worktree.is_path_ignored(&relative_path);
is_subpath.then(|| worktree.is_visible())
diff --git a/crates/project/src/worktree_store.rs b/crates/project/src/worktree_store.rs
index 300d9cf4486..82220ea5acf 100644
--- a/crates/project/src/worktree_store.rs
+++ b/crates/project/src/worktree_store.rs
@@ -468,8 +468,10 @@ impl WorktreeStore {
let abs_path = SanitizedPath::new(abs_path.as_ref());
for tree in self.worktrees() {
let path_style = tree.read(cx).path_style();
- if let Some(relative_path) =
- path_style.strip_prefix(abs_path.as_ref(), tree.read(cx).abs_path().as_ref())
+ if let Some(relative_path) = path_style
+ .strip_prefix(abs_path.as_ref(), tree.read(cx).abs_path().as_ref())
+ .ok()
+ .and_then(|path| RelPath::new(path, path_style).ok())
{
return Some((tree.clone(), relative_path.into_arc()));
}
diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs
index 866fe62c5a8..d1dc10081ab 100644
--- a/crates/workspace/src/workspace.rs
+++ b/crates/workspace/src/workspace.rs
@@ -10934,6 +10934,8 @@ pub async fn find_existing_workspace(
let abs_path = worktree.abs_path();
path_style
.strip_prefix(path.as_ref(), abs_path.as_ref())
+ .ok()
+ .and_then(|path| RelPath::new(path, path_style).ok())
.and_then(|rel| worktree.entry_for_path(&rel))
.is_some_and(|e| e.is_dir())
})