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::join` based on the standard library's implementation (#65966)

Xin Zhao95218401529e
diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs
index c93f2b1f5ed..c3a48eb343c 100644
--- a/crates/agent/src/tools/terminal_tool.rs
+++ b/crates/agent/src/tools/terminal_tool.rs
@@ -1406,7 +1406,7 @@ fn resolve_cd_in_worktrees(
let resolved_path = if subpath.is_empty() {
abs_path.clone()
} else {
- path_style.join_path(&abs_path, subpath).ok()?
+ path_style.normalize_lexically(path_style.join(&abs_path, subpath))
};
if path_style.starts_with(&resolved_path, &abs_path) {
@@ -1420,11 +1420,10 @@ fn resolve_cd_in_worktrees(
#[cfg(test)]
mod tests {
use super::*;
+ use util::paths::PathStyle::{Unix, Windows};
#[test]
fn test_resolve_cd_uses_project_path_style() {
- use util::paths::PathStyle::{Unix, Windows};
-
// Deliberately ambiguous root names to stress test path resolution.
let unix_roots: Vec<(&str, PathBuf)> = vec![
("worktree", PathBuf::from("/a/worktree")),
@@ -1554,6 +1553,33 @@ mod tests {
);
}
+ #[test]
+ fn test_resolve_cd_rejects_traversal_with_empty_root_name() {
+ let unix_roots = vec![("", PathBuf::from("/tmp/example/root"))];
+ let windows_roots = vec![("", PathBuf::from("C:\\work\\worktree"))];
+
+ assert_eq!(
+ resolve_cd_in_worktrees("../outside", Unix, &unix_roots),
+ None,
+ "a relative `cd` that escapes the worktree is rejected"
+ );
+ assert_eq!(
+ resolve_cd_in_worktrees("..", Unix, &unix_roots),
+ None,
+ "a relative `cd` to the parent of the worktree is rejected"
+ );
+ assert_eq!(
+ resolve_cd_in_worktrees("..", Windows, &windows_roots),
+ None,
+ "a relative `cd` to the parent of the worktree is rejected"
+ );
+ assert_eq!(
+ resolve_cd_in_worktrees("..\\escape", Windows, &windows_roots),
+ None,
+ "a relative `cd` that escapes the worktree is rejected"
+ );
+ }
+
#[test]
fn test_initial_title_shows_full_multiline_command() {
let input = TerminalToolInput {
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 39be2672f2f..24be2377e8f 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -14035,7 +14035,7 @@ pub(crate) fn open_link(
.into_iter()
.flatten()
.filter_map(move |path| {
- path_style.join_path_preserving_components(root, path).ok()
+ (!path_style.has_root(path)).then(|| path_style.join(root, path))
})
})
.collect::<Vec<_>>()
diff --git a/crates/extension_host/src/extension_host.rs b/crates/extension_host/src/extension_host.rs
index 44d6e84d589..a59488ecb17 100644
--- a/crates/extension_host/src/extension_host.rs
+++ b/crates/extension_host/src/extension_host.rs
@@ -2269,6 +2269,12 @@ impl ExtensionStore {
) -> Result<()> {
static UPLOAD_NONCE: AtomicU64 = AtomicU64::new(0);
+ anyhow::ensure!(
+ !path_style.has_root(Path::new(&missing_extension.id)),
+ "extension id must not be rooted: {:?}",
+ missing_extension.id
+ );
+
if !already_prepared {
this.update(cx, |this, cx| {
this.prepare_remote_extension(
@@ -2293,11 +2299,8 @@ impl ExtensionStore {
let dest_dir = RemotePathBuf::new(
path_style
.join(remote_tmp_dir, &upload_name)
- .with_context(|| {
- format!(
- "failed to construct destination path: {remote_tmp_dir:?}, {upload_name:?}"
- )
- })?,
+ .to_string_lossy()
+ .into_owned(),
path_style,
);
log::info!(
diff --git a/crates/markdown_preview/src/markdown_preview_view.rs b/crates/markdown_preview/src/markdown_preview_view.rs
index 7c2ec3a20dc..867abac25b4 100644
--- a/crates/markdown_preview/src/markdown_preview_view.rs
+++ b/crates/markdown_preview/src/markdown_preview_view.rs
@@ -1580,11 +1580,16 @@ fn resolve_preview_image(
let path = if let (Some(stripped), Some(root)) = (workspace_relative_path, workspace_directory)
{
- client_path_style.join_path(root, stripped).ok()?
+ // A second leading separator leaves a rooted path, which would replace
+ // the workspace root when joined.
+ if client_path_style.has_root(Path::new(stripped)) {
+ return None;
+ }
+ client_path_style.normalize_lexically(client_path_style.join(root, stripped))
} else if client_path_style.has_root(Path::new(&decoded)) {
PathBuf::from(decoded)
} else {
- client_path_style.join_path(base_directory?, decoded).ok()?
+ client_path_style.normalize_lexically(client_path_style.join(base_directory?, decoded))
};
path.exists()
@@ -1616,8 +1621,7 @@ fn resolve_project_path_for_preview_image(
.into_owned()
} else {
let joined_path = path_style
- .join_path(source_directory.as_std_path(), decoded_path)
- .ok()?;
+ .normalize_lexically(path_style.join(source_directory.as_std_path(), decoded_path));
RelPath::new(&joined_path, path_style).ok()?.into_owned()
};
@@ -2590,6 +2594,21 @@ mod tests {
cx,
);
assert!(missing.is_none());
+
+ let outside_tree = TempTree::new(json!({ "outside.svg": "mock data" }));
+ let outside_image = outside_tree.path().join("outside.svg");
+ for workspace_root_prefix in ["/", "\\"] {
+ let outside_workspace = resolve_preview_image(
+ &format!("{workspace_root_prefix}{}", outside_image.display()),
+ Some(&base_directory),
+ Some(workspace_directory),
+ None,
+ None,
+ PathStyle::local(),
+ cx,
+ );
+ assert!(outside_workspace.is_none());
+ }
}
#[gpui::test]
diff --git a/crates/open_path_prompt/src/open_path_prompt.rs b/crates/open_path_prompt/src/open_path_prompt.rs
index ae043324bde..3a46504b74d 100644
--- a/crates/open_path_prompt/src/open_path_prompt.rs
+++ b/crates/open_path_prompt/src/open_path_prompt.rs
@@ -22,7 +22,7 @@ use std::{
use ui::{Context, LabelLike, ListItem, Window};
use ui::{HighlightedLabel, ListItemSpacing, prelude::*};
use util::{
- ResultExt, maybe,
+ maybe,
paths::{PathStyle, compare_paths},
};
use workspace::Workspace;
@@ -671,17 +671,10 @@ impl PickerDelegate for OpenPathDelegate {
if parent_path == &self.prompt_root && candidate.path.string.is_empty() {
PathBuf::from(&self.prompt_root)
} else {
- let Some(confirmed_path) = self
- .path_style
- .join_path_preserving_components(
- Path::new(self.lister.resolve_tilde(parent_path, cx).as_ref()),
- &candidate.path.string,
- )
- .log_err()
- else {
- return;
- };
- confirmed_path
+ self.path_style.normalize_separators(self.path_style.join(
+ Path::new(self.lister.resolve_tilde(parent_path, cx).as_ref()),
+ &candidate.path.string,
+ ))
};
if let Some(tx) = self.tx.take() {
tx.send(Some(vec![confirmed_path])).ok();
@@ -701,17 +694,8 @@ impl PickerDelegate for OpenPathDelegate {
if parent_path == &self.prompt_root && user_input.file.string.is_empty() {
PathBuf::from(&self.prompt_root)
} else {
- let Some(prompted_path) = self
- .path_style
- .join_path_preserving_components(
- Path::new(self.lister.resolve_tilde(parent_path, cx).as_ref()),
- &user_input.file.string,
- )
- .log_err()
- else {
- return;
- };
- prompted_path
+ let parent_path = self.lister.resolve_tilde(parent_path, cx);
+ PathBuf::from(format!("{parent_path}{}", user_input.file.string))
};
if user_input.exists {
self.should_dismiss = false;
diff --git a/crates/open_path_prompt/src/open_path_prompt_tests.rs b/crates/open_path_prompt/src/open_path_prompt_tests.rs
index 6254be253f8..26e7dc638a6 100644
--- a/crates/open_path_prompt/src/open_path_prompt_tests.rs
+++ b/crates/open_path_prompt/src/open_path_prompt_tests.rs
@@ -372,6 +372,44 @@ async fn test_new_path_prompt(cx: &mut TestAppContext) {
assert_eq!(collect_match_candidates(&picker, cx), vec!["dir1"]);
}
+#[gpui::test]
+async fn test_create_confirmation_keeps_the_checked_destination(cx: &mut TestAppContext) {
+ let app_state = init_test(cx);
+ app_state
+ .fs
+ .as_fake()
+ .insert_tree(path!("/root"), json!({}))
+ .await;
+
+ let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
+ let (picker, cx) = build_open_path_prompt(project, true, false, cx);
+ picker.update_in(cx, |picker, _, _| {
+ picker.delegate.path_style = util::paths::PathStyle::Windows;
+ });
+
+ for query in [
+ r"\\?\C:\root\victim.txt\.",
+ r"\\?\C:\root\dir\..",
+ r"\\?\C:\root\test/file",
+ r"\\?\C:\root\test/\file",
+ r"C:\base\C:victim.txt",
+ ] {
+ insert_query(query, &picker, cx).await;
+
+ let (tx, receiver) = futures::channel::oneshot::channel();
+ picker.update_in(cx, |picker, window, cx| {
+ picker.delegate.tx = Some(tx);
+ picker.delegate.confirm(false, window, cx);
+ });
+
+ assert_eq!(
+ receiver.await.unwrap(),
+ Some(vec![std::path::PathBuf::from(query)]),
+ "{query}"
+ );
+ }
+}
+
#[gpui::test]
async fn test_open_path_prompt_panics_with_stale_highlight_positions(cx: &mut TestAppContext) {
let app_state = init_test(cx);
diff --git a/crates/path/src/path.rs b/crates/path/src/path.rs
index b0fdba0327e..721952ef92e 100644
--- a/crates/path/src/path.rs
+++ b/crates/path/src/path.rs
@@ -18,7 +18,7 @@ use std::{
use tendril::fmt::{Format, WTF8};
use crate::path_component::{
- Component, Components, Prefix, PrefixExt, iter_after, rsplit_file_at_dot,
+ Component, Components, PathBufExt, Prefix, PrefixExt, iter_after, rsplit_file_at_dot,
};
use crate::rel_path::{RelPath, StripPrefixError};
@@ -123,63 +123,11 @@ impl PathStyle {
*self == PathStyle::Unix
}
- pub fn join(self, left: impl AsRef<Path>, right: impl AsRef<Path>) -> Option<String> {
- let right = right.as_ref();
- if self.has_root(right) {
- return None;
- }
- let right = right.to_str()?;
- let left = left.as_ref().to_str()?;
- if left.is_empty() {
- Some(right.into())
- } else {
- Some(format!(
- "{left}{}{right}",
- if left.ends_with(self.primary_separator()) {
- ""
- } else {
- self.primary_separator()
- }
- ))
- }
- }
+ pub fn join(self, left: impl AsRef<Path>, right: impl AsRef<Path>) -> PathBuf {
+ let mut buf = left.as_ref().to_path_buf();
+ buf.styled_push(right.as_ref(), self);
- pub fn join_path(
- self,
- left: impl AsRef<Path>,
- right: impl AsRef<Path>,
- ) -> anyhow::Result<PathBuf> {
- let left = left
- .as_ref()
- .to_str()
- .ok_or_else(|| anyhow::anyhow!("Path contains invalid UTF-8"))?;
- let right = self.normalize_separators(right);
- let right_string = right
- .to_str()
- .ok_or_else(|| anyhow::anyhow!("Path contains invalid UTF-8"))?;
- let joined = self
- .join(left, right_string)
- .ok_or_else(|| anyhow::anyhow!("Path must be relative: {right:?}"))?;
- Ok(self.normalize_lexically(&joined))
- }
-
- pub fn join_path_preserving_components(
- self,
- left: impl AsRef<Path>,
- right: impl AsRef<Path>,
- ) -> anyhow::Result<PathBuf> {
- let left = left
- .as_ref()
- .to_str()
- .ok_or_else(|| anyhow::anyhow!("Path contains invalid UTF-8"))?;
- let right = right.as_ref();
- let right_string = right
- .to_str()
- .ok_or_else(|| anyhow::anyhow!("Path contains invalid UTF-8"))?;
- let joined = self
- .join(left, right_string)
- .ok_or_else(|| anyhow::anyhow!("Path must be relative: {right:?}"))?;
- Ok(PathBuf::from(&joined))
+ buf
}
pub fn normalize_separators(&self, path: impl AsRef<Path>) -> PathBuf {
@@ -350,35 +298,111 @@ mod tests {
use super::*;
#[test]
- fn test_join_path_uses_path_style_separator() {
- let posix_path = PathStyle::Unix
- .join_path(Path::new("/home/user/dev"), "worktrees")
- .unwrap();
- let windows_path = PathStyle::Windows
- .join_path(Path::new("C:\\Users\\user\\dev"), "worktrees")
- .unwrap();
-
- assert_eq!(posix_path, PathBuf::from("/home/user/dev/worktrees"));
- assert_eq!(
- windows_path.to_string_lossy(),
- "C:\\Users\\user\\dev\\worktrees"
- );
- }
+ fn test_join() {
+ let unix_paths_and_joined = [
+ ("", "foo", "foo"),
+ ("foo", "bar", "foo/bar"),
+ ("foo/", "bar", "foo/bar"),
+ ("foo//", "bar", "foo//bar"),
+ ("foo/.", "bar", "foo/./bar"),
+ ("foo./.", "bar", "foo././bar"),
+ ("foo", "", "foo/"),
+ ("foo", ".", "foo/."),
+ ("foo", "..", "foo/.."),
+ ("foo", "/", "/"),
+ ("/foo/bar", "/", "/"),
+ ("/foo/bar", "/baz", "/baz"),
+ ("/foo/bar", "./baz", "/foo/bar/./baz"),
+ ];
+ for (left, right, joined) in unix_paths_and_joined {
+ assert_eq!(
+ PathStyle::Unix.join(left, right).as_os_str(),
+ OsStr::new(joined),
+ "join({left:?}, {right:?})"
+ );
+ }
- #[test]
- fn test_join_path_preserving_components() {
- let posix_path = PathStyle::Unix
- .join_path_preserving_components(Path::new("/home/user/symlink"), "../worktrees")
- .unwrap();
- let windows_path = PathStyle::Windows
- .join_path_preserving_components(Path::new(r"C:\Users\user\symlink"), r"..\worktrees")
- .unwrap();
-
- assert_eq!(posix_path, PathBuf::from("/home/user/symlink/../worktrees"));
- assert_eq!(
- windows_path.to_string_lossy(),
- r"C:\Users\user\symlink\..\worktrees"
- );
+ let windows_paths_and_joined = [
+ ("", "foo", "foo"),
+ ("foo", "bar", r"foo\bar"),
+ ("foo/", "bar", r"foo/bar"),
+ (r"foo\", "bar", r"foo\bar"),
+ ("foo//", "bar", r"foo//bar"),
+ (r"foo\\", "bar", r"foo\\bar"),
+ ("foo/.", "bar", r"foo/.\bar"),
+ ("foo./.", "bar", r"foo./.\bar"),
+ (r"foo\.", "bar", r"foo\.\bar"),
+ (r"foo.\.", "bar", r"foo.\.\bar"),
+ ("foo", "", r"foo\"),
+ ("foo", ".", r"foo\."),
+ ("foo", "..", r"foo\.."),
+ ("foo", "/", "/"),
+ ("foo", r"\", r"\"),
+ ("/foo/bar", "/", "/"),
+ (r"\foo\bar", r"\", r"\"),
+ ("/foo/bar", "/baz", "/baz"),
+ ("/foo/bar", r"\baz", r"\baz"),
+ ("/foo/bar", "./baz", r"/foo/bar\./baz"),
+ ("/foo/bar", r".\baz", r"/foo/bar\.\baz"),
+ // a rooted `right` replaces everything in `left` after its prefix
+ (r"\foo", r"\bar", r"\bar"),
+ ("c:\\", "windows", "c:\\windows"),
+ ("c:", "windows", "c:windows"),
+ (r"a\b\c", "d", r"a\b\c\d"),
+ (r"\a\b\c", "d", r"\a\b\c\d"),
+ (r"a\b", r"c\d", r"a\b\c\d"),
+ (r"a\b", r"\c\d", r"\c\d"),
+ (r"a\b", ".", r"a\b\."),
+ (r"a\b", r"..\c", r"a\b\..\c"),
+ (r"a\b", "C:a.txt", "C:a.txt"),
+ (r"a\b", r"C:\a.txt", r"C:\a.txt"),
+ (r"C:\a", r"C:\b.txt", r"C:\b.txt"),
+ (r"C:\a\b\c", "C:d", "C:d"),
+ (r"C:a\b\c", "C:d", "C:d"),
+ ("C:", r"a\b\c", r"C:a\b\c"),
+ ("C:", r"..\a", r"C:..\a"),
+ // UNC
+ (r"\\server\share\foo", "bar", r"\\server\share\foo\bar"),
+ (r"\\server\share\foo", "C:baz", "C:baz"),
+ (r"\\server\share\foo", r"\bar", r"\\server\share\bar"),
+ // verbatim
+ (r"\\?\C:\a\b", r"C:c\d", r"C:c\d"),
+ (r"\\?\C:a\b", r"C:c\d", r"C:c\d"),
+ (r"\\?\C:\a\b", r"C:\c\d", r"C:\c\d"),
+ (r"\\?\foo\bar", "baz", r"\\?\foo\bar\baz"),
+ (
+ r"\\?\UNC\server\share\foo",
+ "bar",
+ r"\\?\UNC\server\share\foo\bar",
+ ),
+ (r"\\?\UNC\server\share", r"C:\a", r"C:\a"),
+ (r"\\?\UNC\server\share", "C:a", "C:a"),
+ (r"\\?\UNC\server", "foo", r"\\?\UNC\server\foo"),
+ (r"C:\a", r"\\?\UNC\server\share", r"\\?\UNC\server\share"),
+ (r"\\?\C:", "foo", r"\\?\C:\foo"),
+ (r"\\?\C:\bar", "../foo", r"\\?\C:\foo"),
+ (r"\\?\C:\bar", "../../foo", r"\\?\C:\foo"),
+ (r"\\?\C:\", "../foo", r"\\?\C:\foo"),
+ (r"\\?\C:", r"D:\foo/./", r"D:\foo/./"),
+ (r"\\?\C:", r"\\?\D:\foo\.\", r"\\?\D:\foo\.\"),
+ (r"\\?\A:\x\y", "/foo", r"\\?\A:\foo"),
+ (r"\\?\A:", r"..\foo\.", r"\\?\A:\foo"),
+ (r"\\?\A:\x\y", r".\foo\.", r"\\?\A:\x\y\foo"),
+ (r"\\?\A:\x\y", r"", r"\\?\A:\x\y\"),
+ (r"\\?\C:\foo", r"\bar", r"\\?\C:\bar"),
+ // device namespace
+ (r"\\.\foo\bar", "baz", r"\\.\foo\bar\baz"),
+ (r"\\.\foo\bar", "C:a", "C:a"),
+ (r"\\.\foo", r"..\bar", r"\\.\foo\..\bar"),
+ (r"\\.\device\foo", r"\bar", r"\\.\device\bar"),
+ ];
+ for (left, right, joined) in windows_paths_and_joined {
+ assert_eq!(
+ PathStyle::Windows.join(left, right).as_os_str(),
+ OsStr::new(joined),
+ "join({left:?}, {right:?})"
+ );
+ }
}
#[test]
diff --git a/crates/path/src/path_component.rs b/crates/path/src/path_component.rs
index c71d3bd2ea7..8c2a9fc1c6a 100644
--- a/crates/path/src/path_component.rs
+++ b/crates/path/src/path_component.rs
@@ -8,9 +8,9 @@
//! private inherent methods on `Prefix` live in the local [`PrefixExt`] trait.
use crate::PathStyle;
-use std::ffi::OsStr;
-use std::path::Path;
+use std::ffi::{OsStr, OsString};
pub use std::path::Prefix;
+use std::path::{Path, PathBuf};
pub(crate) trait PrefixExt {
fn len(&self) -> usize;
@@ -488,3 +488,90 @@ pub(crate) fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr
}
}
}
+
+pub(crate) trait PathBufExt {
+ fn styled_push(&mut self, path: impl AsRef<Path>, path_style: PathStyle);
+}
+
+impl PathBufExt for PathBuf {
+ fn styled_push(&mut self, path: impl AsRef<Path>, path_style: PathStyle) {
+ let path = path.as_ref();
+ // in general, a separator is needed if the rightmost byte is not a separator
+ let buf = self.as_os_str().as_encoded_bytes();
+ let mut need_sep = buf
+ .last()
+ .map(|c| !path_style.is_sep_byte(*c))
+ .unwrap_or(false);
+
+ // in the special case of `C:` on Windows, do *not* add a separator
+ let comps = path_style.components(self);
+
+ if comps.prefix_len() > 0
+ && comps.prefix_len() == comps.path.len()
+ && comps.prefix.is_some_and(|p| p.is_drive())
+ {
+ need_sep = false
+ }
+
+ let path_comps = path_style.components(path);
+
+ // absolute `path` replaces `self`
+ if path_style.is_absolute(path) || path_comps.prefix().is_some() {
+ self.clear();
+
+ // verbatim paths need . and .. removed
+ } else if comps.prefix_verbatim() && !path.is_empty() {
+ let mut buf: Vec<_> = comps.collect();
+ for c in path_comps {
+ match c {
+ Component::RootDir => {
+ buf.truncate(1);
+ buf.push(c);
+ }
+ Component::CurDir => (),
+ Component::ParentDir => {
+ if let Some(Component::Normal(_)) = buf.last() {
+ buf.pop();
+ }
+ }
+ _ => buf.push(c),
+ }
+ }
+
+ let mut res = OsString::new();
+ let mut need_sep = false;
+
+ for c in buf {
+ if need_sep && c != Component::RootDir {
+ res.push(path_style.primary_separator());
+ }
+ res.push(c.as_os_str(path_style));
+
+ need_sep = match c {
+ Component::RootDir => false,
+ Component::Prefix(prefix) => {
+ !prefix.parsed.is_drive() && prefix.parsed.len() > 0
+ }
+ _ => true,
+ }
+ }
+
+ *self.as_mut_os_string() = res;
+ return;
+
+ // `path` has a root but no prefix, e.g., `\windows` (Windows only)
+ } else if path_style.has_root(path) {
+ let prefix = match path_style.components(self).next() {
+ Some(Component::Prefix(prefix)) => prefix.raw.to_os_string(),
+ _ => OsString::new(),
+ };
+ *self.as_mut_os_string() = prefix;
+
+ // `path` is a pure relative path
+ } else if need_sep {
+ self.as_mut_os_string().push(path_style.primary_separator());
+ }
+
+ self.as_mut_os_string().push(path);
+ }
+}
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index 4a80ab1bef8..cffd24674d4 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -89,7 +89,7 @@ use task::Shell;
use text::{Bias, BufferId, OffsetRangeExt, Rope, ToOffset};
use util::{
ResultExt, debug_panic,
- paths::{PathStyle, SanitizedPath, normalize_path},
+ paths::{PathStyle, SanitizedPath},
post_inc,
rel_path::RelPath,
};
@@ -6153,6 +6153,11 @@ impl RepositorySnapshot {
worktree_name: &str,
worktree_directory_setting: &str,
) -> Result<PathBuf> {
+ anyhow::ensure!(
+ !self.path_style.has_root(Path::new(worktree_name)),
+ "worktree name must not contain a root directory component"
+ );
+
let repository_anchor = self.linked_worktree_anchor_path();
let project_name = self
.path_style
@@ -6163,8 +6168,17 @@ impl RepositorySnapshot {
worktree_directory_setting,
self.path_style,
)?;
- let directory = self.path_style.join_path(&directory, worktree_name)?;
- self.path_style.join_path(&directory, project_name)
+ let worktree_directory = self
+ .path_style
+ .normalize_lexically(self.path_style.join(&directory, worktree_name));
+
+ anyhow::ensure!(
+ self.path_style.starts_with(&worktree_directory, &directory),
+ "Worktree name {worktree_name:?} resolves to {worktree_directory:?}, \
+ which is outside the configured worktree directory {directory:?}"
+ );
+
+ Ok(self.path_style.join(&worktree_directory, project_name))
}
/// The main worktree is the original checkout that other worktrees were
@@ -6216,11 +6230,8 @@ impl RepositorySnapshot {
pub fn repo_path_to_abs_path(&self, repo_path: &RepoPath) -> PathBuf {
let repo_path = repo_path.display(self.path_style);
- PathBuf::from(
- self.path_style
- .join(&self.work_directory_abs_path, repo_path.as_ref())
- .unwrap(),
- )
+ self.path_style
+ .join(&self.work_directory_abs_path, repo_path.as_ref())
}
#[inline]
@@ -10593,19 +10604,11 @@ pub fn worktrees_directory_for_repo(
anyhow::bail!("git.worktree_directory must not be \"..\" (use \"../some-name\" instead)");
}
- let joined = path_style.join_path(repository_anchor_path, trimmed)?;
- let resolved = if path_style.is_posix() {
- joined
- } else {
- normalize_path(&joined)
- };
+ let resolved = path_style.normalize_lexically(path_style.join(repository_anchor_path, trimmed));
let resolved = if path_style.starts_with(resolved.as_path(), repository_anchor_path) {
resolved
- } else if let Some(repo_dir_name) = path_style
- .file_name(repository_anchor_path)
- .and_then(|name| name.to_str())
- {
- path_style.join_path(&resolved, repo_dir_name)?
+ } else if let Some(repo_dir_name) = path_style.file_name(repository_anchor_path) {
+ path_style.normalize_lexically(path_style.join(&resolved, repo_dir_name))
} else {
resolved
};
@@ -12070,8 +12073,8 @@ mod tests {
let work_dir = Path::new("/home/user/dev/lsp-tests");
let directory =
worktrees_directory_for_repo(work_dir, "../worktrees", PathStyle::Unix).unwrap();
- let directory = PathStyle::Unix.join_path(&directory, "nimble-sky").unwrap();
- let path = PathStyle::Unix.join_path(&directory, "lsp-tests").unwrap();
+ let directory = PathStyle::Unix.join(&directory, "nimble-sky");
+ let path = PathStyle::Unix.join(&directory, "lsp-tests");
assert_eq!(
path,
@@ -12126,6 +12129,51 @@ mod tests {
);
}
+ #[test]
+ fn test_new_worktree_path_rejects_names_outside_worktree_directory() {
+ let unix_snapshot = RepositorySnapshot::empty(
+ RepositoryId(0),
+ Path::new("/home/user/dev/lsp-tests").into(),
+ None,
+ None,
+ None,
+ PathStyle::Unix,
+ );
+
+ let windows_snapshot = RepositorySnapshot::empty(
+ RepositoryId(0),
+ Path::new(r"C:\Users\user\dev\lsp-tests").into(),
+ None,
+ None,
+ None,
+ PathStyle::Windows,
+ );
+
+ for (snapshot, worktree_name) in [
+ (&unix_snapshot, ".."),
+ (&unix_snapshot, "../.."),
+ (&unix_snapshot, "../../test_worktree"),
+ (&unix_snapshot, "feature/../../escaped"),
+ (&windows_snapshot, "D:trial"),
+ (&windows_snapshot, "C:trial"),
+ ] {
+ assert!(
+ snapshot
+ .path_for_new_linked_worktree(worktree_name, "../worktrees")
+ .is_err(),
+ "{worktree_name:?} should be rejected"
+ );
+ }
+
+ // Nested names remain valid as long as they resolve inside the directory.
+ assert_eq!(
+ unix_snapshot
+ .path_for_new_linked_worktree("feature/nested", "../worktrees")
+ .unwrap(),
+ PathBuf::from("/home/user/dev/worktrees/lsp-tests/feature/nested/lsp-tests")
+ );
+ }
+
fn verify_invariants(repository: &Repository) -> anyhow::Result<()> {
match &repository.commit_data_handler {
CommitDataHandlerState::Open(handler) => {
diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs
index 5235a3efe96..a1b40aef311 100644
--- a/crates/project/src/project.rs
+++ b/crates/project/src/project.rs
@@ -5281,9 +5281,8 @@ impl Project {
if let Some(file) = buffer.read(cx).file()
&& let Some(dir) = file.path().parent()
{
- if let Some(joined) = path_style.join(&*dir.display(path_style), path)
- && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
- {
+ let joined = path_style.join(&*dir.display(path_style), path);
+ if let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok() {
candidates.push(joined.into_arc());
}
}
diff --git a/crates/workspace/src/security_modal.rs b/crates/workspace/src/security_modal.rs
index 467a9a356ce..c436fea161d 100644
--- a/crates/workspace/src/security_modal.rs
+++ b/crates/workspace/src/security_modal.rs
@@ -398,8 +398,8 @@ impl SecurityModal {
Some(home_dir) => path_style
.strip_prefix(path, home_dir)
.ok()
- .and_then(|stripped| path_style.join("~", stripped))
- .map(|joined| Cow::Owned(PathBuf::from(joined)))
+ .map(|stripped| path_style.join(Path::new("~"), stripped))
+ .map(Cow::Owned)
.unwrap_or(Cow::Borrowed(path)),
None => Cow::Borrowed(path),
}
@@ -541,13 +541,10 @@ fn validate_trust_scope(
let expanded = match (trimmed.strip_prefix('~'), home_dir) {
(Some(rest), Some(home_dir)) => {
let rest = rest.trim_start_matches(path_style.separators_ch());
- if path_style == PathStyle::local() {
- home_dir.join(rest)
- } else {
- path_style
- .join_path_preserving_components(home_dir, rest)
- .map_err(|error| SharedString::from(error.to_string()))?
+ if path_style.has_root(Path::new(rest)) {
+ return Err("Path must be relative to the home directory".into());
}
+ path_style.join(home_dir, Path::new(rest))
}
_ => PathBuf::from(trimmed),
};
@@ -650,6 +647,21 @@ mod tests {
);
}
+ #[test]
+ fn rejects_rooted_tilde_suffix() {
+ let home = Path::new(r"C:\Users\me");
+ let project = Path::new(r"C:\Users\me\dev\project");
+ let style = PathStyle::Windows;
+
+ assert!(validate_trust_scope(r"~/C:\", project, Some(home), style).is_err());
+ assert!(validate_trust_scope(r"~\C:\Users\me\dev", project, Some(home), style).is_err());
+ assert!(validate_trust_scope(r"~C:\Users\me\dev", project, Some(home), style).is_err());
+ assert_eq!(
+ validate_trust_scope(r"~/dev", project, Some(home), style).unwrap(),
+ PathBuf::from(r"C:\Users\me\dev")
+ );
+ }
+
#[test]
fn expands_leading_tilde() {
let home = Path::new("/Users/me");
diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs
index b4a687c8847..6ad714e32ab 100644
--- a/crates/workspace/src/workspace.rs
+++ b/crates/workspace/src/workspace.rs
@@ -5333,17 +5333,15 @@ impl Workspace {
let path = Path::new(url_or_path);
// Try to resolve relative path against base_path first
let path_from_base = if let Some(base) = base_path {
- let resolved_path = path_style.join(base, path).map(PathBuf::from);
+ let resolved_path = path_style.join(base, path);
if project_is_local {
- if let Some(resolved_path) = resolved_path
- && resolved_path.exists()
- {
+ if resolved_path.exists() {
open_abs_path(self, resolved_path, cx);
return;
}
None
} else {
- resolved_path
+ Some(resolved_path)
}
} else {
None
diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rs
index 28ee817079b..311853a7e41 100644
--- a/crates/worktree/src/worktree.rs
+++ b/crates/worktree/src/worktree.rs
@@ -1291,8 +1291,9 @@ impl Worktree {
&& let Ok(stripped) = full_path.strip_prefix(home_dir())
{
self.path_style
- .join("~", &*stripped.to_string_lossy())
- .unwrap()
+ .join(Path::new("~"), stripped)
+ .to_string_lossy()
+ .into_owned()
} else {
full_path.to_string_lossy().into_owned()
};