From 978bcd6dd4b17af0f5a2b23df5ec0993e201bce0 Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Fri, 4 Dec 2026 04:01:51 -0800 Subject: [PATCH] feat(roots): auto-exclude nested linked Git worktrees from indexing and search (#7967) Linked worktrees of the repository at the project root that live below the root (any path, e.g. some/folder or .wt/topic) are now detected from /worktrees/*/gitdir and marked excluded, so they stay out of indexing, the file watcher, Find in Files and the Commit module list. Worktrees of other repositories, submodules, a linked worktree opened as the project root, attached workspace members and Cancel Exclusion are unaffected. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-host/src/mcp/search.rs | 4 +- crates/ide-host/src/ops/vcs/commands.rs | 6 +- crates/ide-host/src/project.rs | 129 +++++++++++--- crates/ide-host/tests/vcs_worktrees.rs | 165 ++++++++++++++++++ crates/ide-search/src/mask.rs | 2 +- crates/ide-vfs/src/lib.rs | 6 +- crates/ide-vfs/src/watch.rs | 15 +- crates/ide-vfs/tests/vfs.rs | 27 +++ crates/ide-workspace/src/roots/detect.rs | 159 ++++++++++++++++- crates/ide-workspace/src/roots/mod.rs | 8 + .../__tests__/changesGroupByModule.test.tsx | 13 ++ src/features/vcs/changeModules.ts | 8 +- src/platform/projectRoots.test.ts | 19 +- src/platform/projectRoots.ts | 5 +- 14 files changed, 530 insertions(+), 36 deletions(-) diff --git a/crates/ide-host/src/mcp/search.rs b/crates/ide-host/src/mcp/search.rs index bdfa56991e..a8c606aad7 100644 --- a/crates/ide-host/src/mcp/search.rs +++ b/crates/ide-host/src/mcp/search.rs @@ -939,8 +939,10 @@ impl Walk { continue; } let Ok(in_base) = entry.path.strip_prefix(base) else { continue }; + let in_base = in_base.to_string_lossy().replace('\\', "/"); let mask = self.excludes.iter().find(|(b, _)| b == base).map(|(_, m)| m); - if mask.is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) { + if mask.is_some_and(|m| !m.matches(&in_base) || (entry.kind == EntryKind::Dir && m.excludes_dir(&in_base))) + { continue; } match entry.kind { diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index 022eaebc5e..c5356f5f30 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -2883,8 +2883,10 @@ pub async fn vcs_add_worktree( }); // A worktree below the project is a new repository: rescan so its files // join the status and gutter queries (the watcher picks the gitfile up - // too, but only as a debounced event later). + // too, but only as a debounced event later), and refresh detected roots + // so the nested worktree is excluded from indexing and search at once. project.refresh_repositories(); + project.refresh_detected_roots(); result }) .await; @@ -2917,6 +2919,7 @@ pub async fn vcs_remove_worktree( )?; let result = project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force)); project.refresh_repositories(); + project.refresh_detected_roots(); result }) .await @@ -2937,6 +2940,7 @@ pub async fn vcs_move_worktree( check_worktree_away_from_project(&project.root, &path, "Cannot move a worktree containing the open project.")?; let result = project.with_repo_at(repo.as_deref(), |r| r.move_worktree(&path, &to)); project.refresh_repositories(); + project.refresh_detected_roots(); result }) .await diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 685647f99f..1a4f2ca3b0 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -274,6 +274,7 @@ impl Host { { let settings = settings.clone(); let root = root.clone(); + let detected_roots = detected_roots.clone(); let data_dir = self.local_data_dir.clone(); let config_dir = self.config_dir.clone(); let build_cache = self.local_data_dir.join("cache").join(&project_key).join("build"); @@ -418,12 +419,28 @@ impl Host { let (excluded_poms, build_files) = jdtls_maven_import(root, &effective); // Only the agent worktree folders that exist: another excluded folder // gives jdtls a fresh workspace, which every Java project would pay for. - let excluded_folders: Vec = AGENT_WORKTREE_DIRS + let mut excluded_folders: Vec = AGENT_WORKTREE_DIRS .iter() .filter(|dir| root.join(dir).is_dir()) .map(|dir| (*dir).to_owned()) .chain(effective.project_structure.excluded.iter().cloned()) .collect(); + let detected = if root == window_root { + detected_roots.read().clone() + } else { + ide_workspace::roots::detect(root) + }; + for folder in linked_roots(root, &effective, &detected).roots { + if folder.is_detected_worktree() + && !excluded_folders.iter().any(|existing| { + let existing = existing.trim_matches('/'); + folder.path == existing + || folder.path.strip_prefix(existing).is_some_and(|rest| rest.starts_with('/')) + }) + { + excluded_folders.push(folder.path); + } + } ide_sdk::apply::configure_maven_import( cfg, root, @@ -624,28 +641,6 @@ impl Host { sink.clone(), ); } - // Build files / conventional folders changed: re-detect roots. - let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok()); - if touched.into_iter().any(ide_workspace::roots::affects_roots) { - ide_build::gradle::forget_build_dirs(&root); - let fresh = ide_workspace::roots::detect(&root); - if *detected_roots.read() != fresh { - // Detected excluded folders (`target`, `build`) leave the index too. - let effective = settings.effective(); - let members = member_excludes.read(); - index.set_scope( - index_roots( - &root, - content_roots(&effective, &root, &build_cache, trusted.load(Ordering::Acquire)), - &effective, - &members, - ), - exclude_globs(&root, &effective, &fresh, &members), - ); - *detected_roots.write() = fresh; - sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() }); - } - } // A repository was cloned / initialised / removed below the project: // its `.git/HEAD` appeared or went. A linked worktree's `.git` is a // plain gitfile, and that file is the only marker written inside the @@ -696,6 +691,40 @@ impl Host { // the signal. A `git clone` / `git init` inside the project already arrives // through the `.git` paths above; this covers the whole tree being brought in. git_dirs |= batch.created.iter().any(|p| p.join(".git").exists()); + // Build files, conventional folders, or linked Git worktrees changed: re-detect roots. + let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok()); + let build_roots_changed = touched.into_iter().any(ide_workspace::roots::affects_roots); + let removed_worktree = !batch.removed.is_empty() + && detected_roots.read().iter().any(|r| { + r.is_detected_worktree() && batch.removed.iter().any(|p| *p == root.join(&r.path)) + }); + if build_roots_changed || git_dirs || removed_worktree { + if build_roots_changed { + ide_build::gradle::forget_build_dirs(&root); + } + let fresh = ide_workspace::roots::detect(&root); + if *detected_roots.read() != fresh { + // Detected excluded folders (`target`, `build`, linked worktrees) + // leave the index and watcher too. + let effective = settings.effective(); + let members = member_excludes.read(); + let fresh_excludes = exclude_globs(&root, &effective, &fresh, &members); + index.set_scope( + index_roots( + &root, + content_roots(&effective, &root, &build_cache, trusted.load(Ordering::Acquire)), + &effective, + &members, + ), + fresh_excludes.clone(), + ); + if let Some(watcher) = watcher_weak.get().and_then(std::sync::Weak::upgrade) { + watcher.set_excludes(&fresh_excludes); + } + *detected_roots.write() = fresh; + sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() }); + } + } if git_dirs { scan_repositories( &root, @@ -2146,6 +2175,21 @@ impl Project { } } + /// Re-detects project roots (build files, environments, linked worktrees) and refreshes + /// index and watcher scopes when they changed. + pub fn refresh_detected_roots(&self) { + if self.light { + return; + } + let fresh = ide_workspace::roots::detect(&self.root); + if *self.detected_roots.read() == fresh { + return; + } + *self.detected_roots.write() = fresh; + self.refresh_index_scope(); + self.sink.emit(IdeEvent::ProjectRootsChanged { root: self.root.clone().into() }); + } + /// Applies changed content roots and exclude settings to the index (which /// rescans in the background) and the file watchers, without reopening the project. pub fn refresh_index_scope(&self) { @@ -2754,11 +2798,50 @@ fn with_gradle_roots( out } +/// Project-relative paths of explicitly attached workspace projects or content roots inside `root`. +fn attached_in_root(root: &Path, settings: &ide_core::settings::Settings) -> Vec { + let mut out = Vec::new(); + let mut push = |p: &Path| { + if p != root + && let Ok(rel) = p.strip_prefix(root) + { + let rel = ide_workspace::roots::normalize(&rel.to_string_lossy()); + if !rel.is_empty() && !out.contains(&rel) { + out.push(rel); + } + } + }; + if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(root) + && !ws.is_container(root) + { + for p in &ws.projects { + push(p); + } + } + for raw in &settings.project_structure.content_roots { + let trimmed = raw.trim(); + if trimmed.is_empty() { + continue; + } + let p = Path::new(trimmed); + let abs = if p.is_absolute() { p.to_path_buf() } else { root.join(p) }; + push(&dunce::canonicalize(&abs).unwrap_or(abs)); + } + out +} + fn linked_roots(root: &Path, settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> ProjectRoots { let unlinked = ide_build::maven::UnlinkedProjects::load(root, &settings.languages.java.maven); + let attached = attached_in_root(root, settings); let detected = detected .iter() .filter(|folder| !folder.detected_from.as_ref().is_some_and(|pom| unlinked.contains(pom))) + .filter(|folder| { + !(folder.is_detected_worktree() + && attached.iter().any(|a| { + a == &folder.path || a.strip_prefix(&folder.path).is_some_and(|rest| rest.starts_with('/')) + })) + }) .cloned() .collect(); ProjectRoots::compute(detected, &settings.project_structure) diff --git a/crates/ide-host/tests/vcs_worktrees.rs b/crates/ide-host/tests/vcs_worktrees.rs index 2ab12b76d0..ce080f70ae 100644 --- a/crates/ide-host/tests/vcs_worktrees.rs +++ b/crates/ide-host/tests/vcs_worktrees.rs @@ -432,3 +432,168 @@ async fn tmp_alias_is_protected() { let alias = std::path::Path::new("/").join(linked.strip_prefix("/private").unwrap()); f.assert_protected(&alias).await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn linked_worktree_below_project_repo_is_excluded_until_unmarked_or_attached() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let workspace = base.join("workspace"); + let repo = workspace.join("app"); + std::fs::create_dir_all(repo.join("src")).unwrap(); + std::fs::write(repo.join("Cargo.toml"), "[package]\nname = \"app\"\nversion = \"0.1.0\"\n").unwrap(); + std::fs::write( + repo.join("src/lib.rs"), + "pub fn unique_worktree_symbol() -> &'static str { \"unique_worktree_needle\" }\n", + ) + .unwrap(); + git(&repo, &["init", "-b", "main"]); + git(&repo, &["config", "user.name", "Test"]); + git(&repo, &["config", "user.email", "test@example.com"]); + git(&repo, &["config", "commit.gpgsign", "false"]); + git(&repo, &["add", "."]); + git(&repo, &["commit", "-m", "initial"]); + + // Linked worktree of `repo` placed below `repo` at a custom path (not `.worktrees`). + let nested = repo.join("topics/feature"); + git(&repo, &["worktree", "add", "-b", "feature", nested.to_str().unwrap()]); + // Sibling linked worktree outside `repo`, inside the non-repo parent folder `workspace`. + let sibling = workspace.join("app-sibling"); + git(&repo, &["worktree", "add", "-b", "sibling", sibling.to_str().unwrap()]); + + let host = Host::new(common::host_config(&base)); + host.trust.decide(&repo, true, false).unwrap(); + let project = host.open_project("main", &repo).unwrap(); + wait_for_repos(&project, 2).await; + assert!(project.index.wait_idle(Duration::from_secs(10))); + + let search = |include_excluded: bool| { + let host = &host; + async move { + let hits = Arc::new(std::sync::Mutex::new(Vec::new())); + let out = hits.clone(); + let query = serde_json::from_value(serde_json::json!({ + "pattern": "unique_worktree_needle", + "isRegex": false, + "caseSensitive": true, + "wholeWord": false, + "include": [], + "exclude": [], + "scope": { "kind": "project" }, + "maxMatches": 100, + "includeExcluded": include_excluded + })) + .unwrap(); + ide_host::ops::search::search_start( + host, + "main", + RequestId::next(), + query, + ide_host::ops::Channel::new(move |event| { + if let ide_host::ops::search::SearchEvent::File { file } = event { + out.lock().unwrap().push(file.rel_path); + } + }), + ) + .await + .unwrap(); + let mut found = hits.lock().unwrap().clone(); + found.sort(); + found + } + }; + + // Detected as excluded root; skipped in file index, symbol index, and Find in Files. + assert!(project.roots().excluded_globs().contains(&"/topics/feature".to_owned())); + let indexed_files: Vec = project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect(); + assert_eq!(indexed_files, vec!["src/lib.rs"]); + let indexed_syms: Vec = project + .index + .find_symbols("unique_worktree_symbol", ide_index::SymbolFilter::All, 20) + .into_iter() + .map(|m| m.rel_path) + .collect(); + assert_eq!(indexed_syms, vec!["src/lib.rs"]); + assert_eq!(search(false).await, vec!["src/lib.rs"]); + assert_eq!(search(true).await, vec!["src/lib.rs", "topics/feature/src/lib.rs"]); + + // Adding a worktree below `repo` via VCS command excludes it immediately; removing drops it. + let live_wt = repo.join("live-worktree"); + vcs::vcs_add_worktree(&host, "main", None, live_wt.clone(), "main".into(), Some("live".into()), None, None) + .await + .unwrap(); + assert!(project.roots().excluded_globs().contains(&"/live-worktree".to_owned())); + assert!(project.index.wait_idle(Duration::from_secs(10))); + assert_eq!(search(false).await, vec!["src/lib.rs"]); + vcs::vcs_remove_worktree(&host, "main", None, live_wt, false).await.unwrap(); + assert!(!project.roots().excluded_globs().contains(&"/live-worktree".to_owned())); + + // Unmarking the detected exclusion (Cancel Exclusion) opts the worktree back in. + ide_host::ops::project::set_settings( + &host, + "main", + ide_workspace::settings::SettingsScope::Project, + "projectStructure.unmarked", + r#"["topics/feature"]"#, + ) + .unwrap(); + let expected_both = vec!["src/lib.rs".to_owned(), "topics/feature/src/lib.rs".to_owned()]; + let mut after_unmark = Vec::new(); + for _ in 0..100 { + assert!(project.index.wait_idle(Duration::from_secs(10))); + after_unmark = project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect(); + after_unmark.sort(); + if after_unmark == expected_both { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert_eq!(after_unmark, expected_both); + assert_eq!(search(false).await, expected_both); + + // Clear the unmark so the worktree is excluded again, then verify `attach_workspace` opts it back in. + ide_host::ops::project::set_settings( + &host, + "main", + ide_workspace::settings::SettingsScope::Project, + "projectStructure.unmarked", + "[]", + ) + .unwrap(); + for _ in 0..100 { + assert!(project.index.wait_idle(Duration::from_secs(10))); + if project.index.find_files("lib.rs", 20).len() == 1 { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert_eq!(search(false).await, vec!["src/lib.rs"]); + host.trust.decide(&nested, true, false).unwrap(); + ide_host::ops::project::attach_workspace(&host, "main", &nested).unwrap(); + assert!(project.index.wait_idle(Duration::from_secs(10))); + let mut after_attach: Vec = + project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect(); + after_attach.sort(); + assert_eq!(after_attach, expected_both); + assert_eq!(search(false).await, expected_both); + + // Opening the linked worktree directly as the project root indexes and searches it normally. + host.close_project("main"); + host.trust.decide(&nested, true, false).unwrap(); + let wt_project = host.open_project("main", &nested).unwrap(); + assert!(wt_project.index.wait_idle(Duration::from_secs(10))); + assert!(wt_project.roots().excluded_globs().is_empty()); + let wt_files: Vec = wt_project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect(); + assert_eq!(wt_files, vec!["src/lib.rs"]); + assert_eq!(search(false).await, vec!["src/lib.rs"]); + + // Opening a non-repository parent folder holding `app` and sibling `app-sibling` keeps both indexed. + host.close_project("main"); + host.trust.decide(&workspace, true, false).unwrap(); + let parent_project = host.open_project("main", &workspace).unwrap(); + assert!(parent_project.index.wait_idle(Duration::from_secs(10))); + assert!(!parent_project.roots().excluded_globs().contains(&"/app-sibling".to_owned())); + let parent_found = search(false).await; + assert!(parent_found.contains(&"app/src/lib.rs".to_owned()), "{parent_found:?}"); + assert!(parent_found.contains(&"app-sibling/src/lib.rs".to_owned()), "{parent_found:?}"); + host.close_project("main"); +} diff --git a/crates/ide-search/src/mask.rs b/crates/ide-search/src/mask.rs index 1d40af1ba2..e5dad6565a 100644 --- a/crates/ide-search/src/mask.rs +++ b/crates/ide-search/src/mask.rs @@ -61,7 +61,7 @@ impl FileMask { /// Whether an exclusion covers every file below this directory. This is /// deliberately conservative; ordinary masks still filter individual files. - pub(crate) fn excludes_dir(&self, rel_path: &str) -> bool { + pub fn excludes_dir(&self, rel_path: &str) -> bool { if self.exclude_dirs.is_empty() { return false; } diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs index 8effc6047e..ffe2f9f8ed 100644 --- a/crates/ide-vfs/src/lib.rs +++ b/crates/ide-vfs/src/lib.rs @@ -124,15 +124,17 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering { /// /// Inside an archive (`!/`, or the archive file itself) lists its entries. pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult> { - read_dir_with(dir, excludes, None) + read_dir_with(dir, excludes, None, None) } /// [`read_dir`] matching `.gitignore` / `.ignore` with `shared` rules (a watcher's, kept current by its /// events) instead of rules looked up afresh: on a network share each lookup is several round trips. +/// When the directory has no enclosing repository, `exclude_base` anchors root-relative excludes. pub(crate) fn read_dir_with( dir: &Path, excludes: &[String], shared: Option<&rules::GitignoreStack>, + exclude_base: Option<&Path>, ) -> IdeResult> { if let Some((archive, entry)) = split_archive_path(dir) { return read_archive_dir(&archive, &entry); @@ -151,7 +153,7 @@ pub(crate) fn read_dir_with( &fresh } }; - let base = gitignore.repo_root().unwrap_or(dir).to_path_buf(); + let base = gitignore.repo_root().or(exclude_base).unwrap_or(dir).to_path_buf(); let excludes = ExcludeMatcher::new(excludes); let listed: Vec = fs::read_dir(dir)? diff --git a/crates/ide-vfs/src/watch.rs b/crates/ide-vfs/src/watch.rs index c5ec85c359..7da4584db2 100644 --- a/crates/ide-vfs/src/watch.rs +++ b/crates/ide-vfs/src/watch.rs @@ -134,9 +134,18 @@ impl Watcher { /// Replaces the exclude globs (Settings › Project Structure / File Types /// changed): later events below newly excluded folders are dropped. In - /// per-directory mode, folders no longer excluded are watched once they change. + /// per-directory mode, newly excluded directories are unwatched immediately, + /// and folders no longer excluded are watched once they change. pub fn set_excludes(&self, excludes: &[String]) { *self.excludes.write() = ExcludeMatcher::new(excludes); + if self.inner.state.mode == WatchMode::PerDirectory { + let watched: Vec = self.inner.state.watched.lock().iter().cloned().collect(); + for dir in watched { + if dir != self.root && !self.inner.state.filter.should_watch_dir(&dir) { + self.inner.state.remove_watch(&dir); + } + } + } } /// Explicit refresh for writes to Git common metadata outside the watched root. @@ -170,8 +179,8 @@ impl Watcher { /// They are invalidated by the watcher's own events, so expanding folder after folder does not /// look for `.git` and re-read every `.gitignore` up to the repository root each time. pub fn read_dir(&self, dir: &Path, excludes: &[String]) -> IdeResult> { - let shared = dir.starts_with(&self.root).then_some(&*self.rules); - crate::read_dir_with(dir, excludes, shared) + let inside = dir.starts_with(&self.root); + crate::read_dir_with(dir, excludes, inside.then_some(&*self.rules), inside.then_some(self.root.as_path())) } /// Number of OS-level watches (1 in recursive and flat mode). diff --git a/crates/ide-vfs/tests/vfs.rs b/crates/ide-vfs/tests/vfs.rs index 4e93c919f4..f6ece55f56 100644 --- a/crates/ide-vfs/tests/vfs.rs +++ b/crates/ide-vfs/tests/vfs.rs @@ -523,6 +523,33 @@ fn worktree_and_nested_repository_local_excludes_are_reflected_in_listings() { assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored); } +#[test] +fn watcher_read_dir_anchors_excludes_at_root_outside_git_repo() { + let (_t, r) = root(); + fs::create_dir_all(r.join("repo.worktrees/task-1")).unwrap(); + fs::create_dir_all(r.join("repo.worktrees/keep")).unwrap(); + let watcher = + Watcher::start(&r, vec!["/repo.worktrees/task-1".into()], Arc::new(ide_core::NullSink), Box::new(|_| {})) + .unwrap(); + let entries = watcher.read_dir(&r.join("repo.worktrees"), &["/repo.worktrees/task-1".into()]).unwrap(); + assert!(entries.iter().find(|e| e.name == "task-1").unwrap().excluded); + assert!(!entries.iter().find(|e| e.name == "keep").unwrap().excluded); +} + +#[test] +fn per_directory_set_excludes_unwatches_newly_excluded_dirs() { + let (_t, r) = root(); + fs::create_dir_all(r.join("src")).unwrap(); + fs::create_dir_all(r.join("wt/sub")).unwrap(); + let watcher = + Watcher::start_with(&r, vec![], Arc::new(ide_core::NullSink), Box::new(|_| {}), WatchMode::PerDirectory) + .unwrap(); + assert!(watcher.watch_count() >= 4, "expected root, src, wt, wt/sub watched: {}", watcher.watch_count()); + let before = watcher.watch_count(); + watcher.set_excludes(&["/wt".into()]); + assert!(watcher.watch_count() < before, "newly excluded subtree should be unwatched"); +} + #[test] fn create_file_bytes_is_exclusive() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-workspace/src/roots/detect.rs b/crates/ide-workspace/src/roots/detect.rs index 3fc87cf3e6..3fc0b2c345 100644 --- a/crates/ide-workspace/src/roots/detect.rs +++ b/crates/ide-workspace/src/roots/detect.rs @@ -3,7 +3,7 @@ use super::{RootKind, SourceFolder, gradle, maven}; use std::collections::VecDeque; -use std::path::Path; +use std::path::{Path, PathBuf}; /// Module directories deeper than this below the project root are not looked at. const MAX_DEPTH: usize = 6; @@ -55,6 +55,69 @@ pub(crate) fn virtual_env_marker(dir: &Path) -> Option<&'static str> { } } +/// Resolves the `gitdir:` target of a `.git` file in `dir`, if present. +fn gitfile_gitdir(dir: &Path) -> Option { + let dot_git = dir.join(".git"); + let meta = std::fs::metadata(&dot_git).ok()?; + if !meta.is_file() || meta.len() > 8192 { + return None; + } + let text = std::fs::read_to_string(&dot_git).ok()?; + let raw = text.lines().next()?.strip_prefix("gitdir:")?.trim(); + if raw.is_empty() { + return None; + } + let target = Path::new(raw); + Some(if target.is_absolute() { target.to_path_buf() } else { dir.join(target) }) +} + +/// The common `.git` directory of a Git checkout rooted at `dir`, if any. +fn common_git_dir(dir: &Path) -> Option { + let dot_git = dir.join(".git"); + if dot_git.is_dir() { + return Some(dot_git); + } + let gitdir = gitfile_gitdir(dir)?; + if let Ok(common) = std::fs::read_to_string(gitdir.join("commondir")) { + let raw = common.trim(); + if !raw.is_empty() { + let p = Path::new(raw); + return Some(if p.is_absolute() { p.to_path_buf() } else { gitdir.join(p) }); + } + } + gitdir.is_dir().then_some(gitdir) +} + +/// Records linked Git worktrees registered in `common_dir` that lie strictly below `canon_root`. +fn linked_worktrees_from_common(canon_root: &Path, common_dir: &Path, out: &mut Vec) { + let canon_common = dunce::canonicalize(common_dir).unwrap_or_else(|_| common_dir.to_path_buf()); + let Ok(entries) = std::fs::read_dir(canon_common.join("worktrees")) else { return }; + for entry in entries.flatten() { + let wt_meta = entry.path(); + if !wt_meta.is_dir() || !wt_meta.join("commondir").is_file() { + continue; + } + let Ok(raw) = std::fs::read_to_string(wt_meta.join("gitdir")) else { continue }; + let raw = raw.trim(); + if raw.is_empty() { + continue; + } + let target = Path::new(raw); + let wt_gitfile = if target.is_absolute() { target.to_path_buf() } else { wt_meta.join(target) }; + let Some(wt_dir) = wt_gitfile.parent() else { continue }; + let Ok(canon_wt) = dunce::canonicalize(wt_dir) else { continue }; + if !canon_wt.is_dir() || canon_wt == canon_root || !canon_wt.starts_with(canon_root) { + continue; + } + let Ok(rel) = canon_wt.strip_prefix(canon_root) else { continue }; + let rel = super::normalize(&rel.to_string_lossy()); + if !rel.is_empty() && !out.iter().any(|r| r.path == rel) { + let from = join(&rel, ".git"); + out.push(SourceFolder { path: rel, kind: RootKind::Excluded, detected_from: Some(from) }); + } + } +} + /// Build files whose changes can change the detected roots. pub(crate) const BUILD_FILES: &[&str] = &[ "pom.xml", @@ -114,6 +177,14 @@ pub fn affects_roots(rel: &Path) -> bool { /// Detects roots below `root`; paths in the result are unique and sorted. pub fn detect(root: &Path) -> Vec { let mut out: Vec = Vec::new(); + let canon_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + // Linked worktrees of the repository holding `root` that are placed below `root` + // are copies of the same repository and excluded from indexing and search. + if let Some(enclosing) = canon_root.ancestors().find(|a| a.join(".git").exists()) + && let Some(common) = common_git_dir(enclosing) + { + linked_worktrees_from_common(&canon_root, &common, &mut out); + } let mut queue: VecDeque<(String, usize)> = VecDeque::from([(String::new(), 0)]); let mut visited = 0; while let Some((rel, depth)) = queue.pop_front() { @@ -123,6 +194,9 @@ pub fn detect(root: &Path) -> Vec { break; } let dir = if rel.is_empty() { root.to_path_buf() } else { root.join(&rel) }; + if !rel.is_empty() && out.iter().any(|r| r.path == rel && r.kind == RootKind::Excluded) { + continue; + } // The listing alone decides which markers to probe: on a network share every // probe is a round trip, and most folders have none of them. let Ok(entries) = std::fs::read_dir(&dir) else { continue }; @@ -751,4 +825,87 @@ mod tests { assert!(!affects_roots(Path::new(p)), "{p}"); } } + + fn git(dir: &Path, args: &[&str]) { + let out = std::process::Command::new("git").current_dir(dir).args(args).output().unwrap(); + assert!(out.status.success(), "git {:?}: {}", args, String::from_utf8_lossy(&out.stderr)); + } + + fn init_cargo_repo(dir: &Path) { + fs::create_dir_all(dir.join("src")).unwrap(); + fs::write(dir.join("Cargo.toml"), "[package]\nname = \"app\"\nversion = \"0.1.0\"\n").unwrap(); + fs::write(dir.join("src/lib.rs"), "pub fn answer() -> i32 { 42 }\n").unwrap(); + git(dir, &["init", "-q", "-b", "main"]); + git(dir, &["config", "user.name", "Test"]); + git(dir, &["config", "user.email", "test@example.com"]); + git(dir, &["config", "commit.gpgsign", "false"]); + git(dir, &["add", "."]); + git(dir, &["commit", "-qm", "initial"]); + } + + #[test] + fn linked_worktrees_of_the_project_repo_below_root_are_excluded_without_affecting_other_repos() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let workspace = base.join("workspace"); + let app = workspace.join("app"); + init_cargo_repo(&app); + + // External repo whose linked worktree is placed inside `app`. + let external = base.join("external"); + init_cargo_repo(&external); + + // Worktrees of `app` below `app` (custom path, hidden path, agent path) plus a sibling worktree. + let manual_wt = app.join("some/folder"); + let hidden_wt = app.join(".wt/topic"); + let claude_wt = app.join(".claude/worktrees/fix-1"); + let sibling_wt = workspace.join("app-feature"); + let external_wt = app.join("external-wt"); + git(&app, &["worktree", "add", "-qb", "manual", manual_wt.to_str().unwrap()]); + git(&app, &["worktree", "add", "-qb", "topic", hidden_wt.to_str().unwrap()]); + git(&app, &["worktree", "add", "-qb", "fix-1", claude_wt.to_str().unwrap()]); + git(&app, &["worktree", "add", "-qb", "sibling", sibling_wt.to_str().unwrap()]); + git(&external, &["worktree", "add", "-qb", "ext", external_wt.to_str().unwrap()]); + + // A Git submodule has a `.git` file without `commondir`/`gitdir` and stays included. + let submod = app.join("submod"); + fs::create_dir_all(submod.join("src")).unwrap(); + fs::create_dir_all(app.join(".git/modules/submod")).unwrap(); + fs::write(submod.join(".git"), "gitdir: ../.git/modules/submod\n").unwrap(); + fs::write(submod.join("Cargo.toml"), "[package]\nname = \"sub\"\nversion = \"0.1.0\"\n").unwrap(); + + // Opening `app`: only linked worktrees of `app`'s repository placed below `app` are excluded; + // worktrees of a different repository (`external-wt`) and submodules stay indexed. + let detected = detect(&app); + assert_eq!( + summary(&detected), + vec![ + ".claude/worktrees/fix-1=Excluded@.claude/worktrees/fix-1/.git", + ".wt/topic=Excluded@.wt/topic/.git", + "external-wt/src=Source@external-wt/Cargo.toml", + "some/folder=Excluded@some/folder/.git", + "src=Source@Cargo.toml", + "submod/src=Source@submod/Cargo.toml", + ] + ); + assert_eq!(detected.iter().filter(|r| r.is_detected_worktree()).count(), 3); + + // Opening a parent folder outside any repository keeps both `app` and sibling `app-feature`. + assert_eq!( + summary(&detect(&workspace)), + vec![ + "app-feature/src=Source@app-feature/Cargo.toml", + "app/external-wt/src=Source@app/external-wt/Cargo.toml", + "app/some/folder/src=Source@app/some/folder/Cargo.toml", + "app/src=Source@app/Cargo.toml", + "app/submod/src=Source@app/submod/Cargo.toml", + ] + ); + + // Opening a linked worktree directly as the project root never excludes the root itself, + // while another linked worktree of the same repository placed below it is excluded. + let nested_in_wt = sibling_wt.join("nested-wt"); + git(&sibling_wt, &["worktree", "add", "-qb", "nested-in-wt", nested_in_wt.to_str().unwrap()]); + assert_eq!(summary(&detect(&sibling_wt)), vec!["nested-wt=Excluded@nested-wt/.git", "src=Source@Cargo.toml"]); + } } diff --git a/crates/ide-workspace/src/roots/mod.rs b/crates/ide-workspace/src/roots/mod.rs index af4bb83daf..4799827647 100644 --- a/crates/ide-workspace/src/roots/mod.rs +++ b/crates/ide-workspace/src/roots/mod.rs @@ -47,6 +47,14 @@ pub struct SourceFolder { pub detected_from: Option, } +impl SourceFolder { + /// Whether this root is an auto-detected excluded linked Git worktree. + pub fn is_detected_worktree(&self) -> bool { + self.kind == RootKind::Excluded + && self.detected_from.as_deref().is_some_and(|from| from == ".git" || from.ends_with("/.git")) + } +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct ProjectRoots { diff --git a/src/features/vcs/__tests__/changesGroupByModule.test.tsx b/src/features/vcs/__tests__/changesGroupByModule.test.tsx index df3e20acda..2475e9bb89 100644 --- a/src/features/vcs/__tests__/changesGroupByModule.test.tsx +++ b/src/features/vcs/__tests__/changesGroupByModule.test.tsx @@ -108,6 +108,19 @@ describe("resolveChangeModules", () => { { path: "/w/scala", name: "scala-svc", tool: undefined }, ]); }); + + it("omits standalone excluded roots (linked worktrees, venvs) from change modules", () => { + const modules = resolveChangeModules({ + projectRoot: "/w", + projectName: "workspace", + detected: [ + { path: "app/src", kind: "source", detectedFrom: "app/Cargo.toml" }, + { path: "kubernetes-services-style", kind: "excluded", detectedFrom: "kubernetes-services-style/.git" }, + { path: ".venv", kind: "excluded", detectedFrom: ".venv/pyvenv.cfg" }, + ], + }); + expect(modules).toEqual([{ path: "/w/app", name: "app", tool: undefined }]); + }); }); describe("Group By › Module in ChangesTree", () => { diff --git a/src/features/vcs/changeModules.ts b/src/features/vcs/changeModules.ts index 3dc0780401..e0d79c1b58 100644 --- a/src/features/vcs/changeModules.ts +++ b/src/features/vcs/changeModules.ts @@ -68,14 +68,18 @@ export function resolveChangeModules({ if (cleanProjectRoot) { for (const r of detected) { if (!r.detectedFrom) continue; - add(absPath(cleanProjectRoot, detectedModuleDir(r.detectedFrom))); + const dir = detectedModuleDir(r.detectedFrom); + if (r.kind === "excluded" && stripSlash(r.path) === dir) continue; + add(absPath(cleanProjectRoot, dir)); } } for (const m of attached) { add(m.root); for (const r of m.detected) { if (!r.detectedFrom) continue; - add(absPath(m.root, detectedModuleDir(r.detectedFrom))); + const dir = detectedModuleDir(r.detectedFrom); + if (r.kind === "excluded" && stripSlash(r.path) === dir) continue; + add(absPath(m.root, dir)); } } for (const memberRoot of workspaceProjects ?? []) { diff --git a/src/platform/projectRoots.test.ts b/src/platform/projectRoots.test.ts index 3f6ff72d5c..44e566eb26 100644 --- a/src/platform/projectRoots.test.ts +++ b/src/platform/projectRoots.test.ts @@ -13,7 +13,7 @@ import { type RootFolder, } from "./languageSettings"; import { useProject } from "./project"; -import { currentRoots, inFileSet, isTestFile, rootOfPath, useProjectRoots } from "./projectRoots"; +import { currentRoots, inFileSet, isTestFile, projectModules, rootOfPath, useProjectRoots } from "./projectRoots"; const pom = (path: string, kind: RootFolder["kind"]): RootFolder => ({ path, kind, detectedFrom: "pom.xml" }); const DETECTED: RootFolder[] = [ @@ -112,6 +112,23 @@ describe("project roots store", () => { useProjectRoots.setState({ root: "/other", detected: DETECTED }); expect(currentRoots().map((r) => r.path)).toEqual(["out"]); }); + + it("omits standalone excluded roots (linked worktrees, venvs) from projectModules", () => { + const modules = projectModules( + [ + { path: "openidea/src", kind: "source", detectedFrom: "openidea/Cargo.toml" }, + { path: "core/target", kind: "excluded", detectedFrom: "core/pom.xml" }, + { path: "kubernetes-services-style", kind: "excluded", detectedFrom: "kubernetes-services-style/.git" }, + { path: ".venv", kind: "excluded", detectedFrom: ".venv/pyvenv.cfg" }, + ], + "openidea_all", + ); + expect(modules).toEqual([ + { path: "", name: "openidea_all" }, + { path: "core", name: "core" }, + { path: "openidea", name: "openidea" }, + ]); + }); }); it("lists workspace members as scopes and admits their files without admitting workspace state", async () => { diff --git a/src/platform/projectRoots.ts b/src/platform/projectRoots.ts index 59f318401f..fd50f02396 100644 --- a/src/platform/projectRoots.ts +++ b/src/platform/projectRoots.ts @@ -179,7 +179,10 @@ export function projectModules(detected: readonly RootFolder[], projectName: str for (const r of detected) { if (!r.detectedFrom) continue; const i = r.detectedFrom.lastIndexOf("/"); - dirs.add(i < 0 ? "" : r.detectedFrom.slice(0, i)); + const dir = i < 0 ? "" : r.detectedFrom.slice(0, i); + // Standalone excluded directories (linked worktrees, virtualenvs) are not modules. + if (r.kind === "excluded" && r.path === dir) continue; + dirs.add(dir); } return [...dirs] .sort((a, b) => (a === "" ? -1 : b === "" ? 1 : a < b ? -1 : a > b ? 1 : 0))