From 90f9d4ffd0dd6188d19513377294af0f569d4967 Mon Sep 17 00:00:00 2001 From: rolicon <37171528+rolicon@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:02:56 +0800 Subject: [PATCH] feat(java): project-level Maven compile goals to ignore (#7479) A goal bound to the compile phase that local runs don't need (maven-jar-plugin:jar and the like) made the build fall back from the built-in incremental javac to Maven. languages.java.maven.ignoredCompileGoals lists exact groupId:artifactId:goal entries to skip in that decision; the default empty list keeps the old behaviour, and Gradle, dependency and compiler checks are unchanged. Covered by a real Maven reactor test and documented in the Java build README. Co-authored-by: rolicon <37171528+rolicon@users.noreply.github.com> --- crates/ide-build/src/jbuild/mod.rs | 4 +- crates/ide-build/src/jbuild/model.rs | 19 ++- crates/ide-build/src/jbuild/tests.rs | 122 ++++++++++++++++-- crates/ide-core/src/settings.rs | 2 + crates/ide-host/src/ops/java.rs | 1 + crates/ide-workspace/src/settings.rs | 30 +++++ java/java-build/README.md | 20 +++ src/bindings.ts | 2 + .../settings/__tests__/languages.test.ts | 9 ++ src/platform/languageSettings.ts | 4 + 10 files changed, 201 insertions(+), 12 deletions(-) diff --git a/crates/ide-build/src/jbuild/mod.rs b/crates/ide-build/src/jbuild/mod.rs index da7cd4c44..31a79aff9 100644 --- a/crates/ide-build/src/jbuild/mod.rs +++ b/crates/ide-build/src/jbuild/mod.rs @@ -79,6 +79,8 @@ pub struct JavaBuild<'a> { /// Changes when the jar does, so models recorded by an older extension are prepared again. pub jar_version: &'a str, pub local_repo: Option, + /// Explicit Maven goals the project's settings allow the IDE to skip in compile phases. + pub ignored_maven_compile_goals: &'a [String], pub service: &'a JavaBuildService, /// The JDK home that compiles for a release, when Maven's environment names none. pub jdk: &'a (dyn Fn(Option) -> Option + Sync), @@ -558,7 +560,7 @@ impl JavaBuild<'_> { } }; for (project, test) in &projects { - if let Some(reason) = project.unsupported(*test) { + if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) { return Ok(Built::Unsupported(reason)); } // A launch of a Java module runs it from the module path, which the language server reports. diff --git a/crates/ide-build/src/jbuild/model.rs b/crates/ide-build/src/jbuild/model.rs index dfafe407f..3a8d904d1 100644 --- a/crates/ide-build/src/jbuild/model.rs +++ b/crates/ide-build/src/jbuild/model.rs @@ -105,13 +105,26 @@ impl ProjectModel { } /// Why the IDE can't compile this project with javac itself, if it can't. - pub fn unsupported(&self, test: bool) -> Option { + pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option { // What the build tool couldn't resolve or read: the model would be incomplete. if let Some(problem) = self.problems.first() { return Some(format!("{}: {problem}", self.artifact_id)); } - if !self.other_compilers.is_empty() { - return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", "))); + // Keep the recorded model intact: adding or removing a project override must also + // affect an already prepared model. Gradle tasks never use Maven overrides. + let other_compilers: Vec<&str> = self + .other_compilers + .iter() + .filter(|execution| { + !(self.gradle_path.is_none() + && execution.split_once('@').is_some_and(|(goal, _)| { + ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal) + })) + }) + .map(String::as_str) + .collect(); + if !other_compilers.is_empty() { + return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", "))); } if test && !self.test_generators.is_empty() { return Some(format!( diff --git a/crates/ide-build/src/jbuild/tests.rs b/crates/ide-build/src/jbuild/tests.rs index 9fec5b1ef..6d3e8f803 100644 --- a/crates/ide-build/src/jbuild/tests.rs +++ b/crates/ide-build/src/jbuild/tests.rs @@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() { assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ"); } +#[test] +fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() { + let goal = "org.apache.maven.plugins:maven-jar-plugin:jar"; + let project = ProjectModel { + artifact_id: "app".into(), + other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")], + ..Default::default() + }; + let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap(); + assert!(cached.unsupported(false, &[]).unwrap().contains(goal)); + assert_eq!(cached.unsupported(false, &[goal.into()]), None); + assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None); + assert!(cached.unsupported(false, &[]).unwrap().contains(goal)); + assert_eq!(cached.other_compilers, project.other_compilers); +} + +#[test] +fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() { + let jar = "org.apache.maven.plugins:maven-jar-plugin:jar"; + let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile"; + let mut project = ProjectModel { + artifact_id: "app".into(), + other_compilers: vec![format!("{jar}@default-jar")], + ..Default::default() + }; + for unmatched in [ + "", + "*", + "org.apache.maven.plugins:maven-jar-plugin", + "maven-jar-plugin:jar", + "org.apache.maven.plugins:maven-jar-plugin:test-jar", + "org.apache.maven.plugins:*:jar", + ] { + assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}"); + } + project.other_compilers.push(format!("{kotlin}@compile")); + let reason = project.unsupported(false, &[jar.into()]).unwrap(); + assert!(reason.contains(kotlin)); + assert!(!reason.contains(jar)); +} + +#[test] +fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() { + let goal = "org.apache.maven.plugins:maven-jar-plugin:jar"; + let ignored = [goal.into()]; + let mut project = ProjectModel { + artifact_id: "app".into(), + other_compilers: vec![format!("{goal}@default-jar")], + ..Default::default() + }; + project.gradle_path = Some(":app".into()); + assert!(project.unsupported(false, &ignored).is_some()); + project.gradle_path = None; + project.problems.push("unresolved dependency".into()); + assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency")); + project.problems.clear(); + project.test_generators.push("org.example:generator:test@tests".into()); + assert_eq!(project.unsupported(false, &ignored), None); + assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources")); + project.test_generators.clear(); + project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() }); + assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse")); + project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() }); + assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release")); + project.main.compiler = + Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() }); + assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor")); +} + /// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped). fn tools() -> Option<(PathBuf, PathBuf)> { let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?; @@ -169,6 +238,17 @@ impl Fixture { } fn build(&self, target: Target) -> LaunchOutputs { + match self.try_build(target, &[]) { + Ok(Built::Done(outputs)) => outputs, + Ok(Built::Unsupported(reason)) => { + let output = build_output_tail(&self.events.lock().unwrap()); + panic!("unsupported: {reason}\n{output}"); + } + Err(e) => panic!("{e:?}"), + } + } + + fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult { let jdk = |_: Option| None; let build = JavaBuild { root: &self.root, @@ -177,18 +257,12 @@ impl Fixture { jar: Path::new(JAR), jar_version: "test", local_repo: None, + ignored_maven_compile_goals, service: &self.service, jdk: &jdk, }; let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e); - match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) { - Ok(Built::Done(outputs)) => outputs, - Ok(Built::Unsupported(reason)) => { - let output = build_output_tail(&self.events.lock().unwrap()); - panic!("unsupported: {reason}\n{output}"); - } - Err(e) => panic!("{e:?}"), - } + build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) } /// The steps of the launch builds since the last call. @@ -213,6 +287,37 @@ impl Fixture { } } +#[test] +fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() { + let pom = APP_POM.replace( + "", + concat!( + "org.apache.maven.plugins", + "maven-jar-plugin3.4.1", + "early-jarcompile", + "jar", + ), + ); + let Some(f) = Fixture::new(&[ + ("app/pom.xml", &pom), + ("lib/src/main/java/l/L.java", "package l; public class L {}"), + ("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"), + ]) else { + return; + }; + let module = f.root.join("app"); + let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap(); + let goal = "org.apache.maven.plugins:maven-jar-plugin:jar"; + assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal))); + f.steps(); + let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") }; + assert!(output.failure.is_none(), "{:?}", output.messages); + assert!(f.out("t.app/classes/a/A.class").is_file()); + assert!(!f.root.join("app/target/app-1.jar").exists()); + assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused"); + assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal))); +} + #[test] fn builds_maven_modules_with_javac_and_only_what_changed() { let Some(f) = Fixture::new(&[ @@ -583,6 +688,7 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() { jar: Path::new(JAR), jar_version: "test", local_repo: None, + ignored_maven_compile_goals: &[], service: &f.service, jdk: &jdk, }; diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index a4ea06bbb..291aa959b 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -2138,6 +2138,8 @@ pub struct MavenSettings { pub active_profiles: String, /// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ). pub delegate_build: bool, + /// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default. + pub ignored_compile_goals: Vec, /// Download `-sources.jar` of dependencies when the Java language server imports the /// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand /// from a library class's Download Sources banner. diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 2a8081789..9cb56469f 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -335,6 +335,7 @@ impl ServiceBuild<'_> { jar: &jar, jar_version: &version, local_repo: ide_sdk::apply::maven_local_repository(root, settings), + ignored_maven_compile_goals: &settings.languages.java.maven.ignored_compile_goals, service: self.service, jdk: &jdk, }; diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index cae24a934..3ea8eca3a 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -948,6 +948,36 @@ mod tests { assert!(SettingsStore::load(&cfg, Some(&proj)).effective().editor.custom_schemes.is_empty()); } + #[test] + fn maven_compile_goal_overrides_are_loaded_per_project_and_can_be_cleared() { + let tmp = tempfile::tempdir().unwrap(); + let cfg = tmp.path().join("cfg"); + let project = tmp.path().join("project"); + let other = tmp.path().join("other"); + std::fs::create_dir_all(project.join(".openidea")).unwrap(); + std::fs::write( + project.join(".openidea/settings.toml"), + "[languages.java.maven]\nignoredCompileGoals = [\"org.apache.maven.plugins:maven-jar-plugin:jar\"]\n", + ) + .unwrap(); + let store = SettingsStore::load(&cfg, Some(&project)); + assert_eq!( + store.effective().languages.java.maven.ignored_compile_goals, + ["org.apache.maven.plugins:maven-jar-plugin:jar"] + ); + assert!(!store.effective().languages.java.maven.delegate_build); + assert!( + SettingsStore::load(&cfg, Some(&other)).effective().languages.java.maven.ignored_compile_goals.is_empty() + ); + store + .set(SettingsScope::Global, "languages.java.maven.ignoredCompileGoals", json!(["org.example:checks:check"])) + .unwrap(); + store.set(SettingsScope::Project, "languages.java.maven.ignoredCompileGoals", json!([])).unwrap(); + assert!( + SettingsStore::load(&cfg, Some(&project)).effective().languages.java.maven.ignored_compile_goals.is_empty() + ); + } + #[test] fn the_interpreter_list_and_its_view_options_are_user_settings() { let tmp = tempfile::tempdir().unwrap(); diff --git a/java/java-build/README.md b/java/java-build/README.md index 478413296..25b1e0eb1 100644 --- a/java/java-build/README.md +++ b/java/java-build/README.md @@ -26,6 +26,26 @@ The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar h OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs, settings or generator inputs change, then compiles the launch's modules with the server. +### Ignoring Maven goals during IDE compilation + +When the project binds a goal to a compile phase and local runs can skip its output, add the +goal to the project's `.openidea/settings.toml`. For example, local runs may not need a release JAR. + +```toml +[languages.java.maven] +delegateBuild = false +ignoredCompileGoals = ["org.apache.maven.plugins:maven-jar-plugin:jar"] +``` + +The list defaults to empty. Each entry matches all executions of exactly one `groupId:artifactId:goal` +in `compile`, `process-classes`, `test-compile` or `process-test-classes`. The IDE's javac build skips +those executions. Leave out goals whose output local runs require, including bytecode enhancement, +compilation of another language and source generation. + +The IDE reads the list on every build, including builds that use a cached model. The project list +overrides the global list. Set `ignoredCompileGoals = []` to clear inherited entries. This applies +only to the IDE's Maven javac build. Dependency and resource preparation can still invoke Maven. + Gradle builds get the same model from an init script instead (`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with `-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run diff --git a/src/bindings.ts b/src/bindings.ts index 0cf9946da..5f60a106e 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -12484,6 +12484,8 @@ export type MavenSettings = { activeProfiles?: string, /** Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ). */ delegateBuild?: boolean, + /** Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default. */ + ignoredCompileGoals?: string[], /** * Download `-sources.jar` of dependencies when the Java language server imports the * project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index acaebd48c..f648abea4 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -64,6 +64,7 @@ describe("languages settings", () => { threads: "2C", activeProfiles: "", delegateBuild: false, + ignoredCompileGoals: [], downloadSources: false, updateSnapshots: false, runTestsUsing: "ide", @@ -72,6 +73,14 @@ describe("languages settings", () => { expect(validateLanguages({ java: { maven: { threads: 4 } } }).java.maven.threads).toBe(""); }); + it("preserves explicit Maven compile-goal overrides without enabling delegation", () => { + const goal = "org.apache.maven.plugins:maven-jar-plugin:jar"; + const settings = validateSettings({ languages: { java: { maven: { ignoredCompileGoals: [goal] } } } }); + expect(settings.languages.java.maven).toMatchObject({ ignoredCompileGoals: [goal], delegateBuild: false }); + expect(validateSettings(settings).languages.java.maven.ignoredCompileGoals).toEqual([goal]); + expect(validateSettings({}).languages.java.maven.ignoredCompileGoals).toEqual([]); + }); + it("defaults the Maven runner JRE to the project JDK and preserves a chosen JDK", () => { expect(validateSettings({}).languages.java.maven.runnerJre).toBe(""); expect(validateSettings({}).languages.java.maven.delegateBuild).toBe(false); diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index a3639d58b..ed0ab9680 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -262,6 +262,8 @@ export interface LanguagesValid { activeProfiles: string; /** Delegate IDE build/run actions to Maven (`javac`) instead of jdtls (ECJ). */ delegateBuild: boolean; + /** Exact Maven goals the IDE may skip in compile phases. */ + ignoredCompileGoals: string[]; /** Download dependencies' `-sources.jar` when jdtls imports the project. */ downloadSources: boolean; /** Always update snapshots: `-U` on Maven runs, `java.maven.updateSnapshots` for jdtls. */ @@ -381,6 +383,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = { threads: "", activeProfiles: "", delegateBuild: false, + ignoredCompileGoals: [], downloadSources: false, updateSnapshots: false, runTestsUsing: "ide", @@ -612,6 +615,7 @@ export function validateLanguages(raw: unknown): LanguagesValid { threads: text(maven.threads, d.java.maven.threads), activeProfiles: text(maven.activeProfiles, d.java.maven.activeProfiles), delegateBuild: bool(maven.delegateBuild, d.java.maven.delegateBuild), + ignoredCompileGoals: strings(maven.ignoredCompileGoals), downloadSources: bool(maven.downloadSources, d.java.maven.downloadSources), updateSnapshots: bool(maven.updateSnapshots, d.java.maven.updateSnapshots), runTestsUsing: oneOf(maven.runTestsUsing, ["ide", "maven"] as const, d.java.maven.runTestsUsing),