From cb7bddec1496ee83dcb28632477b9779b01cf885 Mon Sep 17 00:00:00 2001 From: tomgor <22257170@qq.com> Date: Tue, 17 Nov 2026 20:06:44 +0800 Subject: [PATCH] fix(java): show Maven-generated sources in Problems (#3944) jdtls/m2e only import source folders declared in the POM. Generators such as protobuf/gRPC, jOOQ, Avro, OpenAPI and QueryDSL add theirs with addCompileSourceRoot while the build runs, so Problems stayed red after a successful Maven compile. After a Maven project update, and after Build, Rebuild and Compile File, the IDE now scans target/generated-sources and generated-test-sources and puts those folders on the jdtls classpath through openidea.java.generatedSources (java-usages bundle 1.16.0), marked so a later scan can drop them; annotation-processor output, which jdtls compiles itself, is left out. A Maven build never starts jdtls by itself. Co-authored-by: tomgor <12905387+tomgor@users.noreply.github.com> --- crates/ide-host/src/ops/build.rs | 19 +- crates/ide-lsp/src/jdtls.rs | 51 ++- crates/ide-lsp/src/jdtls/generated.rs | 421 ++++++++++++++++++ crates/ide-lsp/tests/mock_server.rs | 51 +++ crates/ide-sdk/src/java.rs | 2 +- java/java-usages/MANIFEST.MF | 2 +- java/java-usages/README.md | 5 +- java/java-usages/openidea-java-usages.jar | Bin 172300 -> 183948 bytes java/java-usages/plugin.xml | 3 + .../sources/GeneratedSourcesCommand.java | 162 +++++++ 10 files changed, 706 insertions(+), 10 deletions(-) create mode 100644 crates/ide-lsp/src/jdtls/generated.rs create mode 100644 java/java-usages/src/ai/openidea/sources/GeneratedSourcesCommand.java diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 92e18a888..df984c74d 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -886,12 +886,19 @@ pub async fn build_run( for (path, items) in compile::diagnostics(&result.messages) { sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items }); } - Ok(result) + Ok::<_, IdeError>(result) }) .await .map_err(join_err); host.end_request(request); - result? + let outcome = result??; + // Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the + // folders the build wrote are attached. An up-to-date build skips Maven and + // still needs this: the classes can already be on disk. + if outcome.system == ide_build::compile::BuildSystem::Maven { + project.lsp.sync_maven_generated_sources(&project.root).await; + } + Ok(outcome) } /// Build › Compile File: compiles one Java source of a linked Maven module with @@ -928,12 +935,16 @@ pub async fn build_compile_file( for (path, items) in compile::diagnostics(&result.messages) { sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items }); } - Ok(result) + Ok::<_, IdeError>(result) }) .await .map_err(join_err); host.end_request(request); - result? + let outcome = result??; + if outcome.system == ide_build::compile::BuildSystem::Maven { + project.lsp.sync_maven_generated_sources(&project.root).await; + } + Ok(outcome) } #[cfg(test)] diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index d4e725ac1..fc72b5a0b 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -17,10 +17,12 @@ use std::sync::Arc; use std::time::{Duration, Instant}; pub(crate) const SERVER: &str = "jdtls"; +const GENERATED_SOURCES: &str = "openidea.java.generatedSources"; pub(crate) mod configuration; mod extract_interface; mod formatter; +mod generated; mod hierarchy; pub(crate) mod jvm_inspect; mod move_refactoring; @@ -638,6 +640,7 @@ impl LspManager { /// jdtls reports `ProjectStatus` when an import or project update ends (a POM /// change, a Maven sync, other Maven profiles), but does not check open documents /// again against the new classpath: their errors would stay until the next edit. + /// Generated Maven sources are attached first, so that recheck sees them. pub(crate) fn java_projects_updated(self: &Arc, server: Arc, generation: u64) { let uris: Vec = self .docs @@ -650,11 +653,10 @@ impl LspManager { }) .map(|d| crate::uri::path_to_uri_string(&d.path)) .collect(); - if uris.is_empty() { - return; - } + let mgr = self.clone(); self.runtime.spawn(async move { let Some(run) = server.running_gen(generation) else { return }; + mgr.sync_generated_sources(&server, &run).await; for uri in uris { let params = json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] }); @@ -668,6 +670,49 @@ impl LspManager { }); } + /// Puts Maven plugin output that already exists on disk (`target/generated-sources/...`) + /// onto the jdtls classpath. Best-effort: only a jdtls that is already running is + /// touched, so a Maven build does not start the language server by itself. + pub async fn sync_maven_generated_sources(&self, root: &Path) { + let servers: Vec<_> = self + .servers + .lock() + .iter() + .filter(|server| server.name == SERVER && server.running().is_some()) + .filter(|server| server.root == root || root.starts_with(&server.root) || server.root.starts_with(root)) + .cloned() + .collect(); + for server in servers { + let Some(run) = server.running() else { continue }; + self.sync_generated_sources(&server, &run).await; + } + } + + async fn sync_generated_sources(&self, server: &Arc, run: &Running) { + if !run.caps.read().commands().iter().any(|command| command == GENERATED_SOURCES) { + return; + } + let root = server.root.clone(); + let scan = tokio::task::spawn_blocking(move || generated::scan(&root)) + .await + .unwrap_or(generated::GeneratedScan { maven: false, roots: Vec::new() }); + if !scan.maven { + return; + } + let arguments: Vec = scan + .roots + .into_iter() + .map(|root| json!({ "path": root.path.to_string_lossy(), "test": root.test })) + .collect(); + let params = json!({ "command": GENERATED_SOURCES, "arguments": arguments }); + let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None); + if let Ok(Err(e)) | Err(e) = + tokio::time::timeout(COMMAND_TIMEOUT, request).await.map_err(|_| ide_jsonrpc::RpcError::Timeout) + { + tracing::debug!("jdtls: {GENERATED_SOURCES}: {e}"); + } + } + /// The jdtls instance serving `path` (a module directory or source file), /// started if needed and waited for. async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc, Running)> { diff --git a/crates/ide-lsp/src/jdtls/generated.rs b/crates/ide-lsp/src/jdtls/generated.rs new file mode 100644 index 000000000..81b5f1d5e --- /dev/null +++ b/crates/ide-lsp/src/jdtls/generated.rs @@ -0,0 +1,421 @@ +//! Maven plugin output that jdtls never imports. +//! +//! `protobuf-maven-plugin` and the same kind of generator call +//! `MavenProject.addCompileSourceRoot` while the build runs. That list is not in the +//! POM, so m2e never adds the folders and the editor keeps reporting missing packages +//! after a successful Maven compile. Annotation-processor output (`annotations`, +//! `test-annotations`) is left out: jdtls compiles it itself, and adding it as a source +//! folder makes the processor emit the same file twice. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +const MAX_DEPTH: usize = 16; +const MAX_JAVA_FILES: usize = 4_000; +const MAX_PARENTS: usize = 8; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct GeneratedRoot { + pub path: PathBuf, + pub test: bool, +} + +pub(crate) struct GeneratedScan { + pub maven: bool, + pub roots: Vec, +} + +/// Generated Java source folders under `root` (a reactor or one module). +pub(crate) fn scan(root: &Path) -> GeneratedScan { + let mut modules = Vec::new(); + collect_modules(root, 0, &mut modules); + let mut roots = Vec::new(); + for module in &modules { + let build = build_dir(module); + collect_tree(&build.join("generated-sources"), false, &mut roots); + collect_tree(&build.join("generated-test-sources"), true, &mut roots); + } + roots.sort(); + roots.dedup(); + GeneratedScan { maven: !modules.is_empty(), roots } +} + +fn collect_modules(dir: &Path, depth: usize, modules: &mut Vec) { + if depth > MAX_DEPTH { + return; + } + let has_pom = dir.join("pom.xml").is_file(); + if has_pom { + modules.push(dir.to_path_buf()); + } + let build_name = has_pom.then(|| build_dir(dir)).and_then(|dir| dir.file_name().map(|name| name.to_os_string())); + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let Ok(kind) = entry.file_type() else { continue }; + if !kind.is_dir() || kind.is_symlink() { + continue; + } + let name = entry.file_name(); + let shown = name.to_string_lossy(); + if shown.starts_with('.') || shown == "node_modules" || shown == "target" { + continue; + } + if build_name.as_ref().is_some_and(|build| build == &name) { + continue; + } + collect_modules(&entry.path(), depth + 1, modules); + } +} + +fn collect_tree(tree: &Path, test: bool, roots: &mut Vec) { + let mut files = Vec::new(); + walk_java(tree, 0, &mut files); + let mut found = HashSet::new(); + for file in files { + let Some(package) = package_name(&read_head(&file)) else { continue }; + let Some(root) = source_root(&file, &package) else { continue }; + if root.starts_with(tree) && found.insert(root.clone()) { + roots.push(GeneratedRoot { path: root, test }); + } + } +} + +fn walk_java(dir: &Path, depth: usize, files: &mut Vec) { + if depth > MAX_DEPTH || files.len() >= MAX_JAVA_FILES { + return; + } + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + if files.len() >= MAX_JAVA_FILES { + return; + } + let Ok(kind) = entry.file_type() else { continue }; + if kind.is_symlink() { + continue; + } + let path = entry.path(); + if kind.is_dir() { + // The compiler's own output. jdtls already consumes it as annotation processing. + if depth == 0 && matches!(entry.file_name().to_str(), Some("annotations" | "test-annotations")) { + continue; + } + walk_java(&path, depth + 1, files); + } else if kind.is_file() && path.extension().is_some_and(|ext| ext == "java") { + files.push(path); + } + } +} + +fn read_head(path: &Path) -> String { + let Ok(bytes) = std::fs::read(path) else { return String::new() }; + let head = &bytes[..bytes.len().min(4096)]; + String::from_utf8_lossy(head).into_owned() +} + +/// The `package` declaration, ignoring comments that precede it. +fn package_name(text: &str) -> Option { + let mut rest = text; + loop { + let trimmed = rest.trim_start(); + if let Some(after) = trimmed.strip_prefix("//") { + rest = after.split_once('\n').map(|(_, next)| next).unwrap_or(""); + continue; + } + if let Some(after) = trimmed.strip_prefix("/*") { + rest = after.split_once("*/").map(|(_, next)| next).unwrap_or(""); + continue; + } + let after = trimmed.strip_prefix("package")?; + if !after.starts_with(|c: char| c.is_whitespace()) { + return None; + } + let after = after.trim_start(); + let end = after.find([';', '{', '\n', '\r', ' ', '\t', '/']).unwrap_or(after.len()); + let name = after[..end].trim(); + if name.is_empty() || !name.split('.').all(java_identifier) { + return None; + } + return Some(name.to_owned()); + } +} + +fn java_identifier(segment: &str) -> bool { + let mut chars = segment.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') +} + +/// Directory that is the source root for `file` declaring `package`. +fn source_root(file: &Path, package: &str) -> Option { + let mut dir = file.parent()?.to_path_buf(); + for segment in package.split('.').rev() { + if dir.file_name().and_then(|n| n.to_str()) != Some(segment) { + return None; + } + dir.pop(); + } + Some(dir) +} + +fn build_dir(module: &Path) -> PathBuf { + let mut pom = module.join("pom.xml"); + let mut seen = HashSet::new(); + for _ in 0..MAX_PARENTS { + if !seen.insert(pom.clone()) { + break; + } + let Ok(text) = std::fs::read_to_string(&pom) else { break }; + let text = strip_comments(&text); + if let Some(raw) = own_build_directory(&text) { + let rel = relative_build_dir(&raw).unwrap_or_else(|| "target".to_owned()); + return module.join(rel); + } + let Some(parent) = parent_pom(pom.parent().unwrap_or(module), &text) else { break }; + pom = parent; + } + module.join("target") +} + +fn own_build_directory(pom: &str) -> Option { + let build = section(pom, "build")?; + let own = plugins_removed(build); + section(&own, "directory").map(str::to_owned) +} + +fn parent_pom(dir: &Path, pom: &str) -> Option { + let parent = section(pom, "parent")?; + let rel = match relative_path(parent) { + Some(value) if value.trim().is_empty() => return None, + Some(value) => value.trim(), + None => "../pom.xml", + }; + if rel.contains("${") || rel.starts_with(['/', '\\']) || rel.contains(':') { + return None; + } + let path = dir.join(rel); + path.is_file().then_some(path) +} + +/// `` text, or `Some("")` for a self-closing `` (no local parent). +fn relative_path(parent: &str) -> Option<&str> { + if let Some(value) = section(parent, "relativePath") { + return Some(value); + } + ["", ""].iter().any(|tag| parent.contains(tag)).then_some("") +} + +fn relative_build_dir(raw: &str) -> Option { + let mut value = raw.trim(); + for prefix in ["${project.basedir}", "${basedir}"] { + if let Some(rest) = value.strip_prefix(prefix) { + value = rest.trim_start_matches(['/', '\\']); + } + } + if value.is_empty() + || value.contains("${") + || value.contains("..") + || value.starts_with(['/', '\\']) + || value.contains(':') + { + return None; + } + Some(value.replace('\\', "/")) +} + +fn strip_comments(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(start) = rest.find("").map_or("", |end| &rest[start + end + 3..]); + } + out.push_str(rest); + out +} + +fn section<'a>(text: &'a str, tag: &str) -> Option<&'a str> { + let open = format!("<{tag}>"); + let start = text.find(&open)? + open.len(); + let end = text[start..].find(&format!(""))?; + Some(&text[start..start + end]) +} + +fn plugins_removed(build: &str) -> String { + let mut text = build.to_owned(); + for tag in ["plugins", "pluginManagement"] { + let (open, close) = (format!("<{tag}>"), format!("")); + let mut kept = String::with_capacity(text.len()); + let mut rest = text.as_str(); + while let Some(start) = rest.find(&open) { + kept.push_str(&rest[..start]); + rest = rest[start..].find(&close).map_or("", |end| &rest[start + end + close.len()..]); + } + kept.push_str(rest); + text = kept; + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(root: &Path, rel: &str, text: &str) { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + fn grpc(root: &Path) { + write(root, "pom.xml", "app"); + write( + root, + "target/generated-sources/protobuf/java/com/example/hello/Hello.java", + "package com.example.hello;\npublic class Hello {}", + ); + write( + root, + "target/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java", + "/* generated */\npackage com.example.hello;\npublic class HelloGrpc {}", + ); + write( + root, + "target/generated-sources/annotations/com/example/hello/HelloMapperImpl.java", + "package com.example.hello;\nclass HelloMapperImpl {}", + ); + } + + #[test] + fn protobuf_and_grpc_roots_are_kept_and_annotation_output_is_not() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + grpc(root); + let scan = scan(root); + assert!(scan.maven); + assert_eq!( + scan.roots, + vec![ + GeneratedRoot { path: root.join("target/generated-sources/protobuf/grpc-java"), test: false }, + GeneratedRoot { path: root.join("target/generated-sources/protobuf/java"), test: false }, + ] + ); + } + + #[test] + fn comments_before_the_package_and_test_sources() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write(root, "pom.xml", ""); + write( + root, + "target/generated-test-sources/protobuf/java/com/example/hello/HelloTest.java", + "// package ignored.nope;\n/* package also.nope; */\npackage com.example.hello;\nclass HelloTest {}", + ); + write( + root, + "target/generated-test-sources/test-annotations/com/example/hello/Skip.java", + "package com.example.hello;\nclass Skip {}", + ); + write( + root, + "target/generated-sources/protobuf/java/com/example/Wrong.java", + "package com.other;\nclass Wrong {}", + ); + let scan = scan(root); + assert_eq!( + scan.roots, + vec![GeneratedRoot { path: root.join("target/generated-test-sources/protobuf/java"), test: true }] + ); + } + + #[test] + fn custom_build_directory_ignores_plugin_configuration_and_inherits_from_the_parent() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write( + root, + "pom.xml", + r#"outapp"#, + ); + write( + root, + "app/pom.xml", + r#" + gp1 + + nope + ${project.basedir}/custom + + "#, + ); + write( + root, + "lib/pom.xml", + "gp1", + ); + write( + root, + "app/custom/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java", + "package com.example.hello;\nclass HelloGrpc {}", + ); + write( + root, + "lib/out/generated-sources/protobuf/java/com/example/hello/Hello.java", + "package com.example.hello;\nclass Hello {}", + ); + write( + root, + "lib/target/generated-sources/protobuf/java/com/example/hello/Stale.java", + "package com.example.hello;\nclass Stale {}", + ); + let scan = scan(root); + let paths: Vec<_> = scan.roots.iter().map(|r| r.path.clone()).collect(); + assert_eq!( + paths, + vec![ + root.join("app/custom/generated-sources/protobuf/grpc-java"), + root.join("lib/out/generated-sources/protobuf/java"), + ] + ); + } + + #[test] + fn an_empty_relative_path_does_not_inherit_the_parent_build_directory() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write(root, "pom.xml", "out"); + write( + root, + "app/pom.xml", + "gp1", + ); + write( + root, + "app/target/generated-sources/protobuf/java/com/example/hello/Hello.java", + "package com.example.hello;\nclass Hello {}", + ); + write( + root, + "app/out/generated-sources/protobuf/java/com/example/hello/Other.java", + "package com.example.hello;\nclass Other {}", + ); + let scan = scan(root); + assert_eq!( + scan.roots, + vec![GeneratedRoot { path: root.join("app/target/generated-sources/protobuf/java"), test: false }] + ); + } + + #[test] + fn a_project_without_maven_is_not_a_scan() { + let tmp = tempfile::tempdir().unwrap(); + write( + tmp.path(), + "target/generated-sources/protobuf/java/com/example/hello/Hello.java", + "package com.example.hello;\nclass Hello {}", + ); + let scan = scan(tmp.path()); + assert!(!scan.maven); + assert!(scan.roots.is_empty()); + } +} diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 498a37197..43f81d90d 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -2943,6 +2943,57 @@ async fn open_java_files_are_checked_again_after_a_project_update() { eventually(|| refreshed() == expected).await; } +#[tokio::test(flavor = "multi_thread")] +async fn a_project_update_attaches_maven_generated_sources_before_rechecking() { + let mut caps = incremental_caps(); + caps["executeCommandProvider"]["commands"].as_array_mut().unwrap().push(json!("openidea.java.generatedSources")); + let h = harness_for("java", "java", &[("jdtls", caps)], &[]); + let (_, _) = h.open("App.java", "package com.example;\nclass App {}"); + h.wait_status("jdtls", ServerStatus::Ready).await; + let write = |rel: &str, text: &str| { + let path = h.root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + }; + write("pom.xml", "app"); + write( + "target/generated-sources/protobuf/java/com/example/hello/Hello.java", + "package com.example.hello;\npublic class Hello {}", + ); + write( + "target/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java", + "package com.example.hello;\npublic class HelloGrpc {}", + ); + write( + "target/generated-sources/annotations/com/example/hello/HelloMapperImpl.java", + "package com.example.hello;\nclass HelloMapperImpl {}", + ); + let state = h.launcher.state("jdtls"); + state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap(); + eventually(|| { + let requests = state.requested("workspace/executeCommand"); + let generated = requests.iter().position(|p| p["command"] == "openidea.java.generatedSources"); + let refresh = requests.iter().position(|p| p["command"] == "java.project.refreshDiagnostics"); + matches!((generated, refresh), (Some(generated), Some(refresh)) if generated < refresh) + }) + .await; + let requests = state.requested("workspace/executeCommand"); + let generated = requests.iter().find(|p| p["command"] == "openidea.java.generatedSources").unwrap(); + let paths: Vec<_> = generated["arguments"] + .as_array() + .unwrap() + .iter() + .map(|arg| (arg["path"].as_str().unwrap().to_owned(), arg["test"].as_bool().unwrap())) + .collect(); + assert_eq!( + paths, + vec![ + (h.root.join("target/generated-sources/protobuf/grpc-java").to_string_lossy().into_owned(), false), + (h.root.join("target/generated-sources/protobuf/java").to_string_lossy().into_owned(), false), + ] + ); +} + #[tokio::test(flavor = "multi_thread")] async fn library_classes_in_jars_open_as_their_source_or_decompiled() { use std::io::Write; diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 889c43935..b6ee57400 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1614,7 +1614,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.15.0", + "1.16.0", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index b4ed35585..8380d7f7b 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA Java usages Bundle-SymbolicName: ai.openidea.usages;singleton:=true -Bundle-Version: 1.15.0 +Bundle-Version: 1.16.0 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core, org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime, diff --git a/java/java-usages/README.md b/java/java-usages/README.md index a842d0dcd..f0d724a2d 100644 --- a/java/java-usages/README.md +++ b/java/java-usages/README.md @@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity. ## Rebuild and delivery The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as -`java-usages-1.15.0.jar`, and added alongside existing initialization bundles. +`java-usages-1.16.0.jar`, and added alongside existing initialization bundles. Users need no compiler, Maven or Python. Manifest/install version must change when replacing the bundle because OSGi caches bundles. @@ -136,6 +136,9 @@ Version 1.12.0 caches usages answers until the Java model or an unsaved edit cha Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an implementation in a dependency declares (the standard request starts at its class file); its reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`. +Version 1.16.0 adds `openidea.java.generatedSources`, which puts Maven plugin output such as +protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is +`a5feda1cae11bdea1044fb311404840b048601af037f65685973721f1eefff8b`. ```sh export PATH=/path/to/jdk25/bin:$PATH diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index 98d9c9b086248db24634a8ed8293e5c483ca93c9..a5dff7a48e864401a9c6368d1ef67ba77394aaeb 100644 GIT binary patch delta 6720 zcmbVR33yc3b^gzr<;^@jAt5255!w-Wv?E~)7}hbH1ro@JO=2CSXAnplp&8lWCBtSH zx7Y?o_y)|T*hZ~QFt`CUCJ^B?apKg4c&i&yFWsD^Zer{>NnK*)+&3e(*e&kpo8_K+ z?zw0A&$;J5?RZ(+aUd?KcDBVj1kqRS(vL3WDZ7%+Qsw50Coj^pgCYC2x8CTt0rFkR zT)yTqf4kAv++_I50{+g9Mk7!*(`Yj~d_kkBE=ri{Z*BFpHRac}8;zxnExthD)h}K; z$BVs~tU@7-x@9S9OpLhuRdT8AzTg@{j@aCyB;%lBT)1yoVR+Bxhbdopim8xypRq-VE5)>@V&%i1 zEWB?7Am8P;6lLK(L_-Uy*^K8c=o8*-TWPQH&YL}bUU=}X!n@K2P*l45M)VMDHQt5O z=QuEkkn8VQU1~J8G`9zg($)&2w9((eKYaHZZ54BT!OjjN{H`tCo~$DQiK5m`L&TuN zw1r$^*J0Y9Ovu!cg>04?U>^hsd16@-r6qL+n_J4Nn*+h|8gemQWqR3mDzoHcgz#;r ziO$|Y6#_7Mxi`B#j(^r8h5C;U95b7T;ZJ# zC$m>#j5z-&O%$W@l$7uVOSWYKCWbF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eneratedSourcesCommand.java new file mode 100644 index 000000000..54ebb4e67 --- /dev/null +++ b/java/java-usages/src/ai/openidea/sources/GeneratedSourcesCommand.java @@ -0,0 +1,162 @@ +package ai.openidea.sources; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.IClasspathAttribute; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; + +/** + * Adds Maven plugin output (protobuf, gRPC, jOOQ, …) as source folders. + * + *

The argument is {@code [{path, test}, …]}: absolute directories the build already + * generated. Folders this command added are marked {@code openidea.generatedSource} and + * dropped again when they are no longer in that list, so a later reload does not keep a + * source folder Maven has cleaned. Entries m2e or build-helper already created are left + * as they are. + */ +public final class GeneratedSourcesCommand implements IDelegateCommandHandler { + static final String MARKER = "openidea.generatedSource"; + private static final String MAVEN = "org.eclipse.m2e.core.maven2Nature"; + + private record Spec(IPath path, boolean test) {} + + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + List specs = specs(arguments); + IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects(); + int changed = 0; + for (IJavaProject project : projects) { + if (monitor.isCanceled()) throw new OperationCanceledException(); + if (!isMaven(project)) continue; + if (sync(project, owned(projects, project, specs), monitor)) changed++; + } + return changed; + } + + private static List specs(List arguments) { + List specs = new ArrayList<>(); + if (arguments == null) return specs; + for (Object argument : arguments) { + if (!(argument instanceof Map map)) continue; + if (!(map.get("path") instanceof String path) || path.isBlank()) continue; + specs.add(new Spec(Path.fromOSString(path), Boolean.TRUE.equals(map.get("test")))); + } + return specs; + } + + /** Specs whose longest Maven project prefix is `project`. A reactor parent also prefixes its modules. */ + private static List owned(IJavaProject[] projects, IJavaProject project, List specs) { + IPath location = project.getProject().getLocation(); + List owned = new ArrayList<>(); + if (location == null) return owned; + for (Spec spec : specs) { + if (!location.isPrefixOf(spec.path)) continue; + IJavaProject best = project; + int segments = location.segmentCount(); + for (IJavaProject other : projects) { + if (other == project || !isMaven(other)) continue; + IPath otherLocation = other.getProject().getLocation(); + if (otherLocation != null && otherLocation.isPrefixOf(spec.path) + && otherLocation.segmentCount() > segments) { + best = other; + segments = otherLocation.segmentCount(); + } + } + if (best == project) owned.add(spec); + } + return owned; + } + + private static boolean sync(IJavaProject project, List specs, IProgressMonitor monitor) { + try { + IPath location = project.getProject().getLocation(); + if (location == null) return false; + Map wanted = new LinkedHashMap<>(); + for (Spec spec : specs) { + if (monitor.isCanceled()) throw new OperationCanceledException(); + IPath relative = spec.path.makeRelativeTo(location); + if (relative.isAbsolute() || relative.segmentCount() == 0) continue; + IFolder folder = project.getProject().getFolder(relative); + refresh(folder, monitor); + if (folder.exists()) wanted.put(project.getPath().append(relative), spec.test); + } + IClasspathEntry[] raw = project.getRawClasspath(); + List next = new ArrayList<>(); + boolean changed = false; + for (IClasspathEntry entry : raw) { + if (!marked(entry)) { + next.add(entry); + continue; + } + if (wanted.containsKey(entry.getPath())) next.add(entry); + else changed = true; + } + for (Map.Entry entry : wanted.entrySet()) { + if (hasSource(next, entry.getKey())) continue; + IClasspathAttribute[] attributes = entry.getValue() + ? new IClasspathAttribute[] { + JavaCore.newClasspathAttribute(IClasspathAttribute.TEST, "true"), + JavaCore.newClasspathAttribute(MARKER, "true") + } + : new IClasspathAttribute[] { JavaCore.newClasspathAttribute(MARKER, "true") }; + next.add(JavaCore.newSourceEntry(entry.getKey(), new IPath[0], new IPath[0], null, attributes)); + changed = true; + } + if (!changed) return false; + project.setRawClasspath(next.toArray(IClasspathEntry[]::new), monitor); + return true; + } catch (CoreException | OperationCanceledException e) { + JavaLanguageServerPlugin.logException("Adding generated Maven sources to " + project.getElementName(), e); + return false; + } + } + + private static void refresh(IFolder folder, IProgressMonitor monitor) throws CoreException { + IResource resource = folder; + while (resource.getType() != IResource.ROOT && !resource.exists()) { + IResource parent = resource.getParent(); + if (parent == null) return; + resource = parent; + } + resource.refreshLocal(IResource.DEPTH_INFINITE, monitor); + } + + private static boolean marked(IClasspathEntry entry) { + if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) return false; + for (IClasspathAttribute attribute : entry.getExtraAttributes()) { + if (MARKER.equals(attribute.getName()) && "true".equals(attribute.getValue())) return true; + } + return false; + } + + private static boolean hasSource(List entries, IPath path) { + for (IClasspathEntry entry : entries) { + if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && entry.getPath().equals(path)) return true; + } + return false; + } + + private static boolean isMaven(IJavaProject project) { + IProject resource = project.getProject(); + try { + return resource.isAccessible() && resource.hasNature(MAVEN); + } catch (CoreException e) { + return false; + } + } +}