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.

Map canonical LSP paths into symlinked external directories (#64895)

Sergey Sitnikov66432e4ca957
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 412b2db0d43..dfca6238fac 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -15162,12 +15162,41 @@ async fn find_worktree_for_lsp_path(
let Ok(canonical_path) = fs.canonicalize(abs_path).await else {
return Ok(None);
};
- lsp_store.read_with(cx, |lsp_store, cx| {
- lsp_store
- .worktree_store
- .read(cx)
- .find_worktree(&canonical_path, cx)
- })
+ let (worktree, mut scans) = lsp_store.read_with(cx, |lsp_store, cx| {
+ let worktree_store = lsp_store.worktree_store.read(cx);
+ if let Some(worktree) = worktree_store.find_worktree(&canonical_path, cx) {
+ return (Some(worktree), FuturesUnordered::new());
+ }
+ let scans = worktree_store
+ .worktrees()
+ .filter_map(|worktree| {
+ let scan_complete = worktree.read(cx).as_local()?.scan_complete();
+ Some(async move {
+ scan_complete.await;
+ worktree
+ })
+ })
+ .collect::<FuturesUnordered<_>>();
+ (None, scans)
+ })?;
+ if worktree.is_some() {
+ return Ok(worktree);
+ }
+ // Language servers may report files in symlinked external
+ // directories by their canonical path. These directories are
+ // known only after they are scanned. `scan_complete` resolves
+ // immediately for worktrees that are not scanning.
+ while let Some(worktree) = scans.next().await {
+ let relative_path = worktree.read_with(cx, |worktree, _| {
+ worktree
+ .as_local()?
+ .relative_path_for_external_abs_path(&canonical_path)
+ });
+ if let Some(relative_path) = relative_path {
+ return Ok(Some((worktree, Arc::from(relative_path))));
+ }
+ }
+ Ok(None)
}
}
}
diff --git a/crates/project/tests/integration/lsp_store.rs b/crates/project/tests/integration/lsp_store.rs
index de5056fe200..b15463027b3 100644
--- a/crates/project/tests/integration/lsp_store.rs
+++ b/crates/project/tests/integration/lsp_store.rs
@@ -8,7 +8,7 @@ use std::{
use collections::HashMap;
use fs::{FakeFs, Fs};
use futures::{FutureExt, StreamExt};
-use gpui::{Entity, TestAppContext};
+use gpui::{Entity, TestAppContext, UpdateGlobal as _};
use language::{
Buffer, CodeLabel, DiagnosticSourceKind, FakeLspAdapter, HighlightId, LocalFile, rust_lang,
};
@@ -22,6 +22,7 @@ use project::{
},
};
use serde_json::json;
+use settings::{ScanSymlinksSetting, SettingsStore};
use unindent::Unindent;
use util::{path, rel_path::rel_path};
@@ -339,6 +340,129 @@ async fn test_open_buffer_via_lsp_preserves_external_symlink_path(cx: &mut TestA
);
}
+#[gpui::test]
+async fn test_open_buffer_via_lsp_maps_external_symlink_target(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.executor().allow_parking();
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/shared"),
+ json!({ "pkg": { "def.rs": "pub fn def() {}", "other.rs": "pub fn other() {}" } }),
+ )
+ .await;
+ fs.insert_tree(
+ path!("/project"),
+ json!({ "src": { "main.rs": "fn main() {}" } }),
+ )
+ .await;
+ fs.create_symlink(
+ path!("/project/pkg").as_ref(),
+ PathBuf::from(path!("/shared/pkg")),
+ )
+ .await
+ .unwrap();
+
+ let (project, server_id) =
+ project_with_rust_server(fs, path!("/project"), path!("/project/src/main.rs"), cx).await;
+
+ project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_via_lsp(
+ Uri::from_file_path(path!("/project/pkg/def.rs")).unwrap(),
+ server_id,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_via_lsp(
+ Uri::from_file_path(path!("/shared/pkg/other.rs")).unwrap(),
+ server_id,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ assert_eq!(
+ buffer_paths(&buffer, cx),
+ (
+ "pkg/other.rs".to_string(),
+ PathBuf::from(path!("/project/pkg/other.rs"))
+ )
+ );
+ assert_eq!(
+ worktree_roots(&project, cx),
+ vec![PathBuf::from(path!("/project"))]
+ );
+}
+
+#[gpui::test]
+async fn test_open_buffer_via_lsp_maps_external_symlink_target_with_scan_symlinks_always(
+ cx: &mut TestAppContext,
+) {
+ init_test(cx);
+ cx.executor().allow_parking();
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.worktree.scan_symlinks = Some(ScanSymlinksSetting::Always);
+ });
+ });
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/shared"),
+ json!({ "pkg": { "other.rs": "pub fn other() {}" } }),
+ )
+ .await;
+ fs.insert_tree(
+ path!("/project"),
+ json!({ "src": { "main.rs": "fn main() {}" } }),
+ )
+ .await;
+ fs.create_symlink(
+ path!("/project/pkg").as_ref(),
+ PathBuf::from(path!("/shared/pkg")),
+ )
+ .await
+ .unwrap();
+
+ let (project, server_id) =
+ project_with_rust_server(fs, path!("/project"), path!("/project/src/main.rs"), cx).await;
+
+ let buffer = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_via_lsp(
+ Uri::from_file_path(path!("/shared/pkg/other.rs")).unwrap(),
+ server_id,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ assert_eq!(
+ buffer_paths(&buffer, cx),
+ (
+ "pkg/other.rs".to_string(),
+ PathBuf::from(path!("/project/pkg/other.rs"))
+ )
+ );
+ assert_eq!(
+ worktree_roots(&project, cx),
+ vec![PathBuf::from(path!("/project"))]
+ );
+}
+
#[gpui::test]
async fn test_open_buffer_via_lsp_case_variant_in_unscanned_dir(cx: &mut TestAppContext) {
init_test(cx);
diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rs
index 1f1809a8e91..66997d31929 100644
--- a/crates/worktree/src/worktree.rs
+++ b/crates/worktree/src/worktree.rs
@@ -63,7 +63,7 @@ use std::{
future::Future,
io::Read,
mem::{self},
- ops::{Deref, DerefMut, Range},
+ ops::{Bound, Deref, DerefMut, Range},
path::{Path, PathBuf},
pin::Pin,
sync::{
@@ -77,7 +77,7 @@ use text::{LineEnding, Rope};
use util::{
ResultExt, maybe,
paths::{PathMatcher, PathStyle, SanitizedPath, home_dir},
- rel_path::RelPath,
+ rel_path::{RelPath, RelPathBuf},
};
pub use worktree_settings::WorktreeSettings;
@@ -2960,6 +2960,28 @@ impl Snapshot {
}
impl LocalSnapshot {
+ /// Maps an absolute path inside a scanned external (symlinked) directory,
+ /// given by its canonical form, to its path within this worktree.
+ pub fn relative_path_for_external_abs_path(&self, abs_path: &Path) -> Option<RelPathBuf> {
+ let mut query = abs_path;
+ loop {
+ let (canonical, relative) = self
+ .external_canonical_to_relative
+ .range::<Path, _>((Bound::Unbounded, Bound::Included(query)))
+ .next_back()?;
+ if let Ok(suffix) = abs_path.strip_prefix(canonical) {
+ let suffix = RelPath::new(suffix, PathStyle::local()).ok()?;
+ return Some(relative.join(&suffix));
+ }
+ // Keys are nested, so the nearest smaller key can be under a sibling
+ // directory. No key lies between it and `query`, so no ancestor of
+ // `query` below their common ancestor is a key. Retry from there.
+ query = query
+ .ancestors()
+ .find(|ancestor| canonical.starts_with(ancestor))?;
+ }
+ }
+
fn local_repo_for_work_directory_path(&self, path: &RelPath) -> Option<&LocalRepositoryEntry> {
self.git_repositories
.iter()
@@ -5069,24 +5091,10 @@ impl BackgroundScanner {
&& let Ok(path) = RelPath::new(path, PathStyle::local())
{
path
- } else if let Some(path) = snapshot.external_canonical_to_relative.iter().find_map(
- |(canonical, relative)| {
- abs_path
- .as_path()
- .strip_prefix(canonical.as_ref())
- .ok()
- .and_then(|suffix| {
- RelPath::new(suffix, PathStyle::local())
- .ok()
- .map(|suffix_rel| {
- std::borrow::Cow::Owned(
- relative.join(&suffix_rel).to_rel_path_buf(),
- )
- })
- })
- },
- ) {
- path
+ } else if let Some(path) =
+ snapshot.relative_path_for_external_abs_path(abs_path.as_path())
+ {
+ std::borrow::Cow::Owned(path)
} else {
skip_ix(&mut ranges_to_drop, ix);
continue;
diff --git a/crates/worktree/tests/integration/worktree_tests.rs b/crates/worktree/tests/integration/worktree_tests.rs
index ad23eab8b64..7bd1179d16a 100644
--- a/crates/worktree/tests/integration/worktree_tests.rs
+++ b/crates/worktree/tests/integration/worktree_tests.rs
@@ -869,6 +869,93 @@ async fn test_scan_symlinks_always(cx: &mut TestAppContext) {
});
}
+#[gpui::test]
+async fn test_relative_path_for_external_abs_path(cx: &mut TestAppContext) {
+ init_test(cx);
+
+ cx.update(|cx| {
+ cx.update_global::<SettingsStore, _>(|store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.worktree.scan_symlinks =
+ Some(settings::ScanSymlinksSetting::Always);
+ });
+ });
+ });
+
+ let fs = FakeFs::new(cx.background_executor.clone());
+ fs.insert_tree(
+ "/root",
+ json!({
+ "dir1": {
+ "deps": {},
+ "src": {
+ "a.rs": "",
+ },
+ },
+ "lib": {
+ "a": {
+ "deep": {
+ "d.rs": "",
+ },
+ "x.rs": "",
+ },
+ "b": {
+ "b.rs": "",
+ },
+ "c.rs": "",
+ },
+ "other": {
+ "file.rs": "",
+ },
+ }),
+ )
+ .await;
+
+ fs.create_symlink("/root/dir1/deps/lib".as_ref(), "../../lib".into())
+ .await
+ .unwrap();
+
+ let tree = Worktree::local(
+ Path::new("/root/dir1"),
+ true,
+ fs.clone(),
+ Default::default(),
+ true,
+ WorktreeId::from_proto(0),
+ &mut cx.to_async(),
+ )
+ .await
+ .unwrap();
+
+ cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
+ .await;
+
+ tree.read_with(cx, |tree, _| {
+ let snapshot = tree.as_local().unwrap().snapshot();
+ let lookup = |abs_path: &str| {
+ snapshot
+ .relative_path_for_external_abs_path(Path::new(abs_path))
+ .map(|path| path.as_unix_str().to_string())
+ };
+ assert_eq!(
+ lookup("/root/lib/a/x.rs").as_deref(),
+ Some("deps/lib/a/x.rs")
+ );
+ assert_eq!(lookup("/root/lib/c.rs").as_deref(), Some("deps/lib/c.rs"));
+ assert_eq!(
+ lookup("/root/lib/zzz/new.rs").as_deref(),
+ Some("deps/lib/zzz/new.rs")
+ );
+ assert_eq!(
+ lookup("/root/lib/b-x/file.rs").as_deref(),
+ Some("deps/lib/b-x/file.rs")
+ );
+ assert_eq!(lookup("/root/lib").as_deref(), Some("deps/lib"));
+ assert_eq!(lookup("/root/other/file.rs"), None);
+ assert_eq!(lookup("/root/dir1/src/a.rs"), None);
+ });
+}
+
#[gpui::test]
async fn test_scan_symlinks_expanded(cx: &mut TestAppContext) {
init_test(cx);