diff --git a/crates/ide-core/src/output_encoding.rs b/crates/ide-core/src/output_encoding.rs index 94c30e91fb..006cee7d17 100644 --- a/crates/ide-core/src/output_encoding.rs +++ b/crates/ide-core/src/output_encoding.rs @@ -170,8 +170,24 @@ pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\ import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } -allprojects { - each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' } +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +eachProject { p -> + each(p.tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' } } "; @@ -622,7 +638,7 @@ mod tests { #[test] fn gradle_script_respects_the_builds_own_file_encoding() { let s = GRADLE_FILE_ENCODING_SCRIPT; - assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}"); + assert!(s.contains("each(p.tasks.withType(JavaExec))"), "{s}"); assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}"); assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}"); assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}"); diff --git a/crates/ide-coverage/src/plan.rs b/crates/ide-coverage/src/plan.rs index 336d4c1616..a0f07c4935 100644 --- a/crates/ide-coverage/src/plan.rs +++ b/crates/ide-coverage/src/plan.rs @@ -9,7 +9,23 @@ const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage. import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } -allprojects { p -> +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +eachProject { p -> p.plugins.withId('java') { p.apply plugin: 'jacoco' each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') } @@ -582,4 +598,97 @@ mod tests { CoveragePrepared::Unsupported { .. } )); } + + /// The coverage init script on a real Gradle, with and without Isolated Projects (#8261). + /// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path). + #[test] + fn gradle_init_script_configures_each_project() { + let gradle = std::env::var_os("JAVA_HOME").and_then(|_| { + std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(std::path::PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path())) + }); + let Some(gradle) = gradle else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let version = std::process::Command::new(&gradle).arg("--version").output().unwrap(); + let version = + String::from_utf8_lossy(&version.stdout).lines().find_map(|l| l.strip_prefix("Gradle ").map(str::to_owned)); + let mut parts = version + .expect("a `Gradle x.y` line") + .trim() + .split('.') + .map(|p| p.parse::().unwrap_or(0)) + .collect::>(); + parts.resize(2, 0); + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let script = base.join("coverage.init.gradle"); + std::fs::write(&script, GRADLE_INIT).unwrap(); + for (name, props) in [ + ("plain", ""), + ( + "isolated", + "org.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n", + ), + ] { + if name == "isolated" && (parts[0], parts[1]) < (8, 8) { + // Before Gradle 8.8 the script keeps reading every project, as the plain build checked. + continue; + } + let root = base.join(name); + for (rel, text) in [ + ("gradle.properties", format!("org.gradle.daemon=false\n{props}")), + ("settings.gradle", "include 'lib'\n".to_owned()), + ("build.gradle", String::new()), + ( + "lib/build.gradle", + "plugins { id 'java' }\nrepositories { mavenCentral() }\n\ + dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'; \ + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\n\ + test { useJUnitPlatform() }\n" + .to_owned(), + ), + ( + "lib/src/main/java/l/L.java", + "package l;\npublic class L { public static int one() { return 1; } }\n".to_owned(), + ), + ( + "lib/src/test/java/l/LTest.java", + "package l;\nclass LTest { @org.junit.jupiter.api.Test void one() { L.one(); } }\n".to_owned(), + ), + ] { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + let report = root.join("lib/build/reports/jacoco/test/jacocoTestReport.xml"); + // With Isolated Projects the configuration cache is on: a miss, then a hit. + for pass in if name == "isolated" { &["miss", "hit"][..] } else { &["run"][..] } { + // Fresh test results and execution data, so each pass runs the tests under the agent. + for dir in ["lib/build/jacoco", "lib/build/test-results", "lib/build/reports"] { + let _ = std::fs::remove_dir_all(root.join(dir)); + } + let out = std::process::Command::new(&gradle) + .args(["--console=plain", "--init-script"]) + .arg(&script) + .arg(":lib:test") + .current_dir(&root) + .output() + .unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "{name} {pass}:\n{text}"); + let xml = + std::fs::read_to_string(&report).unwrap_or_else(|_| panic!("{name} {pass}: no report\n{text}")); + assert_eq!(text.contains("Reusing configuration cache."), *pass == "hit", "{name} {pass}:\n{text}"); + let method = + xml.split(r#"").next()); + assert!( + method.is_some_and(|m| m.contains(r#""#)), + "{name} {pass}: {xml}" + ); + } + } + } } diff --git a/crates/ide-run/src/gradle_jvm.rs b/crates/ide-run/src/gradle_jvm.rs index 44f90292c8..4e9875de93 100644 --- a/crates/ide-run/src/gradle_jvm.rs +++ b/crates/ide-run/src/gradle_jvm.rs @@ -21,18 +21,35 @@ fn groovy_string(s: &str) -> String { out } +const HEADER: &str = r#"// Written by OpenIDEA: VM options of the run configuration. +import org.gradle.util.GradleVersion +// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. +def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +"#; + /// The init script adding `jvm_args` (one argument each) to the forked JVMs. pub fn init_script(jvm_args: &[String]) -> String { let list = jvm_args.iter().map(|a| groovy_string(a)).collect::>().join(", "); format!( - "// Written by OpenIDEA: VM options of the run configuration.\n\ - import org.gradle.util.GradleVersion\n\ - // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\ - def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \ - tasks.configureEach(action) : tasks.all(action) }}\n\ - allprojects {{\n \ - each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \ - each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\ + "{HEADER}eachProject {{ p ->\n \ + each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \ + each(p.tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\ }}\n" ) } @@ -79,8 +96,8 @@ mod tests { fn adds_each_argument_to_java_exec_and_test_tasks() { let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"])); let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']"; - assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); - assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); + assert!(script.contains(&format!("each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); + assert!(script.contains(&format!("each(p.tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}"); // Gradle before 4.9 has no `configureEach` (#3864). assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}"); } diff --git a/crates/ide-run/tests/integration/gradle_init_scripts.rs b/crates/ide-run/tests/integration/gradle_init_scripts.rs new file mode 100644 index 0000000000..5c8ea847e7 --- /dev/null +++ b/crates/ide-run/tests/integration/gradle_init_scripts.rs @@ -0,0 +1,201 @@ +//! The init scripts of Gradle run, debug and test launches on a real Gradle, with and without +//! Isolated Projects (#8261). Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else +//! `gradle` on the search path); skipped without them, like ide-build's Gradle tests. +use std::path::{Path, PathBuf}; +use std::process::Command; + +const RUN: &str = include_str!("../../../../src/features/run/gradleRun.gradle"); +const BOOT: &str = include_str!("../../../../src/features/run/gradleBoot.gradle"); +const TESTS: &str = include_str!("../../../../src/features/run/gradleTests.gradle"); + +const MAIN: &str = r#"package a; +public class Main { + public static void main(String[] args) { + String token = ""; + for (String a : java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments()) + if (a.startsWith("-Dopenidea.")) token += " " + a; + System.out.println("APP " + String.join(",", args) + " enc=" + System.getProperty("file.encoding") + " vm=" + System.getProperty("openidea.vm") + token); + } +} +"#; + +const TEST: &str = r#"package l; +class LTest { + @org.junit.jupiter.api.Test + void ok() { + System.out.println("TEST vm=" + System.getProperty("openidea.vm") + " late=" + System.getProperty("openidea.late")); + } +} +"#; + +const JUNIT: &str = "org.junit.jupiter:junit-jupiter:5.11.0"; + +fn gradle() -> Option { + std::env::var_os("JAVA_HOME")?; + std::env::var_os("OPENIDEA_TEST_GRADLE") + .map(PathBuf::from) + .or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path())) +} + +fn write(root: &Path, files: &[(&str, &str)]) { + for (rel, text) in files { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } +} + +/// Runs `tasks` with every init script; the output, or the failure with it. +fn run(gradle: &Path, root: &Path, tasks: &[&str]) -> Result { + let scripts = root.parent().unwrap().join("scripts"); + let mut args = vec!["--console=plain".to_owned()]; + for name in ["jvm", "encoding", "run", "boot", "tests"] { + args.extend(["--init-script".to_owned(), scripts.join(format!("{name}.init.gradle")).display().to_string()]); + } + args.extend( + [ + "-Dopenidea.run.project=:app", + "-Dopenidea.run.main=a.Main", + r#"-Dopenidea.run.args=["openidea"]"#, + "-Dopenidea.run.token=t1", + ] + .map(String::from), + ); + args.extend(tasks.iter().map(|t| t.to_string())); + let out = Command::new(gradle).args(&args).current_dir(root).output().unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + if out.status.success() { Ok(text) } else { Err(text) } +} + +/// The test-events script reported the test, with its output, from a test JVM given the VM options. +fn assert_test_events(out: &str) { + for event in [ + "##teamcity[testStarted name='ok()' className='l.LTest'", + "##teamcity[testStdOut name='ok()' className='l.LTest' reportName='ok()' out='TEST vm=1", + "##teamcity[testFinished name='ok()' className='l.LTest'", + ] { + assert!(out.contains(event), "no `{event}`:\n{out}"); + } +} + +fn app_line<'a>(out: &'a str, arg: &str) -> &'a str { + let prefix = format!("APP {arg} "); + out.lines().find(|l| l.starts_with(&prefix)).unwrap_or_else(|| panic!("no `{prefix}` line:\n{out}")) +} + +/// Gradle's version, as (major, minor). +fn version(gradle: &Path) -> (u32, u32) { + let out = Command::new(gradle).arg("--version").output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + let v = text.lines().find_map(|l| l.strip_prefix("Gradle ")).expect("a `Gradle x.y` line"); + let mut parts = v.trim().split('.').map(|p| p.parse::().unwrap_or(0)); + (parts.next().unwrap(), parts.next().unwrap_or(0)) +} + +#[test] +fn run_debug_and_test_scripts_configure_each_project() { + let Some(gradle) = gradle() else { + eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)"); + return; + }; + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let jvm = ide_run::gradle_jvm::init_script(&["-Dopenidea.vm=1".to_owned()]); + write( + &base, + &[ + ("scripts/jvm.init.gradle", &jvm), + ("scripts/encoding.init.gradle", ide_core::output_encoding::GRADLE_FILE_ENCODING_SCRIPT), + ("scripts/run.init.gradle", RUN), + ("scripts/boot.init.gradle", BOOT), + ("scripts/tests.init.gradle", TESTS), + ], + ); + + // Without Isolated Projects, in the Groovy DSL: the build's own setting still wins over the + // scripts' UTF-8 default, also when the root configures its subprojects. + let plain = base.join("plain"); + write( + &plain, + &[ + ("gradle.properties", "org.gradle.daemon=false\n"), + ("settings.gradle", "rootProject.name = 'plain'\ninclude 'app', 'lib'\n"), + ( + "build.gradle", + "subprojects { tasks.withType(JavaExec).configureEach { defaultCharacterEncoding = 'ISO-8859-1' } }\n", + ), + ( + "app/build.gradle", + "plugins { id 'application' }\napplication { mainClass = 'a.Main' }\ntasks.named('run') { args 'run' }\n\ + tasks.register('bootRun', JavaExec) { mainClass = 'a.Main'; classpath = sourceSets.main.runtimeClasspath; args 'boot' }\n", + ), + ("app/src/main/java/a/Main.java", MAIN), + ( + "lib/build.gradle", + &format!( + "plugins {{ id 'java' }}\nrepositories {{ mavenCentral() }}\n\ + dependencies {{ testImplementation '{JUNIT}'; testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }}\n\ + test {{ useJUnitPlatform() }}\n" + ), + ), + ("lib/src/test/java/l/LTest.java", TEST), + ], + ); + let out = run(&gradle, &plain, &[":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"]).unwrap(); + assert_eq!(app_line(&out, "run"), "APP run enc=ISO-8859-1 vm=1 -Dopenidea.vm=1"); + assert_eq!(app_line(&out, "boot"), "APP boot enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1"); + assert_eq!(app_line(&out, "openidea"), "APP openidea enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1"); + assert_test_events(&out); + + // With Isolated Projects, in the Kotlin DSL, on a configuration cache miss and then a hit. + let isolated = base.join("isolated"); + write( + &isolated, + &[ + ( + "gradle.properties", + "org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\ + org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n", + ), + ("settings.gradle.kts", "rootProject.name = \"isolated\"\ninclude(\"app\", \"lib\")\n"), + ("build.gradle.kts", ""), + ( + "app/build.gradle.kts", + "plugins { application }\napplication { mainClass.set(\"a.Main\") }\n\ + tasks.named(\"run\") { args(\"run\"); defaultCharacterEncoding = \"ISO-8859-1\"; jvmArgs(\"-Dopenidea.vm=build\") }\n\ + tasks.register(\"bootRun\") { mainClass.set(\"a.Main\"); classpath = sourceSets[\"main\"].runtimeClasspath; args(\"boot\") }\n\ + afterEvaluate { tasks.named(\"bootRun\") { setJvmArgs(listOf(\"-Dopenidea.late=1\")) } }\n", + ), + ("app/src/main/java/a/Main.java", MAIN), + ( + "lib/build.gradle.kts", + &format!( + "plugins {{ java }}\nrepositories {{ mavenCentral() }}\n\ + dependencies {{ testImplementation(\"{JUNIT}\"); testRuntimeOnly(\"org.junit.platform:junit-platform-launcher\") }}\n\ + tasks.test {{ useJUnitPlatform() }}\n\ + afterEvaluate {{ tasks.named(\"test\") {{ systemProperty(\"openidea.late\", \"1\") }} }}\n" + ), + ), + ("lib/src/test/java/l/LTest.java", TEST), + ], + ); + let tasks = [":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"]; + if version(&gradle) < (8, 8) { + // Before Gradle 8.8 the scripts keep reading every project, as the build above checked. + return; + } + for pass in ["miss", "hit"] { + let out = run(&gradle, &isolated, &tasks).unwrap_or_else(|e| panic!("cache {pass}:\n{e}")); + assert_eq!(out.contains("Reusing configuration cache."), pass == "hit", "{out}"); + // The build's own charset and VM option win over the scripts' values. + let run = app_line(&out, "run"); + assert!(run.starts_with("APP run enc=ISO-8859-1 vm=build "), "{run}"); + // The token comes after the build's own `afterEvaluate`, which replaced the JVM arguments. + assert_eq!(app_line(&out, "boot"), "APP boot enc=UTF-8 vm=null -Dopenidea.late=1 -Dopenidea.run.token=t1"); + assert_eq!(app_line(&out, "openidea"), "APP openidea enc=UTF-8 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1"); + // Test tasks always run, also on a cache hit. + assert_test_events(&out); + // The test task the build configures in its own `afterEvaluate` ran with that setting. + assert!(out.contains("out='TEST vm=1 late=1"), "{out}"); + } +} diff --git a/crates/ide-run/tests/integration/main.rs b/crates/ide-run/tests/integration/main.rs index 7187da2dc1..59421043d2 100644 --- a/crates/ide-run/tests/integration/main.rs +++ b/crates/ide-run/tests/integration/main.rs @@ -2,6 +2,7 @@ mod config; mod detect; mod dotnet; mod dotnet_cli; +mod gradle_init_scripts; mod import_jetbrains; mod import_vscode; #[cfg(unix)] diff --git a/src/features/run/gradleBoot.gradle b/src/features/run/gradleBoot.gradle index 409312d62f..d2507cfafb 100644 --- a/src/features/run/gradleBoot.gradle +++ b/src/features/run/gradleBoot.gradle @@ -4,19 +4,34 @@ import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } -gradle.projectsEvaluated { - allprojects { - each(tasks.matching { it.name == 'bootRun' }) { task -> - def token = System.getProperty('openidea.run.token') - if (token) task.jvmArgs('-Dopenidea.run.token=' + token) - if (System.getProperty('openidea.run.debug') == 'true') { - task.debug = false - task.doFirst { - task.setJvmArgs(task.jvmArgs.findAll { - !it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:') - }) - task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0') - } +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`. +def afterProjects = { Closure action -> isolated ? gradle.lifecycle.afterProject { p -> p.afterEvaluate(action) } : gradle.projectsEvaluated { allprojects(action) } } +afterProjects { p -> + each(p.tasks.matching { it.name == 'bootRun' }) { task -> + def token = System.getProperty('openidea.run.token') + if (token) task.jvmArgs('-Dopenidea.run.token=' + token) + if (System.getProperty('openidea.run.debug') == 'true') { + task.debug = false + task.doFirst { + task.setJvmArgs(task.jvmArgs.findAll { + !it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:') + }) + task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0') } } } diff --git a/src/features/run/gradleRun.gradle b/src/features/run/gradleRun.gradle index f8492d547d..f461d04877 100644 --- a/src/features/run/gradleRun.gradle +++ b/src/features/run/gradleRun.gradle @@ -6,10 +6,26 @@ import groovy.json.JsonSlurper import org.gradle.util.GradleVersion def lazyTasks = GradleVersion.current() >= GradleVersion.version('4.9') +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } // Gradle 7.0 and older give a build JVM with its own `org.gradle.jvmargs` the command line's // `-D` values only once the settings load, after init scripts run: read them in project actions (#4093). -allprojects { p -> +eachProject { p -> // An identity path (`:lib:core` for a project of an included build); none: not a delegated run. def id = { try { p.identityPath.toString() } catch (ignored) { p.path } } if (id() != System.getProperty('openidea.run.project')) return diff --git a/src/features/run/gradleRun.test.ts b/src/features/run/gradleRun.test.ts index 184707a2be..c4fdd8fb64 100644 --- a/src/features/run/gradleRun.test.ts +++ b/src/features/run/gradleRun.test.ts @@ -296,7 +296,7 @@ describe("Build and run using: Gradle", () => { const run = delegatedGradleConfig(app, module, { ...ctx, configurationCache: false })!; expect(run.args).toContain(`-Dopenidea.run.project=${project}`); expect(run.args.at(-1)).toBe(task); - // The init script compares each project's identity path with it inside `allprojects`. + // The init script compares each project's identity path with it. expect(RUN_SCRIPT).toContain("if (id() != System.getProperty('openidea.run.project')) return"); }); diff --git a/src/features/run/gradleTests.gradle b/src/features/run/gradleTests.gradle index 7604742a16..de28e3c0fc 100644 --- a/src/features/run/gradleTests.gradle +++ b/src/features/run/gradleTests.gradle @@ -6,6 +6,24 @@ import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } +// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there +// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is +// only injected, so a class compiled here reads it. +def isolated = false +// When that fails, the build is treated as one without Isolated Projects. +if (GradleVersion.current() >= GradleVersion.version('8.8')) try { + def features = new GroovyClassLoader(Gradle.classLoader).parseClass(''' + abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin { + @javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures() + boolean active + void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) } + }''') + gradle.pluginManager.apply(features) + isolated = gradle.plugins.getPlugin(features).active +} catch (Throwable ignored) {} +def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) } +// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`. +def afterProjects = { Closure action -> isolated ? gradle.lifecycle.afterProject { p -> p.afterEvaluate(action) } : gradle.projectsEvaluated { allprojects(action) } } def tc = { String s -> s == null ? '' : s.replace('|', '||').replace("'", "|'").replace('\n', '|n').replace('\r', '|r') @@ -25,8 +43,8 @@ def id = { TestDescriptor test -> "${own} invocation='${tc(shown)}'" } -allprojects { - each(tasks.withType(Test)) { Test task -> +eachProject { p -> + each(p.tasks.withType(Test)) { Test task -> task.outputs.upToDateWhen { false } task.addTestListener(new TestListener() { void beforeSuite(TestDescriptor suite) {} @@ -63,17 +81,15 @@ allprojects { } // Replace build-configured agents only for this debug launch, after project configuration. -gradle.projectsEvaluated { - allprojects { - each(tasks.withType(Test)) { Test task -> - if (System.getProperty('openidea.run.debug') == 'true') { - task.debug = false - task.doFirst { - task.setJvmArgs(task.jvmArgs.findAll { - !it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:') - }) - task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0') - } +afterProjects { p -> + each(p.tasks.withType(Test)) { Test task -> + if (System.getProperty('openidea.run.debug') == 'true') { + task.debug = false + task.doFirst { + task.setJvmArgs(task.jvmArgs.findAll { + !it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:') + }) + task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0') } } }