Apache Lucene open-source search software
Convert more gradle convention plugins to java (#14981)
Dawid Weiss5ba547954c56
diff --git a/build-tools/build-infra-shadow/build.gradle b/build-tools/build-infra-shadow/build.gradleindex 76d4abef2d7..5a41ed1e90c 100644--- a/build-tools/build-infra-shadow/build.gradle+++ b/build-tools/build-infra-shadow/build.gradle@@ -44,6 +44,9 @@ dependencies {implementation localGroovy()implementation deps.commons.codecimplementation deps.randomizedtesting.runner+ implementation deps.rat+ implementation deps.zstd+implementation deps.gjfimplementation deps.jgitimplementation deps.ecj@@ -51,6 +54,7 @@ dependencies {implementation plugin(deps.plugins.carrotsearch.buildopts)implementation plugin(deps.plugins.carrotsearch.dependencychecks)implementation plugin(deps.plugins.forbiddenapis)+ implementation plugin(deps.plugins.spotless)implementation plugin(deps.plugins.undercouch.download)}diff --git a/build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradle b/build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradleindex dd5243a352c..0a3b0bc544a 100644--- a/build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradle+++ b/build-tools/build-infra/src/main/groovy/lucene.documentation.render-javadoc.gradle@@ -324,10 +324,6 @@ abstract class RenderJavadocTask extends RenderJavadocTaskBase {@InputList<String> javadocMissingIgnore = []- @Input- @Optional- ListProperty<String> extraOpts = project.objects.listProperty(String)-@InputDirectory@PathSensitive(PathSensitivity.RELATIVE)@IgnoreEmptyDirectoriesdiff --git a/build-tools/build-infra/src/main/groovy/lucene.hacks.turbocharge-jvm-opts.gradle b/build-tools/build-infra/src/main/groovy/lucene.hacks.turbocharge-jvm-opts.gradledeleted file mode 100644index da4f717e8e8..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.hacks.turbocharge-jvm-opts.gradle+++ /dev/null@@ -1,75 +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.- */--// LUCENE-9861: tune JVM options for short-lived java subprocesses.--allprojects {- def vmOpts = [- '-XX:+UseParallelGC',- '-XX:TieredStopAtLevel=1',- '-XX:ActiveProcessorCount=1'- ]-- // Inject vm options into custom javadoc rendering. We can't refer- // to the task type because it's dynamic.- tasks.matching {- it.name in [- "renderJavadoc",- "renderSiteJavadoc"- ]- }.configureEach {- extraOpts.addAll(vmOpts.collect {"-J" + it})- }-- // Inject vm options into any JavaExec task... We could narrow it- // down but I don't think there is any harm in keeping it broad.- tasks.withType(JavaExec).configureEach { task ->- // Skip tuning java exec for benchmarks.- if (task.path == ":lucene:benchmark:run") {- return- }-- jvmArgs += vmOpts- }-- // Tweak javac to not be too resource-hungry.- // This applies to any JVM when javac runs forked (e.g. error-prone)- // Avoiding the fork entirely is best.- tasks.withType(JavaCompile).configureEach { JavaCompile task ->- task.options.forkOptions.jvmArgumentProviders.add(new CommandLineArgumentProvider() {- @Override- Iterable<String> asArguments() {- // Gradle bug: https://github.com/gradle/gradle/issues/22746- //- // Evaluation of this block is delayed until execution time when- // we know which "mode" java compiler task will pick and can set arguments- // accordingly.- //- // There is a side-effect to this that arguments passed via the provider- // are not part of up-to-date checks but these are internal JVM flags so we- // don't care.- //- // Pass VM options via -J when a custom javaHome is used and we're in fork mode.- if (task.options.fork && task.options.forkOptions.javaHome != null) {- return vmOpts.collect {"-J" + it}- } else {- return vmOpts- }- }- })- }-}diff --git a/build-tools/build-infra/src/main/groovy/lucene.java.core.mrjar.gradle b/build-tools/build-infra/src/main/groovy/lucene.java.core.mrjar.gradledeleted file mode 100644index 28be2f079e1..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.java.core.mrjar.gradle+++ /dev/null@@ -1,99 +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 de.thetaphi.forbiddenapis.gradle.CheckForbiddenApis--// Produce an MR-JAR for panama vector implementations--configure(project(":lucene:core")) {- plugins.withType(JavaPlugin).configureEach {- mrjarJavaVersions.each { jdkVersion ->- sourceSets.create("main${jdkVersion}") {- java {- srcDirs = ["src/java${jdkVersion}"]- }- }-- configurations["main${jdkVersion}Implementation"].extendsFrom(configurations.maybeCreate("implementation"))- dependencies.add("main${jdkVersion}Implementation", sourceSets.main.output)-- def apijar = apijars.file("jdk${jdkVersion}-api.jar")-- tasks.withType(CheckForbiddenApis).named("forbiddenApisMain${jdkVersion}").configure {- it.classpath = it.classpath + files(apijar)- }-- tasks.named("compileMain${jdkVersion}Java").configure {- // TODO: this depends on the order of argument configuration...- int releaseIndex = options.compilerArgs.indexOf("--release")- options.compilerArgs.removeAt(releaseIndex)- options.compilerArgs.removeAt(releaseIndex)-- // Remove conflicting options for the linter. #14782- options.compilerArgs.removeAll("-Xlint:options")-- options.compilerArgs += [- "-Xlint:-options",- "--add-exports",- "java.base/java.lang.foreign=ALL-UNNAMED",- // for compilation we patch the incubator packages into java.base, this has no effect on resulting class files:- "--add-exports",- "java.base/jdk.incubator.vector=ALL-UNNAMED",- ]-- def argsProvider = objects.newInstance(CompilerArgsProvider)- argsProvider.apiJarFile.set(apijar)- options.compilerArgumentProviders.add(argsProvider)- }- }-- tasks.named('jar').configure {- boolean needMRJAR = false- int minJavaVersion = Integer.parseInt(buildGlobals.getMinJavaVersion().get().majorVersion)-- mrjarJavaVersions.each { jdkVersion ->- // the sourceSet which corresponds to the minimum/base Java version- // will copy its output to root of JAR, all other sourceSets will go into MR-JAR folders:- boolean isBaseVersion = (jdkVersion.toString() as int) <= minJavaVersion- into(isBaseVersion ? '' : "META-INF/versions/${jdkVersion}") {- from sourceSets["main${jdkVersion}"].output- }- needMRJAR |= !isBaseVersion- }-- if (needMRJAR) {- manifest.attributes(- 'Multi-Release': 'true'- )- }- }- }-}--abstract class CompilerArgsProvider implements CommandLineArgumentProvider {- @InputFile- @PathSensitive(PathSensitivity.RELATIVE)- abstract RegularFileProperty getApiJarFile()-- @Override- Iterable<String> asArguments() {- return [- "--patch-module",- "java.base=${apiJarFile.get().asFile.absolutePath}".toString()- ]- }-}diff --git a/build-tools/build-infra/src/main/groovy/lucene.regenerate.extract-jdk-apis.gradle b/build-tools/build-infra/src/main/groovy/lucene.regenerate.extract-jdk-apis.gradledeleted file mode 100644index 33884dd4440..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.regenerate.extract-jdk-apis.gradle+++ /dev/null@@ -1,58 +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.- */--def resources = rootProject.file("gradle/regenerate/extract-jdk-apis")--configure(project(":lucene:core")) {- plugins.withType(JavaPlugin) {- mrjarJavaVersions.each { jdkVersion ->- def task = tasks.create(name: "generateJdkApiJar${jdkVersion}", type: JavaExec) {- description = "Regenerate the API-only JAR file with public Panama Vector API from JDK ${jdkVersion}"- group = "generation"-- javaLauncher = javaToolchains.launcherFor {- languageVersion = JavaLanguageVersion.of(jdkVersion)- }-- onlyIf {- try {- javaLauncher.get()- return true- } catch (Exception e) {- logger.warn('Launcher for Java {} is not available; skipping regeneration of Panama Vector API JAR.', jdkVersion)- logger.warn('Error: {}', e.cause?.message)- logger.warn("Please make sure to point env 'JAVA{}_HOME' to exactly JDK version {} or enable Gradle toolchain auto-download.", jdkVersion, jdkVersion)- return false- }- }-- mainClass = file("${resources}/ExtractJdkApis.java") as String- systemProperties = [- 'user.timezone': 'UTC',- 'file.encoding': 'UTF-8',- ]- args = [- buildGlobals.getMinJavaVersion().get().toString(),- jdkVersion,- apijars.file("jdk${jdkVersion}-api.jar"),- ]- }-- regenerate.dependsOn task- }- }-}diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.gradlew-scripts-customizations.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.gradlew-scripts-customizations.gradledeleted file mode 100644index 0c4d5e38a07..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.validation.gradlew-scripts-customizations.gradle+++ /dev/null@@ -1,46 +0,0 @@-import java.nio.charset.StandardCharsets--/*- * 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.- */--// Check if Lucene customizations to gradlew scripts are present.--if (project != project.rootProject) {- throw new GradleException("Applicable to rootProject only: " + project.path)-}--def gradlewScriptsTweaked = tasks.register("gradlewScriptsTweaked", {- def scripts = [- file("gradlew"),- file("gradlew.bat")- ]-- inputs.files(scripts)-- doFirst {- scripts.each { file ->- def content = new String(file.readBytes(), StandardCharsets.US_ASCII)- if (content.indexOf("START OF LUCENE CUSTOMIZATION") < 0) {- throw new GradleException("Launch script ${file} does not have Lucene customizations?")- }- }- }-})--tasks.named("check").configure {- dependsOn gradlewScriptsTweaked-}diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.lockfile.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.lockfile.gradledeleted file mode 100644index a15cff8a2c5..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.validation.lockfile.gradle+++ /dev/null@@ -1,77 +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 com.carrotsearch.gradle.buildinfra.dependencychecks.DependencyChecksPlugin--// Configure dependency checks plugin which validates and updates the top-level-// versions.lock, taking care of cross-configuration consistency of transitive dependencies.-//-// https://github.com/carrotsearch/gradle-build-infra#plugin-comcarrotsearchgradlebuildinfradependencychecksdependencychecksplugin--allprojects {- // We don't care about the build infra deps in the lock file.- if (it.path == ":lucene:build-tools:build-infra-shadow") {- return- }-- plugins.apply(DependencyChecksPlugin)-- def mainConfigurations = project.configurations.matching {- it.name in [- "compileClasspath",- "runtimeClasspath"- ]- }-- def testConfigurations = project.configurations.matching {- it.name in [- "annotationProcessor",- "testCompileClasspath",- "testRuntimeClasspath"- ]- }-- dependencyVersionChecks {- lockFileComment = "An inventory of resolved dependency versions. Do not edit this file directly."-- configurationGroups {- main_dependencies {- include provider {- mainConfigurations.collect {- it.name- }- }- }-- test_dependencies {- include provider {- testConfigurations.collect {- it.name- }- }- }- }- }-- dependencies {- constraints {- mainConfigurations.configureEach { Configuration conf ->- // no resolutions for conflicting dependencies at the moment.- }- }- }-}diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.source-patterns.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.source-patterns.gradledeleted file mode 100644index d1728abba9c..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.validation.source-patterns.gradle+++ /dev/null@@ -1,185 +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 java.nio.charset.CharacterCodingException;-import java.nio.charset.CodingErrorAction;-import java.nio.charset.StandardCharsets;--import org.apache.rat.Defaults-import org.apache.rat.document.impl.FileDocument-import org.apache.rat.api.MetaData--import javax.inject.Inject;-import org.gradle.internal.logging.progress.ProgressLoggerFactory-import org.gradle.internal.logging.progress.ProgressLogger--if (project != project.rootProject) {- throw new GradleException("Applicable to rootProject only: " + project.path)-}--List<String> extensions = ['java', 'xml',]--// Create source validation task local to each project-allprojects {- def validateSourcePatterns = tasks.register("validateSourcePatterns", ValidateSourcePatternsTask, {- group = 'Verification'- description = 'Validate Source Patterns'-- sourceFiles = fileTree(projectDir) {- include extensions.collect { ext ->"**/*." + ext }-- // Don't go into child projects (scanned separately).- childProjects.keySet().each{- exclude "${it}/**"- }-- // default excludes.- exclude '**/build/**'- exclude '**/.idea/**'- exclude '**/.gradle/**'- // ignore txt files in source resources and tests.- exclude 'src/**/*.txt'- }- })-- // Add source validation to per-project checks as well.- tasks.named("check").configure {- dependsOn validateSourcePatterns- }-- // Ensure validation runs prior to any compilation task. This also means- // no executable code can leak out to other modules.- tasks.withType(JavaCompile).configureEach {- mustRunAfter validateSourcePatterns- }-}--project(':lucene:benchmark').tasks.withType(ValidateSourcePatternsTask).configureEach {- sourceFiles.exclude 'data/**'- sourceFiles.exclude 'work/**'- // Known .txt offenders.- sourceFiles.exclude '**/reuters.first20.lines.txt', '**/trecQRels.txt'-}--project(':').tasks.withType(ValidateSourcePatternsTask).configureEach {- // Exclude ourselves because there are invalid patterns in the invalid patterns list...- sourceFiles.exclude '**/lucene.validation.source-patterns.gradle'-}--@CacheableTask-class ValidateSourcePatternsTask extends DefaultTask {- private static final Object ratBug = new Object()- private ProgressLoggerFactory progressLoggerFactory-- @InputFiles- @PathSensitive(PathSensitivity.RELATIVE)- @IgnoreEmptyDirectories- FileTree sourceFiles-- @Inject- ValidateSourcePatternsTask(ProgressLoggerFactory progressLoggerFactory) {- this.progressLoggerFactory = progressLoggerFactory- }-- @TaskAction- public void check() {- def invalidPatterns = []-- def violations = new TreeSet();- def reportViolation = { f, name ->- String msg = String.format(Locale.ROOT, "%s: %s", f, name)- logger.error(msg)- violations.add(msg)- }-- def xmlCommentPattern = ~$/(?sm)\Q<!--\E(.*?)\Q-->\E/$;- def lineSplitter = ~$/[\r\n]+/$;- def xmlTagPattern = ~$/(?m)\s*<[a-zA-Z].*/$;-- def isLicense = { matcher, ratDocument ->- // See LUCENE-10419 - rat is not thread safe.- synchronized (ratBug) {- def licenseMatcher = Defaults.createDefaultMatcher();- licenseMatcher.reset()- return lineSplitter.split(matcher.group(1)).any { licenseMatcher.match(ratDocument, it) }- }- }-- def checkLicenseHeaderPrecedes = { f, description, contentPattern, commentPattern, text, ratDocument ->- def contentMatcher = contentPattern.matcher(text);- if (contentMatcher.find()) {- def contentStartPos = contentMatcher.start();- def commentMatcher = commentPattern.matcher(text);- while (commentMatcher.find()) {- if (isLicense(commentMatcher, ratDocument)) {- if (commentMatcher.start() < contentStartPos) {- break; // This file is all good, so break loop: license header precedes 'description' definition- } else {- reportViolation(f, description+' declaration precedes license header');- }- }- }- }- }-- ProgressLogger progress = progressLoggerFactory.newOperation(this.class)- progress.start(this.name, this.name)-- def validatingDecoder = StandardCharsets.UTF_8.newDecoder()- .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)-- sourceFiles.each { f ->- try {- progress.progress("Scanning ${f.name}")- logger.debug('Scanning source file: {}', f);-- String text- try {- validatingDecoder.reset()- text = f.withInputStream { input ->- new InputStreamReader(input, validatingDecoder).getText()- }- } catch (CharacterCodingException e) {- reportViolation(f, "incorrect UTF-8 encoding [${e}]")- return // we can't proceed for this file- }-- invalidPatterns.each { pattern, name ->- def matcher = pattern.matcher(text);- if (matcher.find()) {- reportViolation(f, String.format(Locale.ROOT, '%s [start=%d, end=%d]', name, matcher.start(), matcher.end()));- }- }- if (f.name.endsWith('.xml')) {- def ratDocument = new FileDocument(f);- checkLicenseHeaderPrecedes(f, '<tag>', xmlTagPattern, xmlCommentPattern, text, ratDocument);- }- } catch (e) {- e.printStackTrace()- throw new GradleException("Unhandled exception while validating patterns on file: " + f, e)- }- }-- progress.completed()-- if (!violations.isEmpty()) {- throw new GradleException(String.format(Locale.ENGLISH, 'Found %d source violation(s):\n %s',- violations.size(),- violations.join('\n ')))- }- }-}diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-groovy.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-groovy.gradledeleted file mode 100644index 18ea7b63cd5..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-groovy.gradle+++ /dev/null@@ -1,81 +0,0 @@-import com.diffplug.gradle.spotless.GroovyGradleExtension-import com.diffplug.gradle.spotless.SpotlessPlugin--/*- * 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.- */--// Apply spotless formatter to groovy code (gradle scripts in the build-infra plugin-// and possibly other places).--if (project != project.rootProject) {- throw new GradleException("Applicable to rootProject only: " + project.path)-}--plugins.apply(SpotlessPlugin.class)--def spotlessGradleScriptsOptionName = "lucene.spotlessGradleScripts"-Provider<Boolean> spotlessGradleScriptsOption = buildOptions.addBooleanOption(spotlessGradleScriptsOptionName,- "Enable formatting and validation of groovy/gradle scripts (you may want to turn it on locally if you" +- " work with gradle/groovy scripts)", false)--if (!spotlessGradleScriptsOption.get()) {- // register empty stubs for the corresponding set of spotless tasks.- [- "spotlessGradleScripts",- "spotlessGradleScriptsApply",- "spotlessGradleScriptsCheck"- ].each {taskName ->- tasks.register(taskName, {- doFirst {- logger.info("Spotless is turned off for gradle/groovy scripts. CI " +- "checks may not pass if you have formatting " +- "differences (enable '${spotlessGradleScriptsOptionName}' build option to check" +- "and apply gradle/groovy formatting).")- }- })- }-} else {- spotless.format("gradleScripts", GroovyGradleExtension.class, { ext ->- ext.greclipse()- ext.leadingTabsToSpaces(2)- ext.trimTrailingWhitespace()- ext.endWithNewline()- ext.target([- "build-tools/**/*.gradle",- "build-tools/**/*.groovy",- "**/build.gradle"- ])- })-}--tasks.named("spotlessGradleScripts").configure {- mustRunAfter ":lucene:build-tools:missing-doclet:applyGoogleJavaFormat"- mustRunAfter ":lucene:build-tools:missing-doclet:renderJavadoc"- mustRunAfter ":lucene:build-tools:missing-doclet:compileJava"- mustRunAfter ":lucene:build-tools:build-infra-shadow:applyGoogleJavaFormat"- mustRunAfter ":lucene:build-tools:build-infra-shadow:pluginUnderTestMetadata"- mustRunAfter ":lucene:build-tools:build-infra-shadow:pluginDescriptors"- mustRunAfter ":lucene:build-tools:build-infra-shadow:compileJava"-}--tasks.named("tidy").configure {- dependsOn ":spotlessGradleScriptsApply"-}--tasks.named("check").configure {- dependsOn ":spotlessGradleScriptsCheck"-}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.javaindex fa842d1c465..bc3f94197b6 100644--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.java+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/LuceneGradlePlugin.java@@ -70,7 +70,7 @@ public abstract class LuceneGradlePlugin implements Plugin<Project> {* Returns a filesystem path to a given resource that the plugin uses. At the moment, these* resources are located under the top-level {@code gradle/} folder.*/- protected final Path gradlePluginResource(Project project, String relativePath) {+ protected static Path gradlePluginResource(Project project, String relativePath) {return project.getLayout().getSettingsDirectory()@@ -81,7 +81,7 @@ public abstract class LuceneGradlePlugin implements Plugin<Project> {}/** Utility method returning {@link BuildOptionsExtension}. */- protected final BuildOptionsExtension getBuildOptions(Project project) {+ protected static BuildOptionsExtension getBuildOptions(Project project) {return project.getExtensions().getByType(BuildOptionsExtension.class);}@@ -89,7 +89,7 @@ public abstract class LuceneGradlePlugin implements Plugin<Project> {* Return the {@link org.apache.lucene.gradle.plugins.globals.LuceneBuildGlobalsExtension} with* global Lucene constants.*/- protected final LuceneBuildGlobalsExtension getLuceneBuildGlobals(Project project) {+ protected static LuceneBuildGlobalsExtension getLuceneBuildGlobals(Project project) {return project.getExtensions().getByType(LuceneBuildGlobalsExtension.class);}}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/HacksPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/HacksPlugin.javaindex 415f465e69d..89967f68ac8 100644--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/HacksPlugin.java+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/HacksPlugin.java@@ -17,7 +17,14 @@package org.apache.lucene.gradle.plugins.hacks;import de.undercouch.gradle.tasks.download.Download;+import java.io.File;+import java.io.IOException;+import java.io.UncheckedIOException;+import java.nio.file.Files;import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.apache.lucene.gradle.plugins.java.EcjLintPlugin;+import org.apache.lucene.gradle.plugins.misc.CheckGradlewScriptsTweakedPlugin;+import org.apache.lucene.gradle.plugins.spotless.ValidateSourcePatternsPlugin;import org.gradle.api.Project;/** This applies various odd hacks that we probably should not need. */@@ -32,6 +39,47 @@ public class HacksPlugin extends LuceneGradlePlugin {.forEach(project -> {applyRetryDownloads(project);+ addDummyOutputs(project);+ });+ }++ /**+ * Set up dummy outputs for certain tasks so that {@code clean[TaskName]} works, allowing re-runs+ * and incremental builds.+ *+ * @see "https://github.com/apache/lucene/issues/10544"+ */+ private void addDummyOutputs(Project project) {+ project+ .getTasks()+ .matching(+ task -> {+ var taskName = task.getName();+ return taskName.startsWith(EcjLintPlugin.TASK_PREFIX)+ || taskName.equals(CheckGradlewScriptsTweakedPlugin.TASK_NAME)+ || taskName.equals(ValidateSourcePatternsPlugin.TASK_NAME);+ })+ .configureEach(+ task -> {+ File dummyOutput =+ project+ .getLayout()+ .getBuildDirectory()+ .file("tasks/${task.name}/dummy-output.txt")+ .get()+ .getAsFile();+ task.getOutputs().file(dummyOutput);++ task.doLast(+ _ -> {+ if (!dummyOutput.exists()) {+ try {+ Files.createFile(dummyOutput.toPath());+ } catch (IOException e) {+ throw new UncheckedIOException(e);+ }+ }+ });});}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/TuneJvmOptionsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/TuneJvmOptionsPlugin.javanew file mode 100644index 00000000000..f73c9685a11--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/TuneJvmOptionsPlugin.java@@ -0,0 +1,103 @@+/*+ * 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.hacks;++import java.util.ArrayList;+import java.util.List;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.apache.lucene.gradle.plugins.java.RenderJavadocTaskBase;+import org.gradle.api.Project;+import org.gradle.api.tasks.JavaExec;+import org.gradle.api.tasks.compile.JavaCompile;+import org.gradle.process.CommandLineArgumentProvider;++/**+ * This plugin tunes JVM options for tasks that fork short-lived java subprocesses (if there are+ * such tasks).+ *+ * @see "https://github.com/apache/lucene/pull/33"+ */+public class TuneJvmOptionsPlugin extends LuceneGradlePlugin {++ private static final List<String> vmOpts =+ List.of("-XX:+UseParallelGC", "-XX:TieredStopAtLevel=1", "-XX:ActiveProcessorCount=1");++ @Override+ public void apply(Project project) {+ var tasks = project.getTasks();++ // Inject vm options into custom javadoc rendering.+ tasks+ .withType(RenderJavadocTaskBase.class)+ .configureEach(+ task -> {+ task.getExtraOpts().addAll(vmOpts.stream().map(it -> "-J" + it).toList());+ });++ // Inject vm options into any JavaExec task... We could narrow it+ // down, but I don't think there is any harm in keeping it broad.+ if (project.getPath().equals(":lucene:benchmark")) {+ // Skip this tuning in the benchmarks project.+ } else {+ tasks+ .withType(JavaExec.class)+ .configureEach(+ task -> {+ List<String> jvmArgs = new ArrayList<>(task.getJvmArgs());+ jvmArgs.addAll(vmOpts);+ task.setJvmArgs(jvmArgs);+ });+ }++ // Tweak javac to not be too resource-hungry.+ // This applies to any JVM when javac runs forked (e.g. error-prone)+ // Avoiding the fork entirely is best.+ tasks+ .withType(JavaCompile.class)+ .configureEach(+ task -> {+ task.getOptions()+ .getForkOptions()+ .getJvmArgumentProviders()+ .add(+ new CommandLineArgumentProvider() {+ @Override+ public Iterable<String> asArguments() {+ // Gradle bug: https://github.com/gradle/gradle/issues/22746+ //+ // Evaluation of this block is delayed until execution time when+ // we know which "mode" java compiler task will pick and can set arguments+ // accordingly.+ //+ // There is a side effect to this that arguments passed via the provider+ // are not part of up-to-date checks but these are internal JVM flags so+ // we+ // don't care.+ //+ // Pass VM options via -J when a custom javaHome is used, and we're in+ // fork mode.+ if (task.getOptions().isFork()+ && task.getOptions().getForkOptions().getJavaHome() != null) {+ return vmOpts.stream().map(it -> "-J" + it).toList();+ } else {+ return vmOpts;+ }+ }+ });+ });+ }+}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.javaindex 8c378f979e0..149c1140d11 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@@ -46,6 +46,7 @@ import org.gradle.process.CommandLineArgumentProvider;* "https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-using_batch_compiler.htm"*/public class EcjLintPlugin extends LuceneGradlePlugin {+ public static final String TASK_PREFIX = "ecjLint";/** Using an explicit dependency means we can't be as flexible in using interim "drops" of ecj,@@ -72,13 +73,13 @@ public class EcjLintPlugin extends LuceneGradlePlugin {.map(sourceSet ->tasks.register(- sourceSet.getTaskName("ecjLint", null),+ sourceSet.getTaskName(TASK_PREFIX, null),task -> configureEcjTask(sourceSet, javaExt, javadocPrefsPath, task))).toList();var ecjLintTask =tasks.register(- "ecjLint",+ TASK_PREFIX,task -> {task.setGroup("Verification");task.setDescription("Lint Java sources using ECJ.");diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/RenderJavadocTaskBase.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/RenderJavadocTaskBase.javaindex 176b726ea6f..dedf1c5af34 100644--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/RenderJavadocTaskBase.java+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/RenderJavadocTaskBase.java@@ -17,6 +17,7 @@package org.apache.lucene.gradle.plugins.java;import org.gradle.api.DefaultTask;+import org.gradle.api.provider.ListProperty;import org.gradle.api.provider.Property;import org.gradle.api.tasks.Input;import org.gradle.api.tasks.Optional;@@ -28,11 +29,17 @@ public abstract class RenderJavadocTaskBase extends DefaultTask {@Inputpublic abstract Property<String> getExecutable();+ @Input+ @Optional+ public abstract ListProperty<String> getExtraOpts();+public RenderJavadocTaskBase() {getExecutable().convention(getProject().getProviders().provider(() -> Jvm.current().getJavadocExecutable().toString()));++ getExtraOpts().set(getProject().getObjects().listProperty(String.class));}}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.javaindex e2e143009ab..865c0ac2fad 100644--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/java/TestsAndRandomizationPlugin.java@@ -432,8 +432,7 @@ public class TestsAndRandomizationPlugin extends LuceneGradlePlugin {var loggingFileProvider =project.getObjects().newInstance(LoggingFileArgumentProvider.class);- Path loggingConfigFile =- super.gradlePluginResource(project, "testing/logging.properties");+ Path loggingConfigFile = gradlePluginResource(project, "testing/logging.properties");loggingFileProvider.getLoggingConfigFile().set(loggingConfigFile.toFile());loggingFileProvider.getTempDir().set(tmpDirOption.get());task.getJvmArgumentProviders().add(loggingFileProvider);diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckGradlewScriptsTweakedPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckGradlewScriptsTweakedPlugin.javanew file mode 100644index 00000000000..6649fa15bac--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckGradlewScriptsTweakedPlugin.java@@ -0,0 +1,80 @@+/*+ * 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.misc;++import java.io.IOException;+import java.io.UncheckedIOException;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.stream.Stream;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.gradle.api.GradleException;+import org.gradle.api.Project;++/**+ * Check that gradlew scripts contain custom Lucene tweaks (memory settings, wrapper jar download+ * and verification, etc.). These can be accidentally overwritten if somebody updates the wrapper+ * automatically.+ */+public class CheckGradlewScriptsTweakedPlugin extends LuceneGradlePlugin {+ public static final String TASK_NAME = "gradlewScriptsTweaked";++ @Override+ public void apply(Project rootProject) {+ applicableToRootProjectOnly(rootProject);++ checkGradlewScriptsTweaked(rootProject);+ }++ private void checkGradlewScriptsTweaked(Project project) {+ var gradlewScriptsTweaked =+ project+ .getTasks()+ .register(+ TASK_NAME,+ task -> {+ var scripts =+ Stream.of("gradlew", "gradlew.bat")+ .map(+ name ->+ project.getLayout().getProjectDirectory().file(name).getAsFile())+ .toList();++ task.getInputs().files(scripts);+ task.doFirst(+ _ -> {+ try {+ for (var script : scripts) {+ var content = Files.readString(script.toPath(), StandardCharsets.UTF_8);+ if (!content.contains("START OF LUCENE CUSTOMIZATION")) {+ throw new GradleException(+ "Launch script "+ + script+ + " seems to be missing Lucene-specific"+ + " customizations (have you upgraded gradle wrapper?)."+ + " Review the history of this file and reapply the required tweaks.");+ }+ }+ } catch (IOException e) {+ throw new UncheckedIOException(e);+ }+ });+ });++ project.getTasks().named("check").configure(t -> t.dependsOn(gradlewScriptsTweaked));+ }+}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/ConfigureLockFilePlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/ConfigureLockFilePlugin.javanew file mode 100644index 00000000000..60e9dd33732--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/ConfigureLockFilePlugin.java@@ -0,0 +1,75 @@+/*+ * 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.misc;++import com.carrotsearch.gradle.buildinfra.dependencychecks.DependencyChecksPlugin;+import com.carrotsearch.gradle.buildinfra.dependencychecks.DependencyVersionChecksExtension;+import java.util.Set;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.gradle.api.Project;++/**+ * Configure dependency checks plugin which validates and updates the top-level {@code+ * versions.lock}, taking care of cross-configuration consistency of transitive dependencies.+ *+ * @see "https://github.com/apache/lucene/blob/main/help/dependencies.txt"+ * @see+ * "https://github.com/carrotsearch/gradle-build-infra#plugin-comcarrotsearchgradlebuildinfradependencychecksdependencychecksplugin"+ */+public class ConfigureLockFilePlugin extends LuceneGradlePlugin {++ @Override+ public void apply(Project rootProject) {+ applicableToRootProjectOnly(rootProject);++ rootProject.allprojects(+ project -> {+ // We don't care about the build infra deps in the lock file.+ if (project.getPath().equals(":lucene:build-tools:build-infra-shadow")) {+ return;+ }++ configureLockFile(project);+ });+ }++ private void configureLockFile(Project project) {+ project.getPlugins().apply(DependencyChecksPlugin.class);++ Set<String> includedMainConfigurations = Set.of("compileClasspath", "runtimeClasspath");+ Set<String> includedTestConfigurations =+ Set.of("annotationProcessor", "testCompileClasspath", "testRuntimeClasspath");++ var mainConfigurations =+ project+ .getConfigurations()+ .matching(conf -> includedMainConfigurations.contains(conf.getName()));++ var testConfigurations =+ project+ .getConfigurations()+ .matching(conf -> includedTestConfigurations.contains(conf.getName()));++ var ext = project.getExtensions().getByType(DependencyVersionChecksExtension.class);+ ext.getLockFileComment()+ .set("An inventory of resolved dependency versions. Do not edit this file directly.");++ var configurationGroups = ext.getConfigurationGroups();+ configurationGroups.create("main_dependencies").include(mainConfigurations);+ configurationGroups.create("test_dependencies").include(testConfigurations);+ }+}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.javaindex 195a60b70a9..bdec45b1d76 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@@ -18,7 +18,6 @@ package org.apache.lucene.gradle.plugins.misc;import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsPlugin;import java.util.Collection;-import java.util.List;import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;import org.apache.lucene.gradle.plugins.astgrep.AstGrepPlugin;import org.apache.lucene.gradle.plugins.eclint.EditorConfigLintPlugin;@@ -26,15 +25,17 @@ import org.apache.lucene.gradle.plugins.gitgrep.GitGrepPlugin;import org.apache.lucene.gradle.plugins.gitinfo.GitInfoPlugin;import org.apache.lucene.gradle.plugins.globals.RegisterBuildGlobalsPlugin;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.regenerate.RegenerateTasksSupportPlugin;+import org.apache.lucene.gradle.plugins.spotless.GradleGroovyFormatPlugin;+import org.apache.lucene.gradle.plugins.spotless.ValidateSourcePatternsPlugin;import org.gradle.api.Project;import org.gradle.api.file.DuplicatesStrategy;import org.gradle.api.initialization.IncludedBuild;import org.gradle.api.plugins.BasePlugin;import org.gradle.api.plugins.BasePluginExtension;-import org.gradle.api.plugins.ExtraPropertiesExtension;import org.gradle.api.plugins.PluginContainer;import org.gradle.api.tasks.TaskContainer;import org.gradle.api.tasks.bundling.AbstractArchiveTask;@@ -71,18 +72,21 @@ public class RootProjectSetupPlugin extends LuceneGradlePlugin {plugins.apply(HelpPlugin.class);plugins.apply(HacksPlugin.class);plugins.apply(WipeGradleTempPlugin.class);+ plugins.apply(GradleGroovyFormatPlugin.class);+ plugins.apply(ValidateSourcePatternsPlugin.class);+ plugins.apply(ConfigureLockFilePlugin.class);+ plugins.apply(CheckGradlewScriptsTweakedPlugin.class);++ // Apply more convention plugins to all projects.+ rootProject+ .getAllprojects()+ .forEach(+ project -> {+ project.getPlugins().apply(TuneJvmOptionsPlugin.class);+ });// wire up included composite builds to validation tasks.connectCompositeTasksToMainBuild(rootProject);-- // TODO: this shouldn't be here but it's used in multiple scripts that are racy in- // lazy-evaluation.- {- Project project = rootProject.project(":lucene:core");- var ext = project.getExtensions().getByType(ExtraPropertiesExtension.class);- ext.set("mrjarJavaVersions", List.of(24));- ext.set("apijars", project.getLayout().getProjectDirectory().dir("src/generated/jdk"));- }}private void applyCommonConfiguration(Project project) {diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/ExtractJdkApis.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/ExtractJdkApis.javanew file mode 100644index 00000000000..e18993a3a23--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/ExtractJdkApis.java@@ -0,0 +1,264 @@+/*+ * 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.mrjar;++import java.io.IOException;+import java.lang.classfile.AccessFlags;+import java.lang.classfile.Attributes;+import java.lang.classfile.ClassFile;+import java.lang.classfile.ClassFileBuilder;+import java.lang.classfile.ClassFileElement;+import java.lang.classfile.ClassFileVersion;+import java.lang.classfile.ClassModel;+import java.lang.classfile.ClassTransform;+import java.lang.classfile.CodeModel;+import java.lang.classfile.FieldModel;+import java.lang.classfile.MethodModel;+import java.lang.classfile.MethodTransform;+import java.lang.classfile.attribute.InnerClassesAttribute;+import java.lang.classfile.attribute.RuntimeInvisibleAnnotationsAttribute;+import java.lang.classfile.attribute.SourceFileAttribute;+import java.lang.classfile.constantpool.ClassEntry;+import java.lang.constant.ClassDesc;+import java.lang.invoke.MethodHandles;+import java.lang.reflect.AccessFlag;+import java.lang.reflect.ClassFileFormatVersion;+import java.net.URI;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.PathMatcher;+import java.nio.file.Paths;+import java.nio.file.attribute.FileTime;+import java.time.Instant;+import java.util.Arrays;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Objects;+import java.util.Set;+import java.util.TreeMap;+import java.util.function.Predicate;+import java.util.stream.Collectors;+import java.util.stream.Stream;+import java.util.zip.ZipEntry;+import java.util.zip.ZipOutputStream;++/**+ * Extract API stubs from future JDK versions. This class must not have any dependencies outside of+ * the standard library.+ */+public final class ExtractJdkApis {+ private static final FileTime FIXED_FILEDATE =+ FileTime.from(Instant.parse("2025-05-05T00:00:00Z"));++ private static final String PATTERN_VECTOR_INCUBATOR =+ "jdk.incubator.vector/jdk/incubator/vector/*";+ private static final String PATTERN_VECTOR_VM_INTERNALS =+ "java.base/jdk/internal/vm/vector/VectorSupport{,$Vector,$VectorMask,$VectorPayload,$VectorShuffle}";++ static final Map<Integer, List<String>> CLASSFILE_PATTERNS =+ Map.of(24, List.of(PATTERN_VECTOR_VM_INTERNALS, PATTERN_VECTOR_INCUBATOR));++ private static final ClassDesc CD_PreviewFeature =+ ClassDesc.ofInternalName("jdk/internal/javac/PreviewFeature");++ public static void main(String... args) throws IOException {+ if (args.length != 3) {+ throw new IllegalArgumentException(+ "Required parameters: [target java version] [extract java version] [output apijar file], received: "+ + List.of(args));+ }+ int targetJdk = Integer.parseInt(args[0]);+ Integer extractJdk = Integer.valueOf(args[1]);+ int runtimeJdk = Runtime.version().feature();+ if (extractJdk.intValue() != runtimeJdk) {+ throw new IllegalStateException("Incorrect runtime java version: " + runtimeJdk);+ }+ if (extractJdk.intValue() < targetJdk) {+ throw new IllegalStateException(+ "extract java version " + extractJdk + " < target java version " + targetJdk);+ }+ if (!CLASSFILE_PATTERNS.containsKey(extractJdk)) {+ throw new IllegalArgumentException(+ "No support to extract stubs from java version: " + extractJdk);+ }+ var outputPath = Paths.get(args[2]);++ // the output class files need to be compatible with the targetJdk of our compilation, so we+ // need to adapt them:+ var classFileVersion =+ ClassFileVersion.of(ClassFileFormatVersion.valueOf("RELEASE_" + targetJdk).major(), 0);++ // create JRT filesystem and build a combined FileMatcher:+ var jrtPath = Paths.get(URI.create("jrt:/")).toRealPath();+ var patterns =+ CLASSFILE_PATTERNS.get(extractJdk).stream()+ .map(pattern -> jrtPath.getFileSystem().getPathMatcher("glob:" + pattern + ".class"))+ .toArray(PathMatcher[]::new);+ PathMatcher pattern = p -> Arrays.stream(patterns).anyMatch(matcher -> matcher.matches(p));++ // Collect all files to process:+ final List<Path> filesToExtract;+ try (var stream = Files.walk(jrtPath)) {+ filesToExtract = stream.filter(p -> pattern.matches(jrtPath.relativize(p))).toList();+ }++ // Process all class files:+ try (var out = new ZipOutputStream(Files.newOutputStream(outputPath))) {+ process(filesToExtract, out, classFileVersion);+ }+ }++ private static void process(+ List<Path> filesToExtract, ZipOutputStream out, ClassFileVersion classFileVersion)+ throws IOException {+ System.out.println("Loading and analyzing " + filesToExtract.size() + " class files...");+ var classesToInclude = new HashSet<String>();+ var toProcess = new TreeMap<String, ClassModel>();+ var cc =+ ClassFile.of(+ ClassFile.ConstantPoolSharingOption.NEW_POOL,+ ClassFile.DebugElementsOption.DROP_DEBUG,+ ClassFile.LineNumbersOption.DROP_LINE_NUMBERS,+ ClassFile.StackMapsOption.DROP_STACK_MAPS);+ for (Path p : filesToExtract) {+ ClassModel parsed = cc.parse(p);+ String internalName = parsed.thisClass().asInternalName();+ toProcess.put(internalName, parsed);+ if (isVisible(parsed.flags())) {+ classesToInclude.add(internalName);+ }+ }+ // recursively add all superclasses / interfaces / outer classes of visible classes to+ // classesToInclude:+ for (Set<String> a = classesToInclude; !a.isEmpty(); ) {+ classesToInclude.addAll(+ a =+ a.stream()+ .map(toProcess::get)+ .filter(Objects::nonNull)+ .flatMap(ExtractJdkApis::getReferences)+ .collect(Collectors.toSet()));+ }+ // remove all non-visible or not referenced classes:+ toProcess.keySet().removeIf(Predicate.not(classesToInclude::contains));+ // transformation of class files:+ System.out.println("Writing " + toProcess.size() + " visible classes...");+ for (var parsed : toProcess.values()) {+ String internalName = parsed.thisClass().asInternalName();+ System.out.println("Writing stub for class: " + internalName);+ ClassTransform ct =+ ClassTransform.dropping(+ ce ->+ switch (ce) {+ case MethodModel e -> !isVisible(e.flags());+ case FieldModel e -> !isVisible(e.flags());+ case SourceFileAttribute _ -> true;+ default -> false;+ })+ .andThen(+ (builder, ce) -> {+ switch (ce) {+ case ClassFileVersion _ -> builder.with(classFileVersion);+ // the PreviewFeature annotation may refer to its own inner classes and+ // therefore we must get rid of the inner class entry:+ case InnerClassesAttribute a ->+ builder.with(+ InnerClassesAttribute.of(+ a.classes().stream()+ .filter(+ c ->+ !CD_PreviewFeature.equals(+ c.outerClass()+ .map(ClassEntry::asSymbol)+ .orElse(null)))+ .toList()));+ default -> builder.with(ce);+ }+ })+ .andThen(ExtractJdkApis::dropPreview)+ .andThen(+ ClassTransform.transformingMethods(+ MethodTransform.dropping(CodeModel.class::isInstance)+ .andThen(ExtractJdkApis::dropPreview))+ .andThen(ClassTransform.transformingFields(ExtractJdkApis::dropPreview)));+ out.putNextEntry(+ new ZipEntry(internalName.concat(".class")).setLastModifiedTime(FIXED_FILEDATE));+ out.write(cc.transformClass(parsed, ct));+ out.closeEntry();+ }+ // make sure that no classes are left over except those which are in java.base module+ classesToInclude.removeIf(toProcess.keySet()::contains);+ var missingClasses =+ classesToInclude.stream()+ .filter(+ internalName -> {+ try {+ return ClassDesc.ofInternalName(internalName)+ .resolveConstantDesc(MethodHandles.publicLookup())+ .getModule()+ != Object.class.getModule();+ } catch (ReflectiveOperationException _) {+ return true;+ }+ })+ .sorted()+ .toList();+ if (!missingClasses.isEmpty()) {+ throw new IllegalStateException(+ "Some referenced classes are not publicly available in java.base module: "+ + missingClasses);+ }+ }++ /**+ * returns all superclasses, interfaces, and outer classes of the parsed class as stream of+ * internal names+ */+ private static Stream<String> getReferences(ClassModel parsed) {+ var parents =+ Stream.concat(parsed.superclass().stream(), parsed.interfaces().stream())+ .map(ClassEntry::asInternalName)+ .collect(Collectors.toSet());+ var outerClasses =+ parsed.findAttributes(Attributes.innerClasses()).stream()+ .flatMap(a -> a.classes().stream())+ .filter(i -> parents.contains(i.innerClass().asInternalName()))+ .flatMap(i -> i.outerClass().stream())+ .map(ClassEntry::asInternalName);+ return Stream.concat(parents.stream(), outerClasses);+ }++ @SuppressWarnings("unchecked") // no idea how to get generics correct!?!+ private static <E extends ClassFileElement, B extends ClassFileBuilder<E, B>> void dropPreview(+ ClassFileBuilder<E, B> builder, E ele) {+ switch (ele) {+ case RuntimeInvisibleAnnotationsAttribute att ->+ builder.with(+ (E)+ RuntimeInvisibleAnnotationsAttribute.of(+ att.annotations().stream()+ .filter(ann -> !CD_PreviewFeature.equals(ann.classSymbol()))+ .toList()));+ default -> builder.with(ele);+ }+ }++ private static boolean isVisible(AccessFlags access) {+ return access.has(AccessFlag.PUBLIC) || access.has(AccessFlag.PROTECTED);+ }+}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/LuceneJavaCoreMrjarPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/LuceneJavaCoreMrjarPlugin.javanew file mode 100644index 00000000000..8fb8f2f0e73--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/LuceneJavaCoreMrjarPlugin.java@@ -0,0 +1,235 @@+/*+ * 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.mrjar;++import de.thetaphi.forbiddenapis.gradle.CheckForbiddenApis;+import java.util.List;+import java.util.Map;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.gradle.api.GradleException;+import org.gradle.api.Project;+import org.gradle.api.file.Directory;+import org.gradle.api.file.RegularFile;+import org.gradle.api.file.RegularFileProperty;+import org.gradle.api.plugins.JavaPlugin;+import org.gradle.api.plugins.JavaPluginExtension;+import org.gradle.api.provider.Property;+import org.gradle.api.tasks.InputFile;+import org.gradle.api.tasks.JavaExec;+import org.gradle.api.tasks.PathSensitive;+import org.gradle.api.tasks.PathSensitivity;+import org.gradle.api.tasks.SourceSet;+import org.gradle.api.tasks.bundling.Jar;+import org.gradle.api.tasks.compile.JavaCompile;+import org.gradle.jvm.toolchain.JavaLanguageVersion;+import org.gradle.jvm.toolchain.JavaLauncher;+import org.gradle.jvm.toolchain.JavaToolchainService;+import org.gradle.process.CommandLineArgumentProvider;++/**+ * Sets up the infrastructure required to extract API stubs from newer JDKs and compile+ * multi-release JARs against those stubs.+ */+public class LuceneJavaCoreMrjarPlugin extends LuceneGradlePlugin {+ @Override+ public void apply(Project project) {+ if (!project.getPath().equals(":lucene:core")) {+ throw new GradleException("This plugin needs to be applied to :lucene:core only.");+ }++ requiresAppliedPlugin(project, JavaPlugin.class);++ project.getExtensions().create(MrJarsExtension.NAME, MrJarsExtension.class);+ }++ static void setupMrJarInfrastructure(Project project, List<Integer> mrjarJavaVersions) {+ Directory apijars = project.getLayout().getProjectDirectory().dir("src/generated/jdk");++ var javaExt = project.getExtensions().getByType(JavaPluginExtension.class);++ for (var jdkVersion : mrjarJavaVersions) {+ SourceSet sourceSet = javaExt.getSourceSets().create("main" + jdkVersion);+ sourceSet.getJava().setSrcDirs(List.of("src/java" + jdkVersion));++ var configurations = project.getConfigurations();+ var confName = "main" + jdkVersion + "Implementation";+ var conf = configurations.maybeCreate(confName);+ conf.extendsFrom(configurations.maybeCreate("implementation"));++ project+ .getDependencies()+ .add(confName, javaExt.getSourceSets().getByName("main").getOutput());++ RegularFile apijar = apijars.file("jdk" + jdkVersion + "-api.jar");++ // include api jar in forbidden APIs.+ project+ .getTasks()+ .withType(CheckForbiddenApis.class)+ .named("forbiddenApisMain" + jdkVersion)+ .configure(+ spec -> {+ spec.setClasspath(spec.getClasspath().plus(project.files(apijar)));+ });++ // configure javac.+ project+ .getTasks()+ .withType(JavaCompile.class)+ .named("compileMain" + jdkVersion + "Java")+ .configure(+ spec -> {+ // TODO: this depends on the order of argument configuration...+ List<String> compilerArgs = spec.getOptions().getCompilerArgs();+ int releaseIndex = compilerArgs.indexOf("--release");+ assert releaseIndex >= 0;+ compilerArgs.subList(releaseIndex, releaseIndex + 2).clear();++ // Remove conflicting options for the linter. #14782+ compilerArgs.remove("-Xlint:options");+ compilerArgs.add("-Xlint:-options");++ compilerArgs.addAll(+ List.of(+ "--add-exports",+ "java.base/java.lang.foreign=ALL-UNNAMED",+ // for compilation, we patch the incubator packages into java.base, this has+ // no effect on resulting class files:+ "--add-exports",+ "java.base/jdk.incubator.vector=ALL-UNNAMED"));++ var argsProvider = project.getObjects().newInstance(CompilerArgsProvider.class);+ argsProvider.getApiJarFile().set(apijar);+ spec.getOptions().getCompilerArgumentProviders().add(argsProvider);+ });+ }++ // configure jar task to include mr-jar classes.+ var buildGlobals = getLuceneBuildGlobals(project);+ project+ .getTasks()+ .withType(Jar.class)+ .configureEach(+ spec -> {+ boolean needMRJAR = false;+ int minJavaVersion =+ Integer.parseInt(buildGlobals.getMinJavaVersion().get().getMajorVersion());++ for (var jdkVersion : mrjarJavaVersions) {+ // the sourceSet which corresponds to the minimum/base Java version+ // will copy its output to the root of this JAR,+ // all other sourceSets will go into MR-JAR folders.+ boolean isBaseVersion = jdkVersion <= minJavaVersion;+ spec.into(+ isBaseVersion ? "" : "META-INF/versions/" + jdkVersion,+ copySpec -> {+ copySpec.from(+ javaExt.getSourceSets().getByName("main" + jdkVersion).getOutput());+ });+ needMRJAR |= !isBaseVersion;+ }++ if (needMRJAR) {+ spec.getManifest().getAttributes().put("Multi-Release", "true");+ }+ });++ // add regeneration of the apijar(s).+ var javaToolchains = project.getExtensions().getByType(JavaToolchainService.class);+ for (var jdkVersion : mrjarJavaVersions) {+ var generateJdkApiJarTask =+ project+ .getTasks()+ .register(+ "generateJdkApiJar" + jdkVersion,+ JavaExec.class,+ spec -> {+ spec.setDescription(+ "Regenerate the API-only JAR file with public Panama Vector API from JDK "+ + jdkVersion);+ spec.setGroup("generation");++ Property<JavaLauncher> javaLauncher = spec.getJavaLauncher();+ javaLauncher.set(+ javaToolchains.launcherFor(+ toolchainSpec -> {+ toolchainSpec+ .getLanguageVersion()+ .set(JavaLanguageVersion.of(jdkVersion));+ }));++ spec.setOnlyIf(+ t -> {+ try {+ return javaLauncher.isPresent() && javaLauncher.get() != null;+ } catch (Exception e) {+ var logger = t.getLogger();+ logger.warn(+ "Launcher for Java {} is not available; skipping regeneration of Panama Vector API JAR.",+ jdkVersion);+ logger.warn("Error: {}", e.getCause().getMessage());+ logger.warn(+ "Please make sure to point env 'JAVA{}_HOME' to exactly JDK version {} or enable Gradle toolchain auto-download.",+ jdkVersion,+ jdkVersion);+ return false;+ }+ });++ spec.getMainClass()+ .set(+ getProjectRootPath(project)+ .resolve(+ "build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/ExtractJdkApis.java")+ .toString());++ spec.getSystemProperties()+ .putAll(+ Map.of(+ "user.timezone", "UTC",+ "file.encoding", "UTF-8"));++ RegularFile apijar = apijars.file("jdk" + jdkVersion + "-api.jar");+ spec.setArgs(+ List.of(+ buildGlobals.getMinJavaVersion().get().toString(),+ jdkVersion.toString(),+ apijar.getAsFile().toString()));+ });++ project+ .getTasks()+ .named("regenerate")+ .configure(+ t -> {+ t.dependsOn(generateJdkApiJarTask);+ });+ }+ }++ public abstract static class CompilerArgsProvider implements CommandLineArgumentProvider {+ @InputFile+ @PathSensitive(PathSensitivity.RELATIVE)+ abstract RegularFileProperty getApiJarFile();++ @Override+ public Iterable<String> asArguments() {+ return List.of(+ "--patch-module", "java.base=" + getApiJarFile().get().getAsFile().getAbsolutePath());+ }+ }+}diff --git a/build-tools/build-infra/src/main/groovy/lucene.hacks.dummy-outputs.gradle b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/MrJarsExtension.javasimilarity index 54%rename from build-tools/build-infra/src/main/groovy/lucene.hacks.dummy-outputs.gradlerename to build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/MrJarsExtension.javaindex 9c8fa0efc39..125a2d48d14 100644--- a/build-tools/build-infra/src/main/groovy/lucene.hacks.dummy-outputs.gradle+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/mrjar/MrJarsExtension.java@@ -14,29 +14,24 @@* See the License for the specific language governing permissions and* limitations under the License.*/+package org.apache.lucene.gradle.plugins.mrjar;-import java.nio.file.Files+import java.util.stream.IntStream;+import javax.inject.Inject;+import org.gradle.api.Project;-// LUCENE-9505: utility function that sets up dummy outputs for a task so that-// clean[TaskName] works and allows selective re-runs.+public abstract class MrJarsExtension {+ public static final String NAME = "mrJars";-allprojects {- tasks.matching {- it.name.startsWith("ecjLint") ||- it.name in [- "gradlewScriptsTweaked",- "validateSourcePatterns"- ]- }.configureEach { Task task ->- task.logger.info("Adding a dummy-output to ${task.path}.")+ @Inject+ public abstract Project getProject();- File dummyOutput = layout.buildDirectory.file("tasks/${task.name}/dummy-output.txt").get().asFile- task.outputs.file(dummyOutput)-- task.doLast {- if (!dummyOutput.exists()) {- Files.createFile(dummyOutput.toPath())- }- }+ /**+ * Immediately configures additional tasks and infrastructure for apijar stubs for the provided+ * list of Java feature JDKs.+ */+ public void setupFor(int... jdkVersions) {+ LuceneJavaCoreMrjarPlugin.setupMrJarInfrastructure(+ getProject(), IntStream.of(jdkVersions).boxed().toList());}}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/GradleGroovyFormatPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/GradleGroovyFormatPlugin.javanew file mode 100644index 00000000000..be57c4d4732--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/GradleGroovyFormatPlugin.java@@ -0,0 +1,105 @@+/*+ * 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.spotless;++import com.diffplug.gradle.spotless.GroovyGradleExtension;+import com.diffplug.gradle.spotless.SpotlessExtension;+import com.diffplug.gradle.spotless.SpotlessPlugin;+import java.util.List;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.gradle.api.Project;+import org.gradle.api.provider.Provider;+import org.gradle.api.tasks.TaskContainer;++/** This adds automatic gradle/groovy code formatting and format compliance checks. */+public class GradleGroovyFormatPlugin extends LuceneGradlePlugin {+ @Override+ public void apply(Project project) {+ applicableToRootProjectOnly(project);++ project.getPlugins().apply(SpotlessPlugin.class);++ // register an option to turn this formatting on or off (it is heavy).+ String spotlessGradleScriptsOptionName = "lucene.spotlessGradleScripts";+ Provider<Boolean> spotlessGradleScriptsOption =+ getBuildOptions(project)+ .addBooleanOption(+ spotlessGradleScriptsOptionName,+ "Enable formatting and validation of groovy/gradle scripts (you may want to turn it on locally if you"+ + " work with gradle/groovy scripts)",+ false);++ if (!spotlessGradleScriptsOption.get()) {+ // register empty stubs for the corresponding set of spotless tasks, if disabled.+ registerEmptyStubs(project, spotlessGradleScriptsOptionName);+ } else {+ var spotless = project.getExtensions().getByType(SpotlessExtension.class);+ spotless.format(+ "gradleScripts",+ GroovyGradleExtension.class,+ ext -> {+ ext.greclipse();+ ext.leadingTabsToSpaces(2);+ ext.trimTrailingWhitespace();+ ext.endWithNewline();+ ext.target("build-tools/**/*.gradle", "build-tools/**/*.groovy", "**/build.gradle");+ });+ }++ TaskContainer tasks = project.getTasks();+ tasks.named(+ "spotlessGradleScripts",+ task -> {+ task.mustRunAfter(+ List.of(+ ":lucene:build-tools:build-infra-shadow:applyGoogleJavaFormat",+ ":lucene:build-tools:build-infra-shadow:compileJava",+ ":lucene:build-tools:build-infra-shadow:pluginDescriptors",+ ":lucene:build-tools:build-infra-shadow:pluginUnderTestMetadata",+ ":lucene:build-tools:missing-doclet:applyGoogleJavaFormat",+ ":lucene:build-tools:missing-doclet:compileJava",+ ":lucene:build-tools:missing-doclet:renderJavadoc"));+ });++ tasks.named("tidy").configure(task -> task.dependsOn(":spotlessGradleScriptsApply"));+ tasks.named("check").configure(task -> task.dependsOn(":spotlessGradleScriptsCheck"));+ }++ private static void registerEmptyStubs(Project project, String spotlessGradleScriptsOptionName) {+ for (var taskName :+ List.of(+ "spotlessGradleScripts", "spotlessGradleScriptsApply", "spotlessGradleScriptsCheck")) {+ project+ .getTasks()+ .register(+ taskName,+ spec -> {+ spec.doFirst(+ t -> {+ t.getLogger()+ .info(+ "Spotless is turned off for gradle/groovy scripts. CI "+ + "checks may not pass if you have formatting "+ + "differences (enable '"+ + spotlessGradleScriptsOptionName+ + "' build option to check"+ + "and apply gradle/groovy formatting).");+ });+ });+ }+ }+}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ValidateSourcePatternsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ValidateSourcePatternsPlugin.javanew file mode 100644index 00000000000..1eb57eeb7a7--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/spotless/ValidateSourcePatternsPlugin.java@@ -0,0 +1,236 @@+/*+ * 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.spotless;++import com.google.common.base.Splitter;+import java.io.File;+import java.io.IOException;+import java.io.InputStreamReader;+import java.io.StringWriter;+import java.nio.charset.CharsetDecoder;+import java.nio.charset.CodingErrorAction;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.util.Locale;+import java.util.Set;+import java.util.TreeSet;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import java.util.stream.Collectors;+import javax.inject.Inject;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.apache.rat.Defaults;+import org.apache.rat.analysis.RatHeaderAnalysisException;+import org.apache.rat.document.impl.FileDocument;+import org.gradle.api.DefaultTask;+import org.gradle.api.GradleException;+import org.gradle.api.Project;+import org.gradle.api.file.ConfigurableFileTree;+import org.gradle.api.tasks.CacheableTask;+import org.gradle.api.tasks.IgnoreEmptyDirectories;+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.compile.JavaCompile;+import org.gradle.internal.logging.progress.ProgressLogger;+import org.gradle.internal.logging.progress.ProgressLoggerFactory;++/** Checks for invalid usage patterns in source files. */+public class ValidateSourcePatternsPlugin extends LuceneGradlePlugin {+ public static final String TASK_NAME = "validateSourcePatterns";++ @Override+ public void apply(Project project) {+ applicableToRootProjectOnly(project);++ project.allprojects(this::configureProject);+ }++ private void configureProject(Project project) {+ var validateSourcePatternsTask =+ project+ .getTasks()+ .register(+ TASK_NAME,+ ValidateSourcePatternsTask.class,+ task -> {+ task.setGroup("Verification");+ task.setDescription("Validate Source Patterns");++ ConfigurableFileTree sourceFiles = task.getSourceFiles();+ sourceFiles.setDir(project.getLayout().getProjectDirectory());++ // it seems we only scan XML files - everything else has been moved+ // to rat scanning or elsewhere.+ sourceFiles.include("**/*.xml");++ // default excludes.+ sourceFiles.exclude("**/build/**");+ sourceFiles.exclude("**/.idea/**");+ sourceFiles.exclude("**/.gradle/**");+ sourceFiles.exclude("**/.git/**");++ // Don't go into subproject folders (each is scanned individually).+ sourceFiles.exclude(+ project.getChildProjects().keySet().stream()+ .map(name -> name + "/**")+ .toList());+ });++ // Add to all checks.+ project.getTasks().named("check").configure(task -> task.dependsOn(validateSourcePatternsTask));++ // Ensure validation runs prior to any compilation task.+ project+ .getTasks()+ .withType(JavaCompile.class)+ .configureEach(+ task -> {+ task.mustRunAfter(validateSourcePatternsTask);+ });++ // project-specific tuning.+ project+ .project(":lucene:benchmark")+ .getTasks()+ .withType(ValidateSourcePatternsTask.class)+ .configureEach(+ task -> {+ task.getSourceFiles().exclude("data/**", "work/**");+ });+ }++ @CacheableTask+ public abstract static class ValidateSourcePatternsTask extends DefaultTask {+ @InputFiles+ @PathSensitive(PathSensitivity.RELATIVE)+ @IgnoreEmptyDirectories+ public abstract ConfigurableFileTree getSourceFiles();++ @Inject+ protected abstract ProgressLoggerFactory getProgressLoggerFactory();++ @TaskAction+ public void check() {+ Set<File> files = getSourceFiles().getFiles();+ getLogger()+ .info(+ "Input files for scanning:\n{}",+ files.stream().map(f -> " - " + f).collect(Collectors.joining("\n")));++ var xmlCommentPattern = Pattern.compile("(?sm)\\Q<!--\\E(.*?)\\Q-->\\E");+ var xmlTagPattern = Pattern.compile("(?m)\\s*<[a-zA-Z].*");+ var violations = new TreeSet<String>();++ ProgressLogger progress = getProgressLoggerFactory().newOperation(this.getClass());+ progress.start(this.getName(), this.getName());+ for (var file : files) {+ progress.progress("Scanning " + file.getName());++ String fileText = readUtf8WithValidation(file);++ if (file.getName().endsWith(".xml")) {+ var ratDocument = new FileDocument(file);+ checkLicenseHeaderPrecedes(+ file, "<tag>", xmlTagPattern, xmlCommentPattern, fileText, ratDocument, violations);+ }+ }+ progress.completed();++ if (!violations.isEmpty()) {+ throw new GradleException(+ String.format(+ Locale.ROOT,+ "Found %d source violation(s):\n %s",+ violations.size(),+ String.join("\n ", violations)));+ }+ }++ private void checkLicenseHeaderPrecedes(+ File file,+ String description,+ Pattern contentPattern,+ Pattern commentPattern,+ String fileText,+ FileDocument ratDocument,+ TreeSet<String> violations) {+ Matcher contentMatcher = contentPattern.matcher(fileText);+ if (contentMatcher.find()) {+ int contentStartPos = contentMatcher.start();+ Matcher commentMatcher = commentPattern.matcher(fileText);+ while (commentMatcher.find()) {+ if (isLicense(file, commentMatcher.group(1), ratDocument)) {+ if (commentMatcher.start() < contentStartPos) {+ // This file is all good, so break the loop:+ // license header precedes 'description' definition+ break;+ } else {+ reportViolation(+ violations, file, description + " declaration precedes license header");+ }+ }+ }+ }+ }++ private void reportViolation(TreeSet<String> violations, File file, String name) {+ String msg = String.format(Locale.ROOT, "%s: %s", file, name);+ getLogger().error(msg);+ violations.add(msg);+ }++ // See LUCENE-10419 - rat is not thread safe.+ private static final Object ratLockBug = new Object();+ private static final Splitter lineSplitter = Splitter.on(Pattern.compile("[\\r\\n]+"));++ private boolean isLicense(File file, String text, FileDocument ratDocument) {+ synchronized (ratLockBug) {+ var licenseMatcher = Defaults.createDefaultMatcher();+ licenseMatcher.reset();+ return lineSplitter.splitToList(text).stream()+ .anyMatch(+ it -> {+ try {+ return licenseMatcher.match(ratDocument, it);+ } catch (RatHeaderAnalysisException e) {+ throw new GradleException("Could not scan this file with rat: " + file, e);+ }+ });+ }+ }++ private static String readUtf8WithValidation(File file) {+ String fileText;+ CharsetDecoder validatingDecoder =+ StandardCharsets.UTF_8+ .newDecoder()+ .onMalformedInput(CodingErrorAction.REPORT)+ .onUnmappableCharacter(CodingErrorAction.REPORT);+ try (var is = Files.newInputStream(file.toPath());+ var sw = new StringWriter();+ var reader = new InputStreamReader(is, validatingDecoder)) {+ reader.transferTo(sw);+ fileText = sw.toString();+ } catch (IOException e) {+ throw new GradleException("Could not read: " + file, e);+ }+ return fileText;+ }+ }+}diff --git a/build.gradle b/build.gradleindex 10f5b8f38b6..36a3f0bdc1f 100644--- a/build.gradle+++ b/build.gradle@@ -25,10 +25,8 @@ plugins {id "base"id "lucene.root-project.setup"-id "lucene.java-projects.conventions"- id "lucene.java.core.mrjar"id "lucene.java.fail-on-no-tests"id "lucene.java.slowest-tests-at-end"id "lucene.java.show-failed-tests-at-end"@@ -36,13 +34,9 @@ plugins {id "lucene.java.coverage"id "lucene.java.modules"- id "lucene.validation.spotless-groovy"- id "lucene.validation.lockfile"id "lucene.validation.gradle-versions-cleanup"- id "lucene.validation.gradlew-scripts-customizations"id "lucene.validation.error-prone"id "lucene.validation.jar-checks"- id "lucene.validation.source-patterns"id "lucene.validation.rat-sources"id "lucene.validation.owasp"@@ -58,9 +52,6 @@ plugins {id "lucene.datasets.external-datasets"- id "lucene.hacks.turbocharge-jvm-opts"- id "lucene.hacks.dummy-outputs"-id "lucene.documentation"id "lucene.documentation.changes-to-html"id "lucene.documentation.markdown"@@ -76,7 +67,6 @@ plugins {id "lucene.regenerate.javacc"id "lucene.regenerate.antlr"id "lucene.regenerate.unicode-test-classes"- id "lucene.regenerate.extract-jdk-apis"id "lucene.regenerate.snowball"}diff --git a/gradle/regenerate/extract-jdk-apis/ExtractJdkApis.java b/gradle/regenerate/extract-jdk-apis/ExtractJdkApis.javadeleted file mode 100644index 1ff33f84578..00000000000--- a/gradle/regenerate/extract-jdk-apis/ExtractJdkApis.java+++ /dev/null@@ -1,197 +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 java.io.IOException;-import java.lang.classfile.AccessFlags;-import java.lang.classfile.Attributes;-import java.lang.classfile.ClassFile;-import java.lang.classfile.ClassFileBuilder;-import java.lang.classfile.ClassFileElement;-import java.lang.classfile.ClassFileVersion;-import java.lang.classfile.ClassModel;-import java.lang.classfile.ClassTransform;-import java.lang.classfile.CodeModel;-import java.lang.classfile.FieldModel;-import java.lang.classfile.MethodModel;-import java.lang.classfile.MethodTransform;-import java.lang.classfile.attribute.InnerClassesAttribute;-import java.lang.classfile.attribute.RuntimeInvisibleAnnotationsAttribute;-import java.lang.classfile.attribute.SourceFileAttribute;-import java.lang.classfile.constantpool.ClassEntry;-import java.lang.constant.ClassDesc;-import java.lang.invoke.MethodHandles;-import java.lang.reflect.AccessFlag;-import java.lang.reflect.ClassFileFormatVersion;-import java.net.URI;-import java.nio.file.Files;-import java.nio.file.Path;-import java.nio.file.PathMatcher;-import java.nio.file.Paths;-import java.nio.file.attribute.FileTime;-import java.time.Instant;-import java.util.Arrays;-import java.util.HashSet;-import java.util.List;-import java.util.Map;-import java.util.Objects;-import java.util.Set;-import java.util.TreeMap;-import java.util.function.Predicate;-import java.util.stream.Collectors;-import java.util.stream.Stream;-import java.util.zip.ZipEntry;-import java.util.zip.ZipOutputStream;--public final class ExtractJdkApis {-- private static final FileTime FIXED_FILEDATE = FileTime.from(Instant.parse("2025-05-05T00:00:00Z"));-- private static final String PATTERN_VECTOR_INCUBATOR = "jdk.incubator.vector/jdk/incubator/vector/*";- private static final String PATTERN_VECTOR_VM_INTERNALS = "java.base/jdk/internal/vm/vector/VectorSupport{,$Vector,$VectorMask,$VectorPayload,$VectorShuffle}";-- static final Map<Integer,List<String>> CLASSFILE_PATTERNS = Map.of(- 24, List.of(PATTERN_VECTOR_VM_INTERNALS, PATTERN_VECTOR_INCUBATOR)- );-- private static final ClassDesc CD_PreviewFeature = ClassDesc.ofInternalName("jdk/internal/javac/PreviewFeature");-- public static void main(String... args) throws IOException {- if (args.length != 3) {- throw new IllegalArgumentException("Need two parameters: target java version, extract java version, output file");- }- int targetJdk = Integer.parseInt(args[0]);- Integer extractJdk = Integer.valueOf(args[1]);- int runtimeJdk = Runtime.version().feature();- if (extractJdk.intValue() != runtimeJdk) {- throw new IllegalStateException("Incorrect runtime java version: " + runtimeJdk);- }- if (extractJdk.intValue() < targetJdk) {- throw new IllegalStateException("extract java version " + extractJdk + " < target java version " + targetJdk);- }- if (!CLASSFILE_PATTERNS.containsKey(extractJdk)) {- throw new IllegalArgumentException("No support to extract stubs from java version: " + extractJdk);- }- var outputPath = Paths.get(args[2]);-- // the output class files need to be compatible with the targetJdk of our compilation, so we need to adapt them:- var classFileVersion = ClassFileVersion.of(ClassFileFormatVersion.valueOf("RELEASE_" + targetJdk).major(), 0);-- // create JRT filesystem and build a combined FileMatcher:- var jrtPath = Paths.get(URI.create("jrt:/")).toRealPath();- var patterns = CLASSFILE_PATTERNS.get(extractJdk).stream()- .map(pattern -> jrtPath.getFileSystem().getPathMatcher("glob:" + pattern + ".class"))- .toArray(PathMatcher[]::new);- PathMatcher pattern = p -> Arrays.stream(patterns).anyMatch(matcher -> matcher.matches(p));-- // Collect all files to process:- final List<Path> filesToExtract;- try (var stream = Files.walk(jrtPath)) {- filesToExtract = stream.filter(p -> pattern.matches(jrtPath.relativize(p))).toList();- }-- // Process all class files:- try (var out = new ZipOutputStream(Files.newOutputStream(outputPath))) {- process(filesToExtract, out, classFileVersion);- }- }-- private static void process(List<Path> filesToExtract, ZipOutputStream out, ClassFileVersion classFileVersion) throws IOException {- System.out.println("Loading and analyzing " + filesToExtract.size() + " class files...");- var classesToInclude = new HashSet<String>();- var toProcess = new TreeMap<String, ClassModel>();- var cc = ClassFile.of(ClassFile.ConstantPoolSharingOption.NEW_POOL, ClassFile.DebugElementsOption.DROP_DEBUG,- ClassFile.LineNumbersOption.DROP_LINE_NUMBERS, ClassFile.StackMapsOption.DROP_STACK_MAPS);- for (Path p : filesToExtract) {- ClassModel parsed = cc.parse(p);- String internalName = parsed.thisClass().asInternalName();- toProcess.put(internalName, parsed);- if (isVisible(parsed.flags())) {- classesToInclude.add(internalName);- }- }- // recursively add all superclasses / interfaces / outer classes of visible classes to classesToInclude:- for (Set<String> a = classesToInclude; !a.isEmpty();) {- classesToInclude.addAll(a = a.stream().map(toProcess::get).filter(Objects::nonNull).flatMap(ExtractJdkApis::getReferences).collect(Collectors.toSet()));- }- // remove all non-visible or not referenced classes:- toProcess.keySet().removeIf(Predicate.not(classesToInclude::contains));- // transformation of class files:- System.out.println("Writing " + toProcess.size() + " visible classes...");- for (var parsed : toProcess.values()) {- String internalName = parsed.thisClass().asInternalName();- System.out.println("Writing stub for class: " + internalName);- ClassTransform ct = ClassTransform.dropping(ce -> switch (ce) {- case MethodModel e -> !isVisible(e.flags());- case FieldModel e -> !isVisible(e.flags());- case SourceFileAttribute _ -> true;- default -> false;- }).andThen((builder, ce) -> {- switch (ce) {- case ClassFileVersion _ -> builder.with(classFileVersion);- // the PreviewFeature annotation may refer to its own inner classes and therefore we must get rid of the inner class entry:- case InnerClassesAttribute a -> builder.with(InnerClassesAttribute.of(a.classes().stream()- .filter(c -> !CD_PreviewFeature.equals(c.outerClass().map(ClassEntry::asSymbol).orElse(null)))- .toList()));- default -> builder.with(ce);- }- }).andThen(ExtractJdkApis::dropPreview)- .andThen(ClassTransform.transformingMethods(MethodTransform.dropping(CodeModel.class::isInstance).andThen(ExtractJdkApis::dropPreview))- .andThen(ClassTransform.transformingFields(ExtractJdkApis::dropPreview)));- out.putNextEntry(new ZipEntry(internalName.concat(".class")).setLastModifiedTime(FIXED_FILEDATE));- out.write(cc.transformClass(parsed, ct));- out.closeEntry();- }- // make sure that no classes are left over except those which are in java.base module- classesToInclude.removeIf(toProcess.keySet()::contains);- var missingClasses = classesToInclude.stream().filter(internalName -> {- try {- return ClassDesc.ofInternalName(internalName).resolveConstantDesc(MethodHandles.publicLookup()).getModule() != Object.class.getModule();- } catch (ReflectiveOperationException _) {- return true;- }- }).sorted().toList();- if (!missingClasses.isEmpty()) {- throw new IllegalStateException("Some referenced classes are not publicly available in java.base module: " + missingClasses);- }- }-- /** returns all superclasses, interfaces, and outer classes of the parsed class as stream of internal names */- private static Stream<String> getReferences(ClassModel parsed) {- var parents = Stream.concat(parsed.superclass().stream(), parsed.interfaces().stream())- .map(ClassEntry::asInternalName).collect(Collectors.toSet());- var outerClasses = parsed.findAttributes(Attributes.innerClasses()).stream()- .flatMap(a -> a.classes().stream())- .filter(i -> parents.contains(i.innerClass().asInternalName()))- .flatMap(i -> i.outerClass().stream())- .map(ClassEntry::asInternalName);- return Stream.concat(parents.stream(), outerClasses);- }-- @SuppressWarnings("unchecked") // no idea how to get generics correct!?!- private static <E extends ClassFileElement, B extends ClassFileBuilder<E, B>> void dropPreview(ClassFileBuilder<E, B> builder, E ele) {- switch (ele) {- case RuntimeInvisibleAnnotationsAttribute att -> builder.with((E) RuntimeInvisibleAnnotationsAttribute.of(att.annotations().stream()- .filter(ann -> !CD_PreviewFeature.equals(ann.classSymbol()))- .toList()));- default -> builder.with(ele);- }- }-- private static boolean isVisible(AccessFlags access) {- return access.has(AccessFlag.PUBLIC) || access.has(AccessFlag.PROTECTED);- }--}diff --git a/lucene/core/build.gradle b/lucene/core/build.gradleindex eddd4013560..9dc103cf3a7 100644--- a/lucene/core/build.gradle+++ b/lucene/core/build.gradle@@ -14,8 +14,10 @@* See the License for the specific language governing permissions and* limitations under the License.*/+import org.apache.lucene.gradle.plugins.mrjar.LuceneJavaCoreMrjarPlugin+import org.apache.lucene.gradle.plugins.mrjar.MrJarsExtension-+plugins.apply(LuceneJavaCoreMrjarPlugin)description = 'Lucene core library'@@ -23,3 +25,6 @@ dependencies {moduleTestImplementation project(':lucene:codecs')moduleTestImplementation project(':lucene:test-framework')}++// Setup api stub generation and multi-release jar support for the following JDKs.+project.getExtensions().getByType(MrJarsExtension).setupFor(24)