Skip to content

Apache Lucene open-source search software

More gradle plugins converted to java and cleaned up (#15088)

Dawid Weiss45a7c38cfe3c
diff --git a/build-tools/build-infra-shadow/build.gradle b/build-tools/build-infra-shadow/build.gradle
index 5a41ed1e90c..845a7c51d43 100644
--- a/build-tools/build-infra-shadow/build.gradle
+++ b/build-tools/build-infra-shadow/build.gradle
@@ -56,6 +56,7 @@ dependencies {
implementation plugin(deps.plugins.forbiddenapis)
implementation plugin(deps.plugins.spotless)
implementation plugin(deps.plugins.undercouch.download)
+ implementation plugin(deps.plugins.jacocolog)
}
tasks.matching {
diff --git a/build-tools/build-infra/src/main/groovy/lucene.ide.eclipse.gradle b/build-tools/build-infra/src/main/groovy/lucene.ide.eclipse.gradle
deleted file mode 100644
index 8706cf1931c..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.ide.eclipse.gradle
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.tools.ant.filters.ReplaceTokens;
-import org.gradle.plugins.ide.eclipse.model.SourceFolder
-import org.gradle.plugins.ide.eclipse.model.ClasspathEntry
-
-if (project != project.rootProject) {
- throw new GradleException("Applicable to rootProject only: " + project.path)
-}
-
-Provider<String> eclipseJavaVersionOption = buildOptions.addOption("eclipse.javaVersion", "Set Java version for Eclipse IDE", deps.versions.minJava.get())
-Provider<String> eclipseErrorsOption = buildOptions.addOption("eclipse.errors", "Sets eclipse IDE lint level (ignore/warning/error)", "warning")
-
-if (gradle.startParameter.taskNames.contains("eclipse")) {
- project.pluginManager.apply("java-base")
- project.pluginManager.apply("eclipse")
-
- def resources = rootProject.file("gradle/ide/eclipse")
- def eclipseJavaVersion = eclipseJavaVersionOption.get()
- def relativize = { File other -> rootProject.rootDir.relativePath(other).toString() }
-
- eclipse {
- project {
- name = "Apache Lucene ${version}"
- }
-
- classpath {
- defaultOutputDir = file('build/eclipse')
-
- downloadSources = true
- downloadJavadoc = false
-
- plusConfigurations += allprojects.findAll{ prj ->
- return prj.plugins.hasPlugin(JavaPlugin)
- }.collectMany {
- return [
- it.configurations.compileClasspath,
- it.configurations.testCompileClasspath
- ]
- }
-
- file {
- whenMerged { classpath ->
- classpath.entries.removeAll {
- return it.kind == "src" || (it.kind == "lib" && it.getPath() ==~ /(.+)lucene-.*\.jar/)
- }
-
- // Wipe attributes which only contain a blank "gradle_used_by_scope" for every single library.
- classpath.entries.each {
- if (it.kind == "lib") {
- it.getEntryAttributes().clear()
- }
- // The generated gradle-api.jar has no source attached, attaching source is a PITA
- // for now just attach a javadocs URL, which improves editor functionality:
- if (it.getPath() ==~ /(.+)gradle-api-.*\.jar/) {
- it.getEntryAttributes().put("javadoc_location", "https://docs.gradle.org/${deps.versions.minGradle.get()}/javadoc")
- }
- }
-
- def projects = allprojects.findAll { prj ->
- return prj.plugins.hasPlugin(JavaPlugin)
- }
-
- Set<String> sourceSetNames = [
- 'main',
- 'test',
- "main${eclipseJavaVersion}" as String,
- "test${eclipseJavaVersion}" as String,
- 'tools'
- ] as Set
- Set<String> sources = []
- projects.each { prj ->
- prj.sourceSets.each { sourceSet ->
- if (sourceSetNames.contains(sourceSet.name)) {
- sources += sourceSet.java.srcDirs.findAll { dir -> dir.exists() }.collect { dir -> relativize(dir) }
- sources += sourceSet.resources.srcDirs.findAll { dir -> dir.exists() }.collect { dir -> relativize(dir) }
- }
- }
- }
-
- classpath.entries += sources.sort().collect { name ->
- def sourceFolder = new SourceFolder(name, "build/eclipse/" + name)
- sourceFolder.setExcludes(["module-info.java"])
- return sourceFolder
- }
- }
- }
- }
-
- jdt {
- sourceCompatibility = eclipseJavaVersion
- targetCompatibility = eclipseJavaVersion
- javaRuntimeName = "JavaSE-$eclipseJavaVersion"
- }
- }
-
- tasks.register("luceneEclipseJdt", Sync, {
- def errorMode = eclipseErrorsOption.get()
- def ecjLintFile = rootProject.file('gradle/validation/ecj-lint/ecj.javadocs.prefs');
-
- description = 'Generates the Eclipse JDT settings file.'
-
- inputs.file(ecjLintFile)
- inputs.property('errorMode', errorMode)
- inputs.property('eclipseJavaVersion', eclipseJavaVersion as String)
-
- from rootProject.file("${resources}/dot.settings")
- into rootProject.file(".settings")
- filter(ReplaceTokens, tokens: [
- 'ecj-lint-config': ecjLintFile.getText('UTF-8').replaceAll(/=error\b/, '=' + errorMode),
- 'eclipseJavaVersion': eclipseJavaVersion as String
- ])
- filteringCharset = 'UTF-8'
-
- doLast {
- logger.lifecycle('Eclipse config for Java {} written with ECJ errors configured as {}. Change by altering build option eclipse.errors to ignore/warning/error.', eclipseJavaVersion, errorMode)
- logger.lifecycle('To edit classes of MR-JARs for a specific Java version, use e.g., -Peclipse.javaVersion=19')
- }
- })
-
- eclipseJdt {
- enabled = false
- dependsOn 'luceneEclipseJdt'
- }
-
- eclipseClasspath {
- inputs.property('eclipseJavaVersion', eclipseJavaVersion as String)
- }
-}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.ide.intellij-idea.gradle b/build-tools/build-infra/src/main/groovy/lucene.ide.intellij-idea.gradle
deleted file mode 100644
index 34ad5f3c164..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.ide.intellij-idea.gradle
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// Tweak settings to allow easier working with IntelliJ Idea
-
-if (project != project.rootProject) {
- throw new GradleException("Applicable to rootProject only: " + project.path)
-}
-
-if (buildGlobals.intellijIdea.get().isIdea) {
- logger.warn("IntelliJ Idea IDE detected.")
-
- allprojects {
- apply plugin: 'idea'
-
- idea {
- module {
- outputDir file('build/idea/classes/main')
- testOutputDir file('build/idea/classes/test')
- downloadSources = true
- }
- }
- }
-}
-
-if (buildGlobals.intellijIdea.get().isIdeaSync) {
- allprojects {
- // disable all MR-JAR folders by hiding them from IDE after evaluation:
- plugins.withType(JavaPlugin).configureEach {
- project.afterEvaluate {
- sourceSets.matching { it.name ==~ /main\d+/ }.configureEach { SourceSet sourceSet ->
- logger.lifecycle("Skipping MR-JAR sourceSet on IntelliJ Idea: " + sourceSet.name)
- sourceSet.java.srcDirs = []
- sourceSet.resources.srcDirs = []
- }
- }
- }
- }
-}
-
-if (buildGlobals.intellijIdea.get().isIdeaBuild) {
- // Skip certain long tasks that are dependencies
- // of 'assemble' if we're building from within IntelliJ.
- def skipTasks = [
- // Skip site javadoc rendering
- ".*:(renderSiteJavadoc)",
- ]
- tasks.matching { task ->
- return skipTasks.any { pattern -> task.path ==~ pattern }
- }.configureEach {
- logger.debug("Skipping task on IntelliJ: " + it.path)
- task.enabled = false
- }
-}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.coverage.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.coverage.gradle
deleted file mode 100644
index 228b04db861..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.java.coverage.gradle
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// This adds jacoco code coverage to tests.
-
-if (project != project.rootProject) {
- throw new GradleException("Applicable to rootProject only: " + project.path)
-}
-
-Provider<Boolean> coverageOption = buildOptions.addBooleanOption("tests.coverage", "Enables jacoco test coverage.", false)
-
-// Run with jacoco if either 'coverage' task is explicitly enabled or tests.coverage option is true.
-def withCoverage = gradle.startParameter.taskNames.contains("coverage") || coverageOption.get()
-
-if (withCoverage) {
- plugins.apply(deps.plugins.jacocolog.get().pluginId)
-
- // Synthetic task to enable test coverage (and aggregated reports).
-
- def jacocoAggregatedReport = tasks.named("jacocoAggregatedReport")
- tasks.register("coverage", {
- dependsOn jacocoAggregatedReport
- })
-
- jacocoAggregatedReport.configure {
- doLast {
- logger.lifecycle("Aggregated code coverage report at: ${reports.html.entryPoint}\n")
- }
- }
-
- subprojects {
- plugins.apply(deps.plugins.jacocolog.get().pluginId)
-
- plugins.withType(JavaPlugin).configureEach {
- // Synthetic task to enable test coverage (and reports).
- def jacocoTestReport = tasks.named("jacocoTestReport")
- tasks.register("coverage", {
- dependsOn "test", jacocoTestReport
- })
-
- tasks.withType(Test).configureEach { testTask ->
- // Configure jacoco destination file to be within the test
- // task's working directory
- jacoco {
- destinationFile = file("${testTask.workingDir}/jacoco.exec")
- }
-
- // Test reports run after the test task, if it's run at all.
- testTask.finalizedBy jacocoTestReport
- }
-
- jacocoTestReport.configure {
- doLast {
- logger.lifecycle("Code coverage report at: ${reports.html.entryPoint}.\n")
- }
- }
- }
- }
-}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.fail-on-no-tests.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.fail-on-no-tests.gradle
deleted file mode 100644
index 4c3edaa7561..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.java.fail-on-no-tests.gradle
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// If we run the test task with a filter we want to fail if no test actually ran (everything was excluded).
-
-if (project != project.rootProject) {
- throw new GradleException("Applicable to rootProject only: " + project.path)
-}
-
-def args = gradle.startParameter.taskNames
-def filterParameters = args.findAll({ arg ->
- return arg == /--tests/
-})
-
-boolean doCount = !filterParameters.isEmpty()
-int executedTests = 0
-int executedTasks = 0
-
-configure(allprojects) {
- plugins.withType(JavaPlugin).configureEach {
- tasks.withType(Test).configureEach {
- filter {
- failOnNoMatchingTests = false
- }
-
- // Only apply the check if we are actually filtering.
- if (doCount) {
- doFirst {
- executedTasks++
- }
- afterSuite { desc, result ->
- executedTests += result.testCount
- }
- }
- }
- }
-}
-
-if (doCount) {
- // After the build is finished, check the test count.
- gradle.buildFinished {
- if (executedTests == 0 && executedTasks > 0) {
- throw new GradleException("No tests found for the given filters?")
- }
- }
-}
diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.profiling.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.profiling.gradle
deleted file mode 100644
index 029dfbb1e4b..00000000000
--- a/build-tools/build-infra/src/main/groovy/lucene.java.profiling.gradle
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.lucene.gradle.ProfileResults
-
-// Enable JFR profiling for tests.
-
-if (project != project.rootProject) {
- throw new GradleException("Applicable to rootProject only: " + project.path)
-}
-
-def recordings = files()
-
-allprojects {
- Provider<Boolean> profileOption = buildOptions.addBooleanOption("tests.profile", "Enable Java Flight Recorder profiling.", false)
-
- plugins.withType(JavaPlugin).configureEach {
- if (profileOption.get()) {
- def hasJavaFlightRecorder = ModuleLayer.boot().findModule('jdk.jfr')
- .map { module -> this.getClass().module.canRead(module) }.orElse(false)
- if (hasJavaFlightRecorder) {
- tasks.withType(Test).configureEach {
- jvmArgs("-XX:StartFlightRecording=dumponexit=true,maxsize=250M,settings=" + rootProject.file("gradle/testing/profiling.jfc"),
- "-XX:+UnlockDiagnosticVMOptions",
- "-XX:+DebugNonSafepoints")
- // delete any previous profile results
- doFirst {
- project.delete fileTree(dir: workingDir, include: '*.jfr')
- }
- doLast {
- recordings = recordings.plus fileTree(dir: workingDir, include: '*.jfr')
- }
- }
- } else {
- throw new GradleException('Module jdk.jfr is not available; Java Flight Recorder profiles cannot be enabled.')
- }
- }
- }
-
- Provider<String> modeOption = buildOptions.addOption(ProfileResults.MODE_KEY, "Profiling mode.", ProfileResults.MODE_DEFAULT)
- Provider<Integer> stackSizeOption = buildOptions.addIntOption(ProfileResults.STACKSIZE_KEY, "Profiling stack size.", Integer.parseInt(ProfileResults.STACKSIZE_DEFAULT))
- Provider<Integer> countOption = buildOptions.addIntOption(ProfileResults.COUNT_KEY, "Profiling entry count.", Integer.parseInt(ProfileResults.COUNT_DEFAULT))
- Provider<Boolean> lineNumbersOption = buildOptions.addBooleanOption(ProfileResults.LINENUMBERS_KEY, "Profiling with line numbers.", Boolean.parseBoolean(ProfileResults.LINENUMBERS_KEY))
- Provider<Boolean> frametypesOption = buildOptions.addBooleanOption(ProfileResults.FRAMETYPES_KEY, "Profiling frame types.", Boolean.parseBoolean(ProfileResults.FRAMETYPES_DEFAULT))
-
- if (it == rootProject && profileOption.get()) {
- gradle.buildFinished {
- if (!recordings.isEmpty()) {
- ProfileResults.printReport(recordings.getFiles().collect { it.toString() },
- modeOption.get(),
- stackSizeOption.get(),
- countOption.get(),
- lineNumbersOption.get(),
- frametypesOption.get())
- }
- }
- }
-}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java
index 50e2b51b5f2..f3ba9d58959 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java
@@ -20,6 +20,7 @@ import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsTask;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import org.apache.lucene.gradle.plugins.ide.EclipseSupportPlugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
@@ -36,7 +37,11 @@ public class BuildOptionGroupsPlugin implements Plugin<Project> {
optionGroups -> {
optionGroups.group("Lucene version strings", "version\\.(.*)");
- optionGroups.group("IDE-tweaking options", "eclipse\\.(.+)");
+ optionGroups.group(
+ "IDE-tweaking options",
+ explicitList(
+ EclipseSupportPlugin.OPT_ECLIPSE_ERRORS,
+ EclipseSupportPlugin.OPT_ECLIPSE_JAVA_VERSION));
optionGroups.group(
"Optional testing and test resources",
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/ide/EclipseSupportPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/ide/EclipseSupportPlugin.java
new file mode 100644
index 00000000000..535d6baa60e
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/ide/EclipseSupportPlugin.java
@@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.ide;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.apache.lucene.gradle.plugins.java.EcjLintPlugin;
+import org.apache.tools.ant.filters.ReplaceTokens;
+import org.gradle.api.JavaVersion;
+import org.gradle.api.Project;
+import org.gradle.api.artifacts.Configuration;
+import org.gradle.api.artifacts.VersionCatalog;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.plugins.JavaPluginExtension;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.tasks.Sync;
+import org.gradle.plugins.ide.eclipse.EclipsePlugin;
+import org.gradle.plugins.ide.eclipse.GenerateEclipseClasspath;
+import org.gradle.plugins.ide.eclipse.GenerateEclipseJdt;
+import org.gradle.plugins.ide.eclipse.model.AbstractClasspathEntry;
+import org.gradle.plugins.ide.eclipse.model.Classpath;
+import org.gradle.plugins.ide.eclipse.model.ClasspathEntry;
+import org.gradle.plugins.ide.eclipse.model.EclipseClasspath;
+import org.gradle.plugins.ide.eclipse.model.EclipseModel;
+import org.gradle.plugins.ide.eclipse.model.SourceFolder;
+
+/** Adds (limited) development support for Eclipse IDE. */
+public class EclipseSupportPlugin extends LuceneGradlePlugin {
+ public static final String OPT_ECLIPSE_JAVA_VERSION = "eclipse.javaVersion";
+ public static final String OPT_ECLIPSE_ERRORS = "eclipse.errors";
+
+ @Override
+ public void apply(Project rootProject) {
+ applicableToRootProjectOnly(rootProject);
+
+ // Always add configurable build options so that they show up in the
+ // option list.
+ var buildOptions = getBuildOptions(rootProject);
+ Provider<String> eclipseJavaVersionOption =
+ buildOptions.addOption(
+ OPT_ECLIPSE_JAVA_VERSION,
+ "Set Java version for Eclipse IDE",
+ getLuceneBuildGlobals(rootProject).getMinJavaVersion().map(JavaVersion::toString));
+ buildOptions.addOption(
+ OPT_ECLIPSE_ERRORS, "Sets eclipse IDE lint level (ignore/warning/error)", "warning");
+
+ // Only apply Eclipse configuration setup if an explicit 'eclipse' parameter is invoked.
+ if (rootProject.getGradle().getStartParameter().getTaskNames().contains("eclipse")) {
+ configureEclipseIdeSettings(rootProject, eclipseJavaVersionOption.get());
+ }
+ }
+
+ private void configureEclipseIdeSettings(Project project, String eclipseJavaVersion) {
+ var plugins = project.getPlugins();
+ plugins.apply("java-base");
+ plugins.apply(EclipsePlugin.class);
+
+ var eclipse = project.getExtensions().getByType(EclipseModel.class);
+ eclipse.getProject().setName("Apache Lucene " + project.getVersion());
+ var classpath = eclipse.getClasspath();
+ classpath.setDefaultOutputDir(project.file("build/eclipse"));
+ classpath.setDownloadJavadoc(false);
+ classpath.setDownloadSources(true);
+
+ project
+ .getAllprojects()
+ .forEach(
+ p -> {
+ p.getPlugins()
+ .withType(JavaPlugin.class)
+ .configureEach(_ -> addDependencyConfigurations(p, classpath));
+ });
+
+ classpath
+ .getFile()
+ .whenMerged(
+ cp -> configureClasspath(project, (org.gradle.plugins.ide.eclipse.model.Classpath) cp));
+
+ var jdt = eclipse.getJdt();
+ jdt.setSourceCompatibility(eclipseJavaVersion);
+ jdt.setTargetCompatibility(eclipseJavaVersion);
+ jdt.setJavaRuntimeName("JavaSE-" + eclipseJavaVersion);
+
+ var luceneEclipseJdt =
+ project
+ .getTasks()
+ .register(
+ "luceneEclipseJdt",
+ Sync.class,
+ task -> {
+ task.setDescription("Generates the Eclipse JDT settings file.");
+
+ Path ecjLintFile =
+ gradlePluginResource(project, EcjLintPlugin.ECJ_LINT_PREFS_PATH);
+ var errorMode = getBuildOptions(project).optionValue(OPT_ECLIPSE_ERRORS).get();
+
+ var inputs = task.getInputs();
+ inputs.file(ecjLintFile);
+ inputs.property("errorMode", errorMode);
+ inputs.property("eclipseJavaVersion", eclipseJavaVersion);
+
+ task.from(gradlePluginResource(project, "ide/eclipse/dot.settings"));
+ task.into(project.file(".settings"));
+
+ task.setFilteringCharset("UTF-8");
+
+ String ecjLintProps;
+ try {
+ ecjLintProps =
+ Files.readString(ecjLintFile).replaceAll("=error\\b", "=" + errorMode);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ task.filter(
+ Map.of(
+ "tokens",
+ new Hashtable<>(
+ Map.ofEntries(
+ Map.entry("eclipseJavaVersion", eclipseJavaVersion),
+ Map.entry("ecj-lint-config", ecjLintProps)))),
+ ReplaceTokens.class);
+
+ task.doLast(
+ t -> {
+ var logger = t.getLogger();
+ logger.lifecycle(
+ "Eclipse config for Java {} written with ECJ errors configured as '{}'. "
+ + "Change by altering the build option '{}' to ignore/warning/error: "
+ + "-P{}=ignore",
+ eclipseJavaVersion,
+ errorMode,
+ OPT_ECLIPSE_ERRORS,
+ OPT_ECLIPSE_ERRORS);
+ logger.lifecycle(
+ "To edit classes of MR-JARs for a specific Java version, regenerate"
+ + " Eclipse options using: -P{}=24",
+ OPT_ECLIPSE_JAVA_VERSION);
+ });
+ });
+
+ var tasks = project.getTasks();
+ tasks
+ .withType(GenerateEclipseJdt.class)
+ .named("eclipseJdt")
+ .configure(
+ task -> {
+ task.setEnabled(false);
+ task.dependsOn(luceneEclipseJdt);
+ });
+
+ tasks
+ .withType(GenerateEclipseClasspath.class)
+ .named("eclipseClasspath")
+ .configure(
+ task -> {
+ task.getInputs().property("eclipseJavaVersion", eclipseJavaVersion);
+ });
+ }
+
+ private static void addDependencyConfigurations(Project p, EclipseClasspath classpath) {
+ List<Configuration> newConfigurations = new ArrayList<>(classpath.getPlusConfigurations());
+ var conf = p.getConfigurations();
+ newConfigurations.add(conf.getByName("compileClasspath"));
+ newConfigurations.add(conf.getByName("testCompileClasspath"));
+ classpath.setPlusConfigurations(newConfigurations);
+ }
+
+ private void configureClasspath(Project project, Classpath cp) {
+ // wipe references to sources and cross-project refs.
+ cp.getEntries()
+ .removeIf(
+ (ClasspathEntry e) -> {
+ return e.getKind().equals("src")
+ || (e.getKind().equals("lib")
+ && ((AbstractClasspathEntry) e).getPath().matches("(.+)lucene-.*\\.jar"));
+ });
+
+ // Wipe attributes which only contain a blank "gradle_used_by_scope" for every single library.
+ VersionCatalog versionCatalog = getVersionCatalog(project);
+ String expectedGradleVersion = versionCatalog.findVersion("minGradle").get().toString();
+
+ for (ClasspathEntry entry : cp.getEntries()) {
+ if (entry instanceof AbstractClasspathEntry cpEntry && entry.getKind().equals("lib")) {
+ cpEntry.getEntryAttributes().clear();
+ if (cpEntry.getPath().matches(".*gradle-api-.*\\.jar")) {
+ String javadocUrl = "https://docs.gradle.org/" + expectedGradleVersion + "/javadoc";
+ cpEntry.getEntryAttributes().put("javadoc_location", javadocUrl);
+ }
+ }
+ }
+
+ // When this is called, all projects should have all the plugins applied (after the xml is
+ // merged).
+ String eclipseJavaVersion =
+ getBuildOptions(project).optionValue(OPT_ECLIPSE_JAVA_VERSION).get();
+ Set<String> sourceSetNames =
+ Set.of("main", "test", "main" + eclipseJavaVersion, "test" + eclipseJavaVersion, "tools");
+ Path rootDir = getProjectRootPath(project);
+
+ var sourceFolderList =
+ project.getAllprojects().stream()
+ .filter(p -> p.getPlugins().hasPlugin(JavaPlugin.class))
+ .flatMap(
+ p ->
+ p.getExtensions().getByType(JavaPluginExtension.class).getSourceSets().stream())
+ .filter(s -> sourceSetNames.contains(s.getName()))
+ .flatMap(
+ ss ->
+ Stream.concat(
+ ss.getJava().getSrcDirs().stream(),
+ ss.getResources().getSrcDirs().stream()))
+ .filter(File::exists)
+ .map(dir -> rootDir.relativize(dir.toPath()).toString())
+ .sorted()
+ .map(
+ path -> {
+ var sourceFolder = new SourceFolder(path, "build/eclipse/" + path);
+ sourceFolder.setExcludes(List.of("module-info.java"));
+ return sourceFolder;
+ })
+ .toList();
+ cp.getEntries().addAll(sourceFolderList);
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/ide/IdeaSupportPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/ide/IdeaSupportPlugin.java
new file mode 100644
index 00000000000..41c7ee8d2b8
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/ide/IdeaSupportPlugin.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.ide;
+
+import java.util.List;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.Project;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.plugins.JavaPluginExtension;
+import org.gradle.plugins.ide.idea.model.IdeaModel;
+
+/** Adds some development support for IntelliJ Idea IDE. */
+public class IdeaSupportPlugin extends LuceneGradlePlugin {
+
+ @Override
+ public void apply(Project rootProject) {
+ applicableToRootProjectOnly(rootProject);
+
+ var intellijIdea = getLuceneBuildGlobals(rootProject).getIntellijIdea().get();
+ if (intellijIdea.isIdea()) {
+ var logger = rootProject.getLogger();
+ logger.warn("IntelliJ Idea IDE detected.");
+
+ rootProject.allprojects(
+ project -> {
+ project.getPlugins().apply("idea");
+
+ var idea = project.getExtensions().getByType(IdeaModel.class);
+ var module = idea.getModule();
+ module.setOutputDir(project.file("build/idea/classes/main"));
+ module.setTestOutputDir(project.file("build/idea/classes/test"));
+ module.setDownloadSources(true);
+ });
+ }
+
+ if (intellijIdea.isIdeaSync()) {
+ rootProject.allprojects(
+ project -> {
+ // disable all MR-JAR folders by hiding them from IDE after evaluation:
+ project
+ .getPlugins()
+ .withType(JavaPlugin.class)
+ .configureEach(
+ _ -> {
+ var sourceSets =
+ project
+ .getExtensions()
+ .getByType(JavaPluginExtension.class)
+ .getSourceSets();
+ sourceSets
+ .matching(
+ sourceSet -> {
+ return sourceSet.getName().matches("main\\d+");
+ })
+ .configureEach(
+ sourceSet -> {
+ project
+ .getLogger()
+ .lifecycle(
+ "Skipping MR-JAR sourceSet on IntelliJ Idea: "
+ + sourceSet.getName());
+ sourceSet.getJava().setSrcDirs(List.of());
+ sourceSet.getResources().setSrcDirs(List.of());
+ });
+ });
+ });
+ }
+
+ if (intellijIdea.isIdeaBuild()) {
+ // Skip certain long tasks that are dependencies of 'assemble' if we're building from within
+ // IntelliJ.
+ rootProject.allprojects(
+ project -> {
+ project
+ .getTasks()
+ .matching(task -> task.getName().equals("renderSiteJavadoc"))
+ .configureEach(
+ task -> {
+ project.getLogger().lifecycle("Skipping task on IntelliJ: " + task.getPath());
+ task.setEnabled(false);
+ });
+ });
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/CodeCoveragePlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/CodeCoveragePlugin.java
new file mode 100644
index 00000000000..0a9418e56a7
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/CodeCoveragePlugin.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.java;
+
+import java.io.File;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.barfuin.gradle.jacocolog.JacocoLogPlugin;
+import org.gradle.api.Project;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.tasks.TaskCollection;
+import org.gradle.api.tasks.TaskContainer;
+import org.gradle.api.tasks.TaskProvider;
+import org.gradle.api.tasks.testing.Test;
+import org.gradle.testing.jacoco.plugins.JacocoTaskExtension;
+import org.gradle.testing.jacoco.tasks.JacocoReport;
+
+/**
+ * This adds jacoco code coverage to test tasks, along with an aggregated report of all coverage.
+ */
+public class CodeCoveragePlugin extends LuceneGradlePlugin {
+ public static final String TESTS_COVERAGE_OPTION = "tests.coverage";
+
+ public abstract static class RootExtPlugin extends LuceneGradlePlugin {
+ @Override
+ public void apply(Project project) {
+ applicableToRootProjectOnly(project);
+
+ boolean withCoverage = addCoverageOptions(project);
+
+ if (withCoverage) {
+ project.getPlugins().apply(JacocoLogPlugin.class);
+
+ var tasks = project.getTasks();
+
+ String jacocoTaskName = "jacocoAggregatedReport";
+ var jacocoAggregatedReport =
+ configureJacocoReport(tasks, jacocoTaskName, "Aggregated code coverage report at: ");
+
+ tasks.register(
+ "coverage",
+ task -> {
+ task.dependsOn(jacocoAggregatedReport);
+ });
+ }
+ }
+ }
+
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+
+ if (project != project.getRootProject()) {
+ project.getRootProject().getPlugins().apply(RootExtPlugin.class);
+ }
+
+ boolean withCoverage = addCoverageOptions(project);
+
+ if (withCoverage) {
+ project.getPlugins().apply(JacocoLogPlugin.class);
+
+ var jacocoTestReport =
+ configureJacocoReport(
+ project.getTasks(), "jacocoTestReport", "Code coverage report at: ");
+
+ TaskCollection<Test> testTasks = project.getTasks().withType(Test.class);
+
+ project
+ .getTasks()
+ .register(
+ "coverage",
+ task -> {
+ task.dependsOn(testTasks);
+ task.dependsOn(jacocoTestReport);
+ });
+
+ testTasks.configureEach(
+ task -> {
+ // Configure jacoco destination file to be within the test
+ // task's working directory
+ var jacoco = task.getExtensions().getByType(JacocoTaskExtension.class);
+ jacoco.setDestinationFile(
+ project
+ .getProviders()
+ .provider(() -> new File(task.getWorkingDir(), "jacoco.exec")));
+
+ // Test reports run after the test task, if it's run at all.
+ task.finalizedBy(jacocoTestReport);
+ });
+ }
+ }
+
+ private static TaskProvider<JacocoReport> configureJacocoReport(
+ TaskContainer tasks, String jacocoTaskName, String logLine) {
+ var jacocoAggregatedReport = tasks.withType(JacocoReport.class).named(jacocoTaskName);
+
+ jacocoAggregatedReport.configure(
+ task -> {
+ task.doLast(
+ _ -> {
+ task.getLogger()
+ .lifecycle(logLine + task.getReports().getHtml().getEntryPoint() + "\n");
+ });
+ });
+ return jacocoAggregatedReport;
+ }
+
+ private static boolean addCoverageOptions(Project project) {
+ // add a build option to run with coverage.
+ Provider<Boolean> coverageOption =
+ getBuildOptions(project)
+ .addBooleanOption(TESTS_COVERAGE_OPTION, "Enables jacoco test coverage.", false);
+
+ // Run with jacoco if either 'coverage' task is explicitly enabled or tests.coverage option is
+ // true.
+ return project.getGradle().getStartParameter().getTaskNames().contains("coverage")
+ || coverageOption.get();
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/CodeProfilingPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/CodeProfilingPlugin.java
new file mode 100644
index 00000000000..4b7847c62af
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/CodeProfilingPlugin.java
@@ -0,0 +1,257 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.java;
+
+import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsExtension;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.DefaultTask;
+import org.gradle.api.GradleException;
+import org.gradle.api.Project;
+import org.gradle.api.file.ConfigurableFileCollection;
+import org.gradle.api.file.ConfigurableFileTree;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.provider.ListProperty;
+import org.gradle.api.provider.Property;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.tasks.Delete;
+import org.gradle.api.tasks.IgnoreEmptyDirectories;
+import org.gradle.api.tasks.Input;
+import org.gradle.api.tasks.InputFiles;
+import org.gradle.api.tasks.PathSensitive;
+import org.gradle.api.tasks.PathSensitivity;
+import org.gradle.api.tasks.TaskAction;
+import org.gradle.api.tasks.TaskCollection;
+import org.gradle.api.tasks.TaskContainer;
+import org.gradle.api.tasks.testing.Test;
+
+/** This enables and configures JFR profiling for tests. */
+public class CodeProfilingPlugin extends LuceneGradlePlugin {
+
+ public abstract static class ShowJfrProfileSummaryTask extends DefaultTask {
+ static final String TASK_NAME = "showJfrProfileSummary";
+
+ @InputFiles
+ @PathSensitive(PathSensitivity.RELATIVE)
+ @IgnoreEmptyDirectories
+ public abstract ConfigurableFileCollection getJfrFiles();
+
+ @Input
+ public abstract Property<String> getMode();
+
+ @Input
+ public abstract Property<Integer> getStackSize();
+
+ @Input
+ public abstract Property<Integer> getCount();
+
+ @Input
+ public abstract Property<Boolean> getLineNumbers();
+
+ @Input
+ public abstract Property<Boolean> getFrametypes();
+
+ @Input
+ public abstract ListProperty<Boolean> getShouldRunConditions();
+
+ @TaskAction
+ public void run() {
+ try {
+ if (getShouldRunConditions().get().stream().anyMatch(value -> value == false)) {
+ getLogger().lifecycle("One of the test tasks failed, skipping.");
+ return;
+ }
+
+ List<String> jfrFiles = getJfrFiles().getFiles().stream().map(File::toString).toList();
+ getLogger()
+ .lifecycle(
+ "Aggregated summary of {} jfr {}.",
+ jfrFiles.size(),
+ jfrFiles.size() == 1 ? "profile" : "profiles");
+ ProfileResults.printReport(
+ jfrFiles,
+ getMode().get(),
+ getStackSize().get(),
+ getCount().get(),
+ getLineNumbers().get(),
+ getFrametypes().get());
+ } catch (IOException e) {
+ throw new GradleException("Error when generating jfr profile summaries.", e);
+ }
+ }
+ }
+
+ public static class CodeProfilingRootExtPlugin extends LuceneGradlePlugin {
+ @Override
+ public void apply(Project project) {
+ applicableToRootProjectOnly(project);
+
+ ProfilingOptions options = addProfilingOptions(project);
+ if (options.profileOption.get()) {
+ project
+ .getRootProject()
+ .getTasks()
+ .register(
+ ShowJfrProfileSummaryTask.TASK_NAME,
+ ShowJfrProfileSummaryTask.class,
+ task -> {
+ task.getMode().set(options.modeOption);
+ task.getStackSize().set(options.stackSizeOption);
+ task.getCount().set(options.countOption);
+ task.getLineNumbers().set(options.lineNumbersOption);
+ task.getFrametypes().set(options.frametypesOption);
+ });
+ }
+ }
+ }
+
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+
+ if (project != project.getRootProject()) {
+ project.getRootProject().getPlugins().apply(CodeProfilingRootExtPlugin.class);
+ }
+
+ ProfilingOptions options = addProfilingOptions(project);
+ if (options.profileOption().get()) {
+ boolean hasJavaFlightRecorder =
+ ModuleLayer.boot()
+ .findModule("jdk.jfr")
+ .map(jfrModule -> this.getClass().getModule().canRead(jfrModule))
+ .orElse(false);
+ if (!hasJavaFlightRecorder) {
+ throw new GradleException(
+ "Module jdk.jfr is not available; Java Flight Recorder profiles cannot be enabled.");
+ }
+
+ TaskContainer tasks = project.getTasks();
+ TaskCollection<Test> testTasks = tasks.withType(Test.class);
+
+ // jfr files are generated in each Test task's working dir.
+ Provider<List<ConfigurableFileTree>> jfrFiles =
+ project
+ .getProviders()
+ .provider(
+ () -> {
+ return testTasks.stream()
+ .map(Test::getWorkingDir)
+ .map(
+ dir ->
+ project.fileTree(
+ dir,
+ cft -> {
+ cft.include("*.jfr");
+ }))
+ .toList();
+ });
+
+ // wipe any previous jfr files.
+ var cleanPreviousProfiles =
+ tasks.register(
+ "cleanPreviousJfrProfiles",
+ Delete.class,
+ task -> {
+ task.delete(jfrFiles);
+ });
+
+ // One global task to display profiling summary.
+ var showProfileSummary =
+ project
+ .getRootProject()
+ .getTasks()
+ .withType(ShowJfrProfileSummaryTask.class)
+ .named(ShowJfrProfileSummaryTask.TASK_NAME);
+ showProfileSummary.configure(
+ task -> {
+ task.getJfrFiles().from(jfrFiles);
+ });
+
+ // configure Test tasks to start with the jfr.
+ testTasks.configureEach(
+ task -> {
+ task.jvmArgs(
+ List.of(
+ "-XX:StartFlightRecording=dumponexit=true,maxsize=250M,settings="
+ + gradlePluginResource(project, "testing/profiling.jfc"),
+ "-XX:+UnlockDiagnosticVMOptions",
+ "-XX:+DebugNonSafepoints"));
+ task.dependsOn(cleanPreviousProfiles);
+ task.finalizedBy(showProfileSummary);
+
+ showProfileSummary.configure(
+ t -> {
+ t.getShouldRunConditions()
+ .add(
+ project
+ .getProviders()
+ .provider(
+ () -> {
+ return task.getState().getFailure() == null;
+ }));
+ });
+ });
+ }
+ }
+
+ private static ProfilingOptions addProfilingOptions(Project project) {
+ BuildOptionsExtension buildOptions = getBuildOptions(project);
+ Provider<Boolean> profileOption =
+ buildOptions.addBooleanOption(
+ "tests.profile", "Enable Java Flight Recorder profiling.", false);
+ Provider<String> modeOption =
+ buildOptions.addOption(
+ ProfileResults.MODE_KEY, "Profiling mode.", ProfileResults.MODE_DEFAULT);
+ Provider<Integer> stackSizeOption =
+ buildOptions.addIntOption(
+ ProfileResults.STACKSIZE_KEY,
+ "Profiling stack size.",
+ Integer.parseInt(ProfileResults.STACKSIZE_DEFAULT));
+ Provider<Integer> countOption =
+ buildOptions.addIntOption(
+ ProfileResults.COUNT_KEY,
+ "Profiling entry count.",
+ Integer.parseInt(ProfileResults.COUNT_DEFAULT));
+ Provider<Boolean> lineNumbersOption =
+ buildOptions.addBooleanOption(
+ ProfileResults.LINENUMBERS_KEY,
+ "Profiling with line numbers.",
+ Boolean.parseBoolean(ProfileResults.LINENUMBERS_KEY));
+ Provider<Boolean> frametypesOption =
+ buildOptions.addBooleanOption(
+ ProfileResults.FRAMETYPES_KEY,
+ "Profiling frame types.",
+ Boolean.parseBoolean(ProfileResults.FRAMETYPES_DEFAULT));
+ return new ProfilingOptions(
+ profileOption,
+ modeOption,
+ stackSizeOption,
+ countOption,
+ lineNumbersOption,
+ frametypesOption);
+ }
+
+ private record ProfilingOptions(
+ Provider<Boolean> profileOption,
+ Provider<String> modeOption,
+ Provider<Integer> stackSizeOption,
+ Provider<Integer> countOption,
+ Provider<Boolean> lineNumbersOption,
+ Provider<Boolean> frametypesOption) {}
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/EcjLintPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/EcjLintPlugin.java
index 149c1140d11..41b38c63cb5 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/EcjLintPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/EcjLintPlugin.java
@@ -47,6 +47,7 @@ import org.gradle.process.CommandLineArgumentProvider;
*/
public class EcjLintPlugin extends LuceneGradlePlugin {
public static final String TASK_PREFIX = "ecjLint";
+ public static final String ECJ_LINT_PREFS_PATH = "validation/ecj-lint/ecj.javadocs.prefs";
/*
* Using an explicit dependency means we can't be as flexible in using interim "drops" of ecj,
@@ -58,7 +59,7 @@ public class EcjLintPlugin extends LuceneGradlePlugin {
public void apply(Project project) {
requiresAppliedPlugin(project, JavaPlugin.class);
- Path javadocPrefsPath = gradlePluginResource(project, "validation/ecj-lint/ecj.javadocs.prefs");
+ Path javadocPrefsPath = gradlePluginResource(project, ECJ_LINT_PREFS_PATH);
// Create a [sourceSetName]EcjLint task for each source set
// with a non-empty java.srcDirs. These tasks are then
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/FailOnNoMatchingFilteredTestsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/FailOnNoMatchingFilteredTestsPlugin.java
new file mode 100644
index 00000000000..2a1b30ec6c0
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/FailOnNoMatchingFilteredTestsPlugin.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.gradle.plugins.java;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.inject.Inject;
+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;
+import org.gradle.api.GradleException;
+import org.gradle.api.Project;
+import org.gradle.api.plugins.JavaPlugin;
+import org.gradle.api.provider.Provider;
+import org.gradle.api.services.BuildService;
+import org.gradle.api.services.BuildServiceParameters;
+import org.gradle.api.tasks.testing.Test;
+import org.gradle.api.tasks.testing.TestDescriptor;
+import org.gradle.api.tasks.testing.TestListener;
+import org.gradle.api.tasks.testing.TestResult;
+
+/**
+ * This plugin implements the logic to fail the build if {@code --tests} filters have been provided
+ * on command line and no matching tests have been found (in any module). A situation like this is
+ * usually caused by a typo in the filter pattern.
+ */
+public class FailOnNoMatchingFilteredTestsPlugin extends LuceneGradlePlugin {
+ private static final String SERVICE_NAME = "testCountService";
+ private static final String CHECK_TASK_NAME = "checkAnyTestIncludedAfterFiltering";
+
+ public abstract static class RootExtPlugin extends LuceneGradlePlugin {
+ @Override
+ public void apply(Project project) {
+ applicableToRootProjectOnly(project);
+
+ // Register the shared build service that will do the end-of-build check
+ Provider<TestCountService> serviceProvider =
+ project
+ .getGradle()
+ .getSharedServices()
+ .registerIfAbsent(SERVICE_NAME, TestCountService.class, _ -> {});
+
+ project
+ .getTasks()
+ .register(
+ CHECK_TASK_NAME,
+ task -> {
+ task.usesService(serviceProvider);
+ task.doFirst(
+ _ -> {
+ var service = serviceProvider.get();
+ int tasks = service.executedTasks.get();
+ int tests = service.executedTests.get();
+ if (tasks > 0 && tests == 0) {
+ throw new GradleException(
+ String.format(
+ Locale.ROOT,
+ "%d test %s executed but no tests matched the provided --tests filters?",
+ tasks,
+ tasks == 1 ? "task" : "tasks"));
+ }
+ });
+ });
+ }
+ }
+
+ @Override
+ public void apply(Project project) {
+ requiresAppliedPlugin(project, JavaPlugin.class);
+
+ if (project != project.getRootProject()) {
+ project.getRootProject().getPlugins().apply(RootExtPlugin.class);
+ }
+
+ // Detect if test filtering is in effect.
+ List<String> taskNames = project.getGradle().getStartParameter().getTaskNames();
+ boolean doCount = taskNames.stream().anyMatch("--tests"::equals);
+
+ project
+ .getTasks()
+ .withType(Test.class)
+ .configureEach(
+ task -> {
+ // Always: do not fail the Test task itself on no matching tests
+ task.getFilter().setFailOnNoMatchingTests(false);
+
+ if (doCount) {
+ @SuppressWarnings("unchecked")
+ Provider<TestCountService> service =
+ (Provider<TestCountService>)
+ project
+ .getGradle()
+ .getSharedServices()
+ .getRegistrations()
+ .getByName(SERVICE_NAME)
+ .getService();
+
+ task.usesService(service);
+ task.finalizedBy(":" + CHECK_TASK_NAME);
+ task.doFirst(_ -> service.get().incrementExecutedTasks());
+ task.addTestListener(
+ new TestListener() {
+ @Override
+ public void beforeSuite(TestDescriptor suite) {}
+
+ @Override
+ public void afterSuite(TestDescriptor suite, TestResult result) {
+ service.get().addExecutedTests((int) result.getTestCount());
+ }
+
+ @Override
+ public void beforeTest(TestDescriptor testDescriptor) {}
+
+ @Override
+ public void afterTest(TestDescriptor testDescriptor, TestResult result) {}
+ });
+ }
+ });
+ }
+
+ /**
+ * Build service that tracks executed test tasks and total tests, and fails the build at
+ * completion if test filtering was applied and no tests ran.
+ */
+ public abstract static class TestCountService
+ implements BuildService<BuildServiceParameters.None> {
+ private final AtomicInteger executedTests = new AtomicInteger(0);
+ private final AtomicInteger executedTasks = new AtomicInteger(0);
+
+ @Inject
+ public TestCountService() {}
+
+ void incrementExecutedTasks() {
+ executedTasks.incrementAndGet();
+ }
+
+ void addExecutedTests(int n) {
+ executedTests.addAndGet(n);
+ }
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaProjectConventionsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaProjectConventionsPlugin.java
index fcd6f8a8fff..0d5b50cc691 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaProjectConventionsPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/JavaProjectConventionsPlugin.java
@@ -51,5 +51,8 @@ public class JavaProjectConventionsPlugin extends LuceneGradlePlugin {
plugins.apply(ApplyForbiddenApisPlugin.class);
plugins.apply(EcjLintPlugin.class);
plugins.apply(GoogleJavaFormatPlugin.class);
+ plugins.apply(CodeProfilingPlugin.class);
+ plugins.apply(FailOnNoMatchingFilteredTestsPlugin.class);
+ plugins.apply(CodeCoveragePlugin.class);
}
}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ProfileResults.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/ProfileResults.java
similarity index 99%
rename from build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ProfileResults.java
rename to build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/ProfileResults.java
index 5507150234b..e4073c9e56f 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/ProfileResults.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/ProfileResults.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.lucene.gradle;
+package org.apache.lucene.gradle.plugins.java;
import java.io.IOException;
import java.nio.file.Paths;
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java
index bdec45b1d76..d8e4ba18c50 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java
@@ -28,6 +28,8 @@ import org.apache.lucene.gradle.plugins.hacks.HacksPlugin;
import org.apache.lucene.gradle.plugins.hacks.TuneJvmOptionsPlugin;
import org.apache.lucene.gradle.plugins.hacks.WipeGradleTempPlugin;
import org.apache.lucene.gradle.plugins.help.BuildOptionGroupsPlugin;
+import org.apache.lucene.gradle.plugins.ide.EclipseSupportPlugin;
+import org.apache.lucene.gradle.plugins.ide.IdeaSupportPlugin;
import org.apache.lucene.gradle.plugins.regenerate.RegenerateTasksSupportPlugin;
import org.apache.lucene.gradle.plugins.spotless.GradleGroovyFormatPlugin;
import org.apache.lucene.gradle.plugins.spotless.ValidateSourcePatternsPlugin;
@@ -77,6 +79,9 @@ public class RootProjectSetupPlugin extends LuceneGradlePlugin {
plugins.apply(ConfigureLockFilePlugin.class);
plugins.apply(CheckGradlewScriptsTweakedPlugin.class);
+ plugins.apply(EclipseSupportPlugin.class);
+ plugins.apply(IdeaSupportPlugin.class);
+
// Apply more convention plugins to all projects.
rootProject
.getAllprojects()
diff --git a/build.gradle b/build.gradle
index 36a3f0bdc1f..fd78dceaa9d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -27,11 +27,8 @@ plugins {
id "lucene.root-project.setup"
id "lucene.java-projects.conventions"
- id "lucene.java.fail-on-no-tests"
id "lucene.java.slowest-tests-at-end"
id "lucene.java.show-failed-tests-at-end"
- id "lucene.java.profiling"
- id "lucene.java.coverage"
id "lucene.java.modules"
id "lucene.validation.gradle-versions-cleanup"
@@ -40,9 +37,6 @@ plugins {
id "lucene.validation.rat-sources"
id "lucene.validation.owasp"
- id "lucene.ide.intellij-idea"
- id "lucene.ide.eclipse"
-
id "lucene.publications.maven"
id "lucene.publications.maven-to-nexus-releases"
id "lucene.publications.maven-to-nexus-snapshots"