mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
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>
This commit is contained in:
@@ -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)]
|
||||
|
||||
@@ -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<Self>, server: Arc<Server>, generation: u64) {
|
||||
let uris: Vec<String> = 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<Server>, 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<Value> = 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<Server>, Running)> {
|
||||
|
||||
@@ -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<GeneratedRoot>,
|
||||
}
|
||||
|
||||
/// 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<PathBuf>) {
|
||||
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<GeneratedRoot>) {
|
||||
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<PathBuf>) {
|
||||
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<String> {
|
||||
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<PathBuf> {
|
||||
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<String> {
|
||||
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<PathBuf> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// `<relativePath>` text, or `Some("")` for a self-closing `<relativePath/>` (no local parent).
|
||||
fn relative_path(parent: &str) -> Option<&str> {
|
||||
if let Some(value) = section(parent, "relativePath") {
|
||||
return Some(value);
|
||||
}
|
||||
["<relativePath/>", "<relativePath />"].iter().any(|tag| parent.contains(tag)).then_some("")
|
||||
}
|
||||
|
||||
fn relative_build_dir(raw: &str) -> Option<String> {
|
||||
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("<!--") {
|
||||
out.push_str(&rest[..start]);
|
||||
rest = rest[start..].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!("</{tag}>"))?;
|
||||
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!("</{tag}>"));
|
||||
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", "<project><artifactId>app</artifactId></project>");
|
||||
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", "<project/>");
|
||||
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#"<project><build><directory>out</directory></build><modules><module>app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project>
|
||||
<parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version></parent>
|
||||
<build>
|
||||
<plugins><plugin><configuration><directory>nope</directory></configuration></plugin></plugins>
|
||||
<directory>${project.basedir}/custom</directory>
|
||||
</build>
|
||||
</project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/pom.xml",
|
||||
"<project><parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version></parent></project>",
|
||||
);
|
||||
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", "<project><build><directory>out</directory></build></project>");
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
"<project><parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version><relativePath/></parent></project>",
|
||||
);
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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", "<project><artifactId>app</artifactId></project>");
|
||||
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;
|
||||
|
||||
@@ -1614,7 +1614,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.15.0",
|
||||
"1.16.0",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
Binary file not shown.
@@ -20,6 +20,9 @@
|
||||
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
|
||||
<command id="openidea.java.refreshArchives"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.sources.GeneratedSourcesCommand">
|
||||
<command id="openidea.java.generatedSources"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
|
||||
<command id="openidea.java.implementationLocations"/>
|
||||
</delegateCommandHandler>
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
List<Spec> 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<Spec> specs(List<Object> arguments) {
|
||||
List<Spec> 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<Spec> owned(IJavaProject[] projects, IJavaProject project, List<Spec> specs) {
|
||||
IPath location = project.getProject().getLocation();
|
||||
List<Spec> 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<Spec> specs, IProgressMonitor monitor) {
|
||||
try {
|
||||
IPath location = project.getProject().getLocation();
|
||||
if (location == null) return false;
|
||||
Map<IPath, Boolean> 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<IClasspathEntry> 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<IPath, Boolean> 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<IClasspathEntry> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user