diff --git a/crates/ide-host/src/mcp/files.rs b/crates/ide-host/src/mcp/files.rs index 6162c5e71..93e9a24e3 100644 --- a/crates/ide-host/src/mcp/files.rs +++ b/crates/ide-host/src/mcp/files.rs @@ -184,10 +184,9 @@ marked directory are not marked again.", } let deadline = Instant::now() + Duration::from_millis(timeout.max(0) as u64); let cancel = call.cancel.clone(); - let marks = Marks { - root: call.root().to_path_buf(), - excludes: FileMask::new(&[], &call.project().search_excludes()).ok(), - }; + // Matched from the root holding the directory: an attached project has its own exclusions. + let root = call.project().root_of(&dir); + let marks = Marks { excludes: FileMask::new(&[], &call.project().search_excludes_in(&root)).ok(), root }; // The directory itself, when it or one above it is left out. let root_mark = marker(ide_index::walk_skips(call.root(), &dir), marks.ide_excluded(&dir, true)); let mut tree = TreeRender { diff --git a/crates/ide-host/src/mcp/search.rs b/crates/ide-host/src/mcp/search.rs index 385928756..b3d966066 100644 --- a/crates/ide-host/src/mcp/search.rs +++ b/crates/ide-host/src/mcp/search.rs @@ -837,8 +837,6 @@ async fn file_search(call: Call) -> IdeResult { .add(build_glob(&normalize_glob(&q, call.root(), &[])?)?) .build() .map_err(|_| IdeError::invalid(format!("Invalid glob pattern: {q}")))?; - // Ignored names and "Exclude files" patterns, which `read_dir` does not flag. - let excludes = if include_excluded { None } else { Some(FileMask::new(&[], &call.project().search_excludes())?) }; let root = call.root().to_path_buf(); let content = call.project().content_roots(); // Where a folder's exclusions are matched from: the content root holding it, or the project. @@ -862,6 +860,15 @@ async fn file_search(call: Call) -> IdeResult { .map(|r| (r.clone(), r)) .collect(), }; + // Ignored names and "Exclude files" patterns, which `read_dir` does not flag, by walked root. + let mut excludes = Vec::new(); + if !include_excluded { + for (_, base) in &roots { + if !excludes.iter().any(|(b, _)| b == base) { + excludes.push((base.clone(), FileMask::new(&[], &call.project().search_excludes_in(base))?)); + } + } + } let host = call.host(); let walk = Walk { host: host.clone(), @@ -898,7 +905,7 @@ struct Walk { window: String, root: PathBuf, include_excluded: bool, - excludes: Option, + excludes: Vec<(PathBuf, FileMask)>, glob: GlobSet, scope: PathScope, limit: usize, @@ -931,7 +938,8 @@ impl Walk { continue; } let Ok(in_base) = entry.path.strip_prefix(base) else { continue }; - if self.excludes.as_ref().is_some_and(|m| !m.matches(&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('\\', "/"))) { continue; } match entry.kind { diff --git a/crates/ide-host/src/ops/bdd.rs b/crates/ide-host/src/ops/bdd.rs index ae3565dc6..03c7388f3 100644 --- a/crates/ide-host/src/ops/bdd.rs +++ b/crates/ide-host/src/ops/bdd.rs @@ -81,12 +81,12 @@ pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec { /// Every Cucumber source of the project (its folder and the content roots outside it). pub fn cucumber_sources(host: &Host, window: &str) -> IdeResult> { let project = host.project(window)?; - let mut excludes = project.search_excludes(); - // Cucumber's own sources (and every other package's) are not the project's steps. - excludes.push("node_modules".to_owned()); - excludes.push("site-packages".to_owned()); let mut out = Vec::new(); for root in std::iter::once(project.root.clone()).chain(project.content_roots()) { + let mut excludes = project.search_excludes_in(&root); + // Cucumber's own sources (and every other package's) are not the project's steps. + excludes.push("node_modules".to_owned()); + excludes.push("site-packages".to_owned()); out.extend(sources_in(&root, &excludes)); } out.sort_by(|a, b| a.path.cmp(&b.path)); diff --git a/crates/ide-host/src/ops/fs.rs b/crates/ide-host/src/ops/fs.rs index 6d090710a..baf00ca74 100644 --- a/crates/ide-host/src/ops/fs.rs +++ b/crates/ide-host/src/ops/fs.rs @@ -85,11 +85,13 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult< host.blocking(move || { let excludes = project .map(|p| { - let globs = p.exclude_globs(); + // An attached project's folders follow its own exclusions. + let root = p.root_of(&path); + let globs = p.exclude_globs_in(&root); // `read_dir` matches relative to the enclosing repository: re-anchor - // project-root patterns (`/build`) when the project is a repo subfolder. - let repo = p.root.ancestors().find(|d| d.join(".git").exists()); - match repo.and_then(|r| p.root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) { + // root patterns (`/build`) when the project is a repo subfolder. + let repo = root.ancestors().find(|d| d.join(".git").exists()); + match repo.and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) { Some(rel) => { let rel = rel.to_string_lossy().replace('\\', "/"); globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect() diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index 2584b5500..b24905bb3 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -378,7 +378,14 @@ pub fn set_settings( // Content roots and excludes (files.exclude, ignored names, excluded folders) reach the // index and the watchers without reopening the project (the rescan runs in the background). if roots_changed || key == "files" || key.starts_with("files.") { - let affected = affected(); + let mut affected = affected(); + // A workspace open in another window may hold this project: its excluded folders apply there. + if roots_changed + && project_scope + && let Some(own) = ¤t + { + affected.extend(host.projects().into_iter().filter(|p| p.member_excludes.read().contains_key(&own.root))); + } host.runtime.spawn_blocking(move || { for project in affected { project.refresh_index_scope(); diff --git a/crates/ide-host/src/ops/routes.rs b/crates/ide-host/src/ops/routes.rs index 3d6f2e1ce..00cf1f990 100644 --- a/crates/ide-host/src/ops/routes.rs +++ b/crates/ide-host/src/ops/routes.rs @@ -70,15 +70,14 @@ fn scan_roots(root: &Path, content_roots: Vec) -> Vec { /// Every mapping source of the project, for the request-path index. pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult> { let project = host.project(window)?; - let excludes = project.search_excludes(); let mut out = Vec::new(); for root in scan_roots(&project.root, project.content_roots()) { - out.extend(sources_in(&root, &excludes)); + out.extend(sources_in(&root, &project.search_excludes_in(&root))); } out.sort_by(|a, b| a.path.cmp(&b.path)); out.dedup_by(|a, b| a.path == b.path); match out.len() { - 0 => tracing::warn!("spring routes: no mapping source under {:?} (excludes: {})", project.root, excludes.len()), + 0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root), n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root), } Ok(out) diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs index ce118ee6d..c340b19d2 100644 --- a/crates/ide-host/src/ops/search.rs +++ b/crates/ide-host/src/ops/search.rs @@ -123,6 +123,10 @@ pub(crate) fn search_project( if let Some(prefix) = &prefix { remaining.include = rebase_masks(&query.include, prefix); remaining.exclude = rebase_masks(&query.exclude, prefix); + // An attached project's own excluded folders: the project's were rebased away. + if !query.include_excluded && project.member_excludes.read().contains_key(dir) { + remaining.exclude.extend(project.search_excludes_in(dir)); + } // Only paths elsewhere were asked for. if remaining.include.is_empty() && !query.include.is_empty() { continue; diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index b200b85ea..c8ba4ddaf 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -47,6 +47,8 @@ pub struct Project { pub structure: Arc, /// Roots auto-detected from build files; see [`Project::roots`]. pub detected_roots: Arc>>, + /// The excluded folders of the workspace's other projects; see [`member_excludes`]. + pub(crate) member_excludes: MemberExcludes, /// Per-project cache directory (build tool sync results…). pub cache_dir: PathBuf, /// Superseded launch snapshots retained until this project session ends. @@ -121,7 +123,8 @@ impl Host { } let settings = SettingsStore::load(&self.config_dir, Some(&root)); let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root))); - let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read()); + let member_excludes: MemberExcludes = Arc::new(RwLock::new(member_excludes(&settings, &root))); + let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read(), &member_excludes.read()); let build_cache = self.local_data_dir.join("cache").join(project_key(&root)).join("build"); let extra_roots = content_roots(&settings.effective(), &root, &build_cache, trusted.load(Ordering::Acquire)); mark("roots"); @@ -145,7 +148,7 @@ impl Host { let index = ProjectIndex::open( &root, &self.local_data_dir.join("index").join(&project_key), - index_roots(&root, extra_roots.clone()), + index_roots(&root, extra_roots.clone(), &settings.effective(), &member_excludes.read()), excludes.clone(), languages.clone(), self.syntax(), @@ -385,6 +388,7 @@ impl Host { let sink = sink.clone(); let root = root.clone(); let detected_roots = detected_roots.clone(); + let member_excludes = member_excludes.clone(); let history = history.clone(); let remote = self.remote.clone(); let runtime = self.runtime.clone(); @@ -447,12 +451,15 @@ impl Host { 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), + exclude_globs(&root, &effective, &fresh, &members), ); *detected_roots.write() = fresh; sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() }); @@ -569,9 +576,10 @@ impl Host { let content_watchers = extra_roots .iter() .filter_map(|r| { + let globs = root_globs(&settings.effective(), &member_excludes.read(), r); let w = content_root_watcher( r, - &excludes, + globs.as_deref().unwrap_or(&excludes), &sink, &index, &documents, @@ -625,6 +633,7 @@ impl Host { structure: Arc::new(StructureService::new(syntax.clone())), syntax, detected_roots, + member_excludes, cache_dir: self.local_data_dir.join("cache").join(&project_key), java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new( self.local_data_dir.join("cache").join(&project_key).join("build"), @@ -851,6 +860,7 @@ impl Host { structure: Arc::new(StructureService::new(syntax.clone())), syntax, detected_roots: Arc::default(), + member_excludes: Arc::default(), cache_dir: self.local_data_dir.join("cache").join(&project_key), java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new( self.local_data_dir.join("cache").join(&project_key).join("build"), @@ -1244,8 +1254,23 @@ impl Project { /// excluded roots, the ignored names and the "Exclude files" patterns (files, /// and everything under such folders). pub fn search_excludes(&self) -> Vec { - let mut out: Vec = - self.roots().excluded_globs().iter().map(|d| format!("{}/**", d.trim_start_matches('/'))).collect(); + let mut folders = self.roots().excluded_globs(); + folders.extend(nested_member_globs(&self.root, &self.member_excludes.read())); + self.search_masks(&folders) + } + + /// [`Self::search_excludes`] for paths below `dir` (the project folder or a content root), + /// relative to it: an attached project's own excluded folders apply there, not this project's. + pub fn search_excludes_in(&self, dir: &Path) -> Vec { + let own = self.member_excludes.read().get(dir).cloned(); + match own { + Some(own) => self.search_masks(&own), + None => self.search_excludes(), + } + } + + fn search_masks(&self, folders: &[String]) -> Vec { + let mut out: Vec = folders.iter().map(|d| format!("{}/**", d.trim_start_matches('/'))).collect(); let settings = self.settings.effective(); let names = settings.files.ignored_names.iter().cloned().chain(settings.project_structure.exclude_file_patterns()); @@ -1277,7 +1302,7 @@ impl Project { let Some(root) = root else { return ide_lsp::CandidateFiles::default(); }; - let mut exclude = self.search_excludes(); + let mut exclude = self.search_excludes_in(&root); // Directories the server analyses fully: their files are never read. exclude.extend(q.skip.iter().filter_map(|dir| { let rel = dir.strip_prefix(&root).ok()?.to_str()?.replace('\\', "/"); @@ -1296,7 +1321,23 @@ impl Project { /// `files.exclude`, the ignored names and the effective excluded roots (user-marked and detected). pub fn exclude_globs(&self) -> Vec { - exclude_globs(&self.root, &self.settings.effective(), &self.detected_roots.read()) + exclude_globs(&self.root, &self.settings.effective(), &self.detected_roots.read(), &self.member_excludes.read()) + } + + /// The exclude globs below `dir` (the project folder or a content root), relative to it: a + /// project attached to this one has its own excluded folders, the other roots share these. + pub fn exclude_globs_in(&self, dir: &Path) -> Vec { + let own = root_globs(&self.settings.effective(), &self.member_excludes.read(), dir); + own.unwrap_or_else(|| self.exclude_globs()) + } + + /// Where `path`'s exclusions are matched from: the workspace project outside this one holding + /// it, else the project folder (whose globs cover the projects inside it, anchored there). + pub fn root_of(&self, path: &Path) -> PathBuf { + let members = self.member_excludes.read(); + let outside = members.keys().filter(|r| !r.starts_with(&self.root) && path.starts_with(r)); + let member = outside.max_by_key(|r| r.components().count()); + member.cloned().unwrap_or_else(|| self.root.clone()) } /// Project Structure content roots besides the project folder (existing directories). @@ -1321,6 +1362,7 @@ impl Project { if self.light { return; } + *self.member_excludes.write() = member_excludes(&self.settings, &self.root); let (roots, excludes) = (self.content_roots(), self.exclude_globs()); self.lsp.set_content_roots(language_server_roots(&self.root, roots.clone())); self.lsp.set_jdtls_import_roots(ide_build::maven_external_roots( @@ -1329,12 +1371,16 @@ impl Project { &self.settings.effective().languages.java.maven, self.is_trusted(), )); - self.index.set_scope(index_roots(&self.root, roots.clone()), excludes.clone()); + let settings = self.settings.effective(); + self.index.set_scope( + index_roots(&self.root, roots.clone(), &settings, &self.member_excludes.read()), + excludes.clone(), + ); self.watcher.set_excludes(&excludes); let mut watchers = self.content_watchers.lock(); watchers.retain(|(p, _)| roots.contains(p)); - for (_, w) in watchers.iter() { - w.set_excludes(&excludes); + for (p, w) in watchers.iter() { + w.set_excludes(&self.exclude_globs_in(p)); } for r in roots { if watchers.iter().any(|(p, _)| *p == r) { @@ -1342,7 +1388,7 @@ impl Project { } if let Some(w) = content_root_watcher( &r, - &excludes, + &self.exclude_globs_in(&r), &self.sink, &self.index, &self.documents, @@ -1426,10 +1472,68 @@ pub fn history_retention(settings: &ide_core::settings::Settings) -> ide_workspa } /// Only explicit workspace containers exclude their root from indexed content. -fn index_roots(root: &Path, folders: Vec) -> ide_index::IndexRoots { +fn index_roots( + root: &Path, + folders: Vec, + settings: &ide_core::settings::Settings, + members: &BTreeMap>, +) -> ide_index::IndexRoots { let container = ide_workspace::workspace::Workspace::load(root).ok().flatten().is_some_and(|w| w.is_container(root)); - ide_index::IndexRoots { include_root: !container, folders: folders.into_iter().filter(|p| p != root).collect() } + let folders: Vec = folders.into_iter().filter(|p| p != root).collect(); + let excludes = folders.iter().filter_map(|f| Some((f.clone(), root_globs(settings, members, f)?))).collect(); + ide_index::IndexRoots { include_root: !container, folders, excludes } +} + +/// Excluded folders (as `/`-anchored globs) by workspace project. +type MemberExcludes = Arc>>>; + +/// The excluded folders of the workspace's projects besides `root`, each from its own Project +/// Structure settings and build files (as when it is opened alone), relative to its folder. +fn member_excludes(settings: &SettingsStore, root: &Path) -> BTreeMap> { + let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(root) else { return BTreeMap::new() }; + // A workspace folder is no project of its own: its excluded folders apply in every member. + let shared = match workspace.is_container(root) { + true => linked_roots(root, &settings.effective(), &[]).excluded_globs(), + false => Vec::new(), + }; + workspace + .projects + .into_iter() + .filter(|p| p != root && p.is_dir()) + .map(|p| { + let own = settings.for_project(&p).effective(); + let mut globs = shared.clone(); + globs.extend(linked_roots(&p, &own, &ide_workspace::roots::detect(&p)).excluded_globs()); + (p, globs) + }) + .collect() +} + +/// The exclude globs below the workspace project `dir`: the ignored names and "Exclude files" +/// patterns apply everywhere, excluded folders only in the project that marked them. +fn root_globs( + settings: &ide_core::settings::Settings, + members: &BTreeMap>, + dir: &Path, +) -> Option> { + let own = members.get(dir)?; + let mut globs = settings.file_excludes(); + globs.extend(own.iter().cloned()); + Some(globs) +} + +/// The excluded folders of the workspace projects inside `root` (those its walk covers), +/// anchored at `root`. +fn nested_member_globs(root: &Path, members: &BTreeMap>) -> Vec { + let mut out = Vec::new(); + for (dir, own) in members { + if let Ok(rel) = dir.strip_prefix(root) { + let rel = rel.to_string_lossy().replace('\\', "/"); + out.extend(own.iter().map(|g| format!("/{rel}{g}"))); + } + } + out } /// The member roots of an explicit workspace container (empty for a plain @@ -1828,9 +1932,15 @@ fn linked_roots(root: &Path, settings: &ide_core::settings::Settings, detected: ProjectRoots::compute(detected, &settings.project_structure) } -fn exclude_globs(root: &Path, settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> Vec { +fn exclude_globs( + root: &Path, + settings: &ide_core::settings::Settings, + detected: &[SourceFolder], + members: &BTreeMap>, +) -> Vec { let mut globs = settings.file_excludes(); globs.extend(linked_roots(root, settings, detected).excluded_globs()); + globs.extend(nested_member_globs(root, members)); globs } @@ -2316,7 +2426,8 @@ mod composer_tests { #[cfg(test)] mod content_roots_tests { - use super::content_roots; + use super::{SettingsStore, content_roots, exclude_globs, member_excludes, root_globs}; + use std::path::Path; #[test] #[cfg(windows)] @@ -2405,4 +2516,46 @@ mod content_roots_tests { // ... while its files go to a language server of its own. assert_eq!(super::language_server_roots(&root, roots), vec![other, nested]); } + + #[test] + fn each_workspace_project_excludes_its_own_folders() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let (config, root, nested, other) = + (base.join("config"), base.join("app"), base.join("app/mod"), base.join("lib")); + for dir in [&nested, &other] { + std::fs::create_dir_all(dir).unwrap(); + } + let store = |dir: &Path| SettingsStore::load(&config, Some(dir)); + let exclude = |dir: &Path, folders: serde_json::Value| { + store(dir) + .set(ide_workspace::settings::SettingsScope::Project, "projectStructure.excluded", folders) + .unwrap(); + }; + exclude(&root, serde_json::json!(["target"])); + exclude(&nested, serde_json::json!(["out"])); + exclude(&other, serde_json::json!(["gen/"])); + assert!(member_excludes(&store(&root), &root).is_empty(), "a plain project has no members"); + + ide_workspace::workspace::Workspace::attach(&root, "app", vec![root.clone(), nested.clone(), other.clone()]) + .unwrap(); + let members = member_excludes(&store(&root), &root); + assert_eq!(members[&other], ["/gen"]); + let settings = store(&root).effective(); + let globs = exclude_globs(&root, &settings, &[], &members); + // The project's own folders, and those of the project its walk covers, anchored there. + assert!(globs.contains(&"/target".to_owned()) && globs.contains(&"/mod/out".to_owned())); + assert!(!globs.contains(&"/gen".to_owned())); + let own = root_globs(&settings, &members, &other).unwrap(); + assert!(own.contains(&"/gen".to_owned()) && !own.contains(&"/target".to_owned())); + assert_eq!(root_globs(&settings, &members, &root), None, "the project folder has the project's"); + + // A workspace folder's own excluded folders apply in every member, as before. + let ws = base.join("ws"); + ide_workspace::workspace::Workspace::save(&ws, "ws", vec![root.clone(), other.clone()], true).unwrap(); + exclude(&ws, serde_json::json!(["dist"])); + let members = member_excludes(&store(&ws), &ws); + assert_eq!(members[&other], ["/dist", "/gen"]); + assert_eq!(members[&root], ["/dist", "/target"]); + } } diff --git a/crates/ide-host/tests/attached_excludes.rs b/crates/ide-host/tests/attached_excludes.rs new file mode 100644 index 000000000..cda04fa3e --- /dev/null +++ b/crates/ide-host/tests/attached_excludes.rs @@ -0,0 +1,114 @@ +//! Each project of a workspace keeps its own excluded folders: they apply below that project only. +use ide_core::{NullSink, RequestId}; +use ide_host::{Host, HostConfig, ops}; +use ide_workspace::settings::SettingsScope; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +fn host(base: &Path) -> Host { + Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(NullSink)), + owner: |window| window, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }) +} + +/// Files containing `needle` that Find in Files reports, by path. +async fn found(host: &Host) -> Vec { + let hits = Arc::new(Mutex::new(Vec::new())); + let out = hits.clone(); + let query = serde_json::from_value(serde_json::json!({"pattern": "needle", "isRegex": false, "caseSensitive": false, "wholeWord": false, "include": [], "exclude": [], "scope": {"kind": "project"}, "maxMatches": 100})).unwrap(); + let channel = ops::Channel::new(move |event| { + if let ops::search::SearchEvent::File { file } = event { + out.lock().unwrap().push(file.path.0); + } + }); + ops::search::search_start(host, "main", RequestId::next(), query, channel).await.unwrap(); + let mut paths = std::mem::take(&mut *hits.lock().unwrap()); + paths.sort(); + paths +} + +/// The folders of `dir` the Project view shows as excluded. +async fn excluded(host: &Host, dir: &Path) -> Vec { + let entries = ops::fs::fs_read_dir(host, "main", dir.to_path_buf()).await.unwrap(); + entries.into_iter().filter(|e| e.excluded).map(|e| e.name).collect() +} + +fn indexed(host: &Host, name: &str) -> Vec { + let project = host.project("main").unwrap(); + assert!(project.index.wait_idle(Duration::from_secs(20))); + project.index.files_named(name) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn attached_projects_keep_their_own_excluded_folders() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let (app, lib) = (base.join("app"), base.join("lib")); + // Both projects have a `gen` and a `dist` folder. + for root in [&app, &lib] { + for dir in ["gen", "dist", "src"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + std::fs::write(root.join(dir).join(format!("{dir}.txt")), "needle\n").unwrap(); + } + } + let config = base.join("config"); + // `lib` excluded its `dist` when it was opened on its own. + ide_workspace::SettingsStore::load(&config, Some(&lib)) + .set(SettingsScope::Project, "projectStructure.excluded", serde_json::json!(["dist"])) + .unwrap(); + ide_workspace::workspace::Workspace::attach(&app, "app", vec![app.clone(), lib.clone()]).unwrap(); + + let host = host(&base); + host.trust.decide(&app, true, false).unwrap(); + host.trust.decide(&lib, true, false).unwrap(); + host.open_project("main", &app).unwrap(); + ops::project::set_settings(&host, "main", SettingsScope::Project, "projectStructure.excluded", r#"["gen"]"#) + .unwrap(); + host.project("main").unwrap().refresh_index_scope(); + + let expect = |paths: &[&str]| paths.iter().map(|p| base.join(p)).collect::>(); + // `app` excludes its `gen`, `lib` its `dist`: neither reaches into the other project. + assert_eq!( + found(&host).await, + expect(&["app/dist/dist.txt", "app/src/src.txt", "lib/gen/gen.txt", "lib/src/src.txt"]) + ); + assert_eq!(excluded(&host, &app).await, ["gen"]); + assert_eq!(excluded(&host, &lib).await, ["dist"]); + assert_eq!(indexed(&host, "gen.txt"), expect(&["lib/gen/gen.txt"])); + assert_eq!(indexed(&host, "dist.txt"), expect(&["app/dist/dist.txt"])); + + // `lib` changes its exclusions in its own window: the workspace follows. + host.open_project("lib", &lib).unwrap(); + ops::project::set_settings(&host, "lib", SettingsScope::Project, "projectStructure.excluded", "[]").unwrap(); + let project = host.project("main").unwrap(); + for _ in 0..100 { + if project.exclude_globs_in(&lib).iter().all(|g| g != "/dist") { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(excluded(&host, &lib).await.is_empty()); + assert_eq!(indexed(&host, "dist.txt"), expect(&["app/dist/dist.txt", "lib/dist/dist.txt"])); + ops::project::set_settings(&host, "lib", SettingsScope::Project, "projectStructure.excluded", r#"["dist"]"#) + .unwrap(); + host.shutdown().await; + + // Reopened: each project's exclusions come back from its own settings. + let host = self::host(&base); + host.open_project("main", &app).unwrap(); + assert_eq!( + found(&host).await, + expect(&["app/dist/dist.txt", "app/src/src.txt", "lib/gen/gen.txt", "lib/src/src.txt"]) + ); + assert_eq!(indexed(&host, "dist.txt"), expect(&["app/dist/dist.txt"])); + host.shutdown().await; +} diff --git a/crates/ide-index/src/filter.rs b/crates/ide-index/src/filter.rs index bf4dffaf9..b12f7b82f 100644 --- a/crates/ide-index/src/filter.rs +++ b/crates/ide-index/src/filter.rs @@ -30,6 +30,8 @@ struct ExtraRoot { path: PathBuf, /// Shown before the paths inside it (`shared-lib/src/x.rs`). name: String, + /// Its own exclude globs (an attached project's); `None` shares the project's. + excludes: Option, } /// Whether an ignore-aware content walk of `root` leaves out `dir` or an ancestor. @@ -55,6 +57,32 @@ pub fn walk_skips(root: &Path, dir: &Path) -> bool { !walker.flatten().any(|e| e.path() == dir) } +/// Exclude globs as gitignore reads them: a leading `/` anchors at the root, a bare name matches at any depth. +fn glob_set(exclude_globs: &[String]) -> GlobSet { + let mut set = GlobSetBuilder::new(); + for raw in exclude_globs { + let p = raw.trim().trim_end_matches('/'); + let anchored = p.starts_with('/'); + let p = p.trim_start_matches("./").trim_start_matches('/'); + if p.is_empty() { + continue; + } + let mut patterns = vec![p.to_owned()]; + if !anchored && !p.contains('/') { + patterns.push(format!("**/{p}")); + } + for pat in patterns { + match GlobBuilder::new(&pat).literal_separator(true).build() { + Ok(g) => { + set.add(g); + } + Err(e) => tracing::warn!("invalid exclude glob {raw:?}: {e}"), + } + } + } + set.build().unwrap_or_else(|_| GlobSet::empty()) +} + fn rel_string(rel: &Path) -> String { let mut out = String::new(); for c in rel.components() { @@ -93,28 +121,7 @@ pub(crate) fn mtime_of(meta: &std::fs::Metadata) -> u64 { impl PathFilter { pub(crate) fn new(root: &Path, extra_roots: &crate::IndexRoots, exclude_globs: &[String]) -> Self { - let mut set = GlobSetBuilder::new(); - for raw in exclude_globs { - let p = raw.trim().trim_end_matches('/'); - let anchored = p.starts_with('/'); - let p = p.trim_start_matches("./").trim_start_matches('/'); - if p.is_empty() { - continue; - } - let mut patterns = vec![p.to_owned()]; - if !anchored && !p.contains('/') { - patterns.push(format!("**/{p}")); - } - for pat in patterns { - match GlobBuilder::new(&pat).literal_separator(true).build() { - Ok(g) => { - set.add(g); - } - Err(e) => tracing::warn!("invalid exclude glob {raw:?}: {e}"), - } - } - } - let excludes = set.build().unwrap_or_else(|_| GlobSet::empty()); + let excludes = glob_set(exclude_globs); let mut extra: Vec = Vec::new(); for r in &extra_roots.folders { let path = dunce::canonicalize(r).unwrap_or_else(|_| r.clone()); @@ -130,7 +137,8 @@ impl PathFilter { Ok(rel) if extra_roots.include_root => rel_string(rel), _ => path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), }; - extra.push(ExtraRoot { name, path }); + let excludes = extra_roots.excludes.get(r).map(|globs| glob_set(globs)); + extra.push(ExtraRoot { name, path, excludes }); } Self { root: root.to_owned(), @@ -159,6 +167,13 @@ impl PathFilter { stamp.push_str(exclude); stamp.push('\n'); } + for (folder, excludes) in &self.config.0.excludes { + stamp.push_str(&format!("-- {}\n", folder.to_string_lossy())); + for exclude in excludes { + stamp.push_str(exclude); + stamp.push('\n'); + } + } stamp } @@ -229,8 +244,9 @@ impl PathFilter { }) } - fn excluded_rel(&self, rel: &str) -> bool { - self.excludes.is_match(rel) + /// The exclude globs below `base` (a root): its own, or the project's. + fn excludes_of(&self, base: &Path) -> &GlobSet { + self.extra.iter().find(|e| e.path == base).and_then(|e| e.excludes.as_ref()).unwrap_or(&self.excludes) } fn skip_name(name: &str) -> bool { @@ -245,6 +261,7 @@ impl PathFilter { if rel.is_empty() { return true; } + let excludes = self.excludes_of(base); let mut prefix = String::new(); for seg in rel.split('/') { if Self::skip_name(seg) { @@ -254,7 +271,7 @@ impl PathFilter { prefix.push('/'); } prefix.push_str(seg); - if self.excluded_rel(&prefix) { + if excludes.is_match(&prefix) { return true; } } @@ -268,8 +285,8 @@ impl PathFilter { if dir != root && self.is_excluded(dir) { return None; } + let excludes = self.excludes_of(root).clone(); let root = root.to_path_buf(); - let excludes = self.excludes.clone(); let extra: Vec = self.extra.iter().filter(|e| e.path != dir).map(|e| e.path.clone()).collect(); let mut builder = WalkBuilder::new(dir); builder.standard_filters(false).follow_links(false).filter_entry(move |e| { @@ -524,6 +541,34 @@ src/local/ assert!(!filter.same_config(&vec![shared].into(), &["target".into()])); } + #[test] + fn each_root_applies_its_own_excluded_folders() { + let dir = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(dir.path()).unwrap(); + let (root, attached, shared) = (base.join("app"), base.join("lib"), base.join("shared")); + for f in ["app/target/a.rs", "app/gen/b.rs", "lib/target/c.rs", "lib/gen/d.rs", "shared/target/e.rs"] { + touch(&base, f); + } + let roots = crate::IndexRoots { + include_root: true, + folders: vec![attached.clone(), shared.clone()], + excludes: [(attached.clone(), vec!["/gen".to_owned()])].into(), + }; + let filter = PathFilter::new(&root, &roots, &["/target".into()]); + let mut found: Vec = filter + .roots() + .flat_map(|r| filter.walk(r, &AtomicBool::new(false))) + .filter_map(|f| filter.rel(&f.path)) + .collect(); + found.sort(); + // `lib` has exclusions of its own; `shared` shares the project's. + assert_eq!(found, ["gen/b.rs", "lib/target/c.rs"]); + assert!(filter.is_excluded(&attached.join("gen/new.rs"))); + assert!(!filter.is_excluded(&root.join("gen/new.rs"))); + assert!(filter.stamp().contains("/gen")); + assert!(!filter.same_config(&vec![attached, shared].into(), &["/target".into()])); + } + #[test] fn an_ignored_folder_inside_the_root_is_a_root_with_its_own_rules() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index 2e38171ed..576659ed0 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -92,15 +92,18 @@ pub struct ProjectIndex { } /// Folders indexed alongside the internal state root. -#[derive(Clone, PartialEq)] +#[derive(Clone, Default, PartialEq)] pub struct IndexRoots { pub include_root: bool, pub folders: Vec, + /// Folders with exclude globs of their own (an attached project's), relative to the folder; + /// the other folders share the project's. + pub excludes: std::collections::BTreeMap>, } impl From> for IndexRoots { fn from(folders: Vec) -> Self { - Self { include_root: true, folders } + Self { include_root: true, folders, ..Default::default() } } } diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index d4ea41bfb..3116b9d74 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -825,7 +825,7 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() { let idx = ProjectIndex::open( &fx.root, &fx.cache, - crate::IndexRoots { include_root: false, folders: vec![member.clone()] }, + crate::IndexRoots { include_root: false, folders: vec![member.clone()], ..Default::default() }, Vec::new(), Arc::new(LanguageRegistry::load(None).unwrap()), Arc::new(Syntax::new()), @@ -841,7 +841,7 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() { assert!(idx.wait_idle(WAIT)); assert!(symbols(&idx, "hidden", SymbolFilter::All).is_empty()); assert_eq!(symbols(&idx, "visible", SymbolFilter::All), ["visible"]); - idx.set_scope(crate::IndexRoots { include_root: false, folders: Vec::new() }, Vec::new()); + idx.set_scope(crate::IndexRoots { include_root: false, folders: Vec::new(), ..Default::default() }, Vec::new()); assert!(idx.wait_idle(WAIT)); assert!(idx.find_files("", 100).is_empty()); } @@ -1104,7 +1104,7 @@ fn repository_rule_changes_refresh_members_of_an_unindexed_container() { let idx = ProjectIndex::open( &fx.root, &fx.cache, - IndexRoots { include_root: false, folders: vec![fx.root.join("member")] }, + IndexRoots { include_root: false, folders: vec![fx.root.join("member")], ..Default::default() }, vec![], Arc::new(LanguageRegistry::load(None).unwrap()), Arc::new(Syntax::new()), diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index 5cd372e9d..8053a4130 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -265,6 +265,11 @@ impl SettingsStore { store } + /// The settings of the project at `root` under the same user settings. + pub fn for_project(&self, root: &Path) -> Self { + Self::load(self.global_file.parent().unwrap_or(Path::new("")), Some(root)) + } + pub fn file(&self, scope: SettingsScope) -> Option<&Path> { match scope { SettingsScope::Global => Some(&self.global_file),