diff --git a/crates/ide-build/src/jbuild/mod.rs b/crates/ide-build/src/jbuild/mod.rs index ba2a0a65d6..5c7cbfb342 100644 --- a/crates/ide-build/src/jbuild/mod.rs +++ b/crates/ide-build/src/jbuild/mod.rs @@ -113,12 +113,15 @@ impl JavaBuildService { let had_state = previous.is_some(); let previous = previous.unwrap_or_default(); + let force_canonical: HashSet = set.force.iter().filter_map(|p| dunce::canonicalize(p).ok()).collect(); let mut changed: BTreeSet = source_stamps .iter() .filter(|(path, stamp)| { previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || set.force.contains(*path) + || (!force_canonical.is_empty() + && dunce::canonicalize(path).ok().is_some_and(|c| force_canonical.contains(&c))) }) .map(|(path, _)| path.clone()) .collect(); @@ -507,42 +510,111 @@ fn ant_match(pattern: &str, path: &str) -> bool { segments(&p, &s) } -/// The `.java` files of a source set, filtered by the compiler's includes and excludes. +/// The `.java` files of a source set, filtered by the compiler's includes and excludes. A file +/// reached through several links is listed once: javac 8 fails on a class named twice, and newer +/// ones record a single source for it, whose removal would leave the other spelling uncompiled. +/// Deduplication runs after includes/excludes so an excluded alias cannot hide a valid path, and +/// prefers a path that passes through no symlink over a linked one. fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult> { let config = set.compiler.as_ref(); let includes = config.map(|c| c.includes.as_slice()).unwrap_or_default(); let excludes = config.map(|c| c.excludes.as_slice()).unwrap_or_default(); - let mut out = Vec::new(); - let mut seen = HashSet::new(); + let mut kept: HashMap = HashMap::new(); for root in &set.source_roots { if model::is_processor_output(set, root) || !root.is_dir() { continue; } - let mut pending = vec![root.clone()]; - while let Some(dir) = pending.pop() { - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); + walk_files(root, cancel, &mut |path, canonical, via_link| { + if path.extension().is_none_or(|e| e != "java") { + return; } - let Ok(entries) = std::fs::read_dir(&dir) else { continue }; - for entry in entries.flatten() { - let path = entry.path(); - let Ok(kind) = entry.file_type() else { continue }; - if kind.is_dir() { - pending.push(path); - } else if path.extension().is_some_and(|e| e == "java") { - let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); - let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel)); - if included && !excludes.iter().any(|p| ant_match(p, &rel)) && seen.insert(path.clone()) { - out.push(path); + let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); + let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel)); + if !included || excludes.iter().any(|p| ant_match(p, &rel)) { + return; + } + match kept.entry(canonical) { + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert((path, via_link)); + } + std::collections::hash_map::Entry::Occupied(mut slot) => { + if slot.get().1 && !via_link { + slot.insert((path, false)); } } } - } + })?; } + let mut out: Vec = kept.into_values().map(|(path, _)| path).collect(); out.sort(); Ok(out) } +/// Reports the files under `root` with their canonical paths and whether the path passed through +/// any symlink, following links to folders: a module can link a shared source folder into its own, +/// and Maven's resources plugin copies through such links too. Files keep the spelling under +/// `root`, so javac's messages and the debugger name the path the user opened. Only links back to +/// an ancestor on the current descent path (cycles) are skipped. Each folder is read in full +/// before its subfolders, so a deep tree holds one open directory at a time; real entries come +/// before links, by name, so the walk order does not depend on the file system's order. +fn walk_files(root: &Path, cancel: &CancellationToken, found: &mut dyn FnMut(PathBuf, PathBuf, bool)) -> IdeResult<()> { + type DirEntry = (bool, std::ffi::OsString, PathBuf, bool); + struct Frame { + canonical: std::rc::Rc, + via_link: bool, + entries: std::vec::IntoIter, + } + + fn read_sorted_entries(dir: &Path, cancel: &CancellationToken) -> IdeResult>> { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Ok(read) = std::fs::read_dir(dir) else { return Ok(None) }; + let mut entries: Vec = read + .flatten() + .filter_map(|e| { + let kind = e.file_type().ok()?; + Some((kind.is_symlink(), e.file_name(), e.path(), kind.is_dir())) + }) + .collect(); + entries.sort(); + Ok(Some(entries.into_iter())) + } + + let Ok(canonical) = dunce::canonicalize(root) else { return Ok(()) }; + let via_link = std::fs::symlink_metadata(root).is_ok_and(|m| m.file_type().is_symlink()); + let Some(entries) = read_sorted_entries(root, cancel)? else { return Ok(()) }; + + let root_canonical = std::rc::Rc::new(canonical); + let mut ancestors: HashSet> = HashSet::from([std::rc::Rc::clone(&root_canonical)]); + let mut stack = vec![Frame { canonical: root_canonical, via_link, entries }]; + + while let Some(frame) = stack.last_mut() { + let Some((linked, name, path, is_dir)) = frame.entries.next() else { + let done = stack.pop().expect("top frame"); + ancestors.remove(&done.canonical); + continue; + }; + let (is_dir, real) = if linked { + let (Ok(meta), Ok(target)) = (std::fs::metadata(&path), dunce::canonicalize(&path)) else { continue }; + (meta.is_dir(), target) + } else { + (is_dir, frame.canonical.join(&name)) + }; + let entry_via_link = frame.via_link || linked; + if !is_dir { + found(path, real, entry_via_link); + } else if !ancestors.contains(&real) + && let Some(children) = read_sorted_entries(&path, cancel)? + { + let real = std::rc::Rc::new(real); + ancestors.insert(std::rc::Rc::clone(&real)); + stack.push(Frame { canonical: real, via_link: entry_via_link, entries: children }); + } + } + Ok(()) +} + /// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always /// compiles with `-g`: breakpoints need line numbers and local variables, whatever /// maven-compiler-plugin's `` / `` ask of Maven's own build (#7786). @@ -1241,21 +1313,11 @@ fn remove_classes(dir: &Path) { fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult> { let mut out = BTreeMap::new(); for root in &set.resources { - let mut pending = vec![root.directory.clone()]; - while let Some(dir) = pending.pop() { - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); + walk_files(&root.directory, cancel, &mut |path, _, _| { + if let Some(stamp) = file_stamp(&path) { + out.insert(path, stamp); } - let Ok(entries) = std::fs::read_dir(&dir) else { continue }; - for entry in entries.flatten() { - let path = entry.path(); - if entry.file_type().is_ok_and(|t| t.is_dir()) { - pending.push(path); - } else if let Some(stamp) = file_stamp(&path) { - out.insert(path, stamp); - } - } - } + })?; } Ok(out) } @@ -1265,27 +1327,15 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult IdeResult> { let mut out = BTreeSet::new(); for root in &set.resources { - let mut pending = vec![root.directory.clone()]; - while let Some(dir) = pending.pop() { - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); + walk_files(&root.directory, cancel, &mut |path, _, _| { + let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/"); + let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel)); + if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) { + return; } - let Ok(entries) = std::fs::read_dir(&dir) else { continue }; - for entry in entries.flatten() { - let path = entry.path(); - if entry.file_type().is_ok_and(|t| t.is_dir()) { - pending.push(path); - continue; - } - let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/"); - let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel)); - if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) { - continue; - } - let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/"); - out.insert(set.output.join(target.trim_matches('/')).join(&rel)); - } - } + let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/"); + out.insert(set.output.join(target.trim_matches('/')).join(&rel)); + })?; } Ok(out) } diff --git a/crates/ide-build/src/jbuild/tests.rs b/crates/ide-build/src/jbuild/tests.rs index 05ed1b0712..e04013fdef 100644 --- a/crates/ide-build/src/jbuild/tests.rs +++ b/crates/ide-build/src/jbuild/tests.rs @@ -819,3 +819,314 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() { Err(e) => panic!("{e:?}"), } } + +/// The `.java` files `java_sources` lists for one source root. +#[cfg(unix)] +fn sources_of(root: &Path) -> Vec { + let set = SourceSet { source_roots: vec![root.to_path_buf()], ..Default::default() }; + java_sources(&set, &CancellationToken::new()).unwrap() +} + +#[cfg(unix)] +#[test] +fn java_sources_follow_directory_links_and_keep_the_linked_spelling() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let root = base.join("app/src/main/java"); + write(&root, "a/A.java", "package a;\nclass A {}\n"); + write(&base, "shared/b/B.java", "package b;\npublic class B {}\n"); + write(&base, "shared/b/c/C.java", "package b.c;\npublic class C {}\n"); + symlink(base.join("shared/b"), root.join("b")).unwrap(); + // A link to a file was already listed; it stays listed. + write(&base, "shared/D.java", "package d;\npublic class D {}\n"); + fs::create_dir_all(root.join("d")).unwrap(); + symlink(base.join("shared/D.java"), root.join("d/D.java")).unwrap(); + // A broken link is skipped. + symlink(base.join("missing"), root.join("gone")).unwrap(); + // javac and the debugger get the path the user opened, not the link's target. + assert_eq!( + sources_of(&root), + [root.join("a/A.java"), root.join("b/B.java"), root.join("b/c/C.java"), root.join("d/D.java")] + ); +} + +#[cfg(unix)] +#[test] +fn java_sources_stop_at_link_cycles() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let root = base.join("src"); + write(&root, "a/A.java", "package a;\nclass A {}\n"); + write(&base, "shared/b/B.java", "package b;\npublic class B {}\n"); + symlink(&root, root.join("a/up")).unwrap(); + symlink(".", root.join("a/here")).unwrap(); + symlink(base.join("shared/b"), root.join("b")).unwrap(); + symlink(base.join("shared"), base.join("shared/b/back")).unwrap(); + assert_eq!(sources_of(&root), [root.join("a/A.java"), root.join("b/B.java")]); +} + +#[cfg(unix)] +#[test] +fn java_sources_follow_links_that_share_a_folder() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + write(&base, "shared/s/S.java", "package s;\npublic class S {}\n"); + let shared = base.join("shared/s"); + // Each module links the same folder into its own sources: every one of them compiles it. + let (one, two) = (base.join("one/src"), base.join("two/src")); + for root in [&one, &two] { + fs::create_dir_all(root).unwrap(); + symlink(&shared, root.join("s")).unwrap(); + } + assert_eq!(sources_of(&one), [one.join("s/S.java")]); + assert_eq!(sources_of(&two), [two.join("s/S.java")]); + // Within one source set a file reached through two links is listed once, real entries before links, then by name. + let three = base.join("three/src"); + fs::create_dir_all(three.join("x")).unwrap(); + symlink(&shared, three.join("s")).unwrap(); + symlink(&shared, three.join("x/s")).unwrap(); + assert_eq!(sources_of(&three), [three.join("x/s/S.java")]); +} + +#[cfg(unix)] +#[test] +fn java_sources_list_a_file_reached_through_two_paths_once() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("src"); + write(&root, "p/C.java", "package p;\npublic class C {}\n"); + symlink(root.join("p"), root.join("alias")).unwrap(); + symlink(root.join("p/C.java"), root.join("C.java")).unwrap(); + // The real folder comes before the links to it. + assert_eq!(sources_of(&root), [root.join("p/C.java")]); +} + +#[test] +fn java_sources_match_each_nested_root_against_its_own_paths() { + // Without links the listing is what it was before links were followed: a file the outer + // root's relative path excludes is still listed through the inner root. + let tmp = tempfile::tempdir().unwrap(); + let outer = dunce::canonicalize(tmp.path()).unwrap(); + let inner = outer.join("inner"); + write(&outer, "inner/X.java", "class X {}\n"); + write(&outer, "Y.java", "class Y {}\n"); + let set = SourceSet { + source_roots: vec![outer.clone(), inner.clone()], + compiler: Some(CompilerConfig { excludes: vec!["inner/**".into()], ..Default::default() }), + ..Default::default() + }; + assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [outer.join("Y.java"), inner.join("X.java")]); +} + +#[test] +fn java_sources_find_a_file_deep_in_plain_folders() { + // Iterative walk with one folder open at a time: avoids exhausting file descriptors under + // macOS's default limit of 256 and avoids overflowing Windows' 1-2 MB thread stack in deep + // trees. Target 3000 levels on Windows (long paths up to 32,767 chars); on Unix, cap to the + // deepest path that fits under PATH_MAX (1024 bytes on macOS, 4096 bytes on Linux). + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let max_path_bytes: Option = if cfg!(target_os = "macos") { + Some(1020) + } else if cfg!(unix) { + Some(4090) + } else { + None + }; + let target_depth = 3000; + let depth = match max_path_bytes { + Some(limit) => target_depth.min(limit.saturating_sub(root.as_os_str().len() + "/C.java".len()) / 2), + None => target_depth, + }; + assert!(depth >= 300, "temp root too long for deep folder test: {}", root.display()); + + let mut dir = root.clone(); + for _ in 0..depth { + dir.push("d"); + fs::create_dir(&dir).unwrap(); + } + let file = dir.join("C.java"); + fs::write(&file, "class C {}\n").unwrap(); + + let set = SourceSet { source_roots: vec![root], ..Default::default() }; + let found = java_sources(&set, &CancellationToken::new()).unwrap(); + + // Remove iteratively so deep trees don't rely on recursive directory removal. + fs::remove_file(&file).unwrap(); + for _ in 0..depth { + fs::remove_dir(&dir).unwrap(); + dir.pop(); + } + assert_eq!(found, [file]); +} + +#[cfg(unix)] +#[test] +fn compiles_the_other_spelling_when_the_kept_link_goes() { + use std::os::unix::fs::symlink; + let Some(f) = Fixture::new(&[ + ("app/src/main/java/a/A.java", "package a;\nclass A { p.C c; }\n"), + ("shared/p/C.java", "package p;\npublic class C {}\n"), + ]) else { + return; + }; + let java = f.root.join("app/src/main/java"); + symlink(f.root.join("shared/p"), java.join("p")).unwrap(); + symlink(f.root.join("shared/p"), java.join("z")).unwrap(); + f.steps_of_launch(); + let class = f.out("t.app/classes/p/C.class"); + assert!(class.is_file()); + + // The class keeps its source through the link that is left. + fs::remove_file(java.join("p")).unwrap(); + let steps = f.steps_of_launch(); + assert!(class.is_file(), "C.class is gone after {steps:?}"); + assert!(f.steps_of_launch().is_empty()); +} + +#[cfg(unix)] +#[test] +fn builds_and_recompiles_sources_under_a_linked_folder() { + let Some(f) = Fixture::new(&[ + ("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new b.B().b(); } }\n"), + ("shared/b/B.java", "package b;\npublic class B { public int b() { return 1; } }\n"), + ]) else { + return; + }; + std::os::unix::fs::symlink(f.root.join("shared/b"), f.root.join("app/src/main/java/b")).unwrap(); + let steps = f.steps_of_launch(); + assert!(steps.contains(&"javac app (main, 2 files)".to_owned()), "{steps:?}"); + assert!(f.steps_of_launch().is_empty()); + + // An edit behind the link is seen through it. + f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return 2; } }\n"); + assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]); + + // Errors name the file as it sits under the source root. + f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return \"\"; } }\n"); + let failed = f.launch(false); + let error = failed.messages.iter().find(|m| m.severity == Severity::Error).expect("an error"); + assert_eq!( + error.path.as_deref(), + Some(f.root.join("app/src/main/java/b/B.java").as_path()), + "{:?}", + failed.messages + ); +} + +#[cfg(unix)] +#[test] +fn resources_under_a_linked_folder_are_copied_refreshed_and_pruned() { + let Some(f) = + Fixture::new(&[("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"), ("shared/r/x.txt", "one\n")]) + else { + return; + }; + fs::create_dir_all(f.root.join("app/src/main/resources")).unwrap(); + std::os::unix::fs::symlink(f.root.join("shared/r"), f.root.join("app/src/main/resources/r")).unwrap(); + assert_eq!(f.launch(false).failure, None); + assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "one\n"); + + // An edit behind the link reaches the copy the launch reads. + f.write("shared/r/x.txt", "two\n"); + let steps = f.steps_of_launch(); + assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}"); + assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "two\n"); + + // So does a file deleted behind it. + fs::remove_file(f.root.join("shared/r/x.txt")).unwrap(); + f.steps_of_launch(); + assert!(!f.out("t.app/classes/r/x.txt").exists(), "the removed resource stays on the classpath"); +} + +#[cfg(unix)] +#[test] +fn java_sources_keep_a_valid_link_when_an_earlier_alias_is_excluded() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let root = base.join("src/main/java"); + write(&base, "shared/one/p/C.java", "package p;\npublic class C {}\n"); + fs::create_dir_all(&root).unwrap(); + symlink(base.join("shared/one"), root.join("a")).unwrap(); + symlink(base.join("shared/one"), root.join("z")).unwrap(); + let set = SourceSet { + source_roots: vec![root.clone()], + compiler: Some(CompilerConfig { excludes: vec!["a/**".into()], ..Default::default() }), + ..Default::default() + }; + assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [root.join("z/p/C.java")]); +} + +#[cfg(unix)] +#[test] +fn excluded_link_alias_does_not_drop_compiled_classes() { + use std::os::unix::fs::symlink; + let pom = APP_POM.replace( + "", + concat!( + "maven-compiler-plugin", + "a/**", + "", + ), + ); + let Some(f) = Fixture::new(&[("app/pom.xml", &pom), ("shared/one/p/C.java", "package p;\npublic class C {}\n")]) + else { + return; + }; + let java = f.root.join("app/src/main/java"); + fs::create_dir_all(&java).unwrap(); + symlink(f.root.join("shared/one"), java.join("z")).unwrap(); + f.steps_of_launch(); + let class = f.out("t.app/classes/p/C.class"); + assert!(class.is_file()); + + // Adding an excluded link to the same folder must not hide the surviving link or delete its class. + symlink(f.root.join("shared/one"), java.join("a")).unwrap(); + let steps = f.steps_of_launch(); + assert!(class.is_file(), "C.class is gone after {steps:?}"); + assert!(steps.is_empty(), "{steps:?}"); +} + +#[cfg(unix)] +#[test] +fn java_sources_prefer_a_plain_path_over_an_earlier_linked_alias() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("src/main/java"); + write(&root, "p/C.java", "package p;\npublic class C {}\n"); + fs::create_dir_all(root.join("a")).unwrap(); + symlink(root.join("p"), root.join("a/link")).unwrap(); + assert_eq!(sources_of(&root), [root.join("p/C.java")]); +} + +#[cfg(unix)] +#[test] +fn recompiles_a_single_file_through_either_the_plain_or_linked_spelling() { + use std::os::unix::fs::symlink; + let Some(f) = Fixture::new(&[("app/src/main/java/p/C.java", "package p;\npublic class C {}\n")]) else { + return; + }; + f.steps_of_launch(); + let java = f.root.join("app/src/main/java"); + assert!(f.out("t.app/classes/p/C.class").is_file()); + + // Adding a link under an earlier directory keeps the plain spelling and still lets Recompile + // hit through either spelling. + fs::create_dir_all(java.join("a")).unwrap(); + symlink(java.join("p"), java.join("a/link")).unwrap(); + let second = f.steps_of_launch(); + + f.steps(); + assert_eq!(f.build(Target::File(&java.join("p/C.java"))).failure, None); + assert_eq!(f.steps(), ["javac app (main, 1 file)"]); + + f.steps(); + assert_eq!(f.build(Target::File(&java.join("a/link/C.java"))).failure, None); + assert_eq!(f.steps(), ["javac app (main, 1 file)"]); + + assert!(second.is_empty(), "{second:?}"); +}